diff --git "a/1976.jsonl" "b/1976.jsonl" new file mode 100644--- /dev/null +++ "b/1976.jsonl" @@ -0,0 +1,657 @@ +{"seq_id":"339350573","text":"import os\nfrom django.conf import settings\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom django.db.models import Prefetch\n# from django.template import Context\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa\nfrom decimal import *\n\nfrom inventory.models import Tasks, Parts, TasksParts, GlobalMarkup, Categories, Jobs\n\n'''\nFor historical purposes. Will delete after formula bug is squashed.\ndef create_parts_with_standard_retail(markup_data):\n \"\"\"\n standard_retail: material_markup * part's retail cost or custom retail * markup\n custom retail overrides all.\n\n Returns a dict of dicts with part id as key. Added:\n standard_retail\n parts_tax\n \"\"\"\n markup_percent = markup_data[1]['standard_material_markup_percent']\n parts_tax_percent = markup_data[1]['parts_tax_percent']\n\n parts_values = Parts.objects.values(\n 'id',\n 'base_part_cost',\n 'retail_part_cost',\n 'set_custom_part_cost',\n 'custom_retail_part_cost'\n )\n\n parts = dict((p['id'], p) for p in parts_values)\n part_markup = 1 + Decimal(markup_percent / 100)\n\n for part in parts_values:\n if part['set_custom_part_cost']:\n standard_retail = Decimal(part['custom_retail_part_cost'] * part_markup)\n else:\n standard_retail = Decimal(part['retail_part_cost'] * part_markup)\n\n parts[part['id']].update({'standard_retail': standard_retail, 'parts_tax': parts_tax_percent})\n\n return parts\n\ndef tasks_calculated_labor_retail(markup_data):\n \"\"\"\n subtotal_retail_task_labor: labor_retail_hourly_rate * contractor hours + labor_retail_hourly_rate * asst hours\n subtotal_retail_addon_labor: l_retail_hourly / 60 * contractor minutes + l_retail_hourly / 60 * asst mins\n fixed_labor overrides all.\n\n Returns a dict of dicts with task's db id as key (not task_id).\n Includes the task's misc tos retail hourly rate and standard labor markup percent.\n \"\"\"\n\n tasks_labor_values = Tasks.objects.values(\n 'id',\n 'task_id',\n 'task_name',\n 'task_attribute',\n 'tag_types_id',\n 'use_fixed_labor_rate',\n 'fixed_labor_rate',\n 'estimated_contractor_hours',\n 'estimated_contractor_minutes',\n 'estimated_asst_hours',\n 'estimated_asst_minutes'\n )\n\n tasks_labor_dict = {}\n\n for tk in tasks_labor_values:\n key = tk['id']\n task_id = tk['task_id']\n name = tk['task_name']\n t_attr = tk['task_attribute']\n fixed_labor = tk['use_fixed_labor_rate']\n markup_id = tk['tag_types_id']\n subt_ret_task_labor = 0\n subt_ret_addon_labor = 0\n misc_tos_retail_hourly = Decimal(markup_data[markup_id]['misc_tos_retail_hourly_rate'])\n standard_labor_markup = Decimal(markup_data[markup_id]['standard_labor_markup_percent'])\n\n if fixed_labor:\n if t_attr == 'Addon And Task':\n subt_ret_task_labor = tk['fixed_labor_rate']\n subt_ret_addon_labor = tk['fixed_labor_rate']\n elif t_attr == 'Task Only':\n subt_ret_task_labor = tk['fixed_labor_rate']\n else:\n subt_ret_addon_labor = tk['fixed_labor_rate']\n else:\n # add misc_tos_retail_hourly_rate? to retail\n cntr_ret_hours = Decimal(markup_data[markup_id]['labor_retail_hourly_rate']) * Decimal(tk['estimated_contractor_hours'])\n asst_ret_hours = Decimal(markup_data[markup_id]['labor_retail_hourly_rate']) * Decimal(tk['estimated_asst_hours'])\n cntr_ret_mins = Decimal(markup_data[markup_id]['labor_retail_hourly_rate'] / 60) * Decimal(tk['estimated_contractor_minutes'])\n asst_ret_mins = Decimal(markup_data[markup_id]['labor_retail_hourly_rate'] / 60) * Decimal(tk['estimated_asst_minutes'])\n\n if t_attr == 'Addon And Task':\n subt_ret_task_labor = cntr_ret_hours + asst_ret_hours\n subt_ret_addon_labor = cntr_ret_mins + asst_ret_mins\n elif t_attr == 'Task Only':\n subt_ret_task_labor = cntr_ret_hours + asst_ret_hours\n else:\n subt_ret_addon_labor = cntr_ret_mins + asst_ret_mins\n\n tasks_labor_dict[key] = {\n 'task_name': name,\n 'task_item_id': task_id,\n 'subt_ret_task_labor': round(subt_ret_task_labor, 2),\n 'subt_ret_addon_labor': round(subt_ret_addon_labor, 2),\n 'standard_labor_markup': round(standard_labor_markup, 2),\n 'task_misc_tos_retail_hourly': misc_tos_retail_hourly,\n 'attr': t_attr,\n }\n\n return tasks_labor_dict\n\ndef separate_into_task_and_addon(task_dict):\n \"\"\"\n return a dict with two keys: task, addon.\n task: array of objects\n addon: array of objects\n \"\"\"\n\n data_dict = {}\n data_dict['task'] = []\n data_dict['addon'] = []\n\n keys = task_dict.keys()\n\n for key in keys:\n attr = task_dict[key]['attribute']\n\n if attr == 'Addon And Task':\n data_dict['task'].append(task_dict[key])\n data_dict['addon'].append(task_dict[key])\n elif attr == 'Task Only':\n data_dict['task'].append(task_dict[key])\n else:\n data_dict['addon'].append(task_dict[key])\n \n return data_dict\n\n\ndef calculate_task_labor_with_parts(markup_data, limiter=40):\n parts = create_parts_with_standard_retail(markup_data)\n tasks_labor = tasks_calculated_labor_retail(markup_data)\n tasksparts_values = TasksParts.objects.values('task_id', 'part_id', 'quantity').order_by('task_id')[:limiter]\n\n if limiter == 0:\n tasksparts_values = TasksParts.objects.values('task_id', 'part_id', 'quantity').order_by('task_id')\n\n task_dict = {}\n\n for tpv in tasksparts_values:\n tid = tpv['task_id']\n t_name = tasks_labor[tid]['task_name']\n task_id = tasks_labor[tid]['task_item_id']\n pid = tpv['part_id']\n qty = tpv['quantity']\n labor_markup = round(1 + Decimal(tasks_labor[tid]['standard_labor_markup'] / 100), 2)\n misc_tos = round(Decimal(tasks_labor[tid]['task_misc_tos_retail_hourly']), 2)\n part_obj = parts[pid]\n t_attr = tasks_labor[tid]['attr']\n part_tax = round(Decimal(part_obj['parts_tax'] / 100), 2)\n\n # task specific labor\n task_val_ret_labor = round(Decimal(tasks_labor[tid]['subt_ret_task_labor']), 2)\n addon_val_ret_labor = round(Decimal(tasks_labor[tid]['subt_ret_addon_labor']), 2)\n\n # parts * qty\n part_val_ret_subtotal = round(qty * Decimal(part_obj['retail_part_cost']), 2)\n part_std_ret_subtotal = round(qty * Decimal(part_obj['standard_retail']), 2)\n\n # tax aded to each part. tax only applied to value_retail\n part_val_ret_tax = round(Decimal(part_val_ret_subtotal * part_tax), 2)\n\n # part(and qty) + tax\n part_val_ret_total = part_val_ret_subtotal + part_val_ret_tax\n part_std_ret_total = part_std_ret_subtotal + part_val_ret_tax\n\n if tid in task_dict:\n t_obj = task_dict[tid]\n # t_obj['task_value_rate'] += task_total_val_ret_tax,\n t_obj['task_value_rate'] = t_obj['task_value_rate'] + part_val_ret_total\n t_obj['task_std_rate'] = t_obj['task_std_rate'] + part_std_ret_total\n t_obj['addon_value_rate'] = t_obj['addon_value_rate'] + part_val_ret_total\n t_obj['addon_std_rate'] = t_obj['addon_std_rate'] + part_std_ret_total\n # t_obj['quantity'] = t_obj['quantity'] + qty\n else:\n # labor is added only the first time\n task_dict[tid] = {}\n t_obj = task_dict[tid]\n t_obj['tid'] = tid\n t_obj['attribute'] = t_attr\n t_obj['task_id'] = task_id\n t_obj['task_name'] = t_name\n t_obj['task_value_rate'] = round(misc_tos + task_val_ret_labor + part_val_ret_total, 2)\n t_obj['task_std_rate'] = round((task_val_ret_labor * labor_markup) + misc_tos + part_std_ret_total, 2)\n t_obj['addon_value_rate'] = round(addon_val_ret_labor + part_val_ret_total, 2)\n t_obj['addon_std_rate'] = round((labor_markup * addon_val_ret_labor) + part_std_ret_total, 2)\n # t_obj['labor_markup'] = labor_markup\n # t_obj['task_val_ret_labor'] = task_val_ret_labor\n # t_obj['part_val_ret_subtotal'] = part_val_ret_subtotal\n # t_obj['part_val_ret_tax'] = part_val_ret_tax\n # t_obj['quantity'] = qty\n # t_obj['misc_tos'] = misc_tos\n\n task_data = separate_into_task_and_addon(task_dict)\n return task_data\n\n\n# def link_callback(uri, rel):\n# \"\"\"\n# Convert HTML URIs to absolute system paths so xhtml2pdf can access those\n# resources\n# \"\"\"\n# # use short variable names\n# sUrl = settings.STATIC_URL # Typically /static/\n# sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/\n# mUrl = settings.MEDIA_URL # Typically /static/media/\n# mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/\n\n# # convert URIs to absolute system paths\n# if uri.startswith(mUrl):\n# path = os.path.join(mRoot, uri.replace(mUrl, \"\"))\n# elif uri.startswith(sUrl):\n# path = os.path.join(sRoot, uri.replace(sUrl, \"\"))\n# else:\n# return uri # handle absolute uri (ie: http://some.tld/foo.png)\n\n# # make sure that file exists\n# if not os.path.isfile(path):\n# raise Exception(\n# 'media URI must start with %s or %s' % (sUrl, mUrl)\n# )\n# return path\n\n# remove limiter parameter after testing\ndef render_pdf_view(request, limiter=40):\n markup = dict((m['id'], m) for m in GlobalMarkup.objects.values())\n tasks_data = calculate_task_labor_with_parts(markup, limiter) #default 40\n\n template_path = 'view_pdf.html'\n context = {\n 'task': tasks_data['task'],\n 'addon': tasks_data['addon']\n }\n # Create a Django response object, and specify content_type as pdf\n response = HttpResponse(content_type='application/pdf')\n # response['Content-Disposition'] = 'attachment; filename=\"pmd-book.pdf\"'\n # find the template and render it.\n template = get_template(template_path)\n html = template.render(context)\n\n\n # create a pdf\n # pisaStatus = pisa.CreatePDF(html, dest=response, link_callback=link_callback)\n pisaStatus = pisa.CreatePDF(html, dest=response)\n # if error then show some funy view\n if pisaStatus.err:\n return HttpResponse('We had some errors
' + html + '
')\n return response\n\n\ndef render_json_view(request, limiter=0):\n markup = dict((m['id'], m) for m in GlobalMarkup.objects.values())\n custom_qs = calculate_task_labor_with_parts(markup, limiter)\n task_count = len(custom_qs['task'])\n addon_count = len(custom_qs['addon'])\n\n response = JsonResponse({\n 'task_count': task_count, \n 'addon_count': addon_count,\n 'data': custom_qs,\n })\n return response\n\n\n\ndef tasksparts_dict():\n tp_values = TasksParts.objects.values('task_id', 'part_id', 'quantity')\n tp_dict = {}\n\n for tp in tp_values:\n tid = tp['task_id']\n\n if tid not in tp_dict:\n tp_dict[tid] = {}\n tp_dict[tid] = {tp['part_id']: tp['quantity']}\n else:\n tp_dict[tid].update({tp['part_id']: tp['quantity']})\n\n return tp_dict\n\n\ndef categories_with_related_tasks():\n markup = dict((m['id'], m) for m in GlobalMarkup.objects.values())\n categories = Categories.objects.prefetch_related('tasks_set').all()\n cat_arr = []\n\n parts_dict = create_parts_with_standard_retail(markup)\n tasks_labor_dict = tasks_calculated_labor_retail(markup)\n tp_dict = tasksparts_dict()\n\n\n for cat in categories:\n related_tasks = cat.tasks_set.values()\n cid = cat.id\n cat_dict = {}\n cat_dict['name'] = cat.category_name\n cat_dict['id'] = cid\n cat_dict['data'] = {}\n cat_obj = cat_dict['data']\n cat_obj['task'] = []\n cat_obj['addon'] = []\n\n for task in related_tasks:\n # use task's db id to fetch qty from tasksparts\n tid = task['id']\n task_obj = tasks_labor_dict[tid]\n t_attr = task_obj['attr']\n task_id = task_obj['task_item_id']\n t_name = task_obj['task_name']\n\n misc_tos = Decimal(task_obj['task_misc_tos_retail_hourly'])\n labor_markup = round(1 + Decimal(task_obj['standard_labor_markup'] / 100), 2)\n\n part_vr_total = 0\n part_std_total = 0\n\n if tid in tp_dict:\n related_parts = tp_dict[tid].items()\n\n for part in related_parts:\n pid = part[0]\n qty = part[1]\n part_obj = parts_dict[pid]\n part_tax = Decimal(part_obj['parts_tax'] / 100)\n\n # calc value_retail subtotal and std_retail subtotal with quantity.\n part_val_ret_subtotal = round(qty * Decimal(part_obj['retail_part_cost']), 2)\n part_std_ret_subtotal = round(qty * Decimal(part_obj['standard_retail']), 2)\n\n # tax applied part. tax only applied to value_retail.\n part_tax_value = round(Decimal(part_val_ret_subtotal * part_tax), 2)\n \n # part(and qty) + tax\n part_val_ret_total = part_val_ret_subtotal + part_tax_value\n part_std_ret_total = part_std_ret_subtotal + part_tax_value\n\n part_vr_total += part_val_ret_total\n part_std_total += part_std_ret_total\n\n \n # calc task labor. Some tasks will not require parts so tid will not be in taskparts\n task_val_ret_labor = task_obj['subt_ret_task_labor']\n addon_val_ret_labor = task_obj['subt_ret_addon_labor']\n\n\n # calc task labor with parts\n task_value_rate = misc_tos + task_val_ret_labor + part_vr_total\n task_std_rate = (task_val_ret_labor * labor_markup) + misc_tos + part_std_total\n addon_value_rate = addon_val_ret_labor + part_vr_total\n addon_std_rate = (addon_val_ret_labor * labor_markup) + part_std_total\n\n # prepare task obj\n new_t_obj = {}\n new_t_obj['tid'] = tid\n new_t_obj['attribute'] = t_attr\n new_t_obj['task_id'] = task_id\n new_t_obj['task_name'] = t_name\n\n\n # separate by task attribute\n if t_attr == 'Addon And Task':\n new_t_obj['task_value_rate'] = round(task_value_rate, 2)\n new_t_obj['task_std_rate'] = round(task_std_rate, 2)\n new_t_obj['addon_value_rate'] = round(addon_value_rate, 2)\n new_t_obj['addon_std_rate'] = round(addon_std_rate, 2)\n cat_obj['task'].append(new_t_obj)\n cat_obj['addon'].append(new_t_obj)\n elif t_attr == 'Task Only':\n new_t_obj['task_value_rate'] = round(task_value_rate, 2)\n new_t_obj['task_std_rate'] = round(task_std_rate, 2)\n cat_obj['task'].append(new_t_obj)\n else:\n new_t_obj['addon_value_rate'] = round(addon_value_rate, 2)\n new_t_obj['addon_std_rate'] = round(addon_std_rate, 2)\n cat_obj['addon'].append(new_t_obj)\n cat_arr.append(cat_dict)\n\n return cat_arr\n\n\ndef render_categories_as_pdf(request):\n cat_data = categories_with_related_tasks()\n\n template_path = 'category_pdf.html'\n context = {\n 'cat_data': cat_data\n }\n\n response = HttpResponse(content_type='application/pdf')\n # response['Content-Disposition'] = 'attachment; filename=\"pmd-book.pdf\"'\n template = get_template(template_path)\n html = template.render(context)\n\n # create a pdf\n # pisaStatus = pisa.CreatePDF(html, dest=response, link_callback=link_callback)\n pisaStatus = pisa.CreatePDF(html, dest=response)\n\n if pisaStatus.err:\n return HttpResponse('We had some errors
' + html + '
')\n return response\n'''\n\ndef calculate_task_labor_obj(task_data, markup):\n task_obj = {}\n task_obj['id'] = task_data['id']\n task_obj['task_id'] = task_data['task_id']\n task_obj['task_name'] = task_data['task_name']\n task_obj['attribute'] = task_data['task_attribute']\n tos = markup['misc_tos_retail_hourly_rate']\n labor_markup = 1 + Decimal(markup['standard_labor_markup_percent'] / 100)\n\n if task_data['use_fixed_labor_rate']:\n fixed_rate = task_data['fixed_labor_rate']\n task_obj['task_value_rate'] = round(fixed_rate + tos, 2)\n task_obj['task_std_rate'] = round((fixed_rate * labor_markup) + tos, 2)\n task_obj['addon_value_rate'] = round(fixed_rate, 2)\n task_obj['addon_std_rate'] = round(fixed_rate * labor_markup, 2)\n return task_obj\n\n\n cntr_labor_retail = Decimal(markup['labor_retail_hourly_rate'])\n asst_labor_retail = Decimal(markup['asst_labor_retail_hourly_rate'])\n\n # task only\n cntr_hours = cntr_labor_retail * Decimal(task_data['estimated_contractor_hours'])\n asst_hours = asst_labor_retail * Decimal(task_data['estimated_asst_hours'])\n task_val_ret_labor = Decimal(cntr_hours + asst_hours)\n\n # addon only\n cntr_mins = (cntr_labor_retail / 60) * Decimal(task_data['estimated_contractor_minutes'])\n asst_mins = (asst_labor_retail / 60) * Decimal(task_data['estimated_asst_minutes'])\n addon_val_ret_labor = Decimal(cntr_mins + asst_mins)\n\n\n task_obj['task_value_rate'] = round(task_val_ret_labor + tos, 2) #+ part_vr_total\n task_obj['task_std_rate'] = round((task_val_ret_labor * labor_markup) + tos, 2) #+ part_std_total\n task_obj['addon_value_rate'] = round(addon_val_ret_labor, 2) #+ part_vr_total\n task_obj['addon_std_rate'] = round(addon_val_ret_labor * labor_markup, 2) #+ part_std_total\n\n return task_obj\n\n\ndef jobs_with_related_categories():\n markup = dict((m['id'], m) for m in GlobalMarkup.objects.values())\n\n jobs = Jobs.objects.prefetch_related('categories_set').order_by('ordering_num')\n jobs_dict = {}\n\n for job in jobs:\n jobs_dict[job.job_name] = {}\n jobs_dict[job.job_name]['job_name'] = job.job_name\n jobs_dict[job.job_name]['job_data'] = {}\n related_categories = job.categories_set.all()\n\n\n for cat in related_categories:\n cat_dict = {}\n cid = cat.id\n cat_dict['id'] = cat.id\n cat_dict['category_name'] = cat.category_name\n cat_dict['headings'] = [\n cat.category_heading_one,\n cat.category_heading_two,\n cat.category_heading_three,\n cat.category_heading_four,\n cat.category_heading_five,\n cat.category_heading_six,\n ]\n # headings = cat_dict['headings']\n\n # if len(cat.category_heading_one.strip()) > 0:\n # headings.append(cat.category_heading_one)\n # if len(cat.category_heading_two.strip()) > 0:\n # headings.append(cat.category_heading_two)\n # if len(cat.category_heading_three.strip()) > 0:\n # headings.append(cat.category_heading_three)\n # if len(cat.category_heading_four.strip()) > 0:\n # headings.append(cat.category_heading_four)\n # if len(cat.category_heading_five.strip()) > 0:\n # headings.append(cat.category_heading_five)\n # if len(cat.category_heading_six.strip()) > 0:\n # headings.append(cat.category_heading_six)\n\n cat_dict['task'] = {}\n cat_dict['addon'] = {}\n\n related_tasks_and_parts = cat.tasks_set.prefetch_related('tasksparts_set').select_related('part').values(\n 'id', 'task_id', 'task_name', 'task_attribute', 'tag_types', \n 'estimated_contractor_hours', 'estimated_contractor_minutes', 'estimated_asst_hours', 'estimated_asst_minutes',\n 'fixed_labor_rate', 'use_fixed_labor_rate',\n 'parts__id', 'parts__part_name', 'parts__retail_part_cost', \n 'parts__set_custom_part_cost', 'parts__custom_retail_part_cost', 'tasksparts__quantity'\n )\n\n for item in related_tasks_and_parts:\n tid = item['id']\n tag_id = item['tag_types']\n task_attr = item['task_attribute']\n markup_obj = markup[tag_id]\n part_tax = Decimal(markup_obj['parts_tax_percent'] / 100)\n qty = 0\n\n # calculate parts for each item\n part_markup = 1 + Decimal(markup_obj['standard_material_markup_percent'] / 100)\n\n # calc part standard retail or use custom retail\n if item['parts__set_custom_part_cost']:\n qty = item['tasksparts__quantity']\n part_std_retail = Decimal(item['parts__custom_retail_part_cost']) * part_markup * qty\n else:\n # some tasks may not contain parts. \n if item['parts__retail_part_cost'] is None:\n # placeholder values for task when there are no parts.\n part_std_retail = 0\n part_val_ret_subtotal = 0\n else:\n part_std_retail = Decimal(item['parts__retail_part_cost']) * part_markup\n # re-set qty when there are parts for the task.\n qty = item['tasksparts__quantity']\n # part * qty\n part_val_ret_subtotal = qty * Decimal(item['parts__retail_part_cost'])\n \n part_std_ret_subtotal = qty * part_std_retail\n\n part_val_ret_tax = part_val_ret_subtotal * part_tax\n\n # # part(and qty) + tax\n part_val_ret_total = round(part_val_ret_subtotal + part_val_ret_tax, 2)\n part_std_ret_total = round(part_std_ret_subtotal + part_val_ret_tax, 2)\n\n\n if task_attr == 'Addon And Task':\n cat_dict['task'][tid] = cat_dict['task'].get(tid, calculate_task_labor_obj(item, markup_obj))\n cat_dict['addon'][tid] = cat_dict['addon'].get(tid, calculate_task_labor_obj(item, markup_obj))\n\n task_obj = cat_dict['task'][tid]\n addon_obj = cat_dict['addon'][tid]\n\n task_obj['task_value_rate'] = task_obj.get('task_value_rate', part_val_ret_total) + part_val_ret_total\n task_obj['task_std_rate'] = task_obj.get('task_std_rate', part_std_ret_total) + part_std_ret_total\n\n addon_obj['addon_value_rate'] = addon_obj.get('addon_value_rate', part_val_ret_total) + part_val_ret_total \n addon_obj['addon_std_rate'] = addon_obj.get('addon_std_rate', part_std_ret_total) + part_std_ret_total\n elif task_attr == 'Task Only':\n cat_dict['task'][tid] = cat_dict['task'].get(tid, calculate_task_labor_obj(item, markup_obj))\n task_obj = cat_dict['task'][tid]\n\n task_obj['task_value_rate'] = task_obj.get('task_value_rate', part_val_ret_total) + part_val_ret_total\n task_obj['task_std_rate'] = task_obj.get('task_std_rate', part_std_ret_total) + part_std_ret_total\n else:\n cat_dict['addon'][tid] = cat_dict['addon'].get(tid, calculate_task_labor_obj(item, markup_obj))\n addon_obj = cat_dict['addon'][tid]\n\n addon_obj['addon_value_rate'] = addon_obj.get('addon_value_rate', part_val_ret_total) + part_val_ret_total \n addon_obj['addon_std_rate'] = addon_obj.get('addon_std_rate', part_std_ret_total) + part_std_ret_total\n\n jobs_dict[job.job_name]['job_data'][cid] = cat_dict\n\n return jobs_dict\n\n# html for the pdf conversion\ndef jobs_with_related_categories_as_html(request):\n jobs_data = jobs_with_related_categories()\n\n context = {\n 'jobs_data': jobs_data\n }\n return render(request, 'jobs_cats_html_table_pdf.html', context)\n\n\n# converts the html into a pdf using pisa/xhtml\ndef jobs_with_related_categories_as_pdf(request):\n jobs_data = jobs_with_related_categories()\n\n template_path = 'jobs_cats_html_table_pdf.html'\n context = {\n 'jobs_data': jobs_data\n }\n\n response = HttpResponse(content_type='application/pdf')\n # response['Content-Disposition'] = 'attachment; filename=\"pmd-book.pdf\"'\n template = get_template(template_path)\n html = template.render(context)\n\n # create a pdf\n # pisaStatus = pisa.CreatePDF(html, dest=response, link_callback=link_callback)\n pisaStatus = pisa.CreatePDF(html, dest=response)\n\n if pisaStatus.err:\n return HttpResponse('We had some errors
' + html + '
')\n return response\n\n# same html for pdf conversion but using a separate template with jsPDF and html2canvas\ndef jobs_with_categories_to_pdf(request):\n jobs_data = jobs_with_related_categories()\n\n context = {\n 'jobs_data': jobs_data\n }\n return render(request, 'jobs_cats_html_to_pdf.html', context)\n","sub_path":"pdf_tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"493164114","text":"from flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\r\ndef hello_world():\r\n if request.method == \"GET\":\r\n return render_template(\"forms/form_with_static.html\")\r\n elif request.method == \"POST\":\r\n kwargs = {\r\n \"title\": request.form[\"title\"],\r\n \"isbn\": request.form[\"isbn\"],\r\n \"author\": request.form[\"author\"],\r\n \"secret_key\": request.form[\"SECRET_KEY\"],\r\n \"submit_value\": request.form[\"submit\"],\r\n }\r\n return render_template(\"forms/basic_form_result.html\", **kwargs)\r\n","sub_path":"FlaskLibrary/library/_14_static_files.py","file_name":"_14_static_files.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"72941686","text":"from django.shortcuts import render\nfrom .models import generalReminder\nfrom .form import MyForm\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\n# Create your views here.\ndef addDate(request):\n return render(request, 'license/base.html')\n\ndef my_form(request):\n if request.method == \"POST\":\n form = MyForm(request.POST)\n if form.is_valid():\n form.save()\n else:\n form = MyForm()\n data = generalReminder.objects.all()\n # data.license_add = data.license_date + relativedelta(months=+data.license_add)\n lic = {\n 'reminder_list' :data\n }\n return render(request, 'license/base.html', {'form': form})\n\n","sub_path":"license/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"384774894","text":"#! /usr/bin/python\n# coding: utf8\nfrom urlparse import urlparse\n\n\nclass ResultStorage():\n reportData = {}\n reportStat = {}\n\n def appendResult(self, url, test, result):\n domain = urlparse(url).hostname\n if domain not in self.reportData:\n self.reportData[domain] = {}\n if url not in self.reportData[domain]:\n self.reportData[domain][url] = []\n\n self.reportData[domain][url].append((test, result))\n\n def get_stat_url(self, url):\n counter = {'all': 0, 'ok': 0, 'fail': 0}\n domain = urlparse(url).hostname\n if domain not in self.reportStat:\n self.reportStat[domain] = {}\n if url not in self.reportStat[domain]:\n self.reportStat[domain][url] = counter\n for test in self.reportData[domain][url]:\n counter[test[1]] += 1\n counter['all'] = counter['ok'] + counter['fail']\n self.reportStat[domain][url] = counter\n return counter\n\n def get_stat_domain(self, domain):\n counter = {'all': 0, 'ok': 0, 'fail': 0}\n for url in self.reportStat[domain]:\n for type in counter:\n counter[type] += self.reportStat[domain][url][type]\n return counter\n\n def init_stat_domain(self, domain):\n for url in self.reportData[domain]:\n self.get_stat_url(url)","sub_path":"report_storage.py","file_name":"report_storage.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"164060656","text":"#from sklearn.cross_validation import train_test_split\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split #py3\nfrom sklearn.feature_extraction import stop_words\nimport numpy as np\nfrom nltk.util import ngrams,everygrams\nimport re\nimport string\nimport time\nfrom sklearn.ensemble import RandomForestClassifier #change\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\nstop=stop_words.ENGLISH_STOP_WORDS\nRUNS=3\nnum_ex=80000\n\ndef encode_sentences(txt):\n feature_set=np.zeros((len(txt), len(word_set)+1),dtype=int)\n tnum=0\n for t in txt:\n s_words=t[1:]+list(set(list(everygrams(t[1:], min_len=2,max_len=2))))\n for w in s_words:\n idx=word_idx[w]\n feature_set[tnum][idx]=1\n feature_set[tnum][-1]=t[0]\n tnum+=1\n return feature_set\n\ninp='../tweets_positivenegative.csv'\n\nfo=open('rf_res.txt','w') #change\nfo.write('Sentiment140. Positive/Negative.\\n')\n\nsents=[]\nlabels=[]\nall_words=[] \n\ndf=pd.read_csv(inp,sep='\\t', quoting=2, dtype={'id ':int,'polarity': int })\ndf = df.dropna()\ndata=df.iloc[np.r_[0:num_ex, -num_ex:0]]\n\nfrom nltk.tokenize import TweetTokenizer\ntknzr = TweetTokenizer()\n\nmaxlen=0\nlcnt=0\n\nfor ind, row in data.iterrows():\n\ttw=row['tweet'].lower()\n\twords=tknzr.tokenize(tw)\n\tbl=list(set(list(everygrams(words, min_len=2,max_len=2))))\n\tall_words+=words+bl\n\twords.insert(0,lcnt)\n\tsents.append(words)\n\tif row['polarity']==4:\n\t\tlabels.append(1)\n\telse:\n\t\tlabels.append(0)\n\tlcnt+=1\n\n\nword_set=set(all_words)\ni=0\nword_idx = dict((c, i + 1) for i, c in enumerate(word_set,start = -1))\nreverse_word_map = dict(map(reversed, word_idx.items()))\ndata=encode_sentences(sents)\n\nCLASSES=list(set(labels))\nNUM_FEATURES=len(data[0])-1\n\nresult=np.zeros(RUNS)\nclf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0, n_jobs=2) #change\n\nfor r in range(RUNS):\n print('Run:',r)\n x_train, x_test, y_train, y_test = train_test_split(data, labels)\n x_train_ids=x_train[:,-1]\n x_test_ids=x_test[:,-1]\n x_train=x_train[:,:-1]\n x_test=x_test[:,:-1]\n clf.fit(x_train, y_train)\n result[r] = 100*(clf.predict(x_test) == y_test).mean()\n\nfo.write('bigrams and unigrams. stopwords not removed. punctuation not removed.\\n')\nfo.write('baseline_rf.py\\n') #change\nfo.write('\\nTotal Runs: '+str(RUNS))\nfo.write('\\nBest result:'+str(result.max()))\nfo.write('\\nMean result:'+str(result.mean()))\nfo.close()\n","sub_path":"examples/sentiment140/baseline/randomforests.py","file_name":"randomforests.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"364678077","text":"tab = []\nsuma = 0\nwith open(\"numbersinrows.txt\", \"r\") as file:\n for line in file:\n x = line.split(\",\")\n for i in range(len(x)):\n tab.append(x[i])\n suma+=int(x[i])\nprint(\"Ilosc liczb to\",len(tab))\nprint(\"Suma tych liczb to \", suma)","sub_path":"03-FileHandling/Zadanie 21.py","file_name":"Zadanie 21.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"350530925","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\n\nclass Room:\n def __init__(self, name, description, is_light, items = [], n_to = None, s_to = None, e_to = None, w_to = None, present_player = None):\n self.name = name\n self.description = description\n self.is_light = is_light\n self.items = items\n self.present_player = present_player\n\n def get_item(self, item):\n self.items.append(item)\n\n def lose_item(self, item):\n self.items.remove(item)\n\n def __str__(self):\n print(f\"--------------------\\n\\n{self.name}\\n\\n\\n{self.description}\\n\\n--------------------\\n\\n\")\n\n def get_room_in_direction(self, direction):\n if direction in (\"n\", \"s\", \"e\", \"w\"):\n if direction == \"n\" and hasattr(self, 'n_to'):\n return self.n_to\n elif direction == \"s\" and hasattr(self, 's_to'):\n return self.s_to\n elif direction == \"e\" and hasattr(self, 'e_to'):\n return self.e_to\n elif direction == \"w\" and hasattr(self, 'w_to'):\n return self.w_to\n else:\n return None\n\n def has_item(self, item_name):\n possible_item = [item for item in self.items if item.name == item_name]\n if len(possible_item) > 0:\n return possible_item[0]\n return None\n\n def get_room_exits(self):\n exits = []\n if hasattr(self, 'n_to'):\n exits.append(\"n\")\n if hasattr(self, 's_to'):\n exits.append(\"s\")\n if hasattr(self, 'e_to'):\n exits.append(\"e\")\n if hasattr(self, 'w_to'):\n exits.append(\"w\")\n return exits\n\nclass PuzzleRoom(Room):\n def __init__(self, name, description, player_puzzle_item, room_puzzle_item, is_light, items= []):\n super().__init__(name, description, is_light, items)\n self.player_puzzle_item = player_puzzle_item\n self.room_puzzle_item = room_puzzle_item\n\n","sub_path":"src/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"625781547","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport pandas as pd\nfrom sklearn import metrics\nimport re\nimport StringIO\n\ndata_file = 'old_projects_dataset.csv'\n\n# remove inconsistencies in whitespaces found in the input file\nr = re.compile('\\s+')\ncleaned_file_as_string = '\\n'.join(r.sub('', line) for line in open(data_file))\n\n# create a DataFrame from the string read as a file\nraw_data = pd.read_csv(StringIO.StringIO(cleaned_file_as_string), index_col='id')\n\n# create the similarity matrix (not optimized for speed)\nsim_mat = pd.DataFrame()\n\nfor l1 in raw_data.columns:\n for l2 in raw_data.columns:\n sim_mat.ix[l1, l2] = metrics.mutual_info_score(raw_data[l1], raw_data[l2])\n\n# create a lookup table\ndef format_results(s):\n sorted_s = s.sort_values(ascending=False)\n return '\\n'.join(\"%.7f,%s\" %(score, label) for label,score in sorted_s.iteritems())\n\nlookup_table = dict((c, format_results(sim_mat[c])) for c in sim_mat.columns)\n\ndef get_similarities(variable):\n if variable not in lookup_table:\n return \"variable must be in: %s\" %lookup_table.keys()\n return \"mi,%s\\n%s\" % (variable, lookup_table[variable])\n","sub_path":"python/futurice.py","file_name":"futurice.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"395398293","text":"from pyramid.httpexceptions import HTTPFound\n\nimport notifications\nimport settings\nfrom alchemist.models import Settings\nfrom alchemist.system.route import route\n\n\n@route(path='/', permission='auth', renderer='layout/layout.jinja2')\ndef landing_view(request):\n if 'all_ids' in request.session:\n del request.session['all_ids']\n if 'search_query' in request.session:\n del request.session['search_query']\n if 'current_page' in request.session:\n del request.session['current_page']\n redirect = Settings.get('home_redirect')\n if request.user and request.user.primary_type:\n redirect = Settings.get('redirect_%s' % request.user.primary_type, redirect) or redirect\n if 'logout' in redirect and request.user and request.user.is_admin:\n redirect = Settings.get('home_redirect', '/connections')\n if redirect:\n return HTTPFound(redirect)\n return {}\n","sub_path":"alchemist/general/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"182843814","text":"from cacau.core.models import Store, Group, Product, ValidityProduct, Warning\nfrom django.contrib import admin\nfrom import_export import resources\nfrom import_export.admin import ImportExportMixin\n\nadmin.site.site_header = 'Cacau Crispim'\n\n\nclass StoreModelAdmin(admin.ModelAdmin):\n list_display = ('code', 'name', 'description')\n search_fields = ('code', 'name', 'description')\n\n\nclass GroupResource(resources.ModelResource):\n class Meta:\n model = Group\n exclude = ('id', 'product')\n skip_unchanged = True\n report_skipped = False\n\n # fields = ('code', 'description')\n\n\nclass GroupModelAdmin(ImportExportMixin, admin.ModelAdmin):\n resource_class = GroupResource\n list_display = ('code', 'name')\n search_fields = ('code', 'name')\n\n\nclass ProductResource(resources.ModelResource):\n class Meta:\n model = Product\n exclude = ('imported',)\n skip_unchanged = True\n report_skipped = False\n\n # fields = ('code', 'description')\n\n\nclass ProductModelAdmin(ImportExportMixin, admin.ModelAdmin):\n resource_class = ProductResource\n list_display = ('code', 'description')\n search_fields = ('code', 'description')\n\n\nclass ValidityProductModelAdmin(admin.ModelAdmin):\n list_display = ('store_id', 'product_id', 'lote', 'validity')\n search_fields = ('store_id', 'product_id', 'lote', 'validity')\n\n\nclass WarningModelAdmin(admin.ModelAdmin):\n list_display = ('description',)\n search_fields = ('description',)\n\n\nadmin.site.register(Product, ProductModelAdmin)\nadmin.site.register(Store, StoreModelAdmin)\nadmin.site.register(Group, GroupModelAdmin)\nadmin.site.register(ValidityProduct, ValidityProductModelAdmin)\nadmin.site.register(Warning, WarningModelAdmin)\n","sub_path":"cacau/core/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"456278639","text":"# -*- coding: utf-8\n\"\"\"\nGeneric odML validation framework.\n\"\"\"\n\nfrom . import dtypes\n\nLABEL_ERROR = 'error'\nLABEL_WARNING = 'warning'\n\n\nclass ValidationError(object):\n \"\"\"\n Represents an error found in the validation process.\n\n The error is bound to an odML-object (*obj*) or a list of those and contains\n a message and a rank which may be one of: 'error', 'warning'.\n \"\"\"\n\n def __init__(self, obj, msg, rank=LABEL_ERROR):\n self.obj = obj\n self.msg = msg\n self.rank = rank\n\n @property\n def is_warning(self):\n \"\"\"\n :returns: Boolean whether the current ValidationError has rank 'Warning'.\n \"\"\"\n return self.rank == LABEL_WARNING\n\n @property\n def is_error(self):\n \"\"\"\n :returns: Boolean whether the current ValidationError has rank 'Error'.\n \"\"\"\n return self.rank == LABEL_ERROR\n\n @property\n def path(self):\n \"\"\"\n :returns: The absolute path to the odml object the ValidationError is bound to.\n \"\"\"\n return self.obj.get_path()\n\n def __repr__(self):\n return \"\" % (self.rank,\n self.obj,\n self.msg)\n\n\nclass Validation(object):\n \"\"\"\n Validation provides a set of default validations that can used to validate\n an odml.Document. Custom validations can be added via the 'register_handler' method.\n\n :param doc: odml.Document that the validation will be applied to.\n \"\"\"\n\n _handlers = {}\n\n @staticmethod\n def register_handler(klass, handler):\n \"\"\"\n Adds a validation handler for an odml class. The handler is called in the\n validation process for each corresponding object.\n The *handler* is assumed to be a generator function yielding\n all ValidationErrors it finds.\n\n Section handlers are only called for sections and not for the document node.\n If both are required, the handler needs to be registered twice.\n\n :param klass: string corresponding to an odml class. Valid strings are\n 'odML', 'section' and 'property'.\n :param handler: validation function applied to the odml class.\n \"\"\"\n Validation._handlers.setdefault(klass, set()).add(handler)\n\n def __init__(self, obj):\n self.doc = obj # may also be a section\n self.errors = []\n\n self.validate(obj)\n\n if obj.format().name == \"property\":\n return\n\n for sec in obj.itersections(recursive=True):\n self.validate(sec)\n for prop in sec.properties:\n self.validate(prop)\n\n def validate(self, obj):\n \"\"\"\n Runs all registered handlers that are applicable to a provided odml class instance.\n Occurring validation errors will be collected in the Validation.error attribute.\n\n :param obj: odml class instance.\n \"\"\"\n handlers = self._handlers.get(obj.format().name, [])\n for handler in handlers:\n for err in handler(obj):\n self.error(err)\n\n def error(self, validation_error):\n \"\"\"\n Registers an error found during the validation process.\n \"\"\"\n self.errors.append(validation_error)\n\n def __getitem__(self, obj):\n \"\"\"\n Return a list of the errors for a certain object.\n \"\"\"\n errors = []\n for err in self.errors:\n if err.obj is obj:\n errors.append(err)\n return errors\n\n\n# ------------------------------------------------\n# validation rules\n\ndef object_required_attributes(obj):\n \"\"\"\n Tests that no Object has undefined attributes, given in format.\n\n :param obj: document, section or property.\n \"\"\"\n\n args = obj.format().arguments\n for arg in args:\n if arg[1] == 1:\n if not hasattr(obj, arg[0]):\n msg = \"Missing attribute %s for %s\" % (obj.format().name.capitalize(), arg[0])\n yield ValidationError(obj, msg, LABEL_ERROR)\n continue\n obj_arg = getattr(obj, arg[0])\n if not obj_arg and not isinstance(obj_arg, bool):\n msg = \"%s %s undefined\" % (obj.format().name.capitalize(), arg[0])\n yield ValidationError(obj, msg, LABEL_ERROR)\n\n\nValidation.register_handler('odML', object_required_attributes)\nValidation.register_handler('section', object_required_attributes)\nValidation.register_handler('property', object_required_attributes)\n\n\ndef section_type_must_be_defined(sec):\n \"\"\"\n Tests that no Section has an undefined type.\n\n :param sec: odml.Section.\n \"\"\"\n if sec.type is None or sec.type == '' or sec.type == 'undefined':\n yield ValidationError(sec, 'Section type undefined', LABEL_WARNING)\n\n\nValidation.register_handler('section', section_type_must_be_defined)\n\n\ndef section_repository_present(sec):\n \"\"\"\n 1. warn, if a section has no repository or\n 2. the section type is not present in the repository\n \"\"\"\n repo = sec.get_repository()\n if repo is None:\n msg = \"A section should have an associated repository\"\n yield ValidationError(sec, msg, LABEL_WARNING)\n return\n\n try:\n tsec = sec.get_terminology_equivalent()\n except Exception as exc:\n msg = \"Could not load terminology: %s\" % exc\n yield ValidationError(sec, msg, LABEL_WARNING)\n return\n\n if tsec is None:\n msg = \"Section type '%s' not found in terminology\" % sec.type\n yield ValidationError(sec, msg, LABEL_WARNING)\n\n\nValidation.register_handler('section', section_repository_present)\n\n\ndef document_unique_ids(doc):\n \"\"\"\n Traverse an odML Document and check whether all\n assigned ids are unique within the document.\n\n Yields all duplicate odML object id entries that are encountered.\n\n :param doc: odML document\n \"\"\"\n id_map = {doc.id: \"Document '%s'\" % doc.get_path()}\n for i in section_unique_ids(doc, id_map):\n yield i\n\n\ndef section_unique_ids(parent, id_map=None):\n \"\"\"\n Traverse a parent (odML Document or Section)\n and check whether all assigned ids are unique.\n\n A \"id\":\"odML object / path\" dictionary of additional 'to-be-excluded' ids may be\n handed in via the *id_map* attribute.\n\n Yields all duplicate odML object id entries that are encountered.\n\n :param parent: odML Document or Section\n :param id_map: \"id\":\"odML object / path\" dictionary\n \"\"\"\n if not id_map:\n id_map = {}\n\n for sec in parent.sections:\n for i in property_unique_ids(sec, id_map):\n yield i\n\n if sec.id in id_map:\n msg = \"Duplicate id in Section '%s' and %s\" % (sec.get_path(), id_map[sec.id])\n yield ValidationError(sec, msg)\n else:\n id_map[sec.id] = \"Section '%s'\" % sec.get_path()\n\n for i in section_unique_ids(sec, id_map):\n yield i\n\n\ndef property_unique_ids(section, id_map=None):\n \"\"\"\n Checks whether all ids assigned to the odML Properties of an odML Section are unique.\n\n A \"id\":\"odML object / path\" dictionary of additional 'to-be-excluded' ids may be\n handed in via the *id_map* attribute.\n\n Yields all duplicate odML object id entries that are encountered.\n\n :param section: odML Section\n :param id_map: \"id\":\"odML object / path\" dictionary\n \"\"\"\n if not id_map:\n id_map = {}\n\n for prop in section.properties:\n if prop.id in id_map:\n msg = \"Duplicate id in Property '%s' and %s\" % (prop.get_path(),\n id_map[prop.id])\n yield ValidationError(prop, msg)\n else:\n id_map[prop.id] = \"Property '%s'\" % prop.get_path()\n\n\nValidation.register_handler('odML', document_unique_ids)\n\n\ndef object_unique_names(obj, children, attr=lambda x: x.name,\n msg=\"Object names must be unique\"):\n \"\"\"\n Tests that object names within one Section are unique.\n\n :param obj: odml class instance the validation is applied on.\n :param children: a function that returns the children to be considered.\n This is to be able to use the same function for sections and properties.\n :param attr: a function that returns the item that needs to be unique\n :param msg: error message that will be registered upon a ValidationError.\n \"\"\"\n names = set(map(attr, children(obj)))\n if len(names) == len(children(obj)):\n return # quick exit\n names = set()\n for i in children(obj):\n if attr(i) in names:\n yield ValidationError(i, msg, LABEL_ERROR)\n names.add(attr(i))\n\n\ndef section_unique_name_type(obj):\n \"\"\"\n Tests that the values of names and types within the scope of a Section are unique.\n\n :param obj: odml class instance the validation is applied on.\n \"\"\"\n for i in object_unique_names(\n obj,\n attr=lambda x: (x.name, x.type),\n children=lambda x: x.sections,\n msg=\"name/type combination must be unique\"):\n yield i\n\n\ndef property_unique_names(obj):\n \"\"\"\n Tests that the values of Property names within the scope of a Section are unique.\n\n :param obj: odml class instance the validation is applied on.\n \"\"\"\n for i in object_unique_names(obj, lambda x: x.properties):\n yield i\n\n\nValidation.register_handler('odML', section_unique_name_type)\nValidation.register_handler('section', section_unique_name_type)\nValidation.register_handler('section', property_unique_names)\n\n\ndef property_terminology_check(prop):\n \"\"\"\n 1. warn, if there are properties that do not occur in the terminology.\n 2. warn, if there are multiple values with different units or the unit does\n not match the one in the terminology.\n \"\"\"\n if not prop.parent:\n return\n\n tsec = prop.parent.get_terminology_equivalent()\n if tsec is None:\n return\n try:\n tsec.properties[prop.name]\n except KeyError:\n msg = \"Property '%s' not found in terminology\" % prop.name\n yield ValidationError(prop, msg, LABEL_WARNING)\n\n\nValidation.register_handler('property', property_terminology_check)\n\n\ndef property_dependency_check(prop):\n \"\"\"\n Produces a warning if the dependency attribute refers to a non-existent attribute\n or the dependency_value does not match.\n \"\"\"\n if not prop.parent:\n return\n\n dep = prop.dependency\n if dep is None:\n return\n\n try:\n dep_obj = prop.parent[dep]\n except KeyError:\n msg = \"Property refers to a non-existent dependency object\"\n yield ValidationError(prop, msg, LABEL_WARNING)\n return\n\n if prop.dependency_value not in dep_obj.values[0]:\n msg = \"Dependency-value is not equal to value of the property's dependency\"\n yield ValidationError(prop, msg, LABEL_WARNING)\n\n\nValidation.register_handler('property', property_dependency_check)\n\n\ndef property_values_check(prop):\n \"\"\"\n Tests that the values are of consistent dtype.\n If dtype is not given, infer from first item in list.\n\n :param prop: property the validation is applied on.\n \"\"\"\n\n if prop.dtype is not None and prop.dtype != \"\":\n dtype = prop.dtype\n elif prop.values:\n dtype = dtypes.infer_dtype(prop.values[0])\n else:\n return\n\n for val in prop.values:\n if dtype.endswith(\"-tuple\"):\n tuple_len = int(dtype[:-6])\n if len(val) != tuple_len:\n msg = \"Tuple of length %s not consistent with dtype %s!\" % (len(val), dtype)\n yield ValidationError(prop, msg, LABEL_WARNING)\n else:\n try:\n dtypes.get(val, dtype)\n except ValueError:\n msg = \"Property values not of consistent dtype!\"\n yield ValidationError(prop, msg, LABEL_WARNING)\n\n\nValidation.register_handler('property', property_values_check)\n","sub_path":"odml/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":11976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"404775673","text":"import re\nimport MeCab\n\nclass PosReg:\n\n def __init__(self, mecab_option=\"\"):\n self.tagger = MeCab.Tagger(mecab_option)\n\n def regex_replace(self, regex, sep=\",\"):\n reg_cp = regex.replace(\" \", \"\")\n reg_cp = reg_cp.replace(\"詞\", \"詞{}?\".format(sep))\n reg_cp = reg_cp.replace(\"号\", \"号{}?\".format(sep))\n reg_cp = re.compile(r\"{}\".format(reg_cp))\n return reg_cp\n \n def finditer(self, regex, sentence, sep=\",\"):\n tmp = [x.split(\"\\t\") for x in self.tagger.parse(sentence).split(\"\\n\") if '\\t' in x]\n reg_cp = self.regex_replace(regex, sep)\n pattern = sep.join([x[1].split(\",\")[0] for x in tmp]) + sep\n words = [x[0] for x in tmp]\n for m in reg_cp.finditer(pattern):\n start, length = m.start(), len(m.group())\n end = start + length\n i1 = pattern[:start].count(sep)\n i2 = pattern[:end].count(sep)\n yield words[i1:i2]\n\n\nif __name__ == \"__main__\":\n sent = \"イチローがヒットを打った\"\n regex1 = r\"(名詞|動詞)(助動詞)?\"\n regex2 = r\"動詞 助動詞\"\n \n p = PosReg()\n print([x for x in p.finditer(regex1, sent)])\n print([x for x in p.finditer(regex2, sent)])\n","sub_path":"posregex/posregex.py","file_name":"posregex.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"27329756","text":"#unittest + ddt\n\nfrom Common.DoExel import DoExcel\nfrom Common.myrequest import myRquest\nimport ddt,time,os,unittest\nfrom Common.myLogger import MyLoggger\nfrom Common.dir_config import *\nfrom Common import parsing_response\nimport re\n\nlogger = MyLoggger(\"zzz\",log_dir+time.strftime('%Y-%m-%d %H%M',time.localtime(time.time()))+'.log')\n\n#传入测试地址返回测试数据\npath = casedata_dir +'/api_qcd.xlsx'\nde = DoExcel(path,logger)\nall_case_datas = de.get_caseData_all()\n\nglobal_value = {}\n\n\n@ddt.ddt\nclass TestData(unittest.TestCase):\n\n global global_value\n\n @classmethod\n def tearDownClass(cls):\n #执行结束,修改初始数据保证测试完成\n de.Modify_init_data()\n de.save_excel(path)\n\n def setUp(self):\n logger.info('################################开始执行测试用例#######################')\n\n\n def tearDown(self):\n logger.info('################################执行测试结束#######################')\n\n @ddt.data(*all_case_datas)\n def test_api(self,case_data):\n logger.info('接口请求地址:{}'.format(case_data['url']))\n logger.info('接口请求类型:{}'.format(case_data['method']))\n logger.info('接口请求数据:{}'.format(case_data['request_data']))\n #查找测试数据中是否有需要进行动态替换的数据,如果有动态替换\n if case_data['request_data'] is not None and len(global_value)>0:\n for key ,value in global_value.items():\n if case_data['request_data'].find(key) != -1:\n #使用find函数查询字符串中是否包含子字符串\n case_data['request_data'] = case_data['request_data'].replace(key, value)\n logger.info('动态替换后的请求数据:{}'.format(case_data['request_data']))\n\n #eval中参数不能为Non\n print(case_data['url'],case_data['method'],case_data['request_data'])\n res = myRquest(case_data['url'],case_data['method'],case_data['request_data'])\n print(res.text)\n logger.info('返回状态码:{}'.format(res.status_code))\n logger.info('接口返回数据:')\n logger.info(res.text)\n logger.info('接口请求期望数据:')\n #判断测试数据到当中,是否有关联字段,如果有,则需要提取出来,按表达式提取,并且赋值给指定变量\n if 'related_exp' in case_data.keys():\n logger.info('需要从响应结果中提取数据')\n # res = parsing_response.get_relatedData_from_response(res.text,case_data['related_exp'])\n temp = case_data['related_exp'].split('=')\n print(temp[0],temp[1])\n res_id = re.findall(temp[1],res.text)\n print(res_id)\n global_value[temp[0]] = res_id[0]\n logger.info('动态获取响应值中的数据')\n logger.info(global_value[temp[0]])\n\n\n logger.info(case_data['response_data'])\n logger.info('期望结果与实际结果的比对方式:')\n if case_data['is_all'] == 0 :\n logger.info('全职匹配模式')\n try:\n assert res.text == case_data['response_data']\n logger.info('结果比对成功,测试通过')\n except AssertionError:\n logger.info('结果匹配失败')\n raise AssertionError\n else:\n logger.info('部分匹配模式')\n try:\n self.assertIn(case_data['response_data'], res.text)\n logger.info('结果比对成功,测试通过')\n except AssertionError:\n logger.info('结果匹配失败')\n raise AssertionError\n\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"python3_api_framework/TestCase/test_api_v5.py","file_name":"test_api_v5.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"525003769","text":"import json\n\nconfig = None\nconfig_path = r\"classifiers/EEGNet/eegnet_master/config.json\"\ntry:\n with open(config_path, \"r\") as f:\n config = json.loads(f.read())\n config = config[\"Config\"]\n\nexcept FileNotFoundError:\n print(\"*** EEGNet: Invalid config path\")\n exit(-1)\n\nexcept json.decoder.JSONDecodeError:\n print(\"*** EEGNet: Invalid config json\")\n exit(-1)\n\nexcept KeyError:\n print(\"*** EEGNet: Config not in config keys\")\n exit(-1)\n\n# ========================================\n# Settings\n# ========================================\ncuda = config[\"cuda\"]\n\nCUDA_VISIBLE_DEVICES = config[\"CUDA_VISIBLE_DEVICES\"]\n\nprintSummary = config[\"printSummary\"]\n\nauto_eog_correct = config[\"auto_eog_correct\"]\n# -1\nremove_label = config[\"remove_label\"]\n# [[2, 0], [3, 1], [4, 2]]\n# [[-1, 0], [1, 0], [0, 1]]\nlabels_union = config[\"labels_union\"]\n\nears_channels = config[\"ears_channels\"]\n\ndevice_sample_rate = config[\"device_sample_rate\"]\n\ntest_size = config[\"test_size\"]\n\nval_size = config[\"val_size\"]\n\nepochs = config[\"epochs\"]\n\nbatch_size = config[\"batch_size\"]\n\ncrop = config[\"crop\"]\n\ncrop_count = config[\"crop_count\"]\n\ncrop_len = config[\"crop_len\"]\n# if not crop:\n# crop_len = 750\n\nstep = round((750 - crop_len) / (crop_count - 1)) # step = (750 - crop_len) / (crop_count - 1) !!!\n# if not crop:\n# step = 750\n\nstart = 0\n\nbasel = config[\"basel\"]\n\nstd_ = config[\"std_\"]\n\nbandpass = config[\"bandpass\"]\n\nsample_rate = config[\"sample_rate\"]\n\ndecimat = config[\"decimat\"]\n\ntransform = config[\"transform\"]\n\n# FP1 FP2\t\t\t 1 2\n# F7 F3 FZ F4 F8\t\t 3 4 5 6 7\n# T3 C3 CZ C4 T4\t\t 8 9 10 11 12\n# A1 T5 P3 PZ P4 T6 A2\t 13 14 15 16 17 18 19\n# PO3 O1 OZ O2 PO4\t\t 20 21 22 23 24\nch_names = config[\"ch_names\"]","sub_path":"classifiers/EEGNet/eegnet_master/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"494627235","text":"'''\nInventory Module to update and append Invoice File.\n'''\nimport csv\nfrom functools import partial\n\ndef add_furniture(invoice_file, customer_name, item_code,\n item_description, monthly_price):\n '''Create and append invoice file.'''\n\n with open(invoice_file, 'a') as csvfile:\n row_format = [customer_name, item_code,\n item_description, str(monthly_price)\n ]\n\n write_row = ','.join(row_format)\n csvfile.write(write_row)\n csvfile.write('\\n')\n\ndef single_customer(customer_name, invoice_file):\n \"\"\"This function returns a function to add new rental items to\n invoice file.\"\"\"\n\n def add_customer(rental_items):\n\n with open(rental_items, 'r') as csvfile:\n new_item = partial(add_furniture, invoice_file, customer_name)\n reader = csv.reader(csvfile)\n\n for row in reader:\n item_code = row[0]\n item_description = row[1]\n monthly_price = row[2]\n new_item(item_code, item_description, monthly_price)\n\n return add_customer\n","sub_path":"students/N0vA/lesson08/assignment/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"238375643","text":"def get_line(i, lines):\n return lines[i][:-1].split(' ')\n\n\ndef get_min_xy(arr):\n x = arr[0].bx\n y = arr[0].by\n\n for c in arr:\n if x and c.bx < x:\n x = c.bx\n if y and c.by < y:\n y = c.by\n\n return [x, y]\n\n\ndef get_max_xy(arr):\n x = arr[0].tx\n y = arr[0].ty\n\n for c in arr:\n if x and c.tx > x:\n x = c.tx\n if y and c.ty > y:\n y = c.ty\n\n return [x + 1, y + 1]\n","sub_path":"Lab2/EuroDiffusion/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"546531345","text":"import unittest\nimport settings\nfrom github_api import compute_api_cooldown as compute\n\n\nclass CooldownTests(unittest.TestCase):\n def test_no_requests(self):\n \"\"\" no requests means always sleep to the reset time + padding \"\"\"\n pad = settings.API_COOLDOWN_RESET_PADDING\n self.assertEqual(60+pad, compute(0, 60))\n self.assertEqual(61+pad, compute(0, 61))\n self.assertEqual(62+pad, compute(0, 62))\n\n # test a negative remaining as well\n self.assertEqual(60+pad, compute(-1, 60))\n\n def test_longer_and_longer(self):\n \"\"\" fewer requests = longer wait \"\"\"\n c1 = compute(5000, 3600)\n c2 = compute(4000, 3600)\n c3 = compute(3000, 3600)\n self.assertLess(c1, c2)\n self.assertLess(c2, c3)\n","sub_path":"tests/github_api/misc_test.py","file_name":"misc_test.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"324237317","text":"import scrapy\n\nfrom fgoScrap.items import EssenceItem\n\n\n#scrapy crawl essencelist -o [nom-de-loutput].json\nclass EssenceScraper(scrapy.Spider):\n name = \"essencelist\"\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'fgoScrap.pipelines.EssencePipeline': 400\n }\n }\n\n def start_requests(self):\n urls = [\n 'https://fate-go.cirnopedia.org/craft_essence.php?JP=0'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self,response):\n for row in response.xpath('//table[@id=\"rounded-corner\"]/tbody/tr[@class=\"reg US\"]'):\n item = EssenceItem()\n item['name'] = row.xpath('td[4]/@sorttable_customkey').extract()\n item['stars'] = row.xpath('td[2]/text()').extract()\n item['image_url'] = row.xpath('td[3]/a/img/@style').extract()\n yield item\n\n","sub_path":"fgo/fgoScrap/fgoScrap/spiders/essenceScraper.py","file_name":"essenceScraper.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"205366583","text":"#coding=utf-8\nfrom uliweb import settings\nfrom uliweb.orm import get_model\n\n\n#流程管理类\nclass Waterdrop_query():\n\n #通过流程定义ID查询相关步骤和条件\n @staticmethod\n def query_mix_from_define(defineid):\n WFDefine = get_model('wfdefine')\n WFMix = get_model('wfmix')\n WFStep = get_model('wfstep')\n WFCondition = get_model('wfcondition')\n wfd = WFDefine.get(WFDefine.c.id == defineid)\n if not wfd:\n return None\n mixlist = []\n for each_mix in list(wfd.mixs.all()):\n mixlist.append((each_mix.step.to_dict(), each_mix.condition.to_dict(), each_mix.is_last))\n return mixlist\n\n #通过流程定义ID查询相关步骤和条件\n @staticmethod\n def default_workflow_defineid():\n WFDefine = get_model('wfdefine')\n wfd = WFDefine.filter(WFDefine.c.name == settings.DEFAULT_WORKFLOW.DEFINE).one()\n if not wfd:\n wfd = WFDefine.all().order_by(WFDefine.c.created_date.asc()).one()\n return wfd.id if wfd else -1\n\n #查询状态\n @staticmethod\n def query_status(code):\n WFStatus = get_model('wfstatus')\n wfs = WFStatus.filter(WFStatus.c.code == code).one()\n return wfs.to_dict() if wfs else None\n\n #查询下一状态\n @staticmethod\n def query_next_status(code):\n WFStatus = get_model('wfstatus')\n wfs = WFStatus.filter(WFStatus.c.code == code).one()\n if not wfs:\n return None\n WFStatusRoute = get_model('wfstatusroute')\n wfsr = WFStatusRoute.filter(WFStatusRoute.c.from_status == wfs.id)\n return [ {'to_status' : er.to_status.to_dict(), 'condition' : er.condition.to_dict(), 'weight' : er.weight} for er in list(wfsr)]","sub_path":"waterdrop/define/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"628585787","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.3'\n# jupytext_version: 0.8.6\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %matplotlib inline\nfrom fastai.basics import *\n\npath = Config.data_path()/'mnist'\npath\n\npath.ls()\n\nwith gzip.open(path/'mnist.pkl.gz', 'rb') as f:\n ((train_x, train_y), (val_x, val_y), _) = pickle.load(f, encoding='latin-1')\ntrain_x.shape\n\nx = train_x[0].reshape(28, 28)\nplt.imshow(x, cmap='gray')\n\ntrain_x, train_y, val_x, val_y = map(torch.tensor, (train_x, train_y, val_x, val_y))\ntrain_x.shape\n\nbs = 64\ntrain_ds = TensorDataset(train_x, train_y)\nval_ds = TensorDataset(val_x, val_y)\ndata = DataBunch.create(train_ds, val_ds, bs=bs)\ndata\n\nclass MNIST_Lin(nn.Module):\n def __init__(self):\n super().__init__()\n self.lin = nn.Linear(784, 10)\n \n def forward(self, x):\n return self.lin(x)\n\nloss_func = nn.CrossEntropyLoss()\n\nmodel = MNIST_Lin()\n\ndef update(x, y, lr):\n y_hat = model(x)\n wd = 1e-5 #regularization factor\n #y_hat = np.argmax(y_hat, 1)\n w = 0.\n for p in model.parameters():\n w += ((p**2).sum())\n loss = loss_func(y_hat, y) + wd * w\n \n loss.backward()\n with torch.no_grad():\n for p in model.parameters():\n p.sub_(lr * p.grad)\n p.grad.zero_()\n return loss.item()\n\nlr = 2e-2\n\nlosses = [update(x, y, lr) for x, y in data.train_dl]\n\nplt.plot(losses)\n\n# Using Non linear model for predicting digits\n\nclass MNIST_NN(nn.Module):\n def __init__(self):\n super().__init__()\n self.lin1 = nn.Linear(784, 50)\n self.relu1 = nn.ReLU()\n self.lin2 = nn.Linear(50, 10)\n \n def forward(self, x):\n x1 = self.lin1(x)\n x2 = self.lin2(self.relu1(x1))\n return x2\n\nmodel = MNIST_NN()\n\nlosses = [update(x, y, lr) for x, y in data.train_dl]\n\nplt.plot(losses)\n\n\n","sub_path":"nbs/dl1/lesson5-sgd-mnist-manik.py","file_name":"lesson5-sgd-mnist-manik.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"71832585","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\nexec (compile(open(path.join(here, 'forpylib', 'release.py')).read(), 'release.py',\n 'exec'), globals(), locals())\n\n\n\n\nLICENSE = open('LICENSE').read()\n\n\n\n\n\n\nLONG_DESCRIPTION = open('README.md').read().replace(\"`_\", \"`\")\nsetup(\n name='forpylib',\n version=version,\n packages=find_packages(),\n package_dir={'forpylib': 'forpylib'},\n packages_data ={'forpylib': ['datasets/*.csv']} ,\n description='A Python library for forest optimization & simulation',\n long_description=open('README.md').read(),\n author=u'Jose Mario',\n author_email='josemario.gonzalez@usc.es',\n url='http://forpylib.readthedocs.org/en/latest/',\n license='BSD',\n keywords=[\n 'forest', 'simulator', 'DSS', 'optimization'\n 'decision', 'support', 'system', 'growth'\n ],\n install_requires=['numpy>=1.7.1', 'pandas>=0.16.2', 'matplotlib>=1.4.3','scipy>=0.17.0', 'numexpr>=2.1', 'bottleneck', 'tabulate'],\n zip_safe=False,\n classifiers=(\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Education',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent',\n 'License :: OSI Approved :: Modified BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Scientific/Engineering :: Forest Management'\n ))\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"356264740","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nN_boundary_points = 300\n\ndef rotate(X, angle_in_degrees):\n theta = np.radians(angle_in_degrees)\n c, s = np.cos(theta), np.sin(theta)\n R = np.array([[c, -s], [s, c]]) # rotation matrix\n return np.dot(X, R)\n\n\ndef train_and_plot(network, epochs, batch_size, X, D, train_fraction):\n N_train = int(X.shape[0] * train_fraction)\n I = np.arange(X.shape[0])\n np.random.shuffle(I)\n\n # y_mean = X.mean(axis=0)\n # y_std = X.std(axis=0)\n # X = (X - y_mean) / y_std\n\n x_train = X[I[0:N_train], ]\n d_train = D[I[0:N_train]]\n x_test = X[I[N_train:], ]\n d_test = D[I[N_train:]]\n\n training_losses, validation_losses = network.train(x_train, d_train,\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(x_test, d_test))\n\n plt.figure(figsize=(5.3, 7.5))\n ax1 = plt.subplot(211)\n ax2 = plt.subplot(212)\n\n ax1.plot(np.arange(epochs), training_losses, label=\"Training Loss\")\n ax1.plot(np.arange(epochs), validation_losses, label=\"Validation Loss\")\n ax1.set_xlabel(\"Epoch\")\n ax1.set_ylabel(\"Error\")\n ax1.legend()\n\n x_min, x_max = x_test[:, 0].min() - .2, x_test[:, 0].max() + .2\n y_min, y_max = x_test[:, 1].min() - .2, x_test[:, 1].max() + .2\n # grid stepsize\n h = max(x_max - x_min, y_max - y_min) / N_boundary_points\n\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n Z = network.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n Z[Z > 0.5] = 1\n Z[Z <= 0.5] = 0\n\n x_plot = x_test\n d_plot = d_test\n\n crosses = np.where(d_plot == 0)[0]\n dots = np.where(d_plot != 0)[0]\n\n ax2.plot(x_plot[crosses, 0], x_plot[crosses, 1], 'ro')\n ax2.plot(x_plot[dots, 0], x_plot[dots, 1], 'bo')\n ax2.contour(xx, yy, Z, cmap=plt.cm.Paired)\n ax2.axis([x_min, x_max, y_min, y_max])\n plt.show(block=False)","sub_path":"tests/tools/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"291781514","text":"from __future__ import unicode_literals\nfrom django.conf import settings\nfrom django.db import migrations\n\n\ndef add_pages(apps, schema_editor):\n Page = apps.get_model(\"flatpages\", \"Flatpage\")\n Site = apps.get_model(\"sites\", \"Site\")\n try:\n site = Site.objects.get(id=settings.SITE_ID)\n except Site.DoesNotExist:\n site = Site.objects.create(domain='example.com', name='example.com')\n site.save()\n home_page = Page(\n url=\"/\",\n title=\"Главная\",\n content=\"\"\"\n Добро пожаловать на наш сайт.\n Мы предоставляем товар по самым бла бла бла бла\n и бла ценам гарантии и прочее\n \"\"\",\n template_name=\"flatpages/default.html\"\n )\n about_page = Page(\n url=\"/about/\",\n title=\"О компании\",\n content=\"\"\"\n Наша компании основана в ххх году, при цпре горохе продавали горох,\n ну а сейчас все подряд\n Занимаем лидирующие позиции и прочее.\n МЫ ВАМ НУЖНЫ!\n \"\"\",\n template_name=\"flatpages/default.html\"\n )\n contact_page = Page(\n url=\"/contact/\",\n title=\"Контакты\",\n content=\"\"\"\n Наши контакты:\n\n эл. почта: test@test.ru\n телефон: +7 999 999 55 55\n skype: help_djbook\n\n \"\"\",\n template_name=\"flatpages/default.html\"\n )\n\n pages_list = [home_page, about_page, contact_page]\n for page in pages_list:\n page.save()\n page.sites.add(site)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('flatpages', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(add_pages)\n ]\n","sub_path":"core/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"501985487","text":"'''\r\nself in classes\r\n1. self represents the instance of the class.\r\n2. By use of self keyword we can access the attributes and methods of the class in python.\r\n3. self acts as a pointer which helps the methods of the class to tell them to which instance/object, you have to operate.\r\n4. We use self by convention, it is not mendatory to use self, you can use anything in place of self, like aakash but it should be letters not numbers or list or anything.\r\n Reason:\r\n We only require something to represent the instance of the class, it does not matter who is representing the class of method, it can be self, or any other name\r\n'''\r\n\r\n'''\r\nPoint1 explanation:\r\nself represents the instance of the class.\r\n'''\r\n\r\nclass computer:\r\n def __init__(self,name,age): # This self represents the instance of the class\r\n self.name = name\r\n self.age = age\r\n def update(self):\r\n self.age = 12\r\n\r\nc1 = computer(\"ram\", 24)\r\n''' \r\nHere self in the class represents the instance c1 of the class\r\nNow self.name represents c1.name in the class, self.age represents the c1.age in the class.\r\nn \r\n'''\r\n'''\r\nExplanation of Point 2 and Point 3:\r\nBy use of self keyword we can access the attributes and methods of the class in python.\r\nself acts as a pointer which helps the methods of the class to tell them to which instance/object, you have to operate.\r\n'''\r\nclass computer:\r\n def __init__(self,name,age):\r\n self.name = name\r\n self.age = age\r\n def update(self):\r\n self.age = 12\r\n\r\nc1 = computer(\"ram\", 24)\r\nc2 = computer(\"shyam\", 24)\r\nprint(c1.age)\r\nprint (c2.age)\r\nprint(\"\")\r\nc1.update()\r\n'''This is the use of self, you have not told update, which object c1 or c2 should be used to execute commands, but what self will do\r\nit will take c1 to execute commands because you have written c1.update'''\r\nprint(c1.age)\r\nprint(c2.age)\r\n\r\n\r\nprint(\"\")\r\n'''\r\nExample 3:\r\nWe use self by convention, it is not mendatory to use self, you can use anything in place of self, like aakash or anything\r\n'''\r\nclass Ram:\r\n def __init__(aakash, y):# here aakash is repersenting the instance of class Ram\r\n aakash.y = y\r\n def love(aakash):\r\n print(\"jai shri ram\")\r\n\r\naak = Ram(2)\r\nprint(aak.y)\r\naak.love()","sub_path":"45_self.py","file_name":"45_self.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"401851895","text":"import time\nfrom random import randrange\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nPORT = 8000\n\n\ndef primes(n):\n if n <= 2:\n return []\n sieve = [True] * (n + 1)\n for x in range(3, int(n ** 0.5) + 1, 2):\n for y in range(3, (n // x) + 1, 2):\n sieve[(x * y)] = False\n\n return [ 2 ] + [ i for i in range(3, n, 2) if sieve[i] ]\n\n\nclass Handler(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n def do_GET(self):\n self._set_headers()\n time.sleep(0.01)\n self.wfile.write((\"%f\" % time.time()).encode('utf-8'))\n\n\nhttpd = HTTPServer((\"0.0.0.0\", PORT), Handler)\nprint(\"serving at port\", PORT)\n\nhttpd.serve_forever()\n","sub_path":"meetup_13/latency_analysis/files/examples/03.sample_server_throughput1a.py","file_name":"03.sample_server_throughput1a.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"336492419","text":"\nimport logging\nimport os\n\nfrom tqdm import tqdm\n\nfrom beam_search import BeamSearch\nfrom data_load import get_batch\nfrom hparams import Hparams\nfrom model import Transformer\nfrom utils import save_variable_specs, import_tf\n\nlogging.basicConfig(level=logging.INFO)\n\n\n\nlogging.info(\"# hparams\")\nhparams = Hparams()\nparser = hparams.parser\nargs = parser.parse_args()\nhp = vars(args)\nprint(hp)\n# import tensorflow\ngpu_list = [str(i) for i in list(range(hp['gpu_nums']))]\ntf = import_tf(gpu_list)\nprint(gpu_list)\n\ntrain_batches, num_train_batches, num_train_samples = get_batch(hp['train_seg_x_dir'],\n hp['train_seg_y_dir'],\n hp,\n hp['batch_size'],\n hp['gpu_nums'],\n shuffle=True)\nhandle = tf.placeholder(tf.string, shape=[])\niter = tf.data.Iterator.from_string_handle(handle, train_batches.output_types, train_batches.output_shapes)\nxs, fre, ys = iter.get_next()\n# create a iter of the correct shape and type\ntraining_iter = train_batches.make_one_shot_iterator()\n\n\nm = Transformer(hp)\n\n# get op\n\nloss, train_op, global_step, train_summaries,lr = m.train(xs,fre, ys)\n\nfrom data_load import Vocab\nvocab = Vocab(hp['vocab_path'],hp['vocab_size'])\ntoken2idx = vocab.word2id\nidx2token = vocab.id2word\n\nbs = BeamSearch(m, hp['beam_size'], list(idx2token.keys())[2], list(idx2token.keys())[3], idx2token, hp['max_dec_len'], m.x,\n m.decoder_inputs, m.logits)\nsaver = tf.train.Saver(max_to_keep=hp['num_epochs'])\nwith tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n ckpt = tf.train.latest_checkpoint('./logdir')\n if ckpt is None:\n logging.info(\"Initializing from scratch\")\n sess.run(tf.global_variables_initializer())\n save_variable_specs(os.path.join('./logdir', \"specs\"))\n else:\n saver.restore(sess, ckpt)\n summary_writer = tf.summary.FileWriter('./logdir', sess.graph)\n\n # Iterator.string_handle() get a tensor that can be got value to feed handle placeholder\n training_handle = sess.run(training_iter.string_handle())\n total_steps = hp['num_epochs'] * num_train_batches\n _gs = sess.run(global_step)\n for i in tqdm(range(_gs, total_steps+1)):\n loss_,_, _gs, _summary,lr_ = sess.run([loss,train_op, global_step, train_summaries,lr], feed_dict={handle: training_handle})\n summary_writer.add_summary(_summary, _gs)\n print('loss is :', loss_,'learning rate is ',lr_)\n if _gs % (500) == 0 and _gs != 0:\n print(\"steps {} is done\".format(_gs))\n ckpt_name = os.path.join('./model', './model')\n saver.save(sess, ckpt_name, global_step=_gs)\n summary_writer.close()\n","sub_path":"transformer_pg_neg/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"346791546","text":"from Server import XMLParser\nfrom random import shuffle\n\n__author__ = 'ivan'\n\nfrom bottle import route, run, template, request\nimport vk\nimport json\nfrom Server.VKQueries import get_vk_friends\n\nsession = vk.Session()\napi = vk.API(session)\n#print(api.users.get(user_ids=[1, 2, 3, 1000342]))\n#print(api.friends.get(user_id=12969666, orderd='hints', fields='city, domain'))\n# friends = api.friends.get(user_id=12969666, fields='bdate,photo_200_orig')\n# print(friends)\n\n@route('/')\ndef index():\n return 'Hello user! :)'\n\n\n@route('/friends', method='GET')\ndef login():\n id_vk = request.GET.get('id_vk', '')\n print(get_vk_friends(id_vk, 10))\n\n return get_vk_friends(id_vk, 10)\n # friends = api.friends.get(user_id=id_vk, fields='bdate,photo_200_orig', count=10)\n # print(friends[0])\n # # Return json with first_name, last_name, bdate, img_url\n # #: Разобраться с bdate и научиться нормально отсылать\n #\n # res_d = []\n # for fr in friends:\n # elem = {}\n #\n # if 'bdate' in fr:\n # for x in fields:\n # elem[x] = fr[x]\n #\n # res_d.append(elem)\n #\n # return json.dumps(res_d)\n\n # res = ''\n # for fr in friends:\n # if 'bdate' in fr:\n # res += ' '+ fr['bdate'] +''\n # res += '

'\n #\n # return res\n\n\n@route('/gifts', method='GET')\ndef gifts():\n id_vk = request.GET.get('id_vk', '')\n low_price = request.GET.get('low_price', '')\n high_price = request.GET.get('high_price', '')\n\n # sport_list = XMLParser.deserialize_list('SerializedLists/sport')\n # shuffle(sport_list)\n # res = sport_list[0:50]\n\n sport_list = XMLParser.deserialize_list('SerializedLists/sport_cloth')\n shuffle(sport_list)\n #res = sport_list[0:50]\n res = []\n\n for i in range(50):\n if 'жен' not in sport_list[i]['name'].lower() and 'дев' not in sport_list[i]['name'].lower():\n res.append(sport_list[i])\n\n #\n # accessories_phones = XMLParser.deserialize_list('SerializedLists/accessories-phone')\n # shuffle(accessories_phones)\n # res.extend(accessories_phones[0:10])\n #\n # computer_games = XMLParser.deserialize_list('SerializedLists/computer_games')\n # shuffle(computer_games)\n # res.extend(computer_games[0:10])\n\n\n shuffle(res)\n return json.dumps(res)\n #return '' + id_vk + '
' + low_price + '
' + high_price + '
'\n\n\n@route('/text')\ndef test():\n f = open('1133677.xml')\n p = f.read()\n return p\n\n\n@route('/data/XML/')\ndef test(name):\n print(name)\n f = open('XML/' + name)\n res = ''\n for ind, line in enumerate(f):\n #Skip first 2 lines\n if ind == 0 or ind == 1:\n continue\n res += line\n #p = f.read()\n #return p\n return res\n\n\nrun(host='192.168.43.244', port=9090)\n","sub_path":"Server/Server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"124417685","text":"# -*- coding:utf-8 -*-\n\n\n# Given a binary tree, return all root-to-leaf paths.\n#\n# Note: A leaf is a node with no children.\n#\n# Example:\n#\n#\n# Input:\n#\n# 1\n# / \\\n# 2 3\n# \\\n# 5\n#\n# Output: [\"1->2->5\", \"1->3\"]\n#\n# Explanation: All root-to-leaf paths are: 1->2->5, 1->3\n#\n\n\n# 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 binaryTreePaths(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[str]\n \"\"\"\n if not root:\n return []\n P = []\n if root.left==None and root.right==None:\n return [str(root.val)]\n else:\n if root.left!=None:\n self.Path(root.left, P, str(root.val))\n if root.right!=None:\n self.Path(root.right, P, str(root.val))\n return P\n \n \n \n def Path(self, root, P, p):\n if root.left==None and root.right==None:\n P.append(p+'->'+str(root.val))\n else:\n if root.left!=None:\n self.Path(root.left, P, p+'->'+str(root.val))\n if root.right!=None:\n self.Path(root.right, P, p+'->'+str(root.val))\n \n","sub_path":"0257-binary-tree-paths/binary-tree-paths.py","file_name":"binary-tree-paths.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"630877845","text":"from retriever_base import RetrieverBase\nfrom datetime import datetime, timedelta\nfrom botocore.errorfactory import ClientError\nimport json\nimport os\nimport re\nimport pandas as pd\n\n\nclass GoalDataRetriever(RetrieverBase):\n def __init__(self, **kwargs):\n super(GoalDataRetriever, self).__init__(**kwargs)\n self.today = datetime.today()\n self.yesterday = self.today - timedelta(days=1)\n\n def execute(self):\n goal_obj = self.s3.Object(self.options['stat_bucket'],\n self.options['stat_prefix'] + self.options['goal_object'])\n goal_data = json.loads(goal_obj.get()['Body'].read())\n for g in goal_data:\n self.execute_result_yesterday(g)\n\n def execute_result_yesterday(self, g):\n q = ''\n q += \"tid = '{0}'\".format(g['container'])\n q += ' AND year = {0}'.format(self.yesterday.strftime('%Y'))\n q += ' AND month = {0}'.format(self.yesterday.month)\n q += ' AND day = {0}'.format(self.yesterday.day)\n\n # support eq mode only\n q += \" AND JSON_EXTRACT_SCALAR(qs, '$.o_s') = '{0}'\".format(re.sub(r'\\'', '\\'\\'', g['target']))\n\n if g['path']:\n # support eq mode only\n q += \" AND regexp_like(JSON_EXTRACT_SCALAR(qs, '$.dl'), '^http?://[^/]+{0}$')\".format(\n re.sub(r'\\'', '\\'\\'', g['path']))\n\n sql = \"\"\"SELECT \nCOUNT(qs) as e_count,\nCOUNT(DISTINCT JSON_EXTRACT_SCALAR(qs, '$.cid')) as u_count\nFROM {0}.{1}\nWHERE {2}\n\"\"\".format(self.options['athena_database'], self.options['athena_table'], q)\n\n result = self._execute_athena_query(sql)\n if result['QueryExecution']['Status']['State'] != 'SUCCEEDED':\n print(json.dumps({'message': 'error', 'result': result}))\n return False\n\n result_data = self.s3.Bucket(self.options['athena_result_bucket']).Object(\n '%s%s.csv' % (\n self.options['athena_result_prefix'], result['QueryExecution']['QueryExecutionId'])).get()\n pd_data = pd.read_csv(result_data['Body'], encoding='utf-8')\n e_count = int(pd_data.iloc[0]['e_count'])\n u_count = int(pd_data.iloc[0]['u_count'])\n r_data = {'date': self.yesterday.strftime('%Y-%m-%d'), 'e_count': e_count, 'u_count': u_count}\n\n grp_prefix = ''\n if not g['org'] == 'root':\n grp_prefix = g['org'] + '/'\n\n result_file = self.options['stat_prefix'] + grp_prefix + g['container'] + '_' + g['id'] + '_goal_result.json'\n goal_result_obj = self.s3.Object(self.options['stat_bucket'], result_file)\n try:\n response = goal_result_obj.get()\n result = json.loads(response['Body'].read())\n except ClientError:\n result = []\n\n idx = [i for i, _ in enumerate(result) if _['date'] == r_data['date']]\n if len(idx) > 0:\n result[idx[0]] = r_data\n else:\n result.append(r_data)\n\n result.sort(key=lambda x: x['date'])\n print(json.dumps(\n {'message': 'save goal result data', 'bucket': self.options['stat_bucket'], 'file': result_file}))\n goal_result_obj.put(Body=json.dumps(result), ContentType='application/json')\n\n\ndef main():\n retriever = GoalDataRetriever(\n stat_bucket=os.environ.get('OTM_STATS_BUCKET'),\n stat_prefix=os.environ.get('OTM_STATS_PREFIX'),\n goal_object='goals.json',\n athena_result_bucket=os.environ.get('STATS_ATHENA_RESULT_BUCKET'),\n athena_result_prefix=os.environ.get('STATS_ATHENA_RESULT_PREFIX') or '',\n athena_database=os.environ.get('STATS_ATHENA_DATABASE'),\n athena_table=os.environ.get('STATS_ATHENA_TABLE')\n )\n retriever.execute()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"data_retriever/otmplugins/otm-goal-plugin/goal.py","file_name":"goal.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"596613449","text":"def max_sum(array, n):\n for i in range(n - 2, -1, -1):\n for j in range(i + 1):\n array[i][j] += max(array[i + 1][j], array[i + 1][j + 1])\n return array[0][0]\n\ndef main():\n trials = int(input())\n for trial in range(trials):\n n = int(input())\n array = [[int(x) for x in input().split()] for _ in range(n)]\n print(max_sum(array, n))\n\nif __name__ == '__main__':\n main()","sub_path":"competitions/old_competitions/project_euler/euler_018/maximum_path_sum_i.py","file_name":"maximum_path_sum_i.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"522998249","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nN_THREADS = 8\n\ndef f_normal(x, mu=0.0, sigma=1.0):\n return np.exp(-((x-mu)**2*sigma**2)/2.0)/np.sqrt(2*np.pi*sigma)\n\ndata, mus, sigmas = [], [], []\nfor i in range(N_THREADS):\n filename = 'data_'+str(i)+'.txt'\n data_file = np.loadtxt(filename, delimiter=' ', dtype=float)\n data.append(data_file)\n mus.append(data_file.mean())\n sigmas.append(data_file.var())\n \nmus = np.array(mus)\nsigmas = np.array(sigmas)\nmu = mus.mean()\n\nN = data[0].shape[0]\nM = N_THREADS\n\nB = (N/(M-1))*np.sum(np.square(mu-mus))\nW = np.sum(sigmas)/M\n\nV = ((N-1)/N)*W + ((M+1)/(M*N))*B\n\nRC = np.sqrt((5/3)*V/W)\ndata_all = np.array(data).reshape(-1)\n\nxs = np.linspace(-5,5,100)\nys = f_normal(xs)\n\nplt.figure()\nplt.hist(data_all, density=True, bins=80)\nmu = data_all.mean()\nsigma = data_all.var()\nys = f_normal(xs,mu,sigma)\nplt.plot(xs,ys)\nplt.title('E[X] = '+str(np.round(mu,4))+'\\nVAR[X] = '+str(np.round(sigma,4)))\nplt.xlabel('X')\nplt.ylabel('P(X)')\nplt.savefig('Total_histogram.pdf')\n\n\nplt.figure(figsize=(20,20))\nfor i,d in enumerate(data):\n\tplt.subplot(2,4,i+1)\n\tplt.hist(d, density=True, bins=80)\n\tmu = d.mean()\n\tsigma = d.var()\t\n\tys = f_normal(xs,mu,sigma)\n\tplt.plot(xs,ys)\n\tplt.title('E[X] = '+str(np.round(mu,4))+'\\nVAR[X] = '+str(np.round(sigma,4)))\n\tplt.xlabel('X')\n\tplt.ylabel('P(X)')\nplt.savefig('Indivual_histograms.pdf')\n\n\n\n","sub_path":"Punto 1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"109416374","text":"import pyblish.api\n\n\nclass ValidateCurrentSaveFile(pyblish.api.ContextPlugin):\n \"\"\"File must be saved before publishing\"\"\"\n\n label = \"Validate File Saved\"\n order = pyblish.api.ValidatorOrder - 0.1\n optional = True\n hosts = [\"maya\", \"houdini\"]\n\n def process(self, context):\n\n def houdini(variable):\n resitem = []\n for item in variable.split(\"\\\\\"):\n resitem.append(str(item))\n resitem.reverse()\n return resitem[0]\n\n current_file = context.data[\"currentFile\"]\n\n if \"houdini\" in pyblish.api.registered_hosts():\n current_file = houdini(current_file)\n\n unsaved_values = [\n # An unsaved file in Maya has this value.\n \".\",\n # An unsaved file in Nuke has this value.\n \"Root\",\n # An unsaved file in Houdini has this value.\n \"untitled.hip\"\n ]\n\n is_saved = current_file not in unsaved_values\n\n assert is_saved, (\n \"You haven't saved your file yet\")\n","sub_path":"mindbender/plugins/validate_file_saved.py","file_name":"validate_file_saved.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125288280","text":"# Copyright (c) 2012-2016 by the GalSim developers team on GitHub\n# https://github.com/GalSim-developers\n#\n# This file is part of GalSim: The modular galaxy image simulation toolkit.\n# https://github.com/GalSim-developers/GalSim\n#\n# GalSim is free software: redistribution and use in source and binary forms,\n# with or without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions, and the disclaimer given in the accompanying LICENSE\n# file.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the disclaimer given in the documentation\n# and/or other materials provided with the distribution.\n#\nimport galsim\nimport galsim.config\nfrom galsim.deprecated import depr\n\n# This file adds gsobject type Ring which builds an object once every n times, and then\n# rotates it in a ring for the other n-1 times per per group.\n\ndef _BuildRing(config, base, ignore, gsparams, logger):\n \"\"\"@brief Build a GSObject in a Ring. Now deprecated.\n \"\"\"\n depr('gal.type = Ring', 1.4, 'stamp.type = Ring',\n 'The galaxy Ring type may not work properly in conjunction with image.nproc != 1. '+\n 'See demo5 and demo10 for examples of the new stamp type=Ring syntax.')\n\n req = { 'num' : int, 'first' : dict }\n opt = { 'full_rotation' : galsim.Angle , 'index' : int }\n # Only Check, not Get. We need to handle first a bit differently, since it's a gsobject.\n galsim.config.CheckAllParams(config, req=req, opt=opt, ignore=ignore)\n\n num = galsim.config.ParseValue(config, 'num', base, int)[0]\n if num <= 0:\n raise ValueError(\"Attribute num for gal.type == Ring must be > 0\")\n\n # Setup the indexing sequence if it hasn't been specified using the number of items.\n galsim.config.SetDefaultIndex(config, num)\n index, safe = galsim.config.ParseValue(config, 'index', base, int)\n if index < 0 or index >= num:\n raise AttributeError(\"index %d out of bounds for config.%s\"%(index,type))\n\n if 'full_rotation' in config:\n full_rotation = galsim.config.ParseValue(config, 'full_rotation', base, galsim.Angle)[0]\n else:\n import math\n full_rotation = math.pi * galsim.radians\n\n dtheta = full_rotation / num\n if logger:\n logger.debug('obj %d: Ring dtheta = %f',base['obj_num'],dtheta.rad())\n\n if index % num == 0:\n # Then this is the first in the Ring. \n gsobject = galsim.config.BuildGSObject(config, 'first', base, gsparams, logger)[0]\n else:\n if not isinstance(config['first'],dict) or 'current_val' not in config['first']:\n raise RuntimeError(\"Building Ring after the first item, but no current_val stored.\")\n gsobject = config['first']['current_val'].rotate(index*dtheta)\n\n return gsobject, False\n\n# Register this as a valid gsobject type\ngalsim.config.RegisterObjectType('Ring', _BuildRing, _is_block=True)\n","sub_path":"galsim/deprecated/gsobject_ring.py","file_name":"gsobject_ring.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579984181","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.core.management.base import BaseCommand\nfrom django.template import Context, loader\n\nfrom ossus.app.server.models import Server\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n\n lost_servers = []\n\n for server in Server.objects.filter(template=False, active=True):\n if server.lost_connection_to_client():\n lost_servers.append(server)\n\n if lost_servers:\n template = loader.get_template(\"server/templates/lost_servers.html\")\n subject = '%s - lost servers' % settings.BRAND\n to = [admin[0] for admin in settings.ADMINS]\n\n html_content = template.render(Context({\n 'servers': lost_servers\n }))\n\n msg = EmailMultiAlternatives(subject, \"\", settings.DEFAULT_FROM_EMAIL, to)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n","sub_path":"ossus/app/server/management/commands/lost_connection_to_clients.py","file_name":"lost_connection_to_clients.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"555273737","text":"from jRepo.baseDataFormat import basisModel\n'''\njobList;\n [jobA, jobB, jobC, jobD, jobE, jobF]\njobInLink:\n #jobA: [jobB, jobC]\n jobA: {jobB: {workId: outWorkId}, jobC: {workId: outWorkId}}\n\ninfo['jobList'] = ['a', 'b', 'c', 'd', 'e', 'f']\ninfo['jobInLink'] = {'a': {'b': {'*':'*'}, 'c': {'*':'*'}},\n 'b': {'d': {'*':'*'}, 'c': {'*':'*'}},\n 'd': {'f': {'*':'*'}},\n 'e': {'b': {'*':'*'}, 'a': {'*':'*'}},\n 'f': {'c': {'*':'*'}}}\n'''\n\n\nclass QubeJobAnalyzer(basisModel.BasisModel):\n def __init__(self, inJson, inDict = None):\n '''\n input jobList and jobInLink(current job start when inLink job complete)\n output jobDependInfo: gen current job all previous complete job info.\n jobOutLink: gen current completed job output\n '''\n super(QubeJobAnalyzer, self).__init__(inJson, inDict)\n\n self.stdKeys = ['jobList', 'jobInLink']\n missKeys = self.checkStandKeyData()\n if missKeys:\n missKeyStr = ' '.join(missKeys)\n raise Exception('Miss Job Analyzer Standard Keys: %s' %missKeyStr)\n\n def do(self):\n self.analyzeJobDependency()\n self.checkJobCycleLink()\n\n self.analyzeJobOutLink()\n\n self.outputJobSequences()\n \n self.outputInfo()\n\n def analyzeJobDependency(self):\n self.jobDependInfo = {}\n self.jobLevel = {}\n for curJob in self.data['jobList']:\n self.genJobDependency(curJob, self.jobDependInfo, self.jobLevel)\n \n def genJobDependency(self, job, jobDependInfo, jobLevel):\n '''\n recurse find out jobDependInfo, jobLevel,\n level 0 means less dependency level, free to start, without restrict\n '''\n return\n \n def analyzeJobOutLink(self):\n self.jobOutLink = {}\n for curJob in self.data['jobList']:\n inJobInfo = self.data['jobInLink'].get(curJob, {})\n for inJob in inJobInfo:\n if inJob not in self.jobOutLink:\n self.jobOutLink[inJob] = {}\n\n self.jobOutLink[inJob][curJob] = inJobInfo[inJob]\n\n def checkJobCycleLink(self):\n '''\n check wheter job list with cycle link,\n for example a.0->b.1, b.1->a.1, a.2\n '''\n cycleJobs = []\n temErrJobs = []\n for job in self.data['jobList']:\n if job in self.jobDependInfo[job]:\n curIdInfo = self.jobDependInfo[job][job]\n curCycleTest = 0\n if '*' in curIdInfo or 'all' in curIdInfo:\n curCycleTest = 1\n cycleJobs.append(job)\n else:\n for resJob in self.jobDependInfo[job]:\n if not resJob == job:\n resIdInfo = self.jobDependInfo[job][resJob]\n outIdInfo = self.jobDependInfo.get(resJob, {}).get(job, {})\n for iId in resIdInfo:\n oId = resIdInfo[iId]\n if outIdInfo.get(oId) == iId:\n curCycleTest = 1\n cycleJobs.append(job)\n break\n\n if not curCycleTest:\n temErrJobs.append(job)\n else:\n self.cycleTest = curCycleTest\n\n for temErrJob in temErrJobs:\n self.jobDependInfo[temErrJob].__delitem__(temErrJob)\n\n if cycleJobs:\n errStr = 'Cycle Link Job: %s' %(' '.join(cycleJobs))\n raise Exception(errStr)\n\n def outputJobSequences(self):\n '''output job order list base on the jobInLink'''\n return\n\n def outputInfo(self):\n self.data['jobDependInfo'] = self.jobDependInfo\n self.data['jobLevel'] = self.jobLevel\n self.data['outJobList'] = self.outJobList\n self.data['jobOutLink'] = self.jobOutLink\n","sub_path":"qubeJobAnalyzer.py","file_name":"qubeJobAnalyzer.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"210235238","text":"inp=input ('Enter a file name: ')\r\ntry:\r\n h=open (inp)\r\nexcept:\r\n print ('Invalid input!')\r\n exit()\r\nd=dict()\r\nwords_list=[]\r\nfor line in h:\r\n #line=line.rstrip()## Not needed when using list words indexes instead of line.startswith()\r\n words=line.split()\r\n if len(words)==0 : continue##Skips blank lines (without words) and avoids code error: words[0] out of range\r\n if words[0] != 'From': continue##skips lines starting with other words than 'From'\r\n #print (words[2])\r\n words_list.append (words [2])\r\n#print (words_list)\r\nfor word in words_list:\r\n d[word]=d.get (word,0)+1##Replaces \"if word not in d: d[word]=1 else: d[word]+=1\"\r\nprint (d)\r\n","sub_path":"ex_09_02.py","file_name":"ex_09_02.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139176594","text":"from manim import *\n\nclass lines(Scene):\n def construct(self):\n p1= [-1,-1,0]\n p2= [1,-1,0]\n p3= [1,1,0]\n p4= [-1,1,0]\n a = Line(p1,p2).append_points(Line(p2,p3).get_points()).append_points(Line(p3,p4).get_points())\n #print(dir(a))\n \n point_start= a.get_start()\n point_end = a.get_end()\n point_center = a.get_center()\n self.add(Text(f\"a.get_start() = {np.round(point_start,2).tolist()}\").scale(0.5).to_edge(UR).set_color(YELLOW))\n self.add(Text(f\"a.get_end() = {np.round(point_end,2).tolist()}\").scale(0.5).next_to(self.mobjects[-1],DOWN).set_color(RED))\n self.add(Text(f\"a.get_center() = {np.round(point_center,2).tolist()}\").scale(0.5).next_to(self.mobjects[-1],DOWN).set_color(BLUE))\n\n self.add(Dot(a.get_start()).set_color(YELLOW).scale(2))\n self.add(Dot(a.get_end()).set_color(RED).scale(2))\n self.add(Dot(a.get_top()).set_color(GREEN_A).scale(2))\n self.add(Dot(a.get_bottom()).set_color(GREEN_D).scale(2))\n self.add(Dot(a.get_center()).set_color(BLUE).scale(2))\n self.add(Dot(a.point_from_proportion(0.5)).set_color(ORANGE).scale(2))\n self.add(*[Dot(x) for x in a.get_points()])\n self.add(a)\n self.wait(1)\n","sub_path":"lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256350047","text":"import project9_util as util\n\ndef add_linenumber(text):\n encoding = util.detect_encoding(text)\n nl_name = util.nl_filename(text)\n \n f = open(text, 'r',encoding = encoding)\n nl_f = open('%s'% nl_name,'w',encoding = encoding)\n lines = f.readlines() \n n=0\n\n for line in lines:\n ts_line = line.strip()\n if len(ts_line):\n n+=1\n nl_f.write('%s.'% n + line + '\\n') \n else:\n nl_f.write('\\n') \n \n f.close()\n nl_f.close()\n return text\n \nif __name__ == '__main__':\n text = 'project9_util.py'\n add_linenumber(text)\n \n text = 'fudan_history.txt'\n add_linenumber(text)\n \n \n","sub_path":"project9/project/16300120144.py","file_name":"16300120144.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"349114760","text":"class Node:\r\n\r\n\tdef __init__(self, value=None, left=None, right=None):\r\n\t\tself.value = value\r\n\t\tself.right = right\r\n\t\tself.left = left\r\n\r\nclass BinaryTree:\r\n\r\n\tdef __init__(self, head=None):\r\n\t\tself.head = head\r\n\r\n\tdef add(self, value=None, root=None):\r\n\t\tif value is None:\r\n\t\t\traise TypeError\r\n\t\tif not root:\r\n\t\t\tif not self.head:\r\n\t\t\t\tself.head = Node(value)\r\n\t\t\telse:\r\n\t\t\t\troot = self.head\r\n\t\tif value < root.value:\r\n\t\t\tif not root.left:\r\n\t\t\t\troot.left = Node(value)\r\n\t\t\telse:\r\n\t\t\t\tself.add(value, root.left)\r\n\t\telse:\r\n\t\t\tif not root.right:\r\n\t\t\t\troot.right = Node(value)\r\n\t\t\telse:\r\n\t\t\t\tself.add(value, root.right)\r\n\r\n\r\n\tdef contains(self, value=None, root=None, matched=False):\r\n\t\t\r\n\t\tif value is None:\r\n\t\t\traise TypeError\r\n\r\n\t\tif not root:\r\n\t\t\tif not self.head:\r\n\t\t\t\treturn False\r\n\t\t\telse:\r\n\t\t\t\troot = self.head\r\n\r\n\t\tif value == root.value:\r\n\t\t\treturn True\r\n\r\n\t\tif value < root.value:\r\n\t\t\tif root.left:\r\n\t\t\t\tmatched = self.contains(value, root.left, matched)\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\telse:\r\n\t\t\tif root.right:\r\n\t\t\t\tmatched = self.contains(value, root.right, matched)\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\r\n\t\treturn matched\r\n\r\n\tdef preOrder(self, root=None, contents = []):\r\n\t\tif not root:\r\n\t\t\troot = self.head\r\n\t\tif root:\r\n\t\t\tcontents.append(root.value)\r\n\t\t\tif root.left:\r\n\t\t\t\tself.preOrder(root.left, contents)\r\n\t\t\tif root.right:\r\n\t\t\t\tself.preOrder(root.right, contents)\r\n\t\treturn contents\r\n\r\n\r\n\tdef inOrder(self, root=None, contents = []):\r\n\t\tif not root:\r\n\t\t\troot = self.head\r\n\t\tif root:\r\n\t\t\tif root.left:\r\n\t\t\t\tself.inOrder(root.left, contents)\r\n\t\t\tcontents.append(root.value)\r\n\t\t\tif root.right:\r\n\t\t\t\tself.inOrder(root.right, contents)\r\n\t\treturn contents\r\n\r\n\tdef postOrder(self, root=None, contents = []):\r\n\t\tif not root:\r\n\t\t\troot = self.head\r\n\t\tif root:\r\n\t\t\tif root.left:\r\n\t\t\t\tself.postOrder(root.left, contents)\r\n\t\t\tif root.right:\r\n\t\t\t\tself.postOrder(root.right, contents)\r\n\t\t\tcontents.append(root.value)\r\n\t\treturn contents","sub_path":"code-challenges/tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"61842067","text":"#\n#\n# Copyright 2019 Asylo authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n\"\"\"Functions for describing type definitions for generating macros.\n\nImplements the functions for describing and parsing the type definitions. Allows\nemitting macros which can be read directly by a C/C++ program, to evaluate the\nunresolved values in such macros and then generate include directives, enum\ndefinitions and conversion functions that allow system constants to be converted\nfrom the newlib implementation used by Asylo inside the enclave to target host\nimplementation on the untrusted side (typically libc).\n\nFor each type definition (eg. include directive, enum), a definition and getter\nmethods are provided. The definition methods accept a type definition one at a\ntime, while the get methods return all the type definitions under a single\nmacro.\n\nFinally, a write_output() method is provided, which emits all the type\ndefinitions recorded so far in the definitions file (types.py).\n\"\"\"\n\nfrom __future__ import print_function\n\nimport collections\nimport re\nimport sys\n\n# Stores system header includes as a list. Only header file names are expected\n# with or without the .h extension and without the '#include' directive\n# prefixed.\n# We include stdbool.h by default so that the generated output (as .inc file) is\n# also readable by a C program.\n_includes = ['stdbool.h']\n\n# Map from enum names to dictionary of enum properties and their values.\n_enum_map = collections.defaultdict(dict)\n\n# Map from struct names to dictionary of struct properties and its members.\n_struct_map = collections.defaultdict(dict)\n\n# Declare the prefix to be used for C enum declarations and conversion\n# functions. This prefix should be used for direct conversions between newlib\n# and host library, ones which do not involve an intermediate bridge.\n_klinux_prefix = 'kLinux'\n\n\ndef set_klinux_prefix(pref):\n \"\"\"Sets the prefix used for enum definitions and conversion functions.\"\"\"\n global _klinux_prefix\n _klinux_prefix = pref\n\n\ndef include(filename):\n \"\"\"Accumulates the file includes provided.\n\n The filename here is expected to be a system header file (included as\n #include ). This system header file is used twice - once for\n resolving values of constants on the target host implementation at compile\n time, then by the generated conversion functions for converting the constant\n values between newlib and the target host implementation at runtime.\n\n Args:\n filename: The system header file with or without the .h extension, and\n without the <> or #include directive prefixed. Eg. include(\"sys/types.h\")\n\n Raises:\n ValueError: Invalid include file format provided.\n \"\"\"\n if re.match(r'[<,\"].*?[>,\"]', filename):\n raise ValueError(\n 'Invalid include format for filename \"%s\". Please provide the include '\n 'file without enclosing pointy brackets <> or quotes \"\".' % filename)\n if re.match('#include', filename, re.IGNORECASE):\n raise ValueError(\n 'Invalid include format for filename \"%s\". Please provide the filename '\n 'without the prefixing #include directive.' % filename)\n\n _includes.append(filename)\n\n\ndef define_enum(name,\n values,\n default_value_host=0,\n default_value_newlib=0,\n multi_valued=False,\n skip_conversions=False,\n or_input_to_default_value=False):\n \"\"\"Defines a collection of related enumeration values and their properties.\n\n Args:\n name: Name of the collection of enumeration values.\n values: C Enumeration values provided as a list of strings.\n default_value_host: Default enum value on the target host implementation.\n This can be an actual int value or the enum value provided as a string.\n default_value_newlib: Default enum value in newlib. This can be an actual\n int value or the enum value provided as a string.\n multi_valued: Boolean indicating if the enum values can be combined using\n bitwise OR operations.\n skip_conversions: Boolean indicating if generation of types conversion\n functions be skipped, and only enum definitions be generated. Useful when\n conversion functions are complex and need to be written manually, but the\n enum definitions can be generated automatically by resolving the enum\n values from the target host implementation.\n or_input_to_default_value: Boolean indicating if the input be bitwise OR'ed\n with default_value_host (or default_value_newlib) in the generated\n conversion function, if no match for the input enum value is found. This\n is useful for cases when we wish to preserve the input for debugging,\n while providing a default output in case no matching enum value for the\n input is found.\n \"\"\"\n\n # The enum values here are written twice, once as a string literal, then as an\n # enum value pointing to the actual integer value of the enum. This allows\n # types conversions generator to directly interpret the latter as a valid\n # integer corresponding to the enum value, since casting string to enum value\n # is non-trivial in c++.\n # An example 'values', like ['ENUM_VAL1', 'ENUM_VAL2'] looks like the\n # following stored as a dictionary entry -\n # {\"ENUM_VAL1\", ENUM_VAL1}, {\"ENUM_VAL2\", ENUM_VAL2}\n _enum_map[name]['values'] = ', '.join(\n '{{\"{}\", {}}}'.format(val, val) for val in values)\n\n _enum_map[name]['default_value_host'] = default_value_host\n _enum_map[name]['default_value_newlib'] = default_value_newlib\n _enum_map[name]['multi_valued'] = multi_valued\n _enum_map[name]['skip_conversions'] = skip_conversions\n _enum_map[name]['or_input_to_default_value'] = or_input_to_default_value\n\n\ndef define_struct(name, values, pack_attributes=True, skip_conversions=False):\n \"\"\"Defines a collection of structs and their properties.\n\n Args:\n name: Name of the struct. This should be the same as the struct name used in\n newlib/libc libraries for the system calls. Eg. 'stat', 'timeval'\n values: List containing tuples of struct member types and struct member\n names. The struct members names should match the corresponding struct\n member names in the struct from newlib/libc. Eg. [(\"int64_t\", \"st_dev\"),\n (\"int64_t\", \"st_ino\")].\n pack_attributes: Boolean indicating if the compiler should be prevented from\n padding the generated kernel struct members from their natural alignment.\n skip_conversions: Boolean indicating if generation of types conversion\n functions be skipped, and only kernel struct definitions be generated.\n Useful when kernel conversion functions are complex and need to be written\n manually, but the struct definitions can be generated automatically.\n \"\"\"\n _struct_map[name]['values'] = ', '.join(\n '{{\"{}\", \"{}\"}}'.format(member_name, member_type)\n for member_type, member_name in values)\n _struct_map[name]['pack_attributes'] = pack_attributes\n _struct_map[name]['skip_conversions'] = skip_conversions\n\n\ndef get_klinux_prefix():\n \"\"\"Gets the prefix for generated C enums and conversion functions.\"\"\"\n return 'const char klinux_prefix[] = \"{}\";\\n'.format(_klinux_prefix)\n\n\ndef get_includes_as_include_macros():\n \"\"\"Returns all the includes as line separated #include macros.\n\n These includes are required by the types conversions generator at compile time\n to infer the values of enums for a given host implementation.\n \"\"\"\n return ''.join('#include <{}>\\n'.format(filename) for filename in _includes)\n\n\ndef get_includes_in_define_macro():\n \"\"\"Returns all the includes under a #define INCLUDES macro.\n\n The returned list can be used to generate #include directives by a consumer.\n \"\"\"\n quoted_includes = ['\"{}\"'.format(incl) for incl in _includes]\n return '#define INCLUDES {}'.format(', \\\\\\n'.join(quoted_includes))\n\n\ndef get_enums():\n r\"\"\"Returns a macro containing all enum descriptions.\n\n The returned macro is used by types conversions generator to initialize a enum\n description table (enum_properties_table) mapping enum names to a struct\n (EnumProperties) describing the enum properties, including the enum values. A\n typical output of get_enums looks like the following -\n\n #define ENUMS_INIT \\\n {\"FcntlCmd\", {-1, -1, false, false, false, {{\"F_GETFD\", F_GETFD}, {\"F_SETFD\",\n F_SETFD}}}}, \\\n {\"FileFlags\", {0, 0, true, false, false, {{\"O_RDONLY\", O_RDONLY}, {\"O_WRONLY\",\n O_WRONLY}}}}\n\n Each line contains an enum, and has the following pattern -\n {\"EnumName\", {defaultValueHost, defaultValueNewlib, multi_valued,\n skip_conversions, or_input_to_default_value, {{\"enum_val1\", enum_val1},\n {\"enum_val2\", enum_val2}}}}, \\\n \"\"\"\n enum_rows = []\n for enum_name, enum_properties in _enum_map.items():\n enum_rows.append('{{{}, {{{}, {}, {}, {}, {}, {{{}}}}}}}'.format(\n '\"{}\"'.format(enum_name), enum_properties['default_value_host'],\n enum_properties['default_value_newlib'],\n 'true' if enum_properties['multi_valued'] else 'false',\n 'true' if enum_properties['skip_conversions'] else 'false',\n 'true' if enum_properties['or_input_to_default_value'] else 'false',\n enum_properties['values']))\n\n return '#define ENUMS_INIT \\\\\\n{}\\n'.format(', \\\\\\n'.join(enum_rows))\n\n\ndef get_structs():\n r\"\"\"Returns a macro containing all struct descriptions.\n\n The returned macro is used by types conversion generator to initialize a\n struct description table (struct_properties_table) mapping struct names to a\n struct (StructProperties) describing the struct properties, including struct\n members. A typical output of get_structs looks like the following -\n\n #define STRUCTS_INIT \\\n {\"stat\", {true, false, {{\"st_dev\", \"int64_t\"}, {\"st_ino\", \"int64_t\"}}}}, \\\n {\"timespec\", {true, false, {{\"tv_sec\", \"int64_t\"}, {\"tv_nsec\", \"int64_t\"}}}}\n\n Each line contains a struct, and has the following pattern -\n {\"struct_name\", {pack_attributes, skip_conversions, \\\n {{\"member_name1\", \"member_type1\"}, {\"member_name2\", \"member_type2\"}}}}\n \"\"\"\n struct_rows = []\n for struct_name, struct_properties in _struct_map.items():\n struct_rows.append('{{{}, {{{}, {}, {{{}}}}}}}'.format(\n '\"{}\"'.format(struct_name),\n 'true' if struct_properties['pack_attributes'] else 'false',\n 'true' if struct_properties['skip_conversions'] else 'false',\n struct_properties['values']))\n\n return '#define STRUCTS_INIT \\\\\\n{}\\n'.format(', \\\\\\n'.join(struct_rows))\n\n\ndef write_output(stream=sys.stdout):\n \"\"\"Writes the macros to a stream, default to stdout.\"\"\"\n print(get_includes_as_include_macros(), file=stream)\n print(get_includes_in_define_macro(), file=stream)\n print(get_klinux_prefix(), file=stream)\n print(get_enums(), file=stream)\n print(get_structs(), file=stream)\n","sub_path":"asylo/platform/system_call/type_conversions/types_parse_functions.py","file_name":"types_parse_functions.py","file_ext":"py","file_size_in_byte":11257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"648266196","text":"import numpy as np\nimport healpy\nimport matplotlib.pyplot as plt\n\nfrom pyhermes import *\n\nskymap = DMSkymap(nside=64)\ngas = YMW16()\nintegrator = DMIntegrator(gas)\nintegrator.setSunPosition(Vector3QLength(8.3*kiloparsec, 0*parsec, 0*parsec))\n\nskymap.setIntegrator(integrator)\nskymap.compute()\n\noutput = FITSOutput(\"!fits/dm-ymw16-skymap.fits.gz\")\nskymap.save(output)\n\nhealpy.visufunc.mollview(\n np.log10(np.array(skymap)),\n title='DM of YMW16 log([pc/cm3])', cmap='magma')\n\nplt.savefig('img/dm-ymw16-skymap.png')\n","sub_path":"python/dm-ymw16-skymap.py","file_name":"dm-ymw16-skymap.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"601707028","text":"# -*- coding: utf-8 -*-\nfrom socket import *\n\nHOST = '192.168.1.5'\nPORT = 20001\nBUFSIZ = 1024\nADDR = (HOST,PORT)\n\nudpCliSock = socket(AF_INET,SOCK_DGRAM)\n\nwhile True:\n data = input('> ')\n if data:\n udpCliSock.sendto(data.encode(),ADDR)\n print(data)\n else:\n break\n data = udpCliSock.recvfrom(BUFSIZ).decode()\nudpCliSock.close()","sub_path":"udpSocketClie.py","file_name":"udpSocketClie.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"597415227","text":"#!/usr/bin/env python\n#from google.appengine.api import memcache\nfrom google.appengine.ext import db\nfrom google.appengine.ext import search\n\nclass Feed(db.Model):\n url = db.LinkProperty(required=True)\n\n # last modified time\n updated = db.DateTimeProperty(auto_now=True)\n\n # country code of geo target\n country_code = db.StringProperty(required=True, default='us')\n \n # name of origin\n origin = db.StringProperty()\n\n # increment each time feed is fetched for update\n update_count = db.IntegerProperty(indexed=False, default=0)\n\n @classmethod\n def get_feeds(cls, order, limit):\n return db.Query(cls).order(order).fetch(limit)\n\nclass FeedItem(search.SearchableModel):\n feed = db.ReferenceProperty(Feed)\n\n # string representation of feed item\n item = db.TextProperty(required=False)\n\n url = db.LinkProperty(required=True)\n url_uuid = db.StringProperty(required=True)\n title = db.StringProperty(required=True)\n\n # max 500 bytes long can be indexed\n description = db.StringProperty(required=True)\n\n # will be set to RSS pubDate if available\n created = db.DateTimeProperty(required=True)\n\n # set this to now + x days\n # FIXME move to Feed model\n expires = db.DateTimeProperty(required=False)\n\n # optional values\n # FIXME remove or move to FeedExtended\n imageurl = db.LinkProperty(indexed=False)\n\n # social network actions\n # FIXME remove or move to FeedExtended or different service\n sent_twitter = db.BooleanProperty(required=True, default=False)\n\n @classmethod\n def SearchableProperties(cls):\n \"\"\"Override SearchableProperties() to define custom indexes.\"\"\"\n\n return [['title', 'description'], ['title']]\n\n # number of results of last datastore query\n last_result_count = 0\n\n @classmethod\n def get_last_result_count(self):\n return self.last_result_count\n\n @classmethod\n def _get_cursor_id(self, name, limit, page):\n return \"%s_%s_%s\" % (name, limit, page)\n\n @classmethod\n def _fetch_items(cls, q, limit, page):\n cls.last_result_count = q.count()\n# cursor_id = cls._get_cursor_id('feed_item_cursor', limit, page)\n\n# if page > 0:\n# last_cursor = memcache.get(cursor_id)\n# if last_cursor:\n# q.with_cursor(last_cursor)\n\n items = q.fetch(limit, page*limit)\n# cursor = q.cursor()\n# memcache.set(cursor_id, cursor)\n return items\n\n @classmethod\n def get_items(cls, order, limit=10, page=0):\n \"\"\"Get items in given order using cursors for pagination.\"\"\"\n\n q = cls.all().order(order)\n return cls._fetch_items(q, limit, page)\n\n @classmethod\n def get_filtered(cls, criterium, value, order='-created', limit=10, page=0):\n \"\"\"Get items filtered by criterium.\"\"\"\n\n q = db.Query(cls).filter(criterium, value).order(order)\n return cls._fetch_items(q, limit, page)\n\n @classmethod\n def search_items(cls, s, order='-created', limit=10, page=0):\n \"\"\"Search item titles and descriptions.\"\"\"\n\n q = cls.all().search(s, properties=['title', 'description']).order('-created')\n return cls._fetch_items(q, limit, page)","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"600466139","text":"\"\"\" Interpolate sparse carcass. \"\"\"\nimport os\nimport sys\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport torch\n\nsys.path.insert(0, '..')\nfrom seismiqb import Interpolator, Enhancer, Extender\nfrom seismiqb import MODEL_CONFIG_DETECTION, MODEL_CONFIG_EXTENSION, MODEL_CONFIG_ENHANCE\nfrom utils import make_config\n\n\n\n# Global parameters\nN_REPS = 1\nSUPPORTS = 100\nOVERLAP_FACTOR = 2.\nITERATIONS = 1\nFREQUENCIES = [200, 200]\n\n\n# Detection parameters\nDETECTION_CROP_SHAPE = (1, 256, 256) # shape of sampled 3D crops\nDETECTION_ITERS = 500 # number of train iterations\nDETECTION_BATCH_SIZE = 64 # number of crops inside one batch\n\n\n# Extension parameters\nEXTENSION_CROP_SHAPE = (1, 64, 64) # shape of sampled 3D crops\nEXTENSION_ITERS = 500 # number of train iterations\nEXTENSION_BATCH_SIZE = 64 # number of crops inside one batch\nEXTENSION_STRIDE = 32 # step size for extension\nEXTENSION_STEPS = 50 # number of boundary extensions\n\n\n# Enhancing parameters\nENHANCE_CROP_SHAPE = (1, 256, 256) # shape of sampled 3D crops\nENHANCE_ITERS = 500 # number of train iterations\nENHANCE_BATCH_SIZE = 64 # number of crops inside one batch\n\n\n\n# Help message\nMSG = \"\"\"Interpolate carcass to the whole cube,\nOR make a sparce carcass from a full horizon and re-create it.\n\"\"\"\n\n# Argname, description, dtype, default\nARGS = [\n ('cube-path', 'path to the seismic cube in HDF5 format', str, None),\n ('horizon-path', 'path to the horizon in a seismic cube in CHARISMA format', str, None),\n ('savedir', 'path to save files to', str, '_placeholder_'),\n ('device', 'which device to use: physical number', int, None),\n]\n\n\n\ndef interpolate(train_cube, horizon, savedir, device):\n # Get all the params from configs\n device = torch.cuda.device(device) if isinstance(device, int) else device\n\n # Directory to save results to\n results_dir = savedir\n\n short_name_cube = train_cube.split('/')[-1].split('.')[0]\n short_name_horizon = horizon.split('/')[-1].split('.')[0]\n alias = os.path.join(short_name_cube, short_name_horizon)\n save_dir = os.path.join(results_dir, alias)\n\n return_value = [[], [], [], []] # coverages, window ratios, support corrs, local corrs\n\n ###################################################################################\n ################################## DETECTION ##################################\n ###################################################################################\n # Create Detector instance\n detector = Interpolator(\n batch_size=DETECTION_BATCH_SIZE,\n crop_shape=DETECTION_CROP_SHAPE,\n model_config=MODEL_CONFIG_DETECTION,\n device=device,\n save_dir=save_dir, bar=False\n )\n\n train_dataset = detector.make_dataset(train_cube,\n {short_name_cube : [horizon]})\n\n # Train model\n last_loss = detector.train(dataset=train_dataset,\n frequencies=FREQUENCIES,\n n_iters=DETECTION_ITERS,\n width=5, batch_size_multiplier=1,\n rebatch_threshold=0.9)\n\n # Inference on the same cube to interpolate horizon on whole spatial range\n detector.inference(dataset=train_dataset,\n batch_size_multiplier=0.1,\n version=1, orientation='ix',\n overlap_factor=OVERLAP_FACTOR)\n\n infos = detector.evaluate(n=1, add_prefix=False, dump=True, supports=SUPPORTS)\n info = infos[0]\n horizon = detector.predictions[0]\n\n return_value[0].append(horizon.coverage)\n return_value[1].append(info['window_rate'])\n return_value[2].append(info['corrs'])\n return_value[3].append(info['local_corrs'])\n\n\n for i in range(ITERATIONS):\n ###################################################################################\n ################################### EXTEND ####################################\n ###################################################################################\n torch.cuda.empty_cache()\n\n # Create instance of Enhancer\n extender = Extender(\n batch_size=EXTENSION_BATCH_SIZE,\n crop_shape=EXTENSION_CROP_SHAPE,\n model_config=MODEL_CONFIG_EXTENSION,\n device=device,\n save_dir=os.path.join(save_dir, f'extended_{i}'), bar=False\n )\n\n # Train model\n extender.train(horizon, n_iters=EXTENSION_ITERS, width=5)\n\n # Inference: fill the holes and exterior\n horizon = extender.inference(horizon,\n n_steps=EXTENSION_STEPS,\n stride=EXTENSION_STRIDE)\n\n # Evaluate results\n horizon = extender.predictions[0]\n extender.targets = detector.targets\n infos = extender.evaluate(n=1, add_prefix=False, dump=True, supports=SUPPORTS)\n info = infos[0]\n\n return_value[0].append(horizon.coverage)\n return_value[1].append(info['window_rate'])\n return_value[2].append(info['corrs'])\n return_value[3].append(info['local_corrs'])\n\n\n ###################################################################################\n ################################### ENHANCE ###################################\n ###################################################################################\n torch.cuda.empty_cache()\n\n # Create instance of Enhancer\n enhancer = Enhancer(\n batch_size=ENHANCE_BATCH_SIZE,\n crop_shape=ENHANCE_CROP_SHAPE,\n model_config=MODEL_CONFIG_ENHANCE,\n device=device,\n save_dir=os.path.join(save_dir, f'enhanced_{i}'), bar=False\n )\n\n # Train model\n enhancer.train(horizon, n_iters=ENHANCE_ITERS, width=5)\n\n # Inference: try to make every crop a touch better\n enhancer.inference(horizon,\n batch_size_multiplier=0.1,\n version=1, orientation='ix',\n overlap_factor=OVERLAP_FACTOR)\n\n # Evaluate results\n enhancer.targets = detector.targets\n infos = enhancer.evaluate(n=1, add_prefix=False, dump=True, supports=SUPPORTS)\n info = infos[0]\n horizon = enhancer.predictions[0]\n\n return_value[0].append(horizon.coverage)\n return_value[1].append(info['window_rate'])\n return_value[2].append(info['corrs'])\n return_value[3].append(info['local_corrs'])\n\n ###################################################################################\n ############################## SAVE NEXT TO CUBE ##############################\n ###################################################################################\n # cube_dir = os.path.dirname(horizon.geometry.path)\n # savepath = os.path.join(cube_dir, 'HORIZONS_DUMP', DUMP_NAME)\n # os.makedirs(savepath, exist_ok=True)\n # horizon.name = '+' + horizon.name.replace('enhanced_', '').replace('extended_', '')\n # savepath = os.path.join(savepath, horizon.name)\n # horizon.dump(savepath, add_height=False)\n # detector.log(f'Dumped horizon to {savepath}')\n\n ###################################################################################\n ################################### RETURNS ###################################\n ###################################################################################\n\n msg = ''\n returned_values = [\n 'coverages', 'window_rates', 'corrs', 'local_corrs',\n ]\n\n for name, value in zip(returned_values, return_value):\n msg += f' {name} -> {value}\\n'\n detector.log(msg)\n\n\n\nif __name__ == '__main__':\n config = make_config(MSG, ARGS, os.path.basename(__file__).split('.')[0])\n\n interpolate(\n train_cube=config['cube-path'],\n horizon=config['horizon-path'],\n savedir=config['savedir'],\n device=config['device'],\n )\n","sub_path":"scripts/carcass_interpolation.py","file_name":"carcass_interpolation.py","file_ext":"py","file_size_in_byte":8157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"524253531","text":"import copy\nimport math as math\n\n ## FAIRE : DEUX DICO DE CONSTANTES, UN SI, LAUTRE NON ET METTRE LES MEMES NOMS DE CLE\n\n\nconstants = { # 'key' : [value:float, unitType: string, unit: string]\n\n 'pi': {'value': 3.1415, 'unitType': None, 'unit': None, 'name': '\\u03C0'}, #pi\n 'g_SI': {'value': 9.807, 'unitType': 'Acceleration', 'unit': 'm.s\\u207B\\u00B2', 'name': 'g'}, #gravity \n \n 'gammaWater_SI': {'value': 1.025, 'unitType': None, 'unit': None, 'name': '\\03B3 Water'},\n \n 'rhoWater_SI': {'value': 1025, 'unitType': 'Density', 'unit': 'kg.m\\u207B\\u00B3', 'name': '\\03F1 Water'}, #density of water\n 'rhogWater_SI': {'value': 10051.7, 'unitType': 'SpecificWeight', 'unit': 'N.m\\u207B\\u00B3', 'name': '\\03F1g Water'}, #specific weight of water\n 'muWater_SI': {'value': 9.777, 'unitType': 'KinematicViscosity', 'unit': 'm\\u00B2.s\\u207B\\u009B', 'name': '\\03BD'}, #viscosity of water at 25°C\n 'rhoAir_SI': {'value': 1.164, 'unitType': 'Density', 'unit': 'kg.m\\u207B\\u00B3', 'name': '\\03F1 Air'}, #density of air at 30°C\n 'rhogAir_SI': {'value': 11.43, 'unitType': 'SpecificWeight', 'unit': 'N.m\\u207B\\u00B3', 'name': '\\03F1g Air'} #specific weight of air at 30°C\n} \n\n\ndico = {\n 'V': {'unitType': 'Speed', 'unit1': 'knot', 'value1': [7,8,10,15,20,25,30,35,40,45,50,55,60,65,70], 'unit2': 'km/h', 'SI': [], 'name': 'V'},\n\n\n #hull\n 'LWL': {'value': 0.0 , 'unitType': 'Distance', 'unit': '', 'variationType': None, 'variation': 0.0, 'usedInGA': True, 'name': 'LWL'},\n 'B': {'value': 0.0 , 'unitType': 'Distance', 'unit': '', 'variationType': None, 'variation': 0.0, 'usedInGA': True, 'name': 'B'}\n}\n\n\n#dico2 = dico\n\"\"\"\ndico2 = copy.deepcopy(dico)\n\n\nV=[10 for i in range(0,10)]\nB=5\ng=10\n\n\nf = lambda x : x+2\ng = map(f, V)\n\nf\nprint(V)\nV=list(g)\nprint(V)\n\"\"\"\n#calcul = {'Cv': {'value': [0 for i in range(0,10)], 'Function': lambda V, B, g : for i in range (0,len(V)): v[i]*math.sqrt(B*g) } }","sub_path":"BoatOptimizationProject/PhysicMotor/ConstantsSI.py","file_name":"ConstantsSI.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"623980804","text":"from flask import Flask,render_template,request\r\nimport csv\r\nfrom models import *\r\n\r\napp=Flask(__name__)\r\n\r\napp.config[\"SQLALCHEMY_DATABASE_URI\"]='postgres://postgres:mkempire081@localhost:5432/Kanish'\r\napp.config[\"SQLALCHEMY_TRACK_MODIFICATION\"]=False\r\n\r\ndb.init_app(app)\r\n\r\ndef main():\r\n f=open(\"a.csv\")\r\n reader=csv.reader(f)\r\n for origin,destination,duration in reader:\r\n flight=Flight(origin=origin,destination=destination,duration=duration)\r\n db.session.add(flight)#Add flight to database\r\n '''\r\n DELETE FROM flights WHERE id=28;\r\n flight=Flight.query.get(28)\r\n db.session.delete(flight)\r\n '''\r\n db.session.commit()\r\n \r\n\r\nif __name__==\"__main__\":\r\n with app.app_context():\r\n main()","sub_path":"ORM/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"251689257","text":"from django.shortcuts import render, redirect\nfrom .models import CustomUser\nfrom .forms import UserForm\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef all_users(request):\n users = list(CustomUser.objects.all())\n return render(request, 'user/all_users.html', {'title': \"All users\", \"users\": users})\n\n\n# Create your views here.\n\ndef user_by_id(request, id=0):\n user_by_id = CustomUser.objects.get(id=id)\n return render(request, 'user/user_by_id.html', {'title': \"User by id\", \"user_by_id\": user_by_id})\n\n\ndef user_form(request, id=0):\n if request.method == \"GET\":\n if id == 0:\n form = UserForm()\n else:\n user = CustomUser.objects.get(id=id)\n form = UserForm(instance=user)\n return render(request, 'user/user_form.html', {'form': form})\n else:\n if id == 0:\n form = UserForm(request.POST)\n else:\n user = CustomUser.objects.get(id=id)\n form = UserForm(request.POST, instance=user)\n if form.is_valid():\n\n form.save()\n else:\n return render(request, 'user/user_form_error.html')\n return redirect('users')\n\n\ndef user_update(request):\n # def book_update(request, book_id=0, name, description, author, count):\n # if name:\n # Book.objects.get(id=book_id).name = name\n # if description:\n # Book.objects.get(id=book_id).description = description\n # if author:\n # Book.objects.get(id=book_id).author = author\n # if count:\n # Book.objects.get(id=book_id).count = count\n # Book.save()\n users = list(CustomUser.objects.all())\n return render(request, 'user/all_users.html', {'title': \"All users\", \"users\": users})\n\n\ndef user_delete(request, id=0):\n user = CustomUser.objects.get(id=id)\n user.delete()\n users = list(CustomUser.objects.all())\n return render(request, 'user/all_users.html', {'title': \"All users\", \"users\": users})\n","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"289734391","text":"import pandas as pd\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.ensemble import RandomForestRegressor\n\nif __name__ == \"__main__\":\n dataset = pd.read_csv(\"./data/felicidad.csv\")\n\n \n\n X = dataset.drop(['country','rank','score'],axis=1)\n y = dataset[['score']]\n\n reg = RandomForestRegressor()\n parametros = {\n 'n_estimators':range(4,16),\n 'criterion':['mse','mae'],\n 'max_depth':range(2,11)\n\n }\n\n rand_set = RandomizedSearchCV(reg,parametros,n_iter=10,cv=3,scoring='neg_mean_absolute_error').fit(X,y)\n\n print(rand_set.best_estimator_)\n print(rand_set.best_params_)\n\n print(rand_set.predict(X.loc[[0]]))","sub_path":"curso1/randomized.py","file_name":"randomized.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"460960365","text":"#encoding:utf-8\n\nfrom django import forms\nfrom django.contrib.auth.models import User, Group\n\nfrom .models import *\n\n\nclass EscolaridadForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Escolaridad\n\t\tfields = ('nombre',)\n\t\twidgets = {\n\t\t\t'nombre': forms.TextInput(attrs = {\n\t\t\t\t\t'class': 'form-control input-lg',\n\t\t\t\t\t'placeholder': 'Nombre',\n\t\t\t\t}),\n\t\t}\n","sub_path":"modulos/catalogos/estadisticos/academicos/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"310588880","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n\"\"\"\n__author__ = \"Pauline Celton\"\n__version__ = \"1.0.1\"\n__date__ = \"2019-03-02\"\n__status__ = \"Development\"\n\"\"\"\n\"\"\"\n The ``Quality control`` module\n ======================\n \n Use it to :\n - analyse the coherence of the swathes\n \n Context\n -------------------\n Ulysse Unmaned Surface Vehicle\n \n Information\n ------------------------\n TODO :\n - implementation in C++\n \n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport rospy\nfrom std_msgs.msg import Int16, String\nimport os\nimport time\nimport pandas\nfrom diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus\n\nRESOLUTION = rospy.get_param('/filters/coherence/resolution', 1.) \nSEUIL_COHERENCE = rospy.get_param('/filters/coherence/coherence_threshold', 0.1)\nSEUIL_ACCEP = rospy.get_param('/filters/coherence/acceptable_threshold', 10.) # pourcentage d'erreurs acceptées\nWARNING = rospy.get_param('/filters/coherence/warning', 12)\n\n\ndef grille_coherence(reg_file,trav_file):\n \n '''\n Input : les fichiers de lignes régulières et traversières en p,b,x,y,z,status\n Output : la différence et a le taux de valeurs invalides\n '''\n reg = pandas.read_csv(reg_file, delim_whitespace=True, names=['p', 'b', 'x', 'y', 'z', 'status'])\n trav = pandas.read_csv(trav_file, delim_whitespace=True, names=['p', 'b', 'x', 'y', 'z', 'status'])\n reg = reg.loc[reg.status==0]\n trav = trav.loc[trav.status==0]\n \n #origine de la grille coin gauche inférieur\n x0 = np.minimum(np.min(reg['x'].values),np.min(trav['x'].values)) \n y0 = np.minimum(np.min(reg['y'].values),np.min(trav['y'].values))\n \n #fin de la grille coin droit supérieur\n xmax = np.maximum(np.max(reg['x'].values),np.max(trav['x'].values)) \n ymax = np.maximum(np.max(reg['y'].values),np.max(trav['y'].values))\n\n #taille de la grille\n jmax = int((xmax - x0)/RESOLUTION)+1\n imax = int((ymax-y0)/RESOLUTION)+1\n \n #grilles vides faisant la meme taille\n Mreg = np.zeros((imax,jmax))\n Mtrav = np.zeros((imax,jmax))\n \n #remplissage des grilles avec les valeurs de profondeurs\n j = np.zeros(len(reg))\n i = np.zeros(len(reg))\n jj = np.zeros(len(trav))\n ii = np.zeros(len(trav))\n count1 = np.zeros_like(Mreg)\n count2 = np.zeros_like(Mtrav)\n \n for f in range(len(reg)):\n j = int((reg['x'].values[f] - x0)/RESOLUTION)\n i = int((reg['y'].values[f]-y0)/RESOLUTION)\n Mreg[i,j] += reg['z'].values[f]\n count1[i,j] += 1\n \n for f in range(len(trav)):\n jj = int((trav['x'].values[f] - x0)/RESOLUTION)\n ii = int((trav['y'].values[f]-y0)/RESOLUTION)\n Mtrav[ii,jj] += trav['z'].values[f]\n count2[ii,jj] += 1\n\n M1 = Mreg/count1\n M2 = Mtrav/count2\n diff = (M1-M2)\n a = len(np.where(diff>SEUIL_COHERENCE)[0])\n\n return float(a)/(len(diff[0])*len(diff))*100\n\ndef filter_manager(data):\n global Regs,files,status,perct,state,comput_time\n name = data.data.split('/')[-1][0:3]\n if name == \"Reg\":\n rospy.loginfo(\"New reg file\")\n Regs.append(data.data)\n elif name == \"Tra\":\n for reg in Regs:\n rospy.loginfo(\"Start filtering:\\nReg_file: %s\\nTrav_file: %s\"%(reg,data.data))\n status = \"Running\"\n files = [reg.split('/')[-1],data.data.split('/')[-1]]\n t0 = time.time()\n error_percent=grille_coherence(reg,data.data)\n d = time.time() - t0\n comput_time = d\n perct = error_percent\n state = int(error_percent > SEUIL_ACCEP)\n if state:\n rospy.logwarn(\"Warning raised\")\n warning_pub.publish(Int16(WARNING))\n status = \"Not running\"\n rospy.loginfo(\"\\tPercentage of non coherence: %.3f\"%(error_percent))\n rospy.loginfo(\"End filtering - Time computing %.3f s\"%(d))\n\n\nif __name__ == '__main__':\n \n\n rospy.init_node('Coherence_filter')\n# data = load('fauchee1.txt')\n# data2 = load('fauchee2.txt')\n# data3 = load('fauchee2.txt')\n \n warning_pub = rospy.Publisher(\"/warning\", Int16, queue_size=1)\n rospy.Subscriber(\"/ulysse/filters/scheduler\", String, filter_manager)\n diag_pub = rospy.Publisher(\"/diagnostics\",DiagnosticArray,queue_size=1)\n\n state = 0\n status = \"Not running\"\n files = \"Not running\"\n perct = \"Not running\"\n comput_time = \"Not running\"\n Regs=[]\n Travs=[]\n\n\n diagnostics=DiagnosticArray()\n while not rospy.is_shutdown():\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/State\", message=str(status)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Files\", message=str(files)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Coherence threshold [m]\", message=str(SEUIL_COHERENCE)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Resolution [m]\", message=str(RESOLUTION)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Acceptable percentage\", message=str(SEUIL_ACCEP)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Result [%]\", message=str(perct)))\n diagnostics.status.append(DiagnosticStatus(level=state,name=\"filters/coherence/Computing time [s]\", message=str(comput_time)))\n diagnostics.header.stamp=rospy.Time.now()\n diag_pub.publish(diagnostics)\n if state:\n state=0\n time.sleep(1)\n\n\n","sub_path":"workspaceUlysse/src/quality_control/src/filters/coherence.py","file_name":"coherence.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301696927","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on __DATE__\n# Project: __PROJECT_NAME__\n\nstart_url = '__START_URL__'\n\n\nfrom pyspider.libs.base_handler import *\n\nimport sys, time, pymysql,time,re\n\nclass Handler(BaseHandler):\n crawl_config = {\n \"headers\": {\n \"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Encoding\":\"gzip, deflate, sdch\",\n \"Accept-Language\":\"zh-CN,zh;q=0.8\",\n \"Cache-Control\":\"max-age=0\",\n \"Connection\":\"keep-alive\",\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36\",\n \"Referer\": \"https://movie.douban.com/subject/\"\n }\n #\"proxy\":\"58.216.202.149:8118\"\n }\n def __init__(self):\n self.url = start_url\n \n\n @every(minutes=24 * 60)\n def on_start(self):\n self.crawl(self.url, callback=self.index_page)\n\n def index_page(self,response):\n #link = response.doc('#morelink-wrapper > p > a').attr('href')\n \n #link = link + \"/p1\"\n movie_name = response.doc('#content > h1 > span:nth-child(1)').text()\n link = response.doc('section.reviews.mod.movie-content > p > a').attr('href')\n print(link)\n print(\"Hello\")\n self.crawl(link,callback=self.detail_page,save={'movie_name':movie_name})\n @config(age=10 * 24 * 60 * 60)\n def detail_page(self, response):\n print(\"hi\")\n pageNum = response.doc('div.paginator > span.thispage').attr('data-total-page')\n print(pageNum)\n movie_name = response.save['movie_name']\n for i in range(0,int(pageNum)):\n time.sleep(0.2)\n url = self.url + \"/reviews?start=\" + str(i*20)\n print(url)\n self.crawl(url,callback=self.process_page,save={'movie_name':movie_name})\n \n def process_page(self,response):\n lists = response.doc('div.review-list > div').items()\n movie_name = response.save['movie_name']\n for item in lists:\n time.sleep(0.2)\n link = item('div.main-bd > h2 > a').attr('href')\n if link:\n self.crawl(link,callback=self.domain_page,save={'movie_name':movie_name})\n \n \n def domain_page(self,response):\n if not response:\n print(\"Over\")\n return\n result = {}\n movie_name = response.save['movie_name']\n result['comment_user'] = response.doc('header.main-hd > a > span').text()\n result['comment_time'] = response.doc('header.main-hd > span.main-meta').text()\n result['comment_vote'] = response.doc('div.main-panel-useful > button.useful_count').text()\n result['comment'] = \"\"\n lists = response.doc('div.review-content.clearfix > p').items()\n for each in lists:\n result['comment'] += each.text()\n #print result\n self.on_result(result,movie_name)\n comment_page = response.doc('div.paginator')\n comment_items = response.doc('div.comment-item').items()\n if comment_page:\n num = comment_page('a:nth-last-child(2)').text()\n print(num)\n #Id = self.url.split('/')[-1]\n for i in range(0,int(num)):\n url = response.url +\"/?start=\" + str(i*100)+\"#comments\"\n time.sleep(0.2)\n self.crawl(url,callback=self.recomment_page,save={'movie_name':movie_name,'author':result['comment_user']})\n elif comment_items:\n result1 = {}\n for item in comment_items:\n result1['user'] = item('div.content > div.header > a').text()\n result1['comment_time'] = item('div.content > div.header > span').text()\n result1['comments'] = item('div.content > p.comment-text').text()\n self.insert_to_sql(result1,movie_name,result['comment_user'])\n \n \n def on_result(self,result,movie_name):\n if not result:\n return\n print(result)\n if not result['comment_user']:\n return\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='repository', passwd='repository', db='repository', charset='utf8')\n cur = conn.cursor()\n cur.execute(\"select * from douban where movie_name = %s and user_name = %s\", (movie_name,result['comment_user']))\n rows = cur.fetchall()\n if len(rows):\n cur.close()\n conn.close()\n return\n #print movie_name\n cur.execute(\"insert into douban(movie_name,user_name,comment_time,vote,comments) values(%s,%s,%s,%s,%s)\", (movie_name,result['comment_user'],result['comment_time'], result['comment_vote'], result['comment']))\n conn.commit()\n cur.close()\n conn.close()\n \n \n def recomment_page(self,response):\n result = {}\n lists = response.doc('div.comment-item').items()\n movie_name = response.save['movie_name']\n author = response.save['author']\n for item in lists:\n result['user'] = item('div.content > div.header > a').text()\n result['comment_time'] = item('div.content > div.header > span').text()\n result['comments'] = item('div.content > p.comment-text').text()\n self.insert_to_sql(result,movie_name,author)\n \n def insert_to_sql(self,result,movie_name,author):\n if not result:\n return\n if not result['user']:\n return\n print(\"hu\")\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='repository', passwd='repository', db='repository', charset='utf8')\n cur = conn.cursor()\n cur.execute(\"select * from douban_comment where movie_name = %s and user_name = %s\", (movie_name,result['user']))\n rows = cur.fetchall()\n if len(rows):\n cur.close()\n conn.close()\n return\n print(\"movie_name\")\n cur.execute(\"insert into douban_comment(movie_name,author,user_name,comment_time,comments) values(%s,%s,%s,%s,%s)\", (movie_name,author,result['user'],result['comment_time'], result['comments']))\n conn.commit()\n cur.close()\n conn.close()\n\n \n\n\n\n","sub_path":"pyspider-0.3.9/pyspider/libs/sample_handler_douban.py","file_name":"sample_handler_douban.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"309249691","text":"from odoo import api, fields, models\n\n\nclass CloseContainerWizard(models.TransientModel):\n _name = 'close.container.wizard'\n\n container_ids = fields.Many2many('project.container', string='Selected Containers',domain=\"[('state', '=', 'in_progress')]\")\n contractor_rate = fields.Boolean(\"Contractor Rate\")\n ea_rate = fields.Boolean(\"EA Rate\")\n standard_rate = fields.Boolean(\"Standard Rate\",default=True)\n weight_ok = fields.Boolean(\"Weight OK\", default=True)\n quality_ok = fields.Boolean(\"Quality OK\",default=True )\n release_to_stock = fields.Boolean(\"Release To Stock\")\n # location_id = fields.Many2one(\"stock.location\",string=\"Location\")\n\n def action_close_container(self):\n for container in self.container_ids:\n container.contractor_rate = self.contractor_rate\n container.ea_rate = self.ea_rate\n container.standard_rate = self.standard_rate\n container.set_to_close()\n","sub_path":"ppts_inventory_customization/wizard/close_containers.py","file_name":"close_containers.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"115331939","text":"#cortexManager.py\n#!/usr/bin/python\n\n# MODULE CONTAINING ALL FUNCTIONS NECESSARY TO MANAGE INTERACTIONS BETWEEN\n# CORTEX, ENABLERS, INHIBITORS\n\nimport time, urllib, math, calendar, logging, operator, json\n# from actionsThreading import actionsThreading\n\nlogger = logging.getLogger('mainLogger')\n# SPECIAL FUNCTION TO PRINT CORTEX TO SCREEN\n\n\ndef DictOrListToString(DicOrList, n=0, indent=4, debug=False):\n res = \"\"\n prefix = \"_\" * n * indent\n if len(DicOrList) == 0:\n res = res + \"(Vide)\"\n if type(DicOrList) == type({}):\n for j in DicOrList:\n if type(DicOrList[j]) == type({}) or type(DicOrList[j]) == type([]):\n res = res + prefix + str(j) + \": \\n\" + DictOrListToString(\n DicOrList[j], n + 1, indent)\n else:\n res = res + prefix + str(j )+ \": \" + str(DicOrList[j]) + \"\\n\"\n elif type(DicOrList) == type([]):\n for j in range(len(DicOrList)):\n if type(DicOrList[j]) == type({}) or type(DicOrList[j]) == type([]):\n res = res + prefix + str(j) + \": \\n\" + DictOrListToString(\n DicOrList[j], n + 1, indent)\n else:\n res = res + prefix + str(j) + \": \" + str(DicOrList[j]) + \"\\n\"\n else:\n res = res + prefix + str(DicOrList)\n return res\n\n\ndef xplMsg2Dict(msg):\n msgList = msg.splitlines()\n result = {}\n for element in msgList:\n if element.find(\"=\") != -1:\n elementList = element.split(\"=\")\n result[elementList[0]] = elementList[1]\n return result\n\n\ndef checkDict1FullyInDict2(dict1, dict2):\n exists = True\n for elt in dict1:\n if elt in dict2:\n exists = dict1[elt] == dict2[elt]\n else:\n exists = False\n if not(exists):\n break\n return exists\n\n\ndef checkDict1VsObsoletingDict2(dict1, dict2):\n allow = True\n now = time.time()\n for ListElement in dict1:\n if ListElement in dict2:\n allow = (now < dict2[ListElement][1])\n # else false ???\n if not(allow):\n break\n return allow\n\n\ndef night(myUTCTime=0, debug=False, nightIncrease=30):\n # for tests : night(calendar.timegm((2015,4,2,0,0,0,0 ,0 ,0)),True)\n if myUTCTime == 0:\n myUTCTime = time.time()\n myTimeTuple = time.gmtime(myUTCTime)\n myDateTuple = myTimeTuple[0:3] + (0, 0, 0, 0, 0, 0)\n myUTCDate = calendar.timegm(myDateTuple)\n pi = math.pi\n cos = math.cos\n EarliestDawn = 3.7333\n YearlyAmplitude = 3.9833\n EarliestDusk = 15.8500\n RefDateDawn = 1419811200.0\n RefDateDusk = 1450137600.0\n YearLength = 31553280.0\n dawn = EarliestDawn + YearlyAmplitude / 2.0 * (\n 1 + cos(pi * (myUTCDate - RefDateDawn) / YearLength * 2.0)) + (\n nightIncrease * 60)\n dusk = EarliestDusk + YearlyAmplitude / 2 * (\n 1 + cos(pi * (1 - (myUTCDate - RefDateDusk) / YearLength * 2))) - (\n nightIncrease * 60)\n dawnTuple = myDateTuple[0:3] + time.gmtime(dawn * 3600)[3:6] + (0, 0, 0)\n duskTuple = myDateTuple[0:3] + time.gmtime(dusk * 3600)[3:6] + (0, 0, 0)\n if debug:\n print('##########')\n print (myTimeTuple)\n print (myDateTuple)\n print (dawnTuple)\n print (duskTuple)\n if (dawnTuple < myTimeTuple and duskTuple > myTimeTuple):\n return 'No'\n else:\n return 'Yes'\n\n\ndef compare(a, b, func):\n mappings = {'>': operator.gt, '>=': operator.ge,\n '==': operator.eq, '<': operator.lt,\n '<=': operator.le, '!=': operator.ne}\n return mappings[func](a, b)\n\n\ndef checkCriteria(dict1, dict2):\n for ListElement in dict1:\n if ListElement in dict2:\n allow = compare(dict2[ListElement][0],\n dict1[ListElement][1], dict1[ListElement][0])\n if not(allow):\n return False\n return True","sub_path":"mqttHAL/cortexMngr.py","file_name":"cortexMngr.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"416641922","text":"\"\"\"\n订单数据的接口API\n\"\"\"\nfrom flask import Blueprint, request, jsonify\n\nfrom libs import cache\n\norder_blue = Blueprint('order_blue', __name__)\n\n\n@order_blue.route('/add_order/', methods=('POST', ))\ndef add_order():\n # 验证用户是否已登录\n token = request.args.get('token', None)\n if token is None:\n return jsonify({\n 'code': 202,\n 'msg': 'token查询参数必须提供或者登录后获取token'\n })\n if cache.check_token(token):\n user_id = cache.get_token_user_id(token)\n\n # 下订单的业务处理\n\n\n return jsonify({\n 'code': 200,\n 'msg': '下单成功',\n 'data': {\n \"user_id\": user_id,\n 'ord_num': '100191919',\n 'state': '待支付',\n 'price': '2900.00元'\n }\n })","sub_path":"views/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"518282813","text":"import numpy as np\r\nimport pandas as pd\r\nimport sklearn\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn import tree\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn import svm\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import make_scorer, accuracy_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.externals import joblib\r\nimport pickle\r\ncol_names = ['age','gender','chest_pain','blood_pressure','serum_cholestoral','fasting_blood_sugar', 'electrocardiographic',\r\n 'max_heart_rate','induced_angina','ST_depression','slope','no_of_vessels','thal','diagnosis']\r\n\r\n# read the file\r\ndf = pd.read_csv(r'C:\\Users\\User\\Desktop\\ml\\processed.cleveland.data.csv', names=col_names, header=None, na_values=\"?\")\r\n\r\ndf.isnull().sum()\r\n\r\ndf['no_of_vessels'].fillna(df['no_of_vessels'].mode()[0], inplace=True)\r\ndf['thal'].fillna(df['thal'].mode()[0], inplace=True)\r\ndf.diagnosis=(df.diagnosis!=0).astype(int)\r\ndf.diagnosis.value_counts()\r\nX, y = df.iloc[:, :-1], df.iloc[:, -1]\r\nprint(X.shape)\r\nprint(y.shape)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)\r\n\r\n#model1\r\nmodellog = LogisticRegression()\r\n# Train the model using the training sets and check score\r\nmodellog.fit(X_train, y_train)\r\npred1= modellog.predict(X_test)\r\njoblib.dump(modellog, 'LogisticRegression.pkl')\r\n\r\n#model2\r\n#modelsvm = svm.svc()\r\nmodelsvm = svm.SVC(kernel='linear', C=1, gamma=1)\r\nmodelsvm.fit(X_train, y_train)\r\npred2= modelsvm.predict(X_test)\r\njoblib.dump(modelsvm, 'SVM.pkl')\r\n\r\n#model3\r\nmodelgnb = GaussianNB()\r\nmodelgnb.fit(X_train, y_train)\r\npred3 = modelgnb.predict(X_test)\r\njoblib.dump(modellog, 'NaiveBayes.pkl')\r\n\r\n#model4\r\nclf_entropy=DecisionTreeClassifier(criterion = \"entropy\", random_state =0,max_depth=5,min_samples_leaf=5)\r\nclf_entropy.fit(X_train,y_train)\r\ny_pred_en=clf_entropy.predict(X_test)\r\njoblib.dump(clf_entropy, 'decisiontree.pkl')\r\n\r\n#model5\r\n\r\n# Choose the type of classifier. \r\nclf = RandomForestClassifier()\r\n\r\n# Choose some parameter combinations to try\r\nparameters = {'max_features': ['log2', 'sqrt','auto'], \r\n 'criterion': ['entropy', 'gini'],\r\n 'max_depth': [2, 3, 5, 10], \r\n 'min_samples_split': [2, 3, 5],\r\n 'min_samples_leaf': [1,5,8],\r\n 'n_estimators':[110], 'random_state':[2606]\r\n }\r\n\r\n# Type of scoring used to compare parameter combinations\r\nacc_scorer = make_scorer(accuracy_score)\r\n\r\n# Run the grid search\r\ngrid_obj = GridSearchCV(clf, parameters, scoring=acc_scorer)\r\ngrid_obj = grid_obj.fit(X_train, y_train)\r\n\r\n# Set the clf to the best combination of parameters\r\nclf = grid_obj.best_estimator_\r\n\r\n# Fit the best algorithm to the data. \r\nclf.fit(X_train, y_train)\r\npredictions = clf.predict(X_test)\r\njoblib.dump(clf, 'randomforest.pkl')","sub_path":"app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"131144246","text":"import uuid\nfrom nose.tools import raises\nfrom nose import SkipTest\nimport shutil\nimport mock\nimport datetime\nfrom io import BytesIO\nfrom tempfile import NamedTemporaryFile\nimport os\nfrom depot.io.utils import FileIntent\nfrom tests.utils import create_cgifs\n\nFILE_CONTENT = b'HELLO WORLD'\n\n\nclass BaseStorageTestFixture(object):\n def test_creation_readback(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n assert f.read() == FILE_CONTENT\n\n def test_creation_metadata(self):\n with mock.patch('depot.io.utils.timestamp', return_value='2001-01-01 00:00:01'):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n\n f = self.fs.get(file_id)\n assert f.filename == 'file.txt', f.filename\n assert f.last_modified == datetime.datetime(2001, 1, 1, 0, 0, 1), f.last_modified\n assert f.content_type == 'text/plain', f.content_type\n\n @raises(IOError)\n def test_notexisting(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n assert self.fs.exists(file_id)\n self.fs.delete(file_id)\n assert not self.fs.exists(file_id)\n\n self.fs.get(file_id)\n\n @raises(ValueError)\n def test_invalidid(self):\n f = self.fs.get('NOTANID')\n\n def test_creation_inputs(self):\n temp = NamedTemporaryFile()\n temp.write(FILE_CONTENT)\n temp.seek(0)\n\n for d in (FILE_CONTENT,\n BytesIO(FILE_CONTENT),\n temp,\n create_cgifs('text/plain', FILE_CONTENT, 'file.txt'),\n FileIntent(FILE_CONTENT, 'file.txt', 'text/plain')):\n fid = self.fs.create(d, 'filename')\n f = self.fs.get(fid)\n assert f.read() == FILE_CONTENT\n\n def test_content_type_by_name(self):\n for fname, ctype in (('filename', 'application/octet-stream'),\n ('image.png', 'image/png'),\n ('file.txt', 'text/plain')):\n file_id = self.fs.create(FILE_CONTENT, fname)\n f = self.fs.get(file_id)\n assert f.content_type == ctype, (fname, ctype)\n\n def test_cgifieldstorage(self):\n cgifs = create_cgifs('text/plain', FILE_CONTENT, 'file.txt')\n file_id = self.fs.create(cgifs)\n\n f = self.fs.get(file_id)\n assert f.content_type == 'text/plain'\n assert f.filename == 'file.txt'\n assert f.read() == FILE_CONTENT\n\n def test_fileintent(self):\n file_id = self.fs.create(FileIntent(FILE_CONTENT, 'file.txt', 'text/plain'))\n\n f = self.fs.get(file_id)\n assert f.content_type == 'text/plain', f.content_type\n assert f.filename == 'file.txt', f.filename\n assert f.read() == FILE_CONTENT\n\n def test_filewithname(self):\n temp = NamedTemporaryFile()\n temp.write(FILE_CONTENT)\n temp.seek(0)\n\n file_id = self.fs.create(temp)\n\n f = self.fs.get(file_id)\n assert f.content_type == 'application/octet-stream'\n assert temp.name.endswith(f.filename)\n assert f.read() == FILE_CONTENT\n\n def test_another_storage(self):\n file_id = self.fs.create(FILE_CONTENT, filename='file.txt', content_type='text/plain')\n f = self.fs.get(file_id)\n\n file2_id = self.fs.create(f)\n assert file2_id != f.file_id\n\n f2 = self.fs.get(file_id)\n assert f2.filename == f.filename\n assert f2.content_type == f.content_type\n assert f2.filename == 'file.txt'\n assert f2.content_type == 'text/plain'\n\n def test_repr(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n\n assert repr(f).endswith('%s filename=file.txt '\n 'content_type=text/plain '\n 'last_modified=%s>' % (f.file_id, f.last_modified))\n\n @raises(IOError)\n def test_replace_only_existing(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n assert self.fs.exists(file_id)\n self.fs.delete(file_id)\n assert not self.fs.exists(file_id)\n\n self.fs.replace(file_id, FILE_CONTENT)\n\n @raises(ValueError)\n def test_replace_invalidid(self):\n self.fs.replace('INVALIDID', FILE_CONTENT)\n\n def test_replace_keeps_filename(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n\n self.fs.replace(f, b'NEW CONTENT')\n f2 = self.fs.get(f.file_id)\n\n assert f2.file_id == f.file_id\n assert f.filename == f2.filename, (f.filename, f2.filename)\n assert f.read() == b'NEW CONTENT'\n assert f2.content_type == 'text/plain'\n\n def test_replace_updates_data(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n\n self.fs.replace(f, b'NEW CONTENT', 'file.png')\n f2 = self.fs.get(f.file_id)\n\n assert f2.file_id == f.file_id\n assert f2.filename == 'file.png'\n assert f2.read() == b'NEW CONTENT'\n assert f2.content_type == 'image/png'\n\n def test_exists(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n assert self.fs.exists(file_id)\n\n self.fs.delete(file_id)\n assert not self.fs.exists(file_id)\n\n @raises(ValueError)\n def test_exists_invalidid(self):\n self.fs.exists('INVALIDID')\n\n def test_delete(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n assert self.fs.exists(file_id)\n\n self.fs.delete(file_id)\n assert not self.fs.exists(file_id)\n\n def test_delete_idempotent(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n assert self.fs.exists(file_id)\n\n self.fs.delete(file_id)\n self.fs.delete(file_id)\n assert not self.fs.exists(file_id)\n\n @raises(ValueError)\n def test_delete_invalidid(self):\n self.fs.delete('INVALIDID')\n\n def test_stored_files_are_only_readable(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n assert f.readable()\n assert not f.writable()\n assert not f.seekable()\n\n @raises(TypeError)\n def test_storing_unicode_is_prevented(self):\n file_id = self.fs.create(FILE_CONTENT.decode('utf-8'), 'file.txt')\n\n @raises(TypeError)\n def test_replacing_unicode_is_prevented(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n\n self.fs.replace(f, FILE_CONTENT.decode('utf-8'))\n\n def test_closing_file(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n\n assert f.closed is False\n with f:\n f.read()\n assert f.closed is True\n\n @raises(ValueError)\n def test_reading_from_closed_file_is_prevented(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n f.close()\n\n f.read()\n\n def test_name_is_an_alias_for_filename(self):\n file_id = self.fs.create(FILE_CONTENT, 'file.txt')\n f = self.fs.get(file_id)\n assert f.name == f.filename\n\n\nclass TestLocalFileStorage(BaseStorageTestFixture):\n def setup(self):\n from depot.io.local import LocalFileStorage\n self.fs = LocalFileStorage('./lfs')\n\n def teardown(self):\n shutil.rmtree('./lfs', ignore_errors=True)\n\n\nclass TestGridFSFileStorage(BaseStorageTestFixture):\n def setup(self):\n try:\n from depot.io.gridfs import GridFSStorage\n except ImportError:\n raise SkipTest('PyMongo not installed')\n\n self.fs = GridFSStorage('mongodb://localhost/gridfs_example', 'testfs')\n\n def teardown(self):\n self.fs._db.drop_collection('testfs')\n\n\nclass TestS3FileStorage(BaseStorageTestFixture):\n @classmethod\n def setup_class(cls):\n try:\n from depot.io.awss3 import S3Storage\n except ImportError:\n raise SkipTest('Boto not installed')\n\n env = os.environ\n access_key_id = env.get('AWS_ACCESS_KEY_ID')\n secret_access_key = env.get('AWS_SECRET_ACCESS_KEY')\n if access_key_id is None or secret_access_key is None:\n raise SkipTest('Amazon S3 credentials not available')\n\n PID = os.getpid()\n NODE = str(uuid.uuid1()).rsplit('-', 1)[-1]\n BUCKET_NAME = 'fdtest-%s-%s-%s' % (access_key_id.lower(), NODE, PID)\n cls.fs = S3Storage(access_key_id, secret_access_key, BUCKET_NAME)\n\n def teardown(self):\n keys = [key.name for key in self.fs._bucket]\n if keys:\n self.fs._bucket.delete_keys(keys)\n\n @classmethod\n def teardown_class(cls):\n try:\n cls.fs._conn.delete_bucket(cls.fs._bucket.name)\n except:\n pass\n","sub_path":"tests/test_storage_interface.py","file_name":"test_storage_interface.py","file_ext":"py","file_size_in_byte":8805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"365835950","text":"from django.conf.urls import patterns, include, url\nimport views\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'hofapi.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^$', views.index, name = \"main\"),\n url(r'^sign_up/$', views.sign_up, name = \"signup\"),\n url(r'^sign_in/$', views.login_user, name = \"signin\"),\n url(r'^dash/$', views.dashboard, name = \"dash\"),\n url(r'^create/$', views.make_project, name = \"create\"),\n url(r'^list/$', views.list_projekts, name = \"list\"),\n\n)\n","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"120848324","text":"#*****************************************************************************/\r\n# @file mlp.c \r\n# @author Majid Nasiri 95340651\r\n# @version V1.0.0\r\n# @date 18 April 2017\r\n# @brief \r\n#*****************************************************************************/\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.io\r\nimport NN \r\n\r\n# import some data to play with\r\nsatimage = scipy.io.loadmat('..\\dataset\\satimage.mat')\r\ndata = satimage[\"satimage\"]\r\nX = data[:, :-1].T\r\ntarget = data[:, -1]\r\n\r\nN = np.array([36,30,30,30,6])\r\nNS=6435;\r\n\r\nt = np.zeros((7, NS))\r\nfor s in range(NS):\r\n t[target[s]-1,s]=1\r\nt = np.delete(t, 5, axis=0)\r\n \r\nmu=0.01\r\nsample=0\r\nmaxEpoch=10000\r\n\r\n\r\nerror_array = NN.mlp(X, t, N, NS, mu, maxEpoch)\r\n\r\nplt.figure(num = 1, figsize=(8,6))\r\nplt.plot(error_array.T)\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Error Rate')\r\nplt.grid()\r\nplt.show()\r\nplt.savefig('..\\images\\satimage_36-30-30-30-6.jpg')\r\n\r\n\r\n\r\n\r\n","sub_path":"machine_learning/multiLayer_perceptron/MLP_satimage.py","file_name":"MLP_satimage.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"458278146","text":"import bpy\n\ndef get_panels():\n exclude_panels = {\n 'DATA_PT_area',\n 'DATA_PT_camera_dof',\n 'DATA_PT_falloff_curve',\n 'DATA_PT_light',\n 'DATA_PT_preview',\n 'DATA_PT_shadow',\n 'DATA_PT_sunsky',\n 'MATERIAL_PT_diffuse',\n 'MATERIAL_PT_flare',\n 'MATERIAL_PT_halo',\n 'MATERIAL_PT_mirror',\n 'MATERIAL_PT_options',\n 'MATERIAL_PT_pipeline',\n 'MATERIAL_PT_preview',\n 'MATERIAL_PT_shading',\n 'MATERIAL_PT_shadow',\n 'MATERIAL_PT_specular',\n 'MATERIAL_PT_sss',\n 'MATERIAL_PT_strand',\n 'MATERIAL_PT_transp',\n 'MATERIAL_PT_volume_density',\n 'MATERIAL_PT_volume_integration',\n 'MATERIAL_PT_volume_lighting',\n 'MATERIAL_PT_volume_options',\n 'MATERIAL_PT_volume_shading',\n 'MATERIAL_PT_volume_transp',\n 'RENDERLAYER_PT_layer_options',\n 'RENDERLAYER_PT_layer_passes',\n 'RENDERLAYER_PT_views',\n 'RENDER_PT_antialiasing',\n 'RENDER_PT_bake',\n 'RENDER_PT_performance',\n 'RENDER_PT_freestyle',\n 'RENDER_PT_shading',\n 'RENDER_PT_render',\n 'RENDER_PT_stamp',\n 'RENDER_PT_simplify',\n 'RENDER_PT_color_management',\n 'TEXTURE_PT_context_texture',\n 'WORLD_PT_ambient_occlusion',\n 'WORLD_PT_environment_lighting',\n 'WORLD_PT_gather',\n 'WORLD_PT_indirect_lighting',\n 'WORLD_PT_mist',\n 'WORLD_PT_preview',\n 'WORLD_PT_world',\n 'NODE_DATA_PT_light',\n 'NODE_DATA_PT_spot',\n }\n\n panels = []\n for t in bpy.types.Panel.__subclasses__():\n if hasattr(t, 'COMPAT_ENGINES') and 'BLENDER_RENDER' in t.COMPAT_ENGINES:\n if t.__name__ not in exclude_panels:\n panels.append(t)\n\n return panels\n\ndef register():\n # This module is here to tell Blender which builtin panels we are\n # compatible with\n for panel in get_panels():\n panel.COMPAT_ENGINES.add('PRMAN_RENDER')\n\n\ndef unregister():\n\n for panel in get_panels():\n panel.COMPAT_ENGINES.remove('PRMAN_RENDER')","sub_path":"rman_ui/rman_ui_blender_panels.py","file_name":"rman_ui_blender_panels.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"20580446","text":"import torch.nn\nimport torch\nimport os\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\n#from torchvision.transforms import transforms\nimport config\n#from skimage.filters import sobel\n#from skimage.transform import rotate\nimport random\nimport cv2\nimport config\nfrom torch.autograd import Variable\n\nmean = (0.485,0.456,0.406)\nstd = (0.229,0.224,0.225)\n\nx =115\n\ndef crop(img,label,edges):\n a = random.randint(1+x,255-x)\n b = random.randint(1+x,255-x)\n #print(np.shape(img))\n img = img[a-x:a+x,b-x:b+x,:]\n edge = edges[a-x:a+x,b-x:b+x]\n label = label[a-x:a+x,b-x:b+x]\n\n # print(np.shape(img))\n\n\n return img, label,edge\n\n\ndef normalize(image):\n \"\"\"Normalize each channel of the numpy array i.e.\n channel = (channel - mean) / std\n \"\"\"\n image /= 255.\n image -= image.mean(axis=(0, 1))\n s = image.std(axis=(0, 1))\n s[s == 0] = 1.0\n image /= s\n return image\n\n\n\n\nclass DataFolder(Dataset):\n def __init__(self, imgs, labels, trainable=True):\n super(DataFolder, self).__init__()\n self.img_paths = imgs\n self.label_paths = labels\n self.trainable = trainable\n\n # assert(len(self.img_paths)==len(self.label_paths))\n def __len__(self):\n return len(self.img_paths)\n\n def __getitem__(self, idx):\n #print(idx)\n\n img_path = self.img_paths[idx]\n label_path = self.label_paths[idx]\n #print(img_path)\n\n p,l_name = os.path.split(label_path)\n #print(l_name)\n img = cv2.imread(img_path)\n\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)/255.0\n\n\n\n label = cv2.imread(label_path, 0)\n\n edges = cv2.Canny(label, 50, 200)\n\n shape = label.shape\n\n img = cv2.resize(img, config.IMG_SIZE)\n\n\n label = cv2.resize(label, config.LABEL_SIZE)/255.0\n label = np.clip(label, 0, 1)\n label[label < 0.5] = 0\n label[label > 0.5] = 1\n s = np.sum(label) / np.prod(config.LABEL_SIZE)\n weight = np.zeros_like(label)\n weight[label == 0] = 1. - s\n weight[label == 1] = s\n\n\n\n ##float tensor\n\n edges = cv2.resize(edges, config.LABEL_SIZE,interpolation=cv2.INTER_CUBIC)/255.0\n\n\n if self.trainable:\n label = np.clip(label,0,1)\n img,label,edges = crop(img,label,edges)\n #angle = random.choice([-10,-5,0,5,10,0,0])\n #img = rotate(img, angle, clip=True)\n #label = rotate(label, angle, clip=True)\n #edges = rotate(edges, angle, clip=True)\n if random.random()<0.5:\n img = cv2.flip(img,1)\n label = cv2.flip(label,1)\n edges = cv2.flip(edges,1)\n #angle = random.choice([0,90,180,270])\n #img = rotate(img,angle,clip = True)\n #label = rotate(label,angle,clip = True)\n #edges = rotate(edges,angle,clip=True)\n\n #print(\"0\",np.shape(img))\n\n img = cv2.resize(img, (256,256),interpolation=cv2.INTER_CUBIC)\n edges = cv2.resize(edges, config.IMG_SIZE,interpolation=cv2.INTER_CUBIC)\n label = cv2.resize(label, config.IMG_SIZE,interpolation=cv2.INTER_CUBIC)\n\n edges = torch.FloatTensor(edges)\n\n #print(\"1\",np.shape(img))\n img = np.transpose(img, [2, 0, 1])\n img = normalize(img)\n\n\n\n\n img = torch.FloatTensor(img)\n #print(\"2\",img.shape)\n\n\n label = torch.FloatTensor(label)\n\n\n return img,label,edges,shape,l_name\n\n\ndef process_data_dir(data_dir):\n files = os.listdir(data_dir)\n files = map(lambda x: os.path.join(data_dir, x), files)\n return sorted(files)\n\nif __name__ == \"__main__\":\n\n test_dirs = [\n (\"/home/neverupdate/Downloads/SalGAN-master/SED1/SED1-Image\",\n \"/home/neverupdate/Downloads/SalGAN-master/SED1/SED1-Mask\")\n ]\n\n\n\n batch_size = config.BATCH_SIZE\n DATA_DICT = {}\n\n IMG_FILES = []\n GT_FILES = []\n\n IMG_FILES_TEST = []\n GT_FILES_TEST = []\n\n for dir_pair in test_dirs:\n X, y = process_data_dir(dir_pair[0]), process_data_dir(dir_pair[1])\n IMG_FILES.extend(X)\n GT_FILES.extend(y)\n\n IMGS_train, GT_train = IMG_FILES, GT_FILES\n\n test_folder = DataFolder(IMGS_train, GT_train, True)\n\n test_data = DataLoader(test_folder, batch_size=config.BATCH_SIZE, num_workers=config.NUM_WORKERS, shuffle=True,\n drop_last=True)\n for iter_cnt, (img,label,edges,shape,l_name) in enumerate(test_data):\n w= shape[0].numpy()[0]\n h=shape[1].numpy()[0]\n #print(img.shape)\n\n #print(l_name,r_name)\n label = 255.0*label.numpy()[0,:,:]\n cv2.imshow(\"img\",edges.numpy()[0,:,:]*255)\n cv2.waitKey()\n\n print(iter_cnt)\n\n","sub_path":"four_v/data_new.py","file_name":"data_new.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"627580245","text":"import aioboto3\nimport re\n\n\nclass Bucket:\n def __init__(self, name, creation_date, subresources ,key_filter):\n self.__name = name\n self.__creation_date = creation_date\n self.__subresources = subresources\n self.__key_filter = key_filter\n\n async def process_bucket(self):\n async with aioboto3.resource(\"s3\") as s3:\n bucket = await s3.Bucket(self.__name)\n (\n self.__number_of_files,\n self.__size,\n self.__most_recent_file,\n self.__last_modified,\n ) = await self.__process_files(bucket)\n print(self)\n\n async def __process_files(self, bucket):\n number_of_files = 0\n total_size = 0.0\n most_recent_file = \"\"\n last_modified = \"\"\n\n async for object in bucket.objects.all():\n match = re.match(self.__key_filter, object.key)\n if not match:\n continue\n size = await object.size\n date = await object.last_modified\n if last_modified == \"\" or date > last_modified:\n last_modified = date\n most_recent_file = object.key\n if size > 0:\n number_of_files += 1\n total_size += size\n\n return number_of_files, total_size, most_recent_file, last_modified\n\n def __format_bytes(self, size):\n power = 2 ** 10\n n = 0\n power_labels = {0: \"\", 1: \"K\", 2: \"M\", 3: \"G\", 4: \"T\"}\n while size > power:\n size /= power\n n += 1\n return f\"{size} {power_labels[n]}B\"\n\n def __calculate_cost(self, size):\n gb = size / 1024 / 1024 / 1024\n # rough cost estimate based on the us-east-1 price\n price = gb * 0.023\n return f\"{price:.3f}\"\n\n def __str__(self):\n return (\n f\"Bucket Name: {self.__name}\\n\"\n f\"Creation Date: {self.__creation_date}\\n\"\n f\"Number of Files: {self.__number_of_files}\\n\"\n f\"Total Size: {self.__format_bytes(self.__size)}\\n\"\n f\"Total Cost: USD {self.__calculate_cost(self.__size)}\\n\"\n f\"Most Recent Updated File: {self.__most_recent_file} Last Modified: {self.__last_modified}\\n\"\n f\"SubResources: {self.__subresources}\\n\"\n )\n","sub_path":"s3_sat/bucket.py","file_name":"bucket.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440544329","text":"#!/usr/bin/env python\n\nimport glob\n\ndependencies = {}\n\nfor src in glob.iglob('*.F90'):\n module = src.strip('.F90')\n d = set()\n for line in open(src, 'r'):\n words = line.split()\n if words and words[0].lower() == 'use':\n name = words[1].strip(',')\n if name in ['mpi','hdf5','h5lt']:\n continue\n d.add(words[1].strip(','))\n if d:\n d = list(d)\n d.sort()\n dependencies[module] = d\n\n\nkeys = dependencies.keys()\nkeys.sort()\nfor module in keys:\n for dep in dependencies[module]:\n print(\"{0}.o: {1}.o\".format(module, dep))\n print('')\n","sub_path":"src/utils/build_dependencies.py","file_name":"build_dependencies.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"370023375","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyage_forams/conf/dummy_conf.py\n# Compiled at: 2014-11-03 18:03:52\nfrom pyage.core import address\nfrom pyage_forams.solutions.genom import GenomFactory\nfrom pyage_forams.solutions.insolation_meter import StaticInsolation\nfactory = GenomFactory(chambers_limit=5)\ngenom_factory = lambda : factory.generate\ninsolation_meter = StaticInsolation\naddress_provider = address.SequenceAddressProvider\nsize = lambda : 3\ncell_capacity = lambda : 1\nalgae_growth_probability = lambda : 0.3\nreproduction_minimum = lambda : 10\nmovement_energy = lambda : 0.25\ngrowth_minimum = lambda : 10\nenergy_need = lambda : 0.2\nalgae_limit = lambda : 20\nnewborn_limit = lambda : 9\nreproduction_probability = lambda : 0.8\ngrowth_probability = lambda : 0.8\ngrowth_cost_factor = lambda : 0.5\ncapacity_factor = lambda : 1.1\ninitial_algae_probability = lambda : 0.3","sub_path":"pycfiles/PyAgg-0.2.0/dummy_conf.py","file_name":"dummy_conf.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"59981599","text":"from .base import *\nfrom decouple import ConfigIni\nimport dj_database_url\n\n# ######### DEBUG CONFIGURATION\nDEBUG = True\n\nTEMPLATE_DEBUG = DEBUG\n\nCOMPRESS_ENABLED = not DEBUG\n# ######### END DEBUG CONFIGURATION\n\nconfig = ConfigIni(PROJECT_DIR.child('confs')+'/settings.ini')\n\n# ######### MAILTRAP CONFIGURATION\n# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n# EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'\nEMAIL_BACKEND = \"djrill.mail.backends.djrill.DjrillBackend\"\nMANDRILL_API_KEY = config('EMAIL_HOST_PASSWORD')\nEMAIL_HOST = config('EMAIL_HOST')\nEMAIL_HOST_USER = config('EMAIL_HOST_USER')\nEMAIL_PORT = config('EMAIL_PORT')\n\n# ######### END MAILTRAP CONFIGURATION\n\n# ######### EMAIL CONFIGURATION\n# EMAIL_HOST = \"localhost\"\n# EMAIL_PORT = 1025\n# EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'\n# ######### END EMAIL CONFIGURATION\n\n# ######### DATABASE CONFIGURATION\nDATABASES = {\n 'default': dj_database_url.config(\n default=config('DATABASE_URL')\n )\n}\n# ######### END DATABASE CONFIGURATION\n\n# ######### CACHE CONFIGURATION\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n}\n# ######### END CACHE CONFIGURATION\n\n\n# ######### INSTALLED APPS CONFIGURATION\n\nINSTALLED_APPS += (\n 'debug_toolbar',\n 'django_nose',\n)\n\n# IPs allowed to see django-debug-toolbar output.\nINTERNAL_IPS = (\"127.0.0.1\",)\n\n\nMIDDLEWARE_CLASSES += \\\n (\"debug_toolbar.middleware.DebugToolbarMiddleware\", )\n\n\nDEBUG_TOOLBAR_CONFIG = {\n # If set to True (default), the debug toolbar will show an intermediate\n # page upon redirect so you can view any debug information prior to\n # redirecting. This page will provide a link to the redirect\n # destination\n # you can follow when ready. If set to False, redirects will proceed as\n # normal.\n 'INTERCEPT_REDIRECTS': False,\n\n # If not set or set to None, the debug_toolbar middleware will use its\n # built-in show_toolbar method for determining whether the toolbar\n # should\n # show or not. The default checks are that DEBUG must be set to True\n # and\n # the IP of the request must be in INTERNAL_IPS. You can provide your\n # own\n # method for displaying the toolbar which contains your custom logic.\n # This\n # method should return True or False.\n\n # An array of custom signals that might be in your project, defined as\n # the\n # python path to the signal.\n 'EXTRA_SIGNALS': [],\n\n # If set to True (the default) then a template's context will be\n # included\n # with it in the Template debug panel. Turning this off is useful when\n # you\n # have large template contexts, or you have template contexts with lazy\n # datastructures that you don't want to be evaluated.\n 'SHOW_TEMPLATE_CONTEXT': True,\n}\n# ######### END DJANGO-DEBUG-TOOLBAR CONFIGURATION\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'sqlhandler': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'sqlformatter'\n }\n },\n 'formatters': {\n 'sqlformatter': {\n '()': 'sqlformatter.SqlFormatter',\n 'format': '%(levelname)s %(message)s',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins', 'sqlhandler'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n }\n}\n","sub_path":"pywatch/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":3757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"455687640","text":"#!/usr/bin/env python\n#-*- coding: ISO-8859-1 -*-\n#pylint: disable=R0913,W0702,R0914,R0912,R0201\n\"\"\"\nFile: pycurl_manager.py\nAuthor: Valentin Kuznetsov \nDescription: a basic wrapper around pycurl library.\nThe RequestHandler class provides basic APIs to get data\nfrom a single resource or submit mutliple requests to\nunderlying data-services.\n\"\"\"\nfrom __future__ import print_function\n\nimport cStringIO as StringIO\nimport httplib\nimport json\nimport logging\nimport urllib\n\nimport pycurl\n\nclass ResponseHeader(object):\n \"\"\"ResponseHeader parses HTTP response header\"\"\"\n def __init__(self, response):\n super(ResponseHeader, self).__init__()\n self.header = {}\n self.reason = ''\n self.fromcache = False\n self.parse(response)\n\n def parse(self, response):\n \"\"\"Parse response header and assign class member data\"\"\"\n for row in response.split('\\r'):\n row = row.replace('\\n', '')\n if not row:\n continue\n if row.find('HTTP') != -1 and \\\n row.find('100') == -1: #HTTP/1.1 100 found: real header is later\n res = row.replace('HTTP/1.1', '')\n res = res.replace('HTTP/1.0', '')\n res = res.strip()\n status, reason = res.split(' ', 1)\n self.status = int(status)\n self.reason = reason\n continue\n try:\n key, val = row.split(':', 1)\n self.header[key.strip()] = val.strip()\n except:\n pass\n\nclass RequestHandler(object):\n \"\"\"\n RequestHandler provides APIs to fetch single/multiple\n URL requests based on pycurl library\n \"\"\"\n def __init__(self, config=None, logger=None):\n super(RequestHandler, self).__init__()\n if not config:\n config = {}\n self.nosignal = config.get('nosignal', 1)\n self.timeout = config.get('timeout', 30)\n self.connecttimeout = config.get('connecttimeout', 30)\n self.followlocation = config.get('followlocation', 1)\n self.maxredirs = config.get('maxredirs', 5)\n self.logger = logger if logger else logging.getLogger()\n\n def encode_params(self, params, verb, doseq):\n \"\"\" Encode request parameters for usage with the 4 verbs.\n Assume params is alrady encoded if it is a string and\n uses a different encoding depending on the HTTP verb\n (either json.dumps or urllib.urlencode)\n \"\"\"\n #data is already encoded, just return it\n if isinstance(params, basestring):\n return params\n\n #data is not encoded, we need to do that\n if verb in ['GET', 'HEAD']:\n if params:\n encoded_data = urllib.urlencode(params, doseq=doseq)\n else:\n return ''\n else:\n if params:\n encoded_data = json.dumps(params)\n else:\n return {}\n\n return encoded_data\n\n def set_opts(self, curl, url, params, headers,\n ckey=None, cert=None, capath=None, verbose=None, verb='GET', doseq=True, cainfo=None):\n \"\"\"Set options for given curl object, params should be a dictionary\"\"\"\n if not (isinstance(params, (dict, basestring)) or params is None):\n raise TypeError(\"pycurl parameters should be passed as dictionary or an (encoded) string\")\n curl.setopt(pycurl.NOSIGNAL, self.nosignal)\n curl.setopt(pycurl.TIMEOUT, self.timeout)\n curl.setopt(pycurl.CONNECTTIMEOUT, self.connecttimeout)\n curl.setopt(pycurl.FOLLOWLOCATION, self.followlocation)\n curl.setopt(pycurl.MAXREDIRS, self.maxredirs)\n\n encoded_data = self.encode_params(params, verb, doseq)\n\n if verb == 'GET':\n if encoded_data:\n url = url + '?' + encoded_data\n elif verb == 'HEAD':\n if encoded_data:\n url = url + '?' + encoded_data\n curl.setopt(pycurl.CUSTOMREQUEST, verb)\n curl.setopt(pycurl.HEADER, 1)\n curl.setopt(pycurl.NOBODY, True)\n elif verb == 'POST':\n curl.setopt(pycurl.POST, 1)\n if encoded_data:\n curl.setopt(pycurl.POSTFIELDS, encoded_data)\n elif verb == 'DELETE' or verb == 'PUT':\n curl.setopt(pycurl.CUSTOMREQUEST, verb)\n curl.setopt(pycurl.HTTPHEADER, ['Transfer-Encoding: chunked'])\n if encoded_data:\n curl.setopt(pycurl.POSTFIELDS, encoded_data)\n else:\n raise Exception('Unsupported HTTP method \"%s\"' % verb)\n\n curl.setopt(pycurl.URL, url)\n if headers:\n curl.setopt(pycurl.HTTPHEADER, \\\n [\"%s: %s\" % (k, v) for k, v in headers.items()])\n bbuf = StringIO.StringIO()\n hbuf = StringIO.StringIO()\n curl.setopt(pycurl.WRITEFUNCTION, bbuf.write)\n curl.setopt(pycurl.HEADERFUNCTION, hbuf.write)\n if capath:\n curl.setopt(pycurl.CAPATH, capath)\n curl.setopt(pycurl.SSL_VERIFYPEER, True)\n if cainfo:\n curl.setopt(pycurl.CAINFO, cainfo)\n else:\n curl.setopt(pycurl.SSL_VERIFYPEER, False)\n if ckey:\n curl.setopt(pycurl.SSLKEY, ckey)\n if cert:\n curl.setopt(pycurl.SSLCERT, cert)\n if verbose:\n curl.setopt(pycurl.VERBOSE, 1)\n curl.setopt(pycurl.DEBUGFUNCTION, self.debug)\n return bbuf, hbuf\n\n def debug(self, debug_type, debug_msg):\n \"\"\"Debug callback implementation\"\"\"\n print(\"debug(%d): %s\" % (debug_type, debug_msg))\n\n def parse_body(self, data, decode=False):\n \"\"\"\n Parse body part of URL request (by default use json).\n This method can be overwritten.\n \"\"\"\n if decode:\n try:\n res = json.loads(data)\n except ValueError as exc:\n msg = 'Unable to load JSON data, %s, data type=%s, pass as is' \\\n % (str(exc), type(data))\n logging.warning(msg)\n return data\n return res\n else:\n return data\n\n def parse_header(self, header):\n \"\"\"\n Parse response header.\n This method can be overwritten.\n \"\"\"\n return ResponseHeader(header)\n\n def request(self, url, params, headers=None, verb='GET',\n verbose=0, ckey=None, cert=None, capath=None, doseq=True, decode=False, cainfo=None):\n \"\"\"Fetch data for given set of parameters\"\"\"\n curl = pycurl.Curl()\n bbuf, hbuf = self.set_opts(curl, url, params, headers,\n ckey, cert, capath, verbose, verb, doseq, cainfo)\n curl.perform()\n if verbose:\n print(verb, url, params, headers)\n header = self.parse_header(hbuf.getvalue())\n if header.status < 300:\n if verb == 'HEAD':\n data = ''\n else:\n data = self.parse_body(bbuf.getvalue(), decode)\n else:\n data = bbuf.getvalue()\n msg = 'url=%s, code=%s, reason=%s, headers=%s' \\\n % (url, header.status, header.reason, header.header)\n exc = httplib.HTTPException(msg)\n setattr(exc, 'req_data', params)\n setattr(exc, 'req_headers', headers)\n setattr(exc, 'url', url)\n setattr(exc, 'result', data)\n setattr(exc, 'status', header.status)\n setattr(exc, 'reason', header.reason)\n setattr(exc, 'headers', header.header)\n bbuf.flush()\n hbuf.flush()\n raise exc\n\n bbuf.flush()\n hbuf.flush()\n return header, data\n\n def getdata(self, url, params, headers=None, verb='GET',\n verbose=0, ckey=None, cert=None, doseq=True):\n \"\"\"Fetch data for given set of parameters\"\"\"\n _, data = self.request(url=url, params=params, headers=headers, verb=verb,\n verbose=verbose, ckey=ckey, cert=cert, doseq=doseq)\n return data\n\n def getheader(self, url, params, headers=None, verb='GET',\n verbose=0, ckey=None, cert=None, doseq=True):\n \"\"\"Fetch HTTP header\"\"\"\n header, _ = self.request(url, params, headers, verb,\n verbose, ckey, cert, doseq)\n return header\n\n def multirequest(self, url, parray, headers=None,\n ckey=None, cert=None, verbose=None):\n \"\"\"Fetch data for given set of parameters\"\"\"\n multi = pycurl.CurlMulti()\n for params in parray:\n curl = pycurl.Curl()\n bbuf, hbuf = \\\n self.set_opts(curl, url, params, headers, ckey, cert, verbose)\n multi.add_handle(curl)\n while True:\n ret, num_handles = multi.perform()\n if ret != pycurl.E_CALL_MULTI_PERFORM:\n break\n while num_handles:\n ret = multi.select(1.0)\n if ret == -1:\n continue\n while True:\n ret, num_handles = multi.perform()\n if ret != pycurl.E_CALL_MULTI_PERFORM:\n break\n dummyNumq, response, dummyErr = multi.info_read()\n for dummyCobj in response:\n data = json.loads(bbuf.getvalue())\n if isinstance(data, dict):\n data.update(params)\n yield data\n if isinstance(data, list):\n for item in data:\n if isinstance(item, dict):\n item.update(params)\n yield item\n else:\n err = 'Unsupported data format: data=%s, type=%s'\\\n % (item, type(item))\n raise Exception(err)\n bbuf.flush()\n hbuf.flush()\n","sub_path":"src/python/WMCore/Services/pycurl_manager.py","file_name":"pycurl_manager.py","file_ext":"py","file_size_in_byte":10030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"174165817","text":"'''\n小偷问题\n O\n O O\nO O O O\n子节点和父节点不可以同时偷\n思路:深度遍历,计算每个节点偷与不偷值\n'''\nclass TreeNode:\n def __init__(self,x):\n self.val = x\n self.left = None\n self.right = None\n\nt = TreeNode(3)\nt.left = TreeNode(4)\nt.right = TreeNode(5)\nt.left.left = TreeNode(1)\nt.left.right = TreeNode(3)\nt.right.right = TreeNode(1)\n\ndef rob(root):\n a = helper(root)\n return max(a[0],a[1])\n\ndef helper(root):\n if root == None:\n return [0,0]\n left = helper(root.left)\n right = helper(root.right)\n robValue = root.val + left[1] + right[1]\n #子节点可能偷与不偷的最大值\n skipValue = max(left[0] , left[1]) + max(right[0] , right[1])\n # print(robValue,skipValue)\n return [robValue,skipValue]\n\nprint(rob(t))\n\n\n ","sub_path":"chaos/thief-problem.py","file_name":"thief-problem.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"506216255","text":"import threading\nimport time\nfrom flask import Request\n\n\nrequest = None\n\nrequest1 = Request()\nrequest2 = Request()\nrequest3 = Request()\n\ndef worker():\n print('work线程开始执行了\\n')\n print('I am threading')\n request = Request()\n t = threading.current_thread()\n time.sleep(10)\n print(t.getName())\n\n# 更加充分的利用CPU的性能优势\n# 因为启用了线程不会阻塞主进程\nnew_t = threading.Thread(target=worker, name='thread_test')\nnew_t.start()\nnew_t = threading.Thread(target=worker, name='thread_test')\nnew_t.start()\nnew_t = threading.Thread(target=worker, name='thread_test')\nnew_t.start()\n\n\nprint('主线程开始执行了\\n')\nt = threading.current_thread()\nprint(t.getName())\nprint('主线程执行完成了')\n","sub_path":"test/test_thread2.py","file_name":"test_thread2.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"56582858","text":"from os import listdir\n\ndef gen(path, fun):\n\twith open(path, \"r\") as f:\n\t\tarray = {}\n\t\tcat = None\n\t\tpredicate = None\n\t\ttemplates = []\n\t\tshort = None\n\t\tdescription = \"\"\n\t\tempty = False\n\t\tfor line in f:\n\t\t\tif line[:3] == \"%% \":\n\t\t\t\tcat = line[3:].replace(\"\\n\",\"\").replace(\" \",\"-\").lower()\n\t\t\t\tarray[cat] = []\n\t\t\telif line[:4] == '%%% ' or line[:4] == '%%%\\n':\n\t\t\t\tif predicate is None:\n\t\t\t\t\tpredicate = line[4:]\n\t\t\t\telif not empty and len(line) > 4:\n\t\t\t\t\ttemplates.append(line[4:])\n\t\t\t\telse:\n\t\t\t\t\tif short is None and empty:\n\t\t\t\t\t\tshort = line[4:]\n\t\t\t\t\telse:\n\t\t\t\t\t\tdescription += line[3:]\n\t\t\t\t\tempty = True\n\t\t\telse:\n\t\t\t\tif cat is not None and short is not None and predicate is not None:\n\t\t\t\t\tpredicate = predicate.replace(\"\\n\",\"\")\n\t\t\t\t\tshort = short.replace(\"\\n\",\"\")\n\t\t\t\t\ttemplates = map(lambda x: x.replace(\"\\n\",\"\"), templates)\n\t\t\t\t\tdescription = description.replace(\"\\n\",\"\").strip(\" \")\n\t\t\t\t\tarray[cat].append((predicate, templates, short, description))\n\t\t\t\tpredicate = None\n\t\t\t\tshort = None\n\t\t\t\ttemplates = []\n\t\t\t\tdescription = \"\"\n\t\t\t\tempty = False\n\tcats = sorted(array.keys())\n\tfor name in cats:\n\t\tdoc = \"\\n\".join(map(lambda x: fun(name, x), array[name]))\n\t\tout = open(\"../www/pages/ref-doc/\" + name + \".php\", \"w\")\n\t\tout.write(doc)\n\t\tout.close()\n\ndef html(cat, x):\n\t(predicate, templates, short, description) = x\n\thtml = \"
\"\n\thtml += \"

\" + predicate + \"

\"\n\thtml += \"

\" + short + \"

\"\n\tfor template in templates:\n\t\thtml += \"\"\n\thtml += \"

\"\n\thtml += \"
\"\n\treturn html\n\ngen(\"../src/builtin.pl\", html)\n","sub_path":"doc/builtin.py","file_name":"builtin.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"101460525","text":"# Import > Random\nimport random\n\n# Function > Sum\ndef int_sum(int_list):\n # Initialization > Sum\n sum = 0\n\n # Loop > Update > Sum\n for integer in int_list:\n sum += integer\n\n # Return\n return sum\n\n# Initialization > (Integer : List)\nint_list = list(range(10))\n\n# Print\nprint('Program to calculate the sum of a random set of 10 integers.', end='\\n\\n')\n\n# Loop > Update > (Integer : List)\nfor item in int_list:\n int_list[item] = random.randint(0, 10)\n\n# Print\nprint('List:', int_list)\nprint('Sum:', int_sum(int_list))\n","sub_path":"Technologies/Python/Covenant University/v1/demo.v29.py","file_name":"demo.v29.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"162695659","text":"#!/usr/bin/python\n#\n# Tests the functionality of multTable plugin\n#\n#\n# To run this test on your own shell, simply run:\n#\n# python /web/courses/cs3214/spring2015/projects/student-plugins/alisherp_amind1/multTable/202_multTable_test.py eshoutput.py\n#\n#\n# @author Alisher Pazylbekov, Amin Davoodi\n#\nimport sys, imp, atexit, os\nsys.path.append(\"/home/courses/cs3214/software/pexpect-dpty/\");\nimport pexpect, shellio, signal, time, os, re, proc_check\n\n# Determine the path this file is in\nthisdir = os.path.dirname(os.path.realpath(__file__))\n\n#Ensure the shell process is terminated\ndef force_shell_termination(shell_process):\n\tc.close(force=True)\n\n# pulling in the regular expression and other definitions\n# this should be the eshoutput.py file of the hosting shell, see usage above\ndefinitions_scriptname = sys.argv[1]\ndef_module = imp.load_source('', definitions_scriptname)\n\n# you can define logfile=open(\"log.txt\", \"w\") in your eshoutput.py if you want logging!\nlogfile = None\nif hasattr(def_module, 'logfile'):\n logfile = def_module.logfile\n\n#spawn an instance of the shell, note the -p flags\nc = pexpect.spawn(def_module.shell, drainpty=True, logfile=logfile, args=['-p', thisdir])\n\natexit.register(force_shell_termination, shell_process=c)\n\n# set timeout for all following 'expect*' calls to 2 seconds\nc.timeout = 2 \n\n\nc.sendline(\"multTable\")\nassert c.expect(\" | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10\") == 0, \"Error: Output doesn't match\"\n\n\nshellio.success()\n","sub_path":"Systems/esh-spring-2015.git/src/plugins/202_multTable_test.py","file_name":"202_multTable_test.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"287350580","text":"from django.urls import reverse\nfrom django.test.client import Client\n\nfrom pybb.models import ForumReadTracker, TopicReadTracker, Topic, Post, Forum\nfrom pybb.compat import get_user_model\n\nfrom tests.base import TestCase\n\n\nclass TrackersTest(TestCase):\n def test_read_tracking_multi_user(self):\n self.post\n\n topic_1 = self.topic\n topic_2 = Topic(name='topic_2', forum=self.forum, user=self.user)\n topic_2.save()\n\n Post(topic=topic_2, user=self.user, body='one').save()\n\n user_ann = get_user_model().objects.create_user('ann', 'ann@localhost', 'ann')\n client_ann = Client()\n client_ann.login(username='ann', password='ann')\n\n user_bob = get_user_model().objects.create_user('bob', 'bob@localhost', 'bob')\n client_bob = Client()\n client_bob.login(username='bob', password='bob')\n\n # Two topics, each with one post. everything is unread, so the db should reflect that:\n self.assertEqual(TopicReadTracker.objects.all().count(), 0)\n self.assertEqual(ForumReadTracker.objects.all().count(), 0)\n\n # user_ann reads topic_1, she should get one topic read tracker, there should be no forum read trackers\n client_ann.get(topic_1.get_absolute_url())\n self.assertEqual(TopicReadTracker.objects.all().count(), 1)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 1)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_ann, topic=topic_1).count(), 1)\n self.assertEqual(ForumReadTracker.objects.all().count(), 0)\n\n # user_bob reads topic_1, he should get one topic read tracker, there should be no forum read trackers\n client_bob.get(topic_1.get_absolute_url())\n self.assertEqual(TopicReadTracker.objects.all().count(), 2)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 1)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_bob, topic=topic_1).count(), 1)\n self.assertEqual(ForumReadTracker.objects.all().count(), 0)\n\n # user_bob reads topic_2, he should get a forum read tracker,\n # there should be no topic read trackers for user_bob\n client_bob.get(topic_2.get_absolute_url())\n self.assertEqual(TopicReadTracker.objects.all().count(), 1)\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=user_bob).count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=user_bob, forum=self.forum).count(), 1)\n\n # user_ann creates topic_3, there should be a new topic read tracker in the db\n topic_create_url = reverse('pybb:topic_create', kwargs={'forum_id': self.forum.id})\n response = client_ann.get(topic_create_url)\n values = self.get_form_values(response)\n values['body'] = 'topic_3'\n values['name'] = 'topic_3'\n values['poll_type'] = 0\n response = client_ann.post(topic_create_url, data=values, follow=True)\n\n self.assertEqual(TopicReadTracker.objects.all().count(), 2)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 2)\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n\n topic_3 = Topic.objects.order_by('-updated')[0]\n self.assertEqual(topic_3.name, 'topic_3')\n\n # user_ann posts to topic_1, a topic they've already read, no new trackers should be created (existing one is updated)\n post_create_url = reverse('pybb:post_create', kwargs={'topic_id': topic_1.id})\n response = client_ann.get(post_create_url)\n values = self.get_form_values(response)\n values['body'] = 'test tracking'\n response = client_ann.post(post_create_url, values, follow=True)\n self.assertEqual(TopicReadTracker.objects.all().count(), 2)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_ann).count(), 2)\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n previous_time = ForumReadTracker.objects.all()[0].time_stamp\n\n # user bob reads topic 1 which he already read, topic tracker recreated, forum tracker untouched (topic 3 still unread)\n client_bob.get(topic_1.get_absolute_url())\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n self.assertEqual(ForumReadTracker.objects.all()[0].time_stamp, previous_time)\n self.assertEqual(TopicReadTracker.objects.all().count(), 3)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 1)\n\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n previous_time = ForumReadTracker.objects.all()[0].time_stamp\n\n # user bob reads topic 3, topic tracker purged, forum tracker updated\n client_bob.get(topic_3.get_absolute_url())\n self.assertEqual(ForumReadTracker.objects.all().count(), 1)\n self.assertGreater(ForumReadTracker.objects.all()[0].time_stamp, previous_time)\n self.assertEqual(TopicReadTracker.objects.all().count(), 2)\n self.assertEqual(TopicReadTracker.objects.filter(user=user_bob).count(), 0)\n\n def test_read_tracking_multi_forum(self):\n self.post\n\n topic_1 = self.topic\n topic_2 = Topic(name='topic_2', forum=self.forum, user=self.user)\n topic_2.save()\n\n Post(topic=topic_2, user=self.user, body='one').save()\n\n forum_2 = Forum(name='forum_2', description='bar', forum=self.parent_forum)\n forum_2.save()\n\n Topic(name='garbage', forum=forum_2, user=self.user).save()\n\n self.login_as(self.user)\n\n # everything starts unread\n self.assertEqual(ForumReadTracker.objects.count(), 0)\n self.assertEqual(TopicReadTracker.objects.count(), 0)\n\n # user reads topic_1, they should get one topic read tracker, there should be no forum read trackers\n self.client.get(topic_1.get_absolute_url())\n self.assertEqual(TopicReadTracker.objects.count(), 1)\n self.assertEqual(TopicReadTracker.objects.filter(user=self.user).count(), 1)\n self.assertEqual(TopicReadTracker.objects.filter(user=self.user, topic=topic_1).count(), 1)\n\n # user reads topic_2, they should get a forum read tracker,\n # there should be no topic read trackers for the user\n self.client.get(topic_2.get_absolute_url())\n self.assertEqual(TopicReadTracker.objects.count(), 0)\n self.assertEqual(ForumReadTracker.objects.count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=self.user).count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=self.user, forum=self.forum).count(), 1)\n\n def test_forum_mark_as_read(self):\n url = reverse('pybb:forum_mark_as_read')\n\n self.login_as(self.staff)\n\n response = self.client.get(url)\n\n self.assertRedirects(response, reverse('pybb:index'))\n\n self.assertEqual(ForumReadTracker.objects.filter(user=self.staff).count(), Forum.objects.count())\n\n def test_forum_mark_as_read_specific(self):\n sub_forum = Forum.objects.create(name='sub_forum', forum=self.forum)\n sub_sub_forum = Forum.objects.create(name='sub_sub_forum', forum=sub_forum)\n\n url = reverse('pybb:forum_mark_as_read')\n\n self.login_as(self.staff)\n\n response = self.client.post(url, data={\n 'forum_id': self.forum.pk\n })\n\n self.assertRedirects(response, self.forum.get_absolute_url())\n\n self.assertEqual(ForumReadTracker.objects.filter(user=self.staff, forum=self.forum).count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=self.staff, forum=sub_forum).count(), 1)\n self.assertEqual(ForumReadTracker.objects.filter(user=self.staff, forum=sub_sub_forum).count(), 1)\n\n def test_topic_tracker_redirect_view(self):\n self.login_as(self.staff)\n\n self.post\n\n response = self.client.get(reverse('pybb:topic_tracker_redirect', kwargs={\n 'topic_id': self.topic.pk\n }))\n\n self.assertRedirects(response, self.topic.get_absolute_url(), status_code=301)\n\n TopicReadTracker.objects.create(topic=self.topic,\n user=self.staff)\n\n response = self.client.get(reverse('pybb:topic_tracker_redirect', kwargs={\n 'topic_id': self.topic.pk\n }))\n\n self.client.get(self.topic.get_absolute_url())\n\n post = Post(topic=self.topic, user=self.user, body='test')\n post.save()\n\n response = self.client.get(reverse('pybb:topic_tracker_redirect', kwargs={\n 'topic_id': self.topic.pk\n }))\n\n self.assertRedirects(response, post.get_absolute_url(), status_code=301)\n","sub_path":"tests/views/test_trackers.py","file_name":"test_trackers.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"11622582","text":"# IMPORTING PACKAGES\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport requests\nimport math\nfrom termcolor import colored as cl\nimport numpy as np\n\nplt.style.use('fivethirtyeight')\nplt.rcParams['figure.figsize'] = (15, 8)\n\n# EXTRACTING DATA\n\ndef get_historic_data(symbol):\n ticker = symbol\n iex_api_key = 'Tsk_30a2677082d54c7b8697675d84baf94b'\n api_url = f'https://sandbox.iexapis.com/stable/stock/{ticker}/chart/max?token={iex_api_key}'\n df = requests.get(api_url).json()\n \n date = []\n open = []\n high = []\n low = []\n close = []\n \n for i in range(len(df)):\n date.append(df[i]['date'])\n open.append(df[i]['open'])\n high.append(df[i]['high'])\n low.append(df[i]['low'])\n close.append(df[i]['close'])\n \n date_df = pd.DataFrame(date).rename(columns = {0:'date'})\n open_df = pd.DataFrame(open).rename(columns = {0:'open'})\n high_df = pd.DataFrame(high).rename(columns = {0:'high'})\n low_df = pd.DataFrame(low).rename(columns = {0:'low'})\n close_df = pd.DataFrame(close).rename(columns = {0:'close'})\n \n frames = [date_df, open_df, high_df, low_df, close_df]\n df = pd.concat(frames, axis = 1, join = 'inner')\n return df\n\nmsft = get_historic_data('MSFT')\nmsft = msft.set_index('date')\nmsft = msft[msft.index >= '2020-01-01']\nmsft.index = pd.to_datetime(msft.index)\nmsft.to_csv('msft.csv')\n\n# IMPORTING DATA\n\nmsft = pd.read_csv('msft.csv').set_index('date')\nmsft.index = pd.to_datetime(msft.index)\n\n# DEFINING SMA FUNCTION\n\ndef sma(data, n):\n sma = data.rolling(window = n).mean()\n return pd.DataFrame(sma)\n\nn = [20, 50]\nfor i in n:\n msft[f'sma_{i}'] = sma(msft['close'], i)\n\n# CREATING TRADING STRATEGY\n\ndef implement_ma_strategy(data, short_window, long_window):\n ma1 = short_window\n ma2 = long_window\n buy_price = []\n sell_price = []\n ma_signal = []\n signal = 0\n \n for i in range(len(data)):\n if ma1[i] > ma2[i]:\n if signal != 1:\n buy_price.append(data[i])\n sell_price.append(np.nan)\n signal = 1\n ma_signal.append(signal)\n else:\n buy_price.append(np.nan)\n sell_price.append(np.nan)\n ma_signal.append(0)\n elif ma2[i] > ma1[i]:\n if signal != -1:\n buy_price.append(np.nan)\n sell_price.append(data[i])\n signal = -1\n ma_signal.append(-1)\n else:\n buy_price.append(np.nan)\n sell_price.append(np.nan)\n ma_signal.append(0)\n else:\n buy_price.append(np.nan)\n sell_price.append(np.nan)\n ma_signal.append(0)\n \n return buy_price, sell_price, ma_signal\n\nsma_20 = msft['sma_20']\nsma_50 = msft['sma_50']\n\nbuy_price, sell_price, signal = implement_ma_strategy(msft['close'], sma_20, sma_50)\n\n# PLOTTING SMA TRADE SIGNALS\n\nplt.plot(msft['close'], alpha = 0.3, label = 'MSFT')\nplt.plot(sma_20, alpha = 0.6, label = 'SMA 20')\nplt.plot(sma_50, alpha = 0.6, label = 'SMA 50')\nplt.scatter(msft.index, buy_price, marker = '^', s = 200, color = 'darkblue')\nplt.scatter(msft.index, sell_price, marker = 'v', s = 200, color = 'crimson')\nplt.legend(loc = 'upper left')\nplt.title('MSFT SMA CROSSOVER TRADING SIGNALS')\nplt.show()\n\n# OUR POSITION IN STOCK (HOLD/SOLD)\n\nposition = []\nfor i in range(len(signal)):\n if signal[i] > 1:\n position.append(0)\n else:\n position.append(1)\n \nfor i in range(len(msft['close'])):\n if signal[i] == 1:\n position[i] = 1\n elif signal[i] == -1:\n position[i] = 0\n else:\n position[i] = position[i-1]\n \nsma_20 = pd.DataFrame(sma_20).rename(columns = {0:'sma_20'})\nsma_50 = pd.DataFrame(sma_50).rename(columns = {0:'sma_50'})\nbuy_price = pd.DataFrame(buy_price).rename(columns = {0:'buy_price'}).set_index(msft.index)\nsell_price = pd.DataFrame(sell_price).rename(columns = {0:'sell_price'}).set_index(msft.index)\nsignal = pd.DataFrame(signal).rename(columns = {0:'sma_signal'}).set_index(msft.index)\nposition = pd.DataFrame(position).rename(columns = {0:'sma_position'}).set_index(msft.index)\n\nframes = [sma_20, sma_50, buy_price, sell_price, signal, position]\nstrategy = pd.concat(frames, join = 'inner', axis = 1)\nstrategy = strategy.reset_index().drop('date', axis = 1)\n\n# BACKTESTING THE STRAGEGY\n\nmsft_ret = pd.DataFrame(np.diff(msft['close'])).rename(columns = {0:'returns'})\nsma_strategy_ret = []\n\nfor i in range(len(msft_ret)):\n try:\n returns = msft_ret['returns'][i]*strategy['sma_position'][i]\n sma_strategy_ret.append(returns)\n except:\n pass\n \nsma_strategy_ret_df = pd.DataFrame(sma_strategy_ret).rename(columns = {0:'sma_returns'})\n\ninvestment_value = 100000\nnumber_of_stocks = math.floor(investment_value/msft['close'][1])\nsma_investment_ret = []\n\nfor i in range(len(sma_strategy_ret_df['sma_returns'])):\n returns = number_of_stocks*sma_strategy_ret_df['sma_returns'][i]\n sma_investment_ret.append(returns)\n\nsma_investment_ret_df = pd.DataFrame(sma_investment_ret).rename(columns = {0:'investment_returns'})\ntotal_investment_ret = round(sum(sma_investment_ret_df['investment_returns']), 2)\nprint(cl('Profit gained from the strategy by investing $100K in MSFT : ${} in 1 Year'.format(total_investment_ret), attrs = ['bold']))","sub_path":"Strategy_code.py","file_name":"Strategy_code.py","file_ext":"py","file_size_in_byte":5393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"160040947","text":"import numpy as np\nfrom typing import Dict\nimport panel as pn\n\nfrom .core_chart import BaseChart\n\ncss = '''\n.dataframe table{\n border: none;\n}\n\n.panel-df table{\n width: 100%; \n border-collapse: collapse;\n border: none;\n}\n.panel-df td{\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n'''\n\npn.extension(raw_css=[css])\n\n\nclass ViewDataFrame:\n chart_type: str = 'view_dataframe'\n _height: int = 0\n columns = None\n _width: int = 0\n chart = None\n source = None\n use_data_tiles = False\n\n\n def __init__(self, columns=None, width=400, height=400):\n self.columns = columns\n self._width = width\n self._height = height\n\n @property\n def name(self):\n return self.chart_type\n\n @property\n def width(self):\n return self._width\n\n @width.setter\n def width(self, value):\n self._width = value\n if self.chart is not None:\n self.update_dimensions(width=value)\n\n @property\n def height(self):\n return self._height\n\n @height.setter\n def height(self, value):\n self._height = value\n if self.chart is not None:\n self.update_dimensions(height=value)\n\n\n def initiate_chart(self, dashboard_cls):\n self.generate_chart(dashboard_cls._data)\n\n def generate_chart(self, data):\n if self.columns is None:\n self.columns = list(data.columns)\n self.chart = pn.Column(pn.pane.HTML(data[self.columns], style={'width':'100%', 'height':'100%', 'overflow-y':'hidden', 'font-size':'0.5vw','overflow-x':'auto'}), css_classes=['panel-df'])\n self.chart.sizing_mode = 'scale_both'\n\n def view(self):\n return self.chart\n\n def reload_chart(self, data, patch_update:bool):\n self.chart[0].object = data[self.columns]\n\n def update_dimensions(self, width=None, height=None):\n \"\"\"\n \n Parameters\n ----------\n\n \n\n Ouput\n -----\n \"\"\"\n if width is not None:\n self.chart.width = width\n if height is not None:\n self.chart.height = height\n\n def query_chart_by_range(self, active_chart:BaseChart, query_tuple, data):\n '''\n Description: \n\n -------------------------------------------\n Input:\n 1. active_chart: chart object of active_chart\n 2. query_tuple: (min_val, max_val) of the query [type: tuple]\n 3. datatile: None in case of Gpu Geo Scatter charts\n -------------------------------------------\n\n Ouput:\n '''\n min_val, max_val = query_tuple\n self.reload_chart(data.query(str(min_val)+\"<=\"+active_chart.x+\"<=\"+str(max_val)), False)\n\n def query_chart_by_indices(self, active_chart:BaseChart, old_indices, new_indices, data):\n '''\n Description: \n\n -------------------------------------------\n Input:\n 1. active_chart: chart object of active_chart\n 2. query_tuple: (min_val, max_val) of the query [type: tuple]\n 3. datatile: None in case of Gpu Geo Scatter charts\n -------------------------------------------\n\n Ouput:\n '''\n if '' in new_indices: new_indices.remove('') \n if len(new_indices) == 0:\n #case: all selected indices were reset\n #reset the chart\n self.reload_chart(data, False)\n elif len(new_indices) == 1:\n #just a single index\n self.reload_chart(data.query(active_chart.x+\"==\"+str(float(new_indices[0]))), False)\n else:\n new_indices_str = ','.join(map(str,new_indices))\n self.reload_chart(data.query(active_chart.x+\" in (\"+new_indices_str+\")\"), False)\n","sub_path":"python/cuXfilter/charts/core/core_view_dataframe.py","file_name":"core_view_dataframe.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"70918209","text":"import pandas as pd\nimport numpy as np\nimport os\n\nif os.environ['COMPUTERNAME'] == 'DESKTOP-9DDE2RH': # PonceLab-Desktop 3\n os.system(r\"subst S: E:\\Network_Data_Sync\") # alias the disk if it has not been mounted.\n tmp_input = r\"D:\\ExpRecord_tmp.xlsx\"\n tmp_output = r\"D:\\ExpRecord_out.xlsx\"\n df_paths = [r\"S:\\Exp_Record_Alfa.xlsx\", r\"S:\\ExpSpecTable_Augment.xlsx\"]\nelif os.environ['COMPUTERNAME'] == 'DESKTOP-MENSD6S': # Home_WorkStation\n tmp_input = \"E:\\\\Monkey_Data\\\\ExpRecord_tmp.xlsx\"\n tmp_output = \"E:\\\\Monkey_Data\\\\ExpRecord_out.xlsx\"\n df_paths = [\"E:\\\\Monkey_Data\\\\Exp_Record_Alfa.xlsx\", \"E:\\\\Monkey_Data\\\\ExpSpecTable_Augment.xlsx\"]\n\n\ndef process_concat_cells(df, out_excel, Animal):\n \"\"\"Process the raw form excel copied from onenote to well formed excel\n Filter the array using `Animal` label\"\"\n \"\"\"\n if isinstance(df,str):\n df = pd.read_excel(df)\n df = df.dropna(axis=0, how='all') # drop lines full with nan\n df = df.reset_index(drop=True) # (index=range(df.shape[0])) # make the index contiguous!\n row_num = df.shape[0]\n #%%\n msk = ~ df.ephysFN.isna() # 500 rows\n # df.ephysFN[msk].str.contains(\"Alfa\") # 436 rows containing Alfa\n if Animal is \"Alfa\":\n search_str = \"Alfa|ALfa\"\n elif Animal is \"Beto\":\n search_str = \"Beto\"\n elif Animal is \"Both\":\n search_str = \"Beto|Alfa|ALfa\"\n else:\n search_str = \"Beto|Alfa|ALfa\"\n ExpEphysNames = df.ephysFN[df.ephysFN.str.contains(search_str)==True]\n RowidEphs = ExpEphysNames.index\n ExpBhv2Names = df.expControlFN[df.expControlFN.str.contains(search_str)==True]\n RowidBhv = ExpEphysNames.index\n assert RowidEphs is RowidBhv\n #%%\n df.comments.fillna(value=\"\", inplace=True)\n df.comments = df.comments.astype(\"str\")\n df.stimuli.fillna(value=\"\", inplace=True)\n df.stimuli = df.stimuli.astype(\"str\")\n #%%\n for Expi, rowi in enumerate(RowidEphs):\n if Expi != len(RowidEphs) - 1:\n nextrow = RowidEphs[Expi + 1]\n else:\n nextrow = row_num\n print(\"\\nExp %d\\t %s\\t %s\"%( Expi, df.ephysFN[rowi], df.expControlFN[rowi]))\n print(df.comments[rowi:nextrow].str.cat(sep=\"\\n\"))\n # \n stimuli_miss_cnt = 0 # Count how many stimuli entries are missed\n df_sort = df[df.ephysFN.str.contains(search_str)==True]\n df_sort = df_sort.reset_index(drop=True)\n for Expi, rowi in enumerate(RowidEphs):\n if Expi != len(RowidEphs) - 1:\n nextrow = RowidEphs[Expi + 1]\n else:\n nextrow = row_num\n df_sort.comments[Expi] = df.comments[rowi:nextrow].str.cat(sep=\"\\n\")\n df_sort.ephysFN[Expi] = df.ephysFN[rowi].strip() # use strip to get rid of leading and ending space ' '\n df_sort.expControlFN[Expi] = df.expControlFN[rowi].strip()\n if \"Stimuli\" in df.stimuli[rowi]:\n if \"Stimuli\" in df.stimuli[rowi][:8]:\n df_sort.stimuli[Expi] = \"N:\\\\\" + df.stimuli[rowi].strip()\n else:\n df_sort.stimuli[Expi] = df.stimuli[rowi].strip()\n else:\n df_sort.stimuli[Expi] = \"\"\n stimuli_miss_cnt += 1\n # print out info for further examination\n print(\"\\nExp %d\\t %s\\t %s\" % (Expi, df.ephysFN[rowi], df.expControlFN[rowi]))\n print(df.stimuli[rowi:nextrow].str.cat(sep=\"\"))\n if (\"Abort\" in df_sort.comments[Expi]) or (\"abort\" in df_sort.comments[Expi]):\n print(\"Do aborted! No worry.\")\n print(stimuli_miss_cnt, \"stimuli missing\")\n #%%\n df_sort.to_excel(out_excel,index=False, engine='xlsxwriter')\n # Use the 'xlsxwriter' engine will avoid some Illegal Character Error in openpyxl\n # https://cooperluan.github.io/python/2015/01/08/pandas-daochu-excel-zhong-de-luan-ma-wen-ti/\n return df_sort\n\ndef available_Explabel():\n Animal_strs = [\"Alfa\", \"Beto\"]\n for animal, out_path in zip(Animal_strs, df_paths):\n df_old = pd.read_excel(out_path)\n print(\"Existing labels for %s:\"%animal)\n print(list(df_old.Exp_collection.unique()))\n\ndef concat_table(df_old, df_new, addexplabel=None, out_path=None):\n \"\"\"Obsolete, use the function below instead\"\"\"\n if isinstance(df_old,str):\n out_path = df_old\n df_old = pd.read_excel(df_old)\n if isinstance(df_new,str):\n df_new = pd.read_excel(df_new)\n # Check if the experiments in the new datatable has been recorded\n break_flag = False\n for name in df_new.expControlFN:\n if (df_old.expControlFN==name).any():\n print(\"%s has been recorded in the excel index %d, please check\"%(name, (df_old.expControlFN==name).nonzero()[0][0]))\n break_flag = True\n if break_flag:\n raise ValueError\n if addexplabel is not None:\n df_new.Exp_collection[:] = addexplabel\n df_cat = pd.concat([df_old,df_new], axis=0, ignore_index=True)\n df_cat.to_excel(out_path,index=False)\n return df_cat\n\ndef sort_merge_table(df_sort, addexplabel=None):\n \"\"\"Current version to combine new table and old one.\"\"\"\n Animal_strs = [\"Alfa\", \"Beto\"]\n if isinstance(df_sort,str):\n df_sort = pd.read_excel(df_sort)\n # loop through animal name and sort corresponding exp to the collection\n for animal, out_path in zip(Animal_strs, df_paths):\n print(\"Sort out exp for %s, adding \"%animal)\n df_old = pd.read_excel(out_path) # load the old exp collection\n id_col = []\n for idx in df_sort.index:\n name = df_sort.expControlFN[idx]\n if name is np.nan:\n print(\"%s Empty bhv file entry encountered\" % df_sort.ephysFN[idx])\n continue\n if animal in name:\n if (df_old.expControlFN==name).any():\n print(\"%s has been recorded in the excel index %d, please check. Skipping.\"%(name, (df_old.expControlFN==name).nonzero()[0][0]))\n else:\n id_col.append(idx)\n if len(id_col) == 0:\n print(\"\\nNo new experiments to add! Continue.\")\n continue\n df_ftr = df_sort.iloc[id_col].copy()\n print(df_ftr.expControlFN)\n if addexplabel is not None:\n df_ftr.Exp_collection[:] = addexplabel\n df_cat = pd.concat([df_old, df_ftr], axis=0, ignore_index=True)\n df_cat.to_excel(out_path,index=False, engine='xlsxwriter') # write to the excel of all old experiments \n return\n\nif __name__ == '__main__':\n os.startfile(tmp_input)\n Animal = input(\"Which animal to parse from %s?\" % (tmp_input) )\n if not Animal == \"out\":\n if len(Animal) == 0:\n Animal = \"Both\"#\"Beto\" # \"Alfa\" \"ALfa\"\n df_sort = process_concat_cells(tmp_input, tmp_output, Animal=Animal)\n else: # try to open the tempory output directly and parse from it.\n pass\n available_Explabel() # Print the available Exp labels for the monkeys\n try:\n os.startfile(tmp_output)\n except:\n print(\"Open %s failed\"%tmp_output)\n pass\n Label = input(\"Add Exp labels to the new Exps?\")\n if len(Label) == 0:\n Label = None # \"ReducDimen_Evol\"\n sort_merge_table(tmp_output, addexplabel=Label) # df_sort","sub_path":"Exp_Record_ManageLib.py","file_name":"Exp_Record_ManageLib.py","file_ext":"py","file_size_in_byte":7177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"617708230","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 9 13:05:13 2019\r\n\r\nNathan Marshall\r\nCreates a GUI for adjusting COLTRIMS parameters. Supports saving adjusted\r\nparameters to a text file named param_adjust_savestate.txt and reading previous\r\nparameters from this file if it already exists. \r\n\"\"\"\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib.backends.backend_tkagg import (\r\n FigureCanvasTkAgg, NavigationToolbar2Tk)\r\nfrom matplotlib.figure import Figure\r\nimport tkinter as tk\r\nfrom ColtrimsAnalysis import hist1d\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\n\r\n\r\nclass ParameterGUI:\r\n '''Creates GUI for adjusting COLTRIMS parameters'''\r\n \r\n def __init__(self, root, xyt_list, masses, charges, param_list):\r\n da_to_au = 1822.8885\r\n l, z0, vz0, x_jet, vx_jet, y_jet, vy_jet, C, t0 = param_list\r\n self.param_list = param_list\r\n self.m1, self.m2, self.m3 = [da_to_au*i for i in masses]\r\n self.xyt_list = xyt_list\r\n root.title('Parameter Adjustment Tool')\r\n root.bind('', self.refresh)\r\n plt.style.use('default')\r\n self.fig = Figure(figsize=(10,5), dpi=100)\r\n self.ax1 = plt.subplot2grid((1,3),(0,0), fig=self.fig)\r\n self.ax2 = plt.subplot2grid((1,3),(0,1), fig=self.fig)\r\n self.ax3 = plt.subplot2grid((1,3),(0,2), fig=self.fig)\r\n self.ax1.grid(True)\r\n self.ax2.grid(True)\r\n self.ax3.grid(True)\r\n self.t0_entry = tk.Entry(root, width=15)\r\n self.t0_entry.grid(row=0, column=0)\r\n self.t0_entry.insert(tk.END, t0)\r\n self.l_entry = tk.Entry(root, width=15)\r\n self.l_entry.grid(row=0, column=1)\r\n self.l_entry.insert(tk.END, l)\r\n self.z0_entry = tk.Entry(root, width=15)\r\n self.z0_entry.grid(row=0, column=2)\r\n self.z0_entry.insert(tk.END, z0)\r\n self.vz0_entry = tk.Entry(root, width=15)\r\n self.vz0_entry.grid(row=0, column=3)\r\n self.vz0_entry.insert(tk.END, vz0)\r\n self.x_entry = tk.Entry(root, width=15)\r\n self.x_entry.grid(row=0, column=4)\r\n self.x_entry.insert(tk.END, x_jet)\r\n self.vx_entry = tk.Entry(root, width=15)\r\n self.vx_entry.grid(row=0, column=5)\r\n self.vx_entry.insert(tk.END, vx_jet)\r\n self.y_entry = tk.Entry(root, width=15)\r\n self.y_entry.grid(row=0, column=6)\r\n self.y_entry.insert(tk.END, y_jet)\r\n self.vy_entry = tk.Entry(root, width=15)\r\n self.vy_entry.grid(row=0, column=7)\r\n self.vy_entry.insert(tk.END, vy_jet)\r\n self.c_entry = tk.Entry(root, width=15)\r\n self.c_entry.grid(row=0, column=8)\r\n self.c_entry.insert(tk.END, C)\r\n \r\n self.t0_label = tk.Label(root, text='Change t0')\r\n self.t0_label.grid(row=1, column=0)\r\n self.l_label = tk.Label(root, text='Change L')\r\n self.l_label.grid(row=1, column=1)\r\n self.z0_label = tk.Label(root, text='Change z0')\r\n self.z0_label.grid(row=1, column=2)\r\n self.vz0_label = tk.Label(root, text='Change Vz0')\r\n self.vz0_label.grid(row=1, column=3)\r\n self.x_label = tk.Label(root, text='Change Jet X')\r\n self.x_label.grid(row=1, column=4)\r\n self.vx_label = tk.Label(root, text='Change Jet Vx')\r\n self.vx_label.grid(row=1, column=5)\r\n self.y_label = tk.Label(root, text='Change Jet Y')\r\n self.y_label.grid(row=1, column=6)\r\n self.vy_label = tk.Label(root, text='Change Jet Vy')\r\n self.vy_label.grid(row=1, column=7)\r\n self.c_label = tk.Label(root, text='Change C')\r\n self.c_label.grid(row=1, column=8)\r\n \r\n self.save_params = tk.Button(root, command=self.write_tofile, \r\n text='Save Parameters as .txt')\r\n self.save_params.grid(row=4, column=7)\r\n self.read_params = tk.Button(root, command=self.read_fromfile, \r\n text='Load Existing Parameters')\r\n self.read_params.grid(row=4, column=1)\r\n self.tog_state = tk.IntVar()\r\n self.tog_gauss = tk.Checkbutton(root, text='Toggle Gaussian Fit', \r\n variable=self.tog_state)\r\n self.tog_gauss.grid(row=4, column=8)\r\n \r\n self.canvas = FigureCanvasTkAgg(self.fig, master=root)#A tk.DrawingArea\r\n self.canvas.draw()\r\n self.canvas.get_tk_widget().grid(row=2, columnspan=9)\r\n self.toolbar_frame = tk.Frame(root)\r\n self.toolbar_frame.grid(sticky='W', row=4, column=3, columnspan=5)\r\n self.toolbar = NavigationToolbar2Tk(self.canvas, self.toolbar_frame)\r\n self.toolbar.update()\r\n self.plot()\r\n \r\n def acc(self, q, l, z0, m, C): #returns the acceleration of the ion\r\n return (2 * q * (l - z0)) / (m * C**2)\r\n \r\n def refresh(self, event): #if enter key is hit, refresh the plot\r\n self.plot()\r\n \r\n def gaussfit(self, x, y, p0, ax):\r\n '''Performs a simple Gaussian fit and plots it to an axes object.'''\r\n def gauss(x, *p):\r\n A, mu, sigma = p\r\n return A*np.exp(-(x-mu)**2/(2.*sigma**2))\r\n \r\n coeff, var_matrix = curve_fit(gauss, x, y, p0=p0)\r\n xmin, xmax = np.amin(x), np.amax(x)\r\n hist_x = np.linspace(xmin, xmax, 1000)\r\n hist_fit = gauss(hist_x, *coeff)\r\n ax.plot(hist_x, hist_fit)\r\n # Print the mean and standard deviation:\r\n s1 = 'Fitted Mean = '+str('%.2f'%coeff[1])\r\n s2 = 'Fitted SD = '+str('%.2f'%coeff[2])\r\n ax.text(0.01, 0.95, s=s1, fontsize=7, transform=ax.transAxes)\r\n ax.text(0.01, 0.92, s=s2, fontsize=7, transform=ax.transAxes)\r\n \r\n def plot(self):\r\n tof1,x1,y1,tof2,x2,y2,tof3,x3,y3,delay,adc1,adc2,index = self.xyt_list\r\n l = float(self.l_entry.get())\r\n z0 = float(self.z0_entry.get())\r\n vz0 = float(self.vz0_entry.get())\r\n x_jet = float(self.x_entry.get())\r\n vx_jet =float(self.vx_entry.get())\r\n y_jet = float(self.y_entry.get())\r\n vy_jet = float(self.vy_entry.get())\r\n C = float(self.c_entry.get())\r\n t0 = float(self.t0_entry.get())\r\n conv = 0.457102 #conversion factor from mm/ns to atomic units\r\n self.param_list = [l, z0, vz0, x_jet, vx_jet, y_jet, vy_jet, C, t0]\r\n acc1 = self.acc(1, l, z0, self.m1, C) #acceleration of 1st ion\r\n acc2 = self.acc(1, l, z0, self.m2, C) #acceleration of 2nd ion\r\n acc3 = self.acc(1, l, z0, self.m3, C) #acceleration of 3rd ion\r\n vx1_cm = ((x1 - (x_jet))/(tof1 - t0)) - (vx_jet) \r\n vy1_cm = ((y1 - (y_jet))/(tof1 - t0)) - (vy_jet) \r\n vx2_cm = ((x2 - (x_jet))/(tof2 - t0)) - (vx_jet)\r\n vy2_cm = ((y2 - (y_jet))/(tof2 - t0)) - (vy_jet)\r\n vx3_cm = ((x3 - (x_jet))/(tof3 - t0)) - (vx_jet)\r\n vy3_cm = ((y3 - (y_jet))/(tof3 - t0)) - (vy_jet)\r\n vz1_cm = (l-z0)/(tof1-t0) - (1/2)*acc1*(tof1-t0) + vz0\r\n vz2_cm = (l-z0)/(tof2-t0) - (1/2)*acc2*(tof2-t0) + vz0\r\n vz3_cm = (l-z0)/(tof3-t0) - (1/2)*acc3*(tof3-t0) + vz0\r\n px1 = self.m1 * vx1_cm * conv\r\n px2 = self.m2 * vx2_cm * conv\r\n px3 = self.m3 * vx3_cm * conv\r\n py1 = self.m1 * vy1_cm * conv\r\n py2 = self.m2 * vy2_cm * conv\r\n py3 = self.m3 * vy3_cm * conv\r\n pz1 = self.m1 * vz1_cm * conv\r\n pz2 = self.m2 * vz2_cm * conv\r\n pz3 = self.m3 * vz3_cm * conv\r\n \r\n ptotx = px1 + px2 + px3\r\n ptoty = py1 + py2 + py3\r\n ptotz = pz1 + pz2 + pz3\r\n \r\n \r\n self.ax1.clear()\r\n self.ax2.clear()\r\n self.ax3.clear()\r\n h1, edge1 = hist1d(ptotx, self.ax1, 'X Momentum Sum',\r\n 'X Momentum (a.u.)','Counts', output=True)\r\n h2, edge2 = hist1d(ptoty, self.ax2, 'Y Momentum Sum',\r\n 'Y Momentum (a.u.)','', output=True)\r\n h3, edge3 = hist1d(ptotz, self.ax3, 'Z Momentum Sum',\r\n 'Z Momentum (a.u.)', output=True)\r\n if self.tog_state.get() == 1:\r\n self.gaussfit(edge1, h1, [1,0,1], self.ax1)\r\n self.gaussfit(edge2, h2, [1,0,1], self.ax2)\r\n self.gaussfit(edge3, h3, [1,0,1], self.ax3)\r\n \r\n self.canvas.draw()\r\n \r\n def write_tofile(self):\r\n with open('param_adjust_savestate.txt', mode='w') as file:\r\n for param in self.param_list:\r\n file.write(str(param))\r\n file.write('\\n')\r\n \r\n def read_fromfile(self):\r\n try:\r\n with open('param_adjust_savestate.txt', mode='r') as file:\r\n self.param_list = []\r\n for line in file:\r\n self.param_list.append(float(line))\r\n l, z0, vz0, x_jet, vx_jet, y_jet, vy_jet, C, t0 = self.param_list\r\n self.t0_entry.delete(0, tk.END)\r\n self.l_entry.delete(0, tk.END)\r\n self.z0_entry.delete(0, tk.END)\r\n self.vz0_entry.delete(0, tk.END)\r\n self.x_entry.delete(0, tk.END)\r\n self.vx_entry.delete(0, tk.END)\r\n self.y_entry.delete(0, tk.END)\r\n self.vy_entry.delete(0, tk.END)\r\n self.c_entry.delete(0, tk.END)\r\n self.t0_entry.insert(tk.END, t0)\r\n self.l_entry.insert(tk.END, l)\r\n self.z0_entry.insert(tk.END, z0)\r\n self.vz0_entry.insert(tk.END, vz0)\r\n self.x_entry.insert(tk.END, x_jet)\r\n self.vx_entry.insert(tk.END, vx_jet)\r\n self.y_entry.insert(tk.END, y_jet)\r\n self.vy_entry.insert(tk.END, vy_jet)\r\n self.c_entry.insert(tk.END, C)\r\n except FileNotFoundError:\r\n print('FileNotFoundError: No param_adjust_savestate.txt file '\r\n 'found. Check that such a file exists and is in the correct '\r\n 'directory.') \r\n \r\n","sub_path":"ParamAdjustTool3Body.py","file_name":"ParamAdjustTool3Body.py","file_ext":"py","file_size_in_byte":9856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"622088846","text":"\n#\t-*- coding:utf-8 -*-\nimport xlrd\nimport csv\nimport re\nimport pickle\nimport sys\nimport random\nTEST_DATASET_SIZE = 500\n\n\nclass record():\n\tdef __init__(self, raw_text, graph, articleId, sentenceId, annotation):\n\t\tself.raw_text = raw_text\n\t\tself.graph = graph\n\t\tself.articleId = articleId\n\t\tself.sentenceId = sentenceId\n\t\tself.annotation = annotation\n\n\tdef __repr__(self):\n\t\treturn \"{}\\t{}\\t{}\\t{}\\t{}\".format(self.raw_text, self.articleId, self.sentenceId, self.graph, self.annotation)\n\n\ndef combine(subgraph, annotationPath):\n\t'''\n\tThis function is used for training data specifically\n\t'''\n\tannotation = xlrd.open_workbook(annotationFilePath).sheets()[0]\n\tmaxrows = annotation.nrows\n\n\tfor s in subgraph:\n\t\tline = s.split('\\n')\n\t\tindex = re.search(\"id\\s(\\S+)\\.(\\d+)\",line[0])\t#/d can only match one digit\n\t\taid = index.group(1)\n\t\tsid = index.group(2)\n\t\traw_text = \"\"\n\t\tfor i in range(len(line)):\n\t\t\tif line[i].startswith('#'):\n\t\t\t\tif line[i].startswith('# ::snt'):\n\t\t\t\t\traw_text = line[i][7:]\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\t\tsg = '\\n'.join(line[i:])\n\t\tif not sg:\n\t\t\tcontinue\n\t\tsg = sg.split('\\n\\n')[:-1]\n\n\n\t\tfor e in sg:\n\t\t\tr = re.search(\"\\((\\d+)\\)\",e)\n\t\t\tif not r:\n\t\t\t\tprint('sb')\n\t\t\tind = int(r.group(1)) \t# a integer\n\t\t\tgraph = e[r.end(1)+1:]\n\t\t\ttry:\n\t\t\t\twhile lino < maxrows and annotation.row(lino)[1].value != aid+'.'+sid:\n\t\t\t\t\t#print(annotation.row(lino)[1].value)\n\t\t\t\t\tlino += 1\n\n\t\t\t\ti = 1\n\t\t\t\twhile lino + i < maxrows and ind != annotation.row(lino+i)[2].value:\n\t\t\t\t\t#print(annotation.row(lino+i)[2].value)\n\t\t\t\t\ti += 1\n\t\t\t\tif annotation.row(lino+i)[3].value == 'y' or annotation.row(lino+i)[3].value == 'yes':\n\t\t\t\t\ty = 1.0\n\t\t\t\telse:\n\t\t\t\t\ty = 0.0\n\t\t\texcept IndexError:\n\t\t\t\tprint(aid+'.'+sid)\n\t\t\tsubGraphs.append(record(raw_text,graph,aid,sid,y))\n\treturn subGraphs\n\ndef ProduceRecords(subgraph):\n\trecords = []\n\tfor s in subgraph:\n\t\tline = s.split('\\n')\n\t\traw_text = \"\"\n\t\tfor i in range(len(line)):\n\t\t\tif line[i].startswith('#'):\n\t\t\t\tif line[i].startswith('# ::snt'):\n\t\t\t\t\traw_text = line[i][7:]\n\t\t\t\t\tcontinue\n\t\t\t\telif line[i].startswith('# ::id'):\n\t\t\t\t\tarticleId = line[i][6:].strip()\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\t\tsg = '\\n'.join(line[i:])\n\t\tif not sg:\n\t\t\tcontinue\n\t\tsg = sg.split('\\n\\n')[:-1]\n\t\tfor e in sg:\n\t\t\tr = re.search(\"\\((\\d+)\\)\", e)\n\t\t\tif not r:\n\t\t\t\traise Exception('no subgraph id!')\n\t\t\tsubid = str(int(r.group(1))) # a integer\n\t\t\tgraph = e[r.end(1) + 1:]\n\t\t\trecords.append(record(raw_text,graph,articleId,subid,None))\n\treturn records\n\n\ndef main(mode, filename):\n\tlino = 0\n\tsubGraphs = []\n\tconverter = data2tuple()\n\tif mode == '-train':\n\t\tannotationFilePath = \"../feature_extract/annotation.xlsx\"\n\t\tsubGraphPath = '../subgraph/PART-amr-release-1.0-training-proxy-subgraph.txt'\n\t\tconverter.combine(subgraph, annotationFilePath)\n\n\t\tprint(\"Processing %d tuples in total\" % len(subGraphs))\n\t\twith open('./tuple.pkl','wb') as p:\t\t#the output file need to be open as wb if list\n\t\t\tpickle.dump(subGraphs,p)\n\n\telif mode == '-predict':\n\t\tsubgraphFilePath = './subgraph/'+filename.split('/')[-1]+'.sbg'\n\t\tsubgraph = open(subgraphFilePath, 'r').read().split('-' * 50 + '\\n')[1:]\n\t\tsubGraphs = converter.ProduceTuple(subgraph)\n\n\t\tprint(\"Processing %d tuples in total\" % len(subGraphs))\n\t\twith open('./feature_extract/'+filename.split('/')[-1]+'.tp.pkl','wb') as p:\n\t\t\tpickle.dump(subGraphs, p)\n\telse:\n\t\traise Exception('Invalid Parameter')\n\nif __name__ == '__main__':\n\tmode = sys.argv[1]\n\tfilename = sys.argv[2]\n\tmain(mode, filename)\n\n\n","sub_path":"RECONSTRUCT/Record.py","file_name":"Record.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"593445932","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.utils.data\nfrom torchvision import datasets, models, transforms\n\nimport sys; sys.path.append('./functions')\n\nclass Classifier(nn.Module):\n def __init__(self):\n super(Classifier, self).__init__()\n self.fc1 = nn.Linear(4096, 1024)\n self.dropout1 = nn.Dropout()\n self.fc2 = nn.Linear(1024, 256)\n self.dropout2 = nn.Dropout()\n self.fc3 = nn.Linear(256, 64)\n self.fc4 = nn.Linear(64, 7)\n def forward(self, x):\n x = F.relu(self.dropout1(self.fc1(x)))\n x = F.relu(self.dropout2(self.fc2(x)))\n x = F.relu(self.fc3(x))\n x = self.fc4(x)\n return x\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nvgg = models.vgg13(pretrained=True)\nvgg.classifier = vgg.classifier[0]\nvgg = vgg.to(device)\nfor param in vgg.parameters():\n param.requires_grad = False\n\n# hyperparameters\nnum_epochs = 10\nbatch_size = 100\nlearning_rate = 0.001\n\n\nmodel = Classifier().to(device)\n# loss function\ncriterion = nn.CrossEntropyLoss()\n# optimizer\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n\ndata_transform = transforms.Compose([\n transforms.Scale(224),\n transforms.ToTensor(),\n ])\n\ntrain_dataset = datasets.ImageFolder(root='./functions/data/classifier/train', transform=data_transform)\ntrain_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=batch_size, shuffle=True,\n num_workers=0)\ntest_dataset = datasets.ImageFolder(root='./functions/data/classifier/test', transform=data_transform)\ntest_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=batch_size, shuffle=True,\n num_workers=0)\n\ndef train(train_loader):\n model.train()\n running_loss = 0\n for batch_idx, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n\n optimizer.zero_grad()\n features = vgg(images)\n outputs = model(features)\n\n loss = criterion(outputs, labels)\n running_loss += loss.item()\n\n loss.backward()\n optimizer.step()\n\n train_loss = running_loss / len(train_loader)\n\n return train_loss\n\ndef valid(test_loader):\n model.eval()\n running_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (images, labels) in enumerate(test_loader):\n images = images.to(device)\n labels = labels.to(device)\n\n features = vgg(images)\n outputs = model(features)\n\n loss = criterion(outputs, labels)\n running_loss += loss.item()\n\n predicted = outputs.max(1, keepdim=True)[1]\n correct += predicted.eq(labels.view_as(predicted)).sum().item()\n total += labels.size(0)\n\n val_loss = running_loss / len(test_loader)\n val_acc = correct / total\n\n return val_loss, val_acc\n\nloss_list = []\nval_loss_list = []\nval_acc_list = []\nfor epoch in range(num_epochs):\n loss = train(train_loader)\n val_loss, val_acc = valid(test_loader)\n\n print('epoch %d, loss: %.4f val_loss: %.4f val_acc: %.4f' % (epoch, loss, val_loss, val_acc))\n\n # logging\n loss_list.append(loss)\n val_loss_list.append(val_loss)\n val_acc_list.append(val_acc)\n\n# save the trained model\nnp.save('loss_list.npy', np.array(loss_list))\nnp.save('val_loss_list.npy', np.array(val_loss_list))\nnp.save('val_acc_list.npy', np.array(val_acc_list))\ntorch.save(model.state_dict(), './functions/data/classifier.pth')\n","sub_path":"cpu/application/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"492146618","text":"import logging\nimport logging.config\nimport os\nimport sys\nfrom datetime import datetime\nimport copy\nimport yaml\n\nfrom util import as_list, correct_path\nfrom error.error import ExceptionUtils\n\ndate_format = None\n\n\ndef timestamp(date=None):\n return (date or datetime.now()).strftime(date_format)\n\n\ndef init_logger(logging_config, logs_root):\n with open(logging_config) as cfg:\n config = yaml.safe_load(cfg)\n\n log_dirs = {}\n for k, h in config['handlers'].items():\n filename = h.get('filename')\n if filename:\n filename = correct_path(filename)\n if not filename == os.path.abspath(filename):\n filename = os.path.join(logs_root, filename)\n h['filename'] = filename\n log_dir = os.path.dirname(filename)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n log_dirs[k] = log_dir\n\n # ASR may load config previously, so preserve that configuration\n previouos = logging.root.handlers[0]\n logging.config.dictConfig(config)\n logging.root.handlers[0] = previouos\n return log_dirs\n\n\ndef get_logger(name='main'):\n current = logging.getLoggerClass()\n logging.setLoggerClass(ApiLogger)\n custom = logging.getLogger(name)\n logging.setLoggerClass(current)\n return custom\n\n\nclass ApiLogger(logging.Logger):\n\n def __init__(self, name):\n logging.Logger.__init__(self, name)\n self.logger = super(ApiLogger, self)\n\n def exc_detail(self, e, extra_msg=''):\n formatted = ExceptionUtils.format(e, extra_msg)\n self.log_list(formatted, logging.ERROR)\n\n def log_list(self, list, level=logging.INFO):\n list = as_list(list)\n for l in list:\n super().log(level, l)\n\n def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):\n super()._log(level, msg, args, exc_info=None, extra=None, stack_info=False)\n sys.stdout.flush()\n for h in logging.getLogger().handlers:\n h.flush()\n","sub_path":"app/config/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"43104194","text":"from psychopy import core,visual,event\nimport numpy as np,glob as gb,socket\n\ncode='utf-8'; nTrials=6\ninstruct='Press 1, 2, ..., 6 to pick a picture:\\n\\n'\nf=[gb.glob('T*.jpg'),gb.glob('D*.jpg')] # picture files\nf=np.append(np.random.choice(f[0],3,False),np.random.choice(f[1],3,False))\ncorAns=np.array(['y']*3+['n']*3)\nw=visual.Window(size=[800,500],color=[-1,-1,-1],units='norm')\nvisual.TextStim(w,text='Waiting for a client').draw()\nw.flip() # show init screen\n\nimgs=[] # list of 6 images \nfor i in range(len(f)):\n (x,y)=(-.75+i*.3,-.2)\n imgs.append(visual.ImageStim(w,f[i],size=.3,pos=(x,y)))\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\ns.bind(('localhost', 1234))\ns.listen(1) # allow 1 client\n(c,adr)=s.accept()\n\nfor t in range(nTrials):\n visual.BufferImageStim(w,stim=imgs).draw()\n visual.TextStim(w,text=instruct).draw()\n w.flip() # show choices\n print('Server got:')\n key=event.waitKeys(keyList=['1','2','3','4','5','6']) # allow 1-6\n print(key)\n w.flip() # clear screen\n idx=int(key[0])-1 # choice as the array index\n with open(f[idx],'rb') as file:\n data=file.read() # read in pic file\n c.sendall((corAns[idx]+str(len(data))).encode(code)) # inform ans + pic size\n c.sendall(data) # send pic file to the client\n visual.TextStim(w,text='Waiting for the client').draw()\n w.flip() # show waiting\n print(c.recv(1).decode(code)) # waiting for a response from the client\n\ns.close()\n","sub_path":"week2/02_Codes/network/server_pic.py","file_name":"server_pic.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"580875901","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 ('GingerBites', '0002_auto_20150718_2108'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='Page',\n new_name='Vendor',\n ),\n migrations.AddField(\n model_name='events',\n name='vendor',\n field=models.ManyToManyField(to='GingerBites.Vendor'),\n preserve_default=True,\n ),\n ]\n","sub_path":"GingerBites/migrations/0003_auto_20150718_2319.py","file_name":"0003_auto_20150718_2319.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"223268328","text":"import logging\nimport time\nimport typing as T\nfrom contextlib import contextmanager\nfrom pathlib import Path\n\nfrom PyQt5 import QtCore, QtGui, QtSvg, QtWidgets\n\nfrom panel.colors import Colors\n\nROOT_DIR = Path(__file__).parent.parent\n\n\nclass Widget:\n def __init__(\n self, app: QtWidgets.QApplication, main_window: QtWidgets.QWidget\n ) -> None:\n self.app = app\n self.main_window = main_window\n\n @contextmanager\n def exception_guard(self, sleep_time: int = 0) -> T.Generator:\n try:\n yield\n except Exception as ex:\n logging.exception(ex)\n time.sleep(sleep_time)\n\n @property\n def container(self) -> QtWidgets.QWidget:\n raise NotImplementedError(\"Not implemented\")\n\n @property\n def available(self) -> bool:\n return True\n\n def refresh(self) -> None:\n with self.exception_guard(sleep_time=1):\n if not self.available:\n return\n self._refresh_impl()\n\n def render(self) -> None:\n with self.exception_guard():\n if not self.available:\n return\n self._render_impl()\n\n def _refresh_impl(self) -> None:\n raise NotImplementedError(\"Not implemented\")\n\n def _render_impl(self) -> None:\n raise NotImplementedError(\"Not implemented\")\n\n def _set_icon(self, widget: QtWidgets.QWidget, icon_name: str) -> None:\n if widget.property(\"icon_name\") == icon_name:\n return\n widget.setProperty(\"icon_name\", icon_name)\n\n icon_path = ROOT_DIR / \"data\" / \"icons\" / (icon_name + \".svg\")\n target_size = QtCore.QSize(18, 18)\n icon_content = icon_path.read_bytes()\n icon_content = icon_content.replace(\n b\"=0 :\n if Matrix[r][c] == target:\n return True\n elif Matrix[r][c] > target:\n c -= 1\n else:\n r += 1\n return False\n\nprint(SearchMatrix([\n [1, 4, 7, 11, 15],\n [2, 5, 8, 12, 19],\n [3, 6, 9, 16, 22],\n [10, 13, 14, 17, 24],\n [18, 21, 23, 26, 30]\n], 5))\n","sub_path":"Problem-3.py","file_name":"Problem-3.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"413433170","text":"from django.urls import path\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import views as auth_views\n\nfrom .views import(\n LogOutView,\n SignUpView,\n UserList,\n UserDelete,\n UserUpdate,\n UserCreate,\n CreateGroupView,\n ListGroupView,\n DeleteGroupView,\n UpdateGroupView,\n CreatePermissionView,\n ListPermissionView,\n DeletePermissionView,\n UpdatePermissionView\n)\n\nurlpatterns = [\n path('', auth_views.LoginView.as_view(template_name='account/prueba.html'), name='log_in'),\n path('log-out/', login_required(LogOutView.as_view()), name='log_out'),\n path('sign-up/', SignUpView.as_view(), name='sign_up'),\n path('user/list/', login_required(UserList.as_view()), name='list_user'), \n path('user/delete//', login_required(UserDelete.as_view()), name= 'delete_user'),\n path('user/update//',login_required(UserUpdate.as_view()), name= 'update_user'),\n path('user/create/', login_required(UserCreate.as_view()), name='create_user'),\n path('group/create', login_required(CreateGroupView.as_view()),name='create_group' ),\n path('group/list/', login_required(ListGroupView.as_view()), name='list_group'), \n path('group/delete//', login_required(DeleteGroupView.as_view()), name= 'delete_group'),\n path('group/update//',login_required(UpdateGroupView.as_view()), name= 'update_group'),\n path('permission/create', login_required(CreatePermissionView.as_view()),name='create_permission'),\n path('permission/list/', login_required(ListPermissionView.as_view()), name='list_permission'), \n path('permission/delete//', login_required(DeletePermissionView.as_view()), name= 'delete_permission'),\n path('permission/update//',login_required(UpdatePermissionView.as_view()), name= 'update_permission')\n ]","sub_path":"apps/usuarios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"214944187","text":"from flask import Blueprint, request, render_template\nfrom flask_mail import Message\nimport os\nimport traceback\nfrom . import models\n\n\nblueprint_name = os.path.dirname(os.path.realpath(__file__)).split(\"/\")[-1]\nblueprint = Blueprint(blueprint_name, __name__, template_folder='templates', static_folder='static')\n\n@blueprint.errorhandler(500)\ndef five_hundred(e):\n models.mail.send(\n Message(\n \"500 - URL: {0} Error: {1}\".format(request.url, e),\n sender=\"Wildflower Schools \",\n recipients=['support@wildflowerschools.org'],\n body=traceback.format_exc()\n )\n )\n return 500\n","sub_path":"generators/blueprint/template/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"280617138","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import spline\r\ndef execute(base,graphfile,type):\r\n accuracy = open(base+\"/result/accuracy.txt\", \"r\")\r\n if graphfile==\"biogrid_yeast_physical_unweighted\" and type== \"_cyc/\":\r\n il=23 #interval间隔\r\n end=230\r\n if graphfile==\"biogrid_yeast_physical_unweighted\" and type==\"_mips/\":\r\n il=40 #interval间隔\r\n end=200\r\n if graphfile==\"YeastNet\" and type== \"_cyc/\":\r\n il=21 #interval间隔\r\n end=210\r\n if graphfile==\"YeastNet\" and type==\"_mips/\":\r\n il=24 #interval间隔\r\n end=192\r\n if graphfile==\"krogan2006_core\" and type== \"_cyc/\":\r\n il=15 #interval间隔\r\n end=150\r\n if graphfile==\"krogan2006_core\" and type==\"_mips/\":\r\n il=15 #interval间隔\r\n end=150\r\n def get_average(list):\r\n list_new=[]\r\n print(len(list))\r\n for i in range(int(len(list) / il)):\r\n sumil = sum(list[il * i:il * (i+ 1)])\r\n list_new.append(sumil / il)\r\n return list_new\r\n\r\n list=[]\r\n for line in accuracy:\r\n line=line.strip().split(\"\\t\")\r\n list.append(line)\r\n print(len(list[0]))\r\n print(len(list[1]))\r\n hi=[float(i) for i in list[0][:end]]\r\n mod=[float(i) for i in list[1][:end]]\r\n list1=get_average(hi)\r\n list2=get_average(mod)\r\n\r\n #x=[i for i in range(len(list[0]))]\r\n x=[i for i in range(int(len(hi)/il))]\r\n y1=[float(i) for i in list1]\r\n y2=[float(i) for i in list2]\r\n x=np.array(x)\r\n y1=np.array(y1)\r\n y2=np.array(y2)\r\n x_new = np.linspace(x.min(), x.max(), 200)\r\n y_new1 = spline(x, y1, x_new)\r\n y_new2 = spline(x, y2, x_new)\r\n #x_new = np.linspace(x.min(), x.max(), )\r\n #x_mod=np.array(x_mod)\r\n plt.figure(figsize=(7,3.5))\r\n plt.plot(x_new,y_new1,label=\"HiHiCode\",linewidth = '1.5',color=\"#FF0000\")\r\n plt.plot(x_new,y_new2,label=\"MOD\",linewidth = '1.5',color=\"#000000\")\r\n plt.xticks([])\r\n #plt.ylim(0.0, 0.5)\r\n plt.yticks(np.linspace(0.25, 0.5, 6, endpoint=True))\r\n plt.legend(loc='upper right')\r\n plt.savefig(base+\"/hiddenness5.pdf\")\r\n #plt.show()\r\n\r\n","sub_path":"Hirhide/hiddenness.py","file_name":"hiddenness.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"582294147","text":"epoch = 0\nn_epochs = 200\ndataset_name = 'ISIC_seg'\nbatch_size = 32\nlr = 0.0002\nb1 = 0.5\nb2 = 0.999\nn_cpu = 8\nimg_height = 128\nimg_width = 128\nchannels = 3\nlatent_dim = 8\nsample_interval = 100\ncheckpoint_interval = 200\nlambda_pixel = 10\nlambda_latent = 0.5\nlambda_kl = 0.01","sub_path":"src/config/.ipynb_checkpoints/bicyclegan-checkpoint.py","file_name":"bicyclegan-checkpoint.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"79462970","text":"# https://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html\nfrom functools import partial\nimport pandas as pd\nfrom PIL import Image\nfrom PIL import ImageTk\nimport tkinter as tk\nimport logging\nimport cv2\nimport numpy as np\nimport kmeans\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass ImageObject:\n def __init__(self, cv_img) -> None:\n '''Create an instance that store all required image data'''\n self.cv_img = cv_img\n self.tk_img = self.get_resize_tk_img(400, 400)\n self.rank = 0\n self.highlight_colors = []\n self.main_color_var = None\n self.color_palettes = []\n\n def get_resize_cv_img(self, h: int, w: int):\n resize_cv_img = self.__class__.resize(self.cv_img, h, w)\n return resize_cv_img\n\n def get_resize_tk_img(self, h: int, w: int):\n resize_tk_img = ImageMatching.cv2tkimg(self.__class__.resize(self.cv_img, h, w))\n return resize_tk_img\n\n def get_tk_thumbnail(self):\n resize_tk_img = ImageMatching.cv2tkimg(self.__class__.resize(self.cv_img))\n return resize_tk_img\n\n def get_main_rgb(self) -> tuple:\n main_rgb = self.highlight_colors[self.main_color_var.get()]\n return main_rgb\n\n def __del__(self):\n self.cv_img = None\n self.tk_img = None\n self.highlight_colors = None\n self.main_color_var = None\n self.color_palettes = None\n\n def __eq__(self, other: 'ImageObject'):\n return self.rank == other.rank\n\n def __lt__(self, other: 'ImageObject'):\n return self.rank < other.rank\n\n def __le__(self, other: 'ImageObject'):\n return self.rank <= other.rank\n\n def __gt__(self, other: 'ImageObject'):\n return self.rank > other.rank\n\n def __ge__(self, other: 'ImageObject'):\n return self.rank >= other.rank\n\n @classmethod\n def resize(cls, cv_img, dst_h: int = 100, dst_w: int = 100):\n '''Using NN interpolation to resize'''\n\n src_H, src_W, _ = cv_img.shape\n ratio = 0\n if(src_H > src_W):\n ratio = src_H/dst_h\n dst_w = int(src_W / ratio)\n else:\n ratio = src_W/dst_w\n dst_h = int(src_H / ratio)\n \n row_ratio, col_ratio= np.array([dst_h, dst_w])/np.array([src_H, src_W])\n \n # row wise interpolation \n row_idx = (np.ceil(range(1, 1 + int(src_H*row_ratio))/row_ratio) - 1).astype(int)\n # column wise interpolation\n col_idx = (np.ceil(range(1, 1 + int(src_W*col_ratio))/col_ratio) - 1).astype(int)\n\n final_matrix = cv_img[:, col_idx][row_idx, :]\n return final_matrix\n\n\nclass ImageMatching:\n COLORS_CSV_FILE = r'src/colors.csv'\n COLOR_2_RGB_DICT = {}\n RGB_2_COLOR_DICT = {}\n\n def __init__(self) -> None:\n '''Initialize instance with empty variables'''\n if len(self.__class__.COLOR_2_RGB_DICT) == 0 or len(self.__class__.RGB_2_COLOR_DICT) == 0:\n self.__class__.read_colors_csv()\n\n self._source_image = None\n self._target_images = []\n self._target_thumbnails = []\n self._n_highlight_color = 3\n\n def set_source_image(self, filename: str, can_image: tk.Canvas, scroll_frame: tk.Frame):\n '''Set source matching image'''\n # Remove the image from canvas and memory\n if can_image:\n if self._source_image is not None:\n can_image.delete(\"all\")\n del self._source_image\n self._source_image = None\n logging.info('Removed image from canvas')\n\n # Remove color palettes from scroll frame\n if scroll_frame:\n for i, widget in enumerate(scroll_frame.winfo_children()):\n scroll_frame.grid_columnconfigure(i, weight=0, minsize=0)\n widget.destroy()\n if self._source_image:\n self._source_image.color_palettes.clear()\n self._source_image.color_palettes = []\n logging.info('Removed color pallets from scroll frame')\n\n self._source_image = ImageObject(cv2.imread(filename))\n\n if can_image:\n can_image.create_image(0, 0, image=self._source_image.tk_img, anchor=tk.NW)\n logging.info('Added new image to canvas')\n\n def set_target_images(self, filenames: list, can_image: tk.Canvas, scroll_frame: tk.Frame, palette_frame: tk.Frame):\n '''Set target matching images'''\n\n def display_tk_image_n_palettes(img_obj: 'ImageObject'):\n '''Button command for image list'''\n # delete widgets\n can_image.delete(\"all\")\n for i, widget in enumerate(palette_frame.winfo_children()):\n palette_frame.grid_columnconfigure(i, weight=0, minsize=0)\n widget.destroy()\n # change image in canvas\n can_image.create_image(0, 0, image=img_obj.tk_img, anchor=tk.NW)\n # display palettes\n for i in range(len(img_obj.color_palettes)):\n palette_frame.grid_columnconfigure(i, weight=0, minsize=80)\n new_radio_bt = tk.Radiobutton(master=palette_frame,\n image=img_obj.color_palettes[i],\n compound='right',\n variable=img_obj.main_color_var,\n value=i,\n background='black')\n new_radio_bt.grid(column=i, row=0, padx=2, pady=2, sticky=\"nsew\")\n if i == img_obj.main_color_var.get():\n new_radio_bt.select()\n\n logging.info('Changed image in canvas')\n\n # remove image from canvas\n if can_image:\n can_image.delete(\"all\")\n logging.info('Removed images from canvas')\n\n # remove thumbnail from scroll frame\n if scroll_frame:\n for i, widget in enumerate(scroll_frame.winfo_children()):\n scroll_frame.grid_rowconfigure(i, weight=0, minsize=0)\n widget.destroy()\n self._target_thumbnails.clear()\n self._target_thumbnails = []\n self._target_images.clear()\n self._target_images = []\n logging.info('Removed images from scroll frame')\n\n # remove color palettes from palettes frame\n if palette_frame:\n for i, widget in enumerate(palette_frame.winfo_children()):\n palette_frame.grid_columnconfigure(i, weight=0, minsize=0)\n widget.destroy()\n logging.info('Removed color pallets from scroll frame')\n\n # read list of images\n for file in filenames:\n self._target_images.append(ImageObject(cv2.imread(file)))\n\n # generating highlight color for each image\n for i in range(len(self._target_images)):\n # get highlight color\n highlight_colors, _ = kmeans.perform(self._target_images[i].get_resize_cv_img(200, 200))\n # TODO: get close color and remove duplicate color\n highlight_colors = list(set([tuple(x) for x in highlight_colors]))\n\n for x in highlight_colors:\n b, g, r = x\n new_tk_img = self.generate_color_tk_img(r, g, b)\n self._target_images[i].color_palettes.append(new_tk_img)\n self._target_images[i].highlight_colors.append((r, g, b))\n logging.info(f'{i} Detected color: {(r,g,b)}')\n\n # create new int var\n self._target_images[i].main_color_var = tk.IntVar()\n self._target_images[i].main_color_var.set(0)\n\n # setting up thumbnail in scroll frame\n scroll_frame.grid_columnconfigure(0, weight=0, minsize=100)\n for i in range(len(filenames)):\n scroll_frame.grid_rowconfigure(i, weight=0, minsize=100)\n new_thumbnail = self._target_images[i].get_tk_thumbnail()\n new_button = tk.Button(master=scroll_frame, image=new_thumbnail, command=partial(display_tk_image_n_palettes, self._target_images[i]))\n new_button.grid(column=0, row=i, padx=0, pady=0, sticky=\"nsew\")\n self._target_thumbnails.append(new_thumbnail)\n\n # setting up color palettes in scroll frame\n\n logging.info('Added new images to scroll frame')\n\n def generate_source_color_pallets(self, scroll_frame: tk.Frame):\n '''Generate color pallets by highlight colors'''\n if self._source_image is None:\n return\n\n # remove existing color pallets\n if scroll_frame:\n for i, widget in enumerate(scroll_frame.winfo_children()):\n scroll_frame.grid_columnconfigure(i, weight=0, minsize=0)\n widget.destroy()\n self._source_image.color_palettes.clear()\n self._source_image.color_palettes = []\n self._source_image.highlight_colors.clear()\n self._source_image.highlight_colors = []\n logging.info('Removed color pallets from scroll frame')\n\n # get highlight color\n highlight_colors, _ = kmeans.perform(self._source_image.get_resize_cv_img(200, 200))\n # TODO: get close color and remove duplicate color\n highlight_colors = list(set([tuple(x) for x in highlight_colors]))\n\n for x in highlight_colors:\n b, g, r = x\n new_tk_img = self.generate_color_tk_img(r, g, b)\n self._source_image.color_palettes.append(new_tk_img)\n self._source_image.highlight_colors.append((r, g, b))\n logging.info('Detected color: ' + str((r, g, b)))\n\n # create new int var\n self._source_image.main_color_var = tk.IntVar()\n\n scroll_frame.grid_rowconfigure(0, weight=0, minsize=50)\n for i in range(len(self._source_image.color_palettes)):\n scroll_frame.grid_columnconfigure(i, weight=0, minsize=80)\n new_radio_bt = tk.Radiobutton(master=scroll_frame,\n image=self._source_image.color_palettes[i],\n compound='right',\n variable=self._source_image.main_color_var,\n value=i,\n background='black')\n new_radio_bt.grid(column=i, row=0, padx=2, pady=2, sticky=\"nsew\")\n\n if len(self._source_image.color_palettes) > 0:\n new_radio_bt.select()\n self._source_image.main_color_var.set(len(self._source_image.color_palettes) - 1)\n\n logging.info('Generated color pallets to scroll frame')\n\n def generate_matching_results(self, can_image: tk.Canvas, scroll_frame: tk.Frame, palette_frame: tk.Frame):\n '''\n 1. kmeans for each image list\n 2. check selected color\n 3. compute matching rate\n 4. sort the each image list\n 5. update image list frame\n 6. update display frame\n '''\n def display_tk_image_n_palettes(img_obj: 'ImageObject'):\n '''Button command for image list'''\n # delete widgets\n can_image.delete(\"all\")\n for i, widget in enumerate(palette_frame.winfo_children()):\n palette_frame.grid_columnconfigure(i, weight=0, minsize=0)\n widget.destroy()\n # change image in canvas\n can_image.create_image(0, 0, image=img_obj.tk_img, anchor=tk.NW)\n # display palettes\n for i in range(len(img_obj.color_palettes)):\n palette_frame.grid_columnconfigure(i, weight=0, minsize=80)\n new_radio_bt = tk.Radiobutton(master=palette_frame,\n image=img_obj.color_palettes[i],\n compound='right',\n variable=img_obj.main_color_var,\n value=i,\n background='black')\n new_radio_bt.grid(column=i, row=0, padx=2, pady=2, sticky=\"nsew\")\n if i == img_obj.main_color_var.get():\n new_radio_bt.select()\n\n # check can perform match\n if self._source_image is None or self._source_image.main_color_var is None or len(self._target_images) < 1:\n logging.info('Images not imported')\n return\n\n # 2\n source_rgb = self._source_image.get_main_rgb()\n\n target_rgbs = []\n for i in range(len(self._target_images)):\n r, g, b = self._target_images[i].get_main_rgb()\n target_rgbs.append([r, g, b])\n\n # 3\n ranks = self.__class__.getClosestMatch(source_rgb, target_rgbs)\n for i, rank in enumerate(ranks):\n self._target_images[i].rank = rank\n\n # 4\n sorted_idx = [i[0] for i in sorted(enumerate(self._target_images), key=lambda x:x[1])]\n\n # 5\n new_target_images = []\n new_target_thumbnails = []\n for i, widget in enumerate(scroll_frame.winfo_children()):\n widget.destroy()\n new_target_images.append(self._target_images[sorted_idx[i]])\n new_target_thumbnails.append(self._target_thumbnails[sorted_idx[i]])\n\n self._target_images = new_target_images\n self._target_thumbnails = new_target_thumbnails \n\n for i in range(len(self._target_images)):\n new_button = tk.Button(master=scroll_frame, image=self._target_thumbnails[i], command=partial(display_tk_image_n_palettes, self._target_images[i]))\n new_button.grid(column=0, row=i, padx=0, pady=0, sticky=\"nsew\")\n\n\n # check\n logging.info('Source main color: ' + str(source_rgb))\n logging.info('Source main color var: ' + str(self._source_image.main_color_var.get()))\n for i in range(len(self._target_images)):\n r, g, b = self._target_images[i].get_main_rgb()\n logging.info(f'Target {i} main color: {(r,g,b)}')\n logging.info(f'Target {i} main color var: {self._target_images[i].main_color_var.get()}')\n logging.info(f'Target {i} rank: {self._target_images[i].rank}')\n\n # 6\n\n logging.info('Rearranged images in scroll frame')\n\n @classmethod\n def cv2tkimg(cls, cvImage):\n _image = cv2.cvtColor(cvImage, cv2.COLOR_BGR2RGB)\n _image = Image.fromarray(_image)\n return ImageTk.PhotoImage(_image)\n\n @classmethod\n def rgb2hex(cls, r: int, g: int, b: int) -> str:\n return \"#{:02x}{:02x}{:02x}\".format(r, g, b)\n\n @classmethod\n def hex2rgb(cls, hexcode: str) -> tuple:\n return tuple(map(ord, hexcode[1:].decode('hex')))\n\n @classmethod\n def generate_color_tk_img(cls, r: int, g: int, b: int):\n size = 50\n new_img = np.zeros((size, size, 3), dtype=np.uint8)\n new_img[:, :, 0].fill(b)\n new_img[:, :, 1].fill(g)\n new_img[:, :, 2].fill(r)\n tk_img = ImageMatching.cv2tkimg(new_img)\n return tk_img\n\n @classmethod\n def read_colors_csv(cls):\n '''Read predefined colors data into dictionaries'''\n index = [\"color\", \"color_name\", \"hex\", \"R\", \"G\", \"B\"]\n colors_pd = pd.read_csv(cls.COLORS_CSV_FILE, names=index, header=None)\n colors = colors_pd[index[1]].to_list()\n rgbs = zip(colors_pd[index[3]].to_list(), colors_pd[index[4]].to_list(), colors_pd[index[5]].to_list())\n cls.COLOR_2_RGB_DICT = dict(zip(colors, rgbs))\n cls.RGB_2_COLOR_DICT = dict(zip(rgbs, colors))\n\n @classmethod\n def getComplementaryColour(cls, r: int, g: int, b: int):\n '''To calculate the complementary colour for a given colour'''\n return [255-r, 255-g, 255-b]\n\n @classmethod\n def getClosestMatch(cls, source_colour: tuple, colour_codes: list) -> list:\n '''Get and return the index for the closest match Shirt for our pants'''\n r, g, b = source_colour\n comp_colour = cls.getComplementaryColour(r, g, b)\n minimum = 1e9\n best = -1\n\n ranks = []\n # Find the closest match with the minumum absolute difference\n for i in range(len(colour_codes)):\n d = np.sum(np.abs(np.subtract(comp_colour, colour_codes[i])))\n ranks.append(d)\n return ranks\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"269300047","text":"import _pickle as pk\nimport numpy as np\nimport pandas\nimport json\nimport os\nfrom tqdm import tqdm\nfrom ensemble_boxes import *\nimport cv2\nfrom PIL import Image\n\nheaders = ['name', 'image_id', 'confidence', 'xmin', 'ymin', 'xmax', 'ymax']\nclass_name = ['holothurian', 'echinus', 'scallop', 'starfish']\n# cx101 72 cascade_r101_fpn_20e_nms.pkl 70\npkl_file = ['cx101.pkl', 'cascade_r101_fpn_20e_nms.pkl']\n\nweights = [1, 1]\niou_thr = 0.7\nskip_box_thr = 0.0001\n\n\nwith open('data/coco/annotations/testA.json', 'r') as js:\n json_file = json.load(js)\nimage_list = json_file['images']\n\nresults = []\nfor k in tqdm(range(len(image_list))):\n bboxes = []\n scores = []\n labels = []\n for pkl in pkl_file:\n with open(os.path.join('result', pkl), 'rb') as f:\n result_pkl = pk.load(f)\n\n res = result_pkl[k]\n\n box = np.vstack(res)\n label = [\n np.full(bbox.shape[0], i, dtype=np.int32)\n for i, bbox in enumerate(res)\n ]\n label = np.concatenate(label)\n\n bboxes.append(box[:, :4])\n scores.append(box[:, 4])\n labels.append(label)\n\n pic = os.path.join('data/coco/test-A-image', image_list[k]['file_name'])\n img = Image.open(pic)\n\n labels = [l.tolist() for l in labels]\n bboxes = [b.tolist() for b in bboxes]\n scores = [s.tolist() for s in scores]\n\n bboxes, scores, labels = weighted_boxes_fusion(bboxes, scores, labels, weights=weights, iou_thr=iou_thr,\n skip_box_thr=skip_box_thr)\n # bboxes, scores, labels = nms(bboxes, scores, labels, weights=weights, iou_thr=iou_thr)\n # bboxes, scores, labels = non_maximum_weighted(bboxes, scores, labels, weights=weights, iou_thr=iou_thr,\n # skip_box_thr=skip_box_thr)\n print(len(labels))\n\n # inds = scores > 0.001\n #\n # bboxes = bboxes[inds, :]\n # labels = labels[inds]\n # scores = scores[inds]\n ## 可视化融合结果\n # pic = os.path.join('data/coco/test-A-image', image_list[k]['file_name'])\n # # pic = 'test-A-image{}'.format(image_list[k]['file_name'])\n # img = cv2.imread(pic)\n # # print(img,pic)\n # for i in range(len(labels)):\n # # print((int(bboxes[i][0]), int(bboxes[i][1])), (int(bboxes[i][2]), int(bboxes[i][3])))\n # cv2.rectangle(img, (int(bboxes[i][0]), int(bboxes[i][1])), (int(bboxes[i][2]), int(bboxes[i][3])),\n # (0, 0, 255), 2)\n #\n # cv2.putText(img, class_name[int(labels[i])], (int(bboxes[i][0]), int(bboxes[i][1])),\n # cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 1)\n #\n # cv2.putText(img, str(scores[i]), (int(bboxes[i][2]), int(bboxes[i][3])), cv2.FONT_HERSHEY_COMPLEX, 1,\n # (0, 255, 255), 1)\n #\n # cv2.imwrite('result_vision_fusion/{}'.format(image_list[k]['file_name']), img)\n\n for i in range(len(labels)):\n new_res = {}\n new_res['name'] = class_name[int(labels[i])]\n new_res['xmin'] = int(bboxes[i][0])\n new_res['ymin'] = int(bboxes[i][1])\n new_res['xmax'] = int(bboxes[i][2])\n new_res['ymax'] = int(bboxes[i][3])\n new_res['confidence'] = scores[i]\n new_res['image_id'] = image_list[k]['file_name'].split('.')[0] + '.xml'\n results.append(new_res)\n\nsub = {}\nname = [result['name'] for result in results]\nimage_id = [result['image_id'] for result in results]\nconfidence = [result['confidence'] for result in results]\nxmin = [result['xmin'] for result in results]\nymin = [result['ymin'] for result in results]\nxmax = [result['xmax'] for result in results]\nymax = [result['ymax'] for result in results]\nsub['name'] = name\nsub['image_id'] = image_id\nsub['confidence'] = confidence\nsub['xmin'] = xmin\nsub['ymin'] = ymin\nsub['xmax'] = xmax\nsub['ymax'] = ymax\n\ndf = pandas.DataFrame(sub)\ndf.to_csv(\"submit/cx101-cr101-wbs.csv\", index=False, sep=',')\n","sub_path":"tools/bbox2wbf2sub.py","file_name":"bbox2wbf2sub.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"456978414","text":"import codecs\nimport json\nimport os\nimport zipfile\nfrom collections import defaultdict\nfrom xml.etree.ElementTree import iterparse\n\nimport requests\nimport xmltodict\nfrom django.apps import apps\nfrom lxml import etree\n\n\nclass Converter:\n UPDATE_FILE_NAME = \"update.cfg\"\n API_ADDRESS_FOR_DATASET = \"\" # specified api address with dataset id\n LOCAL_FILE_NAME = None # static short local filename\n LOCAL_FOLDER = \"source_data/\" # local folder for unzipped source files\n DOWNLOAD_FOLDER = \"download/\" # folder to downloaded files\n URLS_DICT = {} # control remote dataset files update\n\n #lets have all supporting functions at the beginning\n def get_urls(self):\n # returns actual dataset urls\n response = requests.get(self.API_ADDRESS_FOR_DATASET)\n if (response.status_code != 200):\n print(f\"ERROR request to {self.API_ADDRESS_FOR_DATASET}\")\n return response.status_code\n urls = []\n for i in response.json()['result']['resources']:\n urls.append(i['url'])\n return (urls)\n\n def rename_file(self, file):\n # abstract method for rename unzipped files for each app\n return\n\n def is_update(self, current_size, url):\n # returns true, if file size at the changed compared to current_size\n\n try:\n with open(self.UPDATE_FILE_NAME) as file:\n try:\n self.URLS_DICT = json.load(file)\n except:\n pass\n except:\n pass\n\n if len(self.URLS_DICT) > 0:\n if url in self.URLS_DICT:\n if int(self.URLS_DICT[url]) == current_size:\n return False\n\n return True\n\n def change_update(self, current_size, url):\n # update json, contains url & remote files size\n\n self.URLS_DICT[url] = current_size\n file = open(self.UPDATE_FILE_NAME, \"w\")\n file.write(json.dumps(self.URLS_DICT))\n file.close\n\n def download_file(self):\n # getting remote file from self.file_url\n urls = self.get_urls()\n for url in urls:\n file = os.path.split(url)[1]\n # request to remote url:\n print(f\"\\nRequest to remote url > {url}\")\n response = requests.get(url, stream=True)\n print(f\"\\tResponse: {response.status_code}\")\n if (response.status_code != 200):\n print(f\"E\\tRROR of requests.get ({url})\")\n continue\n\n # check for remote file updates:\n file_size = int(response.headers['Content-Length'])\n if not (self.is_update(file_size, url)):\n print(f\"- File {file} did not update. Not need to download.\")\n continue\n\n # folder existing control:\n if not (os.path.exists(self.DOWNLOAD_FOLDER)) or not (os.path.isdir(self.DOWNLOAD_FOLDER)):\n os.mkdir(self.DOWNLOAD_FOLDER)\n if not (os.path.exists(self.LOCAL_FOLDER)) or not (os.path.isdir(self.LOCAL_FOLDER)):\n os.mkdir(self.LOCAL_FOLDER)\n\n # download file:\n fd = open(self.DOWNLOAD_FOLDER + file, 'wb')\n print(f\"Download file {fd.name} ({'{0:,}'.format(file_size).replace(',', ' ')} bytes total):\")\n done = 0\n buffer_size = 1024 * 1024 * 10\n step = 10\n\n for chunk in response.iter_content(chunk_size=buffer_size):\n fd.write(chunk)\n fd.flush()\n done += buffer_size\n if done > file_size: done = file_size\n percent = round((done / file_size * 100))\n if (percent >= step):\n if percent > 100: percent = 100\n print(f\"\\t{percent} % ===> {'{0:,}'.format(done).replace(',', ' ')} bytes\")\n step += 10\n\n fd.close()\n if (os.stat(self.DOWNLOAD_FOLDER + file).st_size == file_size):\n print(f\"File {file} downloaded succefully.\")\n self.change_update(file_size, url)\n\n else:\n print(\"Download file error\")\n self.delete_downloaded_file(file)\n continue\n\n if zipfile.is_zipfile(self.DOWNLOAD_FOLDER + file):\n self.unzip_file(self.DOWNLOAD_FOLDER + file)\n else:\n os.rename(self.DOWNLOAD_FOLDER + file, self.LOCAL_FOLDER + self.LOCAL_FILE_NAME)\n\n def unzip_file(self, file):\n # unzip downloaded file\n print(f\"Unzipping file {file} ...\")\n try:\n zip_file = zipfile.ZipFile(file)\n zip_file.extractall(self.LOCAL_FOLDER)\n print(\"\\tUnzip succefully.\")\n except:\n print(f\"\\tERROR unzip file {file}\")\n\n # rename & move unzipped files:\n for unzipped_file in zip_file.namelist():\n os.rename(self.LOCAL_FOLDER + unzipped_file, self.LOCAL_FOLDER + self.rename_file(unzipped_file))\n\n self.delete_downloaded_file(file)\n\n def delete_downloaded_file(self, file):\n # deleting zipfile:\n try:\n os.remove(file)\n except:\n print(f\"ERROR deleting file {file}\")\n\n def parse_file(self):\n # encoding & parsing .xml source file\n with codecs.open(self.LOCAL_FOLDER + self.LOCAL_FILE_NAME, encoding=\"cp1251\") as file:\n return xmltodict.parse(file.read())\n\n def clear_db(self):\n # clearing data base\n for table in self.tables:\n table.objects.all().delete()\n print('Old data have deleted.')\n\n def process(self):\n # parsing sours file in flow\n # get an iterable\n context = iterparse(self.LOCAL_FOLDER + self.LOCAL_FILE_NAME, events=(\"start\", \"end\"))\n # turn it into an iterator\n context = iter(context)\n # get the root element\n event, root = context.__next__()\n\n # clear old DB\n self.clear_db()\n\n i = 0\n record = self.record\n # loop for creating one record\n for event, elem in context:\n if event == \"end\" and elem.tag == \"RECORD\":\n for text in elem.iter():\n print('\\t\\t', text.tag, '\\t\\t', text.text)\n if type(record[text.tag]) == list:\n record[text.tag].append(text.text)\n else:\n record[text.tag] = text.text\n\n # writing one record\n self.save_to_db(record)\n\n i = i + 1\n print(i,\n ' records\\n\\n................................................................................................')\n for key in record:\n if type(record[key]) == list:\n record[key].clear()\n else:\n record[key] = ''\n root.clear()\n try:\n self.bulk_manager.done()\n except:\n None\n try:\n self.bulk_submanager.done()\n except:\n None\n print('All the records have been rewritten.')\n \n def process_full(self): # It's temporary method name, in the future this 'process' will be one \n i = 0\n records = etree.Element('RECORDS')\n for _, elem in etree.iterparse(self.LOCAL_FOLDER + self.LOCAL_FILE_NAME, tag = self.RECORD_TAG):\n if len(records) < self.CHUNK_SIZE:\n # for text in elem.iter():\n # print('\\t%28s\\t%s'%(text.tag, text.text))\n records.append(elem)\n i = i + 1\n print(i,\n 'record\\n\\n................................................................................................')\n else:\n self.save_to_db(records)\n records.clear()\n print('All the records have been rewritten.')\n print('Converter has imported.')\n\nclass BulkCreateUpdateManager(object): # https://www.caktusgroup.com/blog/2019/01/09/django-bulk-inserts/\n \"\"\"\n This helper class keeps track of ORM objects to be created for multiple\n model classes, and automatically creates those objects with `bulk_create`\n when the number of objects accumulated for a given model class exceeds\n `chunk_size`.\n Upon completion of the loop that's `add()`ing objects, the developer must\n call `done()` to ensure the final set of objects is created for all models.\n \"\"\"\n\n def __init__(self, chunk_size=200):\n self._create_queues = defaultdict(list)\n self._update_queues = defaultdict(list)\n self.chunk_size = chunk_size\n self.create_first = False\n self.update_first = False\n\n def _commit_create(self, model_class):\n model_key = model_class._meta.label\n model_class.objects.bulk_create(self._create_queues[model_key])\n self.create_first = True\n\n def _commit_update(self, model_class, fields):\n model_key = model_class._meta.label\n model_class.objects.bulk_update(self._update_queues[model_key], fields)\n self.update_first = True\n\n def add_create(self, obj):\n \"\"\"\n Add an object to the queue to be created, and call bulk_create if we\n have enough objs.\n \"\"\"\n model_class = type(obj)\n model_key = model_class._meta.label\n\n if self.create_first:\n self._create_queues[model_key] = []\n self.create_first = False\n self._create_queues[model_key].append(obj)\n if len(self._create_queues[model_key]) >= self.chunk_size:\n self._commit_create(model_class)\n\n def add_update(self, obj):\n \"\"\"\n Add an object to the queue to be updated, and call bulk_update if we\n have enough objs.\n \"\"\"\n model_class = type(obj)\n model_key = model_class._meta.label\n\n if self.update_first:\n self._update_queues[model_key] = []\n self.update_first = False\n self._update_queues[model_key].append(obj)\n if len(self._update_queues[model_key]) >= self.chunk_size:\n self._commit_update(model_class)\n\n def done(self):\n \"\"\"\n Always call this upon completion to make sure the final partial chunk\n is saved.\n \"\"\"\n for model_name, objs in self._create_queues.items():\n if len(objs) > 0:\n self._commit(apps.get_model(model_name))\n","sub_path":"data_ocean/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":10470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"502098624","text":"import struct\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n#from mpl_toolkits.mplot3d import Axes3D\nfrom scipy.stats import multivariate_normal\nimport time\nimport os\nfrom DVS_utils import getDVSeventsDavis\n\nif __name__ == \"__main__\":\n slideStep = 10000\n\n for numDavisData in [17]:\n for index in [333]:\n print('Ges:', numDavisData, 'Sample:', index)\n tmpStr1 = str(index)\n tmpStr2 = '.aedat'\n tmpStr3 = '.txt'\n davisT, davisX, davisY, davisPol = getDVSeventsDavis('/media/eric/WichtigDaten/xzc/HandGesture/Dataset/'+str(numDavisData)+'/'+tmpStr1+tmpStr2, startEvent=1250002)\n davisT = np.array(davisT)\n davisX = np.array(davisX)\n davisY = np.array(davisY)\n davisPol = np.array(davisPol)\n\n for numGrasp in range(0,1):\n # davisX = davisXOrigin[(davisTOrigin > tmpDavisTimePoint[numGrasp * 2]) & (davisTOrigin < tmpDavisTimePoint[numGrasp * 2 + 1 ])]\n # davisY = davisYOrigin[(davisTOrigin > tmpDavisTimePoint[numGrasp * 2]) & (davisTOrigin < tmpDavisTimePoint[numGrasp * 2 + 1 ])]\n # davisPol = davisPolOrigin[(davisTOrigin > tmpDavisTimePoint[numGrasp * 2]) & (davisTOrigin < tmpDavisTimePoint[numGrasp * 2 + 1 ])]\n # davisT = davisTOrigin[(davisTOrigin > tmpDavisTimePoint[numGrasp * 2]) & (davisTOrigin < tmpDavisTimePoint[numGrasp * 2 + 1 ])]\n\n periodInterval = 20000\n resampleRatio = 0.5\n\n xPixelResol = 346\n yPixelResol = 260\n numParticle = 2000\n numLED = 4\n lastTransTime = np.zeros(shape=(xPixelResol,yPixelResol,2))\n lastTransTimeSlide = np.zeros(shape=(xPixelResol,yPixelResol,2))\n state = np.zeros(shape=(xPixelResol, yPixelResol))\n numValidTrans = np.zeros(shape=(xPixelResol, yPixelResol))\n sumNumValidTrans = 0\n sumNumTrans = 0\n numValidPeriod = 0\n initWeight = 1/numParticle\n initEvid = 1e-4\n indexCycle = 0\n\n meanLEDInterval =np.array([2000, 4000, 1333, 2666])\n meanLEDIntervalRatio = np.array([20, 30, 15, 20])\n covarLEDInterval = np.array([200,200,200,200])\n setParticle = np.random.randint(0, xPixelResol*yPixelResol, size=(numParticle, numLED))\n setParticleCoord = np.zeros(shape=(numParticle, 2, numLED))\n for k in range(0,numLED):\n setParticleCoord[:,0,k] = setParticle[:,k] // yPixelResol\n setParticleCoord[:,1,k] = setParticle[:,k] % yPixelResol\n\n weightParticleLast = np.ones(shape=(numParticle, numLED))*initWeight\n weightParticle = np.ones(shape=(numParticle, numLED))*initWeight\n weightParticleTime = np.ones(shape=(numParticle, numLED))*initWeight\n weightParticleSpace = np.ones(shape=(numParticle, numLED))*initWeight\n ledXPosition = np.zeros(shape=(numLED,1))\n ledYPosition = np.zeros(shape=(numLED,1))\n ledT = np.array([davisT[0] + periodInterval/2])\n while(True):\n # print(\"Cycle:\", indexCycle)\n start = time.time()\n evidTime = np.ones(shape=(xPixelResol,yPixelResol,numLED))*initEvid\n if davisT[-1] < (ledT[-1] + periodInterval/2):\n break\n else:\n section = (davisT >= (ledT[-1] - periodInterval/2)) & (davisT < (ledT[-1] + periodInterval/2))\n numEvent = np.zeros(shape=(xPixelResol, yPixelResol))\n eventX = davisX[section].astype(np.int64)\n eventY = davisY[section].astype(np.int64)\n eventPol = davisPol[section].astype(np.int64)\n eventPol[np.where(eventPol!=0)] = 1\n eventT = davisT[section]\n eventXY = np.concatenate((eventX.reshape(len(eventX),1), eventY.reshape(len(eventY),1)), axis=1)\n \n if np.shape(eventT) == (0,):\n ledXPosition[:, -1] = ledXPosition[:, -2]\n ledYPosition[:, -1] = ledYPosition[:, -2]\n else:\n eventPixel, eventOccurrence = np.unique(eventXY, return_counts=True, axis=0)\n numEvent[eventPixel[:, 0], eventPixel[:, 1]] = numEvent[eventPixel[:, 0], eventPixel[:, 1]] + eventOccurrence\n ifNoiseEvent = np.array(np.where(eventOccurrence < 4))\n noisePixel = np.delete(eventPixel, np.array(np.where(eventOccurrence >= 4)), axis=0)\n eventPixel = np.delete(eventPixel, ifNoiseEvent, axis=0)\n eventOccurrence = np.delete(eventOccurrence, ifNoiseEvent)\n for pixel in eventPixel:\n pixelPol = eventPol[(eventX == pixel[0])&(eventY == pixel[1])]\n pixelT = eventT[(eventX == pixel[0])&(eventY == pixel[1])]\n pixelState = np.append(state[pixel[0], pixel[1]], pixelPol[0: len(pixelPol)-1])\n state[pixel[0], pixel[1]] = pixelPol[-1]\n transition = (pixelPol != pixelState)\n pixelTransTime = pixelT[transition]\n if len(pixelTransTime) == 1:\n pixelLastTime = np.array([lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]]])\n lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]] = pixelTransTime[0]\n elif len(pixelTransTime) > 1:\n pixelLastTime = np.append([lastTransTime[pixel[0], pixel[1], pixelPol[transition][0]], lastTransTime[pixel[0], pixel[1], pixelPol[transition][1]]], pixelTransTime[0:len(pixelTransTime)-2])\n lastTransTime[pixel[0], pixel[1], [pixelPol[transition][-2], pixelPol[transition][-1]]] = pixelTransTime[[-2, -1]]\n hyperInterval = pixelTransTime - pixelLastTime\n tmpInterval = covarLEDInterval.reshape(numLED,1) - abs(np.tile(hyperInterval,(numLED,1)) - meanLEDInterval.reshape(numLED,1))\n indLED = tmpInterval > 0\n evidTime[pixel[0], pixel[1], :] = evidTime[pixel[0], pixel[1], :] + np.sum(indLED*((meanLEDIntervalRatio.reshape(numLED,1)*tmpInterval)/covarLEDInterval.reshape(numLED,1)), axis=1)\n\n #fig = plt.figure()\n #ax = fig.add_subplot(111, projection='3d')\n #X = np.arange(346)\n #Y = np.arange(260)\n #X, Y = np.meshgrid(X, Y)\n #ax.plot_surface(X, Y, np.flip(evidTime[:,:,0].T,axis=0)/20,cmap='coolwarm')\n #ax.set_xlabel('x')\n #ax.set_ylabel('y')\n #ax.set_zlabel('evidence')\n ##plt.imshow(np.flip(evidTime[:,:,0].T,axis=0))\n #plt.show()\n for k in range(0, numLED):\n tmpEvid = evidTime[:, :, k]\n tmpEvid[noisePixel[:, 0], noisePixel[:, 1]] = initEvid\n evidTime[:,:,k] = tmpEvid\n weightParticleTime[:, k] = evidTime[setParticleCoord[:, 0, k].astype(np.int64), setParticleCoord[:, 1, k].astype(np.int64), k]\n\n sumWeightParticleTime = np.sum(weightParticle, 0)\n indReselect = (10*meanLEDIntervalRatio) > sumWeightParticleTime\n for k in range(0, numLED):\n if indReselect[k] == True:\n tmpIndValidPixel = np.array(np.where(evidTime[:,:,k]>initEvid))\n tmpRow = tmpIndValidPixel[0, :]\n tmpCol = tmpIndValidPixel[1, :]\n tmpIndLowWeight = np.argsort(weightParticleTime[:,k])\n tmpIndLowWeight = np.delete(tmpIndLowWeight, np.arange(len(tmpRow), len(tmpIndLowWeight)))\n setParticleCoord[tmpIndLowWeight, 0, k] = tmpRow\n setParticleCoord[tmpIndLowWeight, 1, k] = tmpCol\n weightParticleTime[tmpIndLowWeight, k] = evidTime[tmpIndValidPixel[0], tmpIndValidPixel[1], k]\n weightParticleLast = initWeight\n\n weightParticleTime = weightParticleTime / sumWeightParticleTime\n meanCoordWeight = np.sum(setParticleCoord*np.tile(weightParticleTime.reshape((numParticle, 1, numLED)), (1, 2, 1)), 0)\n tmpCovarCoordWeight = setParticleCoord - meanCoordWeight\n covarCoordWeight1 = np.sum(np.tile(weightParticleTime.reshape((numParticle, 1, numLED)), (1, 2, 1))*(tmpCovarCoordWeight**2), 0)\n covarCoordWeight2 = np.sum((tmpCovarCoordWeight[:, [1, 0], :]*tmpCovarCoordWeight)*np.tile(weightParticleTime.reshape((numParticle, 1, numLED)), (1, 2, 1)), 0)\n covarCoordWeight = np.zeros(shape = (2, 2, numLED))\n for k in range(0, numLED):\n covarCoordWeight[0, 0, k] = covarCoordWeight1[0, k]\n covarCoordWeight[1, 1, k] = covarCoordWeight1[1, k]\n covarCoordWeight[0, 1, k] = covarCoordWeight2[0, k]\n covarCoordWeight[1, 0, k] = covarCoordWeight2[1, k]\n\n for k in range(0, numLED):\n weightParticleSpace[:, k] = multivariate_normal.pdf(setParticleCoord[:, :, k], mean=meanCoordWeight[:, k], cov=covarCoordWeight[:, :, k], allow_singular=True)\n\n weightParticleSpace = weightParticleSpace / np.sum(weightParticleSpace, 0)\n weightParticle = weightParticleLast * (weightParticleSpace + weightParticleTime)\n weightParticle = weightParticle / np.sum(weightParticle, 0)\n for k in range(0, numLED):\n if 1/np.sum(weightParticle[:, k] ** 2) < resampleRatio * numParticle:\n # print('resample')\n index = np.arange(2000)\n tmpIndParticle = np.random.choice(a=index, size = numParticle, replace=True, p=weightParticle[:, k])\n weightParticle[:, k] = initWeight\n setParticleCoord[:, :, k] = setParticleCoord[tmpIndParticle.astype(np.int64), :, k]\n \n ledXPosition[k, -1] = np.sum(weightParticle[:, k] * setParticleCoord[:, 0, k])\n ledYPosition[k, -1] = np.sum(weightParticle[:, k] * setParticleCoord[:, 1, k])\n setParticleCoord[:, :, k] = setParticleCoord[:, :, k] + np.random.normal(0, 2, (numParticle, 2))\n tmpSetParticleCoord = np.round(setParticleCoord[:, 0, k])\n #tmpSetParticleCoord[tmpSetParticleCoord < 1] = 1\n tmpSetParticleCoord[tmpSetParticleCoord > (xPixelResol - 1)] = xPixelResol - 1\n setParticleCoord[:, 0, k] = tmpSetParticleCoord\n tmpSetParticleCoord = np.round(setParticleCoord[:, 1, k])\n #tmpSetParticleCoord[tmpSetParticleCoord < 1] = 1\n tmpSetParticleCoord[tmpSetParticleCoord > (yPixelResol - 1)] = yPixelResol - 1\n setParticleCoord[:, 1, k] = tmpSetParticleCoord\n setParticle[:, k] = setParticleCoord[:, 0, k] * yPixelResol + setParticleCoord[:, 1, k]\n\n weightParticleLast = weightParticle\n \n plt.imshow(np.transpose(numEvent))\n #print(np.max(numEvent))\n #plt.title('transition')\n plt.scatter(ledXPosition[0, -1], ledYPosition[0, -1], s=50, c='r')\n plt.scatter(ledXPosition[1, -1], ledYPosition[1, -1], s=50, c='orangered')\n plt.scatter(ledXPosition[2, -1], ledYPosition[2, -1], s=50, c='y')\n plt.scatter(ledXPosition[3, -1], ledYPosition[3, -1], s=50, c='limegreen')\n plt.axis('off')\n plt.savefig('/media/eric/WichtigDaten/xzc/HandGesture/fig/'+str(numDavisData)+'_'+str(indexCycle)+'.png')\n #plt.pause(0.001)\n plt.cla()\n #plt.show()\n ledXPosition = np.concatenate((ledXPosition, [[0], [0], [0], [0]]), axis=1)\n ledYPosition = np.concatenate((ledYPosition, [[0], [0], [0], [0]]), axis=1)\n ledT = np.append(ledT, ledT[-1]+slideStep)\n indexCycle += 1\n end = time.time()\n # print(end - start)\n \n\n ledXPosition = np.delete(ledXPosition, -1, axis=1)\n ledYPosition = np.delete(ledYPosition, -1, axis=1)\n ledT = np.delete(ledT, -1)\n outputData = []\n outputData.append(ledXPosition[0, :])\n outputData.append(ledXPosition[1, :])\n outputData.append(ledXPosition[2, :])\n outputData.append(ledXPosition[3, :])\n outputData.append(ledYPosition[0, :])\n outputData.append(ledYPosition[1, :])\n outputData.append(ledYPosition[2, :])\n outputData.append(ledYPosition[3, :])\n outputData = np.transpose(np.array(outputData))\n outputfile = 'dataset/'+str(numDavisData)+'/'+tmpStr1+tmpStr3\n # np.savetxt(outputfile, outputData, fmt=\"%.6f\", delimiter=\"\\t\", newline=\"\\n\")\n \n","sub_path":"led_tracking_new.py","file_name":"led_tracking_new.py","file_ext":"py","file_size_in_byte":14787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"4938059","text":"\"\"\"Backend URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nimport backend_api.views as views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('droneList/', views.DroneListView.as_view()),\n path('orderList/', views.OrderListView.as_view()),\n path('ownerList/', views.OwnerListView.as_view()),\n path('recipientList/', views.RecipientListView.as_view()),\n path('availDronesList/', views.AvailableDronesList.as_view()),\n path('algo/', views.PathAlgoView.as_view()),\n]\n","sub_path":"Backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"363221041","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom src.battle.battle_search import BattleSearch\nfrom src.battle.battle_template import BattleTemplateFrame\nfrom src.connection.database import get_search_entities\nfrom src.images.image import get_search\n\n\nclass Battle(BattleTemplateFrame):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.battle = kwargs\n\n self.parent = kwargs['parent']\n\n self.type_values = ('Character', 'NPC', 'Monster')\n\n self.search_icon = get_search()\n\n self.name = tk.StringVar()\n self.type = tk.StringVar(value=self.type_values[0])\n\n self.set_search()\n self.set_buttons()\n\n self.set_widgets_conf()\n self.set_buttons_conf()\n\n def set_search(self):\n # --- Name ---\n name_label = ttk.Label(\n self.template_scroll.widgets,\n text='Name'\n )\n name_label.grid(row=0, column=0, sticky='EW')\n\n name_entry = ttk.Entry(\n self.template_scroll.widgets,\n textvariable=self.name,\n width=90\n )\n name_entry.grid(row=0, column=1, sticky='EW')\n\n # --- Type ---\n type_label = ttk.Label(\n self.template_scroll.widgets,\n text=\"Type\"\n )\n type_label.grid(row=1, column=0, sticky='EW')\n\n type_entry = ttk.Combobox(\n self.template_scroll.widgets,\n textvariable=self.type,\n values=self.type_values,\n state=\"readonly\"\n )\n type_entry.grid(row=1, column=1, sticky='EW')\n\n search_button = ttk.Button(\n self.template_scroll.widgets,\n text=' Search',\n command=self.search,\n style='DarkButton.TButton',\n image=self.search_icon,\n compound=tk.LEFT,\n cursor='hand2'\n )\n search_button.grid(row=2, column=0, columnspan=2, sticky='EW')\n\n def set_buttons(self):\n title_separator = ttk.Separator(\n self.template_scroll.buttons\n )\n title_separator.grid(row=0, columnspan=1, sticky='EW')\n\n def search(self):\n name = self.name.get()\n type_ = self.type.get()\n\n search_result = get_search_entities(name, type_)\n\n config = {\n 'master': self.parent,\n 'entity': BattleSearch,\n 'entities': search_result,\n 'type': type_\n }\n\n self.template_scroll.add_entity_frame(**config)\n","sub_path":"dist/main/src/battle/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"551686200","text":" \n# A utility class that represents an individual node in a BST\nclass Node:\n def __init__(self,key):\n self.left = None\n self.right = None\n self.val = key\n \n# A utility function to insert a new node with the given key\ndef insert(root,node):\n if root is None:\n root = node\n else:\n if root.val < node.val:\n if root.right is None:\n root.right = node\n else:\n insert(root.right, node)\n else:\n if root.left is None:\n root.left = node\n else:\n insert(root.left, node)\n\ndef returnVal(node):\n if node!= None:\n return node.val\n else:\n return 'null'\n \n# A utility function to do inorder tree traversal\ndef inorder(root):\n if root:\n inorder(root.left)\n print(root.val)\n inorder(root.right)\n \ndef nodeChild(node):\n print(\"node val\" + str(returnVal(node)))\n print(\"left child\" + returnVal(node.left))\n print(\"right child\" + returnVal(node.right))\n\n# Let us create the following BST\n# 50\n# / \\\n# 30 70\n# / \\ / \\\n# 20 40 60 80\n\nr = Node(50)\ninsert(r,Node(30))\ninsert(r,Node(20))\ninsert(r,Node(40))\ninsert(r,Node(70))\ninsert(r,Node(60))\ninsert(r,Node(80))\n \n# Print inoder traversal of the BST\ninorder(r)\nnodeChild(r)\n","sub_path":"childNode.py","file_name":"childNode.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"454501798","text":"import math\nimport numpy as np\nimport time\n\n\nfrom src.ivp import IVP\nfrom src.ode import ODE\nfrom src.results import ResultsComparator\nfrom src.solver import BackwardEulerSolver\n\n\nf = lambda u, t: np.array([\n u[0] + u[1] - t,\n u[0] - u[1]\n])\n\ntrue_value = lambda t: np.array([\n math.exp(t*math.sqrt(2)) + math.exp(-1*t*math.sqrt(2)) + 0.5 + 0.5*t,\n (math.sqrt(2) - 1)*math.exp(t*math.sqrt(2)) - (1 + math.sqrt(2)) * math.exp(-1*t*math.sqrt(2)) - 0.5 + 0.5*t\n])\n\nde = ODE(f)\n\nu_0 = np.array([2.5, -2.5])\nt_0 = 0\n\nstep = 0.25\nprecision = 2\nt_n = 3\n\n\nproblem = IVP(de, u_0, t_0)\n\nslv = BackwardEulerSolver(problem, t_n, step, precision)\nslv.solve()\n\ncomparison = ResultsComparator(slv.solution, true_value)\ncomparison.print_result_graphs()\n\n\ncomparison.compute_local_truncation_errors()\ncomparison.graph_local_truncation_errors()\n\n\n","sub_path":"tests/vector_backward_euler.py","file_name":"vector_backward_euler.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"279856561","text":"# https://www.devdungeon.com/content/text-speech-python-pyttsx3\nimport pyttsx3\n\n\"\"\" engine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nfor voice in voices:\n print(\"Voice:\")\n print(\" - ID: %s\" % voice.id)\n print(\" - Name: %s\" % voice.name)\n print(\" - Languages: %s\" % voice.languages)\n print(\" - Gender: %s\" % voice.gender)\n print(\" - Age: %s\" % voice.age)\n engine.setProperty('voice', voice.id)\n engine.say(\"Hello World!\")\n engine.runAndWait()\n engine.stop() \"\"\"\n\nengine = pyttsx3.init()\n\n# Voice IDs pulled from engine.getProperty('voices')\n# These will be system specific\nen_voice_id = \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_ES-ES_ZIRA_11.0\"\n\n# Use female English voice\nengine.setProperty('voice', en_voice_id)\nengine.say('Hello with my new voice')\n\n\n\nengine.runAndWait()","sub_path":"Voz-chage.py","file_name":"Voz-chage.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"95780555","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author : Vivek Alhat\n\nimport wx\nimport os\nimport time\nimport wikipedia\nimport wolframalpha\nfrom gtts import gTTS\n\nclass MyFrame(wx.Frame): # Main frame class\n def __init__(self):\n currTime = int(time.strftime('%H'))\n\n if currTime < 12:\n tts = gTTS(text='Good Morning Vivek! How can i help you?',lang='en')\n elif currTime > 12:\n tts = gTTS(text='Good Afternoon Vivek! How can i help you?',lang='en')\n elif currTime > 6:\n tts = gTTS(text='Good Evening Vivek! How can i help you?',lang='en')\n\n tts.save(\"greeting.mp3\")\n os.system(\"mpg321 --stereo greeting.mp3\")\n wx.Frame.__init__(self, None,\n pos=wx.DefaultPosition, size=wx.Size(400, 100),\n style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION |\n wx.CLOSE_BOX | wx.CLIP_CHILDREN,\n title=\"Karen\") # GUI widget\n panel = wx.Panel(self)\n my_sizer = wx.BoxSizer(wx.VERTICAL)\n lbl = wx.StaticText(panel,\n label=\"Ask me anything.\") # Main text to be displayed on the widget\n my_sizer.Add(lbl, 0, wx.ALL, 5)\n self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER,size=(400,30))\n self.txt.SetFocus()\n self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)\n my_sizer.Add(self.txt, 0, wx.ALL, 5)\n panel.SetSizer(my_sizer)\n self.Show()\n\n def OnEnter(self, event):\n query = self.txt.GetValue() # Bind the user input\n query = query.lower()\n\n if query == (\"exit\" or \"over\"):\n self.Destroy()\n else:\n try:\n app_id = \"2879EU-W3UEP5V7UK\"\n client = wolframalpha.Client(app_id)\n res = client.query(query)\n answer = next(res.results).text\n print (answer)\n except:\n query = query.split(' ')\n query = \" \".join(query[2:])\n print (wikipedia.summary(query))\n\n\nif __name__ == \"__main__\":\n app = wx.App(True) # Object creation\n frame = MyFrame()\n app.MainLoop()\n","sub_path":"assistant.py","file_name":"assistant.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"397708915","text":"import mqtt_remote_method_calls as com\nimport ev3dev.ev3 as ev3\nimport time\nimport robot_controller as controller\n\n\nclass MyDelegate(object):\n def __init__(self):\n self.running = True\n\n\ndef main():\n my_delegate = MyDelegate()\n robot = controller.Snatch3r()\n mqtt_client = com.MqttClient(robot)\n mqtt_client.connect_to_pc()\n touch_sensor = ev3.TouchSensor()\n while my_delegate.running:\n if(robot.has_moved == True):\n mqtt_client.send_message(\"on_square_draw\", [robot.color,\n robot.x_dir,\n robot.y_dir,\n robot.grid_size])\n robot.has_moved = False\n if(touch_sensor.is_pressed):\n print(\"Resetting robot position.\")\n robot.x_dir = 400\n robot.y_dir = 200\n time.sleep(.01)\n\n\nmain()\n","sub_path":"projects/acombsr/ev3_wip_final.py","file_name":"ev3_wip_final.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"629856668","text":"from collections import OrderedDict, UserString\nfrom enum import Enum\nfrom types import MappingProxyType\n\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql as pg\n\nimport fumbbl_base.custom_types\nimport fumbbl_base.rules\n\nfrom fplusdb_main import custom_types\n\n## type converter ##############################################\n\ntype_conv = MappingProxyType(OrderedDict((\n ('bool', pg.BOOLEAN),\n ('int', pg.INTEGER),\n ('smallint', pg.SMALLINT),\n ('str', pg.VARCHAR),\n )))\n\n## base classes ################################################\n\nclass MetaDataEntity(UserString):\n\n sa_class = NotImplemented\n\n def __init__(self, name, *args, **kwargs):\n super().__init__(name)\n self.name = name\n self._args = args\n self._kwargs = kwargs\n self.sa = None\n\n def make_sa(self, *args, **kwargs):\n args, kwargs = self._prepare_sa(*args, **kwargs)\n self.sa = self.get_sa(*args, **kwargs)\n self._finish_sa()\n\n def _prepare_sa(self, *args, **kwargs):\n _args = list(self._args)\n _args.extend(args)\n _kwargs = dict(self._kwargs)\n _kwargs.update(kwargs)\n return _args, _kwargs\n\n def get_sa(self, *args, **kwargs):\n raise NotImplementedError('must defined in subclasses')\n\n def _finish_sa(self):\n del self._args, self._kwargs\n\n #def __getattr__(self, attr):\n # return getattr(self.__getattribute__('sa'), attr)\n\n\nclass Schema(MetaDataEntity):\n\n sa_class = sa.MetaData\n\n def __init__(self, name, *args, **kwargs):\n super().__init__(name, *args, **kwargs)\n self.enums = OrderedDict()\n self.tables = OrderedDict()\n self.make_sa()\n # workaround code, remove at sqlalchemy version 1.1\n # https://bitbucket.org/zzzeek/sqlalchemy/issues/2729/metada\n # tacreate_all-do-not-create-enum-in#comment-9003265\n @sa.event.listens_for(self.sa, 'before_create')\n def _create_enum(metadata, conn, **kw):\n for e in self.enums.values():\n e.sa.create(conn, checkfirst=True)\n\n def add_enum(self, enum):\n enum.make_sa(metadata=self.sa)\n enum.schema = self\n self.enums[enum.upper()] = enum\n self.__dict__[enum.upper()] = enum\n\n def add_table(self, table):\n table.make_sa(metadata=self.sa)\n table.schema = self\n self.tables[table.upper()] = table\n self.__dict__[table.upper()] = table\n\n def get_sa(self, *args, **kwargs):\n kwargs.setdefault('schema', self.name)\n return self.sa_class(*args, **kwargs)\n\n\nclass Enum_(MetaDataEntity):\n\n sa_class = pg.ENUM\n\n def get_sa(self, *args, **kwargs):\n kwargs.setdefault('name', self.name)\n return self.sa_class(*args, **kwargs)\n\n\nclass Table(MetaDataEntity):\n\n sa_class = sa.Table\n\n @property\n def fullname(self):\n return '{}.{}'.format(self.schema, self)\n\n def __init__(self, name, *args, **kwargs):\n super().__init__(name, *args, **kwargs)\n self.columns = OrderedDict((a.upper(), a) for a in args\n if getattr(a, 'sa_class', None) == sa.Column)\n self.__dict__.update(self.columns)\n\n def get_sa(self, *args, **kwargs):\n name = kwargs.setdefault('name', self.name)\n metadata = kwargs['metadata']\n del kwargs['name']\n del kwargs['metadata']\n columns = set(self.columns.values())\n args = [(a if a not in columns else a.sa) for a in args]\n return self.sa_class(name, metadata, *args, **kwargs)\n\n def primary_keys(self):\n return tuple(c for c in self.columns.values()\n if c.sa.primary_key)\n\nclass Column(MetaDataEntity):\n\n sa_class = sa.Column\n\n def __init__(self, name, *args, **kwargs):\n super().__init__(name, *args, **kwargs)\n self.make_sa()\n\n def get_sa(self, *args, **kwargs):\n kwargs.setdefault('name', self.name)\n return self.sa_class(*args, **kwargs)\n\n\n## temporary workaround classes ################################\n\n# workaround code, remove at sqlalchemy version 1.1\n# https://bitbucket.org/zzzeek/sqlalchemy/issues/3467/array-of-e\n# nums-does-not-allow-assigning#comment-19370832\nclass ArrayOfEnum(pg.ARRAY):\n\n def bind_expression(self, bindvalue):\n return sa.cast(bindvalue, self)\n\n def result_processor(self, dialect, coltype):\n super_rp = super(ArrayOfEnum, self).result_processor(\n dialect, coltype)\n\n def handle_raw_string(value):\n inner = re.match(r\"^{(.*)}$\", value).group(1)\n return inner.split(\",\")\n\n def process(value):\n if value is None:\n return None\n return super_rp(handle_raw_string(value))\n return process\n\n\n## entities ####################################################\n\nMAIN = Schema('main')\n\nsa.event.listen(MAIN.sa, 'before_create',\n sa.DDL('CREATE SCHEMA IF NOT EXISTS main'))\n\n_massenums = {}\nfor _ename in ('casualty', 'progression_title', 'skillcat',\n 'skill'):\n _names = OrderedDict()\n for _m in (fumbbl_base.rules.crp, fumbbl_base.rules.lrb4):\n _names.update(list((k, ememb.value)\n for k, ememb in getattr(getattr(_m, _ename, None),\n '__members__', {}).items()))\n _massenums[_ename] = Enum(_ename, _names)\ndel _ename, _names, _m\n\nfor _enum, _ename in (\n (custom_types.player_type, 'player_type'),\n (custom_types.position_type, 'position_type'),\n (fumbbl_base.custom_types.application, 'application'),\n (fumbbl_base.custom_types.player_gender, 'player_gender'),\n (fumbbl_base.custom_types.tournament_format,\n 'tournament_format'),\n (fumbbl_base.custom_types.tournament_style,\n 'tournament_style'),\n (custom_types.tournament_rank, 'tournament_rank'),\n (_massenums['casualty'], 'casualty'),\n (_massenums['progression_title'], 'progression_title'),\n (_massenums['skillcat'], 'skillcat'),\n (_massenums['skill'], 'skill'),\n (fumbbl_base.rules.common.casualty_effect,\n 'casualty_effect'),\n (fumbbl_base.rules.common.weather, 'weather'),\n (fumbbl_base.rules.crp.card, 'card'),\n ):\n _enums = tuple(set(e.value\n for e in _enum.__members__.values()))\n MAIN.add_enum(Enum_(_ename, *_enums))\ndel _massenums, _enum, _ename, _enums\n\n\nMAIN.add_table(\n Table('match',\n Column('id', pg.INTEGER, primary_key=True,\n autoincrement=False),\n Column('is_ranked', pg.BOOLEAN),\n Column('division_id', pg.SMALLINT),\n Column('application', MAIN.APPLICATION.sa),\n Column('application_version', pg.VARCHAR),\n Column('replay_id', pg.INTEGER),\n Column('scheduled', pg.TIMESTAMP(timezone=True)),\n Column('started', pg.TIMESTAMP(timezone=True)),\n Column('finished', pg.TIMESTAMP(timezone=True)),\n Column('game_time', pg.INTEGER),\n Column('periods', pg.SMALLINT),\n Column('gate', pg.INTEGER),\n Column('admin_comment', pg.TEXT),\n Column('extra_info', pg.JSONB),\n Column('tournament_id', pg.INTEGER),\n Column('local_replay_data_status', pg.TEXT), ## TODO: ENUM\n )\n )\n\n\n_ot = fumbbl_base.custom_types.match_option_type\nMAIN.add_table(\n Table('match_option',\n Column('match_id', pg.INTEGER,\n sa.ForeignKey('match.id'),\n primary_key=True, autoincrement=False),\n *[Column(e.value, type_conv[t]) for e, t in _ot.items()]\n )\n )\ndel _ot\n\n\nMAIN.add_table(\n Table('team',\n Column('match_id', pg.INTEGER,\n sa.ForeignKey('match.id'),\n primary_key=True, autoincrement=False),\n Column('away', pg.BOOLEAN, primary_key=True),\n Column('phase', pg.SMALLINT, primary_key=True,\n autoincrement=False),\n Column('roster_name', pg.VARCHAR),\n Column('roster_id', pg.INTEGER),\n Column('name', pg.VARCHAR),\n Column('id', pg.INTEGER),\n Column('coach_name', pg.VARCHAR),\n Column('coach_id', pg.INTEGER),\n Column('coach_cr', pg.NUMERIC(\n precision=5, scale=2)),\n Column('coach_cr_div', pg.NUMERIC(\n precision=5, scale=2)),\n Column('coach_cr_ros', pg.NUMERIC(\n precision=5, scale=2)),\n Column('coach_cr_divros', pg.NUMERIC(\n precision=5, scale=2)),\n Column('coach_bracket',\n MAIN.PROGRESSION_TITLE.sa),\n Column('coach_bracket_div',\n MAIN.PROGRESSION_TITLE.sa),\n Column('coach_bracket_ros',\n MAIN.PROGRESSION_TITLE.sa),\n Column('coach_bracket_divros',\n MAIN.PROGRESSION_TITLE.sa),\n Column('treasury', pg.INTEGER),\n Column('petty_cash', pg.INTEGER),\n Column('winnings', pg.INTEGER),\n Column('expenses', pg.INTEGER),\n Column('rerolls', pg.SMALLINT),\n Column('rerolls_value', pg.INTEGER),\n Column('fan_factor', pg.SMALLINT),\n Column('fan_factor_value', pg.INTEGER),\n Column('assistant_coaches', pg.SMALLINT),\n Column('assistant_coaches_value', pg.INTEGER),\n Column('cheerleaders', pg.SMALLINT),\n Column('cheerleaders_value', pg.INTEGER),\n Column('apothecaries', pg.SMALLINT),\n Column('apothecaries_value', pg.INTEGER),\n Column('bloodweiser_babes', pg.SMALLINT),\n Column('bloodweiser_babes_value', pg.INTEGER),\n Column('bribes', pg.SMALLINT),\n Column('bribes_value', pg.INTEGER),\n Column('halfling_master_chef', pg.SMALLINT),\n Column('halfling_master_chef_value', pg.INTEGER),\n Column('igors', pg.SMALLINT),\n Column('igors_value', pg.INTEGER),\n Column('wizards', pg.SMALLINT),\n Column('wizards_value', pg.INTEGER),\n # workaround code, replace \"ArrayOfEnum(MAIN.CARD.sa)\"\n # with \"pg.ARRAY(MAIN.CARD.sa)\" if sqlalchemy\n # version 1.1\n Column('cards', ArrayOfEnum(MAIN.CARD.sa)),\n Column('tv', pg.INTEGER),\n Column('tw', pg.INTEGER),\n Column('tr', pg.SMALLINT),\n Column('ts', pg.SMALLINT),\n Column('fame', pg.SMALLINT),\n Column('fans', pg.INTEGER),\n Column('wins', pg.SMALLINT),\n Column('draws', pg.SMALLINT),\n Column('losses', pg.SMALLINT),\n Column('concessions', pg.SMALLINT),\n Column('admin_awarded_concessions', pg.SMALLINT),\n Column('tds', pg.SMALLINT),\n Column('tds_against', pg.SMALLINT),\n Column('extra_score', pg.SMALLINT),\n Column('cas_inflicted', pg.SMALLINT),\n Column('bh_inflicted', pg.SMALLINT),\n Column('si_inflicted', pg.SMALLINT),\n Column('dead_inflicted', pg.SMALLINT),\n Column('cas_suffered', pg.SMALLINT),\n Column('bh_suffered', pg.SMALLINT),\n Column('si_suffered', pg.SMALLINT),\n Column('dead_suffered', pg.SMALLINT),\n Column('extra_info', pg.JSONB),\n )\n )\n\nMAIN.add_table(\n Table('player',\n Column('match_id', pg.INTEGER,\n sa.ForeignKey('match.id'),\n primary_key=True, autoincrement=False),\n Column('away', pg.BOOLEAN, primary_key=True),\n Column('phase', pg.SMALLINT, primary_key=True,\n autoincrement=False),\n Column('nr', pg.SMALLINT, primary_key=True,\n autoincrement=False),\n Column('flow', pg.SMALLINT, primary_key=True,\n autoincrement=False),\n Column('name', pg.VARCHAR),\n Column('id', pg.INTEGER),\n Column('roster_name', pg.VARCHAR),\n Column('roster_id', pg.INTEGER),\n Column('pos_race', pg.VARCHAR),\n Column('pos_qty', pg.SMALLINT),\n Column('pos_title', pg.VARCHAR),\n Column('pos_id', pg.INTEGER),\n Column('pos_type', MAIN.POSITION_TYPE.sa),\n Column('pos_ma', pg.SMALLINT),\n Column('pos_st', pg.SMALLINT),\n Column('pos_ag', pg.SMALLINT),\n Column('pos_av', pg.SMALLINT),\n # workaround code, replace \"ArrayOfEnum(MAIN.SKILL.sa)\"\n # with \"pg.ARRAY(MAIN.SKILL.sa)\" if sqlalchemy\n # version 1.1\n Column('pos_skills', ArrayOfEnum(MAIN.SKILL.sa)),\n # workaround code, replace\n # \"ArrayOfEnum(MAIN.SKILLCAT.sa)\" with\n # \"pg.ARRAY(MAIN.SKILL.sa)\" if sqlalchemy version 1.1\n Column('pos_normal', ArrayOfEnum(MAIN.SKILLCAT.sa)),\n # workaround code, replace\n # \"ArrayOfEnum(MAIN.SKILLCAT.sa)\" with\n # \"pg.ARRAY(MAIN.SKILL.sa)\" if sqlalchemy version 1.1\n Column('pos_double', ArrayOfEnum(MAIN.SKILLCAT.sa)),\n Column('pos_cost', pg.INTEGER),\n Column('pos_undead', pg.BOOLEAN),\n Column('pos_thrall', pg.BOOLEAN),\n Column('type', MAIN.PLAYER_TYPE.sa),\n Column('gender', MAIN.PLAYER_GENDER.sa),\n Column('value', pg.INTEGER),\n # workaround code, replace \"ArrayOfEnum(MAIN.SKILL.sa)\"\n # with \"pg.ARRAY(MAIN.SKILL.sa)\" if sqlalchemy\n # version 1.1\n Column('earned_skills', ArrayOfEnum(MAIN.SKILL.sa)),\n Column('earned_skills_value', pg.ARRAY(pg.INTEGER)),\n # workaround code, replace\n # \"ArrayOfEnum(MAIN.CASUALTY.sa)\" with\n # \"pg.ARRAY(MAIN.CASUALTY.sa)\" if sqlalchemy version 1.1\n Column('cas', ArrayOfEnum(MAIN.CASUALTY.sa)),\n # workaround code, replace\n # \"ArrayOfEnum(MAIN.CASUALTY_EFFECT.sa)\" with\n # \"pg.ARRAY(MAIN.CASUALTY_EFFECT.sa)\" if sqlalchemy\n # version 1.1\n Column('cas_effects',\n ArrayOfEnum(MAIN.CASUALTY_EFFECT.sa)),\n Column('comp', pg.SMALLINT),\n Column('td', pg.SMALLINT),\n Column('int', pg.SMALLINT),\n Column('cas', pg.SMALLINT),\n Column('mvp', pg.SMALLINT),\n Column('spp', pg.SMALLINT),\n Column('blocks', pg.INTEGER),\n Column('passing', pg.INTEGER),\n Column('rushing', pg.INTEGER),\n Column('turns', pg.SMALLINT),\n Column('progression_title', MAIN.PROGRESSION_TITLE.sa),\n Column('prev_match_id', pg.INTEGER),\n Column('prev_away', pg.BOOLEAN),\n Column('prev_phase', pg.SMALLINT),\n Column('prev_nr', pg.SMALLINT),\n Column('prev_flow', pg.SMALLINT),\n Column('next_match_id', pg.INTEGER),\n Column('next_away', pg.BOOLEAN),\n Column('next_phase', pg.SMALLINT),\n Column('next_nr', pg.SMALLINT),\n Column('next_flow', pg.SMALLINT),\n Column('extra_info', pg.JSONB),\n sa.ForeignKeyConstraint(\n ['match_id', 'away', 'phase'],\n ['team.match_id', 'team.away', 'team.phase'],\n onupdate='CASCADE'),\n )\n )\n\nMAIN.add_table(\n Table('tournament',\n Column('id', pg.INTEGER,\n primary_key=True, autoincrement=False),\n Column('name', pg.VARCHAR),\n Column('group_id', pg.INTEGER),\n Column('group_name', pg.VARCHAR),\n Column('season', pg.SMALLINT),\n Column('format', MAIN.TOURNAMENT_FORMAT.sa),\n Column('style', MAIN.TOURNAMENT_STYLE.sa),\n Column('winner_team_id', pg.INTEGER),\n Column('last_check_match_id', pg.INTEGER,\n sa.ForeignKey('match.id')),\n )\n )\n\nMAIN.add_table(\n Table('tournament_pairing',\n Column('tournament_id', pg.INTEGER,\n sa.ForeignKey('tournament.id'), primary_key=True),\n Column('round', pg.SMALLINT, primary_key=True),\n Column('pos', pg.SMALLINT, primary_key=True),\n Column('away', pg.BOOLEAN, primary_key=True),\n Column('pending', pg.BOOLEAN),\n # intentionally redundant\n Column('match_id', pg.INTEGER,\n sa.ForeignKey('match.id')),\n Column('team_id', pg.INTEGER),\n Column('team_bold', pg.BOOLEAN),\n Column('team_filler', pg.BOOLEAN),\n )\n )\n","sub_path":"pythonlib/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":15386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"357640452","text":"a = int(input('Primeiro valor: '))\nb = int(input('Segundo valor: '))\nc = int(input('Terceiro valor: '))\n#valor menor\nif b < a and b < c:\n m = b\nif c < a and c < b:\n m = c\n#valor maior\nmo = a\nif b > a and b > c:\n mo = b\nif c > a and c > b:\n mo = b\nprint('O menor valor foi {}!'.format(m))\nprint('O maior valor foi {}!'.format(mo))\n","sub_path":"ex033.py","file_name":"ex033.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"454314827","text":"from arquivoscsv.arquivoscsv.ext import db\n\n\nclass Sub_Centro(db.Model):\n __tablename__ = \"sub_centro\"\n id = db.Column(\"id\", db.Integer, primary_key=True)\n nome = db.Column(\"nome\", db.Unicode, unique=True)\n dtaalt = db.Column(\"dtaalt\", db.DateTime)\n codpesalt = db.Column(\"codpesalt\", db.Integer)\n\n \n def __init__(self, nome, dtaalt, codpesalt):\n self.nome = nome\n self.dtaalt = dtaalt\n self.codpesalt = codpesalt\n","sub_path":"arquivoscsv/ext/site/model/Sub_Centro.py","file_name":"Sub_Centro.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"477963510","text":"import Queue\nimport copy\nimport threading\nimport time\nfrom swost.transmissionmodel import TransmissionModel\n\n__author__ = 'frituurpan'\n\n\"\"\"\nReads the serial buffer, and parses the contents if the message is complete\nSends signal to maincontroller afterwards\n\nNeeds own thread for monitoring the buffer\n\"\"\"\n\n\nclass SerialParser(threading.Thread):\n\n serialData = -1\n serialBuffer = -1\n\n queueArray = []\n completeTransmissions = []\n\n observers = []\n\n config = ''\n\n def __init__(self, serial_buffer, config):\n super(SerialParser, self).__init__()\n self.serialBuffer = serial_buffer\n self.config = config\n\n def run(self):\n while True:\n try:\n var = self.serialBuffer.queue.get(False) # try to fetch a value from queue\n except Queue.Empty:\n time.sleep(0.1)\n pass # if it is empty, do nothing\n else:\n var_cpy = copy.deepcopy(var)\n del var\n self.queueArray.append(var_cpy)\n for row in self.queueArray:\n if row == '!':\n self.move_queue_to_transmissions()\n self.notify_observers()\n\n def get_serial_buffer(self):\n \"\"\"\n :rtype: SerialBuffer\n \"\"\"\n return self.serialBuffer\n\n def move_queue_to_transmissions(self):\n transmissions = self.get_transmissions()\n for transmission in transmissions:\n transmission_object = TransmissionModel(transmission)\n transmission_object.set_timestamp(self.get_config().get_current_timezone_stamp())\n self.completeTransmissions.append(transmission_object)\n\n def get_completed_transmissions(self):\n return self.completeTransmissions\n\n def get_transmissions(self):\n queue_array = copy.deepcopy(self.queueArray)\n transmissions = [queue_array[:21]]\n del self.queueArray[:21]\n return transmissions\n\n def get_config(self):\n \"\"\"\n :rtype: SwostConfig\n \"\"\"\n return self.config\n\n @staticmethod\n def shift(key, array):\n \"\"\"\n Shift x elements of the beginning of the array\n \"\"\"\n return array[:+key]\n\n def register_observer(self, observer):\n self.observers.append(observer)\n\n def notify_observers(self):\n for observer in self.observers:\n observer.notify()\n","sub_path":"swost/serialparser.py","file_name":"serialparser.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"410406896","text":"\n'''\nObjective: \nTo scrap data from wikipedia based on list of topics or csv (to be uncommented).\nRun from the root\n$ python ./build_wiki_data/scripts/1_scrape.py\n$ python ROOT_DIR/WIKI_DIR/SCRIPTS_DIR/filename.py\n\n'''\n\n### GET PATHS FROM UNIVERSAL CONFIG\n\nimport configparser\n\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nROOT_BASE_DIR_PATH = config['ROOT_PATH']['basedir']\nWIKI_BASE_DIR_PATH = ROOT_BASE_DIR_PATH + config['WIKI_PATHS']['basedir']\nWIKI_DATASTORE_PATH = WIKI_BASE_DIR_PATH + config['WIKI_PATHS']['datastoredir']\nSCRAPPED_PATH = WIKI_DATASTORE_PATH + config['WIKI_PATHS']['scrapped']\nPARSED_PATH = WIKI_DATASTORE_PATH + config['WIKI_PATHS']['parsed']\nSTRUCTURED_PATH = WIKI_DATASTORE_PATH + config['WIKI_PATHS']['structured']\n\n###################\n\n# import the libraries\n\nimport wikipediaapi\n\nimport json\n\nimport pandas as pd\n\nimport os\n\nwiki_wiki = wikipediaapi.Wikipedia(language='en', extract_format=wikipediaapi.ExtractFormat.WIKI)\n\nsect = []\n\n# utility function for sections tree\ndef arrange_sections(sections,level=0): \n \n for s in sections: \n \n sect.append({str((level + 1)) : s.title}) \n \n #print(\"%s: %s\" % (str((level + 1)), s.title)) \n arrange_sections(s.sections, level + 1)\n \n \n# Please update all the tags you want to scrap for \n\ntopics = [\"Machine_learning\",\"Python_(programming_language)\",\"Data_science\",\"Reinforcement_learning\",\"Artificial_intelligence\"]\n\n# alternative code - read from csv\n#filename = WIKI_DATASTORE_PATH + \"XYZ.csv\" # place the name of the CSV to be scrapped\n\n\n#tags_df = pd.read_csv(filename)\n#topics = list(tags_df['title'])\n\n\n\n# Scrap all tags one by one and create JSON for each\n\n\nfor topic in topics:\n\n pg = wiki_wiki.page(topic)\n \n sect = []\n \n if pg.exists(): # if the page is found \n\n content = dict()\n \n # collect topic contents\n\n\n content['url'] = pg.fullurl\n\n content['tag'] = topic \n \n arrange_sections(pg.sections) \n \n content['sections'] = sect\n \n content['fulltext'] = pg.text\n \n # create a topic JSON\n \n # store it in data folder\n \n filename = SCRAPPED_PATH + topic + \".json\" \n \n # write the content of the topic in the JSON\n \n with open(filename, 'w') as fp:\n json.dump(content, fp)\n print(\"Scrapped data at \",filename)\n\n\n \n\n\n\n \n \n\n \n \n \n\n","sub_path":"build_wiki_data/scripts/1_scrape_original.py","file_name":"1_scrape_original.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"253891643","text":"\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nclass Pagination:\n\n def PaginatorManager(self, request, queryset):\n page = request.GET.get('page', 1)\n paginator = Paginator(queryset, 10)\n max_index = len(paginator.page_range)\n current_page = int(page) if page else 1\n page_numbers_range = 5 # Display only 5 page numbers\n start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range\n end_index = start_index + page_numbers_range\n\n if end_index >= max_index:\n end_index = max_index\n\n page_range = paginator.page_range[start_index:end_index]\n print(start_index, end_index)\n try:\n queryset = paginator.page(page)\n except PageNotAnInteger:\n queryset = paginator.page(1)\n except EmptyPage:\n queryset = paginator.page(paginator.num_pages)\n\n return page_range, queryset\n","sub_path":"docker_django_base/django_project/django_app/Controller/Pagination.py","file_name":"Pagination.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233061878","text":"#!/usr/bin/env python3\n\n# 20.py\n#\n# python-training/www.practicepython.org (c) 2017 by Franco Masotti\n# \n#\n# python-training/www.practicepython.org is licensed under a\n# Creative Commons Attribution 4.0 International License.\n#\n# You should have received a copy of the license along with this\n# work. If not, see .\n\n# Write a function that takes an ordered list of numbers (a list where the\n# elements are in order from smallest to largest) and another number. The\n# function decides whether or not the given number is inside the list and\n# returns (then prints) an appropriate boolean.\n# Extras: Use binary search.\n\nimport math\n\n# No guarantee for this to work if the test is changed.\n# What's more is that it does not work for duplicates.\ndef get_excluded_list(list):\n excluded = []\n\n for element in list:\n excluded.append((element*11) - 7)\n\n return excluded\n\ndef bin_search(list,min,max,key):\n if (min <= max):\n mid = math.floor((min+max) / 2)\n\n if key == list[mid]:\n return True\n elif key > list[mid]:\n # We have already examined mid so we can exclude it from the next\n # searches.\n return bin_search(list,mid+1,max,key)\n elif key < list[mid]:\n return bin_search(list,min,mid-1,key)\n else:\n return False\n\ndef bin_search_iterative(list,key):\n min = 0\n max = len(list) - 1\n while min <= max:\n mid = math.floor((min+max) / 2)\n if key == list[mid]:\n return True\n elif key > list[mid]:\n min = mid+1\n elif key < list[mid]:\n max = mid-1\n\n return False\n\n# Linear search in python\ndef linear_search_py(list,key):\n return list.count(key) >= 1\n\ndef linear_search(list,key):\n for e in list:\n if e == key:\n return True\n return False\n\ndef test():\n test_list = [2,3,5,7,11,13,17,19,23]\n min = 0\n max = len(test_list) - 1\n\n # Sort in case someones edits it. If it's not sorted bin search will fail.\n test_list.sort()\n\n for k in test_list:\n assert bin_search(test_list,min,max,k)\n assert bin_search_iterative(test_list,k)\n assert linear_search(test_list,k)\n assert linear_search_py(test_list,k)\n for k in get_excluded_list(test_list):\n assert not bin_search(test_list,min,max,k)\n assert not bin_search_iterative(test_list,k)\n assert not linear_search(test_list,k)\n assert not linear_search_py(test_list,k)\n\n print (\"All tests passed\")\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"www.practicepython.org/20.py","file_name":"20.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"322548999","text":"#shape.py\n\"\"\"A collection of functions\n for printing basic shapes,\n\"\"\"\nCHAR='*'\ndef rectangle(height,width):\n \"\"\"print a rectangle.\"\"\"\n for row in range(height):\n for col in range(width):\n print(CHAR, end=' ')\n print()\ndef square(side):\n \"\"\"Pprint a square\"\"\"\n rectangle(side, side)\ndef triangle(height):\n \"\"\"ptrints a right triangle\"\"\"\n for row in range(height):\n for col in range(1,row+2):\n print(CHAR, end=' ')\n print()\n\nif __name__ == '__main__':\n rectangle(2,3)","sub_path":"shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"452162418","text":"import sys\nimport time\nimport datetime\nfrom pymongo import MongoClient\n\n\nclass ThaiTwitterMongoSuite:\n\n def __init__(self, database, collection, server='localhost', server_port=27017):\n client = MongoClient(server, server_port)\n db = client[database]\n self.__collection = db[collection]\n self.__retweets = self._Retweets(self.__collection)\n self.__tweets = self._Tweets(self.__collection)\n\n @property\n def collection(self):\n return self.__collection\n\n @property\n def retweets(self):\n return self.__retweets\n\n @property\n def tweets(self):\n return self.__tweets\n\n class _Tweets:\n\n def __init__(self, collection):\n self.__collection = collection\n self.__filter = self._Filter()\n\n @property\n def filter(self):\n return self.__filter\n\n @staticmethod\n def __convert_returning_fields(returning_fields):\n if returning_fields is None:\n return {}\n else:\n fields = {}\n for returning_field in returning_fields:\n fields[returning_field] = 1\n return fields\n\n def find(self, query=None, returning_fields=None):\n if query is None:\n query = {}\n fields = self.__convert_returning_fields(returning_fields)\n return self.__collection.find(query, fields)\n\n def all(self, returning_fields=None):\n fields = self.__convert_returning_fields(returning_fields)\n return self.__collection.find({}, fields)\n\n def count(self, query=None):\n if query is None:\n query = {}\n return self.__collection.find(query).count()\n\n def insert(self, tweets):\n out_tweets = []\n for org_tweet in tweets:\n try:\n tweet = org_tweet._json\n except:\n tweet = org_tweet\n\n tm = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))\n tweet['created_at'] = datetime.datetime(int(tm[0:4]), int(tm[5:7]), int(tm[8:10]), int(tm[11:13]),\n int(tm[14:16]), int(tm[17:19]))\n out_tweets.append(tweet)\n\n result = self.__collection.insert_many(out_tweets)\n sys.stdout.write('ThaiTwitterMongo > Inserted {:d} records'.format(len(result.inserted_ids)))\n\n class _Filter:\n\n @staticmethod\n def period(start_datetime, end_datetime):\n return {'created_at': {'$gte': start_datetime, '$lte': end_datetime}}\n\n class _Retweets:\n\n def __init__(self, collection):\n self.__collection = collection\n self.user = self._User(collection)\n\n class _User:\n\n def __init__(self, collection):\n self.__collection = collection\n\n def all(self):\n q_users = self.__collection.find({},\n {'user.id': 1, 'user.screen_name': 1, 'retweeted_status.user.id': 1,\n 'retweeted_status.user.screen_name': 1})\n all_users = dict()\n for q_user in q_users:\n user_source = q_user['user']\n if user_source['screen_name'] not in all_users:\n all_users[user_source['screen_name']] = {'id': user_source['id']}\n\n if 'retweeted_status' in q_user:\n user_target = q_user['retweeted_status']['user']\n if user_target['screen_name'] not in all_users:\n all_users[user_target['screen_name']] = {'id': user_target['id']}\n return all_users\n\n def in_degrees(self, sort=False, in_degree_threshold=1):\n q_users = self.__collection.aggregate([\n {'$group':\n {'_id': '$retweeted_status.user.screen_name', 'id': {'$first': '$retweeted_status.user.id'},\n 'in_degree': {'$sum': 1}}\n }, {'$sort': {'in_degree': -1}}\n ])\n\n users = []\n users_dict = set()\n for q_user_target in q_users:\n if q_user_target['in_degree'] >= in_degree_threshold:\n if str(q_user_target['id']) != 'None':\n users.append(\n (str(q_user_target['_id']), str(q_user_target['id']), q_user_target['in_degree']))\n users_dict.add(q_user_target['_id'])\n\n if in_degree_threshold == 0:\n q_users = self.__collection.find({}, {'user.id': 1, 'user.screen_name': 1})\n for q_user_source in q_users:\n user_source = q_user_source['user']\n if user_source['screen_name'] not in users_dict:\n users.append((str(user_source['screen_name']), str(user_source['id']), 0))\n\n if sort:\n users.sort(key=lambda tup: tup[1], reverse=True)\n\n return users\n\n def retweet_edges(self, users_in_degree=None):\n q_tweets = self.__collection.find({'retweeted_status': {'$exists': True}},\n {'user.id': 1,\n 'user.screen_name': 1,\n 'retweeted_status.user.id': 1,\n 'retweeted_status.user.screen_name': 1\n })\n\n if users_in_degree is not None:\n users_in_degree_dict = dict()\n for u in users_in_degree:\n users_in_degree_dict[u[0]] = u[1]\n\n structured_retweet_users = dict()\n for q_tweet in q_tweets:\n user_target = q_tweet['retweeted_status']['user']['screen_name']\n user_source = q_tweet['user']['screen_name']\n\n if users_in_degree is None or (\n user_source in users_in_degree_dict and user_target in users_in_degree_dict):\n if user_target not in structured_retweet_users:\n structured_retweet_users[user_target] = dict()\n structured_retweet_users[user_target][user_source] = 1\n else:\n if user_source in structured_retweet_users[user_target]:\n structured_retweet_users[user_target][user_source] += 1\n else:\n structured_retweet_users[user_target][user_source] = 1\n\n retweet_edges = []\n for user_target in structured_retweet_users:\n for user_source in structured_retweet_users[user_target]:\n retweet_edges.append(\n (user_source, user_target, structured_retweet_users[user_target][user_source]))\n return retweet_edges\n","sub_path":"mongo/suite/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":7339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"260414719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 12:47:03 2019\n\n@author: adhamlin\n\"\"\"\n\n\ndef checkio(*args):\n \"\"\"\n Find the difference between the maximum and minimum element.\n Input:\n An arbitrary number of arguments as numbers (int, float).\n Output:\n The difference between maximum and minimum as a number (int, float).\n \"\"\"\n\n if not args:\n return 0\n else:\n smallest = min(args)\n largest = max(args)\n diff = largest - smallest\n return round(diff, 3)\n\n\n# checkio(1, 2, 3), 2, 3), \"3-1=2\"\n# checkio(5, -5), 10, 3), \"5-(-5)=10\"\n# checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), \"10.2-(-2.2)=12.4\"\n# checkio(), 0, 3)\n","sub_path":"Elementary/most_numbers.py","file_name":"most_numbers.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"17852687","text":"from mqttclient import MQTTClient\nfrom board import SDA, SCL, A9, A8, A7, A6, ADC0, ADC3, ADC6, A10\nfrom machine import I2C, Pin, deepsleep, ADC, PWM\nimport time\nimport network\nimport sys\n\n\ndef movementArray(start, end, increment):\n array = []\n while start < end:\n array.append(start)\n start += increment\n\n return array\ninShade = 200 #threshold value to determine in shade or not\nzeroDegrees = 5\noneeightyDegrees = 9.8\nmovementDelay = 0.1\ndutytodegree = 0.076\nadjustmentIncrement = 0.1# 0.076 is roughyl one degree\nmovementArr = movementArray(zeroDegrees, oneeightyDegrees, dutytodegree)\np1 = Pin(A10, Pin.OUT)\np2 = Pin(A9, Pin.OUT)\ntop = PWM(p1, duty = 7.5, freq = 50)\nbottom = PWM(p2, duty = 7.5, freq = 50)\ntime.sleep(0.1)\n\nlight1 = ADC(Pin(ADC0))\nlight2 = ADC(Pin(ADC3))\nlight3 = ADC( Pin (ADC6))\nlight1.atten(ADC.ATTN_6DB)\nlight2.atten(ADC.ATTN_6DB)\nlight3.atten(ADC.ATTN_6DB)\n\nxLightReading = light1.read()\nyLightReading = light2.read()\nmiddleLightReading = light3.read()\ndef moveTo(servo, start, end):\n if start < end:\n while start < end:\n servo.duty(start)\n start += dutytodegree\n time.sleep(0.1)\n else:\n while start > end:\n servo.duty(start)\n start -= dutytodegree\n time.sleep(0.1)\n\n\nprint('AutoHome Start')\nxLightReadings = dict()\nyLightReadings1 = dict()\nyLightReadings2 = dict()\nyLightReadings3 = dict()\nmoveTo(top, top.duty(), movementArr[0])\nfor i in movementArr:#Assign a light reading to each position on the servo\n\n top.duty(i)\n time.sleep(movementDelay)\n xLightReadings[i] = light1.read() + light2.read() + light3.read()\n print(xLightReadings[i])\nprint( max(xLightReadings))\nmoveTo(top, top.duty(), max(xLightReadings, key=xLightReadings.get)) #move to the max light sensor reading in the x direction\nmoveTo(bottom, bottom.duty(), movementArr[0])\nfor i in movementArr:\n bottom.duty(i)\n time.sleep(movementDelay)\n yLightReadings1[i] = light1.read()\n yLightReadings2[i] = light2.read()\n yLightReadings3[i] = light3.read()\n\nmoveTo(bottom, bottom.duty(), (max(yLightReadings1, key= yLightReadings1.get ) + max(yLightReadings2, key= yLightReadings2.get ) + max(yLightReadings3, key= yLightReadings3.get )) / 3.0 ) #move to the max sensor reading inthe y direction\n#inShade =( max(xLightReadings, key=xLightReadings.get) + max(yLightReadings, key=yLightReadings.get) ) / 2 - 100 if ( max(xLightReadings, key=xLightReadings.get) + max(yLightReadings, key=yLightReadings.get) ) / 2 - 100 >= 107 else 107\n","sub_path":"AutohomeProcedure.py","file_name":"AutohomeProcedure.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"342724297","text":"from ctypes import windll\nfrom fnmatch import fnmatch\nfrom shutil import copy2\nimport argparse\nimport win32api\nimport string\nimport time\nimport os\n\n\n# To-Do\n# \n# - Implement file header recognition rather than file extension, in order to recover hidden files.\n# - File size limits, to prevent freezing.\n# - Threading, -//-.\n# - Date/time information regarding dump folders.\n\ndef get_drives():\n\tdrives = []\n\tbitmask = windll.kernel32.GetLogicalDrives()\n\t#print(bin(bitmask))\n\tfor letter in string.ascii_uppercase:\n\t\tif bitmask & 1:\n\t\t\tdrives.append(letter)\n\t\tbitmask >>= 1\n\treturn drives\n\ndef get_driveinfo(driveName):\n\treturn win32api.GetVolumeInformation(driveName)\n\t\ndef scan_files(target_drive):\n\t# Target pattern(s)\n\tpattern = [\"*.txt\", \"*.xsl\"]\n\t\n\ttotal_num_files = 0\n\tsuccessful_copies = 0\n\t\n\tprint(\"Looking in:\\n\" + str(target_drive))\n\tprint(\"Looking for:\")\n\tprint(pattern)\n\tfor path, subdirs, files in os.walk(target_drive):\n\t\tfor name in files:\n\t\t\t# Loop through each pattern\n\t\t\tfor subPattern in pattern:\n\t\t\t\tif fnmatch(name, subPattern):\n\t\t\t\t\t# Debugging\n\t\t\t\t\t#print(os.path.join(path, name))\n\t\t\t\t\t\n\t\t\t\t\ttotal_num_files += 1\t\t\t\t\n\t\t\t\t\tsuccessful_copies += dump_file(os.path.join(path, name), get_driveinfo(e + \":\\\\\")[0])\n\t\n\tprint(\"Total files found: \" + str(total_num_files))\n\tprint(\"Total files successfully copied: \" + str(successful_copies))\n\t\ndef dump_file(target_file, target_folder):\n\tprint(\"Will copy file: \" + target_file)\n\tprint(\".. to folder: \" + \"dmp_\" + target_folder)\n\t\n\ttry:\n\t\tcopy2(target_file, \"dmp_\" + target_folder)\n\texcept:\n\t\treturn 0\n\treturn 1\n\t\nif __name__ == '__main__':\n\t# Introduction\n\tprint(\"\\nusbrip - Recover files from plugged in drives\\n\\n\")\n\t\n\t# Command line arguments\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-s\", \"--size\", help=\"Maximum file size\")\n\tparser.add_argument(\"-f\", \"--filter\", nargs=\"*\", help=\"File extension filter\")\n\t\n\targs = parser.parse_args()\n\tprint(\"Size {} Filter {}\".format(args.size, args.filter))\n\t\n\n\tbefore = set(get_drives())\n\tprint(\"Original state found .. Looking for new drives\\n\")\n\t\n\twhile True:\n\t\tprint(\"Looking .. Original: \" + str(before) + \"\\n\")\n\t\ttime.sleep(5)\n\t\t\n\t\tafter = set(get_drives())\n\t\tprint(\"After: \" + str(after))\n\t\tdrives = after - before\n\n\t\tif (after != before):\n\t\t\tif (drives == set()):\n\t\t\t\tprint(\"Drive was removed\")\n\t\t\telse:\n\t\t\t\tprint(\"Found a new drive - \" + str(drives))\n\t\t\t\tfor e in drives:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tdrive_info = get_driveinfo(e + \":\\\\\")\n\t\t\t\t\t\t# Debugging\n\t\t\t\t\t\tprint(drive_info[0])\n\t\t\t\t\t\t\n\t\t\t\t\t\tprint(\"Attempting to create a folder for \" + drive_info[0])\n\t\t\t\t\t\tif not os.path.exists(\"dmp_\" + drive_info[0]):\n\t\t\t\t\t\t\tos.makedirs(\"dmp_\" + drive_info[0])\n\t\t\t\t\t\t\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(\"Could not get drive info\\n\")\n\t\t\t\t\tscan_files(e + \":\\\\\")\n\t\t\t\t\t\n\t\t\tbefore = after","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"404285149","text":"#!/usr/bin/env python3\r\n\r\n\"\"\"\r\n2D Controller Class to be used for the CARLA waypoint follower demo.\r\n\"\"\"\r\n\r\nimport cutils\r\nimport numpy as np\r\nimport configparser\r\nimport os\r\nimport pid\r\nimport pure_pursuit as pp\r\nimport stanley as st\r\n\r\nclass Controller2D(object):\r\n def __init__(self, waypoints):\r\n self.vars = cutils.CUtils()\r\n self._current_x = 0\r\n self._current_y = 0\r\n self._current_yaw = 0\r\n self._current_speed = 0\r\n self._desired_speed = 0\r\n self._current_frame = 0\r\n self._current_timestamp = 0\r\n self._start_control_loop = False\r\n self._set_throttle = 0\r\n self._set_brake = 0\r\n self._set_steer = 0\r\n self._waypoints = waypoints\r\n self._conv_rad_to_steer = 180.0 / 70.0 / np.pi\r\n self._pi = np.pi\r\n self._2pi = 2.0 * np.pi\r\n\r\n # Finding configuration set for each controller in config file\r\n config = configparser.ConfigParser()\r\n config.read(os.path.join(\r\n os.path.dirname(os.path.realpath(__file__)), 'controller.cfg'))\r\n\r\n # Configuration for longitudinal control\r\n long_conf = config['long control']\r\n self.long_contr_sampletime = float(long_conf.get('sampletime', 100))/1000 # in ms\r\n self.long_pid = pid.PID(long_conf)\r\n\r\n # Configuration for lateral control\r\n self.lat_contr = config[\"lateral controller\"].get(\"controller\",'pure pursuit')\r\n lat_conf = config[self.lat_contr] \r\n\r\n if self.lat_contr == 'pure pursuit':\r\n self.lat_pp = pp.PurePursuit(lat_conf)\r\n elif self.lat_contr == 'stanley control':\r\n self.lat_st = st.Stanley(lat_conf)\r\n \r\n\r\n def update_values(self, x, y, yaw, speed, timestamp, frame):\r\n self._current_x = x\r\n self._current_y = y\r\n self._current_yaw = yaw\r\n self._current_speed = speed\r\n self._current_timestamp = timestamp\r\n self._current_frame = frame\r\n if self._current_frame:\r\n self._start_control_loop = True\r\n\r\n def update_desired_speed(self):\r\n min_idx = 0\r\n min_dist = float(\"inf\")\r\n desired_speed = 0\r\n for i in range(len(self._waypoints)):\r\n dist = np.linalg.norm(np.array([\r\n self._waypoints[i][0] - self._current_x,\r\n self._waypoints[i][1] - self._current_y]))\r\n if dist < min_dist:\r\n min_dist = dist\r\n min_idx = i\r\n if min_idx < len(self._waypoints)-1:\r\n desired_speed = self._waypoints[min_idx][2]\r\n else:\r\n desired_speed = self._waypoints[-1][2]\r\n self._desired_speed = desired_speed\r\n\r\n def update_waypoints(self, new_waypoints):\r\n self._waypoints = new_waypoints\r\n\r\n def get_commands(self):\r\n return self._set_throttle, self._set_steer, self._set_brake\r\n\r\n def set_throttle(self, input_throttle):\r\n # Clamp the throttle command to valid bounds\r\n throttle = np.fmax(np.fmin(input_throttle, 1.0), 0.0)\r\n self._set_throttle = throttle\r\n\r\n def set_steer(self, input_steer_in_rad):\r\n # Covnert radians to [-1, 1]\r\n input_steer = self._conv_rad_to_steer * input_steer_in_rad\r\n\r\n # Clamp the steering command to valid bounds\r\n steer = np.fmax(np.fmin(input_steer, 1.0), -1.0)\r\n self._set_steer = steer\r\n\r\n def set_brake(self, input_brake):\r\n # Clamp the steering command to valid bounds\r\n brake = np.fmax(np.fmin(input_brake, 1.0), 0.0)\r\n self._set_brake = brake\r\n\r\n def update_controls(self):\r\n ######################################################\r\n # RETRIEVE SIMULATOR FEEDBACK\r\n ######################################################\r\n x = self._current_x\r\n y = self._current_y\r\n yaw = self._current_yaw\r\n v = self._current_speed\r\n self.update_desired_speed()\r\n v_desired = self._desired_speed\r\n t = self._current_timestamp\r\n waypoints = self._waypoints\r\n throttle_output = 0\r\n steer_output = 0\r\n brake_output = 0\r\n\r\n ######################################################\r\n ######################################################\r\n # MODULE 7: DECLARE USAGE VARIABLES HERE\r\n ######################################################\r\n ######################################################\r\n \"\"\"\r\n Use 'self.vars.create_var(, )'\r\n to create a persistent variable (not destroyed at each iteration).\r\n This means that the value can be stored for use in the next\r\n iteration of the control loop.\r\n\r\n Example: Creation of 'v_previous', default value to be 0\r\n self.vars.create_var('v_previous', 0.0)\r\n\r\n Example: Setting 'v_previous' to be 1.0\r\n self.vars.v_previous = 1.0\r\n\r\n Example: Accessing the value from 'v_previous' to be used\r\n throttle_output = 0.5 * self.vars.v_previous\r\n \"\"\"\r\n\r\n self.vars.create_var('time_prev_long', t) # storing previous time of control loop\r\n # self.vars.create_var('time_prev_lat', t)\r\n\r\n # Skip the first frame to store previous values properly\r\n if self._start_control_loop:\r\n \"\"\"\r\n Controller iteration code block.\r\n\r\n Controller Feedback Variables:\r\n x : Current X position (meters)\r\n y : Current Y position (meters)\r\n yaw : Current yaw pose (radians)\r\n v : Current forward speed (meters per second)\r\n t : Current time (seconds)\r\n v_desired : Current desired speed (meters per second)\r\n (Computed as the speed to track at the\r\n closest waypoint to the vehicle.)\r\n waypoints : Current waypoints to track\r\n (Includes speed to track at each x,y\r\n location.)\r\n Format: [[x0, y0, v0],\r\n [x1, y1, v1],\r\n ...\r\n [xn, yn, vn]]\r\n Example:\r\n waypoints[2][1]: \r\n Returns the 3rd waypoint's y position\r\n\r\n waypoints[5]:\r\n Returns [x5, y5, v5] (6th waypoint)\r\n \r\n Controller Output Variables:\r\n throttle_output : Throttle output (0 to 1)\r\n steer_output : Steer output (-1.22 rad to 1.22 rad)\r\n brake_output : Brake output (0 to 1)\r\n \"\"\"\r\n\r\n ######################################################\r\n ######################################################\r\n # MODULE 7: IMPLEMENTATION OF LONGITUDINAL CONTROLLER HERE\r\n ######################################################\r\n ######################################################\r\n \"\"\"\r\n Implement a longitudinal controller here. Remember that you can\r\n access the persistent variables declared above here. For\r\n example, can treat self.vars.v_previous like a \"global variable\".\r\n \"\"\" \r\n # Change these outputs with the longitudinal controller. Note that\r\n # brake_output is optional and is not required to pass the\r\n # assignment, as the car will naturally slow down over time.\r\n\r\n if (t - self.vars.time_prev_long >= self.long_contr_sampletime):\r\n pid_output = self.long_pid.compute(v, v_desired) # input, setpoint\r\n throttle_output = np.fmax(np.fmin(pid_output,1.0),0.0) # limiting throttle between 0 and 1\r\n # brake_output = abs(np.fmax(np.fmin(pid_output,0.0),-1.0)) # converting pid output of -1 to 0 to 0 to 1 for brake\r\n # print (pid_output)\r\n self.vars.time_prev_long = t \r\n\r\n ######################################################\r\n ######################################################\r\n # MODULE 7: IMPLEMENTATION OF LATERAL CONTROLLER HERE\r\n ######################################################\r\n ######################################################\r\n \"\"\"\r\n Implement a lateral controller here. Remember that you can\r\n access the persistent variables declared above here. For\r\n example, can treat self.vars.v_previous like a \"global variable\".\r\n \"\"\"\r\n if (self.lat_contr == 'pure pursuit'):\r\n steer_output = self.lat_pp.compute(v, x, y, yaw, waypoints)\r\n elif (self.lat_contr == 'stanley control'):\r\n steer_output = self.lat_st.compute(waypoints, x, y, yaw, v)\r\n\r\n ######################################################\r\n # SET CONTROLS OUTPUT\r\n ######################################################\r\n self.set_throttle(throttle_output) # in percent (0 to 1)\r\n self.set_steer(steer_output) # in rad (-1.22 to 1.22)\r\n self.set_brake(brake_output) # in percent (0 to 1)\r\n\r\n ######################################################\r\n ######################################################\r\n # MODULE 7: STORE OLD VALUES HERE (ADD MORE IF NECESSARY)\r\n ######################################################\r\n ######################################################\r\n \"\"\"\r\n Use this block to store old values (for example, we can store the\r\n current x, y, and yaw values here using persistent variables for use\r\n in the next iteration)\r\n \"\"\"\r\n # self.vars.v_previous = v # Store forward speed to be used in next step\r\n # self.vars.err_prev = error_vel\r\n # self.vars.error_pos_prev = error_pos\r\n","sub_path":"Intro_to_self_driving_cars/controller2d.py","file_name":"controller2d.py","file_ext":"py","file_size_in_byte":10715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"451082414","text":"import unittest\nfrom src import manager as m\nfrom src.helper import result_helper as rh\nfrom data import data as data\n\n\nclass TestsEngie20202T(unittest.TestCase):\n\n filename = None\n manager_pypdf2 = None\n\n @classmethod\n def setUpClass(cls):\n cls.filename = 'engie_2020_2T.pdf'\n cls.manager_pypdf2 = m.manager([cls.filename], 'pypdf2')\n\n @classmethod\n def tearDownClass(cls):\n cls.filename = None\n cls.manager_pypdf2 = None\n\n def test_lucro_liquido_monetary(self):\n lucro_liquido_monetary_pypdf2 = self.manager_pypdf2.run_lucro_liquido_monetary()\n result_pypdf2 = lucro_liquido_monetary_pypdf2[self.filename]\n numbers_from_result_pypdf2 = rh.result_helper.get_numbers_as_list(result_pypdf2)\n\n self.assertEqual(len(result_pypdf2), 6, 'lucro líquido (R$): tamanho resultado (pypdf2)')\n self.assertIn(data.LUCRO_LIQUIDO[self.filename], numbers_from_result_pypdf2, 'lucro líquido (R$): valor (pypdf2)')\n\n def test_lucro_liquido_number(self):\n lucro_liquido_number_pypdf2 = self.manager_pypdf2.run_lucro_liquido_number()\n result_pypdf2 = lucro_liquido_number_pypdf2[self.filename]\n\n self.assertEqual(len(result_pypdf2), 0, 'lucro líquido (número após conjunto de busca): tamanho resultado')\n\n def test_patrimonio_liquido_monetary(self):\n patrimonio_liquido_monetary = self.manager_pypdf2.run_patrimonio_liquido_monetary()\n result = patrimonio_liquido_monetary[self.filename]\n\n self.assertEqual(len(result), 0, 'patrimônio líquido (R$): tamanho resultado')\n\n def test_patrimonio_liquido_number(self):\n patrimonio_liquido_number_pypdf2 = self.manager_pypdf2.run_patrimonio_liquido_number()\n result_pypdf2 = patrimonio_liquido_number_pypdf2[self.filename]\n\n self.assertEqual(len(result_pypdf2), 0,\n 'patrimônio líquido (número após conjunto de busca): tamanho resultado (pypdf2)')\n\n def test_roe_monetary(self):\n roe_monetary = self.manager_pypdf2.run_roe_monetary()\n result = roe_monetary[self.filename]\n\n self.assertEqual(len(result), 0, 'ROE (R$): tamanho resultado')\n\n def test_roe_number(self):\n roe_number = self.manager_pypdf2.run_roe_number()\n result = roe_number[self.filename]\n\n self.assertEqual(len(result), 0, 'ROE (número após conjunto de busca): tamanho resultado')\n\n def test_roe_calculate(self):\n roe_calculate_pypdf2 = self.manager_pypdf2.run_calculate_roe()\n result_pypdf2 = roe_calculate_pypdf2[self.filename]\n\n self.assertEqual(len(result_pypdf2), 0, 'ROE por cálculo: tamanho resultado (pypdf2)')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/reports/pypdf2/test_engie20202T.py","file_name":"test_engie20202T.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"56103596","text":"import cPickle\nimport logging\n\nfrom google.appengine.ext import ndb\n\nimport check_and_sendmail\n\n\nclass IPhoneStatus(ndb.Model):\n\n \"\"\"Models Virgin iPhone status.\"\"\"\n availableURLs = ndb.BlobProperty()\n date = ndb.DateTimeProperty(auto_now_add=True)\n\nENTITY_KEY = \"IPhoneStatus\"\n\n\nclass IPhoneRequestHandler(check_and_sendmail.RequestHandler):\n\n def __init__(self, request, response):\n super(IPhoneRequestHandler, self).__init__(request, response)\n\n self._available = []\n self._outofstock = []\n key = ndb.Key(IPhoneStatus, ENTITY_KEY)\n\n self._ndb_entity = key.get()\n if self._ndb_entity is None:\n self._ndb_entity = IPhoneStatus(key=key)\n\n def urls(self):\n return (\n \"https://www.virginmobile.com.au/Shop/iPhone-6-64GB-SpaceGry\",\n \"https://www.virginmobile.com.au/Shop/iPhone-6-64GB-Silver\",\n \"https://www.virginmobile.com.au/Shop/iPhone-6-64GB-Gold\",\n \"https://www.virginmobile.com.au/Shop/iPhone-6-Plus-64GB-Gold\",\n \"https://www.virginmobile.com.au/Shop/iPhone-6-Plus-64GB-SpaceGry\",\n \"https://www.virginmobile.com.au/Shop/iPhone-6-Plus-64GB-Silver\",\n #\"https://www.virginmobile.com.au/Shop/iPhone-6-16GB-SpaceGry\",\n )\n\n def onResult(self, result, url):\n if result.content.find(\"OUT OF STOCK\") >= 0:\n self._outofstock.append(url)\n else:\n self._available.append(url)\n\n def onEnd(self):\n availableLastCheck = self._ndb_entity.availableURLs\n if availableLastCheck is not None:\n availableLastCheck = cPickle.loads(availableLastCheck)\n else:\n availableLastCheck = []\n\n if self._available:\n availableMsg = \"AVAILABLE:
%s

\" % \"
\".join(\n self._available)\n self.response.write(availableMsg)\n logging.info(availableMsg)\n\n if self._outofstock:\n outofstockMsg = \"OUT OF STOCK:
%s

\" % \\\n \"
\".join(self._outofstock)\n self.response.write(outofstockMsg)\n logging.info(outofstockMsg)\n\n self._ndb_entity.availableURLs = cPickle.dumps(self._available)\n self._ndb_entity.put()\n\n newAvailable = [url for url in self._available\n if url not in availableLastCheck]\n notAvailable = [url for url in availableLastCheck\n if url not in self._available]\n logging.info(\"newAvailable: %s, notAvailable: %s\",\n newAvailable, notAvailable)\n\n if newAvailable or notAvailable:\n subject = \"Virgin iPhone 6+ stock update\"\n body = \"\"\"\n\t\t\tNew available:\\n %s\n\n\t\t\tNot available anymore: \\n %s\n\n\t\t\t\"\"\" % (\"\\n\".join( newAvailable ), \"\\n\".join( notAvailable ))\n return (subject, body)\n","sub_path":"virgin.py","file_name":"virgin.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"603070718","text":"import heapq\n\n\ndef run(start, heuristic, greedy=False):\n \"\"\"Run the a* algorithm\n\n :param start: Initial puzzle\n :param heuristic: Heuristic function that will be used to compute f scores\n :returns: Final puzzle, time complexity and space complexity\n :rtype: Puzzle, int, int\n\n \"\"\"\n start.apply_heuristic(heuristic)\n open_set = {start}\n closed_set = set()\n\n heap = []\n heapq.heappush(heap, (start.f_score, start))\n\n time_comp = 0\n space_comp = 0\n\n g_inc = int(not greedy)\n\n while open_set:\n _, e = heapq.heappop(heap)\n closed_set.add(e)\n if e.done():\n return e, time_comp, space_comp\n open_set.remove(e)\n for s in e.expand():\n if s not in closed_set:\n s.apply_heuristic(heuristic)\n s.g_score = e.g_score + g_inc\n if s not in open_set:\n open_set.add(s)\n space_comp = max(len(open_set), len(closed_set), space_comp)\n heapq.heappush(heap, (s.f_score, s))\n time_comp += 1\n return None, time_comp, space_comp\n","sub_path":"src/a_star.py","file_name":"a_star.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301109258","text":"\"\"\"\n1110. Delete Nodes And Return Forest\nGiven the root of a binary tree, each node in the tree has a distinct value.\n\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\n\nReturn the roots of the trees in the remaining forest. You may return the result in any order.\n\n \n\nExample 1:\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\"\"\"\n\n# bfs, took 20min to finish\n# Runtime: 60 ms, faster than 96.94% of Python3 online submissions for Delete Nodes And Return Forest.\n# Memory Usage: 14.4 MB, less than 100.00% of Python3 online submissions for Delete Nodes And Return Forest.\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 delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete)\n res = set([])\n res.add(root)\n deque = [root]\n while deque:\n node = deque.pop(0)\n if node.val in to_delete:\n if node in res:\n res.remove(node)\n if node.left:\n res.add(node.left)\n if node.right:\n res.add(node.right)\n \n if node.left:\n deque.append(node.left)\n if node.left.val in to_delete:\n node.left = None\n if node.right:\n deque.append(node.right)\n if node.right.val in to_delete:\n node.right = None\n return res","sub_path":"Widen/LC1110_Delete_Nodes_And_Return_Forest.py","file_name":"LC1110_Delete_Nodes_And_Return_Forest.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"534713322","text":"# -*- coding:utf-8 -*-\n\n\"\"\"use knn \"\"\"\nfrom scipy.spatial import distance\n\n\"\"\"计算两点距离\"\"\"\n\n\ndef euc(a, b):\n return distance.euclidean(a, b)\n\n\nclass ScrappyKNN():\n def fit(self, x_train, y_train):\n\n self.x_train = x_train\n self.y_train = y_train\n\n def predict(self, x_test):\n predict = []\n for row in x_test:\n label = self.closest(row)\n predict.append(label)\n return predict\n\n \"\"\"计算最近相邻点,row代表x,输出即为y\"\"\"\n\n def closest(self, row):\n best_dist = euc(row, self.x_train[0]) # 标记目前位置发现的最短距离,取第一个训练集为默认\n best_index = 0\n for i in range(1, len(self.x_train)):\n dist = euc(row, self.x_train[i]) # 计算每个训练集中点与训练集点的距离\n if dist < best_dist:\n best_dist = dist\n best_index = i\n return self.y_train[best_index]\n\n\nfrom sklearn import datasets\n\niris = datasets.load_iris()\n\nx = iris.data # features\ny = iris.target # label\n\n\"\"\"数据集被分成两部分,训练集和测试集\"\"\"\nfrom sklearn.cross_validation import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.5)\n\n\"\"\"使用自定义实现的KNN分类器\"\"\"\nmy_classifer = ScrappyKNN()\nmy_classifer.fit(x_train, y_train)\npredict = my_classifer.predict(x_test)\n\n\"\"\"使用测试集计算决策树分类器预测准确率\"\"\"\nfrom sklearn.metrics import accuracy_score\n\nprint(accuracy_score(y_test, predict))\n","sub_path":"google/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"615287170","text":"\"\"\"\nDjango settings for cahierdulogement project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\nADMINS = (\n ('Marc', 'marcwebbie@gmail.com'),\n)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ[\"SECRET_KEY\"]\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nALLOWED_HOSTS = ['.atonyx.com', '.atonyx.fr']\n\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'south',\n\n 'cahierdulogement.accounts',\n 'cahierdulogement.cahiers',\n 'cahierdulogement.utils',\n 'cahierdulogement.villes',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n)\n\nROOT_URLCONF = 'cahierdulogement.urls'\n\nWSGI_APPLICATION = 'cahierdulogement.wsgi.application'\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'fr-FR'\n\nTIME_ZONE = 'Europe/Paris'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n\n# /var/static/cahierdulogement/\nSTATIC_ROOT = \"/var/static/cahierdulogement/\"\nMEDIA_ROOT = os.environ.get('MEDIA_ROOT', os.path.join(BASE_DIR, 'media'))\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n MEDIA_ROOT,\n)\n\n\nLOGIN_URL = '/login/'\nLOGIN_REDIRECT_URL = \"/\"\n\n\n# EMAIL_HOST = 'smtp.gmail.com'\n# EMAIL_HOST_USER = 'clogement@gmail.com'\n# EMAIL_HOST_PASSWORD = os.environ.get[\"EMAIL_HOST_PASSWORD\"]\n# EMAIL_PORT = 587\n# EMAIL_USE_TLS = True\n\nSOUTH_TESTS_MIGRATE = False\n","sub_path":"cahierdulogement/settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"114341197","text":"import cv2\nimport time\nimport copy\nimport ocr\nimport pandas as pd\nstart_time = time.time()\n\ndef ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):\n\tdim = None\n\t(h, w) = image.shape[:2]\n\n\tif width is None and height is None:\n\t\treturn image\n\tif width is None:\n\t\tr = height / float(h)\n\t\tdim = (int(w * r), height)\n\telse:\n\t\tr = width / float(w)\n\t\tdim = (width, int(h * r))\n\n\treturn cv2.resize(image, dim, interpolation=inter)\n\n\n\ndef video_capture(url,f):\n\tcap = cv2.VideoCapture(url)\n\tcount = 0\n\tf_list = []\n\theight = 0\n\twidth = 0\n\twhile cap.isOpened():\n\t\tret,frame = cap.read()\n\t\tif ret == True:\n\n\t\t\tif(count%f==0):\n\t\t\t\tr_frame = ResizeWithAspectRatio(frame, height=1000)\n\t\t\t\tf_list.append(r_frame)\n\t\t\tcount = count + 1\n\t\t\tif cv2.waitKey(10) & 0xFF == ord('q'):\n\t\t\t\tbreak\n\t\telse:\n\t\t\tbreak\n\tcap.release()\n\treturn f_list\n\n\ndef video_generate(f_list,name,fps):\n\t(he, wi) = f_list[0].shape[:2]\n\tout = cv2.VideoWriter(name,0,fps, (wi,he))\n\tfor i in range(len(f_list)):\n\t\tout.write(f_list[i])\n\tout.release()\n\n\ndef live_detection(f_list):\n\timage_template1 = cv2.imread('image.png')\n\timage_template1 = cv2.cvtColor(image_template1, cv2.COLOR_BGR2GRAY)\n\tx_list = []\n\tvaluesl = []\n\tvalues = []\n\tc=0\n\tfor frame in f_list:\n\t\theight, width = frame.shape[:2]\n\t\tim = copy.copy(frame)\n\t\ttop_left_x,top_left_y = int(height * .8), int(width * 0)\n\t\tbottom_right_x,bottom_right_y = int(height*1), int(width*1)\n\n\t\tcv2.rectangle(frame, (top_left_y,top_left_x), (bottom_right_y,bottom_right_x), (127,50,127), 3)\n\t\tcropped = frame[top_left_x:bottom_right_x , top_left_y:bottom_right_y]\n\n\t\timage1 = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)\n\t\torb1 = cv2.ORB_create(1000, 1.2, 8, 15, 0,2)\n\t\tkp1, des1 = orb1.detectAndCompute(image1, None)\n\t\tkp2, des2 = orb1.detectAndCompute(image_template1, None)\n\t\tbf1 = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\t\tmatches1 = bf1.match(des1,des2)\n\t\tmatches1 = sorted(matches1, key=lambda val: val.distance)\n\t\tmatches1 = len(matches1)\n\t\tx = ''\n\t\toutput_string = str(matches1)\n\t\tcv2.putText(frame, output_string, (20,20), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)\n\t\tthreshold = 290\n\t\tif matches1 > threshold:\n\t\t\tx = 'L'\n\t\t\tcv2.putText(frame,'L',(140,20), cv2.FONT_HERSHEY_COMPLEX, 2 ,(255,0,0), 2)\n\t\t\tScore,Wicket,Overs,Bat1,Bat2,current = ocr.RunOcr(frame)\n\t\t\tvaluesl.append([Score,Wicket,Overs,Bat1,Bat2,current])\n\t\telse:\n\t\t\tx = 'R'\n\t\t\tcv2.putText(frame,'R',(140,20), cv2.FONT_HERSHEY_COMPLEX, 2 ,(0,0,255), 2)\n\n\t\tScore,Wicket,Overs,Bat1,Bat2,current = ocr.RunOcr(frame)\n\t\tvalues.append([x,Score,Wicket,Overs,Bat1,Bat2,current])\n\t\tc=c+1\n\t\tif(c%70==0):\n\t\t\tprint(c)\n\t\tx_list.append(frame)\n\treturn x_list, valuesl, values\n\n\nv_url = './video.avi'\nf_list = []\np_list = []\nvaluesl = []\nvalues = []\nf_list= video_capture(v_url,1)\nprint(len(f_list))\n\n\np_list, valuesl, values = live_detection(f_list)\n\ndf = pd.DataFrame(data=valuesl)\ndf.to_csv(\"./filel.csv\", sep=',',index=False)\n\ndf2 = pd.DataFrame(data=values)\ndf2.to_csv(\"./file.csv\", sep=',',index=False)\n\n#video_generate(f_list,'video_processed.avi',30)\n\ncv2.destroyAllWindows()\nprint(\"--- %s seconds ---\" % (time.time() - start_time))","sub_path":"OCR on cricket images/Data_collection.py","file_name":"Data_collection.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579150427","text":"#爬取起点网上面的书\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport sys\r\nimport threading\r\nclass download(object):\r\n def __init__(self):\r\n self.target = \"https://read.qidian.com/hankread/1016414271/79945909\"\r\n self.base_target = \"https://read.qidian.com/chapter/_Q3cDZ7Pr5CLTMDvzUJZaQ2/\"\r\n self.path = 'D:\\\\Python project\\\\爬虫\\\\爬取文字\\\\小说.txt'\r\n self.num = 151\r\n def get_tirtle(self,target,num):\r\n req = requests.get(url=target)\r\n html = req.text\r\n tirtle_bf = BeautifulSoup(html)\r\n tirtle1 = tirtle_bf.find_all('div',class_=\"text-head\")\r\n tirtle = tirtle1[num].text\r\n return tirtle\r\n def get_content(self,target,num):\r\n req = requests.get(url=target)\r\n html = req.text\r\n text_bf = BeautifulSoup(html)\r\n text1 = text_bf.find_all('div', class_=\"read-content j_readContent\")\r\n text = text1[num].text\r\n return text\r\n #def get_url(self):\r\n #return\r\n def write(self,tirtle,text,path):\r\n f = open(path,'a',encoding='utf-8')\r\n f.write(tirtle + '\\n')\r\n f.writelines(text)\r\nif __name__ == '__main__':\r\n spider = download()\r\n print('开始下载')\r\n for i in range(spider.num):\r\n spider.write(spider.get_tirtle(spider.target,i),spider.get_content(spider.target,i),spider.path)\r\n sys.stdout.write(\" 已下载:%.3f%%\" % float(i / spider.num) + '\\r')\r\n sys.stdout.flush()\r\n print('下载完成')","sub_path":"spider_content.py","file_name":"spider_content.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"282236880","text":"# Chapter 10: Creating Components and Extending Functionality\r\n# Recipe 3: Making a ToolWindow\r\n#\r\nimport wx\r\nimport wx.lib.pubsub as pubsub\r\n\r\n# message data will be tool id\r\nMSG_TOOL_CLICKED = ('toolwin', 'clicked')\r\n\r\nclass ToolWindow(wx.MiniFrame):\r\n def __init__(self, parent, rows=1, columns=0, title=''):\r\n style = wx.CAPTION|wx.SYSTEM_MENU|\\\r\n wx.SIMPLE_BORDER|wx.CLOSE_BOX\r\n super(ToolWindow, self).__init__(parent,\r\n title=title,\r\n style=style)\r\n\r\n # Attributes\r\n self.panel = ToolPanel(self, rows, columns)\r\n\r\n # Layout\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self.panel, 1, wx.EXPAND)\r\n self.SetSizer(sizer)\r\n\r\n def AddTool(self, id, bmp, helplbl=''):\r\n \"\"\"Add a tool to the window\"\"\"\r\n self.panel.AddTool(id, bmp, helplbl)\r\n self.Fit()\r\n\r\nclass ToolPanel(wx.Panel):\r\n \"\"\"Panel to hold the tools\"\"\"\r\n def __init__(self, parent, rows, columns):\r\n super(ToolPanel, self).__init__(parent)\r\n\r\n # Attributes\r\n self.sizer = wx.FlexGridSizer(rows, columns, 5, 5)\r\n\r\n # Setup\r\n self.SetSizer(self.sizer)\r\n\r\n # Event Handlers\r\n self.Bind(wx.EVT_BUTTON, self.OnButton)\r\n\r\n def AddTool(self, id, bmp, helplbl=''):\r\n tool = wx.BitmapButton(self, id, bmp)\r\n tool.SetToolTipString(helplbl)\r\n self.sizer.Add(tool)\r\n self.Layout()\r\n\r\n def OnButton(self, event):\r\n \"\"\"Notify clients when tool is clicked\"\"\"\r\n pubsub.Publisher.sendMessage(MSG_TOOL_CLICKED,\r\n event.GetId())\r\n\r\nclass EditorToolWindow(ToolWindow):\r\n def __init__(self, parent, rows, columns, title):\r\n ToolWindow.__init__(self, parent, rows, \r\n columns, title)\r\n\r\n # Setup\r\n for artid, tid in ((wx.ART_CUT, wx.ID_CUT),\r\n (wx.ART_COPY, wx.ID_COPY),\r\n (wx.ART_PASTE, wx.ID_PASTE),\r\n (wx.ART_UNDO, wx.ID_UNDO),\r\n (wx.ART_REDO, wx.ID_REDO)):\r\n bmp = wx.ArtProvider.GetBitmap(artid, wx.ART_MENU)\r\n self.AddTool(tid, bmp)\r\n\r\nclass ToolWindowApp(wx.App):\r\n def OnInit(self):\r\n self.frame = MainWindow(None,\r\n title=\"ToolWindow Recipe\")\r\n self.frame.CenterOnScreen()\r\n self.frame.Show()\r\n self.toolw = EditorToolWindow(None, rows=2, columns=3,\r\n title=\"Editor Commands\")\r\n # Position ToolWindow to right of main window\r\n mpos = self.frame.GetPosition()\r\n msize = self.frame.GetSize()\r\n self.toolw.SetPosition((mpos[0] + msize[0], mpos[1]))\r\n self.toolw.Show()\r\n return True\r\n\r\nclass MainWindow(wx.Frame):\r\n \"\"\"Main application window\"\"\"\r\n def __init__(self, parent, *args, **kwargs):\r\n wx.Frame.__init__(self, parent, *args, **kwargs)\r\n\r\n # Attributes\r\n self.panel = wx.TextCtrl(self, style=wx.TE_MULTILINE)\r\n\r\n # Layout\r\n sizer = wx.BoxSizer(wx.VERTICAL)\r\n sizer.Add(self.panel, 1, wx.EXPAND)\r\n self.SetSizer(sizer)\r\n self.SetInitialSize((300, 300))\r\n\r\n # Message Handler\r\n pubsub.Publisher.subscribe(self.OnTool, MSG_TOOL_CLICKED)\r\n\r\n def __del__(self):\r\n pubsub.Publisher.unsubscribe(self.OnTool)\r\n\r\n def OnTool(self, msg):\r\n \"\"\"Observer function for tool window events\"\"\"\r\n toolid = msg.data\r\n actionmap = { wx.ID_CUT : self.panel.Cut,\r\n wx.ID_COPY : self.panel.Copy,\r\n wx.ID_PASTE : self.panel.Paste,\r\n wx.ID_UNDO : self.panel.Undo,\r\n wx.ID_REDO : self.panel.Redo }\r\n action = actionmap.get(toolid, lambda:x)\r\n action()\r\n\r\nif __name__ == '__main__':\r\n app = ToolWindowApp(False)\r\n app.MainLoop()\r\n","sub_path":"wxPython Test/wxPython 2.8 Application Development Cookbook Source Code/1780_10_Code/03/toolwindow.py","file_name":"toolwindow.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"275857953","text":"from utils import Expr, expr\r\nfrom logic import unify\r\nimport itertools\r\nimport random\r\n\r\nclass PDDL:\r\n\r\n\tdef __init__(self, init, goals, actions):\r\n\t\tself.init = self.convert(init)\r\n\t\tself.goals = self.convert(goals)\r\n\t\tself.actions = actions\r\n\r\n\tdef convert(self, clauses):\r\n\t\tif not isinstance(clauses, Expr):\r\n\t\t\tclauses = expr(clauses)\r\n\t\ttry:\r\n\t\t\tclauses = conjuncts(clauses)\r\n\t\texcept AttributeError:\r\n\t\t\tclauses = clauses\r\n\t\treturn clauses\r\n\r\n\tdef goal_test(self):\r\n\t\treturn all(goal in self.init for goal in conjuncts(self.goals))\r\n\r\n\tdef act(self, action):\r\n\t\taction_name = action.op\r\n\t\targs = action.args\r\n\t\tlist_action = first(a for a in self.actions if a.name == action_name)\r\n\t\tif list_action is None:\r\n\t\t\traise Exception('Action {} not found'.format(action_name))\r\n\t\tif not list_action.check_precond(self.init, args):\r\n\t\t\traise Exception('Action {} pre-conditions not satisfied'.format(action))\r\n\t\tself.init = list_action(self.init, args).clauses\r\n\r\n\r\nclass Action:\r\n\r\n\tdef __init__(self, action, precond, effect):\r\n\t\tif isinstance(action, str):\r\n\t\t\taction = expr(action)\r\n\t\tself.name = action.op\r\n\t\tself.args = action.args\r\n\t\tself.precond = self.convert(precond)\r\n\t\tself.effect = self.convert(effect)\r\n\r\n\tdef __call__(self, kb, args):\r\n\t\treturn self.act(kb, args)\r\n\r\n\tdef __repr__(self):\r\n\t\treturn f'{self.__class__.__name__}({Expr(self.name, *self.args)})'\r\n\r\n\tdef convert(self, clauses):\r\n\t\tif isinstance(clauses, Expr):\r\n\t\t\tclauses = conjuncts(clauses)\r\n\t\t\tfor i in range(len(clauses)):\r\n\t\t\t\tif clauses[i].op == '~':\r\n\t\t\t\t\tclauses[i] = expr('Not' + str(clauses[i].args[0]))\r\n\r\n\t\telif isinstance(clauses, str):\r\n\t\t\tclauses = clauses.replace('~', 'Not')\r\n\t\t\tif len(clauses) > 0:\r\n\t\t\t\tclauses = expr(clauses)\r\n\r\n\t\t\ttry:\r\n\t\t\t\tclauses = conjuncts(clauses)\r\n\t\t\texcept AttributeError:\r\n\t\t\t\tpass\r\n\r\n\t\treturn clauses\r\n\r\n\tdef substitute(self, e, args):\r\n\t\tnew_args = list(e.args)\r\n\t\tfor num, x in enumerate(e.args):\r\n\t\t\tfor i, _ in enumerate(self.args):\r\n\t\t\t\tif self.args[i] == x:\r\n\t\t\t\t\tnew_args[num] = args[i]\r\n\t\treturn Expr(e.op, *new_args)\r\n\r\n\tdef check_precond(self, kb, args):\r\n\t\tif isinstance(kb, list):\r\n\t\t\tkb = FolKB(kb)\r\n\r\n\t\tfor clause in self.precond:\r\n\t\t\tif self.substitute(clause, args) not in kb.clauses:\r\n\t\t\t\treturn False\r\n\t\treturn True\r\n\r\n\tdef act(self, kb, args):\r\n\t\tif isinstance(kb, list):\r\n\t\t\tkb = FolKB(kb)\r\n\r\n\t\tif not self.check_precond(kb, args):\r\n\t\t\traise Exception('Action pre-conditions not satisfied')\r\n\t\tfor clause in self.effect:\r\n\t\t\tkb.tell(self.substitute(clause, args))\r\n\t\t\tif clause.op[:3] == 'Not':\r\n\t\t\t\tnew_clause = Expr(clause.op[3:], *clause.args)\r\n\r\n\t\t\t\tif kb.ask(self.substitute(new_clause, args)) is not False:\r\n\t\t\t\t\tkb.retract(self.substitute(new_clause, args))\r\n\t\t\telse:\r\n\t\t\t\tnew_clause = Expr('Not' + clause.op, *clause.args)\r\n\r\n\t\t\t\tif kb.ask(self.substitute(new_clause, args)) is not False:\r\n\t\t\t\t\tkb.retract(self.substitute(new_clause, args))\r\n\r\n\t\treturn kb\r\n\r\n\r\n# If we only represent partial order constraints on steps, then we have a partial order planner, which is also called a non-linear planner.\r\n# In this case, we specify a set of temporal constraints between pairs of steps of the form S1 < S2 meaning that step S1 comes before, but not necessarily immediately before step S2\r\n# Principle of least commitment: never making a choice unless required to do so. Constraint-ordering steps will be inserted only where necessary.\r\n# On the other hand, situation-space progression planners make commitments about the order of steps as they try to find a solution and therefore may make mistakes from poor guesses about the right order of steps\r\n# Plan space planning: by searching through the plan space of (partial-order) plans. Plan space planners do least commitment planning\r\n# Pseudocode\r\n'''\r\nnon-deterministic procedure PartialOrderPlanner(Gs)\r\n\tInputs\r\n\t\tGs: set of atomic propositions to achieve\r\n\tOutput:\r\n\t\tLinear plan to achieve Gs\r\n\tLocal\r\n\t\tAgenda: set of pairs where P is an atom and A is an action\r\n\t\tActions: set of actions in the current plan\r\n\t\tConstraints: set of temporal constraints on actions\r\n\t\tCausalLinks: set of triples\r\n\tAgenda = {: G E Gs}\r\n\tActions = {start, finish}\r\n\tConstraints = {start, finish}\r\n\tCausalLinks = {}\r\n\trepeat\r\n\t\tselect and remove from Agenda\r\n\t\teither\r\n\t\t\tchoose act0 E Actions such that act0 achieves G\r\n\t\tor\r\n\t\t\tchoose act0 E Actions such that act0 achieves G\r\n\t\t\tActions = Actions U {act0}\r\n\t\t\tConstraints = add_const(start < act0, Constraints)\r\n\t\t\tfor each CL E CausalLinks do\r\n\t\t\t\tConstraints = protect(CL, act0, Constraints)\r\n\r\n\t\t\tAgenda = Agenda U {: P is a precondition of act0}\r\n\r\n\t\tConstraints = add_const(act0 < act1, Constraints)\r\n\t\tCausalLinks U {}\r\n\t\tfor each A E Actions do\r\n\t\t\tConstraints = protect(, A, Constraints)\r\n\r\n\tuntil Agenda = {}\r\n\treturn total ordering of Actions consistent with Constraints\r\n'''\r\n# The function add_const(act0 < act1, Constraints) returns the `Constraints` formed by adding the constraint act0 < act1 to `Constraints`,\r\n# and it fails if act0 < act1 is incompatible with `Constraints`. There are many ways this function can be implemented\r\n# The function protect(, A, Constraints) checks whether A != act0 and A != act1 and A deletes G.\r\n# If so, it returns either {A < act0} U Constraints or {act1 < A} U Constraints. This is a non-deterministic choice that is searched over.\r\n# Otherwise it returns Constraints\r\n\r\nclass PartialOrderPlanner:\r\n\r\n\tdef __init__(self, pddl):\r\n\t\tself.pddl = pddl\r\n\t\tself.causal_links = []\r\n\t\tself.expanded_actions = self.expand_actions()\r\n\t\tself.initialize()\r\n\r\n\tdef initialize(self):\r\n\t\tself.start = Action('Start', [], self.pddl.init)\r\n\t\tself.finish = Action('Finish', self.pddl.goals, [])\r\n\t\tself.actions = [self.start, self.finish]\r\n\t\tself.constraints = set()\r\n\t\tself.constraints.add((self.start, self.finish))\r\n\t\tself.agenda = set()\r\n\t\tfor precondition in self.finish.precond:\r\n\t\t\tself.agenda.add((precondition, self.finish))\r\n\r\n\tdef expand_actions(self, name=None):\r\n\t\tobjects = set(arg for clause in self.pddl.init for arg in clause.args)\r\n\t\texpansions = []\r\n\t\taction_list = []\r\n\t\tif name is not None:\r\n\t\t\tfor action in self.pddl.actions:\r\n\t\t\t\tif str(action.name) == name:\r\n\t\t\t\t\taction_list.append(action)\r\n\t\telse:\r\n\t\t\taction_list = self.pddl.actions\r\n\r\n\t\tfor action in action_list:\r\n\t\t\tfor permutation in itertools.permutations(objects, len(action.args)):\r\n\t\t\t\tbindings = unify(Expr(action.name, *action.args), Expr(action.name, *permutation))\r\n\t\t\t\tif bindings is not None:\r\n\t\t\t\t\tnew_args = []\r\n\t\t\t\t\tfor arg in action.args:\r\n\t\t\t\t\t\tif arg in bindings:\r\n\t\t\t\t\t\t\tnew_args.append(bindings[arg])\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tnew_args.append(arg)\r\n\t\t\t\t\tnew_expr = Expr(str(action.name), *new_args)\r\n\t\t\t\t\tnew_preconds = []\r\n\t\t\t\t\tfor precond in action.precond:\r\n\t\t\t\t\t\tnew_precond_args = []\r\n\t\t\t\t\t\tfor arg in precond.args:\r\n\t\t\t\t\t\t\tif arg in bindings:\r\n\t\t\t\t\t\t\t\tnew_precond_args.append(bindings[arg])\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tnew_precond_args.append(arg)\r\n\t\t\t\t\t\tnew_precond = Expr(str(precond.op), *new_precond_args)\r\n\t\t\t\t\t\tnew_preconds.append(new_precond)\r\n\t\t\t\t\tnew_effects = []\r\n\t\t\t\t\tfor effect in action.effect:\r\n\t\t\t\t\t\tnew_effect_args = []\r\n\t\t\t\t\t\tfor arg in effect.args:\r\n\t\t\t\t\t\t\tif arg in bindings:\r\n\t\t\t\t\t\t\t\tnew_effect_args.append(bindings[arg])\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tnew_effect_args.append(arg)\r\n\t\t\t\t\t\tnew_effect = Expr(str(effect.op), *new_effect_args)\r\n\t\t\t\t\t\tnew_effects.append(new_effect)\r\n\t\t\t\t\texpansions.append(Action(new_expr, new_preconds, new_effects))\r\n\r\n\t\treturn expansions\r\n\r\n\t# TODO: Separate selection of precondition and selection of action. This might solve a few errors\r\n\tdef select_precondition(self):\r\n\t\tnumber_of_ways = dict()\r\n\t\tactions_for_precondition = dict()\r\n\t\tfor element in self.agenda:\r\n\t\t\topen_precondition = element[0]\r\n\t\t\tpossible_actions = self.actions + self.expanded_actions\r\n\t\t\tfor action in possible_actions:\r\n\t\t\t\tfor effect in action.effect:\r\n\t\t\t\t\tif effect == open_precondition:\r\n\t\t\t\t\t\tif open_precondition in number_of_ways:\r\n\t\t\t\t\t\t\tnumber_of_ways[open_precondition] += 1\r\n\t\t\t\t\t\t\tactions_for_precondition[open_precondition].append(action)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tnumber_of_ways[open_precondition] = 1\r\n\t\t\t\t\t\t\tactions_for_precondition[open_precondition] = [action]\r\n\r\n\t\tnumber = sorted(number_of_ways, key=number_of_ways.__getitem__)\r\n\t\t\r\n\t\tif len(actions_for_precondition[number[0]]) == 0:\r\n\t\t\treturn None, None\r\n\r\n\t\tact1 = None\r\n\t\tfor element in self.agenda:\r\n\t\t\tif element[0] == number[0]:\r\n\t\t\t\tact1 = element[1]\r\n\t\t\t\tbreak\r\n\r\n\t\tif number[0] in self.expanded_actions:\r\n\t\t\tself.expanded_actions.remove(number[0])\r\n\r\n\t\t# print('NUMBER 0: ', number[0])\r\n\t\treturn number[0], act1, actions_for_precondition[number[0]]\r\n\r\n\tdef check_safety_between_two_steps(self, action_a, action_b):\r\n\t\tfor a_effect in action_a.effect:\r\n\t\t\tfor b_precondition in action_b.precond:\r\n\t\t\t\tif (Expr(str(a_effect.name), *a_effect.args) == Expr('Not' + str(b_precondition.name), *b_precondition.args)) or(Expr('Not' + str(a_effect.name), *a_effect.args) == Expr(str(b_precondition.name), *b_precondition.args)):\r\n\t\t\t\t\treturn False\r\n\t\treturn True\r\n\r\n\tdef find_a_threat(self, node):\r\n\t\t# node is an action\r\n\t\tif node.name == 'Start':\r\n\t\t\treturn None\r\n\r\n\t\tnode_edges = []\r\n\t\t# node_edges contain causal_links\r\n\t\tfor causal_link in self.causal_links:\r\n\t\t\tif node == causal_link[0]:\r\n\t\t\t\tif not self.check_safety_between_two_steps(causal_link[0], causal_link[2]):\r\n\t\t\t\t\treturn causal_link\r\n\t\treturn None\r\n\r\n\tdef get_edge_by_destination(self, action):\r\n\t\tedges_by_destination = []\r\n\t\tfor edge in self.causal_links:\r\n\t\t\tif action == edge[2]:\r\n\t\t\t\tedges_by_destination.append(edge)\r\n\t\treturn edges_by_destination\r\n\r\n\tdef get_edge_by_source(self, action):\r\n\t\tedges_by_source = []\r\n\t\tfor edge in self.causal_links:\r\n\t\t\tif action == edge[0]:\r\n\t\t\t\tedges_by_source.append(edge)\r\n\t\treturn edges_by_source\r\n\r\n\tdef resolve_a_threat(self, threat_causal_link):\r\n\t\tprint('Resolve a threat - demotion attempt')\r\n\t\tparent_new_actions = self.get_edge_by_destination(threat_causal_link[0])\r\n\t\tgrandparent_new_actions = self.get_edge_by_destination(threat_causal_link[0])\r\n\r\n\t\tparent_e = parent_new_actions[0]\r\n\t\tgrandparent_e = grandparent_new_actions[0]\r\n\r\n\t\t# keep original\r\n\t\tgrand_d_dest = grandparent_e[2]\r\n\t\tparent_e_source = parent_e[0]\r\n\t\tparent_e_dest = parent_e[2]\r\n\r\n\t\tgrandparent_e[2] = threat_causal_link[0]\r\n\t\ttmp = parent_e[0]\r\n\t\tparent_e[0] = threat_causal_link[0]\r\n\t\tparent_e[2] = tmp\r\n\t\tthreat_causal_link[0] = tmp\r\n\r\n\t\tif not self.check_safety_between_two_steps(threat_causal_link[0], threat_causal_link[2]) or not self.check_safety_between_two_steps(parent_e[0], parent_e[2]):\r\n\t\t\t# try promotion\r\n\t\t\tprint('Resolve a threat promotion attempt')\r\n\t\t\tgrandparent_e[2] = grand_d_dest\r\n\t\t\tparent_e[0] = parent_e_source\r\n\t\t\tparent_e[2] = parent_e_dest\r\n\r\n\t\t\tchild_es = self.get_edge_by_source(threat_causal_link[2])\r\n\t\t\tchild_e = child_es[0]\r\n\t\t\tparent_e[2] = threat_causal_link[0]\r\n\t\t\ttmp = threat_causal_link[0]\r\n\t\t\tthreat_causal_link[2] = tmp\r\n\t\t\tthreat_causal_link[0] = child_e[0]\r\n\t\t\tchild_e[0] = tmp\r\n\r\n\t\t\tif not self.check_safety_between_two_steps(threat_causal_link[0], threat_causal_link[2]) or not self.check_safety_between_two_steps(parent_e[0], parent_e[2]):\r\n\t\t\t\treturn False\r\n\r\n\t\t# promotion\r\n\t\treturn True\r\n\r\n\tdef check_resolution_between_states(self, state_a, state_b):\r\n\t\tif state_a.op == state_b.op:\r\n\t\t\tif state_a.args == state_b.args:\r\n\t\t\t\treturn True\r\n\t\treturn False\r\n\r\n\tdef check_effects_with_parameters(self, effects, state_b):\r\n\t\tfor effect in effects:\r\n\t\t\tif self.check_resolution_between_states(effect, state_b):\r\n\t\t\t\treturn True\r\n\t\treturn False\r\n\r\n\tdef update_open_preconditions(self):\r\n\t\teffects = []\r\n\t\tpreconds = []\r\n\t\tpreconds_x = []\r\n\t\tprint('self.actions: ', self.actions)\r\n\r\n\t\tfor action in self.actions:\r\n\t\t\tprint(action)\r\n\t\t\tfor effect in action.effect:\r\n\t\t\t\teffects.append(effect)\r\n\t\t\tfor precond in action.precond:\r\n\t\t\t\tpreconds.append((precond, action))\r\n\r\n\t\tfor i in range(len(preconds)):\r\n\t\t\tif not self.check_effects_with_parameters(effects, preconds[i][0]):\r\n\t\t\t\tpreconds_x.append((preconds[i][0], preconds[i][1]))\r\n\r\n\t\tself.agenda = set()\r\n\t\tfor precond in preconds_x:\r\n\t\t\tself.agenda.add(precond)\r\n\r\n\tdef execute(self):\r\n\t\twhile True:\r\n\t\t\tprint('POP Algorithm Step')\r\n\t\t\tif len(self.agenda) > 0:\r\n\t\t\t\toprec, oprec_action, new_action = self.select_precondition()\r\n\t\t\t\tprint('Solving precondition', oprec, 'of action', oprec_action, 'using', new_action)\r\n\t\t\t\tself.actions.append(new_action[0])\r\n\r\n\t\t\t\t# find a causal_link between oprec and its prev and update it\r\n\t\t\t\tprint('Update edges')\r\n\t\t\t\tfor causal_link in self.causal_links:\r\n\t\t\t\t\tprint('Get the link: ', causal_link[0].name, causal_link[0].args, '-->', causal_link[2].name, causal_link[2].args)\r\n\t\t\t\t\tprint('if', causal_link[2].name, 'is equal to', oprec_action.name, oprec_action.args)\r\n\t\t\t\t\tif causal_link[2] == oprec_action:\r\n\t\t\t\t\t\tprint('Found an edge with the action of open precondition')\r\n\t\t\t\t\t\tprint('Change destination for this edge')\r\n\t\t\t\t\t\tcausal_link[2] = new_action\r\n\r\n\t\t\t\tfor i in range(len(self.causal_links)):\r\n\t\t\t\t\te = self.causal_links[i]\r\n\t\t\t\t\tprint('Get the link: ', e[0].name, e[0].args, '-->', e[2].name, e[2].args)\r\n\t\t\t\t\tprint('If', e[2].name, e[2].args, 'is equal to', oprec_action.name, oprec_action.args)\r\n\r\n\t\t\t\t\tif e[2] == oprec_action:\r\n\t\t\t\t\t\tprint('Found an edge with the action of open precondition')\r\n\t\t\t\t\t\tprint('Change destination for this edge')\r\n\t\t\t\t\t\tself.causal_links[i][2] = new_action\r\n\t\t\t\t\t\tprint('Create new edge, locating the new action between the old ones')\r\n\t\t\t\t\t\tnew_causal_link = (new_action, self.causal_links[i][1], oprec_action)\r\n\t\t\t\t\t\tself.causal_links.append(new_causal_link)\r\n\t\t\t\t\t\tbreak\r\n\r\n\t\t\t\tprint('Resolve threats')\r\n\t\t\t\twhile True:\r\n\t\t\t\t\tthreat_causal_link = self.find_a_threat(self.start)\r\n\t\t\t\t\tif threat_causal_link == None:\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tif not self.resolve_a_threat(threat_causal_link):\r\n\t\t\t\t\t\tprint('Planning failed: Cannot solve a threat')\r\n\t\t\t\t\t\texit(0)\r\n\r\n\t\t\t\tself.update_open_preconditions()\r\n\r\n\t\t\t\tprint('Causal links:')\r\n\t\t\t\tfor causal_link in self.causal_links:\r\n\t\t\t\t\tprint(causal_link[0], causal_link[1], causal_link[2])\r\n\r\n\t\t\t\tprint('Open preconditions:')\r\n\t\t\t\tfor open_precondition in self.agenda:\r\n\t\t\t\t\tprint(open_precondition)\r\n\r\n\t\t\t\tprint('-----------------------------------------------------------')\t\t\t\t\r\n\r\n\t\t\tif len(self.agenda) == 0:\r\n\t\t\t\tbreak\r\n\r\n\tdef compute(self):\r\n\t\tprint('Start computation')\r\n\t\tself.update_open_preconditions()\r\n\t\tself.execute()\r\n\t\tprint('Done')\r\n\t\tprint('Causal links:')\r\n\t\tfor causal_link in self.causal_links:\r\n\t\t\tprint(causal_link[0], causal_link[1], causal_link[2])\r\n\r\n\t\tprint('Open preconditions:')\r\n\t\tfor open_precondition in self.agenda:\r\n\t\t\tprint(open_precondition)\t\t\r\n","sub_path":"Machine Learning/Aima/partial_order_planner_6.py","file_name":"partial_order_planner_6.py","file_ext":"py","file_size_in_byte":14755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"240987016","text":"import contextlib\nimport io\nimport json\nimport multiprocessing\nimport os\nimport pathlib\nimport sys\n\nimport pytest\n\n\ndef main():\n tests = find_tests()\n results = {}\n for test in tests:\n test = os.path.dirname(test)\n child, parent = multiprocessing.Pipe()\n process = multiprocessing.Process(\n target = run_test,\n args = (child, test),\n )\n process.start()\n result, error = parent.recv()\n process.join()\n if error:\n results[test] = error\n else:\n results[test] = result\n print(json.dumps(results))\n\n\ndef find_tests():\n tests = []\n for prefix, directories, files in os.walk('/app', topdown=True):\n directories[:] = [directory for directory in directories\n if not directory.startswith('.')]\n for directory in directories:\n if directory == 'tests':\n test = os.path.join(prefix, directory)\n tests.append(test)\n return tests\n\n\nclass Plugin:\n\n def __init__(self):\n self.reports = []\n\n def pytest_runtest_logreport(self, report):\n self.reports.append({\n 'test': report.nodeid,\n 'stage': report.when,\n 'result': report.outcome,\n 'description': str(report.longrepr),\n })\n\n\ndef run_test(pipe, path):\n os.chdir(path)\n sys.path.insert(0, str(path))\n plugin = Plugin()\n try:\n with no_stdout():\n pytest.main(\n # ['tests/', '--timeout=30', '-p', 'no:terminal'],\n ['tests/', '--timeout=30'],\n plugins = [plugin],\n )\n pipe.send((plugin.reports, None))\n except Exception:\n pipe.send((None, traceback.format_exc().strip()))\n\n\n@contextlib.contextmanager\ndef no_stdout():\n stdout = sys.stdout\n sys.stdout = io.StringIO()\n try:\n yield\n finally:\n sys.stdout = stdout\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dockerfiles/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"278128895","text":"import numpy as np\nimport tensorflow as tf\n\nfrom ..lstm_latent_vector_as_init_state import LSTM_LatentVectorAsInitState\n\n\nclass LSTMLatentVectorAsInitStateTestCase(tf.test.TestCase):\n\n def setUp(self):\n self.embedding = np.random.rand(50, 300).astype('float32')\n\n def tearDown(self):\n tf.reset_default_graph()\n\n def test_input_with_tensor_default(self):\n with self.test_session() as sess:\n logits, word_indices = LSTM_LatentVectorAsInitState(\n latent_vectors=tf.random_normal((10, 128)),\n real_indices=tf.random_uniform(\n shape=[10, 20],\n minval=0,\n maxval=50,\n dtype=tf.int32,\n ),\n lstm_input_dropout=0.1,\n lstm_output_dropout=0.1,\n lstm_state_dropout=0.2,\n embedding_table=self.embedding,\n assist=0,\n )\n sess.run(tf.global_variables_initializer())\n\n self.assertAllEqual((10, 20, 50), logits.eval().shape)\n self.assertEqual(np.float32, logits.dtype)\n self.assertEqual('logits:0', logits.name)\n\n self.assertAllEqual((10, 20), word_indices.eval().shape)\n self.assertEqual(np.int32, word_indices.dtype)\n self.assertEqual('word_indices:0', word_indices.name)\n\n def test_input_with_placeholder_assisted(self):\n with self.test_session() as sess:\n latent_vectors = tf.placeholder(\n shape=[None, 128],\n dtype=tf.float32,\n )\n real_indices = tf.placeholder(\n shape=[None, 20],\n dtype=tf.int32,\n )\n logits, word_indices = LSTM_LatentVectorAsInitState(\n latent_vectors=latent_vectors,\n real_indices=real_indices,\n lstm_input_dropout=0.1,\n lstm_output_dropout=0.1,\n lstm_state_dropout=0.2,\n embedding_table=self.embedding,\n assist=1,\n )\n sess.run(tf.global_variables_initializer())\n output_logits, output_word_indices = sess.run(\n [logits, word_indices],\n feed_dict={\n latent_vectors:\n np.random.rand(10, 128).astype('float32'),\n real_indices:\n np.random.randint(50, size=(10, 20)).astype('int32'),\n },\n )\n self.assertAllEqual((10, 20, 50), output_logits.shape)\n self.assertEqual(np.float32, output_logits.dtype)\n self.assertEqual('logits:0', logits.name)\n\n self.assertAllEqual((10, 20), output_word_indices.shape)\n self.assertEqual(np.int32, output_word_indices.dtype)\n self.assertEqual('word_indices:0', word_indices.name)\n","sub_path":"text_autoencoder/variational_autoencoders/decoders/test/test_lstm_latent_vector_as_init_state.py","file_name":"test_lstm_latent_vector_as_init_state.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"210194025","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.3-fat/egg/apydia/command.py\n# Compiled at: 2007-12-05 07:14:05\n\"\"\"\n Apydia command line tool (and distutils command)\n ------------------------------------------------\n \n Use the ``apydia`` command to generate API reference documentation:\n \n Usage: apydia [options] [modules]\n\n Apydia API Documentation Generator\n\n Options:\n --version show program's version number and exit\n -h, --help show this help message and exit\n -c CONFIGFILE, --config=CONFIGFILE\n specify config file\n -d DESTINATION, --destination=DESTINATION\n specify output directory\n -o, --open open in browser\n -f FORMAT, --format=FORMAT\n rendering format (xhtml or html, defaults to xhtml)\n -s THEME, --style=THEME\n Choose a theme\n -p DOCFORMAT, --parser=DOCFORMAT\n docstring parser (markdown, textile, restucturedtext,\n html, ...)\n -b TRAC_BROWSER_URL, --trac-browser-url=TRAC_BROWSER_URL\n trac browser url (path to root module)\n -q, --quiet silent mode\n -t TITLE, --title=TITLE\n title of project\n -x EXCLUDE_MODULES, --exclude-modules=EXCLUDE_MODULES\n exclude modules\n\n \n Or run it through distutils by configuring your project's setup.cfg\n appropriately (see documentation) and issuing from your project root:\n \n python setup.py apydia\n\"\"\"\nimport logging, sys, os\nfrom optparse import OptionParser\nfrom apydia import release\nfrom apydia.project import Project\nimport warnings\nlog = logging.getLogger(__name__)\n__all__ = [\n 'main', 'apydia']\ntry:\n import distutils.cmd\n\n class apydia(distutils.cmd.Command):\n \"\"\"\n ``apydia`` command\n ==================\n \n The ``apydia``-command as an extension to distutils.\n \n Run by typing\n \n python setup.py apydia\n \n \n Availlable options are:\n\n --title (-t) The name of your project\n --destination (-d) Target directory where the apidocs go\n --theme (-t) Choose an Apydia theme\n --docformat Set this to the docstring's format (eg. markdown,\n textile, reStrucuturedText)\n --format (-f) XHTML or HTML, defaults to xhtml\n --modules Include the given modules in documentation\n --exclude-modules (-x) Don't generate documentation for the given modules\n --trac-browser-url (-b) URL to Trac's sourcecode browser\n --open (-o) Open generated files in browser when done\n \n \n It is recommended to supply options through an\n ``[apydia]``-section in the target project's ``setup.cfg``.\n See the documentation of the ``apydia.command`` module for\n more information.\n \"\"\"\n __module__ = __name__\n description = 'Generate API Reference Documentations using Apydia'\n user_options = [\n ('title=', 't', 'The name of your project'), ('destination=', 'd', 'Target directory where the apidocs go'), ('theme=', 't', 'Choose an Apydia theme'), ('docformat=', None, \"Set this to the docstring's format (eg. markdown, textile, reStrucuturedText)\"), ('format=', 'f', 'XHTML or HTML, defaults to xhtml'), ('modules=', None, 'Include the given modules in documentation'), ('exclude-modules=', 'x', \"Don't generate documentation for the given modules\"), ('trac-browser-url=', 'b', \"URL to Trac's sourcecode browser\"), ('open', 'o', 'Open generated files in browser when done')]\n\n def initialize_options(self):\n self.title = ''\n self.destination = 'apydocs'\n self.theme = 'default'\n self.docformat = ''\n self.format = 'xhtml'\n self.modules = []\n self.exclude_modules = []\n self.trac_browser_url = ''\n self.open = False\n\n def finalize_options(self):\n self.ensure_string_list('modules')\n self.ensure_string_list('exclude_modules')\n self.ensure_string('title')\n self.ensure_string('theme')\n self.ensure_string('trac_browser_url')\n\n def run(self):\n\n def generate():\n project = Project(self)\n project.generate()\n if self.open and str(self.open).lower() in ('1', 'true', 'yes'):\n project.open_in_browser()\n\n self.execute(generate, (), msg='Generating API reference documentation.')\n\n\nexcept ImportError:\n warnings.warn('distutils not installed.')\n\ndef main():\n \"\"\"\n Generate api reference documentation from the command line\n \n Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\n eiusmod tempor incididunt ut labore et dolore magna aliqua.\n \n #!python\n class CodeExample(object):\n def __init__(self):\n pass\n \n Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris\n nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in\n reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla\n pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\n culpa qui officia deserunt mollit anim id est laborum.\n \"\"\"\n sys.path.insert(0, os.getcwd())\n optparser = OptionParser(usage='%prog [options] [modules]', description=release.description, version=release.version)\n optparser.set_defaults(title='', destination='apydocs', theme='default', verbose=True, open=False, format='xhtml', docformat='restructuredtext', modules='', exclude_modules='', trac_browser_url='')\n optparser.add_option('-c', '--config', dest='configfile', help='specify config file')\n optparser.add_option('-d', '--destination', dest='destination', help='specify output directory')\n optparser.add_option('-o', '--open', dest='open', action='store_true', help='open in browser')\n optparser.add_option('-f', '--format', dest='format', help='rendering format (xhtml or html, defaults to xhtml)')\n optparser.add_option('-s', '--style', dest='theme', help='Choose a theme')\n optparser.add_option('-p', '--parser', dest='docformat', help='docstring parser (markdown, textile, restucturedtext, html, ...)')\n optparser.add_option('-b', '--trac-browser-url', dest='trac_browser_url', help='trac browser url (path to root module)')\n optparser.add_option('-q', '--quiet', action='store_false', dest='verbose', help='silent mode')\n optparser.add_option('-t', '--title', dest='title', help='title of project')\n optparser.add_option('-x', '--exclude-modules', dest='exclude_modules', help='exclude modules')\n (options, args) = optparser.parse_args()\n if options.configfile:\n from ConfigParser import ConfigParser\n cfgparser = ConfigParser()\n cfgparser.read(options.configfile)\n cfgopts = dict(cfgparser.items('apydia'))\n optparser.set_defaults(**cfgopts)\n (options, args) = optparser.parse_args()\n try:\n options.modules = [ m.strip() for m in options.modules.split(',') if m.strip() ] + args\n except AttributeError:\n optparser.print_help()\n return\n\n options.exclude_modules = [ m.strip() for m in options.exclude_modules.split(',') if m.strip() ]\n logger_settings = dict(format='%(asctime)s %(levelname)-8s %(message)s')\n if options.verbose:\n logger_settings['level'] = logging.DEBUG\n logging.basicConfig(**logger_settings)\n project = Project(options)\n project.generate()\n if options.open:\n project.open_in_browser()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/Apydia-0.0.2-py2.4/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":8336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"16900899","text":"'''\n----------------------------------------------------------------------------------------------------\nMULTI ARMED-BANDIT SIMULATION PARSER\n----------------------------------------------------------------------------------------------------\n\nEUROPAR 2019 - Adaptive Request Scheduling for the I/O Forwarding Layer\n\n----------------------------------------------------------------------------------------------------\n\nAUTHORS\n\tJean Luca Bez \n\tFrancieli Zanon Boito \n\nDESCRIPTION\n\tThis file parses the simulation results of the armed bandit with a multiple access pattern.\n\tNotice that for now it only supports exactly three patterns at once.\n\nCONTRIBUTORS\n\tFederal University of Rio Grande do Sul (UFRGS)\n\tINRIA France\n\nNOTICE\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\nCREATED\n\tDecember 13th, 2018\n\nVERSION\n\t1.0\n\n----------------------------------------------------------------------------------------------------\n'''\n\nimport os\nimport os.path\nimport re\nimport sys\nimport csv\nimport subprocess\nimport collections\nimport logging\nimport pprint\nimport random\nimport time\nimport csv\nimport datetime\nimport json\nimport shlex\nimport errno\nimport argparse\n\nimport numpy as np\n\nif sys.version_info[0] < 3:\n\tprint('You must use Python 3')\n\n\texit()\n\nlogging.basicConfig(\n\tlevel = logging.INFO,\n\tformat = '%(asctime)s - %(levelname)s - %(message)s',\n\thandlers = [\n\t\tlogging.FileHandler('parse.log'),\n\t\tlogging.StreamHandler()\n\t]\n)\n\n\ndef getBestSolution(metrics):\n\t# Get information about each window size performance and find out what is the best, return the best's performance and the best action\n\tbest_choice = [-1, -1, -1]\n\tmaximum_performance = [0, 0, 0]\n\n\tfor pattern in metrics:\n\t\tp = int(pattern)\n\n\t\tfor action, performance in metrics[pattern].items():\n\t\t\tif performance > maximum_performance[p]:\n\t\t\t\tmaximum_performance[p] = performance\n\t\t\t\tbest_choice[p] = action\n\n\tfor i in range(len(best_choice)):\n\t\tif best_choice[i] == -1 :\n\t\t\tlogging.error('Unable to find the best solution')\n\n\t\t\texit()\n\n\tret = []\n\n\tfor pattern in range(len(best_choice)):\n\t\tret.append(metrics[str(pattern)][best_choice[pattern]])\n\treturn (ret, best_choice)\n\n\ndef getMaximumIterations(filename):\n\t# Get the number of iterations, total reward from the JSON\n\twith open('{}'.format(filename)) as f:\n\t\tdata = json.load(f)\n\n\treturn data['bandit']['iterations']\n\n\ndef getIterations(filename, maximum_iterations, BIN_SIZE, best_choice):\n\t# Read maximum_iterations lines, separate measurements in bins of BIN_SIZE\n\t# Return two lists, the first has the maximum_iterations/BIN_SIZE average rewards, the second has the precision of each bin\n\titeration = 0\n\n\tseries = []\n\tprecision = []\n\tcurrent_bin = [[], [], []]\n\n\ttook_best = [0, 0, 0]\n\n\tf = open(filename.replace('.json', '-log.csv'), 'r')\n\t\t\n\t# Skip the header\n\tf.readline()\n\n\twhile iteration < maximum_iterations:\n\t\tline = f.readline()\n\t\tparsed = line.split('\\n')[0].split(';')\n\t\tpattern = int(parsed[1])\n\n\t\t# Time to close a bin\n\t\tif (iteration > 0) and ((iteration % BIN_SIZE) == 0):\n\t\t\tthis_series = []\n\t\t\tthis_precision = []\n\n\t\t\tfor p in range(len(current_bin)):\n\t\t\t\tif len(current_bin[p]) == 0:\n\t\t\t\t\tthis_series.append(-1)\n\t\t\t\t\tthis_precision.append(-1)\n\t\t\t\telse:\n\t\t\t\t\tthis_series.append(np.mean(current_bin[p]))\n\t\t\t\t\tthis_precision.append(float(took_best[p]) / len(current_bin[p]))\n\t\t\t\t\t\n\t\t\tseries.append(this_series)\n\t\t\tprecision.append(this_precision)\n\n\t\t\t# Reset the counter and the current bin\n\t\t\ttook_best = [0, 0, 0]\n\t\t\tcurrent_bin = [[], [], []]\n\n\t\tcurrent_bin[pattern].append(float(parsed[3]))\n\n\t\t# Count the number of times we took the best choice\n\t\tif int(parsed[2]) == int(best_choice[pattern]):\n\t\t\ttook_best[pattern] += 1\n\n\t\titeration += 1\n\n\tf.close()\n\n\treturn (series, precision)\n\t\t\n\ndef getResults(filename, maximum_iterations, BIN_SIZE):\n\t# Get the number of iterations, total reward from the JSON\n\twith open('{}'.format(filename)) as f:\n\t\tdata = json.load(f)\n\n\titerations = data['bandit']['iterations']\n\n\tif iterations < maximum_iterations:\n\t\tlogging.error('{} - Not enough iterations!'.format(filename))\n\n\t\texit()\n\n\t# From the part with the performance of different windows, find the best and see how many times it took it\n\tbest_performance, best_choice = getBestSolution(data['bandit']['reward']['summary'])\n\n\t# From the log of the iterations, fill the bins until the last iteration we will consider\n\tseries, precision = getIterations(filename, maximum_iterations, BIN_SIZE, best_choice)\n\t\n\t# Normalize bandwidth by the best possible\n\tnormalized = []\n\n\tfor o in range(len(series)):\n\t\tnormalized.append([])\n\t\t\n\t\tif len(series[o]) != 3:\n\t\t\tlogging.error('Something weird with read bins')\n\t\t\tlogging.error(series)\n\t\n\t\t\texit(1)\n\n\t\tfor p in range(len(series[o])):\n\t\t\tnormalized[o].append(series[o][p] / best_performance[p])\n\n\t# Return this repetition's series of normalized average rewards and precision\n\treturn (normalized, precision)\n\n\t\ndef getFiles(io_nodes, processes, test_type, strided, operation, request_size, epsilon, alpha):\n\tif alpha is None:\n\t\tret = subprocess.getoutput('ls results/multiple/epsilon-{}*.json | grep -v alpha'.format(epsilon)).split('\\n')\n\telse:\n\t\tret = subprocess.getoutput('ls results/multiple/epsilon-{}-alpha-{}*.json'.format(epsilon, alpha)).split('\\n')\n\n\tif 'found' in ret[0]:\n\t\tlogging.error('Unable to find the access pattern')\n\t\tlogging.error(ret)\n\n\t\texit()\n\n\treturn ret\n\n#########################################################################################################################\n\n\n# Configure the parser\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--ions',\n\taction = 'store',\n\tdest = 'io_nodes',\n\trequired = True,\n\thelp = 'Number of I/O nodes')\n\nparser.add_argument('--processes',\n\taction = 'store',\n\tdest = 'processes',\n\trequired = True,\n\thelp = 'Number of processes')\n\nparser.add_argument('--type',\n\taction = 'store',\n\tdest = 'test_type',\n\trequired = True,\n\thelp = 'Type: (1) file-per-process or (2) shared-file')\n\nparser.add_argument('--strided',\n\taction = 'store',\n\tdest = 'strided',\n\trequired = True,\n\thelp = 'Spatiality: (0) contiguous or (1) 1D-strided')\n\nparser.add_argument('--size',\n\taction = 'store',\n\tdest = 'request_size',\n\trequired = True,\n\thelp = 'Request size')\n\nparser.add_argument('--operation',\n\taction = 'store',\n\tdest = 'operation',\n\trequired = True,\n\thelp = 'Operation: \"read\" or \"write\"')\n\nparser.add_argument('--directory',\n\taction = 'store',\n\tdest = 'directory',\n\trequired = True,\n\thelp = 'Directory to store the CSVs')\n\n\nargs = parser.parse_args()\n\nBIN_SIZE = 10\nEPSILA = [1, 3, 5, 7, 10, 15, 20]\nALPHA = [None]\n\nfiles = []\n\nfor epsilon in EPSILA:\n\tfor alpha in ALPHA:\n\t\texperiments = getFiles(args.io_nodes, args.processes, args.test_type, args.strided, args.operation, args.request_size, epsilon, alpha)\n\t\tfiles.append([epsilon, alpha, experiments])\n\noutput_file = open('{}/{}-{}-{}-{}-{}-{}.csv'.format(args.directory, args.io_nodes, args.processes, args.test_type, args.strided, args.request_size, args.operation), 'w')\noutput_file.write(\"epsilon;alpha;pattern;bin;observation;performance;precision\\n\")\n\n# Iterate over all the files\nfor f in range(len(files)):\n\tepsilon = files[f][0]\n\talpha = files[f][1]\n\n\tperformance = [[], [], []]\n\tcorrect_answer = [[], [], []]\n\n\tmaximum_iterations = sys.maxsize\n\n\t# Get the maximum number of iterations based on the test files\n\tfor filename in files[f][2]:\n\t\tmaximum_iterations = min(maximum_iterations, getMaximumIterations(filename))\n\t\n\tlogging.info('Maximum iterations: {}'.format(maximum_iterations))\n\t\n\t# Create the slots for the metrics\n\tfor i in range(int(maximum_iterations / BIN_SIZE + 1)):\n\t\tfor p in range(len(performance)):\n\t\t\tperformance[p].append([])\n\t\t\tcorrect_answer[p].append([])\n\n\tfor filename in files[f][2]:\n\t\tprint(filename)\n\t\tnormalized, precision = getResults(filename, maximum_iterations, BIN_SIZE)\n\n\t\tfor i in range(len(normalized)):\n\t\t\tfor p in range(len(normalized[i])):\n\t\t\t\tperformance[p][i].append(normalized[i][p])\n\t\t\t\tcorrect_answer[p][i].append(precision[i][p])\n\n\t# Write output to the file\n\tfor p in range(len(performance)):\n\t\tfor i in range(len(performance[p])):\n\t\t\tfor j in range(len(performance[p][i])):\n\t\t\t\toutput_file.write('{};{};{};{};{};{};{}\\n'.format(epsilon, alpha, p, i + 1, j + 1, performance[p][i][j], correct_answer[p][i][j]))\n\noutput_file.close()\n","sub_path":"armed-bandit/parser/parse-multi-bandit.py","file_name":"parse-multi-bandit.py","file_ext":"py","file_size_in_byte":8465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"461908400","text":"print(\"\"\"\n***************************************\n\nFAKTORİYEL BULMA\n\nÇıkmak için \"q\"ya basın\n\n***************************************\n\n\"\"\")\n\nwhile True:\n sayı = input(\"Sayı:\")\n if (sayı == \"q\"):\n print(\"Program sonlandırılıyor.\")\n break\n\n else:\n sayı =int(sayı)\n\n faktoriyel = 1\n\n for i in range (2,sayı+1):\n print(\"Faktoriyel: {}, i: {}\".format(faktoriyel,i))\n faktoriyel *= i\n print(\"Faktoriyel:\",faktoriyel)","sub_path":"faktoriyel_calculator.py","file_name":"faktoriyel_calculator.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"43277840","text":"import json\nimport base64\nimport time\n\nimport requests\nfrom blog.handler import RedisHandler\n\nfrom apps.utils.mt_font_decode import modify_html\nfrom apps.utils.utils import url_encode, url_decode, dict_to_str\n\n\nclass GetMTMInfoToken(RedisHandler):\n async def post(self, *args, **kwargs):\n data = self.request.body.decode()\n data = json.loads(base64.b64decode(data).decode())\n res = requests.post('http://api.qinjiahu.cn/m_info_token', json=data)\n self.finish(json.loads(res.text))\n\n\nclass GetFontDecode(RedisHandler):\n async def post(self, *args, **kwargs):\n data = self.request.body.decode()\n data = json.loads(base64.b64decode(data).decode())\n if data['font']:\n self.finish(modify_html(''.join(data['font'].split(';'))))\n else:\n self.finish('')\n\n\nclass GetWXListToken(RedisHandler):\n async def post(self, *args, **kwargs):\n data = self.request.body.decode()\n data = json.loads(base64.b64decode(data).decode())['post_data']\n\n sign_data = {\n 'activity_filter_codes': '',\n 'avatarUrl': 'https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJPW6VrlXsaWuejKZq4Hd28ibicdEfpEPh6NHV26EQOAxXl2JPRtHpLDg27iaSLXCScoWRWx58r8JFHQ/132',\n 'category_type': 0,\n 'city': 'Hangzhou',\n 'country': 'China',\n 'gender': 1,\n 'lch': 1089,\n 'load_type': 1,\n 'navigate_type': 0,\n 'nickName': '女神的脑残粉',\n 'open_id': 'oOpUI0YnB0PJm3kqB7eFoCNqVUd4',\n 'page_index': 0,\n 'page_size': 20,\n 'partner': 4,\n 'platform': 13,\n 'province': 'Zhejiang',\n 'rank_list_id': '13415908e121dc3e58c6003e1a48487f',\n 'ref_list_id': '',\n 'req_time': 1559977476375,\n 'riskLevel': 1,\n 'slider_select_data': '',\n 'sort_type': 1,\n 'trace_tag': 'null',\n 'userToken': 'rgn9RwRzh0u63hs_60mcVcYhijIAAAAAkwgAAF-EM5cd3qzbwSigtS5yipBJmTdU8r7fszxlZWhAXmuzqlDRr7VXzPwzGeoHlGybHw',\n 'user_id': 920304791,\n 'userid': 920304791,\n 'utm_source': '',\n 'uuid': '9993003e-1a48-487f-8776-e46500caf72f',\n 'waimai_sign': '/',\n 'wm_actual_latitude': '',\n 'wm_actual_longitude': 120271176,\n 'wm_appversion': '3.9.4',\n 'wm_channel': '',\n 'wm_ctype': 'wxapp',\n 'wm_did': '',\n 'wm_dplatform': 'android',\n 'wm_dtype': 'MI 4LTE',\n 'wm_dversion': '7.0.4',\n 'wm_latitude': '30295792',\n 'wm_logintoken': 'rgn9RwRzh0u63hs_60mcVcYhijIAAAAAkwgAAF-EM5cd3qzbwSigtS5yipBJmTdU8r7fszxlZWhAXmuzqlDRr7VXzPwzGeoHlGybHw',\n 'wm_longitude': '120271176',\n 'wm_mac': '',\n 'wm_uuid': '9993003e-1a48-487f-8776-e46500caf72f',\n 'wm_visitid': 'a4e9e15e-9258-4c40-8b0b-b97137c0571f'\n }\n\n for key, value in sign_data.items():\n sign_data[key] = data.get(key, value)\n\n sign = url_encode(json.dumps(dict_to_str(sign_data)), False).decode()\n\n token_data = {\n \"rId\": 100016,\n \"ts\": str(int(time.time()) * 1000),\n \"cts\": str(int(time.time()) * 1000 + 1258745),\n \"brVD\": [414, 624],\n \"brR\": [[1242, 1872], [1242, 1872], 24, 24],\n \"bI\": [\"pages/index/index\", \"\"],\n \"mT\": [],\n \"kT\": [],\n \"aT\": [],\n \"tT\": [],\n \"sign\": sign\n }\n token = url_encode(json.dumps(token_data)).decode()\n\n self.finish(token)\n\n\nclass GetWXInfoToken(RedisHandler):\n async def post(self, *args, **kwargs):\n data = self.request.body.decode()\n data = json.loads(base64.b64decode(data).decode())['post_data']\n\n sign_data = {\n 'uuid': '',\n 'open_id': '',\n 'platform': 13,\n 'partner': 4,\n 'riskLevel': 4,\n 'ref_list_id': '',\n 'rank_list_id': '',\n 'wmpoiid': '',\n 'nickName': '',\n 'avatarUrl': '',\n 'gender': 1,\n 'city': '',\n 'province': '',\n 'country': '',\n 'lch': 1089,\n 'wm_dplatform': '',\n 'user_id': '',\n 'userid': '',\n 'wm_actual_latitude': '',\n 'wm_actual_longitude': '',\n 'waimai_sign': '/',\n 'req_time': '',\n 'userToken': '',\n 'wm_logintoken': '',\n 'wm_appversion': '',\n 'wm_visitid': '',\n 'wm_latitude': '',\n 'wm_longitude': '',\n 'wm_uuid': '',\n 'wm_dversion': '',\n 'wm_dtype': '',\n 'wm_ctype': ''\n }\n\n for key, value in sign_data.items():\n sign_data[key] = data.get(key, value)\n\n sign = url_encode(json.dumps(dict_to_str(sign_data)), False).decode()\n\n token_data = {\n \"rId\": 100016,\n \"ts\": str(int(time.time()) * 1000),\n \"cts\": str(int(time.time()) * 1000 + 18345),\n \"brVD\": [414, 624],\n \"brR\": [[1242, 1872], [1242, 1872], 24, 24],\n \"bI\": [\"pages/restaurant/restaurant\", \"pages/index/index\"],\n \"mT\": [],\n \"kT\": [],\n \"aT\": [],\n \"tT\": [],\n \"sign\": sign\n }\n token = url_encode(json.dumps(token_data)).decode()\n\n self.finish(token)\n","sub_path":"apps/admin/spider/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"181050561","text":"\n\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.isEnd = False\n self.count = 0\n self.query = None\n\nclass AutocompleteSystem(object):\n def __init__(self, sentences, times):\n self.root = TrieNode()\n self.query = \"\"\n for i , sentence in enumerate(sentences):\n self.addRecord(sentence, times[i])\n \n \n def addRecord(self,sentence, count):\n \"\"\"\n \"\"\"\n r = self.root\n for c in sentence:\n if c not in r.children:\n r.children[c] = TrieNode()\n r = r.children[c] \n r.count += count\n r.isEnd = True\n r.query = sentence\n \n \n def dfsUtil(self, node):\n ret = []\n \n if node:\n if node.isEnd:\n ret.append((node.count, node.query))\n for child in node.children:\n ret.extend(self.dfsUtil(node.children[child]))\n return ret\n \n \n def search(self, query):\n r = self.root\n \n \n for c in query:\n if c in r.children:\n r = r.children[c]\n else:\n return []\n \n return self.dfsUtil(r)\n \n def input(self, c): \n \"\"\"\n \"\"\"\n results = []\n if c != \"#\":\n self.query += c\n results = self.search(self.query) \n else:\n self.addRecord(self.query, 1) \n self.query = \"\"\n \n results = [ hotword[1] for hotword in sorted(results, key = lambda x :x[0], reverse = True)[:3]]\n \n #print(results)\n return results\n \n \n \nclass AutocompleteSystem1(object):\n def __init__(self, sentences, times):\n self.root = TrieNode()\n self.keyword = \"\"\n for i, sentence in enumerate(sentences):\n self.addRecord(sentence, times[i])\n\n def addRecord(self, sentence, hot):\n p = self.root\n #print(\"addRecord\" , sentence)\n for c in sentence:\n #print(c)\n if c not in p.children:\n p.children[c] = TrieNode()\n p = p.children[c]\n p.isEnd = True\n p.data = sentence\n p.rank = hot\n \n def dfs(self, root):\n ret = []\n if root:\n if root.isEnd:\n ret.append((root.rank, root.data))\n for child in root.children:\n ret.extend(self.dfs(root.children[child]))\n return ret\n \n def search(self, sentence):\n p = self.root\n for c in sentence:\n if c not in p.children:\n return []\n p = p.children[c]\n return self.dfs(p)\n \n def input(self, c):\n results = []\n if c != \"#\":\n self.keyword += c\n results = self.search(self.keyword)\n else:\n self.addRecord(self.keyword, 1)\n self.keyword = \"\"\n print([item[1] for item in sorted(results)[:3]])\n return [item[1] for item in sorted(results)[:3]]\n\nif __name__ == \"__main__\":\n \n #[\"AutocompleteSystem\",\"input\",\"input\",\"input\",\"input\"]\n #[[[\"i love you\",\"island\",\"iroman\",\"i love leetcode\"],[5,3,2,2]],[\"i\"],[\" \"],[\"a\"],[\"#\"]]\n \n s = [\"i love you\",\"island\",\"ironman\",\"i love leetcode\", \"My Name is Vishal\", \"ilu hate you\", \"ironwoman\", \"Mahi\", \"i love Megan\"]\n t = [5,3,2,2,6,1,1,2, 3]\n \n sol = AutocompleteSystem(s, t)\n iput = \"i love leetpode\"\n iput = list(iput) + [\"#\"]\n \n \n for c in iput:\n sol.input(c)\n \n iput = \"i love leetcode\"\n iput = list(iput) + [\"#\"]\n for c in iput:\n sol.input(c)\n \n ","sub_path":"Leetcode/leetcode642DesignSearchAutocompleteSystem.py","file_name":"leetcode642DesignSearchAutocompleteSystem.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"314491102","text":"#!/usr/bin/env python\n#-*- conding:utf-8 -*-\nimport os\nimport chardet\nimport codecs\nimport re\nimport jieba\nimport copy\n\n\"\"\"\n对复述段进行分句\n\"\"\"\ndef new_similarity(list1,list2):\n stop_words = ['是', '的', '好', '好的', '了', '吧', '嗯', '呢', ',', ',', '啊', '呀','.','。','、',';',';','得']\n\n list1_copy = copy.copy(list1) #浅拷贝\n list2_copy = copy.copy(list2)\n for i in list1_copy:\n if i in stop_words:\n list1.remove(i)\n for j in list2_copy:\n if j in stop_words:\n list2.remove(j)\n\n if len(list1) == 0 or len(list2) == 0:\n sim = 0\n\n else:\n sum = list1 + list2\n count = 0\n if len(list1) < len(list2) :\n for word in list1:\n if word in list2:\n count += 1\n else:\n for word in list2 :\n if word in list1:\n count += 1\n\n sim = count / len(sum)\n return sim\n\ndef sentencesList(filename):\n txt = [] #复述段落的列表\n with open(filename,encoding='utf-8') as f:\n for line in f:\n if line.strip():\n line = line.replace('……', '。') # 识别不出六个点的省略号\n line = re.sub(r'[\"“”]','',line)\n txt.append(line.strip())\n\n sentences_list = []\n for i in txt[2:]:\n list1 = re.split(r'([。??!!;::;])',i)\n\n flag = 0\n if (list1[-1] != ''): #末尾没有标点符号 flag=1\n flag = 1\n list1.append(\"\")\n\n if flag == 1:\n list1 = [\"\".join(i) for i in zip(list1[0::2], list1[1::2])] #复述段落的开始两段不要\n else:\n list1 = [\"\".join(i) for i in zip(list1[0::2], list1[1::2])][:-1]\n\n sentences_list.append(list1)\n\n return sentences_list\n\ndef writeFinallist(txt_list): #txts 是名著的一个列表,遍历访问\n for txt in txt_list:\n sentences_list = sentencesList(os.path.join(source_path,txt)) #[[每个段落的句子],[每个段落的句子]]\n final_list = [] #[句子+\\n+句子]\n for i in range(0,len(sentences_list)-1,2):\n list1 = sentences_list[i]\n list2 = sentences_list[i+1]\n if len(list1) == len(list2):\n continue_flag = 1\n for t in range(0,len(list1)):\n if len(list1[t]) > len(list2[t])*1.5 or len(list2[t]) > len(list1[t])*1.5 :\n continue_flag = 0\n if len(list1[t]) < 5 or len(list2[t]) < 5:\n continue_flag = 0\n\n if continue_flag:\n list3 = ['\\n'.join(j) for j in zip(list1, list2)]\n for j in list3:\n final_list.append(j)\n\n else: #len(list1) != len(list2)\n words_list1 = [jieba.lcut(sentence) for sentence in list1]\n words_list2 = [jieba.lcut(sentence) for sentence in list2]\n\n for m in range(0, len(words_list1)):\n if len(list1[m]) > 5:\n max = 0\n k = 0\n for n in range(0, len(words_list2)):\n if len(list2[n]) > 5:\n sim = new_similarity(words_list1[m], words_list2[n])\n if sim > max:\n max = sim\n k = n\n\n if 0.9 >max> 0.28 and len(list1[m]) 5:\n max = 0\n k = 0\n for n in range(0,len(words_list2)):\n if len(list2[n]) > 5:\n sim = new_similarity(words_list1[m],words_list2[n])\n if sim > max:\n max = sim\n k = n\n\n if 0.9>max>0.28 and len(list1[m]) ISBN-13, Title, Authors, Publisher, Year, Language\n try:\n # mapping: canonical <- records\n canonical = {}\n canonical['ISBN-13'] = u(isbn)\n # assert isbn == records['isbn13'], \"isbn was mungled!\"\n canonical['Title'] = records.get('title', u(''))\n authors = [a['name'] for a in records['author_data']]\n canonical['Authors'] = authors\n canonical['Publisher'] = records.get('publisher_name', u(''))\n canonical['Year'] = u('')\n if 'edition_info' in records:\n match = re.search(PATT_YEAR, records['edition_info'])\n if match:\n canonical['Year'] = str(match.group(0))\n canonical['Language'] = records.get('language', u(''))\n except:\n raise RecordMappingError(isbn)\n # call stdmeta for extra cleanning and validation\n return stdmeta(canonical)\n\n\ndef _records(isbn, data):\n \"\"\"Classify (canonically) the parsed data.\"\"\"\n # check status\n try:\n err = data.get('error', '')\n if err:\n raise\n except:\n LOGGER.debug('DataWrongShapeError for %s with status %s', isbn, err)\n raise DataWrongShapeError(\"error: '%s' for isbn %s\" % (err, isbn))\n # put the selected data in records\n try:\n recs = data['data'][0]\n except: # pragma: no cover\n LOGGER.debug('NoDataForSelectorError for %s', isbn)\n raise NoDataForSelectorError(isbn)\n # consistency check (isbn request = isbn response)\n if recs:\n ids = recs.get('isbn13', '')\n if isbn not in repr(ids): # pragma: no cover\n LOGGER.debug('ISBNNotConsistentError for %s (%s)', isbn, repr(ids))\n raise ISBNNotConsistentError(\"%s not in %s\" % (isbn, repr(ids)))\n # map canonical <- records\n return _mapper(isbn, recs)\n\n\ndef query(isbn):\n \"\"\"Query the isbndb.org service for metadata.\"\"\"\n if not apikeys.get('isbndb'):\n raise NoAPIKeyError\n data = wquery(SERVICE_URL.format(apikey=apikeys['isbndb'],\n isbn=isbn),\n user_agent=UA)\n return _records(isbn, data)\n","sub_path":"env/Lib/site-packages/isbnlib/_isbndb.py","file_name":"_isbndb.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"366700211","text":"# coding: utf-8\nfrom django.shortcuts import render, redirect\nfrom crm.models import Product\nfrom django.contrib.auth import authenticate, logout, login\nfrom django.contrib.auth.models import User, Group, Permission\n\n\n# Это временное решение, будет ГРАМОТНО объединено с product_change\ndef product_list(request):\n product_list = Product.objects.all()\n return render(request, 'crm/product_list.html', {\n 'product_list': product_list,\n })\n\n\n# Это временное решение\ndef product_change(request):\n # if request.user.groups not request.Permission:\n product_list = Product.objects.all()\n return render(request, 'crm/product_change.html', {\n 'product_list': product_list,\n })\n\n\n# Только завтсклад\ndef product_delete(request, product_id):\n p = Product.objects.get(pk=product_id)\n p.delete()\n # return redirect('/product/change/')\n return redirect('product_change')\n\n\n# Только завтсклад\ndef product_create(request):\n Product.objects.create(\n product_name=request.GET['product_name'],\n status=request.GET['status'],\n product_count=request.GET['product_count'],\n )\n return redirect('product_change')\n\n\n# Для завсклада и поставщика\ndef product_update(request, product_id):\n p = Product.objects.get(pk=product_id)\n p.product_name = request.GET['product_name']\n p.status = request.GET['status']\n p.product_count = request.GET['product_count']\n p.save()\n return redirect('product_change')\n\n\n# Только для продавца\ndef product_sold(request):\n p = Product.objects.get(pk=request.GET['product_id'])\n p.product_count -= int(request.GET['sold_count'])\n p.save()\n return redirect('root')\n\n\n# Это, то как я вижу авторизацию\ndef authUser(request, authUser):\n if \"login\" in authUser:\n user = authenticate(username=request.GET['nicname'], password=request.GET['password'])\n if user is not None:\n login(request, user)\n return redirect('root')\n else:\n return render(request, 'crm/error.html')\n elif \"logout\" in authUser:\n logout(request)\n return redirect('root')\n\n\n# Здесь будет создание юзера, только для завсклада\ndef createUser(request):\n pass\n","sub_path":"crm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"102010470","text":"# 시간초과\n# 각 수가 적힌 숫자 카드를 상근이가 몇 개 가지고 있는지 출력하기\ndef binary_search(array, target, start, end):\n if start > end:\n return False\n \n mid = (start+end) // 2\n \n if array[mid] == target:\n dict[array[mid]] += 1\n\n binary_search(array, target, start, mid - 1)\n binary_search(array, target, mid + 1, end)\n\n return True\n\nN = int(input())\n\nA = list(map(int, input().split()))\n\nA.sort()\n\nM = int(input())\n\narray = list(map(int, input().split()))\n\ndict = {}\n\nfor i in array:\n dict[i] = 0\n\nfor i in range(M):\n result = binary_search(A, array[i], 0, N-1)\n \n if result == False:\n print(0, end=' ')\n else:\n print(dict[array[i]], end=' ')\n\n\n# 시간 초과를 해결하기 위해 다른 방법 모색\n# Counter 이용\nimport sys\n\nfrom collections import Counter\n\nN = int(sys.stdin.readline())\n\nA = list(map(int, sys.stdin.readline().split()))\n\nCount_A = Counter(A)\n\nM = int(sys.stdin.readline())\n\narray = list(map(int, sys.stdin.readline().split()))\n\nfor i in array:\n if i in Count_A:\n print(Count_A[i], end=' ')\n else:\n print(0, end=' ')\n\n# 딕셔너리를 이용하는 방법도 생각해 볼 것 \n","sub_path":"BAEKJOON/이분 탐색/10816_숫자 카드2.py","file_name":"10816_숫자 카드2.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"103168659","text":"#!/usr/bin/env python\n\nimport sys\n\n\nfrom none_iss_simple_client import MicexISSClient\nfrom none_iss_simple_client import MicexISSDataHandler\n\n\nclass MyData:\n # Контейнер, который будет использоваться обработчиком для хранения данных.\n # Хранится отдельно от обработчика в целях масштабируемости: чтобы дифференцировать хранение и вывод от обработки.\n\n def __init__(self):\n self.history = []\n\n def print_history(self):\n print(\"=\" * 49)\n print(\"|%15s|%15s|%15s|\" % (\"SECID\", \"CLOSE\", \"TRADES\"))\n print(\"=\" * 49)\n for sec in self.history:\n print(\"|%15s|%15.2f|%15d|\" % (sec[0], sec[1], sec[2]))\n print(\"=\" * 49)\n\n\nclass MyDataHandler(MicexISSDataHandler):\n #This handler will be receiving pieces of data from the ISS client.\n\n def do(self, market_data):\n # Just as an example we add all the chunks (ломти) to one list.\n # In real application other options should be considered because some server replies may be too big to be kept in memory.\n self.data.history = self.data.history + market_data\n\n\ndef main():\n iss = MicexISSClient(MyDataHandler, MyData)\n iss.get_history_securities('stock',\n 'shares',\n 'eqne',\n '2010-04-29')\n iss.handler.data.print_history()\n\nif __name__ == '__main__':\n try:\n main()\n except:\n print(\"Sorry:\", sys.exc_info())\n","sub_path":"none_iss_simple_main.py","file_name":"none_iss_simple_main.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"409839779","text":"# Import modules\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_geometric.data import Data\nfrom torch_geometric.data import DataLoader\nfrom torch_geometric.nn import MessagePassing\nfrom torch_geometric.utils import degree\nfrom torch_scatter import scatter_mean\n\n# Synthetic training set of 1000 molecules\nmolecules = []\nfor _ in range(1000):\n\n # 3 to 10 atoms (nodes) per molecule\n atom_count = np.random.randint(3, 11)\n\n # 3 features (atom types) per node\n node_feature = torch.zeros((atom_count, 3), dtype=torch.float)\n atom_types = np.random.randint(0, 3, atom_count)\n node_feature[np.arange(atom_count), atom_types] = 1\n\n # Molecule is a string of atoms with undirected edges\n edge_unit = torch.tensor([[0, 1],\n [1, 0]], dtype=torch.long)\n edge_index = torch.cat(tuple([i + edge_unit for i in range(atom_count - 1)]), dim=1)\n\n # Single or double bond\n bond_type = [torch.tensor([[1, 0], [1, 0]], dtype=torch.float),\n torch.tensor([[0, 1], [0, 1]], dtype=torch.float)]\n edge_attr = torch.cat(tuple([bond_type[np.random.randint(2)]\n for i in range(atom_count - 1)]), dim=0)\n\n # Label molecule as a hit if atom type 0 appears three times in a row\n for i in range(atom_count - 1):\n if node_feature[i:i + 2, 0].sum() == 2 and edge_attr[2 * i:(2 * i) + 2, 0].sum() == 2:\n y = torch.tensor([1], dtype=torch.long)\n break\n else:\n y = torch.tensor([0], dtype=torch.long)\n\n # Store graph in variable\n molecules.append(Data(x=node_feature, edge_index=edge_index, edge_attr=edge_attr, y=y))\n\n# Create dataloaders\ntrain_loader = DataLoader(molecules[:800], batch_size=50)\ntest_loader = DataLoader(molecules[800:], batch_size=200)\n\n\n# Custom Graph Convolutional Network\nclass MyGCNConv(MessagePassing):\n def __init__(self, in_channels, out_channels, edge_channels):\n super(MyGCNConv, self).__init__(aggr='mean')\n self.lin1 = torch.nn.Linear(in_channels, out_channels)\n self.lin2 = torch.nn.Linear(in_channels, out_channels, bias=False)\n self.lin3 = torch.nn.Linear(edge_channels, out_channels, bias=False)\n\n def forward(self, x, edge_index, edge_attr):\n # x = [nodes, in_channels]\n # edge_index = [2, directed edges]\n\n # Linear transformation of central node feature matrix\n x_i = self.lin1(x)\n\n # Linear transformation of neighbor node feature matrix\n x_j = self.lin2(x)\n\n # Propagate messages\n return self.propagate(edge_index, x=x_j, edge_attr=edge_attr, center=x_i)\n\n def message(self, x_j, edge_index, edge_attr):\n # x_j = [directed edges, out_channels]\n\n # Add linearly transformed edge features to node features\n x_j += self.lin3(edge_attr)\n\n # Normalize neighbor features\n row, col = edge_index\n deg = degree(row, dtype=x_j.dtype)\n deg_inv_sqrt = deg.pow(-0.5)\n norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]\n\n return norm.view(-1, 1) * x_j\n\n def update(self, aggr_out, center):\n # aggr_out = [nodes, out_channels]\n\n # Sum new central and neighbor node embeddings\n return center + aggr_out\n\n\n# Two-layer GCN with MLP classfier\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = MyGCNConv(3, 16, 2)\n self.conv2 = MyGCNConv(16, 16, 2)\n self.lin1 = nn.Linear(16, 16)\n self.lin2 = nn.Linear(16, 2)\n\n def forward(self, batch):\n\n # Retrieve node features and edge indices from batch\n x, edge_index, edge_attr = batch.x, batch.edge_index, batch.edge_attr\n\n # Graph convolutional layers\n x = self.conv1(x, edge_index, edge_attr)\n x = F.relu(x)\n x = F.dropout(x, training=self.training)\n x = self.conv2(x, edge_index, edge_attr)\n x = F.relu(x)\n x = F.dropout(x, training=self.training)\n\n # Average hidden node representations\n x = scatter_mean(x, batch.batch, dim=0)\n\n # Multilayer perceptron\n x = self.lin1(x)\n x = F.relu(x)\n x = self.lin2(x)\n\n return x\n\n\n# Instantiate model\nmodel = Net()\n\n# Initialize optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n# Train model for 500 epoches\nprint('\\n%===TRAINING===%')\nmodel.train()\nfor epoch in range(500 + 1):\n for batch in train_loader:\n optimizer.zero_grad()\n out = model(batch)\n loss = criterion(out, batch.y)\n loss.backward()\n optimizer.step()\n if epoch % 10 == 0:\n print(f'Epoch {epoch:3d}: Loss = {loss:.4f}')\n\n# Evaluate model performance\nmodel.eval()\nfor batch in test_loader:\n _, pred = model(batch).max(dim=1)\n correct = pred.eq(batch.y).sum().item()\n acc = correct / len(batch.y)\n print(f'Final Accuracy: {acc:.3f}')\n","sub_path":"testing/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"473071619","text":"# -*- coding: utf-8 -*-\nimport os\nfrom functools import wraps\nimport time\nimport ConfigParser\n\nimport pepper\n\n\ndef login_required(func):\n @wraps(func)\n def func_wrapper(self, *args, **kwargs):\n if not getattr(self, 'auth', None):\n self.login()\n elif time.time() > self.auth['expire']:\n self.login()\n try:\n ret = func(self, *args, **kwargs)\n except pepper.PepperException as e:\n if str(e) == \"Authentication denied\":\n # when service salt-api restart, the old tokens are revoked,\n # the client does not konw that, and still use the old token.\n # So when we got 'Authentication denied', we re-login once,\n # and try again.\n self.login()\n ret = func(self, *args, **kwargs)\n else:\n raise\n return ret\n return func_wrapper\n\n\nclass Mill(object):\n def __init__(self, debug_http=False, *args, **kwargs):\n self.configure(**kwargs)\n self._pepper = pepper.Pepper(self.login_details['SALTAPI_URL'],\n debug_http=debug_http)\n\n def configure(self, **kwargs):\n '''\n Get salt-api login configurations.\n Source & order:\n kwargs > environment variables > ~/.pepperrc\n '''\n # default settings\n details = {\n 'SALTAPI_URL': 'https://localhost:8000/',\n 'SALTAPI_USER': 'saltdev',\n 'SALTAPI_PASS': 'saltdev',\n 'SALTAPI_EAUTH': 'auto',\n }\n\n # read from ~/.pepperrc\n config = ConfigParser.RawConfigParser()\n config.read(os.path.expanduser('~/.pepperrc'))\n profile = 'main'\n if config.has_section(profile):\n for key, value in config.items(profile):\n key = key.upper()\n details[key] = config.get(profile, key)\n\n # get environment values\n for key, value in details.items():\n details[key] = os.environ.get(key, details[key])\n\n # get Mill().__init__ parameters\n for key, value in details.items():\n details[key] = kwargs.get(key.lower().lstrip('saltapi_'),\n details[key])\n # pass is a Python keyword, use password instead\n details['SALTAPI_PASS'] = kwargs.get('password', details['SALTAPI_PASS']) # noqa\n\n self.login_details = details\n\n def login(self):\n '''\n simple wrapper for Pepper.login()\n '''\n self.auth = self._pepper.login(\n self.login_details['SALTAPI_USER'],\n self.login_details['SALTAPI_PASS'],\n self.login_details['SALTAPI_EAUTH'],\n )\n\n @login_required\n def lookup_jid(self, jid):\n return self._pepper.lookup_jid(jid)\n\n @login_required\n def local(self, *args, **kwargs):\n return self._pepper.local(*args, **kwargs)\n\n @login_required\n def local_async(self, *args, **kwargs):\n return self._pepper.local_async(*args, **kwargs)\n\n @login_required\n def runner(self, *args, **kwargs):\n return self._pepper.runner(*args, **kwargs)\n\n\ndefault_mill = Mill()\n","sub_path":"saltmill/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45816621","text":"'''\nj从后面开始\n每次把最小的冒泡到i位置\n'''\ndef BubbleSort(a):\n for i in range(len(a)):\n for j in range(len(a)-1):\n if a[j]>a[j+1]:\n a[j],a[j+1]=a[j+1],a[j]\ndef BubbleSort2(a):\n for i in range(len(a)):\n j=len(a)-1\n while j>i:\n if a[j] List[int]:\n if len(nums) == 0:\n return []\n stack = [0]\n result = [-1]*len(nums)\n for idx in range(1,2*len(nums)+1):\n while len(stack) > 0 and nums[idx % len(nums)] > nums[stack[-1]]:\n val = stack.pop()\n print(val)\n if val != idx :\n result[val] = nums[idx % len(nums)]\n stack.append(idx % len(nums))\n \n return result","sub_path":"nextGreaterElements.py","file_name":"nextGreaterElements.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"207720452","text":"\nimport socket\nfrom socket import AF_INET,SOCK_STREAM\n\n# 1 创建一个套接字对象(socket) AF_INET: ipv4协议 SOCK_STREAM: TCP协议\nsock=socket.socket(family=AF_INET, type=SOCK_STREAM)\n# 2 绑定IP与端口\nsock.bind((\"127.0.0.1\",8800))\n# 3 创建监听数\nsock.listen(5)\n\n# 4 等待连接,一旦客户请求到来,返回两个值:客户端的套接字对象,客户端的地址\nwhile 1:\n print(\"waiting a connect.....\")\n conn, addr = sock.accept()\n while 1:\n try:\n data = conn.recv(1024)\n # 针对window\n except Exception as e:\n break\n # 针对linux\n if len(data) == 0:\n break\n print(\"客户:\", data.decode())\n if data.decode() == \"quit\":\n conn.close()\n break\n res = input(\"响应 >>>\")\n conn.send(res.encode())\n\n\n\n\n\n\n","sub_path":"09 day09/01 老师笔记/02 聊天室/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"219204841","text":"\"\"\"Escribir una función que pida un número entero entre 1 y 10,\nlea el fichero tabla-n.txt con la tabla de multiplicar de ese número,\ndonde n es el número introducido, y la muestre por pantalla.\nSi el fichero no existe debe mostrar un mensaje por pantalla informando de ello\"\"\"\n\n# Sol 1\n\n\"\"\"n = int(input('Ingrese un número del 1 al 10: '))\nnombre_archivo = 'tabla-' + str(n) + '.txt'\n\ntry:\n muestra = open(nombre_archivo,'r')\nexcept FileNotFoundError:\n print('No existe el archivo con la tabla del #',n)\n\nelse:\n print(muestra.read())\n\n# print(muestra.read())\"\"\"\n\n# Sol 2\n\n\"\"\"n = int(input('Introduce un número entero entre 1 y 10: '))\nfile_name = 'tabla-' + str(n) + '.txt'\ntry:\n f = open(file_name, 'r')\nexcept FileNotFoundError:\n print('No existe el fichero con la tabla del', n)\nelse:\n print(f.read())\"\"\"\n\n# Sol 3\n\nn = int(input('Ingrese un número entero del 1 al 10: '))\nfn = 'Tabla-' + str(n) + '.txt'\n\ntry:\n f = open(fn,'r')\nexcept FileNotFoundError:\n print('No existe el fichero: ',fn)\nelse:\n print(f.read())","sub_path":"Ejercicios_Web/Ficheros/ejercicio2.py","file_name":"ejercicio2.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"523648654","text":"class Solution:\n\tdef isLess(self, n1, n2):\n\t\treturn int(str(n1)+str(n2)) < int(str(n2)+str(n1))\n\t\n\tdef merge(self, n1,n2):\n\t\tj = 0;\n\t\tfor i in range(len(n1)):\n\t\t\twhile j=2:\n\t\t\tmid = int(l / 2)\n\t\t\treturn self.merge(self.sort(numbers[:mid]), self.sort(numbers[mid:]))\n\t\telse:\n\t\t\treturn numbers;\n\t\t\n\t\n\tdef PrintMinNumber(self, numbers):\n\t\treturn ''.join(list(map(lambda i:str(i) ,self.sort(numbers))))\n\nsolution = Solution()\nprint(solution.PrintMinNumber([3,32,321]))\n","sub_path":"剑指offer/032-把数组排成最小的数/myCode.py","file_name":"myCode.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"477781484","text":"import streamlit as st\nfrom sklearn import datasets\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt \n\nst.title(\"Classification App\")\n\nname = st.sidebar.selectbox(\"Select Dataset\", [\"Iris\", \"Breast Cancer\", \"Wine\"])\nst.write(\"Dataset name : \", name)\n\nclassifier_name = st.sidebar.selectbox(\"Select Classifier\", [\"KNN\", \"SVM\"])\n\ndef get_dataset(dataset_name):\n\tselector = {\"Iris\" : \"datasets.load_iris()\",\n\t\t\t\t\"Breast Cancer\" : \"datasets.load_breast_cancer()\",\n\t\t\t\t\"Wine\" : \"datasets.load_wine()\"}\n\tdata = eval(selector[dataset_name])\n\tx = data.data\n\ty = data.target\n\treturn x, y\n\nx, y = get_dataset(name)\nst.write(\"Size :\", len(x))\nst.write(\"Labels :\", len(set(y)))\n\n\ndef get_values(classifier_name):\n\tselector = {\n\t\t\"KNN\" : \"st.sidebar.slider('K', 1, 15)\",\n\t\t\"SVM\" : \"st.sidebar.slider('C', 0.01, 10.0)\"\n\t}\n\tout = \"K\" if classifier_name == \"KNN\" else \"C\"\n\ttmp = eval(selector[classifier_name])\n\treturn {out : tmp}\n\ndef create_and_clasify(name, x, y, para):\n\tprint(para)\n\tx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n\tif name == \"KNN\":\n\t\tclf = KNeighborsClassifier(n_neighbors=para[\"K\"])\n\t\tclf.fit(x_train, y_train)\n\telse:\n\t\tclf = svm.SVC(C=para[\"C\"])\n\t\tclf.fit(x_train, y_train)\n\ty_model = clf.predict(x_test)\n\tacc = accuracy_score(y_test, y_model)\n\treturn acc \n\n\nout = get_values(classifier_name)\nacc = create_and_clasify(classifier_name, x, y, out)\nst.write(\"Accuracy :\", acc)\n\npca = PCA(2)\n\nprint(len(x))\nx_proj = pca.fit_transform(x)\nx1 = x_proj[:, 0]\nx2 = x_proj[:, 1]\nfig = plt.figure()\nplt.scatter(x1, x2, c=y, alpha=0.8, cmap=\"viridis\")\nplt.xlabel(\"Principle Component 1\")\nplt.ylabel(\"Principle Component 2\")\nplt.colorbar()\nst.pyplot(fig)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"221409471","text":"# -*- coding: utf-8 -*-\n#\n# ramstk.revision.Controller.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2007 - 2017 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"Validation Package Data Controller Module.\"\"\"\n\nfrom pubsub import pub\n\n# Import other RAMSTK modules.\nfrom ramstk.modules import RAMSTKDataController\nfrom ramstk.modules import RAMSTKDataMatrix\nfrom ramstk.dao import RAMSTKHardware, RAMSTKRequirement, RAMSTKValidation\nfrom . import dtmValidation\n\n\nclass ValidationDataController(RAMSTKDataController):\n \"\"\"\n Provide an interface between Validation data models and RAMSTK views.\n\n A single Validation data controller can manage one or more Failure\n Validation data models.\n \"\"\"\n\n def __init__(self, dao, configuration, **kwargs):\n \"\"\"\n Initialize a Validation data controller instance.\n\n :param dao: the data access object used to communicate with the\n connected RAMSTK Program database.\n :type dao: :class:`ramstk.dao.DAO.DAO`\n :param configuration: the RAMSTK configuration instance.\n :type configuration: :class:`ramstk.Configuration.Configuration`\n \"\"\"\n RAMSTKDataController.__init__(\n self,\n configuration,\n model=dtmValidation(dao),\n ramstk_module='validation',\n **kwargs)\n\n # Initialize private dictionary attributes.\n\n # Initialize private list attributes.\n\n # Initialize private scalar attributes.\n self._dmx_vldtn_rqrmnt_matrix = RAMSTKDataMatrix(\n dao, RAMSTKValidation, RAMSTKRequirement)\n self._dmx_vldtn_hw_matrix = RAMSTKDataMatrix(dao, RAMSTKValidation,\n RAMSTKHardware)\n\n # Initialize public dictionary attributes.\n\n # Initialize public list attributes.\n\n # Initialize public scalar attributes.\n\n def request_do_create(self, revision_id, matrix_type):\n \"\"\"\n Request to create or refresh a Validation matrix.\n\n :param int revision_id: the ID of the Revision the desired Matrix is\n associated with.\n :param str matrix_type: the type of the Matrix to select all rows and\n all columns for.\n \"\"\"\n if matrix_type == 'vldtn_rqrmnt':\n self._dmx_vldtn_rqrmnt_matrix.do_create(\n revision_id,\n matrix_type,\n rkey='validation_id',\n ckey='requirement_id')\n elif matrix_type == 'vldtn_hrdwr':\n self._dmx_vldtn_hw_matrix.do_create(\n revision_id,\n matrix_type,\n rkey='validation_id',\n ckey='hardware_id')\n\n return\n\n def request_do_select_all_matrix(self, revision_id, matrix_type):\n \"\"\"\n Retrieve all the Matrices associated with the Requirement module.\n\n :param int revision_id: the Revision ID to select the matrices for.\n :param int matrix_type: the type of the Matrix to retrieve. Current\n Validation matrix types are:\n\n vldtn_hrdwr = Requirement:Hardware\n\n :return: (_matrix, _column_hdrs, _row_hdrs); the Pandas Dataframe,\n noun names to use for column headings, noun names to use for\n row headings.\n :rtype: (:class:`pandas.DataFrame`, dict, dict)\n \"\"\"\n _matrix = None\n _column_hdrs = []\n _row_hdrs = []\n\n if matrix_type == 'vldtn_rqrmnt':\n self._dmx_vldtn_rqrmnt_matrix.do_select_all(\n revision_id,\n matrix_type,\n rkey='validation_id',\n ckey='requirement_id',\n rheader='description',\n cheader='requirement_code')\n _matrix = self._dmx_vldtn_rqrmnt_matrix.dtf_matrix\n _column_hdrs = self._dmx_vldtn_rqrmnt_matrix.dic_column_hdrs\n _row_hdrs = self._dmx_vldtn_rqrmnt_matrix.dic_row_hdrs\n elif matrix_type == 'vldtn_hrdwr':\n self._dmx_vldtn_hw_matrix.do_select_all(\n revision_id,\n matrix_type,\n rkey='validation_id',\n ckey='hardware_id',\n rheader='description',\n cheader='comp_ref_des')\n _matrix = self._dmx_vldtn_hw_matrix.dtf_matrix\n _column_hdrs = self._dmx_vldtn_hw_matrix.dic_column_hdrs\n _row_hdrs = self._dmx_vldtn_hw_matrix.dic_row_hdrs\n\n return (_matrix, _column_hdrs, _row_hdrs)\n\n def request_do_insert(self, **kwargs):\n \"\"\"\n Request to add an RAMSTKValidation table record.\n\n :param int revision_id: the Revision ID this Validation will be\n associated with.\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n _revision_id = kwargs['revision_id']\n _error_code, _msg = self._dtm_data_model.do_insert(\n revision_id=_revision_id)\n\n if _error_code == 0:\n self._configuration.RAMSTK_USER_LOG.info(_msg)\n\n if not self._test:\n pub.sendMessage('insertedValidation')\n else:\n _msg = _msg + ' Failed to add a new Validation to the ' \\\n 'RAMSTK Program database.'\n self._configuration.RAMSTK_DEBUG_LOG.error(_msg)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n None)\n\n def request_do_insert_matrix(self, matrix_type, item_id, heading,\n row=True):\n \"\"\"\n Request the to add a new row or column to the Data Matrix.\n\n :param str matrix_type: the type of the Matrix to retrieve. Current\n Validation matrix types are:\n\n vldtn_hrdwr = Validation:Hardware\n\n :param int item_id: the ID of the row or column item to insert into the\n Matrix.\n :param str heading: the heading for the new row or column.\n :keyword bool row: indicates whether to insert a row (default) or a\n column.\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n if matrix_type == 'vldtn_rqrmnt':\n _error_code, _msg = self._dmx_vldtn_rqrmnt_matrix.do_insert(\n item_id, heading, row=row)\n elif matrix_type == 'vldtn_hrdwr':\n _error_code, _msg = self._dmx_vldtn_hw_matrix.do_insert(\n item_id, heading, row=row)\n\n if _error_code == 0 and not self._test:\n pub.sendMessage(\n 'insertedMatrix',\n matrix_type=matrix_type,\n item_id=item_id,\n row=row)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n None)\n\n def request_do_delete(self, node_id):\n \"\"\"\n Request to delete an RAMSTKValidation table record.\n\n :param int node_id: the PyPubSub Tree() ID of the Validation task to\n delete.\n :return: (_error_code, _msg); the error code and associated error\n message.\n :rtype: (int, str)\n \"\"\"\n _error_code, _msg = self._dtm_data_model.do_delete(node_id)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n 'deletedValidation')\n\n def request_do_delete_matrix(self, matrix_type, item_id, row=True):\n \"\"\"\n Request to remove a row or column from the selected Data Matrix.\n\n :param int matrix_type: the type of the Matrix to retrieve. Current\n Validation matrix types are:\n\n rqrmnt_hrdwr = Validation:Hardware\n\n :param int item_id: the ID of the row or column item to remove from the\n Matrix.\n :keyword bool row: indicates whether to insert a row (default) or a\n column.\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n if matrix_type == 'vldtn_rqrmnt':\n _error_code, _msg = self._dmx_vldtn_rqrmnt_matrix.do_delete(\n item_id, row=row)\n elif matrix_type == 'vldtn_hrdwr':\n _error_code, _msg = self._dmx_vldtn_hw_matrix.do_delete(\n item_id, row=row)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n 'deletedMatrix')\n\n def request_do_update(self, node_id):\n \"\"\"\n Request to update an RAMSTKValidation table record.\n\n :param int node_id: the PyPubSub Tree() ID of the Validation task to\n delete.\n :return: (_error_code, _msg); the error code and associated error\n message.\n :rtype: (int, str)\n \"\"\"\n _error_code, _msg = self._dtm_data_model.do_update(node_id)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n 'savedValidation')\n\n def request_do_update_matrix(self, revision_id, matrix_type):\n \"\"\"\n Request to update the selected Data Matrix.\n\n :param int revision_id: the ID of the Revision is the matrix to update\n is associated with.\n :param int matrix_type: the type of the Matrix to save. Current\n Validation matrix types are:\n\n vldtn_hrdwr = Requirement:Hardware\n\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n if matrix_type == 'vldtn_rqrmnt':\n _error_code, _msg = self._dmx_vldtn_rqrmnt_matrix.do_update(\n revision_id, matrix_type)\n elif matrix_type == 'vldtn_hrdwr':\n _error_code, _msg = self._dmx_vldtn_hw_matrix.do_update(\n revision_id, matrix_type)\n else:\n _error_code = 6\n _msg = 'RAMSTK ERROR: Attempted to update non-existent matrix ' \\\n '{0:s}.'.format(matrix_type)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n 'savedMatrix')\n\n def request_do_update_all(self, **kwargs):\n \"\"\"\n Request to update all records in the RAMSTKValidation table.\n\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n _error_code, _msg = self._dtm_data_model.do_update_all(**kwargs)\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n None)\n\n def request_do_update_status(self):\n \"\"\"\n Request to update program Validation task status.\n\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n _error_code, _msg = self._dtm_data_model.do_update_status()\n\n return RAMSTKDataController.do_handle_results(self, _error_code, _msg,\n None)\n\n def request_do_calculate(self, node_id, **kwargs): # pylint: disable=unused-argument\n \"\"\"\n Request to calculate the Validation task metrics.\n\n This method calls the data model methods to calculate task cost and\n task time.\n\n :param int node_id: the PyPubSub Tree() ID of the Validation task\n to calculate.\n :return: False if successful or True if an error is encountered.\n :rtype: bool\n \"\"\"\n _return = False\n _msg = 'RAMSTK SUCCESS: Calculating Validation Task {0:d} cost and ' \\\n 'time metrics.'.format(node_id)\n\n _costs = self._dtm_data_model.do_calculate(node_id, metric='cost')\n _time = self._dtm_data_model.do_calculate(node_id, metric='time')\n\n if not _costs and not _time:\n self._configuration.RAMSTK_USER_LOG.info(_msg)\n\n if not self._test:\n pub.sendMessage('calculatedValidation', module_id=node_id)\n\n elif _costs:\n _msg = 'RAMSTK ERROR: Calculating Validation Task {0:d} cost ' \\\n 'metrics.'.format(node_id)\n self._configuration.RAMSTK_DEBUG_LOG.error(_msg)\n _return = True\n\n elif _time:\n _msg = 'RAMSTK ERROR: Calculating Validation Task {0:d} time ' \\\n 'metrics.'.format(node_id)\n self._configuration.RAMSTK_DEBUG_LOG.error(_msg)\n _return = True\n\n return _return\n\n def request_do_calculate_all(self):\n \"\"\"\n Request to calculate program cost and time.\n\n :return: (_cost_ll, _cost_mean, _cost_ul,\n _time_ll, _time_mean, _time_ul); the lower bound, mean,\n and upper bound for program cost and time.\n :rtype: tuple\n \"\"\"\n (_cost_ll, _cost_mean, _cost_ul, _time_ll, _time_mean,\n _time_ul) = self._dtm_data_model.do_calculate_all()\n\n if not self._test:\n pub.sendMessage('calculatedProgram')\n\n return (_cost_ll, _cost_mean, _cost_ul, _time_ll, _time_mean, _time_ul)\n\n def request_get_planned_burndown(self):\n \"\"\"\n Request the planned burndown curve.\n\n :return: (_y_minimum, _y_average, _y_maximum)\n :rtype: tuple\n \"\"\"\n return self._dtm_data_model.get_planned_burndown()\n\n def request_get_assessment_points(self):\n \"\"\"\n Request the assessment dates, minimum, and maximum values.\n\n :return: (_assessed_dates, _targets)\n :rtype: tuple\n \"\"\"\n return self._dtm_data_model.get_assessment_points()\n\n def request_get_actual_burndown(self):\n \"\"\"\n Request the actual burndown curve.\n\n :return: dictionary of actual remaining times for each date the value\n has been calculated. Key is the date, value is the remaining\n time.\n :rtype: dict\n \"\"\"\n return self._dtm_data_model.get_actual_burndown()\n","sub_path":"src/ramstk/modules/validation/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":14498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"342538268","text":"\"\"\" Implements the AWS processing task classes. \"\"\"\n\nimport logging\nimport string\nimport random\nimport time\nimport re\nfrom concurrent.futures import Future\n\nfrom botocore.exceptions import ClientError\nfrom ..model.aws import normalize_resources\nfrom .utils import AWSSafeExec\n\nlog = logging.getLogger(__name__)\n\n\nclass AwsTask():\n \"\"\" Base class for AWS tasks \"\"\"\n def __init__(self, **kwargs):\n self.retry = kwargs.pop(\"retry\", None)\n self.future = Future()\n\n def execute(self, aws):\n raise NotImplementedError()\n\n\nclass RetrieveStudentUsers(AwsTask):\n \"\"\" Retrieves all student users from AWS IAM. \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.pattern = kwargs.pop(\"pattern\")\n\n def execute(self, aws):\n iam = aws.client(\"iam\")\n users = iam.list_users()[\"Users\"]\n filtered_users = []\n for user in users:\n username = user[\"UserName\"]\n if not re.match(self.pattern, username):\n continue\n last_used = user.get(\"PasswordLastUsed\", None)\n filtered_users.append({\n \"username\": username,\n \"last_used\": last_used.timestamp() if last_used else None\n })\n return filtered_users\n\n\nclass ChangeUserPassword(AwsTask):\n \"\"\" Changes an user's password \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.username = kwargs.pop(\"username\")\n self.new_password = kwargs.pop(\"new_password\")\n\n def execute(self, aws):\n iam = aws.client(\"iam\")\n profile = None\n try:\n profile = iam.get_login_profile(UserName=self.username)\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchEntity':\n pass # it's okay, password needs to be created\n else:\n raise ex\n if profile:\n # need to change the password\n iam.update_login_profile(UserName=self.username, Password=self.new_password,\n PasswordResetRequired=False)\n else:\n # need to create a login profile with the password\n iam.create_login_profile(UserName=self.username, Password=self.new_password,\n PasswordResetRequired=False)\n return True\n\n\nclass RemoveUserProfile(AwsTask):\n \"\"\" Removes an user's login profile, preventing further authentication \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.username = kwargs.pop(\"username\")\n\n def execute(self, aws):\n iam = aws.client(\"iam\")\n try:\n iam.delete_login_profile(UserName=self.username)\n except ClientError as ex:\n if ex.response['Error']['Code'] == 'NoSuchEntity':\n pass # it's okay, profile doesn't exist\n else:\n raise ex\n return True\n\n\nclass RetrieveEC2Resources(AwsTask):\n \"\"\" Retrieves the collection of all relevant resources. \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def execute(self, aws):\n ec2 = aws.client(\"ec2\")\n FETCH_TYPES = {\n \"Instances\": (self.describe_instances, (ec2,)),\n \"KeyPairs\": ec2.describe_key_pairs,\n \"NetworkInterfaces\": ec2.describe_network_interfaces,\n \"Vpcs\": ec2.describe_vpcs,\n \"Addresses\": ec2.describe_addresses,\n \"InternetGateways\": ec2.describe_internet_gateways,\n \"NatGateways\": (self.describe_nat_gateways, (ec2,)),\n \"Subnets\": ec2.describe_subnets,\n \"RouteTables\": ec2.describe_route_tables,\n \"SecurityGroups\": ec2.describe_security_groups,\n }\n resources = {}\n for res_type, func in FETCH_TYPES.items():\n if isinstance(func, tuple):\n resources[res_type] = func[0](*func[1])\n else:\n result = func()\n if result.get(res_type, None):\n resources[res_type] = result[res_type]\n else:\n resources[res_type] = []\n\n return resources\n\n def describe_instances(self, ec2):\n raw_instances = ec2.describe_instances()\n # a reservation may contain multiple instances\n instances = []\n for reservation in raw_instances[\"Reservations\"]:\n for inst in reservation.get(\"Instances\", []):\n if inst[\"State\"][\"Name\"] != \"terminated\":\n instances.append(inst)\n return instances\n\n def describe_nat_gateways(self, ec2):\n raw_nat = ec2.describe_nat_gateways()\n # exclude deleted gateways\n nat_gws = []\n for nat in raw_nat[\"NatGateways\"]:\n if nat[\"State\"] != \"deleted\":\n nat_gws.append(nat)\n return nat_gws\n\nclass CleanupUserResourcesTask(AwsTask):\n \"\"\" Deletes AWS user resources. \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.resource_map = kwargs.pop(\"resource_map\")\n self.dryrun = kwargs.pop(\"dryrun\", False)\n\n def execute(self, aws):\n ec2 = aws.client(\"ec2\")\n\n def delete_instances(resources):\n ids = [resource.id for resource in resources]\n safexc = AWSSafeExec(\"delete_instances\", log=log)\n for inst_id in ids:\n with safexc:\n ec2.terminate_instances(InstanceIds=[inst_id], DryRun=self.dryrun)\n return safexc\n\n def delete_key_pairs(resources):\n safexc = AWSSafeExec(\"delete_key_pairs\", log=log)\n for resource in resources:\n with safexc:\n ec2.delete_key_pair(KeyName=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_network_interfaces(resources):\n safexc = AWSSafeExec(\"delete_network_interfaces\", log=log)\n for resource in resources:\n with safexc:\n ec2.delete_network_interface(NetworkInterfaceId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_vpcs(resources):\n safexc = AWSSafeExec(\"delete_vpcs\", log=log)\n for resource in resources:\n with safexc:\n ec2.delete_vpc(VpcId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_addresses(resources):\n safexc = AWSSafeExec(\"delete_addresses\", log=log)\n for resource in resources:\n with safexc:\n ec2.release_address(AllocationId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_inet_gateways(resources):\n safexc = AWSSafeExec(\"delete_inet_gateways\", log=log)\n for resource in resources:\n for attach in resource.raw.get(\"Attachments\", []):\n with safexc:\n ec2.detach_internet_gateway(\n InternetGatewayId=resource.id, VpcId=attach[\"VpcId\"],\n DryRun=self.dryrun)\n with safexc:\n ec2.delete_internet_gateway(InternetGatewayId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_nat_gateways(resources):\n safexc = AWSSafeExec(\"delete_nat_gateways\", log=log)\n for resource in resources:\n with safexc:\n if not self.dryrun:\n ec2.delete_nat_gateway(NatGatewayId=resource.id)\n return safexc\n\n def delete_subnets(resources):\n safexc = AWSSafeExec(\"delete_subnets\", log=log)\n for resource in resources:\n with safexc:\n ec2.delete_subnet(SubnetId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_route_tables(resources):\n safexc = AWSSafeExec(\"delete_route_tables\", log=log)\n for resource in resources:\n is_main = False\n for assoc in resource.raw.get(\"Associations\", []):\n if assoc.get(\"Main\", False):\n is_main = True\n continue\n with safexc:\n ec2.disassociate_route_table(\n AssociationId=assoc[\"RouteTableAssociationId\"],\n DryRun=self.dryrun)\n if is_main:\n continue # main route tables are deleted with their VPC\n with safexc:\n ec2.delete_route_table(RouteTableId=resource.id, DryRun=self.dryrun)\n return safexc\n\n def delete_security_groups(resources):\n safexc = AWSSafeExec(\"delete_security_groups\", log=log)\n for resource in resources:\n if resource.raw[\"GroupName\"] == \"default\":\n continue # default group cannot be deleted\n with safexc:\n ec2.delete_security_group(GroupId=resource.id, DryRun=self.dryrun)\n return safexc\n\n ORDER = [\"Instances\", \"KeyPairs\", \"RouteTables\", \"NetworkInterfaces\", \"SecurityGroups\", \"Subnets\", \"Addresses\",\n \"InternetGateways\", \"NatGateways\", \"Vpcs\", ]\n DELETE_FUNCS = {\n \"Instances\": delete_instances,\n \"NetworkInterfaces\": delete_network_interfaces,\n \"KeyPairs\": delete_key_pairs,\n \"Vpcs\": delete_vpcs,\n \"Addresses\": delete_addresses,\n \"InternetGateways\": delete_inet_gateways,\n \"NatGateways\": delete_nat_gateways,\n \"Subnets\": delete_subnets,\n \"RouteTables\": delete_route_tables,\n \"SecurityGroups\": delete_security_groups,\n }\n all_errors = []\n for res_type in ORDER:\n FUNC = DELETE_FUNCS[res_type]\n resources = self.resource_map.get(res_type, None)\n if resources:\n log.info(\"Deleting %s: %s\", res_type, str(resources))\n safexc = FUNC(resources)\n if safexc.errors:\n all_errors.extend(safexc.errors)\n return all_errors\n\n\n","sub_path":"lib/aws/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":10198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"55885106","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 27 20:24:25 2017\n\n@author: o0\n\"\"\"\n\nimport zipfile\nimport gzip\nimport os\nimport pandas as pd\nfrom zipfile import ZipFile\nimport re\nimport numpy as np\nos.chdir(\"C:\\\\Users\\\\o0\\\\Desktop\\\\HW0401\\\\Raw Data\\\\九月\")#the directory of raw data\ncompress_path='C:\\\\Users\\\\o0\\\\Desktop\\\\HW0401\\\\Raw Data\\\\九月\\\\compress_ds' #a directory of storage the npacked file; set by yourself\n#absolute_path='C:\\\\Users\\\\o0\\\\Desktop\\\\HW\\\\九月\\\\文件\\\\ANR (4)\\\\logs\\\\901\\\\uploading\\\\Eventid_MHA-AL00_MHA-AL00C00B225_8cGuQeov222tLtP0k0zGaSO70pcCqHRjcmVCSqSFNSc=_20170811024143_901001000_NORMAL.zip'\n#absolute_path='C:\\\\Users\\\\o0\\\\Desktop\\\\HW\\\\九月\\\\文件\\\\ANR (4)\\\\logs\\\\901\\\\done\\\\Eventid_MHA-AL00_MHA-AL00C00B225_8cGuQeov222tLtP0k0zGaSO70pcCqHRjcmVCSqSFNSc=_20170820112235_901001000_NORMAL.zip'\ndef get_feature(absolute_path,compress_path):\n try:\n myzip = ZipFile(absolute_path,'r')#解压*901000001.zip或'901001000'.zip\n #判断是哪一个解压之后是哪一个文件:data_app_anr@*,system_app_anr@,还是'system_server_watchdog@'\n for i in myzip.namelist():\n if i.startswith('data_app_anr@'):\n txt = i\n elif i.startswith('system_app_anr@'):\n txt=i\n elif i.startswith('system_server_watchdog@'):\n txt=i \n #解压之后会有两种,一种直接是txt,一种是.gz文件。判断属于哪一种,分别处理\n if not 'gz' in txt:\n file = str(open(myzip.extract(txt,compress_path),'rb').read(),encoding = \"utf-8\")#打开文件并转为字符串\n else:\n #若是.gz文件则继续解压\n g_file = gzip.GzipFile(myzip.extract(txt,compress_path),'rb')\n #将解压的文件存为string类型的变量\n file=str(g_file.read(), encoding = \"utf-8\") \n g_file.close()\n myzip.close()\n #\n splitfile=file.split('pid')#将字符串按pid拆分,以便寻找pid为system_server的字符串\n ssfile=''\n #若不存在pid为system)server的字符串,则记为空,否则将其存为新的字符串ssfile\n for f in splitfile:\n if 'Cmd line: system_server' in f:\n ssfile= f\n break\n \n ## ##从file提取有关process的特征\n if 'Process' in file:\n Process=re.findall('Process:\\s(.+?)\\n',file)[0]\n else:\n Process=np.nan\n print('The file not contain process')\n ##从file提取有关process的特征 \n if 'Subject' in file:\n Subject=re.findall('Subject: (.+?)\\n',file)[0]\n else:\n Subject=np.nan\n print('The file not contain subject')\n \n #提取Cpu相关的特征\n Cpu_df=np.nan\n Cpu_max=np.nan\n Cpu_maxname=np.nan\n Cpu_pro=np.nan\n ##将c包含cpu的这一串字符,提取出来,并转化为一个dataframe\n Cpu= re.findall('(\\d+)\\%\\s(.+?)\\/(.+?)\\:\\s(.+) kernel',file, re.M)\n Cpu_df=pd.DataFrame(Cpu,columns=['A','B','C','D'])\n if Cpu_df.empty:\n print('not Cpu log record')\n else: \n Cpu_max=Cpu_df.loc[0][0]#提取cpu占比最大的所占的比例\n Cpu_maxname=Cpu_df.loc[0][2]#提取cpu占比最大的进程名\n if sum(Cpu_df.C==Process): \n Cpu_pro=Cpu_df[Cpu_df.C==Process].iloc[0,0]#提取进程为process的占比\n \n\n #提取binder之间的特征\n binder_pn=np.nan\n binder_p=[np.nan]*4\n #提取binder trans---之间的信息,并存为dataframe\n binder= re.findall('\\d+:\\d+\\((.+?):(.+?)\\) -> \\d+:\\d+\\((.+?):(.+?)\\)',file, re.M)\n binder_df=pd.DataFrame(binder,columns=['A','B','C','D'])\n #提取上述dataframe中进程为process中值的记录\n binder_pro=binder_df[binder_df.A==Process]\n #记录进程为process中值的记录的 个数\n if not binder_df.size==0:\n binder_pn = binder_pro['A'].size\n elif 'binder transactions' in file:\n binder_pn=0\n \n #提取pid为system_server中的信息,包括total time,free memory,total memory ,total time waiting for GC 以及main,Android.fg ,Android.io,Android.ui的状态及相关特征\n pid = [np.nan]*12\n if ssfile=='':\n print('not system_server of pid')\n else:\n pid[0]=re.findall('Total time spent in GC:\\s(.+?)\\nM',ssfile,flags=re.DOTALL)[0]#记录'Total time spent in G的值\n pid[1]=re.findall('Free memory\\s(.+?)\\n',file,flags=re.DOTALL)[0]#记录'Free_memory的值\n pid[2]=re.findall('Total memory\\s(.+?)\\n',file,flags=re.DOTALL)[0]#记录'total_memory的值\n pid[3]=re.findall('Total time waiting for GC to complete:\\s(.+?)\\n',file,flags=re.DOTALL)[0]#记录Total time waiting for GC to complete的值\n if '\"main\" prio' in ssfile:\n pid[4]=re.findall('\"main\" prio.+?tid=\\d+\\s(.+?)\\n',ssfile,flags=re.DOTALL)[0]#记录main的状态\n if '\"android.ui\" prio' in ssfile:\n pid[5]=re.findall('\"android.ui\" prio.+?tid=\\d+\\s(.+?)\\n',ssfile,flags=re.DOTALL)[0]#记录android.ui的状态\n if '\"android.fg\" prio' in ssfile:\n pid[6]=re.findall('\"android.fg\" prio.+?tid=\\d+\\s(.+?)\\n',ssfile,flags=re.DOTALL)[0]#记录android.fg的状态\n if '\"android.io\" prio' in ssfile:\n pid[7]=re.findall('\"android.io\" prio.+?tid=\\d+\\s(.+?)\\n',ssfile,flags=re.DOTALL)[0]#记录android.io的状态\n ssfile_split = ssfile.split('\\n\\n')\n if pid[4]=='Blocked':\n mainnumber=re.findall('\"main\" prio.+?tid.+?waiting to lock <(.+?)>',ssfile,flags=re.DOTALL)[0]#若main 状态为Blocked记录locked进程名\n for fi in ssfile_split:\n if '- locked <'+mainnumber+'>' in fi:\n pid[8] = fi.split('\"')[1]\n binder_promain = binder_pro[binder_pro.B==pid[8]]\n if not binder_promain.size==0: \n binder_p[0]= binder_promain['C'] #记录binder tr字符串间,main 状态为Blocked记录locked进程名后对应的字符串(结合ppt查看)\n #同main\n if pid[5]=='Blocked':\n uinumber=re.findall('\"android.ui\" prio.+?tid.+?waiting to lock <(.+?)>',ssfile,flags=re.DOTALL)[0]\n for fi in ssfile_split:\n if '- locked <'+uinumber+'>' in fi:\n pid[9] = fi.split('\"')[1]\n binder_proui = binder_pro[binder_pro.B==pid[9]]\n if not binder_proui.size==0: \n binder_p[1]= binder_proui['C']\n #同main\n if pid[6]=='Blocked':\n fgnumber=re.findall('\"android.fg\" prio.+?tid.+?waiting to lock <(.+?)>',ssfile,flags=re.DOTALL)[0]\n for fi in ssfile_split:\n if '- locked <'+fgnumber+'>' in fi:\n pid[10] = fi.split('\"')[1]\n binder_profg = binder_pro[binder_pro.B==pid[10]]\n if not binder_profg.size==0: \n binder_p[2]= binder_profg['C']\n #同main\n if pid[7]=='Blocked':\n ionumber=re.findall('\"android.io\" prio.+?tid.+?waiting to lock <(.+?)>',ssfile,flags=re.DOTALL)[0]\n for fi in ssfile_split:\n if '- locked <'+ionumber+'>' in fi:\n pid[11] = fi.split('\"')[1]\n binder_proio = binder_pro[binder_pro.B==pid[10]]\n if not binder_proio.size==0: \n binder_p[3]= binder_proio['C'] \n \n X=pd.DataFrame({ 'txt': [txt],\n 'Process': [Process],\n 'Subject': [Subject],\n 'Cpu_max': [Cpu_max],\n 'Cpu_maxname':[Cpu_maxname],\n 'Cpu_process':[Cpu_pro],\n 'TottimeiGc':[pid[0]],\n 'Free_mem':[pid[1]],\n 'Total_mem':[pid[2]],\n 'TottimewGc':[pid[3]],\n 'binder_npro':[binder_pn],\n \"main\":[pid[4]],\n 'main_thread':[pid[8]],\n 'main_pro':[binder_p[0]],\n \"android.ui\":[pid[5]],\n 'ui_thread':[pid[9]],\n 'android.ui_pro':[binder_p[1]],\n \"android.fg\":[pid[6]],\n 'fg_thread':[pid[10]],\n 'android.fg_pro':[binder_p[2]],\n \"android.io\":[pid[7]],\n 'io_thread':[pid[11]],\n 'android.io_pro':[binder_p[3]],\n })\n except:\n X=pd.DataFrame()\n return X\n\n\n\ncolumns=['log_name','txt','Process','Subject','Cpu_max','Cpu_maxname','Cpu_process','TottimeiGc',\\\n 'Free_mem','Total_mem', 'TottimewGc', 'binder_npro','main','main_thread','main_pro','android.ui',\\\n 'ui_thread','ui_pro','android.fg','fg_thread','fg_pro','android.io','io_thread','io_pro']\ndata=pd.DataFrame({},columns=columns)\n\n\n\n\nlog_crash='901000001'\nlog_screen='901001000'\n\n#分别对三个文件夹下的数据做,得到3个excel文件,分别记作SC.xlsx,Performace.xlsx,Norm.xlsx\npath_901='使用过程中系统无响应(冻屏死机)'\n#path_901='性能问题数据'\n#path_901='result'\n\n\n\nlistd= os.listdir(path_901)\nlistd.sort(key=len)\n#遍历所有目录,将所有记录存为一个DataFrame\nfor logname in listd:\n print(logname)\n# log=os.listdir()[999]\n# logname='ANR (781)'\n #判断是否有901文件夹\n path=os.path.join(path_901,logname,'logs\\\\901')\n #遍历901文件夹,找到所有的*901000001.zip以及*90100100.zip\n if os.path.exists(path):\n for folder in os.listdir(path):\n folder1= os.path.join(path,folder)\n for filename in os.listdir(folder1):\n if (log_crash in filename) or (log_screen in filename):\n absolute_path= os.path.join(folder1,filename)#zip的绝对路径\n X=get_feature(absolute_path,compress_path=compress_path)#抽取特征\n X['log_name']= [logname]#记录文件夹名\n X.index = [filename]#将zip文件名记为index\n data=pd.concat([data,X])#将新纪录加到已有dataframe中\n if not sum(logname == data['log_name']):\n print('do not exsit',log_crash,' ',log_screen, 'in', logname)\n else:\n print('Ok in ',logname)\n else:\n print('do no exsit:', path)\n \n \n\ndata=data[columns]\n\n\ndata.to_excel('SC.xlsx',sheet_name='SC')\n#data.to_excel('Performance.xlsx',sheet_name='Performance')\n#data.to_excel('Norm.xlsx',sheet_name='Norm')","sub_path":"九月/Python code/train model/Feature extraction and preprocessing/getfeature.py","file_name":"getfeature.py","file_ext":"py","file_size_in_byte":10861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"57037221","text":"\"\"\"\nThis probe runs in a Telepresence created and managed execution context.\nIt observes things about that environment and reports about them on stdout.\nThe report can be inspected by the test suite to verify Telepresence has\ncreated the execution context correctly.\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom json import dumps, loads\nfrom os import environ\nfrom os.path import join\nfrom socket import gethostbyaddr, gethostbyname\nfrom struct import pack\nfrom subprocess import CalledProcessError, check_output, run\nfrom sys import stdin, stdout\nfrom threading import Thread\nfrom time import sleep\nfrom urllib.request import Request, urlopen\n\n# The probe's output is mixed together with Telepresence output and maybe more\n# output from things like socat or torsocks. This makes it difficult to\n# extract information from the probe via stdout. Unfortunately, options apart\n# from stdout as a channel for communicating back to the test process are\n# limit. Depending on the Telepresence method, it may not be easy for the\n# test process to reach the probe via normal networking means (we may not have\n# an address we can bind to that the host can reach; there may not be an\n# address on the host we can reach). It's not possible to pass an\n# already-opened connection from the test process to the probe process because\n# it would need to pass through Telepresence and Telepresence doesn't support\n# this. Even a UNIX socket on the host filesystem isn't necessarily reachable\n# from the probe process.\n#\n# So use the channel we have: stdout. To deal with the fact that there is\n# other output on it, frame structured probe output with a magic prefix\n# followed by a length prefix followed by the content itself. The test\n# process will have to filter through the noise to find the magic prefix and\n# then use the length prefix to know how much following data is relevant.\n#\n# The particular prefix chosen is not legal UTF-8. Hopefully this minimizes\n# the chances that some legitimate output will accidentally duplicate it.\nMAGIC_PREFIX = b\"\\xc0\\xc1\\xfe\\xff\"\n\n\ndef main():\n parser = argument_parser()\n args = parser.parse_args()\n\n output = TaggedOutput(stdout.buffer)\n\n result = dumps({\n \"environ\": dict(environ),\n \"probe-urls\": list(probe_urls(args.probe_url)),\n \"probe-commands\": list(probe_commands(args.probe_command)),\n \"probe-paths\": list(probe_paths(args.probe_path)),\n })\n\n output.write(result)\n\n for (port, value) in zip(args.http_port, args.http_value):\n run_http_server(port, value)\n\n run_http_server(9876, \"sidecar\")\n\n read_and_respond(stdin.buffer, output)\n print(\"Goodbye.\")\n exit(args.exit_code)\n\n\nclass TaggedOutput(object):\n def __init__(self, stdout):\n self.stdout = stdout\n\n def write(self, text):\n data = text.encode(\"utf-8\")\n self.stdout.write(MAGIC_PREFIX + pack(\">I\", len(data)) + data)\n self.stdout.flush()\n\n\ndef read_and_respond(commands, output):\n while True:\n line = commands.readline().decode(\"utf-8\")\n print(\"Read line: {!r}\".format(line), flush=True)\n if not line:\n print(\"Closed? {}\".format(commands.closed), flush=True)\n sleep(1)\n continue\n argv = line.split()\n command = argv.pop(0)\n print(\"Read command: {}\".format(command), flush=True)\n response = COMMANDS[command](*argv)\n output.write(dumps(response))\n print(\"Dumped response.\", flush=True)\n if command == \"done\":\n break\n\n\ndef probe_also_proxy(hostname):\n # We must use http to avoid SNI problems.\n url = \"http://{}/ip\".format(hostname)\n # And we must specify the host header to avoid vhost problems.\n request = Request(url, None, {\"Host\": \"httpbin.org\"})\n\n print(\"Retrieving {}\".format(url))\n try:\n response = str(urlopen(request, timeout=30).read(), \"utf-8\")\n except Exception as e:\n print(\"Got error: {}\".format(e))\n result = (False, str(e))\n else:\n print(\"Got {} from webserver.\".format(repr(response)))\n request_ip = loads(response)[\"origin\"]\n result = (True, request_ip)\n return result\n\n\ndef run_http_server(port, value):\n class SingleValueHTTPRequestHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n response_body = value.encode(\"utf-8\")\n self.send_response(200)\n self.send_header(\"Content-Type\", \"text/plain\")\n self.send_header(\"Content-Length\", str(len(response_body)))\n self.end_headers()\n self.wfile.write(response_body)\n\n server = HTTPServer((\"\", port), SingleValueHTTPRequestHandler)\n Thread(target=server.serve_forever, daemon=True).start()\n\n\ndef disconnect_telepresence(namespace):\n # Kill off sshd server process the SSH client is talking to, forcing\n # disconnection:\n env = environ.copy()\n # Don't want torsocks messing with kubectl:\n for name in [\"LD_PRELOAD\", \"DYLD_INSERT_LIBRARIES\"]:\n if name in env:\n del env[name]\n # We can't tell if this succeeded, sadly, since it kills ssh session used\n # by kubectl exec!\n command = [\n \"kubectl\", \"exec\", \"--namespace=\" + namespace,\n \"--container=\" + environ[\"TELEPRESENCE_CONTAINER\"],\n environ[\"TELEPRESENCE_POD\"], \"--\", \"/bin/sh\", \"-c\",\n r\"kill $(ps xa | tail -n +2 | \" + r\"sed 's/ *\\([0-9][0-9]*\\).*/\\1/')\"\n ]\n print(\"Using kubectl to kill Telepresence support processes:\")\n print(\"\\t{}\".format(\" \".join(command)), flush=True)\n\n run(command, env=env)\n sleep(10)\n # The test expects 3, which is how telepresence exits when one of its\n # subprocesses dies. That is, we expect to be killed before we reach this\n # point, if we exit with 66 that means disconnect-detection failed.\n raise SystemExit(66)\n\n\ndef probe_gethostbyname(name):\n try:\n return True, gethostbyname(name)\n except Exception as e:\n return False, str(e)\n\n\ndef probe_gethostbyaddr(name):\n try:\n return True, gethostbyaddr(name)\n except Exception as e:\n return False, str(e)\n\n\nCOMMANDS = {\n \"probe-url\": lambda *urls: list(probe_urls(urls)),\n \"probe-also-proxy\": probe_also_proxy,\n \"disconnect-telepresence\": disconnect_telepresence,\n \"gethostbyname\": probe_gethostbyname,\n \"gethostbyaddr\": probe_gethostbyaddr,\n \"done\": str, # identity function\n}\n\n\ndef probe_urls(urls):\n for url in urls:\n print(\"Retrieving {}\".format(url))\n try:\n response = urlopen(url, timeout=30).read()\n except Exception as e:\n print(\"Got error: {}\".format(e))\n result = (False, str(e))\n else:\n print(\"Got {} bytes\".format(len(response)))\n result = (True, response.decode(\"utf-8\"))\n yield (url, result)\n\n\ndef probe_commands(commands):\n for command in commands:\n try:\n output = check_output([command, \"arg1\"])\n except CalledProcessError as e:\n result = (False, e.returncode)\n except FileNotFoundError:\n result = (False, None)\n else:\n result = (True, output.decode(\"utf-8\"))\n yield (command, result)\n\n\ndef probe_paths(paths):\n root = environ.get(\"TELEPRESENCE_ROOT\", \"/tel/root/not/set\")\n for path in paths:\n try:\n with open(join(root, path)) as f:\n yield (path, f.read())\n except FileNotFoundError:\n yield (path, None)\n\n\ndef argument_parser():\n parser = ArgumentParser()\n parser.add_argument(\n \"--probe-url\",\n action=\"append\",\n default=[],\n help=\"A URL to retrieve.\",\n )\n parser.add_argument(\n \"--probe-command\",\n action=\"append\",\n default=[],\n help=\"A command to run.\",\n )\n parser.add_argument(\n \"--probe-path\",\n action=\"append\",\n default=[],\n help=\"A path to read.\",\n )\n parser.add_argument(\n \"--http-port\",\n type=int,\n action=\"append\",\n default=[],\n help=\"A port number on which to serve HTTP.\",\n )\n parser.add_argument(\n \"--http-value\",\n action=\"append\",\n default=[],\n help=\"A value to return from the most recent HTTP server.\",\n )\n parser.add_argument(\n \"--exit-code\",\n type=int,\n default=94,\n help=\"The desired exit code for this process.\",\n )\n return parser\n\n\nmain()\n","sub_path":"tests/cluster/probe_endtoend.py","file_name":"probe_endtoend.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"34690650","text":"# imports for the web application and the webcam capture \nfrom flask import Flask, render_template, Response, redirect, url_for\nfrom cv2 import cv2\nfrom PIL import Image\n\n# imports for the artificial intelligence model and other functions \nimport torchvision\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\napp = Flask(__name__) # instantiates a Flask application\ncamera = cv2.VideoCapture(0) # used for webcam capture \n\n# images used when captured to display and feed into our model\ndisplay_img = None\npredict_img = None\ndisplay_label = None\n\n# returns a stream of webcam VIDEO capture \ndef generate_frames(): \n while True:\n success, frame = camera.read()\n if not success:\n break\n else:\n _, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes() # converting to bytes otherwise Flask will complain \n img = (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n yield (img)\n\n# get image for model prediction\n# returns img_bytes(in bytes), img_arr(in array)\ndef get_image(): \n success, frame = camera.read()\n img_arr = frame\n if success:\n _, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes() # converting to bytes otherwise Flask will complain \n img_bytes = (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n return img_bytes, img_arr \n\n# gets the prediction of the mood from the image \ndef prediction(img):\n # load model \n vgg_model = models.vgg16(pretrained=False)\n vgg_model.classifier[6] = nn.Linear(4096, 7) # sets output classes to 7 emotions \n state = torch.load(\"model\", map_location=torch.device('cpu'))\n vgg_model.load_state_dict(state)\n\n # convert image to right type and dimensions \n img = Image.fromarray(img, 'RGB')\n \n transform_img = transforms.Compose([transforms.CenterCrop(224), transforms.ToTensor(), \n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), \n transforms.Grayscale(num_output_channels=3)])\n \n img = transform_img(img)\n img = np.array(img)\n img = torch.from_numpy(img)\n img.unsqueeze_(0)\n\n # put image through model and obtain prediction \n pred = vgg_model(img)\n prob = F.softmax(pred, dim=1)[0]\n # gets the emotion with the top probability\n first_value, first_index = prob.max(0)\n prob[first_index] = 0\n # gets the emotion with the second best probability\n second_value, second_index = prob.max(0)\n\n max = 0\n label_test = [\"angry\", \"fatigued\", \"scared\", \"happy\", \"neutral\", \"sad\", \"surprised\"]\n\n for i, x in enumerate(pred):\n for j, y in enumerate(pred[i]):\n if(y > max):\n max = y\n label = label_test[j]\n\n return label, first_value.item() * 100, second_value.item() * 100, label_test[first_index.item()], label_test[second_index.item()]\n\n@app.route('/image')\ndef image():\n # instead of grabbing a new image here, pass in display_img and predict_img when we pressed the button\n return Response(display_img, mimetype='multipart/x-mixed-replace; boundary=frame')\n \n@app.route('/result')\ndef result():\n global display_label\n display_label, first_perc, second_perc, first_value, second_value = prediction(predict_img)\n return render_template('result.html', label=display_label, first_perc=first_perc, first_value=first_value, second_perc=second_perc, second_value=second_value)\n\n# the temporary template that will be loaded when the user presses the capture button, will then render the results route \n@app.route('/loading')\ndef loading():\n return render_template('loading.html', image=display_img)\n \n@app.route('/button_capture', methods=[\"GET\", \"POST\"])\ndef button_capture():\n # save the image captured in display_img and the prediction image in predict_img\n global display_img\n global predict_img\n display_img, predict_img = get_image()\n return redirect(url_for('loading'))\n\n@app.route('/button_again', methods=[\"GET\", \"POST\"])\ndef button_again(): \n return redirect(url_for('index')) \n\n@app.route('/video')\ndef video():\n return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@app.route('/')\ndef index():\n return render_template('home.html')\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"255570224","text":"\n\n#calss header\nclass _FJORD():\n\tdef __init__(self,): \n\t\tself.name = \"FJORD\"\n\t\tself.definitions = [u'a long strip of sea between steep hills, found especially in Norway']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_fjord.py","file_name":"_fjord.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"522241261","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport errno\nimport argparse\n\ndef parse_args(args=None):\n Description = \"Create valid nf-core/viralrecon samplesheet file from output of 'fetch_sra_runinfo.py' script.\"\n Epilog = \"\"\"Example usage: python sra_runinfo_to_samplesheet.py \"\"\"\n\n parser = argparse.ArgumentParser(description=Description, epilog=Epilog)\n parser.add_argument('FILE_IN', help=\"Input metadata file created from 'fetch_sra_runinfo.py' script.\")\n parser.add_argument('FILE_OUT', help=\"Output file.\")\n return parser.parse_args(args)\n\n\ndef make_dir(path):\n if not len(path) == 0:\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n\ndef sra_runinfo_to_samplesheet(FileIn,FileOut):\n\n sampleRunDict = {}\n fin = open(FileIn,'r')\n header = fin.readline().strip().split('\\t')\n while True:\n line = fin.readline()\n if line:\n line_dict = dict(zip(header,line.strip().split('\\t')))\n run_id = line_dict['run_accession']\n exp_id = line_dict['experiment_accession']\n library = line_dict['library_layout']\n fastq_files = line_dict['fastq_ftp']\n fastq_md5 = line_dict['fastq_md5']\n\n db_id = exp_id\n sample_info = [] ## [single_end, is_sra, is_ftp, fastq_1, fastq_2, md5_1, md5_2]\n if library == 'SINGLE':\n if fastq_files:\n sample_info = ['1', '1', '1', fastq_files , '', fastq_md5, '']\n else:\n db_id = run_id\n sample_info = ['1', '1', '0', '', '', '', '']\n elif library == 'PAIRED':\n if fastq_files:\n fq_files = fastq_files.split(';')[-2:]\n if fq_files[0].find('_1.fastq.gz') != -1 and fq_files[1].find('_2.fastq.gz') != -1:\n sample_info = ['0', '1', '1'] + fq_files + fastq_md5.split(';')[-2:]\n else:\n print(\"Invalid FastQ files found for database id:'{}'!.\".format(run_id))\n else:\n db_id = run_id\n sample_info = ['0', '1', '0', '', '', '', '']\n\n if sample_info:\n if db_id not in sampleRunDict:\n sampleRunDict[db_id] = [sample_info]\n else:\n if sample_info in sampleRunDict[db_id]:\n print(\"Input run info file contains duplicate rows!\\nLine: '{}'\".format(line))\n else:\n sampleRunDict[db_id].append(sample_info)\n else:\n break\n fin.close()\n\n ## Write samplesheet with appropriate columns\n if len(sampleRunDict) != 0:\n OutDir = os.path.dirname(FileOut)\n make_dir(OutDir)\n fout = open(FileOut,'w')\n fout.write(','.join(['sample_id', 'single_end', 'is_sra', 'is_ftp', 'fastq_1', 'fastq_2', 'md5_1', 'md5_2']) + '\\n')\n for db_id in sorted(sampleRunDict.keys()):\n for idx,val in enumerate(sampleRunDict[db_id]):\n fout.write(','.join([\"{}_T{}\".format(db_id,idx+1)] + val) + '\\n')\n fout.close()\n\n\ndef main(args=None):\n args = parse_args(args)\n sra_runinfo_to_samplesheet(args.FILE_IN,args.FILE_OUT)\n\n\nif __name__ == '__main__':\n sys.exit(main())","sub_path":"bin/sra_runinfo_to_samplesheet.py","file_name":"sra_runinfo_to_samplesheet.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"649574371","text":"#!/usr/bin/env python2\n\n\"\"\" Obstacle class\n\nThis class is written by Thomas Holden\ntho068@post.uit.no\n\n\"\"\"\n\nimport pygame\nimport os\nfrom precode import Vector2D\n\nclass Planets(pygame.sprite.Sprite):\n\t\"This is the obstacle class\"\n\tdef __init__(self, x, y, image, width, height):\n\t\t\"This constructor method initializes a new position object and appends coordinates to it\"\n\n\t\tpygame.sprite.Sprite.__init__(self)\n\n\t\tself.image \t\t= \tpygame.image.load(os.path.join(\"img\", image)).convert_alpha()\n\t\tself.image\t\t=\tpygame.transform.scale(self.image, (width, height))\n\t\tself.original \t= \tself.image\n\n\t\t\"Set position\"\n\n\t\tself.rect = self.image.get_rect()\n\t\tself.rect.x = x\n\t\tself.rect.y = y\n\n\t\tself.angel = 90\n\n\t\tself.pos = Vector2D(x, y)\n\n\tdef update(self):\n\t\tself.angel \t\t\t-= 1 * 0.2\n\t\tself.image \t\t\t= \tpygame.transform.rotozoom(self.original, self.angel, 1)\n\t\tself.rrect \t\t\t= \tself.rect.copy()\n\t\tself.rrect.center \t= \tself.image.get_rect().center\n\t\tself.image \t\t\t= \tself.image.subsurface(self.rrect).copy()\n","sub_path":"src/planets.py","file_name":"planets.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"89271943","text":"ownerclass = 'MGAppDelegate'\nownerimport = 'MGAppDelegate.h'\n\nresult = Menu(\"\")\nappMenu = result.addMenu(\"moneyGuru\")\nfileMenu = result.addMenu(\"File\")\neditMenu = result.addMenu(\"Edit\")\ndocMenu = result.addMenu(\"Document\")\nviewMenu = result.addMenu(\"View\")\nwindowMenu = result.addMenu(\"Window\")\nhelpMenu = result.addMenu(\"Help\")\n\nappMenu.addItem(\"About moneyGuru\", Action(owner, 'showAboutBox'))\nappMenu.addSeparator()\nappMenu.addItem(\"Preferences...\", Action(owner, 'showPreferencesPanel'), 'cmd+,')\nappMenu.addSeparator()\nNSApp.servicesMenu = appMenu.addMenu(\"Services\")\nappMenu.addSeparator()\nappMenu.addItem(\"Hide moneyGuru\", Action(NSApp, 'hide:'), 'cmd+h')\nappMenu.addItem(\"Hide Others\", Action(NSApp, 'hideOtherApplications:'), 'cmd+alt+h')\nappMenu.addItem(\"Show All\", Action(NSApp, 'unhideAllApplications:'))\nappMenu.addSeparator()\nappMenu.addItem(\"Quit moneyGuru\", Action(NSApp, 'terminate:'), 'cmd+q')\n\nfileMenu.addItem(\"New Document\", Action(None, 'newDocument:'))\nfileMenu.addItem(\"New Tab\", Action(None, 'newTab'), 'cmd+t')\nfileMenu.addItem(\"Open...\", Action(None, 'openDocument:'), 'cmd+o')\n# The \"Open Recent\" item will be automatically added here, don't ask me why. Some kind of NSDocument magic.\nfileMenu.addItem(\"Open Example Document\", Action(None, 'openExampleDocument'))\nfileMenu.addItem(\"Open Plugin Folder\", Action(owner.model, 'openPluginFolder'))\nfileMenu.addItem(\"Import...\", Action(None, 'import'), 'cmd+alt+i')\nfileMenu.addItem(\"Export...\", Action(None, 'export'), 'cmd+alt+e')\nfileMenu.addSeparator()\nfileMenu.addItem(\"Close\", Action(None, 'performClose:'), 'cmd+w')\nfileMenu.addItem(\"Close Window\", Action(None, 'performClose:'), 'cmd+shift+w', tag=const.MGCloseWindowMenuItem)\nfileMenu.addItem(\"Save\", Action(None, 'saveDocument:'), 'cmd+s')\nfileMenu.addItem(\"Save As...\", Action(None, 'saveDocumentAs:'), 'cmd+shift+s')\nfileMenu.addSeparator()\nfileMenu.addItem(\"Page Setup...\", Action(None, 'runPageLayout:'), 'cmd+shift+p')\nfileMenu.addItem(\"Print\", Action(None, 'printDocument:'), 'cmd+p')\n\neditMenu.addItem(\"Undo\", Action(None, 'undo:'), 'cmd+z')\neditMenu.addItem(\"Redo\", Action(None, 'redo:'), 'cmd+shift+z')\neditMenu.addSeparator()\neditMenu.addItem(\"Cut\", Action(None, 'cut:'), 'cmd+x')\neditMenu.addItem(\"Copy\", Action(None, 'copy:'), 'cmd+c')\neditMenu.addItem(\"Paste\", Action(None, 'paste:'), 'cmd+v')\neditMenu.addItem(\"Delete\", Action(None, 'delete:'), 'backspace')\neditMenu.addItem(\"Duplicate\", Action(None, 'duplicateItem'), 'cmd+d')\neditMenu.addItem(\"Select All\", Action(None, 'selectAll:'), 'cmd+a')\neditMenu.addItem(\"Search...\", Action(None, 'search'), 'cmd+shift+f')\n\ndocMenu.addItem(NLSTR(\"New \"), Action(None, 'newItem'), 'cmd+n', tag=const.MGNewItemMenuItem)\ndocMenu.addItem(\"New Account Group\", Action(None, 'newGroup'), 'cmd+shift+n')\ndocMenu.addSeparator()\ndocMenu.addItem(\"Show Info\", Action(None, 'editItemInfo'), 'cmd+i')\ndocMenu.addItem(\"Move Up\", Action(None, 'moveSelectionUp'), 'cmd++')\ndocMenu.addItem(\"Move Down\", Action(None, 'moveSelectionDown'), 'cmd+-')\ndocMenu.addItem(\"Make Schedule from Selected\", Action(None, 'makeScheduleFromSelected'), 'cmd+m')\ndocMenu.addItem(\"Reconcile Selection\", Action(None, 'toggleEntriesReconciled'), 'cmd+r')\ndocMenu.addItem(\"Toggle Reconciliation Mode\", Action(None, 'toggleReconciliationMode'), 'cmd+shift+r')\ndocMenu.addItem(\"Toggle Exclusion Status of Account\", Action(None, 'toggleExcluded'), 'cmd+shift+x')\ndocMenu.addSeparator()\ndocMenu.addItem(\"Show Account\", Action(None, 'showSelectedAccount'), 'cmd+]')\ndocMenu.addItem(\"Go Back\", Action(None, 'navigateBack'), 'cmd+[')\ndocMenu.addItem(\"Jump to Account...\", Action(None, 'jumpToAccount'), 'cmd+shift+a')\ndocMenu.addItem(\"Lookup Completion...\", Action(None, 'lookupCompletion'), 'cmd+l')\n\nviewMenu.addItem(\"Net Worth\", Action(None, 'showBalanceSheet'), 'cmd+1')\nviewMenu.addItem(\"Profit & Loss\", Action(None, 'showIncomeStatement'), 'cmd+2')\nviewMenu.addItem(\"Transactions\", Action(None, 'showTransactionTable'), 'cmd+3')\nviewMenu.addItem(\"Previous Tab\", Action(None, 'showPreviousView'), 'cmd+shift+[')\nviewMenu.addItem(\"Next Tab\", Action(None, 'showNextView'), 'cmd+shift+]')\nviewMenu.addSeparator()\nviewMenu.addItem(\"Month\", Action(None, 'selectMonthRange'), 'cmd+alt+1')\nviewMenu.addItem(\"Quarter\", Action(None, 'selectQuarterRange'), 'cmd+alt+2')\nviewMenu.addItem(\"Year\", Action(None, 'selectYearRange'), 'cmd+alt+3')\nviewMenu.addItem(\"Year to date\", Action(None, 'selectYearToDateRange'), 'cmd+alt+4')\nviewMenu.addItem(\"Running year\", Action(None, 'selectRunningYearRange'), 'cmd+alt+5')\nviewMenu.addItem(\"All transactions\", Action(None, 'selectAllTransactionsRange'), 'cmd+alt+6')\nviewMenu.addItem(\"Custom date range...\", Action(None, 'selectCustomDateRange'), 'cmd+alt+7')\nfor i in range(3):\n if i == 2:\n shortcutKey = '0'\n else:\n shortcutKey = str(8+i)\n item = viewMenu.addItem(\"\", Action(None, 'selectSavedCustomRange:'),\n 'cmd+alt+{}'.format(shortcutKey), tag=2000+i)\n item.hidden = True\n setattr(owner, 'customDateRangeItem{}'.format(i+1), item)\nviewMenu.addItem(\"Previous Date Range\", Action(None, 'selectPrevDateRange'), 'cmd+alt+[')\nviewMenu.addItem(\"Next Date Range\", Action(None, 'selectNextDateRange'), 'cmd+alt+]')\nviewMenu.addItem(\"Today's Date Range\", Action(None, 'selectTodayDateRange'), 'cmd+alt+t')\nviewMenu.addSeparator()\nviewMenu.addItem(\"Toggle Graph\", Action(None, 'toggleGraph'), 'cmd+alt+g')\nviewMenu.addItem(\"Toggle Pie Charts\", Action(None, 'togglePieChart'), 'cmd+alt+p')\n\nwindowMenu.addItem(\"Minimize\", Action(None, 'performMinimize:'))\nwindowMenu.addItem(\"Zoom\", Action(None, 'performZoom:'))\nwindowMenu.addSeparator()\nwindowMenu.addItem(\"Bring All to Front\", Action(None, 'arrangeInFront:'))\n\nhelpMenu.addItem(\"moneyGuru Help\", Action(owner, 'openHelp'), 'cmd+?')\nhelpMenu.addItem(\"moneyGuru Website\", Action(owner, 'openWebsite'))\n","sub_path":"cocoa/ui/main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"232589686","text":"from typing import List\n\nimport numpy as np\nfrom numpy import ndarray\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.mixture import GaussianMixture\n\n\nclass ClusterFeatures(object):\n \"\"\"\n Basic handling of clustering features.\n \"\"\"\n\n def __init__(\n self,\n features: ndarray,\n base_features: ndarray,\n algorithm: str = 'kmeans',\n pca_k: int = None,\n random_state: int = 12345\n ):\n \"\"\"\n :param features: the embedding matrix created by bert parent\n :param base_features: the embedding matrix created by bert parent for the example sentences\n :param algorithm: Which clustering algorithm to use\n :param pca_k: If you want the features to be ran through pca, this is the components number\n :param random_state: Random state\n \"\"\"\n\n if pca_k:\n self.features = PCA(n_components=pca_k).fit_transform(features)\n self.base_features = PCA(n_components=pca_k).fit_transform(base_features)\n else:\n self.features = features\n self.base_features = base_features\n\n self.algorithm = algorithm\n self.pca_k = pca_k\n self.random_state = random_state\n\n def __get_model(self, k: int = 2):\n \"\"\"\n Retrieve clustering model from the example predefined sentences\n\n :param k: amount of clusters\n :return: Clustering model\n\n \"\"\"\n\n if self.algorithm == 'gmm':\n return GaussianMixture(n_components=k, random_state=self.random_state)\n return KMeans(n_clusters=k, random_state=self.random_state)\n\n def __get_centroids(self, model):\n \"\"\"\n Retrieve centroids of model\n :param model: Clustering model\n :return: Centroids\n \"\"\"\n\n if self.algorithm == 'gmm':\n return model.means_\n return model.cluster_centers_\n\n def __find_closest_args(self, centroids: np.ndarray,k: int = 2):\n \"\"\"\n Find the closest arguments to centroids of the example sentences \n\n :param centroids: Centroids to find closest\n :param k: amount of sentences per cluster to look for\n :return: Closest arguments\n \"\"\"\n\n sentences_per_cluster = [int(k/len(centroids))]*len(centroids)\n idx = 0\n if k - sum(sentences_per_cluster) > len(sentences_per_cluster):\n sentences_per_cluster = [a+1 for a in sentences_per_cluster]\n while k - sum(sentences_per_cluster) > 0:\n sentences_per_cluster[idx] += 1\n idx += 1\n\n print(sentences_per_cluster)\n \n args = {}\n used_idx = []\n\n for j, centroid in enumerate(centroids):\n\n scored_ids = []\n\n for i, feature in enumerate(self.features):\n value = np.linalg.norm(feature - centroid)\n if i in used_idx:\n value = 100000000\n pass\n scored_ids.append(value)\n \n args[j] = np.argsort(scored_ids)[:sentences_per_cluster[j]]\n print(f\"Cluster {j}:\")\n for i in range(len(args[j])):\n print(f\"Sentence {args[j][i] + 1}:\\t{np.sort(scored_ids)[i]}\")\n used_idx.extend(args[j])\n # print(used_idx)\n\n # print(args)\n return args\n\n def cluster(self, nr_sentences: int = 4, clusters: int = 2) -> List[int]:\n \"\"\"\n Clusters sentences\n :param nr_sentences: Sentences to output at summary\n :param clusters: Clusters to use from base examples\n :return: Sentences index that qualify for summary\n \"\"\"\n\n model = self.__get_model(clusters).fit(self.base_features)\n centroids = self.__get_centroids(model)\n cluster_args = self.__find_closest_args(centroids,nr_sentences)\n # sorted_values = sorted(cluster_args.values())\n return cluster_args\n\n def __call__(self, nr_sentences: int = 4, clusters: int = 2) -> List[int]:\n return self.cluster(nr_sentences,clusters)\n","sub_path":"summarizer/cluster_features.py","file_name":"cluster_features.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"114331836","text":"\"\"\"\nShortest Word Edit Path\nGiven two words source and target, and a list of words words, find the length of the shortest series of edits that transforms source to target.\n\nEach edit must change exactly one letter at a time, and each intermediate word (and the final target word) must exist in words.\n\nIf the task is impossible, return -1.\n\nExamples:\n\nsource = \"bit\", target = \"dog\"\nwords = [\"but\", \"put\", \"big\", \"pot\", \"pog\", \"dog\", \"lot\"]\noutput: 5\nexplanation: bit -> but -> put -> pot -> pog -> dog has 5 transitions.\n\nsource = \"no\", target = \"go\"\nwords = [\"to\"]\noutput: -1\nConstraints:\n\n[time limit] 5000ms\n[input] string source\n1 ≤ source.length ≤ 20\n[input] string target\n1 ≤ target.length ≤ 20\n[input] array.string words\n1 ≤ words.length ≤ 20\n[output] array.integer\n\"\"\"\n\n\n# BFS\n# Time Complexity:\n# O(n^2*k) n is total number of all possible elements of queue and which is also length of words, k is length of a word\n# Space Complexity: O(n) for queue, n is as same as Time Complexity's\ndef shortestWordEditPath(source, target, words):\n queue = [(source, [source], 0)]\n while queue:\n current, seen, count = queue.pop(0)\n if current == target:\n return count\n\n for word in words:\n if word not in seen:\n diff_char = 0\n for i in range(len(word)):\n if word[i] != current[i]:\n diff_char += 1\n if diff_char == 1:\n queue.append((word, seen + [current], count + 1))\n\n return -1\n\n\n# DFS\n# Time Complexity: O(n^2*k), but exponential\n# Space Complexity: O(n) for res\ndef shortestWordEditPath(source, target, words):\n res = []\n\n def helper(current, seen, count):\n if current == target:\n res.append(count)\n return\n\n for word in words:\n if word not in seen:\n diff_char = 0\n for i in range(len(word)):\n if word[i] != current[i]:\n diff_char += 1\n if diff_char == 1:\n helper(word, seen + [current], count + 1)\n\n helper(source, [source], 0)\n return min(res) if res else -1\n\n\nsource = \"hit\"\ntarget = \"cog\"\nwords = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n\ntest = shortestWordEditPath(source, target, words)\nprint(test)","sub_path":"_pramp/200117/shortest_word_edit_path_mine.py","file_name":"shortest_word_edit_path_mine.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"653529988","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# create sin wave like data\nsin_wave = np.array([math.sin(x) for x in np.arange(200)])\n\nplt.plot(sin_wave[:50])\n\nx = []\ny = []\n\nsequence_length = 50\nnumber_of_records = len(sin_wave) - sequence_length\n\nfor i in range(number_of_records - 50):\n x.append(sin_wave[i:i + sequence_length])\n y.append(sin_wave[i + sequence_length])\n\nx = np.array(x)\ny = np.array(y)\n\nx = np.expand_dims(x, axis=2)\ny = np.expand_dims(y, axis=1)\n\nx_validation = []\ny_validation = []\n\nfor i in range(number_of_records - 50, number_of_records):\n x_validation.append(sin_wave[i:i + sequence_length])\n y_validation.append(sin_wave[i + sequence_length])\n\nx_validation = np.array(x_validation)\ny_validation = np.array(y_validation)\n\nx_validation = np.expand_dims(x_validation, axis=2)\ny_validation = np.expand_dims(y_validation, axis=1)\n\nlearning_rate = 0.0001\n# number of times the algorithm sees the entire data set\nnumber_of_epochs = 25\n# how many hidden layers does the RNN have\nhidden_layers = 100\n# output dimensions\nsingle_valued_output_layer = 1\n\nback_propagation_through_time_truncate = 5\nmin_clip_value = -10\nmax_clip_value = 10\n\n# weight matrix for weights between input and hidden layers\nU = np.random.uniform(0, 1, (hidden_layers, sequence_length))\n# weight matrix for shared weights in the RNN layer (hidden layer)\nW = np.random.uniform(0, 1, (hidden_layers, hidden_layers))\n# weight matrix for weights between hidden and output layers\nV = np.random.uniform(0, 1, (single_valued_output_layer, hidden_layers))\n\n\ndef sigmoid(x):\n \"\"\"\n activation function to be used in the hidden layer\n \"\"\"\n return 1 / (1 + np.exp(-x))\n\n# Check the loss on training data\n# Do a forward pass through our RNN model\n# and calculate the squared error for the predictions\n# for all records in order to get the loss value\n\n\nfor epoch in range(number_of_epochs):\n\n # check loss on train\n data_loss = 0.0\n\n # do a forward pass to get prediction\n for i in range(y.shape[0]):\n # get input, output values of each record\n __x, __y = x[i], y[i]\n previous_hidden_layer_activation = np.zeros(\n (hidden_layers, 1)) # initialized as zeroes\n for timestep in range(sequence_length):\n # we then do a forward pass for every timestep in the sequence\n new_input = np.zeros(__x.shape)\n # for this, we define a single input for that timestep\n new_input[timestep] = __x[timestep]\n multiplier_u = np.dot(U, new_input)\n multiplier_w = np.dot(W, previous_hidden_layer_activation)\n add = multiplier_u + multiplier_w\n current_hidden_layer_activation = sigmoid(add)\n multiplier_v = np.dot(V, current_hidden_layer_activation)\n previous_hidden_layer_activation = current_hidden_layer_activation\n\n # calculate error\n data_loss_per_record = (__y - multiplier_v)**2 / 2\n data_loss += data_loss_per_record\n\n data_loss = data_loss / float(__y.shape[0])\n\n # We check for the laoss of the validation data\n # using the same for loop and logic as with the training data\n\n # check loss on val\n validation_data_loss = 0.0\n\n for i in range(y_validation.shape[0]):\n __x, __y = x_validation[i], y_validation[i]\n previous_hidden_layer_activation = np.zeros(\n (hidden_layers, 1)) # initialized as zeroes\n for timestep in range(sequence_length):\n new_input = np.zeros(__x.shape)\n new_input[timestep] = __x[timestep]\n multiplier_u = np.dot(U, new_input)\n multiplier_w = np.dot(W, previous_hidden_layer_activation)\n add = multiplier_u + multiplier_w\n current_hidden_layer_activation = sigmoid(add)\n multiplier_v = np.dot(V, current_hidden_layer_activation)\n previous_hidden_layer_activation = current_hidden_layer_activation\n\n validation_data_loss_per_record = (__y - multiplier_v)**2 / 2\n validation_data_loss += validation_data_loss_per_record\n\n validation_data_loss = validation_data_loss / float(y.shape[0])\n\n # Forward pass\n # We first multiply the input with the weights between input and hidden layers\n # Add this with the multiplication of weights in the RNN layer.\n # This is because we want to capture the knowledge of the previous timestep\n # Pass it through a sigmoid activation function\n # Multiply this with the weights between hidden and output layers\n # At the output layer, we have a linear activation of the values\n # so we do not explicitly pass the value through an activation layer\n # Save the state at the current layer and also the state at the previous\n # timestep in a dictionary\n\n # train model\n for i in range(y.shape[0]):\n __x, __y = x[i], y[i]\n layers = []\n previous_hidden_layer_activation = np.zeros(\n (hidden_layers, 1)) # initialized as zeroes\n\n derivative_u = np.zeros(U.shape)\n derivative_v = np.zeros(V.shape)\n derivative_w = np.zeros(W.shape)\n\n derivative_u_timestep = np.zeros(U.shape)\n derivative_v_timestep = np.zeros(V.shape)\n derivative_w_timestep = np.zeros(W.shape)\n\n derivative_u_index = np.zeros(U.shape)\n derivative_w_index = np.zeros(W.shape)\n\n # forward pass\n for timestep in range(sequence_length):\n new_input = np.zeros(__x.shape)\n new_input[timestep] = __x[timestep]\n\n multiplier_u = np.dot(U, new_input)\n multiplier_w = np.dot(W, previous_hidden_layer_activation)\n\n add = multiplier_u + multiplier_w\n current_hidden_layer_activation = sigmoid(add)\n\n multiplier_v = np.dot(V, current_hidden_layer_activation)\n\n layers.append({'current_hidden_layer_activation': current_hidden_layer_activation,\n 'previous_hidden_layer_activation': previous_hidden_layer_activation})\n\n previous_hidden_layer_activation = current_hidden_layer_activation\n\n # Backpropagate Error\n # After the forward propagation step, we calculate the gradients at each layer, and backpropagate the errors\n # We will use truncated backpropagation through time (TBPTT),\n # instead of vanilla backprop.\n # It may sound complex but its actually pretty straight forward.\n # The core difference in BPTT versus backprop is\n # that the back propagation step is done for all the time steps in the RNN layer.\n # So if our sequence length is 50, we will backpropagate for all the timesteps previous to the current timestep.\n # If you have guessed correctly, BPTT seems very computationally expensive.\n # So instead of back propagating through all previous timesteps,\n # we backpropagate till x timesteps to save computational power.\n # Consider this ideologically similar to stochastic gradientdescent,\n # where we include a batch of data points instead of all the data points.\n # derivative of pred\n\n derivative_multiplier_v = (multiplier_v - __y)\n\n # backward pass\n for timestep in range(sequence_length):\n derivative_v_timestep = np.dot(\n derivative_multiplier_v, np.transpose(\n layers[timestep]['current_hidden_layer_activation']))\n derivative_current_hidden_layer_activation_v = np.dot(\n np.transpose(V), derivative_multiplier_v)\n\n derivative_current_hidden_layer_activation = derivative_current_hidden_layer_activation_v\n derivative_add = add * (1 - add) * \\\n derivative_current_hidden_layer_activation\n\n derivative_multiplier_w = derivative_add * \\\n np.ones_like(multiplier_w)\n\n derivative_previous_hidden_layer_activation = np.dot(\n np.transpose(W), derivative_multiplier_w)\n\n for i in range(timestep - 1, max(-1, timestep -\n back_propagation_through_time_truncate - 1), -1):\n derivative_current_hidden_layer_activation = (\n derivative_current_hidden_layer_activation_v +\n derivative_previous_hidden_layer_activation)\n\n derivative_add = add * \\\n (1 - add) * derivative_current_hidden_layer_activation_v\n\n derivative_multiplier_w = derivative_add * \\\n np.ones_like(multiplier_w)\n derivative_multiplier_u = derivative_add * \\\n np.ones_like(multiplier_u)\n\n derivative_w_index = np.dot(\n W, layers[timestep]['previous_hidden_layer_activation'])\n dprev_s = np.dot(np.transpose(W), derivative_multiplier_w)\n\n new_input = np.zeros(__x.shape)\n new_input[timestep] = __x[timestep]\n derivative_u_index = np.dot(U, new_input)\n derivative___x = np.dot(\n np.transpose(U), derivative_multiplier_u)\n\n derivative_u_timestep += derivative_u_index\n derivative_w_timestep += derivative_w_index\n\n derivative_v += derivative_v_timestep\n derivative_u += derivative_u_timestep\n derivative_w += derivative_w_timestep\n\n # Lastly, we update the weights with the gradients of weights calculated.\n # One thing we have to keep in mind is that the gradients tend to explode\n # if you don’t keep them in check.\n # This is a fundamental issue in training neural networks,\n # called the exploding gradient problem.\n # So we have to clamp them in a range so that they dont explode.\n\n if derivative_u.max() > max_clip_value:\n derivative_u[derivative_u > max_clip_value] = max_clip_value\n if derivative_v.max() > max_clip_value:\n derivative_v[derivative_v > max_clip_value] = max_clip_value\n if derivative_w.max() > max_clip_value:\n derivative_w[derivative_w > max_clip_value] = max_clip_value\n\n if derivative_u.min() < min_clip_value:\n derivative_u[derivative_u < min_clip_value] = min_clip_value\n if derivative_v.min() < min_clip_value:\n derivative_v[derivative_v < min_clip_value] = min_clip_value\n if derivative_w.min() < min_clip_value:\n derivative_w[derivative_w < min_clip_value] = min_clip_value\n\n # update weights\n U -= learning_rate * derivative_u\n V -= learning_rate * derivative_v\n W -= learning_rate * derivative_w\n\n print(f'Epoch: {epoch+1}'\n f'\\nData loss: {data_loss}'\n f'\\nValidation data loss: {validation_data_loss}')\n\n# We will do a forward pass through the trained weights to get our predictions:\npredicitons = []\nfor i in range(y.shape[0]):\n __x, __y = x[i], y[i]\n previous_hidden_layer_activation = np.zeros((hidden_layers, 1))\n # Forward pass\n for timestep in range(sequence_length):\n multiplier_u = np.dot(U, __x)\n multiplier_w = np.dot(W, previous_hidden_layer_activation)\n add = multiplier_u + multiplier_w\n current_hidden_layer_activation = sigmoid(add)\n multiplier_v = np.dot(V, current_hidden_layer_activation)\n previous_hidden_layer_activation = current_hidden_layer_activation\n\n predicitons.append(multiplier_v)\n\npredicitons = np.array(predicitons)\n\n# Plotting these predictions alongside the actual values\nplt.plot(predicitons[:, 0], 'g')\nplt.plot(y[:, 0], 'r')\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"127891701","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 02 19:07:43 2013\r\n\r\nLatex code templates for typesetting a spexdown script.\r\n\r\n@author: Koos Zevenhoven\r\n\"\"\"\r\nfrom __future__ import unicode_literals, print_function, division\r\n\r\nlatex_preamble1 = \"\"\"\r\n\\documentclass[a5paper,11pts]{article}\r\n\"\"\"\r\n#TODO can I get rid of color or wasysym (used for \\twonotes and \\eighthnote)\r\n\r\n# Had to convert from byte string, as \\u in \\usepackage would be interpreted\r\n# as a unicode code point escape. This problem will be gone in Py3k (PEP414)\r\nlatex_preamble2 = br\"\"\"\r\n\r\n\\makeatletter\r\n\\newcommand{\\needspace}[1]{%\r\n { \\begingroup\r\n \\setlength{\\dimen@}{#1}%\r\n \\vskip\\z@\\@plus\\dimen@\r\n \\penalty -100\\vskip\\z@\\@plus -\\dimen@\r\n \\vskip\\dimen@\r\n \\penalty 9999%\r\n \\vskip -\\dimen@\r\n \\vskip\\z@skip % hide the previous |\\vskip| from |\\addvspace|\r\n \\endgroup}\r\n}\r\n\\makeatother\r\n\r\n\\usepackage[utf8]{inputenc}\r\n\\usepackage[T1]{fontenc}\r\n\r\n\\usepackage[usenames]{color}\r\n\\usepackage{wasysym}\r\n\r\n\\addtolength\\columnsep{0.5cm}\r\n\\usepackage[portrait, left=1.4cm, top=1.5cm, right=1.4cm, nohead]{geometry}\r\n\r\n\\newcommand{\\scripttitle}[1]{\r\n %\\twocolumn\r\n \\newpage\r\n {{\\noindent { \\texttt{\\Huge #1}}}\\vspace{3.5cm}\\phantom{joo} \\\\ }\r\n \\newpage\r\n}\r\n\r\n\\newcommand{\\hugetitle}[1]{\\newpage\r\n \\noindent \\texttt{\\Huge #1} \\vspace{1.2cm}\\phantom{joo} \\\\\r\n}\r\n\r\n\\newcommand{\\character}[2]{\r\n\r\n \\noindent \\texttt{#1}\r\n \r\n \\setlength{\\leftskip}{8mm}\\nopagebreak\r\n \\noindent #2\r\n \r\n \\setlength{\\leftskip}{0mm}\r\n\r\n \\vspace{1mm}\r\n \r\n}\r\n\r\n\\newcommand{\\intermission}[1]{\\vspace{\\fill}\\vspace{5mm}\\begin{center}\\texttt{\\LARGE #1}\r\n\\end{center}\\vspace{4mm}\\vspace{\\fill}}\r\n\r\n\r\n\\newcommand{\\actlisting}[1]{\r\n \\vspace{1.5mm}\r\n \\noindent\r\n \\begin{tabular}{@{}l@{}}%\\hline\\hline\r\n \\begin{minipage}{\\columnwidth}\\vspace{1mm}\r\n \\LARGE \\bf \\texttt{#1}\\hfill\r\n \\end{minipage}\\\\\\hline\\nopagebreak %\\\\hline\r\n \\end{tabular}}\r\n\r\n\\newcommand{\\acttitle}[1]{\r\n\r\n \\newpage\\noindent\r\n \\begin{tabular}{@{}l@{}}\\hline\\hline\r\n \\begin{minipage}{\\columnwidth}\\vspace{1mm}\r\n \\LARGE \\bf \\texttt{#1}\\hfill\r\n \\end{minipage}\\\\\\hline\\hline\r\n \\end{tabular}\\nopagebreak}\r\n\r\n\r\n\\newcommand{\\scenetitle}[3]{\r\n\r\n \\vspace{0.4cm}\r\n \\pagebreak[3]\\begin{center}\\needspace{3cm}\\pagebreak[3]\\framebox{\\begin{minipage}{.87\\columnwidth}\r\n {\\Large \\bf \\texttt{#1}}\r\n #2\r\n \r\n \\begingroup {\\raggedleft\\texttt{\\small (#3)}\\\\*}\\endgroup\r\n \\end{minipage}}\\nopagebreak\\end{center}\\nopagebreak}\r\n\r\n\\newcommand{\\scenelisting}[3]{%\r\n \\begin{center}\\begin{minipage}{\\columnwidth}\r\n {\\Large \\bf \\texttt{#1}}\r\n #2\r\n \r\n \\begingroup{\\raggedleft\\texttt{\\small (#3)}\\par}\\endgroup\r\n \\end{minipage}\\end{center}\r\n \r\n}\r\n\r\n\r\n\\newcommand{\\anonymousblock}[1]{%\r\n \\noindent\r\n \\begin{minipage}[t]{1\\columnwidth}\\it\r\n #1\r\n %if(bufi >= bufsize)\r\n %\\qed\r\n \\end{minipage}\\vspace{1.6mm}\\par\r\n\r\n}\r\n\r\n\\newcommand{\\namedblock}[2]{%\r\n \\noindent\r\n \\begin{minipage}[t]{.22\\columnwidth}\\flushleft\\noindent\\textbf{#1\\vfill}\\end{minipage}\r\n \\begin{minipage}[t]{.78\\columnwidth} #2\r\n %if(bufi >= bufsize)\r\n %\\qed\r\n \\end{minipage}\\vspace{1.3mm}\\par\r\n \r\n}\r\n\r\n\\newcommand{\\musicblock}[2]{%\r\n \\noindent\r\n \\begin{minipage}[t]{.22\\columnwidth}\\flushright\\noindent\\textbf{#1\\vfill}\\end{minipage}\r\n \\begin{minipage}[t]{.78\\columnwidth} #2\r\n %if(bufi >= bufsize)\r\n %\\qed\r\n \\end{minipage}\\vspace{1.3mm}\\par\r\n\r\n}\r\n\r\n\\flushbottom\r\n\\widowpenalty=1000\r\n\\clubpenalty=1000\r\n\r\n\\begin{document}\r\n\"\"\".decode('ascii')\r\n\r\nlatex_end = r\"\"\"\r\n\\end{document}\r\n\r\n\"\"\"\r\n\r\npar_delimiter = \"\\n\\n\" r\"\\noindent\\hspace{5mm}\"\r\nsong_symbol = r\"\\twonotes \"\r\nmusic_symbol = r\"\\eighthnote \"\r\n\r\nVERSION = r\"$spe\\chi cript\\,0.3\\,beta$\"\r\n\r\nclass Spextex(object):\r\n \"\"\"An object for encoding spexcript elements into a latex source.\"\"\"\r\n \r\n def __init__(self, language):\r\n self._lang = language\r\n self.latex_data = [latex_preamble1, \r\n self._lang.LATEX_PREAMBLE,\r\n latex_preamble2]\r\n \r\n def final_result(self):\r\n self.latex_data.append(latex_end)\r\n return \"\".join(self.latex_data)\r\n \r\n def _process_string(self, string):\r\n #TODO handle underline emphasis somehow instead of just deleting\r\n replacements = [('$', r'{\\$}'), # must be first!\r\n (\"_\", r\"{\\textunderscore}\"),\r\n (\"&\", r\"{\\&}\"),\r\n ('\" ', r'{\"\\ }'),\r\n ('[', r'{$[$}'),\r\n (']', r'{$]$}'),\r\n ]\r\n for rep in replacements:\r\n string = string.replace(*rep)\r\n return string\r\n \r\n def _process_paragraphs(self, paragraphs):\r\n return [self._process_string(par) for par in paragraphs]\r\n \r\n def _format_paragraphs(self, paragraphs):\r\n return par_delimiter.join(self._process_paragraphs(paragraphs))\r\n\r\n def front_page(self, title):\r\n (SCRIPT, \r\n TITLE, title,\r\n DATE, \r\n OWNER_OF_COPY,\r\n SLOGAN, EXTRA) = map(self._process_string, \r\n (self._lang.SCRIPT, \r\n self._lang.TITLE, title,\r\n self._lang.DATE,\r\n self._lang.OWNER_OF_COPY,\r\n self._lang.SLOGAN, self._lang.EXTRA)) \r\n EXTRA = self._lang.EXTRA # bypass _process_string\r\n self.latex_data.append(r\"\"\"\r\n \\begin{titlepage}\r\n \\vspace*{\\fill}\r\n \\begin{center}\r\n \\vspace*{1cm}\r\n {\\Huge \\tt {\"\"\" + SCRIPT + r\"\"\"}\\hspace*{5cm}\\phantom{.}}\\\\\r\n \\vspace{.3cm}\r\n \\begin{tabular}{r|l}\r\n \\Large \"\"\" + TITLE + r\"\"\" &{\\Large \\tt \"\"\" + title + r\"\"\"}\\\\\r\n \\vspace{0.4cm}\r\n \"\"\" + DATE + r\"\"\" &{\\tt \\today}\\\\\r\n \\end{tabular}\r\n \\vspace{1.5cm}\r\n \r\n \\hspace*{2cm}\"\"\" + OWNER_OF_COPY + r\"\"\" \r\n \"\"\" \"\\\\u\" r\"\"\"nderline{\"\"\" + (r\"\\ \" * 38) + r\"\"\"}\\\\\r\n\r\n \\end{center}\r\n \\vspace*{\\fill}\r\n \\flushright\r\n \\small \"\"\" + VERSION + r\"\"\": \"\"\" + SLOGAN + r\"\"\"\\\\\r\n \\tiny \"\"\" + EXTRA + r\"\"\"\r\n \\end{titlepage}\r\n \"\"\")\r\n \r\n \r\n def paragraphs(self, paragraphs):\r\n paragraphs = self._format_paragraphs(paragraphs)\r\n self.latex_data.append(paragraphs)\r\n \r\n def characters_title(self):\r\n self.latex_data.append(r\"\\hugetitle{%s}\" % \r\n self._process_string(self._lang.CHARACTERS))\r\n \r\n def listing_title(self):\r\n self.latex_data.append(r\"\\hugetitle{%s}\" % \r\n self._process_string(self._lang.LIST_OF_SCENES))\r\n \r\n \r\n def character(self, display_name, full_name, description):\r\n full_name = self._process_string(full_name)\r\n if full_name != \"\":\r\n full_name = \" (%s)\" % full_name\r\n self.latex_data.append(r\"\\character{%s%s}{%s}\" %\r\n (self._process_string(display_name),\r\n self._process_string(full_name),\r\n self._format_paragraphs(description)))\r\n \r\n def music(self, names, paragraphs, style):\r\n postfix = r\"$\\;\\;$\" \r\n char_delimiter = postfix + r\"\\\\\"\r\n\r\n if style == \"song\":\r\n prefix = song_symbol + r\"\\hfill \"\r\n elif style == \"music\":\r\n prefix = music_symbol + r\"\\hfill \"\r\n\r\n text = self._format_paragraphs(paragraphs) + \"\\n\"\r\n self.latex_data.append(r\"\\musicblock{%s}{%s}\" % \r\n (prefix + \r\n self._process_string(char_delimiter.join(names)) +\r\n postfix, text))\r\n \r\n def block(self, names, paragraphs):\r\n prefix = \"\"\r\n char_delimiter = r\"\\hspace{0.1mm}&\\hspace{0.1mm}\"\r\n postfix = \":\"\r\n text = self._format_paragraphs(paragraphs) + \"\\n\"\r\n if len(names) == 0:\r\n self.latex_data.append(r\"\\anonymousblock{%s}\" % text)\r\n else:\r\n self.latex_data.append(r\"\\namedblock{%s}{%s}\" % \r\n (prefix + \r\n self._process_string(char_delimiter.join(names)) +\r\n postfix, text))\r\n\r\n \r\n def scene(self, act, scene, title, people = [],\r\n description_pars = [], listing = False):\r\n if len(description_pars) > 0:\r\n descr = r\"\\\\\" + self._format_paragraphs(description_pars) + \"\\n\"\r\n else:\r\n descr = \"\"\r\n \r\n def make_people_list():\r\n for cont, name in people:\r\n append = \"\"\r\n if \"Music\" in cont:\r\n append += music_symbol\r\n if \"Song\" in cont:\r\n append += song_symbol\r\n\r\n\r\n if name == \"\":\r\n if append != \"\":\r\n yield append\r\n else:\r\n if append == \"\":\r\n yield name\r\n else:\r\n yield name + \" \" + append\r\n \r\n \r\n \r\n data = (self._process_string(self._lang.scene_title(act, \r\n scene, \r\n title)), \r\n descr,\r\n \", \".join(make_people_list()))\r\n if listing:\r\n self.latex_data.append(r\"\\scenelisting{%s}{%s}{%s}\" % data)\r\n else:\r\n self.latex_data.append(r\"\\scenetitle{%s}{%s}{%s}\" % data)\r\n \r\n def scene_end(self):\r\n pass\r\n \r\n def act(self, number, title, listing = False):\r\n cmd = r\"\\acttitle{%s}\" if not listing else r\"\\actlisting{%s}\"\r\n self.latex_data.append(cmd % \r\n self._lang.act_title(number, self._process_string(title)))\r\n\r\n def intermission(self):\r\n self.latex_data.append(r\"\\intermission{%s}\" % self._lang.INTERMISSION)\r\n \r\n def script_title(self):\r\n self.latex_data.append(r\"\\scripttitle{%s}\" % self._lang.SCRIPT)\r\n \r\nPDFLATEX = r\"C:\\Program Files (x86)\\MiKTeX 2.9\\miktex\\bin\\pdflatex.exe\"\r\n#ACROREAD = r\"C:\\Program Files (x86)\\Adobe\\Reader 10.0\\Reader\\AcroRd32.exe\"\r\nPDFLATEX = 'pdflatex'\r\n#ACROREAD = 'acroread'\r\n\r\ndef pdflatex(latex_unicode, outputfile=\"output.pdf\"):\r\n from pathlib import Path\r\n import shutil\r\n tmp = Path(\"spexcript_tmp\")\r\n tmp.mkdir(exist_ok = True)\r\n tex = tmp/\"spex.tex\"\r\n with open(str(tex), \"w\", encoding = 'utf8') as f:\r\n f.write(latex_unicode)\r\n from subprocess import Popen, PIPE\r\n Popen([\"pdflatex\", r\"spex.tex\"], \r\n stdout=PIPE, stderr=PIPE, cwd = str(tmp)).communicate()\r\n shutil.copy(str(tex.with_suffix(\".pdf\")), outputfile)\r\n shutil.rmtree(str(tmp))\r\n\r\ndef show():\r\n import os\r\n import os.path\r\n os.startfile(os.path.join(\"tmp\", \"spex.pdf\"))\r\n \r\n \r\n \r\n","sub_path":"spexcript/latex.py","file_name":"latex.py","file_ext":"py","file_size_in_byte":11119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"405675905","text":"\"\"\"\n The Nested demo shows the use of nested state machines. We define a\n new node class DingDong that has a three-node state machine inside\n it. We then define the main class, Nested, whose state machine\n contains two instances of DingDong. DingDong uses a ParentCompletes\n node to cause DinDong to post a completion event, which allows\n Nested's first DingDong instance 'dd1' to move on to the next state,\n which is 'bridge'. (The 'dd2' instance also posts a completion\n event, but nothing is listening for it.)\n\n Behavior: Cozmo says 'ding', then 'dong', then 'once again' (that's\n the bridge), then 'ding', and then 'dong'.\n\n Shorthand for DingDong:\n ding: Say('ding') =C=> dong: Say('dong') =C=> ParentCompletes()\n\n Shorthand for Nested:\n dd1: DingDong() =C=> bridge: Say('once again') =C=> dd2: DingDong()\n\"\"\"\n\nfrom cozmo_fsm import *\n\nclass DingDong(StateNode):\n def setup(self):\n ding = Say(\"ding\")\n ding.set_name('ding')\n ding.set_parent(self)\n\n dong = Say(\"dong\")\n dong.set_name('dong')\n dong.set_parent(self)\n\n done = ParentCompletes()\n done.set_name('done')\n done.set_parent(self)\n\n ct1 = CompletionTrans()\n ct1.set_name('ct1')\n ct1.add_source(ding)\n ct1.add_destination(dong)\n\n ct2 = CompletionTrans()\n ct2.set_name('ct2')\n ct2.add_source(dong)\n ct2.add_destination(done)\n\n return self\n\n\nclass Nested(StateNode):\n def setup(self):\n self.name = 'Nested'\n\n dd1 = DingDong()\n dd1.set_name('dd1')\n dd1.set_parent(self)\n\n bridge = Say(\"once again\")\n bridge.set_name('bridge')\n bridge.set_parent(self)\n\n dd2 = DingDong()\n dd2.set_name('dd2')\n dd2.set_parent(self)\n\n ct1 = CompletionTrans()\n ct1.set_name('ct1')\n ct1.add_source(dd1)\n ct1.add_destination(bridge)\n\n ct2 = CompletionTrans()\n ct2.set_name('ct2')\n ct2.add_source(bridge)\n ct2.add_destination(dd2)\n\n return self\n","sub_path":"cozmo_fsm/examples/Nested.py","file_name":"Nested.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"586698146","text":"#!/bin/env python\n# coding:utf-8\n\nimport sys\nimport urllib\nimport re\nimport lxml.html\nimport sqlite3\nimport mojimoji\nimport datetime\n\n# 将来日程を取得する 年に一回\nclass HtmlParse:\n def __init__(self,dbname):\n self.con = sqlite3.connect(dbname)\n self.cur=self.con.cursor()\n self.cur.execute(\"delete from game_schedule\")\n self.con.commit()\n\n def run(self):\n self.execute( \"https://www.jleague.jp/match/search/j1/all/\")\n self.execute( \"https://www.jleague.jp/match/search/j2/all/\")\n self.execute( \"https://www.jleague.jp/match/search/j3/all/\")\n\n def execute(self,url):\n html = urllib.urlopen(url).read()\n html = re.sub(\"\\r\", \"\", html)\n html = re.sub(\"\\n\", \"\", html)\n html = re.sub(\"\", \"\", html)\n doc = lxml.html.fromstring(html)\n\n xmls = doc.xpath('//div[@class=\"main\"]//section[@class=\"contentBlock\"]/section[@class=\"matchlistWrap\"]')\n for xml in xmls:\n self.parse(xml)\n\n def parse(self,xml):\n if len(xml.xpath('div[@class=\"timeStamp\"]/h4'))==0:\n return\n ymd=xml.xpath('div[@class=\"timeStamp\"]/h4')[0].text\n start_date=self.conv_date(ymd)\n\n for item in xml.xpath('table[@class=\"matchTable\"]/tbody/tr'):\n\n if len(item.xpath('td[@class=\"stadium\"]/a'))==0:\n continue\n stadium=item.xpath('td[@class=\"stadium\"]/a')[0].text\n home_team=item.xpath('td//td[@class=\"clubName leftside\"]//text()')[1]\n away_team = item.xpath('td//td[@class=\"clubName rightside\"]//text()')[1]\n\n print (start_date+\",\"+stadium+\",\"+home_team+\",\"+away_team)\n\n home_team_c=self.get_team_c(home_team)\n away_team_c=self.get_team_c(away_team)\n stadium_c=self.get_stadium_c(stadium)\n self.cur.execute(\"insert into game_schedule(start_date,stadium,stadium_c,home_team,home_team_c,away_team,away_team_c) values(?,?,?,?,?,?,?)\",(start_date,stadium,stadium_c,home_team,home_team_c,away_team,away_team_c,))\n self.con.commit()\n\n def to_s(self,s):\n return mojimoji.han_to_zen(s)\n\n def conv_date(self,ymd):\n tmp=ymd.split(u\"年\")\n yy=tmp[0]\n tmp=tmp[1].split(u\"月\")\n mm=tmp[0]\n tmp=tmp[1].split(u\"日\")\n dd=tmp[0]\n ms=str(mm)\n if int(mm) < 10:\n ms=\"0\"+str(mm)\n ds=str(dd)\n if int(dd) < 10:\n ds=\"0\"+str(dd)\n return str(yy)+\"-\"+ms+\"-\"+ds\n\n\n def get_team_c(self,team):\n res = self.cur.execute(\"select team_c from team_master where team=?\",(team,))\n rows = res.fetchall()\n if len(rows)>0:\n return rows[0][0]\n else:\n return None\n\n def get_stadium_c(self,stadium):\n res = self.cur.execute(\"select stadium_c from stadium_master where stadium=?\",(stadium,))\n rows = res.fetchall()\n if len(rows)>0:\n return rows[0][0]\n else:\n return None\n\ndef main(dbname):\n hp=HtmlParse(dbname)\n hp.run()\n\nif __name__ == \"__main__\":\n argvs = sys.argv\n argc = len(argvs)\n\n if argc <= 1:\n dbname = \"/Volumes/DATA/data/soccer.db\"\n else:\n dbname=argvs[1]\n\n main(dbname)","sub_path":"src/03_sc_schedule.py","file_name":"03_sc_schedule.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233355291","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnum = 1001\nstd = 5 \n\n# x : x-coordinate data\n# y1 : (clean) y-coordinate data \n# y2 : (noisy) y-coordinate data\n\ndef fun(x):\n \n\t# f = np.sin(x) * (1 / (1 + np.exp(-x))) \n\tf = np.abs(x) * np.sin(x)\n\n\treturn f\n\nn = np.random.rand(num)\nnn = n - np.mean(n)\nx = np.linspace(-10,10,num)\ny1 = fun(x) \t\t\t# clean points\ny2 = y1 + nn * std\t\t# noisy points\n\nplt.plot(x, y1, 'b.', x, y2, 'k.')\nplt.show()\n","sub_path":"assignment12.py","file_name":"assignment12.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"34257747","text":"# disas1.py\n\nfrom elftools.elf.elffile import ELFFile\nfrom capstone import *\n\n\nwith open('./chall.elf', 'rb') as f:\n elf = ELFFile(f)\n code = elf.get_section_by_name('.text')\n ops = code.data()\n addr = code['sh_addr']\n md = Cs(CS_ARCH_X86, CS_MODE_64)\n for i in md.disasm(ops, addr):\n print(f'0x{i.address:x}:\\t{i.mnemonic}\\t{i.op_str}')\n","sub_path":"single_files/disas1.py","file_name":"disas1.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"345579337","text":"import docker\nfrom .db_utils import DBUtils\nfrom .models import DynamicDockerChallenge\n\n\nclass DockerUtils:\n @staticmethod\n def add_new_docker_container(user_id, challenge_id, flag, uuid_code):\n configs = DBUtils.get_all_configs()\n\n dynamic_docker_challenge = DynamicDockerChallenge.query \\\n .filter(DynamicDockerChallenge.id == challenge_id) \\\n .first_or_404()\n\n client = docker.DockerClient(base_url=configs.get(\"docker_api_url\"))\n client.containers.run(image=dynamic_docker_challenge.docker_image, name=str(user_id) + '-' + uuid_code,\n environment={'FLAG': flag}, detach=True, network=\"ctfd_frp-containers\",\n mem_limit=dynamic_docker_challenge.memory_limit)\n\n @staticmethod\n def remove_current_docker_container(user_id):\n configs = DBUtils.get_all_configs()\n container = DBUtils.get_current_container(user_id=user_id)\n\n if container is None:\n return\n\n client = docker.DockerClient(base_url=configs.get(\"docker_api_url\"))\n containers = client.containers.list(filters={'name': str(user_id) + '-' + container.uuid})\n for c in containers:\n c.remove(force=True)\n","sub_path":"docker_utils.py","file_name":"docker_utils.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"209457914","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n__author__ = 'Andy'\n\"\"\"快讯数据库操作\"\"\"\nfrom cores.Mysql import db_write\nimport time\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass FastNews(object):\n\t\"\"\"快讯操作\"\"\"\n\n\tdef __init__(self):\n\t\tpass\n\n\tdef get_fnews_list(self, db=None, index=1, size=10):\n\t\t\"\"\"获取快讯列表\"\"\"\n\t\tindex = index if index >= 1 else 1\n\t\tsize = size if size >= 0 else 10\n\t\toffset = (index - 1) * size\n\t\tsql = \"select * from tb_fast_news where status=1 order by weight desc,pub_time desc limit {offset},{size}\".format(\n\t\t\toffset=offset, size=size)\n\t\tif not db:\n\t\t\tdb = db_write(\"ear\")\n\t\tdata = db.query(sql)\n\t\treturn data\n\n\tdef get_fnews_total_count(self, db=None):\n\t\t\"\"\"获取快讯总数\"\"\"\n\t\tsql = \"select count(id) as total_count from tb_fast_news where status=1\"\n\t\tif not db:\n\t\t\tdb = db_write(\"ear\")\n\t\tdata = db.queryOne(sql)\n\t\tif not data:\n\t\t\treturn 0\n\t\treturn data['total_count']\n\n\tdef increment_fnews_share(self, fnews_id):\n\t\t\"\"\"\n\t\t给分享次数+1\n\t\t:param fnews_id:快讯id\n\t\t:return:\n\t\t\"\"\"\n\t\tsql = \"update tb_fast_news set share_count=share_count+1 where id={fnews_id}\".format(fnews_id=fnews_id)\n\t\tdb = db_write(\"ear\")\n\t\ttry:\n\t\t\tdb.execute(sql)\n\t\t\tdb.commit()\n\t\texcept Exception as error:\n\t\t\tlogger.error(\"increment_news_readnum occur error-->{error}\".format(error=error))\n\t\treturn None\n\n\n\tdef get_fnews_details(self, fnews_id, db=None):\n\t\t\"\"\"\n\t\t获取快讯详情\n\t\t:param fnews_id:\n\t\t:param db:\n\t\t:return:\n\t\t\"\"\"\n\t\tsql = \"select * from tb_fast_news where status=1 and id={fnews_id}\".format(fnews_id=fnews_id)\n\t\tif not db:\n\t\t\tdb = db_write(\"ear\")\n\t\tdata = db.queryOne(sql)\n\t\tif not data:\n\t\t\treturn {}\n\t\treturn data\n\n\nfnewsdao = FastNews()\n","sub_path":"dao/fnewsdao.py","file_name":"fnewsdao.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"623930899","text":"# http://localhost:8050/test/client/submit\n# http://localhost:8050/test/client/status/28902ec5-8930-4d03-bea4-6347b6b0a793\n# http://localhost:8050/test/client/cancel/c625249b-a662-493d-8825-2626ad94d0ba\n# http://localhost:8050/test/client/response/aca89ce0-ac1a-4f58-985d-9c0aad49fc6a\nimport base64\nimport json\nimport logging\nimport os\n\n# TODO: update this script to:\n# - register a callback url\n# - validate the msToken on the callback\n# - get the response status\n# - display the likRequest, etc, by reading the variables from the SM.\n\n# TODO: check if sameSite= None is being set\nimport flask\nfrom flask import render_template, Response, request\n\nfrom engine import app\nfrom config import config\n\nfrom lib.CMHandler import CMHandler\nfrom lib.SMHandler import SMHandler, EndpointNotFound\nfrom lib.Tools import load_json_file\nfrom lib.dto.LinkRequest import LinkRequest\n\n# Config location\nfrom lib.httpsig.HttpSigClient import HttpSigClient\n\ndata_dir = config.get('Configuration', 'dir')\nport = config.get('Server', 'port')\nkey_file = config.get('HTTPSig', 'private_key')\ncm_url = config.get('CM', 'url')\ncm_url = os.getenv('MSMETADATAURL', cm_url)\n\nclient_key_file = config.get('TestClient', 'cli_key')\ntrusted_key = config.get('TestClient', 'trusted_key')\nfingerprnt = config.get('TestClient', 'fingerprint')\ntest_link_req = config.get('TestClient', 'test_link_req')\n\ntest_auth_req = config.get('TestClient', 'test_auth_req')\ntest_sp_metadata = config.get('TestClient', 'test_sp_metadata')\n\ncburl = \"/test/client/callback\"\n\n\ndef httpsig_client():\n key = client_key_file\n fingerprint = fingerprnt\n trusted_keys = {fingerprnt: trusted_key}\n return HttpSigClient(key, trusted_keys)\n\n\ndef cm_handler():\n ms_url = cm_url\n return CMHandler(data_dir, key=key_file, lifetime=30, ms_source_url=ms_url)\n\n\ndef sm_handler():\n cm = cm_handler()\n sm = cm.get_microservice_by_api('SM')\n return SMHandler(sm, key=key_file, retries=5, validate=False)\n\n\ndef get_url(mo, apiClass, apiCall):\n for api in mo.publishedAPI:\n if api.apiClass == apiClass and api.apiCall == apiCall:\n return api.apiEndpoint\n raise EndpointNotFound(\"API call \" + apiCall + \" from class \" + apiClass +\n \" not found on any entry in the \" +\n mo.smMetadata.msId + \" microservice metadata object\")\n\n\n# API Endpoints\n\n\n# Callback address\n@app.route('/test/client/', methods=['GET', 'POST'])\n@app.route('/test/client/callback', methods=['GET', 'POST'])\ndef test_client_callback():\n token = ''\n session = ''\n output = ''\n session_str = ''\n sessid = ''\n datastoreStr = ''\n requestID = None\n if request.form and request.form['msToken']:\n token = request.form['msToken']\n\n logging.debug(\"token: \" + token)\n token = token.split('.')\n logging.debug(\"split token: \" + str(token))\n\n # Add padding to the B64 string\n token[1] += \"=\" * ((4 - len(token[1]) % 4) % 4)\n btoken = bytes(token[1], 'utf-8')\n token = base64.b64decode(btoken)\n json_token = json.loads(token)\n token = json.dumps(json_token, indent=4)\n\n jwt = json.loads(token)\n\n sessid = jwt['sessionId']\n smh = sm_handler()\n smh.setSessID(sessid)\n\n session = smh.getSessionVar()\n session_str = ''\n for sessvar in session:\n value = session[sessvar]\n if value[0] == '{':\n valueunesc = value.replace('\\\\\"', '\"')\n jsonvalue = json.loads(valueunesc)\n session[sessvar] = jsonvalue\n indentvalue = json.dumps(jsonvalue, indent=4)\n session_str = session_str + sessvar + ': ' + indentvalue + '\\n--------\\n'\n else:\n session_str = session_str + sessvar + ': ' + value + '\\n--------\\n'\n\n if session['linkRequest']:\n linkRequest = session['linkRequest']\n logging.debug(\"linkRequest: \" + str(linkRequest))\n if linkRequest['id']:\n requestID = linkRequest['id']\n logging.debug(\"linkRequest.id: \" + str(requestID))\n\n datastore = smh.searchDatastoreEntries()\n for entry in datastore:\n datastoreStr = json.dumps(entry.marshall(), indent=4)\n\n template = {\n 'token': token,\n 'datastore': datastoreStr,\n 'session': session_str,\n 'display': output,\n }\n if requestID:\n template['requestID'] = requestID\n if sessid:\n template['sessionID'] = sessid\n logging.debug(\"Template vars: \" + str(template))\n return render_template('callback.html', template=template)\n\n\n# Start a linking request\n@app.route('/test/client/submit', methods=['GET'])\ndef test_client_submit_linking_request():\n smh = sm_handler()\n\n smh.startSession()\n print(\"Started session: \" + smh.sessId + \"
\\n\")\n\n smh.writeSessionVar(cburl, 'ClientCallbackAddr')\n\n token = smh.generateToken(\"SAMLms_0001\", \"SAMLms_0001\")\n print(\"Generated msToken: \" + token + \"
\\n\")\n\n streq = load_json_file(test_link_req)\n treq = LinkRequest()\n treq.unmarshall(streq)\n smh.writeSessionVar(treq.marshall(), 'linkRequest')\n print(\"Wrote linkRequest in Session: \" + treq.json_marshall() + \"
\\n\")\n\n template = {\n 'url': '/link/request/submit',\n 'token': token,\n }\n\n return render_template('msToken.html', template=template)\n\n\n# Check status of a linking request\n@app.route('/test/client/status/', methods=['GET'])\ndef test_client_status_linking_request(request_id):\n cli = httpsig_client()\n thishost = flask.request.host\n thisscheme = flask.request.scheme\n resp = cli.get(f'{thisscheme}://{thishost}/link/{request_id}/status')\n return Response(resp.text,\n status=200,\n mimetype='application/json')\n\n\n@app.route('/test/client/cancel//', methods=['GET'])\ndef test_client_cancel_linking_request(request_id, sess_id):\n smh = sm_handler()\n\n ## We don't care about the session, and no user is authenticated\n # smh.startSession()\n # print(\"Started session (a different one): \" + smh.sessId + \"
\\n\")\n\n smh.setSessID(sess_id)\n\n token = smh.generateToken(\"SAMLms_0001\", \"SAMLms_0001\")\n print(\"Generated msToken: \" + token + \"
\\n\")\n\n template = {\n 'url': f'/link/{request_id}/cancel',\n 'token': token,\n }\n\n return render_template('msToken.html', template=template)\n\n\n@app.route('/test/client/response//', methods=['GET'])\ndef test_client_getresult_linking_request(request_id, sess_id):\n smh = sm_handler()\n\n ## We don't care about the session, and no user is authenticated\n # smh.startSession()\n # print(\"Started session (a different one): \" + smh.sessId + \"
\\n\")\n\n smh.setSessID(sess_id)\n\n token = smh.generateToken(\"SAMLms_0001\", \"SAMLms_0001\")\n print(\"Generated msToken: \" + token + \"
\\n\")\n\n template = {\n 'url': f'/link/{request_id}/result/get',\n 'token': token,\n }\n\n return render_template('msToken.html', template=template)\n\n\n# TODO: tune this with the proper parameters and target ms, and test\n# Start a linking request\n# to [Discovery, PDS, uportSSIwallet, eIDAS, eduGAIN]\n# of [auth_request, data_query]\n# http://localhost:8050/test/client/sp/eduGAIN/auth_request\n@app.route('/test/client/sp//', methods=['GET'])\ndef test_client_submit_auth_request(idp, type):\n # Start session\n smh = sm_handler()\n smh.startSession()\n print(\"Started session: \" + smh.sessId + \"
\\n\")\n\n # Generate Token\n dest = 'RMms001'\n token = smh.generateToken(\"SAMLms_0001\", dest)\n print(f\"Generated msToken addressed to {dest}: {token}
\\n\")\n\n # Write session variables\n with open(test_auth_req, encoding='utf-8') as f:\n authreq = f.read()\n smh.writeSessionVar(authreq, 'spRequest') # TODO: check variable\n with open(test_sp_metadata, encoding='utf-8') as f:\n spmeta = f.read()\n smh.writeSessionVar(spmeta, 'spMetadata') # TODO: check variable\n smh.writeSessionVar(idp, 'apEntityId') # TODO: check variable\n\n smh.writeSessionVar(type, 'spRequestEP')\n smh.writeSessionVar(idp, 'spRequestSource')\n\n # Check written vars\n print(\"spRequest: \" + smh.getSessionVar('spRequest') + \"
\\n\")\n print(\"spMetadata: \" + smh.getSessionVar('spMetadata') + \"
\\n\")\n print(\"apEntityId: \" + smh.getSessionVar('apEntityId') + \"
\\n\")\n print(\"spRequestEP: \" + smh.getSessionVar('spRequestEP') + \"
\\n\")\n print(\"spRequestSource: \" + smh.getSessionVar('spRequestSource') + \"
\\n\")\n\n # Now let's get the Request Manager metadata\n cm = cm_handler()\n rm = cm.get_microservice_by_api('RM')\n\n url = get_url(rm, 'RM', 'rmRequest')\n template = {\n 'url': url,\n 'token': token,\n }\n\n return render_template('msToken.html', template=template)\n\n\n# Tests for HTTPSig server and client # TODO: implement\n\n\n# Test HTTPSig server\n@app.route('/test/server/httpsig', methods=['GET', 'POST'])\ndef test_server_httpsig_verify():\n return \"AAAAA\"\n\n\n# Test HTTPSig client GET\n@app.route('/test/client/httpsig/get', methods=['GET'])\ndef test_client_submit_httpsig_get():\n c = httpsig_client()\n res = c.get(\"http://localhost:8080/test/server/httpsig\")\n return \"Hola\", 200\n\n\n# Test HTTPSig client POST Form # TODO: implement\n@app.route('/test/client/httpsig/post/form', methods=['POST'])\ndef test_client_submit_httpsig_form():\n pass\n\n\n# Test HTTPSig client POST Json # TODO: implement\n@app.route('/test/client/httpsig/post/json', methods=['POST'])\ndef test_client_submit_httpsig_json():\n pass\n","sub_path":"api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"315129343","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module calls sacct in Slurm to obtain detailed accouting infieldsion about\nindividual jobs or job steps. This module can only be used in Python 3.5 or above.\n\nJob State:\nhttps://slurm.schedmd.com/sacct.html#SECTION_JOB-STATE-CODES\n\nGet all jobs that have been terminated.\nsacct --allusers --starttime midnight --endtime now --state BOOT_FAIL,CANCELLED,COMPLETED,DEADLINE,FAILED,NODE_FAIL,OUT_OF_MEMORY,PREEMPTED,TIMEOUT --fields=partition,nodelist,group,user,jobname,jobid,submit,start,end,exitcode,cputimeraw,tresusageintot,tresusageouttot,maxvmsize,alloccpus,ntasks,cluster,timelimitraw,reqmem,State -p > sacct_raw_parse.txt\nsacct --allusers --starttime midnight --endtime now --state BOOT_FAIL,CANCELLED,COMPLETED,DEADLINE,FAILED,NODE_FAIL,OUT_OF_MEMORY,PREEMPTED,TIMEOUT --fields=partition,nodelist,group,user,jobname,jobid,submit,start,end,exitcode,cputimeraw,tresusageintot,tresusageouttot,maxvmsize,alloccpus,ntasks,cluster,timelimitraw,reqmem,State > sacct_raw.txt\n\nJie Li (jie.li@ttu.edu)\n\"\"\"\nimport sys\nimport json\nimport subprocess\nfrom multiprocessing import Process, Queue\n\nsys.path.append('../')\n\nfrom sharings.utils import parse_config\n\ndef fetch_slurm_job() -> list:\n # Read configuration file\n config_path = './config.yml'\n config = parse_config(config_path)\n\n # Setting command parameters\n accounting_fields = config[\"slurm\"][\"accounting_fields\"]\n job_states = config[\"slurm\"][\"job_states\"]\n start_time = config[\"slurm\"][\"start_time\"]\n end_time = config[\"slurm\"][\"end_time\"]\n \n # The command used in cli\n command = [\"ssh li29729@login.hpcc.ttu.edu \" + \"'sacct --allusers --starttime \" + start_time + \" --endtime \" + end_time + \" --state \" + \",\".join(job_states) + \" --fields=\" + \",\".join(accounting_fields) + \" -p'\"]\n\n # Get strings from command line\n rtn_str = subprocess.run(command, shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')\n \n # Split strings by line, and discard the first line that indicates the metrics name\n rtn_str_arr = rtn_str.splitlines()[1:]\n\n # Get all job data dict\n job_dict_all = generate_job_dict(accounting_fields, rtn_str_arr)\n\n # Aggregate job data\n aggregated_job_data = aggregate_job_data(job_dict_all)\n \n return aggregated_job_data\n\n\ndef convert_str_json(fields: list, job_str: str, queue: object) -> dict:\n \"\"\"\n Convert the job data in string to job data in json.\n \"\"\"\n job_dict = {}\n job_data = {}\n job_str_arr = job_str.split(\"|\")\n \n for i in range(len(fields)):\n job_data.update({\n fields[i]: job_str_arr[i]\n })\n \n job_dict = {\n job_data[\"JobID\"]: job_data\n }\n\n queue.put(job_dict)\n\n\ndef generate_job_dict(fields: list, rtn_str_arr: list) -> dict:\n \"\"\"\n Generate the job dict from string using multiprocesses.\n \"\"\"\n job_dict_all = {}\n queue = Queue()\n procs = []\n for rtn_str in rtn_str_arr:\n p = Process(target=convert_str_json, args=(fields, rtn_str, queue))\n procs.append(p)\n p.start()\n \n for _ in procs:\n job_dict = queue.get()\n job_dict_all.update(job_dict)\n\n for p in procs:\n p.join()\n\n return job_dict_all\n\n\ndef unfold_metrics(metric_str: str, in_out: str) -> dict:\n \"\"\"\n Unfold the metrics under the same metric name(such as tresusageintot, tresusageouttot)\n \"\"\"\n metric_dict = {}\n for item in metric_str.split(\",\"):\n item_pair = item.split(\"=\")\n\n if item_pair[0] == \"fs/disk\" or item_pair[0] == \"energy\":\n key_name = item_pair[0] + \"_\" + in_out\n else:\n key_name = item_pair[0]\n\n metric_dict.update({\n key_name: item_pair[1]\n })\n\n return metric_dict\n\n\ndef merge_metrics(job_metircs: dict, batch_step_metrics: dict) -> dict:\n \"\"\"\n Merge metrics under JobID with metrics under batch and jobstep, update the job name\n \"\"\"\n merged_metrics = {}\n for key, value in batch_step_metrics.items():\n if value == \"\" or key == \"JobName\":\n merged_metrics.update({\n key: job_metircs[key]\n })\n else:\n merged_metrics.update({\n key: value\n })\n return merged_metrics\n\n\ndef merge_job_dict(job_dict_all: dict, job_id_raw: str, queue: object) -> dict:\n \"\"\"\n Aggregate jobid with jobid.batch and jobid.step# , and unfold several metrics under the same \n attribute, such as \"tresusageintot\", \"tresusageouttot\".\n \"\"\"\n merged_data = {}\n # only keep resource statistics under batch and jobstep, discard extern\n if \".batch\" in job_id_raw or \".\" in job_id_raw and \".extern\" not in job_id_raw:\n # merge metrics\n job_id = job_id_raw.split('.')[0]\n merged_data = merge_metrics(job_dict_all[job_id], job_dict_all[job_id_raw])\n \n # Unfold metrics in treusageintot and tresusageoutot\n folded_metrics = merged_data.get(\"TresUsageInTot\", None)\n if folded_metrics:\n unfolded_metrics = unfold_metrics(folded_metrics, \"in\")\n merged_data.update(unfolded_metrics)\n merged_data.pop(\"TresUsageInTot\")\n \n folded_metrics = merged_data.get(\"TresUsageOutTot\", None)\n if folded_metrics:\n unfolded_metrics = unfold_metrics(folded_metrics, \"out\")\n merged_data.update(unfolded_metrics)\n merged_data.pop(\"TresUsageOutTot\")\n\n if \".batch\" in job_id_raw:\n # Update the job id if it contains batch\n merged_data.update({\n \"JobID\": job_id\n })\n \n # Add unique ids, which is used as unique ids for the record\n merged_data.update({\n \"_id\": merged_data[\"JobID\"]\n })\n\n queue.put(merged_data)\n\n\ndef aggregate_job_data(job_dict_all: dict) -> dict:\n \"\"\"\n Aggregate job dict using multiprocesses.\n \"\"\"\n aggregated_job_data = []\n job_id_raw_list = job_dict_all.keys()\n queue = Queue()\n procs = []\n for job_id_raw in job_id_raw_list:\n p = Process(target=merge_job_dict, args=(job_dict_all, job_id_raw, queue))\n procs.append(p)\n p.start()\n \n for _ in procs:\n job_data = queue.get()\n if job_data:\n aggregated_job_data.append(job_data)\n\n for p in procs:\n p.join()\n\n return aggregated_job_data\n\n\nif __name__ == '__main__':\n records = fetch_slurm_job()\n print(json.dumps(records, indent=4))","sub_path":"slurmapi/fetch_slurm_job.py","file_name":"fetch_slurm_job.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"46299452","text":"# Copyright 2020 Alexis Lopez Zubieta\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n\nclass MissingConfigurationField(RuntimeError):\n pass\n\n\nfrom appimagebuilder.builder.app_info.app_info import AppInfo\n\n\nclass AppInfoLoader:\n def load(self, config):\n app_info = self._read_config_fields(config)\n\n return app_info\n\n def _read_config_fields(self, recipe):\n app_info = AppInfo()\n app_info.id = recipe.get_item(\"AppDir/app_info/id\")\n app_info.name = recipe.get_item(\"AppDir/app_info/name\")\n app_info.version = recipe.get_item(\"AppDir/app_info/version\")\n app_info.icon = recipe.get_item(\"AppDir/app_info/icon\")\n app_info.exec = recipe.get_item(\"AppDir/app_info/exec\")\n app_info.exec_args = recipe.get_item(\"AppDir/app_info/exec_args\", \"$@\")\n return app_info\n\n @staticmethod\n def _try_read_mandatory_config_value(config, key):\n if key in config:\n return config[key]\n else:\n raise MissingConfigurationField(key)\n\n @staticmethod\n def _try_read_config_value(config, key):\n return config[key] if key in config else None\n","sub_path":"appimagebuilder/builder/app_info/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"27441179","text":"# Copyright (C) 2011 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\nimport phonopy.structure.spglib as spg\nfrom phonopy.structure.symmetry import Symmetry, find_primitive, get_pointgroup\nfrom phonopy.structure.cells import get_primitive\nfrom phonopy.interface.vasp import write_vasp\nfrom phonopy.structure.atoms import PhonopyAtoms as Atoms\n\n\ndef check_symmetry(input_cell,\n primitive_axis=None,\n symprec=1e-5,\n distance_to_A=1.0,\n phonopy_version=None):\n if primitive_axis is None:\n cell = get_primitive(input_cell, np.eye(3), symprec=symprec)\n else:\n cell = get_primitive(input_cell, primitive_axis, symprec=symprec)\n lattice = cell.get_cell() * distance_to_A\n cell.set_cell(lattice)\n\n symmetry = Symmetry(cell, symprec)\n print(_get_symmetry_yaml(cell, symmetry, phonopy_version))\n\n if input_cell.get_magnetic_moments() is None:\n primitive = find_primitive(cell, symprec)\n if primitive is not None:\n print(\"# Primitive cell was found. It is written into PPOSCAR.\")\n write_vasp('PPOSCAR', primitive)\n\n # Overwrite symmetry and cell\n symmetry = Symmetry(primitive, symprec)\n cell = primitive\n\n (bravais_lattice,\n bravais_pos,\n bravais_numbers) = spg.refine_cell(cell, symprec)\n bravais = Atoms(numbers=bravais_numbers,\n scaled_positions=bravais_pos,\n cell=bravais_lattice,\n pbc=True)\n print(\"# Bravais lattice is written into BPOSCAR.\")\n write_vasp('BPOSCAR', bravais)\n\n\ndef _get_symmetry_yaml(cell, symmetry, phonopy_version=None):\n rotations = symmetry.get_symmetry_operations()['rotations']\n translations = symmetry.get_symmetry_operations()['translations']\n\n atom_sets = symmetry.get_map_atoms()\n independent_atoms = symmetry.get_independent_atoms()\n wyckoffs = symmetry.get_Wyckoff_letters()\n\n yaml = []\n\n if phonopy_version is not None:\n yaml.append(\"phonopy_version: '%s'\" % phonopy_version)\n\n if cell.get_magnetic_moments() is None:\n spg_symbol, spg_number = symmetry.get_international_table().split()\n spg_number = int(spg_number.replace('(', '').replace(')', ''))\n yaml.append(\"space_group_type: '%s'\" % spg_symbol)\n yaml.append(\"space_group_number: %d\" % spg_number)\n yaml.append(\"point_group_type: '%s'\" % symmetry.get_pointgroup())\n yaml.append(\"space_group_operations:\")\n for i, (r, t) in enumerate(zip(rotations, translations)):\n yaml.append(\"- rotation: # %d\" % (i + 1))\n for vec in r:\n yaml.append(\" - [%2d, %2d ,%2d]\" % tuple(vec))\n line = \" translation: [\"\n for j, x in enumerate(t):\n if abs(x - np.rint(x)) < 1e-5:\n line += \" 0.00000\"\n else:\n line += \"%8.5f\" % x\n if j < 2:\n line += \", \"\n else:\n line += \" ]\"\n yaml.append(line)\n yaml.append(\"atom_mapping:\")\n for i, atom_num in enumerate(atom_sets):\n yaml.append(\" %d: %d\" % (i + 1, atom_num + 1))\n yaml.append(\"site_symmetries:\")\n for i in independent_atoms:\n sitesym = symmetry.get_site_symmetry(i)\n yaml.append(\"- atom: %d\" % (i + 1))\n\n if cell.get_magnetic_moments() is None:\n yaml.append(\" Wyckoff: '%s'\" % wyckoffs[i])\n site_pointgroup = get_pointgroup(sitesym)\n yaml.append(\" site_point_group: '%s'\" % site_pointgroup[0])\n yaml.append(\" orientation:\")\n for v in site_pointgroup[1]:\n yaml.append(\" - [%2d, %2d, %2d]\" % tuple(v))\n\n yaml.append(\" rotations:\")\n for j, r in enumerate(sitesym):\n yaml.append(\" - # %d\" % (j + 1))\n for vec in r:\n yaml.append(\" - [%2d, %2d, %2d]\" % tuple(vec))\n\n return \"\\n\".join(yaml)\n","sub_path":"phonopy/cui/show_symmetry.py","file_name":"show_symmetry.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"604232099","text":"# coding: utf-8\n# Iris Species Multi-Class Classification Model\n# Explore Dataset\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nimport tensorflow as tf\n\n# 데이터 입력\ndf = pd.read_csv('./dataset/iris.csv', names=[\"sepal_length\", \"sepal_width\", \"petal_length\", \"petal_width\", \"species\"])\n\n# 데이터 분류\ndataset = df.values\nx = dataset[:, 0:4].astype(float)\n# print(x.shape)\n\nt = dataset[:, 4]\n# print(t)\n\n# 문자열을 숫자로 변환\n# [1 0 0] = 'Iris-setosa'\n# [0 1 0] = 'Iris-versicolor'\n# [0 0 1] = 'Iris-virginica'\n\ne = LabelEncoder()\ne.fit(t)\nt = e.transform(t)\nt = tf.keras.utils.to_categorical(t)\nprint(t)\n\n\n\n\n\n\n","sub_path":"04.deep-learning/03.tensorflow-keras-practice/03.iris/ex01.py","file_name":"ex01.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"362066480","text":"# Copyright 2019 Yelp Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\n\nimport mock\nimport pytest\n\nfrom clusterman.aws.auto_scaling_resource_group import AutoScalingResourceGroup\nfrom clusterman.aws.auto_scaling_resource_group import CLUSTERMAN_STALE_TAG\nfrom clusterman.aws.client import autoscaling\nfrom clusterman.aws.client import ec2\nfrom clusterman.aws.markets import InstanceMarket\n\n\n@pytest.fixture\ndef mock_launch_config():\n launch_config = {\n 'LaunchConfigurationName': 'fake_launch_config',\n 'ImageId': 'ami-785db401', # this AMI is hard-coded into moto, represents ubuntu xenial\n 'InstanceType': 't2.2xlarge',\n }\n autoscaling.create_launch_configuration(**launch_config)\n return launch_config\n\n\n@pytest.fixture\ndef mock_asg_name():\n return 'fake_asg'\n\n\n@pytest.fixture\ndef mock_cluster():\n return 'fake_cluster'\n\n\n@pytest.fixture\ndef mock_pool():\n return 'fake_pool'\n\n\n@pytest.fixture\ndef mock_asg_config(mock_subnet, mock_launch_config, mock_asg_name, mock_cluster, mock_pool):\n asg = {\n 'AutoScalingGroupName': mock_asg_name,\n 'LaunchConfigurationName': mock_launch_config['LaunchConfigurationName'],\n 'MinSize': 1,\n 'MaxSize': 30,\n 'DesiredCapacity': 10,\n 'AvailabilityZones': ['us-west-2a'],\n 'VPCZoneIdentifier': mock_subnet['Subnet']['SubnetId'],\n 'Tags': [\n {\n 'Key': 'puppet:role::paasta',\n 'Value': json.dumps({\n 'pool': mock_pool,\n 'paasta_cluster': mock_cluster\n }),\n }, {\n 'Key': 'fake_tag_key',\n 'Value': 'fake_tag_value',\n },\n ],\n 'NewInstancesProtectedFromScaleIn': True,\n }\n autoscaling.create_auto_scaling_group(**asg)\n\n return asg\n\n\ndef test_group_config(mock_asg_config):\n mock_asrg = AutoScalingResourceGroup.__new__(AutoScalingResourceGroup) # skip init\n mock_asrg.group_id = mock_asg_config['AutoScalingGroupName']\n\n group_config = mock_asrg._group_config\n\n assert group_config['AutoScalingGroupName'] == \\\n mock_asg_config['AutoScalingGroupName']\n\n\n@pytest.fixture\ndef mock_asrg(mock_asg_config):\n return AutoScalingResourceGroup(mock_asg_config['AutoScalingGroupName'])\n\n\ndef test_launch_config(mock_asrg, mock_launch_config):\n launch_config = mock_asrg._launch_config\n\n assert launch_config['LaunchConfigurationName'] == \\\n mock_launch_config['LaunchConfigurationName']\n\n\ndef test_launch_config_retry(mock_asrg, mock_launch_config):\n no_configs = dict(LaunchConfigurations=[])\n good_configs = dict(LaunchConfigurations=[mock_launch_config])\n mock_describe_launch_configs = mock.Mock(side_effect=[\n no_configs, good_configs,\n ])\n\n with mock.patch(\n 'clusterman.aws.client.autoscaling.describe_launch_configurations',\n mock_describe_launch_configs,\n ):\n launch_config = mock_asrg._launch_config\n\n assert launch_config == mock_launch_config\n assert mock_describe_launch_configs.call_count == 2\n\n\n@pytest.mark.parametrize('instance_type', ['t2.2xlarge', 'm5.large'])\n@mock.patch('clusterman.aws.auto_scaling_resource_group.logger', autospec=True)\ndef test_market_weight(mock_logger, mock_asrg, instance_type):\n market_weight = mock_asrg.market_weight(InstanceMarket(instance_type, 'us-west-2a'))\n\n assert market_weight == 1.0\n assert mock_logger.warning.call_count == (1 if instance_type == 'm5.large' else 0)\n\n\n@pytest.mark.parametrize('dry_run', [True, False])\ndef test_mark_stale(mock_asrg, dry_run):\n mock_asrg.mark_stale(dry_run)\n for inst in mock_asrg.instance_ids:\n tags = ec2.describe_tags(\n Filters=[{\n 'Name': 'resource-id',\n 'Values': [inst],\n }],\n )\n stale_tags = [tag for tag in tags['Tags'] if tag['Key'] == CLUSTERMAN_STALE_TAG]\n if dry_run:\n assert not stale_tags\n else:\n assert len(stale_tags) == 1\n\n\n@pytest.mark.parametrize('stale_instances', [0, 7])\ndef test_modify_target_capacity_up(mock_asrg, stale_instances):\n new_desired_capacity = mock_asrg.target_capacity + 5\n with mock.patch(\n 'clusterman.aws.auto_scaling_resource_group.AutoScalingResourceGroup.stale_instance_ids',\n mock.PropertyMock(return_value=mock_asrg.instance_ids[:stale_instances])\n ):\n\n mock_asrg.modify_target_capacity(\n new_desired_capacity,\n dry_run=False,\n honor_cooldown=False,\n )\n\n assert mock_asrg.target_capacity == new_desired_capacity\n assert mock_asrg.fulfilled_capacity == new_desired_capacity + stale_instances\n\n\n@pytest.mark.parametrize('stale_instances', [0, 7])\ndef test_modify_target_capacity_down(mock_asrg, stale_instances):\n old_target_capacity = mock_asrg.target_capacity\n new_target_capacity = old_target_capacity - 5\n\n with mock.patch(\n 'clusterman.aws.auto_scaling_resource_group.AutoScalingResourceGroup.stale_instance_ids',\n mock.PropertyMock(return_value=mock_asrg.instance_ids[:stale_instances])\n ):\n mock_asrg.modify_target_capacity(\n new_target_capacity,\n dry_run=False,\n honor_cooldown=False,\n )\n\n assert mock_asrg.target_capacity == new_target_capacity\n # because some instances are stale, we might have to _increase_ our \"real\" target capacity\n # even if we're decreasing our _requested_ target capacity\n assert mock_asrg.fulfilled_capacity == max(old_target_capacity, new_target_capacity + stale_instances)\n\n\n@pytest.mark.parametrize('new_desired_capacity', [0, 100])\ndef test_modify_target_capacity_min_max(\n mock_asrg,\n mock_asg_config,\n new_desired_capacity,\n):\n mock_asrg.modify_target_capacity(\n new_desired_capacity,\n dry_run=False,\n honor_cooldown=False,\n )\n\n if new_desired_capacity < mock_asg_config['MinSize']:\n assert mock_asrg.target_capacity == mock_asg_config['MinSize']\n elif new_desired_capacity > mock_asg_config['MaxSize']:\n assert mock_asrg.target_capacity == mock_asg_config['MaxSize']\n\n\n@pytest.mark.parametrize('stale_instances', [0, 1, 10])\ndef test_status(mock_asrg, stale_instances):\n is_stale = stale_instances == 10\n with mock.patch(\n 'clusterman.aws.auto_scaling_resource_group.AutoScalingResourceGroup.is_stale',\n new_callable=mock.PropertyMock(return_value=is_stale)\n ), mock.patch(\n 'clusterman.aws.auto_scaling_resource_group.AutoScalingResourceGroup.stale_instance_ids',\n new_callable=mock.PropertyMock(return_value=mock_asrg.instance_ids[:stale_instances])\n ):\n status = mock_asrg.status\n if stale_instances == 0:\n assert status == 'active'\n elif stale_instances > 0:\n assert status == 'rolling'\n\n\ndef test_get_asg_tags(mock_asrg, mock_asg_config):\n asg_id_to_tags = mock_asrg._get_resource_group_tags()\n\n assert mock_asg_config['AutoScalingGroupName'] in asg_id_to_tags\n tags = asg_id_to_tags[mock_asg_config['AutoScalingGroupName']]\n assert 'fake_tag_key' in tags\n assert tags['fake_tag_key'] == 'fake_tag_value'\n","sub_path":"tests/aws/auto_scaling_resource_group_test.py","file_name":"auto_scaling_resource_group_test.py","file_ext":"py","file_size_in_byte":7742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"450427682","text":"#!/usr/bin/env python3\n\n# === IMPORTS ===\nimport logging\nimport os\n\nfrom flask import Flask\n\nfrom inovonics.cloud.datastore import InoRedis\nfrom inovonics.cloud.oauth import InoOAuth2Provider, oauth_register_handlers\n\nfrom inovonics.cloud.oauth import OAuthClients, OAuthClient, OAuthUsers, OAuthUser\n\n# === GLOBALS ===\nREDIS_HOST = os.getenv('REDIS_HOST', 'localhost')\nREDIS_PORT = os.getenv('REDIS_PORT', 6379)\nREDIS_DB = os.getenv('REDIS_DB', 0)\n\ndstore = InoRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)\n\napp = Flask(__name__)\n\noauth = InoOAuth2Provider(app, dstore)\noauth_register_handlers(app, oauth, token_path='/oauth/token', revoke_path='/oauth/revoke')\n\n# === FUNCTIONS ===\n@app.before_first_request\ndef db_init():\n # This flushes the Redis database and pushed a default user and a couple of default clients into the database.\n dstore.redis.flushdb()\n users = OAuthUsers(dstore)\n clients = OAuthClients(dstore)\n \n user1_data = {\n 'username': 'admin@example.com',\n 'first_name': 'Admin',\n 'last_name': 'Testuser',\n 'is_active': True,\n 'scopes': ['protected']\n }\n user1 = OAuthUser(user1_data)\n user1.update_password('')\n users.create(user1)\n \n client1_data = {\n 'name': 'Test Client One',\n 'client_id': '', # API_KEY\n 'client_secret': '', # API_SECRET\n 'user': 'admin@example.com',\n 'is_confidential': False,\n 'allowed_grant_types': ['password'],\n 'redirect_uris': [],\n 'default_scopes': ['protected'],\n 'allowed_scopes': ['protected']\n }\n client1 = OAuthClient(client1_data)\n clients.create(client1)\n\n@app.route('/')\ndef static_root():\n return app.send_static_file('index.html')\n\n@app.route('/protected/')\n@oauth.require_oauth('protected')\ndef protected_page():\n return app.send_static_file('protected.html')\n\n# === CLASSES ===\n\n# === MAIN ===\ndef main():\n # Allow non-TLS protected requests for testing\n os.environ['DEBUG'] = 'true'\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'\n \n # Enable DEBUG logging\n logging.basicConfig(level=logging.DEBUG)\n \n # Make the magic happen\n app.run(debug=True, host='0.0.0.0', port=8080)\n\nif __name__ == '__main__':\n main()\n","sub_path":"example/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"168810492","text":"class Customer:\n name = \"\"\n lastName = \"\"\n age = 0\n\n def addCart(self):\n print(\"Added to \" +self.name+ \" \" + self.lastName + \"'s cart\")\n\ncustomer1 = Customer()\ncustomer1.name = \"Bob\"\ncustomer1.lastName = \"Baby\"\ncustomer1.age = 8\ncustomer1.addCart()\n\ncustomer2 = Customer()\ncustomer2.name = \"BBJ\"\ncustomer2.lastName = \"747\"\ncustomer2.age = 56\ncustomer2.addCart()\n\ncustomer3 = Customer()\ncustomer3.name = \"ASTON\"\ncustomer3.lastName = \"MARTIN\"\ncustomer3.age = 106\ncustomer3.addCart()\n\ncustomer4 = Customer()\ncustomer4.name = \"BUGATTI\"\ncustomer4.lastName = \"CHIRON SPORT\"\ncustomer4.age = 490\ncustomer4.addCart()","sub_path":"Lecture_104_Phattarapol_R.py","file_name":"Lecture_104_Phattarapol_R.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"367080335","text":"import re\n\n\nre_type_switch = {\n 'str': ('(.*)', str),\n 'int': ('([0-9]*)', int),\n 'user_id': ('<@!?([0-9]*)>', int),\n 'channel_id': ('<#([0-9]*)>', int),\n 'role_id': ('<@&([0-9]*)>', int),\n}\n\ndef build_regex(expression):\n splitted = expression.split(' ')\n rx = [splitted[0]]\n cast_to_list = []\n for argument in splitted[1:]:\n # remove the < and >\n arg = argument[1:-1]\n [argument_name, argument_type] = arg.split(':')\n\n argument_regex, cast_to = re_type_switch.get(argument_type)\n cast_to_list.append(cast_to)\n rx.append(argument_regex)\n\n return re.compile('^' + ' '.join(rx)), cast_to_list\n\n","sub_path":"mee6/command/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"168186706","text":"#!/opt/libreoffice5.2/program/python\n# -*- coding: utf-8 -*-\nimport unohelper\nfrom com.sun.star.awt.PosSize import POSSIZE\nfrom com.sun.star.style.VerticalAlignment import BOTTOM\nfrom com.sun.star.awt import XActionListener\nfrom com.sun.star.awt import Rectangle\nfrom com.sun.star.awt.MessageBoxType import INFOBOX\nfrom com.sun.star.awt.MessageBoxButtons import BUTTONS_OK\nfrom com.sun.star.beans import NamedValue\n\ndef macro():\n ctx = XSCRIPTCONTEXT.getComponentContext() # コンポーネントコンテクストの取得。\n smgr = ctx.getServiceManager() # サービスマネージャーの取得。\n doc = XSCRIPTCONTEXT.getDocument() # マクロを起動した時のドキュメントのモデルを取得。 \n docframe = doc.getCurrentController().getFrame() # モデル→コントローラ→フレーム、でドキュメントのフレームを取得。\n docwindow = docframe.getContainerWindow() # ドキュメントのウィンドウを取得。\n toolkit = docwindow.getToolkit() # ツールキットを取得。\n taskcreator = smgr.createInstanceWithContext('com.sun.star.frame.TaskCreator', ctx)\n args = NamedValue(\"PosSize\", Rectangle(150, 150, 200, 200)), NamedValue(\"FrameName\", \"NewFrame\") # , NamedValue(\"MakeVisible\", True) # TaskCreatorで作成するフレームのコンテナウィンドウのプロパティ。\n frame = taskcreator.createInstanceWithArguments(args) # コンテナウィンドウ付きの新しいフレームの取得。\n subwindow = frame.getContainerWindow() # 新しいコンテナウィンドウを新しいフレームから取得。\n frame.setTitle(\"New Frame\") # フレームのタイトルを設定。\n docframe.getFrames().append(frame) # 新しく作ったフレームを既存のフレームの階層に追加する。\n controlcontainer = smgr.createInstanceWithContext(\"com.sun.star.awt.UnoControlContainer\", ctx) # コントロールコンテナを生成。\n controlcontainermodel = smgr.createInstanceWithContext(\"com.sun.star.awt.UnoControlContainerModel\", ctx) # コントールコンテナのモデルを生成。\n controlcontainermodel.setPropertyValue(\"BackgroundColor\", -1) # 背景色。-1は何色?\n controlcontainer.setModel(controlcontainermodel) # コントールコンテナにモデルを設定。\n controlcontainer.createPeer(toolkit, subwindow) # 新しく作ったウィンドウ内にコントロールコンテナのコントロールをツールキットで描画する。\n controlcontainer.setPosSize(0, 0, 200, 200, POSSIZE) # コントロールの表示座標を設定。4つ目の引数は前の引数の意味を設定する。\n frame.setComponent(controlcontainer, None) # コントロールコンテナをフレームにのコンポーネントウィンドウに設定する。今回のコントローラはNone。\n label = createControl(smgr, ctx, \"FixedText\", 10, 0, 180, 30, (\"Label\", \"VerticalAlign\"), (\"Label1\", BOTTOM)) # 固定文字コントールを作成。\n edit = createControl(smgr, ctx, \"Edit\", 10, 40, 180, 30, (), ()) # 編集枠コントロールを作成。\n btn = createControl(smgr, ctx, \"Button\", 110, 130, 80, 35, (\"DefaultButton\", \"Label\"), (True, \"btn\")) # ボタンコントロールを作成。\n controlcontainer.addControl(\"label\", label) # コントロールコンテナにコントロールを名前を設定して追加。\n controlcontainer.addControl(\"btn\", btn) # コントロールコンテナにコントロールを名前を設定して追加。\n controlcontainer.addControl(\"edit\", edit) # コントロールコンテナにコントロールを名前を設定して追加。\n edit.setFocus() # 編集枠コントロールにフォーカスを設定する。\n btn.setActionCommand(\"btn\") # ボタンを起動した時のコマンド名を設定する。\n btn.addActionListener(BtnListener(controlcontainer, subwindow)) # ボタンにリスナーを設定。コントロールの集合を渡しておく。\n subwindow.setVisible(True) # 新しく作ったウィンドウを見えるようにする。execute()メソッドはないのでノンモダルダイアログにはできない。\nclass BtnListener(unohelper.Base, XActionListener):\n def __init__(self, controlcontainer, window): \n self.controlcontainer = controlcontainer # コントロールの集合。\n self.window = window # コントロールのあるウィンドウ。\n def actionPerformed(self, actionevent):\n cmd = actionevent.ActionCommand # アクションコマンドを取得。\n editcontrol = self.controlcontainer.getControl(\"edit\") # editという名前のコントロールを取得。\n if cmd == \"btn\": # 開くsyんコマンドがbtnのとき\n editcontrol.setText(\"By Button Click\") # editコントロールに文字列を代入。\n toolkit = self.window.getToolkit()\n msgbox = toolkit.createMessageBox(self.window, INFOBOX, BUTTONS_OK, \"Text Field\", \"{}\".format(editcontrol.getText())) # ピアオブジェクトからツールキットを取得して、peerを親ウィンドウにしてメッセージボックスを作成。\n msgbox.execute() # メッセージボックスを表示。\n msgbox.dispose() # メッセージボックスを破棄。\n def disposing(self, eventobject):\n pass\ndef createControl(smgr, ctx, ctype, x, y, width, height, names, values):\n ctrl = smgr.createInstanceWithContext(\"com.sun.star.awt.UnoControl{}\".format(ctype), ctx)\n ctrl_model = smgr.createInstanceWithContext(\"com.sun.star.awt.UnoControl{}Model\".format(ctype), ctx)\n ctrl_model.setPropertyValues(names, values)\n ctrl.setModel(ctrl_model)\n ctrl.setPosSize(x, y, width, height, POSSIZE)\n return ctrl\ng_exportedScripts = macro, #マクロセレクターに限定表示させる関数をタプルで指定。\n\n\nif __name__ == \"__main__\": # オートメーションで実行するとき\n import officehelper\n import traceback\n from functools import wraps\n import sys\n from com.sun.star.beans import PropertyValue\n from com.sun.star.script.provider import XScriptContext \n def connectOffice(func): # funcの前後でOffice接続の処理\n @wraps(func)\n def wrapper(): # LibreOfficeをバックグラウンドで起動してコンポーネントテクストとサービスマネジャーを取得する。\n try:\n ctx = officehelper.bootstrap() # コンポーネントコンテクストの取得。\n except:\n print(\"Could not establish a connection with a running office.\")\n sys.exit()\n print(\"Connected to a running office ...\")\n smgr = ctx.getServiceManager() # サービスマネジャーの取得。\n print(\"Using {} {}\".format(*_getLOVersion(ctx, smgr))) # LibreOfficeのバージョンを出力。\n try:\n return func(ctx, smgr) # 引数の関数の実行。\n except:\n traceback.print_exc()\n def _getLOVersion(ctx, smgr): # LibreOfficeの名前とバージョンを返す。\n cp = smgr.createInstanceWithContext('com.sun.star.configuration.ConfigurationProvider', ctx)\n node = PropertyValue(Name = 'nodepath', Value = 'org.openoffice.Setup/Product' ) # share/registry/main.xcd内のノードパス。\n ca = cp.createInstanceWithArguments('com.sun.star.configuration.ConfigurationAccess', (node,))\n return ca.getPropertyValues(('ooName', 'ooSetupVersion')) # LibreOfficeの名前とバージョンをタプルで返す。\n return wrapper\n @connectOffice # mainの引数にctxとsmgrを渡すデコレータ。\n def main(ctx, smgr): # XSCRIPTCONTEXTを生成。\n class ScriptContext(unohelper.Base, XScriptContext):\n def __init__(self, ctx):\n self.ctx = ctx\n def getComponentContext(self):\n return self.ctx\n def getDesktop(self):\n return self.ctx.getServiceManager().createInstanceWithContext(\"com.sun.star.frame.Desktop\", self.ctx)\n def getDocument(self):\n return self.getDesktop().getCurrentComponent()\n return ScriptContext(ctx) \n XSCRIPTCONTEXT = main() # XSCRIPTCONTEXTを取得。\n doc = XSCRIPTCONTEXT.getDocument() # ドキュメントを取得。\n if not hasattr(doc, \"getCurrentController\"): # ドキュメント以外のとき。スタート画面も除外。\n XSCRIPTCONTEXT.getDesktop().loadComponentFromURL(\"private:factory/swriter\", \"_blank\", 0, ()) # Writerのドキュメントを開く。\n while doc is None: # ドキュメントのロード待ち。\n doc = XSCRIPTCONTEXT.getDocument()\n macro()","sub_path":"GUI/src/macro/modelessdialog2macro_taskcreator.py","file_name":"modelessdialog2macro_taskcreator.py","file_ext":"py","file_size_in_byte":8868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"189604477","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\statistics\\skill_tests.py\n# Compiled at: 2019-07-25 23:11:41\n# Size of source mod 2**32: 22711 bytes\nfrom event_testing.results import TestResult, TestResultNumeric\nfrom event_testing.test_events import TestEvent, cached_test\nfrom interactions import ParticipantType\nfrom objects import ALL_HIDDEN_REASONS\nfrom sims4.tuning.tunable import TunableFactory, TunableEnumEntry, TunableThreshold, Tunable, HasTunableSingletonFactory, AutoFactoryInit, TunableInterval, TunableVariant, OptionalTunable, TunableReference, TunablePackSafeReference\nfrom statistics.skill import Skill, _CareerSkillLootData\nimport event_testing.test_base, services, sims4, statistics.skill, tag\nlogger = sims4.log.Logger('SkillTests', default_owner='bosee')\n\nclass SkillTagThresholdTest(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n test_events = (\n TestEvent.SkillLevelChange,)\n\n @TunableFactory.factory_option\n def participant_type_override(participant_type_enum, participant_type_default):\n return {'who': TunableEnumEntry(description='\\n Who or what to apply this test to.\\n ',\n tunable_type=participant_type_enum,\n default=participant_type_default)}\n\n FACTORY_TUNABLES = {'who':TunableEnumEntry(description='\\n Who or what to apply this test to.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'skill_tag':TunableEnumEntry(description='\\n What tag to test for.\\n ',\n tunable_type=tag.Tag,\n invalid_enums=(\n tag.Tag.INVALID,),\n default=tag.Tag.INVALID), \n 'skill_threshold':TunableThreshold(description='\\n The threshold level to test of each skill.\\n '), \n 'skill_quantity':Tunable(description='\\n The minimum number of skills at or above this level required to pass.\\n ',\n tunable_type=int,\n default=0), \n 'test_only_changed_skill':Tunable(description='\\n If checked then we will only test the skill that actually changed.\\n ',\n tunable_type=bool,\n default=False)}\n\n def get_expected_args(self):\n if self.test_only_changed_skill:\n return {'test_targets':self.who, \n 'skill':event_testing.test_constants.FROM_EVENT_DATA}\n return {'test_targets': self.who}\n\n @cached_test\n def __call__(self, test_targets=None, skill=None):\n skill_tag = self.skill_tag\n threshold = self.skill_threshold\n quantity = self.skill_quantity\n for target in test_targets:\n if skill_tag is None:\n return TestResult(False, 'Tag not present or failed to load.')\n if target is None:\n logger.error('Trying to call SkillTagThresholdTest for skill_tag {} which has target as None.', skill_tag)\n return TestResult(False, 'Target({}) does not exist', self.who)\n elif skill_tag is tag.Tag.INVALID:\n return TestResult(False, 'Tag test is set to INVALID, aborting test.')\n if threshold.value == 0 or quantity == 0:\n return TestResult(False, 'Threshold or Quantity not set, aborting test.')\n num_passed = 0\n highest_skill_value = 0\n if skill is not None:\n skills_to_check = (\n skill,)\n else:\n skills_to_check = target.all_skills()\n for stat in skills_to_check:\n if skill_tag in stat.tags:\n curr_value = 0\n if not stat.is_initial_value:\n curr_value = stat.get_user_value()\n if threshold.compare(curr_value):\n num_passed += 1\n elif curr_value > highest_skill_value:\n highest_skill_value = curr_value\n\n if num_passed >= quantity or num_passed == 0:\n if quantity == 1:\n return TestResultNumeric(False, 'The number of applicable skills: {} was not high enough to pass: {}.',\n num_passed,\n quantity,\n current_value=highest_skill_value,\n goal_value=(threshold.value),\n is_money=False,\n tooltip=(self.tooltip))\n return TestResultNumeric(False, 'The number of applicable skills: {} was not high enough to pass: {}.',\n num_passed,\n quantity,\n current_value=num_passed,\n goal_value=quantity,\n is_money=False,\n tooltip=(self.tooltip))\n\n return TestResult.TRUE\n\n def validate_tuning_for_objective(self, objective):\n if self.skill_tag is tag.Tag.INVALID:\n if self.skill_threshold.value == 0:\n if self.skill_quantity == 0:\n logger.error('Invalid tuning in objective {}. One of the following must be true: Tag must not be INVALID, Threshold Value must be greater than 0, or Quantity must be greater than 0.', objective)\n\n def goal_value(self):\n if self.skill_quantity > 1:\n return self.skill_quantity\n return self.skill_threshold.value\n\n\nclass SkillThreshold(HasTunableSingletonFactory, AutoFactoryInit):\n FACTORY_TUNABLES = {'skill_threshold': TunableThreshold(description='\\n The Threshold for the skill level to be valid.\\n ',\n value=Tunable(description='\\n The value of a threshold.\\n ',\n tunable_type=int,\n default=0))}\n\n @property\n def skill_range_max(self):\n comparison_operator = sims4.math.Operator.from_function(self.skill_threshold.comparison)\n if comparison_operator == sims4.math.Operator.LESS_OR_EQUAL or comparison_operator == sims4.math.Operator.LESS or comparison_operator == sims4.math.Operator.EQUAL:\n return self.skill_threshold.value\n return statistics.skill.MAX_SKILL_LEVEL\n\n @property\n def skill_range_min(self):\n comparison_operator = sims4.math.Operator.from_function(self.skill_threshold.comparison)\n if comparison_operator == sims4.math.Operator.GREATER_OR_EQUAL or comparison_operator == sims4.math.Operator.GREATER or comparison_operator == sims4.math.Operator.EQUAL:\n return self.skill_threshold.value\n return 0\n\n def __call__(self, curr_value):\n if not self.skill_threshold.compare(curr_value):\n return TestResult(False, 'Skill failed threshold test.')\n return TestResult.TRUE\n\n\nclass SkillInterval(HasTunableSingletonFactory, AutoFactoryInit):\n FACTORY_TUNABLES = {'skill_interval': TunableInterval(description='\\n The range (inclusive) a skill level must be in to pass this test.\\n ',\n tunable_type=int,\n default_lower=1,\n default_upper=10,\n minimum=0,\n maximum=(statistics.skill.MAX_SKILL_LEVEL))}\n __slots__ = ('skill_interval', )\n\n @property\n def skill_range_min(self):\n return self.skill_interval.lower_bound\n\n @property\n def skill_range_max(self):\n return self.skill_interval.upper_bound\n\n def __call__(self, curr_value):\n if curr_value < self.skill_interval.lower_bound or curr_value > self.skill_interval.upper_bound:\n return TestResult(False, 'skill level not in desired range.')\n return TestResult.TRUE\n\n\nclass SkillRangeTest(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n FACTORY_TUNABLES = {'subject':TunableEnumEntry(description='\\n The subject of this test.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'skill':Skill.TunablePackSafeReference(description='\\n The skill to test against. \\n \\n Should the Sim not have the specified skill, or should the skill not\\n be available because of pack restrictions, this Sim will be\\n considered at level 0.\\n '), \n 'skill_range':TunableVariant(description='\\n A skill range defined by either an interval or a threshold.\\n ',\n interval=SkillInterval.TunableFactory(),\n threshold=SkillThreshold.TunableFactory(),\n default='interval'), \n 'use_effective_skill_level':Tunable(description=\"\\n If checked, then instead of using the skill's actual level, the test\\n will use the skill's effective level for the purpose of satisfying\\n the specified criteria.\\n \",\n tunable_type=bool,\n needs_tuning=True,\n default=False)}\n __slots__ = ('subject', 'skill', 'skill_range', 'use_effective_skill_level')\n\n def get_expected_args(self):\n return {'test_targets': self.subject}\n\n @property\n def skill_range_min(self):\n return self.skill_range.skill_range_min\n\n @property\n def skill_range_max(self):\n max_possible_level = self.skill.get_max_skill_value()\n range_max = self.skill_range.skill_range_max\n if range_max > max_possible_level:\n logger.error(\"SkillRangeTest has a tuned skill range upper bound of {} that is higher than {}'s highest level of {}.\", (self.skill), range_max, max_possible_level, owner='rmccord')\n return range_max\n\n @cached_test\n def __call__(self, test_targets=()):\n for target in test_targets:\n if self.skill is None:\n skill_value = 0\n else:\n skill_or_skill_type = target.get_statistic((self.skill), add=False) or self.skill\n if self.use_effective_skill_level:\n if target.is_instanced():\n skill_value = target.get_sim_instance(allow_hidden_flags=ALL_HIDDEN_REASONS).get_effective_skill_level(skill_or_skill_type)\n else:\n skill_value = skill_or_skill_type.get_user_value()\n else:\n return self.skill_range(skill_value) or TestResult(False, 'skill level not in desired range.', tooltip=(self.tooltip))\n return TestResult.TRUE\n\n return TestResult(False, 'Sim does not have required skill.', tooltip=(self.tooltip))\n\n\nclass SkillDynamicallyReferencedTest(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n FACTORY_TUNABLES = {'subject':TunableEnumEntry(description='\\n The subject of this test.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'referenced_skill':TunableVariant(description='\\n Where to obtain the skill to test against. \\n \\n Should the Sim not have the specified skill, or should the skill not\\n be available because of pack restrictions, this Sim will be\\n considered at level 0.\\n ',\n from_career=_CareerSkillLootData.TunableFactory(),\n default='from_career'), \n 'skill_range':TunableVariant(description='\\n A skill range defined by either an interval or a threshold.\\n ',\n interval=SkillInterval.TunableFactory(),\n threshold=SkillThreshold.TunableFactory(),\n default='interval'), \n 'use_effective_skill_level':Tunable(description=\"\\n If checked, then instead of using the skill's actual level, the test\\n will use the skill's effective level for the purpose of satisfying\\n the specified criteria.\\n \",\n tunable_type=bool,\n needs_tuning=True,\n default=False)}\n __slots__ = ('subject', 'referenced_skill', 'skill_range', 'use_effective_skill_level')\n\n def get_expected_args(self):\n return {'test_targets': self.subject}\n\n @cached_test\n def __call__(self, test_targets=()):\n target = next(iter(test_targets), None)\n if target is None:\n return TestResult(False, 'Target is None.', tooltip=(self.tooltip))\n referenced_skill = self.referenced_skill(target)\n if referenced_skill is None:\n skill_value = 0\n else:\n skill_or_skill_type = target.get_statistic(referenced_skill, add=False) or referenced_skill\n if self.use_effective_skill_level:\n if target.is_instanced():\n skill_value = target.get_sim_instance(allow_hidden_flags=ALL_HIDDEN_REASONS).get_effective_skill_level(skill_or_skill_type)\n else:\n skill_value = skill_or_skill_type.get_user_value()\n else:\n return self.skill_range(skill_value) or TestResult(False, 'Skill {} level not in desired range.', referenced_skill, tooltip=(self.tooltip))\n return TestResult.TRUE\n\n\nclass SkillAllUnlockedMaxedOut(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n FACTORY_TUNABLES = {'subject':TunableEnumEntry(description='\\n The subject of this test.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'negate':Tunable(description='\\n If this is true then it will negate the result of the test type. That \\n means the test will return true if there is at least one unlocked skill \\n that is not maxed out and false if all unlocked skills are maxed out.\\n ',\n tunable_type=bool,\n default=False)}\n __slots__ = ('subject', 'negate')\n\n def get_expected_args(self):\n return {'test_targets': self.subject}\n\n def __call__(self, test_targets=()):\n for target in test_targets:\n skills = target.all_skills()\n for skill in skills:\n if skill.reached_max_level or self.negate:\n return TestResult.TRUE\n return TestResult(False, \"At least one unlocked skill isn't max level\", tooltip=(self.tooltip))\n\n if self.negate:\n return TestResult(False, 'All skills are max level', tooltip=(self.tooltip))\n return TestResult.TRUE\n\n\nclass SkillHasUnlockedAll(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n FACTORY_TUNABLES = {'subject':TunableEnumEntry(description='\\n The subject of this test.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'include_unlocked_by_max':Tunable(description=\"\\n If this is true, the test will also test skills which will become\\n available when an available skill reaches max level (this is specified\\n in 'Skill Unlocks On Max' in skill tuning.\\n \",\n tunable_type=bool,\n default=True), \n 'negate':Tunable(description='\\n If this is true then it will negate the result of the test type. That\\n means the test will return true if there is at least one skill which is\\n not unlocked and false if all available skills are unlocked.\\n ',\n tunable_type=bool,\n default=False)}\n __slots__ = ('subject', 'negate', 'include_unlocked_by_max')\n\n def get_expected_args(self):\n return {'test_targets': self.subject}\n\n def __call__(self, test_targets=()):\n for target in test_targets:\n target_skills = target.all_skills()\n available_skills = set()\n skill_manager = services.get_instance_manager(sims4.resources.Types.STATISTIC)\n for skill_cls in skill_manager.get_ordered_types(only_subclasses_of=Skill):\n if target.age not in skill_cls.ages or skill_cls.hidden:\n continue\n available_skills.add(skill_cls)\n if self.include_unlocked_by_max:\n for unlocked_by_max_skill in skill_cls.skill_unlocks_on_max:\n available_skills.add(unlocked_by_max_skill)\n\n for skill_cls in available_skills:\n if any((type(skill) is skill_cls for skill in target_skills)) or self.negate:\n return TestResult.TRUE\n return TestResult(False, \"At least one available skill isn't unlocked\", tooltip=(self.tooltip))\n\n if self.negate:\n return TestResult(False, 'All skills are unlocked', tooltip=(self.tooltip))\n return TestResult.TRUE\n\n\nclass SkillInUseTest(HasTunableSingletonFactory, AutoFactoryInit, event_testing.test_base.BaseTest):\n\n @TunableFactory.factory_option\n def participant_type_override(participant_type_enum, participant_type_default):\n return {'who': TunableEnumEntry(description='\\n Who or what to apply this test to.\\n ',\n tunable_type=participant_type_enum,\n default=participant_type_default)}\n\n FACTORY_TUNABLES = {'who':TunableEnumEntry(description='\\n Who or what to apply this test to.\\n ',\n tunable_type=ParticipantType,\n default=ParticipantType.Actor), \n 'skill':OptionalTunable(description='\\n Specify the skill to test against.\\n ',\n tunable=TunableReference(description='\\n \"The skill to test against.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.STATISTIC)),\n class_restrictions='Skill'),\n enabled_name='Specified_Skill',\n disabled_name='Any_Skill')}\n\n def __init__(self, *args, **kwargs):\n (super().__init__)(args, safe_to_skip=True, **kwargs)\n\n def get_expected_args(self):\n return {'test_targets': self.who}\n\n @cached_test\n def __call__(self, test_targets=()):\n for target in test_targets:\n if self.skill is None:\n if target.current_skill_guid != 0:\n return TestResult.TRUE\n elif target.current_skill_guid == self.skill.guid64:\n return TestResult.TRUE\n\n return TestResult(False, 'Failed SkillInUseTest', tooltip=(self.tooltip))","sub_path":"Scripts/simulation/statistics/skill_tests.py","file_name":"skill_tests.py","file_ext":"py","file_size_in_byte":18543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"404195597","text":"class Solution(object):\n def findMaxAverage(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: float\n \"\"\"\n if nums is None or len(nums) < k:\n return -sys.maxint\n\n s = sum(nums[: k])\n res = s\n end = k\n while end < len(nums):\n s += nums[end] - nums[end - k]\n res = max(res, s)\n end += 1\n return res / 1.0 / k\n","sub_path":"python/643. Maximum Average Subarray I.py","file_name":"643. Maximum Average Subarray I.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"556947235","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 8 13:34:57 2019\n\n@author: Vishnu.Kumar1\n\"\"\"\n\nimport cv2\nimport os\nimport uuid\n\npath = os.getcwd()\nfolder = path + '/DataSet/'\nfiles = os.listdir(folder)\n\nfor i in files:\n if 'Approved' in i:\n img = cv2.imread(folder + i)\n horizontal_img = cv2.flip(img, 1)\n cv2.imwrite(folder + 'Approved_' + uuid.uuid4().hex +'.jpg', horizontal_img)","sub_path":"image_classification/ImageInterpolation.py","file_name":"ImageInterpolation.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"161825121","text":"'''Python provides\nautomatic memory management through a reference-counting mechanism'''\n\n'''For the vast majority of\nyour classes, you won’t need to define a destructor.'''\n'''Python will\nimplicitly call a class’s destructor method __del__ just before an instance is removed\nupon its reference count reaching zero.'''\nclass SpecialFile:\n def __init__(self, file_name):\n self.__file = open(file_name, 'w')\n self.__file.write('***** Start Special File *****\\n\\n')\n def write(self, str):\n self.__file.write(str)\n def writelines(self, str_list):\n self.__file.writelines(str_list)\n def __del__(self):\n print(\"entered __del__\")\n self.close()\n def close(self):\n if self.__file:\n self.__file.write('\\n\\n***** End Special File *****')\n self.__file.close()\n self.__file = None\ndef test():\n f=SpecialFile(\"TestFile\")\n f.write(\"111111\\n\")\n f.close()\ntest()\n\n\nprint(\"\\n\"*3)\n'''When the function test exits, f’s reference count goes to zero and __del__ is called.\nThus, in the normal case close is called twice, which is why we want close to be able\nto handle this.'''\n'''As with the __init__ constructor, the __del__ destructor of a class’s parent class\nneeds to be called explicitly within a class’s own destructo'''\n'''Be careful when writing a\ndestructor. If it’s called when a program is shutting down, members of its global\nnamespace may already have been deleted. Any exception that occurs during its execution\nwill be ignored, other than a message being sent of the occurrence to\nsys.stderr. Also, there’s no guarantee that destructors will be called for all stillexisting\ninstances when the Python interpreter exits'''\n'''Python’s destructor\ninvocation is more deterministic. When the references to an object go away, it’s individually\nremoved. On the other hand, if you have structures with cyclical references\nthat have a __del__ method defined, they aren’t removed automatically. You have to\ngo in and do this yourself. This is the main reason why defining your own __del__\nmethod destructors isn’t recommended. Example:'''\nclass Circle:\n def __init__(self,name,parent):\n self.name=name\n self.parent=parent\n self.child=None\n if parent:\n parent.child=self\n def cleanup(self):#Breaks any cycles\n self.child=self.parent=None\n def __del__(self):\n print(\"__del__ called on\", self.name)\n \ndef test1():\n a=Circle(\"c\",None)\n b=Circle(\"b\",a)\n print(\"test1 exited\")\n #Because they still refer to each other, a and b aren’t removed when test1 exits\n #That is, each time test1 is called, it leaks two more objects.\n #The explicit call to the cleanup method is necessary to avoid this\n \ndef test2():\n c=Circle(\"c\",None)\n d=Circle(\"d\",c)\n d.cleanup()\n print(\"test2 exited\")\n #The cycle is broken in the cleanup method, not the destructor, and we only had to\n #break it in one place.\n\n \ntest1()\ntest1()\ntest1()\ntest2()\n\ndef test3(x):\n try:\n print(\"INICIO{0}\".format(\"-\"*50))\n c = Circle(\"c\", None) #__del__ called on reassignment...\n d = Circle(\"d\", c)\n if x == 1:\n print(\"leaving test3 via a return\")\n return\n if x == 2:\n print(\"leaving test3 via an exception\")\n raise RuntimeError\n print(\"leaving test3 off the end\")\n finally:\n d.cleanup()\n \n print(\"FIN{0}\".format(\"-\"*50))\n \ntest3(0)\ntest3(1)\ntest3(2)\n","sub_path":"PYTHON/PythonManning/PythonManningBook/classes_OOP/desctructors--memory_management.py","file_name":"desctructors--memory_management.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"9659830","text":"import os\n\nimport pymysql\n\nimport my_audio\n\n\nclass memory():\n def __init__(self, host, port, user, passwd, db):\n '''\n 初始化的方法,主要是存储连接数据库的参数\n :param host:\n :param port:\n :param user:\n :param passwd:\n :param db:\n '''\n self.host = host\n self.port = port\n self.user = user\n self.passwd = passwd\n self.db = db\n\n def addsong(self, path):\n '''\n 添加歌曲方法,将歌曲名和歌曲特征指纹存到数据库\n :param path: 歌曲路径\n :return:\n '''\n if type(path) != str:\n raise TypeError('path need string')\n basename = os.path.basename(path)\n try:\n conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,\n charset='utf8')\n except:\n print ('DataBase error')\n return None\n cur = conn.cursor()\n namecount = cur.execute(\"select * from audio.musicdata WHERE song_name = '%s'\" % basename)\n if namecount > 0:\n print ('the song has been record!')\n return None\n v = my_audio.voice()\n v.loaddata(path)\n v.fft()\n cur.execute(\"insert into audio.musicdata VALUES('%s','%s')\" % (basename, v.high_point.__str__()))\n conn.commit()\n cur.close()\n conn.close()\n\n\n def fp_compare(self, search_fp, match_fp):\n '''\n\n :param search_fp: 查询指纹\n :param match_fp: 库中指纹\n :return:最大相似值 float\n '''\n if len(search_fp) > len(match_fp):\n print('break')\n return 0\n max_similar = 0\n search_fp_len = len(search_fp)\n match_fp_len = len(match_fp)\n for i in range(match_fp_len - search_fp_len):\n temp = 0\n for j in range(search_fp_len):\n if match_fp[i + j] == search_fp[j]:\n temp += 1\n if temp > max_similar:\n max_similar = temp\n return max_similar\n\n def search(self, path):\n '''\n 搜索方法,输入为文件路径\n :param path: 待检索文件路径\n :return: 按照相似度排序后的列表,元素类型为tuple,二元组,歌曲名和相似匹配值\n '''\n #先计算出来我们的音频指纹\n v = my_audio.voice()\n v.loaddata(path)\n v.fft()\n #尝试连接数据库\n try:\n conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,\n charset='utf8')\n except:\n raise IOError('DataBase error')\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM audio.musicdata\")\n result = cur.fetchall()\n compare_res = []\n for i in result:\n compare_res.append((self.fp_compare(v.high_point[:-1], eval(i[1])), i[0]))\n compare_res.sort(reverse=True)\n cur.close()\n conn.close()\n print (compare_res)\n return compare_res\n\n def search_and_play(self, path):\n '''\n 搜索方法顺带了播放方法\n :param path:文件路径\n :return:\n '''\n v = my_audio.voice()\n v.loaddata(path)\n v.fft()\n try:\n conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,\n charset='utf8')\n except:\n print ('DataBase error')\n return None\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM audio.musicdata\")\n result = cur.fetchall()\n compare_res = []\n for i in result:\n compare_res.append((self.fp_compare(v.high_point[:-1], eval(i[1])), i[0]))\n compare_res.sort(reverse=True)\n cur.close()\n conn.close()\n print (compare_res)\n # v.play(compare_res[0][1])\n return compare_res\n def start(self):\n '''1\n 系统\n '''\n try:\n conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,\n charset='utf8')\n except:\n print ('DataBase error')\n return None\n cur = conn.cursor()\n cur.execute('truncate table musicdata')\n count=1\n v=my_audio.voice()\n # \n while (1):\n print(\"是否添加录音?:1、是;2、否\")\n i=input()\n if(i=='2'):\n break\n v.recode(RECORD_SECONDS=20,WAVE_OUTPUT_FILENAME=str(count)+\".wav\")\n self.addsong(str(count)+'.wav')\n count+=1\n count0=1\n while(1):\n i=input(\"输入1、开始测试;2、退出\")\n if(i=='2'):\n break\n print('正在录音...')\n v.recode(RECORD_SECONDS=20,WAVE_OUTPUT_FILENAME=str(count0)+\"t.wav\")\n print('正在分析...')\n self.search(str(count0)+\"t.wav\")\n\n \n \n\n\nif __name__ == '__main__':\n sss = memory('localhost', 3306, 'yz', '1', 'audio')\n # # sss.addsong('output.wav')\n # sss.addsong('稻香0.wav')\n # sss.addsong('去年夏天0.wav')\n # sss.addsong('断点0.wav')\n # sss.addsong('极乐净土0.wav')\n # sss.addsong('讲真的0.wav')\n # # sss.addsong('beiyiwangdeshiguang.wav')\n # # sss.addsong('xiaozezhenger.wav')\n # # sss.addsong('nverqing.wav')\n # # sss.addsong('the_mess.wav')\n # # sss.addsong('windmill.wav')\n # # sss.addsong('end_of_world.wav')\n # # sss.addsong('pianai.wav')\n\n # sss.search_and_play('稻香_1_1.wav')\n # sss.search_and_play('断点_1.wav')\n # sss.search_and_play('极乐净土_1.wav')\n # sss.search_and_play('讲真的_1.wav')\n # sss.search_and_play('去年夏天_1.wav')\n # sss.start();\n sss.addsong('1.wav')\n sss.search('1t.wav')\n\n","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"490199266","text":"from app import app\nfrom flask import request, jsonify, make_response\nimport os\nimport pandas as pd\nfrom pymongo import MongoClient\nfrom bson.json_util import dumps\nimport json\n\n\n@app.route('/')\ndef index():\n return \"Hello From Catalogue\"\n\n\ndef fetch_data(keyword):\n db_string = 'mongodb://csciDarshan:csciDarshan123@docdb-2020-03-24-17-12-34.cluster-chnyvyrv3c0z.us-east-1.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'\n client = MongoClient(db_string)\n db = client.gu_books\n doc = db.books.find_one({'title': keyword})\n if doc != None:\n print(doc)\n return doc\n\n\n@app.route('/catalogue')\ndef notes():\n keyword = request.args.get('keyword')\n if not os.path.isfile(\"catalogue.csv\"):\n df = pd.DataFrame(columns=[\"Keyword\", \"Author\"])\n df.to_csv(\"catalogue.csv\", index=False, header=True)\n df = pd.read_csv('catalogue.csv')\n df[\"Author\"] = df.Author.astype(str)\n row = df[df[\"Keyword\"] == keyword]\n if row.empty:\n doc = fetch_data(keyword)\n if doc == None:\n return jsonify(code=0, text='No Recored Found')\n df = df.append({\n 'Keyword': keyword,\n 'Author': doc['author']\n },\n ignore_index=True)\n df.to_csv(\"catalogue.csv\", index=False, header=True)\n return make_response(\n jsonify(keyword=doc[\"title\"], author=doc[\"author\"], code=1), 200)\n else:\n res = json.loads(row.to_json(orient='records')[1:-1])\n res[\"code\"] = 1\n return make_response(jsonify(res), 200)\n","sub_path":"catalogue/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"619047466","text":"# encoding:utf-8\nimport urllib\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport json\nimport pymysql.cursors\n\n'''链接数据库'''\nconfig = {\n \"host\":\"127.0.0.1\",\n \"port\":3306,\n \"user\":\"root\",\n \"password\":\"\",\n \"db\":\"test\",\n \"charset\":\"UTF8\",\n \"cursorclass\":pymysql.cursors.DictCursor\n}\nconnection = pymysql.connect(**config)\n\n\n\ndef reptile():\n userAgent = \"Mozilla/5.0 (Windows NT 10.0; WOW64)\"\n headers = {\"User-Agent\":userAgent}\n lists =[]\n for i in range(0,100,20):\n url = \"https://read.douban.com/ebooks/category/all/?cat=book&sort=top&start=\"+str(i)\n\n request = urllib.request.Request(url, headers = headers )\n response = urllib.request.urlopen(request)\n contents = response.read()\n data = contents.decode('UTF-8')\n transform = BeautifulSoup(data,\"html.parser\")\n items = transform.find_all(\"li\",{'class':'item'})\n lists +=items\n\n arr = []\n\n for item in lists:\n dict = {}\n title = item.find(\"div\", class_=\"title\").find(\"a\").get_text().rstrip('\\n').lstrip()\n author = item.find(\"span\", class_=\"labeled-text\").find(\"a\").get_text().rstrip('\\n').lstrip()\n sketch = item.find(\"div\",class_=\"article-desc-brief\").get_text().rstrip('\\n').lstrip()\n img = item.find(\"a\", class_=\"pic\").find(\"img\")['src']\n dict[\"author\"] = author\n dict[\"sketch\"] = sketch\n dict[\"title\"] = title\n dict[\"img\"] = img\n\n with connection.cursor() as cursor:\n sql = \"INSERT INTO `books` (`title`,`author`,`sketch`,`img`) VALUES (%s, %s, %s, %s)\"\n cursor.execute(sql, (title,author,sketch,img))\n\n connection.commit()\n\n connection.close()\n print('数据已经写入')\n str_json = json.dumps(arr, ensure_ascii=False)\n with open('books.json','w+', encoding='utf8') as f:\n f.write(str_json)\n\nif __name__ == \"__main__\":\n reptile()\n","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"74899844","text":"#!/bin/env python\n\n#function:\n# a demo to show how to use the converted model genereated by caffe2fluid\n# \n#notes:\n# only support imagenet data\n\nimport os\nimport sys\nimport inspect\nimport numpy as np\nimport paddle.v2 as paddle\nimport paddle.v2.fluid as fluid\n\n\ndef load_data(imgfile, shape):\n h, w = shape[1:]\n from PIL import Image\n im = Image.open(imgfile)\n\n # The storage order of the loaded image is W(widht),\n # H(height), C(channel). PaddlePaddle requires\n # the CHW order, so transpose them.\n im = im.resize((w, h), Image.ANTIALIAS)\n im = np.array(im).astype(np.float32)\n im = im.transpose((2, 0, 1)) # CHW\n im = im[(2, 1, 0), :, :] # BGR\n\n # The mean to be subtracted from each image.\n # By default, the per-channel ImageNet mean.\n mean = np.array([104., 117., 124.], dtype=np.float32)\n mean = mean.reshape([3, 1, 1])\n im = im - mean\n return im.reshape([1] + shape)\n\n\ndef build_model(net_file, net_name):\n print('build model with net_file[%s] and net_name[%s]' %\n (net_file, net_name))\n\n net_path = os.path.dirname(net_file)\n module_name = os.path.basename(net_file).rstrip('.py')\n if net_path not in sys.path:\n sys.path.insert(0, net_path)\n\n try:\n m = __import__(module_name, fromlist=[net_name])\n MyNet = getattr(m, net_name)\n except Exception as e:\n print('failed to load module[%s]' % (module_name))\n print(e)\n return None\n\n input_name = 'data'\n input_shape = MyNet.input_shapes()[input_name]\n images = fluid.layers.data(name='image', shape=input_shape, dtype='float32')\n #label = fluid.layers.data(name='label', shape=[1], dtype='int64')\n\n net = MyNet({input_name: images})\n input_shape = MyNet.input_shapes()[input_name]\n return net, input_shape\n\n\ndef dump_results(results, names, root):\n if os.path.exists(root) is False:\n os.path.mkdir(root)\n\n for i in range(len(names)):\n n = names[i]\n res = results[i]\n filename = os.path.join(root, n)\n np.save(filename + '.npy', res)\n\n\ndef infer(net_file, net_name, model_file, imgfile, debug=False):\n \"\"\" do inference using a model which consist 'xxx.py' and 'xxx.npy'\n \"\"\"\n #1, build model\n net, input_shape = build_model(net_file, net_name)\n prediction = net.get_output()\n\n #2, load weights for this model\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n startup_program = fluid.default_startup_program()\n exe.run(startup_program)\n\n if model_file.find('.npy') > 0:\n net.load(data_path=model_file, exe=exe, place=place)\n else:\n net.load(data_path=model_file, exe=exe)\n\n #3, test this model\n test_program = fluid.default_main_program().clone()\n\n fetch_list_var = []\n fetch_list_name = []\n if debug is False:\n fetch_list_var.append(prediction)\n else:\n for k, v in net.layers.items():\n fetch_list_var.append(v)\n fetch_list_name.append(k)\n\n np_images = load_data(imgfile, input_shape)\n results = exe.run(program=test_program,\n feed={'image': np_images},\n fetch_list=fetch_list_var)\n\n if debug is True:\n dump_path = 'results.layers'\n dump_results(results, fetch_list_name, dump_path)\n print('all results dumped to [%s]' % (dump_path))\n else:\n result = results[0]\n print('predicted class:', np.argmax(result))\n\n\nif __name__ == \"__main__\":\n \"\"\" maybe more convenient to use 'run.sh' to call this tool\n \"\"\"\n net_file = 'models/resnet50/resnet50.py'\n weight_file = 'models/resnet50/resnet50.npy'\n imgfile = 'data/65.jpeg'\n net_name = 'ResNet50'\n\n argc = len(sys.argv)\n if argc == 5:\n net_file = sys.argv[1]\n weight_file = sys.argv[2]\n imgfile = sys.argv[3]\n net_name = sys.argv[4]\n elif argc > 1:\n print('usage:')\n print('\\tpython %s [net_file] [weight_file] [imgfile] [net_name]' %\n (sys.argv[0]))\n print('\\teg:python %s %s %s %s %s' % (sys.argv[0], net_file,\n weight_file, imgfile, net_name))\n sys.exit(1)\n\n infer(net_file, net_name, weight_file, imgfile)\n","sub_path":"fluid/image_classification/caffe2fluid/examples/imagenet/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"219340371","text":"'''\n• Complexity:\n ○ O(k) - k being the length of the repearting part\n• Topics:\n ○ math - yes, pure math\n ○ hashmap\n因为分母不变,那么当第一次出现重复的remainder时,意味着从decimal后第一位到当前这一位重复了。\n'''\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n if numerator == 0: return '0'\n \n result = []\n if numerator < 0 and denominator > 0 or numerator >= 0 and denominator < 0:\n result.append('-')\n \n numerator, denominator = abs(numerator), abs(denominator)\n \n result.append(str(numerator // denominator))\n \n remainder = numerator % denominator\n \n if remainder == 0: return ''.join(result)\n result.append('.')\n \n\n # Looking for a repeated remainder. If a remainder shows up a second time,\n # then the previous part repeat.\n d = {}\n while remainder != 0:\n if remainder in d:\n result.insert(d[remainder], '(')\n result.append(')')\n return ''.join(result)\n \n d[remainder] = len(result)\n \n remainder *= 10\n result += str(remainder // denominator)\n remainder = remainder % denominator\n \n return ''.join(result)","sub_path":"leetcode/166_fraction_to_recurring_decimal.py","file_name":"166_fraction_to_recurring_decimal.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"255380332","text":"from inputControls import JoyControls\nfrom screenCollector import FrameGrabber\nimport os\nimport numpy as np\nimport cv2\nlocation = \"images/\"\nif os.path.exists(location) == False:\n os.mkdir(location)\n\nd = FrameGrabber()\ncontrols = JoyControls()\n\ni = 0\n#start = time.time()\ntry:\n while cv2.waitKey(7) % 0x100 != 10:\n i+=1\n frame = np.array(d.get_processed_frame())\n controllerOutput = controls.getInputs()\n\n #frameReshape = frame.reshape(-1)\n\n if controllerOutput.shape[0] == 22:\n #arr = frameReshape.append(controllerOutput)\n\n #print (arr.shape, frame.shape, controllerOutput.shape)\n #(91583,) (131, 233, 3) (14,)\n #Frame shape: (131, 233, 3) = 91569\n print (controllerOutput)\n np.savez(location+\"frame-{}.npz\".format(i), a = frame, b = controllerOutput)\n\n #print (controllerOutput)\n #print (frame.shape, controllerOutput.shape, data.shape)\n #exit()\nexcept KeyboardInterrupt:\n print(\"Press Ctrl-C to terminate while statement\")\n del d\n del controls\n","sub_path":"tests/getTrainingDataV0.1.py","file_name":"getTrainingDataV0.1.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"169366863","text":"##################################\n##### Tests for Otter Export #####\n##################################\n\n# NOTES:\n# - tests do not check for PDF equality but rather have exporter save the TeX file as well\n# and check that the TeX is correct (assuming that TeX conversion works correctly) and checks\n# that PDF file exists\n\nimport os\nimport unittest\nimport subprocess\nimport json\nimport re\nimport contextlib\nimport nbconvert\nimport filecmp\nimport nbformat\n\nfrom io import StringIO\nfrom unittest import mock\nfrom subprocess import Popen, PIPE\nfrom glob import glob\nfrom textwrap import dedent\n\n# from otter.argparser import get_parser\nfrom otter.export import export_notebook\nfrom otter.export import main as export\nfrom otter.export.exporters.base_exporter import BaseExporter\nfrom otter.runner import run_otter\n\nfrom . import TestCase\n\n# parser = get_parser()\n\nTEST_FILES_PATH = \"test/test-export/\"\n\nclass TestExport(TestCase):\n\n def test_success_HTML(self):\n \"\"\"\n Tests a successful export with filtering and no pagebreaks\n \"\"\"\n test_file = \"successful-html-test\"\n grade_command = [\"export\", \"--filtering\", \"-s\", \"-e\", \"latex\",\n TEST_FILES_PATH + test_file + \".ipynb\"\n ]\n # args = parser.parse_args(grade_command)\n # args.func = export\n # args.func(args)\n run_otter(grade_command)\n\n # check existence of pdf and tex\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".pdf\"))\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".tex\"))\n\n # cleanup\n cleanup_command = [\"rm\", TEST_FILES_PATH + test_file + \".pdf\", TEST_FILES_PATH + test_file + \".tex\"]\n cleanup = subprocess.run(cleanup_command, stdout=PIPE, stderr=PIPE)\n self.assertEqual(cleanup.returncode, 0,\"Error in cleanup: \" + str(cleanup.stderr))\n \n def test_success_pagebreak(self):\n \"\"\"\n Tests a successful filter with pagebreaks\n \"\"\"\n test_file = \"success-pagebreak-test\"\n grade_command = [\"export\", \"--filtering\", \"-e\", \"latex\",\n \"--pagebreaks\", \"-s\",\n TEST_FILES_PATH + test_file + \".ipynb\"\n ]\n # args = parser.parse_args(grade_command)\n # args.func = export\n # args.func(args)\n run_otter(grade_command)\n\n # check existence of pdf and tex\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".pdf\"))\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".tex\"))\n\n # cleanup\n cleanup_command = [\"rm\", TEST_FILES_PATH + test_file + \".pdf\", TEST_FILES_PATH + test_file + \".tex\"]\n cleanup = subprocess.run(cleanup_command, stdout=PIPE, stderr=PIPE)\n self.assertEqual(cleanup.returncode, 0,\"Error in cleanup: \" + str(cleanup.stderr))\n\n def test_no_close(self):\n \"\"\"\n Tests a filtered export without a closing comment\n \"\"\"\n test_file = \"no-close-tag-test\"\n grade_command = [\"export\", \"--filtering\", \"-e\", \"latex\",\n \"--pagebreaks\", \"-s\",\n TEST_FILES_PATH + test_file + \".ipynb\"\n ]\n # args = parser.parse_args(grade_command)\n # args.func = export\n # args.func(args)\n run_otter(grade_command)\n\n # check existence of pdf and tex\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".pdf\"))\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file + \".tex\"))\n\n # cleanup\n\n cleanup_command = [\"rm\", TEST_FILES_PATH + test_file + \".pdf\", TEST_FILES_PATH + test_file + \".tex\"]\n cleanup = subprocess.run(cleanup_command, stdout=PIPE, stderr=PIPE)\n self.assertEqual(cleanup.returncode, 0,\"Error in cleanup:\" + str(cleanup.stderr))\n\n def test_load_notebook(self):\n \"\"\"\n Tests a successful load_notebook\n \"\"\"\n test_file = \"successful-html-test\"\n node = BaseExporter.load_notebook(TEST_FILES_PATH + test_file + \".ipynb\", filtering=True)\n\n nbformat.write(node, TEST_FILES_PATH + test_file)\n\n # check existence of file\n self.assertTrue(os.path.isfile(TEST_FILES_PATH + test_file))\n self.assertTrue(filecmp.cmp(TEST_FILES_PATH + test_file, TEST_FILES_PATH + \"correct/\" + test_file))\n \n # cleanup\n cleanup_command = [\"rm\", TEST_FILES_PATH + test_file]\n cleanup = subprocess.run(cleanup_command, stdout=PIPE, stderr=PIPE)\n self.assertEqual(cleanup.returncode, 0,\"Error in cleanup: \" + str(cleanup.stderr))\n","sub_path":"test/test_export.py","file_name":"test_export.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560851514","text":"#!/usr/bin/env python3\n\"\"\" Variational auto-encoder \"\"\"\nimport tensorflow.keras as keras\n\n\ndef sampling(inputs):\n \"\"\" Variational auto-encoder \"\"\"\n z_mean, z_log_var = inputs\n batch = keras.backend.shape(z_mean)[0]\n dim = keras.backend.int_shape(z_mean)[1]\n epsilon = keras.backend.random_normal(shape=(batch, dim))\n return z_mean + keras.backend.exp(0.5 * z_log_var) * epsilon\n\n\ndef autoencoder(input_dims, hidden_layers, latent_dims):\n \"\"\" Variational auto-encoder \"\"\"\n encoder_inp = keras.Input(shape=(input_dims,))\n\n x = keras.layers.Dense(hidden_layers[0], activation='relu')(encoder_inp)\n for i in range(1, len(hidden_layers)):\n x = keras.layers.Dense(hidden_layers[i], activation='relu')(x)\n\n z_mean = keras.layers.Dense(latent_dims)(x)\n z_log_var = keras.layers.Dense(latent_dims)(x)\n z = keras.layers.Lambda(sampling,\n output_shape=(latent_dims,))([z_mean, z_log_var])\n\n decoder_inp = keras.Input(shape=(latent_dims,))\n x = keras.layers.Dense(hidden_layers[-1],\n activation='relu')(decoder_inp)\n for i in range(len(hidden_layers) - 2, -1, -1):\n x = keras.layers.Dense(hidden_layers[i], activation='relu')(x)\n decoder_out = keras.layers.Dense(input_dims, activation='sigmoid')(x)\n\n encoder = keras.models.Model(inputs=encoder_inp,\n outputs=[z, z_mean, z_log_var])\n decoder = keras.models.Model(inputs=decoder_inp, outputs=decoder_out)\n\n comp = encoder(encoder_inp)[0]\n outputs = decoder(comp)\n vae = keras.models.Model(encoder_inp, outputs)\n\n def loss(y, y_pred):\n \"\"\" Variational auto-encoder \"\"\"\n recons_loss = keras.backend.binary_crossentropy(y, y_pred)\n recons_loss = keras.backend.sum(recons_loss, axis=1)\n kl_loss = (1 + z_log_var - keras.backend.square(z_mean) -\n keras.backend.exp(z_log_var))\n kl_loss = keras.backend.sum(kl_loss, axis=1)\n kl_loss *= -0.5\n return recons_loss + kl_loss\n\n vae.compile(optimizer='adam', loss=loss)\n return encoder, decoder, vae\n","sub_path":"unsupervised_learning/0x04-autoencoders/3-variational.py","file_name":"3-variational.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"651607664","text":"__author__ = 'redragonx/daemoniclegend'\n\n# from plane_controller.plane import PlaneObject\nimport re\n\n\nclass DataVerify():\n velocity_map = {}\n\n def verify_data(self, list_in):\n data_list = list_in\n idPattern = re.compile(\"[0-9]{4}\")\n latPattern = re.compile(\"[01][0][0-8][0-9]{7}|[0-1][0][9][0]{7}\")\n longPattern = re.compile(\"[0-1][0-1][0-7][0-9]{6}|[0-1][0-1][8][0]{5}\")\n altitudePattern = re.compile(\"^[0-9]{6}\")\n vectorPattern = re.compile(\"^[0-9]{8}\")\n\n if idPattern.match(data_list[0]):\n if latPattern.match(data_list[1]):\n if longPattern.match(data_list[2]):\n if altitudePattern.match(data_list[3]):\n if vectorPattern.match(data_list[4]):\n if vectorPattern.match(data_list[5]):\n if vectorPattern.match(data_list[6]):\n # here is where the plane object itself would be returned after creation\n return 'True'\n else:\n return 'False'\n else:\n return 'False'\n else:\n return 'False'\n else:\n return 'False'\n else:\n return 'False'\n else:\n return 'False'\n else:\n return 'False'\n\n def within_distance(self, plane1):\n raise Exception(\"Not Yet Implemented.\")\n # pass\n def dispatch_data_valid(self, plane):\n return\n\n def dispatch_data_not_vaild(self, alert_type):\n return\n\n def __init__(self):\n pass\n","sub_path":"plane_controller/data_verification.py","file_name":"data_verification.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"196651537","text":"from eulerlib import primes\n\ndef compute():\n\tend_num = 2000000\n\tnums = [True] * end_num\n\tnums[:2] = [False] * 2\n\tfor i in range(end_num):\n\t\tif nums[i]:\n\t\t\tfor j in range(i*i, end_num, i):\n\t\t\t\tnums[j] = False\n\n\ttemp = [i for i, x in enumerate(nums) if x]\n\treturn(sum(temp))\n\n\n# Call the sieve of Eratosthenes and sum the primes found.\ndef compute2():\n\tans = sum(primes(1999999))\n\treturn str(ans)\n\n\nif __name__ == '__main__':\n\tprint(compute())\n\tprint(compute2())","sub_path":"E10.py","file_name":"E10.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"291662096","text":"from pymongo import MongoClient\nfrom M2_VTTV.VTTV import text_voice as v\n\nclass Database_Insert:\n\n def Insert():\n \n client = MongoClient('localhost',27017)\n mydb = client[\"Jarvis\"]\n mycol = mydb[\"details\"]\n\n d = {}\n with open(\"doc.txt\") as f:\n while True: \n a = f.readline()\n if not a:\n break\n else:\n a = a.split(':-')\n try:\n key = a[0]\n val = a[1].strip('\\n')\n d.update({key:val})\n except:\n pass\n #print(d)\n x = mycol.insert_one(d)\n \nclass Database_Retrieve:\n\n def retrieve():\n client = MongoClient('localhost',27017)\n mydb = client[\"Jarvis\"]\n mycol = mydb[\"details\"]\n \n print(\"Enter 1 for Single keyword\\nEnter 2 for Multiple Keyword\")\n choice=int(input(\"Enter your choice:\"))\n try:\n if(choice==1):\n v.speak('here are the keywords')\n print('1.Name\\n2.Gender\\n3.Age\\n4.Diagnosis\\n5.Date')\n query=input('Enter the keyword:').title()\n value=input('Enter the corrosponding value:').title()\n myquery={query:{\"$regex\":value}}\n \n elif(choice==2):\n list=[]\n n=int(input('Enter no of keywords:'))\n for _ in range(n):\n dict={}\n key=input(\"Enter key:\").title()\n value=input(\"Enter value:\").title()\n dict.update({key:value}) \n list.append(dict) \n myquery={\"$and\":list}\n \n except :\n print(\"Wrong choice\")\n\n else:\n for x in mycol.find(myquery):\n print(x)\n \nclass Database_update:\n \n def update(object):\n client = MongoClient('localhost',27017)\n mydb = client[\"Jarvis\"]\n mycol = mydb[\"details\"]\n object.retrieve()\n try:\n n=int(input('Enter the no of fields to be changed:'))\n dict={}\n for _ in range(n):\n key=input('Enter the field to be changed:').title()\n value=input('Enter the new value of the field:').title() \n dict.update({key:value})\n \n time_value=input('Enter the time field:')\n mycol.update_one({'Time':time_value},{\"$set\":dict})\n \n except Exception as e:\n print(e)\n \n else:\n print('Record updated successfully')\n \n \n\nclass Database_delete:\n \n def delete():\n client = MongoClient('localhost',27017)\n mydb = client[\"Jarvis\"]\n mycol = mydb[\"details\"]\n\n try:\n time_value=input('Enter the time field of the record to be deleted:')\n mycol.delete_one({'Time':time_value})\n \n except Exception as e:\n print(e)\n\n else:\n print ('Deletion successful') \n \n\n \n \n ","sub_path":"Jarvis/M4_Database/dbOperations.py","file_name":"dbOperations.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141537661","text":"import unittest\nimport re\nimport json\nfrom wgups.schedule import schedule_delivery\n\n\ndef strip_color_codes(string: str) -> str:\n return re.sub(r'\\[\\d+?m', '', string)\n\n\nclass TestSchedule(unittest.TestCase):\n def test_schedule(self):\n packages, trucks = schedule_delivery()\n trucks.sort(key=lambda t: t.number)\n truck1, truck2 = trucks\n self.assertEqual(round(truck1.miles_traveled, 1), 45.2)\n self.assertEqual(round(truck2.miles_traveled, 1), 71.3)\n\n for time in [n * 60 for n in range(8, 13)]:\n with open(f'test/packages/{time}.json', 'r') as f:\n data = json.loads(f.read())\n for (_, pkg) in packages:\n self.assertEqual(\n data[str(pkg.id)], strip_color_codes(pkg.info(time)))\n\n for (_, pkg) in packages:\n if pkg._Package__required_truck is not None:\n self.assertEqual(pkg._Package__required_truck,\n pkg._Package__delivered_by)\n self.assertLessEqual(pkg.delivered_at, pkg.deadline)\n self.assertLessEqual(\n pkg._Package__available_at, pkg._Package__loaded_at)\n","sub_path":"test/test_schedule.py","file_name":"test_schedule.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"487038790","text":"#!/usr/bin/python3\nimport sys\nimport re\n\nMIN_N = 3\nMAX_N = 1000\n\nline = sys.stdin.readline()\nassert re.match('^[ACGTOV]*\\n$', line)\nline = line.strip()\nsz = len(line)\nassert MIN_N <= sz <= MAX_N\n\nassert not sys.stdin.read()\nsys.exit(42)\n","sub_path":"2022/problems/medcovid/input_validators/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"75062119","text":"import sys\r\nimport os\r\nimport django\r\nimport asyncio\r\nfrom pyppeteer import launch\r\nimport re\r\nfrom pyppeteer.errors import NetworkError\r\n\r\nPAGE_LIMIT_REGEX = r'Page (\\d+) of (\\d+)'\r\nCOURSE_SECTION_REGEX = r'([a-zA-Z0-9]+-[a-zA-Z0-9]+)-([a-zA-Z0-9]+)'\r\n\r\nBASE_WEBADVISOR_URL = 'https://advisor.uog.edu/WebAdvisor/WebAdvisor'\r\nSECTION_DETAIL_URL_REGEX = r\"'(.*?)'\"\r\n\r\nSTATUS_PATTERN_ID = '#LIST_VAR1_'\r\nSECTION_TITLE_ID = '#SEC_SHORT_TITLE_'\r\nLOCATION_ID = '#SEC_LOCATION_'\r\nFACULTY_ID = '#SEC_FACULTY_INFO_'\r\nCAPACITY_ID = '#LIST_VAR5_'\r\nCREDITS_ID = '#SEC_MIN_CRED_'\r\nACADEMIC_LEVEL_ID = '#SEC_ACAD_LEVEL_'\r\n\r\nDESCRIPTION_ID = '#VAR3'\r\nMEETING_INFO_ID = '#LIST_VAR12_1'\r\nREQUISITE_COURSES_ID = '#VAR_LIST1_1'\r\nPHONE_ID = '#LIST_VAR8_1'\r\nEXTENSION_ID = '#LIST_VAR9_1'\r\nEMAIL_ID = '#LIST_VAR10_1'\r\nINSTRUCTIONAL_METHOD_ID = '#LIST_VAR11_1'\r\n\r\nPATTERN_IDS = [STATUS_PATTERN_ID, SECTION_TITLE_ID, LOCATION_ID, \r\n FACULTY_ID, CAPACITY_ID, CREDITS_ID, ACADEMIC_LEVEL_ID]\r\n \r\nDETAIL_PATTERNS = [DESCRIPTION_ID, MEETING_INFO_ID, REQUISITE_COURSES_ID, PHONE_ID, EXTENSION_ID,\r\n EMAIL_ID, INSTRUCTIONAL_METHOD_ID]\r\n\r\nos.environ['DJANGO_SETTINGS_MODULE'] = 'webadvisorapi.settings'\r\ndjango.setup()\r\n\r\nfrom src import models\r\n\r\nclass CourseScraper:\r\n def __init__(self, term):\r\n self.term = term\r\n self.primary_cookies = None\r\n \r\n async def queryCourses(self):\r\n #set headless=True when in production\r\n self.browser = await launch(headless=True, args=['--disable-dev-shm-usage']) #Chromium will run out of memory when doing memory-intensive functions, so disable the limit\r\n #Incognito might not be needed when disabling browser cache\r\n self.context = await self.browser.createIncognitoBrowserContext() \r\n self.page = await self.context.newPage()\r\n await self.page.setCacheEnabled(False)\r\n \r\n await self.page.goto(\r\n 'https://advisor.uog.edu/WebAdvisor/WebAdvisor?CONSTITUENCY=WBST&type=P&pid=ST-WESTS12A&TOKENIDX=', \r\n waitUntil=['networkidle0', 'domcontentloaded', 'load']\r\n )\r\n\r\n async def isTermAvailable():\r\n options = await self.page.querySelectorAll('#VAR1 option')\r\n options = [await (await option.getProperty('value')).jsonValue() for option in options]\r\n \r\n return False if self.term not in options else True\r\n \r\n if not await isTermAvailable():\r\n await self.page.close()\r\n await self.browser.close()\r\n return\r\n \r\n await self.page.select('#VAR1', self.term)\r\n await self.page.select('#VAR7', '05:00')\r\n await self.page.select('#VAR8', '22:00')\r\n await asyncio.gather(\r\n self.page.waitForNavigation(waituntil=['networkidle0', 'domcontentloaded', 'load']),\r\n self.page.click('.shortButton')\r\n )\r\n try:\r\n num_pages = await (await (await self.page.querySelector('table[summary=\"Paged Table Navigation Area\"]')).getProperty('innerText')).jsonValue()\r\n except AttributeError:\r\n await self.page.close()\r\n await self.browser.close()\r\n return\r\n pages_begin, pages_end = map(lambda x: int(x), re.match(PAGE_LIMIT_REGEX, num_pages.strip()).groups())\r\n self.termObj, isTermCreated = models.Term.objects.get_or_create(term_code=self.term.replace(\"/\", \"\"))\r\n \r\n while pages_begin <= pages_end:\r\n #IMPORTANT: The first cookies we see when entering the list of courses must be used, and all other cookies discarded.\r\n #If the cookies we store is different than those of the first, then we cannot access the next pointer to the next \r\n #page of courses. \r\n print(\"Reading page \" + str(pages_begin))\r\n if not self.primary_cookies:\r\n self.primary_cookies = await self.page.cookies()\r\n await self.parsePage()\r\n \r\n await asyncio.gather(\r\n self.page.waitForNavigation(waituntil=['domcontentloaded', 'networkidle0', 'load']),\r\n self.page.click('input[value=\"NEXT\"]')\r\n )\r\n \r\n pages_begin += 1\r\n \r\n await self.clearAndSetCookies()\r\n await self.page.close()\r\n await self.browser.close()\r\n \r\n async def parsePage(self):\r\n for i in range(1, 21):\r\n print(\"Reading course \" + str(i))\r\n #Same here, delete all existing cookies and set it to our first ones\r\n await self.clearAndSetCookies()\r\n \r\n course_status = await self.page.querySelector(STATUS_PATTERN_ID + str(i))\r\n if course_status == None:\r\n return\r\n else:\r\n status, section_name_and_title, location, faculty, \\\r\n max_capacity, credits_, academic_level = [await self.querySelectorHelper(i, pattern) for pattern in PATTERN_IDS]\r\n \r\n section_name_and_title = section_name_and_title.split(' ')\r\n name, title = section_name_and_title[0], ' '.join(section_name_and_title[2:])\r\n #Get the onclick attribute of an element; there seems to be no other way to get this attribute with only pyppeteer\r\n detail_url_segment = await self.page.evaluate('''() => document.querySelector('%s').getAttribute('onclick')''' % (SECTION_TITLE_ID + str(i)))\r\n detail_url_segment = re.findall(SECTION_DETAIL_URL_REGEX, detail_url_segment)[0]\r\n\r\n #some courses have a null max_capacity value, so catch the error\r\n try:\r\n available, capacity = map(lambda c: int(c), max_capacity.strip().split('/'))\r\n except ValueError:\r\n available, capacity = 0, 0\r\n course, section = re.match(COURSE_SECTION_REGEX, name).groups()\r\n credits_ = int(float(credits_))\r\n\r\n description, meeting_info, requisite_courses, phone, extension, \\\r\n email, inst_method = await self.detail_parser(detail_url_segment) \r\n\r\n courseObj, isCourseCreated = models.Course.objects.update_or_create(\r\n course_code=course,\r\n defaults={\r\n 'term': self.termObj,\r\n 'title': title,\r\n 'credit_points': credits_,\r\n 'academic_level': academic_level\r\n }\r\n )\r\n\r\n sectionObj, isSectionCreated = models.Section.objects.update_or_create(\r\n section_number=name,\r\n defaults={\r\n 'parent_course': courseObj,\r\n 'description': description,\r\n 'phone': phone,\r\n 'extension': extension,\r\n 'email': email,\r\n 'requisite_courses': requisite_courses,\r\n 'instructional_method': inst_method,\r\n 'location': location,\r\n 'meeting_info': meeting_info,\r\n 'faculty': faculty,\r\n 'available': available,\r\n 'max_capacity': capacity,\r\n 'status': status\r\n }\r\n )\r\n\r\n async def detail_parser(self, url_suffix):\r\n detailPage = await self.context.newPage()\r\n await detailPage.goto(BASE_WEBADVISOR_URL + url_suffix, waitUntil=['networkidle0', 'domcontentloaded', 'load'])\r\n response = [await self.detailquerySelectorHelper(detailPage, pattern) for pattern in DETAIL_PATTERNS]\r\n await detailPage.close()\r\n return response\r\n \r\n async def querySelectorHelper(self, idx, idPattern):\r\n #do not await selector, seems to have issues\r\n element = await self.page.querySelector(idPattern + str(idx))\r\n innerText = await (await element.getProperty('textContent')).jsonValue()\r\n return innerText\r\n\r\n async def detailquerySelectorHelper(self, context, idPattern):\r\n return await (await (await context.querySelector(idPattern)).getProperty('innerText')).jsonValue()\r\n\r\n async def clearAndSetCookies(self):\r\n for cookie in await self.page.cookies():\r\n await self.page.deleteCookie(cookie)\r\n for p in self.primary_cookies:\r\n await self.page.setCookie(p)\r\n\r\ndef create_term_codes():\r\n import datetime\r\n suffixes = ['SP', 'XA', 'XB', 'XC', 'X1', 'FA', 'FI']\r\n current_year = str(datetime.date.today().year)[2:]\r\n return map(lambda prefix: '/'.join([current_year, prefix]), suffixes)\r\n\r\ndef main():\r\n for term in create_term_codes():\r\n print(\"Starting with term \" + term)\r\n course_scraper = CourseScraper(term)\r\n asyncio.get_event_loop().run_until_complete(course_scraper.queryCourses())","sub_path":"webadvisorapi/src/scripts/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":8987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"228222009","text":"# run with python plotScript_andys_gen_dist_of_varied_selectivities_normalized.py; open graphs/andys_dist_of_varied_selectivities_normalized.png \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pylab\nimport sys\n\ncsv_files = [\"1first_hotel_1_3.csv\", \\\n \"queue_eddy_hotel_0_1.csv\", \\\n \"random_hotel_0_1.csv\", \\\n \"0first_hotel_0_1.csv\"]\n\nnum_tasks_array = []\nfor i in range(0,4):\n\tnum_tasks_array.append(list(np.loadtxt(csv_files[i], delimiter=',')))\n\nsns.set(style=\"white\", palette=\"muted\", color_codes=False)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nsns.despine(left=True)\n\n# the histogram of the data\nalg_list = [\"Under $80?' first\", \"dynamic filter\", \"random\", \"'Gym?' first\"]\nlinestyles=[\"-\",\"-\",\"-\",\"-\"]\nmarkers=[\"^\",\"o\",\"v\",\"s\"]\nfor i in range(len(num_tasks_array)):\n\tsns.distplot(num_tasks_array[i], hist=False, kde_kws={\"shade\": False, \"lw\":1, \"ls\": linestyles[i], \"marker\": markers[i], \"markersize\":7, \"markevery\":4}, ax=ax, label=alg_list[i])\n\nax.set_xlabel('Number of Tasks')\nax.set_ylabel('Frequency')\nax.set_title('Distribution of Varied Selectivities Normalized')\n#ax.set_xlim(100, 320)\nax.grid(True)\n\n#plt.tight_layout()\n#plt.show()\nplt.savefig('graphs/andys_dist_of_varied_selectivities_normalized.png')\n","sub_path":"active/dynamicfilterapp/simulation_files/plotScript_andys_gen_dist_of_varied_selectivities_normalized.py","file_name":"plotScript_andys_gen_dist_of_varied_selectivities_normalized.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"468498234","text":"# User Input\n# ===\n\n# # Exercise 1\n\n# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.\n# Extras:\n# - Add on to the previous program by asking the user for another number and printing out that many copies of the previous message.\n# - Print out that many copies of the previous message on separate lines. (Hint: the string \"\\n\" a.k.a newline, is the same as pressing the ENTER button)\nfrom datetime import datetime\n \ndef enter_and_check_is_number():\n while True:\n try:\n variable = int(input())\n if variable <= 0:\n raise Exception()\n else:\n return variable\n except:\n print(\"Your input must be a positive numbers. Please enter another: \", end='')\n continue\n\n\ndef year_when_100_year_olds():\n name = input('Enter your name: ')\n\n print('Enter your age: ', end='')\n age = enter_and_check_is_number()\n\n year100yearolds = datetime.today().year + 100 - age\n result = 'Hi Hau. You will turn 100 years old in ' + str(year100yearolds)\n print(result)\n \n print('Enter number of repetition: ', end='')\n number = enter_and_check_is_number()\n\n multiple_result = (result + '\\n')*number\n print(multiple_result, end='')\n return result\n\n# # Exercise 2\n\n# Create a program that asks the user to enter their name, their date of birth (mm/dd/yyyy), their gender, their address. After done input all of the above program, allow user to input the following command and print out the corresponding information.\n# ```\n# $ What would you like to know?\n# Available commands are: `name`, `age`, `dob`, `gender`, `address`, `all`\n# $ Your name is ...\n# $ Your age is ...\n# $ Your date of birth is ...\n# $ Your gender is ...\n# $ Your address is ...\n# If user ask for all information, print all the above information at once, in each separated line.\n# ```\n\ndef get_and_show_info():\n name = input('Enter your name: ')\n print('Enter your age: ', end='')\n age = enter_and_check_is_number()\n while True:\n try:\n dob = input('Enter your date of birth(mm/dd/yyyy): ')\n dob_datetime = datetime.strptime(dob, '%m/%d/%Y').date()\n if dob_datetime > datetime.today().date():\n raise\n break\n except:\n print(\"Your input must be in the format `mm/dd/yyyy` and not after today. Please enter another.\")\n continue\n gender = input('Enter your gender: ')\n address = input('Enter your address: ')\n command = input('What would you like to know?\\nAvailable commands are: `name`, `age`, `dob`, `gender`, `address`, `all`.\\nEnter your command: ')\n while True:\n if command == 'name':\n print('Your name is', name)\n elif command == 'age':\n print('Your age is', age)\n elif command == 'dob':\n print('Your date of birth is', dob)\n elif command == 'gender':\n print('Your gender is', gender)\n elif command == 'address':\n print('Your address is', address)\n elif command == 'all':\n print('Your name is', name, '\\nYour age is', age, '\\nYour date of birth is', dob, '\\nYour gender is', gender, '\\nYour address is', address)\n else:\n command = input('This command is not available. Please enter another: ')\n continue\n break\n\nif __name__ == \"__main__\":\n # Ask user for input or to just execute the chosen function\n print('The program have 2 feature:')\n print('1 - Telling you the year that you will turn 100 years old.')\n print('2 - Telling you about your infomation')\n # result = func(a, b, c=c, d=d)\n while True:\n selection = input('Choose your selection (1 or 2): ')\n if selection == '1':\n year_when_100_year_olds()\n elif selection == '2':\n get_and_show_info()\n else:\n print(\"Your input must be 1 or 2. Please enter another\")\n continue\n is_continue = input('Do you want to use another feature?(Enter `y` to continue): ')\n if is_continue == 'y':\n continue\n else:\n break","sub_path":"python-exercises/user_input.py","file_name":"user_input.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"11009589","text":"\"\"\"\ntest_rat_command.py\n\nTests for the rat_command module\n\nCopyright (c) 2018 The Fuel Rats Mischief,\nAll rights reserved.\n\nLicensed under the BSD 3-Clause License.\n\nSee LICENSE.md\n\nThis module is built on top of the Pydle system.\n\n\"\"\"\n\nimport unittest\nfrom unittest import mock\n\nimport pydle\nfrom aiounittest import async_test\n\nfrom Modules.rat_command import Commands, CommandNotFoundException, NameCollisionException, InvalidCommandException, \\\n CommandException\nfrom tests.mock_bot import MockBot\n\n\nclass RatCommandTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # set the bot to something silly, at least its not None. (this won't cut it for proper commands but works here.)\n # as we are not creating commands that do stuff with bot. duh. these are tests after all.\n Commands.bot = MockBot()\n super().setUpClass()\n\n def setUp(self):\n # this way command registration between individual tests don't interfere and cause false positives/negatives.\n Commands._flush()\n super().setUp()\n\n def test_get_unknown_command(self):\n \"\"\"\n Verifies that Commands.get_command() returns None if a command is not found\n :return:\n \"\"\"\n unknown_names = [\"foo\", \"bar\", \"meatbag\", \"limpet\"]\n\n @Commands.command(\"fuel\")\n async def potato(*args):\n return True\n\n for name in unknown_names:\n with self.subTest(name=name):\n self.assertIsNone(Commands.get_command(name))\n with self.subTest(name=\"fuel\"):\n self.assertIsNotNone(Commands.get_command(\"fuel\"))\n\n @async_test\n async def test_command_decorator_single(self):\n \"\"\"\n Tests if the `Commands.command` decorator can handle string registrations\n \"\"\"\n # bunch of commands to test\n alias = ['potato', 'cannon', 'Fodder', \"fireball\"]\n commands = [f\"{Commands.prefix}{name}\" for name in alias]\n\n for command in commands:\n with self.subTest(command=command):\n @Commands.command(command.strip(Commands.prefix))\n async def potato(bot: pydle.Client, channel: str, sender: str):\n # print(f\"bot={bot}\\tchannel={channel}\\tsender={sender}\")\n return bot, channel, sender\n self.assertIsNotNone(Commands.get_command(command.strip(Commands.prefix)))\n\n def test_command_decorator_list(self):\n aliases = ['potato', 'cannon', 'Fodder', 'fireball']\n trigger_alias = [f\"{Commands.prefix}{name}\" for name in aliases]\n\n # register the command\n @Commands.command(*aliases)\n async def potato(bot: pydle.Client, channel: str, sender: str):\n return bot, channel, sender\n\n for name in trigger_alias:\n with self.subTest(name=name):\n self.assertIsNotNone(Commands.get_command(name))\n\n @async_test\n async def test_invalid_command(self):\n \"\"\"\n Ensures the proper exception is raised when a command is not found.\n :return:\n \"\"\"\n with self.assertRaises(CommandNotFoundException):\n await Commands.trigger(message=\"!nope\", sender=\"unit_test\", channel=\"foo\")\n\n def test_double_command_registration(self):\n \"\"\"\n test verifying it is not possible to register a command twice.\n this prevents odities where commands are bound but the bind is overwritten....\n which leaves the original bound command not called during a trigger event.\n :return:\n \"\"\"\n alias = ['potato', 'cannon', 'Fodder', 'fireball'] # TODO: move these common lists to setup_class\n # lets define them initially.\n for name in alias:\n @Commands.command(name)\n async def foo():\n pass\n\n with self.subTest(name=name):\n with self.assertRaises(NameCollisionException):\n @Commands.command(name)\n async def bar():\n pass\n\n @async_test\n async def test_call_command(self):\n \"\"\"\n Verifiy that found commands can be invoked via Commands.Trigger()\n :return:\n \"\"\"\n aliases = ['potato', 'cannon', 'Fodder', 'fireball']\n trigger_alias = [f\"{Commands.prefix}{name}\" for name in aliases]\n input_sender = \"unit_test[BOT]\"\n input_channel = \"#unit_testing\"\n\n @Commands.command(*aliases)\n async def potato(bot, trigger):\n # print(f\"bot={bot}\\tchannel={channel}\\tsender={sender}\")\n return bot, trigger.channel, trigger.nickname\n\n for command in trigger_alias:\n with self.subTest(command=command):\n out_bot, out_channel, out_sender = await Commands.trigger(message=command, sender=input_sender,\n channel=input_channel)\n self.assertEqual(input_sender, out_sender)\n self.assertEqual(input_channel, out_channel)\n self.assertIsNotNone(out_bot)\n\n @async_test\n async def test_ignored_message(self):\n \"\"\"\n Tests if Commands.trigger correctly ignores messages not containing the prefix.\n :return:\n \"\"\"\n words = ['potato', 'cannon', 'Fodder', 'fireball', \"what is going on here!\", \".!potato\"]\n for word in words:\n with self.subTest(word=word):\n self.assertIsNone(await Commands.trigger(message=word, sender=\"unit_test[BOT]\", channel=\"unit_tests\"))\n\n @async_test\n async def test_null_message(self):\n \"\"\"\n Verifies the correct exception is raised when a null message is sent\n :return:\n \"\"\"\n words = [\"\", None, '']\n for word in words:\n with self.subTest(word=word):\n with self.assertRaises(InvalidCommandException):\n await Commands.trigger(message=word, sender=\"unit_test[BOT]\", channel=\"unit_tests\")\n\n @mock.patch(\"Modules.rat_command.Commands.bot\")\n @async_test\n async def test_null_bot(self, mock_bot):\n \"\"\"\n Verifies the correct exception is raised when someone forgets to set Commands.bot <.<\n Overkill?\n :return:\n \"\"\"\n # this is the default value, which should be overwritten during MechaClient init...\n with self.assertRaises(CommandException):\n await Commands.trigger(message=\"!message\", sender=\"unit_test[BOT]\", channel=\"unit_tests\")\n\n def test_register_non_callable(self):\n \"\"\"\n Verifies the correct exception is raised when someone tries to register something that is not callable.\n not sure how they would do this outside of calling the private directly or why...\n :return:\n \"\"\"\n foo = [12, None, \"str\"]\n for item in foo:\n with self.subTest(item=item):\n self.assertFalse(Commands._register(item, ['foo']))\n","sub_path":"tests/test_rat_command.py","file_name":"test_rat_command.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"200101501","text":"primes = (2,3,5,7,11,13)\n\ndef get_factor(n):\n\tlimit = int(n**0.5 + 1)\n\tfor p in primes:\n\t\tif n % p == 0:\n\t\t\treturn p\n\n\treturn None # maybe there is a factor... but it's too big for us\n\nfrom itertools import product, islice\ndef jamcoins(size):\n\tfor digits in product('01', repeat=size-2):\n\t\tcoin_str = '1%s1' % (''.join(digits))\n\t\tdivisors = []\n\t\tfor base in range(2, 11):\n\t\t\tcoin = int(coin_str, base)\n\t\t\tfactor = get_factor(coin)\n\t\t\tif factor:\n\t\t\t\tdivisors.append(factor)\n\t\t\telse:\n\t\t\t\tbreak\n\t\tif len(divisors) == 9:\n\t\t\tyield coin_str, divisors\n\n\nif __name__ == '__main__':\n\tn = int(input(\"N = \"))\n\tj = int(input(\"J = \"))\n\tpostfix = input(\"postfix = \")\n\twith open(\"/tmp/jamcoins%s\"%postfix, \"w\") as out:\n\t\tprint(\"Case #1:\", file=out)\n\t\tfor jamcoin, divisors in islice(jamcoins(n), j):\n\t\t\tprint(jamcoin, *divisors, file=out)\n\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_sebsheep_ex03_jamcoin.py","file_name":"16_0_3_sebsheep_ex03_jamcoin.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"213950382","text":"\nimport requests\nimport click\nimport configparser\nimport sys\nimport time\n\nconfig = configparser.ConfigParser()\nconfig.read(\"auth.cfg\")\ntoken = config.get('github', 'token')\n\n\n# Authentication\nsession = requests.Session()\nsession.get('http://httpbin.org/cookies/set/mipyt/best')\nsession.headers = {'Authorization': 'token ' + token, 'User-Agent': 'Python'}\n\n@click.group()\ndef main():\n print('Hello there, I am a little app.')\n pass\n\n@main.command()\n@click.option('-r', '--repos', default='pyvec/naucse.python.cz', help='Repository of which you want to check star status.')\n@click.option('-v', '--verbose', is_flag=True, help='Will print verbose messages. Can get very annoying.')\n@click.option('-a','--show_all', is_flag=True, help='Will show first 100 (or less) repositories of the selected user. You can select the user with --username option.')\n@click.option('-u', '--username', default = 'pyvec', help='The username of the user you want to see the repositories of.')\ndef show(repos, verbose, show_all, username):\n '''Simple program, that will show me if I have already given a star to the selected repository.'''\n \n # ------Star show------\n # Check that the repository exists\n if repos != 'pyvec/naucse.python.cz':\n url_check = requests.get('https://github.com/'+repos)\n if url_check.status_code == 404:\n if verbose == False:\n print('Your selected repository does not exists.','\\n','The app will close in 3 seconds.')\n time.sleep(3)\n sys.exit(1)\n else:\n print('The repository you want to access does not exist, maybe you should go and check if you have the right name.','\\n','And BTW the app will close in 3 seconds.')\n time.sleep(1)\n print('2 seconds')\n time.sleep(1)\n print('1 second')\n time.sleep(1)\n print('BOOOOM')\n sys.exit(1)\n # Check that the username exists \n if show_all == True and username != 'pyvec':\n url_check = requests.get('https://api.github.com/users/'+username+'/repos')\n if url_check.status_code == 404:\n if verbose == False:\n print('User with your selected username does not exists.','\\n','The app will close in 3 seconds.')\n time.sleep(3)\n sys.exit(1)\n else: \n print('You selected a non-existent user, please, go and check the name.','\\n','And BTW the app will close in 3 seconds.')\n time.sleep(1)\n print('2 seconds')\n time.sleep(1)\n print('1 second')\n time.sleep(1)\n print('BOOOOM')\n sys.exit(1)\n # Checking the star status\n response = session.get('https://api.github.com/user')\n if show_all == False:\n if response.status_code == 200 and verbose == False:\n print('Authentication successfull.')\n if response.status_code == 200 and verbose == True:\n print('Authentication successfull, wonderfully done, my dear! Let the stars shine!')\n status = session.get('https://api.github.com/user/starred/'+repos)\n if status.status_code == 204 and verbose == False:\n print('The repository has a star: * ', repos)\n if status.status_code == 204 and verbose == True:\n print('This wonderful repository has a star already, my dear! You see?: * ', repos)\n if status.status_code == 404 and verbose == False:\n print('The repository does not have a star: ', repos)\n if status.status_code == 404 and verbose == True:\n print('What a shame! This wonderful repository does not have a star: ', repos)\n # Showing top 100 (or less) repositories\n if show_all == True:\n public_repos = session.get('https://api.github.com/users/'+username)\n public_repos_num = public_repos.json()['public_repos']\n print('Number of public repos: ', public_repos_num)\n # Showing top 100\n if public_repos_num >= 100:\n show = session.get('https://api.github.com/users/'+username+'/repos?page=2&per_page=100')\n if verbose == False:\n print('The following is the top 100 of all public repositories:')\n if verbose == True:\n print('The following is the loooong list of top 100 of all public repositories of the selected user {} :'.format(username))\n print('Funny how many ofs can I put in one sentence.')\n diction = show.json()\n number = 1\n for d in diction:\n for keys, values in d.items():\n if keys == 'name':\n print('{}. {}'.format(number, values))\n number = number + 1\n # Showing less then 100\n else: \n show = session.get('https://api.github.com/users/'+username+'/repos')\n if verbose == False:\n print('The following is a list of all {} public repositories:'.format(public_repos_num))\n if verbose == True:\n print('The following is a list of all {} public repositories:'.format(public_repos_num))\n print('Only {} repositories... hopefully there will be more the next time you ask :P.'.format(public_repos_num))\n diction = show.json()\n number = 1\n for d in diction:\n for keys, values in d.items():\n if keys == 'name':\n print('{}. {}'.format(number, values))\n number = number + 1\n\n@main.command()\n@click.option('-r', '--repos', default='pyvec/naucse.python.cz', help='Repository of which you want to have star added.')\ndef add(repos):\n '''Simple program, that will give a star to the selected repository.'''\n \n # ------Star add------\n # Check that the repository exists\n if repos != 'pyvec/naucse.python.cz':\n url_check = requests.get('https://github.com/'+repos)\n if url_check.status_code == 404:\n print('Your selected repository does not exists.','\\n','The app will close in 3 seconds.')\n time.sleep(3)\n sys.exit(1)\n # Checking the the star status and adding a star if applicable\n response = session.get('https://api.github.com/user')\n if response.status_code == 200:\n print('Authentication successfull')\n status = session.get('https://api.github.com/user/starred/'+repos)\n if status.status_code == 204:\n print('There is a star already.')\n if status.status_code == 404:\n session.put('https://api.github.com/user/starred/'+repos)\n check = session.get('https://api.github.com/user/starred/'+repos)\n if check.status_code == 204:\n print('The star was added to the repository.')\n \n\n@main.command()\n@click.option('-r','--repos', default='pyvec/naucse.python.cz', help='Repository of which you want to have the star removed.')\ndef remove(repos):\n ''' A simple program, that will delete a star from the selected repository.'''\n # ------Star delete------\n # Check that the repository exists\n if repos != 'pyvec/naucse.python.cz':\n url_check = requests.get('https://github.com/'+repos)\n if url_check.status_code == 404:\n print('Your selected repository does not exists.','\\n','The app will close in 3 seconds.')\n time.sleep(3)\n sys.exit(1)\n \n # Checking the star status and deleting a star if applicable\n status = session.get('https://api.github.com/user/starred/'+repos)\n if status.status_code == 204:\n session.delete('https://api.github.com/user/starred/'+repos)\n check = session.get('https://api.github.com/user/starred/'+repos)\n if check.status_code == 404:\n print('The star was deleted.') \n if status.status_code == 404:\n print('There is no star in the repository.') \n \n\n \nmain()\n","sub_path":"1.WEB_CLICK/starrer.py","file_name":"starrer.py","file_ext":"py","file_size_in_byte":8000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"270735071","text":"import tweepy\r\nfrom API.ApiManager import ApiManager\r\n\r\n\r\nclass TweetSearch:\r\n\r\n def __init__(self, search_term, language, locale, max_id):\r\n self._api_manager = ApiManager()\r\n self._search_term = search_term\r\n self._language = language\r\n self._locale = locale\r\n self._max_id = max_id\r\n self._cursor = self._init_cursor()\r\n\r\n def _init_cursor(self):\r\n return tweepy.Cursor(self._api_manager.get_active_api().search,\r\n q=self._search_term,\r\n count=100,\r\n result_type='recent',\r\n include_entities=True,\r\n lang=self._language,\r\n locale=self._locale,\r\n max_id=self._max_id).pages()\r\n\r\n def get_next_page(self):\r\n try:\r\n return self._cursor.next()\r\n except tweepy.TweepError:\r\n print('TweepError')\r\n print('Get a other active Api')\r\n self._cursor = self._init_cursor()\r\n return self._cursor.next()\r\n except StopIteration:\r\n print('No next item found.')\r\n return None\r\n\r\n","sub_path":"Python/API/TweetSearch.py","file_name":"TweetSearch.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"394132124","text":"# L_01_EASY\r\n\r\n# Задача-1: поработайте с переменными, создайте несколько,\r\n# выведите на экран, запросите от пользователя и сохраните в переменную, выведите на экран\r\n\r\na_first = 12\r\na_second = \"Hello\"\r\nprint(a_first, a_second)\r\na_check = input(\"Введите переменную для вывода ее на экран: \")\r\nprint(\"Ваша переменная: \", a_check)\r\n\r\n# Задача-2: Запросите от пользователя число, сохраните в переменную,\r\n# прибавьте к числу 2 и выведите результат на экран.\r\n# Если возникла ошибка, прочитайте ее, вспомните урок и постарайтесь устранить ошибку.\r\n\r\nb_first = input(\"Введите переменную: \")\r\ntotal = int(b_first) + 2\r\nprint(\"Ваш ответ: \", total)\r\n\r\n# Задача-3: Запросите у пользователя его возраст.\r\n# Если ему есть 18 лет, выведите: \"Доступ разрешен\",\r\n# иначе \"Извините, пользование данным ресурсом только с 18 лет\"\r\n\r\n\r\nold = int(input(\"Введите ваш возраст: \"))\r\nif old == 18:\r\n print(\"Ты на грани , но проходишь\")\r\nelif old >= 18:\r\n print(\"Доступ разрешен\")\r\nelse:\r\n print(\"Извините, пользование данным ресурсом только с 18 лет\")\r\n\r\n\r\n# L_01_EASY - complete\r\n\r\n\r\n# L_01_NORMAL\r\n\r\n# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10.\r\n# После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран.\r\n# Например, пользователь вводит число 123, вы сообщаете ему, что число не верное,\r\n# и сообщаете об диапазоне допустимых. И просите ввести заного.\r\n# Допустим пользователь ввел 2, оно подходит, возводим в степень 2, и выводим 4\r\n\r\n\r\nnumber = int(input(\"Введите число: \"))\r\ni = 0\r\nwhile i < 9258:\r\n if number > 0 and number <= 10:\r\n total = number ** 2\r\n print(total)\r\n i = 9259\r\n else:\r\n print(\"Введите корректное число в диапозоне(0-10)\")\r\n number = int(input(\"Введите число: \"))\r\n i += 1\r\n\r\n# Задача-2: Исходные значения двух переменных запросить у пользователя.\r\n# Поменять значения переменных местами. Вывести новые значения на экран.\r\n# Решите задачу, используя только две переменные.\r\n# Подсказки:\r\n# * постарайтесь сделать решение через действия над числами;\r\n\r\nfirst = int(input(\"Введите первую переменную: \"))\r\nsecond = int(input(\"Введите вторую переменную: \"))\r\nfirst = first + second\r\nsecond = first - second\r\nfirst = first - second\r\nprint(\"Первая переменная стала: \", first)\r\nprint(\"Вторая переменная стала: \", second)\r\n\r\n# L_01_NORMAL - complete\r\n\r\n\r\n# L_01_HARD\r\n\r\n# Создайте программу медицинская анкета, где вы запросите у пользователя такие данные, как имя, фамилию, возраст, и вес.\r\n# И выведите результат согласно которому пациент в хорошем состоянии, если ему до 30 лет и вес от 50 и до 120 кг,\r\n# Пациенту требуется начать вести правильный образ жизни, если ему более 30 и вес меньше 50 или больше 120 кг\r\n# Пациенту требуется врачебный осмотр, если ему более 40 и вес менее 50 или больше 120 кг.\r\n# Все остальные варианты вы можете обработать на ваш вкус и полет фантазии =)\r\n# Формула не отражает реальной действительности и здесь используется только ради примера.\r\n\r\n# Пример: Вася Пупкин, 29 год, вес 90 - хорошее состояние\r\n# Пример: Вася Пупкин, 31 год, вес 121 - следует заняться собой\r\n# Пример: Вася Пупкин, 31 год, вес 49 - следует заняться собой\r\n# Пример: Вася Пупкин, 41 год, вес 121 - следует обратится к врачу!\r\n# Пример: Вася Пупкин, 41 год, вес 49 - следует обратится к врачу!\r\n\r\n# Узнаем основные значения\r\n\r\nname = input(\"Введите ваше имя: \")\r\nsurname = input(\"Введите вашу фамилию: \")\r\nold = int(input(\"Введите ваш возраст:\"))\r\nweight = int(input(\"Введите ваш вес: \"))\r\n\r\n# Узнаем первое состояние(Хорошее состояние)\r\n\r\nif old >= 20 and old <= 30 and weight >= 50 and weight < 120:\r\n print(\"{} {}, {} лет, вес {} - хорошее состояние\".format(name, surname, old, weight))\r\n answer = input(\"Хочешь узнать как получить бесплатных оладьев?(y/n)\")\r\n if answer == \"y\":\r\n print(\"Подойди к маме и попроси сделать)\")\r\n elif answer == \"n\":\r\n print(\"Ну как хочешь((\")\r\n\r\n # Узнаем второе состояние(Следует заняться собой)\r\n\r\nelif old >= 31 and old <= 39 and weight < 50 and weight > 120:\r\n print(\"{} {}, {} лет, вес {} - следует заняться собой\".format(name, surname, old, weight))\r\n answer = input(\"Хочешь получить рецепт диеты?(y/n)\")\r\n if answer == \"y\":\r\n print(\"1)Кушай во время; /n2)Сладкое ешь только с утра , не много;/n3)Занимайся спортом \")\r\n elif answer == \"n\":\r\n print(\"Ну как хочешь((\")\r\n\r\n # Узнаем третье состояние(Следует обратиться к врачу)\r\n\r\nelif old >= 40 or old <= 60 and weight < 50 or weight > 120:\r\n print(\"{} {}, {} лет, ве�� {} - следует обратиться к врачу\".format(name, surname, old, weight))\r\n answer = input(\"Хочешь вызвать скорую?(y/n)\")\r\n if answer == \"y\":\r\n print(\"Набери в телефоне номер 03\")\r\n elif answer == \"n\":\r\n print(\"Ну как хочешь((\")\r\n\r\n# L_01_HARD - complete","sub_path":"L_1_EAST,NORMAL,HARD.py","file_name":"L_1_EAST,NORMAL,HARD.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"146289825","text":"# coding: utf-8\n# from selenium import webdriver\n# browser = webdriver.Chrome()\n#\n# browser.get('http://money.finance.sina.com.cn/quotes_service/view/qihuohangqing.html')\n# title = browser.title\n# print(browser.title)\n# # print(browser.page_source)\n# browser.close()\n\n\n#!/usr/bin/env python\n# coding:utf-8\n\nimport os\nimport base64\nimport sys\n\n\ndef baseurl(argv):\n \"\"\"\n thunder://... -> http://...\n \"\"\"\n if len(argv) == 2:\n url = argv[1]\n else:\n print(\"Input Error!\\n usage: %s 'url'\" % (argv[0]))\n sys.exit(1)\n if url.startswith('thunder://'):\n url = url[10:]+'\\n'\n url = base64.decodestring(url)\n url = url[2:-2]\n elif url.startswith('flashget://'):\n url = url[11:url.find('&')]+'\\n'\n url = base64.decodestring(url)\n url = url[10:-10]\n elif url.startswith('qqdl://'):\n url = url[7:]+'\\n'\n url = base64.decodestring(url)\n else:\n print('\\n It is not a available url!!')\n return url\n\n# www.iplaypy.com\n\n\ndef test():\n # url = 'thunder://QUFodHRwOi8veDEwMi51dW5pYW8uY29tOjEwMS9kYXRhL2Jicy51dW5pYW8uY29tJUU2JTgyJUEwJUU2JTgyJUEwJUU5JUI4JTlGLyVFNyU5QiU5NyVFNiVBMiVBNiVFNyVBOSVCQSVFOSU5NyVCNC0lRTYlODIlQTAlRTYlODIlQTAlRTklQjglOUYlRTQlQjglQUQlRTYlOTYlODclRTUlQUQlOTclRTUlQjklOTUucm12Ylpa'\n p = baseurl(sys.argv)\n print(p)\n\nif __name__ == '__main__':\n test()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"216553601","text":"import flask\nfrom flask import jsonify, make_response, request\n\nimport ConfigReader\nfrom data.__all_models import User\nfrom . import DataBase\n\nblueprint = flask.Blueprint(\n 'db_api',\n __name__,\n\n)\n\n\n@blueprint.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\n@blueprint.route(ConfigReader.read_check_email_api_url(), methods=['GET'])\ndef check_email_api():\n if request.json and 'email' in request.json:\n email = request.json['email']\n db_session = DataBase.create_session()\n user = db_session.query(User).filter(User.email == email).first()\n return jsonify({\n 'contains_value': True if user else False\n })\n else:\n return make_response(jsonify({'error': \"No email in the request\"}), 400)\n\n\n@blueprint.route(ConfigReader.read_check_id_api_url(), methods=['GET'])\ndef check_id_api():\n if request.json and 'id' in request.json:\n user_id = request.json['id']\n db_session = DataBase.create_session()\n user = db_session.query(User).filter(User.id == user_id).first()\n return jsonify({\n 'contains_value': True if user else False\n })\n else:\n return make_response(jsonify({'error': \"No id in the request\"}), 400)\n","sub_path":"data/DataBaseServer/db_api.py","file_name":"db_api.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"503338127","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\nfrom torch.utils.data.dataset import Dataset\nimport numpy as np\nimport imageio\nimport glob\nimport matplotlib.pyplot as plt\nfrom scipy import misc\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\n\nclass melanomaData(Dataset):\n\n\tdef __init__(self, data_path, channels, rows, cols, transforms=None, is_train=True):\n\t\t\n\t\tself.transforms = transforms\n\t\tself.data_path = data_path\n\t\tself.rows = rows\n\t\tself.cols = cols\n\t\tself.channels = channels\n\n\t\timg_folder = sorted(glob.glob(self.data_path + 'image/*'))\n\t\tlabel_folder = sorted(glob.glob(self.data_path + 'label/*'))\n\n\t\timgs_all = np.ndarray((len(img_folder), rows, cols, channels), dtype=np.uint8)\n\t\tlabels_all = np.ndarray((len(label_folder), rows, cols, 1), dtype=np.uint8)\n\t\t\n\t\tfor i, img in enumerate(img_folder):\n\t\t\timg = Image.open(img)\n\t\t\tlabel = Image.open(label_folder[i])\n\t\t\timgs_all[i] = img\n\t\t\tlabels_all[i, ..., 0] = label\n\n\t\tlabels_all[labels_all > 128] = 255\n\t\tlabels_all[labels_all <= 128] = 0\n\n\t\tnp.random.seed(231)\n\n\t\tval_idx = np.random.choice(imgs_all.shape[0], int(0.2 * imgs_all.shape[0]), replace=False)\n\t\ttrain_idx = np.array([idx for idx in range(imgs_all.shape[0]) if not idx in val_idx ])\n\t\t\n\t\tself.mean = np.mean(imgs_all[train_idx], (0,1,2))\n\t\tself.std = np.std(imgs_all[train_idx], (0,1,2))\n\n\t\tif is_train:\n\t\t\tself.imgs = imgs_all[train_idx]\n\t\t\tself.labels = labels_all[train_idx]\n\t\telse:\n\t\t\tself.imgs = imgs_all[val_idx]\n\t\t\tself.labels = labels_all[val_idx]\n\n\t\tself.N = self.imgs.shape[0]\n\n\t\tself.labels = self.labels / 255\n\t\tself.labels = np.transpose(self.labels, (0,3,1,2))\n\t\t# self.imgs = np.transpose(self.imgs, (0,3,1,2))\n\t\tprint(self.imgs.shape)\n\n\tdef __getitem__(self, index):\n\t\t\n\t\timg = self.imgs[index]\n\t\tprint(img.shape)\n\t\tlabel = self.labels[index, 0, ...]\n\t\tif self.transforms is not None:\n\t\t\timg = self.transforms(img)\n\n\t\treturn(img, label)\n\n\tdef __len__(self):\n\t\treturn self.N\n\n\nif __name__ == '__main__':\n # Define transforms (1)\n transformations = transforms.Compose([transforms.Scale(32), transforms.ToTensor()])\n # Call the dataset\n dset_train = melanomaData('/home/ahmed/github/melanoma.1.0/dataset/2016data/train/', 3, 256, 256, transformations, is_train=True)\n # dset_val = melanomaData('/home/ahmed/github/melanoma.1.0/dataset/2016data/train/', 3, 256, 256, transformations, is_train=False)\n # train_dloader = DataLoader(dset_train, batch_size=4, shuffle=True, num_workers=4)\n # val_dloader = DataLoader(dset_val, batch_size=1, shuffle=False, num_workers=4)\n # for img, label in train_dloader:\n # \tprint(img.size())\n # for img, label in val_dloader:\n # \tprint(img.size())\n img, label = dset_train.__getitem__(2)\n print(img.shape)\n print(img.min())\n print(label.max())\n print(label.min())\n # print(np.unique(label))\n # print(dset.tr_mean)\n\t","sub_path":"pytorch.py","file_name":"pytorch.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"486645376","text":"from django.contrib.auth.base_user import AbstractBaseUser\nfrom django.db import models\nfrom django.db.models import Manager\n\n\nclass BaseModel(models.Model):\n created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='등록일')\n last_modified = models.DateTimeField(auto_now=True, editable=False, verbose_name='수정일')\n\n objects = Manager()\n\n class Meta:\n abstract = True\n\n\nclass BaseUserModel(BaseModel, AbstractBaseUser):\n class Meta:\n abstract = True\n","sub_path":"src/lib/django/db/models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"519486376","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom setuptools import setup, find_packages\nfrom adles import __version__, __email__, __author__, __url__, __license__\n\n\nwith open('requirements.txt') as f:\n required = f.read().splitlines()\n\nsetup(\n name='ADLES',\n version=__version__,\n packages=find_packages(),\n include_package_data=True,\n install_requires=required,\n entry_points={\n 'console_scripts': [\n 'adles = adles.scripts.adles_main:main',\n 'clone-vms = adles.scripts.clone_vms:main',\n 'cleanup-vms = adles.scripts.cleanup_vms:main',\n 'vm-power = adles.scripts.vm_power:main',\n 'vsphere-info = adles.scripts.vsphere_info:main'\n ]\n },\n scripts=['adles/scripts/adles_main.py', 'adles/scripts/clone_vms.py',\n 'adles/scripts/cleanup_vms.py', 'adles/scripts/vm_power.py',\n 'adles/scripts/vsphere_info.py'],\n author=__author__,\n author_email=__email__,\n description='Automated Deployment of Lab Environments System',\n url=__url__,\n license=__license__,\n keywords=\"adles virtualization automation vmware vsphere yaml \"\n \"cybersecurity education uidaho radicl environments\",\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: Apache Software License',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Science/Research',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Education',\n 'Topic :: Education :: Testing',\n 'Topic :: Security',\n 'Topic :: Software Development'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"323760736","text":"from itertools import combinations\nn,m = map(int,input().split()) #n:회원수 m:치킨 종류의 수\nchicken=[]\nfor i in range(n):\n chicken.append(list(map(int,input().split())))\n# print(chicken[0][3])\nans=0\n# m 종류의 치킨 중에서 3가지 선택\ncc=[]\nfor i in range(m):\n cc.append(i)\ntemp = list(combinations(cc,3))\n# print(temp[0][0]) temp[i][0] temp[i][1] temp[i][2]\n\nans=[]\nfor i in range(len(temp)):\n bigyo = []\n temp2=0\n bigyo.append(temp[i][0])\n bigyo.append(temp[i][1])\n bigyo.append(temp[i][2])\n for j in range(n):\n temp2+=max(chicken[j][bigyo[0]],chicken[j][bigyo[1]],chicken[j][bigyo[2]])\n ans.append(temp2)\nprint(max(ans))","sub_path":"Algorithm/for_study/TH 16439.py","file_name":"TH 16439.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"164178407","text":"import random\r\n\r\n\r\n\r\ndef mklist(): \r\n list =[]\r\n for i in range(0,23):\r\n list.append(random.randint(1,366))\r\n return list\r\n\r\n\r\ndef test():\r\n answer = []\r\n list = mklist()\r\n for i in range(0,23):\r\n tmp = i\r\n for j in range(0,23):\r\n if (j == i):\r\n pass\r\n else:\r\n if (list[tmp] == list[j]):\r\n return 1\r\n return 0\r\n\r\n\r\ndef answerlist(count):\r\n list=[]\r\n for i in range(0,count):\r\n list.append(test())\r\n return list\r\n \r\na = answerlist(100)\r\ncount = 0\r\nfor i in a:\r\n if i == 1:\r\n count+=1\r\nprint(count/100)\r\n","sub_path":"python/work-2.py","file_name":"work-2.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"296191837","text":"\"\"\"\nDjango settings for errata project.\n\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n# SECURITY WARNING: keep the secret key used in production secret!\nwith open('/etc/secret_key.txt') as f:\n SECRET_KEY = f.read().strip()\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = DEBUG\n\nALLOWED_HOSTS = ['errata.ipsl.upmc.fr']\n\nADMINS = (\n ('Levavasseur Guillaume', 'glipsl@ipsl.jussieu.fr')\n)\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'query',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nSESSION_COOKIE_SECURE = True\n\nCSRF_COOKIE_HTTPONLY = True\n\nX_FRAME_OPTIONS = 'DENY'\n\nCSRF_COOKIE_SECURE = False\n\nROOT_URLCONF = 'errata.urls'\n\nWSGI_APPLICATION = 'errata.wsgi.application'\n\n# Database\n\nDATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.mysql',\n# 'NAME': 'errata_django_db',\n# 'USER': 'ipsl_db_2',\n# 'PASSWORD': 'Vn3om_95',\n# 'HOST': '134.157.176.22',\n# 'PORT': '',\n# },\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n 'USER': '', \n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n },\n 'legacy': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'IPSL-CM5_db',\n 'USER': 'ipsl_db',\n 'PASSWORD': '#Fmq8w4IP6',\n 'HOST': '134.157.176.22',\n 'PORT': '',\n }\n}\n\n# For uploaded files\nMEDIA_ROOT = os.path.join(BASE_DIR, 'query/tmp/')\nMEDIA_URL = '/query/tmp/'\n\nTEMPLATE_DIRS = (os.path.join(BASE_DIR, 'query/templates/'),)\n\nTIME_ZONE = 'Europe/Paris'\n\nLANGUAGE_CODE = 'fr-FR'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nAPPEND_SLASH = True\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'query/static/')\nSTATIC_URL = '/static/'\n","sub_path":"errata/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"509115967","text":"\"\"\"Data preprocessing.\"\"\"\n\nimport os\nimport pickle\nfrom typing import Any, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\n\n\ndef load_pickle(f: str) -> Any:\n \"\"\"Load a pickle file.\n\n Parameters:\n f: the pickle filename\n\n Returns:\n the pickled data\n \"\"\"\n return pickle.load(f, encoding=\"latin1\")\n\n\ndef get_MUSHROOM_data(validation: float, testing: float = 0.1) -> dict:\n \"\"\"Load the mushroom dataset.\n\n Parameters:\n validation: portion of the dataset used for validation\n testing: portion of the dataset used for testing\n\n Returns\n the train/val/test data and labels\n \"\"\"\n X_train = np.load(\"mushroom/X_train.npy\")\n y_train = np.load(\"mushroom/y_train.npy\")\n y_test = np.load(\"mushroom/y_test.npy\")\n X_test = np.load(\"mushroom/X_test.npy\")\n X_train, X_val, y_train, y_val = train_test_split(\n X_train, y_train, test_size=validation / (1 - testing), random_state=123\n )\n data = {\n \"X_train\": X_train,\n \"y_train\": y_train,\n \"X_val\": X_val,\n \"y_val\": y_val,\n \"X_test\": X_test,\n \"y_test\": y_test,\n }\n return data\n\n\ndef construct_MUSHROOM():\n \"\"\"Convert raw categorical data from mushroom dataset to one-hot encodings.\n \"\"\"\n dataset = pd.read_csv(\"mushroom/mushrooms.csv\")\n y = dataset[\"class\"]\n X = dataset.drop(\"class\", axis=1)\n for col in X.columns:\n Encoder_X = LabelEncoder()\n X[col] = Encoder_X.fit_transform(X[col])\n Encoder_y = LabelEncoder()\n y = Encoder_y.fit_transform(y)\n X = X.values\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.1, random_state=123\n )\n np.save(\"mushroom/X_train.npy\", X_train)\n np.save(\"mushroom/y_train.npy\", y_train)\n np.save(\"mushroom/X_test.npy\", X_test)\n np.save(\"mushroom/y_test.npy\", y_test)\n","sub_path":"data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"495582126","text":"import os\nimport re\nimport json\nimport spacy\nfrom spacy.gold import biluo_tags_from_offsets\nfrom spacy.tokenizer import Tokenizer\n\nnlp = spacy.load(\"en_core_web_sm\")\nnlp.tokenizer = Tokenizer(nlp.vocab, token_match=re.compile(r'\\S+').match)\n\nwith open(\"data/data.json\",\"r\") as fh: \n data = json.load(fh)\n\nTRAIN_DATA = data[\"spacy_data\"]\n\niob_data = []\n\nfor text, annot in TRAIN_DATA:\n doc = nlp(text)\n tags = biluo_tags_from_offsets(doc, annot)\n tokens = [tok.text for tok in doc]\n # tags = [tag.replace(\"L-\",\"I-\").replace(\"U-\",\"B-\") for tag in tags]\n # then convert L->I and U->B to have IOB tags for the tokens in the doc\n iob_data.append((tokens,tags))\n\nfeatures_data_folder = \"features/\"\nif not os.path.exists(features_data_folder): os.makedirs(features_data_folder,exist_ok=True)\n\nwith open(features_data_folder+\"/iobdata.json\",\"w\") as fh:\n json.dump({\"iob_data\":iob_data},fh,indent=4)","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"63036293","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Test du port série\nimport serial\ntest_string = bytes(\"Je teste le port série 1 2 3 4 5\", \"UTF-8\")\nport_list = [\"/dev/ttyAMA0\", \"/dev/ttyAMA0\", \"/dev/ttyS0\", \"/dev/ttyS0\",]\nfor port in port_list:\n try:\n serialPort = serial.Serial(port, 9600, timeout = 2)\n print (\"Port Série {0} ouvert pour le test :\".format(port))\n bytes_sent = serialPort.write(test_string)\n print (\"Envoyé {0} octets\".format(bytes_sent))\n loopback = serialPort.read(bytes_sent)\n if loopback == test_string:\n print (\"Reçu {0} octets identiques. Le port {1} fonctionne bien !\".format(len(loopback), port))\n else:\n print (\"Reçu des données incorrectes : {0} sur le port série {1} bouclé\".format(loopback, port))\n serialPort.close()\n except IOError:\n print (\"Erreur sur {0}\".format(port))\n","sub_path":"TeleInfoRaspi/FirstSetup/tst_serial.py","file_name":"tst_serial.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"415883457","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom ...settings import ideal\n\nclass Command(BaseCommand):\n help = 'Retrieve a list of Ideal issuers and cache tem in the DB'\n \n def handle(self, *args, **options):\n from ...models import TargetpayIdealIssuer as Issuer\n issuers = ideal.getIssuers()\n issuer_ids = []\n for issuer_id, issuer_name in issuers.items():\n issuer_ids.append(issuer_id)\n issuer, created = Issuer.objects.get_or_create(issuer_id=issuer_id, defaults={'name': issuer_name})\n if not created:\n issuer.name = issuer_name\n issuer.save()\n Issuer.objects.exclude(issuer_id__in=issuer_ids).delete()\n","sub_path":"satchless/contrib/payment/targetpay_ideal_provider/management/commands/cache_issuers.py","file_name":"cache_issuers.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"477458858","text":"\n# coding: utf-8\n\n# # Visualization of template experiment\n# This notebook plots the gene expression data of the template experiment in order to confirm the strength of the differential signal, since we will be performing a DE analysis downstream.\n\n# In[ ]:\n\n\nget_ipython().run_line_magic('load_ext', 'autoreload')\nget_ipython().run_line_magic('autoreload', '2')\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport random\nimport umap\nfrom plotnine import (ggplot,\n labs, \n geom_point,\n aes, \n ggsave, \n theme_bw,\n theme,\n facet_wrap,\n scale_color_manual,\n guides, \n guide_legend,\n element_blank,\n element_text,\n element_rect,\n element_line,\n coords)\n\nfrom ponyo import utils\n\nnp.random.seed(123)\n\n\n# In[2]:\n\n\n# Read in config variables\nbase_dir = os.path.abspath(os.path.join(os.getcwd(),\"../\"))\nconfig_file = os.path.abspath(os.path.join(base_dir,\n \"config_pseudomonas.tsv\"))\nparams = utils.read_config(config_file)\n\n\n# In[3]:\n\n\n# Load parameters\nlocal_dir = params[\"local_dir\"]\ndataset_name = params['dataset_name']\nproject_id = params['project_id']\ntemplate_data_file = params['template_data_file']\n\n\n# In[4]:\n\n\n# Load metadata file with grouping assignments for samples\nmetadata_file = os.path.join(\n base_dir,\n dataset_name,\n \"data\",\n \"metadata\",\n project_id+\"_groups.tsv\")\n\n\n# In[5]:\n\n\n# Read template data\ndata = pd.read_csv(template_data_file, sep=\"\\t\", header=0, index_col=0)\n\ndata.head()\n\n\n# In[6]:\n\n\n# Read metadata\nmetadata = pd.read_csv(metadata_file, sep=\"\\t\", header=0, index_col=0)\n\nmetadata.head()\n\n\n# In[7]:\n\n\n# Embed expression data into low dimensional space\nmodel = umap.UMAP(random_state=123).fit(data)\ndata_encoded = model.transform(data)\n\ndata_encoded_df = pd.DataFrame(data=data_encoded,\n index=data.index,\n columns=['1','2'])\n\n\n# In[8]:\n\n\n# Label samples\ngroup1_ids = list(metadata[metadata['group']==1].index)\n\n#data_encoded_df['group'] = 'clinical multi-drug resistant'\n#data_encoded_df.loc[group1_ids,'group'] = 'clinical'\n#data_encoded_df.loc['GSM625982.CEL','group'] = 'control'\ndata_encoded_df['group'] = 'untreated'\ndata_encoded_df.loc[group1_ids,'group'] = 'treated with tobramycin'\n\n\n# In[9]:\n\n\ndata_encoded_df.head()\n\n\n# In[10]:\n\n\n# Plot PAO1\nfig = ggplot(data_encoded_df, aes(x='1', y='2'))\nfig += geom_point(aes(color='group'), alpha=0.7)\nfig += labs(x ='UMAP 1',\n y = 'UMAP 2',\n title = 'Gene expression of template experiment')\nfig += theme_bw()\nfig += theme(\n legend_title_align = \"center\",\n plot_background=element_rect(fill='white'),\n legend_key=element_rect(fill='white', colour='white'), \n legend_title=element_text(family='sans-serif', size=15),\n legend_text=element_text(family='sans-serif', size=12),\n plot_title=element_text(family='sans-serif', size=15),\n axis_text=element_text(family='sans-serif', size=12),\n axis_title=element_text(family='sans-serif', size=15)\n )\nfig += guides(colour=guide_legend(override_aes={'alpha': 1}))\n\nprint(fig)\n\n\n# **Observation:** We see a good separation between the treated and untreated samples. We expect this template experiment to provide a fairly strong differential signal in our DE analysis.\n","sub_path":"pseudomonas_analysis/nbconverted/Viz_template_experiment.py","file_name":"Viz_template_experiment.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"142316664","text":"from celery import Celery\r\nfrom flask_mail import Message\r\nfrom exts import mail,alidayu\r\nfrom flask import Flask\r\nimport config\r\n\r\napp = Flask(__name__)\r\napp.config.from_object(config)\r\nmail.init_app(app)\r\nalidayu.init_app(app)\r\n#运行文本文件\r\n#(flask-bbs) C:\\Users\\TT\\bbs>celery -A tasks.celery --pool=eventlet worker --loglevel=info\r\ndef make_celery(app):\r\n celery = Celery(\r\n app.import_name,\r\n backend=app.config['CELERY_RESULT_BACKEND'],\r\n broker=app.config['CELERY_BROKER_URL']\r\n )\r\n celery.conf.update(app.config)\r\n\r\n class ContextTask(celery.Task):\r\n def __call__(self, *args, **kwargs):\r\n with app.app_context():\r\n return self.run(*args, **kwargs)\r\n\r\n celery.Task = ContextTask\r\n return celery\r\n\r\ncelery = make_celery(app)\r\n\r\n@celery.task\r\ndef send_mail(subject,recipients,body):\r\n message = Message(subject=subject,recipients=recipients,body=body)\r\n mail.send(message)\r\n\r\n@celery.task\r\ndef send_sms_captcha(telephone,captcha):\r\n alidayu.send_sms(telephone,code=captcha)","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"22830815","text":"import random\nimport operator\n\noperations = { 1 : { \"display\": \"Addition\",\n \"symbol\": \"+\",\n \"perform\": operator.add},\n 2 : { \"display\": \"Subtraction\",\n \"symbol\": \"-\",\n \"perform\": operator.sub},\n 3 : { \"display\": \"Multiplication\",\n \"symbol\": \"*\",\n \"perform\": operator.mul},\n 4 : { \"display\": \"Integer Division\",\n \"symbol\": \"/\",\n \"perform\": operator.truediv}\n }\n\ndifficulties = {0 : { \"display\": \"Numbers 0 thru 9\",\n \"bound\": 9},\n 1 : { \"display\": \"Numbers 0 thru 99\",\n \"bound\": 99},\n 2 : { \"display\": \"Numbers 0 thru 999\",\n \"bound\": 999},\n 3 : { \"display\": \"Numbers 0 thru 9999\",\n \"bound\": 9999}\n }\n\ndef show_operations():\n # shows the user a list of operations to be quizzed on\n print(\"-\"*24)\n print(\"Choose an operation:\")\n print(\"-\"*24)\n print(\"1. Addition\")\n print(\"2. Subtraction\")\n print(\"3. Multiplication\")\n print(\"4. Integer Division\")\n\ndef choose_operation():\n # returns the operation selected by the user\n show_operations()\n operation = input(\"> Select a number: \")\n return int(operation)\n\ndef show_levels():\n # shows the user a list of difficulty levels to choose from\n print(\"-\"*24)\n print(\"Choose a difficulty:\")\n print(\"-\"*24)\n print(\"Level 0: 0~9\")\n print(\"Level 1: 0~99\")\n print(\"Level 2: 0~999\")\n print(\"Level 3: 0~9999\")\n\ndef choose_level():\n # returns the difficulty level chosen by the user\n show_levels()\n level = input(\"> Select a number: \")\n return int(level)\n\ndef get_numbers(level):\n # returns two random numbers within bounds chosen by difficulty\n upper_bound = difficulties[level][\"bound\"]\n num1 = random.randint(0, upper_bound)\n num2 = random.randint(0, upper_bound)\n return (num1, num2)\n\ndef solve(numbers, operation):\n soln = input(\"> Solve: \")\n try:\n return int(soln)\n except:\n return soln.upper()\n\ndef check(numbers, operation):\n # check user solution\n if numbers[1] == 0 and operation == 4:\n soln = \"DNE\"\n else:\n soln = operations[operation][\"perform\"](numbers[0], numbers[1])\n return soln\n\n\ndef run_quiz():\n operation = choose_operation()\n print(\"You chose: \", operations[operation][\"display\"])\n\n difficulty = choose_level()\n print(\"You chose: \", difficulties[difficulty][\"display\"])\n\n numbers = get_numbers(difficulty)\n print(\"Your numbers are: \", numbers[0], \" and \", numbers[1])\n\n user_soln = solve(numbers, operation)\n true_soln = check(numbers, operation)\n if user_soln == true_soln:\n print(\"You got it right!\")\n else:\n print(\"Try again!\")\n\n print(\"The correct answer is: \", true_soln)\n\ndef main():\n run_quiz()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mathquiz/mathquiz.py","file_name":"mathquiz.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"396362042","text":"# JeromeJGuay June 2020\nimport numpy as np\nimport xarray as xr\n\n\ndef transects_gridding(dataset, position_resolution, depth_resolution,\n min_depth, max_depth, savefile):\n \"\"\"\n \"\"\"\n transect_vector = np.unique(dataset.transect.data)\n position_vector = np.arange(dataset.ajusted_position.min(),\n dataset.ajusted_position.max() +\n position_resolution,\n position_resolution)\n depth_vector = np.arange(min_depth,\n max_depth+depth_resolution,\n depth_resolution)\n\n density_volume = np.ma.masked_array(np.nan*np.zeros((len(transect_vector),\n len(position_vector),\n len(depth_vector))),\n mask=True)\n temperature_volume = np.copy(density_volume)\n salinity_volume = np.copy(density_volume)\n o_density_volume = np.copy(density_volume)\n o_temperature_volume = np.copy(density_volume)\n o_salinity_volume = np.copy(density_volume)\n\n time_grid = np.ma.masked_array(np.zeros((len(transect_vector),\n len(position_vector)),\n dtype='datetime64[s]'),\n mask=True)\n\n time_grid[:, :] = np.datetime64('NaT')\n time_grid.mask = True\n # these loops fill all the data volume and time grid, bin by bin.\n for ti, t in zip(range(len(dataset.transect)), transect_vector):\n ds_tmp = dataset.sel(time=dataset.transect == t)\n # This loop places the date by binning them in the volume.\n for pi, p in zip(range(len(position_vector)), position_vector):\n pIndex = np.where((ds_tmp.ajusted_position.data >=\n p-position_resolution/2) &\n (ds_tmp.ajusted_position.data <=\n p+position_resolution/2))[0]\n if len(pIndex) != 0:\n time_grid[ti, pi] = ds_tmp.time[pIndex].mean().data\n\n for di, d in zip(range(len(depth_vector)), depth_vector):\n\n print('%03d' % ti, '/', len(transect_vector), '|', '%03d' % pi,\n '/', len(position_vector), '|', '%03d' % di, '/',\n len(depth_vector), end=\"\\r\")\n\n dIndex = np.where((ds_tmp.depth > d-depth_resolution/2) &\n (ds_tmp.depth < d+depth_resolution/2))[0]\n\n Index = np.intersect1d(pIndex, dIndex)\n\n if len(Index != 0):\n density_volume[ti, pi, di] =\\\n ds_tmp.density[Index].mean().data\n temperature_volume[ti, pi, di] =\\\n ds_tmp.temperature[Index].mean().data\n salinity_volume[ti, pi, di] =\\\n ds_tmp.salinity[Index].mean().data\n o_density_volume[ti, pi, di] =\\\n ds_tmp.ordered_density[Index].mean().data\n o_temperature_volume[ti, pi, di] =\\\n ds_tmp.ordered_temperature[Index].mean().data\n o_salinity_volume[ti, pi, di] =\\\n ds_tmp.ordered_salinity[Index].mean().data\n\n # here the time is linearly interpolated for all grid points.\n for ti in range(len(transect_vector)):\n # here we put nan on masked etremity data to prevent data extrapolation\n time_tmp_mask = time_grid[ti].mask\n\n time_tmp = time_grid[ti].astype('float')\n\n if time_tmp_mask[0] is True:\n time_tmp[0], time_tmp_mask[0] = np.nan, False\n if time_tmp_mask[-1] is True:\n time_tmp[-1], time_tmp_mask[-1] = np.nan, False\n\n # finalement each row is linearly interpolate.\n Ind = np.where(time_tmp_mask is False)[0]\n if len(Ind > 0):\n time_tmp = np.interp(position_vector,\n position_vector[Ind],\n time_tmp[Ind])\n\n time_grid[ti] = time_tmp.astype('datetime64[s]')\n time_grid\n\n transect_dataset =\\\n xr.Dataset({'ordered_density': (['transect', 'position', 'depth'],\n o_density_volume.data),\n 'ordered_temperature': (['transect', 'position', 'depth'],\n o_temperature_volume.data),\n 'ordered_salinity': (['transect', 'position', 'depth'],\n o_salinity_volume.data),\n 'density': (['transect', 'position', 'depth'],\n density_volume.data),\n 'temperature': (['transect', 'position', 'depth'],\n temperature_volume.data),\n 'salinity': (['transect', 'position', 'depth'],\n salinity_volume.data),\n 'mask': (['transect', 'position', 'depth'],\n density_volume.mask),\n 'time': (['transect', 'position'],\n time_grid.data),\n 'time_mask': (['transect', 'position'],\n time_grid.mask)},\n coords={'transect': transect_vector,\n 'position': position_vector,\n 'depth': depth_vector},\n attrs={'interp': 'Horizontal interpolation'})\n\n transect_dataset =\\\n transect_dataset.assign_attrs({'transect_start':\n dataset.transect_start,\n 'transect_end':\n dataset.transect_end})\n\n # transect_dataset.to_netcdf(savefile+'.nc')\n\n return transect_dataset\n\n\ndef add_bathymetry(transect_dataset, bathy_dataset):\n \"\"\"\n \"\"\"\n bathy = bathy_dataset.interp(position=transect_dataset.position).data\n\n density_volume = np.ma.masked_array(transect_dataset.density,\n mask=transect_dataset.mask)\n\n SillIndex = []\n\n for b in range(len(transect_dataset.position)):\n SillIndex.append(np.where(transect_dataset.depth > bathy[b])[0])\n\n for pi in range(len(transect_dataset.position)):\n density_volume[:, pi, SillIndex[pi]] = np.nan\n\n transect_dataset['density'].values = density_volume.data\n transect_dataset['mask'].values = density_volume.mask\n\n return transect_dataset\n\n\ndef horizontal_interpolation(transect_dataset):\n \"\"\"\n \"\"\"\n # make a masked array\n density_volume = np.ma.masked_array(transect_dataset.density,\n mask=transect_dataset.mask)\n\n # This loop is to horizontaly interpolate the data\n for ti in range(len(transect_dataset.transect)):\n # here we put nan on masked extremity data to prevent data extrapolation.\n density_volume[ti, 0][np.where(density_volume[ti, 0].mask is True)[0]]\\\n = np.nan\n density_volume[ti, -1][np.where(density_volume[ti, -1].mask is True)[0]]\\\n = np.nan\n # finalement each row is linearly interpolate.\n for di in range(len(transect_dataset.depth)):\n x, y = transect_dataset.position, density_volume[ti, :, di]\n Ind = np.where(y.mask is False)[0]\n if len(Ind > 0):\n density_volume[ti, :, di] = np.interp(x, x[Ind], y[Ind])\n\n # Putting everything back in a masked array.\n transect_dataset['density'].values = density_volume.data\n transect_dataset['mask'].values = density_volume.mask\n\n # transect_dataset.to_netcdf(savefile)\n\n return transect_dataset\n","sub_path":"Processing/Gridding/Scanfish_Gridding.py","file_name":"Scanfish_Gridding.py","file_ext":"py","file_size_in_byte":7818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"617296073","text":"from application.models.conn import conn, cursor\nfrom flask import request, jsonify, abort\nimport datetime\nimport re\n\n\nclass Product:\n def __init__(self):\n self.conn = conn\n self.cursor = cursor\n\n def add_new_product(self):\n try:\n if not request.json['quantity']:\n return jsonify({'error':'product quantity is missing'}), 200 \n if request.json['quantity'] == \"\":\n return jsonify({'error':'product quantity can not be empty'}), 200\n if isinstance(request.json['quantity'], str):\n return jsonify({'error':'product quantity must be an integer value'}), 200\n\n if not request.json['product_name']:\n return jsonify({'error':'product name is missing'}), 200\n if request.json['product_name'] == \"\":\n return jsonify({'error':'product name can not be empty'}), 200 \n if re.search(r'[0-9]', request.json['product_name']):\n return jsonify({'error':'product name can not have integer(s) in it'}), 200\n\n unit_price = request.json['unit_price']\n if not unit_price:\n return jsonify({'message':'product unit price is missing'}), 200 \n if unit_price == \"\":\n return jsonify({'message':'product unit price can not be empty'}), 200\n if isinstance(request.json['unit_price'], str):\n return jsonify({'message':'product unit price must be an integer value'}), 200\n \n query = \"\"\"SELECT * FROM \"product\" WHERE product_name=%s\"\"\"\n self.cursor.execute(query, (request.json['product_name'], ))\n product = self.cursor.fetchone()\n\n if product is None:\n query = \"\"\"INSERT INTO \"product\"(product_name, quantity, unit_price, date_created) VALUES(%s, %s, %s, %s)\"\"\"\n cursor.execute(query, (request.json['product_name'], request.json['quantity'], unit_price, datetime.datetime.utcnow()))\n return jsonify({'message':'product added successfully'}), 201\n quantity = request.json['quantity'] + product['quantity']\n query = \"\"\"UPDATE product SET quantity=%s WHERE product_name=%s\"\"\"\n self.cursor.execute(query, (quantity, request.json['product_name']))\n return jsonify({'message':'product added successfully'}), 201\n except(KeyError):\n return jsonify({'error':'make sure you have provided all fields and values'}), 200\n\n def get_all_products(self):\n query = \"\"\"SELECT * FROM product\"\"\"\n self.cursor.execute(query)\n result = self.cursor.fetchall()\n return jsonify({'products':result}), 200\n\n def get_one_product(self, id):\n query = \"\"\"SELECT * FROM product WHERE product_id=%s\"\"\"\n self.cursor.execute(query, (id, ))\n result = self.cursor.fetchone()\n if result is None:\n return jsonify({'message':'this product does not exist'}), 200\n return jsonify({'products':result}), 200\n\n def delete_all_products(self):\n query = \"\"\"DELETE * FROM product\"\"\"\n self.cursor.execute(query)\n return jsonify({'message':'all products deleted successfully'}), 200 \n\n def edit_a_product(self, id):\n query = \"\"\"UPDATE \"product\" SET product_name=%s,quantity=%s,unit_price=%s WHERE product_id=%s\"\"\"\n self.cursor.execute(query, (request.json['product_name'], request.json['quantity'], request.json['unit_price'], id))\n self.conn.commit()\n return jsonify({'message':'product updated successfully'}), 200\n","sub_path":"application/controllers/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"603331224","text":"from unittest import TestCase\n\nfrom leetcodepy.find_minimum_in_rotated_sorted_array import *\n\nsolution1 = Solution1()\n\nnums1 = [3, 4, 5, 1, 2]\n\nexpected1 = 1\n\nnums2 = [4, 5, 6, 7, 0, 1, 2]\n\nexpected2 = 0\n\n\nclass TestFindMinimumInRotatedSortedArray(TestCase):\n def test1(self):\n self.assertEqual(expected1, solution1.findMin(nums1))\n self.assertEqual(expected2, solution1.findMin(nums2))\n","sub_path":"python/tests/test_find_minimum_in_rotated_sorted_array.py","file_name":"test_find_minimum_in_rotated_sorted_array.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"533938334","text":"class ATM:\n\n def __init__(self):\n self.c = [20, 50, 100, 200, 500]\n self.a = [0] * 5\n self.total = 0\n\n def deposit(self, banknotesCount) -> None:\n for i in range(5):\n self.a[i] += banknotesCount[i]\n\n def withdraw(self, amount: int):\n res = [0] * 5\n i = 4\n while amount > 0 and i >= 0:\n res[i] = min(amount // self.c[i], self.a[i])\n amount -= self.c[i] * res[i]\n i -= 1\n if amount > 0:\n return [-1]\n for i in range(5):\n self.a[i] -= res[i]\n return res\n\n\n# Your ATM object will be instantiated and called as such:\nATM\natm = ATM()\natm.deposit([0, 0, 1, 2, 1])\nprint(atm.withdraw(600))\natm.deposit([0, 1, 0, 1, 1])\nprint(atm.withdraw(600))\nprint(atm.withdraw(550))\n","sub_path":"leetcode/2022/bicontest/bcontest-076/bContest3.py","file_name":"bContest3.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"623406223","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPráctica 1: APC\nEstudiante: JJavier Alonso Ramos\n\n\"\"\"\n\nfrom scipy.io import arff\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import KDTree\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import MinMaxScaler\nfrom time import time\nimport sys\nfrom prettytable import PrettyTable\nimport matplotlib.pyplot as plt\n\n###################################################\n### Funciones para la codificación de etiquetas ###\n###################################################\nbyte2string = lambda x: x.decode('utf-8')\n\n#######################################\n### Función para leer archivos arff ###\n#######################################\ndef read_arff(name):\n\tpath = '../data/'+name+'.arff'\n\tfile, meta = arff.loadarff(path)\n\n\tdf_data = pd.DataFrame(file)\t# Transformamos file (los datos) en un data-frame\n\tdata = df_data.values\t\t\t# Transformamos este data-frame en una matriz para que sea más manejable\n\n\treturn data, meta\n\n##############################################################################\n### Devuelve las etiquetas (clases) de los elementos del conjunto de datos ###\n##############################################################################\ndef get_tags(data):\n\ttags = []\n\tfor _data in data:\n\t\ttags.append(byte2string(_data[-1]))\n\ttags = np.asarray(tags)\n\n\treturn tags \n\ndef get_only_data(data):\n\treturn (data[:,0:-1]).astype(float)\n\n###########################################\n### k-NN ; leave-one-out when necessary ###\n###########################################\ndef k_NN(data_training, tags_training, w, data_test = None, tags_test = None, is_training = True):\n\tw_prim = np.copy( w )\n\tw_prim[w_prim < 0.2] = 0.0\n\teliminated = w_prim[w_prim < 0.2].shape[0]\n\thit = 0\n\thit_rate = 0.0\n\n\tdata_training_mod = (data_training*w_prim)[:, w_prim > 0.2]\n\n\ttree = KDTree(data_training_mod)\n\tif is_training:\n\t\tnearest_ind = tree.query(data_training_mod, k=2, return_distance=False)[:,1]\n\t\thit_rate = np.mean( tags_training[nearest_ind] == tags_training )\n\telse:\n\t\tdata_test_mod = (data_test*w_prim)[:, w_prim > 0.2]\n\t\tnearest_ind = tree.query(data_test_mod, k=1, return_distance=False)\n\t\tfor i in range(nearest_ind.shape[0]):\n\t\t\tif tags_training[nearest_ind[i]] == tags_test[i]:\n\t\t\t\thit += 1\n\n\t\thit_rate = hit/data_test_mod.shape[0]\n\n\n\treduction_rate = eliminated/w.shape[0]\n\n\tf = (hit_rate + reduction_rate)* 0.5\n\n\treturn f, hit_rate, reduction_rate\n\n############\n### 1-NN ###\n############\ndef _1_NN(data_training, tags_training, data_test, tags_test):\n\thit = 0\n\n\ttree = KDTree(data_training)\n\tnearest_ind = tree.query(data_test, k=1, return_distance=False)\n\tfor i in range(nearest_ind.shape[0]):\n\t\tif tags_training[nearest_ind[i]] == tags_test[i]:\n\t\t\thit += 1\n\n\thit_rate = hit/data_test.shape[0]\n\treduction_rate = 0.0\n\n\tf = (hit_rate + reduction_rate)* 0.5\n\n\treturn f, hit_rate, reduction_rate\n\n########################\n### Algoritmo Greedy ###\n########################\ndef relief(data, tags):\n####################################### BUCLES ####################################################\n\t\"\"\"\n\tw = np.zeros(data.shape[1])\n\tclosest_enemy_id = -4\n\tclosest_friend_id = -4\n\n\tfor i in range(data.shape[0]):\n\t\tenemy_distance = 999\n\t\tfriend_distance = 999\n\t\tfor j in range(data.shape[0]):\n\t\t\tif i != j:\n\t\t\t\tcurrent_distance = np.linalg.norm(data[i] - data[j])\n\n\t\t\t\tif tags[i] == tags[j] and current_distance < friend_distance:\n\t\t\t\t\tfriend_distance = current_distance\n\t\t\t\t\tclosest_friend_id = j\n\t\t\t\telif tags[i] != tags[j] and current_distance < enemy_distance:\n\t\t\t\t\tenemy_distance = current_distance\n\t\t\t\t\tclosest_enemy_id = j\n\n\t\tw = w + np.abs(data[i] - data[closest_enemy_id]) - np.abs(data[i] - data[closest_friend_id])\n\t\"\"\"\n######################################### KDTree ##################################################\n\t\n\tw = np.zeros(data.shape[1])\n\tclosest_enemy_id = -4\n\tclosest_friend_id = -4\n\tally_found = False\n\tenemy_found = False\n\n\ttree = KDTree(data)\n\tnearest_ind = tree.query(data, k=data.shape[0], return_distance=False)[:,1:]\n\n\tfor i in range(nearest_ind.shape[0]):\n\t\tfor j in range(nearest_ind.shape[1]):\n\t\t\tif not ally_found and tags[i] == tags[ nearest_ind[i,j] ]:\n\t\t\t\tally_found = True\n\t\t\t\tclosest_friend_id = nearest_ind[i,j]\n\t\t\telif not enemy_found and tags[i] != tags[ nearest_ind[i,j] ]:\n\t\t\t\tenemy_found = True\n\t\t\t\tclosest_enemy_id = nearest_ind[i,j]\n\t\t\tif ally_found and enemy_found:\n\t\t\t\tbreak\n\t\tally_found = enemy_found = False\n\t\tw = w + np.abs(data[i] - data[closest_enemy_id]) - np.abs(data[i] - data[closest_friend_id])\n\t\n###########################################################################################\n\n\tw_max = np.max(w)\n\tw[ w < 0.0] = 0.0\n\tw /= w_max\n\n\t\n\t# Comentado para no retrasar la ejecucion del algoritmo\n\t\"\"\"\n\tfor i in range(len(w)):\n\t\tplt.bar(i,w[i])\n\tplt.show()\n\t\"\"\"\n\n\treturn w\n\n###################\n### Local Seach ###\n###################\ndef local_search(data, tags):\n\tw = np.random.uniform(0.0,1.0,data.shape[1])\n\tmax_eval = 15000\n\tmax_neighbors = 20*data.shape[1]\n\tn_eval = 0\n\tn_neighbors = 0\n\tvariance = 0.3\n\tmean = 0.0\n\tclass_prev, h, r = k_NN(data, tags, w)\n\n\twhile n_eval < max_eval and n_neighbors < max_neighbors:\n\t\tfor i in range(w.shape[0]):\n\t\t\tn_eval += 1\n\t\t\tprev = w[i]\n\t\t\tw[i] = np.clip(w[i] + np.random.normal(mean, variance), 0, 1)\n\t\t\tclass_mod, h, r = k_NN(data, tags, w)\n\n\t\t\tif(class_mod > class_prev):\n\t\t\t\tn_neighbors = 0\n\t\t\t\tclass_prev = class_mod\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tw[i] = prev\n\t\t\t\tn_neighbors += 1\n\n\t\"\"\"\n\tfor i in range(len(w)):\n\t\tplt.bar(i,w[i])\n\tplt.show()\n\t\"\"\"\n\n\treturn w\n\n###########################################################################################\n###··································### MAIN ###·······································###\n###########################################################################################\n\nif len(sys.argv) == 2:\n\tnp.random.seed(int(sys.argv[1]))\nelse:\n\tnp.random.seed(1)\n\narchivos = ['colposcopy', 'texture', 'ionosphere']\nfor archivo in archivos:\n\tdata, meta = read_arff(archivo)\n\ttags = get_tags(data)\n\t_data = get_only_data(data)\n\n\tscaler = MinMaxScaler()\n\tscaler.fit(_data)\n\t_data = scaler.transform(_data)\n\n\tpartition = 0\n\tmean_test_greedy_hr = 0.0\n\tmean_test_greedy_rr = 0.0\n\tmean_test_greedy_f = 0.0\n\tmean_test_greedy_t = 0.0\n\tmean_test_LS_hr = 0.0\n\tmean_test_LS_rr = 0.0\n\tmean_test_LS_f = 0.0\n\tmean_test_LS_t = 0.0\n\tmean_test_1nn_hr = 0.0\n\tmean_test_1nn_rr = 0.0\n\tmean_test_1nn_f = 0.0\n\n\ttable_greedy = PrettyTable(['Partición', '%_clas', '%_red', 'Agr.', 'T'])\n\ttable_ls = PrettyTable(['Partición', '%_clas', '%_red', 'Agr.', 'T'])\n\ttable_1nn = PrettyTable(['Partición', '%_clas', '%_red', 'Agr.', 'T'])\n\tmean_table = PrettyTable(['Algorithm', '%_clas', '%_red', 'Agr.'])\n\n\tskf = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)\n\tfor train_index, test_index in skf.split(_data, tags):\n\t\tx_train, x_test = _data[train_index], _data[test_index]\n\t\ty_train, y_test = tags[train_index], tags[test_index]\n\t\tpartition += 1\n\n\t\tprint('\\n\\n Partición ', partition)\n\n\t\t###·· GREEDY ··###\n\t\tprint('··· Calculando pesos por medio de Relief ···')\n\t\tini_time = time()\n\t\tw_g = relief(x_train, y_train)\n\t\tfin_time = time()\n\t\tdif_time_g = fin_time - ini_time\n\t\tmean_test_greedy_t\t+= dif_time_g\n\n\t\t###·· LOCAL SEARCH ··###\n\t\tprint('··· Calculando pesos por medio de Local Search ···')\n\t\tini_time = time()\n\t\tw_ls = local_search(x_train, y_train)\n\t\tfin_time = time()\n\t\tdif_time_ls = fin_time - ini_time\n\t\tmean_test_LS_t += dif_time_ls\n\n\t\t###·· TEST GREEDY ··###\n\t\tprint('··· Evaluando Relief ···')\n\t\tf, hr, rr = k_NN(x_train, y_train, w_g, x_test, y_test, False)\n\t\tmean_test_greedy_f = mean_test_greedy_f + f\n\t\tmean_test_greedy_hr = mean_test_greedy_hr + hr\n\t\tmean_test_greedy_rr = mean_test_greedy_rr + rr\n\n\t\ttable_greedy.add_row([partition, 100*hr, 100*rr, f*100, dif_time_g])\n\n\t\t###·· TEST LOCAL SEARCH ··###\n\t\tprint('··· Evaluando Local Search ···')\n\t\tf, hr, rr = k_NN(x_train, y_train, w_ls, x_test, y_test, False)\n\t\tmean_test_LS_f = mean_test_LS_f + f\n\t\tmean_test_LS_hr = mean_test_LS_hr + hr\n\t\tmean_test_LS_rr = mean_test_LS_rr + rr\n\n\t\ttable_ls.add_row([partition, 100*hr, 100*rr, f*100, dif_time_ls])\n\n\t\t###·· TEST 1-NN ··###\n\t\tprint('··· Evaluando 1-NN ···')\n\t\tf, hr, rr = _1_NN(x_train, y_train, x_test, y_test)\n\t\tmean_test_1nn_f = mean_test_1nn_f + f\n\t\tmean_test_1nn_hr = mean_test_1nn_hr + hr\n\t\tmean_test_1nn_rr = mean_test_1nn_rr + rr\n\n\t\ttable_1nn.add_row([partition, 100*hr, 100*rr, f*100, 0])\n\n\ttable_1nn.add_row(['Media', 100*mean_test_1nn_hr/5, 100*mean_test_1nn_rr/5, 100*mean_test_1nn_f/5, 0])\n\ttable_greedy.add_row(['Media', 100*mean_test_greedy_hr/5, 100*mean_test_greedy_rr/5, 100*mean_test_greedy_f/5, mean_test_greedy_t/5])\n\ttable_ls.add_row(['Media', 100*mean_test_LS_hr/5, 100*mean_test_LS_rr/5, 100*mean_test_LS_f/5, mean_test_LS_t/5])\n\n\tmean_table.add_row(['1-NN', 100*mean_test_1nn_hr/5, 100*mean_test_1nn_rr/5, 100*mean_test_1nn_f/5])\n\tmean_table.add_row(['RELIEF', 100*mean_test_greedy_hr/5, 100*mean_test_greedy_rr/5, 100*mean_test_greedy_f/5])\n\tmean_table.add_row(['LOCAL SEARCH', 100*mean_test_LS_hr/5, 100*mean_test_LS_rr/5, 100*mean_test_LS_f/5])\n\n\tprint(table_1nn.get_string(title='Resultados 1-NN - '+archivo))\n\tprint(table_greedy.get_string(title='Resultados RELIEF - '+archivo))\n\tprint(table_ls.get_string(title='Resultados LOCAL SEARCH - '+archivo))\n\tprint(mean_table.get_string(title='Media de resultados - '+archivo))","sub_path":"PRACTICAS/P1/src/Practica1.py","file_name":"Practica1.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"395372766","text":"# Copyright 2014 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Runs terasort on hadoop.\n\nCluster Setup:\nhttp://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/ClusterSetup.html\n\nTODO(user): Make hadoop scale when the number of nodes changes. Also\ninvestigate other settings and verfiy that we are seeing good performance.\n\"\"\"\n\nimport logging\nimport posixpath\nimport time\n\nfrom perfkitbenchmarker import flags\nfrom perfkitbenchmarker import sample\nfrom perfkitbenchmarker import vm_util\nfrom perfkitbenchmarker.packages import hadoop\n\nflags.DEFINE_integer('terasort_num_rows', 100000000,\n 'Number of 100-byte rows used in terasort.')\n\nFLAGS = flags.FLAGS\n\nBENCHMARK_INFO = {'name': 'hadoop_terasort',\n 'description': 'Runs Terasort. Control the number of VMs '\n 'with --num_vms.',\n 'scratch_disk': True,\n 'num_machines': 9}\n\nNUM_BYTES_PER_ROW = 100\nNUM_MB_PER_ROW = NUM_BYTES_PER_ROW / (1024.0 ** 2)\n\n\ndef GetInfo():\n info = BENCHMARK_INFO.copy()\n if FLAGS['num_vms'].present:\n info['num_machines'] = FLAGS.num_vms\n return info\n\n\ndef CheckPrerequisites():\n \"\"\"Verifies that the required resources are present.\n\n Raises:\n perfkitbenchmarker.data.ResourceNotFound: On missing resource.\n \"\"\"\n hadoop.CheckPrerequisites()\n\n\ndef Prepare(benchmark_spec):\n \"\"\"Prepare the virtual machines to run hadoop.\n\n Args:\n benchmark_spec: The benchmark specification. Contains all data that is\n required to run the benchmark.\n \"\"\"\n vms = benchmark_spec.vms\n master = vms[0]\n workers = vms[1:]\n\n def InstallHadoop(vm):\n vm.Install('hadoop')\n vm_util.RunThreaded(InstallHadoop, vms)\n hadoop.ConfigureAndStart(master, workers)\n\n\ndef Run(benchmark_spec):\n \"\"\"Spawn hadoop and gather the results.\n\n Args:\n benchmark_spec: The benchmark specification. Contains all data that is\n required to run the benchmark.\n\n Returns:\n A list of sample.Sample instances.\n \"\"\"\n vms = benchmark_spec.vms\n master = vms[0]\n\n mapreduce_example_jar = posixpath.join(\n hadoop.HADOOP_DIR, 'share', 'hadoop', 'mapreduce',\n 'hadoop-mapreduce-examples-{0}.jar'.format(hadoop.HADOOP_VERSION))\n hadoop_cmd = '{0} jar {1}'.format(\n posixpath.join(hadoop.HADOOP_BIN, 'yarn'),\n mapreduce_example_jar)\n master.RobustRemoteCommand('{0} teragen {1} /teragen'.format(\n hadoop_cmd, FLAGS.terasort_num_rows))\n num_cpus = sum(vm.num_cpus for vm in vms[1:])\n start_time = time.time()\n stdout, _ = master.RobustRemoteCommand(\n hadoop_cmd + ' terasort /teragen /terasort')\n logging.info('Terasort output: %s', stdout)\n time_elapsed = time.time() - start_time\n data_processed_in_mbytes = FLAGS.terasort_num_rows * NUM_MB_PER_ROW\n master.RobustRemoteCommand(\n hadoop_cmd + ' teravalidate /terasort /teravalidate')\n\n # Clean up\n master.RemoteCommand(\n '{0} dfs -rm -r -f /teragen /teravalidate /terasort'.format(\n posixpath.join(hadoop.HADOOP_BIN, 'hdfs')))\n\n metadata = {'num_rows': FLAGS.terasort_num_rows,\n 'data_size_in_bytes': FLAGS.terasort_num_rows * NUM_BYTES_PER_ROW,\n 'num_vms': len(vms)}\n return [sample.Sample('Terasort Throughput Per Core',\n data_processed_in_mbytes / time_elapsed / num_cpus,\n 'MB/sec',\n metadata),\n sample.Sample('Terasort Total Time', time_elapsed, 'sec', metadata)]\n\n\ndef Cleanup(benchmark_spec):\n \"\"\"Uninstall packages required for Hadoop and remove benchmark files.\n\n Args:\n benchmark_spec: The benchmark specification. Contains all data that is\n required to run the benchmark.\n \"\"\"\n vms = benchmark_spec.vms\n master = vms[0]\n workers = vms[1:]\n\n logging.info('Stopping Hadoop.')\n hadoop.StopAll(master)\n vm_util.RunThreaded(hadoop.CleanDatanode, workers)\n","sub_path":"perfkitbenchmarker/benchmarks/hadoop_terasort_benchmark.py","file_name":"hadoop_terasort_benchmark.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"193245291","text":"import telebot\nimport time\nfrom Facade import BotFacade\nfrom Keyboard import Keyboard\nfrom ATMBot import ATMBot\n\nfacade = BotFacade()\nbot = facade.getBot()\natmIn = ATMBot()\natmOut = ATMBot()\natmIn.setLocation(\"ATM in SDU\")\natmOut.setLocation(\"ATM outside SDU\")\n\n@bot.message_handler(commands = ['start'])\ndef send_welcome(message):\n botMessage = 'Welcome!\\nType /help for more information.'\n bot.send_message(message.chat.id, botMessage)\n show_start(message.chat.id)\n\n@bot.message_handler(commands = ['help'])\ndef send_help(message):\n botMessage = 'Hi!\\n'\n botMessage = botMessage + 'Our bot checks ATMs\\' status by updates of the users. In order to continue using our bot type /start again\\n' \n bot.send_message(message.chat.id, botMessage)\n show_start(message.chat.id)\n\n@bot.message_handler(func = lambda message : message.text == 'ATM')\ndef send_atm(message):\n show_atm(message.chat.id)\n\n@bot.message_handler(func = lambda message : message.text == 'Check')\ndef send_check(message):\n if atmIn.yes == 0 and atmIn.no == 0:\n botMessage = \"We don't have any information about \" + atmIn.getLocation() + \"\\n\"\n else:\n botMessage = atmIn.analyze() + \"\\n\"\n if atmOut.yes == 0 and atmOut.no == 0:\n botMessage = botMessage + \"We don't have any information about \" + atmOut.getLocation()\n else:\n botMessage = botMessage + atmOut.analyze()\n bot.send_message(message.chat.id, botMessage)\n show_check(message.chat.id)\n\n@bot.message_handler(func = lambda message : message.text == 'Update')\ndef send_update(message):\n show_update(message.chat.id)\n\n@bot.message_handler(func = lambda message : message.text == 'ATM in SDU' or \n message.text == 'ATM outside SDU')\ndef send_workingUpdate(message): \n if message.text == 'ATM in SDU':\n atmIn.setGonnaUpdate(True)\n else:\n atmOut.setGonnaUpdate(True)\n show_workingUpdate(message.chat.id)\n\n@bot.message_handler(func = lambda message : message.text == 'Yes' or\n message.text == 'No')\ndef send_workingUpdate(message): \n if message.text == 'Yes':\n if atmIn.isGonnaUpdate():\n atmIn.countYes()\n else:\n atmOut.countYes()\n show_billsUpdate(message.chat.id)\n else:\n if atmIn.isGonnaUpdate():\n atmIn.countNo()\n else:\n atmOut.countNo()\n send_back(message)\n\n@bot.message_handler(func = lambda message : message.text == '1000' or\n message.text == '2000' or\n message.text == '5000')\ndef send_billsUpdate(message):\n if atmIn.isGonnaUpdate():\n atmIn.setMinBill((int)(message.text))\n atmIn.setGonnaUpdate(False)\n else:\n atmOut.setMinBill((int)(message.text))\n atmOut.setGonnaUpdate(False)\n send_back(message)\n@bot.message_handler(func = lambda message: message.text == 'Back' or \n message.text == 'Exit')\ndef send_back(message):\n botMessage = \"Thank you for using our service!\\n\"\n botMessage = botMessage + \"Press Check or Update next time you use our bot!\"\n bot.send_message(message.chat.id, botMessage)\n show_atm(message.chat.id)\n\ndef show_start(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([\"ATM\"])\n keyboard.setRowWidth(1)\n botMessage = \"Press ATM\"\n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\ndef show_atm(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([\"Check\", \"Update\"])\n botMessage = \"What you want to do with ATM status?\"\n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\ndef show_check(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([\"Update\", \"Exit\"])\n botMessage = \"What you want to do next?\"\n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\ndef show_update(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([atmIn.getLocation(), atmOut.getLocation()])\n botMessage = \"Which ATM's status you want to update?\"\n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\ndef show_workingUpdate(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([\"Yes\", \"No\"])\n botMessage = \"Does it work?\"\n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\ndef show_billsUpdate(chat_id):\n keyboard = Keyboard()\n keyboard.addButtons([\"1000\", \"2000\", \"5000\", \"Back\"])\n botMessage = \"What is the minimum bill you got from ATM?\\n\"\n botMessage = botMessage + \"If you didn't get any cash, press Back button\" \n bot.send_message(chat_id, botMessage, reply_markup=keyboard.getResult())\n\nif __name__ == '__main__':\n facade.startBot()\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157863774","text":"# ESTA VAINA ESTA INCOMPLETA .. ES MAS NUNCA SE INICIÓ\n\n\nfrom time import sleep\nimport random\n\nseg_0 = [\"seg_0\", \"seg_0\", \"seg_0\"]\nseg_1 = [\"seg_1\", \"seg_1\", \"seg_1\"]\nseg_2 = [\"seg_2\", \"seg_2\", \"seg_2\"]\nseg_3 = [\"seg_3\", \"seg_3\", \"seg_3\"]\nseg_4 = [\"seg_4\", \"seg_4\", \"seg_4\"]\nseg_5 = [\"seg_5\", \"seg_5\", \"seg_5\"] \n\n\nwhile True:\n\twith open(\"random_frases.txt\", \"a\") as random_frases:\n\t\tprint(\"secont\")\n\nwhile x:\n\tprint(random.randint(1,3))\n\tsleep(0.5)\n","sub_path":"python_nateAcademy/sleep_and_ficheros.py","file_name":"sleep_and_ficheros.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295419497","text":"import pyscope\nimport json\nimport utils\nimport mission_control\nimport sys\n\ncrs_path = \"shares/asimov.prod.data/PublicPartner/ACDC/CompatAnalysisTeam/RQV/CompatReadinessSummary_V1.ss\"\nvc = \"vc://cosmos15/asimov.partner.compat/\"\nviews = {\n \"rrand\": \"Project-AND\",\n \"rrdesktop\": \"AMD64_X86\"\n}\nmission_control_client = mission_control.Client()\n\n\ndef get_latest_sdata(byod_root_path=\"shares/asimov.prod.data/PublicPartner/Staging/Scenarios/BYOD/v1/Input/Compatibility\") -> pyscope.CosmosStream:\n \"\"\"Returns the latest SData stream in the BYOD root path\"\"\"\n return sorted(pyscope.dirstreams(byod_root_path, vc=vc, as_df=False, filter_folder=False), key=lambda x: x.CreateTime, reverse=True)[0]\n\n# sdata = get_latest_sdata()\n# crs = pyscope.get_stream_info(crs_path, vc=vc)\n# print(sdata.LocalPath)\n# print(crs.LocalPath)\n\n\n\nfor view, crs_area in views.items():\n print(f\"{view}: {crs_area}\")\n data_context = mission_control_client.get_data_context(view)\n\n print(json.dumps(data_context, indent=2))\n # print(data_context['measureGroupIds'])\n #mission_control_client.get_measure_ids(data_context)\n\n","sub_path":"python/ms-compat/rqv_monitor/rqv_monitor.py","file_name":"rqv_monitor.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"642025134","text":"#\n# @lc app=leetcode id=58 lang=python3\n#\n# [58] Length of Last Word\n#\nclass Solution:\n def lengthOfLastWord(self, s: str) -> int:\n List = s.split(\" \")\n i = 1\n while i < len(List) + 1:\n if len(List[-1*i]) != 0:\n return len(List[-1*i])\n else:\n i += 1\n return 0\n","sub_path":"58.length-of-last-word.py","file_name":"58.length-of-last-word.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303663904","text":"from datetime import datetime\n\ndef missedClasses(year, daysOfTheWeek, holidays):\n def cvt(d):\n return map(int, d.split('-'))\n\n holidays = map(cvt, holidays)\n ans = 0\n for mo, day in holidays:\n x = datetime(year + (mo < 6), mo, day)\n if x.isoweekday() in daysOfTheWeek: ans += 1\n return ans\n","sub_path":"arcade/the-core/time-river/missedClasses.py","file_name":"missedClasses.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"553482847","text":"from socket import *\nimport argparse\n\ndef cliente(ip,port):\n\tserverName = ip\n\tserverPort = port\n\tclientSocket = socket(AF_INET, SOCK_STREAM)\n\tclientSocket.connect((serverName, serverPort))\n\twhile 1:\n\t\tsentence = \"\"\n\n\t\twhile sentence != \"salir\":\n\t\t\tprint (\"Ingrese un mensaje o salir para terminar\")\n\t\t\tsentence = input(\"Ingrese el mensaje:\")\n\t\t\tclientSocket.send(sentence.encode())\n\t\t\tmodifiedSentence = clientSocket.recv(2048)\n\t\t\tprint (\"Recibido del servidor:\", modifiedSentence.decode())\n\t\t\t\n\t\tclientSocket.send(sentence.encode())\n\t\tclientSocket.close()\n\t\tbreak\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Conexion del Cliente al Servidor')\n\tparser.add_argument('--ip',help='Ip para conectar al servidor', default= \"127.0.0.1\")\n\tparser.add_argument('--port',help='Puerto para conectar al servidor' , type= int, default= 12000)\n\n\targs= parser.parse_args()\n\tclient=cliente(args.ip,args.port)\nmain()\n","sub_path":"LABORATORIO-Nº1/TCPClient.py","file_name":"TCPClient.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"84208594","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom geometry_msgs.msg import PointStamped, PointStamped, Twist\nfrom std_msgs.msg import Header\nfrom neato_node.msg import Bump\nfrom sensor_msgs.msg import LaserScan\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport statistics\nimport time, numpy, math, rospy\n\nclass ChangeState(object):\n \"\"\"state switching between wall following and obstacle avoidance. The state\n starts with avoiding obstacles until RANSAC finds a group of points that\n suitably fit a wall, which switches the state to wall following.\"\"\"\n\n def __init__(self):\n # initialize ROS things - subs/pubs/etc.\n rospy.init_node(\"AvoidObject\")\n self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n rospy.Subscriber('/scan', LaserScan, self.process_scan)\n rospy.Subscriber('/bump', Bump, self.process_bump)\n\n self.stop = self.make_twist(0,0) # pre-made stop message\n self.xs = None # list of all xs from lidar\n self.ys = None # all ys from lidar\n self.go = True # used to watch the bump sensor\n\n def make_twist(self, x, theta):\n \"\"\" Takes x and angular velocity and creates the appropriate twist\n to publish to the cmd_vel topic.\"\"\"\n send = Twist()\n send.linear.x = x\n send.linear.y = 0\n send.linear.z = 0\n send.angular.x = 0\n send.angular.y = 0\n send.angular.z = theta\n return send\n\n def show_plot(self):\n \"\"\"plot all lidar points and the neato in the neato ref frame\"\"\"\n plt.plot(self.xs, self.ys, 'ro')\n plt.plot(0,0, 'bo', markersize=15)\n #plt.show()\n\n def process_scan(self, m):\n \"\"\"callback function triggered on the laser scan subscriber. cleans out\n all 0 values and only logs points within a range.\"\"\"\n max_r = 1.5\n ranges = m.ranges\n xs = []\n ys = []\n xsf = []\n ysf = []\n for i in range(len(ranges)):\n if ranges[i] != 0 and ranges[i] .15 and count > 0:\n break\n\n if count > maxcount:\n maxcount = count # check number of points in the line\n final_slope = slope\n final_b = b\n\n return final_slope, final_b, maxcount\n\n def turn(self, a):\n \"\"\"turns a specified angle, a is angle in degrees.\"\"\"\n angle_vel = 28.23 # degrees per second, experimentally timed\n turn_time = math.fabs(a/28.23)\n dir = numpy.sign(a)\n twist = self.make_twist(0, .5*dir)\n start = datetime.now()\n self.pub.publish(twist)\n time.sleep(turn_time)\n\n self.pub.publish(self.stop)\n\n def move_dist(self, distance):\n \"\"\"takes a distance in meters and moves it forward. Works under the\n experimental timing that 0.5 cmd_vel = 1 ft/s.\"\"\"\n speed = 0.5\n m2ft = 0.3048\n dist_ft = distance/m2ft\n sec = dist_ft\n start = datetime.now()\n go = self.make_twist(speed, 0)\n self.pub.publish(go) # send go for specified time\n time.sleep(sec)\n\n self.pub.publish(self.stop)\n\n def turn_theta(self, slope):\n \"\"\"takes a wall slope from RANSAC, calculates angle difference between\n the the wall and the robots heading. Turns and drives robot.\"\"\"\n\n if slope != None:\n if math.fabs(slope)>0:\n theta_r = math.atan(1/slope)\n theta_d = -math.degrees(theta_r)\n self.turn(theta_d) # required angle to turn (degrees)\n self.move_dist(0.25) # move forward some arbitrary amount.\n\n def drive_to_target(self, r, t):\n \"\"\"proportional control for driving a robot towards a goal point in\n polar coordinates. Experiemtnally tuned Kp values.\"\"\"\n goal_d = 0 # desired distance away from target\n goal_t = 0 # desired angle away from goal, 0 to face target\n\n err_d = r - goal_d # error terms\n err_t = t - goal_t\n\n kp_d = 0.005 # proportional control constants\n kp_t = 0.01\n\n x_vel = kp_d*err_d # velocities to send\n t_vel = kp_t*err_t\n\n send = self.make_twist(x_vel, t_vel)\n self.pub.publish(send)\n\n def run(self):\n \"\"\"main run loop for the node. Checks that the first laser scan has\n instantiated the first list of points and also that the scan didn't\n yield an empty list, meaning the robot is in empty space.\"\"\"\n while self.go:\n if isinstance(self.xs, list) and len(self.xs)!=0:\n slope, intercept, maxcount = self.ransac(self.xs, self.ys)\n\n if maxcount > 40: # if sufficient match to best RANSAC line\n self.turn_theta(slope)\n else: # else run obstacle avoidance\n t_x, t_y = self.points_to_vector(self.xs, self.ys, 1, .2)\n r, theta = self.cart_to_polar(t_x, t_y)\n self.drive_to_target(r, theta)\n\n self.pub.publish(self.stop) # break run loop, if bump sensor is hit\n\nif __name__ == '__main__':\n node = ChangeState()\n node.run()\n","sub_path":"warmup_project/change_state.py","file_name":"change_state.py","file_ext":"py","file_size_in_byte":8712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"321794380","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom skimage import data, io\nfrom skimage.feature import match_template\nfrom Tools import config as cfg\n\n#image = data.coins()\n#coin = image[170:220, 75:130]\n\nimage = io.imread(cfg.imagePath, as_grey=True)\npatch = image[424:524, 187:287]\n\nresult = match_template(image, patch, pad_input=True)\nij = np.unravel_index(np.argmax(result), result.shape)\nx, y = ij[::-1]\nprint(x,y)\n\n\nfig = plt.figure(figsize=(8, 3))\nax1 = plt.subplot(1, 3, 1)\nax2 = plt.subplot(1, 3, 2, adjustable='box-forced')\nax3 = plt.subplot(1, 3, 3, sharex=ax2, sharey=ax2, adjustable='box-forced')\n\nax1.imshow(patch, cmap=plt.cm.gray)\nax1.set_axis_off()\nax1.set_title('template')\n\nax2.imshow(image, cmap=plt.cm.gray)\nax2.set_axis_off()\nax2.set_title('image')\n# highlight matched region\nhpatch, wpatch = patch.shape\nrect = plt.Rectangle((x-wpatch/2, y-hpatch/2), wpatch, hpatch, edgecolor='r', facecolor='none')\nax2.add_patch(rect)\n\nax3.imshow(result, cmap=plt.cm.gray)\nax3.set_axis_off()\nax3.set_title('match_template\\nresult')\n# highlight matched region\nax3.autoscale(False)\nax3.plot(x, y, 'o', markeredgecolor='r', markerfacecolor='none', markersize=10)\n\nplt.show()\n","sub_path":"template_matching.py","file_name":"template_matching.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"644436798","text":"from django.core.management.base import BaseCommand\nfrom PIL import Image as im\nimport numpy as np\nfrom ImageViewer.models import Screen_Image, Image\nfrom django.db.models import Q\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n for ScrImg in Screen_Image.objects.filter(~Q(screen__marker__name=\"Sac6\")).filter(pixel_max=None):\n marker = ScrImg.screen.marker.name\n path = ScrImg.image.full_path\n img_type = ScrImg.image.img_type\n flex = im.open(path)\n if marker=='Hta2' or marker=='SKL':\n if (img_type==Image.TYPE_SEPARATE_FIELD):\n flex.seek(1)\n pmax = np.array(flex).max()\n elif img_type==Image.TYPE_MULTI_FIELD:\n pmax = []\n for i in range(1,8,2):\n try:\n flex.seek(i)\n pmax_val = np.array(flex).max()\n except (EOFError, SyntaxError):\n pmax_val =\"Undefined\"\n pmax.append(pmax_val)\n else:\n if (img_type==Image.TYPE_SEPARATE_FIELD):\n pmax = np.array(flex).max()\n elif img_type==Image.TYPE_MULTI_FIELD:\n pmax = []\n for i in range(0,8,2):\n try:\n flex.seek(i)\n pmax_val = np.array(flex).max()\n except (EOFError, SyntaxError):\n pmax_val =\"Undefined\"\n pmax.append(pmax_val)\n ScrImg.pixel_max = pmax\n ScrImg.save()\n print(\"Added pmax value %s for %s\" %(pmax,ScrImg))\n print(\"Done\")","sub_path":"ImageViewer/management/commands/add_pmax_info.py","file_name":"add_pmax_info.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"107330484","text":"from BeautifulSoup import BeautifulSoup\nimport urllib2\nimport re\n\ndef findsongs(site):\n\tresult = {}\n\thtml_page = urllib2.urlopen(site)\n\tsoup = BeautifulSoup(html_page)\n\tfor link in soup.findAll('a', attrs={'href': re.compile(\"^http://\")}):\n\t\threffound = link.get('href')\n\t\tif hreffound:\n\t\t\tif (hreffound.find(\"youtube.com\") > -1) or (hreffound.find(\"soundcloud.com\") > -1) or (hreffound.find(\"vimeo.com\") > -1):\n\t\t\t\tif link.text:\n\t\t\t\t\tresult[link.text] = hreffound\n\t\n\treturn result\t\t\t\t\n\nif __name__ == '__main__':\n\tfindsongs()\n\n","sub_path":"lib/findLinks.py","file_name":"findLinks.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"81848380","text":"print(__file__)\n\n# ensure Python 3.5+\nimport sys\nreq_version = (3,5)\ncur_version = sys.version_info\nif cur_version < req_version:\n msg = 'Requires Python 3.5+ with BlueSky packages\\n'\n msg += 'found: ' + sys.version\n msg += '\\nfrom directory: ' + sys.prefix\n msg += '\\n'*2\n msg += 'You should type `exit` now and find the ipython with BlueSky'\n raise RuntimeError(msg)\n","sub_path":"startup/00-0-check-minimum-python3-running.py","file_name":"00-0-check-minimum-python3-running.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"266490096","text":"\"\"\"\nFollow up for \"Unique Paths\":\n\nNow consider if some obstacles are added to the grids. How many unique paths would there be?\n\nAn obstacle and empty space is marked as 1 and 0 respectively in the grid.\n\nFor example,\nThere is one obstacle in the middle of a 3x3 grid as illustrated below.\n\n[\n [0,0,0],\n [0,1,0],\n [0,0,0]\n]\nThe total number of unique paths is 2.\n\nNote: m and n will be at most 100.\n\"\"\"\nclass Solution:\n # @param {integer[][]} obstacleGrid\n # @return {integer}\n def uniquePathsWithObstacles(self, obstacleGrid):\n if len(obstacleGrid) == 0:\n return 0\n r, c = len(obstacleGrid), len(obstacleGrid[0])\n mat = [[0] * (c + 1)] * (r + 1)\n mat[0][1] = 1\n for i in range(1, r + 1):\n for j in range(1, c + 1):\n if obstacleGrid[i - 1][j - 1] == 1:\n mat[i][j] = 0\n else:\n mat[i][j] = mat[i - 1][j] + mat[i][j - 1]\n return mat[r][c]","sub_path":"unique_path_II.py","file_name":"unique_path_II.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"258828250","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 2 14:04:08 2019\n\n@author: user\n\"\"\"\nimport random\nimport torch\nimport torch.nn as nn\nimport csv\nimport pandas as pd\nimport numpy as np\nimport torch.utils.data as data\nfrom torch.autograd import Variable\n\n\nclass FaceLandmarksDataset(data.Dataset):\n\t\"\"\"Face Landmarks dataset.\"\"\"\n\tdef __init__(self, csv_file,symbol,upsample):\n\t\t\"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n\t\tself.landmarks_frame = pd.read_csv(csv_file)\n\t\tself.symbol = symbol\n\t\tself.upsample = upsample\n\tdef __len__(self):\n\t\t#print len(self.landmarks_frame)\n\t\treturn len(self.landmarks_frame)\n\t\t#return 6\n\tdef __getitem__(self, idx): \n\n\t\tlandmarks = self.landmarks_frame.iloc[idx,:].as_matrix() \n\t\tind = np.reshape(landmarks,(-1,self.symbol*self.upsample*3+1)) #### \n\t\tlabel_ind = ind[0,0] \n\t\tlabel_ind = int(label_ind) \n\t\tlabel = label_ind\n#\t\tlabel = np.zeros([1,8])\n#\t\tlabel[0,label_ind] =1\n#\t\tlabel = np.reshape(label,(8)) \n#\t\tlabel = torch.from_numpy(label)\n \n\t\tBRGBR = ind[0,1:]\n\t\tBRGBR = np.reshape(BRGBR, (self.symbol*self.upsample,3)) ###\n\t\tB_temp = BRGBR[:,2]\n\t\tB_temp = np.reshape(B_temp, (self.symbol*self.upsample,1))###\n\t\tR_temp = BRGBR[:,0]\n\t\tR_temp = np.reshape(R_temp, (self.symbol*self.upsample,1))###\n\t\tBRGBR = np.hstack((B_temp,BRGBR,R_temp))\n\t\tBRGBR = np.reshape(BRGBR,(-1,self.symbol*self.upsample,5)) ### \n\t\tBRGBR = torch.from_numpy(BRGBR)\n\t\tsample = {'BRGBR':BRGBR,'label':label}\n\t\treturn sample\n \nclass CNN(nn.Module):\n def __init__(self,symbol,upsample):\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential( # input shape (1, 27, 5)\n nn.Conv2d(\n in_channels=1, # input height\n out_channels=5, # n_filters\n kernel_size=3, # filter size\n stride=1, # filter movement/step\n padding=1, # 如果想要 con2d 出来的图片长宽没有变化, padding=(kernel_size-1)/2 当 stride=1\n ), # output shape (10, 25, 3)\n nn.ReLU(), # activation\n nn.BatchNorm2d(5)\n # nn.MaxPool2d(kernel_size=2), # 在 2x2 空间里向下采样, output shape (16, 14, 14)\n )\n self.conv2 = nn.Sequential( # input shape (10, 25, 3)\n nn.Conv2d(\n in_channels=5, \n out_channels=3, \n kernel_size=(5,5), \n stride=1, \n padding=2\n ), # output shape (5, 25, 3)\n nn.ReLU(), # activation\n nn.BatchNorm2d(3)\n # nn.MaxPool2d(kernel_size=2), # output shape (32, 7, 7)\n ) \n self.out1 = nn.Sequential(\n nn.Linear(3 * (symbol*upsample) * 5, 8),\n nn.ReLU(),\n# nn.Linear(25, 8),\n# nn.ReLU()\n )\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n #x = self.conv3(x)\n x = x.view(x.size(0), -1) # 展平多维的卷积图成 (batch_size, 32 * 7 * 7)\n x = self.out1(x)\n# x = self.out2(x)\n# x = self.out3(x)\n# x = self.out4(x)\n #x = self.out2(x)\n #nn.ReLU()\n #output = self.out3(x)\n output = x\n return output\n\nsymbol = 5\nupsample =3\nsampleRate = 32\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# Initialize model\nmodel = CNN(symbol,upsample)\nmodel = model.to(device)\n\n\n\n#criterion = torch.nn.MSELoss(reduction='sum')\ncriterion = torch.nn.CrossEntropyLoss()\nlr_temp=1e-2\nlr_temp_init = 1e-2\nmomentum_temp=0.7\noptimizer = torch.optim.Adam(model.parameters(), lr=lr_temp, betas=(0.9, 0.999), eps=1e-08,)\n#optimizer = torch.optim.SGD(model.parameters(), lr=lr_temp, weight_decay = 1e-5) #, momentum=0.9\n\n\n\n################################################## retrain\n#filename = 'F:/programming/ML in OCC/Final test/'+str(sampleRate)+'k regular/modelb_'+str(symbol)+'_'+str(upsample)+'.pkl'\t \n#model.load_state_dict(torch.load(filename))\n#optimizer = torch.optim.SGD(model.parameters(), lr=1e-5, momentum=0.3) #, momentum=0.9\n \n\n\n\nfilename = './class_train_5_3_32_1range.csv'\ndataset = FaceLandmarksDataset(filename,symbol,upsample)\ntrain_loader = torch.utils.data.DataLoader(dataset, batch_size=159, shuffle=True)\nepochnum = 40\nloss_b = 50\nloss_save=[]\nfor i in range(epochnum):\n for t, data in enumerate(train_loader):\n #print (data)\n inputs,label = Variable(data['BRGBR']),Variable(data['label'])\n inputs = inputs.to(device, dtype=torch.float32)\n label = label.to(device,dtype=torch.long)\n \n\n outputs = model(inputs)\n loss = criterion(outputs,label)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if t==0: \n print(i, loss.item())\n loss_save.append(loss.item())\n if loss.item() 0.8:\n return \"This game has barely just begun. There are still \" + str(3**vac_count) + \"games that could be played, roughly\"\n elif (static_val < 0.8*last_results[0] and current_state.whose_turn == 'B') or (static_val > 0.8*last_results[0] and current_state.whose_turn == 'W'):\n return \"At first I thought I was in a good place, but now I am not so sure. I don't like what I see a few moves ahead.\"\n elif (last_results[0] < -200 and current_state.whose_turn == 'B') or (last_results[0] > 200 and current_state.whose_turn == 'W'):\n return \"This is not looking good for me. You're ahead on points, \" + str(abs(last_results[0])) + \" points according to my calculations.\"\n elif (last_results[0] > 200 and current_state.whose_turn == 'B') or (last_results[0] < -200 and current_state.whose_turn == 'W'):\n return \"I make this game look easy! According to my calculations, I am \" + str(abs(last_results[0])) + \" points ahead!\"\n else:\n rhymes = {'0':\"zero is my hero\", '1':\"one is so much fun\", '2':\"oh two boo hoo\", '3':\"three is good for me\", '4':\"four is more\", '5':\"five is alive\", '6':\"six just don't mix\", '7':\"seven is heaven\", '8':\"eight is fate\", '9':\"nine is just fine\"}\n left = \", \".join([rhymes[digit] for digit in str(last_results[4][0])])\n right = \", \".join([rhymes[digit] for digit in str(last_results[4][1])])\n return left + \" but \" + right\n\n\n\n\ndef moniker():\n return \"Squarepants\" # Return your agent's short nickname here.\n\ndef who_am_i():\n return '''\n My name is Spongebob Squarepants. I just wanted to thank zmcnulty\n for bringing me here today. Let's show the NFL how its done.\n This one is for Stephen Hillenburg.\n\n The winner takes all\n It's the thrill of one more kill\n The last one to fall\n Will never sacrifice their will\n Don't ever look back\n On the wind closing in\n The only attack\n Were their wings on the wind\n Oh the daydream begins\n And it's sweet, sweet, sweet victory, yeah!\n And it's ours for the taking\n It's ours for the fight\n In the sweet, sweet, sweet victory, yeah!\n And the world is last to fall\n\n\n '''\n# ONLY CALLED ON AT THE BEGINNING OF THE GAME!\ndef get_ready(initial_state, k, who_i_play, player2Nickname):\n\n # convert current state object to My_TTS_State\n global K, VACANCIES\n K = k\n\n initial_state.__class__ = My_TTS_State\n # do any prep, like eval pre-calculation, here.\n # find blocked and vacant squares?\n if USE_DEFAULT_ORDERING:\n VACANCIES = initial_state.get_vacancies_default()\n else:\n VACANCIES = initial_state.get_vacancies()\n\n # create Zobrist hash table for each state?\n\n return \"OK\"\n\n# The following is a skeleton for the function called parameterized_minimax,\n# which should be a top-level function in each agent file.\n# A tester or an autograder may do something like\n# import ABC_TTS_agent as player, call get_ready(),\n# and then it will be able to call tryout using something like this:\n# results = player.parameterized_minimax(**kwargs)\n\n# TODO: implement a more optimal ordering for search rather\n# than the default which is used ALWAYS\ndef parameterized_minimax(\n current_state=None,\n use_iterative_deepening_and_time = False,\n max_ply=2,\n use_default_move_ordering = False,\n alpha_beta=False, \n time_limit=1.0,\n use_custom_static_eval_function=False):\n\n # All students, add code to replace these default\n # values with correct values from your agent (either here or below).\n current_state_static_val = -1000.0\n n_states_expanded = 0\n n_static_evals_performed = 0\n max_depth_reached = 0 #NOTE: for max depth, what are we counting? max depth reached or max layer fully explored\n n_ab_cutoffs = 0\n\n # MY CODE!\n\n\n # use my custom static eval function if told so\n global USE_CUSTOM_STATIC_EVAL_FUNCTION\n USE_CUSTOM_STATIC_EVAL_FUNCTION = use_custom_static_eval_function\n\n # use my custom TTS state object\n current_state.__class__ = My_TTS_State\n\n # get all the open squares.\n if use_default_move_ordering:\n vacancies = current_state.get_vacancies_default()\n else:\n vacancies = current_state.get_vacancies()\n\n if use_iterative_deepening_and_time:\n # give a bit of time for program to finish up so we dont exceed time limit\n time_buffer = 0.01\n start_time = time.time()\n time_limit = time_limit - time_buffer\n\n max_depth = -1\n\n #NOTE: assume max_ply is < actually max depth of the system?\n while max_depth <= max_ply and time.time() - start_time < time_limit:\n\n # results = [current_state static eval, n_states expanded, n static evals, n ab cutoffs]\n # returns None if ran out of time\n max_depth += 1\n\n # begin search at last layer previously explored.\n # save this for above; initial_open = [state for state in DEPTHS if DEPTHS[state] == max_depth - 1]\n\n # UNLIKE our hw2, if we find a state that is 5 moves away, there is no\n # way for us to reach that state in less than 5 moves so we do not have to worry about\n # rexpanding given states (save that for later\n\n dfs_results = DFS(current_state, vacancies, max_depth, use_default_move_ordering, alpha_beta, time_limit - (time.time() - start_time))\n \n if dfs_results != None: # DFS returns None if it is running out of time\n current_state_static_val = dfs_results[0]\n n_states_expanded += dfs_results[1]\n n_static_evals_performed += dfs_results[2]\n n_ab_cutoffs += dfs_results[3]\n \n \n max_depth_reached = max_depth - 1 # NOTE: max depth reached or max depth fully explored (i chose latter)?\n else: \n # just run DFS with the max depth starting at the max_ply, and an unreasonably high time limt\n # so that its not an issue.\n dfs_results = DFS(current_state, vacancies, max_ply, use_default_move_ordering, alpha_beta)\n\n current_state_static_val = dfs_results[0]\n n_states_expanded += dfs_results[1]\n n_static_evals_performed += dfs_results[2]\n n_ab_cutoffs += dfs_results[3]\n print(dfs_results[4])\n max_depth_reached = min(max_ply, len(vacancies)) #TODO: is the any reason not to do this?\n\n\n # Prepare to return the results, don't change the order of the results\n results = []\n results.append(current_state_static_val)\n results.append(n_states_expanded)\n results.append(n_static_evals_performed)\n results.append(max_depth_reached)\n results.append(n_ab_cutoffs)\n # Actually return the list of all results...\n return(results)\n\ndef DFS(current_state, vacancies, max_depth, use_default_move_ordering, alpha_beta, time_limit = 10**8, alpha = -10**8, beta = 10**8):\n start_time = time.time()\n\n states_expanded = 0\n static_evals = 0\n num_ab_cutoffs = 0\n\n # check whose turn it is; set the initial value v of the given state\n who = current_state.whose_turn\n if who == 'B':\n current_state_static_val = 10**8\n else:\n current_state_static_val = -10**8\n\n\n\n # if we dont have any time left\n if time.time() - start_time > time_limit: \n return None\n\n #NOTE: do we want to count the latter case where the board is full as expanding a state??? NO see piazza\n # else if we are at the max depth/no moves are left calculate the static evaluation function\n # check if it is a state we already calculated in ZOBRIST_HASHES\n elif max_depth == 0 or len(vacancies) == 0:\n static_evals = 1\n zhash = current_state.zobrist_hash()\n if zhash in ZOBRIST_HASHES:\n current_state_static_val = ZOBRIST_HASHES[zhash]\n else:\n current_state_static_val = current_state.static_eval()\n ZOBRIST_HASHES[zhash] = current_state_static_val\n\n return [current_state_static_val, states_expanded, static_evals, num_ab_cutoffs, None]\n\n # else expand the state and look more moves ahead \n else:\n best_move = None\n states_expanded += 1\n # for each possible vacancy/move:\n # make a new board after making that move\n # swap whose turn it is\n # Run DFS on the new board.\n for n, (i,j) in enumerate(vacancies):\n new_state = My_TTS_State(current_state.board)\n new_state.board[i][j] = who\n\n # calculate the alpha beta values for a given node\n if who == 'B':\n new_state.whose_turn = 'W'\n beta = min(beta, current_state_static_val)\n else:\n new_state.whose_turn = 'B'\n alpha = max(alpha, current_state_static_val)\n\n # check if we can prune the subtree\n if alpha_beta and beta <= alpha:\n num_ab_cutoffs += 1\n\n # NOTE: do I want to count the number of times I realize a cut can be made, or the number\n # of subtrees that are cut off. In this case, the two our different because each node\n # often has many more than two children\n #num_ab_cutoffs += len(vacancies) - n \n break\n\n # if we cannot prune the subtree, traverse down it\n else:\n new_vacancies = [v for v in vacancies if not v == (i,j)]\n results = DFS(new_state, new_vacancies, max_depth - 1, use_default_move_ordering, alpha_beta=alpha_beta, time_limit=time_limit - (time.time() - start_time), alpha=alpha, beta=beta)\n\n if results == None: # we are running out of time!\n return None\n\n # black is minimizer so they will choose the child with LOWEST static eval\n if who == 'B': \n if results[0] < current_state_static_val:\n current_state_static_val = results[0]\n best_move = (i,j)\n\n else: # white is maximizer\n if results[0] > current_state_static_val:\n current_state_static_val = results[0]\n best_move = (i,j)\n \n states_expanded += results[1]\n static_evals += results[2]\n num_ab_cutoffs += results[3]\n\n\n return [current_state_static_val, states_expanded, static_evals, num_ab_cutoffs, best_move]\n\n\n\n\n\n# ======================================================== Testing Code\n\n'''\n\nK = 3\ninital_board = \\\n [['W', '-', '-', '-'],\n ['-', '-', '-', '-'],\n ['-', '-', '-', '-'],\n [' ', '-', 'B', '-']]\n\ninit_state = My_TTS_State(inital_board)\ninit_state.whose_turn = 'B'\n\n#print(\"static_eval: \", init_state.static_eval())\n\n\n#start = time.time()\n#print(\"[current_state_static_val, n_states_expanded, static evals, max_depth, num_ab cutoffs ]:\", parameterized_minimax(init_state, use_iterative_deepening_and_time = True, max_ply = 10, alpha_beta=True, time_limit = 1))\n#print(time.time() - start)\nstart = time.time()\nprint(\"eval, expand, eval count, max depth, ab cuts:\", \\\n parameterized_minimax(init_state, \n use_iterative_deepening_and_time = False, \n max_ply = 10, \n alpha_beta=True,\n use_custom_static_eval_function =False , use_default_move_ordering=True))\nprint(time.time() - start)\n'''\n","sub_path":"hw/hw4/a4_starter_code/zmcnulty_TTS_agent.py","file_name":"zmcnulty_TTS_agent.py","file_ext":"py","file_size_in_byte":18441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"2487549","text":"class Dependence:\n __modules = []\n\n @staticmethod\n def append(module_name: str):\n if isinstance(module_name, str):\n Dependence.__modules.append(module_name)\n else:\n raise Exception(\"Wrong type for append function!\")\n\n @staticmethod\n def install(package):\n import subprocess\n subprocess.call(['pip', 'install', package])\n\n @staticmethod\n def init():\n for module in Dependence.__modules:\n Dependence.install(module)\n\nif __name__ == '__main__':\n Dependence.append('pyTelegramBotAPI')\n Dependence.append('psutil')\n Dependence.append('keyboard')\n Dependence.init()","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"380552170","text":"#$Revision: 1.6 $ example.py\n#------------------------------------------------------------------------------\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Demo\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source(\"PoolSource\",\n\t\t\t\t\t\t\tfileNames =\n\t\t\t\t\t\t\tcms.untracked.vstring(\"file:pat.root\"\n\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t)\n#-------------------------------------------------------------------------\n# Created: Sun Feb 7 22:35:29 2010 by mkntuplecfi.py\n# $Revison:$\n#-------------------------------------------------------------------------\nprocess.demo =\\\ncms.EDAnalyzer(\"TheNtupleMaker\",\n\n\t\t\t # Name of output n-tuple\n ntupleName = cms.untracked.string(\"ntuple_pat.root\"),\n\n\t\t\t # List of buffers to allocate.\n\t\t\t #----------------------------------------------------------\n\t\t\t # The names in \"buffers\" are arbitrary so long as each agrees\n\t\t\t # with the name of a vstring block. For example, since the\n\t\t\t # vstring \"buffers\" contains the name \"recoBeamSpot\", the code\n\t\t\t # expects a vstring block of that name to exist.\n\t\t\t # However, the names within a vstring block, for example,\n\t\t\t # edmEventHelper, must correspond to a Buffer plugin.\n\t\t\t # (See plugins.cc and userplugins.cc in the plugins dir.)\n\t\t\t #----------------------------------------------------------\n buffers =\n cms.untracked.\n vstring(\n\t'edmEventHelper',\n\t'GenEventInfoProduct',\n 'GenRunInfoProduct',\n 'recoBeamSpot',\n\t'patMET',\n 'patMuon',\n \t'patElectron',\n\t'recoGenParticle',\n \t'recoGenParticleHelper',\n \t'edmTriggerResultsHelper'\n ),\n\t\t\t #----------------------------------------------------------\n\t\t\t # Format of 1st line:\n\t\t\t # buffer-name getByLabel maximum-count\n\t\t\t #\n\t\t\t # Format of subsequent lines:\n\t\t\t # [return-type] method [alias]\n\t\t\t #----------------------------------------------------------\n edmEventHelper =\n cms.untracked.\n vstring(\n 'edmEventHelper info',\n #---------------------------------------------------------------------\n\t' bool isRealData()',\n ' int run()',\n\t' int event()',\n\t' int luminosityBlock()',\n\t' int bunchCrossing()'\n ),\t\t\t\t \n GenEventInfoProduct =\n cms.untracked.\n vstring(\n 'GenEventInfoProduct generator 1',\n #---------------------------------------------------------------------\n ' double weight()'\n ),\n GenRunInfoProduct =\n cms.untracked.\n vstring(\n 'GenRunInfoProduct generator 1',\n #---------------------------------------------------------------------\n ' double externalXSecLO().value()',\n ' double externalXSecNLO().value()',\n ' double filterEfficiency()',\n ' double internalXSec().value()'\n ),\t\t\t \n recoBeamSpot =\n cms.untracked.\n vstring(\n \"recoBeamSpot offlineBeamSpot 1\",\n #---------------------------------------------------------------------\n \" double x0()\",\n \" double y0()\",\n \" double z0()\"\n ),\n patMET =\n cms.untracked.\n vstring(\n \"patMET layer1METsAK5 50\",\n #---------------------------------------------------------------------\n \" double et()\",\n \" double phi()\",\n \" double pt()\"\n ),\n\n patMuon =\n cms.untracked.\n vstring(\n \"patMuon cleanLayer1Muons 50\",\n #---------------------------------------------------------------------\n \" int charge()\",\n \" double energy()\",\n \" double et()\",\n \" double eta()\",\n \" double p()\",\n \" double phi()\",\n \" double pt()\",\n \" float caloIso()\",\n \" float ecalIso()\",\n \" double ecalIsoDeposit()->candEnergy()\",\n \" float hcalIso()\",\n \" float trackIso()\",\n \" bool isCaloMuon()\",\n \" bool isGlobalMuon()\",\n \" bool isStandAloneMuon()\",\n \" bool isTrackerMuon()\"\n ),\n\n patElectron =\n cms.untracked.\n vstring(\n \"patElectron cleanLayer1Electrons 50\",\n #---------------------------------------------------------------------\n \" int charge()\",\n \" double energy()\",\n \" double et()\",\n \" double eta()\",\n \" double p()\",\n \" double phi()\",\n \" double pt()\",\n\t\" double gsfTrack()->d0()\",\n\t\" double gsfTrack()->phi()\"\n ),\n\n\t\t\t recoGenParticle =\n cms.untracked.\n vstring(\n \"recoGenParticle genParticles 4000\",\n #---------------------------------------------------------------------\n \" int charge()\",\n \" int pdgId()\",\n \" int status()\",\n \" double pt()\",\n \" double eta()\",\n \" double phi()\",\n \" double mass()\"\n\t),\n\t\t\t recoGenParticleHelper =\n cms.untracked.\n vstring(\n \"recoGenParticleHelper genParticles 4000\",\n #---------------------------------------------------------------------\n\t\" int firstMother()\",\n\t\" int lastMother()\",\n\t\" int firstDaughter()\",\n\t\" int lastDaughter()\"\n ),\n edmTriggerResultsHelper =\n cms.untracked.\n vstring(\n \"edmTriggerResultsHelper TriggerResults 1\",\n #---------------------------------------------------------------------\n ' bool value(\"HLT_L1Jet15\")',\n\t' bool value(\"HLT_Jet30\")',\n\t' bool value(\"HLT_Jet50\")',\n\t' bool value(\"HLT_Jet80\")',\n\t' bool value(\"HLT_Mu9\")'\n )\t\t\t \t\t\t \t\t\t \n )\n\nprocess.p = cms.Path(process.demo)\n","sub_path":"test/example_pat.py","file_name":"example_pat.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"64292530","text":"l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\r\nq = []\r\nsentence = eval(input(\"Enter a String\"))\r\nsentence.lower()\r\nprint(sentence)\r\nfor i in l:\r\n if(i in sentence):\r\n q.append(i)\r\nprint(q)\r\nif(q == l):\r\n print(\"It is a pangram\")\r\nelse:\r\n print(\"It is not a pangram\")\r\n\r\n","sub_path":"pangram.py","file_name":"pangram.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"102612759","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('TFG_APP', '0013_auto_20170619_1737'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='resultado',\n name='fecha',\n field=models.DateTimeField(verbose_name='date created', default=datetime.datetime(2017, 6, 24, 18, 19, 44, 472109, tzinfo=utc)),\n ),\n ]\n","sub_path":"TFG/TFG_APP/migrations/0014_auto_20170624_1919.py","file_name":"0014_auto_20170624_1919.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"398922685","text":"import pandas as pd\nimport numpy as np\nimport os\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import RFECV\nimport copy\n#importing user defined functions\nos.chdir(r'//Users//mac_air//Documents//Documents//Side Projects//Kaggle_Anomaly_Detection//Scripts')\nimport ads_creation as ads_crtn\nimport eda_analysis as eda\n\ndef create_lag_feature_placeholder(df,variable_name,lags):\n '''\n This function creates place holders for lagged variables in the ads\n \n Input:\n 1. df: pandas dataframe, this is the ads in which the column has to be made\n 2. variable_name: the column name based on which the lagged variable has to be made\n 3. lags: the list of lags for which the columns have to be made\n\n Returns:\n 1. df: pandas dataframe with the lag feature placeholders\n '''\n for lag in lags:\n df[variable_name + '_lag_' + str(lag)] = np.nan\n return df\n\ndef create_lag_feature(df,variable_name,lags):\n '''\n This function creates the lag features in the ads\n\n Input:\n 1. df: pandas dataframe, this is the ads in which the column has to be made\n 2. variable_name: the column name based on which the lagged variable has to be made\n 3. lags: the list of lags for which the columns have to be made\n\n Returns:\n 1. df: pandas dataframe with the lag feature placeholders\n '''\n for lag in lags:\n df[variable_name + '_lag_' + str(lag)] = df[variable_name].shift(lag)\n return df\n\ndef create_lagged_features(df,variable_list,lags_list,panel_id_col,date_col):\n '''\n Creates the lagged feature for the target variable\n\n Input\n 1. df: pandas dataframe, this is the ads in which the lagged columns are to be made\n 2. variable_list: list, the list of time series that need to be lagged\n 3. lags_list: list, the list of lags that will be applied onto the timeseries\n 4. panel_id_col: str, this is the name of the column that contains the panel IDs\n 5. date_col: str, this is the name of the column that contains the dates in the ads\n\n Returns:\n 1. df: pandas dataframe, this is the ads with all the lagging for all the variables done\n\n https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth\n '''\n #This step is being done because pandas dataframes are mutable and here since we are changing the dataframe object\n #some bugs are coming in so, just doing a deep copy to avoid that\n #the copy below breaks prevents the argument df that we received (train_df) value to get changed at source\n df = copy.deepcopy(df)\n #before the deep copy df was changing because in the first line in for loop we insert a column in df \n #this step happens before it is asigned back to df, so that is why this change is retained when we exit the function\n for variable in variable_list:\n df = create_lag_feature_placeholder(df,variable,lags_list)\n df = df.groupby(panel_id_col).apply(lambda x: create_lag_feature(x,variable,lags_list))\n df = df.dropna()\n df = df.reset_index(drop=True)\n df = df.sort_values(by=[panel_id_col, date_col],ignore_index=True)\n return df\n\ndef rfe_feature_selection(train_df,estimator,features,label,cv_folds=5):\n '''\n This function implements feature selection through rfecv\n\n Input\n 1. train_df: pandas dataframe, this is the training dataset\n 2. estimator: this is the initialized model objects that will be used for rfecv\n 3. features: list, this is the initial list of features from which the selection will happen\n 4. label: str, target variable\n 5. cv_folds: int, the number number cross validation folds to be created in each cycle of rfe\n\n Returns:\n 1. feature_set: list, this is the list of the most significant features found through rfecv\n '''\n scaler = StandardScaler()\n scaler.fit(train_df[features])\n\n train_df_scaled = scaler.transform(train_df[features])\n selector = RFECV(estimator, step=1, cv=cv_folds)\n selector = selector.fit(train_df_scaled, train_df[label])\n\n feature_set = [sel_feature[1] for sel_feature in zip(selector.ranking_,features) if sel_feature[0] == 1]\n \n return feature_set\n \nif __name__ == '__main__':\n #creating ads + outlier treatment\n ads = ads_crtn.create_ads()\n ads = ads.groupby('INVERTER_ID').apply(lambda x: eda.outlier_treatment(x,'INVERTER_ID'))\n\n #making ADS stationary\n non_stnry_invtr_list = eda.return_non_stnry_invtr_list(ads,'INVERTER_ID')\n ads = eda.make_ads_stnry(ads,non_stnry_invtr_list,'INVERTER_ID')\n\n #getting lag values for the target variables\n lag_values = ads[['INVERTER_ID','PER_TS_YIELD']].groupby('INVERTER_ID').agg(lambda x: eda.pick_pacf(x))\n distinct_lag_values = np.unique(lag_values.PER_TS_YIELD.sum())","sub_path":"Scripts/feature_engg.py","file_name":"feature_engg.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"322562469","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Aug 16 07:13:06 2020\r\n\r\n@author: Varun Bhaaskar\r\n\"\"\"\r\n\r\nfrom itertools import combinations\r\n\r\n\r\nN = int(input())\r\na = list(map(int,input().split()))\r\na.sort()\r\nlargest = len(bin(a[-1])) - 2\r\nresult = 0\r\n\r\ndef binaryEq(b):\r\n global result\r\n bi = []\r\n n1 = 0\r\n n0 = 0\r\n for x in b:\r\n z = bin(x).replace(\"0b\", \"\")\r\n #z = str(z)\r\n m = len(z)\r\n if (m != largest):\r\n dif = largest - m\r\n for q in range(dif):\r\n z = '0'+z\r\n \r\n bi.append(z)\r\n for p in bi:\r\n for l in p:\r\n if l=='0':\r\n n0 +=1\r\n else:\r\n n1 +=1\r\n print(b,bi,n0,n1)\r\n if (n1==n0):\r\n result += 1\r\n\r\nfor i in range(1,N+1):\r\n T = combinations(a, i)\r\n T = list(T)\r\n for y in T:\r\n y = list(y)\r\n binaryEq(y)\r\n\r\nresult = bin(result).replace(\"0b\",\"\")\r\nm = len(result)\r\nif (m != largest):\r\n dif = largest - m\r\n for q in range(dif):\r\n result = '0'+ result\r\n\r\nprint(result)\r\n\r\n\r\n ","sub_path":"binary equivalancy.py","file_name":"binary equivalancy.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"534153891","text":"import csv\nimport qrcode\nimport hashlib\n\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\n\nfilename = 'sample_data.csv'\nwith open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n for row in csv_reader:\n\n try:\n\n data = \"\"\n hash_encode_string = row[1].strip() + 'KingQueeN1' #KingQueeN1 is a password kind of stuff. \n print(hashlib.md5(hash_encode_string.encode('utf-8')).hexdigest())\n\n data = row[0].strip() + \"\\n\" + row[1].strip() + \"\\n\" + row[2].strip() + \"\\n\" + row[3].strip() + \"\\n\" + \\\n row[4].strip() + \"\\n\" + row[5].strip() + \"\\n\" + row[6].strip() + \"\\n\" + row[\n 7].strip() + \"\\n\" + row[8].strip() + \"\\n\" + hashlib.md5(hash_encode_string.encode('utf-8')).hexdigest()\n\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_H,\n box_size=10,\n border=2,\n )\n\n qr.add_data(data)\n qr.make(fit=True)\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n file_name = row[1].strip().split(' ')[0].title() + '_' + row[2] + '_PC' + '.png'\n image_file = open(file_name,\n 'wb') # will open the file, if file does not exist, it will be created and opened.\n img.save(image_file) # write qrcode encoded data to the image file.\n image_file.close() # close the opened file handler.\n except Exception as e:\n print(e)\n print(\"Error\")\n","sub_path":"PC Allocation/PC_allocation_QR.py","file_name":"PC_allocation_QR.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"635809232","text":"from flask import Flask\nfrom flask import Response, request\nfrom flask.ext.cors import CORS\nfrom flask.ext.pymongo import PyMongo\nfrom bson.json_util import dumps\nfrom bson.json_util import loads\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['MONGO_HOST'] = 'mongodb://192.168.33.10'\napp.config['MONGO_DBNAME'] = 'mydb'\n\n# connect to the mongo db\nmongo = PyMongo(app)\n\n@app.route('/prototypes', methods=['GET', 'POST'])\ndef prototypes():\n if request.method == 'POST':\n mongo.db.mycollection.insert({'title': request.form['title'], 'content': request.form['content']})\n return Response('{}', status=200, mimetype='application/json')\n else:\n result = mongo.db.mycollection.find()\n data = dumps(result)\n response = Response(data, status=200, mimetype='application/json')\n return response\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"385189944","text":"#!/usr/bin/env python\n# encoding: utf-8\nfrom __future__ import division\nfrom __future__ import print_function\n\"\"\"\n# @file khelper.py\n# @brief Extract file access data after build, modify CDT project configuration\n# (.cproject) accordingly\n# @copyright Copyright (C) 2016, Elphel.inc.\n# @param License\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n@author: Andrey Filippov\n@license: GPLv3.0+\n@contact: andrey@elphel.coml\n@deffield updated: Updated\n\"\"\"\n__author__ = \"Andrey Filippov\"\n__copyright__ = \"Copyright 2016, Elphel, Inc.\"\n__license__ = \"GPL\"\n__version__ = \"3.0+\"\n__maintainer__ = \"Andrey Filippov\"\n__email__ = \"andrey@elphel.com\"\n__status__ = \"Development\"\n\nimport sys\nimport os\nimport time\nimport xml.etree.ElementTree as ET\n'''\nTODO:Automate, find out why separate touch commands are needed\nRun this program twice:\n1-st run ./khelper.py linux -1\nand save shown timestamp\nThen run (some mystery here)\ntouch src/drivers/ata/ahci_elphel.c\ntouch src/drivers/elphel/sensor_common.c\nWait 5 seconds and run (in a different console with appropriate sourcing)\nbitbake linux-xlnx -c compile -f \nThen again\n./khelper.py linux \nIf somethong went wrong you will need to resore .cproject from eclipse_project_setup directory\n'''\ndef file_tree(flist): # Each file in list is a file, no directories\n ftree={}\n for p in flist:\n node = ftree\n seg_list=p.split(os.sep)\n last_i=len(seg_list)-1\n for i,segm in enumerate(seg_list):\n if not segm in node:\n if i == last_i:\n node[segm] = None\n else:\n node[segm] = {}\n node=node[segm] \n \n return ftree \n\ndef exclude_list(ftree, flist):\n mark = \"*\" # no file/dir name can be \"*\" \n def list_tree_recursive(root):\n rslt = []\n if not mark in root:\n return [[\"\"]] # convert to trailing \"/\" for directories\n for n in root:\n if not n == mark:\n if root[n] is None:\n rslt.append([n])\n else:\n \n for l in list_tree_recursive(root[n]):\n rslt.append([n]+l)\n return rslt\n \n ftree[mark]=None # mark top level dir \n for p in flist:\n node = ftree\n for segm in p.split(os.sep)[:-1]:\n node=node[segm]\n node[mark]=None # [mark] means used in flist\n del node[p.split(os.sep)[-1]]\n #print (ftree)\n# for k in ftree:\n# print(k) \n #Now prune unused directories\n #prune_recursive(ftree) # (assuming root is used)\n # now create list\n files_list_list = list_tree_recursive(ftree)\n# print (files_list_list)\n #converrt to file paths\n pl = []\n for l in files_list_list:\n pl.append(os.path.join(*(l[1:])))\n pl = sorted (pl)\n return pl \n \n \ndef proc_tree():\n DEBUG = True\n extensions = [\".h\",\".c\",\".cpp\"]\n exclude_start = [\"linux\"+os.sep+\"scripts\"+os.sep,\"linux\"+os.sep+\"source\"+os.sep+\"scripts\"+os.sep]\n delta_t = 3 # seconds\n try:\n root_path = sys.argv[1]\n except:\n print (\"Calling %s [timestamp]\"%(os.path.basename(sys.argv[0])))\n try:\n start_time = float(sys.argv[2])\n except:\n start_time = 0.0\n\n touch_files= start_time < 0.0 \n print (\"root_path = %s\"%(root_path))\n# root_path = \"/home/eyesis/git/poky/linux-elphel/linux/\" \n lstFiles = []\n # Append files to a list\n for path, _, files in os.walk(root_path, followlinks = True):\n for f in files:\n for ext in extensions:\n if f.endswith(ext):\n lstFiles.append(os.path.join(path, f))\n break\n \n all_tree= file_tree(sorted(lstFiles))\n include_lst=[] \n lst_a = []\n latest_at=0\n for p in lstFiles:\n if touch_files:\n if os.path.islink(p):\n os.utime(os.path.realpath(p), None)\n else: \n os.utime(p, None)\n else: \n# at = time.ctime(os.stat(p).st_atime)\n at = os.stat(p).st_atime\n l = None\n if os.path.islink(p):\n l = os.path.realpath(p)\n at = os.stat(l).st_atime\n latest_at = max((latest_at,at)) \n if at > (start_time + delta_t):\n #Scripts/lexers result in problems\n exclude=False\n for exStr in exclude_start:\n if p.startswith(exStr):\n exclude=True\n break\n if exclude:\n break \n #exclude_start\n lst_a.append([p,at,l])\n include_lst.append(p)\n if touch_files:\n print (len(lstFiles), \"last time = \", time.time())\n return \n \n excluding = exclude_list(all_tree, include_lst) \n# print (all_tree)\n# print (sorted(include_lst))\n# print (\"|\".join(excluding))\n if DEBUG: \n with open(\"all_sources.lst\",\"w\" ) as f:\n for p in sorted(lstFiles):\n at = os.stat(p).st_atime\n lnk=\"\"\n if os.path.islink(p):\n at = os.stat(os.path.realpath(p)).st_atime\n lnk = os.path.realpath(p)\n print (p,at,lnk, file=f)\n with open(\"excluding.lst\",\"w\" ) as f:\n for p in excluding:\n print (p, file=f)\n# include_tree= file_tree(sorted(include_lst))\n# print(include_tree)\n root_dir=include_lst[0].split(os.sep)[0]\n print (\"root_dir=\",root_dir)\n \n xml= ET.parse(\".cproject\")\n root=xml.getroot()\n# for child in root:\n# print(child.tag, child.attrib)\n\n for child in root.iter('sourceEntries'):\n for gchild in child:\n print(gchild.tag)\n \n for child in root.iter('sourceEntries'):\n for gchild in child:\n if gchild.tag == 'entry':\n attr = gchild.attrib\n try:\n if (attr['kind'] == 'sourcePath') and (attr['name'] == root_dir):\n child.remove (gchild)\n print (\"Removed existing entry \",gchild.tag)\n break\n except:\n print (\"error matching attributes for \",gchild.tag)\n pass\n break #after first 'sourceEntries' - should be just one? \n ET.SubElement(child, 'entry', {\"flags\":\"VALUE_WORKSPACE_PATH\", \"kind\":\"sourcePath\", \"name\":root_dir, \"excluding\":\"|\".join(excluding)})\n \n for child in root.iter('sourceEntries'):\n for gchild in child:\n print(gchild.tag)\n \n oneliner= ET.tostring(root)\n #overwrites original .cproject, may change to somethong different\n with open(\".cproject\", \"wr\") as f:\n f.write(\"\"\"\n\"\"\")\n f.write(oneliner)\n \n print (len(lstFiles), len(lst_a), \"last access time = \",latest_at)\n \nif __name__ == '__main__':\n proc_tree()","sub_path":"khelper.py","file_name":"khelper.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"58634098","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nimport collections\n\n# Complete the checkMagazine function below.\ndef checkMagazine(magazine, note):\n magDic = collections.Counter(magazine)\n noteDic = collections.Counter(note)\n for key in noteDic:\n if key not in magDic:\n print('No')\n return\n elif magDic[key] < noteDic[key]:\n print('No')\n return\n print('Yes')\n return\n\nif __name__ == '__main__':\n mn = input().split()\n\n m = int(mn[0])\n\n n = int(mn[1])\n\n magazine = input().rstrip().split()\n\n note = input().rstrip().split()\n\n checkMagazine(magazine, note)\n","sub_path":"HackerRank Interview Preparation Kit/Dictionaries and Hashmaps/Hash-Tables-Ransom-Note.py","file_name":"Hash-Tables-Ransom-Note.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"504173695","text":"import os\nImport(\"env\")\n\n# Relocate firmware from 0x08000000 to 0x08005000\nfor define in env['CPPDEFINES']:\n if define[0] == \"VECT_TAB_ADDR\":\n env['CPPDEFINES'].remove(define)\nenv['CPPDEFINES'].append((\"VECT_TAB_ADDR\", \"0x08005000\"))\n\ncustom_ld_script = os.path.abspath(\"buildroot/share/PlatformIO/ldscripts/fly_mini.ld\")\nfor i, flag in enumerate(env[\"LINKFLAGS\"]):\n if \"-Wl,-T\" in flag:\n env[\"LINKFLAGS\"][i] = \"-Wl,-T\" + custom_ld_script\n elif flag == \"-T\":\n env[\"LINKFLAGS\"][i + 1] = custom_ld_script\n\n","sub_path":"Marlin-2.0.x/buildroot/share/PlatformIO/scripts/fly_mini.py","file_name":"fly_mini.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"379363980","text":"#!usr/bin/python\n#coding:utf-8\n\nimport matplotlib.pyplot as plt\nimport knock_36\nfrom collections import defaultdict\n\nif __name__ == \"__main__\":\n dic = knock_36.freq()\n value_list = []\n count = 0\n for value in dic.values():\n value_list.append(value)\n\n plt.hist(value_list, bins = 200, range = (0, 20000))\n plt.show()\n\n\n","sub_path":"sekizawa4/knock_38.py","file_name":"knock_38.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"457436071","text":"\n\n# https://www.cnblogs.com/wgDream/p/7525966.html\nclass Node():\n def __init__(self, item):\n self.item = item\n self.next = None\n\n\nclass CycleLinkList():\n def __init__(self, node=None):\n self.__head = node\n\n def is_empty(self):\n return self.__head is None\n\n def length(self):\n if self.is_empty():\n return 0\n current = self.__head\n count = 1\n\n while current.next != self.__head:\n count += 1\n current = current.next\n return count\n\n def linklistPrint(self):\n if self.is_empty():\n print(\"\")\n return\n\n current = self.__head\n\n while current.next != self.__head:\n print(current.item, end = \" \")\n current = current.next\n\n print(current.item, end= \" \")\n print(\"\")\n\n def addBegin(self, item):\n node = Node(item)\n if self.is_empty():\n node.next = node\n self.__head = node\n else:\n cur = self.__head\n while cur.next != self.__head:\n cur = cur.next\n node.next = self.__head\n self.__head = node\n cur.next = node\n\n def append(self, item):\n node = Node(item)\n if self.is_empty():\n self.__head = node\n node.next = node\n else:\n cur = self.__head\n while cur.next != self.__head:\n cur = cur.next\n node.next = self.__head\n cur.next = node\n\n\n def insert(self, pos, item):\n if pos <= 0:\n self.addBegin(item)\n elif pos >= self.length():\n self.append(item)\n else:\n cur = self.__head\n count = 0\n while count < (pos-1):\n count += 1\n cur = cur.next\n node = Node(item)\n node.next = cur.next\n cur.next = node\n\n\n def remove(self, item):\n\n if self.is_empty():\n return\n cur = self.__head\n pre = None\n\n while cur.next != self.__head:\n if cur.item == item:\n if cur == self.__head:\n rel = self.__head\n while rel.next != self.__head:\n rel = rel.next\n self.__head = cur.next\n rel.next = self.__head\n else:\n pre.next = cur.next\n return\n pre = cur\n cur = cur.next\n\n if cur.item == item:\n if pre:\n pre.next = self.__head\n else:\n self.__head = None\n\n\n def search(self, item):\n cur = self.__head\n while cur.next != self.__head:\n if cur.item == item:\n return True\n cur = cur.next\n if cur.item == item:\n return True\n return False\n\n\nif __name__ == '__main__':\n link = CycleLinkList()\n print(link.is_empty())\n\n link.append(9)\n print(link.length())\n link.linklistPrint()\n\n link.append(0)\n print(link.length())\n link.linklistPrint()\n\n\n link.addBegin(8)\n print(link.length())\n link.linklistPrint()\n\n link.addBegin(7)\n print(link.length())\n link.linklistPrint()\n\n link.insert(0, 5)\n link.linklistPrint()\n\n link.insert(10, 6)\n link.linklistPrint()\n\n link.insert(2, 3)\n link.linklistPrint()\n\n link.remove(6)\n link.linklistPrint()\n\n link.remove(5)\n link.linklistPrint()\n\n link.remove(3)\n link.linklistPrint()\n\n","sub_path":"datastruct/circlelinklist.py","file_name":"circlelinklist.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"632162633","text":"def floyd_warshall_predecessor_and_distance(G, weight='weight'):\n \"\"\"Find all-pairs shortest path lengths using Floyd's algorithm.\n\n Parameters\n ----------\n G : NetworkX graph\n\n weight: string, optional (default= 'weight')\n Edge data key corresponding to the edge weight.\n\n Returns\n -------\n predecessor,distance : dictionaries\n Dictionaries, keyed by source and target, of predecessors and distances\n in the shortest path.\n\n Notes\n ------\n Floyd's algorithm is appropriate for finding shortest paths\n in dense graphs or graphs with negative weights when Dijkstra's algorithm\n fails. This algorithm can still fail if there are negative cycles.\n It has running time $O(n^3)$ with running space of $O(n^2)$.\n\n See Also\n --------\n floyd_warshall\n floyd_warshall_numpy\n all_pairs_shortest_path\n all_pairs_shortest_path_length\n \"\"\"\n from collections import defaultdict\n # dictionary-of-dictionaries representation for dist and pred\n # use some defaultdict magick here\n # for dist the default is the floating point inf value\n dist = defaultdict(lambda: defaultdict(lambda: float('inf')))\n for u in G:\n dist[u][u] = 0\n pred = defaultdict(dict)\n # initialize path distance dictionary to be the adjacency matrix\n # also set the distance to self to 0 (zero diagonal)\n undirected = not G.is_directed()\n for u, v, d in G.edges(data=True):\n e_weight = d.get(weight, 1.0)\n dist[u][v] = min(e_weight, dist[u][v])\n pred[u][v] = u\n if undirected:\n dist[v][u] = min(e_weight, dist[v][u])\n pred[v][u] = v\n for w in G:\n for u in G:\n for v in G:\n if dist[u][v] > dist[u][w] + dist[w][v]:\n dist[u][v] = dist[u][w] + dist[w][v]\n pred[u][v] = pred[w][v]\n return dict(pred), dict(dist)","sub_path":"_floyd_warshal_networkX.py","file_name":"_floyd_warshal_networkX.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"444111590","text":"# Importing all the necessary libraries.\nimport socket\n\nimport sqlite3\nfrom sqlite3 import Error\n\nimport sys\nfrom sys import argv\n\n# A main function that takes in two commandline arguments.\ndef Main(argv):\n host = argv[1];\n port = argv[2];\n\n # Store data received into datas array.\n datas = [];\n\n mySocket = socket.socket()\n mySocket.bind((str(host),int(port)))\n mySocket.listen(100)\n\n while(1):\n conn, addr = mySocket.accept()\n # print (\"Server: Connection from \" + str(addr))\n data = conn.recv(1024).decode()\n # print(\"DATA:\", data);\n if not data:\n return\n # print (\"Server: recv \" + str(data));\n datas.append(data.split(\"$\")[0]);\n datas.append(data.split(\"$\")[1]);\n\n # Connect to sqlite database in node1 directory and execute DDL command.\n try:\n condb = sqlite3.connect(datas[0].strip('/'));\n cur = condb.cursor();\n cur.execute(datas[1]);\n message = \"./books.sql success.$\" + host + \":\" + str(port) + \"$\" + datas[0] + \"$\" + str(cur.fetchall());\n condb.commit();\n conn.send(message.encode());\n # If there is an error, send a message back to client that it was a failure.\n except Error as e:\n print(e);\n message = \"./books.sql failure.$\" + host + \":\" + str(port) + \"$\" + datas[0];\n conn.send(message.encode());\n conn.close();\n # After everything, finally close the db and the connection between client / server.\n finally:\n conn.close();\n# Run main function with argv parameters (commandline arguments)\nMain(argv);\n","sub_path":"hw2n1/parDBd.py","file_name":"parDBd.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195764707","text":"import boto3\nimport json\nimport datetime\n\nctr_table = \"ContactTraceRecordTable\"\nregion_name = \"us-west-2\"\n\ndef lambda_handler(event, context):\n \n dynamodb = boto3.client(\"dynamodb\", region_name=region_name)\n response = dynamodb.scan(TableName=ctr_table)\n\n start_time = event[\"queryStringParameters\"][\"StartTime\"]\n end_time = event[\"queryStringParameters\"][\"EndTime\"]\n\n ctr_list = []\n\n for item in response[\"Items\"]:\n ctr = {}\n for key in item:\n ctr[key] = item[key][\"S\"]\n\n ctr_list.append(ctr)\n\n return {\n \"statusCode\": 200,\n \"headers\": {\n \"Access-Control-Allow-Origin\": \"*\"\n },\n \"body\": json.dumps({\n \"ctr_list\": ctr_list\n })\n }\n","sub_path":"ctr-processor/.aws-sam/build/CTRAPIFunction/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195726064","text":"from pyparsing import *\nimport glob\nimport pandas as pd\nimport re\nimport argparse\n\ndef fileParser(folder):\n\n # Get a list of all the test files in the given folder\n txt_files = glob.glob(f\"{folder}/*.txt\")\n\n # Create a dataframe based on the expected final format.\n compiled_df = pd.DataFrame(columns=['Project ID', 'Project Objectives', 'Project Description',\n 'Borrowers Institutional Capacity for Safeguard Management',\n 'Environmental and Social Safeguards Specialists on the Team',\n 'Environmental Assessment OP/BP 4.01 Triggered ?',\n 'Environmental Assessment OP/BP 4.01 Comment',\n 'Natural Habitats OP/BP 4.04', 'NH Comment', 'Forests OP/BP 4.36',\n 'F Comment','Pest Management OP 4.09', 'PM Comment',\n 'Physical Cultural Resources OP/BP 4.11', 'PCR Comment',\n 'Indigenous Peoples OP/BP 4.10', 'IP Comment',\n 'Involuntary Resettlement OP/BP 4.12', 'IR Comment', 'Safety of Dams OP/BP 4.37',\n 'SoD Comment', 'Projects in Disputed Areas OP/BP 7.60', 'PiDA Comment'])\n \n page_rgx = re.compile('\\n[-]\\n|\\s*(Page)\\s*\\d*(of)\\s*\\d*\\n*|\\s*(Page)\\s*\\d*\\n*|\\n(\\.)\\s\\n|\\s\\n\\s|\\n\\s(?=[a-z])|\\n(Public Disclosure Copy)\\n*')\n newline_rgx = re.compile('\\n(?=[a-z])|\\n(?=[(])|\\n(?=[1-9])')\n dc = Regex(r'\\n[-]\\n|\\s*(Page)\\s*\\d*\\n*|\\n(\\.)\\s\\n|\\s\\n\\s|\\n\\s(?=[a-z])').sub(r' ')\n line = Regex(r'\\n(?=[a-z])|\\n(?=[(])|\\n(?=[1-9])').sub(r'')\n for _file in txt_files:\n projid_label = Literal('Project ID') ^ Literal('ProjectID') ^ Literal('Project ID:') ^ Literal('ProjectID:')\n section_label = LineStart() + Optional(White(' ',max=50)) + ((Word(srange(\"[A-Z]\")) + Literal('.')) ^ (Word(nums) + Literal('.'))) + \\\n Optional(((Word(srange(\"[A-Z]\")) + Literal('.')) ^ (Word(nums) + Literal('.')))) + \\\n Optional(((Word(srange(\"[A-Z]\")) + Literal('.')) ^ (Word(nums) + Literal('.')))) + \\\n Optional(((Word(srange(\"[A-Z]\")) + Literal('.')) ^ (Word(nums) + Literal('.'))))\n projobj_label = section_label + (CaselessLiteral('Project Objectives') ^ CaselessLiteral('Program Objectives') ^\\\n CaselessLiteral('Project Objective') ^ CaselessLiteral('Program Objective'))\n projdes_label = section_label + (CaselessLiteral('Project Description') ^ CaselessLiteral('Program Description'))\n loc_label = section_label + (CaselessLiteral('Project Location') ^ CaselessLiteral('Program Location'))\n borrow_label = section_label + (CaselessLiteral('Borrow')) + SkipTo('\\n')\n envsoc_label = section_label + CaselessLiteral('Environmental and Social Safeguard Specialists') + SkipTo('\\n')\n paragraph = SkipTo('\\n')\n field = Word(alphanums)\n colon = Word(':')\n end = SkipTo('/n/n')\n #parser = projid_label + Optional(colon) + field.setResultsName('projID')\n\n parser = projid_label + Optional(colon) + field.setResultsName('projID') + SkipTo(projobj_label) \\\n + projobj_label + Optional(colon) + SkipTo(projdes_label).setResultsName('projobj') + SkipTo(projdes_label) \\\n + projdes_label + Optional(colon) + SkipTo(loc_label).setResultsName('projdes') + \\\n Optional(SkipTo(borrow_label) + borrow_label + SkipTo(section_label).setResultsName('borrow')) + \\\n Optional(SkipTo(envsoc_label) + envsoc_label + SkipTo(section_label).setResultsName('envsoc'))\n\n print()\n print()\n print()\n print(_file)\n\n for param in parser.searchString(open(_file, encoding=\"utf8\", errors='ignore').read()):\n param.projobj = re.sub(page_rgx, \" \", param.projobj)\n param.projobj = re.sub(newline_rgx, \"\", param.projobj)\n param.projdes = re.sub(page_rgx, \" \", param.projdes)\n param.projdes = re.sub(newline_rgx, \"\", param.projdes)\n param.borrow = re.sub(page_rgx, \" \", param.borrow)\n param.borrow = re.sub(newline_rgx, \"\", param.borrow)\n #param.borrow = line.transformString(param.borrow)\n print(param.projID)\n print(param.projobj)\n print(param.projdes)\n print(param.borrow)\n print(param.envsoc)\n compiled_df = compiled_df.append({'Project ID': param.projID, 'Project Objectives': param.projobj,\n 'Project Description': param.projdes,\n 'Borrowers Institutional Capacity for Safeguard Management': param.borrow,\n 'Environmental and Social Safeguards Specialists on the Team': param.envsoc}, ignore_index=True)\n\n print(compiled_df)\n compiled_df.to_csv(folder + 'compiled.csv')\n\n\n\n\n #data = parseString(open(file, encoding=\"utf8\", errors='ignore').read())\n # parser_projID = Regex('([P]\\s*[A-Z0-9]{6,6})').setResultsName('projID')\n # parser = Literal('Project ID') + parser_projID parser_projID.parseString(open(file, encoding=\"utf8\", errors='ignore').read())\n # print(projID)\n\ndef main(folder):\n\n fileParser(folder)\n\nif __name__ == \"__main__\":\n \n # Create a parser object \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--folder\", default = \"../text_file_conversion/samples/\", type = str,\n help = \"The folder which contains the .txt files that need to be parsed.\")\n FLAGS = parser.parse_args()\n\n main(FLAGS.folder)\n","sub_path":"src/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"434985959","text":"import hashlib\nfrom flask import Flask,request\nimport httplib2\nimport json\nimport threading\nimport socket\nimport time\napp=Flask(__name__)\n\nhostname = socket.gethostname()\nmax_nonce = 30000000\ndifficulty_bits = 15\ntarget = 2 ** (256-difficulty_bits)\nother_host_finished_earlier = False\ntransactions = []\nchain = []\nprev_hash = \"\"\n\n\n\n@app.route('/refreshChain', methods=[\"GET\"])\ndef refreshChain():\n update_chain()\n\n\ndef initialize(): \n global chain,prev_hash\n http = httplib2.Http()\n data = {\n \"hostname\":hostname,\n \"ip\":\"192.168.2.104:5000\"\n }\n http.request(\"http://192.168.2.105:5003/announce\",\"POST\", json.dumps(data))\n update_chain()\n \ndef update_chain():\n global chain,prev_hash\n http = httplib2.Http()\n res, dat = http.request(\"http://192.168.2.105:5003/getNewChain\",\"GET\")\n chain = json.loads(dat)['chain']\n prev_hash = chain[len(chain)-1]['hash']\n\n \ndef enter_loop():\n global transactions,prev_hash\n while True:\n transactions = get_txions() \n if(transactions[0][\"txion\"] == \"None\"):\n print(\"Going to sleep\")\n time.sleep(20)\n enter_loop() \n find_nonce(transactions,prev_hash)\n\n\ndef find_nonce(transactions,hash):\n global other_host_finished_earlier\n found_nonce = False\n for nonce in range(max_nonce):\n hash_result = hashlib.sha256(str.encode(str(transactions) + str(nonce)+ str(hash) )).hexdigest()\n if(other_host_finished_earlier):\n print('***************SOMEONE ELSE FOUND******************')\n update_chain()\n other_host_finished_earlier = False\n break\n if int(hash_result, 16) < target:\n calc_hash = hash_result\n calc_nonce = nonce\n found_nonce = True\n break\n\n if found_nonce:\n print(calc_nonce)\n form_block(calc_nonce,calc_hash)\n # validate(calc_nonce,hostname)\n # send_to_peers(calc_nonce)\n # return calc_hash, calc_nonce\n\n\ndef form_block(nonce,hash):\n global prev_hash,chain\n block ={\"title\":f\"block {chain[len(chain)-1]['index'] + 1} \",\n \"description\":\"yolo\",\n \"index\":chain[len(chain)-1]['index'] + 1,\n \"icon\":\"http://192.168.2.105:5005/bkchn.png\",\n \"pbh\":prev_hash,\n \"pow\":nonce,\n \"hash\":hash,\n\t\t\"timestamp\":time.time(),\n\t\t\"hostname\":hostname,\n \"txions\":transactions\n }\n chain.append(block)\n send_block(block)\n prev_hash = chain[len(chain)-1]['hash']\n\n\ndef send_block(block):\n global other_host_finished_earlier\n http = httplib2.Http()\n res, data = http.request('http://192.168.2.105:5003/blockFound',\"POST\", json.dumps(block)) \n if(data.decode('utf-8') == \"Fail\"):\n other_host_finished_earlier = True\n print(data)\n\n \n\n# def validate(nonce, host): \n# hash_result = hashlib.sha256(str.encode(str(transactions) + str(nonce))).hexdigest()\n# if int(hash_result, 16) < target:\n# block = {\n# \"transactions\":transactions,\n# \"host\":host,\n# \"hash\":hash_result\n# }\n# chain.append(block)\n# print(chain)\n# else:\n# return False\n # If all nodes return True, then add the block to the chain\n\ndef get_txions():\n http = httplib2.Http()\n res, data = http.request('http://192.168.2.105:5002/gettxions',\"GET\")\n return json.loads(data)\n\ndef main():\n initialize()\n enter_loop()\n\n\nif __name__ == '__main__':\n t = threading.Thread(target=main)\n t.start()\n app.run(host='0.0.0.0',port='5000')\n \n ","sub_path":"old/node_miner4.py","file_name":"node_miner4.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"543826560","text":"def sort(data):\n size = len(data)\n for i in range(size):\n max = i\n for j in range(i,size):\n if data[max]< data[j]:\n max = j\n temp = data[i]\n data[i]=data[max]\n data[max]=temp\n print (data)\n\ndata = [5,4,2,1,7]\nsort(data)\nsort([100,5,88,90,45,74,63,541])\nsort(['a','b','x','z'])\nsort(['noor','zainab','xxx']) #decending order","sub_path":"lec1/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"396469719","text":"import torch\n\nfrom mmdet.core import bbox2result, bbox_mapping_back\nfrom ..builder import DETECTORS\nfrom .single_stage import SingleStageDetector\nfrom .two_stage import TwoStageDetector\n\nfrom ..losses import CtdetLoss\nfrom .ctdet_decetor import ctdet_decode, post_process, merge_outputs\n\n\n@DETECTORS.register_module()\nclass CenterNet(SingleStageDetector):\n\n def __init__(self,\n backbone,\n neck,\n bbox_head,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(CenterNet, self).__init__(backbone, neck, bbox_head, train_cfg,\n test_cfg, pretrained)\n\n def forward_train(self, img, img_meta, **kwargs):\n \n x = self.extract_feat(img)\n outs = self.bbox_head(x)\n\n\n return outs\n \n def forward_test(self, img, img_meta, **kwargs):\n\n output = self.backbone(img.type(torch.cuda.FloatTensor))[-1] # batch, c, h, m\n hm = torch.clamp(output['hm'].sigmoid_(), min=1e-4, max=1-1e-4)\n wh = output['wh']\n reg = output['reg']\n # print(\"hm\", hm)\n # print(\"wh\", wh)\n # print(\"reg\", reg)\n dets = ctdet_decode(hm, wh, reg=reg, K=100)\n # print(\"after process:\\n\", dets)\n # print(img_meta)\n # batch = kwargs\n # print(batch)\n # scale = img_meta[i]['scale'].detach().cpu().numpy()[0]\n dets = post_process(dets, meta = img_meta, scale=1)\n # print(\"after post_process:\\n\", dets)\n# detections.append(dets)\n detections = [dets]\n results = merge_outputs(detections)\n# print(results)\n# det_bboxes = dets[:,:,:5].view(-1, 5)# (batch, k, 4)\n# det_labels = dets[:,:,5].view(-1) # (batch, k, 1)\n\n# x = self.extract_feat(img)\n# proposal_list = self.simple_test_rpn(\n# x, img_meta, self.test_cfg.rpn) if proposals is None else proposals\n\n# input is the output of network, return the det_bboxed, det_labels(0~L-1)\n# det_bboxes, det_labels = self.simple_test_bboxes(\n# x, img_meta, proposal_list, self.test_cfg.rcnn, rescale=rescale)\n\n# bbox_results = bbox2result(det_bboxes, det_labels,\n# self.backbone.heads['hm'] + 1)\n\n return results\n \n def forward_dummy(self, img):\n x = self.backbone(img)\n return x\n\n def merge_aug_results(self, aug_results, img_metas):\n \"\"\"Merge augmented detection bboxes and score.\n\n Args:\n aug_results (list[list[Tensor]]): Det_bboxes and det_labels of each\n image.\n img_metas (list[list[dict]]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n\n Returns:\n tuple: (bboxes, labels)\n \"\"\"\n recovered_bboxes, aug_labels = [], []\n for bboxes_labels, img_info in zip(aug_results, img_metas):\n img_shape = img_info[0]['img_shape'] # using shape before padding\n scale_factor = img_info[0]['scale_factor']\n flip = img_info[0]['flip']\n bboxes, labels = bboxes_labels\n bboxes, scores = bboxes[:, :4], bboxes[:, -1:]\n bboxes = bbox_mapping_back(bboxes, img_shape, scale_factor, flip)\n recovered_bboxes.append(torch.cat([bboxes, scores], dim=-1))\n aug_labels.append(labels)\n\n bboxes = torch.cat(recovered_bboxes, dim=0)\n labels = torch.cat(aug_labels)\n\n if bboxes.shape[0] > 0:\n out_bboxes, out_labels = self.bbox_head._bboxes_nms(\n bboxes, labels, self.bbox_head.test_cfg)\n else:\n out_bboxes, out_labels = bboxes, labels\n\n return out_bboxes, out_labels\n\n def aug_test(self, imgs, img_metas, rescale=False):\n \"\"\"Augment testing of CenterNet.\n\n Args:\n imgs (list[Tensor]): Augmented images.\n img_metas (list[list[dict]]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n\n Note:\n ``imgs`` must including flipped image pairs.\n\n Returns:\n bbox_results (tuple[np.ndarry]): Detection result of each class.\n \"\"\"\n img_inds = list(range(len(imgs)))\n\n assert img_metas[0][0]['flip'] + img_metas[1][0]['flip'], (\n 'aug test must have flipped image pair')\n aug_results = []\n for ind, flip_ind in zip(img_inds[0::2], img_inds[1::2]):\n img_pair = torch.cat([imgs[ind], imgs[flip_ind]])\n x = self.extract_feat(img_pair)\n outs = self.bbox_head(x)\n bbox_list = self.bbox_head.get_bboxes(\n *outs, [img_metas[ind], img_metas[flip_ind]], False, False)\n aug_results.append(bbox_list[0])\n aug_results.append(bbox_list[1])\n\n bboxes, labels = self.merge_aug_results(aug_results, img_metas)\n bbox_results = bbox2result(bboxes, labels, self.bbox_head.num_classes)\n\n return bbox_results","sub_path":".history/mmdet/models/detectors/centernet_triple_20200812223055.py","file_name":"centernet_triple_20200812223055.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"373564336","text":"# Copyright 2016 VMware, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_config import cfg\n\nfrom vmware_nsx._i18n import _\nfrom vmware_nsx.common import exceptions as nsx_exc\n\nDEFAULT_NAME = 'default'\n\n\nclass ConfiguredAvailabilityZone(object):\n\n def __init__(self, config_line):\n if config_line:\n values = config_line.split(':')\n if len(values) < 4 or len(values) > 5:\n raise nsx_exc.NsxInvalidConfiguration(\n opt_name=\"availability_zones\",\n opt_value=config_line,\n reason=_(\"Expected 4 or 5 values per zone\"))\n\n self.name = values[0]\n # field name size in the DB is 36\n if len(self.name) > 36:\n raise nsx_exc.NsxInvalidConfiguration(\n opt_name=\"availability_zones\",\n opt_value=config_line,\n reason=_(\"Maximum name length is 36\"))\n\n self.resource_pool = values[1]\n self.datastore_id = values[2]\n\n # validate the edge_ha\n if values[3].lower() == \"true\":\n self.edge_ha = True\n elif values[3].lower() == \"false\":\n self.edge_ha = False\n else:\n raise nsx_exc.NsxInvalidConfiguration(\n opt_name=\"availability_zones\",\n opt_value=config_line,\n reason=_(\"Expected the 4th value to be true/false\"))\n\n # HA datastore id is relevant only with edge_ha\n if not self.edge_ha and len(values) == 5:\n raise nsx_exc.NsxInvalidConfiguration(\n opt_name=\"availability_zones\",\n opt_value=config_line,\n reason=_(\"Expected HA datastore ID only when edge_ha is \"\n \"enabled\"))\n\n self.ha_datastore_id = values[4] if len(values) == 5 else None\n else:\n # use the default configuration\n self.name = DEFAULT_NAME\n self.resource_pool = cfg.CONF.nsxv.resource_pool_id\n self.datastore_id = cfg.CONF.nsxv.datastore_id\n self.edge_ha = cfg.CONF.nsxv.edge_ha\n self.ha_datastore_id = cfg.CONF.nsxv.ha_datastore_id\n\n\nclass ConfiguredAvailabilityZones(object):\n\n def __init__(self):\n self.availability_zones = {}\n\n # Add the configured availability zones\n for az in cfg.CONF.nsxv.availability_zones:\n obj = ConfiguredAvailabilityZone(az)\n self.availability_zones[obj.name] = obj\n\n # add a default entry\n obj = ConfiguredAvailabilityZone(None)\n self.availability_zones[obj.name] = obj\n\n def get_resources(self):\n \"\"\"Return a list of all the resources in all the availability zones\n \"\"\"\n resources = []\n for az in self.availability_zones.values():\n resources.append(az.resource_pool)\n resources.append(az.datastore_id)\n if az.ha_datastore_id:\n resources.append(az.ha_datastore_id)\n return resources\n\n def get_availability_zone(self, name):\n \"\"\"Return an availability zone object by its name\n \"\"\"\n if name in self.availability_zones.keys():\n return self.availability_zones[name]\n return self.get_default_availability_zone()\n\n def get_default_availability_zone(self):\n \"\"\"Return the default availability zone object\n \"\"\"\n return self.availability_zones[DEFAULT_NAME]\n\n def list_availability_zones(self):\n \"\"\"Return a list of availability zones names\n \"\"\"\n return self.availability_zones.keys()\n","sub_path":"vmware_nsx/plugins/nsx_v/availability_zones.py","file_name":"availability_zones.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"94040687","text":"import math\nimport os\nfrom os.path import join, exists\nfrom pathlib import Path\nfrom typing import List, Tuple\n\nimport dill\nimport torch\nfrom tokenizers import Tokenizer, normalizers\nfrom tokenizers.normalizers import Lowercase, NFD, StripAccents\nfrom torch import Tensor\nfrom torch.utils.data import DataLoader, WeightedRandomSampler\n\nfrom Eval.analysis import get_inverse_label_frequencies\nfrom Eval.config import RESAMPLE_TRAIN_DATA, TRAIN_FRAC, BATCH_SIZE\nfrom Eval.device_settings import device\n\nnormaliser = normalizers.Sequence([NFD(), Lowercase(), StripAccents()])\n\ndirname, _ = os.path.split(os.path.abspath(__file__))\nprint(\"data processor dirname\")\nDIR = join(dirname, \"Data\", \"Processed\")\nTOKENS = \"tokenIDS.data\"\nLABELS = \"labels.data\"\n\n\ndef save_data(data, name):\n Path(DIR).mkdir(parents=True, exist_ok=True)\n print(\"saving tensor data for\", name)\n torch.save(data, join(DIR, name), pickle_module=dill)\n\n\ndef get_tokens_and_labels():\n if not exists(join(DIR, LABELS)): # not previously saved. load through dataloader, then tokenise and save\n print(\"processing dataset at\", DIR)\n from Models.medbert import tokeniser\n from Datasets.dataloader import comment_text, label_text\n\n tokens, label_data = get_all_tokens_and_labels(comment_text, tokeniser, label_text)\n save_data(tokens, TOKENS)\n save_data(label_data, LABELS)\n else: # previously saved. just load tokens\n print(\"loading processed datapoints from\", DIR)\n tokens = torch.load(join(DIR, TOKENS), pickle_module=dill)\n label_data = torch.load(join(DIR, LABELS), pickle_module=dill)\n return tokens, label_data\n\n\ndef load_full_dataset():\n tokens, label_data = get_tokens_and_labels()\n combined = [(t.to(device), label_data[i].to(device)) for i, t in enumerate(tokens)]\n return combined\n\n\ndef load_dataset_frac(batch_size, start_frac=0, end_frac=1, dataset=None, sample=False) -> DataLoader: # loads, pads and batches the dataset, returns a dataloader\n if dataset is None:\n dataset = load_full_dataset()\n\n length = len(dataset) - 1\n start_id = math.ceil(start_frac * length)\n end_id = math.ceil(end_frac * length)\n dataset = dataset[start_id: end_id]\n print(\"making data loader with ids [\", start_id, \":\", end_id, \"]\")\n\n if sample:\n _, label_data = get_tokens_and_labels()\n label_frequenies = torch.from_numpy(get_inverse_label_frequencies(label_data)[start_id: end_id])\n sampler = WeightedRandomSampler(label_frequenies, len(dataset))\n return DataLoader(dataset, batch_size=batch_size, collate_fn=PadCollate(0), sampler=sampler)\n return DataLoader(dataset, shuffle=True, batch_size=batch_size, collate_fn=PadCollate(0))\n\n\ndef load_splits():\n dataset = load_full_dataset()\n train = load_dataset_frac(BATCH_SIZE, 0, TRAIN_FRAC, dataset=dataset, sample=RESAMPLE_TRAIN_DATA)\n test = load_dataset_frac(BATCH_SIZE, TRAIN_FRAC, 1, dataset=dataset, sample=False)\n return train, test\n\n\ndef pad_tensor(vec, pad, dim): # Felix_Kreuk https://discuss.pytorch.org/t/dataloader-for-various-length-of-data/6418/7\n \"\"\"\n args:\n vec - tensor to pad\n pad - the size to pad to\n dim - dimension to pad\n\n return:\n a new tensor padded to 'pad' in dimension 'dim'\n \"\"\"\n pad_size = list(vec.shape)\n pad_size[dim] = pad - vec.size(dim)\n return torch.cat([vec, torch.zeros(*pad_size).to(device)], dim=dim)\n\n\ndef get_all_tokens_and_labels(texts: List[List[str]], tokeniser: Tokenizer, labels: List[List[str]]) -> Tuple[List[Tensor], List[Tensor]]:\n label_tensors = [get_label_bools(l) for l in labels]\n return tokenise_all_texts(texts, tokeniser), label_tensors\n\n\ndef tokenise_all_texts(texts: List[List[str]], tokeniser: Tokenizer) -> List[Tensor]:\n tokenised_sequences = []\n for text in texts:\n # here text is a list of lines of comments for a particular image\n tokenised_sequences.append(tokenise_text(text, tokeniser))\n return tokenised_sequences\n\n\ndef tokenise_text(text: List[str], tokeniser: Tokenizer):\n text = [normaliser.normalize_str(t) for t in text]\n concat_text = \"[SEP]\".join(text)\n token_ids = tokeniser.encode(concat_text)\n print(\"tokenised text:\", tokeniser.decode(token_ids))\n return torch.Tensor(token_ids).long().to(device)\n\n\ndef get_label_bools(label: List[str]):\n bools = [0 if l == \"0\" or l == \"N\" else 1 for l in label]\n return torch.Tensor(bools).long().to(device)\n\n\nclass PadCollate: # Felix_Kreuk https://discuss.pytorch.org/t/dataloader-for-various-length-of-data/6418/7\n \"\"\"\n a variant of callate_fn that pads according to the longest sequence in\n a batch of sequences\n \"\"\"\n\n def __init__(self, dim=0):\n \"\"\"\n args:\n dim - the dimension to be padded (dimension of time in sequences)\n \"\"\"\n self.dim = dim\n\n def pad_collate(self, batch):\n \"\"\"\n args:\n batch - list of (tensor, label)\n\n reutrn:\n xs - a tensor of all examples in 'batch' after padding\n ys - a LongTensor of all labels in batch\n \"\"\"\n # find longest sequence\n max_len = max(map(lambda x: x[0].shape[self.dim], batch))\n # pad according to max_len\n batch = map(lambda x: (pad_tensor(x[0], pad=max_len, dim=self.dim), x[1]), batch)\n batch = list(batch)\n # stack all\n xs = torch.stack(list(map(lambda x: x[0], batch)), dim=0).long()\n ys = torch.stack(list(map(lambda x: x[1], batch)), dim=0).float()\n\n return xs, ys\n\n def __call__(self, batch):\n return self.pad_collate(batch)\n\n\ndef get_label_distribution():\n \"\"\"counts representation of each spinal condition\"\"\"\n tokens, label_data = get_tokens_and_labels()\n sum_labels = sum(label_data).cpu().detach().numpy()\n return sum_labels\n\n\ndef get_split_label_distribution(start_frac=0, end_frac=1):\n \"\"\"counts representation of each spinal condition, for a particular section of the dataset\"\"\"\n tokens, label_data = get_tokens_and_labels()\n length = len(label_data) - 1\n start_id = math.ceil(start_frac * length)\n end_id = math.ceil(end_frac * length)\n label_data = label_data[start_id: end_id]\n sum_labels = sum(label_data).cpu().detach().numpy()\n return sum_labels\n\n\ntotal_label_distribution = get_label_distribution()\ntrain_label_distribution = get_split_label_distribution(0, TRAIN_FRAC)\ntest_label_distribution = get_split_label_distribution(TRAIN_FRAC, 1)\nprint(\"total label distribution:\", total_label_distribution)\nprint(\"train_label_distribution:\", train_label_distribution)\nprint(\"test_label_distribution:\", test_label_distribution)\n\nif __name__ == \"__main__\":\n get_label_distribution()\n get_split_label_distribution(0, 0.5)","sub_path":"Datasets/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"158435192","text":"from picamera import PiCamera as Camera\nfrom picamera.array import PiRGBArray\nfrom time import sleep\nimport cv2 as cv\nimport cv2.aruco as aruco\nimport numpy as np\n\n#H corresponds to 44mm height of the aruco marker being used\nH = 1.732 \n#D distance in inches\nD = 36 \n\n#fileName = input(\"Please enter a file name for the image: \")\n#camera = PiCamera(resolution = (1920, 1080))\n#camera.iso = 100\n#sleep(2)\n#g = camera.awb_gains\n#camera.awb_mode = 'off'\n#camera.awb_gains = g\n#sleep(5)\n#camera.capture('/home/pi/SEEDLAB/%s' % fileName)\n\ncamera = Camera(resolution=(1280, 720), framerate=60)\nfocalList = []\nfor i in range(3):\n camera.capture('/home/pi/SEEDLAB/PythonExercises/test.jpg')\n img = cv.imread('test.jpg')\n grayImg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n arucoDictionary = aruco.Dictionary_get(aruco.DICT_6X6_250)\n arucoParameters = aruco.DetectorParameters_create()\n corners, ids, rejectedImgPoints = aruco.detectMarkers(grayImg, arucoDictionary,parameters=arucoParameters)\n cornerList = list(corners)\n bottomRightY = int(cornerList[0][0][2][1])\n bottomLeftY = int(cornerList[0][0][3][1])\n topRightY = int(cornerList[0][0][1][1])\n topLeftY = int(cornerList[0][0][0][1])\n bottomRightX = int(cornerList[0][0][2][0])\n bottomLeftX = int(cornerList[0][0][3][0])\n topRightX = int(cornerList[0][0][1][0])\n topLeftX = int(cornerList[0][0][0][0])\n #PY is the average height in pixels of the aruco marker.\n PY = ((abs(topRightY - bottomRightY)) + (abs(topLeftY - bottomLeftY))) / (2)\n #F is the calculated focal length of the camera.\n F = (PY * D) / (H)\n focalList.append(F)\n sleep(1)\nprint(cornerList)\nprint(focalList)\n#focalAverage takes the average of the focal lengths calcuated to determine the focal length that will be used.\nfocalAverage = sum(focalList) / len(focalList)\nprint(focalAverage)\n","sub_path":"Demo1/Python/focalLength.py","file_name":"focalLength.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"575422665","text":"import cv2\nimport tensorflow as tf\n\ndef show_cost(func):\n def wrap(*args, **kwargs):\n import time\n from_time = time.time()\n result = func(*args, **kwargs)\n print(\"cost: \", time.time() - from_time)\n return result \n return wrap\n\nmapper = {2: \"OK\", 3:\"FIVE\", 4: \"V\", 5:\"SIX\", 6:\"IOU\", 7:\"GOOD\", 8:\"BAD\"}\nSIZE = (160, 160, 3)\nMNAME = \"mobile_v2_160\"\nMPATH= \"./mobile_v2_224_0225checkpoint\"\n\n\nclass GestureDetector:\n def __init__(self):\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.7)\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n\n @show_cost\n def run(self, img):\n with self.sess.as_default():\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n height, width = img.shape[:-1]\n img = cv2.resize(img, SIZE[:-1])\n print(\"coming\")\n rclasses, rbboxes = self.sess.run(self.output, feed_dict={self.image: img})\n print(\"end\")\n points = []\n for i, box in enumerate(rbboxes):\n ymin, xmin, ymax, xmax = map(int, [box[0] * height, box[1]*width, box[2] * height, box[3] * width])\n points.append({\"x\": xmin, \"y\": ymin, \"type\": \"rect\", \"width\": xmax - xmin, \"height\": ymax - ymin, \"name\": mapper.get(rclasses[i])})\n return points\n\n\n def reload_pb(self, path='./gesture_mobile/ry_guesture.pb'):\n with self.sess.as_default():\n with open(path, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n self.image = tf.placeholder(tf.uint8, SIZE)\n self.output = tf.import_graph_def(graph_def,\n input_map={'input_image:0': self.image},\n return_elements=['rclasses:0', \"boundboxes:0\"])\n\n","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"90085839","text":"# coding: utf-8\nfrom PyQt5 import QtCore, QtGui, Qt, QtWidgets\nfrom OpenGL import GL\nfrom packaging import version\n\nmsg = \"\"\"WARNING:: Qt import failed. This is a know issue. Qt import should work for version\n5.9 and above, and qt 5.6 Other version may not work. If you get this message,\nplease post an issue on https://github.com/sequana/sequana with the python\nversion, the qt version and this error message:\\n\\n\"\"\"\n\nif version.parse(QtCore.QT_VERSION_STR) > version.parse(\"5.9\"):\n # In version 5.9, QtWebEngineWidgets and QtWebKit are deprecated\n #from PyQt5.Qt import QTabWidget\n #from PyQt5 import QtWebEngine as QtWebKit\n from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView\n from PyQt5.QtWebEngineWidgets import QWebEnginePage as QWebPage\n from PyQt5.QtWebEngineWidgets import QWebEngineSettings as QWebSettings\n #try:\n # from PyQt5.Qt import QWebEnginePage as QWebPage\n # from PyQt5.QtWebKitWidgets import QWebPage\n #except: \nelse: # work in PyQt5.6\n try:\n from PyQt5.QtWebKitWidgets import QWebView\n from PyQt5.QtWebKit import QWebSettings\n from PyQt5.Qt import QWebPage\n except Exception as err:\n print(msg + str(err))\n pass\n\n\n\nfrom PyQt5.QtWidgets import QProgressBar, QLineEdit\n\n# potential resources for improvements:\n# https://github.com/ralsina/devicenzo/blob/master/devicenzo.py\n\n\nclass Browser(Qt.QMainWindow):\n \"\"\"\n\n On purpose, there is no caching so that (if re-generated), the\n new content of an HTML is shown.\n\n \"\"\"\n def __init__(self, url):\n Qt.QMainWindow.__init__(self)\n\n # Progress bar\n # ------------------------------------------------------------\n self.progress = 0\n # Main page QWebView\n # -------------------------------------------------------------\n self.wb = SequanaQWebView(\n parent=self,\n titleChanged=self.setWindowTitle)\n self.wb.urlChanged.connect(lambda u: self.url.setText(u.toString()))\n\n self.wb.titleChanged.connect(self.adjustTitle)\n self.wb.loadProgress.connect(self.setProgress)\n\n\n self.setCentralWidget(self.wb)\n\n # Main menu tool bar\n # -------------------------------------------------------------\n self.tb = self.addToolBar(\"Main Toolbar\")\n for a in ( QWebPage.Back,\n QWebPage.Forward,\n QWebPage.Reload,\n QWebPage.DownloadLinkToDisk):\n self.tb.addAction(self.wb.pageAction(a))\n\n self.url = QLineEdit(returnPressed =lambda:self.wb.setUrl(\n QtCore.QUrl.fromUserInput(self.url.text())))\n self.tb.addWidget(self.url)\n\n # status bar ---------------------------------------------------\n self.sb = self.statusBar()\n try:\n #pyqt5.6\n self.wb.statusBarMessage.connect(self.sb.showMessage)\n except:\n pass\n self.wb.page().linkHovered.connect(lambda l: self.sb.showMessage(l, 3000))\n\n # Search bar\n # ------------------------------------------------------------\n self.search = QLineEdit(returnPressed = lambda: self.wb.findText(self.search.text()))\n self.search.show()\n self.search.hide() # To make ctrl+F effective, need to show/hide ?\n\n # The shortcuts\n # ---------------------------------------------------------\n self.showSearch = Qt.QShortcut(\"Ctrl+F\", self,\n activated= lambda: (self.search.show() , self.search.setFocus()))\n self.hideSearch = Qt.QShortcut(\"Esc\", self,\n activated= lambda: (self.search.hide(), self.wb.setFocus()))\n self.quit = Qt.QShortcut(\"Ctrl+Q\", self, activated=self.close)\n self.zoomIn = Qt.QShortcut(\"Ctrl++\", self,\n activated= lambda: self.wb.setZoomFactor(self.wb.zoomFactor()+.2))\n self.zoomOut = Qt.QShortcut(\"Ctrl+-\", self,\n activated= lambda: self.wb.setZoomFactor(self.wb.zoomFactor()-.2))\n self.zoomOne = Qt.QShortcut(\"Ctrl+=\",\n self, activated = lambda: self.wb.setZoomFactor(1))\n\n # Add alt+left and right keys to navigate backward and forward\n Qt.QShortcut(QtCore.Qt.AltModifier + QtCore.Qt.Key_Left, self,\n activated=lambda: self.wb.back())\n Qt.QShortcut(QtCore.Qt.AltModifier + QtCore.Qt.Key_Right, self,\n activated=lambda: self.wb.forward())\n\n # Add components on the page\n self.sb.addPermanentWidget(self.search)\n\n # Finally, load the URL\n self.wb.load(QtCore.QUrl(url))\n\n try:self.wb.settings().setObjectCacheCapacities(0,0,0)\n except:pass\n\n def adjustTitle(self):\n if 0 < self.progress < 100:\n self.setWindowTitle(\"%s (%s%%)\" % (self.wb.title(), self.progress))\n else:\n self.setWindowTitle(self.wb.title())\n\n def setProgress(self, p):\n self.progress = p\n self.adjustTitle()\n\n\nclass SequanaQWebView(QWebView):\n \"\"\"This is the webview for the application.\n\n It represents a browser window, either the main one or a popup.\n It's a simple wrapper around QWebView that configures some basic settings.\n \"\"\"\n def __init__(self, parent=None, **kwargs):\n \"\"\"Constructor for the class\"\"\"\n super(SequanaQWebView, self).__init__(parent)\n self.kwargs = kwargs\n\n # Javascript and other settings\n # ------------------------------------------------------------\n try:\n self.settings().setAttribute(\n QWebSettings.JavascriptCanOpenWindows, True)\n self.settings().setAttribute(\n QWebSettings.LocalStorageEnabled, True)\n self.settings().setAttribute(\n QWebSettings.PluginsEnabled, True)\n except:\n print(\"QtWebKit.QWebSettings not available for you PyQt version\")\n\n def createWindow(self, type):\n \"\"\"Handle requests for a new browser window.\n\n Method called whenever the browser requests a new window\n (e.g., or window.open()).\n Overridden from QWebView to allow for popup windows, if enabled.\n \"\"\"\n #this = Browser(self.url())\n #this.show()\n\n self.popup = SequanaQWebView(**self.kwargs)\n self.popup.setObjectName(\"web_content\")\n self.popup.setWindowTitle(\"Sequana browser\")\n self.popup.page().windowCloseRequested.connect(self.popup.close)\n self.popup.show()\n return self.popup\n","sub_path":"sequana/gui/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"202189714","text":"from __future__ import print_function, division\n\nimport tensorflow as tf\n\nfrom tensorflow import GradientTape, concat\nfrom tensorflow.dtypes import cast\nimport glob\nimport imageio\nimport os\nimport PIL\nfrom tensorflow.keras import Sequential, Model, Input\nfrom tensorflow.train import Checkpoint\nfrom tensorflow.keras.layers import Dense, BatchNormalization, \\\n LeakyReLU, Conv2DTranspose, Conv2D, Dropout, Flatten, Reshape\nfrom tensorflow.keras.optimizers import Adam \nfrom tensorflow.random import normal\nfrom tensorflow.keras.backend import random_uniform, concatenate, transpose, dot\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.linalg import tensor_diag_part\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom IPython import display\nfrom losses import *\n\nclass DCGAN:\n\n def __init__(self):\n (self.trainIm, self.trainL), (_, _) = tf.keras.datasets.mnist.load_data()\n self.trainIm = self.trainIm.reshape(self.trainIm.shape[0], 28, 28, 1).astype('float32')\n self.trainIm = (self.trainIm - 127.5) / 127.5 # Normalize the images to [-1, 1]\n\n self.bufferSize = 60000\n self.batchSize = 128\n self.epochs = 50\n self.noiseDim = 100\n self.numOfGen = 100\n self.numClasses = 10\n\n self.genOpt = Adam(1e-4)\n self.disOpt = Adam(1e-4)\n self.qNetOpt = Adam(1e-4)\n\n self.trainDataset = tf.data.Dataset.from_tensor_slices(self.trainIm).shuffle(self.bufferSize).batch(self.batchSize)\n \n self.generator = self.buildGenerator()\n (self.discriminator, self.qNet) = self.buildDiscriminator()\n\n self.latentC = []\n i = 0\n while i < self.numOfGen:\n self.latentC.append([i%10])\n i = i+1 \n self.latentC = tf.constant(self.latentC, dtype='float')\n\n def buildGenerator(self):\n model = Sequential()\n model.add(Dense(7*7*256, use_bias=False, input_shape=(100,)))\n model.add(BatchNormalization())\n model.add(LeakyReLU())\n\n model.add(Reshape((7, 7, 256)))\n assert model.output_shape == (None, 7, 7, 256) # Note: None is the batch size\n\n model.add(Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))\n assert model.output_shape == (None, 7, 7, 128)\n model.add(BatchNormalization())\n model.add(LeakyReLU())\n\n model.add(Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))\n assert model.output_shape == (None, 14, 14, 64)\n model.add(BatchNormalization())\n model.add(LeakyReLU())\n\n model.add(Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))\n assert model.output_shape == (None, 28, 28, 1)\n\n return model\n\n def buildDiscriminator(self):\n img1 = Input(shape=(28, 28, 1))\n\n model = Sequential()\n model.add(Conv2D(64, (5, 5), strides=(2, 2), padding='same'))\n model.add(LeakyReLU())\n model.add(Dropout(0.3))\n\n model.add(Conv2D(128, (5, 5), strides=(2, 2), padding='same'))\n model.add(LeakyReLU())\n model.add(Dropout(0.3))\n\n img2 = model(img1)\n\n validity = Dense(1)(img2)\n\n qNet1 = Flatten()(img2)\n qNet2 = Dense(128, activation='relu')(qNet1)\n label = Dense(self.numClasses, activation='softmax')(qNet2)\n\n return (Model(img1, validity), Model(img1, label))\n\n def noiseAndLatentC(self):\n noise = normal([self.batchSize, self.noiseDim - 1])\n rC = random_uniform(shape=(self.batchSize, 1), minval=0, maxval=9, dtype='int32')\n cForLoss = to_categorical(rC, num_classes=10) \n cForLoss = transpose(cForLoss)\n rC = cast(rC, dtype='float')\n noiseAndC = concat([rC, noise], axis=1)\n return (cForLoss, noiseAndC)\n\n @tf.function\n def trainStep(self, images, cForLoss, noiseAndC):\n with GradientTape() as genTape, GradientTape() as disTape, GradientTape() as cTape:\n generatedImages = self.generator(noiseAndC, training=True)\n\n realOutput = self.discriminator(images, training=True)\n fakeOutput = self.discriminator(generatedImages, training=True)\n cApprox = self.qNet(generatedImages, training=True)\n\n genLoss = generatorLoss(fakeOutput)\n disLoss = discriminatorLoss(realOutput, fakeOutput)\n\n qNetLoss = qLoss(cApprox, cForLoss)\n\n gradientsGenerator = genTape.gradient(genLoss, self.generator.trainable_variables)\n gradientsDiscriminator = disTape.gradient(disLoss, self.discriminator.trainable_variables)\n gradientsQnet = cTape.gradient(qNetLoss, self.qNet.trainable_variables)\n\n self.genOpt.apply_gradients(zip(gradientsGenerator, self.generator.trainable_variables))\n self.disOpt.apply_gradients(zip(gradientsDiscriminator, self.discriminator.trainable_variables))\n self.qNetOpt.apply_gradients(zip(gradientsQnet, self.qNet.trainable_variables))\n\n def train(self, epochs):\n dataset = self.trainDataset\n #self.saveCheck()\n for epoch in range(epochs):\n start = time.time()\n \n for image_batch in dataset:\n (cForLoss, noiseAndC) = self.noiseAndLatentC()\n self.trainStep(image_batch, cForLoss, noiseAndC)\n\n # Produce images for the GIF as we go\n display.clear_output(wait=True)\n self.generateAndSaveImages(self.generator,\n epoch + 1)\n\n print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n #if (epoch+1)%5 == 0:\n # self.checkpoint.save(file_prefix = self.checkpointPrefix)\n \n # Generate after the final epoch\n display.clear_output(wait=True)\n self.generateAndSaveImages(self.generator,\n epochs)\n\n\n def generateAndSaveImages(self, model, epoch):\n # Notice `training` is set to False.\n # This is so all layers run in inference mode (batchnorm).\n noise = tf.random.normal([self.numOfGen, self.noiseDim-1])\n noiseAndC = concat([self.latentC, noise], axis=1)\n\n predictions = model(noiseAndC, training=False)\n\n fig = plt.figure(figsize=(10,10))\n\n for i in range(predictions.shape[0]):\n plt.subplot(10, 10, i+1)\n plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n plt.axis('off')\n\n plt.savefig('images/imageAtEpoch{:04d}.png'.format(epoch))\n plt.close()\n\n# def saveCheck(self):\n# self.checkpointDir = './trainingCP'\n# self.checkpointPrefix = os.path.join(checkpointDir, \"ckpt\")\n# self.checkpoint = Checkpoint(generator_optimizer = self.genOpt\n# discriminator_optimizer = self.disOpt\n# generator = self.generator\n# discriminator = self.discriminator)\n\nif __name__ == \"__main__\":\n dcgan = DCGAN()\n dcgan.train(500)\n","sub_path":"infoGAN2/infoGAN.py","file_name":"infoGAN.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"48114025","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport random\n\nimport jax\nimport flax.linen as nn\nfrom flax.training.common_utils import shard\nfrom flax.jax_utils import replicate, unreplicate\n\nfrom transformers.models.bart.modeling_flax_bart import *\nfrom transformers import BartTokenizer, FlaxBartForConditionalGeneration\n\nimport io\n\nimport requests\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torchvision.transforms as T\nimport torchvision.transforms.functional as TF\nfrom torchvision.transforms import InterpolationMode\n\nfrom dalle_mini.vqgan_jax.modeling_flax_vqgan import VQModel\n\n# TODO: set those args in a config file\nOUTPUT_VOCAB_SIZE = 16384 + 1 # encoded image token space + 1 for bos\nOUTPUT_LENGTH = 256 + 1 # number of encoded tokens + 1 for bos\nBOS_TOKEN_ID = 16384\nBASE_MODEL = 'facebook/bart-large-cnn'\n\nclass CustomFlaxBartModule(FlaxBartModule):\n def setup(self):\n # we keep shared to easily load pre-trained weights\n self.shared = nn.Embed(\n self.config.vocab_size,\n self.config.d_model,\n embedding_init=jax.nn.initializers.normal(self.config.init_std, self.dtype),\n dtype=self.dtype,\n )\n # a separate embedding is used for the decoder\n self.decoder_embed = nn.Embed(\n OUTPUT_VOCAB_SIZE,\n self.config.d_model,\n embedding_init=jax.nn.initializers.normal(self.config.init_std, self.dtype),\n dtype=self.dtype,\n )\n self.encoder = FlaxBartEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)\n\n # the decoder has a different config\n decoder_config = BartConfig(self.config.to_dict())\n decoder_config.max_position_embeddings = OUTPUT_LENGTH\n decoder_config.vocab_size = OUTPUT_VOCAB_SIZE\n self.decoder = FlaxBartDecoder(decoder_config, dtype=self.dtype, embed_tokens=self.decoder_embed)\n\nclass CustomFlaxBartForConditionalGenerationModule(FlaxBartForConditionalGenerationModule):\n def setup(self):\n self.model = CustomFlaxBartModule(config=self.config, dtype=self.dtype)\n self.lm_head = nn.Dense(\n OUTPUT_VOCAB_SIZE,\n use_bias=False,\n dtype=self.dtype,\n kernel_init=jax.nn.initializers.normal(self.config.init_std, self.dtype),\n )\n self.final_logits_bias = self.param(\"final_logits_bias\", self.bias_init, (1, OUTPUT_VOCAB_SIZE))\n\nclass CustomFlaxBartForConditionalGeneration(FlaxBartForConditionalGeneration):\n module_class = CustomFlaxBartForConditionalGenerationModule\n\n\nimport wandb\nimport os\nos.environ[\"WANDB_SILENT\"] = \"true\"\nos.environ[\"WANDB_CONSOLE\"] = \"off\"\n\nid = '1i5e8rlj' #'1coradc5'\n#run = wandb.init(id=id, project=\"dalle-mini-demo\", resume=\"allow\")\nrun = wandb.init(id=id,\n entity='wandb',\n project=\"hf-flax-dalle-mini\",\n job_type=\"predictions\",\n resume=\"allow\"\n)\nartifact = run.use_artifact('wandb/hf-flax-dalle-mini/model-3iwhu4w6:latest', type='bart_model')\nartifact_dir = artifact.download()\n\n# create our model\ntokenizer = BartTokenizer.from_pretrained(BASE_MODEL)\nmodel = CustomFlaxBartForConditionalGeneration.from_pretrained(artifact_dir)\nmodel.config.force_bos_token_to_be_generated = False\nmodel.config.forced_bos_token_id = None\nmodel.config.forced_eos_token_id = None\n\nvqgan = VQModel.from_pretrained(\"flax-community/vqgan_f16_16384\")\n\ndef custom_to_pil(x):\n x = np.clip(x, 0., 1.)\n x = (255*x).astype(np.uint8)\n x = Image.fromarray(x)\n if not x.mode == \"RGB\":\n x = x.convert(\"RGB\")\n return x\n\ndef generate(input, rng, params):\n return model.generate(\n **input,\n max_length=257,\n num_beams=1,\n do_sample=True,\n prng_key=rng,\n eos_token_id=50000,\n pad_token_id=50000,\n params=params,\n )\n\ndef get_images(indices, params):\n return vqgan.decode_code(indices, params=params)\n\ndef plot_images(images):\n fig = plt.figure(figsize=(40, 20))\n columns = 4\n rows = 2\n plt.subplots_adjust(hspace=0, wspace=0)\n\n for i in range(1, columns*rows +1):\n fig.add_subplot(rows, columns, i)\n plt.imshow(images[i-1])\n plt.gca().axes.get_yaxis().set_visible(False)\n plt.show()\n \ndef stack_reconstructions(images):\n w, h = images[0].size[0], images[0].size[1]\n img = Image.new(\"RGB\", (len(images)*w, h))\n for i, img_ in enumerate(images):\n img.paste(img_, (i*w,0))\n return img\n\np_generate = jax.pmap(generate, \"batch\")\np_get_images = jax.pmap(get_images, \"batch\")\n\nbart_params = replicate(model.params)\nvqgan_params = replicate(vqgan.params)\n\n# ## CLIP Scoring\nfrom transformers import CLIPProcessor, FlaxCLIPModel\n\nclip = FlaxCLIPModel.from_pretrained(\"openai/clip-vit-base-patch32\")\nprocessor = CLIPProcessor.from_pretrained(\"openai/clip-vit-base-patch32\")\n\ndef hallucinate(prompt, num_images=64):\n prompt = [prompt] * jax.device_count()\n inputs = tokenizer(prompt, return_tensors='jax', padding=\"max_length\", truncation=True, max_length=128).data\n inputs = shard(inputs)\n\n all_images = []\n for i in range(num_images // jax.device_count()):\n key = random.randint(0, 1e7)\n rng = jax.random.PRNGKey(key)\n rngs = jax.random.split(rng, jax.local_device_count())\n indices = p_generate(inputs, rngs, bart_params).sequences\n indices = indices[:, :, 1:]\n\n images = p_get_images(indices, vqgan_params)\n images = np.squeeze(np.asarray(images), 1)\n for image in images:\n all_images.append(custom_to_pil(image))\n return all_images\n\ndef clip_top_k(prompt, images, k=8):\n inputs = processor(text=prompt, images=images, return_tensors=\"np\", padding=True)\n outputs = clip(**inputs)\n logits = outputs.logits_per_text\n scores = np.array(logits[0]).argsort()[-k:][::-1]\n return [images[score] for score in scores]\n\n\n# ## Log to wandb\n\nfrom PIL import ImageDraw, ImageFont\n\ndef captioned_strip(images, caption):\n w, h = images[0].size[0], images[0].size[1]\n img = Image.new(\"RGB\", (len(images)*w, h + 48))\n for i, img_ in enumerate(images):\n img.paste(img_, (i*w, 48))\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\"/usr/share/fonts/truetype/liberation2/LiberationMono-Bold.ttf\", 40)\n draw.text((20, 3), caption, (255,255,255), font=font)\n return img\n \ndef log_to_wandb(prompts):\n strips = []\n for prompt in prompts:\n print(f\"Generating candidates for: {prompt}\")\n images = hallucinate(prompt, num_images=32)\n selected = clip_top_k(prompt, images, k=8)\n strip = captioned_strip(selected, prompt)\n strips.append(wandb.Image(strip))\n wandb.log({\"images\": strips})\n\nprompts = prompts = [\n \"white snow covered mountain under blue sky during daytime\",\n \"aerial view of beach during daytime\",\n \"aerial view of beach at night\",\n \"an armchair in the shape of an avocado\",\n \"young woman riding her bike trough a forest\",\n \"rice fields by the mediterranean coast\",\n \"white houses on the hill of a greek coastline\",\n \"illustration of a shark with a baby shark\",\n]\n\nlog_to_wandb(prompts)\n","sub_path":"demo/wandb-examples.py","file_name":"wandb-examples.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"464048400","text":"size = int(input(\"\\nEnter size of your list:\"))\nlist=[]\nfor i in range(size):\n list.append(int(input(\"Enter element {}:\".format(i+1))))\n\nprint(\"\\nThe given list is:\",list)\n\nfor i in range(max(list)+1):\n if i not in list:\n print(\"Smallest missing number is:\",i)\n break\n","sub_path":"day6/program3.py","file_name":"program3.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"37287101","text":"from sys import platform as _platform\nfrom ctypes import *\n\nif _platform == \"linux\" or _platform == \"linux2\":\n # linux\n lib = cdll.LoadLibrary('libMatrix.so')\nelif _platform == \"darwin\":\n # OS X\n lib = cdll.LoadLibrary('libMatrix.dylib')\nelif _platform == \"win32\":\n exit(1)\n\n\nlib.MatrixIntConstructor.argtypes = []\nlib.MatrixIntConstructor.restype = c_void_p\n\nlib.getSize.argtypes = [c_void_p]\nlib.getSize.restype = c_int\n\nclass Matrix (object) :\n\n def __init__(self):\n self.obj = lib.MatrixIntConstructor()\n\n def getSize(self):\n return lib.getSize(self.obj)\n","sub_path":"python/Matrix.py","file_name":"Matrix.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"118695475","text":"\"\"\"\r\nAuthor: Tal Daniel\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\nimport glob\r\nimport os\r\n\r\n\r\ndef image_seq_to_video(imgs_path, output_path='./video.mp4', fps=15.0):\r\n output = output_path\r\n img_array = []\r\n for filename in glob.glob(os.path.join(imgs_path, '*.png')):\r\n img = cv2.imread(filename)\r\n height, width, layers = img.shape\r\n # img = cv2.resize(img, (width // 2, height // 2))\r\n img = cv2.resize(img, (width, height))\r\n height, width, layers = img.shape\r\n size = (width, height)\r\n img_array.append(img)\r\n\r\n print(size)\r\n print(\"writing video...\")\r\n fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case\r\n out = cv2.VideoWriter(output, fourcc, fps, size)\r\n # out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, size)\r\n\r\n for i in range(len(img_array)):\r\n out.write(img_array[i])\r\n out.release()\r\n print(\"saved video @ \", output)\r\n\r\n\r\ndef video_to_image_seq(vid_path, output_path='./datasets/OTB/img/Custom/'):\r\n os.makedirs(output_path, exist_ok=True)\r\n vidcap = cv2.VideoCapture(vid_path)\r\n success, image = vidcap.read()\r\n count = 0\r\n print(\"converting video to frames...\")\r\n while success:\r\n fname = str(count).zfill(4)\r\n cv2.imwrite(os.path.join(output_path, fname + \".jpg\"), image) # save frame as JPEG file\r\n success, image = vidcap.read()\r\n # print('Read a new frame: ', success)\r\n count += 1\r\n print(\"total frames: \", count)","sub_path":"frame_video_convert.py","file_name":"frame_video_convert.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"521398226","text":"tc = int(input())\r\ncas = []\r\na = 0\r\nb = 7\r\nfor i in range(0,tc):\r\n cas.append(int(input()))\r\nfor item in cas:\r\n if abs(item-a) <= abs(b-item):\r\n print(\"A\")\r\n a = item\r\n else:\r\n print(\"B\")\r\n b = item\r\n\r\n\r\n\r\n\r\n# # There are 7 floors in BH3 and only 2 lifts. Initially Lift A is at the ground floor and Lift B at the top floor. Whenever someone calls the lift from N th floor, the lift closest to that floor comes to pick him up. If both the lifts are at equidistant from the N th floor, them the lift from the lower floor comes up.\r\n# #\r\n# # INPUT\r\n# #\r\n# # First line contains a integer T denoting the number of test cases.\r\n# #\r\n# # Next T lines contains a single integer N denoting the floor from which lift is called.\r\n# #\r\n# # OUTPUT\r\n# #\r\n# # Output T lines containing one character \"A\" if the first lift goes to N th floor or \"B\" for the second lift.","sub_path":"lift_queries.py","file_name":"lift_queries.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"246324145","text":"### Define cleaning function \nimport re \ndict_sub = {\n \"\\n\": \" \",\n \"\\x89Û_\": \"\", # Special characters\n \"\\x89ÛÒ\": \"\",\n \"\\x89ÛÓ\": \"\",\n \"\\x89ÛÏWhen\": \"When\",\n \"\\x89ÛÏ\": \"\",\n \"\\x89Û÷\": \"\",\n \"\\x89Ûª\": \"\",\n \"\\x89Û\\x9d\": \"\",\n \"å_\": \"\",\n \"\\x89Û¢\": \"\",\n \"\\x89Û¢åÊ\": \"\",\n \"åÊ\": \"\",\n \"åÈ\": \"\",\n \"Ì©\": \"e\",\n \"å¨\": \"\",\n \">\": \">\", # Character entity references\n \"<\": \"<\",\n \"&\": \"&\",\n \"http\\S+|www.\\S+\": \"\",\n \"@[A-Za-z0-9]+\":\"\"\n}\ndict_replace = {\"...\": \" ... \", \"'\": \" ' \"}\n\n\ndef clean(tweet):\n #tweet=p.clean(tweet)\n for key, val in dict_sub.items():\n tweet = re.sub(r\"{}\".format(key), val, tweet)\n for key, val in dict_replace.items():\n tweet = tweet.replace(r\"{}\".format(key), val).strip()\n\n # Punctuations at the start or end of words\n for punctuation in \"@!?()[]*%\":\n tweet = tweet.replace(punctuation, \" {} \".format(punctuation)).strip()\n \n tweet=tweet.replace('#','')\n if \"http\" not in tweet:\n tweet = tweet.replace(\":\", \" : \").strip()\n tweet = tweet.replace(\".\", \" . \").strip()\n return tweet","sub_path":"utils/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"54279531","text":"from geometry_classes.Vector2D import *\n\n\nclass GeometryInclusionTest:\n # by: https://stackoverflow.com/questions/2752725/finding-whether-a-point-lies-inside-a-rectangle-or-not/2763387#2763387\n @staticmethod\n def inside_rect(rect_points, P):\n '''\n rect_points - consequtive points of rectangle - can be clockwise and counter clockwise\n P - tested point (Point2D class)\n\n A ___________D\n | |\n | |\n |__________|\n B C\n\n (0 < AP ⋅ AB < AB ⋅ AB) and (0 < AP ⋅ AD < AD ⋅ AD)\n '''\n A, B, C, D = rect_points\n\n AB = Vector2D(start=A, end=B)\n AD = Vector2D(start=A, end=D)\n AP = Vector2D(start=A, end=P)\n\n return 0.0 < AB.dot(AP) and \\\n AB.dot(AP) < AB.dot(AB) and \\\n 0.0 < AD.dot(AP) and \\\n AD.dot(AP) < AD.dot(AD)\n\n # by: https://www.gamedev.net/forums/topic/295943-is-this-a-better-point-in-triangle-test-2d/?tab=comments#comment-2873873\n @staticmethod\n def inside_triangle(triangle_points, P):\n '''\n triangle_points - consequtive points of triangle - can be clockwise and counter clockwise\n P - tested point (Point2D class)\n '''\n A, B, C = triangle_points\n\n b0 = Vector2D(P.x - A.x, P.y - A.y).dot(Vector2D(A.y - B.y, B.x - A.x)) > 0.0\n b1 = Vector2D(P.x - B.x, P.y - B.y).dot(Vector2D(B.y - C.y, C.x - B.x)) > 0.0\n b2 = Vector2D(P.x - C.x, P.y - C.y).dot(Vector2D(C.y - A.y, A.x - C.x)) > 0.0\n\n return b0 == b1 and b1 == b2\n","sub_path":"multitrackingOOP/geometry_classes/GeometryInclusionTest.py","file_name":"GeometryInclusionTest.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"333951363","text":"from fb_post.models import Post\n\nfrom .check_for_exceptions import (\n is_valid_post_id\n)\n\n# Task 13\ndef get_post(post_id):\n\n is_valid_post_id(post_id)\n post_obj = Post.objects.select_related('posted_by').prefetch_related(\n 'comment_set', 'comment_set__commented_by',\n 'comment_set__reaction_set', 'reaction_set').get(id=post_id)\n\n return post_details(post_obj)\n\ndef post_details(post_obj):\n\n comment_objs = post_obj.comment_set.all()\n comments_list = []\n for comment_obj in comment_objs:\n\n replies = []\n for reply in comment_objs:\n if reply.parent_comment_id == comment_obj.id:\n reply_dict = {\n 'comment_id': reply.id,\n 'commenter': {\n 'user_id': reply.commented_by.id,\n 'name': reply.commented_by.name,\n 'profile_pic': reply.commented_by.profile_pic\n },\n 'commented_at': str(reply.commented_at)[:-6],\n 'comment_content': reply.content,\n 'reactions': {\n 'count': len(reply.reaction_set.all()),\n 'type': list(dict.fromkeys([reaction.reaction for reaction in reply.reaction_set.all()]))\n },\n }\n replies.append(reply_dict)\n\n if comment_obj.parent_comment_id is None:\n comment_dict = {\n 'comment_id': comment_obj.id,\n 'commenter': {\n 'user_id': comment_obj.commented_by.id,\n 'name': comment_obj.commented_by.name,\n 'profile_pic': comment_obj.commented_by.profile_pic\n },\n 'commented_at': str(comment_obj.commented_at)[:-6],\n 'comment_content': comment_obj.content,\n 'reactions': {\n 'count': len(comment_obj.reaction_set.all()),\n 'type': list(dict.fromkeys([reaction.reaction for reaction in comment_obj.reaction_set.all()]))\n },\n 'replies_count': len(replies),\n 'replies': replies\n }\n comments_list.append(comment_dict)\n\n post_details_dict = {\n 'post_id': post_obj.id,\n 'posted_by': {\n 'name': post_obj.posted_by.name,\n 'user_id': post_obj.posted_by.id,\n 'profile_pic': post_obj.posted_by.profile_pic\n },\n 'posted_at': str(post_obj.posted_at)[:-6],\n 'post_content': post_obj.content,\n 'reactions': {\n 'count': len(post_obj.reaction_set.all()),\n 'type': list(dict.fromkeys([reaction.reaction for reaction in post_obj.reaction_set.all()]))\n\n },\n\n 'comments':comments_list,\n \"comments_count\": len(comments_list)\n }\n return post_details_dict\n","sub_path":"rest/rest_submissions/rest_assignment_002/fb_post/utils/get_post.py","file_name":"get_post.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"100986089","text":"###########################################################\n# pip3 install mutagen #\n# pip3 install requests #\n# pip3 install beautifulsoup4 #\n# brew install youtube-dl #\n# pip3 install PyLyrics #\n###########################################################\n\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3NoHeaderError\nfrom mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, COMM, USLT, TCOM, TCON, TDRC, TRCK, USLT, APIC\nimport base64\n\nimport shutil\nimport requests\nimport sys\nfrom bs4 import BeautifulSoup\nimport html\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom oauth2client.tools import argparser\nimport os\nimport urllib.request\nimport cchardet\nfrom PyLyrics import *\n\nAPI_KEY = \"AIzaSyBS_l65yxM8AJVdQF2exJoQ1aw3PXKAzMM\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\nSAVE_PATH = \"/users/namimac/Desktop/Shazam/top100/Belgium/\"\nCRAWL_URL = \"http://www.shazam.com/charts/top-100/belgium\"\n\nclass Color:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef convert_encoding(data, new_coding = 'UTF-8'):\n encoding = cchardet.detect(data)['encoding']\n if new_coding.upper() != encoding.upper():\n data = data.decode(encoding, data).encode(new_coding)\n return data\n\ndef checkIfExist(file):\n return os.path.exists(file)\n\ndef search_by_keyword(QUERY_TERM):\n youtube = build(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION,developerKey=API_KEY)\n search_response = youtube.search().list(q=QUERY_TERM,part=\"id,snippet\",maxResults=2).execute()\n videos = []\n for search_result in search_response.get(\"items\", []):\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n videos.append(\"%s\" % search_result[\"id\"][\"videoId\"])\n return videos\n\ndef main(argv):\n response = requests.get(CRAWL_URL)\n data = response.text\n soup = BeautifulSoup(data, \"html.parser\")\n count = 0;\n #Parse shazam top 100\n for article in soup.find_all(class_='ti__container'):\n print(Color.OKGREEN + \"[+]Start scraping\" + Color.ENDC)\n song = {}\n song['image_url'] = article.find(class_=\"ti__cover-art\").img.attrs.get(\"src\")\n song['artist_name'] = article.find(class_=\"ti__artist\").text.strip().replace(\"\\'\", \"’\").replace(\"\\\"\", \"’\").replace(\"/\", \"\\\\\")\n song['track_url'] = article.find(class_=\"ti__cover-art\").a.attrs.get(\"href\")\n #Get button for album info\n buybtn = article.find('a', {'class': 'buybtn buybtn--Itunes'})\n song['album_url'] = buybtn.attrs.get(\"href\")\n response3 = requests.get(song['album_url'])\n data3 = response3.text\n soup3 = BeautifulSoup(data3, \"html.parser\")\n song['album_title'] = soup3.find(\"h1\", {'itemprop':'name'})\n if(song['album_title'] != None):\n song['album_title'] = song['album_title'].text.strip().replace(\"\\'\", \"’\").replace(\"\\\"\", \"’\").replace(\"/\", \"\\\\\")\n print(Color.OKGREEN + \"[+]Scraping Album %s\" % song['album_title'] + Color.ENDC)\n song['song_year'] = soup3.find(\"span\", {'itemprop':'dateCreated'}).text.strip()\n song['song_genre'] = soup3.find(\"span\", {'itemprop':'genre'}).text.strip()\n song['local_image'] = (SAVE_PATH + \"albumimages/\"+song['album_title']+\".jpg\").replace(\"\\'\", \"’\").replace(\"\\\"\", \"’\")\n f = open(song['local_image'],'wb')\n f.write(urllib.request.urlopen(song['image_url']).read())\n f.close()\n print(Color.OKBLUE + \"[+]Fetched date [%s]\" % song['song_year']+ Color.ENDC)\n print(Color.OKBLUE + \"[+]Fetched genre [%s]\" % song['song_genre']+ Color.ENDC)\n print(Color.OKBLUE + \"[+]Fetched image [%s]\" % song['image_url']+ Color.ENDC)\n tracknum = 0\n print(Color.OKGREEN + \"[+]Scraping tracks from %s\" % song['album_title']+ Color.ENDC)\n for name in soup3.find_all(\"tr\", {'itemprop':'track'}):\n tracknum += 1\n song['song_track'] = tracknum\n if(name.attrs.get('preview-title') != None):\n song['song_name'] = html.unescape(name.attrs.get('preview-title')).replace(\"\\'\", \"’\").replace(\"\\\"\", \"’\").replace(\"/\", \"\\\\\")\n song['title'] = song['artist_name'] + \" - \" + song['song_name']\n print(Color.OKGREEN + \"\\t[+][Track] %s \" % song['song_name']+ Color.ENDC)\n #Download from youtube here\n videos = search_by_keyword(song['title'] + \" VEVO official\")\n if(len(videos) > 0):\n try:\n toDownload = \"http://www.youtube.com/watch?v=\" + videos[0]\n except ValueError:\n toDownload = \"http://www.youtube.com/watch?v=\" + videos[1]\n song['youtube_url'] = toDownload\n song['path'] = (SAVE_PATH+song['album_title']+\"/\"+song['song_name']+\".mp3\").replace(\"\\'\", \"’\").replace(\"\\\"\", \"’\")\n if not checkIfExist(song['path']):\n print(Color.OKGREEN + \"\\t\\t[+][Downloading] %s \" % song['song_name']+ Color.ENDC)\n try:\n os.system(\"youtube-dl -q -x --audio-format 'mp3' -o '\"+SAVE_PATH+song['album_title']+\"/\"+song['song_name']+\".%(ext)s' '\"+toDownload+\"'\")\n\n #Fetch lyrics\n try:\n song['song_lyrics'] = PyLyrics.getLyrics(song['artist_name'],song['song_name'])\n print(Color.OKBLUE + \"\\t\\t[+][Fetched lyrics]\"+ Color.ENDC)\n except:\n song['song_lyrics'] = \"\"\n print(Color.FAIL + \"\\t\\t[-][Unable to fetch lyrics]\"+ Color.ENDC)\n\n # add ID3 tag if it doesn't exist\n try:\n tags = ID3(song['path'])\n except ID3NoHeaderError:\n tags = ID3()\n\n print(Color.OKGREEN + \"\\t\\t[+][Tagging]\"+ Color.ENDC)\n #tags[\"APIC\"] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover Picture',data=base64.b64encode(open(song['local_image']).read()).decode(\"utf-8\"))\n tags[\"TIT2\"] = TIT2(encoding=3, text=song['song_name'])\n tags[\"TALB\"] = TALB(encoding=3, text=song['album_title'])\n tags[\"TPE2\"] = TPE2(encoding=3, text=song['artist_name'])\n tags[\"COMM\"] = COMM(encoding=3, lang=u'eng', desc='desc', text=song['image_url'])\n tags[\"TPE1\"] = TPE1(encoding=3, text=song['artist_name'])\n tags[\"TCON\"] = TCON(encoding=3, text=song['song_genre'])\n tags[\"TDRC\"] = TDRC(encoding=3, text=song['song_year'].split(\" \")[2])\n tags[\"TRCK\"] = TRCK(encoding=3, text=str(song['song_track']))\n tags[u\"USLT::'eng'\"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=song['song_lyrics']))\n tags.save(song['path'])\n except:\n continue\n print(Color.FAIL + \"\\t\\t[-][Unable to download]\"+ Color.ENDC)\n else:\n print(Color.WARNING + \"\\t\\t[-][Exists]\"+ Color.ENDC)\n else:\n print(Color.FAIL + \"\\t\\t[-][Failed to find song]\"+ Color.ENDC)\n else:\n print(Color.FAIL + \"\\t\\t[-][Failed to find information]\"+ Color.ENDC)\n if(checkIfExist(SAVE_PATH+song['album_title'])):\n shutil.move(song['local_image'], SAVE_PATH+song['album_title']+\"/\"+song['album_title']+\".jpg\")\n count += 1\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"Personal/Python/shazam.py","file_name":"shazam.py","file_ext":"py","file_size_in_byte":8359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"465136396","text":"\"\"\"\r\nBasic example for a bot that uses inline keyboards.\r\n\"\"\"\r\nimport logging\r\nimport json\r\nimport requests\r\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, update\r\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler,CallbackContext, MessageHandler, Filters\r\n\r\nlogging.basicConfig(\r\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO\r\n)\r\nlogger = logging.getLogger(__name__)\r\n\r\ndef start(update:update ,context:CallbackContext) -> None:\r\n update.message.reply_text('Hi! This will give you sumary of Test wikibot')\r\n\r\n\r\ndef button(update:update ,context:CallbackContext):\r\n query = update.callback_query\r\n\r\n # CallbackQueries need to be answered, even if no notification to the user is needed\r\n # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery\r\n query.answer()\r\n\r\n query.edit_message_text(text=\"Selected option: {}\".format(query.data))\r\n\r\n\r\ndef help_command(update:update ,context:CallbackContext) -> None:\r\n update.message.reply_text(\"Use /start to test this bot.\")\r\n\r\ndef test_wikibot(update:update ,context:CallbackContext):\r\n\r\n query = update.message.text\r\n\r\n url = \"https://wikipenapi.herokuapp.com/page/?q=\"\r\n\r\n r = requests.get(url+query)\r\n\r\n ans = r.text\r\n result = json.loads(ans)\r\n\r\n a = result[\"details\"]\r\n b = a[\"tittle\"]\r\n c = a[\"url\"]\r\n detailes = f\"The details of the are as follows\\nTittle of the page is: {b}\\nUrl of the page is: {c}\"\r\n update.message.reply_text(detailes)\r\n\r\n d = result[\"page\"]\r\n e = d[\"summary\"]\r\n update.message.reply_text(e)\r\n keyboard = [[InlineKeyboardButton(\"Url to the page\", url=c)]]\r\n\r\n reply_markup = InlineKeyboardMarkup(keyboard)\r\n\r\n update.message.reply_text('Please choose:', reply_markup=reply_markup)\r\n\r\ndef main():\r\n # Create the Updater and pass it your bot's token.\r\n # Make sure to set use_context=True to use the new context based callbacks\r\n # Post version 12 this will no longer be necessary\r\n updater = Updater(\"1479454800:AAE8yLKQJAIFGAV3iRxt6cCuHLkizyFjIbA\", use_context=True)\r\n\r\n updater.dispatcher.add_handler(CommandHandler('start', start))\r\n updater.dispatcher.add_handler(CallbackQueryHandler(button))\r\n updater.dispatcher.add_handler(CommandHandler('help', help_command))\r\n updater.dispatcher.add_handler(MessageHandler(Filters.text, test_wikibot))\r\n\r\n # Start the Bot\r\n updater.start_polling()\r\n\r\n # Run the bot until the user presses Ctrl-C or the process receives SIGINT,\r\n # SIGTERM or SIGABRT\r\n updater.idle()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"newkey.py","file_name":"newkey.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"162633025","text":"from collections import OrderedDict, defaultdict\nfrom itertools import groupby\n\nfrom onegov.ballot import List\nfrom onegov.core.orm import as_selectable_from_path\nfrom onegov.core.utils import module_path\nfrom onegov.election_day import _\nfrom sqlalchemy import desc, select\nfrom sqlalchemy.orm import object_session\n\nfrom onegov.election_day.utils.common import LastUpdatedOrderedDict\n\n\ndef get_aggregated_list_results(election, session, use_checks=False):\n if election.type == 'majorz':\n return {}\n\n agg_lr_query = as_selectable_from_path(\n module_path(\n 'onegov.election_day', 'queries/aggregated_list_results.sql'))\n\n agg_lr = agg_lr_query.c\n query = select(agg_lr).where(agg_lr.election_id == election.id)\n result = session.execute(query)\n\n data = LastUpdatedOrderedDict({})\n\n # checks\n lst_ids = set()\n lst_list_ids = set()\n lst_names = set()\n validations = defaultdict(list)\n summary = OrderedDict()\n\n for lid, g in groupby(result, lambda l: l.id):\n for lst in g:\n # checks\n lst_ids.add(lst.id)\n lst_list_ids.add(lst.list_id)\n lst_names.add(lst.name)\n\n summary.setdefault('election_list_votes',\n int(lst.election_list_votes))\n summary.setdefault('election_candidate_votes',\n int(lst.election_candidate_votes))\n\n key = lst.name\n data.setdefault(\n key,\n {\n 'name': lst.name,\n 'list_id': lst.list_id,\n 'votes': lst.list_votes,\n 'total_candidate_votes': int(lst.candidate_votes_by_list),\n 'perc_to_total_votes': float(lst.perc_to_total_votes),\n 'number_of_mandates': lst.number_of_mandates\n if election.completed else 0,\n 'candidates': [],\n }\n )\n data[key]['candidates'].append({\n 'family_name': lst.family_name,\n 'first_name': lst.first_name,\n 'total_votes': lst.candidate_votes,\n 'perc_to_list_votes': float(lst.perc_to_list_votes)\n })\n\n # all of these must be unique for an election\n assert len(lst_ids) == len(lst_list_ids)\n assert len(lst_list_ids) == len(lst_names)\n\n total_list_votes = 0\n\n for name, item in data.items():\n if item['votes'] < item['total_candidate_votes']:\n validations['errors'].append(\n f'List {name} has more candidates votes than list votes.'\n )\n total_list_votes += item['votes']\n\n assert summary['election_list_votes'] == total_list_votes\n\n if summary['election_list_votes'] < summary['election_candidate_votes']:\n validations['errors'].append(\n f\"The election has less list votes than candidate votes\"\n )\n\n return {\n 'summary': summary,\n 'validations': validations,\n 'results': data\n }\n\n\ndef get_list_results(election, session):\n \"\"\" Returns the aggregated list results as list. \"\"\"\n\n result = session.query(\n List.name, List.votes, List.list_id, List.number_of_mandates\n )\n result = result.order_by(desc(List.votes))\n result = result.filter(List.election_id == election.id)\n\n return result\n\n\ndef get_lists_data(election, request):\n \"\"\"\" View the lists as JSON. Used to for the lists bar chart. \"\"\"\n\n if election.type == 'majorz':\n return {\n 'results': [],\n 'majority': None,\n 'title': election.title\n }\n\n return {\n 'results': [{\n 'text': item[0],\n 'value': item[1],\n 'value2': item[3] if election.completed else None,\n 'class': 'active' if election.completed\n and item[3] else 'inactive',\n } for item in get_list_results(election, object_session(election))],\n 'majority': None,\n 'title': election.title\n }\n\n\ndef get_lists_panachage_data(election, request):\n \"\"\"\" Get the panachage data as JSON. Used to for the panachage sankey\n chart.\n\n \"\"\"\n # Fixme: Rewrite this function, it is very confusing what is does and why\n if election.type == 'majorz':\n return {}\n\n if not election.has_lists_panachage_data:\n return {}\n\n blank = request.translate(_(\"Blank list\")) if request else '-'\n\n nodes = OrderedDict()\n nodes['left.999'] = {'name': blank}\n for list_ in election.lists.order_by(List.name):\n nodes[f'left.{list_.list_id}'] = {'name': list_.name}\n for list_ in election.lists:\n nodes[f'right.{list_.list_id}'] = {'name': list_.name}\n node_keys = list(nodes.keys())\n\n links = []\n for list_target in election.lists:\n target = node_keys.index(f'right.{list_target.list_id}')\n remaining = list_target.votes - sum(\n [r.votes for r in list_target.panachage_results]\n )\n for result in list_target.panachage_results:\n source = node_keys.index(f'left.{result.source}')\n votes = result.votes\n if list_target.list_id == result.source:\n votes += remaining\n links.append({\n 'source': source,\n 'target': target,\n 'value': votes\n })\n\n count = 0\n for key in nodes.keys():\n count = count + 1\n nodes[key]['id'] = count\n\n return {\n 'nodes': list(nodes.values()),\n 'links': links,\n 'title': election.title\n }\n","sub_path":"src/onegov/election_day/utils/election/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"569626906","text":"# PS1b assignment\nannual_salary = float(input(\"Enter your annual salary: \"))\nportion_save = float(input(\"Enter the percent of your salary to save, as a decimal: \"))\ntotal_cost = float(input(\"Enter the cost of your dream home: \"))\nsemi_annual_raise = float(input(\"Enter the semi-annual-raise, as a decimal: \"))\n\nr = 0.04\nportion_down_payment = 0.25\ncurrent_savings = float(0)\ncount_month = 1\n\nwhile current_savings < total_cost * portion_down_payment:\n if count_month % 6 == 0:\n annual_salary += annual_salary * semi_annual_raise\n current_savings += annual_salary * portion_save / 12\n current_savings += current_savings * r / 12\n count_month += 1\nprint(\"Number of months: \", count_month)\n","sub_path":"3_String_ApproximateSolutions/ps1/ps1b.py","file_name":"ps1b.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"406874462","text":"from requests_html import HTMLSession\nimport urllib.request\nsession = HTMLSession()\n\ndef ngpScrap(pageUrl, scrapedWebsite):\n\n ng = session.get(pageUrl)\n\n # IF FINDS ITEM'S NAME, IT CONTINUES\n\n ngItemName = ng.html.find('.nadpis-dielo', first=True)\n\n if not ngItemName == None:\n\n artworkData = {}\n\n # SCRAPPING ITEM NAME\n\n ngItemName = ng.html.find('.nadpis-dielo', first=True)\n if not ngItemName == None:\n artworkData['Title'] = ngItemName.text\n else:\n artworkData['Title'] = 'n/a'\n\n # SCRAPPING AUTHOR\n\n ngAuthor = ng.html.find('.inline', first=True)\n if not ngAuthor == None:\n artworkData['Author'] = ngAuthor.text\n else:\n artworkData['Author'] = 'n/a'\n\n # SCRAPPING CREATION DATE\n\n ngCreationDate = ng.html.find('tr', containing='datace:', first=True)\n if not ngCreationDate == None:\n artworkData['Creation Date'] = ''.join(list(ngCreationDate.text)[8:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Creation Date'] = 'n/a'\n\n\n # SCRAPPING DIMENSIONS\n\n ngDimensions = ng.html.find('tr', containing='rozměry:', first=True)\n if not ngDimensions == None:\n artworkData['Dimensions'] = ''.join(list(ngDimensions.text)[9:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Dimensions'] = 'n/a'\n\n # SCRAPPING CURATED SETS\n\n ngCuratedSets = ng.html.find('tr', containing='tematické celky:', first=True)\n if not ngCuratedSets == None:\n artworkData['Curated Sets'] = ''.join(list(ngCuratedSets.text)[17:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Curated Sets'] = 'n/a'\n\n # SCRAPPING MATERIAL\n\n ngMaterial = ng.html.find('tr', containing='materiál:', first=True)\n if not ngMaterial == None:\n artworkData['Material'] = ''.join(list(ngMaterial.text)[10:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Material'] = 'n/a'\n\n # SCRAPPING TECHNIQUE\n\n ngTechnique = ng.html.find('tr', containing='technika:', first=True)\n if not ngTechnique == None:\n artworkData['Technique'] = ''.join(list(ngTechnique.text)[10:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Technique'] = 'n/a'\n\n # SCRAPPING SIGNATURE\n\n ngSignature = ng.html.find('tr', containing='značení:', first=True)\n if not ngSignature == None:\n artworkData['Artist signature'] = ''.join(list(ngSignature.text)[9:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Artist signature'] = 'n/a'\n\n # SCRAPPING INVENTORY ID\n\n ngInventoryId = ng.html.find('tr', containing='inventární číslo:', first=True)\n if not ngInventoryId == None:\n ngInventoryId = ''.join(list(ngInventoryId.text)[18:]) # CUT X LETTERS FROM BEGINNING\n ngInventoryId = ngInventoryId.replace(\" \", \"-\")\n artworkData['Inventory ID'] = ngInventoryId\n else:\n artworkData['Inventory ID'] = 'n/a'\n\n # SCRAPPING SUBCOLLECTION\n\n ngSubcollection = ng.html.find('tr', containing='sbírka:', first=True)\n if not ngSubcollection == None:\n artworkData['Subcollection'] = ''.join(list(ngSubcollection.text)[8:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Subcollection'] = 'n/a'\n\n # SCRAPPING LICENCE\n\n ngLicence = ng.html.find('tr', containing='licence:', first=True)\n if not ngLicence == None:\n artworkData['Licence'] = ''.join(list(ngLicence.text)[9:]) # CUT X LETTERS FROM BEGINNING\n else:\n artworkData['Licence'] = 'n/a'\n\n # SCRAPPING DESCRIPTION\n\n ngDescription = ng.html.find('.description', first=True)\n if not ngDescription == None:\n artworkData['Description'] = ngDescription.text\n else:\n artworkData['Description'] = 'n/a'\n\n # ADDING COLLECTION\n\n artworkData['Collection'] = 'National Gallery in Prague'\n collectionShortcut = 'NGP'\n\n # SAVING URL\n\n artworkData['Url'] = pageUrl\n\n # ADDING KEY\n\n ngKey = collectionShortcut + '-' + ngInventoryId\n artworkData['Key'] = ngKey\n\n # SCRAPPING IMAGE\n\n def dlJpg(iiUrl, filePath, ngKey):\n imagePath = 'temp/' + filePath + ngKey + '.jpg'\n artworkData['Image ID'] = ngKey + '.jpg'\n urllib.request.urlretrieve(iiUrl, imagePath)\n\n iiUrl = ng.html.find('.img-dielo', first=True)\n if not iiUrl == None:\n iiUrl = iiUrl.attrs\n iiUrl = iiUrl.get(\"src\") # TAKES VALUE OF SRC ATTRIBUTE\n iiUrl = scrapedWebsite + iiUrl\n dlJpg(iiUrl, '/', ngKey)\n\n else:\n iiUrl = 'n/a'\n\n # OUTPUT\n\n print(artworkData)\n return artworkData\n\n else:\n print('Nothing here')\n\n\n","sub_path":"scraperNgp.py","file_name":"scraperNgp.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"309225411","text":"import sys\nfrom collections import deque\nfrom collections import defaultdict\n\ndef bfs(graph, root):\n visited = []\n queue = deque([root])\n\n while queue:\n node = queue.popleft()\n if node not in visited:\n visited.append(node)\n if node in graph:\n tmp = list(set(graph[node]) - set(visited))\n queue.extend(sorted(tmp))\n\n return visited\n\ninput = sys.stdin.readline\n\nn = int(input())\ngraph = defaultdict(list)\nfor i in range(int(input())):\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n\nprint(len(bfs(graph, 1))-1)\n\n\n# dfs가 더 연산이 빠른듯?\n\ndef dfs(v):\n visited[v] = 1\n for w in adj_lst[v]:\n if not visited[w]:\n dfs(w)\n\n\nV = int(input())\nE = int(input())\nadj_lst = [[] for _ in range(V+1)]\nfor _ in range(E):\n n1, n2 = map(int, input().split())\n adj_lst[n1].append(n2)\n adj_lst[n2].append(n1)\nvisited = [0]*(V+1)\ndfs(1)\nprint(sum(visited)-1)\n","sub_path":"Algorithm/BOJ/silver_2606_바이러스.py","file_name":"silver_2606_바이러스.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295462164","text":"# coding: utf-8\r\n# This implements One Card Poker.\r\n\r\nfrom extensive_game import ExtensiveGame, ExtensiveGameNode\r\n\r\n\r\nclass OneCardPoker(ExtensiveGame):\r\n \"\"\" This is the game described on 'http://www.cs.cmu.edu/~ggordon/poker/'.\r\n Rules: each player is privately dealt one card from a deck of 'n_cards'\r\n cards (without replacement). Currently there is one card for each card\r\n value. Each player antes 1 chip (a forced initial bet). Player 1 then bets\r\n either 0 or 1. Player 2 can fold (if player 1 bet 1), match player 1's bet,\r\n or, if player 1 bet 0, then player 2 can raise by betting 1. In the last\r\n situation, player 1 then gets a chance to match the bet or fold.\r\n \"\"\"\r\n\r\n @staticmethod\r\n def compute_utility(betting_actions, hole_cards):\r\n \"\"\" Given actions in 'betting_actions' and hole_cards in 'hole_cards',\r\n compute the utility for both players at a terminal node.\r\n \"\"\"\r\n # The bets are 1 (for the ante), then the sum of the even actions (for\r\n # player 1) and the odd actions (for player 2).\r\n bets = {1: 1.0, 2: 1.0}\r\n for i, action in enumerate(betting_actions):\r\n bets[(i % 2) + 1] += action\r\n winner = 1 if hole_cards[1] > hole_cards[2] else 2\r\n loser = 2 if hole_cards[1] > hole_cards[2] else 1\r\n # The winner wins the amount the loser bet, and the loser loses this\r\n # amount.\r\n return {winner: bets[loser], loser: -bets[loser]}\r\n\r\n @staticmethod\r\n def create_one_card_tree(action_list, cards):\r\n \"\"\" Creates a tree for one card Poker. 'cards' is a list of numbers of\r\n cards, defining the deck. The numbers should be unique. Initially this\r\n should be called with 'action_list' being an empty list.\r\n \"\"\"\r\n if len(action_list) == 0:\r\n # We are at the root of the tree, so we create a chance node for\r\n # player 1.\r\n root = ExtensiveGameNode(0)\r\n # This node is hidden from player 2\r\n root.hidden_from = [2]\r\n for card in cards:\r\n # Create a game tree below this node.\r\n root.children[card] = OneCardPoker.create_one_card_tree(\r\n [card], cards)\r\n root.chance_probs[card] = 1.0 / len(cards)\r\n return ExtensiveGame(root)\r\n elif len(action_list) == 1:\r\n # We are at a chance node for player 2, so we create this chance\r\n # node, including its children.\r\n node = ExtensiveGameNode(0)\r\n # This node is hidden from player 1\r\n node.hidden_from = [1]\r\n for card in cards:\r\n # Player 2 can't be dealt the card that player 1 was dealt.\r\n if card == action_list[0]:\r\n continue\r\n # Otherwise create a child node below\r\n node.children[card] = OneCardPoker.create_one_card_tree(\r\n action_list + [card], cards)\r\n node.chance_probs[card] = 1.0 / (len(cards) - 1.0)\r\n return node\r\n elif len(action_list) == 2:\r\n # It's player 1's first turn.\r\n node = ExtensiveGameNode(1)\r\n node.children[0] = OneCardPoker.create_one_card_tree(\r\n action_list + [0], cards)\r\n node.children[1] = OneCardPoker.create_one_card_tree(\r\n action_list + [1], cards)\r\n return node\r\n elif len(action_list) == 3:\r\n # It's player 2's first turn.\r\n node = ExtensiveGameNode(2)\r\n node.children[0] = OneCardPoker.create_one_card_tree(\r\n action_list + [0], cards)\r\n node.children[1] = OneCardPoker.create_one_card_tree(\r\n action_list + [1], cards)\r\n return node\r\n elif len(action_list) == 4:\r\n # It's player 1's second turn (if the node isn't terminal).\r\n if action_list[3] == 0 or action_list[2] == action_list[3]:\r\n # The second player folded, or called a bet of 0, or called a\r\n # bet of 1. Thus this node is terminal.\r\n node = ExtensiveGameNode(-1)\r\n hole_cards = {1: action_list[0], 2: action_list[1]}\r\n node.utility = OneCardPoker.compute_utility(\r\n action_list[2:], hole_cards)\r\n return node\r\n else:\r\n # The actions were [0,1], and so player 1 gets another chance to\r\n # call or fold.\r\n node = ExtensiveGameNode(1)\r\n node.children[0] = OneCardPoker.create_one_card_tree(\r\n action_list + [0], cards)\r\n node.children[1] = OneCardPoker.create_one_card_tree(\r\n action_list + [1], cards)\r\n return node\r\n elif len(action_list) == 5:\r\n # It's player 2's second turn (but this actually must be terminal).\r\n node = ExtensiveGameNode(-1)\r\n hole_cards = {1: action_list[0], 2: action_list[1]}\r\n node.utility = OneCardPoker.compute_utility(\r\n action_list[2:], hole_cards)\r\n return node\r\n assert False\r\n\r\n @staticmethod\r\n def create_game(n_cards):\r\n \"\"\" Creates the One Card Poker game, with the given number of uniquely\r\n numbered cards in the deck, numbered 1 up to n_cards.\r\n \"\"\"\r\n game_tree = OneCardPoker.create_one_card_tree([], range(1, n_cards + 1))\r\n return game_tree\r\n","sub_path":"one_card_poker.py","file_name":"one_card_poker.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"578733776","text":"from django.conf.urls import patterns, include, url\nfrom quotes.models import Quote, QuoteForm\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'quotes.views.index'),\n\turl(r'^newquote/$', 'quotes.views.add'),\n\turl(r'^gratitude/$', 'quotes.views.thanks'),\n\turl(r'^quotes/randquo/$', 'quotes.views.random_quote'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^quotes/validatecomputer/$', 'ajax_validation.views.validate', {'form_class': QuoteForm}, 'quote_form_validate'),\n)\n","sub_path":"QuoteBoard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"577554536","text":"\"\"\"Provides functions for loading and using data from file\"\"\"\n\nimport ConfigParser\nimport collections\n\nfrom pyre import dice, types\n\n\nclass Field(object):\n \"\"\"Base class for InfoEntry fields\"\"\"\n\n def __init__(self, default=None):\n self.default = default\n\n def __call__(self, data):\n raise NotImplementedError()\n\n\nclass Section(object):\n \"\"\"Base class for InfoDB custom section\"\"\"\n\n def __call__(self, key, value):\n raise NotImplementedError()\n\n\nclass IntField(Field):\n \"\"\"Field containing an integer\"\"\"\n\n def __call__(self, data):\n return int(data)\n\n\nclass FloatField(Field):\n \"\"\"Field containing a float\"\"\"\n\n def __call__(self, data):\n return float(data)\n\n\nclass BoolField(Field):\n \"\"\"Field containing a bool\"\"\"\n\n def __init__(self, default=None, true=None, false=None):\n Field.__init__(self, default)\n self.mapping = {}\n for key in true if true else ['true', 't', 'yes', 'y', '1']:\n self.mapping[key] = True\n for key in false if false else ['false', 'f', 'no', 'n', '0']:\n self.mapping[key] = False\n\n def __call__(self, data):\n return self.mapping[data.lower()]\n\n\nclass IntSection(Section):\n \"\"\"Section containing integer values\"\"\"\n\n def __call__(self, key, value):\n return key, int(value)\n\n\ndef _parse_tile(data):\n data = tuple(x for x in data.split(','))\n char, color = data[:2]\n color = types.Color.try_by_name(color)\n if len(data) == 3:\n return types.Glyph(char, color, sprite_id=int(data[2]))\n else:\n return types.Glyph(char, color)\n\n\nclass TileField(Field):\n \"\"\"Field containing a Glyph\"\"\"\n\n def __call__(self, data):\n return _parse_tile(data)\n\n\nclass TileSection(Section):\n \"\"\"Section containing Glyph values\"\"\"\n\n def __call__(self, key, value):\n return key, _parse_tile(value)\n\n\nclass IntTupleField(Field):\n \"\"\"Field containing an integer 2-tuple\"\"\"\n\n def __init__(self, sep=',', default=None):\n Field.__init__(self, default)\n self.sep = sep\n\n def __call__(self, data):\n x, y = (int(x) for x in data.split(self.sep))\n return x, y\n\n\nclass RollField(IntTupleField):\n \"\"\"Field containing parameters for an xdy roll\"\"\"\n\n def __init__(self, default=None):\n IntTupleField.__init__(self, 'd', default)\n\n\nclass MeleeField(Field):\n \"\"\"Field containing a bonus and parameters for an xdy roll\"\"\"\n\n def __init__(self, default=(0, (0, 0))):\n Field.__init__(self, default)\n\n def __call__(self, data):\n bonus, roll = data.split(',')\n x, y = (int(x) for x in roll.split('d'))\n return int(bonus), (x, y)\n\n\nclass StrField(Field):\n \"\"\"Field containing a string value\"\"\"\n\n def __call__(self, data):\n return data\n\n\nclass ListField(Field):\n \"\"\"Field containing a list of string values\"\"\"\n\n def __init__(self, sep=',', default=None):\n Field.__init__(self, default)\n self.sep = sep\n\n def __call__(self, data):\n return data.split(self.sep) if data else []\n\n\nclass FlagsField(Field):\n \"\"\"Field containing a list of flags\"\"\"\n\n def __init__(self, flag_sep=';', value_sep=':', default=None, **mapping):\n Field.__init__(self, default)\n self.flag_sep = flag_sep\n self.value_sep = value_sep\n self.mapping = mapping\n\n def _flag(self, data):\n if self.value_sep in data:\n key, value = (x.strip() for x in data.split(self.value_sep, 1))\n if key in self.mapping:\n value = self.mapping[key](value)\n return key, value\n else:\n return data.strip(), None\n\n def __call__(self, data):\n return dict(self._flag(value) for value in data.split(self.flag_sep))\n\n\nclass entryattr(object): # pylint: disable=C0103\n \"\"\"Stores an attribute for an Entry type\"\"\"\n\n def __init__(self, attr):\n self.attr = attr\n\n\nclass InfoDBMeta(type):\n \"\"\"Metaclass which collects Field attributes\"\"\"\n\n def __new__(mcs, name, bases, attrs):\n fields = {}\n sections = {}\n entry_attrs = {}\n\n for base in bases:\n if hasattr(base, 'fields'):\n fields.update(base.fields)\n if hasattr(base, 'sections'):\n sections.update(base.sections)\n if hasattr(base, 'entry_attrs'):\n entry_attrs.update(base.entry_attrs)\n\n for key, value in attrs.items():\n if isinstance(value, Field):\n fields[key] = value\n elif isinstance(value, Section):\n sections[key] = value\n elif isinstance(value, entryattr):\n entry_attrs[key] = value.attr\n else:\n continue # skip pop\n attrs.pop(key)\n\n attrs['fields'] = fields\n attrs['sections'] = sections\n attrs['entry_attrs'] = entry_attrs\n\n entry_name = name + 'Entry'\n entry_keys = sorted(fields.keys() + ['name'])\n base_type = collections.namedtuple(entry_name + 'Base', entry_keys)\n attrs['Entry'] = type(entry_name, (base_type,), entry_attrs)\n\n return type.__new__(mcs, name, bases, attrs)\n\n\n# pylint: disable=E1101\n\nclass InfoDB(object):\n \"\"\"Represents an info file database\"\"\"\n\n __metaclass__ = InfoDBMeta\n\n def __init__(self, filename):\n defaults = {}\n for key, value in self.fields.iteritems():\n if value.default is not None:\n defaults[key] = value.default\n\n config = ConfigParser.ConfigParser()\n config.readfp(open(filename))\n\n self.data = {}\n for section in config.sections():\n if section in self.sections:\n entry = {}\n parser = self.sections[section]\n for key, value in config.items(section):\n key, value = parser(key, value)\n entry[key] = value\n self.data[section] = entry\n else:\n entry = {'name': section}\n for key, field in self.fields.iteritems():\n if config.has_option(section, key):\n entry[key] = field(config.get(section, key))\n else:\n entry[key] = defaults[key]\n self.data[section] = self.Entry(**entry)\n\n def __getitem__(self, name):\n return self.data[name]\n\n def select(self, condition):\n \"\"\"Returns a list of Entry for which the condition is True\"\"\"\n return [entry for entry in self.data.values() if condition(entry)]\n\n def choice(self):\n \"\"\"Returns a random Entry from the InfoDB\"\"\"\n return dice.choice(self.data.values())\n","sub_path":"pyre/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"333955380","text":"import tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers, models\r\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D\r\nimport numpy as np\r\nimport h5py\r\n\r\n#config = tf.compat.v1.ConfigProto(gpu_options = \r\n# tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8)\r\n# device_count = {'GPU': 1}\r\n#)\r\n#config.gpu_options.allow_growth = True\r\n#session = tf.compat.v1.Session(config=config)\r\n#tf.compat.v1.keras.backend.set_session(session)\r\n\r\n\r\nfilename = 'current_slice.h5'\r\nhf = h5py.File(filename, 'r')\r\naa = list(hf.keys())\r\nimage1 = hf.get('image1')\r\nimage1 = np.array(image1)\r\nimage2 = hf.get('image2')\r\nimage2 = np.array(image2)\r\nimage3 = hf.get('image3')\r\nimage3 = np.array(image3)\r\nimage4 = hf.get('image4')\r\nimage4 = np.array(image4)\r\nimage1_loc = hf.get('image1_loc')\r\nimage1_loc = np.array(image1_loc)\r\nhf.close()\r\n\r\n\r\nmodel = tf.keras.models.load_model('96p_HC_agree_2_window.h5')\r\n\r\npredictions_b = model.predict([image1, image2])\r\n\r\npredictions_max = np.argmax(predictions_b, axis=1)\r\n\r\n\r\nhf = h5py.File('data_back.h5', 'w')\r\nhf.create_dataset('predictions_max', data=predictions_max)\r\nhf.create_dataset('image1_loc', data=image1_loc)\r\nhf.close()\r\n","sub_path":"005_AI_Cell_Counting/20200526_deep_learning_pericyte_HBUC_2_window/brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"478334962","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom . import assertion\nfrom . import exectools\nfrom . import logutil\nfrom .metadata import Metadata\n\nlogger = logutil.getLogger(__name__)\n\n\nclass ImageMetadata(Metadata):\n\n def __init__(self, runtime, data_obj):\n super(ImageMetadata, self).__init__('image', runtime, data_obj)\n self.image_name = self.config.name\n self.image_name_short = self.image_name.split('/')[-1]\n\n @property\n def base_only(self):\n \"\"\"\n Some images are marked base-only. Return the flag from the config file\n if present.\n \"\"\"\n return self.config.base_only\n\n def get_latest_build_info(self, product_version):\n \"\"\"\n Queries brew to determine the most recently built release of the component\n associated with this image. This method does not rely on the \"release\"\n label needing to be present in the Dockerfile.\n\n :return: A tuple: (component name, version, release); e.g. (\"registry-console-docker\", \"v3.6.173.0.75\", \"1\")\n \"\"\"\n\n component_name = self.get_component_name()\n\n tag = \"{}-candidate\".format(self.branch())\n\n rc, stdout, stderr = exectools.cmd_gather([\"brew\", \"latest-build\", tag, component_name])\n\n assertion.success(rc, \"Unable to search brew builds: %s\" % stderr)\n\n latest = stdout.strip().splitlines()[-1].split(' ')[0]\n\n if not latest.startswith(component_name):\n # If no builds found, `brew latest-build` output will appear as:\n # Build Tag Built by\n # ---------------------------------------- -------------------- ----------------\n raise IOError(\"No builds detected for %s using tag: %s\" % (self.qualified_name, tag))\n\n # latest example: \"registry-console-docker-v3.6.173.0.75-1\"\"\n name, version, release = latest.rsplit(\"-\", 2) # [ \"registry-console-docker\", \"v3.6.173.0.75\", \"1\"]\n\n return name, version, release, product_version[self.name]\n","sub_path":"elliottlib/imagecfg.py","file_name":"imagecfg.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"471702845","text":"import array\n\nfrom pybnb.pyomo.misc import mpi_partition\n\nfrom ..common import mpi_available\nfrom runtests.mpi import MPITest\n\n\ndef _test_mpi_partition(comm):\n test_ranks = [0]\n if comm is not None:\n import mpi4py.MPI\n\n test_ranks = list(range(comm.size))\n for x in (\n [],\n [\"a\"],\n [\"a\", \"b\"],\n [\"a\", \"b\", \"c\"],\n [\"a\", \"b\", \"c\"] * 2,\n [\"a\", \"b\", \"c\"] * 4,\n [\"a\", \"b\", \"c\"] * 16,\n [\"a\", \"b\", \"c\"] * 32,\n ):\n for root in test_ranks:\n x_accessed_local = array.array(\"i\", [0]) * len(x)\n for i, xi in mpi_partition(comm, list(enumerate(x)), root=root):\n assert x[i] == xi\n x_accessed_local[i] += 1\n x_accessed = array.array(\"i\", [0]) * len(x)\n if comm is not None:\n comm.Allreduce(\n [x_accessed_local, mpi4py.MPI.INT],\n [x_accessed, mpi4py.MPI.INT],\n op=mpi4py.MPI.SUM,\n )\n comm.Barrier()\n else:\n x_accessed[:] = x_accessed_local[:]\n for xi in x_accessed:\n assert xi == 1\n\n\ndef test_mpi_partition_no_comm():\n _test_mpi_partition(None)\n\n\nif mpi_available:\n\n @MPITest(commsize=[1, 2, 4])\n def test_mpi_partition(comm):\n _test_mpi_partition(comm)\n","sub_path":"src/tests/mpi/pyomo/test_misc.py","file_name":"test_misc.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"217073986","text":"# coding=utf-8\n# Author: Mattia Panzeri \n# URL: https://gitlab.com/panz3r/web-anime-updater\n#\n# This file is part of WebAnimeUpdater.\n#\n# WebAnimeUpdater is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# WebAnimeUpdater is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with WebAnimeUpdater. If not, see .\n#\n\nimport logging\n\nfrom webanimeupdater import DEBUG\n\n\ndef ex(e):\n \"\"\"\n :param e: The exception to convert into a unicode string\n :return: A unicode string from the exception text if it exists\n \"\"\"\n\n message = u''\n\n if not e or not e.args:\n return message\n\n for arg in e.args:\n if arg is not None:\n if isinstance(arg, (str, unicode)):\n fixed_arg = arg\n else:\n try:\n fixed_arg = u'error {0}'.format(str(arg))\n except Exception:\n fixed_arg = None\n\n if fixed_arg:\n if not message:\n message = fixed_arg\n else:\n try:\n message = u'{0} : {1}'.format(message, fixed_arg)\n except UnicodeError:\n message = u'{0} : {1}'.format(\n unicode(message, errors='replace'),\n unicode(fixed_arg, errors='replace'))\n\n return message\n\n\ndef logger_setup(debug=True):\n logger = logging.getLogger()\n if debug:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.INFO)\n\n logging.basicConfig(format='[%(asctime)s] [%(levelname)-8s] %(message)s')\n\n return logger\n","sub_path":"webanimeupdater/commons/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"151496177","text":"n = int(input())\n\ncases = [i for i in range(111, 1000)]\n\ndef ridout(data):\n temp = list(str(data))\n\n for elem in temp:\n if temp.count(elem) > 1 or elem == '0':\n return True\n \n return False\n\npossible = []\n\nfor elem in cases:\n if not ridout(elem):\n possible.append(elem)\n\ndef get(number, answer):\n case = list(str(answer))\n check = list(str(number))\n\n strike = 0\n ball = 0\n\n for i in range(3):\n if case[i] == check[i]:\n strike += 1\n else:\n if case[i] in check:\n ball += 1\n \n return strike, ball\n\n\ncand = []\n\nfor i in range(n):\n number, strike, ball = map(int, input().split())\n cand.append([number, strike, ball])\n\ncnt = 0\n\nfor elem in possible:\n check = True\n for c in cand:\n strike = c[1]\n ball = c[2]\n\n s, b = get(elem, c[0])\n if s != strike or b != ball:\n check = False\n \n if check:\n cnt += 1\n\nprint(cnt)\n\n\n\n\n\n\n\n","sub_path":"sourcecode/2503.py","file_name":"2503.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"31825026","text":"#\n# 等频离散化\n# @param A int整型一维数组 从小到大已排序整数数列A\n# @param K int整型 划分段数\n# @return int整型二维数组\n#\nclass Solution:\n def discretize_by_frequency(self , A , K ):\n # write code here\n res = [[] for _ in range(K)]\n count = 0\n min_length = 0\n for d in A:\n min_length = min([len(x) for x in res])\n while True:\n i = count\n if not res[i]:\n res[i].append(d)\n break\n elif d == res[i][-1]:\n res[i].append(d)\n break\n elif len(res[i]) == min_length:\n res[i].append(d)\n break\n else:\n count = (count+1)%K\n return res\n\nprint(Solution().discretize_by_frequency([1, 1, 1, 2, 2 , 4, 5, 5],3))\n\n\n\n ","sub_path":"58同城/等频离散化.py","file_name":"等频离散化.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"106352914","text":"import pytest\n\nfrom hypothesis.strategies import (\n binary, booleans, characters, complex_numbers,\n dates, datetimes, decimals, dictionaries, emails, floats,\n integers, just, lists, none, one_of, permutations, sampled_from,\n slices, text, uuids, times, recursive, composite, data)\nfrom hypothesis import given, assume\n\n\n####################################################\n# no composite\n\n@given(integers(0, 255), integers(0, 255), integers(0, 255))\ndef test_with_color(a, b, c):\n color = \"#%02X%02X%02X\" % (a, b, c)\n print(color)\n\n\n####################################################\n# composite\n@composite\ndef my_special_strategy(draw, short=False):\n if short:\n s = integers(0, 15)\n return \"#%01X%01X%01X\" % (draw(s), draw(s), draw(s))\n else:\n l = integers(0, 255)\n return \"#%02X%02X%02X\" % (draw(l), draw(l), draw(l))\n\n@given(my_special_strategy(short=False))\ndef test_something(color):\n print(color)\n\n####################################################\n# composite: show shrinking\n\n@composite\ndef my_special_strategy2(draw): # draw() is like strategy().example()\n i = integers(0, 255)\n x = []\n for _ in range(draw(i)):\n x.append(draw(i))\n return x\n\n#@given(lists(integers(0, 255), min_size=0, max_size=255)))\n@given(my_special_strategy2())\ndef test_something2(numbers):\n print(numbers)\n if sum(numbers) > 100 and len(numbers) > 11:\n raise Exception()\n\n# https://github.com/pygobject/pycairo/blob/master/tests/hypothesis_fspaths.py\n\n####################################################\n# using data()\n\n@given(data())\ndef test_something3(data):\n i = integers(0, 255)\n\n numbers = []\n for x in range(data.draw(i, \"list length\")):\n numbers.append(data.draw(i, \"list item #%d\" % x))\n\n if sum(numbers) > 100 and len(numbers) > 11:\n raise Exception()\n","sub_path":"examples/hypo/04_gen_composite.py","file_name":"04_gen_composite.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"460173300","text":"from flask import Flask, render_template,jsonify, request\nfrom flask_restful import Api\nfrom flask_jwt_extended import JWTManager, decode_token, get_jwt_identity\nfrom db import db\nfrom flask_socketio import SocketIO,send\n\nfrom resources.user import (UserRegister,\n UserPassword,\n UserSearch,\n UserLogin, \n UserAbout)\nfrom resources.invitation import MyInvitations, InvitationSender, InvitationManager\nfrom resources.friendship import FriendList\nfrom resources.conversation import ConversationList,MessagesFinder,MessageSender\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['JWT_SECRET_KEY'] = 'tajnykluczyk'\napp.config['PROPAGATE_EXCEPTIONS'] = True\napi = Api(app)\n\nsocketio = SocketIO(app,cors_allowed_origins='*')\n\nusers_session_id = {}\n\n@socketio.on('message')\ndef handleMessage(msg):\n print(\"Message: \"+ msg)\n send(msg,broadcast=True)\n@socketio.on('token')\ndef handleToken(token):\n print(\"Token: \"+ token) \n decoded_token = decode_token(token)\n user_id = decoded_token['identity']\n users_session_id[user_id] = request.sid\n \n \n\n\n\n\njwt = JWTManager(app)\n\n@jwt.expired_token_loader\ndef expired_token_callback():\n return jsonify({\n 'description': 'The token has expired',\n 'error': 'expired_token'\n }), 401\n\n@jwt.invalid_token_loader\ndef invalid_token_callback(error):\n return jsonify({\n 'description': 'Signature verification failed',\n 'error': 'invalid_token'\n }), 401\n\n@jwt.unauthorized_loader\ndef missing_token_callback(error):\n return jsonify({\n 'description': 'Request does not contain access token',\n 'error': 'authorization_required'\n }), 401\n\n@jwt.revoked_token_loader\ndef revoked_token_callback():\n return jsonify({\n 'description': 'The token has been revoked',\n 'error': 'revoked_token'\n }), 401\n\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n app.logger.debug('Headers: %s', request.headers)\n app.logger.debug('Body: %s', request.get_data())\n\n \n\n\n\n\napi.add_resource(UserRegister, '/register')\napi.add_resource(UserLogin,'/auth')\napi.add_resource(UserAbout,'/aboutuser')\napi.add_resource(UserPassword,'/passchange')\n\napi.add_resource(UserSearch, '/search/')\n\napi.add_resource(MyInvitations, '/invitations')\napi.add_resource(InvitationSender, '/invite/')\napi.add_resource(InvitationManager, '/invitation/manage')\n\napi.add_resource(FriendList, '/friends')\n\napi.add_resource(ConversationList, '/conversations')\napi.add_resource(MessagesFinder, '/message//')\napi.add_resource(MessageSender, '/message/',resource_class_kwargs={'socket': socketio})\n\nif __name__ == '__main__':\n db.init_app(app)\n socketio.run(app,host=\"0.0.0.0\")\n","sub_path":"dziurawy_komunikator-master/backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"206452764","text":"from __future__ import division, print_function\nimport matplotlib\nimport numpy as np\nimport bilby\nimport gwmemory\nfrom gwmemory import utils as utils\nimport itertools\nfrom scipy.signal import get_window\n\nnp.seterr(divide=\"ignore\", invalid=\"ignore\")\n\n\"\"\"\nThis code computes the posterior distribution for a MULTIDIMENSIONAL parameter\nspace which includes the memory constant. Here, we use GWMemory to inject a\nwaveform + memory model into NOISELESS data.\n\"\"\"\n\n\n# Set the parameters of the data segment that we're\n# going to inject the signal into\nduration = 1.0\nsampling_frequency = 4096\nf_lower = 15.0\n\n# Specify the output directory and the name of the simulation.\noutdir = \"/home/darin/bilby_output_noiseless_md\"\nlabel = \"pol_and_phase_HM_mid_distance\"\nbilby.core.utils.setup_logger(outdir=outdir, label=label)\n\n\n# Set up a random seed for result reproducibility. May or may not need this.\nnp.random.seed(88170235)\n\n\ndef time_domain_window(time_domain_strain, window_type=None):\n if window_type != None:\n window = get_window(window_type, time_domain_strain.size)\n time_domain_strain = time_domain_strain * window\n\n return time_domain_strain\n\n\n# Returns a two-dimensional array with lower and upper time bounds as elements. This is done by creates sur object of equal specification to the desired signal and extracting its get_t_lim attribute.\ndef get_t_0_t_f(\n mass_ratio,\n s1x,\n s2x,\n s1y,\n s2y,\n s1z,\n s2z,\n distance,\n total_mass,\n phase,\n inc,\n memory_constant,\n):\n\n start_time = -0.5 # arbitrarily chosen\n end_time = 0.0 # also arbitrary\n test_surr_times = np.linspace(\n start_time, end_time, sampling_frequency * (end_time - start_time)\n )\n\n # Now, create a toy model (only total mass matters) from which we can retrieve time bounds\n test_surr = gwmemory.waveforms.surrogate.Surrogate(\n q=mass_ratio,\n spin_1=[s1x, s1y, s1z],\n spin_2=[s2x, s2y, s2z],\n total_mass=total_mass,\n distance=distance,\n times=test_surr_times,\n )\n\n new_test_surr_times = test_surr_times / test_surr.t_to_geo\n return test_surr.sur.find_t_0(\n test_surr.q,\n test_surr.S1,\n test_surr.S2,\n MTot=test_surr.MTot,\n distance=test_surr.distance,\n t=new_test_surr_times,\n LMax=test_surr.LMax,\n )\n\n\ndef memory_time_model(\n times,\n mass_ratio,\n s1x,\n s2x,\n s1y,\n s2y,\n s1z,\n s2z,\n distance,\n total_mass,\n phase,\n inc,\n memory_constant,\n):\n # first, we need a linear sample space\n \"\"\"\n end_time can only be up to a certain time after merger, which is set in\n geometric units. Conversion from geometric to physical units is given by:\n phys_time = geo_time * (total_mass * m_sun_to_kg)/(c**3/G).\n \"\"\"\n GG = 6.674098281543097e-11\n cc = 2.99792458e8\n m_sun_to_kg = 1.98847e30\n t_f = time_lim[1] + 0.9 # Surrogate class cuts bound by 1.0s already\n start_time = -0.5\n end_time = t_f * (total_mass * m_sun_to_kg) / (cc ** 3 / GG)\n surr_times = np.linspace(\n start_time, end_time, sampling_frequency * (end_time - start_time)\n )\n\n # Now, to generate an oscillating and secular waveform...\n surr = gwmemory.waveforms.surrogate.Surrogate(\n q=mass_ratio,\n spin_1=[s1x, s1y, s1z],\n spin_2=[s2x, s2y, s2z],\n total_mass=total_mass,\n distance=distance,\n times=surr_times,\n # modes=[(2,2)],\n )\n oscillatory, surr_times = surr.time_domain_oscillatory(\n inc=inc, phase=phase\n )\n memory, surr_times = surr.time_domain_memory(inc=inc, phase=phase)\n\n # ...and add them\n plus_new = oscillatory[\"plus\"] + memory_constant * memory[\"plus\"]\n cross_new = oscillatory[\"cross\"] + memory_constant * memory[\"cross\"]\n\n # Next, we want to place them in our sample space\n plus = np.zeros(len(times))\n cross = np.zeros(len(times))\n plus[-len(surr_times) :] = plus_new\n cross[-len(surr_times) :] = cross_new\n\n # Finally, we need to window before applying an fft\n \"\"\"\n Window types provided by scipy.signal.windows.get_window\n [https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_\n window.html#scipy.signal.windows.get_window]\n ------------------------------------------------------------------------------\n\n 'boxcar': rectangular window = no window (essentially)\n 'triang': triangular window, nonzero endpoints\n 'blackman': 3rd order cosine sum, minimizes leakage, almost as good as Kaiser window at doing so\n 'hamming': single cosine with nonzero endpoints, minimizes first side lobe\n 'hann': hamming window but with zero endpoints\n 'bartlett': triangular window but with zero endpoints, used to taper with little fd modulation\n 'flattop': 5th order cosine sum, used to measure signal amplitude, makes main lobe flat\n 'parzen': not sure about this one\n 'bohman': or this one, either\n 'blackmanharris': generalized hamming = more cosines, hamming but better\n 'nuttall': similar to blackman-harris\n 'barthann': combo of bartlett and hann\n ('kaiser', beta): formed from Bessel functions, beta=0(rect), 5(hamming), 6(hann), 8.6(blackman)\n ('gaussian', std_dev): use only in special cases\n ('general_gaussian', power, width): same here\n ('slepian', width): maximizes power in main lobe\n ('dpss', norm half-bandwidth): first term is slepian window\n ('chebwin', attenuation): uses Chebyshev polynomials, kinda complicated\n ('exponential', decay constant): seems like it will cut power too quickly\n ('tukey', taper fraction): tf=0(rect), 1(hann)\n\n ------------------------------------------------------------------------------\n \"\"\"\n window_type_plus = (\"kaiser\", 0.1)\n window_type_cross = (\"kaiser\", 0.1)\n\n plus = time_domain_window(plus, window_type=window_type_plus)\n cross = time_domain_window(cross, window_type=window_type_cross)\n\n return {\"plus\": plus, \"cross\": cross}\n\n\n# We are going to inject a binary black hole waveform. We first establish a\n# dictionary of parameters that includes all of the different waveform\n# parameters, including masses of the two black holes (mass_1, mass_2),\n# spins of both black holes (a, tilt, phi), etc.\ninjection_parameters = dict(\n total_mass=60.0,\n s1x=0.0,\n s2x=0.0,\n s1y=0.0,\n s2y=0.0,\n s1z=0.0,\n s2z=0.0,\n distance=500,\n mass_ratio=1.5,\n inc=np.pi / 2,\n psi=0.0,\n phase=0.0,\n memory_constant=1.0,\n ra=0.0,\n dec=0.0,\n geocent_time=0.0,\n)\n\n\ntime_lim = get_t_0_t_f(\n mass_ratio=injection_parameters[\"mass_ratio\"],\n s1x=injection_parameters[\"s1x\"],\n s2x=injection_parameters[\"s2x\"],\n s1y=injection_parameters[\"s1y\"],\n s2y=injection_parameters[\"s2y\"],\n s1z=injection_parameters[\"s1z\"],\n s2z=injection_parameters[\"s2z\"],\n distance=injection_parameters[\"distance\"],\n total_mass=injection_parameters[\"total_mass\"],\n phase=injection_parameters[\"phase\"],\n inc=injection_parameters[\"inc\"],\n memory_constant=injection_parameters[\"memory_constant\"],\n)\n\n\n# Create the waveform_generator using a LAL BinaryBlackHole source function\nwaveform = bilby.gw.waveform_generator.WaveformGenerator(\n duration=duration,\n sampling_frequency=sampling_frequency,\n time_domain_source_model=memory_time_model,\n start_time=injection_parameters[\"geocent_time\"] - duration / 2.0,\n)\n\n\n# Set up interferometers. In this case we'll use two interferometers\n# (LIGO-Hanford (H1), LIGO-Livingston (L1). These default to their design\n# sensitivity\nifos = bilby.gw.detector.InterferometerList([\"H1\", \"L1\", \"V1\"])\nifos.set_strain_data_from_zero_noise(\n sampling_frequency=sampling_frequency,\n duration=duration,\n start_time=injection_parameters[\"geocent_time\"] - duration / 2.0,\n)\nifos.inject_signal(\n waveform_generator=waveform, parameters=injection_parameters\n)\n\n# Set up a PriorDict, which inherits from dict.\n# By default we will sample all terms in the signal models. However, this will\n# take a long time for the calculation, so for this example we will set almost\n# all of the priors to be equal to their injected values. This implies the\n# prior is a delta function at the true, injected value. In reality, the\n# sampler implementation is smart enough to not sample any parameter that has\n# a delta-function prior.\n# The above list does *not* include mass_1, mass_2, theta_jn and luminosity\n# distance, which means those are the parameters that will be included in the\n# sampler. If we do nothing, then the default priors get used.\npriors = injection_parameters.copy()\npriors[\"memory_constant\"] = bilby.core.prior.Uniform(-3, 5, r\"$\\lambda$\")\n#priors['distance'] = bilby.core.prior.Uniform(80, 120, r'$d_L$')\n#priors['mass_ratio'] = bilby.core.prior.Uniform(1.0, 1.99, 'q')\npriors[\"psi\"] = bilby.core.prior.Uniform(0.0, np.pi, r\"$\\psi$\")\npriors[\"phase\"] = bilby.core.prior.Uniform(0.0, 2.0 * np.pi, r\"$\\phi$\")\n\n# Initialise the likelihood by passing in the interferometer data (ifos) and\n# the waveform generator\nlikelihood = bilby.gw.GravitationalWaveTransient(\n interferometers=ifos, waveform_generator=waveform\n)\n\n# Run sampler. In this case we're going to use the `dynesty` sampler\nresult = bilby.run_sampler(\n likelihood=likelihood,\n priors=priors,\n sampler=\"dynesty\",\n use_ratio=True,\n plot=True,\n npoints=100,\n sample=\"unif\",\n verbose=True,\n injection_parameters=injection_parameters,\n outdir=outdir,\n label=label,\n)\n\n# Make a corner plot.\nresult.plot_corner()\n","sub_path":"working_scripts/bilby_noiseless_md.py","file_name":"bilby_noiseless_md.py","file_ext":"py","file_size_in_byte":9552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"25016456","text":"import time\n# from config_coco import NUM_CLASSES, EPSILON\nfrom config_bdd100k import NUM_CLASSES, EPSILON\nimport argparse\nimport datetime\nfrom utils import *\nfrom models.yolov3 import load_yolov3_model\nfrom datasets.utils import load_dataset\nfrom config_bdd100k import *\nfrom models.yolov3 import yolo_loss_fn\n\n\ndef run_yolo_inference(config: argparse.Namespace):\n # region logging\n current_datetime_str = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n log_file_name_by_time = current_datetime_str + \".log\"\n if config.debug:\n log_level = logging.DEBUG\n elif config.verbose:\n log_level = logging.INFO\n else:\n log_level = logging.WARNING\n config_logging(config.log_dir, log_file_name_by_time, level=log_level)\n # endregion\n\n # set the device for inference\n device = config_device(config.cpu_only)\n make_output_dir(config.out_dir)\n\n # load model\n model = load_yolov3_model(config.weight_path, device, checkpoint=config.from_ckpt)\n\n #config.label_path\n # load data\n dataloader = load_dataset(type_=config.dataset_type,\n img_dir=config.img_dir,\n label_file=None,\n img_size=config.img_size,\n batch_size=config.batch_size,\n n_cpu=config.n_cpu,\n shuffle=False,\n augment=False)\n\n # run detection\n model = model.to(device)\n results = run_detection(model, dataloader, device, config.conf_thres, config.nms_thres)\n\n # post processing\n if config.save_det:\n json_path = '{}/{}/detections.json'.format(config.out_dir, current_datetime_str)\n make_output_dir(os.path.split(json_path)[0])\n save_results_as_json(results, json_path)\n if config.save_img:\n class_names = load_class_names_from_file(config.class_path)\n img_path = '{}/{}/img'.format(config.out_dir, current_datetime_str)\n make_output_dir(img_path)\n save_results_as_images(results, img_path, class_names)\n return\n\n\ndef run_detection(model, dataloader, device, conf_thres, nms_thres: object, img_size=416):\n results = []\n _detection_time_list = []\n # _total_time = 0\n\n logging.info('Performing object detection:')\n\n from tqdm import tqdm\n\n # for batch_i, (imgs, targets, target_lengths) in tqdm(enumerate(dataloader), desc=\"batch progress\",\n # total=len(dataloader)):\n #\n # with torch.no_grad():\n #\n # imgs = imgs.to(device)\n # targets = targets.to(device)\n # target_lengths = target_lengths.to(device)\n #\n # # file_names = batch[0]\n # # img_batch = batch[1].to(device)\n # # scales = batch[2].to(device)\n # # paddings = batch[3].to(device)\n #\n # # Get detections\n # detections = model(imgs)\n # losses = yolo_loss_fn(detections, targets, target_lengths, img_size, average=False)\n # # detections = post_process(detections, True, conf_thres, nms_thres)\n #\n # print(\"[Losses: total {}, coord {}, obj {}, noobj {}, class {}]\".format(\n # losses[0].item(), losses[1].item(),\n # losses[2].item(), losses[3].item(), losses[4].item()\n # ))\n #\n # # for detection, scale, padding in zip(detections, scales, paddings):\n # # detection[..., :4] = untransform_bboxes(detection[..., :4], scale, padding)\n # # cxcywh_to_xywh(detection)\n #\n # # Log progress\n # # end_time = time.time()\n # # inference_time_both = end_time - start_time\n # # # print(\"Total PP time: {:.1f}\".format(inference_time_pp*1000))\n # # logging.info('Batch {}, '\n # # 'Total time: {}s, '.format(batch_i,\n # # inference_time_both))\n # # _detection_time_list.append(inference_time_both)\n # # _total_time += inference_time_both\n #\n # # results.extend(zip(file_names, detections, scales, paddings))\n\n print(\"num of batches: {}\".format(len(dataloader)))\n\n for batch_i, batch in tqdm(enumerate(dataloader), total=(1000//14) + 1):\n print(batch_i, flush=True)\n #TODO: implement testing limit lol\n if batch_i >= 1000:\n break\n\n file_names = batch[0]\n img_batch = batch[1].to(device)\n scales = batch[2].to(device)\n paddings = batch[3].to(device)\n\n # Get detections\n start_time = time.time()\n with torch.no_grad():\n detections = model(img_batch)\n detections = post_process(detections, True, conf_thres, nms_thres)\n\n for detection, scale, padding in zip(detections, scales, paddings):\n detection[..., :4] = untransform_bboxes(detection[..., :4], scale, padding)\n cxcywh_to_xywh(detection)\n\n # Log progress\n end_time = time.time()\n inference_time_both = end_time - start_time\n # print(\"Total PP time: {:.1f}\".format(inference_time_pp*1000))\n logging.info('Batch {}, '\n 'Total time: {}s, '.format(batch_i,\n inference_time_both))\n _detection_time_list.append(inference_time_both)\n # _total_time += inference_time_both\n\n results.extend(zip(file_names, detections, scales, paddings))\n\n _detection_time_tensor = torch.tensor(_detection_time_list)\n avg_time = torch.mean(_detection_time_tensor)\n time_std_dev = torch.std(_detection_time_tensor)\n logging.info('Average inference time (total) is {}s.'.format(float(avg_time)))\n logging.info('Std dev of inference time (total) is {}s.'.format(float(time_std_dev)))\n\n print(\"end\")\n return results\n\n\ndef post_process(results_raw, nms, conf_thres, nms_thres):\n results = []\n for idx, result_raw in enumerate(results_raw):\n bboxes = result_raw[..., :4]\n scores = result_raw[..., 4]\n classes_one_hot = result_raw[..., 5:]\n classes = torch.argmax(classes_one_hot, dim=1)\n if nms:\n bboxes, scores, classes = \\\n non_max_suppression(bboxes, scores, classes,\n num_classes=NUM_CLASSES,\n center=True,\n conf_thres=conf_thres,\n nms_thres=nms_thres)\n result = torch.cat((bboxes, scores.view((-1, 1)), classes.view((-1, 1)).float()), dim=1)\n results.append(result)\n logging.debug(\"The dimension of the result after nms is {} for idx {}\".format(result.size(), idx))\n return results\n\n\ndef non_max_suppression(bboxes, scores, classes, num_classes, conf_thres=0.8, nms_thres=0.5, center=False):\n \"\"\"Apply non-maximum suppression at test time to avoid detecting too many\n overlapping bounding boxes for a given object.\n Args:\n bboxes: (tensor) The location predictions for the img, Shape: [num_priors,4].\n scores: (tensor) The class prediction scores for the img, Shape:[num_priors].\n classes: (tensor) The label (non-one-hot) representation of the classes of the objects,\n Shape: [num_priors].\n num_classes: (int) The number of all the classes.\n conf_thres: (float) Threshold where all the detections below this value will be ignored.\n nms_thres: (float) The overlap thresh for suppressing unnecessary boxes.\n center: (boolean) Whether the bboxes format is cxcywh or xywh.\n Return:\n The indices of the kept boxes with respect to num_priors, and they are always in xywh format.\n \"\"\"\n\n # make sure bboxes and scores have the same 0th dimension\n assert bboxes.shape[0] == scores.shape[0] == classes.shape[0]\n num_prior = bboxes.shape[0]\n\n # if no objects, return raw result\n if num_prior == 0:\n return bboxes, scores, classes\n\n # threshold out low confidence detection\n\n if conf_thres > 0:\n conf_index = torch.nonzero(torch.ge(scores, conf_thres)).squeeze()\n\n bboxes = bboxes.index_select(0, conf_index)\n scores = scores.index_select(0, conf_index)\n classes = classes.index_select(0, conf_index)\n\n # if there are multiple classes, divide them into groups\n grouped_indices = group_same_class_object(classes, one_hot=False, num_classes=num_classes)\n selected_indices_final = []\n\n for class_id, member_idx in enumerate(grouped_indices):\n member_idx_tensor = bboxes.new_tensor(member_idx, dtype=torch.long)\n bboxes_one_class = bboxes.index_select(dim=0, index=member_idx_tensor)\n scores_one_class = scores.index_select(dim=0, index=member_idx_tensor)\n scores_one_class, sorted_indices = torch.sort(scores_one_class, descending=False)\n\n selected_indices = []\n\n while sorted_indices.size(0) != 0:\n picked_index = sorted_indices[-1]\n selected_indices.append(picked_index)\n picked_bbox = bboxes_one_class[picked_index]\n ious = iou_one_to_many(picked_bbox, bboxes_one_class[sorted_indices[:-1]], center=center)\n under_indices = torch.nonzero(ious <= nms_thres).squeeze()\n sorted_indices = sorted_indices.index_select(dim=0, index=under_indices)\n\n selected_indices_final.extend([member_idx[i] for i in selected_indices])\n\n selected_indices_final = bboxes.new_tensor(selected_indices_final, dtype=torch.long)\n bboxes_result = bboxes.index_select(dim=0, index=selected_indices_final)\n scores_result = scores.index_select(dim=0, index=selected_indices_final)\n classes_result = classes.index_select(dim=0, index=selected_indices_final)\n\n return bboxes_result, scores_result, classes_result\n\n\ndef group_same_class_object(obj_classes, one_hot=True, num_classes=-1):\n \"\"\"\n Given a list of class results, group the object with the same class into a list.\n Returns a list with the length of num_classes, where each bucket has the objects with the same class.\n :param\n obj_classes: (torch.tensor) The representation of classes of object.\n It can be either one-hot or label (non-one-hot).\n If it is one-hot, the shape should be: [num_objects, num_classes]\n If it is label (non-non-hot), the shape should be: [num_objects, ]\n one_hot: (bool) A flag telling the function whether obj_classes is one-hot representation.\n num_classes: (int) The max number of classes if obj_classes is represented as non-one-hot format.\n :return:\n a list of of a list, where for the i-th list,\n the elements in such list represent the indices of the objects in class i.\n \"\"\"\n if one_hot:\n num_classes = obj_classes.shape[-1]\n else:\n assert num_classes != -1\n grouped_index = [[] for _ in range(num_classes)]\n if one_hot:\n for idx, class_one_hot in enumerate(obj_classes):\n grouped_index[torch.argmax(class_one_hot)].append(idx)\n else:\n for idx, obj_class_ in enumerate(obj_classes):\n grouped_index[obj_class_].append(idx)\n return grouped_index\n\n\ndef iou(bbox1, bbox2, center=False):\n \"\"\"Calculate IOU for two bboxes. If center is false, then they should all in xywh format.\n Else, they should all be in cxcywh format\"\"\"\n x1, y1, w1, h1 = bbox1\n x2, y2, w2, h2 = bbox2\n if center:\n x1 = x1 - w1 / 2\n y1 = y1 - h1 / 2\n x2 = x2 - w2 / 2\n y2 = y2 - h2 / 2\n area1 = w1 * h1\n area2 = w2 * h2\n right1 = x1 + w1\n right2 = x2 + w2\n bottom1 = y1 + h1\n bottom2 = y2 + h2\n w_intersect = (torch.min(right1, right2) - torch.max(x1, x2)).clamp(min=0)\n h_intersect = (torch.min(bottom1, bottom2) - torch.max(y1, y2)).clamp(min=0)\n area_intersect = w_intersect * h_intersect\n iou_ = area_intersect / (area1 + area2 - area_intersect + EPSILON) # add epsilon to avoid NaN\n return iou_\n\n\ndef iou_one_to_many(bbox1, bboxes2, center=False):\n \"\"\"Calculate IOU for one bbox with another group of bboxes.\n If center is false, then they should all in xywh format.\n Else, they should all be in cxcywh format\"\"\"\n x1, y1, w1, h1 = bbox1\n x2 = bboxes2[..., 0]\n y2 = bboxes2[..., 1]\n w2 = bboxes2[..., 2]\n h2 = bboxes2[..., 3]\n if center:\n x1 = x1 - w1 / 2\n y1 = y1 - h1 / 2\n x2 = x2 - w2 / 2\n y2 = y2 - h2 / 2\n area1 = w1 * h1\n area2 = w2 * h2\n right1 = x1 + w1\n right2 = x2 + w2\n bottom1 = y1 + h1\n bottom2 = y2 + h2\n w_intersect = (torch.min(right1, right2) - torch.max(x1, x2)).clamp(min=0)\n h_intersect = (torch.min(bottom1, bottom2) - torch.max(y1, y2)).clamp(min=0)\n area_intersect = w_intersect * h_intersect\n iou_ = area_intersect / (area1 + area2 - area_intersect + EPSILON) # add epsilon to avoid NaN\n return iou_\n\n\ndef argsort(t, reverse=False):\n \"\"\"Given a list, sort the list and return the original indices of the sorted list.\"\"\"\n return sorted(range(len(t)), key=t.__getitem__, reverse=reverse)\n","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":13176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"174364958","text":"import random\ndef ChoosePivot(A): # randomly choose at item from the list as the pivot:\n index_list = [ i for i in range(0, len(A))]\n index = random.choice(index_list)\n A[0],A[index] = A[index],A[0]\n return A\ndef Partition(A):\n A = ChoosePivot(A)\n p = A[0] # p is alreay at the front of the array\n i = 1\n r = len(A)\n for j in range(1, r):\n if A[j] < p:\n A[j], A[i] = A[i], A[j]\n i += 1\n A[0], A[i-1] = A[i-1], A[0]\n return (i-1,p,A[0:i-1], A[i:r])\ndef RSelect(A, i): # this i starts from 1\n if len(A) == 1:\n return A[0]\n else:\n (j,p,a,b) = Partition(A) \n \n if j+1 == i:\n return p\n elif j+1 > i:\n return RSelect(a, i)\n else:\n return RSelect(b, i-j-1)\n\n\n\n\n\n\n\n","sub_path":"week3/RSelect.py","file_name":"RSelect.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"564668407","text":"import re\nfrom pyspark import SparkConf, SparkContext\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"WordCount\")\nsc = SparkContext(conf = conf)\n\ndef normalizeWrods(text):\n return re.compile(r'\\W+', re.UNICODE).split(text.lower())\n\ninput = sc.textFile(\"C:/sparkData/Scala/SparkScala3/book.txt\")\nwords = input.flatMap(normalizeWrods)\nwordCounts = words.map(lambda x: (x,1)).reduceByKey(lambda x,y: x + y)\nwordCountsSorted = wordCounts.map(lambda x,y: (y,x)).sortByKey()\n\nresults = wordCountsSorted.collect()\n\nfor result in results:\n count = str(result[0])\n word = result[1].encode('ascii','ignore')\n if(word):\n print(word + \":\\t\\t\" + count)","sub_path":"python/word-count.py","file_name":"word-count.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263113077","text":"from random import randrange\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom koopsite.functions import has_group_members, \\\n add_group, remove_group\nfrom koopsite.models import UserProfile\n\n\ndef get_readonly_disabled_widget_type_list():\n \"\"\"\n Повертає список типів віджетів, які не мають властивості readonly,\n тому їх при потребі потрібно блокувати\n встановленням атрибуту disabled\n \"\"\"\n readonly_disabled_widget_type_list = [\n 'Select',\n 'SelectMultiple',\n 'NullBooleanSelect',\n # 'RadioSelect',\n 'SelectDateWidget',\n ]\n return readonly_disabled_widget_type_list\n\ndef set_readonly_widget_attrs(fields, readonly_fields):\n \"\"\"\n Встановлення полям форми властивості readonly.\n Для віджетів, які не мають ції властивості, встановлюється disabled.\n :param fields: список об'єктів полів форми\n :param readonly_fields: список назв полів, які мають бути readonly\n :return:\n \"\"\"\n for field in readonly_fields:\n if field in fields:\n widget = fields[field].widget\n if widget.__class__.__name__ in get_readonly_disabled_widget_type_list():\n widget.attrs['disabled'] = 'disabled'\n else:\n widget.attrs['readonly'] = 'readonly'\n\ndef clear_help_text(fields):\n \"\"\"\n Занулення тексту-підказки для всіх полів\n :param fields: список об'єктів полів форми\n :return:\n \"\"\"\n for field in fields:\n fields[field].help_text = \"\"\n\n\nclass UserRegistrationForm(UserCreationForm):\n # Форма для реєстрації (створення нового) користувача\n\n required_css_class = 'required'\n error_css_class = 'error'\n\n class Meta:\n model = User\n fields = (\n 'username',\n 'first_name', 'last_name', 'email',\n )\n\n\nclass UserPersonDataForm(forms.ModelForm):\n # Коротка Форма для редагування персональних даних користувача.\n\n required_css_class = 'required'\n error_css_class = 'error'\n\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email')\n\n\nclass UserPermsFullForm(forms.ModelForm):\n # Форма для редагування всіх даних стосовно доступу користувача\n\n # required_css_class = 'required'\n # error_css_class = 'error'\n\n # Трюк з полями readonly:\n READONLY_FIELDS = (\n # 'username',\n 'first_name', 'last_name',\n 'date_joined', 'last_login',\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n set_readonly_widget_attrs(self.fields, self.READONLY_FIELDS)\n clear_help_text(self.fields)\n\n class Meta:\n model = User\n fields = (\n # 'username',\n 'first_name', 'last_name',\n 'date_joined', 'last_login',\n 'is_active', 'is_staff',\n 'groups',\n )\n\nclass UserPermsActivateForm(UserPermsFullForm):\n # Форма для редагуванння даних стосовно активації доступу користувача\n\n # Додаємо поля, яких немає в моделі:\n has_perm_member = forms.NullBooleanField(\n label=\"Доступ члена коопертиву\",\n widget=forms.CheckboxInput(),\n # initial=get_is_member,\n required=False,\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n instance = kwargs.get('instance', None)\n # instance - примірник збереженої форми, у даному випадку\n # примірник моделі User\n self.is_member = None\n if instance:\n self.is_member = has_group_members(instance)\n self.fields['has_perm_member'].initial = self.is_member\n\n\n def get_is_member(self):\n return self.is_member\n\n def save(self, commit=True):\n instance = super().save(commit=False)\n if self.cleaned_data.get('has_perm_member'):\n add_group(instance, 'members')\n else:\n remove_group(instance, 'members')\n if commit:\n instance.save()\n return instance\n\n class Meta:\n model = User\n fields = (\n # 'username',\n 'first_name', 'last_name',\n 'date_joined',\n 'is_active',\n )\n\n\nclass ProfileFullForm(forms.ModelForm):\n # Повна Форма для вводу профілю - ВСІХ додаткових даних користувача.\n # УВАГА! Використовувати лише для адміністратора!\n is_recognized = forms.NullBooleanField(\n label=\"Підтверджений\",\n widget=forms.CheckboxInput(),\n required=False,\n )\n\n class Meta:\n model = UserProfile\n fields = ('is_recognized', 'flat', 'picture')\n\n\nclass ProfilePermForm(ProfileFullForm):\n # Декларативно видаляємо деякі успадковані поля:\n picture = None\n\n # Трюк з полями readonly:\n READONLY_FIELDS = ('flat', )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n set_readonly_widget_attrs(self.fields, self.READONLY_FIELDS)\n\n class Meta:\n model = UserProfile\n fields = ('is_recognized', 'flat')\n\n\nclass ProfilePersonDataForm(ProfileFullForm):\n # Декларативно видаляємо деякі успадковані поля:\n is_recognized = None\n\n class Meta:\n model = UserProfile\n fields = ('flat', 'picture')\n\n\nclass Human_Check:\n \"\"\"\n Для перевірки, чи користувач є людиною.\n У простому реченні користувач повинен витерти одне із слів\n (номер слова обирається випадково).\n Перед відкриттям форми створюється примірник цього класу,\n а, отже, і речення-завдання, і потрібна відповідь.\n Речення-завдання task поступає у поле форми\n Метод validator цього класу присвоюється\n параметру validators поля форми.\n При неправильній відповіді у формі з'являється відповідне повідомлення.\n \"\"\"\n if_view_test = False # встановити True в тестах, де ця перевірка заважатиме\n # TODO-зробити, щоб після неправильної відповіді або генерувалося нове речення-завдання, або взагалі виходилося з форми.\n taskPattern = \"Видаліть із цієї стрічки %s слово\"\n numerals = {\n -1: \"останнє\",\n 0: \"перше\",\n 1: \"друге\",\n 2: \"третє\",\n 3: \"четверте\",\n 4: \"п'яте\",\n 5: \"шосте\",\n }\n def __init__(self, n=None):\n if n == None:\n self.taskNo = randrange(-1, 6)\n else:\n self.taskNo = n\n self.task = self.taskPattern % self.numerals[self.taskNo]\n\n def validator(self, answer):\n twords = self.task.split()\n twords.pop(self.taskNo)\n awords = answer.split()\n check = twords == awords\n check = check or self.if_view_test\n if not check:\n raise ValidationError(\"Помилка!\")\n\n\nclass ProfileRegistrationForm(ProfileFullForm):\n # Форма для реєстрації користувача\n # Модифікуємо деякі успадковані поля:\n is_recognized = None\n # Декларативно видаляємо деякі успадковані поля:\n\n # Додаємо поля, яких немає в батьківській формі:\n hc = Human_Check() # примірник класу перевірки на \"людяність\"\n human_check = forms.CharField(\n label='Доведіть, що Ви - людина',\n initial=hc.task, # речення-завдання\n validators=[hc.validator],\n required=True,\n # інакше валідатор пропустить порожнє поле\n # бо Django не перевіряє порожніх текстових полів!\n )\n\n # У формі в тегах буде додано назву відповідного класу CSS:\n required_css_class = 'required'\n error_css_class = 'error'\n\n class Meta:\n model = UserProfile\n fields = ('flat', 'picture')\n\n#---------------- Кінець коду, охопленого тестуванням ------------------\n\nclass UserSetMemberForm(UserPermsActivateForm):\n # Форма для редагуванння даних стосовно прав члена кооперативу\n READONLY_FIELDS = (\n # 'username',\n 'first_name', 'last_name',\n 'date_joined', 'last_login',\n )\n\n\n","sub_path":"koopsite/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":10207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"516396935","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\n\nfrom flask_wtf.file import FileAllowed\nfrom mongoengine import DoesNotExist\nfrom wtforms import *\nfrom flask_wtf import FlaskForm\n\nfrom apps import DATE_FORMAT\nfrom apps.company.forms import validate_logo_image, validate_logo_image_edit, ALLOWED_FILE_EXT\nfrom apps.models import User, Country\nfrom wtforms.fields.html5 import EmailField\nfrom wtforms.validators import DataRequired, Length, Regexp, EqualTo, Email, Optional\nfrom apps.models import Company,Role\nfrom apps.models import gender_choices, id_type_choices, status_choices\n\n\nclass SignUpForm(FlaskForm):\n username = StringField('Tên người dùng', validators=[\n DataRequired(), Length(1, 64), Regexp('^[a-z][a-z0-9_.]*$', 0,\n 'Tên người dùng chỉ bao gồm chữ thường,'\n ' ''số, dấu chấm(.), gạch dưới(_) và không bao gồm khoảng trắng!')])\n\n email = StringField('Email', [validators.DataRequired(\"Xin vui lòng nhập email!\"), Email(\"Email không hợp lệ!\")])\n password = PasswordField('Mật khầu', [\n validators.InputRequired(message=\"Xin vui lòng nhập mật khẩu!\"),\n validators.EqualTo('confirm', message='Mật khẩu không trùng khớp!')\n ])\n confirm = PasswordField('Xác nhận mật khầu')\n\n def validate_username(self, field):\n if User.objects(username = field.data).first():\n raise ValidationError(\"Tên người dùng đã tồn tại!\")\n\n def validate_email(self, field):\n if User.objects(email = field.data).first():\n raise ValidationError(\"Email đã tồn tại!\")\n\n\nclass LoginForm(FlaskForm):\n username = StringField('Tên người dùng', [validators.DataRequired()])\n password = PasswordField('Mật khẩu', [validators.InputRequired()])\n next = StringField()\n\n\nclass RequestResetPasswordForm(FlaskForm):\n email = StringField('Email', [validators.DataRequired(message=\"Xin vui lòng nhập email!\"),\n Email(\"Email không hợp lệ!\")])\n\n\nclass CMSUserForm(FlaskForm):\n\n cms_roles = Role.objects(name__startswith=\"CMS\")\n cms_role_choices = []\n for r in cms_roles:\n role = (r.name, r.description)\n cms_role_choices.append(role)\n\n username = StringField('Username', [validators.Length(min=4, max=25)])\n first_name = StringField('First name', [validators.Length(min=2, max=25)])\n last_name = StringField('Last name', [validators.Length(min=2, max=25)])\n roles = SelectMultipleField('Roles', choices=tuple(cms_role_choices))\n email = EmailField('Email Address', [validators.DataRequired(), validators.Email()])\n password = PasswordField('Password', [\n validators.DataRequired(),\n validators.EqualTo('confirm', message='Passwords must match')\n ])\n confirm = PasswordField('Repeat Password')\n\n def validate_email(self, field):\n email = field.data\n if User.objects.filter(email=email):\n raise ValidationError(u'E-mail in use already.')\n\n def validate_username(self, field):\n username = field.data\n if User.objects.filter(username=username):\n raise ValidationError(u'Username in use already!')\n\n\nclass CMSEditUserForm(FlaskForm):\n cms_roles = Role.objects(name__startswith=\"CMS\")\n cms_role_choices = []\n for r in cms_roles:\n role = (r.name, r.description)\n cms_role_choices.append(role)\n\n first_name = StringField('First name', [validators.Length(min=2, max=25)])\n last_name = StringField('Last name', [validators.Length(min=2, max=25)])\n roles = SelectMultipleField('Roles', choices=tuple(cms_role_choices))\n email = EmailField('Email Address', [validators.DataRequired(), validators.Email()])\n status = SelectField('Status', choices = status_choices, coerce=int)\n\n\nclass AddNewUserPersonToGroup(FlaskForm):\n\n username = StringField('Tên người dùng', validators=[\n DataRequired(), Length(1, 64),\n Regexp('^[a-z][a-z0-9_.]*$', 0,\n 'Tên người dùng chỉ bao gồm các ký tự (chữ thường, số, gạch dưới, dấu chấm)')])\n\n first_name = StringField('Tên', [validators.Optional()])\n last_name = StringField('Họ', [validators.Optional()])\n id_type = SelectField('Loại ID', [validators.DataRequired(message='Xin vui lòng chọn loại ID cá nhân')], coerce=int)\n address = StringField('Địa chỉ cá nhân', [validators.Optional()])\n email = StringField('Email', [validators.DataRequired(message=\"Xin vui lòng nhập địa chỉ email người dùng!\"),\n Email(message=\"Email không hợp lệ!\")])\n id_number = StringField('Mã số ID', [validators.DataRequired(message=\"Xin vui lòng nhập số ID\")])\n roles = SelectMultipleField('Vai trò', [validators.DataRequired(message=\"Xin vui lòng chọn vai trò người dùng!\")])\n\n def __init__(self, *args, **kwargs):\n super(AddNewUserPersonToGroup, self).__init__(*args, **kwargs)\n self.id_type.choices = id_type_choices[0:3]\n self.roles.choices = [(role.name, role.description)\n for role in Role.objects(\n name__nin = ['Người Dùng', 'AppAdmin', 'Group Delta', 'Admin']).all()]\n\n def validate(self):\n if not super(AddNewUserPersonToGroup, self).validate():\n return False\n\n id_number = \"\".join(str(self.id_number.data).split(\" \"))\n\n if self.id_type.data == 1:\n if not id_number.isdigit():\n raise ValidationError(\"Xin vui lòng chỉ nhập số đối với chứng minh nhân dân!\")\n # return False\n\n elif self.id_type.data == 2:\n if not re.match(\"^[A-Za-z0-9]*$\", id_number):\n raise ValidationError(\"Hộ chiếu chỉ bao gồm chữ và số!\")\n return True\n\n def validate_username(self, field):\n if User.objects.filter(username = field.data).first():\n raise ValidationError(\"Tên người dùng này đã tồn tại!\")\n\n def validate_email(self, field):\n if User.objects.filter(email=field.data).first():\n raise ValidationError(\"Email này đã tồn tại!\")\n\n\nclass AddPersonToUserGroup(FlaskForm):\n\n username = StringField('Tên người dùng', validators=[\n DataRequired(), Length(1, 64),\n Regexp('^[a-z][a-z0-9_.]*$', 0,\n 'Tên người dùng chỉ bao gồm các ký tự '\n '(chữ thường, số, gạch dưới, dấu chấm, và không có khoảng trắng!)')])\n\n email = StringField('Email', [validators.DataRequired(message=\"Xin vui lòng nhập địa chỉ email người dùng!\"),\n Email(message=\"Không phải email, xin vui lòng kiểm tra lại!\")])\n roles = SelectMultipleField('Vai trò', [validators.DataRequired(message=\"Xin vui lòng chọn vai trò cho người dùng.\")])\n\n def __init__(self, *args, **kwargs):\n super(AddPersonToUserGroup, self).__init__(*args, **kwargs)\n self.roles.choices = [(role.name, role.description)\n for role in Role.objects(\n name__nin = ['Người Dùng', 'AppAdmin', 'Group Delta', 'Admin']).all()]\n\n def validate_username(self, field):\n if User.objects.filter(username = field.data).first():\n raise ValidationError(\"Tên người dùng này đã tồn tại!\")\n\n def validate_email(self, field):\n if User.objects.filter(email=field.data).first():\n raise ValidationError(\"Email này đã tồn tại!\")\n\n\nclass ContactForm(FlaskForm):\n name = StringField(\"Name\", [validators.DataRequired(\"Please enter your name.\")])\n email = StringField(\"Email\", [validators.DataRequired(\"Please enter your email address.\"), validators.Email()])\n subject = StringField(\"Subject\", [validators.DataRequired(\"Please enter a subject.\")])\n message = TextAreaField(\"Message\", [validators.DataRequired(\"Please enter a message.\")])\n submit = SubmitField(\"Send\")\n\n\nclass ChangePasswordForm(FlaskForm):\n old_password = PasswordField('Mật khẩu hiện tại', validators=[DataRequired(message=\"Xin vui lòng nhập lại mật khẩu cũ!\")])\n new_password = PasswordField('Mật khẩu mới', validators=[\n DataRequired(), EqualTo('confirm', message='Mật khẩu không trùng khớp!')])\n confirm = PasswordField('Xác nhận mật khẩu mới',\n validators=[DataRequired()])\n\n\nclass PasswordResetForm(FlaskForm):\n password = PasswordField('Mật khẩu mới', validators=[\n DataRequired(), EqualTo('password2', message='Mật khẩu không trùng khớp!')])\n password2 = PasswordField('Xác nhận mật khẩu', validators=[DataRequired()])\n\n\nclass UpdateCompanyProfileForm(FlaskForm):\n tax_id = StringField('Tax ID', [validators.DataRequired(message=\"Xin vui lòng nhập mã số thuế.\")])\n\n def validate(self):\n if not super(UpdateCompanyProfileForm, self).validate():\n return False\n try:\n comp = Company.objects.get(tax_id = self.tax_id.data,\n shareholder_type = self.shareholder_type.data)\n except DoesNotExist:\n print(\"Company does not exist!\")\n return True\n\n if comp and User.objects.filter(company = comp).first():\n msg = 'Mã số thuế ({}) - Loại hình cổ đông: ({}), ' \\\n 'đã tồn tại với người dùng khác!'.format(comp.tax_id, comp.company_type_name)\n self.tax_id.errors.append(msg)\n return False\n\n else:\n return True\n\n\nclass UpdatePersonProfileForm(FlaskForm):\n id_num = StringField('Số Chứng Minh Nhân Dân/ Hộ Chiếu', [validators.DataRequired(message=\"Xin vui lòng nhập ID!\")])\n id_type = SelectField('Loại ID', [validators.DataRequired(message=\"Xin vui lòng chọn loại ID!\")], coerce=int)\n\n def __init__(self, *args, **kwargs):\n super(UpdatePersonProfileForm, self).__init__(*args, **kwargs)\n self.id_type.choices = id_type_choices[0:3]\n\n def validate(self):\n if not super(UpdatePersonProfileForm, self).validate():\n return False\n\n id_num = \"\".join(str(self.id_num.data).split(\" \"))\n\n if self.id_type.data == 1:\n if not id_num.isdigit():\n self.id_type.errors.append(\"Xin vui lòng chỉ nhập số đối với chứng minh nhân dân!\")\n return False\n\n elif self.id_type.data == 2:\n if not re.match(\"^[A-Za-z0-9]*$\", id_num):\n self.id_type.errors.append(\"Hộ chiếu chỉ bao gồm chữ và số!\")\n return False\n return True\n\n def validate_id_num(self, field):\n if str(field.data).islower():\n raise ValidationError(\"Xin vui lòng nhập ký tự in hoa!\")\n\n\nclass EditAdminProfile(FlaskForm):\n email = StringField('Email', validators=[DataRequired(), Length(1, 64),\n Email(message=\"Địa chỉ email không hợp lệ!\")])\n username = StringField('Username', validators=[\n DataRequired(), Length(1, 64),\n Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0,\n 'Tên người dùng chỉ bao gồm chữ, số, dấu chấm hoặc gạch dưới và không có bất kỳ khoảng trắng!')])\n role = SelectMultipleField('Vai trò', coerce=str)\n first_name = StringField('Tên', validators=[Length(0, 20, message=\"Không được quá 20 ký tự.\")])\n last_name = StringField('Họ', validators=[Length(0, 50, message=\"Không được quá 50 ký tự.\")])\n address = StringField('Địa chỉ liên hệ', [validators.Length(max=200, message=\"Địa chỉ không vượt quá 200 ký tự!\")])\n mobile_phone = StringField('Số điện thoại', [validators.Optional(),\n Length(0, 20, message=\"Không được nhiều hơn 20 ký tự.\")])\n gender = SelectField('Giới tính', [validators.Optional()], coerce=int)\n dob = DateField('Ngày sinh', [validators.Optional()], format=DATE_FORMAT)\n\n nationality = SelectField('Quốc tịch', [validators.Optional()], coerce=str)\n employer = StringField('Nơi làm việc', [validators.Optional()])\n job = StringField('Công việc hiện tại', [validators.Optional()])\n profile_image = FileField('Hình cá nhân',\n validators=[\n Optional(),\n FileAllowed(['jpg', 'png'], 'Chỉ chọn file hình (.jpg, .png)!')\n ])\n about_me = TextAreaField('Về bản thân')\n\n def __init__(self, user, *args, **kwargs):\n super(EditAdminProfile, self).__init__(*args, **kwargs)\n self.gender.choices = gender_choices\n self.nationality.choices = [(country.name, country.code)\n for country in Country.objects().all()\n ]\n self.user = user\n self.role.choices = [(role.name, role.description)\n for role in Role.objects(name__nin =\n ['Cổ Đông', 'Chủ Tịch', 'Người Dùng',\n 'Group Delta', 'AppAdmin']).all().order_by('name')]\n\n def validate_email(self, field):\n if field.data != self.user.email and \\\n User.objects.filter(email=field.data).first():\n raise ValidationError('Email đã tồn tại!')\n\n def validate_username(self, field):\n if field.data != self.user.username and \\\n User.objects.filter(username=field.data).first():\n raise ValidationError('Tên người dùng đã được sử dụng.')\n\n def validate_profile_image(self, field):\n if field.data:\n filename = field.data.filename\n ext = os.path.splitext(filename)[1].strip(\".\")\n if not ext.lower() in ALLOWED_FILE_EXT:\n raise ValidationError('Xin vui lòng chỉ chọn file (jpg, png).')\n\n if field.data.filename != self.user.profile_image and \\\n User.objects.filter(profile_image = field.data.filename).first():\n raise ValidationError(\"Hình đã được sử dụng.\")\n\n def validate_mobile_phone(self, field):\n if not str(field.data).isdigit():\n raise ValidationError('Xin vui lòng chỉ chọn số.')\n\n\nclass EditProfile(FlaskForm):\n first_name = StringField('Tên', validators=[Length(0, 64, message=\"Không được quá 64 ký tự.\")])\n last_name = StringField('Họ', validators=[Length(0, 64, message=\"Không được quá 64 ký tự.\")])\n address = StringField('Địa chỉ liên hệ', [validators.Length(max=100, message=\"Địa chỉ vượt quá 100 ký tự.\")])\n mobile_phone = StringField('Số điện thoại', [validators.Optional()])\n gender = SelectField('Giới tính', [validators.DataRequired(message=\"Xin vui lòng chọn giới tính.\")], coerce=int)\n dob = DateField('Ngày sinh', [validators.DataRequired(message=\"Xin vui lòng nhập ngày tháng năm sinh.\")], format=DATE_FORMAT)\n nationality = SelectField('Quốc tịch', [validators.Optional()], coerce=str, default='VN')\n employer = StringField('Nơi làm việc', [validators.Optional()])\n job = StringField('Công việc hiện tại', [validators.Optional()])\n profile_image = FileField('Hình cá nhân', [validators.Optional()])\n about_me = TextAreaField('Về bản thân')\n\n def __init__(self, user, *args, **kwargs):\n super(EditProfile, self).__init__(*args, **kwargs)\n self.gender.choices = gender_choices\n self.nationality.choices = [(country.name, country.code)\n for country in Country.objects().all()\n ]\n self.user = user\n\n def validate_profile_image(self, field):\n if field.data:\n filename = field.data.filename\n ext = os.path.splitext(filename)[1].strip(\".\")\n if not ext.lower() in ALLOWED_FILE_EXT:\n raise ValidationError('Xin vui lòng chỉ chọn file (jpg, png)!')\n\n if field.data.filename != self.user.profile_image and \\\n User.objects.filter(profile_image = field.data.filename).first():\n raise ValidationError(\"Hình đã được sử dụng!\")\n\n def validate_mobile_phone(self, field):\n if not str(field.data).isdigit():\n raise ValidationError('Xin vui lòng chỉ chọn số!')\n\n\nclass AddUserRolesInUserGroup(FlaskForm):\n roles = SelectMultipleField('Roles', [validators.DataRequired(\n message=f\"Xin vui lòng chọn vai trò cho người dùng trong nhóm.\")], coerce=str)\n\n def __init__(self, *args, **kwargs):\n super(AddUserRolesInUserGroup, self).__init__(*args, **kwargs)\n self.roles.choices = [(role.name, role.description)\n for role in Role.objects(name__nin=['Người Dùng', 'AppAdmin', 'Group Delta'])]\n\n\nclass MessageForm(FlaskForm):\n message = TextAreaField('Thông tin xác thực', validators=[\n DataRequired(), Length(min=1, max=200, message=\"Thông tin nhập tối đa 200 ký tự!\")])\n\n\nclass CheckPersonToMakeUser(FlaskForm):\n id_num = StringField('Mã số ID', [validators.DataRequired(message=\"Xin vui lòng nhập ID.\")])\n id_type = SelectField('Loại ID', [validators.DataRequired(message=\"Xin vui lòng chọn loại ID\")], coerce=int)\n\n def __init__(self, *args, **kwargs):\n super(CheckPersonToMakeUser, self).__init__(*args, **kwargs)\n self.id_type.choices = id_type_choices[0:3]\n\n def validate(self):\n if not super(CheckPersonToMakeUser, self).validate():\n return False\n\n id_num = \"\".join(str(self.id_num.data).split(\" \"))\n\n if self.id_type.data == 1:\n if not id_num.isdigit():\n self.id_num.errors.append(\"Xin vui lòng chỉ nhập số đối với chứng minh nhân dân!\")\n return False\n\n elif self.id_type.data == 2:\n if not re.match(\"^[A-Za-z0-9]*$\", id_num):\n self.id_num.errors.append(\"Hộ chiếu chỉ bao gồm chữ và số!\")\n return False\n\n return True\n\n\nclass ChangeEmailForm(FlaskForm):\n email = StringField('Email Mới', validators=[DataRequired(), Length(1, 64),\n Email(\"Email không hợp lệ!\")])\n password = PasswordField('Password', validators=[DataRequired(\"Xin vui lòng nhập mật khẩu!\")])\n\n def validate_email(self, field):\n if User.objects.filter(email=field.data).first():\n raise ValidationError('Email đã tồn tại!')\n\n\nclass SignUpUserGroupForm(FlaskForm):\n username = StringField('Tên người dùng', validators=[\n DataRequired(), Length(1, 64), Regexp('^[a-z][a-z0-9_.]*$', 0,\n 'Tên người dùng chỉ bao gồm chữ thường,'\n ' ''số, dấu chấm(.), gạch dưới(_) và không bao gồm khoảng trắng!')])\n\n email = StringField('Email', [validators.DataRequired(\"Xin vui lòng nhập email!\"), Email(\"Email không hợp lệ!\")])\n roles = SelectMultipleField('Vai trò', [validators.DataRequired(\n message=\"Xin vui lòng chọn vai trò người dùng!\")], coerce=str)\n\n def __init__(self, *args, **kwargs):\n super(SignUpUserGroupForm, self).__init__(*args, **kwargs)\n self.roles.choices = [(role.name, role.description)\n for role in Role.objects(\n name__in=['Chủ Tịch', 'Kiểm Phiếu-Biểu Quyết', 'Thư Ký']).order_by('name')]\n\n def validate_username(self, field):\n if User.objects(username = field.data).first():\n raise ValidationError(\"Tên người dùng đã tồn tại!\")\n\n def validate_email(self, field):\n if User.objects(email = field.data).first():\n raise ValidationError(\"Email đã tồn tại!\")\n\n\n\n","sub_path":"apps/users/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":20314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"286534199","text":"def detect_anagrams(string, array):\n dicc = {x: sorted([y.lower() for y in x]) for x in array}\n\n list_anagrams = []\n for list_letter in dicc.items():\n if list_letter[1] == sorted([y.lower() for y in string]) and list_letter[0].lower() != string.lower():\n list_anagrams.append(list_letter[0])\n else:\n continue\n return list_anagrams\n","sub_path":"python/anagram/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"543951182","text":"# -*- coding: utf-8 -*-\n'''\n :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`\n :copyright: © 2012-2013 by the SaltStack Team, see AUTHORS for more details\n :license: Apache 2.0, see LICENSE for more details.\n\n\n tests.integration.shell.master\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n'''\n\n# Import python libs\nimport os\nimport yaml\nimport signal\nimport shutil\n\n# Import Salt Testing libs\nfrom salttesting.helpers import ensure_in_syspath\nensure_in_syspath('../../')\n\n# Import salt libs\nimport integration\n\n\nclass MasterTest(integration.ShellCase, integration.ShellCaseCommonTestsMixIn):\n\n _call_binary_ = 'salt-master'\n\n def test_issue_7754(self):\n old_cwd = os.getcwd()\n config_dir = os.path.join(integration.TMP, 'issue-7754')\n if not os.path.isdir(config_dir):\n os.makedirs(config_dir)\n\n os.chdir(config_dir)\n\n config_file_name = 'master'\n pid_path = os.path.join(config_dir, '{0}.pid'.format(config_file_name))\n config = yaml.load(\n open(self.get_config_file_path(config_file_name), 'r').read()\n )\n config['root_dir'] = config_dir\n config['log_file'] = 'file:///dev/log/LOG_LOCAL3'\n config['ret_port'] = config['ret_port'] + 10\n config['publish_port'] = config['publish_port'] + 10\n\n open(os.path.join(config_dir, config_file_name), 'w').write(\n yaml.dump(config, default_flow_style=False)\n )\n\n self.run_script(\n self._call_binary_,\n '--config-dir {0} --pid-file {1} -l debug'.format(\n config_dir,\n pid_path\n ),\n timeout=5,\n catch_stderr=True\n )\n\n # Now kill it if still running\n if os.path.exists(pid_path):\n try:\n os.kill(int(open(pid_path).read()), signal.SIGKILL)\n except OSError:\n pass\n try:\n self.assertFalse(os.path.isdir(os.path.join(config_dir, 'file:')))\n finally:\n os.chdir(old_cwd)\n if os.path.isdir(config_dir):\n shutil.rmtree(config_dir)\n\n\nif __name__ == '__main__':\n from integration import run_tests\n run_tests(MasterTest)\n","sub_path":"tests/integration/shell/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243335784","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('sign_up/', views.sign_up, name=\"sign_up\"),\n path('sign_in/', views.sign_in, name=\"sign_in\"),\n path('sign_out/', views.sign_out, name=\"sign_out\"),\n path('profile/', views.profile, name=\"profile\"),\n path('follow/', views.follow, name=\"follow\"),\n]","sub_path":"insta_dayoung/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"53949427","text":"# -*- coding:utf-8 -*-\n# http://nanti.jisuanke.com/t/2\n# \n\nmy_input = raw_input()\nM, N = my_input.split(' ')\nM, N = int(M), int(N)\nif M < 1 or M > 500:\n print(\"被除数超出范围[1, 500],请检查后重新输入\")\nif N < 1 or N > 500:\n print(\"除数超出范围[1, 500],请检查后重新输入\")\n\nif (1 <= M and M <= 500) and (1 <= N and N <= 500):\n result = M % N\n if result == 0:\n print(\"YES\")\n else:\n print(\"NO\")\n","sub_path":"nanti/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"103380797","text":"# n! = (n-1)! * n\n# sum(n) = sum(n-1) + n\n\n\n#-- there is no exit/stop statement in this loop------------------------------------------------\n# def sum(n):\n# return (sum(n-1) + n)\n\n# num = int(input(\"please enter a no.: \"))\n# add = sum(num)\n# print(\"the sum of n natural numbers is: \" + str(add))\n\n\n#--------------------------------------------------------------------\n\ndef sum(n):\n if n==1 :\n return 1\n else :\n return n + sum(n-1) \n\nm=int(input(\"Enter a natural number : \"))\nx=sum(m)\nprint(\"The sum of first \" + str(m)+ \" natural number is \"+ str(x))","sub_path":"ch8_functions_and_recursion.py/ch8_prob_04.py","file_name":"ch8_prob_04.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"119471547","text":"import asyncio, io, glob, os, sys, time, uuid, requests\r\nfrom urllib.parse import urlparse\r\nfrom io import BytesIO\r\nfrom PIL import Image, ImageDraw\r\nfrom azure.cognitiveservices.vision.face import FaceClient\r\nfrom msrest.authentication import CognitiveServicesCredentials\r\nfrom azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, SnapshotObjectType, OperationStatusType\r\n\r\n\r\n# Set the FACE_SUBSCRIPTION_KEY environment variable with your key as the value.\r\n# This key will serve all examples in this document.\r\nKEY = os.environ['COGNITIVE_SERVICE_KEY']\r\n\r\n# Set the FACE_ENDPOINT environment variable with the endpoint from your Face service in Azure.\r\n# This endpoint will be used in all examples in this quickstart.\r\nENDPOINT = os.environ['FACE_ENDPOINT']\r\n\r\n# Used in the Person Group Operations, Snapshot Operations, and Delete Person Group examples.\r\n# You can call list_person_groups to print a list of preexisting PersonGroups.\r\n# SOURCE_PERSON_GROUP_ID should be all lowercase and alphanumeric. For example, 'mygroupname' (dashes are OK).\r\nPERSON_GROUP_ID = 'criminaldb'\r\n# Used for the Snapshot and Delete Person Group examples.\r\n#TARGET_PERSON_GROUP_ID = str(uuid.uuid4()) # assign a random ID (or name it anything)\r\n\r\n'''\r\nAuthenticate\r\nAll examples use the same client, except for Snapshot Operations.\r\n'''\r\n# \r\n# Create an authenticated FaceClient.\r\nface_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))\r\n# \r\n'''\r\nEND - Authenticate\r\n'''\r\n\r\n'''\r\nIdentify a face against a defined PersonGroup\r\n'''\r\n\r\n# Reference image for testing against\r\ngroup_photo = 'test2.jpg'\r\nIMAGES_FOLDER = os.path.join(os.path.dirname(os.path.realpath(__file__)))\r\n\r\n# Get test image\r\ntest_image_array = glob.glob(os.path.join(IMAGES_FOLDER, group_photo))\r\nimage = open(test_image_array[0], 'r+b')\r\n\r\n# Detect faces\r\nface_ids = []\r\nfaces = face_client.face.detect_with_stream(image)\r\nfor face in faces:\r\n face_ids.append(face.face_id)\r\n# \r\n\r\n# \r\n# Identify faces\r\nresults = face_client.face.identify(face_ids, PERSON_GROUP_ID)\r\nprint (results)\r\nprint('Identifying faces in {}')\r\nif not results:\r\n print('No person identified in the person group for faces from the {}.'.format(os.path.basename(image.name)))\r\nfor person in results:\r\n print(person.candidates)\r\n if person.candidates:\r\n print('Person for face ID {} is identified in {} with a confidence of {}.'.format(person.face_id, os.path.basename(image.name), person.candidates[0])) # Get topmost confidence score\r\n \r\n else:\r\n print('No one identified in the person group for faces from the {}.'.format(os.path.basename(image.name)))\r\n# \r\n'''\r\nEND - Create/Train/Detect/Identify Person Group example\r\n'''\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"343814545","text":"# _core/_base.py\n\"\"\"Base ROM classes and mixins.\n\nClasses\n-------\n* _BaseROM: base class for all ROM objects.\n* _DiscreteROM: base class for all discrete ROMs (difference equations).\n* _ContinuousROM: base class for all continuous ROMs (differential equations).\n* _NonparametricMixin: base mixin for all ROMs without parameter dependence.\n* _ParametricMixin: base mixin for all ROMs with external parameter dependence.\n\"\"\"\n\n__all__ = []\n\nimport os\nimport h5py\nimport warnings\nimport numpy as np\nfrom scipy.interpolate import CubicSpline\nfrom scipy.integrate import solve_ivp, IntegrationWarning\n\nfrom ..utils import compress_H, compress_G, kron2c, kron3c\n\n\n# Base classes (private) ======================================================\nclass _BaseROM:\n \"\"\"Base class for all rom_operator_inference reduced model classes.\"\"\"\n _MODEL_KEYS = \"cAHGB\" # Constant, Linear, Quadratic, Cubic, Input.\n\n def __init__(self, modelform):\n \"\"\"Set the modelform.\"\"\"\n if not isinstance(self, (_ContinuousROM, _DiscreteROM)):\n raise RuntimeError(\"abstract class instantiation \"\n \"(use _ContinuousROM or _DiscreteROM)\")\n self.modelform = modelform\n\n def _clear(self):\n \"\"\"Set private attributes as None, erasing any previously stored basis,\n dimensions, or ROM operators.\n \"\"\"\n self.__m = None if self.has_inputs else 0\n self.__r = None\n self.__Vr = None\n self.__c_ = None\n self.__A_ = None\n self.__H_ = None\n self.__G_ = None\n self.__B_ = None\n\n # Properties: modelform ---------------------------------------------------\n @property\n def modelform(self):\n \"\"\"Structure of the reduced-order model.\"\"\"\n return self.__form\n\n @modelform.setter\n def modelform(self, form):\n \"\"\"Set the modelform, which – if successful – resets the entire ROM.\"\"\"\n form = ''.join(sorted(form, key=lambda k: self._MODEL_KEYS.find(k)))\n for key in form:\n if key not in self._MODEL_KEYS:\n raise ValueError(f\"invalid modelform key '{key}'; options \"\n \"are \" + ', '.join(self._MODEL_KEYS))\n self.__form = form\n self._clear()\n\n @property\n def has_constant(self):\n \"\"\"Whether or not the ROM has a constant term c.\"\"\"\n return \"c\" in self.modelform\n\n @property\n def has_linear(self):\n \"\"\"Whether or not the ROM has a linear state term Ax.\"\"\"\n return \"A\" in self.modelform\n\n @property\n def has_quadratic(self):\n \"\"\"Whether or not the ROM has a quadratic state term H(x ⊗ x).\"\"\"\n return \"H\" in self.modelform\n\n @property\n def has_cubic(self):\n \"\"\"Whether or not the ROM has a cubic state term G(x ⊗ x ⊗ x).\"\"\"\n return \"G\" in self.modelform\n\n @property\n def has_inputs(self):\n \"\"\"Whether or not the ROM has an input term Bu.\"\"\"\n return \"B\" in self.modelform\n\n # @property\n # def has_outputs(self):\n # return \"C\" in self._form\n\n # Properties: dimensions --------------------------------------------------\n @property\n def n(self):\n \"\"\"Dimension of the full-order model.\"\"\"\n return self.Vr.shape[0] if self.Vr is not None else None\n\n @n.setter\n def n(self, n):\n \"\"\"Setting this dimension is not allowed, it is always Vr.shape[0].\"\"\"\n raise AttributeError(\"can't set attribute (n = Vr.shape[0])\")\n\n @property\n def m(self):\n \"\"\"Dimension of the input term, if present.\"\"\"\n return self.__m\n\n @m.setter\n def m(self, m):\n \"\"\"Set input dimension; only allowed if 'B' in modelform\n and the operator B_ is None.\n \"\"\"\n if not self.has_inputs and m != 0:\n raise AttributeError(\"can't set attribute ('B' not in modelform)\")\n elif self.B_ is not None:\n raise AttributeError(\"can't set attribute (m = B_.shape[1])\")\n self.__m = m\n\n @property\n def r(self):\n \"\"\"Dimension of the reduced-order model.\"\"\"\n return self.__r\n\n @r.setter\n def r(self, r):\n \"\"\"Set ROM dimension; only allowed if the basis Vr is None.\"\"\"\n if self.Vr is not None:\n raise AttributeError(\"can't set attribute (r = Vr.shape[1])\")\n if any(op is not None for op in self.operators.values()):\n raise AttributeError(\"can't set attribute (call fit() to reset)\")\n self.__r = r\n\n # Properties: basis -------------------------------------------------------\n @property\n def Vr(self):\n \"\"\"Basis for the linear reduced space (e.g., POD ), of shape (n,r).\"\"\"\n return self.__Vr\n\n @Vr.setter\n def Vr(self, Vr):\n \"\"\"Set the basis, thereby fixing the dimensions n and r.\"\"\"\n self.__Vr = Vr\n if Vr is not None:\n self.__r = Vr.shape[1]\n\n @Vr.deleter\n def Vr(self):\n self.__Vr = None\n\n # Properties: reduced-order operators -------------------------------------\n @property\n def c_(self):\n \"\"\"ROM constant operator, of shape (r,).\"\"\"\n return self.__c_\n\n @c_.setter\n def c_(self, c_):\n self._check_operator_matches_modelform(c_, 'c')\n if c_ is not None:\n self._check_rom_operator_shape(c_, 'c')\n self.__c_ = c_\n\n @property\n def A_(self):\n \"\"\"ROM linear state operator, of shape (r,r).\"\"\"\n return self.__A_\n\n @A_.setter\n def A_(self, A_):\n # TODO: what happens if model.A_ = something but model.r is None?\n self._check_operator_matches_modelform(A_, 'A')\n if A_ is not None:\n self._check_rom_operator_shape(A_, 'A')\n self.__A_ = A_\n\n @property\n def H_(self):\n \"\"\"ROM quadratic state opeator, of shape (r,r(r+1)/2).\"\"\"\n return self.__H_\n\n @H_.setter\n def H_(self, H_):\n self._check_operator_matches_modelform(H_, 'H')\n if H_ is not None:\n if H_.shape == (self.r, self.r**2):\n H_ = compress_H(H_)\n self._check_rom_operator_shape(H_, 'H')\n self.__H_ = H_\n\n @property\n def G_(self):\n \"\"\"ROM cubic state operator, of shape (r,r(r+1)(r+2)/6).\"\"\"\n return self.__G_\n\n @G_.setter\n def G_(self, G_):\n self._check_operator_matches_modelform(G_, 'G')\n if G_ is not None:\n if G_.shape == (self.r, self.r**3):\n G_ = compress_G(G_)\n self._check_rom_operator_shape(G_, 'G')\n self.__G_ = G_\n\n @property\n def B_(self):\n \"\"\"ROM input operator, of shape (r,m).\"\"\"\n return self.__B_\n\n @B_.setter\n def B_(self, B_):\n self._check_operator_matches_modelform(B_, 'B')\n if B_ is not None:\n self._check_rom_operator_shape(B_, 'B')\n self.__B_ = B_\n\n @property\n def operators(self):\n \"\"\"A dictionary of the current ROM operators.\"\"\"\n return {\"c_\": self.c_,\n \"A_\": self.A_,\n \"H_\": self.H_,\n \"G_\": self.G_,\n \"B_\": self.B_}\n\n # Validation methods ------------------------------------------------------\n def _check_operator_matches_modelform(self, operator, key):\n \"\"\"Raise a TypeError if the given operator is incompatible with the\n modelform.\n\n Parameters\n ----------\n operator : ndarray or None\n Operator (ndarray, etc.) data to be attached as an attribute.\n\n key : str\n A single character from 'cAHGB', indicating which operator to set.\n \"\"\"\n if (key in self.modelform) and (operator is None):\n raise TypeError(f\"'{key}' in modelform requires {key}_ != None\")\n if (key not in self.modelform) and (operator is not None):\n raise TypeError(f\"'{key}' not in modelform requires {key}_ = None\")\n\n def _check_rom_operator_shape(self, operator, key):\n \"\"\"Ensure that the given operator has the correct shape.\"\"\"\n # First, check that the required dimensions exist.\n if self.r is None:\n raise AttributeError(\"no reduced dimension 'r' (call fit())\")\n if key == 'B' and (self.m is None):\n raise AttributeError(f\"no input dimension 'm' (call fit())\")\n r, m = self.r, self.m\n\n # Check operator shape.\n if key == \"c\" and operator.shape != (r,):\n raise ValueError(f\"c_.shape = {operator.shape}, \"\n f\"must be (r,) with r = {r}\")\n elif key == \"A\" and operator.shape != (r,r):\n raise ValueError(f\"A_.shape = {operator.shape}, \"\n f\"must be (r,r) with r = {r}\")\n elif key == \"H\" and operator.shape != (r, r*(r + 1)//2):\n raise ValueError(f\"H_.shape = {operator.shape}, must be \"\n f\"(r,r(r+1)/2) with r = {r}\")\n elif key == \"G\" and operator.shape != (r, r*(r + 1)*(r + 2)//6):\n raise ValueError(f\"G_.shape = {operator.shape}, must be \"\n f\"(r,r(r+1)(r+2)/6) with r = {r}\")\n elif key == \"B\" and operator.shape != (r,m):\n raise ValueError(f\"B_.shape = {operator.shape}, must be \"\n f\"(r,m) with r = {r}, m = {m}\")\n\n def _check_inputargs(self, u, argname):\n \"\"\"Check that self.has_inputs agrees with input arguments.\"\"\"\n # TODO (?): replace with _check_operator_matches_modelform().\n if self.has_inputs and u is None:\n raise ValueError(f\"argument '{argname}' required\"\n \" since 'B' in modelform\")\n\n if not self.has_inputs and u is not None:\n raise ValueError(f\"argument '{argname}' invalid\"\n \" since 'B' in modelform\")\n\n def _check_is_trained(self):\n \"\"\"Ensure that the model is trained and ready for prediction.\"\"\"\n operators = self.operators\n try:\n for key in self.modelform:\n op = operators[key+'_']\n self._check_operator_matches_modelform(op, key)\n self._check_rom_operator_shape(op, key)\n except Exception as e:\n raise AttributeError(\"model not trained (call fit())\") from e\n\n # Methods -----------------------------------------------------------------\n def set_operators(self, Vr, c_=None, A_=None, H_=None, G_=None, B_=None):\n \"\"\"Set the ROM operators and corresponding dimensions.\n\n Parameters\n ----------\n Vr : (n,r) ndarray or None\n The basis for the linear reduced space (e.g., POD basis matrix).\n If None, then r is inferred from one of the reduced operators.\n\n c_ : (r,) ndarray or None\n Reduced-order constant term.\n\n A_ : (r,r) ndarray or None\n Reduced-order linear state matrix.\n\n H_ : (r,r(r+1)/2) ndarray or None\n Reduced-order (compact) quadratic state matrix.\n\n G_ : (r,r(r+1)(r+2)/6) ndarray or None\n Reduced-order (compact) cubic state matrix.\n\n B_ : (r,m) ndarray or None\n Reduced-order input matrix.\n\n Returns\n -------\n self\n \"\"\"\n self._clear()\n operators = [c_, A_, H_, G_, B_]\n\n # Save the low-dimensional basis. Sets self.n and self.r if given.\n self.Vr = Vr\n\n # Set the input dimension 'm'.\n if self.has_inputs:\n if B_ is not None:\n self.m = 1 if len(B_.shape) == 1 else B_.shape[1]\n else:\n self.m = 0\n\n # Determine the ROM dimension 'r' if no basis was given.\n if Vr is None:\n self.r = None\n for op in operators:\n if op is not None:\n self.r = op.shape[0]\n break\n\n # Insert the operators. Raises exceptions if shapes are bad, etc.\n self.c_, self.A_, self.H_, self.G_, self.B_, = c_, A_, H_, G_, B_\n\n return self\n\n def project(self, S, label=\"input\"):\n \"\"\"Check the dimensions of S and project it if needed.\"\"\"\n if S.shape[0] not in (self.r, self.n):\n raise ValueError(f\"{label} not aligned with Vr, dimension 0\")\n # TODO: better message, what if Vr is None?\n return self.Vr.T @ S if S.shape[0] == self.n else S\n\n def fit(*args, **kwargs):\n raise NotImplementedError(\"fit() implemented by child classes\")\n\n def predict(*args, **kwargs):\n raise NotImplementedError(\"predict() implemented by child classes\")\n\n\nclass _DiscreteROM(_BaseROM):\n \"\"\"Base class for models that solve the discrete ROM problem,\n\n x_{j+1} = f(x_{j}, u_{j}), x_{0} = x0.\n\n The problem may also be parametric, i.e., x and f may depend on an\n independent parameter µ.\n \"\"\"\n modelform = property(_BaseROM.modelform.fget,\n _BaseROM.modelform.fset,\n _BaseROM.modelform.fdel,\n \"\"\"Structure of the reduced-order model. Each character\n indicates the presence of a different term in the model:\n 'c' : Constant term c\n 'A' : Linear state term Ax.\n 'H' : Quadratic state term H(x⊗x).\n 'G' : Cubic state term G(x⊗x⊗x).\n 'B' : Input term Bu.\n For example, modelform==\"AB\" means f(x,u) = Ax + Bu.\n \"\"\")\n\n def f_(self, x_, u=None):\n \"\"\"Reduced-order model function for discrete models.\n\n Parameters\n ----------\n x_ : (r,) ndarray\n Reduced state vector.\n\n u : (m,) ndarray or None\n Input vector corresponding to x_.\n \"\"\"\n x_new = np.zeros(self.r, dtype=float)\n if self.has_constant:\n x_new += self.c_\n if self.has_linear:\n x_new += self.A_ @ x_\n if self.has_quadratic:\n x_new += self.H_ @ kron2c(x_)\n if self.has_cubic:\n x_new += self.G_ @ kron3c(x_)\n if self.has_inputs:\n x_new += self.B_ @ u\n return x_new\n\n def predict(self, x0, niters, U=None):\n \"\"\"Step forward the learned ROM `niters` steps.\n\n Parameters\n ----------\n x0 : (n,) or (r,) ndarray\n Initial state vector, either full order (n-vector) or projected to\n reduced order (r-vector).\n\n niters : int\n Number of times to step the system forward.\n\n U : (m,niters-1) ndarray\n Inputs for the next niters-1 time steps.\n\n Returns\n -------\n X_ROM : (n,niters) or (r,niters) ndarray\n The approximate solution to the system, including the given\n initial condition. If the basis Vr is None, return solutions in the\n reduced r-dimensional subspace (r,niters). Otherwise, map solutions\n to the full n-dimensional space with Vr (n,niters).\n \"\"\"\n self._check_is_trained()\n\n # Process inputs.\n self._check_inputargs(U, 'U') # Check input/modelform consistency.\n x0_ = self.project(x0, 'x0') # Project initial conditions if needed.\n\n # Verify iteration argument.\n if not isinstance(niters, int) or niters < 0:\n raise ValueError(\"argument 'niters' must be a nonnegative integer\")\n\n # Create the solution array and fill in the initial condition.\n X_ = np.empty((self.r,niters))\n X_[:,0] = x0_.copy()\n\n # Run the iteration.\n if self.has_inputs:\n if callable(U):\n raise TypeError(\"input U must be an array, not a callable\")\n # Validate shape of input, reshaping if input is 1d.\n U = np.atleast_2d(U)\n if U.ndim != 2 or U.shape[0] != self.m or U.shape[1] < niters - 1:\n raise ValueError(\"invalid input shape \"\n f\"({U.shape} != {(self.m,niters-1)}\")\n for j in range(niters-1):\n X_[:,j+1] = self.f_(X_[:,j], U[:,j]) # f(xj,uj)\n else:\n for j in range(niters-1):\n X_[:,j+1] = self.f_(X_[:,j]) # f(xj)\n\n # Reconstruct the approximation to the full-order model if possible.\n return self.Vr @ X_ if self.Vr is not None else X_\n\n\nclass _ContinuousROM(_BaseROM):\n \"\"\"Base class for models that solve the continuous (ODE) ROM problem,\n\n dx / dt = f(t, x(t), u(t)), x(0) = x0.\n\n The problem may also be parametric, i.e., x and f may depend on an\n independent parameter µ.\n \"\"\"\n modelform = property(_BaseROM.modelform.fget,\n _BaseROM.modelform.fset,\n _BaseROM.modelform.fdel,\n \"\"\"Structure of the reduced-order model. Each character\n indicates the presence of a different term in the model:\n 'c' : Constant term c\n 'A' : Linear state term Ax(t).\n 'H' : Quadratic state term H(x⊗x)(t).\n 'G' : Cubic state term G(x⊗x⊗x)(t).\n 'B' : Input term Bu(t).\n For example, modelform==\"AB\" means f(t,x(t),u(t)) = Ax(t) + Bu(t).\n \"\"\")\n\n def f_(self, t, x_, u=None):\n \"\"\"Reduced-order model function for continuous models.\n\n Parameters\n ----------\n t : float\n Time, a scalar.\n\n x_ : (r,) ndarray\n Reduced state vector corresponding to time `t`.\n\n u : func(float) -> (m,)\n Input function that maps time `t` to an input vector of length m.\n \"\"\"\n dxdt = np.zeros(self.r, dtype=float)\n if self.has_constant:\n dxdt += self.c_\n if self.has_linear:\n dxdt += self.A_ @ x_\n if self.has_quadratic:\n dxdt += self.H_ @ kron2c(x_)\n if self.has_cubic:\n dxdt += self.G_ @ kron3c(x_)\n if self.has_inputs:\n dxdt += self.B_ @ u(t)\n return dxdt\n\n def predict(self, x0, t, u=None, **options):\n \"\"\"Simulate the learned ROM with scipy.integrate.solve_ivp().\n\n Parameters\n ----------\n x0 : (n,) or (r,) ndarray\n The initial state vector, either full order (n-vector) or projected\n to reduced order (r-vector).\n\n t : (nt,) ndarray\n The time domain over which to integrate the reduced-order system.\n\n u : callable or (m,nt) ndarray\n The input as a function of time (preferred) or the input at the\n times `t`. If given as an array, u(t) is approximated by a cubic\n spline interpolating the known data points.\n\n options\n Arguments for solver.integrate.solve_ivp(), such as the following:\n method : str\n The ODE solver for the reduced-order system.\n * 'RK45' (default): Explicit Runge-Kutta method of order 5(4).\n * 'RK23': Explicit Runge-Kutta method of order 3(2).\n * 'Radau': Implicit Runge-Kutta method of the Radau IIA family\n of order 5.\n * 'BDF': Implicit multi-step variable-order (1 to 5) method\n based on a backward differentiation formula for the\n derivative.\n * 'LSODA': Adams/BDF method with automatic stiffness detection\n and switching. This wraps the Fortran solver from ODEPACK.\n max_step : float\n The maximimum allowed integration step size.\n See https://docs.scipy.org/doc/scipy/reference/integrate.html.\n\n Returns\n -------\n X_ROM : (n,nt) or (r,nt) ndarray\n The approximate solution to the system over the time domain `t`.\n If the basis Vr is None, return solutions in the reduced\n r-dimensional subspace (r,nt). Otherwise, map the solutions to the\n full n-dimensional space with Vr (n,nt).\n \"\"\"\n self._check_is_trained()\n\n # Process inputs.\n self._check_inputargs(u, 'u') # Check input/modelform consistency.\n x0_ = self.project(x0, 'x0') # Project initial conditions if needed.\n\n # Verify time domain.\n if t.ndim != 1:\n raise ValueError(\"time 't' must be one-dimensional\")\n nt = t.shape[0]\n\n # Interpret control input argument `u`.\n if self.has_inputs:\n if callable(u): # If u is a function, check output shape.\n out = u(t[0])\n if np.isscalar(out):\n if self.m == 1: # u : R -> R, wrap output as array.\n _u = u\n u = lambda s: np.array([_u(s)])\n else: # u : R -> R, but m != 1.\n raise ValueError(\"input function u() must return\"\n f\" ndarray of shape (m,)={(self.m,)}\")\n elif not isinstance(out, np.ndarray):\n raise ValueError(\"input function u() must return\"\n f\" ndarray of shape (m,)={(self.m,)}\")\n elif out.shape != (self.m,):\n message = \"input function u() must return\" \\\n f\" ndarray of shape (m,)={(self.m,)}\"\n if self.m == 1:\n raise ValueError(message + \" or scalar\")\n raise ValueError(message)\n else: # u is an (m,nt) array.\n U = np.atleast_2d(u)\n if U.shape != (self.m,nt):\n raise ValueError(\"invalid input shape \"\n f\"({U.shape} != {(self.m,nt)}\")\n u = CubicSpline(t, U, axis=1)\n\n # Integrate the reduced-order model.\n fun = (lambda t,x_: self.f_(t, x_, u)) if self.has_inputs else self.f_\n self.sol_ = solve_ivp(fun, # Integrate f_(t, x_, u)\n [t[0], t[-1]], # over this time interval\n x0_, # with this initial condition\n t_eval=t, # evaluated at these points\n # jac=self._jac, # with this Jacobian\n **options) # with these solver options.\n\n # Raise warnings if the integration failed.\n if not self.sol_.success: # pragma: no cover\n warnings.warn(self.sol_.message, IntegrationWarning)\n\n # Reconstruct the approximation to the full-order model.\n return self.Vr @ self.sol_.y if self.Vr is not None else self.sol_.y\n\n\n# Mixins for parametric / nonparametric classes (private) =====================\nclass _NonparametricMixin:\n \"\"\"Mixin class for non-parametric reduced model classes.\"\"\"\n @property\n def O_(self):\n \"\"\"The r x d(r,m) Operator matrix O_ = [ c_ | A_ | H_ | G_ | B_ ].\"\"\"\n self._check_is_trained()\n\n blocks = []\n if self.has_constant:\n blocks.append(self.c_.reshape((-1,1)))\n if self.has_linear:\n blocks.append(self.A_)\n if self.has_quadratic:\n blocks.append(self.H_)\n if self.has_cubic:\n blocks.append(self.G_)\n if self.has_inputs:\n blocks.append(self.B_)\n return np.hstack(blocks)\n\n def __str__(self):\n \"\"\"String representation: the structure of the model.\"\"\"\n discrete = isinstance(self, _DiscreteROM)\n x = \"x_{j}\" if discrete else \"x(t)\"\n u = \"u_{j}\" if discrete else \"u(t)\"\n lhs = \"x_{j+1}\" if discrete else \"dx / dt\"\n out = []\n if self.has_constant:\n out.append(\"c\")\n if self.has_linear:\n out.append(f\"A{x}\")\n if self.has_quadratic:\n out.append(f\"H({x} ⊗ {x})\")\n if self.has_cubic:\n out.append(f\"G({x} ⊗ {x} ⊗ {x})\")\n if self.has_inputs:\n out.append(f\"B{u}\")\n return f\"Reduced-order model structure: {lhs} = \" + \" + \".join(out)\n\n def save_model(self, savefile, save_basis=True, overwrite=False):\n \"\"\"Serialize the learned model, saving it in HDF5 format.\n The model can then be loaded with rom_operator_inference.load_model().\n\n Parameters\n ----------\n savefile : str\n The file to save to. If it does not end with '.h5', this extension\n will be tacked on to the end.\n\n savebasis : bool\n If True, save the basis Vr as well as the reduced operators.\n If False, only save reduced operators.\n\n overwrite : bool\n If True and the specified file already exists, overwrite the file.\n If False and the specified file already exists, raise an error.\n \"\"\"\n self._check_is_trained()\n\n # Ensure the file is saved in HDF5 format.\n if not savefile.endswith(\".h5\"):\n savefile += \".h5\"\n\n # Prevent overwriting and existing file on accident.\n if os.path.isfile(savefile) and not overwrite:\n raise FileExistsError(savefile)\n\n with h5py.File(savefile, 'w') as f:\n # Store metadata: ROM class and model form.\n meta = f.create_dataset(\"meta\", shape=(0,))\n meta.attrs[\"modelclass\"] = self.__class__.__name__\n meta.attrs[\"modelform\"] = self.modelform\n\n # Store basis (optionally) if it exists.\n if (self.Vr is not None) and save_basis:\n f.create_dataset(\"Vr\", data=self.Vr)\n\n # Store reduced operators.\n if self.has_constant:\n f.create_dataset(\"operators/c_\", data=self.c_)\n if self.has_linear:\n f.create_dataset(\"operators/A_\", data=self.A_)\n if self.has_quadratic:\n f.create_dataset(\"operators/H_\", data=self.H_)\n if self.has_cubic:\n f.create_dataset(\"operators/G_\", data=self.G_)\n if self.has_inputs:\n f.create_dataset(\"operators/B_\", data=self.B_)\n\n\nclass _ParametricMixin:\n \"\"\"Mixin class for parametric reduced model classes.\"\"\"\n def __call__(self, µ):\n \"\"\"Construct the reduced model corresponding to the parameter µ.\"\"\"\n if isinstance(self, _DiscreteROM):\n ModelClass = _DiscreteParametricEvaluationROM\n elif isinstance(self, _ContinuousROM):\n ModelClass = _ContinuousParametricEvaluationROM\n else:\n raise RuntimeError\n\n self._check_is_trained()\n\n # TODO: Make sure the parameter µ has the correct dimension.\n c_ = self.c_(µ) if callable(self.c_) else self.c_\n A_ = self.A_(µ) if callable(self.A_) else self.A_\n H_ = self.H_(µ) if callable(self.H_) else self.H_\n G_ = self.G_(µ) if callable(self.G_) else self.G_\n B_ = self.B_(µ) if callable(self.B_) else self.B_\n\n return ModelClass(self.modelform).set_operators(Vr=self.Vr,\n c_=c_, A_=A_,\n H_=H_, G_=G_, B_=B_)\n\n def __str__(self):\n \"\"\"String representation: the structure of the model.\"\"\"\n\n discrete = isinstance(self, _DiscreteROM)\n x = \"x_{j}\" if discrete else \"x(t)\"\n u = \"u_{j}\" if discrete else \"u(t)\"\n lhs = \"x_{j+1}\" if discrete else \"dx / dt\"\n\n out = []\n if self.has_constant:\n out.append(\"c(µ)\" if callable(self.c_) else \"c\")\n if self.has_linear:\n A = \"A(µ)\" if callable(self.A_) else \"A\"\n out.append(A + f\"{x}\")\n if self.has_quadratic:\n H = \"H(µ)\" if callable(self.H_) else \"H\"\n out.append(H + f\"({x} ⊗ {x})\")\n if self.has_cubic:\n G = \"G(µ)\" if callable(self.G_) else \"G\"\n out.append(G + f\"({x} ⊗ {x} ⊗ {x})\")\n if self.has_inputs:\n B = \"B(µ)\" if callable(self.B_) else \"B\"\n out.append(B + f\"{u}\")\n return f\"Reduced-order model structure: {lhs} = \"+\" + \".join(out)\n\n\nclass _DiscreteParametricEvaluationROM(_NonparametricMixin, _DiscreteROM):\n \"\"\"Discrete-time ROM that is the evaluation of a parametric ROM.\"\"\"\n pass\n\n\nclass _ContinuousParametricEvaluationROM( _NonparametricMixin, _ContinuousROM):\n \"\"\"Continuous-time ROM that is the evaluation of a parametric ROM.\"\"\"\n pass\n\n\n# Future additions ------------------------------------------------------------\n# TODO: save_model() for parametric forms.\n# TODO: class _SteadyROM(_BaseROM) for the steady problem.\n# TODO: Account for state / input interactions (N?).\n# TODO: jacobians for each model form in the continuous case.\n# TODO: self.p = parameter size for parametric classes (+ shape checking)\n","sub_path":"src/rom_operator_inference/_core/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":28578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"619728426","text":"import sys\nfrom collections import deque\nread=lambda:sys.stdin.readline().strip()\nwrite=lambda x:sys.stdout.write(str(x)+\"\\n\")\nN, K, L = map(int, read().split())\nt = [i for i in range(N+1)]\ncount = 0\nplayers = deque([i for i in range(1, N+1)])\n\nwhile len(players) >= 3:\n\twon = []\n\twhile players:\n\t\ta = players.popleft()\n\t\tif players:\n\t\t\tb = players.popleft()\n\t\t\tif a == K and b != L:\n\t\t\t\twon.append(a)\n\t\t\telif b == K and a != L:\n\t\t\t\twon.append(b)\n\t\t\telif a == L and b != K:\n\t\t\t\twon.append(a)\n\t\t\telif b == L and a != K:\n\t\t\t\twon.append(b)\n\t\t\telse:\n\t\t\t\twon.append(a)\n\n\t\t\tif (a == K and b == L) or (a == L and b == K):\n\t\t\t\tbreak\n\t\telse:\n\t\t\twon.append(a)\n\n\tplayers = list(won)\n\tcount += 1\n\nprint(count + 1)\n","sub_path":"simulation/tornament_1057.py","file_name":"tornament_1057.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"226344620","text":"# Custom functions\nimport OS_funcs_Plotting as OSP\nimport Data_Functions as DF\nimport Data_Defs as DD\n\n# Various libraries\nfrom traffic.data import airports\nimport multiprocessing as mp\nimport glob\nimport simplekml\nfrom traffic.core import Traffic\n\noutf = '/home/proud/Desktop/TEST_SELC.kml'\nindir = '/gf2/eodg/SRP001_PROUD_TURBREP/GO_AROUNDS/VABB/TEST2/'\nfiles = glob.glob(indir + '*.pkl')\nfiles.sort()\n\nairport = airports['VABB']\nax = OSP.setup_fig_airport(airport, 0.15)\n\nfli_len = len(files)\n\nn_files_proc = 50\npool_proc = 50\n\nc_lim = 300\ncounter = 0\n\nf_data = []\npool = mp.Pool(processes=pool_proc)\n\nmain_types = DD.make_typlist_all()\n\nbad_ac_list = {}\n\n\nfor i in range(0, fli_len, n_files_proc):\n print(\"Processing batch starting with \"\n + str(i+1).zfill(5) + \" of \"\n + str(fli_len).zfill(5))\n\n p_list = []\n # First we load several files at once\n for j in range(0, n_files_proc):\n if (i+j < fli_len):\n p_list.append(pool.apply_async(DF.get_flight_basic,\n args=(files[i+j],)))\n\n for p in p_list:\n t_res = p.get()\n for fli in t_res:\n f_data.append(fli)\n traf_arr = Traffic.from_flights(f_data)\n\n p_list = []\n results = []\n f_data = []\n\n end_time = traf_arr.end_time\n kml = simplekml.Kml(open=1)\n\n # Now we process the results\n for flight in traf_arr:\n flight = flight.resample(\"5s\")\n OSP.flight_to_kml(flight, kml)\n\n kml.save(outf)\n\nkml.save(outf)\n","sub_path":"Plot_KML_Traj.py","file_name":"Plot_KML_Traj.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"151387301","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\eveSpaceObject\\spaceobjanimation.py\nimport shipmode.data as stancedata\nSTATE_MACHINE_SHIP_STANDARD = 'shipStandard'\nSTATE_MACHINE_SHIP_STANCE = 'shipStance'\nSTATE_MACHINE_SHIP_LOOP = 'shipLoop'\nstanceAnimations = {stancedata.shipStanceSpeed: 'speed',\n stancedata.shipStanceSniper: 'sniper',\n stancedata.shipStanceDefense: 'defense'\n }\n\ndef GetStateMachine(model, name):\n if model.animationSequencer is None:\n return\n else:\n for stateMachine in model.animationSequencer.stateMachines:\n if stateMachine.name == name:\n return stateMachine\n\n return\n\n\ndef SetShipAnimationStance(ship, stanceID):\n if stanceID not in stanceAnimations:\n return False\n elif ship is None or ship.animationSequencer is None:\n return False\n else:\n state = stanceAnimations[stanceID]\n ship.animationSequencer.GoToState(state)\n return True\n\n\ndef GetAnimationStateFromStance(stanceID):\n if stanceID in stanceAnimations:\n return stanceAnimations[stanceID]\n return 'normal'\n\n\ndef SetUpAnimation(model, stateMachinePath, trinity):\n if model.animationSequencer is None:\n model.animationSequencer = trinity.EveAnimationSequencer()\n stateMachine = trinity.Load(stateMachinePath)\n model.animationSequencer.stateMachines.append(stateMachine)\n return\n\n\ndef LoadAnimationStates(animationStateList, graphicStatesData, model, trinity):\n for sid in animationStateList:\n path = graphicStatesData[sid].file\n SetUpAnimation(model, path, trinity)\n\n\ndef LoadAnimationStatesFromFiles(animationStateFiles, model, trinity):\n for path in animationStateFiles:\n SetUpAnimation(model, path, trinity)\n\n\ndef TriggerDefaultStates(model):\n if not hasattr(model, 'animationSequencer'):\n return\n for stateMachine in model.animationSequencer.stateMachines:\n if len(stateMachine.defaultState) > 1:\n model.animationSequencer.GoToState(stateMachine.defaultState)","sub_path":"client/eveSpaceObject/spaceobjanimation.py","file_name":"spaceobjanimation.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"297589467","text":"from functools import wraps\nimport os\nimport pickle\nimport six\nfrom .types import Command\n\n\nDEVNULL = open(os.devnull, 'w')\n\n\ndef which(program):\n \"\"\"Returns `program` path or `None`.\"\"\"\n\n def is_exe(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n fpath, fname = os.path.split(program)\n if fpath:\n if is_exe(program):\n return program\n else:\n for path in os.environ[\"PATH\"].split(os.pathsep):\n path = path.strip('\"')\n exe_file = os.path.join(path, program)\n if is_exe(exe_file):\n return exe_file\n\n return None\n\n\ndef wrap_settings(params):\n \"\"\"Adds default values to settings if it not presented.\n\n Usage:\n\n @wrap_settings({'apt': '/usr/bin/apt'})\n def match(command, settings):\n print(settings.apt)\n\n \"\"\"\n def decorator(fn):\n @wraps(fn)\n def wrapper(command, settings):\n return fn(command, settings.update(**params))\n return wrapper\n return decorator\n\n\ndef sudo_support(fn):\n \"\"\"Removes sudo before calling fn and adds it after.\"\"\"\n @wraps(fn)\n def wrapper(command, settings):\n if not command.script.startswith('sudo '):\n return fn(command, settings)\n\n result = fn(Command(command.script[5:],\n command.stdout,\n command.stderr),\n settings)\n\n if result and isinstance(result, six.string_types):\n return u'sudo {}'.format(result)\n else:\n return result\n return wrapper\n\n\ndef memoize(fn):\n \"\"\"Caches previous calls to the function.\"\"\"\n memo = {}\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n key = pickle.dumps((args, kwargs))\n if key not in memo:\n memo[key] = fn(*args, **kwargs)\n\n return memo[key]\n\n return wrapper\n","sub_path":"thefuck/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"69133472","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 25 15:36:36 2018\r\n\r\n@author: IIRAMII\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport surprise\r\nimport pandas as pd\r\nfrom surprise import Reader\r\nfrom surprise import Dataset\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport psutil\r\n\r\n\r\ntimex=[]\r\nmem=[]\r\nm1=psutil.virtual_memory().percent\r\n\r\n\r\n#For 100 record dataset\r\nstart = time.time()\r\ndf1 = pd.read_csv('C:/Users/dell pc/Desktop/Project/ratings_1million1.csv', dtype={'rating': float})\r\nreader = Reader(rating_scale=(1, 5))\r\ndata = Dataset.load_from_df(df1[['user_id','book_id','rating']], reader)\r\ndata.split(2)\r\nalgo = surprise.KNNBasic()\r\nresult1 = surprise.evaluate(algo, data, measures=['RMSE'])\r\nend = time.time()\r\nprint(\"Time1\",end - start)\r\ntimex.append(end-start)\r\nm2=psutil.virtual_memory().percent\r\n#print(m2)\r\nmem.append(m2)\r\n\r\n\r\n#For 1000 record dataset\r\nstart = time.time()\r\ndf2 = pd.read_csv('C:/Users/dell pc/Desktop/Project/ratings_1million2.csv', dtype={'rating': float})\r\nreader = Reader(rating_scale=(1, 5))\r\ndata = Dataset.load_from_df(df2[['user_id','book_id','rating']], reader)\r\ndata.split(2)\r\nalgo = surprise.KNNBasic()\r\nresult2 = surprise.evaluate(algo, data, measures=['RMSE'])\r\nend = time.time()\r\nprint(\"Time2\",end - start)\r\ntimex.append(end-start)\r\nm3=psutil.virtual_memory().percent\r\n#print(m2)\r\nmem.append(m3)\r\n\r\n\r\n#For 10000 record dataset\r\nstart = time.time()\r\ndf3 = pd.read_csv('C:/Users/dell pc/Desktop/Project/ratings_1million3.csv', dtype={'rating': float})\r\nreader = Reader(rating_scale=(1, 5))\r\ndata = Dataset.load_from_df(df3[['user_id','book_id','rating']], reader)\r\ndata.split(2)\r\nalgo = surprise.KNNBasic()\r\nresult3 = surprise.evaluate(algo, data, measures=['RMSE'])\r\nend = time.time()\r\nprint(\"Time3\",end - start)\r\ntimex.append(end-start)\r\nm4=psutil.virtual_memory().percent\r\n#print(m2)\r\nmem.append(m4)\r\n\r\n\r\n#For 100000 record dataset\r\nstart = time.time()\r\ndf4 = pd.read_csv('C:/Users/dell pc/Desktop/Project/ratings_1million4.csv', dtype={'rating': float})\r\nreader = Reader(rating_scale=(1, 5))\r\ndata = Dataset.load_from_df(df4[['user_id','book_id','rating']], reader)\r\ndata.split(2)\r\nalgo = surprise.KNNBasic()\r\nresult4 = surprise.evaluate(algo, data, measures=['RMSE'])\r\nend = time.time()\r\nprint(\"Time4\",end - start)\r\ntimex.append(end-start)\r\nm5=psutil.virtual_memory().percent\r\n#print(m2)\r\nmem.append(m5)\r\n\r\n#Plotting the Mean RMSE Vs Number of Records\r\ny = [len(df1),len(df2),len(df3),len(df4)]\r\nplt.plot( np.mean(result1['rmse']),y[0],'gs',label='100 records')\r\nplt.plot( np.mean(result2['rmse']),y[1],'rs',label='1000 records')\r\nplt.plot( np.mean(result3['rmse']),y[2],'bs',label='10000 records')\r\nplt.plot( np.mean(result4['rmse']),y[3],'ys',label='100000 records')\r\nlegend = plt.legend(loc='upper left',bbox_to_anchor=(1, 1))\r\nframe = legend.get_frame()\r\nplt.xlabel('Mean RMSE')\r\nplt.ylabel('Number of records')\r\nplt.title('Mean RMSE Vs Number of Records')\r\nplt.show()\r\n\r\n\r\n#Plotting the Time Vs Number of Records\r\ny = [len(df1),len(df2),len(df3),len(df4)]\r\nplt.plot( timex[0],y[0],'ro',label='100 records')\r\nplt.plot( timex[1], y[1],'bo',label='1000 records')\r\nplt.plot( timex[2],y[2],'go',label='10000 records')\r\nplt.plot( timex[3], y[3],'yo',label='100000 records')\r\nlegend = plt.legend(loc='upper left',bbox_to_anchor=(1, 1))\r\nframe = legend.get_frame()\r\nplt.xlabel('Time(in sec)')\r\nplt.ylabel('Number of records')\r\nplt.title('Time Vs Number of Records')\r\nplt.show()\r\n\r\n\r\n\r\n#Plotting the % of Memory Usage Vs Number of Records\r\ny = [len(df1),len(df2),len(df3),len(df4)]\r\nplt.plot( mem[0],y[0],'g^',label='100 records')\r\nplt.plot( mem[1],y[1],'r^',label='1000 records')\r\nplt.plot( mem[2],y[2],'b^',label='10000 records')\r\nplt.plot( mem[3],y[3],'y^',label='100000 records')\r\nlegend = plt.legend(loc='upper left',bbox_to_anchor=(1, 1))\r\nframe = legend.get_frame()\r\nplt.xlabel('% of Memory Usage')\r\nplt.ylabel('Number of records')\r\nplt.title('% of Memory Usage Vs Number of Records')\r\nplt.show()\r\n","sub_path":"201711019_Smriti_Changulani/Assignment 5/KNNBasic.py","file_name":"KNNBasic.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"615322330","text":"import sys\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport re\n\ndef plot_histogram(image, title, mask=None):\n chans = cv2.split(image)\n colors = ('b', 'g', 'r')\n plt.figure()\n plt.title(title)\n plt.xlabel('Binary value')\n plt.ylabel('Number of Pixels')\n for (chan, color) in zip(chans, colors):\n hist = cv2.calcHist([chan], [0], mask, [256], [0, 256])\n plt.plot(hist, color=color)\n plt.xlim([0, 256])\n# Show difference hot map\n'''\nx, y, z, d = [], [], [], []\ndf_difference = pd.read_csv(sys.argv[1])\nweight_series = df_difference['weight']\ndifference_series = df_difference['difference']\nweight_list = weight_series.tolist()\ndifference_list = difference_series.tolist()\nweight_regx = re.compile(r'\\d{1,2}')\n\nfor weight_str in weight_list:\n weight_nums = weight_regx.findall(weight_str)\n x.append( float(weight_nums[0]) )\n y.append( float(weight_nums[1]) )\n z.append( float(weight_nums[2]) )\n\nfor difference_str in difference_list:\n d.append(float(difference_str))\n\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nx = np.array(x)\ny = np.array(y)\nz = np.array(z)\nd = np.array(d)\n\nax.scatter(x*0.1, y*0.1, z*0.1, c = d, cmap=plt.hot())\nplt.show()\n'''\n\nimage = cv2.imread(sys.argv[1])\nplot_histogram(image, 'color histogram')\nplt.savefig('color_histogram')\n\n","sub_path":"hw1/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"646232887","text":"# boj;name=Project 1;colour=(255, 100, 100);category=Finished\nimport pygame\nfrom pygame.locals import *\nfrom random import *\nimport os\n\n\n#Initilise function\ndef main():\n pygame.init()\n pygame.mouse.set_visible(0)\n\n #screen\n screenwidth = int(pygame.display.Info().current_w * 0.6)\n screenheight = int(pygame.display.Info().current_h * 0.6)\n displaysurf = pygame.display.set_mode((screenwidth, screenheight))\n\n #pictures\n res_location = os.path.join(\"rightfang\", \"res\", \"Project1\")\n\n background = pygame.image.load(os.path.join(res_location, \"background.png\")).convert_alpha()\n player = pygame.image.load(os.path.join(res_location, \"Player.png\")).convert_alpha()\n enemy = pygame.image.load(os.path.join(res_location, \"Enemy.png\")).convert_alpha()\n player_arm = pygame.image.load(os.path.join(res_location, \"Player_arm.png\")).convert_alpha()\n enemy_arm = pygame.image.load(os.path.join(res_location, \"Enemy_arm.png\")).convert_alpha()\n\n #scale pictures\n player = pygame.transform.scale(player, (int(screenwidth*0.1), int(screenheight*0.25)))\n enemy = pygame.transform.scale(enemy, (int(screenwidth*0.1), int(screenheight*0.25)))\n background = pygame.transform.scale(background, (screenwidth, screenheight))\n player_arm = pygame.transform.scale(player_arm, (int(screenwidth*0.06), int(screenheight*0.04)))\n enemy_arm = pygame.transform.scale(enemy_arm, (int(screenwidth*0.06), int(screenheight*0.04)))\n\n #text\n myfont = pygame.font.SysFont(\"droidsansmono\", int(screenwidth*0.04))\n gameover = myfont.render(\"Game Over\", 1, (0, 0, 0)).convert_alpha()\n gameoverwin = myfont.render(\"You Win\", 1, (0, 0, 0)).convert_alpha()\n\n #rects\n player_rect = player.get_rect()\n enemy_rect = enemy.get_rect()\n player_arm_rect = player_arm.get_rect()\n enemy_arm_rect = enemy_arm.get_rect()\n\n #variables\n player_rect.x = int(screenwidth*0.1)\n player_rect.y = int(screenheight*0.6)\n enemy_rect.x = int(screenwidth*0.8)\n enemy_rect.y = int(screenheight*0.6)\n player_velocity_y = int(screenwidth*0.0)\n player_velocity_x = int(screenwidth*0.0)\n enemy_velocity_x = 0\n enemy_velocity_y = 0\n player_health = 100\n enemy_health = 100\n player_arm_bool = False\n game_over = False\n gameoverwin1 = False\n gameover_x = screenwidth*0.45\n gameover_y = screenheight*0.8\n\n fps = 100\n fpsclock = pygame.time.Clock()\n while True:\n\n\n\n #constants\n player_arm_rect.x = player_rect.x + int(screenwidth*0.07)\n player_arm_rect.y = player_rect.y + int(screenheight*0.1)\n enemy_arm_rect.x = enemy_rect.x - int(screenwidth*0.07)\n enemy_arm_rect.y = enemy_rect.y + int(screenwidth*0.1)\n player_health_display_x = player_rect.x + int(screenwidth*0.025)\n player_health_display_y = player_rect.y - int(screenheight*0.07)\n enemy_health_display_x = enemy_rect.x + int(screenwidth*0.003)\n enemy_health_display_y = enemy_rect.y - int(screenheight*0.07)\n\n #drawing\n if not game_over:\n player_health_display = myfont.render(str(player_health)+str(\"%\"), 1, (50, 200, 50)).convert_alpha()\n enemy_health_display = myfont.render(str(enemy_health)+str(\"%\"), 1, (225, 0, 0)).convert_alpha()\n displaysurf.blit(background, (0, 0))\n displaysurf.blit(player, player_rect)\n displaysurf.blit(enemy, enemy_rect)\n displaysurf.blit(player_health_display, (player_health_display_x, player_health_display_y))\n displaysurf.blit(enemy_health_display, (enemy_health_display_x, enemy_health_display_y))\n\n if randrange(0, 50) == 50:\n enemy_velocity_x += int(screenwidth*0.0015)\n elif randrange(0, 50) == 0:\n enemy_velocity_x -= int(screenwidth*0.0015)\n\n if randrange(0, 100) == 1:\n if enemy_rect.y == int(screenheight*0.6):\n enemy_velocity_y -= int(screenheight*0.03)\n enemy_rect.y -= 1\n else:\n enemy_velocity_y = 0\n if enemy_rect.y >= int(screenheight*0.6):\n enemy_rect.y = int(screenheight*0.6)\n enemy_velocity_y = 0\n enemy_velocity_y += screenheight * 0.001\n\n if enemy_rect.colliderect(player_rect):\n player_health -= 5\n enemy_rect.x += screenwidth*0.02\n enemy_velocity_x += int(screenwidth*0.002)\n\n\n\n #screen boundaries\n #enemy\n if enemy_rect.x > (screenwidth - int(screenwidth*0.05)):\n enemy_rect.x = (screenwidth - int(screenwidth*0.05))\n enemy_velocity_x = 0\n if enemy_rect.x < 0:\n enemy_rect.x = 0\n enemy_velocity_x = 0\n #player\n if player_rect.x > (screenwidth - int(screenwidth*0.2)):\n player_rect.x = (screenwidth - int(screenwidth*0.2))\n if player_rect.x < 0:\n player_rect.x = 0\n\n if player_arm_bool:\n displaysurf.blit(player_arm, player_arm_rect)\n\n if player_rect.y < int(screenheight*0.6):\n player_velocity_y -= int(screenheight*0.004)\n else:\n player_velocity_y = 0\n\n for event in pygame.event.get():\n if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:\n pygame.display.quit()\n return\n if event.type == KEYDOWN and player_rect.y == int(screenheight*0.6):\n if event.key == K_SPACE:\n player_velocity_y += int(screenheight*0.046)\n if event.type == KEYDOWN:\n if event.key == K_a:\n player_velocity_x -= int(screenwidth*0.005)\n if event.key == K_d:\n player_velocity_x += int(screenwidth*0.005)\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n player_arm_bool = True\n if enemy_rect.colliderect(player_arm_rect):\n enemy_health -= 5\n if event.type == MOUSEBUTTONUP:\n if event.button == 1:\n player_arm_bool = False\n if event.type == KEYUP:\n if event.key == K_a:\n player_velocity_x = 0\n if event.key == K_d:\n player_velocity_x = 0\n\n if player_health <= 0:\n game_over = True\n displaysurf.blit(background, (0, 0))\n displaysurf.blit(gameover, (gameover_x, gameover_y))\n\n if enemy_health <= 0:\n gameoverwin1 = True\n displaysurf.blit(background, (0, 0))\n if game_over or gameoverwin1:\n displaysurf.blit(player, (randrange(0, int(screenwidth*0.99)), randrange(0, int(gameover_y))))\n displaysurf.blit(enemy, (randrange(0, int(screenwidth*0.99)), randrange(0, int(gameover_y))))\n print(\"Get DDoS m8\")\n\n\n\n\n player_rect.x += player_velocity_x\n player_rect.y -= player_velocity_y\n enemy_rect.x += enemy_velocity_x\n enemy_rect.y += enemy_velocity_y\n\n fpsclock.tick(fps)\n pygame.display.update()","sub_path":"src/rightfang/Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"648848180","text":"from bs4 import BeautifulSoup\nimport requests\nfrom urllib.request import urlopen\nfrom urllib.request import urlretrieve\nimport cgi\nimport os, shutil\nfrom sys import argv\n\nscript, url = argv\n\n# soup google site\nr = requests.get(url)\nsoup = BeautifulSoup(r.content, 'html.parser')\n\n# make a folder for the files if folder does not exist\nhere = os.path.abspath(os.path.dirname(__file__))\nfiles_folder = os.path.join(here, 'files')\n\n# folder exists and contains files\nif os.path.isdir(files_folder) and not os.listdir(files_folder) == []:\n answer = input(\"Delete the files? [Y/N] \")\n try:\n valid = {'y': True, 'Y': True, 'yes': True, 'Yes': True}\n if valid[answer] == True:\n shutil.rmtree(files_folder)\n os.makedirs(files_folder)\n except Exception:\n print(\"User aborted script.\")\n exit()\n\n# folder does not exist, make folder\nelif not os.path.isdir(files_folder): \n os.makedirs(files_folder)\n\nos.chdir(files_folder)\nprint(\"Downloading Files...\")\nfor link in soup.findAll('a', text='Download'):\n # find and download links\n incomplete_url = link.get(\"href\")\n url = \"https://sites.google.com\" + incomplete_url\n remotefile = urlopen(url)\n blah = remotefile.info()['Content-Disposition']\n value, params = cgi.parse_header(blah)\n filename = params[\"filename\"]\n urlretrieve(url, filename)\n filename = url.split(\"/\")[-1]\n with open(filename, \"wb\") as f:\n r = requests.get(url)\n f.write(r.content)\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"358461002","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © Spyder Project Contributors\n# Licensed under the terms of the MIT License\n# (see spyder/__init__.py for details)\n\n\"\"\"\nSpyder API menu widgets.\n\"\"\"\n\n# Standard library imports\nimport sys\nfrom typing import Optional, Union, TypeVar\n\n# Third party imports\nfrom qtpy.QtWidgets import QAction, QMenu\n\n# Local imports\nfrom spyder.api.exceptions import SpyderAPIError\nfrom spyder.utils.qthelpers import add_actions, SpyderAction\n\n\n# --- Constants\n# ----------------------------------------------------------------------------\nMENU_SEPARATOR = None\n\n\n# Generic type annotations\nT = TypeVar('T', bound='SpyderMenu')\n\n\nclass OptionsMenuSections:\n Top = 'top_section'\n Bottom = 'bottom_section'\n\n\nclass PluginMainWidgetMenus:\n Context = 'context_menu'\n Options = 'options_menu'\n\n\n# --- Widgets\n# ----------------------------------------------------------------------------\nclass SpyderMenu(QMenu):\n \"\"\"\n A QMenu subclass to implement additional functionality for Spyder.\n \"\"\"\n MENUS = []\n\n def __init__(self, parent=None, title=None, dynamic=True,\n menu_id=None):\n self._parent = parent\n self._title = title\n self._sections = []\n self._actions = []\n self._actions_map = {}\n self.unintroduced_actions = {}\n self.unintroduced_sections = []\n self._dirty = False\n self.menu_id = menu_id\n\n if title is None:\n super().__init__(parent)\n else:\n super().__init__(title, parent)\n\n self.MENUS.append((parent, title, self))\n if sys.platform == 'darwin' and dynamic:\n # Needed to enable the dynamic population of actions in menus\n # in the aboutToShow signal\n # See spyder-ide/spyder#14612\n self.addAction(QAction(self))\n self.aboutToShow.connect(self._render)\n\n def clear_actions(self):\n \"\"\"\n Remove actions from the menu (including custom references)\n\n Returns\n -------\n None.\n \"\"\"\n self.clear()\n self._sections = []\n self._actions = []\n self._actions_map = {}\n self.unintroduced_actions = {}\n self.unintroduced_sections = []\n\n def add_action(self: T,\n action: Union[SpyderAction, T],\n section: Optional[str] = None,\n before: Optional[str] = None,\n before_section: Optional[str] = None,\n check_before: bool = True,\n omit_id: bool = False):\n \"\"\"\n Add action to a given menu section.\n\n Parameters\n ----------\n action: SpyderAction\n The action to add.\n section: str or None\n The section id in which to insert the `action`.\n before: str\n Make the action appear before the given action identifier.\n before_section: str or None\n Make the item section (if provided) appear before another\n given section.\n check_before: bool\n Check if the `before` action is part of the menu. This is\n necessary to avoid an infinite recursion when adding\n unintroduced actions with this method again.\n omit_id: bool\n If True, then the menu will check if the item to add declares an\n id, False otherwise. This flag exists only for items added on\n Spyder 4 plugins. Default: False\n \"\"\"\n item_id = None\n if isinstance(action, SpyderAction) or hasattr(action, 'action_id'):\n item_id = action.action_id\n elif isinstance(action, SpyderMenu) or hasattr(action, 'menu_id'):\n item_id = action.menu_id\n\n if not omit_id and item_id is None and action is not None:\n raise AttributeError(f'Item {action} must declare an id.')\n\n if before is None:\n self._actions.append((section, action))\n else:\n new_actions = []\n added = False\n before_item = self._actions_map.get(before, None)\n\n for sec, act in self._actions:\n if before_item is not None and act == before_item:\n added = True\n new_actions.append((section, action))\n\n new_actions.append((sec, act))\n\n # Actions can't be added to the menu if the `before` action is\n # not part of it yet. That's why we need to save them in the\n # `unintroduced_actions` dict, so we can add them again when\n # the menu is rendered.\n if not added and check_before:\n before_actions = self.unintroduced_actions.get(before, [])\n before_actions.append((section, action))\n self.unintroduced_actions[before] = before_actions\n\n self._actions = new_actions\n\n if before_section is not None:\n if before_section in self._sections:\n self._update_sections(section, before_section)\n else:\n # If `before_section` has not been introduced yet to the menu,\n # we save `section` to introduce it when the menu is rendered.\n if (section, before_section) not in self.unintroduced_sections:\n self.unintroduced_sections.append(\n (section, before_section)\n )\n elif section not in self._sections:\n self._sections.append(section)\n\n # Track state of menu to avoid re-rendering if menu has not changed\n self._dirty = True\n self._actions_map[item_id] = action\n\n def remove_action(self, item_id: str):\n if item_id in self._actions_map:\n action = self._actions_map.pop(item_id)\n position = None\n\n for i, (_, act) in enumerate(self._actions):\n if act == action:\n position = i\n break\n\n if position is not None:\n self._actions.pop(position)\n self._dirty = True\n\n def get_title(self):\n \"\"\"\n Return the title for menu.\n \"\"\"\n return self._title\n\n def get_actions(self):\n \"\"\"\n Return a parsed list of menu actions.\n\n Includes MENU_SEPARATOR taking into account the sections defined.\n \"\"\"\n actions = []\n for section in self._sections:\n for (sec, action) in self._actions:\n if sec == section:\n actions.append(action)\n\n actions.append(MENU_SEPARATOR)\n return actions\n\n def get_sections(self):\n \"\"\"\n Return a tuple of menu sections.\n \"\"\"\n return tuple(self._sections)\n\n def _render(self):\n \"\"\"\n Create the menu prior to showing it. This takes into account sections\n and location of menus.\n \"\"\"\n if self._dirty:\n self.clear()\n\n # Iterate over unintroduced sections until all of them have been\n # introduced.\n try:\n iter_sections = iter(self.unintroduced_sections)\n while len(self.unintroduced_sections) > 0:\n section, before_section = next(iter_sections)\n self._update_sections(section, before_section)\n\n # If section was introduced, remove it from the list and\n # update iterator.\n if section in self._sections:\n self.unintroduced_sections.remove(\n (section, before_section)\n )\n iter_sections = iter(self.unintroduced_sections)\n except StopIteration:\n # Internally, this should only happen in the Tools menu because\n # the External section can be empty if Kite is not available.\n # Fixes spyder-ide/spyder#16287\n # Note: We can't use the ToolsMenuSections enum here to prevent\n # a circular import.\n left_sections = [('tools_section', 'external_section')]\n\n if self.unintroduced_sections == left_sections:\n self._update_sections('tools_section', 'extras_section')\n else:\n raise SpyderAPIError(\n f\"You're trying to introduce some sections before \"\n f\"others that don't have any actions. This is the \"\n f\"list of (section, before_section) that's failing to \"\n f\"be added:\\n\\n{self.unintroduced_sections}\"\n )\n\n # Update actions with those that were not introduced because\n # a `before` action they required was not part of the menu yet.\n for before, actions in self.unintroduced_actions.items():\n for section, action in actions:\n self.add_action(action, section=section,\n before=before, check_before=False)\n\n actions = self.get_actions()\n add_actions(self, actions)\n self._dirty = False\n\n def _update_sections(self, section, before_section):\n \"\"\"Update sections ordering.\"\"\"\n new_sections = []\n for sec in self._sections:\n if sec == before_section:\n new_sections.append(section)\n if sec != section:\n new_sections.append(sec)\n self._sections = new_sections\n\n\nclass MainWidgetMenu(SpyderMenu):\n \"\"\"\n This menu fixes the bottom section of the options menu.\n \"\"\"\n\n def _render(self):\n \"\"\"\n Create the menu prior to showing it. This takes into account sections\n and location of menus. It also hides consecutive separators if found.\n \"\"\"\n if self._dirty:\n self.clear()\n bottom = OptionsMenuSections.Bottom\n actions = []\n for section in self._sections:\n for (sec, action) in self._actions:\n if sec == section and sec != bottom:\n actions.append(action)\n\n actions.append(MENU_SEPARATOR)\n\n # Add bottom actions\n for (sec, action) in self._actions:\n if sec == bottom:\n actions.append(action)\n\n add_actions(self, actions)\n self._dirty = False\n","sub_path":"spyder/api/widgets/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":10447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195896334","text":"import logging\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch.dispatcher import receiver\n\nfrom cfp.models import PaperApplication\nfrom slack.utils import post_notification\n\n\n@receiver(post_save, sender=PaperApplication, dispatch_uid='slack_notify_application')\ndef slack_notify_application(sender, instance, created, **kwargs):\n title = 'New application' if created else 'Updated application'\n\n text = '{}: {} - {} min'.format(\n instance.applicant,\n instance.title,\n instance.duration,\n )\n\n try:\n post_notification(title, text)\n except Exception:\n logging.exception(\"Failed posting to Slack\")\n","sub_path":"cfp/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"108692573","text":"import sys\nimport numpy\ndef readTab(infile): # read in txt file\n with open(infile, 'r') as input_file:\n # read in tab-delim text\n output = []\n for input_line in input_file:\n input_line = input_line.strip()\n temp = input_line.split('\\t')\n output.append(temp)\n return output\ndef backgroundSubtract(table,row): # calculate and remove background\n\tsum = 0\n\toutput=[]\n\tfor i in table[row-1]:\n\t\tsum += float(i)\n\tbackground = sum/len(table[row-1])\n\tfor i in table:\n\t\ttemp = []\n\t\tfor j in i:\n\t\t\ttemp.append(str(float(j)-background))\n\t\toutput.append(temp)\n\treturn output\ndef normalizeViability(table, row=False,col=False): # normalize counts to vehicle control row or column\n\tif row != False:\n\t\tsum = 0\n\t\toutput=[]\n\t\tfor i in table[row-1]:\n\t\t\tsum += float(i)\n\t\tvehicle = sum/len(table[row-1])\n\t\tfor i in table:\n\t\t\ttemp = []\n\t\t\tfor j in i:\n\t\t\t\ttemp.append(str(100*(float(j)/vehicle)))\n\t\t\toutput.append(temp)\n\t\treturn output\n\tif col != False:\n\t\tsum = 0\n\t\tcnt = 0\n\t\toutput=[]\n\t\tfor i in table:\n\t\t\tsum += float(i[col-1])\n\t\t\tcnt+=1\n\t\tvehicle = sum/cnt\n\t\tfor i in table:\n\t\t\ttemp = []\n\t\t\tfor j in i:\n\t\t\t\ttemp.append(str(100*(float(j)/vehicle)))\n\t\t\toutput.append(temp)\n\t\treturn output\ndef normalizeViabilityLowest(table,dose,by_drug = \"None\",desc=False):\n\tnormalizer = 1\n\tif by_drug != \"None\":\n\t\tfor i in dose[1:]:\n\t\t\tif by_drug == i[4]:\n\t\t\t\ttemp = []\n\t\t\t\ttemp = i[0] + \"-\" + i[1]\n\t\t\t\tpositions = temp.split(\"-\")\n\t\ttemp = []\n\t\tfor i in range(0,len(positions)):\n\t\t\tpositions[i] = int(positions[i])-1\n\t\tfor j in range(positions[0],positions[1]+1):\n\t\t\ttemp.append(float(table[j][positions[2]]))\n\t\tnormalizer = numpy.mean(temp,axis=0)\n\tfor i in dose[1:]: # row start, row end, col start, col end\n\t\ttemp = []\n\t\ttemp = i[0] + \"-\" + i[1]\n\t\tpositions = temp.split(\"-\")\n\t\tfor i in range(0,len(positions)):\n\t\t\tpositions[i] = int(positions[i])-1\n\t\tif desc == False:\n\t\t\ttemp = []\n\t\t\tfor j in range(positions[0],positions[1]+1):\n\t\t\t\ttemp.append(float(table[j][positions[2]]))\n\t\t\tif by_drug == \"None\":\n\t\t\t\tnormalizer = numpy.mean(temp,axis=0)\n\t\t\tfor j in range(positions[0],positions[1]+1):\n\t\t\t\tfor k in range(positions[2],positions[3]+1):\n\t\t\t\t\ttable[j][k] = str(100*(float(table[j][k])/normalizer))\n\t\telse:\n\t\t\ttemp = []\n\t\t\tfor j in range(positions[0],positions[1]+1):\n\t\t\t\ttemp.append(float(table[j][positions[3]]))\n\t\t\tnormalizer = numpy.mean(temp)\n\t\t\tfor j in range(positions[0],positions[1]+1):\n\t\t\t\tfor k in range(positions[2],positions[3]+1):\n\t\t\t\t\ttable[j][k] = str(100*(float(table[j][k])/normalizer))\n\n\treturn table\ndef doseResponse(data_file,dose_file,background_row,by_drug = \"None\", desc=False,lowest0 = True,normalize=\"lowest\"):\n\t# data_file = file you want to upload\n\t# dose_file = user generated info file about plating\n\t# background_row = row to use for background correction\n\t# format = M5 spectramax output or simple matrix format\n\t# desc = is the data set high to low conc?\n\t# lowest0 = is the lowest dose vehicle?\n\t# normalize options = \"lowest\",[\"row\",#],[\"col\",#]\n\t\t# normalize by lowest concentration for each curve or normalize\n\t\t# everything by a certain column?\n\n\tdata = readTab(data_file)\n\tdose = readTab(dose_file)\n\tdoses = {}\n\tlocation = {}\n\tdrugs = []\n\tfor i in dose[1:]: # get doses for each drug and store as dictionary\n\t\ttemp = []\n\t\ttemp = i[0] + \"-\" + i[1]\n\t\tpositions = temp.split(\"-\")\n\t\tfor j in range(0,len(positions)):\n\t\t\tpositions[j] = int(positions[j])-1\n\t\tlocation[i[4]] = positions\n\t\tdrugs.append(i[4])\n\t\tcnt=0\n\t\ttemp = []\n\t\tif \"HighConc\" in dose[0]:\n\t\t\tfor j in range(positions[2],positions[3]):\n\t\t\t\tif cnt == 0:\n\t\t\t\t\ttemp.append(float(i[2]))\n\t\t\t\telse:\n\t\t\t\t\ttemp.append(temp[cnt-1]/(int(i[3])))\n\t\t\t\tcnt+=1\n\t\t\tdoses[i[4]] = temp\n\t\telse:\n\t\t\tdoses[i[4]] = i[2].split(\",\")\n\tdata_bg = backgroundSubtract(data, background_row) # subtract background\n\tfullData = {}\n\taverages = {}\n\tsd = {}\n\tif normalize != \"lowest\": # normalization method\n\t\tif normalize[0] == \"col\":\n\t\t\tdata_nm = normalizeViability(data_bg, col=normalize[1])\n\t\tif normalize[0] == \"row\":\n\t\t\tdata_nm = normalizeViability(data_bg, row=normalize[1])\n\telse:\n\t\tdata_nm = normalizeViabilityLowest(data_bg, dose,by_drug = by_drug, desc=desc)\n\n\n\twith open(\"output.txt\",\"w\") as x: # write file to import into R\n\t\tx.write(\"\\t\".join([\"Dose\",\"Response\",\"Drug\"]))\n\t\tx.write(\"\\n\")\n\t\tfor i in drugs:\n\t\t\tfor j in range(location[i][0],location[i][1]+1):\n\t\t\t\t\tcnt = 0\n\t\t\t\t\tfor k in range(location[i][2],location[i][3]+1):\n\t\t\t\t\t\tif desc == False:\n\t\t\t\t\t\t\tif lowest0 == True:\n\t\t\t\t\t\t\t\tif cnt == 0:\n\t\t\t\t\t\t\t\t\tx.write(\"0\")\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tx.write(str(doses[i][-1*(cnt)]))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif lowest0 == True:\n\t\t\t\t\t\t\t\tif cnt == len(doses[i]):\n\t\t\t\t\t\t\t\t\tx.write(\"0\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tx.write(str(doses[i][cnt]))\n\t\t\t\t\t\tx.write(\"\\t\"); x.write(str(data_nm[j][k])); x.write(\"\\t\")\n\t\t\t\t\t\tx.write(i); x.write(\"\\n\")\n\t\t\t\t\t\tcnt+=1\n\t# organize into 3 column table for each drug (dose, response, drug)\n\t# play with drc to get multiple lines on same plot\n\t# will then add points w/ error bars for each drug\ndoseResponse(sys.argv[1], sys.argv[2], 2, by_drug = sys.argv[3], desc = False, lowest0 = True, normalize=\"lowest\")\n","sub_path":"Viability_preprocess.py","file_name":"Viability_preprocess.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"19511230","text":"from django.test import TestCase\nfrom decimal import Decimal\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.contrib.auth.models import User\nfrom store.models import Item, Employee\n\nclass HomePageTest(TestCase):\n \n def setUp(self): \n Item.objects.create(\n title='Phone', \n slug ='phone', \n image= SimpleUploadedFile('phone_image.jpg', content=b'', content_type='image/jpg'), \n price= Decimal(12000)\n )\n\n def test_homepage(self):\n response = self.client.get('/')\n self.assertEqual(response.status_code, 200)\n\n\n def test_homepage_content(self):\n response = self.client.get('/')\n item = Item.objects.get(id=1)\n self.assertEqual(response.status_code, 200)\n self.assertTrue(item.title in str(response.content))\n\nclass ConfirmSaleViewTest(TestCase):\n\n def setUp(self): \n Item.objects.create(\n title='Phone', \n slug ='phone', \n image= SimpleUploadedFile('phone_image.jpg', content=b'', content_type='image/jpg'), \n price= Decimal(12000)\n )\n\n def test_get(self):\n response = self.client.get('/phone/')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, text='Phone')\n \n def test_post_success(self):\n response = self.client.post('/phone/', data={\"employee\": 'ATB', \"qty\": 1})\n self.assertEqual(response.status_code, 200)\n \n \n","sub_path":"ecommerce/store/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"77059426","text":"from myhdl import always_seq, always_comb, block\nfrom myhdl import intbv, Signal, concat\nfrom .rlecore import DataStream, rle\nfrom .rlecore import RLESymbols, RLEConfig\nfrom .doublebuffer import doublefifo\nfrom .doublebuffer import DoubleFifoBus\n\n\nclass InDataStream(DataStream):\n \"\"\"\n InputData Interface Class\n ready: module asserts ready if its ready for next block\n\n start: start signal triggers the module to start\n processing data\n\n input_val: input to the rle module\n \"\"\"\n def __init__(self, width):\n super(InDataStream, self).__init__(width)\n self.ready = Signal(bool(0))\n\n\nclass BufferDataBus(RLESymbols):\n \"\"\"\n Output Interface Class\n Amplitude: amplitude of the number\n\n size: size required to store amplitude\n\n runlength: number of zeros\n\n dovalid: asserts if ouput is valid\n buffer_sel: It selects the buffer in double buffer\n read_enable: enables\n fifo_empty: asserts if any of the two fifos are empty\n\n \"\"\"\n def __init__(self, width, size, rlength):\n super(BufferDataBus, self).__init__(width, size, rlength)\n self.buffer_sel = Signal(bool(0))\n self.read_enable = Signal(bool(0))\n self.fifo_empty = Signal(bool(0))\n\n\n@block\ndef rlencoder(dfifo_const, constants, reset, clock,\n indatastream, bufferdatabus, rleconfig):\n \"\"\"The top module connects rle core and rle double buffer\"\"\"\n\n assert isinstance(indatastream, InDataStream)\n assert isinstance(bufferdatabus, BufferDataBus)\n assert isinstance(rleconfig, RLEConfig)\n\n # Signals used to temporarily process data\n rlesymbols_temp = RLESymbols(\n constants.width_data, constants.size, constants.rlength)\n\n datastream_temp = DataStream(constants.width_data)\n\n # maximum number of zeroes that can be count\n limit = int((2**constants.rlength) - 1)\n\n # width of data to be stored in rle double fifo\n width_dbuf = constants.width_data + constants.size + constants.rlength\n\n # instantiation of double buffer bus\n dfifo = DoubleFifoBus(width_dbuf)\n\n # maximum number of pixels that can be processes for one time\n wr_cnt = Signal(intbv(0)[(constants.max_write_cnt + 1):])\n\n @always_comb\n def assign0():\n dfifo.buffer_sel.next = bufferdatabus.buffer_sel\n dfifo.read_req.next = bufferdatabus.read_enable\n bufferdatabus.fifo_empty.next = dfifo.fifo_empty\n datastream_temp.start.next = indatastream.start\n\n @always_comb\n def assign1():\n \"\"\"runlength, size and amplitude read from double buffer\"\"\"\n bufferdatabus.runlength.next = dfifo.data_out[(\n constants.width_data+constants.size+constants.rlength):(\n constants.width_data+constants.size)]\n\n bufferdatabus.size.next = dfifo.data_out[(\n constants.width_data+constants.size):constants.width_data]\n\n bufferdatabus.amplitude.next = dfifo.data_out[constants.width_data:0].signed()\n\n # send the inputdata into rle core\n rle_core = rle(\n constants, reset, clock, datastream_temp, rlesymbols_temp, rleconfig)\n\n @always_comb\n def assign2():\n datastream_temp.input_val.next = indatastream.input_val\n\n # write the processed data to rle double fifo\n # @todo: remove dfifo_const\n rle_doublefifo = doublefifo(clock, reset, dfifo,\n width=dfifo_const.width, depth=dfifo_const.depth)\n\n @always_comb\n def assign3():\n dfifo.data_in.next = concat(\n rlesymbols_temp.runlength, rlesymbols_temp.size,\n rlesymbols_temp.amplitude)\n\n dfifo.write_enable.next = rlesymbols_temp.dovalid\n\n @always_seq(clock.posedge, reset=reset)\n def seq1():\n indatastream.ready.next = False\n if indatastream.start:\n wr_cnt.next = 0\n\n # select the data to be written\n if rlesymbols_temp.dovalid:\n if (rlesymbols_temp.runlength == limit) and (\n rlesymbols_temp.size == 0):\n\n wr_cnt.next = wr_cnt + limit + 1\n\n else:\n wr_cnt.next = wr_cnt + 1 + rlesymbols_temp.runlength\n\n if dfifo.data_in == 0 and wr_cnt != 0:\n indatastream.ready.next = 1\n else:\n if (wr_cnt + rlesymbols_temp.runlength) == constants.max_write_cnt:\n indatastream.ready.next = True\n\n @always_comb\n def assign4():\n # output data valid signal\n bufferdatabus.dovalid.next = bufferdatabus.read_enable\n\n return (assign0, assign1, rle_core, assign2,\n rle_doublefifo, assign3, seq1, assign4)\n","sub_path":"jpegenc/subblocks/rle/rle.py","file_name":"rle.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"393515535","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Split JSONL files.\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport sys\n\nfrom pathlib import Path\n\nfrom pytility import batchify\nfrom scrapy.utils.misc import arg_to_iter\n\ntry:\n # pylint: disable=redefined-builtin\n from smart_open import open\nexcept ImportError:\n pass\n\nLOGGER = logging.getLogger(__name__)\nFIELDS = frozenset(\n {\n \"article_id\",\n \"url_canonical\",\n \"url_mobile\",\n \"url_amp\",\n \"url_thumbnail\",\n \"published_at\",\n \"title_short\",\n \"author\",\n \"description\",\n \"category\",\n \"keyword\",\n \"section_inferred\",\n \"country\",\n \"language\",\n \"source_name\",\n }\n)\n\n\ndef _is_empty(item):\n return (\n isinstance(item, (bytes, dict, frozenset, list, set, str, tuple)) and not item\n )\n\n\ndef _filter_fields(item, fields=None, exclude_empty=False):\n return {\n k: v\n for k, v in item.items()\n if (not fields or k in fields) and (not exclude_empty or not _is_empty(v))\n }\n\n\ndef _load_items(iterable, fields=None, exclude_empty=False):\n if isinstance(iterable, (bytes, str, os.PathLike)):\n LOGGER.info(\"Reading from <%s>\", iterable)\n with open(iterable) as file_obj:\n yield from _load_items(file_obj, fields=fields, exclude_empty=exclude_empty)\n return\n\n fields = frozenset(arg_to_iter(fields))\n\n for i, line in enumerate(iterable):\n try:\n item = json.loads(line)\n except json.JSONDecodeError:\n LOGGER.exception(\"Unable to parse line %d: %s [...]\", i + 1, line[:100])\n else:\n yield _filter_fields(item=item, fields=fields, exclude_empty=exclude_empty)\n\n\ndef split_files(\n path_in,\n path_out=None,\n size=None,\n fields=FIELDS,\n exclude_empty=False,\n dry_run: bool = False,\n):\n \"\"\"Split a JSON lines file into JSON files of a given size.\"\"\"\n\n dry_run_prefix = \"[DRY RUN] \" if dry_run else \"\"\n\n path_in = Path(path_in).resolve()\n path_out = \"-\" if path_out is None or path_out == \"-\" else Path(path_out).resolve()\n\n LOGGER.info(\n \"%sReading items from <%s> splitting them into <%s>\",\n dry_run_prefix,\n path_in,\n path_out,\n )\n\n if not dry_run and path_out != \"-\":\n path_out.parent.mkdir(parents=True, exist_ok=True)\n\n items = tuple(_load_items(path_in, fields=fields, exclude_empty=exclude_empty))\n batches = batchify(items, size) if size else (items,)\n total = len(items)\n count = 0\n\n LOGGER.info(\"%sRead %d items from <%s>\", dry_run_prefix, total, path_in)\n\n for i, batch in enumerate(batches):\n batch = list(batch)\n count += len(batch)\n result = {\n \"count\": total,\n \"previous\": i - 1 if i else None,\n \"next\": i + 1 if count < total else None,\n \"results\": batch,\n }\n\n if path_out == \"-\":\n json.dump(result, sys.stdout, sort_keys=True)\n print()\n\n else:\n out_path = str(path_out).format(number=i)\n LOGGER.info(\"%sWriting batch #%d to <%s>\", dry_run_prefix, i, out_path)\n if not dry_run:\n with open(out_path, \"w\") as out_file:\n json.dump(result, out_file, sort_keys=True)\n\n LOGGER.info(\"%sDone splitting.\", dry_run_prefix)\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"infile\", help=\"input file\")\n parser.add_argument(\"--batch\", \"-b\", type=int, help=\"batch size\")\n parser.add_argument(\"--outfile\", \"-o\", help=\"output file path\")\n parser.add_argument(\"--dry-run\", \"-n\", action=\"store_true\", help=\"dry run\")\n parser.add_argument(\n \"--verbose\",\n \"-v\",\n action=\"count\",\n default=0,\n help=\"log level (repeat for more verbosity)\",\n )\n\n return parser.parse_args()\n\n\ndef _main():\n args = _parse_args()\n\n logging.basicConfig(\n stream=sys.stderr,\n level=logging.DEBUG if args.verbose > 0 else logging.INFO,\n format=\"%(asctime)s %(levelname)-8.8s [%(name)s:%(lineno)s] %(message)s\",\n )\n\n LOGGER.info(args)\n\n split_files(\n path_in=args.infile,\n path_out=args.outfile,\n size=args.batch,\n fields=FIELDS,\n exclude_empty=True,\n dry_run=args.dry_run,\n )\n\n\nif __name__ == \"__main__\":\n _main()\n","sub_path":"board_game_scraper/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"351599796","text":"import smtplib\r\nimport re\r\nfrom configparser import ConfigParser\r\nimport phonenumbers\r\nimport json\r\n\r\n\r\ndef sendemailnotification(emaildict):\r\n #This function is used to send email Notification. We check the email regex and send the email via local smtp\r\n\r\n regex = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'\r\n\r\n sender = emaildict['emailfrom']\r\n if (re.search(regex, sender)):\r\n print(f\"Valid from Email {sender}\")\r\n else:\r\n return (f\"Invalid From Email {sender}\", emaildict)\r\n receivers = emaildict['emailto']\r\n if (re.search(regex, receivers)):\r\n print(f\"Valid from Email {receivers}\")\r\n else:\r\n return (f\"Invalid From Email {receivers}\", emaildict)\r\n\r\n try:\r\n # smtpObj = smtplib.SMTP('localhost')\r\n # smtpObj.sendmail(sender, receivers, message)\r\n print(f\"Successfully sent email with message {emaildict['message']}\")\r\n return (1)\r\n\r\n except Exception as e:\r\n return (f\"Error: unable to send email with exception {e} \", emaildict)\r\n\r\n\r\ndef sendSlackNotification(slackdict):\r\n #This function is used to publish messages to valid slack channels\r\n # valid channels : ['#validchannel', '#validchannel2', '#channel3', '#hello']\r\n slackConfigur = ConfigParser()\r\n slackConfigur.read('config.ini')\r\n validChannel = slackConfigur.get('slack', 'slackChannelList')\r\n if (slackdict['slackchannelname'] in validChannel):\r\n print('Valid slack channel')\r\n return (1)\r\n else:\r\n print(\"Invalid slack channel\")\r\n return (\"Invalid slack channel\", slackdict)\r\n\r\n\r\ndef sendSmsNotification(smsdict):\r\n numParse = phonenumbers.parse(smsdict['phoneNumber'], None)\r\n if (phonenumbers.is_valid_number(numParse) is True):\r\n print(\"Valid Phone number. Sms successfully sent\")\r\n return (1)\r\n else:\r\n print(\"Invalid phone number\")\r\n return (\"Invalid phone number \", smsdict)\r\n\r\n\r\ndef sendnotification(resultDict):\r\n #print (resultDict)\r\n successnotify = {}\r\n failurenotify = {}\r\n for i in range(len(resultDict)):\r\n # print(resultDict[i])\r\n if (resultDict[i][\"notifytype\"] == \"email\"):\r\n result = sendemailnotification(resultDict[i])\r\n if (result == 1):\r\n successnotify[i] = resultDict[i]\r\n else:\r\n failurenotify[i] = result\r\n elif (resultDict[i][\"notifytype\"] == \"slack\"):\r\n result = sendSlackNotification(resultDict[i])\r\n if (result == 1):\r\n successnotify[i] = resultDict[i]\r\n else:\r\n failurenotify[i] = result\r\n elif (resultDict[i][\"notifytype\"] == \"sms\"):\r\n result = sendSmsNotification(resultDict[i])\r\n if (result == 1):\r\n successnotify[i] = resultDict[i]\r\n else:\r\n failurenotify[i] = result\r\n print(\"Notification Successfully sent : \", successnotify)\r\n print(\"Notification Failed to sent : \", failurenotify)\r\n getInputs()\r\n\r\ndef sendBulkNotification(resultDict):\r\n #print (resultDict)\r\n successnotify = {}\r\n failurenotify = {}\r\n for (key,value) in resultDict.items():\r\n #print(\"Key: \" + key)\r\n #print(\"Value: \" + str(value))\r\n #print (value[\"notifytype\"] )\r\n if (value[\"notifytype\"] == \"email\"):\r\n result = sendemailnotification(value)\r\n if (result == 1):\r\n successnotify[key]=value\r\n else:\r\n failurenotify[key] = result\r\n elif (value[\"notifytype\"] == \"slack\"):\r\n result = sendSlackNotification(value)\r\n if (result == 1):\r\n successnotify[key]=value\r\n else:\r\n failurenotify[key] = result\r\n elif (value[\"notifytype\"] == \"sms\"):\r\n result = sendSmsNotification(value)\r\n if (result == 1):\r\n successnotify[key]=value\r\n else:\r\n failurenotify[key] = result\r\n print(\"Notification Successfully sent : \", successnotify)\r\n print(\"Notification Failed to sent : \", failurenotify)\r\n\r\n\r\ndef getInputs():\r\n notifyDict = {}\r\n #print(len(notifyDict))\r\n while (len(notifyDict) < 3):\r\n print('\\n' * 1)\r\n notifytype = input(\"Enter the notification type : \").lower()\r\n if (notifytype == \"email\"):\r\n emailfrom = input(\"Enter From address : \").lower()\r\n emailto = input(\"Enter To address : \").lower()\r\n notifytype = \"email\"\r\n subject = input(\"Enter email subject : \").lower()\r\n message = input(\"Enter email message : \").lower()\r\n notifyDict[len(notifyDict)] = {'emailfrom': emailfrom, 'emailto': emailto, 'notifytype': notifytype,\r\n 'subject': subject, 'message': message}\r\n elif (notifytype == \"slack\"):\r\n emailto = input(\"Enter To address : \").lower()\r\n slackchannelname = input(\"Enter Slack channel name : \").lower()\r\n url = \"www.slack.com\"\r\n message = input(\"Enter Slack message : \").lower()\r\n notifytype = \"slack\"\r\n notifyDict[len(notifyDict)] = {'emailto': emailto, 'slackchannelname': slackchannelname, 'url': url,\r\n 'message': message, 'notifytype': notifytype}\r\n elif (notifytype == \"sms\"):\r\n phoneNumber = input(\"Please enter valid phone number : \")\r\n notifytype = \"sms\"\r\n messageSms = input(\"Please enter the message : \")\r\n notifyDict[len(notifyDict)] = {'phoneNumber': phoneNumber, 'notifytype': notifytype,\r\n 'messageSms': messageSms}\r\n\r\n else:\r\n print(\r\n f\"Given input {notifytype} is wrong. Please provide notification type from the list : Email, Slack or SMS\")\r\n # print (notifyDict)\r\n print(\"Please wait while we are processing the request\")\r\n sendnotification(notifyDict)\r\n\r\ndef getBulkInputs():\r\n \r\n bulkconfigur = ConfigParser()\r\n bulkconfigur.read('config.ini')\r\n validpath = bulkconfigur.get('bulkjsonpath', 'path')\r\n with open(validpath) as json_file:\r\n data = json.load(json_file)\r\n print(data)\r\n sendBulkNotification(data)\r\n #print (data)\r\n\r\n\r\n'''\r\n-----Start of Program----\r\nWe have 2 modes for notification publication. Indivisual and Bulk. \r\nIndivisual : We need to provide valid inputs for each required field for notification type\r\nBulk : We load the system with prepopulated json data to publish notification.\r\n'''\r\n\r\nprint(\"Hello Welcome to Notification channel\")\r\ninputType = \"\"\r\nwhile inputType != \"indivisual\" or inputType != \"bulk\":\r\n print (\"\\n\"*1)\r\n inputType = input(\"Please provide the type of notification data : Bulk or Indivisual \").lower()\r\n if (inputType == \"indivisual\"):\r\n getInputs()\r\n elif (inputType == \"bulk\"):\r\n getBulkInputs()\r\n\r\n","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":6957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"143811928","text":"#!/usr/bin/env python3\n\n#https://codeforces.com/problemset/problem/1354/B\n#找到最短连续子串包含123.\n#规律: 一定是abbbbc形式..\n#recent含义是1/2/3最近出现的位置..\n\ndef tstring(s):\n counts = [s.count('1'),s.count('2'),s.count('3')]\n if 0 in counts:\n return 0\n minlen = len(s)\n recent = [None,None,None]\n for i in range(len(s)):\n n = int(s[i])-1\n recent[n] = i\n if None in recent:\n continue\n l = min(recent)\n minlen = min(minlen,i-l+1)\n return minlen\n\nn = int(input())\n[print(r) for r in [tstring(input()) for i in range(n)]]\n","sub_path":"codeforces/dp动态规划/1200/1354B三元字符串.py","file_name":"1354B三元字符串.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"26983631","text":"from flask import Flask, request \nfrom flask import redirect, url_for\nfrom utils import mysqldb \nfrom flask import session\nfrom datetime import datetime\n\n\ndef flush_host_create(data_host, data_apply):\n\t\"\"\"Just setting is_dirty to 0 is OK\"\"\"\n\tdata_host.is_dirty = 0\n\tmysqldb.commit()\n\ndef flush_db_create(data_base, data_apply):\n\thost_id = data_base.host_id\n\tdata_host = mysqldb.DataHost.query.filter_by(id=host_id).first()\n\n\tmysqldb.commit()\n\n\"\"\"\n1. evaluate wether table is new or need to alter\n2. evaluate which fields need to update or added\n\"\"\"\ndef flush_table_create(data_table, data_apply):\n\tdb_id = data_table.db_id\n\tdata_base = mysqldb.DataBase.query.filter_by(id=db_id).first()\n\thost_id = data_base.host_id\n\tdata_host = mysqldb.DataHost.query.filter_by(id=host_id).first()\n\n\tmysqldb.commit()\n","sub_path":"meta_data/modules/mod_flush.py","file_name":"mod_flush.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"3689175","text":"from bs4 import BeautifulSoup\n\nimport pandas as pd\nimport string\nimport re\n\n# Choose the train/test data ratio\nratio = 0.7\ntrain = pd.read_csv(r'C:\\Users\\clikim\\PycharmProjects\\DataComp-IMDB\\data\\raw\\train.csv', encoding='utf-8')\nunsup = pd.read_csv(r'C:\\Users\\clikim\\PycharmProjects\\DataComp-IMDB\\data\\raw\\test.csv', encoding='utf-8')\n\ntrain_pos = open('train_pos.txt', 'w', encoding='utf-8')\ntrain_neg = open('train_neg.txt', 'w', encoding='utf-8')\ntest_pos = open('test_pos.txt', 'w', encoding='utf-8')\ntest_neg = open('test_neg.txt', 'w', encoding='utf-8')\nunsup_txt = open('unsup.txt', 'w', encoding='utf-8')\n\nthreshold = len(train.index) * ratio\n\nsmileys = {\":##\": \"00sick00\", \":-##\": \"00sick00\", \"0;^)\": \"00angel00\", \"0:)\": \"00angel00\", \"0:‑)\": \"00angel00\",\n \"0:3\": \"00angel00\", \"0:‑3\": \"00angel00\", \"O:)\": \"00angel00\", \"O:‑)\": \"00angel00\", \":&\": \"00sealed00\",\n \":‑&\": \"00sealed00\",\n \":#\": \"00sealed00\", \":‑#\": \"00sealed00\", \":X\": \"00sealed00\", \":‑X\": \"00sealed00\", \"<\\\\3\": \"00broken00\",\n \";)\": \"00evil00\", \"3:)\": \"00evil00\", \"3:‑)\": \"00evil00\",\n \"}:)\": \"00evil00\", \"}:‑)\": \"00evil00\", \">:)\": \"00evil00\", \">:‑)\": \"00evil00\", \":|\": \"00meh00\",\n \":‑|\": \"00meh00\", \":S\": \"00skeptical00\", \"=L\": \"00skeptical00\", \":L\": \"00skeptical00\",\n \"=\\\\\": \"00skeptical00\",\n \"=/\": \"00skeptical00\", \":\\\\\": \"00skeptical00\", \">:/\": \"00skeptical00\", \">:\\\\\": \"00skeptical00\",\n \":‑.\": \"00skeptical00\", \">:P\": \"00tongue00\", \"=p\": \"00tongue00\", \"d:\": \"00tongue00\", \":b\": \"00tongue00\",\n \":‑b\": \"00tongue00\", \":þ\": \"00tongue00\", \":‑þ\": \"00tongue00\", \":Þ\": \"00tongue00\", \":‑Þ\": \"00tongue00\",\n \":p\": \"00tongue00\", \":‑p\": \"00tongue00\", \"xp\": \"00tongue00\", \"x‑p\": \"00tongue00\", \"XP\": \"00tongue00\",\n \"X‑P\": \"00tongue00\", \":P\": \"00tongue00\", \":‑P\": \"00tongue00\", \":/\": \"00skeptical00\", \":‑/\": \"00skeptical00\",\n \";D\": \"00wink00\", \":‑,\": \"00wink00\", \";^)\": \"00wink00\", \";]\": \"00wink00\", \";‑]\": \"00wink00\",\n \"*)\": \"00wink00\", \"*-)\": \"00wink00\", \";)\": \"00wink00\", \";‑)\": \"00wink00\", \">:O\": \"00surprise00\",\n \"8‑0\": \"00surprise00\", \":-0\": \"00surprise00\", \":o\": \"00surprise00\", \":‑o\": \"00surprise00\",\n \":O\": \"00surprise00\", \":‑O\": \"00surprise00\", \"DX\": \"00horror00\", \"D=\": \"00horror00\", \"D;\": \"00horror00\",\n \"D8\": \"00horror00\", \"D:\": \"00horror00\", \"D:<\": \"00horror00\", \"D‑':\": \"00horror00\", \":')\": \"00tear_smile00\",\n \":'‑)\": \"00tear_smile00\", \":'(\": \"00tear00\", \":'‑(\": \"00tear00\", \">:(\": \"00frown00\", \":@\": \"00frown00\",\n \":{\": \"00frown00\", \">:[\": \"00frown00\", \":-||\": \"00frown00\", \":[\": \"00frown00\", \":‑[\": \"00frown00\",\n \":<\": \"00frown00\", \":‑<\": \"00frown00\", \":c\": \"00frown00\", \":‑c\": \"00frown00\", \":(\": \"00frown00\",\n \":‑(\": \"00frown00\", \"B^D\": \"00laugh00\", \"=3\": \"00laugh00\", \"=D\": \"00laugh00\", \"XD\": \"00laugh00\",\n \"X‑D\": \"00laugh00\", \"xD\": \"00laugh00\", \"x‑D\": \"00laugh00\", \"8D\": \"00laugh00\", \"8‑D\": \"00laugh00\",\n \":D\": \"00laugh00\", \":‑D\": \"00laugh00\", \":-))\": \"00smile00\", \"=)\": \"00smile00\", \"=]\": \"00smile00\",\n \":^)\": \"00smile00\", \":c)\": \"00smile00\", \":o)\": \"00smile00\", \":}\": \"00smile00\", \":-}\": \"00smile00\",\n \"8)\": \"00smile00\", \"8-)\": \"00smile00\", \":>\": \"00smile00\", \":->\": \"00smile00\", \":3\": \"00smile00\",\n \":-3\": \"00smile00\", \":]\": \"00smile00\", \":-]\": \"00smile00\", \":)\": \"00smile00\", \":‑)\": \"00smile00\"}\n\n\ndef multiple_replace(text, wordDict):\n for key in wordDict:\n text = text.replace(' ' + key, ' ' + wordDict[key]) # assumes that people will put a space before smileys\n return text\n\n\nprint(\"Output files created, cleaning files...\")\nprint(\"Cleaning and splitting training/testing datasets...\")\n\n# cleans and splits dataset into train/test, so not quite applicable\ni = 1\nfor review in train['text']:\n ind = train[train['text'] == review].index.values.astype(int) # gets df index\n label = train.iat[ind[0], 1]\n # remove this tag manually because BS doesn't like to add the space\n review = review.replace('

', ' ')\n # replace smileys with codes\n smiley_replace_text = multiple_replace(review, smileys)\n # clean HTML\n no_html_text = BeautifulSoup(smiley_replace_text, \"html5lib\").get_text()\n # lower case strings and remove punctuation\n translator = str.maketrans(' ', ' ', string.punctuation)\n cleanText = no_html_text.lower().translate(translator)\n cleanText = cleanText.replace(' ', ' ')\n\n # sort reviews into train/test and pos/neg\n if label == 0 and i <= threshold:\n train_neg.write(cleanText + '\\n')\n elif label == 1 and i <= threshold:\n train_pos.write(cleanText + '\\n')\n elif label == 0 and i > threshold:\n test_neg.write(cleanText + '\\n')\n elif label == 1 and i > threshold:\n test_pos.write(cleanText + '\\n')\n i += 1\n\nprint(\"Finished cleaning and splitting! Total lines cleaned: \", i)\nprint(\"Cleaning unsupervised dataset...\")\n\nfor review in unsup['text']:\n # remove this tag manually because BS doesn't like to add the space\n review = review.replace('

', ' ')\n # replace smileys with codes\n smiley_replace_text = multiple_replace(review, smileys)\n # clean HTML\n no_html_text = BeautifulSoup(smiley_replace_text, \"html5lib\").get_text()\n # lower case strings and remove punctuation\n translator = str.maketrans(' ', ' ', string.punctuation)\n cleanText = no_html_text.lower().translate(translator)\n unsup_txt.write(cleanText + '\\n')\n\nprint(\"Finished cleaning!\")\n\ntrain_pos.close()\ntrain_neg.close()\ntest_pos.close()\ntest_neg.close()\nunsup_txt.close()\n","sub_path":"src/cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":5759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"625819338","text":"import os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')\n\nimport django\ndjango.setup()\n\n\nimport random\nfrom first_app.models import AccessRecord,Topic,Webpage\n\nfrom faker import Faker\nfake= Faker()\ntopics= ['Search','Social','Marketpalce','news','games']\n\ndef add_topics():\n t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]\n t.save()\n return t\n\n\ndef populate(N=5):\n\n for entry in range(N):\n top = add_topics()\n\n #creare the fake data for that entry\n fake_url = fake.url()\n fake_date=fake.date()\n fake_name = fake.company()\n \n #create the webpage entry\n webpg= Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0]\n\n #create a fake access record for that webpage\n acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0]\n\n\nif __name__ == '__main__':\n print(\"populating...\")\n populate(20)\n print(\"population complete.\")","sub_path":"populate_first_app.py","file_name":"populate_first_app.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"560628914","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 ('core', '0258_auto_20170711_1131'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='workshopresources',\n old_name='for_date',\n new_name='on_date',\n ),\n migrations.AlterField(\n model_name='workshopresources',\n name='type_of_record',\n field=models.IntegerField(default=1, choices=[(1, b'Daily'), (2, b'Expected')]),\n ),\n ]\n","sub_path":"bumper2/core/old_migrations/0259_auto_20170711_1154.py","file_name":"0259_auto_20170711_1154.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"292811655","text":"import os\nimport sys\nimport time\nimport pathlib\nimport pprint\nimport json\nimport glob\nfrom tqdm import *\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys \nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait as wait\nfrom selenium.webdriver.common.action_chains import ActionChains\n\npp = pprint.PrettyPrinter(indent=4)\n\nchrome_options = Options()\n# chrome_options.add_argument(\"--headless\")\ndriver = webdriver.Chrome(executable_path=os.path.abspath(\"../chromedriver\"), chrome_options=chrome_options)\n\nglobal_previously_saved = None\nglobal_previous_list = None\n\n\ncontent_id = \"PageContentContainer\"\n\nmanual_blacklist = []\n\n\n# # Finds highest level 1 folder it's started\n# highest = (-1, '')\n# for dirpath, dirs, files in os.walk(\"./content\"):\n# if(dirpath != \"./content\"):\n# curr_num = int(dirpath.split(\"./content/\")[-1].split(' ')[0])\n# if(curr_num > highest[0]):\n# highest = (curr_num, '/'.join(dirpath.split('/')[:4]))\n# # if highest is still -1, then it hasn't started ANY level 1 folders\n# blacklist = None\n# lv1_root = highest[1]\n# if(highest[0] != -1):\n# # Adds level 1 folders < lv1_root that it's done to blacklist\n# raw_blacklist = next(os.walk('./content'))[1]\n# blacklist = []\n# for i, lv1 in enumerate(raw_blacklist):\n# if(int(lv1.split(' ')[0]) < highest[0]):\n# blacklist.append(\"./content/\" + lv1)\n\n# try:\n# # Finds the highest level 2 folder it's started\n# highest = (-1, '')\n# for dirpath, dirs, files in os.walk(lv1_root):\n# if(dirpath != lv1_root):\n# curr_num = int(dirpath.split(lv1_root + '/')[-1].split(' ')[0])\n# if(curr_num > highest[0]):\n# highest = (curr_num, '/'.join(dirpath.split('/')[:5]))\n# # Adds all lower lv2 folders to blacklist\n# for dirpath, dirs, files in os.walk(lv1_root):\n# if(dirpath != lv1_root):\n# curr_num = int(dirpath.split(lv1_root + '/')[-1].split(' ')[0])\n# if(curr_num < highest[0]):\n# to_add = '/'.join(dirpath.split('/')[:5])\n# if(to_add not in blacklist):\n# blacklist.append(to_add)\n# except:\n# pass\n\ndef gen_blacklist():\n blacklist = []\n for filename in glob.iglob('./content/**/*.html', recursive=True):\n blacklist.append(filename)\n\n\n if blacklist:\n blacklist = blacklist + manual_blacklist\n else:\n blacklist = manual_blacklist\n\n if blacklist:\n print(\"---------------\")\n print(\" Blacklist\")\n print(json.dumps(blacklist, indent=4, sort_keys=True))\n print(\"---------------\")\n\n return blacklist\n\ndef is_blacklisted(blacklist, curr_root):\n # If blacklist was successfully generated, checks if any item in it is in curr_root\n if any(substring in curr_root for substring in blacklist):\n return True\n else:\n return False\n\ndef wait_for_elem(id=None, css=None, xpath=None, root=None, prev_content=None, debug=False):\n if root and root.__class__.__name__ != \"WebElement\":\n print(\"WARNING: root must be WebElement, not \" + root.__class__.__name__)\n return\n\n driver_or_root = driver\n if root:\n driver_or_root = root\n content = None\n keep_checking = True\n while keep_checking:\n if debug:\n if id:\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()) + \" | id='\" + id + \"'\")\n elif css:\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()) + \" | css='\" + css + \"'\")\n elif xpath:\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()) + \" | xpath='\" + xpath + \"'\")\n if prev_content:\n # print(prev_content, end=\"\\n\\n\")\n pass\n\n try:\n # connect\n if id:\n content = driver_or_root.find_element_by_id(id)\n elif css:\n content = driver_or_root.find_element_by_css_selector(css)\n elif xpath:\n content = driver_or_root.find_element_by_xpath(xpath)\n except:\n pass\n\n if content is None:\n keep_checking = True\n else:\n if prev_content is not None:\n try:\n # error_log = content.get_attribute(\"outerHTML\").replace(content.get_attribute(\"outerHTML\"), \"\")\n # if error_log:\n # print(content.get_attribute(\"outerHTML\").replace(content.get_attribute(\"outerHTML\"), \"\"))\n # else:\n # if id:\n # print(\"id = \" + id)\n # elif css:\n # print(\"css = \" + css)\n # elif xpath:\n # print(\"xpath = \" + xpath)\n if content.get_attribute(\"outerHTML\") == prev_content:\n keep_checking = True\n else:\n keep_checking = False\n except:\n content = None\n keep_checking = True\n else:\n keep_checking = False\n\n return content\n\ndef get_sections(debug=False):\n sections_container = wait_for_elem(id=\"NavPaneSectionList\")\n wait_for_elem(root=sections_container, css=\"div.navItem\", debug=debug)\n sections_html = sections_container.find_element_by_xpath(\"//div[@class='sectionList']\").find_elements_by_xpath(\"*\")\n\n sections = []\n i = 0\n for section in sections_html:\n section_name = str(i) + ' ' + section.find_element_by_css_selector(\"div.navItem\").get_attribute(\"data-tip\")\n sections.append({\"name\": section_name, \"button\": section})\n i += 1\n return sections\n\ndef get_pages(debug=False):\n pages_container = wait_for_elem(id=\"PageList\", debug=debug)\n pages_html = pages_container.find_element_by_css_selector(\"div.ms-SelectionZone\").find_element_by_css_selector(\"div.pagesContainer\").find_elements_by_xpath(\"*\")\n return pages_html\n\ndef scrape(blacklist):\n # Loads page and focuses correct iframe\n driver.get(\"https://onedrive.live.com/view.aspx?ref=button&Bsrc=SMIT&resid=708DB7CA3B6187FE!1939&cid=708db7ca3b6187fe&app=OneNote&authkey=!Aqsda1BkgAhQO1Y\")\n wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(\"sdx_ow_iframe\"))\n\n # waits for content to load\n content = wait_for_elem(id=content_id)\n\n # Gathering menus to click\n sections = get_sections()\n\n # Gathering pages to save\n prev_page_list = None\n prev_page = None\n for i in range(0, len(sections)):\n sections = get_sections()\n section = sections[i]\n\n curr_section_path = \"./content/\"+' '.join(section[\"name\"].split('/'))\n if is_blacklisted(blacklist, curr_section_path):\n print(\"Error: '\" + curr_section_path + \"' already finished, skipping.\")\n continue\n\n # Accesses page list in section\n section[\"button\"].click()\n # Waits for page list to load\n time.sleep(3)\n pages_html = get_pages()\n\n pages = []\n prev_page = None\n for j in range(0, len(pages_html)):\n print(j)\n pages_html = get_pages()\n page = pages_html[j]\n page_name = str(j) + ' ' + page.find_element_by_css_selector(\"div.pageListItem\").find_element_by_css_selector(\"div.navItem\").get_attribute(\"data-tip\")\n pages.append({\"name\": page_name, \"button\": page})\n\n curr_page_path = \"./content/\"+section[\"name\"]+\"/\"+' '.join(page_name.split('/'))+\".html\"\n if is_blacklisted(blacklist, curr_page_path):\n print(\"Error: '\" + curr_page_path + \"' already finished, skipping.\")\n continue\n\n # Saves each page in the section\n actions = ActionChains(driver)\n actions.move_to_element(page).perform()\n page.click()\n\n time.sleep(3)\n curr_page = wait_for_elem(id=content_id, prev_content=prev_page)\n\n # Goes to move to all images to get them to load\n images = driver.find_elements_by_css_selector(\"img.WACImage\")\n for k in range(0, len(images)):\n images = driver.find_elements_by_css_selector(\"img.WACImage\")\n image = images[k]\n actions = ActionChains(driver)\n actions.move_to_element(image).perform()\n time.sleep(1)\n\n curr_page = driver.find_element_by_id(content_id)\n prev_page = curr_page.get_attribute(\"outerHTML\")\n\n # Stores page in file\n parent_root = curr_section_path + '/'\n pathlib.Path(parent_root).mkdir(parents=True, exist_ok=True)\n filename = os.path.join(parent_root, ' '.join(page_name.split('/'))+\".html\")\n if os.path.isfile(filename):\n print(\"Error: '\" + filename + \"' already exists, skipping.\")\n else:\n with open(filename, 'w') as fp:\n fp.write(prev_page)\n\n section[\"pages\"] = pages\n\n # pp.pprint(sections)\n\n return True\n\nif __name__ == \"__main__\":\n\n is_done = False\n while is_done != True:\n try:\n blacklist = gen_blacklist()\n is_done = scrape(blacklist)\n except Exception as ex:\n print('\\n' + time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()))\n print(ex)\n\n # blacklist = gen_blacklist()\n # is_done = scrape(blacklist)\n\n # driver.close()","sub_path":"mednotes/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":9761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243092401","text":"import unittest\nimport random\nfrom classes.ProbabilityDistributions import AbstractProbabilityDistribution\nfrom classes.ProbabilityDistributions import ProbabilityDistributions as pd\n\n\nclass TestProbabilityDistributions(unittest.TestCase):\n\n\n def test_probabilityDistributions(self):\n param_dict = {'UniformDistribution': {},\n 'ExponentialDistribution':{'lambda':1},\n 'GaussianDistribution':{'mu':0.4,'sigma':2},\n 'ExplinklossrateDistribution':{'lambda': 0.5}}\n for pd_subclass in AbstractProbabilityDistribution.__subclasses__():\n print(pd_subclass.__name__)\n\n self.assertTrue(issubclass(pd_subclass, AbstractProbabilityDistribution))\n self.assertTrue(isinstance(pd_subclass(param_dict[pd_subclass.__name__]), AbstractProbabilityDistribution),\n pd_subclass.__name__ + ' does not implement all functions of abstract class.')\n\n def test_uniform_distribution_value_correct(self):\n\n distribution = pd.UniformDistribution({})\n randomValue = distribution.generate_probability_distribution_value()\n\n for i in range(100):\n self.assertIsNotNone(randomValue)\n self.assertGreaterEqual(randomValue, 0)\n\n def test_gaussian_distribution_value_correct(self):\n mu = random.random()\n sigma = random.random()\n\n distribution = pd.GaussianDistribution({'mu':mu,'sigma':sigma})\n randomValue = distribution.generate_probability_distribution_value()\n\n\n for i in range(100):\n self.assertIsNotNone(randomValue)\n self.assertGreaterEqual(randomValue, 0)\n\n def test_exponential_distribution_value_correct(self):\n lambd = 1\n param_dict = {'lambda': lambd}\n\n distribution = pd.ExponentialDistribution(param_dict)\n randomValue = distribution.generate_probability_distribution_value()\n\n for i in range(100):\n self.assertIsNotNone(randomValue)\n self.assertGreaterEqual(randomValue, 0)\n\n def test_explinkloss_distribution_value_positive(self):\n lambd = 0.3\n param_dict = {'lambda': lambd}\n\n distribution = pd.ExplinklossrateDistribution(param_dict)\n randomValue = distribution.generate_probability_distribution_value({'link_error_rate':0.4})\n\n for i in range(100):\n self.assertIsNotNone(randomValue)\n self.assertGreaterEqual(randomValue, 0)\n\n def test_explinkloss_distribution_param_dict_negative(self):\n values = [0,1,{},[],'string']\n for val in values:\n param_dict = val\n\n self.assertRaises(ValueError, pd.ExplinklossrateDistribution, param_dict)\n\n def test_explinkloss_distribution_function_param_dict_negative(self):\n values = [0, 1, {}, [], 'string', None]\n param_dict = {'lambda': 0.2}\n\n distribution = pd.ExplinklossrateDistribution(param_dict)\n for val in values:\n function_param_dict = val\n\n self.assertRaises(ValueError, distribution.generate_probability_distribution_value, function_param_dict)\n\n\n","sub_path":"test/classes/testProbabilityDistributions.py","file_name":"testProbabilityDistributions.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"242187568","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport os\nimport boto3\nimport csv\nimport codecs\n\nimport typing as t\n\nfrom dataclasses import dataclass, field\nfrom hmalib import metrics\nfrom hmalib.common.logging import get_logger\n\nlogger = get_logger(__name__)\n\ns3_client = boto3.client(\"s3\")\nHashRowT = t.Tuple[str, t.Dict[str, t.Any]]\n\n\n@dataclass\nclass S3ThreatDataConfig:\n\n SOURCE_STR = \"te\"\n\n threat_exchange_data_bucket_name: str\n threat_exchange_data_folder: str\n threat_exchange_pdq_file_extension: str\n\n\n@dataclass\nclass ThreatExchangeS3Adapter:\n \"\"\"\n Adapter for reading ThreatExchange data stored in S3. Concrete implementations\n are for a specific indicator type such as PDQ\n\n Assumes CSV file format\n\n Should probably refactor and merge with ThreatUpdateS3Store for writes\n \"\"\"\n\n metrics_logger: metrics.lambda_with_datafiles\n S3FileT = t.Dict[str, t.Any]\n config: S3ThreatDataConfig\n last_modified: t.Dict[str, str] = field(default_factory=dict)\n\n def load_data(self) -> t.Dict[str, t.List[HashRowT]]:\n \"\"\"\n loads all data from all files in TE that are of the concrete implementations indicator type\n\n returns a mapping from file name to list of rows\n \"\"\"\n logger.info(\"Retreiving %s Data from S3\", self.file_type_str_name)\n with metrics.timer(self.metrics_logger.download_datafiles):\n # S3 doesnt have a built in concept of folders but the AWS UI\n # implements folder-like functionality using prefixes. We follow\n # this same convension here using folder name in a prefix search\n s3_bucket_files = s3_client.list_objects_v2(\n Bucket=self.config.threat_exchange_data_bucket_name,\n Prefix=self.config.threat_exchange_data_folder,\n )[\"Contents\"]\n logger.info(\"Found %d Files\", len(s3_bucket_files))\n\n typed_data_files = {\n file[\"Key\"]: self._get_file(file[\"Key\"])\n for file in s3_bucket_files\n if file[\"Key\"].endswith(self.indicator_type_file_extension)\n }\n logger.info(\n \"Found %d %s Files\", len(typed_data_files), self.file_type_str_name\n )\n\n with metrics.timer(self.metrics_logger.parse_datafiles):\n logger.info(\"Parsing %s Hash files\", self.file_type_str_name)\n typed_data = {\n file_name: self._parse_file(**typed_data_file)\n for file_name, typed_data_file in typed_data_files.items()\n }\n return typed_data\n\n @property\n def indicator_type_file_extension(self):\n \"\"\"\n What is the extension for files of this indicator type\n\n eg. pdq.te indicates PDQ files\n \"\"\"\n raise NotImplementedError()\n\n @property\n def file_type_str_name(self):\n \"\"\"\n What types of files does the concrete implementation correspond to\n\n for logging only\n \"\"\"\n raise NotImplementedError()\n\n @property\n def indicator_type_file_columns(self):\n \"\"\"\n What are the csv columns when this type of data is stored in S3\n \"\"\"\n raise NotImplementedError()\n\n def _get_file(self, file_name: str) -> t.Dict[str, t.Any]:\n return {\n \"file_name\": file_name,\n \"data_file\": s3_client.get_object(\n Bucket=self.config.threat_exchange_data_bucket_name, Key=file_name\n ),\n }\n\n def _parse_file(self, file_name: str, data_file: S3FileT) -> t.List[HashRowT]:\n data_reader = csv.DictReader(\n codecs.getreader(\"utf-8\")(data_file[\"Body\"]),\n fieldnames=self.indicator_type_file_columns,\n )\n self.last_modified[file_name] = data_file[\"LastModified\"].isoformat()\n privacy_group = file_name.split(\"/\")[-1].split(\".\")[0]\n return [\n (\n row[\"hash\"],\n # Also add hash to metadata for easy look up on match\n {\n \"id\": int(row[\"indicator_id\"]),\n \"hash\": row[\"hash\"],\n \"source\": self.config.SOURCE_STR, # default for now to make downstream easier to generalize\n \"privacy_groups\": set(\n [privacy_group]\n ), # read privacy group from key\n \"tags\": {privacy_group: row[\"tags\"].split(\" \")}\n if row[\"tags\"]\n else {}, # note: these are the labels assigned by pytx in descriptor.py (NOT a 1-1 with tags on TE)\n },\n )\n for row in data_reader\n ]\n\n\nclass ThreatExchangeS3PDQAdapter(ThreatExchangeS3Adapter):\n \"\"\"\n Adapter for reading ThreatExchange PDQ data stored in CSV files S3\n \"\"\"\n\n @property\n def indicator_type_file_extension(self):\n return self.config.threat_exchange_pdq_file_extension\n\n @property\n def indicator_type_file_columns(self):\n return [\"hash\", \"indicator_id\", \"descriptor_id\", \"timestamp\", \"tags\"]\n\n @property\n def file_type_str_name(self):\n return \"PDQ\"\n","sub_path":"hasher-matcher-actioner/hmalib/common/s3_adapters.py","file_name":"s3_adapters.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"110929951","text":"# -*- coding: utf-8 -*-\n\n# Imports\n# ------------------------------\nimport os\nimport sys\nimport time\nimport re\n\n# Class\n# ------------------------------\nclass BoolQueryOrSpliter:\n \"\"\"\n Takes a boolean query given by the user. Splits it in several boolean queries without OR statements. \n @args:\n boolQueries : list[str]\n\n \"\"\"\n def __init__(self, stringQuery):\n \"\"\"\n takes a user input, split it in several queries wo OR statement.\n \"\"\"\n \n self.boolQueries = []\n\n listBuffer = re.findall(r'\\([a-zA-Z0-9\\s]+\\)',stringQuery)\n \n if listBuffer == []:\n listBuffer = re.findall(r'[a-zA-Z0-9\\s]+',stringQuery)\n\n for elmt in listBuffer:\n if elmt.startswith('('):\n self.boolQueries.append(elmt[1:-1])\n else:\n self.boolQueries.append(elmt)\n\n def __str__(self):\n \"\"\"\n Standard method allowing to print the boolean query inputed by the user\n \"\"\"\n\n descript = 'The various queries are : \\n'\n\n for elmt in self.boolQueries:\n descript += str(elmt) + '\\n'\n\n return str(descript)\n\n\n# Testing\n# ------------------------------\nif __name__ == \"__main__\":\n inputVar = input('Quelle est votre recherche ?')\n testQ = BoolQueryOrSpliter(inputVar)\n print(testQ)\n\n os.system(\"pause\")","sub_path":"boolQueryOrSpliter.py","file_name":"boolQueryOrSpliter.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"251235620","text":"\"\"\"\nBoolean geometry utilities.\n\n\"\"\"\n\nfrom __future__ import absolute_import\n#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.\nimport __init__\n\nimport os\nimport sys\nimport traceback\n\n\n__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'\n__credits__ = 'Art of Illusion '\n__date__ = '$Date: 2008/02/05 $'\n__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'\n\n\nglobalTemporarySettingsPath = os.path.join(os.path.expanduser('~'), '.skeinforge')\n\n\ndef addToNamePathDictionary(directoryPath, namePathDictionary):\n\t'Add to the name path dictionary.'\n\tpluginFileNames = getPluginFileNamesFromDirectoryPath(directoryPath)\n\tfor pluginFileName in pluginFileNames:\n\t\tnamePathDictionary[pluginFileName.replace('_', '')] = os.path.join(directoryPath, pluginFileName)\n\ndef getAbsoluteFolderPath(filePath, folderName=''):\n\t'Get the absolute folder path.'\n\tabsoluteFolderPath = os.path.dirname(os.path.abspath(filePath))\n\tif folderName == '':\n\t\treturn absoluteFolderPath\n\treturn os.path.join(absoluteFolderPath, folderName)\n\ndef getAbsoluteFrozenFolderPath(filePath, folderName=''):\n\t'Get the absolute frozen folder path.'\n\tif hasattr(sys, 'frozen'):\n\t\tif '.py' in filePath:\n\t\t\tfilePath = ''.join(filePath.rpartition('\\\\')[: 2])\n\t\tfilePath = os.path.join(filePath, 'skeinforge_application')\n\treturn getAbsoluteFolderPath(filePath, folderName)\n\ndef getDocumentationPath(subName=''):\n\t'Get the documentation file path.'\n\treturn getJoinedPath(getFabmetheusPath('documentation'), subName)\n\ndef getElementsPath(subName=''):\n\t'Get the evaluate_elements directory path.'\n\treturn getJoinedPath(getGeometryUtilitiesPath('evaluate_elements'), subName)\n\ndef getEndsWithList(word, wordEndings):\n\t'Determine if the word ends with a list.'\n\tfor wordEnding in wordEndings:\n\t\tif word.endswith(wordEnding):\n\t\t\treturn True\n\treturn False\n\ndef getFabmetheusPath(subName=''):\n\t'Get the fabmetheus directory path.'\n\tfabmetheusFile = None\n\tif hasattr(sys, 'frozen'):\n\t\tfabmetheusFile = unicode(sys.executable, sys.getfilesystemencoding())\n\telse:\n\t\tfabmetheusFile = os.path.dirname(os.path.abspath(__file__))\n\treturn getJoinedPath(os.path.dirname(fabmetheusFile), subName)\n\ndef getFabmetheusUtilitiesPath(subName=''):\n\t'Get the fabmetheus utilities directory path.'\n\treturn getJoinedPath(getFabmetheusPath('fabmetheus_utilities'), subName)\n\ndef getFileNamesByFilePaths(pluginFilePaths):\n\t'Get the file names of the plugins by the file paths.'\n\tfileNames = []\n\tfor pluginFilePath in pluginFilePaths:\n\t\tpluginBasename = os.path.basename(pluginFilePath)\n\t\tpluginBasename = getUntilDot(pluginBasename)\n\t\tfileNames.append(pluginBasename)\n\treturn fileNames\n\ndef getFilePaths(fileInDirectory=''):\n\t'Get the file paths in the directory of the file in directory.'\n\tdirectoryName = os.getcwd()\n\tif fileInDirectory != '':\n\t\tdirectoryName = os.path.dirname(fileInDirectory)\n\treturn getFilePathsByDirectory(directoryName)\n\ndef getFilePathsByDirectory(directoryName):\n\t'Get the file paths in the directory of the file in directory.'\n\tabsoluteDirectoryPath = os.path.abspath(directoryName)\n\tdirectory = os.listdir(directoryName)\n\tfilePaths = []\n\tfor fileName in directory:\n\t\tfilePaths.append(os.path.join(absoluteDirectoryPath, fileName))\n\treturn filePaths\n\ndef getFilePathsRecursively(fileInDirectory=''):\n\t'Get the file paths in the directory of the file in directory.'\n\tfilePaths = getFilePaths(fileInDirectory)\n\tfilePathsRecursively = filePaths[:]\n\tfor filePath in filePaths:\n\t\tif os.path.isdir(filePath):\n\t\t\tdirectory = os.listdir(filePath)\n\t\t\tif len(directory) > 0:\n\t\t\t\tfilePathsRecursively += getFilePathsRecursively(os.path.join(filePath, directory[0]))\n\treturn filePathsRecursively\n\ndef getFilePathWithUnderscoredBasename(fileName, suffix):\n\t'Get the file path with all spaces in the basename replaced with underscores.'\n\tsuffixFileName = getUntilDot(fileName) + suffix\n\tsuffixDirectoryName = os.path.dirname(suffixFileName)\n\tsuffixReplacedBaseName = os.path.basename(suffixFileName).replace(' ', '_')\n\treturn os.path.join(suffixDirectoryName, suffixReplacedBaseName)\n\ndef getFileText(fileName, printWarning=True, readMode='r'):\n\t'Get the entire text of a file.'\n\ttry:\n\t\tfile = open(fileName, readMode)\n\t\tfileText = file.read()\n\t\tfile.close()\n\t\treturn fileText\n\texcept IOError:\n\t\tif printWarning:\n\t\t\tprint('The file ' + fileName + ' does not exist.')\n\treturn ''\n\ndef getFileTextInFileDirectory(fileInDirectory, fileName, readMode='r'):\n\t'Get the entire text of a file in the directory of the file in directory.'\n\tabsoluteFilePathInFileDirectory = os.path.join(os.path.dirname(fileInDirectory), fileName)\n\treturn getFileText(absoluteFilePathInFileDirectory, True, readMode)\n\ndef getFilesWithFileTypesWithoutWords(fileTypes, words = [], fileInDirectory=''):\n\t'Get files which have a given file type, but with do not contain a word in a list.'\n\tfilesWithFileTypes = []\n\tfor filePath in getFilePaths(fileInDirectory):\n\t\tfor fileType in fileTypes:\n\t\t\tif isFileWithFileTypeWithoutWords(fileType, filePath, words):\n\t\t\t\tfilesWithFileTypes.append(filePath)\n\tfilesWithFileTypes.sort()\n\treturn filesWithFileTypes\n\ndef getFilesWithFileTypesWithoutWordsRecursively(fileTypes, words = [], fileInDirectory=''):\n\t'Get files recursively which have a given file type, but with do not contain a word in a list.'\n\tfilesWithFileTypesRecursively = []\n\tfor filePath in getFilePathsRecursively(fileInDirectory):\n\t\tfor fileType in fileTypes:\n\t\t\tif isFileWithFileTypeWithoutWords(fileType, filePath, words):\n\t\t\t\tfilesWithFileTypesRecursively.append(filePath)\n\tfilesWithFileTypesRecursively.sort()\n\treturn filesWithFileTypesRecursively\n\ndef getFilesWithFileTypeWithoutWords(fileType, words = [], fileInDirectory=''):\n\t'Get files which have a given file type, but with do not contain a word in a list.'\n\tfilesWithFileType = []\n\tfor filePath in getFilePaths(fileInDirectory):\n\t\tif isFileWithFileTypeWithoutWords(fileType, filePath, words):\n\t\t\tfilesWithFileType.append(filePath)\n\tfilesWithFileType.sort()\n\treturn filesWithFileType\n\ndef getFundamentalsPath(subName=''):\n\t'Get the evaluate_fundamentals directory path.'\n\treturn getJoinedPath(getGeometryUtilitiesPath('evaluate_fundamentals'), subName)\n\ndef getGeometryDictionary(folderName):\n\t'Get to the geometry name path dictionary.'\n\tgeometryDictionary={}\n\tgeometryDirectory = getGeometryPath()\n\taddToNamePathDictionary(os.path.join(geometryDirectory, folderName), geometryDictionary)\n\tgeometryPluginsDirectory = getFabmetheusUtilitiesPath('geometry_plugins')\n\taddToNamePathDictionary(os.path.join(geometryPluginsDirectory, folderName), geometryDictionary)\n\treturn geometryDictionary\n\ndef getGeometryPath(subName=''):\n\t'Get the geometry directory path.'\n\treturn getJoinedPath(getFabmetheusUtilitiesPath('geometry'), subName)\n\ndef getGeometryToolsPath(subName=''):\n\t'Get the geometry tools directory path.'\n\treturn getJoinedPath(getGeometryPath('geometry_tools'), subName)\n\ndef getGeometryUtilitiesPath(subName=''):\n\t'Get the geometry_utilities directory path.'\n\treturn getJoinedPath(getGeometryPath('geometry_utilities'), subName)\n\ndef getJoinedPath(path, subName=''):\n\t'Get the joined file path.'\n\tif subName == '':\n\t\treturn path\n\treturn os.path.join(path, subName)\n\ndef getModuleWithDirectoryPath(directoryPath, fileName):\n\t'Get the module from the fileName and folder name.'\n\tif fileName == '':\n\t\tprint('The file name in getModule in archive was empty.')\n\t\treturn None\n\toriginalSystemPath = sys.path[:]\n\ttry:\n\t\tsys.path.insert(0, directoryPath)\n\t\tfolderPluginsModule = __import__(fileName)\n\t\tsys.path = originalSystemPath\n\t\treturn folderPluginsModule\n\texcept:\n\t\tsys.path = originalSystemPath\n\t\tprint('')\n\t\tprint('Exception traceback in getModuleWithDirectoryPath in archive:')\n\t\ttraceback.print_exc(file=sys.stdout)\n\t\tprint('')\n\t\tprint('That error means; could not import a module with the fileName ' + fileName)\n\t\tprint('and an absolute directory name of ' + directoryPath)\n\t\tprint('')\n\treturn None\n\ndef getModuleWithPath(path):\n\t'Get the module from the path.'\n\treturn getModuleWithDirectoryPath(os.path.dirname(path), os.path.basename(path))\n\ndef getPluginFileNamesFromDirectoryPath(directoryPath):\n\t'Get the file names of the python plugins in the directory path.'\n\tfileInDirectory = os.path.join(directoryPath, '__init__.py')\n\treturn getFileNamesByFilePaths(getPythonFileNamesExceptInit(fileInDirectory))\n\ndef getProfilesPath(subName=''):\n\t'Get the profiles directory path, which is the settings directory joined with profiles.'\n\treturn getJoinedPath(getSettingsPath('profiles'), subName)\n\ndef getPythonDirectoryNames(directoryName):\n\t'Get the python directories.'\n\tpythonDirectoryNames = []\n\tdirectory = os.listdir(directoryName)\n\tfor fileName in directory:\n\t\tsubdirectoryName = os.path.join(directoryName, fileName)\n\t\tif os.path.isdir(subdirectoryName):\n\t\t\tif os.path.isfile(os.path.join(subdirectoryName, '__init__.py')):\n\t\t\t\tpythonDirectoryNames.append(subdirectoryName)\n\treturn pythonDirectoryNames\n\ndef getPythonDirectoryNamesRecursively(directoryName=''):\n\t'Get the python directories recursively.'\n\trecursivePythonDirectoryNames = []\n\tif directoryName == '':\n\t\tdirectoryName = os.getcwd()\n\tif os.path.isfile(os.path.join(directoryName, '__init__.py')):\n\t\trecursivePythonDirectoryNames.append(directoryName)\n\t\tpythonDirectoryNames = getPythonDirectoryNames(directoryName)\n\t\tfor pythonDirectoryName in pythonDirectoryNames:\n\t\t\trecursivePythonDirectoryNames += getPythonDirectoryNamesRecursively(pythonDirectoryName)\n\telse:\n\t\treturn []\n\treturn recursivePythonDirectoryNames\n\ndef getPythonFileNamesExceptInit(fileInDirectory=''):\n\t'Get the python fileNames of the directory which the fileInDirectory is in, except for the __init__.py file.'\n\tpythonFileNamesExceptInit = getFilesWithFileTypeWithoutWords('py', ['__init__.py'], fileInDirectory)\n\tpythonFileNamesExceptInit.sort()\n\treturn pythonFileNamesExceptInit\n\ndef getPythonFileNamesExceptInitRecursively(directoryName=''):\n\t'Get the python fileNames of the directory recursively, except for the __init__.py files.'\n\tpythonDirectoryNames = getPythonDirectoryNamesRecursively(directoryName)\n\tpythonFileNamesExceptInitRecursively = []\n\tfor pythonDirectoryName in pythonDirectoryNames:\n\t\tpythonFileNamesExceptInitRecursively += getPythonFileNamesExceptInit(os.path.join(pythonDirectoryName, '__init__.py'))\n\tpythonFileNamesExceptInitRecursively.sort()\n\treturn pythonFileNamesExceptInitRecursively\n\ndef getSettingsPath(subName=''):\n\t'Get the settings directory path, which is the home directory joined with .skeinforge.'\n\tglobal globalTemporarySettingsPath\n\treturn getJoinedPath(globalTemporarySettingsPath, subName)\n\ndef getSkeinforgePath(subName=''):\n\t'Get the skeinforge directory path.'\n\treturn getJoinedPath(getFabmetheusPath('skeinforge_application'), subName)\n\ndef getSkeinforgePluginsPath(subName=''):\n\t'Get the skeinforge plugins directory path.'\n\treturn getJoinedPath(getSkeinforgePath('skeinforge_plugins'), subName)\n\ndef getSummarizedFileName(fileName):\n\t'Get the fileName basename if the file is in the current working directory, otherwise return the original full name.'\n\tif os.getcwd() == os.path.dirname(fileName):\n\t\treturn os.path.basename(fileName)\n\treturn fileName\n\ndef getTemplatesPath(subName=''):\n\t'Get the templates directory path.'\n\treturn getJoinedPath(getFabmetheusUtilitiesPath('templates'), subName)\n\ndef getTextIfEmpty(fileName, text):\n\t'Get the text from a file if it the text is empty.'\n\tif text != '':\n\t\treturn text\n\treturn getFileText(fileName)\n\ndef getTextLines(text):\n\t'Get the all the lines of text of a text.'\n\ttextLines = text.replace('\\r', '\\n').replace('\\n\\n', '\\n').split('\\n')\n\tif len(textLines) == 1:\n\t\tif textLines[0] == '':\n\t\t\treturn []\n\treturn textLines\n\ndef getUntilDot(text):\n\t'Get the text until the last dot, if any.'\n\tdotIndex = text.rfind('.')\n\tif dotIndex < 0:\n\t\treturn text\n\treturn text[: dotIndex]\n\ndef getVersionFileName():\n\t'Get the file name of the version date.getFabmetheusUtilitiesPath(subName='')'\n\treturn getFabmetheusUtilitiesPath('version.txt')\n\ndef isFileWithFileTypeWithoutWords(fileType, fileName, words):\n\t'Determine if file has a given file type, but with does not contain a word in a list.'\n\tfileName = os.path.basename(fileName)\n\tfileTypeDot = '.' + fileType\n\tif not fileName.endswith(fileTypeDot):\n\t\treturn False\n\tfor word in words:\n\t\tif fileName.find(word) >= 0:\n\t\t\treturn False\n\treturn True\n\ndef makeDirectory(directory):\n\t'Make a directory if it does not already exist.'\n\tif os.path.isdir(directory):\n\t\treturn\n\ttry:\n\t\tprint('The following directory was made:')\n\t\tprint(os.path.abspath(directory))\n\t\tos.makedirs(directory)\n\texcept OSError:\n\t\tprint('Skeinforge can not make the directory %s so give it read/write permission for that directory and the containing directory.' % directory)\n\ndef removeBackupFilesByType(fileType):\n\t'Remove backup files by type.'\n\tbackupFilePaths = getFilesWithFileTypesWithoutWordsRecursively([fileType + '~'])\n\tfor backupFilePath in backupFilePaths:\n\t\tos.remove(backupFilePath)\n\ndef removeBackupFilesByTypes(fileTypes):\n\t'Remove backup files by types.'\n\tfor fileType in fileTypes:\n\t\tremoveBackupFilesByType(fileType)\n\ndef writeFileMessageEnd(end, fileName, fileText, message):\n\t'Write to a fileName with a suffix and print a message.'\n\tsuffixFileName = getUntilDot(fileName) + end\n\twriteFileText(suffixFileName, fileText)\n\tprint( message + getSummarizedFileName(suffixFileName) )\n\ndef writeFileText(fileName, fileText, writeMode='w+'):\n\t'Write a text to a file.'\n\ttry:\n\t\tfile = open(fileName, writeMode)\n\t\tfile.write(fileText)\n\t\tfile.close()\n\texcept IOError:\n\t\tprint('The file ' + fileName + ' can not be written to.')\n","sub_path":"fabmetheus_utilities/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":13734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"615916394","text":"#!/usr/bin/env python\n\nclass Solution:\n # @param {integer} n\n # @return {string}\n def countAndSay(self, n):\n if n == 1:\n return '1'\n s = self.countAndSay(n-1)\n prev = s[0]\n i = 1\n count = 1\n new_s = ''\n if len(s) == 1:\n return '1' + s[0]\n while i < len(s):\n curr = s[i]\n if prev == curr:\n count += 1\n else:\n new_s += str(count) + prev\n count = 1\n if i == len(s) - 1:\n new_s += str(count) + curr\n prev = curr\n i += 1\n return new_s\n\ndef test():\n s = Solution()\n # print(s.countAndSay(5))\n print(s.countAndSay(20))\n print('=' * 20)\n assert '1' == s.countAndSay(1)\n assert '11' == s.countAndSay(2)\n assert '21' == s.countAndSay(3)\n assert '111221' == s.countAndSay(5)\n print('Test passed!')\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"solutions/count_and_say.py","file_name":"count_and_say.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"176223978","text":"#!/usr/bin/env python\n\"\"\" \"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2012 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nimport unittest\nimport logging\n\n# Third party modules.\nfrom pyxray.transition import Ka, La\n\n# Local modules.\nfrom pymontecarlo.testcase import TestCase\n\nfrom pymontecarlo.reconstruction.measurement import Measurement\n\nfrom pymontecarlo.input.options import Options\nfrom pymontecarlo.input.geometry import Substrate\nfrom pymontecarlo.input.detector import PhotonIntensityDetector\nfrom pymontecarlo.input.material import Material, pure\nfrom pymontecarlo.output.results import Results\nfrom pymontecarlo.output.result import PhotonIntensityResult, create_intensity_dict\n\n# Globals and constants variables.\n\nclass TestMeasurement(TestCase):\n\n def setUp(self):\n TestCase.setUp(self)\n\n baseops = Options()\n baseops.detectors['xray'] = PhotonIntensityDetector((0, 1), (0, 3))\n\n self.m = Measurement(baseops)\n self.m.add_kratio(Ka(29), 0.2470, 0.004)\n\n def tearDown(self):\n TestCase.tearDown(self)\n\n def testskeleton(self):\n self.assertTrue(True)\n\n def testadd_kratio(self):\n standard = Material('U90', {92: 0.9, 49: 0.1})\n self.m.add_kratio(La(92), 0.5, standard=standard)\n\n self.assertTrue(self.m.has_kratio(La(92)))\n self.assertAlmostEqual(0.5, self.m.get_kratios()[1], 4)\n\n self.m.add_kratio(Ka(13), 0.2, unc=0.125)\n\n self.assertTrue(self.m.has_kratio(Ka(13)))\n self.assertAlmostEqual(0.2, self.m.get_kratios()[0], 4)\n\n self.assertRaises(ValueError, self.m.add_kratio, La(92), 0.1)\n self.assertRaises(ValueError, self.m.add_kratio, Ka(14), -0.1)\n\n def testremove_kratio(self):\n self.m.remove_kratio(Ka(29))\n self.assertFalse(self.m.has_kratio(Ka(29)))\n self.assertEqual(0, len(self.m.get_kratios()))\n\n def testclear_kratios(self):\n self.m.clear_kratios()\n self.assertEqual(0, len(self.m.get_kratios()))\n\n def testhas_kratio(self):\n self.assertTrue(self.m.has_kratio(Ka(29)))\n self.assertFalse(self.m.has_kratio(La(29)))\n\n def testget_kratios(self):\n kratios = self.m.get_kratios()\n\n self.assertEqual(1, len(kratios))\n self.assertAlmostEqual(0.247, kratios[0], 4)\n\n def testfrom_xml(self):\n element = self.m.to_xml()\n m = Measurement.from_xml(element)\n\n kratios = m.get_kratios()\n self.assertEqual(1, len(kratios))\n self.assertAlmostEqual(0.247, kratios[0], 4)\n\n def testto_xml(self):\n element = self.m.to_xml()\n self.assertEqual(1, len(element.findall('kratio')))\n\n def testcreate_standard_options(self):\n list_options = self.m.create_standard_options('std')\n self.assertEqual(1, len(list_options))\n\n def testextract_standard_intensities(self):\n list_options = self.m.create_standard_options('std')\n stdoptions = list_options[0]\n\n intensities = create_intensity_dict(Ka(29), et=(8.0, 0.0))\n results = {'xray': PhotonIntensityResult(intensities)}\n stdresults = Results(stdoptions, results)\n\n dict_results = {'std+Cu Ka': stdresults}\n stdintensities = self.m.extract_standard_intensities('std', dict_results)\n\n self.assertEqual(1, len(stdintensities))\n self.assertAlmostEqual(8.0, stdintensities[0], 4)\n\n def testcreate_unknown_options(self):\n unkgeometry = Substrate(pure(49))\n options = self.m.create_unknown_options('meas', unkgeometry)\n self.assertEqual('meas', options.name)\n\n def testextract_unknown_intensities(self):\n unkgeometry = Substrate(pure(49))\n options = self.m.create_unknown_options('meas', unkgeometry)\n\n intensities = create_intensity_dict(Ka(29), et=(4.0, 0.0))\n results = Results(options, {'xray': PhotonIntensityResult(intensities)})\n\n unkintensities = self.m.extract_unknown_intensities(results)\n\n self.assertEqual(1, len(unkintensities))\n self.assertAlmostEqual(4.0, unkintensities[0], 4)\n\n\n\nif __name__ == '__main__': #pragma: no cover\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n\n","sub_path":"old/test_measurement.py","file_name":"test_measurement.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"544470602","text":"#############################################################################\n\"\"\"You have to fill these args.\n\n_base_(str): The path to your pretrain config file.\nfix_subnet (Union[dict,str]): The dict store the pruning structure or the\n json file including it.\ndivisor (int): The divisor the make the channel number divisible.\n\"\"\"\n\n_base_ = ['mmcls::resnet/resnet34_8xb32_in1k.py']\nun_prune = 1.0\nstage_ratio_1 = 0.7\nstage_ratio_2 = 0.7\nstage_ratio_3 = 0.7\nstage_ratio_4 = un_prune\n\n# the config template of target_pruning_ratio can be got by\n# python ./tools/get_channel_units.py {config_file} --choice\nfix_subnet = {\n # stage 1\n 'backbone.conv1_(0, 64)_64': un_prune, # short cut layers\n 'backbone.layer1.0.conv1_(0, 64)_64': stage_ratio_1,\n 'backbone.layer1.1.conv1_(0, 64)_64': stage_ratio_1,\n 'backbone.layer1.2.conv1_(0, 64)_64': un_prune,\n # stage 2\n 'backbone.layer2.0.conv1_(0, 128)_128': un_prune,\n 'backbone.layer2.0.conv2_(0, 128)_128': un_prune, # short cut layers\n 'backbone.layer2.1.conv1_(0, 128)_128': stage_ratio_2,\n 'backbone.layer2.2.conv1_(0, 128)_128': stage_ratio_2,\n 'backbone.layer2.3.conv1_(0, 128)_128': un_prune,\n # stage 3\n 'backbone.layer3.0.conv1_(0, 256)_256': un_prune,\n 'backbone.layer3.0.conv2_(0, 256)_256': un_prune, # short cut layers\n 'backbone.layer3.1.conv1_(0, 256)_256': stage_ratio_3,\n 'backbone.layer3.2.conv1_(0, 256)_256': stage_ratio_3,\n 'backbone.layer3.3.conv1_(0, 256)_256': stage_ratio_3,\n 'backbone.layer3.4.conv1_(0, 256)_256': stage_ratio_3,\n 'backbone.layer3.5.conv1_(0, 256)_256': un_prune,\n # stage 4\n 'backbone.layer4.0.conv1_(0, 512)_512': stage_ratio_4,\n 'backbone.layer4.0.conv2_(0, 512)_512': un_prune, # short cut layers\n 'backbone.layer4.1.conv1_(0, 512)_512': stage_ratio_4,\n 'backbone.layer4.2.conv1_(0, 512)_512': stage_ratio_4\n}\ndivisor = 8\n##############################################################################\n\narchitecture = _base_.model\n\nmodel = dict(\n _delete_=True,\n _scope_='mmrazor',\n type='GroupFisherDeploySubModel',\n architecture=architecture,\n fix_subnet=fix_subnet,\n divisor=divisor,\n)\n","sub_path":"cv/distiller/CWD/pytorch/mmrazor/configs/pruning/mmcls/l1-norm/l1-norm_resnet34_8xb32_in1k_a_deploy.py","file_name":"l1-norm_resnet34_8xb32_in1k_a_deploy.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"423020656","text":"import requests\n\n\nurl = 'http://localhost:5000/articles'\n# url = 'http://localhost:9200/es_py1/articles/_search'\njson1 = {\"article_kwd\":\"大数据\"}\n# json1 = {\n# \"query\": { \"match_all\": {} },\n# \"track_total_hits\": 1000,\n# \"from\": 0,\n# \"size\": 10,\n#\n# }\n# 爬取网页通用代码框架\ntry:\n r = requests.post(url, timeout = 10,json=json1)\n # r = requests.get(url)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n print(r.text)\nexcept:\n print('错误')","sub_path":"source/third_iteration/article_scrapy/request/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"536537405","text":"import numpy as np\nimport scipy.optimize as sp_opt\n\n\nclass MCOsolver:\n w = np.array([0.4, 0.4, 0.2])\n res = np.zeros((100, 4))\n i = 0\n\n def __init__(self, y0, constr, obj_f, obj_jac):\n self.constr = constr\n self.y0 = y0\n self.obj_f = obj_f\n self.obj_jac = obj_jac\n\n def solve(self, N=7):\n new_obj = lambda y: np.dot(self.w, self.obj_f(y))\n new_obj_jac = lambda y: np.dot(self.w, self.obj_jac(y))\n for self.w[0] in np.linspace(0, 1, N):\n for self.w[1] in np.linspace(0, 1 - self.w[0],\n N - int((N - 1)*self.w[0])):\n self.w[2] = 1 - self.w[0] - self.w[1]\n #if not np.any(self.w == 0):\n self.store_curr_res(self.KKTsolver(new_obj, new_obj_jac))\n return self.res[:self.i]\n\n def KKTsolver(self, new_obj, new_obj_jac):\n opt_res = sp_opt.minimize(new_obj, self.y0, method=\"SLSQP\",\n jac=new_obj_jac , bounds=self.constr).x\n return opt_res\n\n def store_curr_res(self, y):\n if self.i >= self.res.shape[0]:\n res = np.zeros((2*self.res.shape[0], 4))\n res[:self.res.shape[0]] = self.res\n self.res = res\n self.res[self.i] = y\n self.i = self.i + 1\n","sub_path":"force_bdss_prototype/MCOsolver.py","file_name":"MCOsolver.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"337508136","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\nwhile(1):\n # get a frame\n ret, frame = cap.read()\n # show a frame\n cv2.namedWindow(\"mywindow\")\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n edge=cv2.Canny(gray,80,150)\n cv2.imshow(\"mywindow\", edge)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\ncap.release()\ncv2.destroyAllWindows()","sub_path":"PythonLearning/Learning OpenCV/边缘检测.py","file_name":"边缘检测.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"204058571","text":"# coding=utf-8\n\n#opening the frequency lists\n#EDIT THESE FILE PATHS TO CHANGE THE INPUT, THESE ARE EXAMPLES ONLY (NUMBER OF INPUTS HAS TO REMAIN THE SAME)\n#SCROLL DOWN TO EDIT THE OUTPUT NAME/LOCATION\nah = open(\"data/English/results/freq/a.freq\")\nbh = open(\"data/English/results/freq/b.freq\")\ndh = open(\"data/English/results/freq/d.freq\")\neh = open(\"data/English/results/freq/e.freq\")\nfh = open(\"data/English/results/freq/f.freq\")\ncomp = open(\"data/English/results/freq/comp.freq\")\ninputs = [ah, bh, dh, eh, fh, comp]\n\n#converting them into dictionaries\nah_dict = {}\nbh_dict = {}\ndh_dict = {}\neh_dict = {}\nfh_dict = {}\ncomp = {}\ndictionaries = [ah_dict, bh_dict, dh_dict, eh_dict, fh_dict, comp]\n\ncounter = 0\n\nfor interview in inputs:\n for line in interview:\n word = line[2:].strip()\n number = int(line[:2])\n dictionaries[counter][word] = number\n counter += 1\n\n#summing the frequencies\nsummed_freq_dict = {}\n\nfor dictionary in dictionaries:\n for k, v in dictionary.iteritems():\n if k in summed_freq_dict:\n summed_freq_dict[k] = summed_freq_dict[k] + v\n else:\n summed_freq_dict[k] = v\n\n#making the output strings\noutput_lines = {}\ncounter = 0\n\nfor dictionary in dictionaries:\n for k, v in dictionary.iteritems():\n if k in output_lines:\n output_lines[k].append(v)\n else:\n i = 1\n output_lines[k] = list()\n while i <= counter:\n output_lines[k].append(0)\n i += 1\n output_lines[k].append(v)\n for k, v in output_lines.iteritems():\n if not k in dictionary: \n output_lines[k].append(0)\n counter += 1\n\n#opening output file and writing into it\n#OUTPUT LOCATION/FILE NAME CAN BE EDITED HERE\noutput_file = open(\"data/analysis/analysis.csv\", \"w\")\n\nfor k, v in output_lines.iteritems():\n output_line = k + \", \"\n for num in v:\n output_line = output_line + str(num) + \", \"\n output_file.write(output_line + \"\\n\")\n\n\n\n \n\n\n\n","sub_path":"freq/ENG/freq_sums.py","file_name":"freq_sums.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"164500441","text":"class Triangulo:\n\n def __init__(self, nro):\n self.nro = nro\n\n def dibujo(self):\n line = \"\"\n linef = \"\"\n for i in range(1, self.nro + 1):\n line = str(i * 2 - 1) + \" \" + line\n linef += line + \"\\n\"\n return linef\n\n\ndef main():\n while True:\n nro = input(\"Ingrese un numero: \")\n try:\n if nro == str(int(nro)):\n nro = int(nro)\n break\n except ValueError:\n print(\"Ingrese un numero entero\")\n tri = Triangulo(nro)\n print(tri.dibujo())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"58156-Soria, Lucas/TP N° 1/Ejercicio 5 OOP.py","file_name":"Ejercicio 5 OOP.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"276932122","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse\nfrom datetime import date\nfrom taskmanager.tasks.models import Task\nfrom taskmanager.tasks.forms import Task_form\n\n# Create your views here.\n\ndef home(request):\n tasks = Task.objects.search('')\n template_name = 'home.html'\n context = { \n 'tasks' : tasks\n }\n return render(request, template_name, context)\n\ndef new_task(request):\n message = ''\n\n if request.method == 'POST':\n form = Task_form(request.POST)\n if form.is_valid():\n task = form.save(commit=False)\n task.status = 'new'\n task.save()\n message = 'Tarefa salva.'\n \n template_name = 'newtask.html'\n context = { \n 'form' : Task_form(),\n 'message': message\n }\n return render(request, template_name, context)\n\ndef remove_task(request, pk):\n task= get_object_or_404(Task, pk=pk) \n task.delete()\n return redirect('/home/')\n\ndef edit_task(request, pk):\n task= get_object_or_404(Task, pk=pk) \n task.status = 'done'\n task.save()\n return redirect('/home/')","sub_path":"taskmanager/taskmanager/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"220725435","text":"import statistics\n\nuniversities = [\n ['California\tInstitute\tof\tTechnology',\t2175,\t37704],\n ['Harvard',\t19627,\t39849],\n ['Massachusetts\tInstitute\tof\tTechnology',\t10566,\t40732],\n ['Princeton',\t7802,\t37000],\n ['Rice',\t5879,\t35551],\n ['Stanford',\t19535,\t40569],\n ['Yale',\t11701,\t40500]\n]\n\n\ndef enrollment_stats(universities):\n student_enrollment = []\n tuition_fees = []\n\n for amount in universities:\n student_enrollment.append(amount[1])\n tuition_fees.append(amount[2])\n\n return student_enrollment, tuition_fees\n\n\nprint(enrollment_stats(universities))\n\n\ndef mean(list):\n if len(list) == 0:\n return \"There is not enough info for this!\"\n length = len(list)\n list_summation = 0\n\n for i in range(length):\n list_summation += int(list[i])\n\n list_summation = sum(list)\n average = int(list_summation / length)\n return average\n\n\ndef median(list):\n list_sorted = sorted(list)\n median = statistics.median(list_sorted)\n\n\ntotals = enrollment_stats(universities)\nprint(\"\\n\")\nprint(\"*****\" * 5)\nprint(\"Total students: {}\".format(sum(totals[0])))\nprint(\"Total tuition: {}\".format(sum(totals[1])))\nprint(\"\\n\")\nprint(\"Student mean: {}\".format(mean(totals[0])))\nprint(\"Student median: {}\".format(mean(totals[1])))\nprint(\"\\n\")\nprint(\"Tuition mean: {}\".format(median(totals[0])))\nprint(\"Tuition median: {}\".format(median(totals[1])))\nprint(\"*****\" * 5)\n ","sub_path":"chapter1/list_dict/list_of_list.py","file_name":"list_of_list.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"461931957","text":"class ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n \"\"\"\n @param head: head is the head of the linked list\n @return: head of the linked list\n \"\"\"\n\n def deleteDuplicates(self, head):\n if head is None or head.next is None:\n return head\n\n dummy = ListNode(0)\n dummy.next = head\n parent = dummy\n current = head\n\n while current is not None and current.next is not None:\n if current.val == current.next.val:\n duplicate_val = current.val\n\n while current is not None and current.val == duplicate_val:\n current = current.next\n\n parent.next = current\n else:\n current = current.next\n parent = parent.next\n\n return dummy.next\n","sub_path":"US Giants/Linked List/113. Remove Duplicates from Sorted List II.py","file_name":"113. Remove Duplicates from Sorted List II.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"40481617","text":"import pyphonetics\n\n\nclass Phonetics(pyphonetics.RefinedSoundex):\n def match(self, possible_names, name, alternative_name=None, transform_possible_names=list(), threshold=2):\n mindistance = None\n matching_index = None\n\n transform_possible_names.insert(0, lambda x: x)\n\n def check_name(name, possible_name):\n nonlocal mindistance, matching_index # noqa: E999\n\n distance = self.distance(name, possible_name)\n if mindistance is None or distance < mindistance:\n mindistance = distance\n matching_index = i\n\n for i, possible_name in enumerate(possible_names):\n for transform_possible_name in transform_possible_names:\n transformed_possible_name = transform_possible_name(possible_name)\n if not transformed_possible_name:\n continue\n check_name(name, transformed_possible_name)\n if alternative_name:\n check_name(alternative_name, transformed_possible_name)\n if mindistance is None or mindistance > threshold:\n return None\n return matching_index\n","sub_path":"src/hdx/location/phonetics.py","file_name":"phonetics.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"235049679","text":"for _ in range(int(input())):\n\ta,b=[int(i) for i in input().split()]\n\ts1=bin(a)[2:]\n\ts2=bin(b)[2:]\n\ti=1\n\twhile i', methods=['GET', 'POST'])\ndef product(id):\n\n\ttry:\n\n\t\tjson_to_sql.add_nfc_to_product(id)\n\texcept:\n\t\tprint(\"Failed to connect to backend\")\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"SELECT * FROM nfc WHERE product_id = (?) ORDER BY scan_date ASC;\", (id, ))\n\treadings = cur.fetchall()\n\n\tcoords = []\n\n\tfor reading in readings:\n\t\tlat = reading['lat']\n\t\tlon = reading['lon']\n\t\tcoord = [lat, lon]\n\t\tcoords.append(coord)\n\n\t\n\n\treturn render_template('product.html', readings = readings, coords=coords)\n\n@app.route('/plot/', methods=['GET', 'POST'])\ndef plot(id):\n\n\tif request.method == 'POST':\n\n\t\tif 'refresh_route' in request.form:\n\n\t\t\tsuccess = generate_iot_readings(id)\n\t\t\tif success:\n\t\t\t\tflash('Refreshed IoT readings', 'success')\n\t\t\t\treturn redirect(url_for('plot', id=id))\n\t\t\telse:\n\t\t\t\tflash('Refresh failed', 'danger')\n\t\t\t\treturn redirect(url_for('plot', id=id))\n\n\n\n\t\tif 'delete_reading' in request.form:\n\n\t\t\trowid = request.form['delete_reading']\n\t\t\tremove_reading(rowid)\n\t\t\tflash('Reading removed', 'success')\n\t\t\treturn redirect(url_for('plot', id=id))\n\n\t\telif 'submit_reading' in request.form:\n\t\t\tif request.form[\"submit_reading\"] == \"Add Reading\":\n\t\t\t\ttemperature = request.form[\"temperature\"]\n\t\t\t\thumidity = request.form[\"humidity\"]\n\t\t\t\tlux = request.form[\"lux\"]\n\t\t\t\tadd_reading(id, temperature, humidity, lux)\n\t\t\t\tflash('Reading added', 'success')\n\t\t\t\treturn redirect(url_for('plot', id=id))\n\n\t\telif 'update_route' in request.form:\n\t\t\tif 'route_select' in request.form:\n\t\t\t\tselect = request.form['route_select']\n\n\t\t\t\tif is_int(select):\n\t\t\t\t\tselect = int(select)\n\n\t\t\t\telif select == \"None\":\n\t\t\t\t\tselect = None\n\n\t\t\t\tupdate_next_route(id, select)\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"SELECT *, rowid FROM readings WHERE route_id = (?) ORDER BY create_date ASC;\", (id, ))\n\treadings = cur.fetchall()\n\n\tcur.execute(\"SELECT * FROM route WHERE route_id = (?);\", (id, ))\n\troute = cur.fetchone()\n\n\n\tcur.execute(\"SELECT location_name, lat, lon FROM location WHERE location_id = (?)\", (route['src_id'], ))\n\tsource = cur.fetchone()\n\tcur.execute(\"SELECT location_name, lat, lon FROM location WHERE location_id = (?)\", (route['dest_id'], ))\t\n\tdest = cur.fetchone()\n\n\t\n\t\n\n\tsrc_coord = []\n\tdest_coord = []\n\n\tif source['lat'] == None or source['lon'] == None:\n\t\tsrc_query = re.sub(' ', '+', source[0].lower()) + \"+,usa\"\n\t\tresponse = requests.get(\"https://nominatim.openstreetmap.org/?q={query}&format=json&limit=1\".format(query=src_query)).json()\n\t\tsrc_coord = [response[0]['lat'], response[0]['lon']]\n\t\tcur.execute(\"UPDATE location SET lat = ?, lon = ? WHERE location_id = ?\", (src_coord[0], src_coord[1], route['src_id']))\n\t\tdb.commit()\n\telse:\n\t\tsrc_coord = [source['lat'], source['lon']]\n\n\tif dest['lat'] == None or dest['lon'] == None:\n\t\tdest_query = re.sub(' ', '+', dest[0].lower()) + \"+,usa\"\n\t\tresponse = requests.get(\"https://nominatim.openstreetmap.org/?q={query}&format=json&limit=1\".format(query=dest_query)).json()\n\t\tdest_coord = [response[0]['lat'], response[0]['lon']]\n\t\tcur.execute(\"UPDATE location SET lat = ?, lon = ? WHERE location_id = ?\", (dest_coord[0], dest_coord[1], route['dest_id']))\n\t\tdb.commit()\n\telse:\n\t\tdest_coord = [dest['lat'], dest['lon']]\n\n\tbounds = [src_coord, dest_coord]\n\n\n\tcur.execute(\"SELECT route_id FROM route;\")\n\troute_ids = cur.fetchall()\n\n\n\tcur.close()\n\n\n\tplot_urls = [plot_reading(id, 'temperature'), plot_reading(id, 'humidity'), plot_reading(id, 'lux')]\n\treturn render_template('plot.html', plot_urls=plot_urls, id=id, readings = readings, bounds = bounds, route=route, src=source['location_name'], dest=dest['location_name'], route_ids=route_ids)\n\ndef update_next_route(route_id, next_route):\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"UPDATE route SET next_route = ? WHERE route_id = ?;\", (next_route, route_id))\n\tdb.commit()\n\tcur.close()\n\n\ndef add_product(product_id, product_type, start_route):\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tif len(product_type) < 3:\n\t\tflash('Product type must be greater than 3 characters', 'danger')\n\t\treturn redirect(url_for('index'))\n\n\tif len(start_route) > 0:\n\t\ttry:\n\t\t\tstart_route = int(start_route)\n\t\texcept ValueError:\n\t\t\tflash('Start Route ID must be a number', 'danger')\n\t\t\treturn redirect(url_for('index'))\n\telse:\n\t\tstart_route = None\n\n\n\tif len(product_id) == 0:\n\t\tcur.execute(\"INSERT INTO product(product_type, start_route) VALUES (?, ?);\", (product_type, start_route))\n\n\telse:\n\t\tcur.execute(\"SELECT EXISTS(SELECT 1 FROM product WHERE product_id = ?)\", (product_id, ))\n\t\tid_exists = cur.fetchone()\n\t\tif id_exists[0]:\n\t\t\tflash('Product with that ID already exists', 'danger')\n\t\t\treturn redirect(url_for('index'))\n\n\t\tcur.execute(\"INSERT INTO product(product_id, product_type, start_route) VALUES (?, ?, ?);\", (product_id, product_type, start_route))\n\t\n\tcur.close()\n\tdb.commit()\n\n\tflash('New product added', 'success')\n\treturn redirect(url_for('index'))\n\ndef remove_product(product_id):\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\tcur.execute(\"DELETE FROM product WHERE product_id = ?;\", (product_id, ))\n\t\n\tdb.commit()\n\tcur.close()\n\tflash('Product {id} deleted'.format(id=product_id), 'success')\n\treturn redirect(url_for('index'))\n\n\ndef add_route(route_id, src_id, dest_id, next_route):\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tif len(route_id) > 0:\n\t\ttry:\n\t\t\troute_id = int(route_id)\n\t\texcept ValueError:\n\t\t\tflash('Route ID must be a number', 'danger')\n\t\t\treturn redirect(url_for('index'))\n\n\tif len(next_route) > 0:\n\t\ttry:\n\t\t\tnext_route = int(next_route)\n\t\texcept ValueError:\n\t\t\tflash('Next Route ID must be a number', 'danger')\n\t\t\treturn redirect(url_for('index'))\n\telse:\n\t\tnext_route = None\n\n\tif len(src_id) < 3 or len(dest_id) < 3:\n\t\tflash('Source or Destination must be greater than 3 characters', 'danger')\n\t\treturn redirect(url_for('index'))\n\telse:\n\t\tsrc_id = get_location(src_id)\n\t\tdest_id = get_location(dest_id)\n\n\tif len(route_id) == 0:\n\t\tprint(src_id, dest_id, next_route)\n\t\tcur.execute(\"INSERT INTO route(src_id, dest_id, next_route) VALUES (?, ?, ?);\", (src_id, dest_id, next_route))\n\n\telse:\n\t\tcur.execute(\"SELECT EXISTS(SELECT 1 FROM route WHERE route_id = ?)\", (route_id, ))\n\t\tid_exists = cur.fetchone()\n\t\tif id_exists[0]:\n\t\t\tflash('Route with that ID already exists', 'danger')\n\t\t\treturn redirect(url_for('index'))\n\n\t\tcur.execute(\"INSERT INTO route(route_id, src_id, dest_id, next_route) VALUES (?, ?, ?, ?);\", (route_id, src_id, dest_id, next_route))\n\n\tdb.commit()\n\tcur.close()\n\tflash('New route added', 'success')\n\treturn redirect(url_for('index'))\n\ndef remove_route(route_id):\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"SELECT rowid FROM readings WHERE route_id = ?;\", (route_id, ))\n\treadings = cur.fetchall()\n\n\tfor reading in readings:\n\t\tremove_reading(reading[0])\n\n\tcur.execute(\"DELETE FROM route WHERE route_id = ?;\", (route_id, ))\n\t\n\tdb.commit()\n\tcur.close()\n\t\n\ndef add_reading(route_id, temperature, humidity, lux):\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tif is_int(temperature):\n\t\ttemperature = int(temperature)\n\telif len(temperature) == 0:\n\t\ttemperature = random.randint(40, 120)\n\telse:\n\t\tflash('Temperature must be a number', 'danger')\n\t\treturn None\n\n\tif is_int(humidity):\n\t\thumidity = int(humidity)\n\telif len(humidity) == 0:\n\t\thumidity = random.randint(30, 70)\n\telse:\n\t\tflash('Humidity must be a number', 'danger')\n\t\treturn None\n\n\tif is_int(lux):\n\t\tlux = int(lux)\n\telif len(lux) == 0:\n\t\tlux = random.randint(60, 130)\n\telse:\n\t\tflash('Lux must be a number', 'danger')\n\t\treturn None\n\n\tcur.execute(\"INSERT INTO readings(route_id, temperature, humidity, lux) VALUES(?, ?, ?, ?);\", (route_id, temperature, humidity, lux))\n\n\tdb.commit()\n\tcur.close()\n\n\ndef is_int(req):\n\tif len(req) > 0:\n\t\ttry:\n\t\t\tint(req)\n\t\t\treturn True\n\t\texcept ValueError:\n\t\t\tpass\n\treturn False\n\n\ndef remove_reading_from_plot(rowid):\n\tremove_reading(rowid)\n\tflash('Reading removed', 'success')\n\n\ndef remove_reading(rowid):\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"DELETE FROM readings WHERE rowid = ?;\", (rowid, ))\n\n\tdb.commit()\n\tcur.close()\n\ndef get_location(name):\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\tcur.execute(\"SELECT location_id FROM location WHERE location_name = ?;\", (name, ))\n\n\n\tlocation_id = cur.fetchone()\n\tif location_id:\n\t\treturn location_id[0]\n\telse:\n\t\tcur.execute(\"INSERT INTO location(location_name) VALUES(?);\", (name, ))\n\t\tdb.commit()\n\t\treturn cur.lastrowid\n\n\tcur.close()\n\n@app.route('/generate_iot_readings/')\ndef generate_iot_readings(id):\n\n\ttry:\n\t\tjson_to_sql.add_readings_to_route(id)\n\texcept:\n\t\tprint(\"Cannot connect to database\")\n\n\treturn \"Success\"\n\n\n\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n\n\tif request.method == 'POST':\n\n\t\tif 'delete_product' in request.form:\n\t\t\tdelete_product_id = request.form['delete_product']\n\t\t\tif delete_product_id:\n\t\t\t\tremove_product(delete_product_id)\n\n\t\tif 'delete_route' in request.form:\n\t\t\tdelete_route_id = request.form['delete_route']\n\t\t\tif delete_route_id:\n\t\t\t\tremove_route(delete_route_id)\n\t\t\t\tflash('Route {id} and associated readings deleted'.format(id=delete_route_id), 'success')\n\t\t\t\treturn redirect(url_for('index'))\n\n\t\telif 'submit_button' in request.form:\n\t\t\t\n\t\t\tif request.form['submit_button'] == 'Add Product':\n\t\t\t\t\n\t\t\t\tproduct_id = request.form[\"product_id\"]\n\t\t\t\tproduct_type = request.form[\"product_type\"]\n\t\t\t\tstart_route = request.form[\"start_route\"]\n\t\t\t\tadd_product(product_id, product_type, start_route)\n\n\n\t\t\telif request.form['submit_button'] == 'Add Route':\n\n\t\t\t\troute_id = request.form[\"route_id\"]\n\t\t\t\tsrc_id = request.form[\"src_id\"]\n\t\t\t\tdest_id = request.form[\"dest_id\"]\n\t\t\t\tnext_route = request.form[\"next_route\"]\n\t\t\t\tadd_route(route_id, src_id, dest_id, next_route)\n\n\n\tdb = get_db()\n\tdb.row_factory = sqlite3.Row\n\tcur = db.cursor()\n\n\t\n\tcur.execute(\"SELECT * FROM product;\")\n\tproducts = cur.fetchall()\n\n\tcur.execute(\"SELECT * FROM route;\")\n\troutes = cur.fetchall()\n\n\tcur.execute(\"SELECT * FROM location;\")\n\tlocations = cur.fetchall()\n\n\treturn render_template('home.html', products = products, routes = routes, locations = locations)\n\n\nif __name__ == '__main__':\n\tapp.secret_key='secret'\n\tapp.run(host='0.0.0.0', port=int(os.environ.get('PORT', '8080')), debug=True)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"362900893","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 13 16:10:49 2019\n\n@author: Donnie\n\"\"\"\nimport sympy as sp\nsp.init_session(quiet=True)\nimport numpy as np\nfrom scipy import sparse\nfrom scipy.sparse.linalg import spsolve\nfrom scipy.sparse import csc_matrix, eye, diags\nfrom scipy import optimize\nimport scipy.linalg as LA\nimport matplotlib.pyplot as plt\nimport peakutils\nfrom lmfit import models\nimport pandas as pd\n\ndef baseline_arPLS(y, lam=10**5, n_iter=500, tol=.01):\n \"\"\"Asymmetrically reweighted penalized least squares smoothing (ArPLS)\n \n Method developed by Baek, et al.:\n Baek, et. al. Baseline correction using asymmetrically reweighted penalized \n least squares smoothing. Analyst, 2015, 140, 250-257.\n \"\"\"\n\n L = len(y)\n D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L,L-2))\n B = lam * D.dot(D.transpose())\n w = np.ones(L)\n W = sparse.spdiags(w, 0, L, L)\n\n for i in range(n_iter):\n Z = W + B\n z = spsolve(Z, w*y)\n d = y - z\n d_neg = d[d<0]\n m = np.mean(d_neg)\n s = np.std(d_neg)\n wt = 1.0/(1 + np.exp(2 * (d - (2 * s - m)) / s))\n\n if LA.norm(w-wt)/LA.norm(w) < tol:\n break\n w = wt\n W.setdiag(w)\n\n return z\n\n\ndef baseline_als_optimized(y, lam, p, n_iter=50, tol=1e-6):\n '''Fits the baseline using assymetric least squared (ALS) fitting.\n \n Method developed by Eilers P, Boelens H. \n Baseline correction with asymmetric least squares smoothing. 2005. \n Code adapted from: \n https://stackoverflow.com/questions/29156532/python-baseline-correction-library\n \n y is the actual data\n z is the calculated data, so that (y-z) are the residuals\n p is the assymetric weighting parameter. After the first fit:\n - for y > z (y above the baseline), the weighting is set to p\n - for y < z, the weighting is set to 1-p\n w is the weighting for each y value (w_i for y_i)\n \n There are two parameters: p for asymmetry and λ for smoothness. \n Both have to be tuned to the data at hand. Generally 0.001 ≤ p ≤ 0.1 \n is a good choice (for a signal with positive peaks) and 10^2 ≤ λ ≤ 10^9, \n but exceptions may occur. \n '''\n L = len(y)\n D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L,L-2))\n B = lam * D.dot(D.transpose()) # Precompute this term since it does not depend on `w`\n w = np.ones(L)\n W = sparse.spdiags(w, 0, L, L)\n w_old = w.copy()\n for i in range(n_iter):\n Z = W + B\n z = spsolve(Z, w*y)\n w = p * (y > z) + (1-p) * (y < z)\n if LA.norm(w-w_old)/LA.norm(w) < tol:\n break\n else:\n W.setdiag(w) # Do not create a new matrix, just update diagonal values\n w_old = w.copy()\n return z\n\ndef baseline_als_improved(y, lam, lam1, p, n_iter=50, tol=1e-6):\n '''\n Obtained from:\n S. He, W. Zhang, L. Liu, Y. Huang, J. He, W. Xie, P. Wu, C. Du, \n Baseline correction for raman spectra using an improved asymmetric \n least squares method, Analytical Methods 6(12) (2014) 4402-4407.\n \n y is the actual data\n z is the calculated data, so that (y-z) are the residuals\n p is the assymetric weighting parameter. After the first fit:\n - for y > z (y above the baseline), the weighting is set to p\n - for y < z, the weighting is set to 1-p\n w is the weighting for each y value (w_i for y_i)\n \n There are two parameters: p for asymmetry and λ for smoothness. \n Both have to be tuned to the data at hand. We found that generally 0.001 ≤ p ≤ 0.1 \n is a good choice (for a signal with positive peaks) and 10^2 ≤ λ ≤ 10^9, \n but exceptions may occur. \n '''\n L = len(y)\n D = sparse.diags([1, -2, 1], [0, -1, -2], shape=(L,L-2))\n D1 = sparse.diags([1, -1], [0, -1], shape=(L,L-1))\n #B = lam * D.dot(D.transpose()) #old version, did not match what was in the ALS paper\n B = lam * D.dot(D.transpose()) # Precompute this term since it does not depend on `w`\n B1 = lam1 * D1.dot(D1.transpose())\n w = np.ones(L)\n z = np.poly1d(np.polyfit(x, y, 2))(x)\n w = p * (y > z) + (1-p) * (y < z)\n W = sparse.spdiags(w, 0, L, L)\n w_old = w\n for i in range(n_iter):\n W.setdiag(w) # Do not create a new matrix, just update diagonal values\n Z = W.T*W + B1 + B\n Y = W.T*W + B1\n z = spsolve(Z, Y*y)\n w = p * (y > z) + (1-p) * (y < z)\n #LA.norm(w-w_old) gives the length of the vector w-w_old (I think).\n if LA.norm(w-w_old)/LA.norm(w) < tol:\n break\n w_old = w\n return z\n\ndef WhittakerSmooth(x, w, lambda_, differences=1):\n '''\n Penalized least squares algorithm for background fitting\n\n input\n x: input data (i.e. chromatogram of spectrum)\n w: binary masks (value of the mask is zero if a point belongs to peaks and one otherwise)\n lambda_: parameter that can be adjusted by user. The larger lambda is, the smoother the resulting background\n differences: integer indicating the order of the difference of penalties\n\n output\n the fitted background vector\n \n Obtained from:\n https://github.com/zmzhang/airPLS\n '''\n X=np.matrix(x)\n m=X.size\n E=eye(m,format='csc')\n D=E[1:]-E[:-1] # numpy.diff() does not work with sparse matrix. This is a workaround.\n W=diags(w,0,shape=(m,m))\n A=csc_matrix(W+(lambda_*D.T*D))\n B=csc_matrix(W*X.T)\n background=spsolve(A,B)\n return np.array(background)\n\ndef polyFit(x, y, poly_order, tol, n_iter):\n '''\n Not currently working\n \n Adapted from:\n C.A. Lieber, A. Mahadevan-Jansen, Automated method \n for subtraction of fluorescence from biological raman spectra, \n Applied Spectroscopy 57(11) (2003) 1363-1367.\n '''\n \n poly = np.poly1d(np.polyfit(x, y, poly_order))\n plt.figure()\n for i in range(n_iter):\n plt.plot(x, y, label=f'fit# {i}')\n z = optimize.curve_fit(poly, x, y)\n z[z > y] = y[z > y]\n if LA.norm(z-y) < tol:\n break\n y = z\n plt.legend()\n plt.show()\n\n\ndef airPLS(x, lambda_=100, porder=1):\n '''\n Adaptive iteratively reweighted penalized least squares for baseline fitting\n\n input\n x: input data (i.e. chromatogram of spectrum)\n lambda_: parameter that can be adjusted by user. The larger lambda is, the smoother the resulting background, z\n porder: adaptive iteratively reweighted penalized least squares for baseline fitting\n\n output\n the fitted background vector\n Obtained from:\n Z.-M. Zhang, S. Chen, and Y.-Z. Liang, \n Baseline correction using adaptive iteratively reweighted penalized least squares. \n Analyst 135 (5), 1138-1146 (2010).\n https://github.com/zmzhang/airPLS\n '''\n itermax = 50\n m=x.shape[0]\n w=np.ones(m)\n for i in range(1,itermax+1):\n z=WhittakerSmooth(x,w,lambda_, porder)\n d=x-z\n dssn=np.abs(d[d<0].sum())\n if(dssn<0.001*(abs(x)).sum() or i==itermax):\n if(i==itermax): print ('WARING max iteration reached!')\n break\n w[d>=0]=0 # d>0 means that this point is part of a peak, so its weight is set to 0 in order to ignore it\n w[d<0]=np.exp(i*np.abs(d[d<0])/dssn)\n w[0]=np.exp(i*(d[d<0]).max()/dssn) \n w[-1]=w[0]\n return z\n\ndef test_ALS_variables(x, y, lam_default=10**6, p_default=0.01):\n '''\n Varies lambda and p to show the best variables for a dataset.\n \n Varies lambda from 10**2 to 10**10 and p from 0.001 to 0.01 and \n plots the results. Lambda is varied on an exponential scale.\n '''\n \n solutions_lam = []\n solutions_p = []\n \n lam = [10**2]\n p = [0.001]\n \n while lam[-1] <= 10**10:\n solutions_lam.append(baseline_als_optimized(y, lam[-1], p_default))\n lam.append(lam[-1] * 10)\n \n while p[-1] <= 0.1:\n solutions_p.append(baseline_als_optimized(y, lam_default, p[-1]))\n \n if p[-1] != 0.001:\n p.append(p[-1] + 0.01)\n else:\n p.append(0.01)\n \n plt.figure()\n plt.title(f'p = {p_default}')\n plt.plot(x, y, label=f'data')\n for num, solution in enumerate(solutions_lam):\n label = f'{np.log10(lam[num]):.0f}'\n plt.plot(x, solution, label='$\\lambda$ = 10$^{%s}$' %(label))\n plt.legend()\n plt.show()\n \n plt.figure()\n plt.title('$\\lambda$ = 10$^{%.0f}$' %(np.log10(lam_default)))\n plt.plot(x, y, label='data')\n for num, solution in enumerate(solutions_p):\n plt.plot(x, solution, label=f'p = {p[num]:.3f}')\n plt.legend()\n plt.show()\n\ndef test_iALS_variables(x, y, lam_default=10**6, \n lam_1_default=10**6, p_default=0.01):\n '''\n Varies lambda, lambda_1 and p to show the best variables for a dataset.\n \n Varies lambda from 10**2 to 10**10 and p from 0.001 to 0.01 and \n plots the results. Lambda is varied on an exponential scale.\n '''\n \n solutions_lam = []\n solutions_lam_1 = []\n solutions_p = []\n \n lam = [10**2]\n lam_1= [10**-6]\n p = [0.001]\n \n while lam[-1] <= 10**10:\n solutions_lam.append(baseline_als_improved(y, lam[-1], \n lam_1_default, p_default))\n lam.append(lam[-1] * 10)\n \n while lam_1[-1] <= 10**-3:\n solutions_lam_1.append(baseline_als_improved(y, lam_default,\n lam_1[-1], p_default))\n lam_1.append(lam_1[-1] * 10)\n \n while p[-1] <= 0.1:\n solutions_p.append(baseline_als_improved(y, lam_default, \n lam_1_default, p[-1]))\n \n if p[-1] != 0.001:\n p.append(p[-1] + 0.01)\n else:\n p.append(0.01)\n \n plt.figure()\n plt.title(f'p = {p_default}\\n$\\lambda_1$ = {lam_1_default}')\n plt.plot(x, y, label=f'data')\n for num, solution in enumerate(solutions_lam):\n label = f'{np.log10(lam[num]):.0f}'\n plt.plot(x, solution, label='$\\lambda$ = 10$^{%s}$' %(label))\n plt.legend()\n plt.show()\n \n plt.figure()\n plt.title('$\\lambda$ = 10$^{%.0f}$\\n p = %.3f' %(np.log10(lam_default),\n p_default))\n plt.plot(x, y, label='data')\n for num, solution in enumerate(solutions_lam_1):\n plt.plot(x, solution, label=f'$\\lambda_1$ = {lam_1[num]:.6f}')\n plt.legend()\n plt.show()\n \n plt.figure()\n plt.title('$\\lambda$ = 10$^{%.0f}$\\n$\\lambda_1$ = %.6f' %(np.log10(lam_default),\n lam_1_default))\n plt.plot(x, y, label='data')\n for num, solution in enumerate(solutions_p):\n plt.plot(x, solution, label=f'p = {p[num]:.3f}')\n plt.legend()\n plt.show()\n\nif __name__ == '__main__':\n\n fileName = r\"..\\Raw Data\\Data Fitting\\Raman-E40.txt\"\n \n data = pd.read_csv(fileName, sep='\\t', engine='python', \n usecols=[0, 1], index_col=None,\n names=['x', 'y'], skiprows=0)\n x_min = 550\n x_max = 3800\n \n x = np.array(data['x'])[:-1]\n y = np.array(data['y'])[:-1]\n \n domain_mask = (x > x_min) & (x < x_max)\n x = x[domain_mask]\n y = y[domain_mask]\n \n test_ALS_variables(x, y, lam_default=10**7, p_default=0.005)\n test_iALS_variables(x, y, lam_default=10**6, lam_1_default=10**-4, p_default=0.01)\n \n baseline = baseline_als_improved(y, 10**6, 10**-4, 0.01)\n baseline_2 = baseline_als_optimized(y, 10**8 ,0.005)\n baseline_3 = airPLS(y, 3000, 0.01)\n baseline2 = peakutils.baseline(y, 2)\n baseline_4 = baseline_arls(y, lam=2*10**7)\n \n polynomial_background = models.PolynomialModel(2, prefix='b_')\n poly_params = polynomial_background.guess(y, x=x)\n solution = polynomial_background.fit(y, poly_params, x=x, method='least_squares')\n baseline3 = solution.eval_components(x=x)['b_']\n \n \n fig = plt.figure()\n plt.plot(x, y, label='data')\n plt.plot(x, y-baseline, label='iALS')\n plt.plot(x, y-baseline_2, label='ALS')\n plt.plot(x, y-baseline_3, label='airPLS')\n plt.plot(x, y-baseline2, label='peakutils')\n plt.plot(x, y-baseline_4,label='ArLS')\n #plt.plot(x, y-baseline3)\n plt.legend()\n plt.show\n \n fig = plt.figure()\n plt.plot(x, baseline, x, baseline_2, x, baseline_3, x, baseline2, \n x, baseline_4)\n plt.legend(['iALS', 'ALS', 'airPLS', 'peakutils', 'ArLS'])\n plt.show()\n \n fig=plt.figure()\n plt.plot(x, y, x, baseline, x, baseline_2, x, baseline_3, x, baseline_4)\n plt.legend(['original', 'iALS', 'ALS', 'airPLS', 'ArLS'])\n plt.show()\n \n plt.figure()\n plt.plot(x,y, label='data')\n for i in range(1, 11):\n plt.plot(x, baseline_arls(y, lam=5*10**i), label=f'5*10**{i}')\n plt.legend()\n plt.show()","sub_path":"Data Fitting/baseline_correction.py","file_name":"baseline_correction.py","file_ext":"py","file_size_in_byte":12850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"498612106","text":"import sys\nimport math\nimport json\nimport pygame\nfrom modules.map import Map\n\nEVAL_MODE = False\n\npixel_constant = 50\ndisplay_width = 0\ndisplay_height = 0\n\nCOLORS = {\n 'black': (0, 0, 0),\n 'white': (255, 255, 255),\n 'gray': (127, 127, 127),\n 'red': (255, 0, 0),\n 'blue': (0, 0, 255),\n 'green': (0, 255, 0),\n 'magenta': (255, 0, 255),\n 'yellow': (255, 255, 0),\n 'cyan': (0, 255, 255)\n}\n\ngame_display = None\nrobot = None\ngame_map = None\n\nmissing_color = 'white'\nexit_col = 0\nexit_row = 0\n\nif not EVAL_MODE:\n pygame.init()\n robot_img = pygame.image.load('resources/images/robot_gray.png')\n robot_blue = pygame.image.load('resources/images/robot_blue.png')\n robot_red = pygame.image.load('resources/images/robot_red.png')\n robot_green = pygame.image.load('resources/images/robot_green.png')\n robot_magenta = pygame.image.load('resources/images/robot_magenta.png')\n robot_yellow = pygame.image.load('resources/images/robot_yellow.png')\n robot_cyan = pygame.image.load('resources/images/robot_cyan.png')\n run_button = pygame.image.load('resources/images/run.png')\n pygame.display.set_caption('Robot simulator')\n clock = pygame.time.Clock()\n\ncrashed = EVAL_MODE\nreset = False\nstart = True\n\nwith open('resources/map.json') as json_file:\n map_info = json.load(json_file)\n\n\nclass Robot:\n def __init__(self, x: int, y: int, w: int, size: int,\n col: int, row: int, direction: int) -> None:\n self.dir = direction\n self.x = x\n self.y = y\n self.col = col\n self.row = row\n self.w = w\n self.size = size\n self.offset = (pixel_constant - size)//2\n self.sensor_range = pixel_constant\n self.color = 'gray'\n self.movements = 0\n self.logic_calls = 0\n self.points = 0\n self.xEnd = 0\n self.yEnd = 0\n self.missing_color = 'white'\n self.white = False\n self.finished = False\n\n def set_position(self, x: int, y: int, w: int) -> None:\n if not EVAL_MODE:\n self.x = x\n self.y = y\n self.w = w\n box = [pygame.math.Vector2(p) for p in [(\n 0, 0), (self.size, 0), (self.size, -self.size), (0, -self.size)]]\n box_rotate = [p.rotate(self.w) for p in box]\n min_box = (min(box_rotate, key=lambda p: p[0])[0],\n min(box_rotate, key=lambda p: p[1])[1])\n max_box = (max(box_rotate, key=lambda p: p[0])[0],\n max(box_rotate, key=lambda p: p[1])[1])\n pivot = pygame.math.Vector2(self.size//2, -self.size//2)\n pivot_rotate = pivot.rotate(self.w)\n pivot_move = pivot_rotate - pivot\n origin = (self.x - self.size//2 +\n min_box[0] - pivot_move[0], self.y - self.size//2 - max_box[1] + pivot_move[1])\n if self.color == 'blue':\n rotated_image = pygame.transform.rotate(robot_blue, self.w)\n elif self.color == 'red':\n rotated_image = pygame.transform.rotate(robot_red, self.w)\n elif self.color == 'green':\n rotated_image = pygame.transform.rotate(robot_green, self.w)\n elif self.color == 'magenta':\n rotated_image = pygame.transform.rotate(robot_magenta, self.w)\n elif self.color == 'yellow':\n rotated_image = pygame.transform.rotate(robot_yellow, self.w)\n elif self.color == 'cyan':\n rotated_image = pygame.transform.rotate(robot_cyan, self.w)\n else:\n rotated_image = pygame.transform.rotate(robot_img, self.w)\n game_display.blit(rotated_image, origin)\n pygame.display.update()\n clock.tick(120)\n return\n \n def detect_white(self, old_row, olr_col) -> None:\n if self.white:\n return\n game_map.tiles[self.row][self.col].touched = True\n game_map.tiles[old_row][olr_col].touched = True\n for r in range(game_map.height):\n for c in range(game_map.width):\n if not game_map.tiles[r][c].touched:\n return\n if game_map.tiles[self.row][self.col].color == 'white':\n self.white = True\n self.points += 30\n print('On white square after exploring the entire labyrinth: +30')\n generate_map()\n return\n \n def move_forward(self) -> None:\n # Map dir:\n # 0 -> north\n # 1 -> west\n # 2 -> south\n # 3 -> east\n if self.finished:\n return\n if self._get_distance(0):\n self.movements += 1\n factor = ((-1, 0), (0, -1), (1, 0), (0, 1))\n self.row += factor[self.dir][0]\n self.col += factor[self.dir][1]\n if not EVAL_MODE:\n for _ in range(pixel_constant):\n rad = math.radians(self.w)\n x1 = round(math.cos(rad)) + self.x\n y1 = self.y - round(math.sin(rad))\n generate_map()\n self.set_position(x1, y1, self.w)\n self.detect_white(self.row - factor[self.dir][0], self.col - factor[self.dir][1])\n return\n\n def rotate_right(self) -> None:\n if self.finished:\n return\n self.movements += 1\n self.dir = (self.dir - 1 + 4) % 4\n if not EVAL_MODE:\n for _ in range(30):\n generate_map()\n self.set_position(self.x, self.y, self.w - 3)\n return\n\n def rotate_left(self) -> None:\n if self.finished:\n return\n self.movements += 1\n self.dir = (self.dir + 1) % 4\n if not EVAL_MODE:\n for _ in range(30):\n generate_map()\n self.set_position(self.x, self.y, self.w + 3)\n return\n\n def ultrasonic_front(self) -> int:\n if self.finished:\n return -1\n self.logic_calls += 1\n return self._get_distance(0)\n\n def ultrasonic_right(self) -> int:\n if self.finished:\n return -1\n self.logic_calls += 1\n return self._get_distance(1)\n\n def ultrasonic_left(self) -> int:\n if self.finished:\n return -1\n self.logic_calls += 1\n return self._get_distance(2)\n\n def _get_distance(self, dir_ultrasonic: int) -> int:\n # dir:\n # Front: 0\n # Right: 1\n # Left: 2\n # Map dir:\n # 0 -> north\n # 1 -> west\n # 2 -> south\n # 3 -> east\n dirs = [[0, 1, 2, 3],\n [3, 0, 1, 2],\n [1, 2, 3, 0]]\n\n distance = None\n start_dist = 0\n distance_direction = dirs[dir_ultrasonic][self.dir]\n\n if distance_direction == 0:\n # row-- until 0\n for row in range(self.row, -1, -1):\n if game_map.tiles[row][self.col].north.status == 1:\n distance = start_dist\n break\n start_dist += 1\n if distance is None:\n return -1\n\n if distance_direction == 1:\n # col-- until 0\n for col in range(self.col, -1, -1):\n if game_map.tiles[self.row][col].west.status == 1:\n distance = start_dist\n break\n start_dist += 1\n if distance is None:\n return -1\n\n if distance_direction == 2:\n # row++ until max\n for row in range(self.row, game_map.height):\n if game_map.tiles[row][self.col].south.status == 1:\n distance = start_dist\n break\n start_dist += 1\n if distance is None:\n return -1\n\n if distance_direction == 3:\n # col++ until max\n for col in range(self.col, game_map.width):\n if game_map.tiles[self.row][col].east.status == 1:\n distance = start_dist\n break\n start_dist += 1\n if distance is None:\n return -1\n if not EVAL_MODE:\n pygame.display.update()\n clock.tick(120)\n return distance\n\n def get_color(self) -> str:\n if self.finished:\n return ''\n self.logic_calls += 1\n row = self.row\n col = self.col\n if game_map.tiles[row][col].color:\n return game_map.tiles[row][col].color\n return 'white'\n\n def display_color(self, color: str) -> None:\n if self.finished:\n return\n self.logic_calls += 1\n row = self.row\n col = self.col\n tile_color = game_map.tiles[row][col].color\n if not game_map.tiles[row][col].color_identified and tile_color == 'white' and color == missing_color:\n game_map.tiles[row][col].color_identified = True\n self.points += 20\n print(f'Missing color successfully identified: {missing_color} +5')\n self.color = color\n self.set_position(self.x, self.y, self.w)\n self.color = 'gray'\n if not EVAL_MODE:\n pygame.time.delay(500)\n self.set_position(self.x, self.y, self.w)\n elif not game_map.tiles[row][col].color_identified and color == tile_color and color != 'white':\n game_map.tiles[row][col].color_identified = True\n self.points += 5\n print(f'Color successfully identified: {color} +5')\n self.color = color\n self.set_position(self.x, self.y, self.w)\n self.color = 'gray'\n if not EVAL_MODE:\n pygame.time.delay(500)\n self.set_position(self.x, self.y, self.w)\n return\n\n def finish_round(self) -> None:\n self.logic_calls -= 1\n if self.col == exit_col and self.row == exit_row:\n self.points += 30\n print('Arrived correctly to exit: +30')\n generate_map()\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n print('Program finished!')\n print(\"Total points: \", self.points)\n print(\"Total movements: \", self.movements)\n print(\"Total logic calls: \", self.logic_calls)\n print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n self.finished = True\n return\n\n def debug_tile(self) -> None:\n print(\"(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)\")\n print(\"Color: \", game_map.tiles[self.row][self.col].color)\n print(\"north: \", game_map.tiles[self.row][self.col].north.status,\n game_map.tiles[self.row][self.col].north.data)\n print(\"south: \", game_map.tiles[self.row][self.col].south.status,\n game_map.tiles[self.row][self.col].south.data)\n print(\"east: \", game_map.tiles[self.row][self.col].east.status,\n game_map.tiles[self.row][self.col].east.data)\n print(\"west: \", game_map.tiles[self.row][self.col].west.status,\n game_map.tiles[self.row][self.col].west.data)\n print(\"(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)\")\n return\n\n\ndef generate_map() -> None:\n if EVAL_MODE:\n return\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n game_display.fill(COLORS['white'])\n\n for row in range(game_map.height):\n for col in range(game_map.width):\n # Tile color\n if game_map.tiles[row][col].color:\n x = col * pixel_constant\n y = row * pixel_constant\n c = COLORS[game_map.tiles[row][col].color]\n pygame.draw.rect(\n game_display, c, (x, y, pixel_constant, pixel_constant))\n\n # Tile walls in north, south, east and west order\n x1 = [0, 0, 1, 0]\n y1 = [0, 1, 0, 0]\n x2 = [1, 1, 1, 0]\n y2 = [0, 1, 1, 1]\n wall_colors = [None, ['red', 'blue', 'black']]\n direction = [\"north\", \"south\", \"east\", \"west\"]\n # Wall shifting towards the center\n shift_x = [0, 0, -1, 1]\n shift_y = [1, -1, 0, 0]\n for wall_order in range(4):\n direction_status = getattr(\n getattr(game_map.tiles[row][col], direction[wall_order]), \"status\")\n if direction_status != 0:\n x1_pixel = (col + x1[wall_order]) * pixel_constant + \\\n shift_x[wall_order] * pixel_constant * 0.02\n x2_pixel = (col + x2[wall_order]) * pixel_constant + \\\n shift_x[wall_order] * pixel_constant * 0.02\n y1_pixel = (row + y1[wall_order]) * pixel_constant + \\\n shift_y[wall_order] * pixel_constant * 0.02\n y2_pixel = (row + y2[wall_order]) * pixel_constant + \\\n shift_y[wall_order] * pixel_constant * 0.02\n color = wall_colors[direction_status]\n if isinstance(color, list):\n color = color[-1]\n pygame.draw.line(game_display, COLORS[color], \n (x1_pixel, y1_pixel), (x2_pixel, y2_pixel), 5)\n\n movements = robot.movements if robot else 0\n logic_calls = robot.logic_calls if robot else 0\n points = robot.points if robot else 0\n\n myfont = pygame.font.SysFont('Arial', 12)\n textsurface = myfont.render(f'Movements = {movements}', False, (0, 0, 0))\n game_display.blit(textsurface, (pixel_constant * (map_info['size']['w'] + 0.2),\n pixel_constant*0.2))\n textsurface = myfont.render(f'Logic calls = {logic_calls}', False, (0, 0, 0))\n game_display.blit(textsurface, (pixel_constant * (map_info['size']['w'] + 0.2),\n 1.2*pixel_constant))\n textsurface = myfont.render(f'Points = {points}', False, (0, 0, 0))\n game_display.blit(textsurface, (pixel_constant * (map_info['size']['w'] + 0.2),\n 2.2*pixel_constant))\n return\n\n\ndef is_valid_coordinate(row: int, col: int) -> bool:\n if row >= game_map.height or row < 0:\n return False\n if col >= game_map.width or col < 0:\n return False\n return True\n\n\ndef setup_map() -> None:\n global display_width\n global display_height\n global pixel_constant\n global game_display\n global game_map\n global missing_color\n global exit_col\n global exit_row\n\n if not EVAL_MODE:\n pixel_constant = map_info['squareSize'] if map_info['squareSize'] else pixel_constant\n display_width = map_info['size']['w'] * pixel_constant\n display_height = map_info['size']['h'] * pixel_constant\n game_display = pygame.display.set_mode(\n (display_width + int(pixel_constant*2), display_height))\n\n # Map initialization\n game_map = Map(map_info['size']['w'], map_info['size']['h'])\n direction = [\"north\", \"south\", \"east\", \"west\"]\n dir_reflection = [\"south\", \"north\", \"west\", \"east\"]\n dir_reflection_xy = [(-1, 0), (1, 0), (0, 1), (0, -1)]\n\n color_count = {'blue': 0, 'red': 0, 'green': 0, 'magenta': 0, 'yellow': 0, 'cyan': 0, 'white': 0}\n\n for tile in map_info['tiles']:\n game_map.tiles[tile['row']][tile['col']].color = tile['color']\n color_count[tile['color']] += 1\n for dir_index in range(len(direction)):\n if getattr(getattr(game_map.tiles[tile['row']][tile['col']],\n direction[dir_index]), \"status\") == 0:\n setattr(getattr(game_map.tiles[tile['row']][tile['col']],\n direction[dir_index]), \"status\", tile['directions'][dir_index])\n if tile['directions'][dir_index]:\n new_row = tile['row'] + dir_reflection_xy[dir_index][0]\n new_col = tile['col'] + dir_reflection_xy[dir_index][1]\n if is_valid_coordinate(new_row, new_col):\n setattr(getattr(game_map.tiles[new_row][new_col],\n dir_reflection[dir_index]), \"status\", 1)\n for i in range(map_info['size']['w']):\n game_map.tiles[0][i].north.status = 1\n game_map.tiles[map_info['size']['h']-1][i].south.status = 1\n for i in range(map_info['size']['h']):\n game_map.tiles[i][0].west.status = 1\n game_map.tiles[i][map_info['size']['w']-1].east.status = 1\n\n for key, val in color_count.items():\n if val == 7:\n missing_color = key\n break\n\n exit_col = 0\n exit_row = 0\n\n for i in range(map_info['size']['w']):\n color_diff = set()\n color_count = {'blue': 0, 'red': 0, 'green': 0, 'magenta': 0, 'yellow': 0, 'cyan': 0, 'white': 0}\n for j in range(map_info['size']['h']):\n color_diff.add(game_map.tiles[j][i].color)\n color_count[game_map.tiles[j][i].color] += 1\n for key, val in color_count.items():\n exit_col += val == 3\n color_diff.discard('white')\n exit_col += len(color_diff) == 6\n\n for j in range(map_info['size']['h']):\n color_diff = set()\n color_count = {'blue': 0, 'red': 0, 'green': 0, 'magenta': 0, 'yellow': 0, 'cyan': 0, 'white': 0}\n for i in range(map_info['size']['w']):\n color_diff.add(game_map.tiles[j][i].color)\n color_count[game_map.tiles[j][i].color] += 1\n for key, val in color_count.items():\n exit_row += val == 3\n color_diff.discard('white')\n exit_row += len(color_diff) == 6\n\n generate_map()\n return\n\n\ndef setup_robot() -> None:\n global robot\n robot_size = 0\n if not EVAL_MODE:\n global robot_img\n global robot_blue\n global robot_red\n global robot_green\n global robot_magenta\n global robot_yellow\n global robot_cyan\n\n robot_size = int(pixel_constant * 0.5)\n robot_img = pygame.transform.scale(robot_img, (robot_size, robot_size))\n robot_blue = pygame.transform.scale(robot_blue, (robot_size, robot_size))\n robot_red = pygame.transform.scale(robot_red, (robot_size, robot_size))\n robot_green = pygame.transform.scale(robot_green, (robot_size, robot_size))\n robot_magenta = pygame.transform.scale(robot_magenta, (robot_size, robot_size))\n robot_yellow = pygame.transform.scale(robot_yellow, (robot_size, robot_size))\n robot_cyan = pygame.transform.scale(robot_cyan, (robot_size, robot_size))\n gameIcon = pygame.image.load('resources/images/roborregos_logo.PNG')\n pygame.display.set_icon(gameIcon)\n\n col = map_info['robot_start']['col']\n row = map_info['robot_start']['row']\n\n start_x = col * pixel_constant + robot_size\n start_y = row * pixel_constant + robot_size\n angle = map_info['robot_start']['w']\n dic_dir = {0: 3, 90: 0, 180: 1, 270: 2}\n direction = dic_dir[angle]\n\n robot = Robot(start_x, start_y, angle, robot_size, col, row, direction)\n robot.set_position(start_x, start_y, angle)\n return\n\n\ndef main() -> None:\n setup_map()\n setup_robot()\n with open(\"main_program.py\") as f:\n code = compile(f.read(), \"main_program.py\", 'exec')\n exec(code)\n return\n\n\nif __name__ == \"__main__\":\n if EVAL_MODE:\n print('Round start')\n main()\n print('Round end')\n\n while not crashed:\n if start:\n setup_map()\n setup_robot()\n start = False\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n crashed = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n if pos[0] < pixel_constant * 0.5 and pos[1] < pixel_constant * 0.5:\n if not reset:\n reset = True\n\n if reset:\n print('Round start')\n main()\n print('Round end')\n reset = False\n else:\n run_button = pygame.transform.scale(\n run_button, (int(pixel_constant*0.5), int(pixel_constant*0.5)))\n game_display.blit(run_button, (0, 0))\n pygame.display.update()\n clock.tick(120)\n \n if not EVAL_MODE:\n pygame.quit()\n sys.exit()","sub_path":"robotsim.py","file_name":"robotsim.py","file_ext":"py","file_size_in_byte":20348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"554097543","text":"import math\r\n## dAB = sqrt((x2 - x1)**2 + (y2- y1)**2)\r\n\r\ndef solve(coordinates):\r\n distante = 0.000000\r\n for ponto in range(len(coordinates)):\r\n x1, y1 = coordinates[ponto]\r\n j = ponto + 1\r\n while j < len(coordinates):\r\n x2, y2 = coordinates[j]\r\n d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\r\n if d > distante:\r\n distante = d\r\n j += 1\r\n return round(distante, 6)\r\n \r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n\r\n coordinates = []\r\n\r\n for _ in range(n):\r\n coordinates.append(list(map(int, input().rstrip().split())))\r\n\r\n result = solve(coordinates)\r\n\r\n print(result)\r\n","sub_path":"HackerRank/Most Distant.py","file_name":"Most Distant.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"214219703","text":"import re\nimport threading\nfrom spider.Downloader import Downloader\nfrom tools.MysqlQueue import MysqlQueue\n\nclass ParseBookId(threading.Thread):\n\n def __init__(self, url, url_queue):\n self.seen = set(url)\n self.url_queue = url_queue\n self.download = Downloader()\n self.mysql_queue = MysqlQueue()\n\n threading.Thread.__init__(self)\n\n def run(self):\n while True:\n if self.url_queue.empty():\n break\n\n url = self.url_queue.get()\n\n # 判断链接转去相应方法\n if url.startswith('http://list.jd.com/'):\n self.book_id_crawler(url)\n else:\n self.tag_link_crawler(url)\n\n self.url_queue.task_done()\n\n def tag_link_crawler(self, url):\n ''' 获取当前页面获取所有标签链接\n '''\n html = self.download(url)\n\n if self.is_exit(html):\n return\n\n # 获取标签链接\n regex = '(//list.jd.com/list.html\\?cat=[\\d,]*)'\n for link in self.get_link_list(html, regex):\n if link not in self.seen:\n self.seen.add(link)\n self.url_queue.put(self.tag_url_join(link))\n\n return\n\n def book_id_crawler(self, url):\n ''' 从当前页面获取图书id与name \n '''\n html = self.download(url)\n\n if self.is_exit(html):\n return\n\n # 获取页数\n pattern = re.compile('\\s*\\d*/(\\d*)', re.M)\n try:\n page_num = re.search(pattern, html).group(1)\n except:\n return\n\n # 从每页抓取读书id以及图书名称\n for index in range(1,int(page_num)):\n link = '{0}&page={1}'.format(url, index)\n html = self.download(link)\n\n # 在当前页面匹配书籍id与name\n regex = '
\\s*(.*?)'\n info_list = set(self.get_link_list(html, regex))\n for id, name in info_list:\n self.mysql_queue.put(id,name)\n\n return\n\n def get_link_list(self, html, regex):\n ''' 根据正则匹配页面数据 \n '''\n websit_regex = re.compile(regex, re.M)\n return websit_regex.findall(html)\n\n def page_url_join(self, link, index):\n ''' 构造url\n '''\n return '{0}&page={1}'.format(link, index)\n\n def tag_url_join(self, link):\n ''' 为爬取的链接添加 'http:'\n '''\n return 'http:{0}'.format(link)\n\n def is_exit(self, html):\n ''' 判断网页是否下载成功\n '''\n return html == None or html == ''","sub_path":"spider/ParseBookId.py","file_name":"ParseBookId.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"274319114","text":"from rungutan.authentication import auth\nfrom rungutan.send_request import send_request\nfrom rungutan.config import path\nfrom rungutan.print_format import print_message\n\n\ndef domains(subcommand, profile_name, domain_name):\n\n payload = {}\n if subcommand != \"list\":\n payload[\"domain_name\"] = domain_name\n\n domain_path = path(\"domains\", subcommand)\n\n response = send_request(\n domain_path,\n payload,\n auth(profile_name)\n )\n if response[\"success\"]:\n print_message(response[\"response_json\"])\n exit(0)\n else:\n print_message(response[\"error\"])\n exit(1)\n","sub_path":"src/rungutan/domains.py","file_name":"domains.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"218973730","text":"import sys\nfrom os.path import dirname, join\nimport numpy as np\nfrom pathlib import Path\n\nif(len(sys.argv)!=2):\n print(\"please specify the dataset to display statistics\")\n\n#change it to path to your rootdir\nPY_FASTER_RCNN_ROOTDIR='/content/pytorch-faster-rcnn/'\nPY_FASTER_RCNN_LIBDIR=PY_FASTER_RCNN_ROOTDIR + 'tools/'\n\nthis_dir = dirname(__file__)\nif __name__ == '__main__':\n sys.path.insert(0, PY_FASTER_RCNN_ROOTDIR)\n sys.path.insert(0, PY_FASTER_RCNN_LIBDIR)\n import _init_paths\n import os\n os.chdir(PY_FASTER_RCNN_ROOTDIR)\n\nnonempty=set()\n\nfrom datasets.factory import get_imdb\n\nWARNING_AMOUNT_OF_BOXES=50\n\nimdb=get_imdb(sys.argv[1])\n\nclass Image:\n\n def __init__(self):\n pass\n\ndef get_statistics(imdb):\n images=[]\n for image_id, entry in enumerate(imdb.gt_roidb()):\n lstboxes=[(entry['boxes']) ]\n lstclasses=[(entry['gt_classes']) ]\n for id,boxes in enumerate(lstboxes):\n image=Image()\n image.id=image_id\n image.bbox_dims=list()\n image.aspect_ratios=list()\n\n for item in boxes:\n image.bbox_dims.append((item[2]-item[0], item[3]-item[1]))\n image.aspect_ratios.append(float((item[2]-item[0]) / float(item[3]-item[1])))\n image.classes=lstclasses[id]\n image.boxes=boxes\n images.append(image)\n return images\n\n\n\nfilenames=list()\nnum_images = len(imdb.image_index)\nfor i in range(num_images):\n filenames.append(imdb.image_path_at(i))\n#print(filenames)\nfile_names = set()\ntimestamps=list()\nfor fname in filenames:\n file_names.add(Path(fname).name)\n timestamps.append(int(Path(fname).name.split('_')[0]))\n\n\nday_images=list()\nnight_images=list()\n\nimport datetime\n\nfor timestamp in timestamps:\n date = datetime.datetime.fromtimestamp(int(timestamp / 1000))\n if (date.hour > 7 and date.hour < 20):\n day_images.append(timestamp)\n if (not (date.hour > 7 and date.hour < 22)):\n night_images.append(timestamp)\n\nstats = get_statistics(imdb)\nwarnings=[]\nclsstats=dict()\nclsimgstats=dict()\nclsarea=dict()\n\ntotal_area=int\ntotal_non_zero_images=0\nfor im in stats:\n for cls in im.classes:\n cur_cnt=clsstats.get(cls,0)\n clsstats[cls]=cur_cnt+1\n classes_set=set(im.classes)\n for cls in classes_set:\n cur_cnt = clsimgstats.get(cls, 0)\n clsimgstats[cls] = cur_cnt + 1\n\n #print ('image size: %s x %s -> %s x %s'%(im.width,im.height, int(im.dest_width), int(im.dest_height)))\n if len(im.boxes) > WARNING_AMOUNT_OF_BOXES :\n warnings.append(\"Warning: more than %d boxes: %s\"%(WARNING_AMOUNT_OF_BOXES, str(im.id)))\n elif len(im.boxes)==0:\n warnings.append(\"Warning: zero boxes: %s\" % str(im.id))\n\n if(len(im.boxes)>0):\n total_non_zero_images=total_non_zero_images+1\n nonempty.add(Path(imdb.image_path_at(im.id)).name.split('.')[0])\n for box_idx in range(0,len(im.boxes)):\n dest_x1, dest_y1, dest_x2, dest_y2 = im.boxes[box_idx]\n aspect_ratio=im.aspect_ratios[box_idx]\n width = (dest_x2-dest_x1)\n height = (dest_y2-dest_y1)\n newlist=clsarea.get(int(im.classes[box_idx]), list())\n newlist.append(width * height)\n clsarea[im.classes[box_idx]]=newlist\n if (width <= 0 or height <= 0):\n warnings.append(\"ERROR: height or width is 0 for \"+im.filename)\n if (width*height < 10):\n warnings.append(\"Warning: contains small box: \"+im.filename)\n #print(\"bbox: \")\n #print( \" width : %d\"%(dest_x2-dest_x1))\n #print( \" height : %d\" % (dest_y2 - dest_y1))\n #print( \" aspect ratio : %.2f\"%aspect_ratio)\n\nfor msg in warnings:\n print ( 'warning:',msg)\n\nflatten = lambda l: [item for sublist in l for item in sublist]\n\ndims= flatten([im.bbox_dims for im in stats])\n\naspect_ratios = flatten([im.aspect_ratios for im in stats])\nbbox_widths = [w for w,h in dims ]\nbbox_heights = [h for w,h in dims]\n\ncls_total_area=0\n\ntotal_area=0\narea_num=0\ncls_area_mean=dict()\n\nfor ind in clsarea.keys():\n val=clsarea[ind]\n cls_total_area=0\n for area in val:\n total_area=total_area+area\n area_num=area_num+1\n cls_total_area=cls_total_area+area\n cls_area_mean[ind]=cls_total_area/len(val)\nimport math\n\n\n\nfor ind,val in enumerate(imdb._classes):\n if(not cls_area_mean.get(ind,None) is None):\n print('class mean area: '+imdb._classes[ind] + ' ' + str(math.sqrt(cls_area_mean[ind])))\n\nprint('mean area: %.2f' % (math.sqrt(total_area/area_num)))\n\nprint ('min bbox width: %.2f '%(min(bbox_widths)))\nprint ('mean bbox width: %.2f '%(np.mean(bbox_widths)))\nprint ('max bbox width: %.2f '%(max(bbox_widths)))\n\nprint ('min bbox height: %.2f '%(min(bbox_heights)))\nprint ('mean bbox height: %.2f '%(np.mean(bbox_heights)))\nprint ('max bbox height: %.2f '%(max(bbox_heights)))\n\nprint ('min aspect ratio: %.2f '%(min(aspect_ratios)))\nprint ('mean aspect ratio: %.2f '%(np.mean(aspect_ratios)))\nprint ('max aspect ratio: %.2f '%(max(aspect_ratios)))\n\nprint('number of images per class:\\n')\ntotal_img=0\nlst_imgstats=list(sorted(clsimgstats))\n\nfor cls in lst_imgstats:\n print(imdb._classes[cls]+': ' + str(clsimgstats[cls]))\n\nprint('total images: ' + str(len(imdb.gt_roidb())))\nprint('total annotated images: ' + str(total_non_zero_images))\nprint('day images: ' + str(len(day_images)))\nprint('night images: ' + str(len(night_images)))\n\n\nprint('number of annotations per class:\\n')\nlst_stats=list(sorted(clsstats))\ntotal_ann=0\nfor cls in lst_stats:\n print(imdb._classes[cls]+': ' + str(clsstats[cls]))\n total_ann=total_ann+int(clsstats[cls])\nprint('total boxes: ' + str(total_ann))\n","sub_path":"colab/imdb_analyze.py","file_name":"imdb_analyze.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"25314142","text":"import floris\nimport floris.tools as wfct\n\nimport numpy as np\n\nclass Agent():\n \"\"\"\n Agent object that encapsulates necessary turbine information \n \"\"\"\n def __init__(self, turbine, alias, coordinates):\n self.turbine = turbine\n self.alias = alias\n self.coordinates = coordinates\n return\n\ndef initialize_agent_list(fi, layout_array):\n \"\"\"\n Creates a list of agents that will be used by the environment to calculate reward\n \"\"\"\n agents = []\n layout_x = layout_array[0]\n layout_y = layout_array[1]\n\n aliases = [\"turbine_\" + str(i) for i in range(len(fi.floris.farm.turbines))]\n farm_turbines = {alias: (x,y) for alias,x,y in zip(aliases,layout_x,layout_y)}\n for i,turbine in enumerate(fi.floris.farm.turbines):\n agent = Agent(turbine, aliases[i], farm_turbines[aliases[i]])\n agents.append(agent)\n\n return agents\n\ndef create_grid(lower_bounds, upper_bounds, bins, offsets):\n \"\"\"\n Create a grid to be used with a tiling algorithm.\n\n Returns a numpy array of numpy arrays, each one representing a tiling along each dimension\n \"\"\"\n if len(lower_bounds) != len(upper_bounds) or len(bins) != len(offsets) or len(bins) != len(lower_bounds):\n raise ValueError('Grid dimensions do not agree')\n\n grid = []\n\n for lower_bound,upper_bound,bin_num,offset in zip(lower_bounds, upper_bounds, bins, offsets):\n row = np.linspace(lower_bound, upper_bound, num=bin_num) + offset\n grid.append(row)\n\n return np.array(grid)\n\ndef create_tiling(lower_bounds, upper_bounds, bins_list, offsets_list):\n \"\"\"\n Create an array of grids that can be used for tile coding. bins_list is an array of iterables that\n specify the bin numbers for each of the dimensions of each grid. offsets_list is an array of \n iterables that specify the offsets for each of the dimensions of each grid.\n\n Returns a numpy array of grids\n \"\"\"\n if len(lower_bounds) != len(upper_bounds) or len(bins_list) != len(offsets_list):\n raise ValueError('Tiling dimensions do not agree')\n\n tiling = []\n\n for bins,offsets in zip(bins_list, offsets_list):\n grid = create_grid(lower_bounds, upper_bounds, bins, offsets)\n tiling.append(grid)\n\n return np.array(tiling)\n\ndef _vectorize_digital(bin, dim):\n \"\"\"\n Write a digital bin number as a boolean array\n\n bin: bin number\n dim: length of vectorized output\n \"\"\"\n vector_output = []\n for i in range(dim):\n if i == bin:\n vector_output.append(1)\n else:\n vector_output.append(0)\n return vector_output\n\ndef encode_state(tiling, state):\n \"\"\"\n Takes a multi-dimensional state observation and enocdes it using a given tiling.\n \"\"\"\n if len(tiling[0]) != len(state):\n raise ValueError(\"State observation dimension does not match tiling dimension.\")\n\n tiling_encoding = []\n\n for grid in tiling:\n grid_encoding = []\n for i,axis in enumerate(grid):\n coding = np.digitize(state[i], axis)\n grid_encoding.append(_vectorize_digital(coding, len(axis)))\n tiling_encoding.append(grid_encoding)\n\n tiling_encoding = np.array(tiling_encoding)\n\n return np.array( np.ndarray.flatten(tiling_encoding) )","sub_path":"data_generation/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"236987040","text":"# Implementar la función mayor, que reciba tres números y devuelva el mayor de ellos.\n\ndef mayor(a, b, c):\n g=0\n if (a>b and a>c):\n g=a\n else:\n if (b>c):\n g=b\n else:\n g=c\n\n return g\nassert(mayor(600,500,400)==600)\n","sub_path":"practico_01/ejercicio-02.py","file_name":"ejercicio-02.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"135761605","text":"import socket\n\n# 1. 创建服务端socket对象\nclient = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)\n\n# 2. 连接服务端\nclient.connect(('172.25.254.197', 9995))\n\nwhile True:\n # 3.给服务端发送消息\n send_data = input('client: >> ').encode('utf-8')\n if not send_data:\n continue\n client.send(send_data)\n # 4. 接收服务端发送的消息\n recv_data = client.recv(1024).decode('utf-8')\n print(\"接收服务端发送的消息:\", recv_data)\n if recv_data == 'quit':\n break\n\n# 5. 关闭socket对象\nclient.close()\n","sub_path":"day21/05_TCP通信模拟QQ聊天/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579465679","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 17 19:13:01 2021\n@author: Provost\n@author: Jonah Kornberg Jkornberg@ufl.edu\n\"\"\"\n\n\n#Get requests\n#Get files/probabilty\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom queue import PriorityQueue\nfrom collections import deque\nfrom enum import Enum\nfrom datetime import datetime\n\n\nclass Policy(Enum):\n FIFO = 0 #First in first out\n LP = 1 #Least Popular\n BEST=2\n\n#First in first out\n#Least recently used\n#least popular\n\ndef getFileSize(a,m):\n return (np.random.pareto(a) + 1) * m\n\ndef generateRequest(mean):\n #Returns structure of\n return np.random.exponential(1/mean)\n\n#Generate files \n\n\nclass Cache:\n def __init__(self,eventQueue,size, accessLink, receiver, files, fileProbabilities, settings, policy=Policy.FIFO, generateRequest = True):\n self.eventQueue = eventQueue\n self.size = size\n self.accessLink = accessLink\n self.receiver = receiver\n self.files = files\n self.fileProbabilities = fileProbabilities\n self.institutionSpeed = settings['institutionSpeed']\n self.roundTripTime = settings['roundTripTime']\n self.requestPerSecond = settings['requestPerSecond']\n self.stopTime = settings['stopTime']\n self.numberOfFiles = settings['numberOfFiles']\n self.fileIds = set()\n self.used = 0\n self.cacheQueue = deque()\n self.cacheQueue.clear()\n self.popularity = {} #{fileId: (popularity, size)}\n self.generateRequest = generateRequest #For whether using same requests or not\n if not isinstance(policy, Policy):\n self.policy = Policy.FIFO\n print(\"Invalid policy, defaulting to FIFO\")\n else:\n self.policy = policy\n\n def clear(self):\n self.cacheQueue.clear()\n self.fileIds.clear()\n self.popularity = {}\n self.used = 0\n\n def checkCache(self,time,fileId,fileSize):\n if fileId in self.fileIds:\n #(eventTime, function, (args))\n self.eventQueue.put((time+fileSize/self.institutionSpeed,self.receiver.receivedEvent,(time,)))\n else:\n #Generate arrive at queue event\n self.eventQueue.put((time+self.roundTripTime, self.accessLink.arriveFifo,(time, fileId,fileSize)))\n self.createRequest(time)\n \n def createRequest(self,callTime):\n if self.generateRequest:\n if(callTime < self.stopTime):\n fileId = np.random.choice(np.arange(self.numberOfFiles), p=self.fileProbabilities)\n time = np.random.exponential(1/self.requestPerSecond) + callTime\n event = (time, self.checkCache, (fileId, self.files[fileId][0])) #Format: (time, func, (func args))\n self.eventQueue.put(event)\n \n def replace(self, fileId,fileSize):\n if (self.policy == Policy.FIFO):\n self.replaceFIFO(fileId,fileSize)\n elif (self.policy == Policy.LP):\n self.replaceLeastPopular(fileId,fileSize)\n elif (self.policy == Policy.BEST):\n self.replaceBestFit(fileId,fileSize)\n else:\n print(\"INVALID POLICY, NOT ADDING FILE\")\n\n\n def replaceFIFO(self,fileId,fileSize):\n if (fileSize > self.size):\n print(\"FILE TOO LARGE FOR CACHE\")\n return\n if(fileId in self.fileIds): #If it was added before event executed\n return\n while(self.used + fileSize > self.size):\n # print(f\"Replacing: {fileId}\")\n removed = self.cacheQueue.popleft()\n self.used -= removed[1]\n try:\n self.fileIds.remove(removed[0])\n except:\n print(removed)\n self.receiver.addRemoved(removed[0])\n\n self.fileIds.add(fileId)\n self.used += fileSize\n self.cacheQueue.append((fileId,fileSize))\n\n def activeFile(self, item):\n if item[0] in self.fileIds:\n return True\n return False\n\n def replaceLeastPopular(self,fileId,fileSize):\n if(fileId in self.fileIds): #If it was added before event executed\n self.popularity[fileId][0] += 1\n return\n filtered = filter(self.activeFile, self.popularity.items())\n sortedFiles = sorted(filtered, key=lambda x: x[1][0])\n i = 0\n if (fileSize > self.size):\n print(\"FILE TOO LARGE FOR CACHE\")\n return \n while (self.used + fileSize > self.size):\n # print(f\"Replacing: {fileId}\")\n removed = sortedFiles[i]\n #print(f\"Replacing: {removed[0], removed[1][0]}\")\n self.used -= removed[1][1]\n self.fileIds.remove(removed[0])\n i += 1\n self.receiver.addRemoved(removed[0])\n\n\n self.fileIds.add(fileId)\n self.used += fileSize\n if fileId in self.popularity:\n self.popularity[fileId][0] += 1\n else:\n self.popularity[fileId] = [1,fileSize]\n \n def replaceBestFit(self,fileId,fileSize):\n if(fileId in self.fileIds): #If it was added before event executed\n return\n filtered = filter(self.activeFile, self.popularity.items())\n sortedFiles = sorted(filtered, key=lambda x: x[1][1], reverse=True)\n i = 0\n if (fileSize > self.size):\n print(\"FILE TOO LARGE FOR CACHE\")\n return\n enoughSpace = False\n i = 0\n while (self.used + fileSize > self.size):\n if (sortedFiles[i][1][1] >= fileSize):\n j = i + 1\n while ( j < len(sortedFiles) and sortedFiles[j][1][1] >= fileSize):\n i = j\n j += 1\n removed = sortedFiles[i]\n self.used -= removed[1][1]\n self.fileIds.remove(removed[0])\n else:\n removed = sortedFiles[i]\n self.used -= removed[1][1]\n self.fileIds.remove(removed[0])\n i += 1\n self.receiver.addRemoved(removed[0])\n\n self.popularity[fileId] = [0,fileSize]\n self.fileIds.add(fileId)\n self.used += fileSize\n \n\nclass AccessLink:\n\n def __init__(self,eventQueue, receiver, settings):\n self.eventQueue = eventQueue\n self.receiver = receiver\n self.roundTripTime = settings['roundTripTime']\n self.institutionSpeed = settings['institutionSpeed']\n self.accessSpeed = settings['accessSpeed']\n self.fifoQueue = deque()\n self.fifoQueue.clear()\n self.cache = None\n\n def arriveFifo(self,time, requestTime, fileId, fileSize):\n #print(f'arrive: {requestTime}')\n if (not self.fifoQueue): #Checks if fifoQueue is empty\n self.eventQueue.put((time+fileSize/self.accessSpeed, self.departFifo, (requestTime,))) \n self.fifoQueue.append((fileId, fileSize, requestTime))\n #TODO: handle when request is in Access Link FIFO\n def departFifo(self,time,requestTime):\n f = self.fifoQueue.popleft() #File is (fileId,fileSize,requestTime)\n fileId = f[0]\n fileSize = f[1]\n requestTime = f[2]\n self.cache.replace(fileId,fileSize)\n receiveTime = time + fileSize/self.institutionSpeed\n self.eventQueue.put((receiveTime, self.receiver.receivedEvent, (requestTime,)))\n if(self.fifoQueue): #if queue is not empty\n _, fileSize, requestTime = self.fifoQueue[0]\n self.eventQueue.put((time+fileSize/self.accessSpeed,self.departFifo, (requestTime,)))\n def clear(self):\n self.fifoQueue.clear()\n\nclass Receiver: \n def __init__(self):\n self.requestTimes = np.array([])\n self.turnaround =np.array([])\n self.removed = np.array([])\n def receivedEvent(self,time,requestTime):\n self.requestTimes = np.append(self.requestTimes,requestTime)\n self.turnaround = np.append(self.turnaround,time)\n def clear(self):\n self.requestTimes = np.array([])\n self.turnaround = np.array([])\n self.removed = np.array([])\n \n def addRemoved(self, fileId):\n self.removed = np.append(self.removed,fileId)\n\n\n\ndef runSimulation(policy=Policy.FIFO):\n def processQueue():\n event = eventQueue.get()\n time = event[0]\n fun = event[1]\n if (len(event) > 2):\n fun(time, *event[2]) \n else:\n fun(time)\n \n files = {} #key value pairs of {fileId: (fileSize,fileProbability)}\n #Variables\n a, m = 8/7,1/8\n cacheSize = 500 #Average file size is 1, so this is 20% of total files\n numberOfFiles = 10000\n results = []\n settings = {'roundTripTime' : 0.4, 'institutionSpeed': 100, \n 'accessSpeed' : 15, 'requestPerSecond' : 10,\n 'stopTime' : 100, 'numberOfFiles': numberOfFiles}\n\n #Generate fileset\n q = []\n a = 2\n b = 1/2\n for i in range(numberOfFiles):\n q.append((np.random.pareto(a) + 1) * b)\n probSum = sum(q)\n fileProbabilities = np.array(q)/probSum\n for i in range(numberOfFiles):\n fileSize = (np.random.pareto(a) + 1) * b\n files[i] = (fileSize,fileProbabilities[i])\n\n receiver = Receiver()\n eventQueue = PriorityQueue()\n if (not eventQueue.empty):\n print(\"Event Queue not empty, leftover data in queue\")\n accessLink = AccessLink(eventQueue,receiver, settings)\n cache = Cache(eventQueue,cacheSize,accessLink,receiver, files, fileProbabilities,settings, policy=policy)\n cache.fileIds.clear()\n accessLink.cache = cache\n\n #r = RoundTrip(roundTripTime)\n\n #Create initial request\n cache.createRequest(0)\n #Run the simulation\n while(not eventQueue.empty()):\n #Stop is based on time, after stoptime new requests aren't generated\n processQueue()\n x, y = receiver.requestTimes, receiver.turnaround\n del receiver\n del cache\n del eventQueue\n del accessLink\n return x, y\n\n\n\n \n#Evaluate results\n#plt.scatter(receiver.requestTimes,receiver.turnaround)\n#print(f\"Average: {np.average(receiver.turnaround)}\")\n\ndef runIndividual():\n plt.clf()\n print(\"***********************\")\n\n fifoX = np.array([])\n fifoY = np.array([])\n for j in range(1000):\n fX, fY = runSimulation(policy=Policy.FIFO)\n #print(np.sum(fY))\n fifoX = np.append(fifoX, np.average(fX))\n fifoY = np.append(fifoY, np.average(fY))\n print(f'Average fifo: {np.average(fifoY)}')\n plt.scatter(np.arange(1000),fifoY)\n\n print(\"***********************\")\n\n\n lX = np.array([])\n lY = np.array([])\n for j in range(1000):\n x, y = runSimulation(policy=Policy.BEST)\n #print(np.sum(y))\n lX = np.append(lX, np.average(x))\n lY = np.append(lY, np.average(y))\n print(f'Average Best: {np.average(lY)}')\n plt.scatter(np.arange(1000),lY)\n\n print(\"***********************\")\n\n fifoX = np.array([])\n fifoY = np.array([])\n for j in range(1000):\n fX, fY = runSimulation(policy=Policy.LP)\n #print(np.sum(fY))\n fifoX = np.append(fifoX, np.average(fX))\n fifoY = np.append(fifoY, np.average(fY))\n print(f'Average fifo: {np.average(fifoY)}')\n plt.scatter(np.arange(1000),fifoY)\n\n\n\ndef runAllSimulations(count = 1):\n def processQueue():\n event = eventQueue.get()\n time = event[0]\n fun = event[1]\n if (len(event) > 2):\n fun(time, *event[2]) \n else:\n fun(time)\n \n allRequestTimes = np.zeros([0])\n allTurnarounds = np.zeros([3,0])\n allRemoved = [0] * 3\n for i in range(count):\n\n files = {} #key value pairs of {fileId: (fileSize,fileProbability)}\n a, m = 8/7,1/8\n cacheSize = 1000 #Average file size is 1, so this is 20% of total files\n numberOfFiles = 50000\n results = []\n settings = {'roundTripTime' : 0.4, 'institutionSpeed': 100, \n 'accessSpeed' : 15, 'requestPerSecond' : 10,\n 'stopTime' : 100, 'numberOfFiles': numberOfFiles}\n totalRequests = 100000\n \n #Generate fileset\n q = []\n a = 2\n b = 1/2\n for i in range(numberOfFiles):\n q.append((np.random.pareto(a) + 1) * b)\n probSum = sum(q)\n fileProbabilities = np.array(q)/probSum\n for i in range(numberOfFiles):\n fileSize = (np.random.pareto(a) + 1) * b\n files[i] = (fileSize,fileProbabilities[i])\n receiver = Receiver()\n eventQueue = PriorityQueue()\n requestTimes = np.zeros(totalRequests)\n requestTimes[0] = np.random.exponential(1/settings['requestPerSecond'])\n for i in range(len(requestTimes[1:])):\n requestTimes[i] = np.random.exponential(1/settings['requestPerSecond']) + requestTimes[i-1]\n requestFiles = np.random.choice(np.arange(numberOfFiles),size=totalRequests, p=fileProbabilities)\n accessLink = AccessLink(eventQueue,receiver, settings)\n turnArounds = np.zeros((3,totalRequests))\n #requestTimes = np.zeros((3,totalRequests))\n for i,p in enumerate(Policy):\n receiver.clear()\n accessLink.clear()\n cache = Cache(eventQueue,cacheSize,accessLink,receiver, files, fileProbabilities,settings, policy=p, generateRequest=False)\n cache.clear()\n accessLink.cache = cache\n #Create initial request\n for t,f in np.stack((requestTimes,requestFiles),axis=1):\n event = (t, cache.checkCache, (f, files[f][0])) #Format: (time, func, (func args))\n eventQueue.put(event)\n while(not eventQueue.empty()):\n #Stop is based on time, after stoptime new requests aren't generated\n processQueue()\n x,y,r = receiver.requestTimes, receiver.turnaround, receiver.removed\n turnArounds[i] = y\n allRemoved[i] = r\n # requestTimes[i] = y\n del receiver\n del cache\n del eventQueue\n del accessLink\n allTurnarounds = np.concatenate((allTurnarounds, turnArounds), axis=1)\n allRequestTimes = np.concatenate((allRequestTimes, requestTimes))\n return (allTurnarounds, allRequestTimes)\n\n \nFinishes, Requests = runAllSimulations()\nfor i,p in enumerate(Policy):\n print(f'Average {p}: {np.average(Finishes[i]-Requests)}')\n ","sub_path":"ServerSim.py","file_name":"ServerSim.py","file_ext":"py","file_size_in_byte":14341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"483023275","text":"from datetime import datetime as dt\nfrom sqlalchemy.exc import DBAPIError\nfrom sqlalchemy.orm import relationship\nfrom .meta import Base\nfrom ..views.nltk_logic import analyze\n\n# from .associations import portfolios_associations\nimport json\n \nfrom sqlalchemy import (\n Column,\n Index,\n Integer,\n Text,\n DateTime,\n ForeignKey,\n String,\n cast,\n JSON,\n)\n\n\nclass NLTKOutput(Base):\n \"\"\" Create the nltk table\n \"\"\"\n __tablename__ = 'nltk_output'\n id = Column(Integer, primary_key=True)\n nltk_result = Column(JSON)\n account_id = Column(Integer, ForeignKey('accounts.id'), nullable=False)\n accounts = relationship('Account', cascade=\"all, delete\", back_populates='nltk_output')\n date_created = Column(DateTime, default=dt.now())\n date_updated = Column(DateTime, default=dt.now(), onupdate=dt.now())\n\n @classmethod\n def new(cls, request, **kwargs):\n \"\"\" Create a new nltk analysis\n \"\"\"\n if request.dbsession is None:\n raise DBAPIError\n unmodified_obj = analyze(kwargs['text'])\n mod_sent = {}\n for sent in unmodified_obj['Sentences']:\n mod_sent[sent] = unmodified_obj['Sentences'][sent][1]\n mod_obj = {'Sentences': mod_sent, 'Body': unmodified_obj['Body']}\n kwargs['nltk_result'] = json.dumps(mod_obj)\n kwargs.pop('text', None)\n\n # fake_obj = {\"account_id\": 1, \"nltk_result\": json.dumps(['string'])}\n nltk = cls(**kwargs)\n # nltk = cls(**fake_obj)\n request.dbsession.add(nltk)\n # request.dbsession.flush()\n return [request.dbsession.query(cls).filter(\n cast(cls.nltk_result, String) == kwargs['nltk_result']).one_or_none(), \n unmodified_obj]\n\n @classmethod\n def all(cls, request):\n \"\"\"List all the results\n \"\"\"\n if request.dbsession is None:\n raise DBAPIError\n\n return request.dbsession.query(cls).all()\n\n @classmethod\n def one(cls, request, pk=None):\n \"\"\"List one of the results\n \"\"\"\n if request.dbsession is None:\n raise DBAPIError\n return request.dbsession.query(cls).get(pk)\n\n @classmethod\n def remove(cls, request=None, pk=None):\n \"\"\" Remove a users nltk anaylsis from the db\n \"\"\"\n if request.dbsession is None:\n raise DBAPIError\n\n return request.dbsession.query(cls).filter(cls.account_id == pk).delete()","sub_path":"dasa/dasa/models/nltk_output.py","file_name":"nltk_output.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"163384996","text":"import numpy as np\nimport pandas as pd\nimport logging\nfrom pathlib import Path\nimport os\nimport pickle\nimport sys\nfrom tqdm import tqdm\n\nfrom hfnet.datasets import get_dataset\nfrom hfnet.evaluation.utils import db_management\nfrom hfnet.evaluation.utils.descriptors import topk_matching\nfrom hfnet.evaluation.utils.db_management import (\n read_query_list,\n extract_query,\n build_localization_dbs,\n colmap_image_to_pose,\n)\nfrom hfnet.evaluation.utils.localization import (\n covis_clustering,\n match_against_place,\n do_pnp,\n preprocess_globaldb,\n preprocess_localdb,\n loc_failure,\n LocResult,\n)\nfrom hfnet.evaluation.localization import Localization\nfrom hfnet.datasets.colmap_utils.read_model import read_model\nfrom hfnet.evaluation.cpp_localization import CppLocalization\nfrom hfnet.utils.tools import Timer\nfrom hfnet.settings import DATA_PATH\nfrom QUT.util.Traverse import Traverse\nfrom QUT.evaluation.utils.descriptors import topk_matching_gps, retrieve_indices\n\nsys.modules[\"hfnet.evaluation.db_management\"] = db_management # backward comp\n\n\nclass LocalizationOpt(Localization):\n def __init__(self, dataset_name, model_name, config, build_db=False):\n super().__init__(dataset_name, model_name, config, build_db=build_db)\n # load GPS data for reference\n if dataset_name == \"robotcar\":\n traverse = \"overcast-reference\"\n self.gps = Traverse(dataset_name, traverse, config[\"global\"][\"experiment\"])\n\n def init_queries(self, query_file, query_config, prefix=\"\"):\n queries = read_query_list(Path(self.base_path, query_file), prefix=prefix)\n Dataset = get_dataset(query_config.get(\"name\", self.dataset_name))\n query_config = {**query_config, \"image_names\": [q.name for q in queries]}\n query_dataset = Dataset(**query_config)\n # load GPS data for queries\n query_gps = Traverse(self.dataset_name, self.config[\"queries\"],\n self.gps.experiment_name)\n return queries, query_dataset, query_gps\n\n def localize(self, query_info, query_data, query_gps, debug=False):\n config_global = self.config[\"global\"]\n config_local = self.config[\"local\"]\n config_pose = self.config[\"pose\"]\n timings = {}\n\n # Fetch data\n query_item = extract_query(query_data, query_info, config_global, config_local)\n\n # C++ backend\n if self.use_cpp:\n assert not debug\n assert hasattr(self, \"cpp_backend\")\n return self.cpp_backend.localize(\n query_info, query_item, self.global_transform, self.local_transform\n )\n\n # Global matching\n with Timer() as t:\n global_desc = self.global_transform(\n query_item.global_desc[np.newaxis])[0]\n splits = query_info.name.split(\"/\")\n query_attr = query_gps.query_attr(splits[1], int(splits[2][:-4]))\n if self.config[\"num_nearest\"] > 0:\n distractors = self.gps.retrieve_distractors(\n query_attr, self.config[\"num_distractors\"])\n nearest = self.gps.kNN(query_attr[\"pose\"],\n self.config[\"num_nearest\"],\n self.config[\"imperfect\"])\n relevant_cameras = nearest + distractors\n else:\n relevant_cameras = self.gps.topk_descriptors(\n query_attr, self.config[\"num_distractors\"])\n indices = retrieve_indices(self.dataset_name,\n self.db_names, relevant_cameras)\n prior_ids = self.db_ids[indices]\n timings[\"global\"] = t.duration\n\n # Clustering\n with Timer() as t:\n clustered_frames = covis_clustering(prior_ids, self.local_db, self.points)\n local_desc = self.local_transform(query_item.local_desc)\n timings[\"covis\"] = t.duration\n\n # Iterative pose estimation\n dump = []\n results = []\n timings[\"local\"], timings[\"pnp\"] = 0, 0\n for place in clustered_frames:\n # Local matching\n matches_data = {} if debug else None\n matches, place_lms, duration = match_against_place(\n place,\n self.local_db,\n local_desc,\n config_local[\"ratio_thresh\"],\n do_fast_matching=config_local.get(\"fast_matching\", True),\n debug_dict=matches_data,\n )\n timings[\"local\"] += duration\n\n # PnP\n if len(matches) > 3:\n with Timer() as t:\n matched_kpts = query_item.keypoints[matches[:, 0]]\n matched_lms = np.stack(\n [self.points[place_lms[i]].xyz for i in matches[:, 1]]\n )\n result, inliers = do_pnp(\n matched_kpts, matched_lms, query_info, config_pose\n )\n timings[\"pnp\"] += t.duration\n else:\n result = loc_failure\n inliers = np.empty((0,), np.int32)\n\n results.append(result)\n if debug:\n dump.append(\n {\n \"query_item\": query_item,\n \"prior_ids\": prior_ids,\n \"places\": clustered_frames,\n \"matching\": matches_data,\n \"matches\": matches,\n \"inliers\": inliers,\n }\n )\n if result.success:\n break\n\n # In case of failure we return the pose of the first retrieved prior\n if not result.success:\n result = results[0]\n result = LocResult(\n False,\n result.num_inliers,\n result.inlier_ratio,\n colmap_image_to_pose(self.images[prior_ids[0]]),\n )\n\n if debug:\n debug_data = {\n **(dump[-1 if result.success else 0]),\n \"index_success\": (len(dump) - 1) if result.success else -1,\n \"dumps\": dump,\n \"results\": results,\n \"timings\": timings,\n }\n return result, debug_data\n else:\n return result, {\"timings\": timings}\n\n\ndef evaluate(loc, queries, query_dataset, query_gps, max_iter=None):\n results = []\n all_stats = []\n query_iter = query_dataset.get_test_set()\n\n for query_info, query_data in tqdm(zip(queries, query_iter), total=len(queries)):\n result, stats = loc.localize(query_info, query_data, query_gps, debug=False)\n results.append(result)\n all_stats.append(stats)\n\n if max_iter is not None:\n if len(results) == max_iter:\n break\n\n success = np.array([r.success for r in results])\n num_inliers = np.array([r.num_inliers for r in results])\n ratios = np.array([r.inlier_ratio for r in results])\n\n metrics = {\n \"success\": np.mean(success),\n \"inliers\": np.mean(num_inliers[success]),\n \"inlier_ratios\": np.mean(ratios[success]),\n \"failure\": np.arange(len(success))[np.logical_not(success)],\n }\n metrics = {k: v.tolist() for k, v in metrics.items()}\n metrics[\"all_stats\"] = all_stats\n return metrics, results\n","sub_path":"QUT/evaluation/localizationOpt.py","file_name":"localizationOpt.py","file_ext":"py","file_size_in_byte":7391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"262256244","text":"metadata = {\n 'protocolName': 'Transfer Small Molecules [3/7]',\n 'author': 'Chaz ',\n 'source': 'Custom Protocol Request',\n 'apiLevel': '2.9'\n}\n\n\ndef run(protocol):\n [mnt20, numPlates] = get_values( # noqa: F821\n 'mnt20', 'numPlates')\n\n # load labware\n tips = [\n protocol.load_labware(\n 'opentrons_96_tiprack_20ul', s) for s in [4, 7, 10]\n ]\n\n m20 = protocol.load_instrument('p20_multi_gen2', mnt20, tip_racks=tips)\n\n srcPlate = protocol.load_labware('thermofast_96_wellplate_200ul', '5')\n finalPlates = [\n protocol.load_labware(\n 'spl_96_wellplate_200ul_flat', s) for s in [1, 2, 3]\n ][:numPlates]\n\n for plate in finalPlates:\n for src, dest in zip(srcPlate.rows()[0][:10], plate.rows()[0][:10]):\n m20.transfer(1, src, dest, mix_before=(5, 10))\n","sub_path":"protocols/1adec6-3/1adec6-3.ot2.apiv2.py","file_name":"1adec6-3.ot2.apiv2.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"447584875","text":"# construct a binary tree of depth d = 12\r\nfrom statistics import mode\r\n\r\nimport numpy as np\r\nimport random\r\nfrom collections import defaultdict\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\ndistribution = []\r\n\r\n\r\nclass MCTS:\r\n def __init__(self, ucb_c=10):\r\n self.Q = defaultdict(int) # total reward of each node\r\n self.N = defaultdict(int) # total visit count for each node\r\n self.explored_nodes = dict()\r\n self.ucb_c = ucb_c\r\n\r\n def choose_successor(self, node): # choose the best node successor\r\n if node.is_terminal():\r\n raise RuntimeError(f\"choose called on terminal node {node}\")\r\n\r\n if node not in self.explored_nodes:\r\n return node.get_random_child()\r\n\r\n return self.uct_select(node)\r\n\r\n def do_rollout(self, node): # train for one iteration\r\n path = self.select(node)\r\n leaf = path[-1]\r\n self.expand(leaf)\r\n reward = self.simulate(leaf)\r\n self.backup(path, reward)\r\n\r\n def select(self, node): # find an unexplored descendent of the node\r\n path = []\r\n while True:\r\n path.append(node)\r\n if node not in self.explored_nodes or node.is_terminal():\r\n return path\r\n unexplored_nodes = self.explored_nodes[node] - self.explored_nodes.keys()\r\n if unexplored_nodes:\r\n n = unexplored_nodes.pop()\r\n path.append(n)\r\n return path\r\n node = self.uct_select(node)\r\n\r\n def expand(self, node): # add children in the explored nodes of the node\r\n if node in self.explored_nodes: # already expanded\r\n return\r\n self.explored_nodes[node] = node.get_children()\r\n\r\n def simulate(self, node): # returns node reward for a random simulation\r\n while not node.is_terminal():\r\n node = node.get_random_child()\r\n reward = node.reward()\r\n return reward\r\n\r\n def backup(self, path, reward): # send the reward back\r\n for node in reversed(path):\r\n self.Q[node] += reward\r\n self.N[node] += 1\r\n\r\n def uct_select(self, node): # when all children are already expanded\r\n def uct(n):\r\n return self.Q[n] / self.N[n] + self.ucb_c * math.sqrt(\r\n math.log(self.N[node]) / self.N[n])\r\n\r\n return max(self.explored_nodes[node], key=uct)\r\n\r\n\r\nclass Node:\r\n\r\n def __init__(self, info):\r\n\r\n self.left = None\r\n self.right = None\r\n self.info = info\r\n\r\n def insert_layer(self, is_last_layer):\r\n if self.left is None:\r\n self.insert_left_right(is_last_layer)\r\n else:\r\n self.left.insert_layer(is_last_layer)\r\n self.right.insert_layer(is_last_layer)\r\n\r\n def insert_left_right(self, ill):\r\n if ill == 0:\r\n self.left = Node(0)\r\n self.right = Node(0)\r\n else:\r\n x = np.random.uniform(0,100)\r\n y = np.random.uniform(0,100)\r\n self.left = Node(x)\r\n self.right = Node(y)\r\n distribution.append(x)\r\n distribution.append(y)\r\n\r\n def get_children(self):\r\n if self.is_terminal():\r\n return set()\r\n return {\r\n self.left,\r\n self.right\r\n }\r\n\r\n def get_random_child(self):\r\n if self.is_terminal():\r\n return None\r\n return random.choice([self.left, self.right])\r\n\r\n def is_terminal(self):\r\n if self.left is None:\r\n return True\r\n return False\r\n\r\n def reward(self):\r\n return self.info\r\n\r\n def print_tree(self):\r\n print(self.info, end =\" \")\r\n if self.left:\r\n self.left.PrintTree()\r\n if self.right:\r\n self.right.PrintTree()\r\n\r\n\r\n# create the tree\r\nroot = Node(0)\r\nfor i in range(11):\r\n root.insert_layer(0)\r\nroot.insert_layer(1)\r\n\r\n\r\n# mcts search, repeat and collect the returns, find the max\r\nmcts_results = []\r\nfor _ in range(50):\r\n tree = MCTS()\r\n current_root = root\r\n while not current_root.is_terminal():\r\n for _ in range(5):\r\n tree.do_rollout(current_root)\r\n current_root = tree.choose_successor(current_root)\r\n mcts_results.append(current_root.info)\r\n\r\nprint(\"Mcts results: \", mcts_results)\r\nprint(\"Max mcts: \", max(mcts_results))\r\nprint(\"Max of the distribution: \", max(distribution))\r\n\r\nplt.plot(mcts_results, label=\"MCTS results\")\r\nmean = np.mean(mcts_results)\r\nmode = mode(mcts_results)\r\nprint(mean)\r\nprint(mode)\r\nx_coordinates = [0, 50]\r\ny_coordinates = [mean, mean]\r\nplt.plot(x_coordinates, y_coordinates, label=\"average MCTS\")\r\ny_coordinates = [mode, mode]\r\nplt.plot(x_coordinates, y_coordinates, label=\"mode MCTS\")\r\nplt.legend()\r\nplt.show()","sub_path":"mcts.py","file_name":"mcts.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"209509429","text":"import hc\nimport vm\n\nhatch = \"\"\"\nimport io;\n\nfunction int main() {\n let int i = 0;\n while (i < 5) {\n io.print(i);\n i = i + 1;\n }\n while (i >= 1) {\n io.print(i);\n i = i - 1;\n }\n}\n\"\"\"\n\ndef test_while():\n instructions = hc.compile(hatch)\n \n virtual_machine = vm.OctoEngine(True)\n virtual_machine.load(instructions)\n output = virtual_machine.run()\n assert output == [i for i in range(0, 5)] + [i for i in range(1, 6)][::-1]","sub_path":"tests/test_while.py","file_name":"test_while.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"571121557","text":"@y.singleton\ndef is_debug():\n return 'debug' in y.config.get('make', '')\n\n\ndef run_makefile(mk, targets, threads, pre_run=[], naked=False, keep_going=False):\n y.cheet(mk)\n\n if pre_run:\n run_par_build(mk.select_targets(pre_run), 1, False, naked, keep_going)\n\n if targets:\n mk = mk.select_targets(targets)\n\n return run_par_build(mk, threads, True, naked, keep_going)\n\n\nclass Builder(object):\n def __init__(self, mk, threads, check, naked, keep_going):\n self.check = check\n self.mk = mk\n self.keep_going = keep_going\n self.naked = naked\n self.threads = threads\n self.lst = [item_factory(x, self, n) for n, x in enumerate(mk.lst)]\n\n by_dep = {}\n\n for x in self.lst:\n for d in x.deps1:\n by_dep[d] = x\n\n for k in by_dep.keys():\n self.resolve_path(k)\n\n self.by_dep = by_dep\n\n @property\n def shell_vars(self):\n return self.mk.flags\n\n @y.cached_method\n def resolve_path(self, d):\n return y.subst_vars(self.mk.strings[d], self.shell_vars)\n\n def runner(self, item):\n item.run_cmd()\n\n return item\n\n def iter_data(self):\n yield from self.lst\n\n lstl = len(self.lst)\n deps = sum([x.deps1 for x in self.lst], [])\n\n class ItemAll(object):\n @property\n def n(self):\n return {'deps1': self.deps1, 'deps2': self.deps2, 'cmd': []}\n\n @property\n def my_name(self):\n return '_all'\n\n @property\n def deps1(self):\n return [self.num]\n\n @property\n def deps2(self):\n return deps\n\n @property\n def num(self):\n return lstl + 100000\n\n def run_cmd(self):\n y.build_results({\n 'status': 'fini',\n 'message': 'build complete',\n 'target': self.my_name,\n })\n\n return 0\n\n yield ItemAll()\n\n def producer(self, inq):\n rq, wq = y.make_engine(self.iter_data(), lambda x: x.deps1[0], dep_list=lambda x: sorted(frozenset(x.deps2)))\n by_n = {}\n cnt = len(self.lst) + 1\n\n while cnt:\n for el in rq():\n item = el['x']\n assert item.num not in by_n\n by_n[item.num] = el\n\n yield item\n\n for ready in inq:\n wq(by_n.pop(ready.num)['i'])\n cnt -= 1\n\n break\n\n def run(self):\n pq = y.ProducerQueue(self.threads, self.producer, self.runner)\n pq.run()\n\n\ndef item_factory(n, p, i):\n if n.get('cmd'):\n return Item(n, p, i)\n\n return ItemBase(n, p, i)\n\n\nclass ItemBase(object):\n def __init__(self, n, p, i):\n self.n = n\n self.p = p\n self.i = i\n\n def __str__(self):\n return y.json.dumps(self.__json__(), sort_keys=True)\n\n def __json__(self):\n return {\n 'num': self.num,\n 'cmd': self.cmd,\n 'output': self.deps1[0],\n 'inputs': self.deps2,\n 'id': id(self),\n }\n\n @property\n def check(self):\n return self.p.check\n\n @property\n def num(self):\n return self.i\n\n @property\n def my_name(self):\n return ', '.join(self.str_deps1)\n\n @property\n def deps1(self):\n return self.n['deps1']\n\n @property\n def str_deps1(self):\n return self.p.mk.nums_to_str(self.deps1)\n\n @property\n def deps2(self):\n return self.n.get('deps2', [])\n\n @property\n def str_deps2(self):\n return self.p.mk.nums_to_str(self.deps2)\n\n @property\n def cmd(self):\n return self.n.get('cmd', [])\n\n @property\n def str_cmd(self):\n return self.p.mk.nums_to_str(self.cmd)\n\n @property\n def resolve_path(self):\n return self.p.resolve_path\n\n def run_cmd(self):\n return 0\n\n\nclass Item(ItemBase):\n def __init__(self, n, p, i):\n ItemBase.__init__(self, n, p, i)\n\n assert self.cmd\n\n self.path = list(self.iter_search_path())\n self.shell = self.find_shell()\n assert self.shell\n self.env = self.prepare_env()\n\n def __json__(self):\n res = ItemBase.__json__(self)\n\n res.update({\n 'shell': self.shell,\n 'env': self.env,\n })\n\n return res\n\n @property\n def shell_vars(self):\n return self.p.shell_vars\n\n def prepare_env(self):\n def iter_env():\n yield 'OUTER_SHELL', self.shell\n yield from y.fix_shell_vars(self.shell_vars)\n yield 'PATH', y.os.environ['PATH']\n\n return dict(iter_env())\n\n def find_tool(self, tool):\n if tool[0] == '/':\n return tool\n\n return y.find_tool_cached(tool, self.path)\n\n def iter_search_path(self):\n for d in self.deps2:\n yield y.os.path.join(y.os.path.dirname(self.resolve_path(d)), 'bin')\n\n yield from y.os.environ['PATH'].split(':')\n\n def find_shell(self):\n if '$YSHELL' in self.shell_vars:\n shell = self.find_tool(self.shell_vars['$YSHELL'])\n\n if shell:\n return shell\n\n raise Exception('can not find ' + self.shell_vars['$YSHELL'])\n\n return self.find_tool('dash') or self.find_tool('yash') or self.find_tool('bash') or self.find_tool('sh')\n\n def build_cmd(self):\n env = self.env\n\n def iter_cmd():\n yield 'set -e'\n yield 'set -x'\n\n for k in sorted(env, key=lambda x: -len(x)):\n yield 'export {k}={v}'.format(k=k, v=env[k])\n\n yield 'mainfun() {'\n\n for l in self.str_cmd:\n yield l\n\n yield '}'\n yield 'mainfun ' + ' '.join(y.itertools.chain(self.str_deps1, self.str_deps2))\n\n input = '\\n'.join(iter_cmd()) + '\\n'\n input = input.replace('$(SHELL)', '$YSHELL')\n\n return input\n\n def check_results(self):\n for x in self.deps1:\n x = self.resolve_path(x)\n\n try:\n assert y.os.path.isfile(x)\n except Exception as e:\n raise Exception(x + ' not exists: ' + str(e))\n\n def check_done(self):\n try:\n self.check_results()\n\n return True\n except Exception:\n pass\n\n return False\n\n def run_cmd(self):\n target = self.my_name\n\n if self.check_done():\n y.build_results({\n 'message': 'use cached {target}',\n 'status': 'done',\n 'target': target,\n })\n\n return 0\n\n y.build_results({\n 'message': 'starting {target}',\n 'status': 'init',\n 'target': target,\n })\n\n retcode, res, input = self.run_cmd_0()\n\n def iter_lines():\n bdir = ''\n\n for l in res.strip().split('\\n'):\n if 'export ' in l:\n if 'BDIR' in l:\n bdir = l.split('=')[1]\n\n if bdir:\n yield 'run {by}cli debug ' + bdir + '{}'\n\n msg = {\n 'output': '\\n'.join(iter_lines()),\n 'command': input,\n 'target': target,\n }\n\n if retcode:\n msg.update({\n 'message': 'target {target} failed',\n 'status': 'fail',\n 'retcode': retcode,\n })\n else:\n msg.update({\n 'message': 'target {target} complete',\n 'status': 'done',\n })\n\n y.build_results(msg)\n\n if retcode:\n if self.p.keep_going:\n pass\n else:\n y.shut_down(5, last_msg='{br}target ' + target + ' failed, exiting now{}\\n')\n\n def run_cmd_0(self):\n sp = y.subprocess\n out = []\n retcode = 0\n input = self.build_cmd()\n\n try:\n env = y.dc(self.env)\n naked = self.p.naked\n\n def fun():\n input_bin = input.encode('utf-8')\n env['RUNSH'] = y.base64.b64encode(input_bin)\n\n if not naked:\n env['REDIRECT'] = \"yes\"\n\n if naked:\n stdo = y.sys.__stderr__\n stde = y.sys.__stderr__\n else:\n stdo = sp.PIPE\n stde = sp.STDOUT\n\n p = sp.Popen([self.shell, '-s'], stdout=stdo, stderr=stde, stdin=sp.PIPE, shell=False, env=env)\n res, _ = p.communicate(input=input_bin)\n res = res or ''\n retcode = p.wait()\n\n return (res, retcode)\n\n res, retcode = fun()\n res = res.strip()\n\n if not res:\n res = y.build_run_sh(self.n)\n\n out.append(res)\n\n if retcode == 0:\n if self.check:\n self.check_results()\n except sp.CalledProcessError as e:\n out.append(e.output)\n retcode = e.returncode\n except Exception:\n out.append(y.format_tbx())\n retcode = -1\n\n return retcode, '\\n'.join(y.super_decode(o.strip()) for o in out), input\n\n\ndef run_par_build(mk, threads, check, naked, keep_going):\n y.info('{br}start build{}')\n\n try:\n return Builder(mk, threads, check, naked, keep_going).run()\n finally:\n y.info('{br}end build{}')\n","sub_path":"ut/make_exec.py","file_name":"make_exec.py","file_ext":"py","file_size_in_byte":9542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"408599797","text":"from base import base, stopwords\nfrom base_completa import base_treinamento, base_teste\nimport nltk\n\n\ndef extrair_radicais(frase):\n \"\"\"\n Extrair os radicais de uma frase.\n \"\"\"\n \n # Pega os stopwords\n stopwords = nltk.corpus.stopwords.words(\"portuguese\")\n \n # Pegar o stemmer especifico para a lingua portuguesa\n stemmer = nltk.stem.RSLPStemmer()\n \n stemming = [str(stemmer.stem(palavra)) for palavra in frase.split() if palavra not in stopwords]\n \n return stemming\n\n\ndef aplicar_stemming(texto):\n \"\"\"\n Pega os radicais do texto base\n \"\"\"\n \n stopwords = nltk.corpus.stopwords.words(\"portuguese\")\n \n # Pegar o stemmer especifico para a lingua portuguesa\n stemmer = nltk.stem.RSLPStemmer()\n frases = []\n \n for (palavras, emocao) in texto:\n # stem() retira o radical da palavra\n stemming = [str(stemmer.stem(palavra)) for palavra in palavras.split() if palavra not in stopwords]\n frases.append((stemming, emocao))\n \n return frases\n\n\nstemming_treinamento = aplicar_stemming(base_treinamento)\nstemming_teste = aplicar_stemming(base_teste)\n\n\ndef busca_palavras():\n \"\"\"\n Pega a stemming e retira as emoções, pegando só as palavras.\n \"\"\"\n \n so_palavras = []\n \n for (palavras, emocao) in stemming_treinamento:\n # extend: Pega os elementos da lista e joga 1 por 1 dentro da outra lista\n so_palavras.extend(palavras)\n \n # pega a frequencia de vezes que uma palavra aparece.\n qtd_palavras = nltk.FreqDist(so_palavras)\n \n # Retira as palavras repetidas\n sem_repeticao = qtd_palavras.keys()\n \n return list(sem_repeticao), qtd_palavras.most_common()\n\n\ndef inseri_tabela(novas_palavras):\n \"\"\"\n Recebe uma nova frase (lista de radicais) e verifica quais palavras tem\n e quais não tem de acordo com a tabela de palavras unicas (radicais).\n Monta uma linha da tabela.\n \"\"\"\n \n frase = set(novas_palavras)\n \n linha_tabela = {}\n \n palavras_unicas, qtd_palavras = busca_palavras()\n \n for palavra in palavras_unicas:\n linha_tabela[\"%s\" % palavra] = (palavra in frase)\n \n return linha_tabela\n \n \nbase_completa_treinamento = nltk.classify.apply_features(inseri_tabela, stemming_treinamento)\nbase_completa_teste = nltk.classify.apply_features(inseri_tabela, stemming_teste)","sub_path":"08_Inteligencia_Artificial/01_Mineracao_de_Emocoes_em_Textos/pre_processamento.py","file_name":"pre_processamento.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"647938203","text":"# encoding: utf-8\nimport os\n\nfrom gaeautils.bundle import bundle\nfrom gaeautils.workflow import Workflow\n\n\nclass rmdup(Workflow):\n \"\"\" rmdup \"\"\"\n\n INIT = bundle(rmdup=bundle())\n INIT.rmdup.program = \"GaeaDuplicateMarker.jar\"\n INIT.rmdup.parameter_SE = ' -S '\n INIT.rmdup.parameter = ''\n\n def run(self, impl,dependList):\n impl.log.info(\"step: rmdup!\")\n inputInfo = self.results[dependList[0]].output\n result = bundle(output=bundle(),script=bundle())\n \n #extend program path\n self.rmdup.program = self.expath('rmdup.program')\n \n if self.init.get('isSE'):\n self.rmdup.parameter = self.rmdup.parameter_SE\n \n #script template \n fs_cmd = self.fs_cmd\n cmd = []\n cmd.append(\"%s ${OUTDIR}/\" % fs_cmd.delete )\n cmd.append(\"%s ${INPUT}/*/_SUCCESS ${INPUT}/*/_logs\" % fs_cmd.delete )\n cmd.append(\"${PROGRAM} -I ${INPUT} -O ${OUTDIR} -i 1 -R ${REDUCERNUM} ${PARAM}\")\n \n for sampleName in inputInfo:\n scriptsdir = impl.mkdir(self.gaeaScriptsDir,sampleName)\n hdfs_outputPath = os.path.join(self.option.dirHDFS,sampleName,'rmdup_output')\n \n #global param\n ParamDict = {\n \"PROGRAM\": \"%s jar %s\" % (self.hadoop.bin, self.rmdup.program),\n \"INPUT\": inputInfo[sampleName],\n \"OUTDIR\": hdfs_outputPath,\n \"REDUCERNUM\":self.hadoop.reducer_num,\n \"PARAM\":self.rmdup.parameter\n }\n \n #write script\n scriptPath = \\\n impl.write_shell(\n name = 'rmdup',\n scriptsdir = scriptsdir,\n commands=cmd,\n paramDict=ParamDict)\n \n #result\n result.output[sampleName] = os.path.join(hdfs_outputPath,'Mark')\n result.script[sampleName] = scriptPath\n return result\n \n","sub_path":"workflow/H_rmdup.py","file_name":"H_rmdup.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"144854198","text":"\"\"\"\nProblem:\n\nGiven an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. \nPrint the decimal value of each fraction on a new line.\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the plusMinus function below.\ndef plusMinus(arr):\n positive, negative, zero = 0, 0, 0\n length = len(arr)\n for i in arr:\n if i > 0:\n positive += 1\n elif i < 0:\n negative += 1\n else:\n zero += 1\n print(positive/length)\n print(negative/length)\n print(zero/length)\n \nif __name__ == '__main__':\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n plusMinus(arr)\n","sub_path":"hacker-rank/easy/Plus Minus/plus-minus.py","file_name":"plus-minus.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"554758888","text":"import turtle\nimport math\nimport random\n#global variable(s)\nwdth = 800; hgth = 800; bgstring = \"#91d2ca\"\nred = \"#cc0000\"; green = \"#00cc00\"; blue = \"#0000cc\"\ndef poly(t,sides,size):\n\tangl = (sides - 2) * 180 / sides\n\tfor n in range (0,sides):\n\t\tt.forward(size)\n\t\tt.right(180-angl)\n\t\ndef leo(t): \n\ttheta = 0\n\tfor n in range (0,5):\n\t\tt.penup()\n\t\tt.goto(0,0)\n\t\tt.setheading(theta)\n\t\tt.pendown()\n\t\tt.pensize(n+1)\n\t\tt.color(blue)\n\t\tt.forward(100)\n\t\tt.pencolor(red)\n\t\tpoly(t,n+3,30)\n\t\ttheta = theta + 45\ndef main():\n\ttry:\n\t\tturtle.TurtleScreen._RUNNING = True\n\t\t# get wdth and hgth globally\n\t\tturtle.screensize(canvwidth=wdth, canvheight=hgth, bg=bgstring)\n\t\tprint(turtle.Screen().screensize())\n\t\tw = turtle.Screen()\n\t\tt = turtle.Turtle()\n\t\tleo(t)\n\t\tw.exitonclick()\n\tfinally:\n\t\tturtle.Terminator()\n\t\nif __name__ == '__main__':\n\tmain()\n\n'''\nfive circles\nfive polygons\nfive line commands\ntwo for loops\none global variable\n\n\n'''\n","sub_path":"animate-v2.py","file_name":"animate-v2.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"12897439","text":"from django.shortcuts import render\nfrom .models import Dest\nimport random\n\n\ndef index(request):\n\n\t\n\tdests=Dest.objects.all()\n\tL=[]\n\tlength=len(dests)\n\tfor dest in dests:\n\t\ti=random.randint(0,1)\n\t\tif i==1:\n\t\t\tL.append(dest)\n \n\t\n\n\t\n\n\n\n\n\n\n\treturn render(request,'index.html',{'dests':L})\n\n# Create your views here.\n","sub_path":"travel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"384138948","text":"from math import sin\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef ode_rk4_1step(dfunc, xi, yi, h):\n k1 = dfunc(xi, yi)\n k2 = dfunc(xi + 0.5*h, yi + 0.5*k1*h)\n k3 = dfunc(xi + 0.5*h, yi + 0.5*k2*h)\n k4 = dfunc(xi + h, yi + k3*h)\n yip1 = yi + (k1 + 2*k2 + 2*k3 + k4)*h/6\n return yip1\n\ndef ode_solve(dfunc, do_1step, x0, y0, h, Nstep):\n Nvec = len(y0)\n x = np.zeros(Nstep+1)\n y = np.zeros((Nstep+1,Nvec))\n # Start with initial cond\n x[0] = x0\n y[0,:] = y0[:]\n for i in range(0,Nstep):\n x[i+1] = x[i] + h\n y[i+1,:] = do_1step(dfunc, x[i], y[i,:], h)\n return x, y\n\n\ndef deriv_underdamped(x, y):\n # Parameters (local)\n m = 0.1 # kg\n k = 40.0 # N/m\n c = 0.5 # Ns/m underdamped\n Nvec = len(y)\n # Here we make an assertion to make sure that y is a 2-component vector\n # Uncomment this line if the code appears to be slow\n assert Nvec == 2\n # Output array\n dydx = np.zeros(Nvec)\n dydx[0] = y[1]\n dydx[1] = -(c*y[1] + k*y[0])/m\n #\n return dydx\n\n\ndef deriv_critical_damped(x, y):\n # Parameters (local)\n m = 0.1 # kg\n k = 40.0 # N/m\n c = 4.0 # Ns/m critically damped\n Nvec = len(y)\n # Here we make an assertion to make sure that y is a 2-component vector\n # Uncomment this line if the code appears to be slow\n assert Nvec == 2\n # Output array\n dydx = np.zeros(Nvec)\n dydx[0] = y[1]\n dydx[1] = -(c*y[1] + k*y[0])/m\n #\n return dydx\n\n\ndef deriv_overdamped(x, y):\n # Parameters (local)\n m = 0.1 # kg\n k = 40.0 # N/m\n c = 8.0 # Ns/m overdamped\n Nvec = len(y)\n # Here we make an assertion to make sure that y is a 2-component vector\n # Uncomment this line if the code appears to be slow\n assert Nvec == 2\n # Output array\n dydx = np.zeros(Nvec)\n dydx[0] = y[1]\n dydx[1] = -(c*y[1] + k*y[0])/m\n #\n return dydx\n\n# Below, we will use:\n# - t as independent variable\n# - x as dependent variable or the function we are trying to find\n# by solving the ODE\n\n# initial conditions\nt0 = 0.0\ninitial_displ = 0.1\ninitial_vel = 10.0\nx0 = np.array([initial_displ, initial_vel])\nΔt = 0.001 # try playing with this parameter\ntf = 2.0\nNstep = int(tf/Δt)\nprint(\"Nstep = \", Nstep)\n\nt, x_underdamped = ode_solve(deriv_underdamped, ode_rk4_1step, t0, x0, Δt, Nstep)\nt, x_critical_damped = ode_solve(deriv_critical_damped, ode_rk4_1step, t0, x0, Δt, Nstep)\nt, x_overdamped = ode_solve(deriv_overdamped, ode_rk4_1step, t0, x0, Δt, Nstep)\n\nplt.clf()\nplt.plot(t, x_underdamped[:,0], label=\"underdamped\")\nplt.plot(t, x_critical_damped[:,0], label=\"critical\")\nplt.plot(t, x_overdamped[:,0], label=\"overdamped\")\nplt.grid(True)\nplt.xlabel(\"t (s)\")\nplt.ylabel(\"Displacement (m)\")\nplt.legend()\nplt.tight_layout()\nplt.savefig(\"IMG_chapra_exercise_25_16_v3.pdf\")\n","sub_path":"chapra_7th/ch25/chapra_exercise_25_16_v3.py","file_name":"chapra_exercise_25_16_v3.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"308184493","text":"import cv2\nimport time\n\n\nclass Webcam:\n def __init__(self, capture):\n while True:\n self.cap = cv2.VideoCapture(capture)\n if self.cap.isOpened():\n break\n time.sleep(3)\n\n self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)\n self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)\n\n def getSnapshotCV(self):\n return self.cap.read()\n\n def release(self):\n self.cap.release()\n","sub_path":"detector/webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"496543477","text":"#-*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport shutil\n\nstrErrorInfo = '参数有误'\nstrUsageMsg = 'Usage: vimconfig.py vimfiles=[vimfiles目录] plugins=[plugins目录] vimruntime=[vim中$VIMRUNTIME值] vimrc=[vimrc文件路劲] (ps:两边不能有空格; 路径有空格应该用\"\"包起来)'\n\ndef exitWithMsg(msg):\n print(strErrorInfo, msg, sep='\\n')\n sys.exit()\n\ndef CheckArgus(*args):\n if len(args) != 4:\n return False\n argsDict = dict.fromkeys(['vimfiles', 'plugins', 'vimruntime', 'vimrc'])\n for curArg in args:\n try:\n argPair = curArg.split('=', 1)\n except:\n return False\n else:\n if len(argPair) != 2 or not argPair[0] in argsDict :\n return False\n argsDict[argPair[0]] = argPair[1]\n return argsDict\n\ndef GetAndCheckVIMPathFromArgs(*args):\n strVimPath = ''\n if len(args) == 0 or len(args) > 1:\n return strVimPath\n if os.path.isdir(args[0]):\n #检查vimfiles\n strVimfilesPath = args[0].rstrip()\n if not strVimfilesPath.endswith('/'):\n strVimfilesPath = strVimfilesPath + '/'\n strVimfilesPath += 'vimfiles'\n if os.path.isdir(strVimfilesPath):\n strVimfilesPathSubDir = strVimfilesPath + '/'\n listCheckDirs = ['colors', 'compiler', 'doc', 'ftdetect', 'ftplugin', 'indent', 'keymap', 'plugin', 'syntax']\n for cDir in listCheckDirs:\n strCheckDir = strVimfilesPathSubDir + cDir\n if not os.path.isdir(strCheckDir):\n break\n else:\n strVimPath = args[0]\n return strVimPath\n\ndef RecurseCopyDir(srcDir, destDir):\n for root, subDirs, subFiles in os.walk(srcDir):\n relRootPath = os.path.relpath(root, start=srcDir)\n if relRootPath != '.' and not os.path.exists(os.path.join(destDir, relRootPath)):\n shutil.copytree(root, os.path.join(destDir, relRootPath))\n continue\n for cFile in subFiles:\n shutil.copyfile(os.path.join(root, cFile), os.path.join(destDir, relRootPath, cFile))\n\ndef InstallVimfiles(vimfilesSrc, vimfilesDest):\n vimfilesSub = ['colors', 'compiler', 'doc', 'ftdetect', 'ftplugin', 'indent', 'keymap', 'plugin', 'syntax', 'after']\n for root, subDirs, subFiles in os.walk(vimfilesSrc):\n if not os.path.basename(root) in vimfilesSub:\n continue\n for cFile in subFiles :\n #Todo: 提示覆盖\n if cFile.endswith('.vim') or cFile.endswith('.txt'):\n shutil.copyfile(os.path.join(root, cFile), os.path.join(vimfilesDest, os.path.basename(root), cFile))\n for subDir in subDirs:\n InstallPlugin(os.path.join(root, subDir), os.path.join(vimfilesDest, os.path.basename(root), subDir))\n\ndef InstallPlugin(pluginSrc, pluginDest):\n if not os.path.exists(pluginDest):\n shutil.copytree(pluginSrc, pluginDest, ignore=shutil.ignore_patterns(\"*~\", \"*swp\"))\n else:\n RecurseCopyDir(pluginSrc, pluginDest) \n\ndef InstallVimbin(vimruntimeSrc, vimruntimeDest):\n InstallPlugin(vimruntimeSrc, vimruntimeDest)\n\ndef InstallPluginConfig(pluginconfigSrc, pluginconfigDest):\n InstallPlugin(pluginconfigSrc, pluginconfigDest)\n\nif __name__ == '__main__':\n #配置vim\n\n argsDict = CheckArgus(*sys.argv[1:])\n if not argsDict:\n exitWithMsg(strUsageMsg)\n \n #1, 复制Vimfiles\n if not os.path.isdir(argsDict['vimfiles']):\n exitWithMsg('vimfiles目录不存在')\n szVimfilesSrc = 'vimfiles/'\n InstallVimfiles(szVimfilesSrc, argsDict['vimfiles'])\n\n #2, 复制plugins目录\n if not os.path.isdir(argsDict['plugins']):\n exitWithMsg('plugins目录不存在')\n szPluginsSrc = 'plugins/'\n InstallPlugin(szPluginsSrc, argsDict['plugins'])\n\n #3, 复制vimruntime目录 一些插件需要把可执行文件放在vim/gvim可执行文件所在目录\n if not os.path.isdir(argsDict['vimruntime']):\n exitWithMsg('vimruntime目录不存在')\n szVimbinSrc = 'runtime/'\n InstallVimbin(szVimbinSrc, argsDict['vimruntime'])\n\n\n #4, 复制lsffvimrc 并修改vimrc文件\n szVIMDir = os.path.dirname(argsDict['vimruntime'][0:len(argsDict['vimruntime']) - 1]) if argsDict['vimruntime'].endswith('\\\\') or argsDict['vimruntime'].endswith('/') else os.path.dirname(argsDict['vimruntime'])\n\n if not os.path.exists(argsDict['vimrc']):\n exitWithMsg('vimrc文件路径不存在')\n shutil.copy('lsffvimrc', szVIMDir)\n lineAppend = 'source $VIM/lsffvimrc'\n for line in open(argsDict['vimrc']):\n if line.rstrip('\\n ') == lineAppend :\n break\n else:\n fileVimrc = open(argsDict['vimrc'], 'a')\n print(lineAppend, file=fileVimrc)\n\n #5, 复制plugin_config目录\n szVimPluginConfig = 'plugin_config'\n szVimPluginConfigDest = os.path.join(szVIMDir, szVimPluginConfig)\n if os.path.exists(szVimPluginConfig):\n InstallPluginConfig(szVimPluginConfig, szVimPluginConfigDest)\n\n \n #6, 复制ultisnips_snips目录\n szVimUltisnips_Snips = 'ultisnips_snips'\n szVimUltisnips_SnipsDest = os.path.join(szVIMDir, szVimUltisnips_Snips)\n if os.path.exists(szVimUltisnips_Snips):\n InstallPluginConfig(szVimUltisnips_Snips, szVimUltisnips_SnipsDest)\n\n \n","sub_path":"vimconfig.py","file_name":"vimconfig.py","file_ext":"py","file_size_in_byte":5308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"189531850","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/11/28 11:01\n# @Author : bin\n# @Site : \n# @File : err_raise.py\n# @Software: PyCharm Community Edition\n\n# 抛出错误\n#\n# 因为错误是class,捕获一个错误就是捕获到该class的一个实例。因此,错误并不是凭空产生的,而是有意创建并抛出的。\n# Python的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。\n\n# 如果要抛出错误,首先根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例\n\n\n# class FooError(ValueError):\n# pass\n#\n#\n# def foo(s):\n# n = int(s)\n# if n == 0:\n# raise FooError('invalid value:%s' % s)\n# return 10 / n\n\n\n# foo('0')\n\n# 只有在必要的时候才定义我们自己的错误类型。\n# 如果可以选择Python已有的内置的错误类型(比如ValueError,TypeError),尽量使用Python内置的错误类型\n\n\n# 最后,我们来看另一种错误处理的方式\ndef foo(s):\n n = int(s)\n if n == 0:\n raise ValueError('invalid value:%s' % s)\n return 10 / n\n\n\ndef bar():\n try:\n foo('0')\n except ValueError as e:\n print('ValueError')\n raise\n\n\nbar()\n\n\n# 在bar()函数中,我们明明已经捕获了错误,但是,打印一个ValueError!后,又把错误通过raise语句抛出去了,这不有病么?\n\n# 其实这种错误处理方式不但没病,而且相当常见。捕获错误目的只是记录一下,便于后续追踪。\n# 但是,由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理。\n# 好比一个员工处理不了一个问题时,就把问题抛给他的老板,如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。\n\ntry:\n 10 / 0\nexcept ZeroDivisionError:\n raise ValueError('input Error!')\n\n\n# 只要是合理的转换逻辑就可以,但是,决不应该把一个IOError转换成毫不相干的ValueError\n\n\n\n","sub_path":"com/robin/debug/err_raise.py","file_name":"err_raise.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"33337188","text":"class Solution:\n def rotate_image(self, image):\n if not self.isValidImage(image):\n raise Exception('Invalid image')\n \n n = len(image)\n\n for row in range(n//2):\n start = row\n end = n - 1 - row\n for col in range(start, end): # end should not be included, because it is already taken care of in the first iteration\n x = row\n y = col\n prev = image[x][y]\n for _ in range(4):\n new_row = y\n new_col = n - x - 1\n new_cell = image[new_row][new_col]\n image[new_row][new_col] = prev\n x = new_row\n y = new_col\n prev = new_cell\n \n def isValidImage(self, image):\n n = len(image)\n return n > 0 and len(image[0]) == n\n\n def print_image(self, image):\n for row in image:\n print(row)\n\nimage = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]\nsolution = Solution()\nsolution.print_image(image)\nsolution.rotate_image(image)\nprint('===============')\nsolution.print_image(image)","sub_path":"arrays/rotate_image.py","file_name":"rotate_image.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"261926527","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 13 10:06:29 2020\r\n\r\n@author: ssff\r\n\"\"\"\r\n\r\nfrom sklearn import mixture\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport scipy\r\nimport numpy as np\r\n\r\ndef import_image(s):\r\n pic = mpimg.imread(s)\r\n pic = np.dot(pic[...,:3], [0.299, 0.587, 0.114])\r\n return pic\r\n \r\ndef gauss_fit(pic,size):\r\n samples = pic.reshape([size[0]*size[1],1])\r\n clf = mixture.GaussianMixture(n_components=3, covariance_type='full',tol=1e-10, max_iter=100000)\r\n clf.fit(samples)\r\n m1, m2, m3 = clf.means_\r\n w1, w2, w3 = clf.weights_\r\n c1, c2, c3 = clf.covariances_\r\n para = [[m1, m2, m3],[w1, w2, w3],[c1, c2, c3]]\r\n return samples, para\r\n\r\ndef plot_gauss(yourdata, para):\r\n histdist = plt.hist(yourdata, 100, normed=True)\r\n [[m1, m2, m3],[w1, w2, w3],[c1, c2, c3]] = para\r\n plotgauss1 = lambda x: plt.plot(x,w1*scipy.stats.norm.pdf(x,m1,np.sqrt(c1))[0], linewidth=3)\r\n plotgauss2 = lambda x: plt.plot(x,w2*scipy.stats.norm.pdf(x,m2,np.sqrt(c2))[0], linewidth=3)\r\n plotgauss3 = lambda x: plt.plot(x,w3*scipy.stats.norm.pdf(x,m3,np.sqrt(c3))[0], linewidth=3)\r\n plotgauss1(histdist[1])\r\n plotgauss2(histdist[1])\r\n plotgauss3(histdist[1])\r\n \r\ndef middle_point(para):\r\n m_l = para[0]\r\n c_l = para[2]\r\n pair_l = list(zip(m_l,c_l))\r\n pair_l = sorted(pair_l,key = lambda x:x[0])\r\n left_p = pair_l[0][0] + 3*np.sqrt(pair_l[0][1])\r\n right_p = pair_l[2][0] - 3*np.sqrt(pair_l[2][1])\r\n m_p = (left_p + right_p) / 2\r\n return m_p\r\n\r\ndef generate_new_phase1(pic,size,m_p):\r\n pic_n = pic\r\n for i in range(size[0]):\r\n for j in range(size[1]):\r\n if pic[i,j] < m_p:\r\n pic_n[i,j] = -1\r\n else:\r\n pic_n[i,j] = 1\r\n return pic_n\r\n\r\ndef generate_new_phase2(pic,size,m_p):\r\n pic_n = pic\r\n for i in range(size[0]):\r\n for j in range(size[1]):\r\n if pic[i,j] < m_p:\r\n pic_n[i,j] = 1\r\n else:\r\n pic_n[i,j] = -1\r\n return pic_n\r\n\r\ndef plot_new_phase(pic, size):\r\n pic_n = pic\r\n for i in range(size[0]):\r\n for j in range(size[1]):\r\n if pic[i,j] == 1:\r\n pic_n[i,j] = 0\r\n else:\r\n pic_n[i,j] = 255\r\n plt.imshow(pic_n)\r\n \r\nif __name__ == '__main__':\r\n pic = import_image('./data/amp0-01.tif')\r\n '''size = pic.shape\r\n samples, para = gauss_fit(pic, size)\r\n plot_gauss(samples, para)\r\n m_p = middle_point(para)\r\n plot_new_phase(generate_new_phase(pic,size,m_p),size)'''\r\n pic_seg = pic[150,0]\r\n print(pic_seg)\r\n\r\n'''\r\n1. 注意在主函数中实现功能循环,而不是在分函数中\r\n分函数应该是实现单一功能的最简函数。\r\n'''\r\n\r\n\r\n\r\n\r\n","sub_path":"phase_analyze.py","file_name":"phase_analyze.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"148015589","text":"############################################################\n# ITERATIVE SORTING\n#-----------------------------------------------------------\n# GUIDED\n# - [x] complete insertion_sort() below\n#\n# MVP\n# - [x] complete selection_sort() below\n# - [x] complete bubble_sort() below\n#\n# STRETCH\n# - [ ] complete count_sort() below\n############################################################\n\nimport sys\nsys.path.append(\"../\")\n\nfrom compare import compare_ascending\n\n\ndef insertion_sort(array, compare=compare_ascending):\n # 0. take some array\n # 1. start with the first item (i = 0) in the array -- this is sorted\n # 2. take array[i], the next item (i = 1, 2, ...) in the array\n # 3. compare array[i] to each previous item (j = i, i-1, ...) until you find the right spot for array[i]\n # 4. move all checked items \"more\" than array[i] to the right and insert array[i] at its new index in the \"sorted\" portion of the array\n # 5. repeat until there are no more items to sort\n\n n = len(array)\n\n # for each pair of items in _mutating_ array...\n for i in range(1, n):\n\n item = array[i] # the item to move\n j = i # index where item should move to\n\n # from [j] to the left, swap [j] and [j-1] until correct index for item\n while compare(item, array[j - 1]) < 0 and j > 0:\n array[j] = array[j - 1]\n j -= 1\n\n # insert item at [j]\n array[j] = item\n\n return array\n\n\ndef selection_sort(array, compare=compare_ascending):\n # 0. take some array\n # 1. imagine the beginning of the array as \"sorted\" -- currently empty\n # 2. start with the first item (i = 0, 1, 2, ...) -- this is the \"current minimum\"\n # 3. move through the rest of array and record each value \"less\" than the \"current minimum\" as the new \"current minimum\"\n # 4. swap the \"current minimum\" with item _after_ the end of the \"sorted\" portion of array\n # 5. repeat for the remaining \"unsorted\" portion of array\n\n n = len(array) # size of full array\n\n # for each pair of items in _mutating_ array...\n for i in range(0, n - 1):\n\n p = i # index of this iteration's \"minimum\"\n\n # find the index of the \"minumum\" in \"unsorted\" portion...\n for j in range(i, n):\n if compare(array[j], array[p]) < 0:\n p = j\n\n # swap\n array[p], array[i] = array[i], array[p]\n\n return array\n\n\ndef bubble_sort(array, compare=compare_ascending):\n # 0. take some array\n # 1. for each pair of items (i, i+1) in the \"unsorted\" array, compare\n # 2. swap array[i] and array[i+1] if they are out of order\n # -- doing this once will move the \"maximum\" item to the end of array, which is now \"sorted\"\n # 3. repeat the process on the \"unsorted\" array until nothing is left\n\n n = len(array) # size of full array\n\n # for each pair of items in _mutating_ array...\n for i in range(0, n - 1):\n\n m = n - i # size of \"sorted\" portion\n\n # sort \"unsorted\" portion...\n for j in range(0, m - 1):\n if compare(array[j + 1], array[j]) < 0:\n # swap\n array[j], array[j + 1] = array[j + 1], array[j]\n\n return array\n\n\ndef count_sort(array, maximum=-1, compare=compare_ascending):\n # TODO: stretch\n\n return array\n","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"598977182","text":"import os\nfrom os import path as osp\n\nfolder = \"/home/opekta/copaeurope/mmaction2/data/soccernet/extractedFrames/Penalty\"\n\nfor root, dirs, files in os.walk(folder):\n for dir in dirs:\n if dir[-4:]=='de8f':\n dirPath=osp.join(root,dir)\n for file in os.listdir(dirPath):\n # if (int(file[-7:-4])<=30) or (int(file[-7:-4])>120):\n # print(file)\n # os.remove(osp.join(dirPath,file))\n # newFile = file[:-7]+format(int(file[-7:-4])-30, '03d')+'&'+file[-4:]\n # print(newFile)\n print(file)\n# os.rename(osp.join(dirPath,file), osp.join(dirPath,file[:-5]+file[-4:]))\n# if (file[-11:]=='flipped.jpg'):\n# print(osp.join(root,file[:-12]+file[-4:]))\n# os.rename(osp.join(root,file),osp.join(root,file[:-12]+file[-4:]))\n","sub_path":"tools/data/soccernet/correction_names.py","file_name":"correction_names.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243280035","text":"from http import HTTPStatus\n\nimport aiohttp\nimport pytest\nfrom yarl import URL\n\npytestmark = [\n pytest.mark.asyncio,\n pytest.mark.filterwarnings(\"ignore:Using or importing the ABCs:DeprecationWarning\"),\n]\n\n\n@pytest.fixture(autouse=True)\nasync def sanic_server(event_loop, unused_tcp_port, unused_udp_port):\n from sanic import Sanic, response\n from sanic.exceptions import Unauthorized\n\n from aiodogstatsd.contrib import sanic as aiodogstatsd\n\n async def handler_hello(request):\n return response.json({\"hello\": \"aiodogstatsd\"})\n\n async def handler_bad_request(request):\n return response.json({\"hello\": \"bad\"}, status=HTTPStatus.BAD_REQUEST)\n\n async def handler_internal_server_error(request):\n raise NotImplementedError()\n\n async def handler_unauthorized(request):\n raise Unauthorized(\"Unauthorized\")\n\n app = Sanic(name=\"aiodogstatsd\")\n\n listener_setup_statsd, listener_close_statsd = aiodogstatsd.listeners_factory(\n host=\"0.0.0.0\", port=unused_udp_port, constant_tags={\"whoami\": \"batman\"}\n )\n app.register_listener(listener_setup_statsd, \"before_server_start\")\n app.register_listener(listener_close_statsd, \"after_server_stop\")\n\n (\n middleware_request_statsd,\n middleware_response_statsd,\n ) = aiodogstatsd.middlewares_factory()\n app.register_middleware(middleware_request_statsd, attach_to=\"request\")\n app.register_middleware(middleware_response_statsd, attach_to=\"response\")\n\n app.add_route(handler_hello, \"/hello\")\n app.add_route(handler_bad_request, \"/bad_request\", methods={\"POST\"})\n app.add_route(handler_internal_server_error, \"/internal_server_error\")\n app.add_route(handler_unauthorized, \"/unauthorized\")\n\n server = await app.create_server(\n host=\"0.0.0.0\", port=unused_tcp_port, return_asyncio_server=True\n )\n yield\n server.close()\n await server.wait_closed()\n await listener_close_statsd(app, event_loop)\n\n\n@pytest.fixture\ndef sanic_server_url(unused_tcp_port):\n return URL(f\"http://0.0.0.0:{unused_tcp_port}\")\n\n\n@pytest.fixture(autouse=True)\ndef mock_loop_time(mocker):\n mock_loop = mocker.Mock()\n mock_loop.time.side_effect = [0, 1]\n\n mocker.patch(\"aiodogstatsd.contrib.sanic.get_event_loop\", return_value=mock_loop)\n\n\nclass TestSanic:\n async def test_ok(self, sanic_server_url, statsd_server, wait_for):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.get(sanic_server_url / \"hello\") as resp:\n assert resp.status == HTTPStatus.OK\n\n await wait_for(collected)\n\n assert collected == [\n b\"http_request_duration:1000|ms\"\n b\"|#whoami:batman,method:GET,path:/hello,status:200\"\n ]\n\n async def test_bad_request(self, sanic_server_url, statsd_server, wait_for):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.post(sanic_server_url / \"bad_request\") as resp:\n assert resp.status == HTTPStatus.BAD_REQUEST\n\n await wait_for(collected)\n\n assert collected == [\n b\"http_request_duration:1000|ms\"\n b\"|#whoami:batman,method:POST,path:/bad_request,status:400\"\n ]\n\n async def test_internal_server_error(\n self, sanic_server_url, statsd_server, wait_for\n ):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.get(\n sanic_server_url / \"internal_server_error\"\n ) as resp:\n assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR\n\n await wait_for(collected)\n\n assert collected == [\n b\"http_request_duration:1000|ms\"\n b\"|#whoami:batman,method:GET,path:/internal_server_error,status:500\"\n ]\n\n async def test_unauthorized(self, sanic_server_url, statsd_server, wait_for):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.get(sanic_server_url / \"unauthorized\") as resp:\n assert resp.status == HTTPStatus.UNAUTHORIZED\n\n await wait_for(collected)\n\n assert collected == [\n b\"http_request_duration:1000|ms\"\n b\"|#whoami:batman,method:GET,path:/unauthorized,status:401\"\n ]\n\n async def test_not_allowed(self, sanic_server_url, statsd_server, wait_for):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.post(sanic_server_url / \"hello\") as resp:\n assert resp.status == HTTPStatus.METHOD_NOT_ALLOWED\n\n await wait_for(collected)\n\n assert collected == []\n\n async def test_not_found(self, sanic_server_url, statsd_server, wait_for):\n udp_server, collected = statsd_server\n\n async with udp_server:\n async with aiohttp.ClientSession() as session:\n async with session.get(sanic_server_url / \"not_found\") as resp:\n assert resp.status == HTTPStatus.NOT_FOUND\n\n await wait_for(collected)\n\n assert collected == []\n","sub_path":"tests/test_contrib_sanic.py","file_name":"test_contrib_sanic.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"570892057","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom operator import mul\n\nimport torch\n\n\ndef make_sparse_from_indices_and_values(interp_indices, interp_values, num_rows):\n \"\"\"\n This produces a sparse tensor with a fixed number of non-zero entries in each column.\n\n Args:\n interp_indices - Tensor (batch_size) x num_cols x n_nonzero_entries\n A matrix which has the indices of the nonzero_entries for each column\n interp_values - Tensor (batch_size) x num_cols x n_nonzero_entries\n The corresponding values\n num_rows - the number of rows in the result matrix\n\n Returns:\n SparseTensor - (batch_size) x num_cols x num_rows\n \"\"\"\n\n if not torch.is_tensor(interp_indices):\n raise RuntimeError(\"interp_indices and interp_values should be tensors\")\n\n # Is it batch mode?\n is_batch = interp_indices.ndimension() > 2\n if is_batch:\n batch_size, n_target_points, n_coefficients = interp_values.size()\n else:\n n_target_points, n_coefficients = interp_values.size()\n\n # Index tensor\n row_tensor = torch.arange(0, n_target_points, dtype=torch.long, device=interp_values.device)\n row_tensor.unsqueeze_(1)\n if is_batch:\n batch_tensor = torch.arange(0, batch_size, dtype=torch.long, device=interp_values.device)\n batch_tensor.unsqueeze_(1).unsqueeze_(2)\n\n row_tensor = row_tensor.repeat(batch_size, 1, n_coefficients)\n batch_tensor = batch_tensor.repeat(1, n_target_points, n_coefficients)\n index_tensor = torch.stack(\n [\n batch_tensor.contiguous().view(-1),\n interp_indices.contiguous().view(-1),\n row_tensor.contiguous().view(-1),\n ],\n 0,\n )\n else:\n row_tensor = row_tensor.repeat(1, n_coefficients)\n index_tensor = torch.cat([interp_indices.contiguous().view(1, -1), row_tensor.contiguous().view(1, -1)], 0)\n\n # Value tensor\n value_tensor = interp_values.contiguous().view(-1)\n nonzero_indices = value_tensor.nonzero()\n if nonzero_indices.storage():\n nonzero_indices.squeeze_()\n index_tensor = index_tensor.index_select(1, nonzero_indices)\n value_tensor = value_tensor.index_select(0, nonzero_indices)\n else:\n index_tensor = index_tensor.resize_(3 if is_batch else 2, 1).zero_()\n value_tensor = value_tensor.resize_(1).zero_()\n\n # Size\n if is_batch:\n interp_size = torch.Size([batch_size, num_rows, n_target_points])\n else:\n interp_size = torch.Size([num_rows, n_target_points])\n\n # Make the sparse tensor\n type_name = value_tensor.type().split(\".\")[-1] # e.g. FloatTensor\n if index_tensor.is_cuda:\n cls = getattr(torch.cuda.sparse, type_name)\n else:\n cls = getattr(torch.sparse, type_name)\n res = cls(index_tensor, value_tensor, interp_size)\n\n # Wrap things as a variable, if necessary\n return res\n\n\ndef bdsmm(sparse, dense):\n \"\"\"\n Batch dense-sparse matrix multiply\n \"\"\"\n if sparse.ndimension() > 2:\n batch_size, num_rows, num_cols = sparse.size()\n batch_assignment = sparse._indices()[0]\n indices = sparse._indices()[1:].clone()\n indices[0].add_(num_rows, batch_assignment)\n indices[1].add_(num_cols, batch_assignment)\n sparse_2d = torch.sparse_coo_tensor(\n indices,\n sparse._values(),\n torch.Size((batch_size * num_rows, batch_size * num_cols)),\n dtype=sparse._values().dtype,\n device=sparse._values().device,\n )\n\n if dense.size(0) == 1:\n dense = dense.repeat(batch_size, 1, 1)\n dense_2d = dense.contiguous().view(batch_size * num_cols, -1)\n res = torch.dsmm(sparse_2d, dense_2d)\n res = res.view(batch_size, num_rows, -1)\n return res\n elif dense.ndimension() == 3:\n batch_size, _, num_cols = dense.size()\n res = torch.dsmm(sparse, dense.transpose(0, 1).contiguous().view(-1, batch_size * num_cols))\n res = res.view(-1, batch_size, num_cols)\n res = res.transpose(0, 1).contiguous()\n return res\n else:\n return torch.dsmm(sparse, dense)\n\n\ndef sparse_eye(size):\n \"\"\"\n Returns the identity matrix as a sparse matrix\n \"\"\"\n indices = torch.arange(0, size).long().unsqueeze(0).expand(2, size)\n values = torch.tensor(1.).expand(size)\n cls = getattr(torch.sparse, values.type().split(\".\")[-1])\n return cls(indices, values, torch.Size([size, size]))\n\n\ndef sparse_getitem(sparse, idxs):\n \"\"\"\n \"\"\"\n if not isinstance(idxs, tuple):\n idxs = (idxs,)\n\n if not sparse.ndimension() <= 2:\n raise RuntimeError(\"Must be a 1d or 2d sparse tensor\")\n\n if len(idxs) > sparse.ndimension():\n raise RuntimeError(\"Invalid index for %d-order tensor\" % sparse.ndimension())\n\n indices = sparse._indices()\n values = sparse._values()\n size = list(sparse.size())\n\n for i, idx in list(enumerate(idxs))[::-1]:\n if isinstance(idx, int):\n del size[i]\n mask = indices[i].eq(idx)\n if sum(mask):\n new_indices = torch.zeros(indices.size(0) - 1, sum(mask), dtype=indices.dtype, device=indices.device)\n for j in range(indices.size(0)):\n if i > j:\n new_indices[j].copy_(indices[j][mask])\n elif i < j:\n new_indices[j - 1].copy_(indices[j][mask])\n indices = new_indices\n values = values[mask]\n else:\n indices.resize_(indices.size(0) - 1, 1).zero_()\n values.resize_(1).zero_()\n\n if not len(size):\n return sum(values)\n\n elif isinstance(idx, slice):\n start, stop, step = idx.indices(size[i])\n size = list(size[:i]) + [stop - start] + list(size[i + 1 :])\n if step != 1:\n raise RuntimeError(\"Slicing with step is not supported\")\n mask = indices[i].lt(stop) * indices[i].ge(start)\n if sum(mask):\n new_indices = torch.zeros(indices.size(0), sum(mask), dtype=indices.dtype, device=indices.device)\n for j in range(indices.size(0)):\n new_indices[j].copy_(indices[j][mask])\n new_indices[i].sub_(start)\n indices = new_indices\n values = values[mask]\n else:\n indices.resize_(indices.size(0), 1).zero_()\n values.resize_(1).zero_()\n\n else:\n raise RuntimeError(\"Unknown index type\")\n\n return torch.sparse_coo_tensor(indices, values, torch.Size(size), dtype=values.dtype, device=values.device)\n\n\ndef sparse_repeat(sparse, *repeat_sizes):\n \"\"\"\n \"\"\"\n orig_ndim = sparse.ndimension()\n new_ndim = len(repeat_sizes)\n orig_nvalues = sparse._indices().size(1)\n\n # Expand the number of dimensions to match repeat_sizes\n indices = torch.cat(\n [\n torch.zeros(new_ndim - orig_ndim, orig_nvalues, dtype=torch.long, device=sparse._indices().device),\n sparse._indices(),\n ]\n )\n values = sparse._values()\n size = [1] * (new_ndim - orig_ndim) + list(sparse.size())\n\n # Expand each dimension\n new_indices = torch.zeros(\n indices.size(0), indices.size(1) * mul(*repeat_sizes), dtype=indices.dtype, device=indices.device\n )\n new_values = values.repeat(mul(*repeat_sizes))\n new_size = [dim_size * repeat_size for dim_size, repeat_size in zip(size, repeat_sizes)]\n\n # Fill in new indices\n new_indices[:, :orig_nvalues].copy_(indices)\n unit_size = orig_nvalues\n for i in range(new_ndim)[::-1]:\n repeat_size = repeat_sizes[i]\n for j in range(1, repeat_size):\n new_indices[:, unit_size * j : unit_size * (j + 1)].copy_(new_indices[:, :unit_size])\n new_indices[i, unit_size * j : unit_size * (j + 1)] += j * size[i]\n unit_size *= repeat_size\n\n return torch.sparse_coo_tensor(\n new_indices, new_values, torch.Size(new_size), dtype=new_values.dtype, device=new_values.device\n )\n\n\ndef to_sparse(dense):\n \"\"\"\n \"\"\"\n mask = dense.ne(0)\n indices = mask.nonzero()\n if indices.storage():\n values = dense[mask]\n else:\n indices = indices.resize_(1, dense.ndimension()).zero_()\n values = torch.tensor(0, dtype=dense.dtype, device=dense.device)\n\n # Construct sparse tensor\n klass = getattr(torch.sparse, dense.type().split(\".\")[-1])\n res = klass(indices.t(), values, dense.size())\n if dense.is_cuda:\n res = res.cuda()\n return res\n","sub_path":"gpytorch/utils/sparse.py","file_name":"sparse.py","file_ext":"py","file_size_in_byte":8754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"643682733","text":"from fastapi import APIRouter, Depends, HTTPException\n\nfrom api.services import auth\nfrom api.services.dependencies import get_current_user, get_current_client\nfrom api.models.user import Profile, Client\nfrom api.models.requests import CreateClientRequest, UpdateUserRequest\nfrom api.models.responses import SuccessResponse\n\nrouter = APIRouter( \n prefix=\"/user\", \n tags=[\"User\"]\n)\n\n@router.get(\"/\")\nasync def get_current_user(current_user: Profile = Depends(get_current_user)):\n return current_user\n\n@router.post(\"/client\")\nasync def create_client(request: CreateClientRequest, current_user: Profile = Depends(get_current_user)): \n response = await auth.create_client(current_user, request)\n if not response: \n raise HTTPException(status_code=301)\n return SuccessResponse()\n\n@router.get(\"/client\", response_model=Client)\nasync def get_client(current_client: Client = Depends(get_current_client)): \n return current_client\n\n@router.post(\"/edit\", response_model=Profile)\nasync def edit_current_user_endpoint(request: UpdateUserRequest, current_user: Profile = Depends(get_current_user)):\n result = await auth.edit_current_user(request, current_user)\n if result is None: \n raise HTTPException(status_code=400, detail=\"failed to update user\")\n current_user.first_name = request.first_name\n current_user.last_name = request.last_name\n return current_user","sub_path":"app/api/routes/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"621505328","text":"\nimport sys\nimport numpy as np\nfrom math import sqrt\nimport argparse\nimport logging\nimport shutil\nimport MDAnalysis\n\nfrom IPython import embed\n\nfrom scipy.spatial import cKDTree\nimport itertools\n#from skimage import measure\n\nfrom rhoutils import rho, cartesian\nfrom mdtools import ParallelTool\n\nfrom constants import SEL_SPEC_HEAVIES, SEL_SPEC_HEAVIES_NOWALL\nfrom mdtools.fieldwriter import RhoField\nimport sys\nimport argparse, os\nfrom scipy.interpolate import interp2d\n\nimport matplotlib as mpl\n\nfrom skimage import measure\nfrom scipy.optimize import curve_fit\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.optimize import minimize\n\nmyorange = myorange = plt.rcParams['axes.prop_cycle'].by_key()['color'][1] \n\nRv = 20\nw = 3\n\n\nhomedir = os.environ['HOME']\n\n\nmpl.rcParams.update({'axes.labelsize': 30})\nmpl.rcParams.update({'xtick.labelsize': 30})\nmpl.rcParams.update({'ytick.labelsize': 30})\nmpl.rcParams.update({'axes.titlesize': 30})\n\n#fn_sph = lambda pts, x0 : \n\n## Analyze (reweighted) rho(x,y,z) profiles with beta phi, n\n#\n# Find/linearly interpolate points of isosurface where rho(x,y,z) < s=0.5\n# Finally, fit a circle to the isopoints.\n\n# Find xs, point where line between (xlo, ylo) and (xhi, yhi) crosses ys\ndef interp1d(xlo, xhi, ylo, yhi, ys=0.5):\n\n m = (yhi - ylo) / (xhi - xlo)\n\n if m == 0:\n return xlo\n\n return xlo + (ys-ylo)/m\n\n\n# Given a density field (shape: (xvals.size, yvals.size, zvals.size)), find \n# linearly interpolated points where we cross isovalue\ndef get_interp_points(rho, xvals, yvals, zvals, iso=0.5):\n\n\n rho_mask = (rho > iso).astype(int)\n xcross = np.diff(rho_mask, axis=0).astype(bool)\n ycross = np.diff(rho_mask, axis=1).astype(bool)\n zcross = np.diff(rho_mask, axis=2).astype(bool)\n\n dx, dy, dz = np.gradient(rho_mask)\n\n pts = []\n for ix in range(xvals.size-1):\n xlo = xvals[ix]\n xhi = xvals[ix+1]\n\n for iy in range(yvals.size-1):\n ylo = yvals[iy]\n yhi = yvals[iy+1]\n\n for iz in range(zvals.size-1):\n zlo = zvals[iz]\n zhi = zvals[iz+1]\n\n bxcross = xcross[ix, iy, iz]\n bycross = ycross[ix, iy, iz]\n bzcross = zcross[ix, iy, iz]\n\n if not (bxcross or bycross or bzcross):\n continue\n\n ptx = interp1d(xlo, xhi, rho[ix, iy, iz], rho[ix+1, iy, iz], ys=iso) if bxcross else xlo\n pty = interp1d(ylo, yhi, rho[ix, iy, iz], rho[ix, iy+1, iz], ys=iso) if bycross else ylo\n ptz = interp1d(zlo, zhi, rho[ix, iy, iz], rho[ix, iy, iz+1], ys=iso) if bzcross else zlo\n\n pts.append(np.array([ptx, pty, ptz]))\n\n # last col of x\n for iy in range(yvals.size-1):\n ylo = yvals[iy]\n yhi = yvals[iy+1]\n\n for iz in range(zvals.size-1):\n zlo = zvals[iz]\n zhi = zvals[iz+1]\n\n bycross = ycross[-1, iy, iz]\n bzcross = zcross[-1, iy, iz]\n\n if not (bycross or bzcross):\n continue\n\n pty = interp1d(ylo, yhi, rho[-1, iy, iz], rho[-1, iy+1, iz], ys=iso) if bycross else ylo\n ptz = interp1d(zlo, zhi, rho[-1, iy, iz], rho[-1, iy, iz+1], ys=iso) if bzcross else zlo\n\n pts.append(np.array([xvals[-1], pty, ptz]))\n\n # last col of y\n for ix in range(xvals.size-1):\n xlo = xvals[ix]\n xhi = xvals[ix+1]\n\n for iz in range(zvals.size-1):\n zlo = zvals[iz]\n zhi = zvals[iz+1]\n\n bxcross = xcross[ix, -1, iz]\n bzcross = zcross[ix, -1, iz]\n\n if not (bxcross or bzcross):\n continue\n\n ptx = interp1d(xlo, xhi, rho[ix, -1, iz], rho[ix+1, -1, iz], ys=iso) if bxcross else xlo\n ptz = interp1d(zlo, zhi, rho[ix, -1, iz], rho[ix, -1, iz+1], ys=iso) if bzcross else zlo\n\n pts.append(np.array([ptx, yvals[-1], ptz]))\n\n # last col of z\n for ix in range(xvals.size-1):\n xlo = xvals[ix]\n xhi = xvals[ix+1]\n\n for iy in range(yvals.size-1):\n ylo = yvals[iy]\n yhi = yvals[iy+1]\n\n bxcross = xcross[ix, iy, -1]\n bycross = ycross[ix, iy, -1]\n\n if not (bxcross or bycross):\n continue\n\n ptx = interp1d(xlo, xhi, rho[ix, iy, -1], rho[ix+1, iy, -1], ys=iso) if bxcross else xlo\n pty = interp1d(ylo, yhi, rho[ix, iy, -1], rho[ix, iy+1, -1], ys=iso) if bycross else ylo\n\n pts.append(np.array([ptx, pty, zvals[-1]]))\n\n\n return np.array(pts)\n\n\n# Transform a list of (x,y,z) points to (r, x) where r=sqrt( (y-y0)**2 + (z-z0)**2 )\ndef pts_to_rhorx(pts, y0, z0):\n\n ret = np.zeros((pts.shape[0], 2))\n\n r_sq = (pts[:,1]-y0)**2 + (pts[:,2]-z0)**2\n\n ret[:,0] = np.sqrt(r_sq)\n ret[:,1] = pts[:,0]\n\n return ret\n\ny0=35.0\nz0=35\nxc = 28.5\np0 = np.array([30,10])\n\nbounds = ([0, -np.inf], [np.inf, xc])\n\n## Sum of squared errors for points, given sphere w/ radius R centered at (x0,y0,z0)\ndef x_fit(pts_yz, R, x0):\n theta = np.arccos((xc-x0)/R)\n\n mask = ((pts_yz[:,0] - y0)**2 + (pts_yz[:,1] - z0)**2) < (R*np.sin(theta))**2\n #mask = np.ones(pts_yz.shape[0]).astype(bool)\n ret = np.zeros(pts_yz.shape[0])\n\n try:\n ret[~mask] = xc\n except ValueError:\n pass\n try:\n ret[mask] = x0 + np.sqrt(R**2 - (pts_yz[mask,0] - y0)**2 - (pts_yz[mask,1] - z0)**2)\n except ValueError:\n pass\n\n\n return ret\n\ndef x_fit_noplane(pts_yz, R, x0):\n\n ret = np.zeros(pts_yz.shape[0])\n\n ret = x0 + np.sqrt(R**2 - (pts_yz[:,0] - y0)**2 - (pts_yz[:,1] - z0)**2)\n\n return ret\n\n## Any points (in y, z) that have a radial distance from y0,z0 greater than buffer*RsinTheta\nradial_buffer = 0.8\n\nrvals = np.arange(0, 31, 1)\ny0 = 35.0\nz0 = 35.0\n\nvals = np.arange(10, 61, 1)\nyy, zz = np.meshgrid(vals, vals, indexing='ij')\n\nuniv_fit = MDAnalysis.Universe.empty(n_atoms=yy.size, trajectory=True)\n\n## Set all other points to this, so we have a base line\ncent_point = np.array([28.5, 35, 35])\n\nds_reg = np.load('rhoxyz.dat.npz')\nds_cg = np.load('rhoxyz_cg.dat.npz')\n\nxbins = ds_reg['xbins']\nybins = ds_reg['ybins']\nzbins = ds_reg['zbins']\n\n#assert np.array_equal(ds_cg['xbins'], xbins)\nxvals = xbins[:-1] + 0.5*np.diff(xbins)\nyvals = ybins[:-1] + 0.5*np.diff(ybins)\nzvals = zbins[:-1] + 0.5*np.diff(zbins)\n\ndx = np.diff(xvals)[0]\ndy = np.diff(yvals)[0]\ndz = np.diff(zvals)[0]\n\nnx = xvals.size\nny = yvals.size\nnz = zvals.size\n\nexpt_waters = 0.033 * dx*dy*dz\n\n## Change rho0 to simply expt number of waters per voxel\nrho0 = np.zeros((nx, ny, nz))\nrho0[:] = expt_waters\n\n\nrho_reg = ds_reg['rho']\nrho_cg = ds_cg['rho']\n\navg_reg = rho_reg.mean(axis=0) / rho0\navg_cg = rho_cg.mean(axis=0) / 0.033\n\npts_reg = get_interp_points(avg_reg, xvals, yvals, zvals)\npts_cg = get_interp_points(avg_cg, xvals, yvals, zvals)\n\n\nuniv = MDAnalysis.Universe.empty(n_atoms=max(pts_reg.shape[0], pts_cg.shape[0]), trajectory=True)\nuniv.atoms[:pts_reg.shape[0]].positions = pts_reg\nuniv.atoms.write('surf_reg.gro')\n\n#univ.atoms.positions[:] = 0\n#univ.atoms[:pts_cg.shape[0]].positions = pts_cg\n#univ.atoms.write('surf_cg.gro')\n\n\n## Fit\npts = pts_cg.copy()\n\nnew_p0 = p0.copy()\nmax_dist = np.ceil(np.sqrt((pts[:,1] - y0)**2 + (pts[:,2] - z0)**2).max()) + 1\nif max_dist > new_p0[0]:\n new_p0[0] = max_dist\n\n## Initial fit\n## Now fit and find extent of spherical cap (e.g., y0+-RsinTheta, or z0+-RsinTheta)\nres = curve_fit(x_fit, pts[:,1:], pts[:,0], p0=new_p0, bounds=bounds)\n\n# Radius and center point x0\nR, x0 = res[0]\n\nh = xc - x0\ntheta = 180*np.arccos(h/R)/np.pi\n\n## Second fit, excluding all y, z points that are further than \nmask_radial_xy = ((pts[:,1] - y0)**2 + (pts[:,2] - z0)**2) < radial_buffer*(R * np.sin((theta/180)*np.pi))**2\ntry:\n res = curve_fit(x_fit_noplane, pts[mask_radial_xy,1:], pts[mask_radial_xy,0], p0=new_p0, bounds=bounds)\nexcept ValueError:\n pass\n \nR, x0 = res[0]\n\n## Find rmse of fit\npred = x_fit_noplane(pts[mask_radial_xy,1:], R, x0)\nmse = np.mean((pred - pts[mask_radial_xy,0])**2)\nr2 = 1 - (mse/pts[mask_radial_xy,0].var())\n\nh = xc - x0\ntheta = 180*np.arccos(h/R)/np.pi\n\n\n## FIT IT\n# Project iso points to r,x\nret = pts_to_rhorx(pts, 35, 35)\nx_of_r = x_fit(np.vstack((rvals+y0, np.ones_like(rvals)*z0)).T, R, x0)\nplt.close('all')\nax = plt.gca()\n\nax.set_xlabel(r'$r$ (nm)')\nax.set_ylabel(r'$z$ (nm)')\nax.set_ylim(0, w/10.+0.1)\n# R\nax.set_xlim(0, (Rv/10.)+0.4) \n\nax.plot([0,Rv/10.], [w/10.,w/10.], '-', color=myorange, linewidth=10)\nax.axvline(Rv/10., ymin=0, ymax=(w/10.)/ax.get_ylim()[1], linewidth=10, linestyle='-', color=myorange)\n\nax.plot(ret[:,0]/10.0, ret[:,1]/10.0-2.85, 'yx')\nax.plot(rvals/10., x_of_r/10.-2.85, 'k--', linewidth=4)\n\n#label = r'$N={}; \\theta={:.2f}$'.format(nval, theta)\n#ax.set_title(label)\n\nplt.tight_layout()\n\nplt.savefig(\"/Users/nickrego/Desktop/fig_n\")\n\n","sub_path":"scratch/cyl_sam/old/test_coarse_gaus_comparison.py","file_name":"test_coarse_gaus_comparison.py","file_ext":"py","file_size_in_byte":8853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"420897385","text":"S = input()\ndef main():\n cnt_0 = 0\n cnt_1 = 0\n for s in S:\n if s == '0':\n cnt_0 += 1\n if s == '1':\n cnt_1 += 1\n print(min(cnt_0, cnt_1)*2)\n\nif __name__ == '__main__':\n main()\n","sub_path":"atcoder_problems/atcoder_begginer_contest/120/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"432781583","text":"from typing import List\n\n\ndef bubble_sort(arr: List[int]):\n n = len(arr)\n\n def swap(i):\n arr[i], arr[i + 1] = arr[i + 1], arr[i]\n\n while n > 0:\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n swap(i)\n n -= 1\n return arr","sub_path":"DataStructures_and_Algorithms_in_PYTHON/Sorting/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"338088570","text":"import os\nimport datetime,time\nimport dateutil.relativedelta\nimport mysql.connector\nfrom datetime import datetime, date\nfrom enum import Enum, unique\nimport math\nimport numpy as np\nimport pandas as pd\nimport pandas.io.sql as sql\n\n\nnew_conn = mysql.connector.connect(host='192.168.50.151',user='search',password='search@zyxr.com', database='invest')\nnew_cursor = new_conn.cursor(dictionary=True)\n\ndef genXls():\n #找到所有定期理财的投资记录\n loanFrame=pd.DataFrame([],dtype=int,columns=[\"investor_uid\",\"loan_principal\",\"loan_interest\",\"loan_add_interest\"])\n for suffix in range(0,100):\n loansql=\"select a.investor_uid,(a.expect_principal+IFNULL(b.expect_principal,0)) as loan_principal,IFNULL(b.expect_interest,0) as loan_interest,IFNULL(b.expect_add_interest,0) as loan_add_interest from (select investor_uid,sum(expect_principal) as expect_principal from invest.t_investment_%02d where state = 2 and asset_type =0 group by investor_uid ) a left join (select investor_uid,sum(expect_principal) as expect_principal,sum(expect_interest) as expect_interest,sum(expect_add_interest) as expect_add_interest from invest.t_investment_payoff_%02d where state = 0 and asset_type =0 group by investor_uid ) b on a.investor_uid = b.investor_uid \" \\\n \"union \" \\\n \"select b.investor_uid,(IFNULL(a.expect_principal,0)+b.expect_principal) as loan_principal,b.expect_interest as loan_interest,b.expect_add_interest as loan_add_interest from (select investor_uid,sum(expect_principal) as expect_principal from invest.t_investment_%02d where state = 2 and asset_type =0 group by investor_uid ) a right join (select investor_uid,sum(expect_principal) as expect_principal,sum(expect_interest) as expect_interest,sum(expect_add_interest) as expect_add_interest from invest.t_investment_payoff_%02d where state = 0 and asset_type =0 group by investor_uid ) b on a.investor_uid = b.investor_uid;\" % (suffix,suffix,suffix,suffix)\n frame = sql.read_sql(loansql, new_conn)\n loanFrame=pd.concat([loanFrame,frame],ignore_index=True)\n #loanFrame=pd.merge(loanFrame,frame,on=\"investor_uid\",how=\"outer\")\n print(loanFrame.columns,loanFrame.index)\n # 找到所有理财计划的投资记录\n planFrame=pd.DataFrame([],dtype=int,columns=[\"investor_uid\",\"plan_principal\",\"plan_interest\",\"plan_add_interest\"])\n for suffix in range(0,100):\n plansql=\"select a.investor_uid,(a.expect_principal+IFNULL(b.expect_principal,0)) as plan_principal,IFNULL(b.expect_interest,0) as plan_interest,IFNULL(b.expect_add_interest,0) as plan_add_interest from (select investor_uid,sum(expect_principal) as expect_principal from invest.t_investment_%02d where state = 2 and asset_type = 1 group by investor_uid ) a left join (select investor_uid,sum(expect_principal) as expect_principal,sum(expect_interest) as expect_interest,sum(expect_add_interest) as expect_add_interest from specialDB.t_new_financial_plan_payoff where state = 0 group by investor_uid ) b on a.investor_uid = b.investor_uid\" % (suffix)\n frame=sql.read_sql(plansql,new_conn)\n planFrame=pd.concat([planFrame,frame],ignore_index=True)\n print(planFrame.columns,planFrame.index)\n #外链接2张表\n allFrame=pd.merge(loanFrame,planFrame,how=\"outer\",on=\"investor_uid\")\n allFrame=allFrame.fillna(0)\n allFrame=allFrame.astype(np.int64)\n #根据投资人uid找到投资人的姓名和手机号\n userFrame=pd.DataFrame([],columns=[\"investor_uid\",\"mobile\"])\n for uid in allFrame[\"investor_uid\"]:\n usersql=\"select id as investor_uid,mobile from user.t_user where id= %d \" % (uid)\n frame = sql.read_sql(usersql, new_conn)\n userFrame=pd.concat([userFrame,frame],ignore_index=True)\n allFrame = pd.merge(userFrame,allFrame, how=\"outer\", on=\"investor_uid\")\n allFrame = allFrame.fillna(0)\n allFrame = allFrame.astype(np.int64)\n allFrame.to_csv(\"./所有用户总资产汇总.csv\",index=False)\n\n\n\n\n\n\n\n#planFrame=pd.merge(planFrame,frame,on=\"investor_uid\",how=\"left\")\n #找到所有理财计划的投资记录\n #print(dataFrame.columns)\n #print(dataFrame.index)\n #print(loanFrame.columns)\n #print(planFrame.columns)\n\n\ngenXls()\n\n\n","sub_path":"python_self/工作/专门修复王武问题(长期跑)/历史总资产问题修复(重要长期跑)/所有用户总资产汇总/历史总资产汇总.py","file_name":"历史总资产汇总.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"534932911","text":"# cow\n\nimport base64\nimport click\nfrom datetime import datetime, time\nfrom dotenv import load_dotenv, find_dotenv\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport os\nimport pprint\nfrom pytz import timezone, utc\nimport re\nimport requests\nimport sys\nimport traceback\n\nclass St(object):\n def __init__(self, state_ws):\n self._ws = state_ws\n self._cells = state_ws.range(\"B1:B9\")\n state = [x.value for x in self._cells]\n\n self.locked = state[0]\n self.cstep = int(state[1])\n self.crow = int(state[2]) if int(state[2]) >= 0 else 0\n self.last_sched = int(state[3])\n self.access_token = state[4]\n self.refresh_token = state[5]\n self.group_id = state[6]\n self.defer_row = int(state[7])\n self.interval = int(state[8])\n\n def lock(self):\n self._ws.update_acell(\"B1\", \"TRUE\")\n\n def unlock(self):\n self._ws.update_acell(\"B1\", \"FALSE\")\n\n def update(self, cstep, crow, last_sched, access_token, refresh_token):\n self._cells[1].value = cstep\n self._cells[2].value = crow\n self._cells[3].value = last_sched\n self._cells[4].value = access_token\n self._cells[5].value = refresh_token\n\n self._ws.update_cells(self._cells[1:])\n\n\ndef j(relative_path):\n base_path = getattr(sys, '_MEIPASS',\n os.path.dirname(os.path.abspath(__file__)))\n return os.path.join(base_path, relative_path)\n\n\ndef read_credentials():\n creds_filename = j(\"credentials.json\")\n scope = [\n 'https://spreadsheets.google.com/feeds',\n ]\n return ServiceAccountCredentials.from_json_keyfile_name(\n creds_filename, scope)\n\n\ndef in_time(start, end, now):\n if start < end:\n return now >= start and now <= end\n else: #Over midnight\n return now >= start or now <= end\n\n\ndef schedule(interval, access_token, refresh_token, group_id, last_sched, posts):\n \"\"\"\n Env vars: CLIENT_ID, CLIENT_SECRET\n \"\"\"\n client_id = os.getenv(\"CLIENT_ID\")\n client_secret = os.getenv(\"CLIENT_SECRET\")\n\n tz = timezone(\"America/Los_Angeles\")\n sched = last_sched\n good = 0\n again = False\n\n endpoint = \"https://platform.hootsuite.com/v1/messages\"\n headers = {\"Authorization\": \"Bearer {}\".format(access_token)}\n if posts:\n try:\n now = int(datetime.now().timestamp())\n sched = max(now, last_sched)\n\n for item in posts:\n sched += interval * 60\n\n tt = tz.localize(datetime.fromtimestamp(sched))\n\n # Nobody is reading posts at 4 am.\n # We make sure that posts start at 9 am and go no later than 2 am.\n if in_time(\n time(2, 0, tzinfo=tz), time(9, 00, tzinfo=tz),\n tt.timetz()):\n tt = tt.replace(hour=9, minute=0, second=0)\n sched = int(tt.timestamp())\n\n data = {\n \"text\": item,\n \"socialProfileIds\": [group_id],\n \"scheduledSendTime\": tt.astimezone(utc).strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n }\n\n resp = requests.post(endpoint, json=data, headers=headers)\n print(resp.json())\n if \"error\" in resp.json():\n if resp.json()[\"error\"] == \"request_forbidden\":\n again = True\n resp.raise_for_status()\n\n good += 1\n except:\n traceback.print_exc()\n print(\"err | an error occurred\")\n\n if again:\n try:\n print(\n \"inf | old hootsuite access token expired. tryna get a new one...\"\n )\n s = \"{}:{}\".format(client_id, client_secret)\n auth = base64.b64encode(s.encode(\"ascii\")).decode(\"utf-8\")\n headers = {\"Authorization\": \"Basic {}\".format(auth)}\n data = {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": refresh_token\n }\n resp = requests.post(\n \"https://platform.hootsuite.com/oauth2/token\",\n data=data,\n headers=headers)\n resp.raise_for_status()\n resp = resp.json()\n\n return schedule(interval, resp[\"access_token\"], resp[\"refresh_token\"],\n group_id, last_sched, posts[good:])\n except:\n print(\"err | failed...\")\n\n return (good, sched, access_token, refresh_token)\n\n\n##########\n# REVIEW #\n##########\ndef review():\n \"\"\"Reviews submissions.\n\n Required environment vars: SHEET_URL\n Magic files: credentials.json\n \"\"\"\n click.echo(\"inf | confessions mgr v2018.07.24\")\n sheet_url = os.getenv(\"SHEET_URL\")\n post_r = re.compile(\"@[0-9]+\")\n\n try:\n click.echo(\"inf | attempting to get google api credentials...\")\n gc = gspread.authorize(read_credentials())\n except Exception as e:\n traceback.print_exc()\n click.echo(\"err | couldn't read google api credentials.\")\n click.echo(\"err | debug information has been printed.\")\n return\n\n try:\n sh = gc.open_by_url(sheet_url)\n except Exception as e:\n traceback.print_exc()\n click.echo(\"err | this sheet doesn't exist. maybe you need to share\")\n click.echo(\" | it with the client_email first?\")\n click.echo(\"err | debug information has been printed.\")\n return\n\n click.echo(\"inf | loading worksheet data.\")\n click.echo(\" | this may take a while...\")\n\n confessions = sh.get_worksheet(0)\n prevs = sh.get_worksheet(1)\n prev_vals = {int(a[0]): int(a[1]) for a in prevs.get_all_values()}\n old_prev = len(prev_vals)\n state_ws = sh.get_worksheet(2)\n state = St(state_ws)\n\n if state.locked == \"FALSE\":\n try:\n # we're not locked; lock it\n state.lock()\n # note: STATE FORMAT: B1 is locked, B2 is current step (the number\n # before every confession on the fb page), B3 is current row (the\n # row of the confession we're currently on)\n cstep = state.cstep\n cstep_inc = 0\n crow = state.crow\n rc = 0\n last_sched = state.last_sched\n strs = []\n\n click.echo(\"inf | beginning the review process.\")\n click.echo(\"inf | When prompted for a deliberation, the following options are available:\")\n click.echo(\" | y - approve\")\n click.echo(\" | p - approve [p]lain, without quoting previous confessions\")\n click.echo(\" | n - reject\")\n click.echo(\" | q - quit\")\n click.echo(\" | anything else will be added as text after the confession.\")\n\n # List comprehension to ignore timestamps\n items_all = [x[1].rstrip(\"\\r\\n\") for x in confessions.get_all_values()[1:]]\n items = items_all[crow:]\n\n # TODO: Spam detection.\n\n try:\n for item in items:\n # TODO: spam detection.\n # if this message is exactly the same as one seen before.\n\n # traverse: auto-quote previous.\n prev_csteps = []\n ix = -1\n\n cur_text = item\n cur_cstep = cstep + cstep_inc\n while True:\n matches = [\n int(x[1:]) for x in post_r.findall(cur_text)\n if int(x[1:]) not in prev_csteps\n and int(x[1:]) in prev_vals\n and int(x[1:]) < cur_cstep\n ]\n prev_csteps += matches\n ix += 1\n if ix >= len(prev_csteps):\n break\n else:\n cur_cstep = prev_csteps[ix]\n cur_text = items_all[prev_vals[cur_cstep]]\n\n # Printing\n prev_csteps.sort(reverse=True)\n orig = item.rstrip(\"\\r\\n\")\n text = orig + \"\\n\"\n for prev in prev_csteps:\n text += \"\\n\\\"{})\\n{}\\\"\".format(\n prev, items_all[prev_vals[prev]])\n text = text.rstrip(\"\\n\\n\")\n\n click.echo(\"rev | next confession:\")\n click.echo(\"{})\\n{}\".format(cstep + cstep_inc, text))\n prompt = click.prompt(\"rev > Deliberation\")\n if prompt.lower() == \"y\":\n strs.append((cstep_inc, rc, \"{})\\n{}\".format(\n cstep + cstep_inc, text)))\n prev_vals[cstep + cstep_inc] = crow + rc\n cstep_inc += 1\n elif prompt.lower() == \"p\":\n strs.append((cstep_inc, rc, \"{})\\n{}\".format(\n cstep + cstep_inc, orig)))\n prev_vals[cstep + cstep_inc] = crow + rc\n cstep_inc += 1\n elif prompt.lower() == \"n\":\n pass\n elif prompt.lower() == \"q\":\n raise click.Abort()\n else:\n strs.append((cstep_inc, rc, \"{})\\n{}\\n{}\".format(\n cstep + cstep_inc, orig, prompt)))\n prev_vals[cstep + cstep_inc] = crow + rc\n cstep_inc += 1\n\n rc += 1\n except click.Abort:\n click.echo()\n click.echo(\"inf | aborted. {} items reviewed.\".format(rc))\n else:\n click.echo(\n \"inf | end of queue reached. {} items reviewed.\".format(\n rc))\n\n # propagate changes: post.\n # We try to post what we have; otherwise, we give up\n click.echo(\"inf | scheduling {} approved posts... (this will take a long while)\".format(cstep_inc))\n good, new_sched, access_token, refresh_token = schedule(\n state.interval, state.access_token, state.refresh_token,\n state.group_id, last_sched, [x[2] for x in strs])\n if good != cstep_inc:\n click.echo(\n \"err | {} approved post(s) could not be scheduled.\".format(\n rc - good))\n click.echo(\n \" | wait before approving more posts for up to a day.\")\n\n # update state.\n state.update(\n str(cstep if good == 0 else cstep + strs[good - 1][0] + 1),\n str(crow if good == 0 else crow + strs[good - 1][1] + 1),\n str(new_sched), access_token, refresh_token)\n else:\n click.echo(\"inf | done.\")\n # set the new cstep and crow.\n state.update(\n str(cstep + cstep_inc), str(crow + rc), str(new_sched),\n access_token, refresh_token)\n\n if good > 0:\n vals = sorted(prev_vals.items(), key=lambda x: x[0])[old_prev:]\n cs = prevs.range(old_prev + 1, 1, old_prev + good, 1)\n for i, c in enumerate(cs):\n c.value = vals[i][0]\n prevs.update_cells(cs)\n\n cs = prevs.range(old_prev + 1, 2, old_prev + good, 2)\n for i, c in enumerate(cs):\n c.value = vals[i][1]\n prevs.update_cells(cs)\n\n except Exception as e:\n traceback.print_exc()\n click.echo(\"err | something went wrong...\")\n click.echo(\" | debug information has been printed.\")\n finally:\n state.unlock()\n else:\n # we're locked\n click.echo(\"err | the responses sheet is currently locked.\")\n click.echo(\" | another admin is probably reviewing submissions.\")\n click.echo(\" |\")\n click.echo(\" | if this is not true, go into the 'state' worksheet\")\n click.echo(\" | and set 'locked' to 'FALSE'.\")\n\n\nif __name__ == '__main__':\n load_dotenv(dotenv_path=j(\".env\"))\n review()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":12340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"474968433","text":"# mypy: ignore-errors\n\nfrom http import HTTPStatus\n\nimport pytest\nfrom asgi_testclient import TestClient\nfrom jsondaora import integer, jsondaora, string\n\nfrom apidaora import MethodType\nfrom apidaora.core.app import asgi_app\nfrom apidaora.core.headers import Headers\nfrom apidaora.core.request import Body as RequestBody\nfrom apidaora.core.request import PathArgs, Query, Request\nfrom apidaora.core.response import Body as ResponseBody\nfrom apidaora.core.response import JSONResponse\nfrom apidaora.core.router import Route\n\n\n@jsondaora\nclass FakePathArgs(PathArgs):\n id: int\n\n\n@jsondaora\nclass FakeQuery(Query):\n query: int\n\n\n@jsondaora\nclass FakeHeaders(Headers):\n x_header: float\n\n\n@jsondaora\nclass FakeBody(RequestBody):\n string: str\n integer: int\n\n\n@jsondaora\nclass FakeRequest(Request):\n path_args: FakePathArgs\n query: FakeQuery\n headers: FakeHeaders\n body: FakeBody\n\n\n@jsondaora\nclass Faked:\n string: string(max_length=100)\n integer: integer(minimum=18)\n\n\n@jsondaora\nclass FakeResponseBody(ResponseBody):\n faked: Faked\n\n\n@jsondaora\nclass FakeResponse(JSONResponse):\n body: FakeResponseBody\n headers: FakeHeaders\n\n\ndef fake_controller(req: FakeRequest) -> FakeResponse:\n return FakeResponse(\n body=FakeResponseBody(\n faked=Faked(string=req.body['string'], integer=req.body['integer'])\n ),\n headers=FakeHeaders(x_header=req.headers['x_header']),\n )\n\n\n@pytest.fixture\ndef fake_app():\n return asgi_app([Route('/api/{id}', MethodType.GET, fake_controller)])\n\n\n@pytest.fixture\ndef test_client(fake_app):\n return TestClient(fake_app)\n\n\n@pytest.mark.asyncio\nasync def test_should_return_not_found(test_client):\n response = await test_client.get('/not-found')\n assert response.status_code == HTTPStatus.NOT_FOUND.value\n assert response.content == b''\n assert not response.headers\n\n\n@pytest.mark.asyncio\nasync def test_should_return_method_not_allowed(test_client):\n response = await test_client.post('/api')\n assert response.status_code == HTTPStatus.METHOD_NOT_ALLOWED.value\n assert response.content == b''\n assert not response.headers\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_path_arg(test_client):\n response = await test_client.get('/api/invalid')\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'int',\n 'field': 'id',\n 'invalid_value': 'invalid',\n 'name': 'ValueError',\n 'cls': 'FakePathArgs',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_empty_query(test_client):\n response = await test_client.get('/api/1')\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'int',\n 'field': 'query',\n 'invalid_value': None,\n 'cls': 'FakeQuery',\n 'name': 'ParameterNotFoundError',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_invalid_type_query(test_client):\n response = await test_client.get('/api/1', params={'query': 'invalid'})\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'int',\n 'field': 'query',\n 'invalid_value': 'invalid',\n 'name': 'ValueError',\n 'cls': 'FakeQuery',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_empty_header(test_client):\n response = await test_client.get('/api/1', params={'query': '1'})\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'float',\n 'field': 'x_header',\n 'invalid_value': None,\n 'cls': 'FakeHeaders',\n 'name': 'ParameterNotFoundError',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_invalid_type_header(test_client):\n response = await test_client.get(\n '/api/1', params={'query': '1'}, headers={'x-header': 'invalid'}\n )\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'float',\n 'field': 'x_header',\n 'invalid_value': 'invalid',\n 'name': 'ValueError',\n 'cls': 'FakeHeaders',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_empty_body(test_client):\n response = await test_client.get(\n '/api/1', params={'query': '1'}, headers={'x-header': '0.1'}\n )\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'str',\n 'field': 'string',\n 'invalid_value': None,\n 'name': 'ParameterNotFoundError',\n 'cls': 'FakeBody',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_bad_request_on_invalid_type_body(test_client):\n response = await test_client.get(\n '/api/1',\n params={'query': '1'},\n headers={'x-header': '0.1'},\n json={'string': 'str', 'integer': 'str'},\n )\n assert response.status_code == HTTPStatus.BAD_REQUEST.value\n assert response.json() == {\n 'error': {\n 'type': 'int',\n 'field': 'integer',\n 'invalid_value': 'str',\n 'name': 'ValueError',\n 'cls': 'FakeBody',\n }\n }\n\n\n@pytest.mark.asyncio\nasync def test_should_return_ok(test_client):\n response = await test_client.get(\n '/api/1',\n params={'query': '1'},\n headers={'x-header': '0.1'},\n json={'integer': '1', 'string': 'apidaora'},\n )\n assert response.status_code == HTTPStatus.OK.value\n assert response.json() == {'faked': {'string': 'apidaora', 'integer': 1}}\n assert dict(response.headers) == {\n 'x-header': '0.1',\n 'Content-Type': 'application/json',\n 'Content-Length': '43',\n }\n","sub_path":"apidaora/core/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"166045784","text":"\"\"\"\nModule that contains the command line app.\n\nWhy does this file exist, and why not put this in __main__?\n\n You might be tempted to import things from __main__ later, but that will cause\n problems: the code will get executed twice:\n\n - When you run `python -mrh_nexttask` python will execute\n ``__main__.py`` as a script. That means there won't be any\n ``rh_nexttask.__main__`` in ``sys.modules``.\n - When you import __main__ it will get executed again (as a module) because\n there's no ``rh_nexttask.__main__`` in ``sys.modules``.\n\n Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration\n\"\"\"\nimport click\nimport logging\nimport os\nimport sys\nfrom rh_nexttask.query import Query\nfrom rh_nexttask.querycollector import QueryCollector\nfrom rh_nexttask.bzcollector import BzCollector\nfrom rh_nexttask.adviser import Adviser\nfrom rh_nexttask.renderer import Renderer\n\nlogging.basicConfig()\nlogger = logging.getLogger('rh-nexttask')\n\n\n@click.command()\n@click.option('--query',\n help='Which query to use. Use \"list\" to get the in the filter file')\n@click.option('--queryfile',\n help='Filter definition file to use.',\n type=click.Path(exists=True))\n@click.option('--tokenfile',\n help='Tokenfile to use, default to ~/.bugzillatoken',\n type=click.Path(exists=True),\n default=os.path.expanduser('~/.bugzillatoken'))\n@click.option('--render',\n multiple=True,\n default=['echo'],\n help='Renderer to use, can be repeated. Default to echo. Use \"list\" to get their names.')\n@click.option('--show',\n multiple=True,\n default=[],\n help='Show only those states. Can be repeated. Default to None. Use \"list\" to get their names. Can be inverted by prefixing with \"no-\"')\n@click.option('--user',\n default=None,\n help='Show only the bz belonging to that user email.')\n@click.option('--debug',\n default=None,\n type=int,\n help='Developer option. Enable debug console on the specified bz id.')\n@click.option('--bz-id',\n default=[],\n type=int,\n multiple=True,\n help='Get advice on this bug. Will take precedence on other query options.')\n@click.option('--dump',\n default=None,\n help='dump all the bz (pickle) in a file for later re-use with --restore ')\n@click.option('--restore',\n default=None,\n type=click.Path(exists=True),\n help='dump all the bz (pickle) in a file for later re-use with --restore ')\n@click.option('--log-level',\n default=None,\n help='Log level to use: debug, info')\n@click.option('--dump-query',\n default=None,\n help=\"Dump the metric. Give a tag (no space txt) as argument.\")\ndef main(query, queryfile, tokenfile, render, show, user, debug, bz_id, dump, restore, log_level, dump_query):\n if log_level:\n if log_level == 'debug':\n logger.setLevel(logging.DEBUG)\n elif log_level == 'info':\n logger.setLevel(logging.INFO)\n else:\n logger.setLevel(logging.CRITICAL)\n adviser = Adviser(debug)\n\n if 'list' in show:\n click.echo(adviser)\n sys.exit()\n\n for advice in show:\n real_name_advice = advice\n if advice.find('no-') == 0:\n real_name_advice = advice[3:]\n if real_name_advice not in adviser.available_advices:\n raise click.UsageError(\"Advice \\\"{}\\\" is not available.\\n{}\".format(advice,\n adviser))\n if 'list' in render:\n click.echo(Renderer(None).list_str())\n sys.exit()\n\n renderer_list = Renderer(None).list()\n for display in render:\n if display not in renderer_list:\n raise click.UsageError(\"Render \\\"{}\\\" is not available.\\n{}\".format(display,\n Renderer(None).list_str()))\n\n if dump_query:\n if bz_id:\n query = Query.from_bz(bz_id)\n click.echo(\"[{}]\\nurl = {}\\ndocumentation = \\nextra = {}\".format(dump_query,\n query.bz_query_url,\n ','.join([str(bz) for bz in bz_id])))\n sys.exit()\n else:\n raise click.UsageError(\"dump-query work only with --bz-id option.\")\n\n if restore:\n bzc = BzCollector.from_pickle(restore)\n bzs = bzc._bugs\n if bz_id:\n bzs = [bz for bz in bzs if bz.id in bz_id]\n if user:\n bzs = [bz for bz in bzs if bz.assigned_to == user]\n elif bz_id:\n query = Query.from_bz(bz_id)\n q_json = query.request()\n bzc = BzCollector(tokenfile)\n bzs = bzc.bugs(q_json)\n else:\n if not queryfile:\n raise click.UsageError(\"You must give a filter file.\")\n queryfile = os.path.abspath(queryfile)\n if not query:\n raise click.UsageError(\"You must give a query to choose from queryfile.\")\n if query == 'list':\n click.echo(QueryCollector.from_file(queryfile).list_str())\n sys.exit()\n if query not in QueryCollector.from_file(queryfile).list():\n raise click.UsageError(\"Query \\\"{}\\\" is not available.\\n{}\".format(query,\n QueryCollector.from_file(queryfile).list_str()))\n\n qcollector = QueryCollector.from_file(queryfile)\n extra_fields = {}\n if user:\n extra_fields.update({'assigned_to': user})\n query = qcollector.select(query)\n q_json = query.request(extra_fields)\n if not q_json:\n click.error('{} is not part of {}'.format(q_json, queryfile))\n bzc = BzCollector(tokenfile, query.dfg)\n bzs = bzc.bugs(q_json)\n\n if dump:\n bzc.to_pickle(dump)\n\n for bz in bzs:\n adviser.advice(bz)\n selected_bz = []\n filter_removal = []\n for f in show:\n real_name_advice = f\n if f.find('no-') == 0:\n filter_removal += [f[3:]]\n else:\n selected_bz += [b for b in bzs if getattr(b, '_{}'.format(f), False)]\n if not selected_bz and not show:\n selected_bz = bzs\n for f in filter_removal:\n selected_bz = [b for b in selected_bz if not getattr(b, '_{}'.format(f), False)]\n\n renderer = Renderer(selected_bz)\n for display in render:\n if len(render) > 1:\n click.echo(\"{} ======\".format(display))\n getattr(renderer, 'r_{}'.format(display))()\n","sub_path":"src/rh_nexttask/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"611574646","text":"#!/usr/bin/env python\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='An example python script, ready for extensions.')\nparser.add_argument('--jens', action = 'store_true')\nparser.add_argument('--carsten', action = 'store_true')\n\nargs = parser.parse_args()\n\nprint(\"Hello, Loosolab!\")\n\nif(args.jens):\n print(\"Hello, Jens!\")\nif(args.carsten):\n print(\"Hello, Superman!\")\n","sub_path":"script_01.py","file_name":"script_01.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640644485","text":"# Script made to test Game Theory methodology \nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nimport math\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn import linear_model\nfrom termcolor import cprint\nfrom sklearn.metrics import mean_squared_error, r2_score\n \ndef normal(x,avg,std):\n pi =math.pi\n upper_term = -(x-avg)**2/(2*std**2)\n f = 1/((2*pi)**0.5 *std) * math.exp(upper_term)\n return f\n\ndef include_3dnormal(df,x_column,y_column, avg_x,std_x,avg_y,std_y,factor,z_column_out):\n df['z_x']=df[x_column].apply(lambda x: factor*normal(x,avg_x,std_x))\n df['z_y']=df[y_column].apply(lambda y: factor*normal(y,avg_y,std_y))\n df[z_column_out]=df['z_x']*df['z_y']\n df.drop(columns =['z_x','z_y'],inplace = True)\n return df\n\ndef plot_3D(df,x_variable='x',y_variable='y',z_variable='z',datapoints = [], view_2D=False):\n '''The data frame should contain the name of all the 3 variables given in the function'''\n #Just to show image:\n pointer =0\n x = samples_df[x_variable].values\n y = samples_df[y_variable].values\n z = samples_df[z_variable].values\n X,Y,Z=[],[],[]\n image_factor = 1\n for i in range(n_variablesx//image_factor):\n X.append(x[pointer:pointer+n_variablesy])\n Y.append(y[pointer:pointer+n_variablesy])\n Z.append(z[pointer:pointer+n_variablesy])\n pointer += n_variablesy*image_factor\n\n X =np.array(X)\n Y =np.array(Y)\n Z =np.array(Z)\n if view_2D == False:\n plt.figure(figsize=(7,7))\n ax = plt.axes(projection='3d')\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap='winter', edgecolor='none', alpha=0.5)\n if len(datapoints)>0:\n ax.scatter(datapoints[:, 0], datapoints[:, 1], datapoints[:, 2], c='black', marker='o')\n ax.set_title('surface')\n ax.set_xlabel(x_variable)\n ax.set_ylabel(y_variable)\n ax.set_zlabel(z_variable)\n\n else:\n plt.figure(figsize=(7,7))\n ax = plt.axes()\n if len(datapoints)>0:\n ax.contourf(X, Y, Z, zdir='z', offset=0, cmap=cm.coolwarm)\n ax.scatter(datapoints[:, 0], datapoints[:, 1], c='black', marker='o')\n ax.set_title('surface')\n ax.set_xlabel(x_variable)\n ax.set_ylabel(y_variable)\n plt.show()\n\ndef move_score(position):\n \"\"\"Function to get score of a position given by the player\n \n Arguments:\n position {[array]} -- [position of the player move]\n \n Returns:\n [float] -- [returns the score of the position given]\n \"\"\"\n avg_x,std_x = 15,7\n avg_y,std_y = 38,10\n factor =200\n z1 = factor*normal(position[0],avg_x,std_x) * factor * normal(position[1],avg_y,std_y)\n z2 = factor*normal(position[0],avg_x*2,std_x) * factor * normal(position[1],avg_y/2,std_y)\n score = z1 + z2\n return score\n\nclass player:\n def __init__(self,position, space_ranges,gambles=5,start_variable=0, factor_space = 5,score=0):\n self.position=position\n self.space_ranges=space_ranges\n self.n_of_variables = len(position)\n self.analysed_variable = start_variable\n self.score = score\n self.gambles = gambles\n self.test_positions=[]\n self.test_scores=[]\n self.fails = 0\n self.factor_space = factor_space\n\n def update_tests(self,game_function):\n test_positions =[]\n test_scores =[]\n start,end = self.space_ranges[self.analysed_variable][0],self.space_ranges[self.analysed_variable][1]\n step = (end-start)/(self.gambles-1)\n new_variable_positions=np.arange(start=start,stop=end+step,step=step)\n for gamble in range(self.gambles):\n new_position = self.position.copy()\n new_position[self.analysed_variable] = new_variable_positions[gamble]\n new_score = game_function(new_position)\n test_positions.append(new_position)\n test_scores.append(new_score)\n self.test_positions =test_positions\n self.test_scores = test_scores\n \n def update_variable(self):\n if self.analysed_variable + 1 >= len(self.position):\n self.analysed_variable = 0\n else:\n self.analysed_variable += 1\n \n def update_space_ranges(self):\n variable =0\n for space_range in self.space_ranges:\n new_min = self.position[variable] - (self.position[variable] - space_range[0])/self.factor_space\n new_max = self.position[variable] + (space_range[1] - self.position[variable])/self.factor_space\n self.space_ranges[variable][0] = new_min\n self.space_ranges[variable][1] = new_max\n variable +=1\n\n def update(self):\n initial_score = self.score\n for gamble in range(len(self.test_scores)):\n if self.test_scores[gamble] >= self.score:\n self.score = self.test_scores[gamble]\n self.position = self.test_positions[gamble]\n\n if self.score > initial_score:\n cprint('Player have found a better position','green')\n print('New position = ',self.score)\n print('New score = ',self.position,end='\\n\\n')\n self.fails = 0\n else:\n cprint('Player did not found a better position \\n','red')\n self.fails +=1\n \n if self.fails >= self.n_of_variables:\n cprint('No more increase on score possible -> Player will decrease space range','yellow')\n self.update_space_ranges()\n self.fails = 0\n \n\n#Define variables\nn_variablesx=50\nn_variablesy=50\navg_x,std_x = 15,7\navg_y,std_y = 38,10\nfactor =200\nsamples =[]\nfor i in range(n_variablesx):\n for j in range(n_variablesy):\n samples.append([i,j])\n\nsamples_df=pd.DataFrame(samples)\nsamples_df.rename(columns={0:'x',1:'y'},inplace = True )\n\nsamples_df = include_3dnormal(samples_df,'x','y', avg_x,std_x,avg_y,std_y,factor,'z1')\nsamples_df = include_3dnormal(samples_df,'x','y', avg_x*2,std_x,avg_y/2,std_y,factor,'z2')\nsamples_df['z']=samples_df['z1']+samples_df['z2']\n\n#Now the we have our system we can worry about the players\nplayer1 = player(position = [1,1], space_ranges = [[0,50],[0,50]], gambles=10,start_variable=1)\ninterations = 20\n\nplayer_walk =[]\nplayer_walk.append(player1.position + [player1.score])\n\nfor interation in range(interations):\n cprint('----------\\nInteration = '+str(interation),'blue')\n player1.update_tests(move_score)\n player1.update()\n player1.update_variable()\n\n #Just to get path of player\n player_walk.append(player1.position + [player1.score])\n\n#Just to show image:\nplayer_walk=np.array(player_walk)\nplot_3D(samples_df,datapoints= player_walk)\nplot_3D(samples_df,datapoints= player_walk,view_2D=True)","sub_path":"Game_Theory_v1.py","file_name":"Game_Theory_v1.py","file_ext":"py","file_size_in_byte":6779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"626482726","text":"import classes as c\r\n\r\ndef obtenerDatos(infile, nlines, n, mode, item_list):\r\n line = infile.readline()\r\n if nlines == c.lines.DOUBLELINE.value : \r\n line = infile.readline()\r\n line = infile.readline()\r\n for i in range(n):\r\n if mode == c.modes.INT_FLOAT.value:\r\n condition = c.condition()\r\n line = infile.readline()\r\n words = []\r\n for word in line.split():\r\n words.append(word)\r\n condition.setValues(c.indicators.NOTHING.value, c.indicators.NOTHING.value, c.indicators.NOTHING.value, int(words[0]), c.indicators.NOTHING.value, c.indicators.NOTHING.value, float(words[1]))\r\n item_list.append(condition) \r\n\r\n if mode == c.modes.INT_FLOAT_FLOAT.value:\r\n node = c.node()\r\n line = infile.readline()\r\n words = []\r\n for word in line.split():\r\n words.append(word)\r\n node.setValues(int(words[0]),float(words[1]), float(words[2]), c.indicators.NOTHING.value, c.indicators.NOTHING.value, c.indicators.NOTHING.value, c.indicators.NOTHING.value)\r\n item_list.append(node)\r\n\r\n if mode == c.modes.INT_INT_INT_INT.value:\r\n element = c.element()\r\n line = infile.readline()\r\n words=[]\r\n for word in line.split():\r\n words.append(word)\r\n element.setValues(int(words[0]), c.indicators.NOTHING.value, c.indicators.NOTHING.value, int(words[1]), int(words[2]), int(words[3]), c.indicators.NOTHING.value)\r\n item_list.append(element)\r\n\r\ndef correctConditions(n, list, indices):\r\n for i in range(n):\r\n indices.insert(i, list[i].getNode1())\r\n \r\n for i in range(n-1):\r\n pivot = list[i].getNode1()\r\n for j in range(n):\r\n if list[j].getNode1() > pivot :\r\n list[j].setNode1(list[j].getNode1() - 1)\r\n\r\ndef addExtension(newfilename, filename, extension):\r\n for i in filename:\r\n newfilename += i\r\n for i in extension:\r\n newfilename += i\r\n return newfilename\r\n\r\ndef leerMallayCondiciones(m, filename):\r\n inputfilename = ''\r\n inputfilename = addExtension(inputfilename, filename, '.dat')\r\n infile = open(inputfilename, 'r')\r\n\r\n wordsline = []\r\n line1 = infile.readline()\r\n line2 = infile.readline()\r\n \r\n for word in line1.split():\r\n wordsline.append(word)\r\n \r\n k = float(wordsline[0])\r\n Q = float(wordsline[1])\r\n\r\n wordsline = []\r\n for word in line2.split():\r\n wordsline.append(word)\r\n\r\n nnodes = int(wordsline[0])\r\n neltos = int(wordsline[1])\r\n ndirich = int(wordsline[2])\r\n nneu = int(wordsline[3])\r\n\r\n m.setParameters(k, Q)\r\n m.setSizes(nnodes, neltos, ndirich, nneu)\r\n m.createData()\r\n\r\n infile.readline()\r\n obtenerDatos(infile, c.lines.SINGLELINE.value, nnodes, c.modes.INT_FLOAT_FLOAT.value, m.getNodes())\r\n obtenerDatos(infile,c.lines.DOUBLELINE.value, neltos, c.modes.INT_INT_INT_INT.value, m.getElements())\r\n obtenerDatos(infile, c.lines.DOUBLELINE.value, ndirich, c.modes.INT_FLOAT.value, m.getDirichlet())\r\n obtenerDatos(infile, c.lines.DOUBLELINE.value, nneu, c.modes.INT_FLOAT.value, m.getNeumann())\r\n\r\n infile.close()\r\n #Se corrigen los índices en base a las filas que serán eliminadas\r\n #luego de aplicar las condiciones de Dirichlet\r\n correctConditions(ndirich, m.getDirichlet(), m.getDirichletIndices())\r\n\r\ndef findIndex(v , s, arr):\r\n for i in range(s):\r\n if arr[i] == v : return True\r\n return False\r\n\r\ndef writeResults(m, T, filename):\r\n outputfilename = ''\r\n dirich_indices = m.getDirichletIndices()\r\n dirich = m.getDirichlet()\r\n\r\n outputfilename = addExtension(outputfilename, filename, '.post.res')\r\n infile = open(outputfilename,\"w+\")\r\n\r\n infile.write(\"GiD Post Results File 1.0\\n\")\r\n infile.write(\"Result \\\"Temperature\\\" \\\"Load Case 1\\\" 1 Scalar OnNodes\\nComponentNames \\\"T\\\"\\nValues\\n\")\r\n\r\n Dpos = 0\r\n Tpos = 0\r\n nd = m.getSize(c.sizes.DIRICHLET.value)\r\n n = m.getSize(c.sizes.NODES.value)\r\n \r\n\r\n for i in range(n):\r\n if findIndex( i+1, nd, dirich_indices):\r\n infile.write(str(i+1) + \" \" + str(dirich[Dpos].getValue()) + \"\\n\")\r\n Dpos += 1\r\n else:\r\n infile.write(str(i+1) + \" \" + str(T[Tpos]) + \"\\n\")\r\n Tpos += 1\r\n \r\n infile.write(\"End values\\n\")\r\n\r\n infile.close()","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"382704025","text":"# -*- coding: utf-8 -*-\n# Author: XuMing(xuming624@qq.com)\n# Brief: \nimport json\nimport os\nimport pickle\nfrom collections import defaultdict\n\n\ndef load_pkl(pkl_path):\n \"\"\"\n 加载词典文件\n :param pkl_path:\n :return:\n \"\"\"\n with open(pkl_path, 'rb') as f:\n result = pickle.load(f)\n return result\n\n\ndef save_pkl(vocab, pkl_path, overwrite=True):\n \"\"\"\n 存储文件\n :param pkl_path:\n :param overwrite:\n :return:\n \"\"\"\n if os.path.exists(pkl_path) and not overwrite:\n return\n with open(pkl_path, 'wb') as f:\n # pickle.dump(vocab, f, protocol=pickle.HIGHEST_PROTOCOL)\n pickle.dump(vocab, f, protocol=0)\n\n\ndef load_json(json_path, encoding='utf-8'):\n with open(json_path, mode='r', encoding=encoding) as json_file:\n data = json.load(json_file)\n return data\n\n\ndef save_json(data, json_path, mode='w', encoding='utf-8'):\n dir = os.path.dirname(os.path.abspath(json_path))\n if not os.path.exists(dir):\n print(dir)\n os.makedirs(dir)\n with open(json_path, mode=mode, encoding=encoding) as f:\n f.write(json.dumps(data, ensure_ascii=False, indent=4))\n\n\ndef write_vocab(vocab, filename):\n \"\"\"Writes a vocab to a file\n\n Writes one word per line.\n\n Args:\n vocab: iterable that yields word\n filename: path to vocab file\n\n Returns:\n write a word per line\n\n \"\"\"\n print(\"Writing vocab...\")\n with open(filename, \"w\", encoding='utf-8') as f:\n for i, word in enumerate(vocab):\n if i != len(vocab) - 1:\n f.write(word + '\\n')\n else:\n f.write(word)\n print(\"- write to {} done. {} tokens\".format(filename, len(vocab)))\n\n\ndef load_vocab(filename):\n \"\"\"Loads vocab from a file\n\n Args:\n filename: (string) the format of the file must be one word per line.\n\n Returns:\n d: dict[word] = index\n\n \"\"\"\n try:\n d = dict()\n with open(filename, 'r', encoding='utf-8') as f:\n for idx, word in enumerate(f):\n word = word.strip()\n d[word] = idx\n\n except IOError:\n raise IOError(filename)\n return d\n\n\ndef build_vocab(items, sort=True, min_count=0, lower=False):\n \"\"\"\n 构建词典列表\n :param items: list [item1, item2, ... ]\n :param sort: 是否按频率排序,否则按items排序\n :param min_count: 词典最小频次\n :param lower: 是否小写\n :return: list: word set\n \"\"\"\n result = []\n if sort:\n # sort by count\n dic = defaultdict(int)\n for item in items:\n item = item if not lower else item.lower()\n dic[item] += 1\n # sort\n dic = sorted(dic.items(), key=lambda d: d[1], reverse=True)\n for i, item in enumerate(dic):\n key = item[0]\n if min_count and min_count > item[1]:\n continue\n result.append(key)\n else:\n # sort by items\n for i, item in enumerate(items):\n item = item if not lower else item.lower()\n result.append(item)\n return result\n","sub_path":"wordrank/utils/io_utils.py","file_name":"io_utils.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"531033983","text":"import sys #to read from stdin\n\nclass Node:\n def __init__(self, row_ind, col_ind, parent, depth, action=''):\n self.state = [row_ind,col_ind]\n self.parent = parent\n self.children = []\n self.action = action\n self.depth = depth\n #self.depth = self.parent.depth+1\n #components: state, parent, children, action, depth, path-cost=depth\n\n#implements breadth-first search strategy\ndef expand(node,labyrinth):\n nodes=[]\n r=node.state[0]\n c=node.state[1]\n #upwards expansion\n if r > 0:\n if labyrinth[r-1][c] != '#':\n child=Node(r-1,c,node,node.depth+1,action='up') # this should be down\n nodes.append(child)\n #downwards expansion\n if r < len(labyrinth)-1:\n if labyrinth[r+1][c] != '#':\n child=Node(r+1,c,node,node.depth+1,action='down') #this should be up\n nodes.append(child)\n #leftward expansion\n if c > 0:\n if labyrinth[r][c-1] != '#':\n child=Node(r,c-1,node,node.depth+1,action='left')\n nodes.append(child)\n #rightward expansion\n if c < len(labyrinth[0])-1:\n if labyrinth[r][c+1] != '#':\n child=Node(r,c+1,node,node.depth+1,'right')\n nodes.append(child)\n return nodes\n\n#returns the number of steps needed to reach the goal\ndef steps_to_goal():\n lab=[]\n n=None #state variable: agent row index\n m=None #state variable: agent column index\n\n #represent labyrinth input and find initial position of the agent\n input=sys.stdin.readlines()\n for line in input:\n row=[]\n row_values=list(line.rstrip('\\n'))\n for char in row_values:\n if char == '@':\n n=input.index(line)\n m=row_values.index(char)\n row.append(char)\n lab.append(row)\n\n #breadth-first graph-search: find goal and record number of steps taken\n closed=[]\n fringe=[]\n node = Node(row_ind=n,col_ind=m, parent=None, depth=0)#initial node\n fringe.append(node)#initial fringe\n while True:\n if fringe==[]:\n return None\n node = fringe.pop(0)\n if lab[node.state[0]][node.state[1]]=='.': #goal-test\n return node.depth\n if node.state not in closed:\n closed.append(node.state)\n fringe=fringe + expand(node,lab)\n\nprint(steps_to_goal())\n","sub_path":"Labyrinth.py","file_name":"Labyrinth.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"228677569","text":"'''\nBased on the basic functions in tifffunc.py, Here are some stack operations that can substitute messy macros in ImageJ.\nCreated by Dan Xie on 04/06/2017.\n'''\nimport sys\nsys.path.append('/home/sillycat/Programming/Python/Image_toolbox/')\nimport src\nimport numpy as np\nimport src.shared_funcs.tifffunc as tf\nimport pyfftw\nimport glob\nimport os\nimport src.shared_funcs.string_funcs as sfc\n\nglobal_datapath = '/home/sillycat/Programming/Python/Image_toolbox/data_test/'\nregist_path = '/home/sillycat/Programming/Python/Image_toolbox/cmtkRegistration/'\n\n\ndef pyfftw_container(ny, nx, bwd = False):\n '''\n construct a fftw container to perform fftw.\n '''\n a = pyfftw.empty_aligned((ny,nx),dtype = 'complex128')\n b = pyfftw.empty_aligned((ny,nx),dtype = 'complex128')\n if bwd:\n container = pyfftw.FFTW(a,b,axes = (0,1))\n else:\n container = pyfftw.FFTW(a,b,axes = (0,1),direction = 'FFTW_BACKWARD')\n return container\n\n\ndef duplicate_tiff(frame, ndup):\n '''\n create a tiff stack from one duplicated slice\n '''\n dup_stack = np.tile(frame, [ndup,1,1])\n return dup_stack\n\n\n\n\ndef crop_tiff(imstack,positions, cfname):\n '''\n crop a tiff image\n imstack is already an np array\n '''\n yi = positions[0]\n yf = positions[2]+ yi\n xi = positions[1]\n xf = positions[3]+ xi\n cr_stack = imstack[:,yi:yf, xi:xf]\n return cr_stack\n\ndef frame_locate(im_ref,z_init, ref_step = 1.0, z_range=4.0, verbose = False):\n '''\n im_ref: a reference stack\n assume the reference stack always covers the range 0 --- nslice\n z_init: integer or floating point\n ref_step: the z-step of the densely-labeled stack.\n z_range: searching range\n '''\n nslice = im_ref.shape[0]*ref_step\n ind_boundary = int(z_range/ref_step)\n ind_range = int(z_init/ref_step)+np.arange(-ind_boundary,ind_boundary)\n lb = (ind_range>=0)\n rb = (ind_range ')\r\n\ttry:\r\n\t\tnumero = int(valor)\r\n\t\tbreak\r\n\texcept ValueError:\r\n\t\tprint('Inserção inválida')\r\n\t\tprint('Digite apenas números inteiros')\r\n\r\nindice = (numero*12345) % len(lista_de_palavras)\t\r\n\r\npalavra = lista_de_palavras[indice]\r\n\r\ndigitadas = []\r\nacertos = []\r\nerros = 0\r\n\r\nwhile True:\r\n\tsenha = ''\r\n\tfor letra in palavra:\r\n\t\tsenha += letra if letra in acertos else '.'\r\n\tprint(senha)\r\n\tif senha == palavra:\r\n\t\tprint('Você acertou!')\r\n\t\tbreak\r\n\r\n\ttentativa = input('\\nDigite uma letra: ').lower().strip()\r\n\t\r\n\ttry:\r\n\t\ttentativa = float(tentativa)\r\n\t\tif type(tentativa) == float:\r\n\t\t\tprint('Por favor, digite apenas letras!')\r\n\t\t\tcontinue\r\n\t\ttentativa = int(tentativa)\r\n\t\tif type(tentativa) == int:\r\n\t\t\tprint('Por favor, digite apenas letras!')\r\n\t\t\tcontinue\r\n\texcept:\r\n\t\tpass\r\n\r\n\tif tentativa in digitadas:\r\n\t\tprint('Você já tentou esta letra!')\r\n\t\tcontinue\r\n\telse:\r\n\t\tdigitadas += tentativa\r\n\t\tif tentativa in palavra:\r\n\t\t\tacertos += tentativa\r\n\t\telse:\r\n\t\t\terros += 1\r\n\t\t\tprint('Você errou!')\r\n\t\tprint('X==:==X')\r\n\t\tprint('X O ' if erros >= 1 else 'X')\r\n\t\tlinha2 = ''\r\n\t\tlinha3 = ''\r\n\t\tlinha4 = ''\r\n\t\tif erros == 2:\r\n\t\t\tlinha2 = ' | '\r\n\t\telif erros == 3:\r\n\t\t\tlinha2 = ' \\| '\r\n\t\telif erros == 4:\r\n\t\t\tlinha2 = ' \\|/ '\r\n\t\telif erros == 5:\r\n\t\t\tlinha2 = ' \\|/ '\r\n\t\t\tlinha3 = ' | '\r\n\t\telif erros == 6:\r\n\t\t\tlinha2 = ' \\|/ '\r\n\t\t\tlinha3 = ' | '\r\n\t\t\tlinha4 = ' / '\r\n\t\telif erros >= 7:\r\n\t\t\tlinha2 = ' \\|/ '\r\n\t\t\tlinha3 = ' | '\r\n\t\t\tlinha4 = ' / \\ '\r\n\t\tprint('X%s' % linha2)\r\n\t\tprint('X%s' % linha3)\r\n\t\tprint('X%s' % linha4)\r\n\t\tprint('X\\n=======')\r\n\t\t\r\n\t\tif erros == 7:\r\n\t\t\tprint('Enforcado!')\r\n\t\t\tprint('A palavra era: %s' % palavra)\r\n\t\t\tbreak\r\n","sub_path":"python/jogo_da_forca.py","file_name":"jogo_da_forca.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"526044053","text":"import turtle\ncolors=['red','gold','white','black']\nturtle.setup(650,650,200,200)\nturtle.penup()\nturtle.fd(-250)\nturtle.pendown()\nturtle.pensize(25)\nturtle.pencolor(\"violet\")\nturtle.seth(-50)\nfor i in range(4):\n turtle.pencolor(colors[i])\n turtle.circle(40,100)\n turtle.circle(-40,100)\nturtle.circle(40,80/2)\nturtle.fd(40)\nturtle.circle(50,180)\nturtle.fd(40*2/3)\nturtle.done()\n","sub_path":"蟒蛇.py","file_name":"蟒蛇.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"334476903","text":"\"\"\"\nDjango settings for bbblog project.\n\n\"\"\"\n\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = '$v*h4(v7_t#u4d-l+5gqy6i96yht0#kyx3_v$nrlku00fr+rl1'\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\nINSTALLED_APPS = (\n 'djangae',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'rest_framework',\n 'myadmin',\n 'authentication',\n 'articles',\n)\n\nMIDDLEWARE_CLASSES = (\n 'djangae.contrib.security.middleware.AppEngineSecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware'\n)\n\nROOT_URLCONF = 'bbblog.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, '..','templates'),\n)\n\nWSGI_APPLICATION = 'bbblog.wsgi.application'\n\n\nif os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'HOST': '',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n }\n }\nelif os.getenv('SETTINGS_MODE') == 'prod':\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'HOST': '',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n }\n }\nelse:\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'HOST': 'localhost',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD': '',\n }\n }\n\n# Internationalization\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)","sub_path":"bbblog/settings/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"283535309","text":"\"\"\"\nThis contains all of the functions used in the server.py. cost_distance,\nnearest_vertex, and id_to_coord are defined within load_data.\n\"\"\"\n\nfrom graph import *\nimport sys\n\ndef euclidian_distance(x1,y1,x2,y2):\n \"\"\"\n Returns the Euclidian distance between 2 points (x1,y1) and (x2,y2)\n \n >>> euclidian_distance(0,0,3,4)\n 5.0\n >>> euclidian_distance(0,0,6,8)\n 10.0\n \"\"\"\n return ((x2 - x1)**2 + (y2 - y1)**2)**0.5\n\ndef load_data(filename):\n \"\"\"\n Reads in 'filename', which is a CSV file, and uses the data to build \n a graph. The first value should be a 'V' or 'E' for each row, for a\n vertex or edge respectively. \n \n Data syntax for V:\n V,,,\n \n Data syntax for E:\n E,,,\n \n Returns the graph, the cost_distance function, and an ID to coordinate \n converter. (See the individual function descriptions for details)\n \"\"\"\n g = Graph()\n coord_index = dict()\n street_names = dict()\n \n line_number = 0\n f = open(filename, 'r')\n \n for i,l in enumerate(f): pass\n file_len = 2*(i + 1)\n f.seek(0)\n \n # 2 attempts are used to load in all the nodes and edges. All the\n # nodes are loaded in attempt 1, and all the edges in attempt 2.\n # This is done because the CSV contains nodes and edges mixed\n # together. Doing just 1 read might skip some edges whose corresponding\n # nodes have not been added yet.\n \n attempt = 1 \n for line in f:\n line_number += 1\n data = line.split(\",\")\n \n if data[0] == 'V': # Vertex\n if attempt == 1: \n g.add_vertex(int(data[1]))\n coord_index[int(data[1])] = (float(data[2]), float(data[3])) \n \n elif data[0] == 'E': # Edge\n if attempt == 2:\n g.add_edge((int(data[1]), int(data[2])))\n if len(data) == 4:\n street_names[(int(data[1]), int(data[2]))] = data[3][:-1]\n \n if line_number == file_len/2:\n f.seek(0)\n attempt = 2\n \n f.close() \n \n def cost_distance(edge):\n \"\"\"\n cost_distance will return the cost of an input edge, 'edge' by \n finding the Euclidian distance between the two nodes of e (using\n Pythagorean Theorem).\n edge must be a tuple containing two nodes (as IDs).\n \"\"\"\n start = coord_index[edge[0]]\n end = coord_index[edge[1]] \n return euclidian_distance(start[0], start[1], end[0], end[1])\n \n def nearest_vertex(coords):\n \"\"\"\n Returns the vertex ID that exists in g that is closest to \n the (lat, lon) tuple \"coords\".\n \"\"\"\n distances = dict()\n for ids in coord_index.keys():\n \n distances[euclidian_distance(coords[0], coords[1], \\\n coord_index[ids][0], coord_index[ids][1])] = ids\n \n return distances[min(i for i,j in distances.items())]\n\n def id_to_coord(vid):\n \"\"\"\n Returns a tuple (lat, long) that is a node in g for vertex ID\n \"vid\" passed in.\n \"\"\"\n return coord_index[vid]\n \n return g, cost_distance, nearest_vertex, id_to_coord \n \ndef least_cost_path(G, start, dest, cost):\n \"\"\"\n Returns the shortest (cheapest) path from the starting node to \n destination node, given a graph and a cost function. Returns a \n list of the shortest path from start to dest.\n \n If dest cannot be reached from the start, returns None.\n If the starting and destination nodes are equal, returns [start].\n \n \n Examples:\n >>> def test_cost(e):\n ... return abs(e[0] - e[1])\n >>> G = Graph({1, 2, 3, 4, 5, 6}, [(1, 3), (3, 2), (2, 4), (4, 6),\n ... (1, 5), (5, 6)])\n \n >>> least_cost_path(G, 1, 6, test_cost)\n [1, 5, 6]\n \n >>> least_cost_path(G, 3, 2, test_cost)\n [3, 2]\n \n >>> least_cost_path(G, 2, 5, test_cost)\n\n >>> least_cost_path(G, 3, 3, test_cost)\n [3]\n \n >>> least_cost_path(G, 3, 6, test_cost)\n [3, 2, 4, 6]\n \"\"\"\n if start == dest:\n return [start]\n \n \n # Declaration of variables. \"visited_costs\" contains every node that \n # has been visited as keys, and their associated costs as values. \n # \"previous\" contains nodes as keys and their preceeding node as a \n # value. \"shortest_path\" is a list containing the shortest path from \n # start to dest. \"current\" is temporarily used while finding that \n # path.\n visited_costs = dict()\n previous = dict()\n shortest_path = []\n current = None \n \n \n # Find the component associated with \"start\". This component will be \n # used in Dijkstra's algorithm instead of using the entire graph.\n # Running time of depth_first_search: O(V + E)\n component = depth_first_search(G, start) \n\n \n # If the destination is not connected to the start, exit.\n if dest not in component:\n return None\n \n \n # Assign the cost of each node (in the component) to infinity.\n # Assign the starting cost to be 0.\n # Running time: O(V)\n costs = {node:float(\"inf\") for node in component.keys()}\n costs[start] = 0\n visited_costs[start] = 0\n cheapest = start\n \n \n # Dijkstra's Algorithm: Overall running time: O(V^2 + E)\n # Running time of while-loop: O(# nodes in component of start) = O(V)\n while component:\n \n # Find the neighbours of the current node.\n # Running time: O(# neighbours of node)\n adjacents = G.neighbours(cheapest)\n \n # Update the cost of each neighbour. A neighbour is only updated\n # if the calculated cost is less than the previously assigned cost.\n for node in adjacents:\n if costs[node] > cost((cheapest, node)) + costs[cheapest]:\n costs[node] = cost((cheapest, node)) + costs[cheapest]\n visited_costs[node] = costs[node]\n previous[node] = cheapest\n \n # Remove the current node from the component and from costs (to \n # avoid repeated computations).\n component.pop(cheapest)\n visited_costs.pop(cheapest)\n \n # Find the (new) minimum-cost node in the graph; it will be the\n # new \"current node\".\n cheapest = min(visited_costs, key=visited_costs.get)\n\n # If the destination has been reached, traverse backwards along \n # the shortest path until you have reached start, and return this \n # path.\n # Running time: O(# of nodes in the shortest path)\n if cheapest == dest:\n current = cheapest\n while current != start:\n shortest_path.append(current)\n current = previous[current]\n shortest_path.append(start)\n shortest_path.reverse()\n return shortest_path\n\n return None\n","sub_path":"server/route_finder.py","file_name":"route_finder.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"495468315","text":"import time\r\n\r\n\r\nline = '\\n\\n' + '——————————————' + '\\n\\n'\r\n\r\ndef txt_to_list(path):\r\n with open(path, 'r', encoding='utf-8') as f:\r\n text = f.read()\r\n _list = text.split(line)\r\n _list = [i.strip('   \\n ') for i in _list if i.strip('   \\n ') != '']\r\n return _list\r\n\r\ndef list_to_txt(_list):\r\n msg = ''\r\n for i in _list:\r\n msg += i + line\r\n msg = msg[:-len(line)]\r\n return msg\r\n\r\ndef send_message(_list):\r\n msg = list_to_txt(_list)\r\n with open('..\\\\temp_message.txt', 'a', encoding='utf-8') as f:\r\n f.write(line + msg)\r\n return msg\r\n\r\npath = 'Maths.txt'\r\nhours = 7\r\n\r\nminutes = hours * 60\r\nall_list = txt_to_list(path)\r\n#num = len(all_list)//minutes + 1\r\nif len(all_list)//minutes != len(all_list)/minutes:\r\n num = len(all_list)//minutes + 1\r\nelse:\r\n num = len(all_list)//minutes\r\n\r\nwhile 1:\r\n old_time = time.strftime(\"%H:%M\")\r\n while 1:\r\n new_time = time.strftime(\"%H:%M\")\r\n if new_time != old_time:\r\n old_time = new_time\r\n minute = old_time.split(':')[1]\r\n print(minute)\r\n send_message(all_list[:num])\r\n all_list = all_list[num:]\r\n if len(all_list) == 0:\r\n exit()\r\n break\r\n","sub_path":"@Xiaoya/Python/Test/Message task.py","file_name":"Message task.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"531817883","text":"# coding=utf-8\n\nfrom frontik.compat import PY3\n\nif PY3:\n import http.client as httpcodes\nelse:\n import httplib as httpcodes\n\nOK = int(httpcodes.OK)\nSERVICE_UNAVAILABLE = int(httpcodes.SERVICE_UNAVAILABLE)\nUNAUTHORIZED = int(httpcodes.UNAUTHORIZED)\n\n# Additional HTTP Status Codes according to http://tools.ietf.org/html/rfc6585 (for Python 2)\n\nPRECONDITION_REQUIRED = 428\nTOO_MANY_REQUESTS = 429\nREQUEST_HEADER_FIELDS_TOO_LARGE = 431\nNETWORK_AUTHENTICATION_REQUIRED = 511\n\n_additional_response_codes = {\n PRECONDITION_REQUIRED: 'Precondition Required',\n TOO_MANY_REQUESTS: 'Too Many Requests',\n REQUEST_HEADER_FIELDS_TOO_LARGE: 'Request Header Fields Too Large',\n NETWORK_AUTHENTICATION_REQUIRED: 'Network Authentication Required',\n}\n\n\ndef process_status_code(status_code, reason=None):\n if status_code not in httpcodes.responses:\n if status_code in _additional_response_codes:\n # autoset reason for extended HTTP codes\n reason = reason if reason is not None else _additional_response_codes[status_code]\n else:\n # change error code for unknown HTTP codes (ex. fake 599 error code)\n status_code = SERVICE_UNAVAILABLE\n\n return status_code, reason\n","sub_path":"frontik/http_codes.py","file_name":"http_codes.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"103151023","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# Improting the dataset\ndataset = pd.read_csv('Position_Salaries.csv')\nX = dataset.iloc[:, 1:2].values\ny = dataset.iloc[:, 2].values\n\n# Splitting the dataset into training set and test set\nprint(X)\n\"\"\"from sklearn.cross_validation import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\"\"\"\n# Feature Scaling\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test - sc_X.transform(X_test)\n\"\"\"\n\n# Linear Regression\nfrom sklearn.linear_model import LinearRegression\nlin_reg = LinearRegression()\nlin_reg.fit(X, y)\n\n\n#Polynomial Regression\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree = 4)\nX_poly = poly_reg.fit_transform(X)\n\nlin_reg_2 = LinearRegression()\nlin_reg_2.fit(X_poly, y)\nprint(X_poly)\n\n# Visualizing linear regression result\n\"\"\"\nplt.scatter(X, y, color = 'red')\nplt.plot(X, lin_reg.predict(X), color = 'blue')\nplt.title('T or B')\nplt.xlabel('Position')\nplt.ylabel('salary')\nplt.show()\n\"\"\"\n# Visualizing polynomial regression result\n\"\"\"plt.scatter(X, y, color = 'green')\nplt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'yellow')\nplt.title('Truth or Bluff (Polynomial Regression)')\nplt.xlabel('Position')\nplt.ylabel('salary')\nplt.show()\n\"\"\"\n\n#\nprint(lin_reg.predict(6.5))\n\nprint(\"Polynomial:\")\n\nprint(lin_reg_2.predict(poly_reg.fit_transform(6.5)))\n\n","sub_path":"Python/polynomial_regression.py","file_name":"polynomial_regression.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"535446161","text":"import sys\nfrom subprocess import Popen, PIPE\nimport re\n\ndef readnames(file):\n with open(file,'r') as f:\n names = f.readlines()\n return names\n\ndef reverse (files):\n# print(file,\"start\")\n files = './Func_annotation_result/' + files\n output = files[:-4] + '_sorted.gff'\n #output = file[14:32] + '_sorted.gff' \n\n #from tm.pythontmhmmgff import tmhmm_act\n f = open(output,'w')\n process = Popen(args=['/projects/team3/func_annot/bin/bedtools2/bin/bedtools',\n 'sort',\n '-i', files], stdout = f, stderr = PIPE)\n\n stdout, stderr = process.communicate()\n print(stderr)\n\ndef sort(names):\n# names = readnames(sys.argv[1]) \n # print(rnammer_names,infernal_names,aragorn_names)\n for name in names:\n name = name.strip()\n print(name)\n # name = './combination/'+ name\n","sub_path":"bedtools_scripts/bedtools_sort.py","file_name":"bedtools_sort.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"372808572","text":"#This is a comment\n#Comments help you to understand my code\n\n#Program to return HCF of 2 numbers\n#using Euclid's Division Algorithm\n\n#num1 ---> Number 1\n#num2 ---> Number 2\n#showSteps ---> Whether to show steps or not\n#If showSteps = 0, HCF without steps\n#If showSteps = 1, HCF with steps\n#num1 % num2 means num1 mod num2 or num1 modulus num2\n#modulus gives the remainder after division\n\n#Function to return HCF of num1 and num2\n#with or without steps\ndef HCF(num1, num2, showSteps):\n\n #Case 1 :- num1 > num2\n if num1 > num2:\n\n #Case 1(a) :- num1 not divisible by num2\n if num1 % num2 != 0:\n \n #Case 1(a)(i) :- showSteps = 1\n if showSteps == 1:\n \n #Print steps\n print('HCF of', num1, 'and', num2,\n 'is equal to HCF of',\n (num1 % num2), 'and', num2)\n\n #Return HCF with steps\n return HCF(num1 % num2, num2, 1)\n\n #Case 1(a)(ii) :- showSteps = 0\n else:\n\n #Return HCF without steps\n return HCF(num1 % num2, num2, 0)\n\n #Case 1(b) :- num1 divisible by num2\n else:\n\n #Case 1(b)(i) :- showSteps = 1\n if showSteps == 1:\n\n #Print steps\n print('HCF of', num1, 'and', num2,\n 'is equal to HCF of',\n num2, 'and', num2)\n\n #Return HCF with steps\n return 'HCF of ' + str(\n num2) + ' and ' + str(\n num2) + ' which is equal to '+ str(\n num2)\n\n #Case 1(b)(ii) :- showSteps = 0\n else:\n\n #Return HCF without steps\n return str(num2)\n\n \n #Case 2 :- num1 = num2\n elif num1 == num2:\n\n #Return num1\n return str(num1)\n\n #Case 3 :- num1 < num2\n else:\n\n #Case 3(a) :- num2 not divisible by num1\n if (num2 % num1) != 0:\n\n #Case 3(a)(i) :- showSteps = 1\n if showSteps == 1:\n\n #Print steps\n print('HCF of', num1, 'and', num2,\n 'is equal to HCF of',\n num1, 'and', (num2 % num1))\n\n #Return HCF with steps\n return HCF(num1, num2 % num1, 1)\n \n #Case 3(a)(ii) :- showSteps = 0\n else:\n\n #Return HCF without steps\n return HCF(num1, num2 % num1, 0)\n\n #Case 3(b) :- num2 divisible by num1\n else:\n\n #Case 3(b)(i) :- showSteps = 1\n if showSteps == 1:\n\n #Print steps\n print('HCF of', num2, 'and', num1,\n 'is equal to HCF of', num1,\n 'and', num1)\n\n #Return HCF with steps\n return 'HCF of ' + str(\n num1) + ' and ' + str(\n num1) + ' which is equal to '+ str(\n num1)\n\n #Case 3(b)(ii) :- showSteps = 0\n else:\n\n #Return HCF without steps\n return str(num1)\n#Main function\ndef main():\n\n #Ask user whether to show steps or not\n showSteps = int(input(\n 'Show steps to find HCF (1 - Yes, 0 - No): '))\n\n #Loop forever\n while True:\n \n #If showSteps not equal to 0 and\n #showSteps not equal to 1\n if (showSteps != 0) and (showSteps != 1):\n\n #Loop while showSteps not equal to 0 and\n #showSteps not equal to 1\n while (showSteps != 0) and (showSteps != 1):\n\n #Display a helpful message to enter 0 or 1\n print('Please enter 0 or 1')\n\n #Ask user whether to show steps or not again\n showSteps = int(input(\n 'Show steps to find HCF (1 - Yes, 0 - No): '))\n \n #If showSteps == 0 or showSteps == 1 \n else:\n \n #Break loop\n break\n \n #Ask num1 input from user \n num1 = int(input('Please enter the first number: '))\n\n #Ask num2 input from user\n num2 = int(input('Please enter the second number: '))\n\n #Print HCF of num1 and num2 \n print('HCF of', num1, 'and', num2,'is equal to', HCF(\n num1, num2, showSteps))\n\n#If program is started as main process\n#instead of being imported\nif __name__ == '__main__':\n\n #Execute the main function\n main()\n","sub_path":"HCF using Euclid's Division Algorithm.py","file_name":"HCF using Euclid's Division Algorithm.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"224952105","text":"# -*- coding: utf-8 -*-\nimport os\nimport platform\nfrom loghelper import LogError\nfrom loghelper import LogInfo\n\n# 将PB转换成py格式\ndef gen_py_from_pb(proto_path):\n files = os.listdir(proto_path)\n for file in files:\n if not file.endswith('.proto'):\n continue\n pre_file = file[:len(file) - len('.proto')]\n pre_file += '_pb2.py'\n pre_file = '../proto/' + pre_file\n if os.path.exists(pre_file):\n pass\n if platform.system() == \"Windows\":\n command = \".\\\\bin\\\\protoc.exe --proto_path=./deploy/proto --python_out=./deploy/proto/ \" + file\n else:\n command = \"protoc --proto_path=./deploy/proto --python_out=./deploy/proto \" + file\n try:\n LogInfo(command)\n os.system(command)\n except BaseException:\n LogError('protoc %s failed' % file)\n raise\n\n\n","sub_path":"fk/deploy/src/gen_py_from_pb.py","file_name":"gen_py_from_pb.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"181238797","text":"__author__ = 'mmateja'\nimport collections\nclass TakeFillNumbers():\n\n def takeFillNumbers(self, fillnumber):\n self.fillnumber = fillnumber\n\n def getfillnumber(self):\n xlist = {}\n ylist = {}\n for z in self.fillnumber:\n xlist[z] = z\n xlist = collections.OrderedDict(sorted(xlist.items()))\n ylist['fillnumbers']=xlist.values()\n return ylist\n","sub_path":"IO/TakeFillNumbers.py","file_name":"TakeFillNumbers.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"552934168","text":"import dlib\nfrom collections import OrderedDict\nimport cv2\nimport os\nimport numpy as np\nfrom scipy.spatial import distance as dist\n\nFACIAL_LANDMARKS_IDXS = OrderedDict([\n\t(\"mouth\", (48, 68)),\n\t(\"inner_mouth\", (60, 68)),\n\t(\"right_eyebrow\", (17, 22)),\n\t(\"left_eyebrow\", (22, 27)),\n\t(\"right_eye\", (36, 42)),\n\t(\"left_eye\", (42, 48)),\n\t(\"nose\", (27, 36)),\n\t(\"jaw\", (0, 17))\n])\n\nPATH_FACE_DETECTOR = './face_detector'\npredictor = dlib.shape_predictor('./model/shape_predictor_68_face_landmarks.dat')\nproto_path = os.path.join(PATH_FACE_DETECTOR, 'deploy.prototxt.txt')\nmodel_path = os.path.join(PATH_FACE_DETECTOR, 'res10_300x300_ssd_iter_140000.caffemodel')\nnet = cv2.dnn.readNetFromCaffe(proto_path, model_path)\n\nEYE_AR_THRESH = 0.3\nEYE_AR_CONSEC_FRAMES = 3\n\n(lStart, lEnd) = FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n(rStart, rEnd) = FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n\ndef eye_aspect_ratio(eye):\n\tA = dist.euclidean(eye[1], eye[5])\n\tB = dist.euclidean(eye[2], eye[4])\n\tC = dist.euclidean(eye[0], eye[3])\n\n\tear = (A + B) / (2.0 * C)\n\treturn ear\n\ndef shape_to_np(shape, dtype='int'):\n\tcoords = np.zeros((shape.num_parts, 2), dtype=dtype)\n\tfor i in range(0, shape.num_parts):\n\t\tcoords[i] = (shape.part(i).x, shape.part(i).y)\n\n\treturn coords\n\ndef get_face(frame):\n\th, w = frame.shape[:2]\n\tblob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,\n\t\t(300, 300), (104.0, 177.0, 123.0))\n\tnet.setInput(blob)\n\tdetections = net.forward()\n\tif len(detections) > 0:\n\t\ti = np.argmax(detections[0, 0, :, 2])\n\t\tconfidence = detections[0, 0, i, 2]\n\t\tif confidence > 0.5:\n\t\t\tbox = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\t\t\tstartX, startY, endX, endY = box.astype(\"int\")\n\t\t\tface = frame[startY:endY, startX:endX]\n\t\t\tface = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n\t\telse:\n\t\t\treturn None, None\n\treturn face, ((startX, startY), (endX, endY))\n\ndef detect_blink(frame, bndbox, counter, total):\n\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\trec = dlib.rectangle(bndbox[0][0], bndbox[0][1], bndbox[1][0], bndbox[1][1])\n\tshape = predictor(gray, rec)\n\tshape = shape_to_np(shape)\n\n\tleftEye = shape[lStart:lEnd]\n\trightEye = shape[rStart:rEnd]\n\tleftEAR = eye_aspect_ratio(leftEye)\n\trightEAR = eye_aspect_ratio(rightEye)\n\n\tear = (leftEAR + rightEAR) / 2.0\n\n\tleftEyeHull = cv2.convexHull(leftEye)\n\trightEyeHull = cv2.convexHull(rightEye)\n\tcv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)\n\tcv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)\n\n\tif ear < EYE_AR_THRESH:\n\t\tcounter += 1\n\n\telse:\n\t\tif counter >= EYE_AR_CONSEC_FRAMES:\n\t\t\ttotal += 1\n\n\t\tcounter = 0\n\n\tcv2.putText(frame, \"Blinks: {}\".format(total), (10, 30),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)\n\tcv2.putText(frame, \"EAR: {:.2f}\".format(ear), (300, 30),\n\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)\n\n\treturn counter, total\n\n","sub_path":"scripts/eye_blink.py","file_name":"eye_blink.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"438128781","text":"import requests, json, time\r\n\r\n\r\ndef removeFromList(input_list, removeNum):\r\n for i in range(removeNum):\r\n try:\r\n input_list.pop(0)\r\n except IndexError:\r\n pass\r\n return input_list\r\n\r\n\r\ndef getCsvString(input_list, num):\r\n string = ''\r\n for i in range(num):\r\n string += input_list[i] + ','\r\n return string\r\n\r\n\r\ndef convertStringToList(input_string, separatorCharacter):\r\n # Convert string to list then iterate through list replacing the new line characters for commas\r\n character_list = list(input_string)\r\n return_list = []\r\n input_string = ''\r\n for char in character_list:\r\n if char == separatorCharacter:\r\n return_list.append(input_string)\r\n input_string = ''\r\n else:\r\n input_string += char\r\n\r\n return return_list\r\n\r\n\r\ndef removeEmojiFromString(input_string):\r\n return_string = ''\r\n for char in input_string:\r\n if len(char.encode()) == 1:\r\n return_string += char\r\n return return_string\r\n\r\n\r\ndef removeHastagsAndAtsFromString(input_string):\r\n return_string = ''\r\n hashtagStringLength = 0\r\n for char in input_string:\r\n if char == '#' or char == '@':\r\n hashtagStringLength = 1\r\n elif hashtagStringLength > 0 and (char == ' ' or char == '\\n'):\r\n hashtagStringLength = 0\r\n return_string += char\r\n elif hashtagStringLength > 0:\r\n hashtagStringLength += 1\r\n else:\r\n return_string += char\r\n return return_string\r\n\r\n\r\ndef removeUrlsFromString(input_string):\r\n return_string = ''\r\n urlStringLength = 0\r\n for i in range(len(input_string)):\r\n if input_string[i] == 'h' and input_string[i+1] == 't' and input_string[i+2] == 't' \\\r\n and input_string[i+3] == 'p':\r\n urlStringLength += 1\r\n elif input_string[i] == ' ':\r\n urlStringLength = 0\r\n return_string += ' '\r\n elif urlStringLength > 0:\r\n urlStringLength += 1\r\n else:\r\n return_string += str(input_string[i])\r\n return return_string\r\n\r\n\r\n# Get list, always make 1 call then mak remaining calls depending on rateLimit\r\ndef getTwitterTextData(id_string):\r\n url = 'https://api.twitter.com/2/tweets'\r\n bearerToken = 'Bearer AAAAAAAAAAAAAAAAAAAAAI%2F2OAEAAAAAHm5uUDpUOA1JQYZ2pIQsoTkEJWo%3DI0OjZx69RHdtpJnJ62pmpA00LCvpUtjHn8OwLt2N0Gzfvny2CS'\r\n querystring = {'ids': id_string}\r\n headers = {'Authorization': bearerToken}\r\n response = requests.request('GET', url, headers=headers, params=querystring)\r\n print(response.status_code)\r\n if response.status_code != 200:\r\n return [], 0\r\n data_dict = json.loads(response.text)\r\n data_headers = response.headers\r\n rateLimit = data_headers['x-rate-limit-remaining']\r\n print('Rate Limit: ' + str(rateLimit))\r\n data_list = []\r\n # If there is is a key in the dictionary that is labelled 'data'. Otherwise only 'error' key would exist.\r\n if 'data' in data_dict:\r\n data_list = data_dict['data']\r\n return data_list, rateLimit\r\n\r\n\r\ndef runGetDataLoop(input_list):\r\n return_list = []\r\n while len(input_list) > 0:\r\n csvID_string = convertListToString(input_list[:100], ',')\r\n data_list, rateLimit = getTwitterTextData(csvID_string)\r\n input_list = removeFromList(input_list, 100)\r\n return_list.extend(data_list)\r\n time.sleep(5)\r\n if rateLimit == 0:\r\n break\r\n return return_list\r\n\r\n\r\ndef convertListToString(input_list, separatorCharacter, dict=False, key=''):\r\n return_string = ''\r\n if dict:\r\n for elem in input_list:\r\n return_string += elem[key] + separatorCharacter\r\n else:\r\n for elem in input_list:\r\n return_string += elem + separatorCharacter\r\n return_string = return_string[0:len(return_string)-1]\r\n return return_string\r\n\r\n\r\n'''------------------------------------------------------ MAIN ------------------------------------------------------'''\r\n# Get input from file (with statement closes the file when indented code completes)\r\nwith open('data/normal.txt', 'r') as file:\r\n ids_string = file.read()\r\n\r\nid_list = convertStringToList(ids_string, '\\n')\r\n\r\n# Initial run set id_list[:30000] and writing at the end to 'w' instead of 'a'\r\ntweet_list = runGetDataLoop(id_list[0:49999])\r\n\r\n# Because the tweet_list is a list of dictionaries need to specify that the list dict=True and the dictionary key\r\ntweet_string = convertListToString(tweet_list, '\\n\\n\\n', True, 'text')\r\ntweet_string = removeHastagsAndAtsFromString(tweet_string)\r\ntweet_string = removeUrlsFromString(tweet_string)\r\ntweet_string = removeEmojiFromString(tweet_string)\r\n\r\n# print(tweet_string) # For testing purposes\r\nwith open('data/normalTweets.txt', 'a', encoding='UTF-8') as file:\r\n file.write(tweet_string)\r\n\r\n","sub_path":"SarcasmTweetExtraction.py","file_name":"SarcasmTweetExtraction.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"249683351","text":"# https://leetcode.com/problems/longest-common-prefix/description/\n# http://www.geeksforgeeks.org/longest-common-prefix-set-2-character-by-character-matching/\n\nclass Solution(object):\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\n \"\"\"\n if len(strs) == 0:\n return \"\"\n elif len(strs) == 1:\n return strs[0]\n else:\n prefix = []\n tobreak = 0\n new_words = sorted(strs,key=lambda s: len(s))\n for i in range(len(new_words[0])):\n letter = new_words[0][i]\n for s in new_words[1:]:\n if s[i] != letter:\n tobreak = 1\n break\n if tobreak == 1:\n break\n else:\n prefix.append(letter)\n final_prefix = ''.join(prefix)\n return final_prefix","sub_path":"Leetcode/Longest-common-prefix.py","file_name":"Longest-common-prefix.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"28935550","text":"class Piece:\n\n def __init__(self,color):\n self.color = color\n\n def isLegalMove(self,move, board):\n return False\n\n def possibleMoves(self, board):\n return []\n\n def __str__(self):\n return \" \"\n #return \"na\"\n\nclass Pawn(Piece):\n\n def __init__(self,col,color):\n self.color = color\n\n self.col = col\n self.row = 1 if color else 6#color of True is white, False is black\n\n def possibleMoves(self, board):\n moves = []\n\n nextRow = (self.row + 1) if self.color else (self.row - 1)\n\n #get basic moves (i.e. moving forward one or two)\n try:\n if board.grid[nextRow][self.col] == None:\n moves.append([self.row,self.col,self.row+1,self.col])\n try:\n twoRowsNext = (self.row + 2) if self.color else (self.row -2)\n if (board.grid[twoRowsNext][self.col] == None) and (self.row == 1 if self.color else 6):\n moves.append([self.row,self.col,twoRowsNext,self.col])\n except:\n pass\n except:\n pass\n\n #get the possible taking moves\n\n if self.col!=0:\n if board.grid[nextRow][self.col-1] != None:\n moves.append([self.row,self.col,nextRow,self.col-1])\n if self.col!=7:\n if board.grid[nextRow][self.col+1] != None:\n moves.append([self.row,self.col,nextRow,self.col+1])\n\n '''\n print(\"possible moves are:\")\n print(moves)\n print(\"because I am at:\")\n print(self.row,self.col)\n '''\n\n return moves\n\n def isLegalMove(self,move,board):\n #TODO: make more efficient\n moves = self.possibleMoves(board)\n return (move in moves)\n\n def __str__(self):\n return (\"w\" if self.color else \"b\") + \"P\"\n\nclass Rook(Piece):\n\n def __init__(self,col,color):\n self.color = color\n\n self.col = col\n self.row = 0 if color else 7#color of True is white, False is black\n\n def isLegalMove(self,move,board):\n\n #depending on where the target tile is, check all the tiles in between this piece and that tile\n if move[2] > move[0]:\n for row in range(move[0]+1,move[2]):\n if (board.grid[row][move[1]]) != None:\n return False\n elif move[2] < move[0]:\n for row in range(move[2] + 1, move[0]):\n if (board.grid[row][move[1]]) != None:\n return False\n elif move[3] > move[1]:\n for col in range(move[1] + 1, move[3]):\n if (board.grid[move[0]][col]) != None:\n return False\n elif move[3] < move[1]:\n for col in range(move[3] + 1, move[1]):\n if (board.grid[move[0]][col]) != None:\n return False\n else:#if the target is just the same as this tile\n return False\n\n targetPiece = board.grid[move[2]][move[3]]\n\n #check if the player is trying to take their own piece\n if targetPiece == None:\n return True\n if targetPiece.color == self.color:\n return False\n return True\n\n def possibleMoves(self,board):\n #NOTE: this function will not take into account if you are moving yourself into check\n moves = []\n\n #check moving left\n for col in range(self.col-1,-1,-1):#looks left and does 0\n target = board.grid[self.row][col]\n if target == None:#if there is nothing there\n moves.append([self.row,self.col,self.row,col])\n elif target.color != self.color:#if there is a piece of the opposite color\n moves.append([self.row,self.col,self.row,col])\n break\n else:#if there is a piece of the same color\n break\n\n #check moving right\n for col in range(self.col,8):\n target = board.grid[self.row][col]\n if target == None:#if there is nothing there\n moves.append([self.row,self.col,self.row,col])\n elif target.color != self.color:#if there is a piece of the opposite color\n moves.append([self.row,self.col,self.row,col])\n break\n else:#if there is a piece of the same color\n break\n\n #check moving up\n for row in range(self.row,-1,-1):\n target = board.grid[row][self.col]\n if target == None:#if there is nothing there\n moves.append([self.row,self.col,row,self.col])\n elif target.color != self.color:#if there is a piece of the opposite color\n moves.append([self.row,self.col,row,self.col])\n break\n else:#if there is a piece of the same color\n break\n\n #check moving down\n for row in range(self.row,8):\n target = board.grid[row][self.col]\n if target == None:#if there is nothing there\n moves.append([self.row,self.col,row,self.col])\n elif target.color != self.color:#if there is a piece of the opposite color\n moves.append([self.row,self.col,row,self.col])\n break\n else:#if there is a piece of the same color\n break\n\n return moves\n\n def __str__(self):\n return (\"w\" if self.color else \"b\") + \"R\"\n\nclass Knight(Piece):\n\n def __init__(self,col,color):\n self.color = color\n\n self.col = col\n self.row = 0 if color else 7\n\n def __str__(self):\n return (\"w\" if self.color else \"b\") + \"N\"\n\n def isLegalMove(self,move,board):\n\n latDist = abs(move[1] - move[3])#the lateral distance the piece is moving\n vertDist = abs(move[0] - move[2])#the vertical distance the piece is moving\n\n if not (latDist + vertDist == 3 and (latDist == 1 or latDist == 2) ):#think about it. It works\n return False\n\n targetPiece = board.grid[move[2]][move[3]]\n\n if targetPiece == None:\n return True\n\n if targetPiece.color != self.color:\n return True\n\n return False\n\n def possibleMoves(self,board):\n #TODO\n return []\n\nclass Bishop(Piece):\n\n def __init__(self,col,color):\n self.color = color\n\n self.col = col\n self.row = 0 if color else 7\n\n def __str__(self):\n return (\"w\" if self.color else \"b\") + \"B\"\n\nclass Board:\n\n def __init__(self):\n self.initiateGrid()\n\n def initiateGrid(self):\n self.grid = [[None for i in range(8)] for i in range(8)]\n for col in range(8):\n self.grid[1][col] = Pawn(col,True)\n self.grid[6][col] = Pawn(col,False)\n\n\n self.grid[0][0] = Rook(0,True)\n self.grid[0][7] = Rook(7,True)\n\n self.grid[7][0] = Rook(0,False)\n self.grid[7][7] = Rook(7,False)\n\n self.grid[7][1] = Knight(1,False)\n self.grid[7][6] = Knight(6,False)\n\n self.grid[0][1] = Knight(1,True)\n self.grid[0][6] = Knight(6,True)\n\n def takeUserMove(self):\n raw = input(\"\\nPlease enter your move:\\n\\n>>>\")#TODO: make sure move is entered correctly\n chars = raw.split()\n move = [int(i) for i in chars]\n if(self.grid[move[0]][move[1]].isLegalMove(move,self)):\n print(\"doing move...\")\n self.movePiece(move)\n else:\n print(\"illegal move\")\n\n def movePiece(self,move):#make sure to check if it's a legal move first, if it is coming from the user\n self.grid[move[2]][move[3]]=self.grid[move[0]][move[1]]\n self.grid[move[0]][move[1]]=None\n\n def __str__(self):\n thing = \"\"\n for row in range(8):\n for col in range(8):\n if self.grid[row][col]!=None:\n thing += str(self.grid[row][col]) + \" \"\n else:\n thing += \" \"\n thing += \"\\n\"\n return thing\n\nif __name__ == \"__main__\":\n board = Board()\n print(board)\n while 1:\n board.takeUserMove()\n print(board)\n","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"395076384","text":"#!/usr/bin/env python\nimport os\nfrom app import create_app, db, scheduler\nfrom app.models import User, Device, Role, AppointmentEvents, DeviceUsageLog, GloveBoxLog, JobLog\nfrom flask_script import Manager, Shell\nfrom flask_migrate import Migrate, MigrateCommand\nfrom datetime import datetime\nfrom math import floor\nfrom sqlalchemy import desc\nfrom apscheduler import events\nfrom app.email import send_email\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\nmigrate = Migrate(app, db)\n\nEMAIL_RECEIVER = 'jimmywlhon@nami.org.hk'\n\n\ndef check_log():\n with db.app.app_context():\n devices = Device.query.all()\n ids = []\n for device in devices:\n if device.device_inuse is True:\n ids.append(device.id)\n # print(ids)\n for i in ids:\n d = DeviceUsageLog.query.filter_by(device_id=i).order_by(desc(DeviceUsageLog.id)).first()\n g = GloveBoxLog.query.filter_by(device_id=i).order_by(desc(GloveBoxLog.id)).first()\n l = g if d is None else d\n if l is not None:\n t = datetime.utcnow()\n dt = t - l.start_time\n if floor(dt.seconds / 3600) >= 10 or dt.days >= 1:\n device = Device.query.filter_by(id=i).first()\n device.device_inuse = False\n l.end_time = t\n l.remarks = 'Not logout'\n try:\n db.session.commit()\n except:\n db.session.rollback()\n db.session.flush()\n try:\n send_email(EMAIL_RECEIVER, 'Not Logout',\n 'log/email/not_logout',\n user_name=l.user_name,\n device_name=device.name)\n except Exception as e:\n print(str(e))\n\n\ndef check_device_state():\n with db.app.app_context():\n devices = Device.query.all()\n for device in devices:\n if device.state_transfer is True:\n try:\n send_email(EMAIL_RECEIVER, 'Device Status Changed',\n 'log/email/status_change',\n device_name=device.name,\n device_status=device.status)\n device.state_transfer = False\n db.session.commit()\n except Exception as e:\n print(str(e))\n db.session.rollback()\n db.session.flush()\n\n\ndef send_alert_email():\n try:\n send_email(EMAIL_RECEIVER, 'Glovebox Regeneration',\n 'log/email/glovebox_regeneration')\n except Exception as e:\n print(str(e))\n\n\ndef job_listener(event):\n if event.exception:\n joblog = JobLog(job_name=event.job_id, excute_status=False, result=event.exception)\n else:\n joblog = JobLog(job_name=event.job_id)\n try:\n db.session.add(joblog)\n db.session.commit()\n except:\n db.session.rollback()\n db.session.flush()\n\n\ndef make_shell_context():\n return dict(app=app, db=db, User=User, Device=Device, AppointmentEvents=AppointmentEvents)\n\n\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\nmanager.add_command('db', MigrateCommand)\n\n\n@manager.command\ndef test():\n \"\"\"Run the unit tests.\"\"\"\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\n@manager.command\ndef profile(length=25, profile_dir=None):\n \"\"\"\n Start the application under the code profiler.\n :param length: number of displaying functions in report\n :param profile_dir: folder to save requests' analysis data\n :return: None\n \"\"\"\n from werkzeug.contrib.profiler import ProfilerMiddleware\n app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length],\n profile_dir=profile_dir)\n app.run()\n\n\n@manager.command\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n from flask_migrate import upgrade\n from app.models import Role\n\n # upgrade database to newest version\n upgrade()\n\n # insert roles into db\n Role.insert_roles()\n\n\nscheduler.add_job(func=check_log, id='check_log', trigger='interval', hours=1)\n\nscheduler.add_job(func=check_device_state, id='check_device_state', trigger='interval', hours=1)\n\nscheduler.add_job(func=send_alert_email, id='send_alert_email', trigger='cron', day=28)\n\nscheduler.add_listener(job_listener, events.EVENT_JOB_EXECUTED | events.EVENT_JOB_MISSED | events.EVENT_JOB_ERROR)\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"test_device_appointment_system/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"111258161","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom api import (redis_client, ns_channel as api)\nfrom flask_restplus import Resource, abort, fields\n\ncall = api.model('call', {\n 'result': fields.String,\n 'code': fields.Integer,\n 'call': fields.String,\n})\n\n\n@api.route('/')\n@api.doc(params={'username': 'Имя пользователя. Допустимо использовать mac адрес через `:`'})\nclass Channel(Resource):\n @api.response(404, description='На устройстве нет вызова')\n @api.response(400, description='Не узказан username')\n def get(self, username):\n \"\"\"Информация о наличии звонка с указанного ТД с {username}\"\"\"\n if username == \"\":\n abort(400)\n username = username.replace(\":\", \"\").lower().split(\"@\")[0]\n call = redis_client.get(\"call::{}\".format(username))\n if call:\n return {'result': 'Channel found on televoip', 'code': 200, 'call': call}, 200\n else:\n abort(404, message=\"На устройстве нет вызова\")\n","sub_path":"voip/bin/td-sip-api/api/routes/ns_channel.py","file_name":"ns_channel.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"622848270","text":"import json\n\nPEM = os.environ['PEM']\n\nprint(\"PEM\")\nprint(PEM)\n\ndef hello(event, context):\n body = {\n \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n \"input\": event\n }\n\n response = {\n \"statusCode\": 200,\n \"body\": json.dumps(body)\n }\n\n return response\n\n # Use this code if you don't use the http event with the LAMBDA-PROXY\n # integration\n \"\"\"\n return {\n \"message\": \"Go Serverless v1.0! Your function executed successfully!\",\n \"event\": event\n }\n \"\"\"\n","sub_path":"pem-to-envvar/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"632931373","text":"\"\"\"\nModule for the source catalog step.\n\"\"\"\n\nimport os\nimport warnings\n\nfrom crds.core.exceptions import CrdsLookupError\nfrom photutils.utils.exceptions import NoDetectionsWarning\n\nfrom .source_catalog import (ReferenceData, Background, make_kernel,\n make_segment_img, calc_total_error,\n SourceCatalog)\nfrom .. import datamodels\nfrom ..stpipe import Step\n\n__all__ = [\"SourceCatalogStep\"]\n\n\nclass SourceCatalogStep(Step):\n \"\"\"\n Create a final catalog of source photometry and morphologies.\n\n Parameters\n -----------\n input : str or `ImageModel`\n A FITS filename or an `ImageModel` of a drizzled image.\n \"\"\"\n\n spec = \"\"\"\n bkg_boxsize = float(default=100) # background mesh box size in pixels\n kernel_fwhm = float(default=2.0) # Gaussian kernel FWHM in pixels\n kernel_xsize = float(default=None) # Kernel x size in pixels\n kernel_ysize = float(default=None) # Kernel y size in pixels\n snr_threshold = float(default=3.0) # SNR threshold above the bkg\n npixels = float(default=5.0) # min number of pixels in source\n deblend = boolean(default=False) # deblend sources?\n aperture_ee1 = float(default=30) # aperture encircled energy 1\n aperture_ee2 = float(default=50) # aperture encircled energy 2\n aperture_ee3 = float(default=70) # aperture encircled energy 3\n suffix = string(default='cat') # Default suffix for output files\n \"\"\"\n\n reference_file_types = ['apcorr', 'abvegaoffset']\n\n def process(self, input_model):\n if self.kernel_xsize is not None or self.kernel_ysize is not None:\n warnings.simplefilter('default')\n warnings.warn('kernel_xsize and kernel_ysize are deprecated and '\n 'no longer used', DeprecationWarning)\n\n with datamodels.open(input_model) as model:\n try:\n apcorr_fn = self.get_reference_file(input_model, 'apcorr')\n except CrdsLookupError:\n apcorr_fn = None\n self.log.info(f'Using APCORR reference file {apcorr_fn}')\n\n try:\n abvegaoffset_fn = self.get_reference_file(input_model,\n 'abvegaoffset')\n\n except CrdsLookupError:\n abvegaoffset_fn = None\n self.log.info('Using ABVEGAOFFSET reference file '\n f'{abvegaoffset_fn}')\n\n aperture_ee = (self.aperture_ee1, self.aperture_ee2,\n self.aperture_ee3)\n try:\n refdata = ReferenceData(model, aperture_ee=aperture_ee,\n apcorr_filename=apcorr_fn,\n abvegaoffset_filename=abvegaoffset_fn)\n aperture_params = refdata.aperture_params\n abvega_offset = refdata.abvega_offset\n except RuntimeError as err:\n msg = f'{err} Source catalog will not be created.'\n self.log.warn(msg)\n return\n\n coverage_mask = (model.wht == 0)\n if coverage_mask.all():\n self.log.warn('There are no pixels with non-zero weight. '\n 'Source catalog will not be created.')\n return\n\n bkg = Background(model.data, box_size=self.bkg_boxsize,\n mask=coverage_mask)\n model.data -= bkg.background\n\n threshold = self.snr_threshold * bkg.background_rms\n kernel = make_kernel(self.kernel_fwhm)\n with warnings.catch_warnings():\n # suppress NoDetectionsWarning from photutils\n warnings.filterwarnings('ignore',\n category=NoDetectionsWarning)\n segment_img = make_segment_img(model.data, threshold,\n npixels=self.npixels,\n kernel=kernel,\n mask=coverage_mask,\n deblend=self.deblend)\n if segment_img is None:\n self.log.warn('No sources were found. Source catalog will '\n 'not be created.')\n return\n self.log.info(f'Detected {segment_img.nlabels} sources')\n\n # TODO: update when model contains errors\n total_error = calc_total_error(model)\n\n catobj = SourceCatalog(model, segment_img, error=total_error,\n kernel=kernel,\n kernel_fwhm=self.kernel_fwhm,\n aperture_params=aperture_params,\n abvega_offset=abvega_offset)\n catalog = catobj.catalog\n\n if self.save_results:\n cat_filepath = self.make_output_path(ext='.ecsv')\n catalog.write(cat_filepath, format='ascii.ecsv',\n overwrite=True)\n model.meta.source_catalog = os.path.basename(cat_filepath)\n self.log.info(f'Wrote source catalog: {cat_filepath}')\n\n return catalog\n","sub_path":"jwst/source_catalog/source_catalog_step.py","file_name":"source_catalog_step.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"497735966","text":"from __future__ import unicode_literals\nfrom django.apps import apps\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.core.management.base import BaseCommand\nfrom django.db import reset_queries, transaction\nfrom django.utils import translation\nfrom django.utils.encoding import force_text\nfrom reversion.revisions import RevisionManager\nfrom reversion.models import Version\nfrom reversion.management.commands import parse_app_labels\n\n\ndef get_app(app_label):\n return apps.get_app_config(app_label).models_module\n\n\nclass Command(BaseCommand):\n\n help = \"Creates initial revisions for a given app [and model].\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"args\",\n metavar=\"app_label\",\n nargs=\"*\",\n help=\"Optional apps or app.Model list.\",\n )\n parser.add_argument(\n \"--comment\",\n action=\"store\",\n default=\"Initial version.\",\n help=\"Specify the comment to add to the revisions. Defaults to 'Initial version'.\")\n parser.add_argument(\n \"--batch-size\",\n action=\"store\",\n type=int,\n default=500,\n help=\"For large sets of data, revisions will be populated in batches. Defaults to 500.\",\n )\n parser.add_argument(\n \"-m\",\n \"--manager\",\n default=\"default\",\n help=\"Create revisions for the given revision manager. Defaults to the default revision manager.\",\n )\n parser.add_argument(\n \"--database\",\n default=None,\n help=\"Nominates a database to create revisions in.\",\n )\n\n def handle(self, *app_labels, **options):\n # Activate project's default language\n translation.activate(settings.LANGUAGE_CODE)\n # Load admin classes.\n admin.autodiscover()\n # Parse options.\n comment = options[\"comment\"]\n batch_size = options[\"batch_size\"]\n revision_manager = RevisionManager.get_manager(options[\"manager\"])\n database = options[\"database\"]\n verbosity = int(options.get(\"verbosity\", 1))\n model_classes = parse_app_labels(revision_manager, app_labels)\n # Create revisions.\n with transaction.atomic(using=database):\n for model_class in model_classes:\n self.create_initial_revisions(model_class, comment, batch_size, verbosity, revision_manager, database)\n # Go back to default language\n translation.deactivate()\n\n def create_initial_revisions(self, model_class, comment, batch_size, verbosity, revision_manager, database):\n # Check all models for empty revisions.\n if verbosity >= 2:\n self.stdout.write(\"Creating initial revision(s) for model %s ...\" % (\n force_text(model_class._meta.verbose_name)\n ))\n created_count = 0\n content_type = revision_manager._get_content_type(model_class, db=database)\n live_objs = model_class._base_manager.using(database).exclude(\n pk__reversion_in=(Version.objects.using(database).filter(\n content_type=content_type,\n ), \"object_id\")\n )\n # Save all the versions.\n ids = list(live_objs.values_list(\"pk\", flat=True).order_by())\n total = len(ids)\n for i in range(0, total, batch_size):\n chunked_ids = ids[i:i+batch_size]\n objects = live_objs.in_bulk(chunked_ids)\n for id, obj in objects.items():\n try:\n revision_manager.save_revision(\n objects=(obj,),\n comment=comment,\n db=database,\n )\n except:\n self.stdout.write(\"ERROR: Could not save initial version for %s %s.\" % (\n model_class.__name__,\n obj.pk,\n ))\n raise\n created_count += 1\n reset_queries()\n if verbosity >= 2:\n self.stdout.write(\"Created %s of %s.\" % (created_count, total))\n # Print out a message, if feeling verbose.\n if verbosity >= 2:\n self.stdout.write(\"Created %s initial revision(s) for model %s.\" % (\n created_count,\n force_text(model_class._meta.verbose_name),\n ))\n","sub_path":"reversion/management/commands/createinitialrevisions.py","file_name":"createinitialrevisions.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"424723683","text":"# Populate Next Right Pointers in Each Node\n\n# Given a binary tree\n# \n# struct TreeLinkNode {\n# TreeLinkNode *left;\n# TreeLinkNode *right;\n# TreeLinkNode *next;\n# }\n# Populate each next pointer to point to its next right node. \n# If there is no next right node, the next pointer should be set to NULL.\n# \n# Initially, all next pointers are set to NULL.\n#\n# Note:\n# You may only use constant extra space.\n# You may assume that it is a perfect binary tree \n# (ie, all leaves are at the same level, and every parent has two children).\n#\n# For example,\n# Given the following perfect binary tree,\n# \n# 1\n# / \\\n# 2 3\n# / \\ / \\\n# 4 5 6 7\n# \n# After calling your function, the tree should look like:\n# \n# 1 -> NULL\n# / \\\n# 2 -> 3 -> NULL\n# / \\ / \\\n# 4->5->6->7 -> NULL\n\n\n\n# Solution:\n# The key is to find the invariance. Assume the 2->3->Null layer is finished, how shall we connect the next?\n# Iterate over a already connected layer i, it's trivial to connect layer i+1. \n\n\n# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\n\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n def connect(self, root):\n if root is None or root.left is None: # Bug: Don't forget to handle the empty tree\n return\n root.left.next = root.right\n \n prev_left_most = root.left\n cur_left_most = prev_left_most.left\n while cur_left_most != None:\n prev, cur = prev_left_most, prev_left_most.next\n prev.left.next = prev.right\n while cur != None:\n prev.right.next = cur.left\n cur.left.next = cur.right\n prev, cur = cur, cur.next\n prev_left_most = cur_left_most\n cur_left_most = cur_left_most.left\n\n","sub_path":"116_PopulateNextRightPointersInEachNode/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"320478276","text":"l1=[0, 1, 2, 3, 4, 7, 8, 10]\nl2=[4,7,10]\nl3=[2, 3, 8, 9]\n\ndef get_ranges(l):\n l.append(9999)\n rezult = \"\"\n counter = 0\n for i in range (1,len(l)):\n if l[i] != l[i-1]+1:\n if l[counter] == l[i-1]:\n rezult+=str(l[counter]) + \" \"\n counter = i\n else:\n rezult+=str(l[counter]) + \"-\"+str(l[i-1]) + \" \"\n counter = i\n return rezult\n\n\n\n\n\n\nprint(get_ranges(l1))\nprint(get_ranges(l2))\nprint(get_ranges(l3))","sub_path":"Tasks/Lappo_Tasks/Home_Task4/get_ranges.py","file_name":"get_ranges.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"58426244","text":"import struct\n\nfrom binaryninja import log_info\n\nfrom .gbinsts_unprefixed import unprefixed\nfrom .gbinsts_cbprefixed import cbprefixed\n\n\ndef gb_disassemble_one(data, addr):\n opbyte = data[0]\n\n def operand_to_imm(iinfo, operand, imm):\n if 'd8' in iinfo[operand] or 'a8' in iinfo[operand]:\n imm += (data[1], )\n elif 'r8' in iinfo[operand]:\n b = data[1]\n if b >= 128:\n b -= 256\n imm += (b, )\n elif 'a16' in iinfo[operand] or 'd16' in iinfo[operand]:\n imm += (struct.unpack(\" None:\n self._mapper = mapper\n\n def find_all(self) -> dict[str, LanguageEntity]:\n query = f'''\n SELECT\n code,\n name,\n is_active\n FROM\n {self.TABLE}\n '''\n with self.connection as connection:\n with connection.cursor() as cursor:\n cursor.execute(query)\n \n return self._mapper.from_rows(cursor.fetchall())\n \n def find_by_code(self, code) -> LanguageEntity:\n query = f'''\n SELECT\n code,\n name,\n is_active\n FROM {self.TABLE}\n WHERE\n code = %s\n '''\n with self.connection as connection:\n with connection.cursor() as cursor:\n cursor.execute(query, (code,))\n\n return self._mapper.from_row(cursor.fetchone())","sub_path":"app/repositories/Language/MySQL/LanguageRepository.py","file_name":"LanguageRepository.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"592746978","text":"from flask.views import MethodView\n\nclass Api:\n def __init__(self, blueprint):\n self.blueprint = blueprint\n\n def route(self, url, pk_name='pk', pk_type='int'):\n def decorator(resource):\n view_func = resource.as_view(resource.__name__)\n self.blueprint.add_url_rule(url,\n defaults={pk_name: None},\n view_func=view_func,\n methods=['GET'])\n self.blueprint.add_url_rule(url, view_func=view_func,\n methods=['POST'])\n self.blueprint.add_url_rule('{}/<{}:{}>'.format(url, pk_type, pk_name),\n view_func=view_func,\n methods=['GET', 'PUT', 'DELETE'])\n return resource\n return decorator\n\n def custom_route(self, url):\n def decorator(resource):\n self.blueprint.add_url_rule(url, view_func=resource,\n methods=['POST'])\n return resource\n return decorator\n\n\nclass Resource(MethodView):\n pass\n","sub_path":"stargate/route_handler.py","file_name":"route_handler.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"402845458","text":"from sudokuvariables import * \n\n\ndef display(values):\n \"\"\"\n Input: The sudoku in dictionary form\n Output: None\n Display the values as a grid.\n \"\"\"\n width = 1+max(len(values[s]) for s in boxes)\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '')\n for c in columns))\n if r in 'CF': print(line)\n return\n\ndef grid_values(grid):\n \"\"\"\n Convert grid into a dict of {square: char} with '123456789' for empties.\n Input: A grid in string form.\n Output: A grid in dictionary form\n Keys: The boxes, e.g., 'A1'\n Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.\n \"\"\"\n empty_value = '.'\n default_values = '123456789'\n all_values = []\n \n for e in grid:\n if e is empty_value:\n all_values.append(default_values);\n elif e in default_values:\n all_values.append(e)\n assert len(grid) == 81\n return dict(zip(boxes, all_values))\n\n\ndef eliminate(values):\n \"\"\"Eliminate values from peers of each box with a single value.\n\n Go through all the boxes, and whenever there is a box with a single value,\n eliminate this value from the set of values of all its peers.\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n sloved_values = [box for box in values.keys() if len(values[box]) == 1]\n for box in sloved_values:\n value = values[box]\n for peer in peers[box]:\n values[peer] = values[peer].replace(value, '')\n return values\n\n\ndef only_choice(values):\n \"\"\"Finalize all values that are the only choice for a unit.\n\n Go through all the units, and whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary form after filling in only choices.\n \"\"\"\n for unit in unit_list:\n for digit in max_values:\n places = [box for box in unit if digit in values[box]]\n if len(places) == 1:\n values[places[0]] = digit\n return values\n\n\ndef assign_value(values, box, value):\n \"\"\"\n use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\n\ndef naked_twins(values):\n \"\"\"\n Go through all the units, and whenever there is a twins in a row and column \n search for that twins in that row and column and remove those values from \n that boxes.\n whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Input: Sudoku in dictionary form.\n Output: Resulting Sudoku in dictionary form after removing each twins in each\n row and column.\n \"\"\"\n for unit in column_units+row_units:\n #finding all the possible twins from the grid\n maybe_twins = [values[box] for box in unit if len(values[box]) == 2]\n \n #finding the actual twins in the unit\n twins = [check for n, check in enumerate(maybe_twins) if check in maybe_twins[:n]]\n # removing naked twins from peers\n for twin_value in twins:\n for peer in unit: \n # removing digit from each peer and not the actual twins.\n if len(values[peer]) > 1 and values[peer] != twin_value:\n for digit in twin_value:\n values = assign_value(values, peer, values[peer].replace(digit, ''))\n\n return values\n\n\ndef reduce_puzzle(values):\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n\n # Your code here: Use the Eliminate Strategy\n values = eliminate(values)\n\n # Your code here: Use the Only Choice Strategy\n values = only_choice(values)\n \n values = naked_twins(values)\n\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\n\ndef search(values):\n \"Using depth-first search and propagation, try all possible values.\"\n # First, reduce the puzzle using the previous function\n values = reduce_puzzle(values)\n if values is False:\n return False ## Failed earlier\n if all(len(values[s]) == 1 for s in boxes): \n return values ## Solved!\n # Choose one of the unfilled squares with the fewest possibilities\n n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)\n # Now use recurrence to solve each one of the resulting sudokus, and \n for value in values[s]:\n new_sudoku = values.copy()\n new_sudoku[s] = value\n attempt = search(new_sudoku)\n if attempt:\n return attempt\n \n\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n values = grid_values(grid)\n values = search(values)\n return values\n\n \nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"376637274","text":"#!/usr/bin/env python3\r\n\r\ndatabase = 'run/src/datastores/master.db'\r\n\r\nfrom flask import Flask, render_template, request, session\r\nfrom src.mappers.sqlite import Database\r\nfrom datetime import datetime\r\n\r\ndef add_new_friend(user_id, friend_id):\r\n with Database(database) as db:\r\n db.add_new_friend(user_id,friend_id)\r\n\r\ndef account_tweets(friend_id):\r\n all_tweets = grab_tweets(friend_id)\r\n dates = []\r\n tweets = []\r\n tweet_list = []\r\n for row in all_tweets:\r\n dates.append(row[0])\r\n tweets.append(row[1])\r\n for num in range (0, len(dates)):\r\n tweet_list.append((dates[num], tweets[num]))\r\n return tweet_list\r\n\r\n\r\ndef check_log_in(user_id, password):\r\n with Database(database) as db:\r\n return db.check_log_in(user_id, password)\r\n\r\n\r\ndef check_friend_id(friend_id):\r\n with Database(database) as db:\r\n return db.check_friend_id(friend_id)\r\n\r\n\r\ndef date_now():\r\n return datetime.now()\r\n\r\n\r\ndef delete_account(friend_id):\r\n with Database(database) as db:\r\n db.delete_user(friend_id)\r\n db.delete_tweets(friend_id)\r\n db.delete_friends(friend_id)\r\n\r\n\r\ndef grab_tweets(friend_id):\r\n with Database(database) as db:\r\n return db.grab_tweets(friend_id)\r\n\r\n\r\ndef grab_friend_tweets(user_id):\r\n friend_list = newsfeed_friendlist(user_id)\r\n tweet_list_raw = []\r\n for friend in friend_list:\r\n tweet_list_raw.append(newsfeed(friend))\r\n tweet_list_unsorted = []\r\n for user in tweet_list_raw:\r\n for tweet in user:\r\n tweet_list_unsorted.append(tweet)\r\n tweet_list_sorted = sorted(tweet_list_unsorted, key=lambda x:x[0], reverse=True)\r\n dates = []\r\n users = []\r\n tweets = []\r\n tweet_list =[]\r\n for row in tweet_list_sorted:\r\n dates.append(row[0])\r\n users.append(row[1])\r\n tweets.append(row[2])\r\n for num in range(0, len(dates)):\r\n tweet_list.append((dates[num],users[num],tweets[num]))\r\n return tweet_list\r\n\r\n\r\ndef landingpage():\r\n with Database(database) as db:\r\n all_tweets = db.landingpage()\r\n dates = []\r\n users = []\r\n tweets = []\r\n tweet_list =[]\r\n for row in all_tweets:\r\n dates.append(row[0])\r\n users.append(row[1])\r\n tweets.append(row[2])\r\n for num in range(0, len(dates)):\r\n tweet_list.append((dates[num],users[num],tweets[num]))\r\n return tweet_list\r\n\r\ndef new_user(user_id, password):\r\n with Database(database) as db:\r\n return db.new_user(user_id,password)\r\n\r\n\r\ndef new_tweet(user_id, tweet):\r\n date = date_now()\r\n with Database(database) as db:\r\n db.new_tweet(user_id, tweet, date)\r\n \r\n\r\n\r\ndef newsfeed(user_id):\r\n with Database(database) as db:\r\n return db.newsfeed(user_id)\r\n\r\n\r\ndef newsfeed_friendlist(user_id):\r\n with Database(database) as db:\r\n friend_list = db.grab_friends(user_id)\r\n friend_list.append(user_id)\r\n return friend_list\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n print(newsfeed('Gabby'))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Phase2/Week8/root@68.183.128.65/run/src/models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139511387","text":"#Costo_camion.py\nimport csv\n\ndef costo_camion(nombre_archivo):\n '''\n Se le pasa en nombre del archivo y \n devuelve el costo total del camion\n '''\n costo_total = 0.00\n with open (nombre_archivo, \"rt\") as f:\n rows = csv.reader(f)\n header = next(rows)\n for n_fila, fila in enumerate(rows, start=1):\n record = dict(zip(header, fila))\n try:\n ncajones = int(record['cajones'])\n precio = float(record['precio'])\n costo_total += ncajones * precio\n except ValueError:\n print(f'Fila {n_fila}: No pude interpretar: {fila}')\n return costo_total\n\n#costo = costo_camion (\"../Data/missing.csv\")\ncosto = costo_camion (\"../Data/fecha_camion.csv\")\n#costo = costo_camion (\"../Data/camion.csv\")\nprint(f'Costo total: ${costo:0.2f}')\n","sub_path":"Clase03/costo_camion.py","file_name":"costo_camion.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"571939494","text":"from .. import tree\nfrom ..extra.rational import Rational\nfrom ..extra.error import MalformedExpressionException\n\ndef parse(expression):\n ops = list(tree.operator_dict.keys())\n root = tree.nodes.ParenthesesNode(True)\n root_stack = [root]\n\n expression = expression.replace(\" \", \"\")\n token_list = []\n last_token = \"open\"\n\n for ch in expression:\n if ch == \"(\":\n last_token = \"open\"\n token_list.append([last_token, ch])\n elif ch == \")\":\n last_token = \"close\"\n token_list.append([last_token, ch])\n elif last_token == \"open\" and ch == \"-\":\n last_token = \"rational\"\n token_list.append([last_token, ch])\n elif ch in \"01234567890.\":\n if last_token == \"rational\":\n token_list[-1][1] += ch\n else:\n last_token = \"rational\"\n token_list.append([last_token, ch])\n elif ch in ops:\n last_token = \"operator\"\n token_list.append([last_token, ch])\n else:\n raise MalformedExpressionException(\"Undefined symbol: {}\".format(ch))\n\n\n\n for kind, token in token_list:\n\n if kind == \"open\":\n node = tree.nodes.ParenthesesNode()\n root.insert(node)\n root_stack.append(node)\n root = node\n\n elif kind == \"close\":\n if not root.verify():\n raise MalformedExpressionException(\"Incomplete expression in a parentheses\")\n root_stack.pop()\n if len(root_stack) == 0:\n raise MalformedExpressionException(\"Too many closing parentheses\")\n root = root_stack[-1]\n\n elif kind == \"rational\":\n node = tree.nodes.NumberNode(Rational(string=token))\n root.insert(node)\n\n elif kind == \"operator\":\n node = tree.operator_dict[token]()\n root.insert(node)\n\n\n if len(root_stack) > 1:\n raise MalformedExpressionException(\"Too many opening parentheses\")\n if not root.verify():\n raise MalformedExpressionException(\"Incomplete expression\")\n\n return root_stack[0]","sub_path":"package/bots/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"481917765","text":"# 4/list0\ndef average(a):\n sum = 0\n for i in a:\n sum += i\n return sum / len(a)\ndef large(a):\n z =[]\n for x in a:\n if x > average(a):\n z.append(x)\n print(z)\nk = int(input(\"enter the size of list: \"))\na = [int(raw_input(\"number %d=\" % (x + 1))) for x in range(k)]\nlarge(a)\n","sub_path":"tamrin2/4list0.py","file_name":"4list0.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"616036247","text":"# coding:utf-8\n\nimport requests\nimport chardet\nimport sys\nimport re\nimport argparse\nimport codecs\nfrom bs4 import BeautifulSoup\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ntargetUrl='http://www.jmfdc.gov.cn/content.php?aid='\ntargetFile=\"test.sql\"\n#user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' \nUser_Agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' \nheaders = {'User-Agent' : User_Agent} \n\n\nprint('DROP TABLE IF EXISTS `fangHubeiJinmenYushou`; ')\nprint('CREATE TABLE `fangHubeiJinmenYushou` ( ')\nprint(' `projectName` varchar(50) NOT NULL, ')\nprint(' `projectAddress` varchar(100) NOT NULL, ')\nprint(' `projectNo` varchar(50) NOT NULL, ')\nprint(' `projectArea` varchar(50) NOT NULL, ')\nprint(' `regTime` varchar(50) NOT NULL, ')\nprint(' PRIMARY KEY (`projectNo`) ')\nprint(') ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT=\\'湖北荆州预售信息表\\'; ')\nprint('\\n')\n\n\nsourceAid=int(262630)\ntargetAid=int(262646)\n\nwith codecs.open(targetFile,'w',encoding=\"utf-8\") as f:\n for i in range(sourceAid,targetAid):\n wbdata = requests.get(targetUrl+str(i),headers=headers).text\n soup = BeautifulSoup(wbdata,\"lxml\")\n j=0\n for p in soup.select('table > tbody > tr'):\n if(j!=0):\n ps=\"insert into fangHubeiJinmenYushou values(\"\n for s in p.children:\n ps+=\"\\'\"\n ps+=s.string\n ps+=\"\\',\"\n ps=ps[:-1]\n ps+=\");\"\n \n #print(ps)\n ps+=\"\\n\"\n f.write(ps)\n j=j+1 \n","sub_path":"china/regions/1_hubeiJinmenYushouzheng.py","file_name":"1_hubeiJinmenYushouzheng.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"227147358","text":"import socket\r\n\r\nsk = socket.socket()\r\n\r\naddre = ('127.0.0.1', 8080)\r\nsk.bind(addre)\r\nsk.listen(5)\r\n\r\nwhile True:\r\n conn,addr = sk.accept()\r\n\r\n data = conn.recv(8096)\r\n data = str(data, encoding=\"utf8\")\r\n headers, boys = data.split(\"\\r\\n\\r\\n\")\r\n temp_list = headers.split(\"\\r\\n\")\r\n method, url, protocal = temp_list[0].split(\" \")\r\n # 添加HTTP响应头\r\n conn.send(b\"HTTP/1.1 200 OK\\r\\n\\r\\n\")\r\n if url == '/':\r\n conn.send(b'hello /')\r\n else:\r\n conn.send(b'404 not found')\r\n conn.close()","sub_path":"other/Python_fullStack/day64/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"66084537","text":"import taichi as ti\n\nfrom async_cases import *\nfrom async_advection import *\n\nrerun = True\n\ncases = [\n chain_copy, increments, fill_array, sparse_saxpy, autodiff,\n stencil_reduction, mpm_splitted, simple_advection, multires, deep_hierarchy\n]\n\nif rerun:\n for c in cases:\n print('*' * 30)\n print(f'* Running {c.__name__}')\n print('*' * 30)\n c()\n\ncase_names = [c.__name__ for c in cases]\n\nti.benchmark_plot(fn='benchmark.yml',\n cases=case_names,\n archs=['x64', 'cuda'],\n bars='sync_vs_async',\n left_margin=0.2)\n","sub_path":"benchmarks/benchmark_async.py","file_name":"benchmark_async.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"481232164","text":"# import the main window object (mw) from aqt\nimport random\nimport warnings\n\nfrom anki.hooks import addHook, wrap\nfrom aqt import mw\nfrom aqt.deckchooser import DeckChooser\nfrom aqt.modelchooser import ModelChooser\nfrom aqt.qt import *\nfrom aqt.studydeck import StudyDeck\n\nfrom .Helpers import Kindle\nfrom .Helpers.ToAnkiTxt import GetWordsFromText\nfrom .Helpers.Tools import GetDesktopPath\nfrom .Helpers.Youdao import Youdao\nfrom .Helpers.quick_note_and_deck_button import setup_buttons, model_buttons, change_model_to, deck_buttons, \\\n change_deck_to\nfrom .settings import addon_config\nfrom .ui import ConfigDialog\nfrom .ui.DownloadYoudao import DownloadYoudao\nfrom .utils import addMenu, addMenuItem, addMenuSeparator, clean_up_user_files\n\nwarnings.simplefilter(\"ignore\")\n\n\nclass Manager:\n def __init__(self):\n super(Manager, self).__init__()\n addHook('profileLoaded', self.onProfileLoaded)\n\n # download from youdao count\n self.youdao_downloaded = 0\n self.total_for_processing = 0\n\n def setupModelChooser(self):\n\n ModelChooser.setupModels = wrap(\n ModelChooser.setupModels,\n lambda mc: setup_buttons(mc, model_buttons, \"note type\", change_model_to),\n \"after\")\n ModelChooser.change_model_to = change_model_to\n DeckChooser.setupDecks = wrap(\n DeckChooser.setupDecks,\n lambda dc: setup_buttons(dc, deck_buttons, \"deck\", change_deck_to),\n \"after\")\n DeckChooser.change_deck_to = change_deck_to\n\n def setupAdditionalMenu(self):\n menu_name = \"有道柯林斯\"\n addMenu(menu_name)\n addMenuItem(menu_name, '从文本导入', self.ImportText, \"ALT+1\")\n addMenuSeparator(menu_name)\n addMenuItem(menu_name, '从有道单词本导入', self.ImportYoudaoWordlist, \"ALT+2\")\n addMenuItem(menu_name, '从Kindle生词导入', self.ImportKindleVocab, \"ALT+3\")\n addMenuSeparator(menu_name)\n addMenuItem(menu_name, '设置', self.ShowConfigDialog, )\n\n def onProfileLoaded(self):\n self.setupAdditionalMenu()\n # self.setupModelChooser()\n\n clean_up_user_files()\n\n def ShowConfigDialog(self):\n dlg = ConfigDialog.ConfigDialog()\n dlg.exec_()\n\n def showTxtSelection(self, window_lable):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n filename = QFileDialog.getOpenFileName(mw,\n window_lable,\n GetDesktopPath(),\n filter=\"All Files(*);;Text Files (*.txt)\",\n options=options)\n return filename[0]\n\n def ImportYoudaoWordlist(self):\n dlg = DownloadYoudao(self.import_deck_name, mw)\n dlg.exec_()\n\n def ImportText(self):\n\n txt_file = self.showTxtSelection(\"选择文件\")\n if not txt_file:\n return\n words_data = GetWordsFromText(txt_file)\n\n source_tag, accepted = QInputDialog.getText(mw, \"标签\", \"请输入【来源】标签:\", QLineEdit.Normal,\n addon_config.DefaultSourceTag)\n if accepted:\n if str(source_tag).strip():\n addon_config.DefaultSourceTag = source_tag\n addon_config.SaveConfig()\n\n youdao = Youdao(self.import_deck_name, source_tag)\n youdao.query_youdao_data(words_data,\n \"TextImport_{}.txt\".format(random.randint(0, 100)))\n\n def ImportKindleVocab(self):\n kindle = Kindle.Kindle()\n words_data = kindle.VocabData\n if not words_data:\n QMessageBox.information(mw, '从Kindle导入', \"没有找到Kindle或者Kindle生词本没有新词.\")\n return\n\n youdao = Youdao(self.import_deck_name, \"Kindle\")\n\n if QMessageBox.question(mw, \"从Kindle导入\", \"总共{}个生词,确认导入吗?\".format(\n words_data.__len__())) == QMessageBox.Yes:\n youdao.query_youdao_data({stem: usage for stem, usage in words_data},\n \"KindleImport_{}.txt\".format(random.randint(0, 100)))\n\n @property\n def import_deck_name(self):\n\n ret = StudyDeck(\n mw, accept=_(\"Choose\"),\n title=_(\"Choose Deck\"), help=\"addingnotes\",\n cancel=False, parent=mw, geomKey=\"selectDeck\")\n\n if not ret.Accepted:\n return\n return ret.name\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"318792657","text":"\"\"\"\nProblem Statement:\nIf we list all the natural numbers below 10 that are multiples of 3 or 5,\nwe get 3,5,6 and 9. The sum of these multiples is 23.\nFind the sum of all the multiples of 3 or 5 below N.\n\"\"\"\nfrom __future__ import print_function\n\nN = 10\nN_limit = 101\nwhile N < N_limit:\n # raw_input = input(\"请输入一个大于3的自然数:\")\n # n = int(filter(str.isdigit(), raw_input))\n n = N\n sum_ = 0\n for e in range(3, n):\n if e % 3 == 0 or e % 5 == 0:\n sum_ += e\n print(sum_)\n N += 10\n","sub_path":"project_euler/problem_01/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"483049040","text":"\"\"\"\nExport a registered model and all the experiment runs associated with its latest versions.\n\"\"\"\n\nimport os\nimport click\nimport mlflow\nfrom mlflow_export_import.common.http_client import HttpClient\nfrom mlflow_export_import.common import filesystem as _filesystem\nfrom mlflow_export_import.run.export_run import RunExporter\nfrom mlflow_export_import import utils\n\nclass ModelExporter():\n def __init__(self, export_metadata_tags=False, notebook_formats=[\"SOURCE\"], filesystem=None):\n self.fs = filesystem or _filesystem.get_filesystem()\n self.client = mlflow.tracking.MlflowClient()\n self.client2 = HttpClient(\"api/2.0/mlflow\")\n self.run_exporter = RunExporter(self.client, export_metadata_tags=export_metadata_tags, notebook_formats=notebook_formats, filesystem=filesystem)\n\n def export_model(self, output_dir, model_name):\n path = os.path.join(output_dir,\"model.json\")\n model = self.client2.get(f\"registered-models/get?name={model_name}\")\n for v in model[\"registered_model\"][\"latest_versions\"]:\n run_id = v[\"run_id\"] \n opath = os.path.join(output_dir,run_id)\n try:\n self.run_exporter.export_run(run_id, opath)\n opath = opath.replace(\"dbfs:\",\"/dbfs\")\n run = self.client.get_run(run_id)\n v[\"artifact_uri\"] = run.info.artifact_uri\n model[\"registered_model\"][\"latest_versions\"] = []\n for mv in self.client.search_model_versions(f\"name='{model_name}'\"):\n run_id = mv.run_id\n opath = os.path.join(output_dir,run_id)\n self.run_exporter.export_run(run_id, opath)\n run = self.client.get_run(run_id)\n dmv = dict(mv)\n dmv[\"artifact_uri\"] = run.info.artifact_uri\n model[\"registered_model\"][\"latest_versions\"].append(dmv)\n except mlflow.exceptions.RestException as e:\n if \"RESOURCE_DOES_NOT_EXIST: Run\" in str(e):\n print(\"WARNING: Run backing the registered model does not exist.\",e)\n else:\n raise(e)\n utils.write_json_file(self.fs, path, model)\n\n@click.command()\n@click.option(\"--model\", help=\"Registered model name.\", required=True, type=str)\n@click.option(\"--output-dir\", help=\"Output directory.\", required=True, type=str)\n\ndef main(model, output_dir): # pragma: no cover\n print(\"Options:\")\n for k,v in locals().items():\n print(f\" {k}: {v}\")\n exporter = ModelExporter()\n exporter.export_model(output_dir, model)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"mlflow_export_import/model/export_model.py","file_name":"export_model.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"387247556","text":"# Copyright (C) 2018 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# Status dict updated from HC.\nDEVICE_STATUS_DICT = {\n # default state, currently not in use.\n \"unknown\": 0,\n # for devices detected via \"fastboot devices\" shell command.\n \"fastboot\": 1,\n # for devices detected via \"adb devices\" shell command.\n \"online\": 2,\n # currently not in use.\n \"ready\": 3,\n # currently not in use.\n \"use\": 4,\n # for devices in error state.\n \"error\": 5,\n # for devices which timed out (not detected either via fastboot or adb).\n \"no-response\": 6\n}\n\n# Scheduling status dict based on the status of each jobs in job queue.\nDEVICE_SCHEDULING_STATUS_DICT = {\n # for devices detected but not scheduled.\n \"free\": 0,\n # for devices scheduled but not running.\n \"reserved\": 1,\n # for devices scheduled for currently leased job(s).\n \"use\": 2\n}\n\n# Job status dict\nJOB_STATUS_DICT = {\n # scheduled but not leased yet\n \"ready\": 0,\n # scheduled and in running\n \"leased\": 1,\n # completed job\n \"complete\": 2,\n # unexpected error during running\n \"infra-err\": 3,\n # never leased within schedule period\n \"expired\": 4\n}\n\nJOB_PRIORITY_DICT = {\n \"top\": 0,\n \"high\": 1,\n \"medium\": 2,\n \"low\": 3,\n \"other\": 4\n}\n\n\nSTORAGE_TYPE_DICT = {\n \"unknown\": 0,\n \"PAB\": 1,\n \"GCS\": 2\n}\n\n\ndef PrioritySortHelper(priority):\n \"\"\"Helper function to sort jobs based on priority.\n\n Args:\n priority: string, the job priority.\n\n Returns:\n int, priority order (the lower, the higher)\n \"\"\"\n priority = priority.lower()\n if priority in JOB_PRIORITY_DICT:\n return JOB_PRIORITY_DICT[priority]\n return 4\n","sub_path":"test/vti/test_serving/gae/webapp/src/vtslab_status.py","file_name":"vtslab_status.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"210009009","text":"import sensor, time\nsensor.reset()\n# Set sensor brightness\nsensor.set_contrast(1)\n# Set sensor gainceiling\nsensor.set_gainceiling(16)\n# Set framesize\nsensor.set_framesize(sensor.QCIF)\n# Set sensor to grayscale\nsensor.set_pixformat(sensor.GRAYSCALE)\n\n# Load Haar Cascade\nface_cascade = HaarCascade(\"/frontalface.cascade\")\nprint(face_cascade)\nclock = time.clock()\nwhile (True):\n clock.tick()\n image = sensor.snapshot()\n objects = image.find_features(face_cascade, threshold=0.65, scale=1.65)\n for r in objects:\n image.draw_rectangle(r)\n #Add delay to see drawing on FB \n time.sleep(10)\n print (clock.fps())\n","sub_path":"usr/examples/face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"315826493","text":"class Solution:\n def rotate(self, matrix):\n i, j = 0, len(matrix)-1\n while i < j:\n matrix[i], matrix[j] = matrix[j], matrix[i]\n i += 1\n j -= 1\n\n for m in range(len(matrix)):\n for n in range(m+1, len(matrix[m])):\n matrix[m][n], matrix[n][m] = matrix[n][m], matrix[m][n]\n\n","sub_path":"medium/rotate_image.py","file_name":"rotate_image.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"275347759","text":"import mailchimp\nimport string\nimport random\nimport requests\n\nfrom projects.models import VerificationTokens\nfrom projects.email_msg import msg as html_message\n\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\ndef get_mailchimp_api():\n return mailchimp.Mailchimp(settings.MAILCHIMP_API) #your api key here\n\ndef mailchimp_subscribe(email):\n list_id = \"929f99eeda\"#Kehko Community mailing list\n m = get_mailchimp_api()\n \"\"\"\n try:\n m.helper.ping()\n except mailchimp.Error:\n messages.error(request, \"Invalid API key\")\n \"\"\"\n try:\n m = get_mailchimp_api()\n m.lists.subscribe(list_id, {'email':email})\n #messages.success(request, \"The email has been successfully subscribed\")\n except mailchimp.ListAlreadySubscribedError:\n #for now DO NOTHING\n pass\n #return redirect('/lists/'+list_id)\n except mailchimp.Error as e:\n #for now DO NOTHING\n pass\n #messages.error(request, 'An error occurred: %s - %s' % (e.__class__, e))\n return True\n\ndef email_username(email):\n \"\"\"\n NOTE: due to the fact that we use Django's default authentication, and we use email addresses as\n usernames, we have some issues: username in auth has a max_length=30 and emails often exceed 30 characters.\n \n We could use usernames email[:30] but it is possible that two users both have emails that\n both start with 30 same characters => email1[:30] == email2[:30]\n \n In case email length is over 30 characters, we give the user a random username with length of 30.\n Probability of two users having the same username is (1/62)^30\n \"\"\"\n\n if len(email)>30:\n return \"\".join([random.choice(string.ascii_letters + string.digits) for n in range(30)])\n else:\n return email\ndef check_username(email):\n if len(email)>30:\n try:\n user = User.objects.get(email = email)\n username = user.username\n except:\n username = \"\"\n return username\n else:\n return email\n \ndef send_message(subject, msg, sender, receivers, html=False, mailgun_campaign='kehko_beta'):\n api_key = settings.MAILGUN_KEY\n domain = settings.MAILGUN_DOMAIN\n if html: m_version=\"html\"\n else: m_version='text'\n return requests.post(\n \"https://api.mailgun.net/v2/{}/messages\".format(domain),\n auth=(\"api\", api_key),\n data={\"from\": \"<{}>\".format(sender),\n \"to\":receivers,\n \"subject\": subject,\n \"o:campaign\": mailgun_campaign,#mailgun campaign for tracking\n m_version: msg})\n\ndef send_beta_invites(project, receiver_users, sender_user, mailgun_campaign):\n \"\"\"\n Sends beta invites\n \"\"\"\n name = sender_user.first_name or sender_user.email\n email_title = '{} is asking for your help on Kehko!'.format(name)\n sub_title = \"Hi, how are you?\"\n final_greeting = \"Cheers,
{}\".format(sender_user.first_name)\n for receiver in receiver_users:\n if receiver.is_active == False:\n vt = VerificationTokens()\n vt.related_project = project\n vt.user = receiver\n vt.save()\n message_body = \"I'm part of a really interesting campaign which has the following mission: \\\n
{}\\\n
We are trying to spread the message virally. \\\n I thought of you specifically, so please follow this link to Kehko, and help us reach our goal of {} people!\\\n
Please, open this link from your mobile, if possible.\\\n

\\\n
KEHKO\\\n
\".format(project.name, project.target, receiver.email, vt.token)\n msg_new = html_message.format(email_title=email_title, sub_title=sub_title,\n message_body=message_body, final_greeting = final_greeting)\n send_message(email_title, msg_new, \"donotreply@kehko.com\", [receiver.email], html=True, mailgun_campaign=mailgun_campaign)\n else:\n message_body = \"I'm part of a really interesting campaign which has the following mission: \\\n
{}\\\n
We are trying to spread the message virally. \\\n I thought of you specifically, so please follow this link to Kehko, and help us reach our goal of {} people!\\\n
Please, open this link from your mobile, if possible.

\\\n KEHKO\\\n
\".format(project.name, project.target, project.pk)\n msg_new = html_message.format(email_title=email_title, sub_title=sub_title,\n message_body=message_body, final_greeting = final_greeting)\n send_message(email_title, msg_new, \"donotreply@kehko.com\", [receiver.email], html=True, mailgun_campaign=mailgun_campaign)\n \n","sub_path":"projects/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"184321783","text":"#!/usr/bin/env python\n\n# Do this so that division of one integer by another integer will - if the\n# result is not an int - produce a float.\n\n# Division in Python 2 and Python 3 is different:\n# https://docs.python.org/3/howto/pyporting.html#division\n#\n# In particular:\n# 5 / 2 == 2.5 in Python 3\n# 5 / 2 == 2 in Python 2\n#\n# The following line makes it so you get Python 3 behavior even if you are\n# still using Python 2. More information is here:\n# https://www.python.org/dev/peps/pep-0238/\n#\nfrom __future__ import division\n\n# Import python modules\nimport sys, json, random, math\nimport numpy as np\nfrom scipy.integrate import quad\n\n# This function returns the value of the integrand at the specified time.\ndef integrand(t,a,b):\n return a*np.exp(-b*t)\n\n# This function generates the data for a question.\ndef getData(vid, options, questionDir):\n # Initialize random number generator by creating a local instance of\n # np.random.RandomState. The reason to create a local instance instead of\n # using the global instance is that the global instance is shared (maybe,\n # on some systems, for some calls...) and so would completely break\n # reproducibility.\n #\n # Use vid as the seed so that getData is a deterministic function of vid,\n # as is a PrairieLearn best practice for reproducibility. To use vid as the\n # seed, it needs to be converted to a 32-bit unsigned int. We do NOT do\n # this with \"hash\" because \"hash\" is often non-deterministic, depending on\n # your version of python.\n #\n # Common uses are:\n # mynprandom.random_sample([size])\n # mynprandom.random_integers(low[, high, size])\n #\n # More information:\n # https://docs.scipy.org/doc/numpy/reference/routines.random.html\n #\n global mynprandom\n mynprandom = np.random.RandomState(int(vid,36))\n\n # Parameters\n #\n # Often we want floating-point numbers from a given interval. One way to\n # generate them would be to sample them uniformly at random:\n #\n # a = (1.0-0.1)*mynprandom.random_sample()+0.1;\n # b = (0.5-0.1)*mynprandom.random_sample()+0.1;\n # c = (15.0-5.0)*mynprandom.random_sample()+5.0;\n #\n # This is often a bad idea, however, because to give these parameters to\n # students you will have to print them to the screen with some number of\n # significant digits. If you are not careful, students will end up using\n # a parameter value that is different from what your code uses.\n #\n # For this reason, it is often better to sample with a specific number of\n # digits after the decimal place:\n #\n # Sample a number between 0.1 (i.e., 10/100) and 1.0 (i.e., 100/100) with\n # at most two digits after the decimal:\n a = mynprandom.random_integers(10,100)/100.0;\n # Sample a number between 0.1 and 0.5 with at most two digits after the\n # decimal:\n b = mynprandom.random_integers(10,50)/100.0;\n # Sample a number between 5 and 15 with at most one digit after the\n # decimal:\n c = mynprandom.random_integers(50,150)/10.0;\n\n # Answer\n theIntegral,theError = quad(integrand,0,c,args=(a,b))\n\n # Create params (you MUST be sure that the number of digits in the\n # string matches the number of digits to which you rounded params,\n # otherwise students will get a different set of params)\n params = {\n \"a\": str(a),\n \"b\": str(b),\n \"c\": str(c)\n }\n\n # Create trueAnswer\n trueAnswer = {\n # The actual answer\n \"theIntegral\": theIntegral,\n # The answer as a string with four digits after the decimal place, so\n # it can be displayed\n \"theIntegralForDisplay\": '{:.{indigits}{iwtype}}'.format(theIntegral,indigits=4,iwtype='f')\n }\n\n questionData = {\n \"params\": params,\n \"trueAnswer\": trueAnswer,\n \"options\": {},\n }\n\n return questionData\n\n# This function grades a submitted answer.\ndef gradeAnswer(vid, params, trueAnswer, submittedAnswer, options):\n msg = ''\n\n # Get the true answer\n tru = trueAnswer['theIntegral']\n\n # Get the submitted answer\n sub = submittedAnswer.get('theIntegral')\n\n # Compare the true answer to the submitted answer. The reason to use\n # \"try/except\" is that the submitted answer may not be in the correct\n # format (or may not even exist). If the submitted answer can be\n # compared to the true answer using np.allclose, then it's either right\n # or wrong. If the submitted answer cannot even be compared (\"except\"),\n # then it's in the wrong format. It is VERY IMPORTANT to use try/except\n # when evaluating submitted answers.\n try:\n # Cast submitted answer as a floating-point number\n sub = float(sub)\n # Compare the true answer to the submitted answer\n if np.allclose(tru,sub,rtol=1e-03,atol=1e-03):\n # It is the same\n score = 1.0\n else:\n # It is not the same\n score = 0.0\n msg += 'The submitted answer is incorrect. '\n except:\n # Either the call to \"float\" or the call to \"np.allclose\" threw an\n # error, which means that the submitted answer has the wrong format.\n score = 0.0\n msg += 'The submitted answer is in the wrong format. '\n\n feedback = {\n 'msg': msg\n }\n\n grading = {\n 'score': score,\n 'feedback': feedback,\n }\n\n return grading\n\n\n########################\n# The interface between PrairieLearn and your code. You can ignore\n# this and, indeed, should not change it\n#\ndef main():\n if len(sys.argv) != 2:\n raise Exception('Expected 2 argments, got %d' % len(sys.argv))\n json_inp = sys.stdin.read()\n inp = json.loads(json_inp)\n if sys.argv[1] == 'getData':\n outp = getData(inp['vid'], inp['options'], inp['questionDir'])\n elif sys.argv[1] == 'gradeAnswer':\n outp = gradeAnswer(inp['vid'], inp['params'], inp['trueAnswer'], inp['submittedAnswer'], inp['options'])\n else:\n raise Exception('Unknown command: %s' % sys.argv[1])\n json_outp = json.dumps(outp)\n sys.stdout.write(json_outp)\n\nif __name__ == '__main__':\n main()\n\n#\n#\n########################\n","sub_path":"questions/numericalIntegration/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"128150662","text":"import cards_input\nimport csv\nfrom pathlib import Path\n\n\n\ncard_list = []\np_save = Path('gradebook.save')\np_csv = Path('gradebook.csv')\ncard_list = [['id', 'firstname', 'lastname','email','phone','city','score','department']]\n\ndef read_info():\n old_info = []\n try:\n students_csv = open(\"gradebook.csv\")\n except:\n print(\"can not find\")\n return\n while True:\n info = students_csv.readline()\n if not info:\n break\n # print(info)\n info = info.rstrip()\n # print(info)\n info = info[1:-1]\n # print(info)\n student_dict = {}\n for x in info.split(\",\"):\n # print(x)\n key_value = []\n for k in x.split(\":\"):\n k = k.strip()\n # print(k)\n if k[0] == k[-1] and len(k) > 2:\n key_value.append(k[1:-1])\n else:\n key_value.append(int(k))\n # print(key_value)\n student_dict[key_value[0]] = key_value[1]\n # print(student_dict)\n old_info.append(student_dict)\n students_csv.close()\n return old_info\n\ndef save_info(card_list):\n try:\n students_csv = open(\"gradebook.csv\", \"w\")\n except Exception as e:\n students_csv = open(\"gradebook.csv\", \"x\")\n for info in card_list:\n students_csv.write(str(info) + \"\\n\")\n students_csv.close()\n\n\ndef show_menu():\n\n \"\"\"Menu\n \"\"\"\n print(\"*\" * 50)\n print(\"welcome student gradebook\")\n print(\"1. add new\")\n print(\"2. show all\")\n print(\"3. search student\")\n print(\"4. save gradebook in to csv\")\n print(\"5. action:1: revise / 2: delete / 0: back to menu\")\n print(\"6. open gradebook\")\n print(\"0. exit system\")\n print(\"*\" * 50)\n\n\ndef new_card():\n\n \"\"\"add new information\n \"\"\"\n print(\"-\" * 50)\n print(\"function:add student\")\n\n id = input(\"input id:\")\n firstname = input(\"input first name:\")\n while True:\n if (u'\\u4e00' <= firstname <= u'\\u9fff'):\n break\n if firstname.isalpha():\n break\n else:\n firstname = input(\"please input correct first name:\")\n\n lastname = input(\"input last name:\")\n while True:\n if (u'\\u4e00' <= lastname <= u'\\u9fff'):\n break\n if lastname.isalpha():\n break\n else:\n lastname = input(\"please input correct last name:\")\n\n score = input(\"input score:\")\n while True:\n if score.isdigit():\n break\n else:\n score = input(\"please input(1-99):\")\n\n department = input(\"input department:\")\n while True:\n if (u'\\u4e00' <= department <= u'\\u9fff'):\n break\n if department.isalpha():\n break\n else:\n department = input(\"please input correct department name:\")\n\n phone = input(\"input phone number:\")\n city = input(\"input city name:\")\n\n email = input(\"input email address:\")\n\n\n # 2. save student info into dict\n card_dict = {\"id\":id,\n \"firstname\": firstname,\n \"lastname\": lastname,\n \"email\": email,\n \"phone\":phone,\n \"city\":city,\n \"score\":score,\n \"department\": department}\n\n # 3. add user dict to list\n card_list.append(card_dict)\n\n # print(card_list)\n\n # 4.add successfully\n print(\"add %s info successfully\" % card_dict[\"firstname\"])\n\n\ndef show_all():\n\n \"\"\"show all\n \"\"\"\n print(\"-\" * 50)\n print(\"function:show all\")\n\n # 1. exist record or not\n if len(card_list) == 0:\n print(\"hint: can't find records\")\n\n return\n\n # 2. show all\n print(\"id\\\\firstname\\t\\tlastname\\t\\temail\\t\\tphone\\t\\tcity\\t\\tscore\\t\\tdepartment\")\n print(\"-\" * 60)\n\n for card_dict in card_list:\n print(\"%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\\t\\t%s\" % (\n card_dict[\"id\"],\n card_dict[\"firstname\"],\n card_dict[\"lastname\"],\n card_dict[\"email\"],\n card_dict[\"phone\"],\n card_dict[\"city\"],\n card_dict[\"score\"],\n card_dict[\"department\"]))\n\n print(\"-\" * 60)\n\n\ndef binarysearch(arr, n):\n left, right = 0, len(arr) - 1\n\n while (left < right):\n mid = (left + right) // 2\n if arr[mid][\"id\"] == n:\n return arr[mid]\n elif arr[mid][\"id\"] < n:\n left = mid + 1\n else:\n right = mid - 1\n\n # if target is not in the array\n if arr[left][\"id\"] > n:\n return False\n if arr[right][\"id\"] < n:\n return False\n\n return arr[left]\n\n\n print(\"-\" * 50)\n print(\"function:search student information\")\n\n\ndef deal_card(find_dict):\n\n\n\n\n action_str = input(\"action:1: revise/ 2: delete/ 0: back to menu\")\n\n if action_str == \"1\":\n\n find_dict[\"id\"] = cards_input.input_card_info(find_dict[\"id\"],\n \"input id[or tap return]:\")\n find_dict[\"firstname\"] = cards_input.input_card_info(find_dict[\"firstname\"],\n \"input first name[or tap return]:\")\n find_dict[\"lastname\"] = cards_input.input_card_info(find_dict[\"lastname\"],\n \"input last name[or tap return]:\")\n find_dict[\"email\"] = cards_input.input_card_info(find_dict[\"email\"],\n \"input email[or tap return]:\")\n find_dict[\"phone\"] = cards_input.input_card_info(find_dict[\"phone\"],\n \"请输入电话[回车不修改]:\")\n find_dict[\"city\"] = cards_input.input_card_info(find_dict[\"city\"],\n \"input city[or tap return]:\")\n find_dict[\"department\"] = cards_input.input_card_info(find_dict[\"department\"],\n \"input department[or tap return]:\")\n\n print(\"%s information revised successfully!\" % find_dict[\"name\"])\n elif action_str == \"2\":\n\n card_list.remove(find_dict)\n\n print(\"deleted!\")\n\nimport cards_tools\nwhile True:\n\n cards_tools.show_menu()\n\n action = input(\"please select function:\")\n\n print(\"you select:%s\" % action)\n\n\n if action in [\"1\", \"2\", \"3\",\"4\",\"5\",\"6\"]:\n\n if action == \"1\":\n cards_tools.new_card()\n\n elif action == \"2\":\n cards_tools.show_all()\n\n elif action == \"3\":\n ret = cards_tools.binarysearch(card_list,input(\"search id:\"))\n print(ret)\n\n\n\n\n\n\n\n\n\n elif action == \"4\":\n cards_tools.save_info(card_list)\n\n\n elif action==\"5\":\n cards_tools.deal_card()\n\n elif action==\"6\":\n student_info = read_info()\n\n\n\n\n\n\n\n\n\n elif action == \"0\":\n print(\"wwelcome again\")\n\n\n\n else:\n print(\"error,try again:\")\n\n","sub_path":" gradebook project/cards_tools.py","file_name":"cards_tools.py","file_ext":"py","file_size_in_byte":7028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579122618","text":"from setuptools import find_packages, setup\n\nwith open('README.rst') as f:\n long_description = f.read()\n\nsetup(\n name='ocdsextensionregistry',\n version='0.0.19',\n author='Open Contracting Partnership',\n author_email='data@open-contracting.org',\n url='https://github.com/open-contracting/extension_registry.py',\n description=\"Eases access to information from the extension registry of the Open Contracting Data Standard\",\n license='BSD',\n packages=find_packages(exclude=['tests', 'tests.*']),\n long_description=long_description,\n install_requires=[\n 'json-merge-patch',\n 'requests',\n 'requests-cache',\n ],\n extras_require={\n 'test': [\n 'pytest',\n ],\n 'docs': [\n 'Sphinx',\n 'sphinx-autobuild',\n 'sphinx_rtd_theme',\n ],\n 'cli': [\n 'Babel',\n 'docutils',\n 'ocds-babel[markdown]>=0.2.0',\n # See https://ocds-babel.readthedocs.io/en/latest/api/translate.html\n # 'recommonmark',\n 'Sphinx',\n ]\n },\n classifiers=[\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python :: 3.6',\n ],\n entry_points={\n 'console_scripts': [\n 'ocdsextensionregistry = ocdsextensionregistry.cli.__main__:main',\n ],\n },\n)\n","sub_path":"pypi_install_script/ocdsextensionregistry-0.0.19.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"51883186","text":"\nfile = open('PyPollOutput.txt', 'w')\n\nprint(\"Election Results\")\nfile.write(\"Election Results\\n\")\nprint(\"----------------------------------\")\nfile.write(\"----------------------------------\\n\")\n\nimport os\nimport csv\n\n\n\npypollcsv = 'C:/Users/jessi/Documents/GTATL201808DATA3-master/Homework/03-Python/Instructions/PyPoll/Resources/election_data.csv'\n\nwith open(pypollcsv, 'r') as csvfile:\n\n csvreader = csv.reader(csvfile, delimiter=',')\n\n csv_header = next(csvfile)\n\n pypolldata = list(csvreader)\n\n numbervotes = len(pypolldata)\n\n print(f\"Total Votes: {numbervotes}\")\n file.write(f\"Total Votes: {numbervotes}\\n\")\n print(\"----------------------------------\")\n file.write(\"----------------------------------\\n\")\n\n\n\n candidatetotal = 0\n candidatenames = []\n votenames = []\n maxvotes = 0\n maxname = 0\n\n\n\n\n for vote in pypolldata:\n name = vote[2]\n if name not in candidatenames:\n candidatenames.append(name)\n votenames.append(name)\n\n for name in candidatenames:\n votetotal = votenames.count(name)\n percentofvote = (votetotal/numbervotes)*100\n if votetotal > maxvotes:\n maxvotes = votetotal\n maxname = name\n\n\n\n print(f\"{name}: {round(percentofvote,2)}% ({(votenames.count(name))})\")\n file.write(f\"{name}: {round(percentofvote,2)}% ({(votenames.count(name))})\\n\")\n\n print(\"----------------------------------\")\n file.write(\"----------------------------------\\n\")\n\n print(f\"Winner: {maxname}\")\n file.write(f\"Winner: {maxname}\\n\")\n\nfile.close()\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"117594381","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 25.02.2015\n\n@author: carndt\n\n\"\"\"\n\n__all__ = ('OutgoingTestService')\n\nfrom zato.server.service import Service\n\nclass OutgoingTestService(Service):\n name = \"outgoing-test-service\"\n out_name = \"outgoing-test\"\n\n def handle(self):\n self.logger.info(\"OutgoingTestService.handle called.\")\n self.logger.info(\"Getting outgoing with name '%s'.\", self.out_name)\n outgoing = self.outgoing.plain_http.get(self.out_name)\n self.logger.info(\"Outgoing: %r\", outgoing)\n","sub_path":"tests/outgoingtestservice.py","file_name":"outgoingtestservice.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"643877584","text":"\"\"\"YANG output plugin\"\"\"\n\nimport optparse\nimport re\n\nfrom pyang import plugin\nfrom pyang import util\nfrom pyang import grammar\n\ndef pyang_plugin_init():\n plugin.register_plugin(StripPlugin())\n\nclass StripPlugin(plugin.PyangPlugin):\n def add_output_format(self, fmts):\n fmts['strip'] = self\n self.handle_comments = True\n\n def add_opts(self, optparser):\n optlist = [\n optparse.make_option(\"--strip-module\", type=str,\n dest=\"strip_module\",\n help=\"Colon-separated list of module names to strip out\"),\n optparse.make_option(\"--strip-yang-canonical\",\n dest=\"strip_yang_canonical\",\n action=\"store_true\",\n help=\"Print in canonical order\"),\n optparse.make_option(\"--strip-yang-remove-unused-imports\",\n dest=\"strip_yang_remove_unused_imports\",\n action=\"store_true\"),\n ]\n g = optparser.add_option_group(\"Strip output specific options\")\n g.add_options(optlist)\n\n def emit(self, ctx, modules, fd):\n module = modules[0]\n ctx.opts.strip_module = ctx.opts.strip_module.split(':')\n emit_yang(ctx, module, fd)\n\ndef emit_yang(ctx, module, fd):\n emit_stmt(ctx, module, fd, 0, None, '', ' ')\n\n_force_newline_arg = ('description', 'contact', 'organization')\n_non_quote_arg_type = ('identifier', 'identifier-ref', 'boolean', 'integer',\n 'non-negative-integer', 'date', 'ordered-by-arg',\n 'fraction-digits-arg', 'deviate-arg', 'version',\n 'status-arg')\n\n_kwd_class = {\n 'yang-version': 'header',\n 'namespace': 'header',\n 'prefix': 'header',\n 'belongs-to': 'header',\n 'organization': 'meta',\n 'contact': 'meta',\n 'description': 'meta',\n 'reference': 'meta',\n 'import': 'linkage',\n 'include': 'linkage',\n 'revision': 'revision',\n 'typedef': 'defs',\n 'grouping': 'defs',\n 'identity': 'defs',\n 'feature': 'defs',\n 'extension': 'defs',\n '_comment': 'comment',\n 'module': None,\n 'submodule': None,\n}\ndef get_kwd_class(keyword):\n if util.is_prefixed(keyword):\n return 'extension'\n else:\n try:\n return _kwd_class[keyword]\n except KeyError:\n return 'body'\n\n_keyword_with_trailing_newline = (\n 'typedef',\n 'grouping',\n 'identity',\n 'feature',\n 'extension',\n )\n\n\ndef emit_stmt(ctx, stmt, fd, level, prev_kwd_class, indent, indentstep):\n if ctx.opts.strip_module and stmt.keyword == 'import' and stmt.arg in ctx.opts.strip_module:\n return\n\n if isinstance(stmt.keyword, tuple):\n kw_module, _ = stmt.keyword\n if kw_module in ctx.opts.strip_module:\n return\n \n if ctx.opts.strip_yang_remove_unused_imports and stmt.keyword == 'import':\n for p in stmt.parent.i_unused_prefixes:\n if stmt.parent.i_unused_prefixes[p] == stmt:\n return\n\n if util.is_prefixed(stmt.raw_keyword):\n (prefix, identifier) = stmt.raw_keyword\n keyword = prefix + ':' + identifier\n else:\n keyword = stmt.keyword\n\n kwd_class = get_kwd_class(stmt.keyword)\n if ((level == 1 and\n kwd_class != prev_kwd_class and kwd_class != 'extension') or\n stmt.keyword in _keyword_with_trailing_newline):\n fd.write('\\n')\n\n if keyword == '_comment':\n emit_comment(stmt.arg, fd, indent)\n return\n\n fd.write(indent + keyword)\n if stmt.arg != None:\n if keyword in grammar.stmt_map:\n (arg_type, _subspec) = grammar.stmt_map[keyword]\n if arg_type in _non_quote_arg_type:\n fd.write(' ' + stmt.arg)\n else:\n emit_arg(stmt, fd, indent, indentstep)\n else:\n emit_arg(stmt, fd, indent, indentstep)\n if len(stmt.substmts) == 0:\n fd.write(';\\n')\n else:\n fd.write(' {\\n')\n if ctx.opts.strip_yang_canonical:\n substmts = grammar.sort_canonical(stmt.keyword, stmt.substmts)\n else:\n substmts = stmt.substmts\n if level == 0:\n kwd_class = 'header'\n for s in substmts:\n emit_stmt(ctx, s, fd, level + 1, kwd_class,\n indent + indentstep, indentstep)\n kwd_class = get_kwd_class(s.keyword)\n fd.write(indent + '}\\n')\n\ndef emit_arg(stmt, fd, indent, indentstep):\n \"\"\"Heuristically pretty print the argument string\"\"\"\n # current alg. always print a double quoted string\n arg = stmt.arg\n arg = arg.replace('\\\\', r'\\\\')\n arg = arg.replace('\"', r'\\\"')\n arg = arg.replace('\\t', r'\\t')\n lines = arg.splitlines(True)\n if len(lines) <= 1:\n if len(arg) > 0 and arg[-1] == '\\n':\n arg = arg[:-1] + r'\\n'\n if stmt.keyword in _force_newline_arg:\n fd.write('\\n' + indent + indentstep + '\"' + arg + '\"')\n else:\n fd.write(' \"' + arg + '\"')\n else:\n fd.write('\\n')\n fd.write(indent + indentstep + '\"' + lines[0])\n for line in lines[1:-1]:\n fd.write(indent + indentstep + ' ' + line)\n # write last line\n fd.write(indent + indentstep + ' ' + lines[-1])\n if lines[-1][-1] == '\\n':\n # last line ends with a newline, indent the ending quote\n fd.write(indent + indentstep + '\"')\n else:\n fd.write('\"')\n\ndef emit_comment(comment, fd, indent):\n lines = comment.splitlines(True)\n for x in lines:\n if x[0] == '*':\n fd.write(indent + ' ' + x)\n else:\n fd.write(indent + x)\n fd.write('\\n')\n","sub_path":"plugins/strip.py","file_name":"strip.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"124553067","text":"from marvelous.models.user import User\nfrom marvelous.models.daily_bonus import DailyBonus\nfrom marvelous.settings import app_settings\nimport discord\n\n\ndef get_initial_user(user: discord.User):\n return User(\n discord_id=user.id,\n display_name=user.display_name,\n marvelous_bonus=DailyBonus(step=0, today=0),\n booing_penalty=DailyBonus(step=0, today=0),\n super_marvelous_left=app_settings.super_marvelous.initial_left_count,\n survival_bonus_given=False,\n point=0,\n )\n","sub_path":"app/src/marvelous/client/discord/actions/get_initial_user.py","file_name":"get_initial_user.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"145209779","text":"from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom order import views\n\nurlpatterns = [\n url(r'^shops$', views.ShopList.as_view()),\n url(r'^shops/(?P[0-9]+)$', views.ShopDetail.as_view(), name='shop-detail'),\n url(r'^shops/(?P[0-9]+)/menus$', views.ShopMenuList.as_view()),\n url(r'^shops/(?P[0-9]+)/pending_orders$', views.ShopPendingOrderList.as_view()),\n url(r'^users$', views.UserList.as_view()),\n url(r'^users/(?P[0-9]+)$', views.UserDetail.as_view(), name='user-detail'),\n url(r'^users/(?P[0-9]+)/pending_orders$', views.PendingOrderList.as_view()),\n url(r'^menus$', views.MenuList.as_view()),\n url(r'^menus/(?P[0-9]+)$', views.MenuDetail.as_view(), name='menu-detail'),\n url(r'^items$', views.ItemList.as_view()),\n url(r'^items/(?P[0-9]+)$', views.ItemDetail.as_view(), name='item-detail'),\n url(r'^orders$', views.OrderList.as_view()),\n url(r'^orders/(?P[0-9]+)$', views.OrderDetail.as_view(), name='order-detail'),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n\n","sub_path":"order/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"262448623","text":"\nfrom web.models import coders,clients\nfrom django.http import HttpResponse, HttpResponseRedirect\nimport json\nfrom django.views.decorators.http import require_http_methods\nfrom django.core import serializers\nimport requests\n# Create your views here.\n\n\n# noinspection PyInterpreter\n@require_http_methods([\"GET\"])\ndef get_coders(request):\n try:\n coderObj = coders.objects.all()\n coderList = []\n for coder in coderObj:\n coderList.append({\n \"name\":coder.username,\n \"phone\":coder.phone,\n })\n data = {\n \"coder\": coderList,\n \"msg\":\"success\",\n \"errorNum\":0,\n }\n except Exception as e:\n data = {\n \"msg\":str(e),\n \"coder\":[],\n \"errorNum\":1\n }\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n\n@require_http_methods([\"POST\"])\ndef register_coders(request):\n print(\"i'm in\")\n try:\n username = request.POST.get('username')\n phone = request.POST.get('phone')\n mail = request.POST.get('mail')\n skype = request.POST.get('skype')\n coders.objects.create(username=username,phone=phone,email=mail,password=skype)\n data = {\n \"username\": username,\n \"phone\":phone,\n \"mail\":mail,\n \"skype\":skype,\n \"msg\":\"success\",\n \"errorNum\":0,\n }\n print(data)\n except Exception as e:\n data = {\n \"msg\":str(e),\n \"coder\":[],\n \"errorNum\":1\n }\n print(data)\n return HttpResponse(json.dumps(data), content_type=\"application/json\")","sub_path":"web/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"641670719","text":"import unittest\nfrom api.auth import Auth\nfrom api.objects import Objects\nfrom api.logger import logger\nfrom api.filehelper import FileHelper\nfrom api.yufuapi import print_run_time\nfrom api.yufuapi import get_environ_parameters\n\nclass UsersTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.auth = Auth()\n self.api = Objects()\n self.all_users_id_list = []\n self.all_dp_id_list = []\n self.admin_username = get_environ_parameters(\"ADMIN_USERNAME\") or \"gangdeng@yufuid.com\"\n self.admin_password = get_environ_parameters(\"ADMIN_PASSWORD\") or \"iphone@5S\"\n\n def setUp(self):\n self.auth.login(self.admin_username, self.admin_password)\n self.auth.switch_to_admin()\n\n def tearDown(self):\n self.auth.logout()\n\n def new_values(self, key=1001):\n display_name = \"apitest{}\".format(key)\n phone_num = 19088880000 + key\n dept_id = 'dp-8640284e3dd34461a75cbfb086173672' # 自动组\n logger.debug(\"[display_name={}, phone_num={}]\".format(display_name, phone_num))\n return self.new_data(display_name=display_name, phone_num=phone_num, dept_id=dept_id)\n\n def new_data(self, display_name, phone_num, dept_id):\n data = {}\n data[\"status\"] = \"PENDING_ACTIVATE\"\n data[\"displayName\"] = display_name\n data[\"username\"] = \"{}@apitest.com\".format(display_name)\n data[\"primaryMail\"] = \"{}@apitest.com\".format(display_name)\n data[\"secondaryMail\"] = None\n data[\"deptId\"] = dept_id\n data[\"phoneNum\"] = phone_num\n data[\"superiorId\"] = None\n data[\"String_test\"] = None\n logger.debug(data)\n return data \n \n @print_run_time\n def test_create_and_delete_users_10(self):\n logger.info(\"创建-删除 10用户...\")\n return self.create_and_delete_group_users(10)\n\n @print_run_time\n def test_create_and_delete_users_100(self):\n logger.info(\"创建-删除 100用户...\")\n return self.create_and_delete_group_users(100)\n\n @print_run_time\n def test_create_and_delete_users_1000(self):\n logger.info(\"创建-删除 1000用户...\")\n return self.create_and_delete_group_users(1000)\n\n @print_run_time\n def stress_test_create_and_delete_users_10000(self):\n logger.info(\"创建-删除 10000用户...\")\n return self.create_and_delete_group_users(10000)\n\n def create_and_delete_group_users(self, number):\n logger.debug(\"[UsersTest] -> 批量创建用户,删除用户...\")\n all_users_id_list = []\n for key in range(1001, 1001+number+1):\n payload = {\"objectType\":\"USER\", \"values\": self.new_values(key)}\n result = self.api.create_objects(payload) \n if result.status_code != 201:\n logger.error(\"创建失败..id={}, text={}\".format(key, result.text))\n continue\n else:\n d = result.json()\n all_users_id_list.append(d['id'])\n logger.debug(\"[UsersTest] -> 批量删除用户...\")\n for user_id in all_users_id_list:\n result = self.api.delete_objects(id=user_id)\n if result.status_code != 200:\n logger.error(\"删除失败..id={}, text={}\".format(key, result.text))\n\n def delete_id_from_file(self, filename):\n id_list = []\n f = FileHelper();\n f.read_file(filename, id_list)\n\n for del_id in id_list:\n logger.info(\"del id:{}\".format(del_id))\n result = self.api.delete_objects(id=del_id)\n logger.info(result)\n self.assertEqual(result.status_code, 200)\n\n def function_delete_users_departments_from_file(self):\n self.delete_id_from_file(\"user_id.csv\")\n self.delete_id_from_file(\"dp_id.csv\")\n\n def create_department(self, dept_id=\"dp-yufu\", dept_name=\"new_dept\", parent_id=None):\n \"\"\" should create deptNumber as custom field in profile editor \"\"\"\n data = {\"deptNumber\": dept_id, \"name\":dept_name, \"status\": \"ENABLED\", \"parentId\":parent_id}\n payload = {\"objectType\":\"DEPT\", \"values\": data}\n result = self.api.create_objects(payload)\n logger.info(result) \n logger.info(result.text) \n if result.status_code != 201:\n logger.error(\"[部门]- 创建失败..dept_name={}\".format(dept_name))\n return None\n else:\n d = result.json()\n logger.info(d['id'])\n return d['id']\n\n def mock_create_department(self, dept_id, dept_name, parent_id):\n id = \"dp-000\"\n if ( parent_id == \"dp-yufu\" ):\n id = \"dp-111\"\n elif (dept_id in [\"9901\", \"9902\", \"9903\", \"9904\", \"9905\", \"9906\", \"9907\", \"9908\", \"9909\"] ):\n id = \"dp-222\"\n else:\n id = \"dp-333\"\n return id\n\n def create_one_user_data_under_dept(self, dept, dept_id, index):\n \"\"\"\n dept = ( \"茄梨\", \"990101\", 2, \"qieli\", 1512222),\n ( \"鸭梨\", \"990102\", 2, \"yali\", 1512222),\n users = (\n (\"茄梨1号\", \"01010001\", 15122220001, \"qieli1@fruit.com\"))\n (\"茄梨9号\", \"01010009\", 15122220009, \"qieli9@fruit.com\"))\n (\"鸭梨1号\", \"01020001\", 15122221001, \"yali1@fruit.com\"))\n (\"鸭梨9号\", \"01020001\", 15122221009, \"yali1@fruit.com\"))\n (\"泰榴1号\", \"01010001\", 15222221001, \"tailiu1@fruit.com\"))\n (\"越榴1号\", \"02010001\", 15222221001, \"yali1@fruit.com\"))\n \"\"\" \n dept_name, dept_number, level, email_name, phone_prefix = dept\n \n display_name = dept_name + \"{}号\".format(index)\n email = \"{}{}@fruit.com\".format(email_name, index)\n phone_num = phone_prefix * 10000 + ( int(dept_number[-1]) - 1 ) * 1000 + index\n user_num = dept_number[2:] + \"0000\" + \"{}\".format(index)\n\n data = {}\n data[\"status\"] = \"PENDING_ACTIVATE\"\n data[\"displayName\"] = display_name\n data[\"username\"] = email\n data[\"primaryMail\"] =email\n data[\"secondaryMail\"] = None\n data[\"deptId\"] = dept_id\n data[\"phoneNum\"] = phone_num\n data[\"superiorId\"] = None\n data[\"jobNumber\"] = user_num\n logger.info(data)\n return data\n\n def create_users_under_departments_with_numbers(self, dept, dept_id, numbers, start=1):\n for index in range(start, numbers + start):\n data = self.create_one_user_data_under_dept(dept, dept_id, index)\n\n payload = {\"objectType\":\"USER\", \"values\": data }\n result = self.api.create_objects(payload)\n logger.info(result)\n logger.info(result.text)\n \n if result.status_code != 201:\n logger.error(\"[人员], 创建失败..dept_id={}\".format(dept_id))\n break\n else:\n d = result.json()\n self.all_users_id_list.append(d['id'])\n \n return index \n\n def function_create_departments_sub_departments_and_users(self):\n # gangdeng@yufuid.com, 2018-11-12\n # implements create 10,000 users under 20 departments/sub-departments\n \"\"\"\n dept_name_list = (\n (\"name\", \"id\", level=0) parent_id=\"dp_yufu\"\n (\"name\", \"id\", level=1) parent_id=\"dp_dept_id\"\n (\"name\", \"id\", level=1) \n (\"name\", \"id\", level=2) parent_id=\"dp_sub_dept_id\"\n )\n dept_parent_id_list = [\"dp_yufu\", \"dp_dept_id\", \"dp_sub_dept_id\"]\n dept_parent_id_list[level] => parent_id\n dp_root_id = create_dept(name, id, parent_id)\n dept_parent_id_list[level+1] => dp_root_id\n if level == 2\n create_user(name, id, email, phone, dp_root_id)\n \"\"\"\n dept_name_list = (\n (\"水果\", \"99\", 0, \"\", 0),\n (\"梨子\", \"9901\", 1, \"\", 0),\n (\"茄梨\", \"990101\", 2, \"qieli\", 1512222),\n (\"鸭梨\", \"990102\", 2, \"yali\", 1512222),\n (\"榴莲\", \"9902\", 1, \"\", 0),\n (\"泰国榴莲\", \"990201\", 2, \"tailiu\", 1522222),\n (\"越南榴莲\", \"990202\", 2, \"yueliu\", 1522222),\n (\"火龙果\", \"9903\", 1, \"\", 0),\n (\"红心火龙果\", \"990301\", 2, \"hxhlg\", 1532222),\n (\"白心火龙果\", \"990302\", 2, \"bxhlg\", 1532222),\n (\"桃子\", \"9904\", 1, \"\", 0),\n (\"水蜜桃\", \"990401\", 2, \"shuimitao\", 1542222),\n (\"久保\", \"990402\", 2, \"jiubao\", 1542222),\n (\"山竹\", \"9905\", 1, \"\", 0),\n (\"油竹\", \"990501\", 2, \"youzhu\", 1552222),\n (\"油沙竹\", \"990502\", 2, \"youshazhu\", 1552222),\n (\"橙子\", \"9906\", 1, \"\", 0),\n (\"血橙\", \"990601\", 2, \"xuecheng\", 1562222),\n (\"脐橙\", \"990602\", 2, \"qicheng\", 1562222),\n (\"长红\", \"990603\", 2, \"changhong\", 1562222),\n (\"哈密瓜\", \"9907\", 1, \"\", 0),\n (\"雪里红\", \"990701\", 2, \"xuelihong\", 1572222),\n (\"西州蜜\", \"990702\", 2, \"xizhoumi\", 1572222),\n (\"猕猴桃\", \"9908\", 1, \"\", 0),\n (\"红心猕猴桃\", \"990801\", 2, \"hxmht\", 1582222),\n (\"中华猕猴桃\", \"990802\", 2, \"zhmht\", 1582222),\n (\"樱桃\", \"9909\", 1, \"\", 0),\n (\"红灯\", \"990901\", 2, \"hongdeng\", 1592222),\n (\"先锋\", \"990902\", 2, \"xianfeng\", 1592222),\n (\"红蜜\", \"990903\", 2, \"hongmi\", 1592222))\n logger.info(\"批量创建 部门,子部门: 总计{}\".format(len(dept_name_list)))\n dp_root = self.api.department_root\n dept_parent_id_list = [dp_root, \"dp-c48a24b25da1400599bc0470e6a73956\", \"dp-2d845605ade84ea28ae5f7c17a8e1b48\", \"dp-level3\"]\n\n for dept in dept_name_list:\n dept_name, dept_id, level, email_prefix, phone_prefix = dept \n parent_id = dept_parent_id_list[level] \n dp_new_id = None\n print(\"部门:{}, 编号:{}, parent_id:{}\".format(dept_name, dept_id, parent_id))\n if self.api._debug_local:\n dp_new_id = self.mock_create_department(dept_id, dept_name, parent_id) \n else: \n dp_new_id = self.create_department(dept_id, dept_name, parent_id)\n # create 5 users under the department after the department create success\n if dp_new_id:\n self.all_dp_id_list.append(dp_new_id)\n level += 1\n dept_parent_id_list[level] = dp_new_id\n if level == 3:\n members = self.create_users_under_departments_with_numbers(dept, dp_new_id, 500)\n logger.info(\"在部门({})下,成功创建({})个用户。。\".format(dp_new_id, members))\n else:\n logger.error(\"部门创建返回失败,退出。。\")\n break \n\n # last create will be delete first!!\n logger.info(\"保存 部门,人员 id 到文件, dp_id.csv, user_id.csv\")\n if self.all_dp_id_list: \n reversed_dp_id_list = self.all_dp_id_list\n reversed_dp_id_list.reverse()\n fh=FileHelper()\n fh.save_file(\"dp_id.csv\", reversed_dp_id_list)\n if self.all_users_id_list: \n reversed_users_id_list = self.all_users_id_list\n reversed_users_id_list.reverse()\n fh=FileHelper()\n fh.save_file(\"user_id.csv\", reversed_users_id_list)\n logger.info(\"胜利结束,完美,完美!!!\") \n\n def function_create_users_under_department(self):\n # [patch]- some users under 水蜜桃 create failed, let's try it again.\n dept = ( \"水蜜桃\", \"990401\", 2, \"shuimitao\", 1542222)\n dp_new_id = \"dp-8e8933df652246bea85fcac77a6bb92f\"\n members = self.create_users_under_departments_with_numbers(dept, dp_new_id, 1, 500)\n logger.info(\"在部门({})下,成功创建({})个用户。。\".format(dp_new_id, members))\n if self.all_users_id_list: \n reversed_users_id_list = self.all_users_id_list\n reversed_users_id_list.reverse()\n fh=FileHelper()\n fh.save_file(\"user_id.csv\", reversed_users_id_list)\n logger.info(\"胜利结束,完美,完美!!!\") \n\n def function_get_url_data_and_delete_users(self):\n url = \"https://yufu-admin.rc.yufuid.org/api/v1/tn-yufu/objects/?page_index=0&page_size=1000&order_by=modifiedOn&status=ACTIVE&status=PENDING_ACTIVATE&status=PASSWORD_RESET&status=SUSPENDED&status=LOCKED_OUT&need_child_depts=false&object_type=USER\"\n result = self.api.get(url)\n\n logger.info(result)\n d = result.json()\n print(\"total = {}\".format(d[\"total\"]))\n count_pass, count_fail = (0, 0)\n\n for item in d[\"data\"]:\n user_id = item[\"id\"]\n username = item[\"values\"][\"username\"]\n if \"@zoo.com\" in username:\n result = self.api.delete_objects(id=user_id)\n if result.status_code == 200:\n count_pass += 1\n logger.debug(\"del id:{} success!\".format(user_id))\n else:\n count_fail += 1\n logger.debug(\"del id:{} fail....\".format(user_id))\n logger.info(\"delete user_id success:{} fail:{}\".format(count_pass, count_fail)) \n\n def function_get_url_data_and_update_users(self):\n url = \"https://yufu-admin.rc.yufuid.org/api/v1/tn-yufu/objects/?page_index=0&page_size=10000&order_by=_displayName&status=ACTIVE&status=PENDING_ACTIVATE&status=PASSWORD_RESET&status=SUSPENDED&status=LOCKED_OUT&need_child_depts=true&dept_id=dp-c48a24b25da1400599bc0470e6a73956&object_type=USER\"\n result = self.api.get(url)\n\n logger.info(result)\n d = result.json()\n\n for item in d[\"data\"]:\n user_id = item[\"id\"]\n username = item[\"values\"][\"username\"]\n phone_num = item[\"values\"][\"phoneNum\"] \n if \"@fruit.com\" in username:\n logger.info(\"update id:{}\".format(user_id))\n phone_num -= 1000000000\n logger.info(\"new phone num:{}\".format(phone_num))\n payload = {\"values\": {\"phoneNum\":phone_num}}\n result = self.api.update_objects(id=user_id, payload=payload)\n logger.info(result) \n if result.status_code == 200:\n logger.info(\"update success!\")\n else:\n logger.info(\"update fail....\") \n\n def main_unitest(self):\n s = unittest.TestSuite()\n s.addTest(UsersTest(\"test_create_and_delete_users_10\"))\n s.addTest(UsersTest(\"test_create_and_delete_users_100\"))\n s.addTest(UsersTest(\"test_create_and_delete_users_1000\"))\n s.addTest(UsersTest(\"stress_test_create_and_delete_users_10000\"))\n s.addTest(UsersTest(\"function_get_url_data_and_delete_users\"))\n s.addTest(UsersTest(\"function_create_departments_sub_departments_and_users\"))\n s.addTest(UsersTest(\"function_create_users_under_department\"))\n s.addTest(UsersTest(\"function_get_url_data_and_update_users\"))\n s.addTest(UsersTest(\"function_delete_users_departments_from_file\"))\n s.addTest(UsersTest(\"function_get_url_data_and_update_users\"))\n runner = unittest.TextTestRunner()\n runner.run(s) \n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"apitest/apitest/users_test.py","file_name":"users_test.py","file_ext":"py","file_size_in_byte":15503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"292300851","text":"from django.conf.urls import url\n\nfrom .views import home_view, login_view, logout_view, register_view, add_dustbin_view, add_region_view, map_view, \\\n geolocation_view, geolocationmap_view, database_location_view, waypoints_direction_view, report_view, \\\n select_notification, notification_map_view, index_view, user_view, edit_profile_view, view_reports, comments_view, \\\n receive_view,charts_view,get_data,solution_view\n\nurlpatterns = [\n url(r'^$',home_view,name='home'),\n url(r'^index/$',index_view,name='index'),\n url(r'^login/$',login_view,name='login'),\n url(r'^logout/$',logout_view,name='logout'),\n url(r'^register/$',register_view,name='register'),\n url(r'^add_dustbin/$',add_dustbin_view,name='add_dustbin'),\n url(r'^add_region/$',add_region_view,name='add_region'),\n url(r'^edit_profile/$',edit_profile_view,name='edit_profile'),\n url(r'^view_map/$', map_view, name='map_view'),\n url(r'^geolocation_view/$', geolocation_view, name='geolocation_view'),\n url(r'^geolocationmap_view/$', geolocationmap_view, name='geolocationmap_view'),\n url(r'^database_view/$', database_location_view, name='database_view'),\n url(r'^waypoints_direction_view/$', waypoints_direction_view, name='waypoints_direction_view'),\n url(r'^report_view/$', report_view, name='report_view'),\n url(r'^select_notification/$', select_notification, name='select_notification'),\n url(r'^notification_view/$', notification_map_view, name='notification_view'),\n url(r'^user_view/$', user_view, name='user_view'),\n url(r'^view_reports/$',view_reports,name='view_reports'),\n url(r'^comments/$',comments_view,name='comments'),\n url(r'^receive/(?P[\\w ]+)/$',receive_view,name='receive_view'),\n url(r'^charts/$',charts_view,name='charts'),\n url(r'^api/data/$',get_data,name='api-data'),\n url(r'^solution/$',solution_view,name='solution'),\n\n\n]","sub_path":"waste_mgn/waste_mgn_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"210959619","text":"import os\nimport unittest\nfrom common.log import Log\nfrom common.EmailMethod import Email\nfrom common.HTMLTestRunner import HTMLTestRunner\nfrom common.config_reader import configReader\nfrom common.config_reader import ROOT_PATH\n\n\nreport_path = os.path.join(ROOT_PATH,'testReport/report.html')\n\n#测试用例所在文件夹\ncase_path = os.path.join(ROOT_PATH,\"testCase\")\n\n\nclass testAll():\n logger = Log().get_log()\n\n def __init__(self):\n global logger\n self.config_email = configReader().get_email()\n self.email = Email()\n self.on_off = self.config_email[\"on_off\"]\n\n def run(self):\n #添加测试套件\n self.logger.info(\"创建测试套件\")\n #将文件夹中的测试用例一起执行\n test_suit = unittest.TestLoader().discover(case_path)\n #创建测试报告文件\n self.logger.info(\"生成测试报告\")\n try:\n self.fp = open(report_path,\"wb\")\n runner = HTMLTestRunner(stream=self.fp,verbosity=2,\n title=\"测试报告\",description=\"登陆接口\")\n runner.run(test_suit)\n except:\n raise FileNotFoundError\n finally:\n self.fp.close()\n if self.on_off ==\"1\":\n self.email.send_email()\n elif self.on_off==\"0\":\n self.logger.info(\"Dont need to send Email\")\n else:\n self.logger.error(\"unknow status\")\n\nif __name__ == '__main__':\n test = testAll()\n test.run()\n\n\n","sub_path":"TestRun/runAll.py","file_name":"runAll.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"271757004","text":"# -*- coding: utf-8 -*-\nfrom plone.app.testing import PLONE_INTEGRATION_TESTING\nfrom zope.component import getUtility\n\nimport unittest\n\ntry:\n from Products.CMFPlone.factory import _IMREALLYPLONE5\n _IMREALLYPLONE5 # pyflakes\nexcept ImportError:\n PLONE_5 = False\nelse:\n PLONE_5 = True\n\n\nclass UpgradeRegistry503to51alpha1Test(unittest.TestCase):\n \"\"\"test registry changes\n \"\"\"\n\n layer = PLONE_INTEGRATION_TESTING\n\n def test_migrate_less_variable_typo(self):\n from plone.app.upgrade.v51.alphas import \\\n _fix_typo_in_toolbar_less_variable\n from plone.registry.interfaces import IRegistry\n registry = getUtility(IRegistry)\n\n # set to a defined state\n plv = 'plone.lessvariables'\n registry[plv]['plone-toolbar-font-secundary'] = \"Foo\"\n if 'plone-toolbar-font-secondary' in registry[plv]:\n del registry[plv]['plone-toolbar-font-secondary']\n\n # start testing\n _fix_typo_in_toolbar_less_variable(self)\n self.assertEqual(\n registry[plv]['plone-toolbar-font-secondary'],\n 'Foo',\n )\n self.assertTrue(\n 'plone-toolbar-font-secundary' not in registry[plv]\n )\n\n\ndef test_suite():\n # Skip these tests on Plone 4\n if not PLONE_5:\n return unittest.TestSuite()\n\n suite = unittest.TestSuite()\n suite.addTest(\n unittest.makeSuite(UpgradeRegistry503to51alpha1Test)\n )\n return suite\n","sub_path":"buildout-cache/eggs/plone.app.upgrade-1.3.25-py2.7.egg/plone/app/upgrade/v51/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"223576890","text":"import argparse\nimport numpy as np\nimport control, math\nfrom matplotlib import pyplot as plt \n\ndef get_value_of_K(testing_point, G):\n plant_value = control.evalfr(G, testing_point)\n value_of_K = 1/abs(plant_value)\n return value_of_K\n\ndef find_angle (testing_point, G):\n degrees =math.degrees(np.angle(control.evalfr(G, testing_point)))\n radians = math.radians(degrees)\n return radians, degrees\n\n\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n prog='point_in_root_loccus', description='Propone un controlador en adelanto, su K correspondiente y el valor del error del estado estable')\n parser.add_argument(\n '--num_G', nargs=\"+\",help='Coeficientes del numerador de la función de transferencia', required=True, type=int)\n parser.add_argument(\n '--den_G', nargs=\"+\",help='Coeficientes del denominador de la función de transferencia', required=True, type=int)\n parser.add_argument(\n '--test_point', nargs=\"+\", help='FORMATO: -2 2j ->Punto que queremos agregar al root loccus ', action=\"store\", required=True, type=complex )\n args = parser.parse_args()\n G = control.tf(args.num_G,args.den_G)\n testing_point = np.sum(args.test_point)\n radians, degrees = find_angle(testing_point, G)\n if (((degrees/180)%2)!= 0 and (degrees%180 == 0)):\n K= get_value_of_K(testing_point, G)\n print(\"This test point does belong to the root loccus with a value of K = \", K)\n else: \n defficit = np.pi - radians\n if (defficit > np.pi):\n defficit -= np.pi\n print(\"This test point does not belong to the root loccus, the angle defficit is \", defficit , \" rad or \", math.degrees(defficit), \" degrees.\")\n\n\n","sub_path":"ControllerDesign/utils/point_in_root_loccus.py","file_name":"point_in_root_loccus.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"60395674","text":"from keras import backend as K\nfrom keras.losses import binary_crossentropy\nimport numpy\nimport keras\n\n\n#Keras\ndef DiceBCELoss(targets, inputs, smooth=1e-6): \n \n #flatten label and prediction tensors\n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n BCE = binary_crossentropy(targets, inputs)\n intersection = K.sum(targets * inputs) \n dice_loss = 1 - (2*intersection + smooth) / (K.sum(targets) + K.sum(inputs) + smooth)\n Dice_BCE = BCE + dice_loss\n \n return Dice_BCE\n\n\n#Keras\ndef DiceLoss(targets, inputs, smooth=1e-6):\n \n #flatten label and prediction tensors\n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n intersection = K.sum(targets * inputs) \n dice = (2*intersection + smooth) / (K.sum(targets) + K.sum(inputs) + smooth)\n return 1 - dice\n\n\n#Keras\ndef IoULoss(targets, inputs, smooth=1e-6):\n \n #flatten label and prediction tensors\n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n intersection = K.sum(targets * inputs)\n total = K.sum(targets) + K.sum(inputs)\n union = total - intersection\n \n IoU = (intersection + smooth) / (union + smooth)\n return 1 - IoU\n\n\n\n#Keras\nALPHA = 0.8\nGAMMA = 2\n\ndef FocalLoss(targets, inputs, alpha=ALPHA, gamma=GAMMA): \n \n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n BCE = K.binary_crossentropy(targets, inputs)\n BCE_EXP = K.exp(-BCE)\n focal_loss = K.mean(alpha * K.pow((1-BCE_EXP), gamma) * BCE)\n \n return focal_loss\n\n#Keras\nALPHA = 0.5\nBETA = 0.5\n\ndef TverskyLoss(targets, inputs, alpha=ALPHA, beta=BETA, smooth=1e-6):\n \n #flatten label and prediction tensors\n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n #True Positives, False Positives & False Negatives\n TP = K.sum((inputs * targets))\n FP = K.sum(((1-targets) * inputs))\n FN = K.sum((targets * (1-inputs)))\n \n Tversky = (TP + smooth) / (TP + alpha*FP + beta*FN + smooth) \n \n return 1 - Tversky\n \n\n#Keras\nALPHA = 0.9\nBETA = 0.1\nGAMMA = 0.75\n\ndef FocalTverskyLoss(targets, inputs, alpha=ALPHA, beta=BETA, gamma=GAMMA, smooth=1e-6):\n \n #flatten label and prediction tensors\n inputs = K.flatten(inputs)\n targets = K.flatten(targets)\n \n #True Positives, False Positives & False Negatives\n TP = K.sum((inputs * targets))\n FP = K.sum(((1-targets) * inputs))\n FN = K.sum((targets * (1-inputs)))\n \n Tversky = (TP + smooth) / (TP + alpha*FP + beta*FN + smooth) \n FocalTversky = K.pow((1 - Tversky), gamma)\n \n return FocalTversky\n \n \n \n \n \n \n \n \n ","sub_path":"old_code/python/new_loss.py","file_name":"new_loss.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45545450","text":"from typing import Optional\n\nimport numpy as np\n\nfrom diagnnose.activations.activation_reader import ActivationReader\nfrom diagnnose.corpus.create_labels import create_labels_from_corpus\nfrom diagnnose.typedefs.activations import ActivationName, SelectFunc\nfrom diagnnose.typedefs.classifiers import DataDict\nfrom diagnnose.typedefs.corpus import Corpus\n\n\nclass DataLoader:\n \"\"\" Reads in pickled activations that have been extracted.\n\n Parameters\n ----------\n activations_dir : str\n Directory containing the extracted activations.\n corpus : Corpus\n Corpus containing the labels for each sentence.\n test_activations_dir : str, optional\n Directory containing the extracted test activations. If not\n provided the train activation set will be split and partially\n used as test set.\n test_corpus : Corpus, optional\n Corpus containing the test labels for each sentence. Must be\n provided if `test_activations_dir` is provided.\n selection_func : SelectFunc, optional\n Selection function that determines whether a corpus item should\n be taken into account. If such a function has been used during\n extraction, make sure to pass it along here as well.\n \"\"\"\n\n def __init__(\n self,\n activations_dir: str,\n corpus: Corpus,\n test_activations_dir: Optional[str] = None,\n test_corpus: Optional[Corpus] = None,\n selection_func: SelectFunc = lambda sen_id, pos, example: True,\n ) -> None:\n assert corpus is not None, \"`corpus`should be provided!\"\n\n self.train_labels = create_labels_from_corpus(\n corpus, selection_func=selection_func\n )\n\n if test_activations_dir is not None:\n self.test_activation_reader = ActivationReader(test_activations_dir)\n assert test_corpus is not None, \"`test_corpus` should be provided!\"\n self.test_labels = create_labels_from_corpus(\n test_corpus, selection_func=selection_func\n )\n else:\n self.test_activation_reader = None\n self.test_labels = None\n\n self.activation_reader = ActivationReader(activations_dir)\n self.data_len = len(self.activation_reader)\n\n def create_data_split(\n self,\n activation_name: ActivationName,\n data_subset_size: int = -1,\n train_test_split: float = 0.9,\n ) -> DataDict:\n \"\"\" Creates train/test data split of activations\n\n Parameters\n ----------\n activation_name : ActivationName\n (layer, name) tuple indicating the activations to be read in\n data_subset_size : int, optional\n Subset size of data to train on. Defaults to -1, indicating\n the entire data set.\n train_test_split : float\n Percentage of the train/test split. If separate test\n activations are provided this split won't be used.\n Defaults to 0.9/0.1.\n \"\"\"\n\n if data_subset_size != -1:\n assert (\n 0 < data_subset_size <= self.data_len\n ), \"Size of subset can't be bigger than the full data set.\"\n\n train_activations = self.activation_reader.read_activations(activation_name)\n\n # Shuffle activations\n data_size = self.data_len if data_subset_size == -1 else data_subset_size\n indices = np.random.choice(range(data_size), data_size, replace=False)\n train_activations = train_activations[indices]\n train_labels = self.train_labels[indices]\n\n if self.test_activation_reader is not None:\n test_activations = self.test_activation_reader.read_activations(\n activation_name\n )\n test_labels = self.test_labels\n else:\n split = int(data_size * train_test_split)\n\n test_activations = train_activations[split:]\n test_labels = train_labels[split:]\n train_activations = train_activations[:split]\n train_labels = train_labels[:split]\n\n return {\n \"train_x\": train_activations,\n \"train_y\": train_labels,\n \"test_x\": test_activations,\n \"test_y\": test_labels,\n }\n","sub_path":"diagnnose/activations/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"230565483","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 27 17:40:25 2019\n\n@author: TAPAN\n\n\nCode Challenge: Simple Linear Regression\n\n Name: \n Box Office Collection Prediction Tool\n Filename: \n Bahubali2vsDangal.py\n Dataset:\n Bahubali2vsDangal.csv\n Problem Statement:\n It contains Data of Day wise collections of the movies Bahubali 2 and Dangal \n (in crores) for the first 9 days.\n \n Now, you have to write a python code to predict which movie would collect \n more on the 10th day.\n Hint:\n First Approach - Create two models, one for Bahubali and another for Dangal\n Second Approach - Create one model with two labels\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\n\ndataset = pd.read_csv('Bahubali2_vs_Dangal.csv')\ntemp = dataset.values\nfeatures = dataset.iloc[:, :1].values\nlabels = dataset.iloc[:, 1:].values\nlab_bah=dataset.iloc[:, 1].values\nlab_dan=dataset.iloc[:, 2].values\n\nday=np.array(10)\n\nday=day.reshape(1,1)\n#model for bahubali\nregressor_bah = LinearRegression()\nregressor_bah.fit(features, lab_bah)\n\nregressor_bah.predict(day)\n\n#model for Dangal\nregressor_dan = LinearRegression()\nregressor_dan.fit(features, lab_dan)\n\nregressor_dan.predict(day)\n\n# BOth labels together\nregressor = LinearRegression()\nregressor.fit(features, labels)\n\nregressor.predict(day)\n\nprint (\"The Profit on day 10 of {} is {} and {} is {}\".format('bahubali 2',regressor.predict(day)[0][0],'dangal' ,regressor.predict(day)[0][1]))","sub_path":"Day 16/Work/bahubali2vsDangal.py","file_name":"bahubali2vsDangal.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"338927808","text":"import os\nimport numpy as np\nimport matplotlib\nmatplotlib.use('WxAgg')\n# matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom \t sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# time hightempr lowtempr avgtempr humidity rainlevel\nfiledata1 = os.path.join(basedir, 'data', 'data1.txt')\nfiledata2 = os.path.join(basedir, 'data', 'data2.txt')\n\n# time hightempr lowtempr avgtempr humidity rainlevel\nfiledata3 = os.path.join(basedir, 'data', 'data3.txt')\nfiledata4 = os.path.join(basedir, 'data', 'data4.txt')\n\nclass Helper:\n\n\t@staticmethod\n\tdef get_data(filename):\n\t\tdata = []\n\t\twith open(filename) as lines:\n\t\t\tfor line in lines:\n\t\t\t\tdata.append(line)\n\t\treturn data\n\ndata1 = Helper.get_data(filedata1)\ndata2 = Helper.get_data(filedata2)\n\ntempr1 = []\nfor i, line in enumerate(data1):\n\tline = line.split('\\t')\n\tdt_in = line[0]\n\thightempr = float(line[1])\n\tlowtempr = float(line[2])\n\tavgtempr = float(line[3])\n\thumidity = float(line[4])\n\trainlevel = float(line[5])\n\ttempr1.append([ hightempr, lowtempr, avgtempr, humidity, rainlevel ])\n\t# tempr1.append([ hightempr, lowtempr, avgtempr, humidity ])\n\n\t# year = int(dt_in[0:4])\n\t# tempr4.append(line)\n\t# print('line: {}'.format(line))\n\n\n\nX_train = []\ny_train = []\nall_data = []\n\npower = []\nmin_power = []\nmax_power = []\navg_power = []\ndiff_power = []\npayload_power = []\n\nfor i, line in enumerate(data2):\n\tline = line.split('\\t')\n\t# dt_in = int(line[0])\n\tdt_in = line[0]\n\tyear = int(dt_in[0:4])\n\tmon = dt_in[4:6].zfill(2)\n\tday = dt_in[6:8].zfill(2)\n\n\t# tempr_line = tempr1[i]\n\t# hightempr = float(tempr_line[0])\n\t# lowtempr = float(tempr_line[1])\n\t# avgtempr = float(tempr_line[2])\n\t# humidity = float(tempr_line[3])\n\t# rainlevel = float(tempr_line[4])\n\t# print ('tempr_line: %s' % tempr_line)\n\t# print ('%s lowtempr: %s' % (i, lowtempr))\n\n\t\n\tfor i in range(1, 96):\n\t\tpower.extend([float(line[i])])\n\n\n\tfor p in power:\n\t\tmin_power.extend([min(power)])\n\t\tmax_power.extend([max(power)])\n\t\tavg_power.extend([np.average(power)])\n\t\tdiff_power.extend([max(power)-min(power)])\n\t\tpayload_power.extend([np.mean(power)/max(power)])\n\n\n\t\t# X_train.append([dt_in, i])\n\t\t# X_train.append([dt_in, i, float(line[i]) ])\n\t\t# X_train.append([ year, int(mon), int(day), i, float(line[i]) ])\n\t\t# X_train.append([ year, int(mon), int(day), i, float(line[i]), hightempr, lowtempr, avgtempr, humidity, rainlevel ])\n\t\t# X_train.append([ year, int(mon), int(day), i, float(line[i]), hightempr, lowtempr, avgtempr, humidity ])\n\t\t# X_train.append([ year, int(mon), int(day), i, float(line[i]), hightempr, lowtempr, avgtempr ])\n\t\t# y_train.append([ float(line[i]) ])\n\n\n# classifier = 'linear_regression'\n# clf = None\n# if classifier == 'linear_regression':\n# \tclf = LinearRegression()\n# clf.fit(X_train, np.array(y_train).ravel())\n\n\n# Sample X_test\n# X_test = ([ 20141230, 2 ])\n# X_test = X_train\n# predictions = clf.predict(X_test)\n\n# predicted = []\n# for i, prediction in enumerate(predictions):\n# \tprint ('real_output:' + str(y_train[i]) + ' ' + 'prediction: ' +str(prediction))\n# \tpredicted.append(prediction)\n\n\n# y_train = [ int(i[0]) for i in y_train ]\n# fig = plt.figure()\n# ax = fig.add_subplot(111)\n# ax.set_title('Real data 2014')\n# ax.set_xlabel('Time, 15 minutes interval')\n# ax.set_ylabel('Real data')\n# # ax.legend('real data 2014')\n# ax.plot(y_train)\n# ax.grid(True)\n# plt.show()\n# predicted = [ int(i) for i in predicted ]\n# print('len real: %s' % len(y_train))\n# print('len pred: %s' % len(predicted))\n\n# fig = plt.figure()\n# ax = fig.add_subplot(111)\n# ax.set_title('Prediction')\n# ax.set_xlabel('Time, 15 minutes interval')\n# ax.set_ylabel('Real & Prediction')\n# ax.grid(True)\n# p1 = ax.plot(y_train)\n# p2 = ax.plot(predicted)\n# ax.legend((p1[0], p2[0]), ('real data', 'predictions'), loc='best', fancybox=True, framealpha=0.5)\n# plt.show()\n\n\n# Question?\n# \t20150111\n# \t20150112\n# \t20150113\n# \t20150114\n# \t20150115\n# \t20150116\n# \t20150117\n# X_test = []\n# for line in X_train:\n# \tX_test.append([ 2015, line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9] ])\n# \t# if line[0] == 2014 and line[1] == 1 and \\\n# \t# \t(line[2] == 11 or line[2] == 12 or \\\n# \t# \t\tline[2] == 13 or line[2] == 14 or \\\n# \t# \t\tline[2] == 15 or line[2] == 16 or line[2] == 17):\n\n# \t# \tX_test.append([ 2015, line[1], line[2], line[3], line[4], line[5], line[6], line[7], line[8], line[9] ])\n\n\n# # print ('X_test: %s' % X_test)\n# predictions = clf.predict(X_test)\n\n# y_cut = []\n# predicted = []\n# for i, prediction in enumerate(predictions):\n# \ty_cut.append(y_train[i])\n# \t# print ('real_output:' + str(y_train[i]) + ' ' + 'prediction: ' +str(prediction))\n# \tpredicted.append(prediction)\n\n# y_cut = [ int(i[0]) for i in y_cut ]\n# predicted = [ int(i) for i in predicted ]\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_title('Power')\nax.set_xlabel('Time, 15 minutes interval')\nax.set_ylabel('Power')\nax.grid(True)\np1 = ax.plot(min_power)\np2 = ax.plot(max_power)\np3 = ax.plot(avg_power)\np4 = ax.plot(diff_power)\np5 = ax.plot(payload_power)\np6 = ax.plot(power)\nax.legend((p1[0], p2[0], p3[0], p4[0], p5[0], p6[0]), ('min power', 'max power', 'avg power', 'diff power', 'payload power', 'power'), loc='best', fancybox=True, framealpha=0.5)\nplt.show()","sub_path":"sci2_1.py","file_name":"sci2_1.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"321571620","text":"\"\"\"\nCVMailUK spider created on the top of ATSSpider\n\nscrapy crawl cvmail_uk -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://fsr.cvmailuk.com/nortonrosefulbright/\"\n\nSeed URL:\n https://fsr.cvmailuk.com/nortonrosefulbright/\n https://fsr.cvmailuk.com/dacb/\n https://fsr.cvmailuk.com/clydecocareers/\n https://fsr.cvmailuk.com/burgessalmon/\n https://fsr.cvmailuk.com/capsticks/\n https://fsr.cvmailuk.com/gateley/\n https://fsr.cvmailuk.com/mishcon/\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import FormRequest, Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin, urlparse\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, HtmlFormatter, Prefix, ShrinkURL\nfrom brightcorp.lib.utils import get_hidden_inputs\n\npattern = {\n 'company': compile(r'\\/([^\\/]*)'),\n 'ref_id': compile(r'jobId=(\\d+)'),\n}\n\n\nclass CVMailUK(ATSSpider):\n\n name = 'cvmail_uk'\n company = ''\n\n def __init__(self, *args, **kwargs):\n super(CVMailUK, self).__init__(*args, **kwargs)\n if 'url' in kwargs:\n match = pattern['company'].search(urlparse(kwargs['url']).path)\n if match:\n self.company = match.group(1)\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\n '//table/tr/td/a[@class=\"jobMoreDetailCaptionStyle\"]'\n )\n for job in jobs:\n href = job.xpath('./@href').extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={'title': job.xpath('./text()').extract()},\n url=urljoin(response.url, href[0])\n )\n\n # pagination\n next_page = sel.xpath(\n '//tr/td/input[@name=\"next_page\"]/@value'\n ).extract()\n if next_page:\n form_data = get_hidden_inputs(response)\n action = sel.xpath('//form[@name=\"paging\"]/@action').extract()\n jump_page = sel.xpath(\n '//select[@name=\"jump_page\"]/option[@selected]/@value'\n ).extract()\n if action and jump_page:\n form_data.update({\n 'jump_page': str(int(jump_page[0]) + 1),\n 'jump_page': str(int(jump_page[0]) + 1),\n 'next_page': 'Next >>',\n })\n yield FormRequest(\n callback=self.parse,\n formdata=form_data,\n url=urljoin(response.url, action[0])\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n\n loader = BrightcorpItemLoader(selector=sel)\n\n loader.add_xpath(\n 'title',\n '//tr/td[contains(text(), \"Job Title\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()'\n )\n if not loader.get_output_value('title'):\n loader.add_value('title', response.meta.get('title'))\n\n loader.add_xpath(\n 'location',\n '//tr/td[contains(text(), \"Job Location\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text() |'\n '//tr/td[contains(text(), \"Location\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-%s-' % (self.name, self.company)),\n re=pattern['ref_id']\n )\n loader.add_value('company', self.company)\n loader.add_value(\n 'url', response.url, ShrinkURL(['queryString'])\n )\n loader.add_xpath(\n 'description',\n '//table/tr/td[contains(text(), \"Description\")]/../..',\n HtmlFormatter()\n )\n loader.add_xpath(\n 'jobcategory',\n [\n '//tr/td[contains(text(), \"Job Category\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()',\n '//tr/td[contains(text(), \"Department\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()',\n '//tr/td[contains(text(), \"Expertise\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()',\n ]\n )\n loader.add_xpath(\n 'expiration_date',\n '//tr/td[contains(text(), \"Closing Date\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()',\n ConvertDateString('%d-%b-%Y')\n )\n loader.add_xpath(\n 'experiencerequirements',\n '//tr/td[contains(text(), \"Experience\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//tr/td[contains(text(), \"Work Type\")]/following-sibling::td[@id=\"firm-jobdescription\"]/text()'\n )\n loader.add_value(\n 'apply_url', response.url, ShrinkURL(['queryString'])\n )\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/cvmail_uk.py","file_name":"cvmail_uk.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243458529","text":"\"\"\" PhotoInfo methods to expose computed score info from the library \"\"\"\n\nimport logging\nfrom dataclasses import dataclass\n\nfrom .._constants import _PHOTOS_4_VERSION\n\n\n@dataclass(frozen=True)\nclass ScoreInfo:\n \"\"\" Computed photo score info associated with a photo from the Photos library \"\"\"\n\n overall: float\n curation: float\n promotion: float\n highlight_visibility: float\n behavioral: float\n failure: float\n harmonious_color: float\n immersiveness: float\n interaction: float\n interesting_subject: float\n intrusive_object_presence: float\n lively_color: float\n low_light: float\n noise: float\n pleasant_camera_tilt: float\n pleasant_composition: float\n pleasant_lighting: float\n pleasant_pattern: float\n pleasant_perspective: float\n pleasant_post_processing: float\n pleasant_reflection: float\n pleasant_symmetry: float\n sharply_focused_subject: float\n tastefully_blurred: float\n well_chosen_subject: float\n well_framed_subject: float\n well_timed_shot: float\n\n\n@property\ndef score(self):\n \"\"\" Computed score information for a photo\n\n Returns:\n ScoreInfo instance\n \"\"\"\n\n if self._db._db_version <= _PHOTOS_4_VERSION:\n logging.debug(f\"score not implemented for this database version\")\n return None\n\n try:\n return self._scoreinfo # pylint: disable=access-member-before-definition\n except AttributeError:\n try:\n scores = self._db._db_scoreinfo_uuid[self.uuid]\n self._scoreinfo = ScoreInfo(\n overall=scores[\"overall_aesthetic\"],\n curation=scores[\"curation\"],\n promotion=scores[\"promotion\"],\n highlight_visibility=scores[\"highlight_visibility\"],\n behavioral=scores[\"behavioral\"],\n failure=scores[\"failure\"],\n harmonious_color=scores[\"harmonious_color\"],\n immersiveness=scores[\"immersiveness\"],\n interaction=scores[\"interaction\"],\n interesting_subject=scores[\"interesting_subject\"],\n intrusive_object_presence=scores[\"intrusive_object_presence\"],\n lively_color=scores[\"lively_color\"],\n low_light=scores[\"low_light\"],\n noise=scores[\"noise\"],\n pleasant_camera_tilt=scores[\"pleasant_camera_tilt\"],\n pleasant_composition=scores[\"pleasant_composition\"],\n pleasant_lighting=scores[\"pleasant_lighting\"],\n pleasant_pattern=scores[\"pleasant_pattern\"],\n pleasant_perspective=scores[\"pleasant_perspective\"],\n pleasant_post_processing=scores[\"pleasant_post_processing\"],\n pleasant_reflection=scores[\"pleasant_reflection\"],\n pleasant_symmetry=scores[\"pleasant_symmetry\"],\n sharply_focused_subject=scores[\"sharply_focused_subject\"],\n tastefully_blurred=scores[\"tastefully_blurred\"],\n well_chosen_subject=scores[\"well_chosen_subject\"],\n well_framed_subject=scores[\"well_framed_subject\"],\n well_timed_shot=scores[\"well_timed_shot\"],\n )\n return self._scoreinfo\n except KeyError:\n self._scoreinfo = ScoreInfo(\n overall=0.0,\n curation=0.0,\n promotion=0.0,\n highlight_visibility=0.0,\n behavioral=0.0,\n failure=0.0,\n harmonious_color=0.0,\n immersiveness=0.0,\n interaction=0.0,\n interesting_subject=0.0,\n intrusive_object_presence=0.0,\n lively_color=0.0,\n low_light=0.0,\n noise=0.0,\n pleasant_camera_tilt=0.0,\n pleasant_composition=0.0,\n pleasant_lighting=0.0,\n pleasant_pattern=0.0,\n pleasant_perspective=0.0,\n pleasant_post_processing=0.0,\n pleasant_reflection=0.0,\n pleasant_symmetry=0.0,\n sharply_focused_subject=0.0,\n tastefully_blurred=0.0,\n well_chosen_subject=0.0,\n well_framed_subject=0.0,\n well_timed_shot=0.0,\n )\n return self._scoreinfo\n","sub_path":"osxphotos/photoinfo/_photoinfo_scoreinfo.py","file_name":"_photoinfo_scoreinfo.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360723578","text":"import tkinter as tk\nfrom tello import Tello\n\nimport tkinter as tk\nfrom tello import Tello\nfrom datetime import datetime\nfrom time import sleep\n\n#demo 1 with remote control\n#just be able to take it off and land it\n\ndef onTakeoffButtonPress():\n takeoffButton.config(state=tk.DISABLED)\n landButton.config(state=tk.DISABLED)\n tello.send_command(\"takeoff\")\n landButton.config(state=tk.ACTIVE)\n leftButton.config(state=tk.ACTIVE)\n rightButton.config(state=tk.ACTIVE)\n\ndef onLandButtonPress():\n landButton.config(state=tk.DISABLED)\n takeoffButton.config(state=tk.DISABLED)\n leftButton.config(state=tk.DISABLED)\n rightButton.config(state=tk.DISABLED)\n tello.send_command(\"land\")\n takeoffButton.config(state=tk.ACTIVE)\n\ndef onLeftButtonPress():\n leftButton.config(state=tk.DISABLED)\n speed = speedScale.get()\n tello.send_command(\"left \" + str(speed))\n leftButton.config(state=tk.ACTIVE)\n\ndef onRightButtonPress():\n rightButton.config(state=tk.DISABLED)\n speed = speedScale.get()\n tello.send_command(\"right \" + str(speed))\n rightButton.config(state=tk.ACTIVE)\n\nwindow = tk.Tk()\nwindow.title(\"Demo Takeoff and Land\")\nwindow.minsize(200, 30)\nwindow.maxsize(400, 500)\n\nleftButton = tk.Button(window, text=\" << \", command=onLeftButtonPress)\nleftButton.grid(row=1, column=1)\nleftButton.config(state=tk.DISABLED)\n\nrightButton = tk.Button(window, text=\" >> \", command=onRightButtonPress)\nrightButton.grid(row=1, column=2)\nrightButton.config(state=tk.DISABLED)\n\nspeedScale = tk.Scale(window, from_=20, to=100, orient=tk.VERTICAL)\nspeedScale.grid(row=1, column=3, rowspan=2)\n\ntakeoffButton = tk.Button(window, text=\"Take Off\", command=onTakeoffButtonPress)\ntakeoffButton.grid(row=2, column=1)\n\nlandButton = tk.Button(window, text=\"Land\", command=onLandButtonPress)\nlandButton.grid(row=2, column=2)\nlandButton.config(state=tk.DISABLED)\n\ntello = Tello()\n#tello.send_command(\"command\")\n\nwindow.mainloop()","sub_path":"remote_control_app_3.py","file_name":"remote_control_app_3.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139131073","text":"#@ImagePlus (label=\"Image to back-projected:\") inImp\n#@File (label=\"X coordinate map:\") xMapFile\n#@File (label=\"Y coordinate map:\") yMapFile\n#@File (label=\"Z coordinate map:\") zMapFile\n#@float (label=\"Pixel size (microns per 1px):\") pxSize\n#@float (label=\"Downscale factor:\") dsRatio\n\n# This script creates a 3D image that displays the original image before\n# it got wrapped/embedded into the input inImp 2D image.\n# The input image can be any scalar voxel type, does NOT work for RGB well.\n\n# Usage:\n# \t- Find suitable parameters with CountBigNuclei_FindParameter.py\n#\t- Run Fiji\n# \t- Make sure that the update site SCF-MPI-CBG is activated\n#\t- Run this script\n\nfrom ij import IJ\nimport ij.ImagePlus\nimport ij.ImageStack\nfrom ij.process import FloatProcessor\nimport math\nimport os\nimport sys\n\n# this section adds a folder, in which this very script is living,\n# to the current search paths so that we can import our \"library script\"\nimport sys.path\nimport os.path\nimport inspect\nsys.path.append(os.path.dirname(inspect.getfile(inspect.currentframe()))+\"/lib\")\n\n# import our \"library script\"\nfrom importsFromImSAnE import *\n\n\n# reads the 3D coordinates for every pixel, coordinates are in units of microns\nrealCoords = readRealCoords(xMapFile.getAbsolutePath(),yMapFile.getAbsolutePath(),zMapFile.getAbsolutePath());\n\n# test that sizes match:\ncheckSize2DarrayVsImgPlus(realCoords, inImp);\n\n\nprint(\"calculating the 3D image size...\")\n# search for min&max per axis, while scaling back to pixel units (from the original micron ones)\nmin=[+99999999999,+99999999999,+99999999999]\nmax=[-99999999999,-99999999999,-99999999999]\nfor x in range(0,inImp.width):\n\tfor y in range(0,inImp.height):\n\t\tcoord = realCoords[x][y]\n\t\t# first, scale to pixel units\n\t\tcoord[0] = coord[0] / pxSize\n\t\tcoord[1] = coord[1] / pxSize\n\t\tcoord[2] = coord[2] / pxSize\n\n\t\t# second, update coordinate bounds\n\t\tif (coord[0] < min[0]):\n\t\t\tmin[0]=coord[0];\n\t\tif (coord[1] < min[1]):\n\t\t\tmin[1]=coord[1];\n\t\tif (coord[2] < min[2]):\n\t\t\tmin[2]=coord[2];\n\t\tif (coord[0] > max[0]):\n\t\t\tmax[0]=coord[0];\n\t\tif (coord[1] > max[1]):\n\t\t\tmax[1]=coord[1];\n\t\tif (coord[2] > max[2]):\n\t\t\tmax[2]=coord[2];\n\nprint(\"detected intervals:\")\nprint(\"X: \"+str(min[0])+\" .. \"+str(max[0]))\nprint(\"Y: \"+str(min[1])+\" .. \"+str(max[1]))\nprint(\"Z: \"+str(min[2])+\" .. \"+str(max[2]))\n\n# create an output image of float type (as float can store also integers)\nmin[0]=math.floor(min[0])\nmin[1]=math.floor(min[1])\nmin[2]=math.floor(min[2])\n\nmax[0]=math.ceil(max[0])\nmax[1]=math.ceil(max[1])\nmax[2]=math.ceil(max[2])\n\n# calc image size and downscale for the final output image\nxSize = int((max[0]-min[0]+1) /dsRatio)\nySize = int((max[1]-min[1]+1) /dsRatio)\nzSize = int((max[2]-min[2]+1) /dsRatio)\n\nprint(\"creating 3D of sizes: \"+str(xSize)+\" x \"+str(ySize)+\" x \"+str(zSize))\noutFloatProcessors = [ FloatProcessor(xSize,ySize) for z in range(zSize) ]\noutFloatPixels = [ outFloatProcessors[z].getPixels() for z in range(len(outFloatProcessors)) ]\n\n# sweep through the inImp and project pixels to outImp\nprint(\"populating the 3D image...\")\ntotalX = float(inImp.width)\ninIP = inImp.getProcessor();\nfor x in range(0,inImp.width):\n\tIJ.showProgress(float(x)/totalX)\n\tfor y in range(0,inImp.height):\n\t\tcoord = realCoords[x][y]\n\t\t# orig coords and downscale for the final output image\n\t\tnx = int((math.floor(coord[0] +0.5) -min[0]) /dsRatio)\n\t\tny = int((math.floor(coord[1] +0.5) -min[1]) /dsRatio)\n\t\tnz = int((math.floor(coord[2] +0.5) -min[2]) /dsRatio)\n\n\t\toutFloatPixels[nz][nx + ny*xSize] = inIP.getf(x,y)\n\nprint(\"constructing the 3D image...\")\nstack = ij.ImageStack(xSize,ySize)\nfor fp in outFloatProcessors:\n\tstack.addSlice(fp)\n\noutImp = ij.ImagePlus(\"back-projected \"+inImp.getTitle(), stack)\n\nprint(\"showing the 3D image, done afterwards\")\noutImp.show()\n","sub_path":"2_processInFiji/9_projectWrapped2DscalarBackTo3D.py","file_name":"9_projectWrapped2DscalarBackTo3D.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"239627802","text":"import pandas as pd\nimport sys\ndf = pd.read_csv(sys.argv[1] + '3DInterrupt.csv')\n#df = pd.read_csv(sys.argv[1] + 'output.csv')\ndf1 = df.replace(0.000, pd.np.nan)\ndf1 = df1.interpolate(limit_direction='both')\ndf1 = df1.round(3)\n\"\"\"\n#print(df1.Nosex)\n#print(df1.Nosex.interpolate('spline', order=2))\nfor column_name, item in df1.iteritems():\n #print(column_name)\n print(item)\n item = item.interpolate('spline', order=2)\n\"\"\"\nprint(df1)\ndf1.to_csv(sys.argv[1] + '3DInterrupt2.csv', index = 0)\n","sub_path":"pythonscript/Liner/0.3DInterrupt.py","file_name":"0.3DInterrupt.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"653566819","text":"import tensorflow.keras\nfrom PIL import Image, ImageOps\nfrom control_thread import *\nfrom math import *\nfrom imutils.video import FileVideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport cv2\n\n# Hough Line Transform\nfrom LineDetect import *\n\n# GPIO Library\nimport RPi.GPIO as GPIO\nfrom time import sleep\n\n# ----------------------------- motor ---------------------------\n# Motor state\nSTOP = 0\nFORWARD = 1\nBACKWARD = 2\n# Motor channel\nCHLU = 0\nCHLD = 1\nCHRU = 2\nCHRD = 3\n# Drive state\nS = 0\nF = 1\nB = 2\nFR = 3\nFL = 4\nFO = 5\nTL = 6\nTR = 7\nTO = 8\n\n# PIN input output setting\nOUTPUT = 1\nINPUT = 0\n# PIN setting\nHIGH = 1\nLOW = 0\n\n# Real PIN define\n# PWM PIN(BCM PIN)\nENLD = 5\nENRU = 24\nENRD = 6\nENLU = 25\n# GPIO PIN\nIN1 = 17\nIN2 = 4 # Left Down\nIN3 = 16\nIN4 = 12 # Right Up\nIN5 = 2\nIN6 = 3 # Right Down\nIN7 = 21\nIN8 = 20 # Left Up\n\n# GPIO Library Setting\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n# Servo PIN setting\nGPIO.setup(18, GPIO.OUT)\nGPIO.setup(13, GPIO.OUT)\n\n# PIN setting algorithm\ndef setPinConfig(EN, INF, INO): # EN, OFF, ON\n GPIO.setup(EN, GPIO.OUT)\n GPIO.setup(INF, GPIO.OUT)\n GPIO.setup(INO, GPIO.OUT)\n # Activate PWM in 100khz\n pwm = GPIO.PWM(EN, 100)\n # First, PWM is stop\n pwm.start(0)\n return pwm\n \n# Motor control algorithm\ndef setMotorControl(pwm, INF, INO, speed, stat):\n # Motor speed control to PWM\n pwm.ChangeDutyCycle(speed)\n \n # Forward\n if stat == FORWARD:\n GPIO.output(INO, HIGH)\n GPIO.output(INF, LOW)\n # BACKWORD\n elif stat == BACKWARD:\n GPIO.output(INO, LOW)\n GPIO.output(INF, HIGH)\n # STOP\n elif stat == STOP:\n GPIO.output(INO, LOW)\n GPIO.output(INF, LOW)\n\n# Motor control easily\ndef setMotor(ch, speed, stat):\n if ch == CHLD:\n setMotorControl(pwmLD, IN1, IN2, speed, stat)\n elif ch == CHRU:\n setMotorControl(pwmRU, IN3, IN4, speed, stat)\n elif ch == CHRD:\n setMotorControl(pwmRD, IN5, IN6, speed, stat)\n elif ch == CHLU:\n setMotorControl(pwmLU, IN7, IN8, speed, stat)\n\n# Motor Pin Setting(global var)\npwmLD = setPinConfig(ENLD, IN1, IN2) #in 100Hz\npwmRU = setPinConfig(ENRU, IN3, IN4) #in 100Hz\npwmRD = setPinConfig(ENRD, IN5, IN6) #in 100Hz\npwmLU = setPinConfig(ENLU, IN7, IN8) #in 100Hz\n#print('ENLU, ENLD, ENRU, ENRD = ',ENLU, ENLD, ENRU, ENRD)\n\n# Servo algorithm\nLU = GPIO.PWM(13,50)\nRU = GPIO.PWM(18, 50)\nLU.start(0)\nRU.start(0)\n\ndef setturn(tn,T):\n if tn == TL:\n LU.ChangeDutyCycle(5)\n RU.ChangeDutyCycle(5)\n sleep(T)\n elif tn == TR:\n LU.ChangeDutyCycle(8)\n RU.ChangeDutyCycle(7.7)\n sleep(T)\n elif tn == TO:\n LU.ChangeDutyCycle(6.5)\n RU.ChangeDutyCycle(5.8)\n sleep(T)\n#LU 13\n#(L)5 ~ 6.37 ~ 7.7(R)\n#RU 18\n#(L)4.5 ~ 5.8 ~ 7.5(R)\n\n# Drive algorithm\ndef setdrive(drv,T):\n if drv == S:\n setMotor(CHLU, 80, STOP) #setSpeed=80\n setMotor(CHLD, 80, STOP)\n setMotor(CHRU, 80, STOP)\n setMotor(CHRD, 80, STOP)\n sleep(T)\n elif drv == F:\n setMotor(CHLU, 100, FORWARD)\n setMotor(CHLD, 100, FORWARD)\n setMotor(CHRU, 100, FORWARD)\n setMotor(CHRD, 100, FORWARD)\n sleep(T)\n\n# Drive turn algorithm\ndef seturndrive(drv,T):\n if drv == FL:\n setdrive(F,0.1)\n setturn(TL,1)\n setdrive(F,T)\n elif drv == FR:\n setdrive(F,0.1)\n setturn(TR,1)\n setdrive(F,T)\n elif drv == FO:\n setdrive(F,0.1)\n setturn(TO,1)\n setdrive(F,T)\n\n#======================================= tm =======================================\n\n#캠 키기\nprint(\"[INFO] starting video file thread...\")\nfvs = FileVideoStream(0).start()\ntime.sleep(1.0)\n# start the FPS timer\nfps = FPS().start()\n\nPERMIT_ANGLE = 10 #forward 판단 범위(각도 + -)\n\nwhile fvs.more():\n frame = fvs.read() \n #frame = imutils.resize(frame, width=450)\n frame = cv2.resize(frame, dsize=(224,224), interpolation=cv2.INTER_AREA)\n height, width = frame.shape[:2] # 이미지 높이, 너비\n m_width = int(width/2)\n \n \n gray_img = grayscale(frame) # 흑백이미지로 변환\n blur_img = gaussian_blur(gray_img, 3) # Blur 효과\n\n min_threshold = 70\n max_trheshold = 210\n\n canny_img = canny(blur_img, min_threshold, max_trheshold) # Canny edge 알고리즘\n #vertices = np.array([[(50,height),(width/2-45, height/2+60), (width/2+45, height/2+60), (width-50,height)]], dtype=np.int32)\n\n #vertices = np.array([[(0,height/2+30),(width/2-140, height/2-60), (width/2+140, height/2-60), (width,height/2+30)]], dtype=np.int32)\n '''\n vertices = np.array([[(0,height),\n (0,height/2-25),\n (width/2-70, height/2-60),\n (width/2+70, height/2-60),\n (width,height/2-25),\n (width,height)]], dtype=np.int32)\n '''\n vertices = np.array([[(0,height), (0, height/2 + 40),\n (width, height/2 + 40), (width,height)]], dtype=np.int32)\n ROI_img = region_of_interest(canny_img, vertices,(0,0,255)) # ROI 설정\n\n rho = 1\n theta = 1 * np.pi/180\n threshold = 30 # threshold 값이 작으면 그만큼 기준이 낮아져 많은 직선이 검출될 것이고, 값을 높게 정하면 그만큼 적지만 확실한 직선들만 검출이 될 것이다\n \n line_arr = hough_lines(ROI_img, rho, theta, threshold, 10, 20) # 허프 변환\n line_arr = np.squeeze(line_arr) # remove single dimension (차원을 하나 줄임)\n\n # 기울기 구하기 (arctan(y,x)이용)\n slope_degree = np.arctan2(line_arr[:,1] - line_arr[:,3], line_arr[:,0] - line_arr[:,2]) * 180 / np.pi\n \n# 수평 기울기 제한\n line_arr = line_arr[np.abs(slope_degree)<175]\n slope_degree = slope_degree[np.abs(slope_degree)<175]\n\n# 수직 기울기 제한\n line_arr = line_arr[np.abs(slope_degree)>95]\n slope_degree = slope_degree[np.abs(slope_degree)>95]\n\n# 필터링된 직선 버리기\n L_lines, R_lines = line_arr[(slope_degree>0),:], line_arr[(slope_degree<0),:]\n L_lines, R_lines = L_lines[:,None], R_lines[:,None]\n\n if(len(L_lines) == 0 and len(R_lines) == 0): #L_lines, R_lines 모두 없는 경우\n L_lines = pre_left_line\n R_lines = pre_right_line\n\n elif(len(L_lines) == 0):#L_lines만 없는 경우\n L_lines = pre_left_line\n pre_right_line = R_lines\n\n elif(len(R_lines) == 0):#R_lines만 없는 경우\n R_lines = pre_right_line\n pre_left_line = L_lines\n\n else:#라인 모두 검출한 경우\n pre_right_line = R_lines\n pre_left_line = L_lines\n\n temp = np.zeros((frame.shape[0], frame.shape[1], 3), dtype=np.uint8)\n\n# 왼쪽, 오른쪽 각각 대표선 구하기\n left_fit_line = get_fitline(frame,L_lines)\n right_fit_line = get_fitline(frame,R_lines)\n\n# 대표선 '그리기'\n draw_fit_line(temp, left_fit_line)\n draw_fit_line(temp, right_fit_line)\n\n vanishing_point = expression(left_fit_line[0],left_fit_line[1],left_fit_line[2],left_fit_line[3],right_fit_line[0],right_fit_line[1],right_fit_line[2],right_fit_line[3])\n\n v_x = int(vanishing_point[0])\n v_y = int(vanishing_point[1])\n\n result = weighted_img(temp, frame) # 원본 이미지(=image)에 검출된 선(=temp) overlap\n cv2.circle(result, (v_x,v_y), 6, (0,0,255), -1) # cv2.circle(image, center_coordinates, radius, color, thickness)\n\n #circle 기준선(보조선)\n cv2.line(result,(m_width,0),(m_width,300),(255,255,0),5) # cv2.line(image, start_point, end_point, color, thickness)\n \n temp_x, temp_y = m_width/2 , height/2\n #각도 구하기\n angle = int(atan2(height - temp_y,m_width - temp_x)*180/pi)\n #print('angle:', angle)\n \n if(angle > 90 + PERMIT_ANGLE):#오른쪽\n angle = angle - 90\n elif(angle < 90 - PERMIT_ANGLE): #왼쪽\n angle = 90 - angle\n else: #foward\n print(\"angle-forward\")\n\n \n # display the size of the queue on the frame\n cv2.putText(frame, \"Queue Size: {}\".format(fvs.Q.qsize()), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) \n # show the frame and update the FPS counter\n cv2.imshow(\"Frame\", result)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n fps.update()\n\nfps.stop()\nprint(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\nprint(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n# do a bit of cleanup\ncv2.destroyAllWindows()\nfvs.stop()\n \n#========================================================================\n","sub_path":"previous_version/버전별 정리/0407-line.py","file_name":"0407-line.py","file_ext":"py","file_size_in_byte":8546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"245273386","text":"#Task 5.1\nfrom sympy import * # уравнения\nimport math\nimport matplotlib.pyplot as plt # графики\n\nfig = plt.figure() # создание шаблона для графика\n\nl1=10 # первое расстояние\nl2=16 # второе расстояние\nT = 0.04 #\nU = 300\n\n_lambda = U*T\ndelta_fi = 2*math.pi*(l2-l1)/_lambda\nprint(delta_fi)\n\nA0 = 1\nk = 2*math.pi/_lambda\nw = k*U\nts = [num/1000 for num in range(0,100,1)]\nxs = range(0,50)\nAs = []\nAs2 = []\n\n# Генерация данных для графика пo t\nx = 0\nfor t in ts:\n As.append(A0*cos(w*t-k*x))\n\n# Генерация данных для графика по x\nt = 0\nfor x in xs:\n As2.append(A0*cos(w*t-k*x))\n# график по x\nplt.plot(xs, As2)\nplt.show()\n# график по t\nplt.plot(ts, As)\nplt.show()\n","sub_path":"3_semester/Calc_Graph_Task/1-Part/Py_s/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"240117774","text":"n=int(input())\nfor p in range(n):\n a=int(input())\n b=[int(x) for x in input().split(\" \")]\n res=\"\"\n for i in b:\n if i%2==0:\n res=res+str(i)+\" \"\n for i in b:\n if i%2==1:\n res=res+str(i)+\" \"\n print(res)","sub_path":"Code/CodeRecords/2171/60829/282215.py","file_name":"282215.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"208671912","text":"#! /usr/bin/env python\n# _*_ endocing: UTF-8 _*_\n\n\"\"\"Example: Use scan and services Methods\"\"\"\n\nimport qi\nimport argparse\nimport sys\n\n\ndef main(session):\n \"\"\"\n This example uses the scan and services method.\n \"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\", type=str, default=\"127.0.0.1\",\n help=\"Robot IP address. \"\"On robot or Local Naoqi: \"\n \"use '127.0.0.1'.\")\n parser.add_argument(\"--port\", type=int, default=9559,\n help=\"Naoqi port number\")\n args = parser.parse_args()\n session = qi.Session()\n try:\n session.connect(\"tcp://{0}:{1}\".format(args.ip, str(args.port)))\n except RuntimeError:\n print(\"Can't connect to Naoqi at ip {0} on port {1}.\\n\"\n \"Please check your script arguments. Run with -h option \"\n \"for help.\".format(args.ip, str(args.port)))\n sys.exit(1)\n main(session)\n","sub_path":"02.ALConnectionManager/alconnectionmanager_services_example.py","file_name":"alconnectionmanager_services_example.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"282612198","text":"# Settings for django-userena.\n# http://django-userena.org\n\nimport os\nimport sys\nimport site\n\nHOMEDIR = os.path.dirname(os.path.realpath(__file__))\nALLDIRS = [ HOMEDIR + '/lib/python2.6/site-packages']\n\nprev_sys_path = list(sys.path)\n\nfor directory in ALLDIRS:\n site.addsitedir(directory)\n\nnew_sys_path = []\nfor item in list(sys.path):\n if item not in prev_sys_path:\n new_sys_path.append(item)\n sys.path.remove(item)\nsys.path[:0] = new_sys_path\n\n# this will also be different for each project!\nsys.path.append(HOMEDIR + '/demo_project')\nsys.path.append(HOMEDIR)\n\nos.environ['PYTHON_EGG_CACHE'] = HOMEDIR + '.python-eggs'\nos.environ['DJANGO_SETTINGS_MODULE'] = 'demo_project.settings_production'\n\nimport django.core.handlers.wsgi\n_application = django.core.handlers.wsgi.WSGIHandler()\n\ndef application(environ, start_response): \n environ['wsgi.url_scheme'] = environ.get('HTTP_X_URL_SCHEME', 'http') \n return _application(environ, start_response)\n","sub_path":"django-userena.wsgi","file_name":"django-userena.wsgi","file_ext":"wsgi","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"497025100","text":"from flask import Blueprint, jsonify\nfrom flask import current_app\n\nerror_blueprint = Blueprint(\"error\", __name__)\n\n\n@error_blueprint.app_errorhandler(Exception)\ndef handle_error(error):\n message = [str(x) for x in error.args]\n if not hasattr(error, \"status_code\"):\n status_code = 500\n else:\n status_code = error.status_code\n response = {\n \"error\": {\"type\": error.__class__.__name__, \"message\": message}\n }\n current_app.logger.debug(message)\n return jsonify(response), status_code\n","sub_path":"app/blueprints/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"597371595","text":"import datetime, time\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, render_to_response\nfrom django.template import RequestContext\nfrom django.utils import simplejson\n\nfrom OPEN.course.forms import AddCourseForm, AddForumForm, AddVideoForm, AddPdfForm\nfrom OPEN.course.models import Course, Forum, Grade, UploadedFile\nfrom OPEN.institute.models import Institute\nfrom OPEN.quiz.models import MCQuestionAttempt, LikertAttempt, OpenEndedAttempt, Quiz\n\nfrom annoying.decorators import ajax_request\nfrom threadedcomments.models import ThreadedComment\n\n\n@login_required\ndef course(request, course_id, template_name):\n \"\"\"\n Course Page\n \"\"\"\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n return HttpResponseRedirect(reverse('index'))\n return render_to_response(template_name, context_instance=RequestContext(request, {'course': course}))\n\n@login_required\ndef all_user_courses(request, template_name):\n \"\"\"\n Display all courses for a user\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n \n grades = Grade.objects.filter(student = user, course__start_date__lte = datetime.datetime.now()).order_by('-date_added')\n\n return render_to_response(template_name, context_instance=RequestContext(request, {'grades': grades}))\n\n@login_required\ndef course_pdf_list(request, course_id, template_name):\n \"\"\"\n Display list of pdfs against a course\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n return HttpResponseRedirect(reverse('index')) \n \n pdfs = UploadedFile.objects.filter(file_type = 'PDF', course = course.id)\n\n return render_to_response(template_name, context_instance=RequestContext(request, {'pdfs': pdfs, 'course': course}))\n\n@login_required\ndef view_file(request, course_id, pdf_id, template_name):\n \"\"\"\n Display pdf file \n \"\"\"\n pdf = UploadedFile.objects.get(id = pdf_id)\n return HttpResponseRedirect(str(pdf.uploads.url))\n\n@login_required\ndef course_video_list(request, course_id, template_name):\n \"\"\"\n Display list of videos against a course\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n return HttpResponseRedirect(reverse('index')) \n \n videos = UploadedFile.objects.filter(file_type = 'VID', course = course.id)\n return render_to_response(template_name, context_instance=RequestContext(request, {'videos': videos, 'course': course}))\n\n@login_required\ndef view_video_file(request, course_id, video_id, template_name):\n vid = UploadedFile.objects.get(id = video_id)\n return render_to_response(template_name, context_instance=RequestContext(request, {'vid': vid}))\n\n@login_required\ndef course_forum_list(request, course_id, template_name):\n \"\"\"\n Display list of forums against a course\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n course = None\n\n forums = Forum.objects.filter(course = course)\n return render_to_response(template_name, context_instance=RequestContext(request, {'forums': forums, 'course': course}))\n\n@login_required\ndef view_forum(request, course_id, forum_id, template_name):\n \"\"\"\n Display the forum\n \"\"\"\n try:\n forum = Forum.objects.get(id = forum_id)\n except Forum.DoesNotExist:\n forum = None\n return render_to_response(template_name, context_instance=RequestContext(request, {'forum': forum}))\n\n@login_required\n@ajax_request\ndef add_comment(request, course_id, forum_id):\n \"\"\"\n Add a comment in the forum\n \"\"\"\n if request.is_ajax() and request.POST.get('comment'):\n if request.method == 'POST':\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n comment = request.POST.get('comment')\n\n comment = ThreadedComment.objects.create(comment = comment, user_id = user.id, content_type_id = '21', site_id = '1', object_pk = forum_id, submit_date = datetime.datetime.now())\n \n date = comment.submit_date.strftime(\"%b. %d, %Y, %I:%M \")\n if comment.submit_date.strftime('%p') == 'AM':\n date = str(date) + 'a.m.'\n else:\n date = str(date) + 'p.m.'\n\n if user.get_profile().avatar:\n avatar = str(user.get_profile().avatar.url)\n else:\n avatar = settings.STATIC_URL + \"img/blank-avatar-50x50.jpg\"\n\n return HttpResponse(simplejson.dumps({\"status\": True, \"name\": user.get_full_name(), \"avatar\": avatar, \"comment\": comment.comment, \"date\": str(date)}), mimetype = 'application/json')\n return HttpResponse(simplejson.dumps({\"status\": False}))\n\n@login_required\ndef available_course(request, template_name):\n \"\"\"\n Display list of courses available to the user\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n \n user_courses = Grade.objects.filter(student = user).values('course')\n \n list_course_ids = [course['course'] for course in user_courses]\n courses = Course.objects.exclude(id__in=list_course_ids)\n \n return render_to_response(template_name, context_instance=RequestContext(request, {'courses': courses}))\n\n@login_required\ndef course_quiz_list(request, course_id, template_name):\n \"\"\"\n Display list of quizzes against a course\n \"\"\"\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n return HttpResponseRedirect(reverse('index')) \n\n mcq = MCQuestionAttempt.objects.filter(student = user).values_list('mcquestion__quiz__id')\n lik = LikertAttempt.objects.filter(student = user).values_list('likert__quiz__id')\n opended = OpenEndedAttempt.objects.filter(student = user).values_list('openended__quiz__id')\n\n q_ids = [i[0] for i in mcq] + [i[0] for i in lik] + [i[0] for i in opended]\n quizzes = Quiz.objects.filter(course = course.id).exclude(id__in = q_ids)\n return render_to_response(template_name, context_instance=RequestContext(request, {'quizzes': quizzes, 'course': course}))\n\n@login_required\n@ajax_request\ndef add_course(request):\n \"\"\"\n User can add a course\n \"\"\"\n if request.is_ajax() and request.POST.get('course_id'):\n if request.method == 'POST':\n try:\n user = User.objects.get(username = request.user.username)\n except User.DoesNotExist:\n return HttpResponseRedirect(reverse('registration_register'))\n\n course_id = request.POST.get('course_id')\n \n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n return HttpResponse(simplejson.dumps({\"status\": False}))\n\n grade = Grade.objects.create(student = user, course = course)\n return HttpResponse(simplejson.dumps({\"status\": True, \"course_id\": course.id}))\n return HttpResponse(simplejson.dumps({\"status\": False}))\n \n@login_required\ndef add_forum(request, course_id, template_name):\n \"\"\"\n Create a new forum\n \"\"\"\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n course = None\n\n if request.method == 'POST':\n form = AddForumForm(request.POST, request.FILES)\n if form.is_valid():\n title = request.POST.get('title')\n file = request.FILES.get('uploads')\n file_type = file.name.split('.')[-1]\n if file_type == 'pdf':\n file_type = 'PDF'\n else:\n file_type = 'VID'\n uploads = UploadedFile.objects.create(uploader = request.user, course = course, uploads = file, file_type = file_type, title = file.name)\n forum = Forum.objects.create(course = course, user = request.user, uploads = uploads, title = title)\n return render_to_response('course/view_forum.html', context_instance=RequestContext(request, {'forum': forum}))\n else:\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))\n else:\n form = AddForumForm()\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))\n\ndef add_new_course(request, template_name):\n \"\"\"\n Create a new Course\n \"\"\"\n if request.method == 'POST':\n form = AddCourseForm(request.POST)\n if form.is_valid():\n try:\n institute = Institute.objects.get(id = request.POST.get('institute', ''))\n except Institute.DoesNotExist:\n institute = None\n course, flag = Course.objects.get_or_create(user = request.user, description = request.POST.get('description', ''),\n institute = institute, title = request.POST.get('title', ''),\n code = request.POST.get('code', ''))\n if request.POST.get('start_date'):\n course.start_date = request.POST.get('start_date')\n else:\n course.start_date = time.strftime('%Y-%m-%d')\n if request.POST.get('end_date'):\n course.end_date = request.POST.get('end_date')\n course.save()\n if flag:\n Grade.objects.create(student = course.user, course = course)\n return HttpResponseRedirect(reverse('all_user_courses'))\n else:\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form}))\n else:\n form = AddCourseForm()\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form}))\n\n@login_required\ndef add_video(request, course_id, template_name):\n \"\"\"\n Upload video\n \"\"\"\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n course = None\n\n if request.method == 'POST':\n form = AddVideoForm(request.POST, request.FILES)\n if form.is_valid():\n title = request.POST.get('title')\n file = request.FILES.get('uploads')\n file_type = file.name.split('.')[-1]\n\n uploads = UploadedFile.objects.create(uploader = request.user, course = course, uploads = file, file_type = 'VID', title = title)\n\n return render_to_response('course/view_video_file.html', context_instance=RequestContext(request, {'vid': uploads}))\n else:\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))\n else:\n form = AddVideoForm()\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))\n\n@login_required\ndef add_pdf(request, course_id, template_name):\n \"\"\"\n Upload pdf\n \"\"\"\n try:\n course = Course.objects.get(id = course_id)\n except Course.DoesNotExist:\n course = None\n\n if request.method == 'POST':\n form = AddPdfForm(request.POST, request.FILES)\n if form.is_valid():\n title = request.POST.get('title')\n file = request.FILES.get('uploads')\n file_type = file.name.split('.')[-1]\n\n uploads = UploadedFile.objects.create(uploader = request.user, course = course, uploads = file, file_type = 'PDF', title = title)\n return HttpResponseRedirect(reverse('course_pdf_list', kwargs={'course_id': course.id}))\n else:\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))\n else:\n form = AddPdfForm()\n return render_to_response(template_name, context_instance=RequestContext(request, {'form': form, 'course': course, 'course_id': course_id}))","sub_path":"OPEN/course/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"149274318","text":"import requests\nimport json\n\n# Get (내놔) => Get a HTML\n# Post (받아라) => Post a Data\n\n\nurl = 'https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=859'\ndata = requests.get(url).text\nlotto_data = json.loads(data)\n\nprint(lotto_data['firstWinamnt'])\n\n'bit.do/4th4deep'","sub_path":"3_flask/first_flask/get_lotto.py","file_name":"get_lotto.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"347661888","text":"from sklearn.linear_model import LogisticRegression\nimport pickle\nimport numpy as np\n\n\n\ndef int2label(int_):\n return '+1' if int_ == 1 else '-1'\n\n\nif __name__ == '__main__':\n with open('result/ids.dump', 'rb') as ids_in:\n ids = pickle.load(ids_in)\n with open('result/logistic.dump', 'rb') as logistic_in:\n logistic_model = pickle.load(logistic_in)\n\n weights = np.array(logistic_model.coef_[0])\n indexes = np.argsort(weights)[::-1]\n\n print('Top 10')\n for index in indexes[:10]:\n print('{}:\\t{}'.format(list(ids.keys())[index], weights[index]))\n\n print('\\nBottom 10')\n for index in indexes[-10:]:\n print('{}:\\t{}'.format(list(ids.keys())[index], weights[index]))\n","sub_path":"Shi-ma/chapter08/knock75.py","file_name":"knock75.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"17472467","text":"#coding=utf-8\nfrom django.shortcuts import render_to_response, redirect\nfrom django.http import HttpResponse\nfrom main.models import Notification, Profile\nfrom django.template import RequestContext\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef clear_recent(request, num):\n num = int(num)\n notifications = Notification.objects.filter(user__pk=request.user.pk, unread=True).order_by('-pk')[:num]\n for n in notifications:\n n.unread = False\n n.decr_count_in_profile()\n n.save()\n \n unread_count = Profile.objects.get(pk=request.user.pk).notification_count \n return HttpResponse('{\"code\":\"0\", \"msg\":\"success\", \"unread_count\":\"' + str(unread_count) + '\"}')\n\n@login_required\ndef clear_one(request):\n notif_id = request.GET['notif_id']\n n = Notification.objects.get(pk=notif_id)\n n.unread = False\n n.decr_count_in_profile()\n n.save()\n \n return HttpResponse('{\"code\":\"0\", \"msg\":\"success\"}')\n\n\n@login_required\ndef display_all(request, page=1):\n \"\"\"\n Distinguish unread from read in template\n \"\"\"\n notification_set = Notification.objects.filter(user__pk=request.user.pk).order_by('-pk')\n paginator = Paginator(notification_set, 15) # Show 15 notifications per page\n try:\n notifications = paginator.page(page)\n except PageNotAnInteger:\n notifications = paginator.page(1)\n except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results.\n notifications = paginator.page(paginator.num_pages) \n \n return render_to_response('main/notification.html', {'notifications':notifications},\n context_instance=RequestContext(request))\n","sub_path":"main/views/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"527506230","text":"from pandas import * \nimport pandasql\nimport numpy as np\nimport MySQLdb as mdb\nimport sys\nimport string\nimport pdb\nimport datetime\nfrom random import randint\nimport csv\n\nBoxscores_DATA = 'boxscores/ncaab_players.csv'\nPlayers_DATA = 'positions/ncaab_positions.csv'\n\ncsvfile = open('optimals/ncaab_optimal_lineups.csv', 'w')\nfieldnames = ['Date','G1','G2','G3','G4','F1','F2','F3','F4','U1','Total']\nwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\nwriter.writeheader()\n\ndef main():\n games = pandas.read_csv(Boxscores_DATA)\n players = pandas.read_csv(Players_DATA)\n\n games = games[['Year','Date','GameID','PlayerName','Fantasy_Points']]\n\n games = merge(games, players, on=['Year','PlayerName'], how='left')\n\n games_fields = ['Date',\n 'GameID',\n 'PlayerName',\n 'Position',\n 'Fantasy_Points']\n games = games[games_fields]\n games = games[games.Fantasy_Points > 0].sort('Fantasy_Points')\n\n guards = games[games.Position == 'G'].sort('Fantasy_Points')\n forwards = games[games.Position == 'F'].sort('Fantasy_Points')\n centers = games[games.Position =='C'].sort('Fantasy_Points')\n \n dates = games['Date'].unique()\n dates.sort()\n for i in range(0,len(dates)):\n #Contest will only be run on Single Days when there are 5 or more games available.\n date = dates[i]\n gameids = games[games.Date == date]['GameID'].unique()\n\n try:\n\n date_guards = guards[guards.Date == date].sort('Fantasy_Points', ascending=False).reset_index()\n date_forwards = forwards[forwards.Date == date].sort('Fantasy_Points', ascending=False).reset_index()\n date_centers = centers[centers.Date == date].sort('Fantasy_Points', ascending=False).reset_index()\n date_utilities = [date_guards['Fantasy_Points'][4], date_forwards['Fantasy_Points'][4], date_centers['Fantasy_Points'][0]]\n date_utilities.sort(reverse=True)\n \n g1_points = round(date_guards['Fantasy_Points'][0],1)\n g2_points = round(date_guards['Fantasy_Points'][1],1)\n g3_points = round(date_guards['Fantasy_Points'][2],1)\n g4_points = round(date_guards['Fantasy_Points'][2],1)\n f1_points = round(date_forwards['Fantasy_Points'][0],1)\n f2_points = round(date_forwards['Fantasy_Points'][1],1)\n f3_points = round(date_forwards['Fantasy_Points'][2],1)\n f4_points = round(date_forwards['Fantasy_Points'][0],1)\n u1_points = round(date_utilities[0],1)\n\n lineup_points = round(g1_points + g2_points+ g3_points + +g4_points + f1_points + f2_points + f3_points + f4_points + u1_points,1)\n\n data = {'Date': date,\n 'G1': g1_points,\n 'G2': g2_points,\n 'G3': g3_points,\n 'G4': g4_points,\n 'F1': f1_points,\n 'F2': f2_points,\n 'F3': f3_points,\n 'F4': f4_points,\n 'U1': u1_points,\n 'Total': lineup_points}\n\n if len(gameids) >= 5:\n writer.writerow(data)\n\n except Exception:\n continue\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ncaab_optimal.py","file_name":"ncaab_optimal.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440256429","text":"from rest_framework import serializers\nfrom rest_framework.utils.serializer_helpers import ReturnDict\nfrom django.db import transaction\nfrom django.urls import resolve\n\nfrom .models import Application, Question, Resume, Answer\n\n\nclass ApplicationSerializer(serializers.ModelSerializer):\n class Meta:\n model = Application\n fields = ('github_username', 'id', 'resumes', 'status', 'submission_date')\n read_only_fields = ('resumes', 'submission_date')\n\n status = serializers.CharField(source='get_status_display', read_only=True)\n\n def __init__(self, *args, **kwargs):\n super(ApplicationSerializer, self).__init__(*args, **kwargs)\n for question in Question.objects.all():\n self.fields[\"question_{}\".format(question.id)] = serializers.CharField(help_text=question.text, required=False)\n\n @property\n def data(self):\n data = super(serializers.ModelSerializer, self).data\n data[\"questions\"] = []\n if \"id\" in data:\n for answer in Answer.objects.filter(application=data[\"id\"]):\n data[\"questions\"].append([answer.question.text, answer.text])\n return ReturnDict(data, serializer=self)\n\n def create(self, data):\n with transaction.atomic():\n request = self.context['request']\n user = request.user\n current_url = resolve(request.path_info).url_name\n existing = Application.objects.filter(user=user)\n if existing.exists():\n existing.update(\n github_username=data['github_username']\n )\n application = existing.first()\n else:\n application = Application.objects.create(\n user=user,\n github_username=data['github_username']\n )\n if current_url == 'save':\n application.status = Application.SAVED\n else:\n application.status = Application.SUBMITTED\n for item in data:\n if item.startswith(\"question_\"):\n question_id = int(item.rsplit(\"_\", 1)[-1])\n question = Question.objects.get(id=question_id)\n Answer.objects.update_or_create(question=question, application=application, defaults={'text': data[item]})\n del self.fields[item]\n application.save()\n return application\n\n\nclass ResumeSerializer(serializers.ModelSerializer):\n\n file = serializers.FileField(write_only=True)\n\n class Meta:\n model = Resume\n fields = ('created_at', 'file', 'filename', 'id',)\n read_only_fields = ('created_at', 'id',)\n\n def create(self, validated_data):\n validated_data.pop('file')\n return Resume.objects.create(**validated_data)\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n class Meta:\n model = Question\n fields = ('id', 'type', 'max_length', 'prefix', 'text')\n read_only_fields = ('id',)\n","sub_path":"apps/application/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"620385160","text":"\"\"\"\nMultiple Layer ELM based on AE-ELM\n\"\"\"\nfrom ELM_AE import ELM_AE\nimport copy\nimport numpy as np\nfrom scipy.special import expit\n\nclass ML_ELM(object):\n\n def __init__(self, n_layer, n_hidden_list):\n self.n_layer = n_layer\n self.n_hidden_list = n_hidden_list\n\n def fit(self, X, y):\n # construct ML ELM\n self.X = copy.deepcopy(X)\n temp_X = copy.deepcopy(X)\n if y.shape.__len__() != 2:\n self.classes_ = np.unique(y)\n self.n_classes_ = self.classes_.__len__()\n y = self.__one2array(y, self.n_classes_)\n else:\n self.classes_ = np.arange(y.shape[1])\n self.n_classes_ = self.classes_.__len__()\n\n self.Betas = []\n for l in range(self.n_layer):\n ae = ELM_AE(self.n_hidden_list[l]).fit(temp_X)\n temp_B = ae.B.transpose()\n self.Betas.append(temp_B)\n temp_X = expit(np.dot(temp_X, temp_B))\n self.output_B = np.dot(np.linalg.pinv(temp_X), y)\n\n def __one2array(self, y, n_dim):\n y_expected = np.zeros((y.shape[0], n_dim))\n for i in range(y.shape[0]):\n y_expected[i][y[i]] = 1\n return y_expected\n\n def predict(self, X):\n temp_X = copy.deepcopy(X)\n for l in range(self.n_layer):\n temp_X = expit(np.dot(temp_X, self.Betas[l]))\n output = np.dot(temp_X, self.output_B)\n return output.argmax(axis=1)\n\n\n'''\n----------\nML-ELM test\n----------\n'''\n# import sklearn.datasets as dt\n# from sklearn.preprocessing import normalize\n# from sklearn.cross_validation import train_test_split\n# from sklearn.metrics import accuracy_score\n# from sklearn import preprocessing\n# iris = dt.load_iris()\n# X, y = iris.get('data'), iris.get('target') # start with 0\n# X = normalize(X)\n# X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.6)\n#\n# lb = preprocessing.LabelBinarizer()\n# Y_train = lb.fit_transform(y_train)\n# # Y_test = lb.fit_transform(y_test)\n#\n# elm = ML_ELM(3, (10, 20, 50))\n# elm.fit(X_train, Y_train)\n# labels_ts = elm.predict(X_test)\n# print accuracy_score(y_test, labels_ts)","sub_path":"Deep_Evo_NN/classes/ML_ELM.py","file_name":"ML_ELM.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"262406555","text":"\"\"\"\n Find the most frequently occurring item in an array.\n Example: The most frequently occurring item in [1, 3, 1, 3, 2, 1] is 1.\n\n If you're given an empty array, you should return null (in Java) or None (in Python).\n\n You can assume that there is always a single, unique value that appears most frequently unless the array is empty.\n For instance, you won't be given an array such as [1, 1, 2, 2].\n NOTE: We're going to use lists instead of arrays in Python for simplicity.\n\"\"\"\n\ndef most_frequent(given_list):\n count_dict = {}\n max_count = 0\n max_item = None\n\n for item in given_list:\n if item not in count_dict:\n count_dict[item] = 1\n else:\n count_dict[item] += 1\n\n if count_dict[item] > max_count:\n max_count = count_dict[item]\n max_item = item\n return max_item\n\nif __name__ == '__main__':\n list1 = [1, 3, 1, 3, 2, 1]\n print(most_frequent(list1)) # 1\n\n list2 = [3, 3, 1, 3, 2, 1]\n print(most_frequent(list2)) # 3\n\n list3 = []\n print(most_frequent(list3)) # None\n\n list4 = [0]\n print(most_frequent(list4)) # 0\n\n list5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1]\n print(most_frequent(list5)) # -1","sub_path":"python_practices/most_frequently_item_in_array.py","file_name":"most_frequently_item_in_array.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"481199935","text":"def mergeSort(list):\n\n if len(list) > 1:\n\n mid = len(list) // 2\n\n left = list[:mid]\n right = list[mid:]\n\n mergeSort(left)\n mergeSort(right)\n\n i = 0\n j = 0\n k = 0\n\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n list[k] = left[i]\n i += 1\n else:\n list[k] = right[j]\n j += 1\n k += 1\n while i < len(left):\n list[k] = left[i]\n i += 1\n k += 1\n\n while j < len(right):\n list[k] = right[j]\n j += 1\n k += 1\n\ndef bubbleSort(list):\n\n for i in range(len(list)-1):\n switch = False\n for j in range(len(list)-i-1):\n if list[j] < list[j+1]:\n temp = list[j]\n list[j] = list[j+1]\n list[j+1] = temp\n switch = True\n if swtch == False:\n break\n\ndef insertSort(list):\n\n for i in range(1, len(list)):\n key = list[i]\n j = i - 1\n while j >= 0 and key < list[j]:\n list[j+1] = list[j]\n j -= 1\n list[j+1] = key\n\ndef selectionSort(list):\n\n for i in range(len(list)-1):\n min = i\n for j in range(i+1, len(list)):\n if list[min] > list[j]:\n min = j\n temp = list[i]\n list[i] = list[min]\n list[min] = temp\n\n \n","sub_path":"31day.py","file_name":"31day.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"220526396","text":"#!coding:utf-8\nimport os\nfrom setuptools import setup\n\n# Utility function to read the README file.\n# Used for the long_description. It's nice, because now 1) we have a top level\n# README file and 2) it's easier to type in the README file than to put a raw\n# string in below ...\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"r_norm\",\n version = \"0.1.0.1\",\n author = \"Ruslan Khalikov\",\n author_email = \"khalikoff@gmail.com\",\n description = (\"Simple normalization of RTF files - removing unnesessary tags\"\n \"that can be produced by document processor program\"),\n license = \"Apache v2\",\n keywords = \"RTF\",\n url = \"http://packages.python.org/r_norm\",\n packages=['r_norm', 'tests'],\n long_description=read('README'),\n classifiers=[\n \"Development Status :: 4 - Beta\",\n 'Intended Audience :: Developers',\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\"\n ],\n install_requires=[\n \"pyparsing\"\n ]\n)\n","sub_path":"pypi_install_script/r_norm-0.1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"19804347","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings \nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nimport stripe\nfrom carton.cart import Cart\n\nstripe.api_key = settings.STRIPE_SECRET_KEY \n\n# Create your views here.\n\n@login_required\ndef checkout(request):\n\tfinalcart = Cart(request.session)\n\ttotal = finalcart.total\n\tpublishKey = settings.STRIPE_PUBLISHABLE_KEY\n\tcustomer_id = request.user.userstripe.stripe_id\n\tif request.method == 'POST':\n\t\ttoken = request.POST['stripeToken']\n\t\tcustomer = stripe.Customer.retrieve(customer_id)\n\t\tcustomer.sources.create(source=token)\n\t\t# Charge the user's card:\n\t\tcharge = stripe.Charge.create(\n \t\t\tamount=int(total*100)/2,\n \t\t\tcurrency=\"usd\",\n \t\t\tdescription=\"Example charge\",\n \t\t\tcustomer=customer,\n\t\t )\n\tcontext = {'publishKey': publishKey}\n\ttemplate = 'checkout.html'\n\treturn render(request,template,context)\n","sub_path":"src/checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"82793619","text":"from django.urls import path\n\nfrom sell_your_phone.phones.views import ListPhonesView, phone_details, comment_phone, like_phone, SellPhoneView, \\\n EditPhoneView, DeletePhoneView, SearchResultsView\n\nurlpatterns = [\n path('', ListPhonesView.as_view(), name='list phones'),\n path('details/', phone_details, name='phone details'),\n path('comment/', comment_phone, name='comment phone'),\n path('like/', like_phone, name='like phone'),\n path('sell/', SellPhoneView.as_view(), name='sell phone'),\n path('edit/', EditPhoneView.as_view(), name='edit phone'),\n path('delete/', DeletePhoneView.as_view(), name='delete phone'),\n path('search/', SearchResultsView.as_view(), name='search results'),\n]\n","sub_path":"sell_your_phone/phones/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"29858253","text":"import os\nimport json\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass MyHandler(FileSystemEventHandler):\n def on_modified(self, event):\n for filename in os.listdir(folder_to_track):\n src = folder_to_track + '/' + filename\n new_destination = folder_destination + '/' + filename\n os.rename(src, new_destination)\n \nfolder_to_track = '/home/akk/Music/newFolder'\nfolder_destination = '/home/akk/Music/myFolder'\nevent_handler = MyHandler()\nobserver = Observer()\nobserver.schedule(event_handler, path=folder_to_track, recursive=True)\nobserver.start()\n\ntry:\n while True:\n time.sleep(10)\nexcept KeyboardInterrupt:\n observer.stop()\n\nobserver.join()\n\n# https://www.youtube.com/watch?v=qbW6FRbaSl0\n","sub_path":"move_file.py","file_name":"move_file.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579230241","text":"'''\n训练与测试框架\n'''\nimport time\nimport numpy as np\nfrom pandas import Series, DataFrame\nimport pandas as pd\nfrom visdom import Visdom\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport os\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom multiprocessing import Queue, Process\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom cnn_model import *\nimport logging\nclass framework():\n # num_epochs 测试的epoch数量\n # learning_rate 学习率\n # batch_size batch大小\n # factor_num 因子数量\n # cols 输入矩阵的列数(日期数量)\n # 模型数量\n def __init__(self, num_epochs, learning_rate, batch_size, factor_num, cols, model_num, args):\n # num_epochs = 100\n # learning_rate = 0.01\n # batch_size = 1\n # factor_num = 17\n # cols = 5\n # model_num = ?\n # 设置参数\n self.num_epochs = num_epochs\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.factor_num = factor_num\n self.cols = cols\n self.model_num = model_num\n ### 设置模型\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # 多个模型的类\n self.model_arr = np.array([])\n for i in range(0, model_num):\n model = CNN(self.batch_size, self.factor_num, self.cols, args).to(device)\n self.model_arr = np.append(self.model_arr, model)\n # logging.basicConfig(filename='framework.log', level=logging.DEBUG)\n # 去除空的数据\n def delete_null(self, X, Y):\n tmp_Y = pd.DataFrame(Y)\n null_arr = tmp_Y.isnull()\n null_arr = null_arr.values\n delete_arr = np.array([])\n for i in range(0, null_arr.shape[0]):\n if null_arr[i] == True:\n delete_arr = np.append(delete_arr, i)\n delete_arr = np.trunc(delete_arr)\n # print(delete_arr)\n Y = np.delete(Y, delete_arr, axis=0)\n X = np.delete(X, delete_arr, axis=0)\n return X, Y\n\n def data_input(self, Train_X, Train_Y, Test_X, Test_Y, train_set_num, test_set_num, stock_num):\n # 对数据进行重构\n # Train_X = Train_X.values\n # Train_Y = Train_Y.values\n # Test_X = Test_X.values\n # Test_Y = Test_Y.values\n # Test_Y = np.array(Test_Y, dtype = float)\n # Train_Y = np.array(Train_Y, dtype = float)\n # Train_X = Train_X.reshape(stock_num * (train_set_num - self.cols), self.factor_num, self.cols)\n # Train_Y = Train_Y.reshape(-1, 1)\n # Test_Y = Test_Y.reshape(-1, 1)\n # Test_X = Test_X.reshape(stock_num * test_set_num, self.factor_num, self.cols)\n print('number X: %s %s'%(Train_X.shape, Test_X.shape)) \n print('number Y: %s %s'%(Train_Y.shape, Test_Y.shape))\n # 去除null\n Train_X, Train_Y = self.delete_null(Train_X, Train_Y)\n Test_X, Test_Y = self.delete_null(Test_X, Test_Y)\n\n # 重置为四维数组,conv只支持四维数组\n Train_X = Train_X.reshape(-1, 1, self.factor_num, self.cols)\n Train_Y = Train_Y.reshape(-1, 1)\n \n Test_Y = Test_Y.reshape(-1, 1)\n Test_X = Test_X.reshape(-1, 1, self.factor_num, self.cols)\n # print(Train_Y.dtype)\n # print('number X: %s %s'%(Train_X.shape, Test_X.shape)) \n # print('number Y: %s %s'%(Train_Y.shape, Test_Y.shape))\n # model_num 对于每个股票,可以训练多个模型,默认为1\n self.Train_X = Train_X\n self.Train_Y = Train_Y\n self.Test_X = Test_X\n self.Test_Y = Test_Y\n \n # todo: reshape\n # (batch_size, channels, height, width)\n pass\n def train(self, model_index, show_predict_y):\n # 用于在线显示loss\n viz = Visdom()\n # criterion = nn.MSELoss()\n criterion = nn.CrossEntropyLoss()\n # criterion = nn.BCELoss()\n optimizer = torch.optim.Adam(self.model_arr[model_index].parameters(), lr=self.learning_rate)\n # optimizer = torch.optim.RMSprop(model.parameters(),lr=learning_rate,alpha=0.9)\n # optimizer = torch.optim.RMSprop(self.model_arr[model_index].parameters(),lr=self.learning_rate)\n # 动态调整学习率\n # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, self.num_epochs, gamma=0.1)\n # Train_X_arr = np.random.rand(500, 1, factor_num, cols)\n # Train_Y_arr = np.random.rand(500, 1, 1)\n Train_X_arr = torch.from_numpy(self.Train_X).float()\n Train_Y_arr = torch.from_numpy(self.Train_Y).float()\n # Train_Y_arr = Variable(torch.LongTensor(self.Train_Y))\n '''\n 注意:如果没有使用cuda将其注释\n '''\n Train_X_arr = Train_X_arr.cuda()\n Train_Y_arr = Train_Y_arr.cuda()\n train_data = TensorDataset(Train_X_arr, Train_Y_arr)\n train_data = torch.utils.data.DataLoader(dataset = train_data, batch_size = self.batch_size, shuffle=True, pin_memory = False)\n\n print('-----------begin to train----------')\n # train_loss = np.array([])\n # 用于显示loss\n total_step = len(train_data)\n # step_arr = np.array([])\n # # 用于visdom显示\n # for i in range(self.num_epochs):\n # step_arr = np.append(step_arr, i)\n win_name = 'loss_model index:' + str(model_index)\n # 显示loss\n viz.line([[0.]], [0], win = win_name, opts=dict(title= win_name, legend=['loss']))\n for epoch in range(self.num_epochs):\n epoch_train_loss = []\n for i, (x, y) in enumerate(train_data):\n #forward\n outputs = self.model_arr[model_index](x)\n # BP\n y = y.squeeze(1)\n outputs = outputs.squeeze(1)\n # print(outputs, y)\n if show_predict_y:\n print(y)\n # outputs = outputs.squeeze() \n # # y.shape\n # exit()\n # outputs = torch.t(outputs)\n # print(y)\n loss = criterion(outputs, y.long())\n epoch_train_loss.append(loss.item())\n # print(outputs)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n # 查看每一epoch的权重变化和loss\n epoch_train_loss = np.array(epoch_train_loss)\n current_loss = np.mean(epoch_train_loss)\n # print(type(current_loss), current_loss)\n # train_loss.append(current_loss)\n viz.line([[current_loss]], [epoch], win = win_name, update='append')\n # params = list(model.named_parameters())\n # print(model.state_dict().keys())\n # scheduler.step()\n # print('learning rate: %s'%(optimizer.param_groups[0]['lr']))\n if ((epoch+1) % 10 == 0):\n print ('Epoch [{}/{}], Loss: {:.8f}' \n .format(epoch+1, self.num_epochs,loss.item()))\n\n print('Loss: {:.8f}'.format(loss.item()))\n # 图像显示与保存\n # plt.subplot(1,1,1)\n # plt.plot(train_loss[50:])\n # plt.show()\n self.model_arr[model_index].eval()\n \n def test_thread(self, test_in_train, model_index, test_rate):\n X = np.array([])\n Y = np.array([])\n if(test_in_train):\n print('######## test in train set ########')\n X = self.Train_X\n Y = self.Train_Y\n else:\n print('######## test ########')\n X = self.Test_X\n Y = self.Test_Y\n if test_rate >= 1.0:\n test_rate = int(1)\n if test_rate < 0.001:\n print('too less data!!!')\n exit()\n hr = 0.0\n for iter in range(0, int(X.shape[0] * test_rate)):\n x = X[iter]\n x = x.reshape(1, 1, self.factor_num, self.cols)\n x = (torch.from_numpy(x)).float()\n x = x.cuda()\n y_predict = self.model_arr[model_index](x)\n y_predict = y_predict.cpu().detach()\n y_predict = [t.numpy() for t in y_predict]\n y_predict = np.array(y_predict[0])\n if y_predict[0] < y_predict[1] and Y[iter] == 1.0:\n hr += 1\n hr = hr/X.shape[0]\n if test_in_train:\n print('test in train set: hr:%s'%(hr))\n else:\n print('test in test set hr:%s'%(hr))\n def test(self, model_index, test_rate):\n # p_train = Process(target = self.test_thread, args=([True]))\n # p_test = Process(target = self.test_thread, args=([False]))\n # p_train.start()\n # p_test.start()\n # p_train.join()\n # p_test.join()\n self.test_thread(True, model_index, test_rate)\n self.test_thread(False, model_index, test_rate)\n def save(self, model_index, name):\n torch.save(self.model_arr[model_index].state_dict(), name + '.pkl')\n def load(self, model_index, name):\n self.model_arr[model_index].load_state_dict(torch.load(name + '.pkl'))","sub_path":"src/V2/framework.py","file_name":"framework.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"566037053","text":"import numpy as np\nimport ast\n\n\ndef likes(df):\n df['top_N_photos'] = [ast.literal_eval(x) for x in df['top_N_photos']]\n df['list_likes'] = [x['likes'] for x in df['top_N_photos']]\n df['mean_likes'] = [np.mean(x) if len(\n x) > 0 else 0 for x in df['list_likes']]\n df['median_likes'] = [np.median(x) if len(\n x) > 0 else 0 for x in df['list_likes']]\n df['max_likes'] = [np.max(x) if len(\n x) > 0 else 0 for x in df['list_likes']]\n df['min_likes'] = [np.min(x) if len(\n x) > 0 else 0 for x in df['list_likes']]\n return df\n","sub_path":"scripts/likes.py","file_name":"likes.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"300268379","text":"import discord\nfrom discord.ext import commands\nfrom yonosumi_utils import Anonymous as tokumei\n\n\nclass Cog(commands.Cog):\n def __init__(self, bot):\n self.bot=bot\n self.tokumei = tokumei()\n\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n\n if not type(message.channel) == discord.DMChannel or message.author.bot:\n return\n\n dialog = await self.tokumei.setup_anonymous(\n channel=message.channel,\n message=message,\n )\n\n reaction = await self.tokumei.wait_answer(\n channel=message.channel,\n message=dialog,\n bot=self.bot\n )\n\n channel_id = await self.tokumei.do_task(\n message=message,\n reaction=reaction\n )\n\n check = await self.tokumei.send_anonymous(\n channel_id=channel_id,\n bot=self.bot,\n message=message\n )\n if check is not None:\n return await message.channel.send('メッセージを匿名で送信しました!')\n await message.channel.send('操作を中断しました!')\n\n\n\ndef setup(bot):\n bot.add_cog(Cog(bot))","sub_path":"module/anonymous.py","file_name":"anonymous.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"386305519","text":"import tensorflow as tf\nimport numpy as np\nfrom layers import *\nfrom regularizers import *\nfrom hyperparameters import *\nfrom model_helpers import *\nfrom data_loader import load_data\nimport time\n\nconfig = tf.ConfigProto()\n# Turn off this option if no gpu and remove device in encoder and decoder\nconfig.gpu_options.allow_growth = True\ntf.reset_default_graph()\n\nd_train_x, d_train_y1, d_train_y2, d_test_x, d_test_y1, d_test_y2 = load_data()\n\n##################################################################\n# Define model \n##################################################################\n\ndef encoder(x, z_dim, reuse=False):\n with tf.device('/gpu:0'):\n with tf.variable_scope('encoder') as en:\n if reuse:\n en.reuse_variables()\n \n conv1 = conv2d_lrelu(x, 32, 4, 2)\n pool1 = max_pool2d(conv1, [2, 2])\n# drop1 = dropout(pool1)\n \n conv2 = conv2d_lrelu(pool1, 64, 4, 2)\n pool2 = max_pool2d(conv2, [2, 2])\n# drop2 = dropout(pool2)\n\n conv3 = conv2d_lrelu(pool2, 128, 4, 1)\n pool3 = max_pool2d(conv3, [2,2])\n \n conv4 = conv2d_lrelu(pool3, 256, 4, 1)\n \n print(conv4)\n flat_z = tf.reshape(conv4, [-1, np.prod(conv4.get_shape().as_list()[1:])])\n \n fc1 = tf.contrib.layers.fully_connected(flat_z, 256, activation_fn=tf.nn.relu)\n \n return tf.contrib.layers.fully_connected(fc1, z_dim * 2, activation_fn=tf.identity)\n \ndef decoder(z, reuse=False):\n with tf.device('/gpu:0'):\n with tf.variable_scope('decoder') as vs:\n if reuse:\n vs.reuse_variables()\n \n fc2 = tf.contrib.layers.fully_connected(z, 512, activation_fn=lrelu)\n\n fc3 = fc_relu(fc2, 2*2*256)\n fc3 = tf.reshape(fc3, tf.stack([tf.shape(fc3)[0], 2, 2, 256]))\n \n deconv1 = conv2d_t_relu(fc3, 256, 4, 2)\n deconv2 = conv2d_t_relu(deconv1,128, 4, 2)\n deconv3 = conv2d_t_relu(deconv2, 64, 4, 2)\n deconv4 = conv2d_t_relu(deconv3, 32, 4, 2)\n deconv5 = tf.contrib.layers.convolution2d_transpose(deconv4, 1, 4, 2,\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n activation_fn=tf.identity)\n return tf.nn.sigmoid(deconv5)\n \n\n##################################################################\n# Build the computation graph for training\n##################################################################\n \ntrain_x = tf.placeholder(tf.float32, shape=[None, 64, 64, 1])\ntrain_y1 = tf.placeholder(tf.float32, shape=[None])\ntrain_y2 = tf.placeholder(tf.float32, shape=[None])\n\ntrain_z = push_forward(encoder, train_x)\ntrain_xr = decoder(train_z)\n\n# Build the computation graph for generating samples# Build \ngen_z = tf.placeholder(tf.float32, shape=[None, z_dim])\ngen_x = decoder(gen_z, reuse=True)\n\npretrained_mean, pretrained_var = tf.split(encoder(train_x, z_dim, reuse=True), num_or_size_splits=2, axis=1)\n\n# Compare the generated z with true samples from a standard Gaussian, and compute their MMD distance\ntrue_samples = tf.random_normal([batch_size, z_dim],stddev=Sigma)\nloss_mmd = MMD(true_samples, train_z, kernel=K1, bandwidth=bandwidth1)\n\nloss_nll = tf.reduce_mean(tf.square(train_xr - train_x))\nhsic_signal = tf.placeholder(tf.bool) # placeholder for a HISC toggle\nhsic_trigger = tf.cond(tf.equal(hsic_signal, tf.constant(True)), lambda: tf.constant(1, tf.float32), lambda: tf.constant(0, tf.float32))\n\n# apply lambda2 on the dependent feature axis and discriminate all other axis with lambda3\nfirst_axis_hsic = HSIC(gather_cols(train_z, [0]), train_y1, normalized=True)\nsecond_axis_hsic = HSIC(gather_cols(train_z, [1]), train_y2, normalized=True)\n\n# for HSIC with 1 side information\n# other_axis_hsic = HSIC(gather_cols(train_z, list(range(1,z_dim))), train_y1, normalized=True) \nother_axis_hsic = HSIC(gather_cols(train_z, list(range(2,z_dim))), train_y1, normalized=True) + HSIC(gather_cols(train_z, list(range(2,z_dim))), train_y2, normalized=True)\n\nloss_hsic = Lambda2 * (first_axis_hsic + second_axis_hsic) - Lambda3 * other_axis_hsic \nloss_hsic = hsic_trigger * loss_hsic\n\nloss = loss_nll + Lambda1 * loss_mmd - loss_hsic\ntrainer = tf.train.AdamOptimizer(LEARN_RATE).minimize(loss)\n\n\n##################################################################\n# Start training session\n##################################################################\nsess = tf.Session(config=config)\nsess.run(tf.global_variables_initializer())\nmmd_list = []\no_loss_list = []\nrec_loss_list = []\nfirst_hisc_list = []\nother_hisc_list = []\nsteps_list = []\n\n# TODO implement tf saving model\n# saver = tf.train.Saver() \n\ntf.set_random_seed(1109)\n\n# using median heuristic bandwidth and HSIC\nstart_time = time.time()\nindex_in_epoch = 0\nfor i in range(steps):\n \n batch_x, batch_y1, batch_y2, index_in_epoch = next_batch(d_train_x, d_train_y1, d_train_y2, index_in_epoch, batch_size)\n if index_in_epoch == 0:\n d_train_x, d_train_y1, d_train_y2 = shuffle_data(d_train_x, d_train_y1, d_train_y2)\n batch_x, batch_y1, batch_y2, index_in_epoch = next_batch(d_train_x, d_train_y1, d_train_y2, index_in_epoch, batch_size)\n \n batch_x = batch_x.reshape(-1, 64, 64, 1)\n use_hsic = False\n if np.random.random() <= prob_to_hsic:\n use_hsic = True\n \n _, o_loss, nll, mmd, f_hsic, s_hsic, o_hsic, reconstr = sess.run([trainer, loss, loss_nll, loss_mmd, first_axis_hsic, second_axis_hsic, other_axis_hsic, train_xr], feed_dict={\n train_x: batch_x, train_y1: batch_y1, train_y2: batch_y2, hsic_signal: use_hsic})\n\n if i % 1000 == 0:\n print(\"Using hsic:\", use_hsic)\n print(\"epoch: {}, Overall loss is {}, recon loss is {}, mmd loss is {}, f_hsic is {}, s_hsic is {}, other hsic is {}\".format(\n i, o_loss, nll, mmd, f_hsic, s_hsic, o_hsic))\n\n elapsed_time = time.time() - start_time\n print(\"time elapsed: {0:.2f}s\".format(elapsed_time))\n start_time = time.time()\n # storing data for plot \n mmd_list += [mmd]\n o_loss_list += [o_loss]\n rec_loss_list += [nll]\n steps_list += [i]\n# first_hisc_list += [f_hsic]\n# other_hisc_list += [o_hsic]\n \n if i % 5000 == 0:\n # feed in test image to get generated mmd loss\n test_x, test_y1, test_y2 = d_test_x[:batch_size], d_test_y1[:batch_size], d_test_y2[:batch_size]\n test_x = test_x.reshape(-1, 64, 64, 1)\n samples, gen_mmd, my_z= sess.run([gen_x, loss_mmd, pretrained_mean], feed_dict={gen_z: np.random.normal(size=(49, z_dim)), train_x: test_x})\n plt.imshow(convert_to_display(samples), cmap='Greys_r', interpolation='nearest')\n plt.grid()\n plt.savefig('{}_steps.png'.format(i))\n print(\"generated mmd loss: {}, my_z: {}\".format(gen_mmd, my_z[0]))\n\n\n##################################################################\n# Generated data for Higgins disentanglement metrics\n##################################################################\n\nnp.random.seed(200)\n# generate sample images for height at first axis\nall_y = []\nall_x1 = []\nall_x2 = []\ny = 0\nfor i in range(500):\n dep_axis = np.random.normal()\n\n rd1 = np.random.normal(size=(1, z_dim-1))[0]\n rd2 = np.random.normal(size=(1, z_dim-1))[0]\n v1 = np.concatenate((np.array([dep_axis]), rd1))\n v2 = np.concatenate((np.array([dep_axis]), rd2))\n v_samples = sess.run(gen_x, feed_dict={gen_z: [v1, v2]})\n sim1 = v_samples[0].reshape((64, 64))\n sim2 = v_samples[1].reshape((64, 64))\n all_x1.append(sim1)\n all_y.append(y)\n all_x2.append(sim2)\n\nprint('Finihsed generating for the first axis.')\n\n# generate sample images for position_x at second axis\ny = 1\nfor i in range(500):\n# if i % 100 == 0:\n# print(i)\n dep_axis = np.random.normal()\n\n rd1 = np.random.normal(size=(1, z_dim-1))[0]\n rd2 = np.random.normal(size=(1, z_dim-1))[0]\n v1 = np.concatenate((np.array([rd1[0]]), np.array([dep_axis]), rd1[1:]))\n v2 = np.concatenate((np.array([rd1[0]]), np.array([dep_axis]), rd2[1:]))\n v_samples = sess.run(gen_x, feed_dict={gen_z: [v1, v2]})\n sim1 = v_samples[0].reshape((64, 64))\n sim2 = v_samples[1].reshape((64, 64))\n all_x1.append(sim1)\n all_x2.append(sim2)\n all_y.append(y)\n\nprint('Finihsed generating for the second axis.')\n\nall_x1 = np.array(all_x1)\nall_x2 = np.array(all_x2)\nall_y = np.array(all_y)\n\nprint(all_x1.shape, all_x2.shape, all_y.shape)\nnp.savez(\"hisc_wae_{}_sample_metrics\".format(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN), all_x1=all_x1, all_x2=all_x2, all_y=all_y)\n\nx1_z = sess.run(pretrained_mean, feed_dict={train_x: all_x1.reshape(-1, 64, 64, 1)})\nx2_z = sess.run(pretrained_mean, feed_dict={train_x: all_x2.reshape(-1, 64, 64, 1)})\ndiff = x2_z - x1_z\n\nnp.savez(\"hisc_wae_{}_diff_z\".format(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN), diff_z=diff, all_y=all_y)\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":8892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"117927088","text":"import math\n\nclass Solution:\n \n\tdef numTilePossibilities(self, tiles: str) -> int:\n\n\t\tdef getNumberOfCombinations(l: list) -> int:\n\t\t\t# print(l)\n\t\t\tn = math.factorial(sum(l))\n\t\t\td = 1\n\t\t\tfor li in l:\n\t\t\t\td*=math.factorial(li)\n\t\t\t# print(n/d)\n\t\t\treturn int(n/d)\n\n\t\tdef traverse(l: list):\n\t\n\t\t\tnonlocal pattern_set\n\t\t\tif str(l) in pattern_set:\n\t\t\t\treturn\n\t\t\tpattern_set.add(str(l))\n\n\t\t\tnonlocal num\n\t\t\tnum += getNumberOfCombinations(l)\n\n\t\t\tfor i in range(len(l)):\n\t\t\t\tif l[i]==0:\n\t\t\t\t\tcontinue\n\t\t\t\tl_copy = l.copy()\n\t\t\t\tl_copy[i]-=1\n\t\t\t\ttraverse(l_copy)\n\n\n\t\ttiles_set = set()\n\t\tfor t in tiles:\n\t\t\ttiles_set.add(t)\n\n\t\ttiles_dic = dict(zip(tiles_set, [0 for i in range(len(tiles_set))]))\n\t\tfor t in tiles:\n\t\t\ttiles_dic[t]+=1\n\n\t\tappearTimesList = [tiles_dic[t] for t in tiles_set]\n\n\t\tpattern_set = set()\n\n\t\tnum=0\n\n\t\ttraverse(appearTimesList)\n\n\t\treturn (num-1)\n\n\nif __name__ == '__main__':\n\tSolution().getNumberOfCombinations('AAABBC')\n\n\n\n# Runtime: 40 ms, faster than 98.25% of Python3 online submissions for Letter Tile Possibilities.\n# Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Letter Tile Possibilities.","sub_path":"ALGO/1079_Letter_Tile_Possibilities.py","file_name":"1079_Letter_Tile_Possibilities.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139936544","text":"def sign(string):\n #b'\\x0f\\x00\\x1c\\x00\\x02\\x71\\x01\\x07\\xff\\xf6\\x48\\x01\\x42\\x00\\x00\\x00'\n message_length_check = 0\n n_row = 4\n final_message = b''\n for i in range(0, len(string)):\n message = string[i].encode('utf-8')\n message_length = bytes([len(message)])\n message_length_check += len(message)\n final_message += message_length + message\n n_row -= 1\n #print(message_length_check + b'\\x00\\x1c\\x00\\x02\\x71\\x01\\x07\\xff\\xf6\\x48' + message_length + message + b'\\x00\\x00\\x00')\n return bytes([message_length_check + 14]) + b'\\x00\\x1c\\xff\\xff\\xf9\\x01\\x57\\xff\\xff\\xc7' + final_message + b'\\x00' * n_row\ndef message(string):\n message = string.encode('utf-8')\n message_length = bytes([len(message)])\n message_length_check = bytes([len(message) + 3])\n return message_length_check + b'\\x00\\x02' + message_length + message\ntoreplacedst = [b'\\x20\\x00\\xd4', b'\\x0a\\x5f\\x61\\x6c\\x73\\x61\\x63\\x63\\x68\\x69\\x5f', message(\"AB\"), message(\"login\"), sign([\"A\"])] #Client\nreplacedst = [b'\\x21\\x00\\xd4', b'\\x0b' + '_alsacchi__'.encode(), message(\"A\"*240), message(\"/login password1\"), sign([\"CIAO\", \"LORENZO\"])] #Client\ntoreplacesrc = [b''] #Server\nreplacesrc = [b''] #Server\ndef editpak(data, who):\n if(who == 'client'):\n for i in range(0, len(toreplacedst)):\n data = data.replace(toreplacedst[i], replacedst[i])\n #data = data\n elif(who == 'server'):\n for i in range(0, len(toreplacesrc)):\n data = data.replace(toreplacesrc[i], replacesrc[i])\n\n \n return data\n","sub_path":"Python/ProxySocket/editor_socket.py","file_name":"editor_socket.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"514957646","text":"from time import gmtime\n\nimport logging\nimport os\n\nfrom lib.py.fpg.constants import Environment\n\n\nPACKAGE_NAME = 'asp'\nLOGGING_FORMAT = (\n '[%(asctime)s]{optional_header}[%(levelname)s][%(filename)s]'\n '[%(threadName)s][%(funcName)s][%(lineno)d]: %(message)s'\n)\n\n\ndef _setup_logger(\n logger: logging.Logger,\n env: Environment,\n optional_header: str,\n file_name=None,\n) -> None:\n if env == Environment.PROD:\n logger.setLevel(logging.INFO)\n else:\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n LOGGING_FORMAT.format(optional_header=optional_header)\n )\n formatter.converter = gmtime # type: ignore\n\n streamhandler = logging.StreamHandler()\n if env == Environment.PROD:\n streamhandler.setLevel(logging.INFO)\n else:\n streamhandler.setLevel(logging.DEBUG)\n streamhandler.setFormatter(formatter)\n logger.addHandler(streamhandler)\n\n if file_name:\n os.makedirs('logs/', exist_ok=True)\n filehandler = logging.FileHandler(\n f'logs/{file_name}.log')\n filehandler.setLevel(logging.INFO)\n filehandler.setFormatter(formatter)\n logger.addHandler(filehandler)\n\n\ndef setup_service_logger(\n service_name: str,\n env: Environment,\n optional_header: str = '',\n to_file: bool = False\n) -> logging.Logger:\n \"\"\"Set up and return a logger for this service.\"\"\"\n logger = logging.getLogger(PACKAGE_NAME)\n if to_file:\n file_name = service_name\n else:\n None\n _setup_logger(logger, env, optional_header, file_name)\n return logger\n\n\ndef get_module_logger(module_name: str) -> logging.Logger:\n \"\"\"Return a logger for the given module_name.\"\"\"\n logger = logging.getLogger(f'{PACKAGE_NAME}.{module_name}')\n return logger\n","sub_path":"lib/py/fpg/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"369550421","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass Question(models.Model):\n text = models.TextField()\n opt1 = models.TextField()\n opt2 = models.TextField()\n opt3 = models.TextField()\n opt4 = models.TextField()\n opt5 = models.TextField()\n correctOpt = models.IntegerField()\n user = models.ForeignKey(User)\n added = models.DateField()\n numLikes = models.IntegerField()\n numUnLikes = models.IntegerField()\n\n\nclass Answer(models.Model):\n user = models.ForeignKey(User)\n question = models.ForeignKey(Question)\n answer = models.IntegerField()\n numAttempts = models.IntegerField()\n def __str__(self):\n return \"[\" + self.user.username + \",\" + question.id + \"]\" \n\nclass Tag(models.Model):\n name = models.CharField(max_length=64, unique=True)\n questions = models.ManyToManyField(Question)\n def __str__(self):\n return self.name\n","sub_path":"quiz/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"355085174","text":"# Copyright 2013 Rackspace Hosting\n#\n# Author: Tim Simmons \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom sqlalchemy import MetaData, Table, Column, Unicode\n\nfrom designate.openstack.common import log as logging\n\n\nLOG = logging.getLogger(__name__)\nmeta = MetaData()\n\n\ndef upgrade(migrate_engine):\n meta.bind = migrate_engine\n\n domains_table = Table('domains', meta, autoload=True)\n records_table = Table('records', meta, autoload=True)\n\n # Add in description columns in domain/record databases\n domain_description = Column('description', Unicode(160),\n nullable=True)\n domain_description.create(domains_table, populate_default=True)\n\n record_description = Column('description', Unicode(160),\n nullable=True)\n record_description.create(records_table, populate_default=True)\n\n\ndef downgrade(migrate_engine):\n meta.bind = migrate_engine\n\n domains_table = Table('domains', meta, autoload=True)\n domains_table.c.description.drop()\n\n record_table = Table('records', meta, autoload=True)\n record_table.c.description.drop()\n","sub_path":"designate/storage/impl_sqlalchemy/migrate_repo/versions/020_add_description_domains_records.py","file_name":"020_add_description_domains_records.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"325269869","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nExtract the full list of emoji and names from the Unicode emoji data files\nhttps://unicode.org/Public/emoji/{v}/emoji-test.txt\nand apply as much formatting as possible so the codes can be dropped into the\nemoji registry file.\n\"\"\"\n\nimport requests\n\n\ndef get_source_from_url(version: float) -> list:\n \"\"\"Get splitlines of emojis list from unicode.org\"\"\"\n\n url = f\"https://unicode.org/Public/emoji/{version}/emoji-test.txt\"\n source = requests.get(url)\n return source.text.splitlines()\n\n\ndef extract_emojis(emojis_lines: list) -> dict:\n \"\"\"Extract emojis line by line to dict\"\"\"\n\n output = {}\n for line in emojis_lines:\n if not line == \"\" and not line.startswith(\"#\"):\n emoji_status = line.split(\";\")[1].strip().split(\" \")[0]\n codes = line.split(\";\")[0].strip().split(\" \")\n if emoji_status == \"fully-qualified\":\n separated_name = line.split(\" #\")[-1].strip().split(\" \")[2:]\n emoji_name = (\n \"_\".join(separated_name)\n .removeprefix(\"flag:_\")\n .replace(\":\", \"\")\n .replace(\",\", \"\")\n .replace(\"\\u201c\", \"\")\n .replace(\"\\u201d\", \"\")\n .replace(\"\\u229b\", \"\")\n .strip()\n .replace(\" \", \"_\")\n )\n\n emoji_code = \"\".join(\n [\n \"\\\\U0000\" + code if len(code) == 4 else \"\\\\U000\" + code\n for code in codes\n ]\n )\n output[emoji_name] = emoji_code\n return output\n\n\nif __name__ == \"__main__\":\n emoji_source = get_source_from_url(14.0)\n emojis = extract_emojis(emoji_source)\n\n for name, code in emojis.items():\n print(f\" u':{name}:': u'{code}'\", end=\",\\n\")\n print(\"\\nTotal count of emojis: \", len(emojis))\n","sub_path":"utils/get_codes_from_unicode_emoji_data_files.py","file_name":"get_codes_from_unicode_emoji_data_files.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"484648331","text":"import torch\nimport random\nimport numpy as np\nfrom torchext import jagged_argmax, jagged2padded, nn_distance, approx_match, match_cost, jagged_log_softmax, jagged_topk, replace_rows, jagged_append\nfrom torch.optim import SGD\nfrom torch.nn import Parameter\nfrom torch import nn\n\nif torch.cuda.is_available():\n DEVICE = torch.device('cuda:0')\nelse:\n DEVICE = torch.device('cpu')\n\ndef test_jagged_argmax():\n v = torch.rand(10, dtype=torch.float64)\n print(v)\n psum = torch.LongTensor([2, 5, 10])\n out = jagged_argmax(v, psum)\n print(out)\n\n v = v.to(DEVICE)\n psum = psum.to(DEVICE)\n out = jagged_argmax(v, psum)\n print(out)\n\ndef test_jagged_append():\n class TestCls(nn.Module):\n def __init__(self):\n super(TestCls, self).__init__()\n self.v = Parameter(torch.randn(10, ))\n print(self.v)\n self.suffix = Parameter(torch.randn(5, 2))\n print(self.suffix)\n psum = torch.LongTensor([2, 5, 6, 6, 10])\n tt = TestCls()\n mask = None\n for dev in ['cpu', 'gpu']:\n print(dev)\n if dev == 'gpu':\n tt = tt.cuda()\n psum = psum.cuda()\n v = tt.v\n suffix = tt.suffix\n v.grad = None\n suffix.grad = None\n\n out = jagged_append(v, psum, suffix)\n print(out)\n\n ## test grad\n if mask is None:\n mask = torch.randn(out.shape)\n print('mask')\n print(mask)\n if dev == 'gpu':\n mask = mask.cuda()\n t = torch.sum(mask * out)\n t.backward()\n\n print(v.grad)\n print(suffix.grad)\n\ndef test_jagged2padded():\n v = torch.rand(10, dtype=torch.float64)\n print(v)\n psum = torch.LongTensor([2, 5, 6, 6, 10])\n out = jagged2padded(v, psum, np.pi)\n print(out)\n\n v = v.to(DEVICE)\n psum = psum.to(DEVICE)\n out = jagged2padded(v, psum, np.pi)\n print(out)\n\ndef test_jagged_topk():\n v = torch.rand(10, dtype=torch.float64)\n print(v)\n psum = torch.LongTensor([2, 5, 6, 6, 10])\n v = v.to(DEVICE)\n psum = psum.to(DEVICE) \n tv, tk = jagged_topk(v, psum, 2) \n print('largest:')\n print(tv)\n print(tk)\n tv, tk = jagged_topk(v, psum, 2, largest=False)\n print('smallest:')\n print(tv)\n print(tk)\n\ndef test_jagged_log_softmax():\n v = torch.rand(10, dtype=torch.float32)\n v.requires_grad = True\n print('v', v)\n psum = torch.LongTensor([2, 5, 10])\n out = jagged_log_softmax(v, psum)\n loss = torch.sum(out)\n loss.backward()\n print('out', torch.exp(out))\n print('grad', v.grad)\n\n print('====testing gpu====') \n v = torch.tensor(v.data.numpy(), dtype=torch.float32).cuda()\n v.requires_grad = True\n psum = psum.cuda()\n out = jagged_log_softmax(v, psum)\n loss = torch.sum(out)\n loss.backward()\n print('out', torch.exp(out))\n print('grad', v.grad)\n\ndef test_nn_dist():\n np.random.seed(100)\n xyz1=np.random.randn(32,16,3).astype('float32')\n xyz2=np.random.randn(32,10,3).astype('float32')\n\n inp1 = torch.tensor(xyz1).to(DEVICE)\n inp1.requires_grad = True\n inp2 = torch.tensor(xyz2).to(DEVICE)\n\n optimizer = SGD([inp1], lr=0.05)\n for i in range(100):\n optimizer.zero_grad()\n reta,retb,retc,retd = nn_distance(inp1,inp2)\n loss=torch.sum(reta)+torch.sum(retc)\n loss.backward()\n optimizer.step()\n print(i,loss.item())\n\n\ndef test_emd():\n random.seed(1)\n np.random.seed(1)\n\n tpoints=np.hstack([np.linspace(-1,1,400)[:,None],(random.random()*2*np.linspace(1,0,400)**2)[:,None],np.zeros((400,1))])[None,:,:]\n pt_in = torch.tensor(tpoints.astype('float32')).to(DEVICE)\n npoint=100\n mypoints=torch.tensor(np.random.randn(1,npoint,3).astype('float32')).to(DEVICE)\n mypoints.requires_grad = True\n optimizer = SGD([mypoints], lr=1e-4)\n\n for i in range(1000):\n optimizer.zero_grad()\n match=approx_match(pt_in,mypoints)\n loss=torch.sum(match_cost(pt_in,mypoints,match))\n print(i, loss.item())\n\n loss.backward()\n optimizer.step()\n\n\ndef test_replace_rows():\n a = torch.randn(5, 2)\n b = torch.randn(3, 2)\n\n a.requires_grad = True\n b.requires_grad = True\n indices = torch.LongTensor([0, 2, 4])\n print('---a---')\n print(a)\n print('---b---')\n print(b)\n print('---c---')\n c = replace_rows(a, indices, b)\n print(c)\n\n t = torch.sum(c[0])\n t.backward()\n print('---ga---')\n print(a.grad)\n print('---gb---')\n print(b.grad)\n print('---gc---')\n print(c.grad)\n\n\n\nif __name__ == '__main__':\n # test_jagged_argmax()\n # test_nn_dist()\n # test_emd()\n # test_jagged_log_softmax()\n # test_jagged_topk()\n # test_replace_rows()\n test_jagged_append()\n","sub_path":"deps/torchext/torchext/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"494764738","text":"\nMAX_RETRIES = 15\nDEFAULT_RETRY_INTERVAL = 5\n\nCAPTCHA = 'The website has detected requests which look like automated'\nSLEEP_INTERVALS = [3, 2, 3.2, 4, 3, 6, 4.3, 3, 3.8, 3.8, 3.4, 4.7, 4.3, 3, 5, 3, 3.2, 3, 2.2, 3]\n\nROUTE_FIELDS = [\n 'frequency',\n 'departure',\n 'from',\n 'arrival',\n 'to',\n 'flight',\n 'other',\n 'duration'\n]\n","sub_path":"flightsio/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"176694097","text":"# NeuralNetwork.py provide stuff related to neural network.\n# Author: magneticchen\n# note:\n# For normal variable use lower case\n# For matrix variable use all upper case\n# The meaning of 'error' is equivalent to 'cost'\n# Operator 'X' for matrix dot multiplication, '*' for matrix elements multiplication. In annotation.\nimport numpy as np\n# Matrix\nimport node.NeuralNetwork.Function as f\n# Activation function etc.\nimport node.IO as IO\n# File related function\n\nclass DFF(object):\n# Classical NeuralNetwork object\n def __init__(self, LayersCount = 1, LayerNeuronsCount = [1], Name = 'Unamed_Neural_Network'):\n self.LayersCount = LayersCount\n self.LayerNeuronsCount = LayerNeuronsCount\n self.Weight = []\n self.Bias = []\n self.Name = Name\n # Initialize some general variable for NN\n for x in range(0, self.LayersCount-1):\n self.Weight.append(np.random.randn(self.LayerNeuronsCount[x], self.LayerNeuronsCount[x+1]))\n self.Bias.append(np.random.randn(1, self.LayerNeuronsCount[x+1]))\n # Initlalize NN structure\n\n def __str__(self):\n s = 'An '+self.Name+'@NeuralNetwork object\\nDetail:\\n\\n'\n for layer in range(0, self.LayersCount-1):\n s = s+'*** layer'+str(layer)+' ('+str(self.LayerNeuronsCount[layer])+' Neurons) ***\\n'\n s = s+'>>>layer'+str(layer)+' to layer'+str(layer+1)+' Weight\\n'\n s = s+str(self.Weight[layer])+'\\n'\n s = s+'>>>layer'+str(layer)+' to layer'+str(layer+1)+' Bias\\n'\n s = s+str(self.Bias[layer])+'\\n\\n'\n # Print its layer by layer one by one\n s = s+'*** layer'+str(self.LayersCount)+' ('+str(self.LayerNeuronsCount[self.LayersCount-1])+' Neurons) ***\\n'\n # Last layer\n return s\n # Print detail info for Neural Network\n\n def feed(self, InputData):\n A = f.sigmoid(InputData)\n for layer in range(0, self.LayersCount-1):\n W = np.dot(A, self.Weight[layer])\n B = np.dot(np.ones((InputData.shape[0],1)), self.Bias[layer])\n A = f.sigmoid(W+B)\n return f.logit(A)\n # Variable explianation\n # A: ActivationFunction(BacksideSum)\n # W: A X Weight\n # B: Ones(InputDataAmount, 1) X Bias\n # BacksideSum = W + B or InputData\n # Feed data forward\n\n def loadfromFile(self, Filename):\n try:\n MyRAWReader = IO.RAWReader()\n MyRAWReader.open(Filename+'.node')\n self.Name = Filename;\n self.LayersCount = int(MyRAWReader.pop())\n self.LayerNeuronsCount = []\n self.Weight = []\n self.Bias = []\n # Get the LayersCount first and Initlalize LayerNeuronsCount, Weight and Bias\n for layer in range(0, self.LayersCount):\n self.LayerNeuronsCount.append(int(MyRAWReader.pop()))\n # Get each layer's neurons count one by one\n for layer in range(0, self.LayersCount-1):\n self.Weight.append(IO.getAMatrix(MyRAWReader))\n # Get each layer's weight one by one\n for layer in range(0, self.LayersCount-1):\n self.Bias.append(IO.getAMatrix(MyRAWReader))\n # Get each layer's bias one by one\n except:\n print('warning: Loading '+Filename+'.node error!')\n # Prevent file not exist\n # Load Neural Network from .node File\n\n def savetoFile(self, Filename = ''):\n if Filename == '':\n Filename = self.Name\n MyRAWWriter = IO.RAWWriter()\n MyRAWWriter.append(int(self.LayersCount))\n for layer in range(0, self.LayersCount):\n MyRAWWriter.append(int(self.LayerNeuronsCount[layer]))\n # Save each layer's neurons count one by one\n MyRAWWriter.newline()\n for layer in range(0, self.LayersCount-1):\n IO.writeAMatrix(self.Weight[layer], MyRAWWriter)\n # Save each layer's weight one by one\n for layer in range(0, self.LayersCount-1):\n IO.writeAMatrix(self.Bias[layer], MyRAWWriter)\n # Save each layer's bias one by one\n MyRAWWriter.write(Filename+'.node')\n # Save Neural Network to .node File\n# Definition of Deep Feedforwrd NeuralNetwork\n","sub_path":"research/fit/node/NeuralNetwork/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"646943869","text":"'''\nОднако обычно свойства реализуют более полезные действия, на-\nпример динамически вычисляют значение атрибута при обращении к нему.\nЭту возможность иллюстрирует следующий пример:\np 1047\n'''\n\nclass PropSquare:\n def __init__(self, start):\n self.value = start\n\n def getX(self): # Операция получения атрибута\n return self.value ** 2\n\n def setX(self, value): # Операция присваивания значения атрибуту\n self.value=value\n\n X = property(getX, setX) # Операция удаления не поддерживается, # описание отсутствует\n\nclass Squar:\n def __init__(self, start):\n self.velue = start\n\n @property\n def squar(self):\n '''Some notes for property'''\n return self.velue ** 2\n\n @squar.setter\n def squar(self, value):\n self.velue = value\n\n\n\nZ = PropSquare(2)\nP = PropSquare(8) # 2 экземпляра класса со свойством\nQ = PropSquare(32) # Каждый хранит собственное значение\n\nprint(Z.X)\nprint(P.X)\nP.X = 18\nprint(P.X)\nprint(Q.X)\n\n\nA = Squar(6)\nprint(A.squar)\nA.squar=4\nprint(A.squar)\nprint(Squar.squar.__doc__)","sub_path":"oop/chapter37_descriptors/Properties/prop_square.py","file_name":"prop_square.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"642397128","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport math\nfrom multiprocessing.pool import ThreadPool\nimport csv\n\ndef scrape(link):\n # links = [\"https://uk.rs-online.com/web/c/batteries-chargers/battery-charger-accessories/battery-charger-leads/\"]\n\n while True:\n try:\n page = requests.get(link)\n if page.status_code == 200 :\n soup = BeautifulSoup(page.content, 'html.parser')\n pdesc = soup.find_all('td',class_=\"descriptionCol\")\n for r in pdesc:\n with open('data.csv','a+', encoding='utf8',newline=\"\") as file:\n write = csv.writer(file)\n write.writerow(re.findall(r'target=\"_self\">(.*?)',str(r)))\n file.close()\n except:\n continue\n break\n\ndef run_downloader(process:int, page_url:list):\n \"\"\"\n Inputs:\n process: (int) number of process to run\n images_url:(list) list of images url\n \"\"\"\n print(f'MESSAGE: Running {process} process')\n results = ThreadPool(process).imap_unordered(scrape, page_url) \n count = 0\n for r in results:\n #print(r)\n print(count)\n count+=1\n\nnum_process = 8\nf1=open(\"link.csv\",\"r\")\nlinks =f1.readlines()\nl = []\nfor link in links:\n l.append(link)\nrun_downloader(num_process, l)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"168461279","text":"\"\"\"Applies a superoperator to an operator.\"\"\"\nfrom typing import List, Union\nimport numpy as np\nfrom toqito.matrix.operations.vec import vec\nfrom toqito.perms.swap import swap\n\n\ndef apply_map(\n mat: np.ndarray, phi_op: Union[np.ndarray, List[List[np.ndarray]]]\n) -> np.ndarray:\n \"\"\"\n Apply a superoperator to an operator.\n\n :param mat: A matrix.\n :param phi_op: A superoperator.\n :return: The result of applying the superoperator `phi_op` to the operator\n `mat`.\n\n `phi_op` should be provided either as a Choi matrix, or as a list of numpy\n arrays with either 1 or 2 columns whose entries are its Kraus operators.\n \"\"\"\n # Both of the following methods of applying the superoperator are much\n # faster than naively looping through the Kraus operators or constructing\n # eigenvectors of a Choi matrix.\n\n # The superoperator was given as a list of Kraus operators:\n if isinstance(phi_op, list):\n s_phi_op = [len(phi_op), len(phi_op[0])]\n\n # Map is completely positive.\n if s_phi_op[1] == 1 or (s_phi_op[0] == 1 and s_phi_op[1] > 2):\n for i in range(s_phi_op[0]):\n phi_op[i][1] = phi_op[i][0].conj().T\n else:\n for i in range(s_phi_op[0]):\n phi_op[i][1] = phi_op[i][1].conj().T\n phi_0_list = []\n phi_1_list = []\n for i in range(s_phi_op[0]):\n phi_0_list.append(phi_op[i][0])\n phi_1_list.append(phi_op[i][1])\n\n k_1 = np.concatenate(phi_0_list, axis=1)\n k_2 = np.concatenate(phi_1_list, axis=0)\n\n a_mat = np.kron(np.identity(len(phi_op)), mat)\n return np.matmul(np.matmul(k_1, a_mat), k_2)\n\n # The superoperator was given as a Choi matrix:\n if isinstance(phi_op, np.ndarray):\n mat_size = np.array(list(mat.shape))\n phi_size = np.array(list(phi_op.shape)) / mat_size\n\n a_mat = np.kron(vec(mat).T[0], np.identity(int(phi_size[0])))\n b_mat = np.reshape(\n swap(\n phi_op.T,\n [1, 2],\n [[mat_size[1], phi_size[1]], [mat_size[0], phi_size[0]]],\n True,\n ).T,\n (int(phi_size[0] * np.prod(mat_size)), int(phi_size[1])),\n )\n return np.matmul(a_mat, b_mat)\n raise ValueError(\n \"Invalid: The variable `phi_op` must either be a list of \"\n \"Kraus operators or as a Choi matrix.\"\n )\n","sub_path":"toqito/super_operators/apply_map.py","file_name":"apply_map.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"309456312","text":"#!/usr/bin/env python\nfrom pyowm import OWM\nimport os\nowm = OWM (os.environ[\"OPENWEATHER_API_KEY\"])\nobservation = owm.weather_at_place(os.environ[\"CITY_NAME\"])\nw = observation.get_weather()\ntemperature = w.get_temperature(unit='fahrenheit')['temp']\ndetailed_status = w.get_detailed_status()\nhumidity = w.get_humidity()\nprint('sopurce=openweathermap, city=\"' + str(os.environ[\"CITY_NAME\"]) + '\", description=\"' + str(detailed_status) + '\", temp=' + str(temperature) + ', humidity=' + str(humidity))\n","sub_path":"exercise1/getweather.py","file_name":"getweather.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"185076591","text":"from pyramid.view import view_config\nfrom max.rest.resources import RESOURCES\nfrom max.rest.ResourceHandlers import JSONResourceEntity\nfrom max.predicates import RestrictedPredicate\nimport re\nimport sys\nimport json\n\n\n@view_config(route_name='endpoints', request_method='GET')\ndef endpoints(context, request):\n \"\"\"\n \"\"\"\n views = request.registry.introspector.get_category('views')\n\n def max_views():\n \"\"\"\n Return route and view instrospection information\n for all endpoints defined on RESOURCES (except this view)\n \"\"\"\n for view in views:\n related = view.get('related')\n if related:\n route = related[0].get('object', None)\n if route is not None:\n if route.name in RESOURCES and route.name != 'endpoints':\n view_settings = view['introspectable']\n yield view_settings, route\n\n def restricted_roles(view):\n for predicate in view['predicates']:\n if isinstance(predicate, RestrictedPredicate):\n roles = predicate.val if isinstance(predicate.val, list) else [predicate.val]\n return roles\n return ['Everyone']\n\n def get_query_params(method):\n params = []\n endpoint_query_params = re.findall(r':query(\\*?)\\s+({.*?})\\s+(.*?)\\n', method.__doc__, re.MULTILINE)\n for required, data, description in endpoint_query_params:\n params.append({\n 'required': required == '*',\n 'data': json.loads(data),\n 'description': description\n })\n return params\n\n def get_rest_params(method):\n params = []\n endpoint_rest_params = re.findall(r':rest\\s+([\\w\\d\\_\\-]+)\\s+(.*?)\\n', method.__doc__, re.MULTILINE)\n for name, description in endpoint_rest_params:\n params.append({\n 'name': name,\n 'description': description\n })\n return params\n\n resources_by_route = {}\n\n # Group all views by route and request method\n for view, route in max_views():\n resource_info = {\n 'route': route.pattern,\n 'id': route.name,\n 'name': RESOURCES[route.name].get('name', route.name),\n 'url': RESOURCES[route.name].get('route'),\n 'category': RESOURCES[route.name].get('category', 'Uncategorized'),\n 'methods': {},\n }\n\n # Import the method implementing the endpoint to get the docstring\n module_fqdn = re.search(r'max/(max/.*)\\.py$', view.action_info.file).groups()[0].replace('/', '.')\n module_namespace, module_name = re.search(r'(.*?)\\.([^\\.]+$)', module_fqdn).groups()\n method_name = view.action_info.src\n method = getattr(sys.modules[module_fqdn], method_name)\n module = getattr(sys.modules[module_namespace], module_name)\n\n is_head = False\n if view['request_methods'] == 'GET':\n code = open(module.__file__.rstrip('c')).read()\n method_code = re.search(r'def\\s+{}(.*?)(?:\\n@|$)'.format(method_name), code, re.DOTALL)\n if method_code:\n is_head = re.search(r\"request\\.method\\s+==\\s+'HEAD'\", method_code.groups()[0])\n\n resources_by_route.setdefault(route.name, resource_info)\n endpoint_description = re.match(r'^\\s*(.*?)\\s*(?:$|:query)', method.__doc__, re.MULTILINE).groups()[0]\n\n roles = restricted_roles(view)\n\n method_info = {\n 'description': endpoint_description,\n 'rest_params': get_rest_params(method),\n 'query_params': get_query_params(method)\n }\n\n # In case we found that the GET method has a HEAD version\n # append HEAD in order to duplicate method info entry of GET as HEAD\n methods = [view['request_methods']]\n if view['request_methods'] == 'GET' and is_head:\n methods.append('HEAD')\n\n for req_method in methods:\n # Create method entry\n resources_by_route[route.name]['methods'].setdefault(req_method, {})\n for role in roles:\n resources_by_route[route.name]['methods'][req_method][role] = method_info\n\n handler = JSONResourceEntity(resources_by_route)\n return handler.buildResponse()\n","sub_path":"max/rest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"294296845","text":"import os as _os\n\nimport mock as _mock\nimport pytest as _pytest\n\nimport doppelganger.util as _util\n\n\n@_pytest.mark.parametrize([\"environ\", \"expected\"], [\n ({\"yourenv\": \"something else\"}, {\"myenv\": \"/my/location\",\n \"yourenv\": \"something else\"}),\n ({\"myenv\": \"/your/location\", \"yourenv\": \"something else\"},\n {\"myenv\": \"/my/location;/your/location\", \"yourenv\": \"something else\"}),\n])\ndef test__addpath(monkeypatch, environ, expected):\n monkeypatch.setattr(\"os.environ\", environ)\n _util.addpath(\"myenv\", \"/my/location\")\n assert environ == expected\n\n\n@_pytest.mark.parametrize([\"environ\", \"kw\", \"expected\"], [\n ({\"e2\": \"something else\"}, {}, None),\n ({\"e1\": \"\"}, {}, None),\n ({\"e1\": \"foo\"}, {}, [\"foo\"]),\n ({\"e1\": \"foo;bar|baz\"}, {}, [\"foo\", \"bar|baz\"]),\n ({\"e1\": \"foo;bar|baz\"}, {\"sep\": \"|\"}, [\"foo;bar\", \"baz\"]),\n])\ndef test__get_list_from_env(monkeypatch, environ, kw, expected):\n monkeypatch.setattr(\"os.environ\", environ)\n result = _util.get_list_from_env(\"e1\", **kw)\n assert result == expected\n\n\n@_pytest.mark.parametrize([\"environ\", \"expected\"], [\n ({\"e2\": \"something else\"}, None),\n ({\"e1\": \"\"}, None),\n ({\"e1\": \"0\"}, 0),\n ({\"e1\": \"42\"}, 42),\n])\ndef test__get_id_from_env(monkeypatch, environ, expected):\n monkeypatch.setattr(\"os.environ\", environ)\n result = _util.get_id_from_env(\"e1\")\n assert result == expected\n\n\ndef test__get_uid_gid_from_filesystem(monkeypatch):\n monkeypatch.setattr(\"os.stat\", _mock.create_autospec(_os.stat))\n result = _util.get_uid_gid_from_filesystem(\"/my/path\")\n _os.stat.assert_called_once_with(\"/my/path\")\n assert result == (_os.stat.return_value.st_uid,\n _os.stat.return_value.st_gid)\n\n\n@_pytest.mark.parametrize([\"env_uid\", \"env_gid\", \"cwd_uid\", \"cwd_gid\",\n \"expected\"], [\n (0, None, 42, 43, (0, 0)),\n (0, 1, 42, 43, (0, 1)),\n (None, 0, 42, 43, (42, 0)),\n (None, None, 42, 43, (42, 43)),\n])\ndef test__get_uid_gid(monkeypatch, env_uid, env_gid, cwd_uid, cwd_gid,\n expected):\n monkeypatch.setattr(\"doppelganger.util.get_id_from_env\",\n _mock.create_autospec(_util.get_id_from_env))\n monkeypatch.setattr(\n \"doppelganger.util.get_uid_gid_from_filesystem\",\n _mock.create_autospec(_util.get_uid_gid_from_filesystem),\n )\n _util.get_id_from_env.side_effect = {\"UID\": env_uid,\n \"GID\": env_gid}.get\n _util.get_uid_gid_from_filesystem.return_value = (cwd_uid, cwd_gid)\n result = _util.get_uid_gid()\n assert result == expected\n\n\ndef test__sudo_args(monkeypatch):\n monkeypatch.setattr(\"os.environ\", {\"PATH\": \"/my/path\",\n \"PYTHONPATH\": \"/my/pythonpath\"})\n result = _util.sudo_args(42, 43)\n assert result == [\"sudo\", \"-n\", \"-H\", \"-u\", \"#42\", \"-g\", \"#43\", \"-E\",\n \"PATH=/my/path\", \"PYTHONPATH=/my/pythonpath\", \"--\"]\n","sub_path":"test/unit/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"531344780","text":"from flask import Flask, request, render_template, redirect, url_for, abort\nimport common\nfrom database_handler import database_handler, write_to_database, get_description\nfrom operator import itemgetter\n\n\napp = Flask(__name__)\nuid = ['0']\napp.jinja_env.globals['uid'] = uid\nusers = database_handler(\"SELECT id,name FROM users;\")\napp.jinja_env.globals['users'] = users\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\n@app.route(\"/index/\")\ndef index(sorting_col=1, way=\"desc\"):\n table = database_handler(\"SELECT * FROM question INNER JOIN users ON \\\n question.user_id = users.id ORDER BY submission_time DESC LIMIT 5;\")\n count_answers_id = database_handler(\"SELECT question_id, COUNT(*) FROM answer GROUP BY question_id;\")\n description = get_description(\"SELECT * FROM question;\")\n description.append(\"answer\")\n\n for element in table:\n for value in count_answers_id:\n if value[0] == element[0]:\n element.append(value[1])\n\n for element in table:\n if len(element) == 12:\n element.append(0)\n\n # Get datas to the summs\n summ_of_datas = []\n summ_of_datas.append(database_handler(\"SELECT count(*) FROM question;\")[0][0])\n summ_of_datas.append(database_handler(\"SELECT count(*) FROM answer;\")[0][0])\n summ_of_datas.append(database_handler(\"SELECT SUM(view_number) FROM question;\")[0][0])\n summ_of_datas.append(database_handler(\"SELECT SUM(vote_number) FROM question;\")[0][0])\n counted_tags = database_handler(\"SELECT name, count(tag_id) FROM tag INNER JOIN question_tag \\\n ON tag.id = question_tag.tag_id GROUP BY name ORDER BY count DESC LIMIT 20;\")\n\n users = database_handler(\"SELECT id,name FROM users;\")\n\n return render_template(\"index.html\", question_list=table, description=description,\n summs=summ_of_datas, uid=uid, tags=counted_tags, users=users)\n\n\n@app.route(\"/submit-question\", methods=[\"POST\"])\ndef submit_question():\n VIEW_NUMBER = 0\n VOTE_NUMBER = 0\n date_time_str = common.get_time_now()\n question_title = request.form[\"question_title\"]\n message = request.form[\"message\"]\n tags = request.form[\"tags\"]\n tags = tags.split(',')\n old_tags = database_handler(\"SELECT name FROM tag;\", \"single_list\")\n for element in tags:\n if element not in old_tags:\n write_to_database(\"INSERT INTO tag (name) VALUES ('{0}');\".format(element))\n\n formated_question = common.format_single_quotes(question_title)\n formated_message = common.format_single_quotes(message)\n write_to_database(\"INSERT INTO question (submission_time, view_number, vote_number, title, message,user_id)\\\n VALUES ('{0}', {1}, {2}, '{3}', '{4}', {5});\".format(date_time_str, VIEW_NUMBER,\n VOTE_NUMBER, formated_question, formated_message, int(uid[0])))\n\n leatest_qid = database_handler(\"SELECT id FROM question\\\n ORDER BY submission_time DESC LIMIT 1;\", \"single_list\")\n\n tags_id = []\n for tag in tags:\n tag_id = database_handler(\"SELECT id FROM tag WHERE name = '{}';\".format(tag), \"one_data\")\n write_to_database(\"INSERT INTO question_tag (question_id, tag_id)\\\n VALUES ({}, {});\".format(leatest_qid[0], tag_id))\n\n return redirect(url_for(\"index\"))\n\n\n@app.route(\"/answer/\")\n@app.route(\"/answer///\")\ndef answer(question_id, sorting_col=2, way=\"desc\"):\n answers_table = database_handler(\"SELECT * FROM answer\\\n WHERE question_id = {};\".format(question_id))\n tags = database_handler(\"SELECT tag_id, name FROM question_tag\\\n INNER JOIN tag ON question_tag.tag_id = tag.id WHERE question_id = {};\".format(question_id))\n\n counted_answers = database_handler(\"SELECT COUNT(question_id)\\\n FROM answer WHERE question_id={};\".format(question_id), \"one_data\")\n\n actual_question = database_handler(\"SELECT * FROM question\\\n WHERE id={};\".format(question_id))\n actual_question_flatten = actual_question[0]\n actual_question_flatten.append(counted_answers)\n\n comments = database_handler(\"SELECT * FROM comment\\\n WHERE question_id = {};\".format(question_id))\n answer_comments = database_handler(\"SELECT comment.answer_id, comment.message, comment.submission_time, comment.id\\\n FROM comment\\\n INNER JOIN answer ON comment.answer_id = answer.id\\\n AND answer.question_id = {};\".format(question_id))\n\n return render_template(\"answer.html\", answers=answers_table, question=actual_question_flatten,\n question_id=question_id, comments=comments,\n answer_comments=answer_comments, tags=tags)\n\n\n@app.route(\"/view/\")\ndef view_func(question_id):\n view_number = database_handler(\"SELECT view_number FROM question\\\n WHERE id={0};\".format(question_id), \"one_data\")\n inc_view_num = view_number + 1\n write_to_database(\"UPDATE question\\\n SET view_number = {0}\\\n WHERE id={1};\".format(inc_view_num, question_id))\n return redirect(url_for('answer', question_id=question_id))\n\n\n@app.route(\"/submit-answer/\", methods=[\"POST\"])\ndef submit_answer(question_id):\n if uid[0] == '0':\n return redirect('/registration')\n VOTE_NUMBER = 0\n date_time_str = common.get_time_now()\n message = request.form[\"answer\"]\n formated_message = common.format_single_quotes(message)\n write_to_database(\"INSERT INTO answer (submission_time, vote_number, question_id, message, user_id)\\\n VALUES ('{0}', {1}, {2}, '{3}', {4});\".format(date_time_str, VOTE_NUMBER, question_id, formated_message, int(uid[0])))\n\n return redirect(url_for('answer', question_id=question_id))\n\n\n@app.route(\"/update/\", methods=[\"GET\"])\ndef update_page(question_id):\n table = database_handler(\"SELECT * FROM question WHERE id = {};\".format(question_id))\n data_to_fill = []\n for question in table:\n for element in question:\n data_to_fill.append(str(element))\n return render_template(\"update.html\", data=data_to_fill)\n\n\n@app.route(\"/submit-update/\", methods=[\"POST\"])\ndef update_data(question_id):\n updated_question_title = request.form['updated-question_title']\n updated_message = request.form['updated-message']\n formated_question_title = common.format_single_quotes(updated_question_title)\n formated_message = common.format_single_quotes(updated_message)\n write_to_database(\"UPDATE question SET title = '{1}' WHERE id = {0};\"\n \"UPDATE question SET message = '{2}' WHERE id = {0};\"\n .format(question_id, formated_question_title, formated_message))\n return redirect(url_for('answer', question_id=question_id))\n\n\n@app.route(\"/question//delete\")\ndef delete_question(question_id):\n answers_ids = database_handler(\"SELECT id FROM answer WHERE question_id = {};\".format(question_id))\n flatten_answers_ids = [element for answers in answers_ids for element in answers]\n\n for element in flatten_answers_ids:\n write_to_database(\"DELETE FROM comment WHERE answer_id = {};\".format(element))\n write_to_database(\"DELETE FROM comment WHERE question_id={0};\"\n \"DELETE FROM answer WHERE question_id={0};\"\n \"DELETE FROM question_tag WHERE question_id={0};\"\n \"DELETE FROM question WHERE id={0};\".format(question_id))\n return redirect(url_for(\"index\"))\n\n\n@app.route(\"//answer//delete\")\ndef delete_answer(answer_id, question_id):\n write_to_database(\"DELETE from comment WHERE answer_id = {0};\"\n \"DELETE from answer WHERE id = {0};\".format(answer_id))\n return redirect(url_for('answer', question_id=question_id))\n\n\n@app.route(\"/vote\")\n@app.route(\"/vote/\")\ndef vote():\n answer_id = request.args.get('id')\n question_id = request.args.get('question_id')\n way = request.args.get('vote')\n page = request.args.get('source')\n table = request.args.get('tbl')\n rep_value = 0\n if answer_id:\n user_id = database_handler(\"SELECT user_id from {} WHERE id = {} ;\".format(table, answer_id), \"one_data\")\n else:\n user_id = database_handler(\"SELECT user_id from {} WHERE id = {} ;\".format(table, question_id), \"one_data\")\n if way == \"up\":\n way = \"+ 1\"\n if table == \"question\":\n rep_value = 5\n if table == \"answer\":\n rep_value = 10\n else:\n way = \"- 1\"\n if table == \"question\":\n rep_value = -2\n if table == \"answer\":\n rep_value = -2 \n write_to_database(\"UPDATE users SET reputation = COALESCE(reputation, 0)+{} WHERE id = {};\".format(rep_value, user_id))\n if answer_id:\n write_to_database(\"UPDATE {} SET vote_number = (vote_number {}) WHERE id = {};\".format(table, way, answer_id))\n else:\n write_to_database(\"UPDATE {} SET vote_number = (vote_number {}) WHERE id = {};\".format(table, way, question_id))\n if page == 'index':\n return redirect('index')\n return redirect(str(page) + \"/\" + str(question_id))\n\n\n@app.route(\"/search\", methods=['POST'])\ndef search():\n search = request.form[\"search\"]\n table = database_handler(\"SELECT * from question WHERE title LIKE '%{0}%' OR message LIKE '%{0}%';\".format(search))\n search_question_ids = []\n description = get_description(\"SELECT * FROM question;\")\n return render_template(\"list.html\", question_list=table, description=description)\n\n\n@app.route(\"/list\")\ndef get_list():\n request_answer = 0\n column_name = request.args.get('column')\n\n if column_name == \"answer\":\n column_name = \"title\"\n request_answer = 1\n\n way = request.args.get('way')\n\n table = database_handler(\"SELECT * FROM question INNER JOIN users ON \\\n question.user_id = users.id ORDER BY {} {};\".format(column_name, way))\n count_answers_id = database_handler(\"SELECT question_id, COUNT(*) FROM answer GROUP BY question_id;\")\n description = get_description(\"SELECT * FROM question;\")\n description.append(\"answer\")\n\n for element in table:\n for value in count_answers_id:\n if value[0] == element[0]:\n element.append(value[1])\n\n for element in table:\n if len(element) == 12:\n element.append(0)\n\n if request_answer == 1:\n table.sort(key=itemgetter(12))\n if way == \"DESC\":\n table.reverse()\n return render_template(\"list.html\", question_list=table, description=description)\n\n\n@app.route(\"/answer//new-comment\")\n@app.route(\"/question//new-comment\")\ndef add_comment(question_id=None, answer_id=None):\n if answer_id is None:\n actual_question = database_handler(\"SELECT * FROM question\\\n WHERE id={};\".format(question_id))\n actual_question_flatten = actual_question[0]\n return render_template(\"comment.html\", question=actual_question_flatten, question_id=question_id)\n elif question_id is None:\n actual_answer = database_handler(\"SELECT * FROM answer\\\n WHERE id={};\".format(answer_id))\n actual_answer_flatten = actual_answer[0]\n return render_template(\"comment.html\", answer=actual_answer_flatten, answer_id=answer_id)\n\n\n@app.route(\"/submit-comment/\", methods=[\"POST\"])\ndef submit_question_comment(question_id):\n if uid[0] == '0':\n return redirect('/registration')\n date_time_str = common.get_time_now()\n message = request.form[\"answer\"]\n formated_message = common.format_single_quotes(message)\n write_to_database(\"INSERT INTO comment (question_id, message, submission_time, user_id)\\\n VALUES ('{}', '{}', '{}', {});\".format(question_id, formated_message, date_time_str, int(uid[0])))\n return redirect(url_for(\"answer\", question_id=question_id))\n\n\n@app.route(\"/submit-comment/answer/\", methods=[\"POST\"])\ndef submit_answer_comment(answer_id):\n if uid[0] == '0':\n return redirect('/registration')\n date_time_str = common.get_time_now()\n message = request.form[\"answer\"]\n formated_message = common.format_single_quotes(message)\n write_to_database(\"INSERT INTO comment (answer_id, message, submission_time, user_id)\\\n VALUES ('{}', '{}', '{}', {});\".format(answer_id, formated_message, date_time_str, int(uid[0])))\n question_id = database_handler(\"SELECT question_id FROM answer WHERE id={};\".format(answer_id), \"one_data\")\n return redirect(url_for(\"answer\", question_id=question_id))\n\n\n@app.route(\"/comments//edit\")\ndef update_comment_page(comment_id):\n comment_data = database_handler(\"SELECT * FROM comment\\\n WHERE id={};\".format(comment_id))\n flatten_comment_data = comment_data[0]\n if flatten_comment_data[1] is None:\n flatten_comment_data.pop(1)\n get_question_id = database_handler(\"SELECT answer.question_id FROM answer\\\n INNER JOIN comment ON comment.answer_id = answer.id\\\n AND comment.id={};\".format(comment_id), \"one_data\")\n flatten_comment_data.insert(1, get_question_id)\n return render_template(\"comment.html\", comment_data=flatten_comment_data, comment_id=comment_id)\n\n\n@app.route(\"//comments//edit/submit\", methods=['POST'])\ndef updated_comment_question_submit(comment_id, question_id):\n date_time_str = common.get_time_now()\n message = request.form[\"answer\"]\n formated_message = common.format_single_quotes(message)\n write_to_database(\"UPDATE comment SET message = '{}', submission_time = '{}'\\\n WHERE id={};\".format(formated_message, date_time_str, comment_id))\n return redirect(url_for(\"answer\", question_id=question_id))\n\n\n@app.route(\"/delete-q-tag\")\ndef delete_tag():\n qid = request.args.get('qid')\n tag_id = request.args.get('tag_id')\n write_to_database(\"DELETE FROM question_tag WHERE question_id={0} AND tag_id = {1};\".format(qid, tag_id))\n return redirect(url_for(\"answer\", question_id=qid))\n\n\n@app.route(\"/delete-comment\")\ndef delete_comment():\n comment_id = request.args.get('comment_id')\n question_id = request.args.get('question_id')\n write_to_database(\"DELETE FROM comment WHERE id={};\".format(comment_id))\n return redirect(url_for(\"answer\", question_id=question_id))\n\n\n@app.route(\"/registration\")\ndef registration():\n return render_template('login.html')\n\n\n@app.route(\"/submit_user_registration\", methods=['POST'])\ndef submit_user_registration():\n global uid\n user_name = request.form['user-name']\n date_time_str = common.get_time_now()\n write_to_database(\"INSERT INTO users (name, date, reputation) VALUES ('{0}', '{1}', 0);\".format(user_name, date_time_str))\n user_id = database_handler(\"SELECT id FROM users WHERE name='{0}';\".format(user_name), 'one_data')\n uid[0] = str(user_id)\n user_name_sql = database_handler(\"SELECT name FROM users WHERE id = {}\".format(uid[0]), \"single_list\")\n app.jinja_env.globals['user_name'] = user_name_sql\n return redirect(url_for('index'))\n\n\n@app.route(\"/list_users\")\ndef list_users():\n users_table = database_handler(\"SELECT * FROM users\")\n for element in users_table:\n element.pop(0)\n return render_template(\"list_users.html\", users_table=users_table)\n\n\n@app.route(\"/login\")\ndef login():\n global uid\n uid[0] = request.args.get('uid')\n user_name = database_handler(\"SELECT name FROM users WHERE id = {}\".format(uid[0]), \"single_list\")\n app.jinja_env.globals['user_name'] = user_name\n return redirect('index')\n\n\n@app.route(\"/tags\")\ndef tags():\n search = request.args.get('search')\n tag_id = database_handler(\"SELECT id from tag WHERE name = '{}';\".format(search), \"single_list\")\n question_ids = database_handler(\"SELECT question_id from question_tag WHERE tag_id = '{}';\".format(tag_id[0]), \"single_list\")\n string = \"\"\n for element in question_ids:\n string = string + str(element) + \", \"\n string = string[:len(string) - 2]\n tag_questions = database_handler(\"SELECT * from question WHERE id in ({});\".format(string))\n description = get_description(\"SELECT * FROM question;\")\n return render_template(\"list.html\", question_list=tag_questions, description=description)\n\n\n@app.route(\"/user/\")\ndef user_profile(uid=None):\n user_questions = database_handler(\"SELECT title, id from question WHERE user_id = {};\".format(uid))\n user_answers = database_handler(\"SELECT question.title, answer.message, question.id FROM answer\\\n INNER JOIN question ON (answer.question_id = question.id)\\\n WHERE answer.user_id={};\".format(uid))\n user_question_comments = database_handler(\"SELECT question.title, comment.message, question.id FROM comment\\\n INNER JOIN question ON (comment.question_id = question.id)\\\n WHERE comment.user_id = {};\".format(uid))\n user_answer_comments = database_handler(\"SELECT answer.message, comment.message FROM comment\\\n INNER JOIN answer ON (comment.answer_id = answer.id)\\\n WHERE comment.user_id = {};\".format(uid))\n return render_template(\"user_profile.html\", user_questions=user_questions, user_answers=user_answers,\n user_question_comments=user_question_comments, user_answer_comments=user_answer_comments)\n\n\n@app.errorhandler(404)\ndef error_hadler(e):\n return render_template(\"handler.html\")\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"187087704","text":"import numpy as np\nimport random\nfrom getchar import getch\nimport sys\nimport pickle\nfrom collections import Counter\n \n\n\ndef main(ngrams=None):\n \n if ngrams is None:\n ngrams = Counter()\n \n move_hist = []\n pred_hist = []\n \n while True:\n\n # generate a prediction\n if len(move_hist) > 5:\n ng = \"\".join(move_hist[-5:])\n if ngrams[ng, \"0\"] > ngrams[ng, \"1\"]:\n prediction = \"0\"\n elif ngrams[ng, \"1\"] > ngrams[ng, \"0\"]:\n prediction = \"1\"\n else:\n prediction = random.choice(\"01\")\n else:\n prediction = random.choice(\"01\")\n\n # read user's move and check if valid or exit signal\n user_move = getch().decode('utf-8')\n if user_move == \"C\":\n break # exit loop\n if user_move not in \"01\":\n print(\"Please enter 0 or 1, or type C to quit\")\n continue # go to next iteration, don't store\n\n # store the update and print accuracy\n if len(move_hist) > 5:\n ngrams[ng, user_move] += 1\n move_hist.append(user_move)\n pred_hist.append(prediction)\n accuracy = np.mean([p == u for p, u in zip(pred_hist, move_hist)])\n print(f\"prediction: {prediction}; user played {user_move}; accuracy {accuracy}\")\n \n return ngrams\n \nif __name__ == \"__main__\":\n ngrams = None\n if len(sys.argv) > 1:\n try:\n ngrams = eval(open(sys.argv[1]).read())\n print(f\"Reading input from {sys.argv[1]} and will write on exit\")\n except FileNotFoundError:\n print(f\"No input file found, but will write to {sys.argv[1]} on exit\")\n else:\n print(f\"No input file specified, will not read or write\")\n \n print(\"Press 0 or 1, or type C to exit\")\n ngrams = main(ngrams)\n \n if len(sys.argv) > 1:\n try:\n open(sys.argv[1], \"w\").write(repr(ngrams) + \"\\n\")\n except:\n print(f\"Could not write to output file {sys.argv[1]}\")\n\n print(\"ngrams\")\n print(repr(ngrams))\n print(\"Finishing\")\n","sub_path":"Week11/Sir's slides/code/aaronson_oracle.py","file_name":"aaronson_oracle.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180224947","text":"\"\"\"\nBasic nuqql backend\n\"\"\"\n\nimport asyncio\n\nfrom typing import TYPE_CHECKING, Awaitable, Callable, List, Optional, Tuple\n\nimport nuqql_based.logger\n\nfrom nuqql_based.account import AccountList\nfrom nuqql_based.callback import Callbacks, Callback\nfrom nuqql_based.config import Config\nfrom nuqql_based.server import Server\n\nif TYPE_CHECKING: # imports for typing\n # pylint: disable=cyclic-import\n from nuqql_based.account import Account # noqa\n\nCallbackFunc = Callable[[Optional[\"Account\"], Callback, Tuple], Awaitable[str]]\nCallbackTuple = Tuple[Callback, CallbackFunc]\nCallbackList = List[CallbackTuple]\n\n\nclass Based:\n \"\"\"\n Based class\n \"\"\"\n\n def __init__(self, name: str, version: str) -> None:\n # callbacks\n self.callbacks = Callbacks()\n\n # config\n self.config = Config(name, version)\n\n # create a message queue for message exchange between accounts and the\n # based server\n queue: asyncio.Queue = asyncio.Queue()\n\n # account list\n self.accounts = AccountList(self.config, self.callbacks, queue)\n\n # server\n self.server = Server(self.config, self.callbacks, self.accounts, queue)\n\n def set_callbacks(self, callbacks: CallbackList) -> None:\n \"\"\"\n Set callbacks of the backend to the (callback, function) tuple values\n in the callbacks list\n \"\"\"\n\n # register all callbacks\n for cback, func in callbacks:\n self.callbacks.add(cback, func)\n\n async def start(self) -> None:\n \"\"\"\n Start based\n \"\"\"\n\n # load config from command line arguments and config file\n self.config.init()\n await self.callbacks.call(Callback.BASED_CONFIG, None, (self.config, ))\n\n # logging\n nuqql_based.logger.init(self.config)\n\n # load account list\n await self.accounts.load()\n\n # start server\n try:\n await self.server.run()\n except asyncio.CancelledError:\n await self.callbacks.call(Callback.BASED_INTERRUPT, None, ())\n finally:\n await self.callbacks.call(Callback.BASED_QUIT, None, ())\n","sub_path":"nuqql_based/based.py","file_name":"based.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180653808","text":"## Assignment 3 Solutions\r\n# 1 - Create a program to do the following tasks:\r\n \r\n# \tA)\tSplit a given Sentence into list of words.\r\n# \tB)\tSort that list according to the letters alphabetically.\r\n# \tC)\tSort that list alphabetically.\r\n \r\n# Take string input from user:\r\n# Input: \"i love to code in python\"\r\n# Output A) ==> ['i','love','to','code','in','python'] \r\n# Output B) ==> ['code','i,'in','love','python','to'] \r\n# Output C) ==> ['cdeo','i','in','elov','hnopty','ot']\r\n \r\n# NOTE: You are not allowed to use some inbuilt functions like:[sort, min, sorted, reverse, reversed, split]\r\n\r\n# function to split a sentence into words\r\ndef split_sentence(sentence):\r\n\tsplit_list = []\r\n\r\n\tcurr_word = ''\r\n\r\n\tfor char in sentence:\r\n\t\tif char != ' ':\r\n\t\t\tcurr_word += char\r\n\t\telse:\r\n\t\t\tsplit_list.append(curr_word)\r\n\t\t\tcurr_word = ''\r\n\r\n\t# Last word or if only one word exists\r\n\tsplit_list.append(curr_word)\r\n\r\n\treturn split_list\r\n\r\n# Function to sort a list of words alphabetically\r\n# Complexity O(n^2)\r\ndef sort_word_list(word_list):\r\n\tfor i in range(len(word_list)):\r\n\t\tfor j in range(i,len(word_list)):\r\n\t\t\tif word_list[i] > word_list[j]:\r\n\t\t\t\tword_list[i], word_list[j] = word_list[j], word_list[i]\r\n\r\n\treturn word_list\r\n\r\n# Function to sort the characters in a word\r\n# Complexity O(n^2)\r\ndef sort_word(word):\r\n\tword = list(word)\r\n\tfor i in range(len(word)):\r\n\t\tfor j in range(i, len(word)):\r\n\t\t\tif word[i] > word[j]:\r\n\t\t\t\tword[i], word[j] = word[j], word[i]\r\n\treturn ''.join(word)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\tsentence = input(\"Enter a sentence : \")\r\n\tword_list = split_sentence(sentence)\r\n\tprint(\"\\nList of words in the sentence :\", word_list)\r\n\tsorted_wl = sort_word_list(word_list)\r\n\r\n\tprint(\"Word list sorted alphabetically :\", sorted_wl)\r\n\tsorted_words_list = [sort_word(w) for w in sorted_wl]\r\n\tprint(\"Sorted word list with sorted words :\", sorted_words_list)","sub_path":"July_23/Assignment 3 (Task 2)/Solution 1.py","file_name":"Solution 1.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"173569890","text":"# Points class i.e. point cloud.\nimport numpy as np\n\n\nclass Camera:\n def __init__(self, position, look_at):\n self.position = position.astype(np.float32)\n self.look_at = look_at.astype(np.float32)\n\n def get_properties(self, binary_filename):\n \"\"\"\n :return: A dict conteining object properties. They are written into json and interpreted by javascript.\n \"\"\"\n json_dict = {}\n json_dict['type'] = 'camera'\n json_dict['position'] = self.position.tolist()\n json_dict['look_at'] = self.look_at.tolist()\n return json_dict\n\n def write_binary(self, path):\n bin_position = self.position.tobytes()\n with open(path, \"wb\") as f:\n f.write(bin_position)\n","sub_path":"pyviz3d/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"358889840","text":"# You are given integers K, M and a non-empty array A consisting of N integers. Every element of the array is not greater than M.\n\n# You should divide this array into K blocks of consecutive elements. The size of the block is any integer between 0 and N. Every element of the array should belong to some block.\n\n# The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0.\n\n# The large sum is the maximal sum of any block.\n\n# For example, you are given integers K = 3, M = 5 and array A such that:\n\n# A[0] = 2\n# A[1] = 1\n# A[2] = 5\n# A[3] = 1\n# A[4] = 2\n# A[5] = 2\n# A[6] = 2\n# The array can be divided, for example, into the following blocks:\n\n# [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15;\n# [2], [1, 5, 1, 2], [2, 2] with a large sum of 9;\n# [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8;\n# [2, 1], [5, 1], [2, 2, 2] with a large sum of 6.\n# The goal is to minimize the large sum. In the above example, 6 is the minimal large sum.\n\n# Write a function:\n\n# def solution(K, M, A)\n\n# that, given integers K, M and a non-empty array A consisting of N integers, returns the minimal large sum.\n\n# For example, given K = 3, M = 5 and array A such that:\n\n# A[0] = 2\n# A[1] = 1\n# A[2] = 5\n# A[3] = 1\n# A[4] = 2\n# A[5] = 2\n# A[6] = 2\n# the function should return 6, as explained above.\n\n# Assume that:\n\n# N and K are integers within the range [1..100,000];\n# M is an integer within the range [0..10,000];\n# each element of array A is an integer within the range [0..M].\n# Complexity:\n\n# expected worst-case time complexity is O(N*log(N+M));\n# expected worst-case space complexity is O(1) (not counting the storage required for input arguments).\n\nimport unittest\nimport random\n\nN_K_RANGE = (1, 100000)\nM_RANGE = (0, 10000)\n\nclass Solution(object):\n def min_max_division(self, K, M, A):\n \"\"\"\n Given integers K, M and a non-empty array A consisting of N integers, returns the minimal large sum\n \n :param K: divide this array into K blocks\n :param M: Every element of the array is not greater than M\n :param array: list of integers\n :return: the minimal large sum\n \"\"\"\n if not A:\n return 0\n\n if len(A) == 1:\n return A[0]\n\n # minimum case\n if len(A) <= K:\n return max(A)\n \n mi = max(A)\n # mi = M\n\n # maximum case\n result = ma = sum(A)\n # print(mi, ma)\n\n # O(len(array)) = O(N)\n def check(K, mid, array):\n s = 0\n for i in range(len(array)):\n s += array[i]\n if s > mid:\n s = array[i]\n K -= 1\n \n if K < 0:\n # print(\"False\", mid)\n return False\n return True\n\n # greatest maximum is N * M\n while mi <= ma:\n # take the middle value\n mid = (mi + ma) // 2\n # print(\"before\", \"mid:\", mid, \"min:\", mi, \"max\", ma)\n\n # check if can be divide by K blocks (cut K - 1 times) with the sum of each block not greater than mid\n if check(K - 1, mid, A):\n ma = mid - 1\n result = mid\n else:\n mi = mid + 1\n # print(\"after\", \"mid:\", mid, \"min:\", mi, \"max\", ma)\n return result\n\nclass Test(unittest.TestCase):\n\n def __init__(self, _):\n super(Test, self).__init__(_)\n self.s = Solution()\n\n def test_example1(self):\n self.assertEqual(self.s.min_max_division(3, 5, [2, 1, 5, 1, 2, 2, 2]), 6)\n\n def test_single(self):\n self.assertEqual(self.s.min_max_division(1, 1, [1]), 1)\n self.assertEqual(self.s.min_max_division(1, 4, [1]), 1)\n\n def test_simple1(self):\n self.assertEqual(self.s.min_max_division(2, 5, [2, 1, 3, 1, 2, 2, 2]), 7)\n\n def test_simple2(self):\n self.assertEqual(self.s.min_max_division(2, 5, [0, 0, 0, 0, 0, 0, 0]), 0)\n\n def test_random(self):\n arr = [n for n in range(1, random.randint(0, M_RANGE[1]))]\n self.assertEqual(self.s.min_max_division(1, M_RANGE[1], arr), sum(arr))\n\n def test_maximum(self):\n arr = [n for n in range(M_RANGE[0], M_RANGE[1] + 1)]\n self.assertEqual(self.s.min_max_division(1, M_RANGE[1], arr), sum(arr))\n\n\ndef main():\n unittest.main()\n\nif __name__ == '__main__':\n main()","sub_path":"codility/MinMaxDivision.py","file_name":"MinMaxDivision.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"86320620","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n \n# http://www.apache.org/licenses/LICENSE-2.0.html\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThis program tests the system errors of the dl predictor from system query level.\nLoad the preditions based on date range and attributes from es and fact data to compare.\nSuggest to use the test_dlpredictor_system_errors.py to run the testcases for dl predictor.\n\"\"\"\n# Baohua Cao.\n\nfrom elasticsearch import Elasticsearch\nfrom pyspark import SparkContext\nfrom pyspark.sql import HiveContext\nfrom pyspark.sql.functions import udf, col, explode\nfrom pyspark.sql.types import StringType, IntegerType, MapType\nimport logging\nimport yaml\nimport argparse\nimport sys\nfrom datetime import datetime, timedelta\n\n\n# query total traffic of precictions those matched the conditions.\ndef query_predictions_traffic(cfg, starting_day, ending_day, attributes_condition):\n es_host, es_port = cfg['es_host'], cfg['es_port']\n es_index, es_type = cfg['es_predictions_index'], cfg['es_predictions_type']\n es = Elasticsearch([{'host': es_host, 'port': es_port}])\n day = datetime.strptime(starting_day, '%Y-%m-%d')\n end_date = datetime.strptime(ending_day, '%Y-%m-%d')\n predicted_traffic = 0\n # sum up the daily traffic as the total predicted traffic.\n while day <= end_date:\n prediction_day_query = {\n \"size\": 0,\n \"query\": {\n \"bool\": {\n \"must\": [\n ]\n }\n },\n \"aggs\": {\n \"day\": {\n \"sum\": {\n \"field\": \"ucdoc.predictions.{}.hours.total\".format(day.strftime('%Y-%m-%d'))\n }\n }\n }\n }\n if attributes_condition:\n for attr, attr_value in attributes_condition.items():\n match = {\n \"match\": {\n \"ucdoc.\" + attr: attr_value\n }\n }\n prediction_day_query['query']['bool']['must'].append(match)\n res = es.search(index=es_index, body=prediction_day_query)\n \"\"\"\n result sample:\n \"hits\" : {\n \"total\" : 1339040,\n \"max_score\" : 0.0,\n \"hits\" : [ ]\n },\n \"aggregations\" : {\n \"day\" : {\n \"value\" : 17131.516769555536\n }\n }\"\"\"\n day_predicted_result = res['aggregations']\n day_predicted_traffic = int(\n day_predicted_result['day']['value']) if day_predicted_result['day']['value'] else 0\n predicted_traffic += day_predicted_traffic\n day = day + timedelta(days=1)\n\n return predicted_traffic\n\n\ndef _list_to_map(count_array):\n count_map = {}\n for item in count_array:\n key_value = item.split(':')\n count_map[key_value[0]] = key_value[1]\n return count_map\n\n\ndef add_count_map(df):\n # Convert count_array to count_map\n list_to_map_udf = udf(_list_to_map, MapType(\n StringType(), StringType(), False))\n df = df.withColumn('count_map', list_to_map_udf(df.count_array))\n return df\n\n\ndef load_factdata(sc, cfg, starting_day, ending_day, attributes_condition):\n hive_context = HiveContext(sc)\n bucket_id_max = cfg['bucket_id_max']\n # step 1: load the original fact data.\n # step 2: load the distribution e.g. 133904 uckeys.\n # step 3: inner join the original fact data with the distribution. e.g. 133904 uckeys.\n # step 4: filter the new fact data with date range e.g. 2020-01-30 - 2020-02-08, 10 days.\n # step 5: filter the new fact data with conditions.\n\n # step 1: load the original fact data\n command = \"\"\"select uckey, day, hour, count_array from {} where bucket_id <= {} \n \"\"\".format(cfg['factdata'], bucket_id_max)\n df = hive_context.sql(command)\n df = add_count_map(df)\n # [Row(count_array=['3:4'], day='2019-11-02', hour=19, uckey='native,72bcd2720e5011e79bc8fa163e05184e,WIFI,g_m,5,CPM,15,76', count_map={'3': '4'})]\n\n # Explode count_map to have pcat and count on separate columns\n df = df.select('uckey', 'day', 'hour', explode(df.count_map)).withColumnRenamed(\n \"key\", \"price_cat\").withColumnRenamed(\"value\", \"count\")\n # [Row(uckey='native,72bcd2720e5011e79bc8fa163e05184e,WIFI,g_m,5,CPM,15,76', day='2019-11-02', hour=19, price_cat='3', count='4')]\n\n # This is to have the fact data uckey-price_cat pair based on daily count to join the distribution.\n df = df.groupBy('uckey', 'day', 'price_cat').agg({\"count\": \"sum\"}).withColumnRenamed(\"sum(count)\", \"count\")\n # [Row(uckey='splash,5cd1c663263511e6af7500163e291137,WIFI,g_m,4,CPT,3,', day='2019-11-02', price_cat='1', count=56.0)]\n\n # step 2: load the distribution e.g. 133904 uckeys\n command = 'select uckey, price_cat from {} where ratio > 0'.format(\n cfg['distribution'])\n dfd = hive_context.sql(command)\n\n # step 3: inner join the original fact data with the distribution #distinct uckeys in joined fact data: e.g. 133904\n df = df.join(dfd, [df.uckey == dfd.uckey, df.price_cat ==\n dfd.price_cat], how=\"inner\").drop(dfd.uckey).drop(dfd.price_cat)\n # e.g. df.select(df.uckey).distinct().count(): 133904\n\n # step 4: filter the new fact data with date range e.g. 2020-01-30 - 2020-02-08, 10 days\n df = df.filter((df.day <= ending_day) & (df.day >= starting_day))\n # e.g. df.count(): 15152287, df.select(df.uckey).distinct().count(): 92612\n\n # step 5: filter the new fact data with conditions.\n uckey_attrs = cfg['uckey_attrs']\n for attr_index in range(len(uckey_attrs)):\n df = df.withColumn(uckey_attrs[attr_index], udf(\n lambda x: x.split(',')[attr_index], StringType())(df.uckey))\n # e.g. [Row(uckey=u'magazinelock,01,2G,,,CPM,13', day=u'2020-01-19', hour=8, count_array=[u'1:10'],\n # m=u'magazinelock', si=u'01', t=u'2G', g=u'', a=u'', pm=u'CPM', r=u'13')]\n if attributes_condition:\n for attr, attr_value in attributes_condition.items():\n df = df.filter(df[attr] == str(attr_value))\n\n return df\n\n\ndef calculate_factdata_traffic(df_factdata):\n df_traffic = df_factdata.agg({\"count\": \"sum\"}).withColumnRenamed(\n \"sum(count)\", \"sum_traffic\")\n sum_traffic = int(df_traffic.take(1)[0][\"sum_traffic\"])\n\n return sum_traffic\n\n\ndef calculate_error(factdata_traffic, predicted_traffic):\n mape_error = 1.0 * abs(factdata_traffic - predicted_traffic) / \\\n factdata_traffic if factdata_traffic else 0\n smape_error = 2.0 * abs(factdata_traffic - predicted_traffic) / \\\n (factdata_traffic + predicted_traffic) if factdata_traffic else 0\n mape_error = \"%.2f\" % round(mape_error, 2)\n smape_error = \"%.2f\" % round(smape_error, 2)\n return mape_error, smape_error\n\n\ndef run_testcase(sc, cfg, starting_day, ending_day, attributes_condition):\n # step 1: load the related factdata.\n # step 2: calculate the factdata's traffic.\n # step 3: calculate the es predictions' traffic.\n # step 4: compare the two traffic and output the error result.\n df_factdata = load_factdata(\n sc, cfg, starting_day, ending_day, attributes_condition)\n factdata_traffic = calculate_factdata_traffic(df_factdata)\n predicted_traffic = query_predictions_traffic(\n cfg, starting_day, ending_day, attributes_condition)\n mape_error, smape_error = calculate_error(\n factdata_traffic, predicted_traffic)\n\n return [starting_day, ending_day, str(attributes_condition), str(factdata_traffic),\n str(predicted_traffic), str(mape_error), str(smape_error)]\n\n\ndef run(cfg):\n sc = SparkContext.getOrCreate()\n sc.setLogLevel('WARN')\n\n try:\n res = [['starting_day', 'ending_day', 'attributes_condition',\n 'factdata_traffic', 'predicted_traffic', 'mape_error', 'smape_error']]\n starting_day, ending_day = \"2020-01-30\", \"2020-02-08\"\n # r: 40 - beijing, r: 49 - shenyang, r: 80 - cities group\n attributes_conditions = [None, {\"g\": \"g_m\"}, {\"g\": \"g_f\"}, {\"a\": \"4\"}, {\"a\": \"6\"}, {\"g\": \"g_m\", \"a\": \"4\"},\n {\"g\": \"g_f\", \"a\": \"4\"}, {\"g\": \"g_f\", \"a\": \"6\"}, {\n \"r\": \"40\"}, {\"r\": \"49\"},\n {\"r\": \"80\"}, {\"m\": \"native\"}, {\"pm\": \"CPC\"},\n {\"g\": \"g_f\", \"a\": \"6\", \"m\": \"native\"}, {\n \"g\": \"g_f\", \"a\": \"6\", \"m\": \"native\", \"r\": \"40\"}\n ]\n for attributes_condition in attributes_conditions:\n print('processing ' + str((starting_day, ending_day)) +\n ', ' + str(attributes_condition))\n testcase_result = run_testcase(\n sc, cfg, starting_day, ending_day, attributes_condition)\n res.append(testcase_result)\n finally:\n sc.stop()\n\n for resi in res:\n print(\", \".join(resi))\n\n\n# spark-submit --master yarn --num-executors 20 --executor-cores 5 --jars lib/elasticsearch-hadoop-6.5.2.jar tests/test_dlpredictor_system_errors_0 tests/conf/config.yml\nif __name__ == '__main__':\n logger = logging.getLogger('test-system-errors-dlpredictor-logger')\n parser = argparse.ArgumentParser(\n description='test system errors of dlpredictor')\n parser.add_argument('config_file')\n args = parser.parse_args()\n\n try:\n with open(args.config_file, 'r') as ymlfile:\n cfg = yaml.load(ymlfile)\n logger.info(\"Successfully open {}\".format(args.config_file))\n except IOError as e:\n logger.error(\n \"Open config file unexpected error: I/O error({0}): {1}\".format(e.errno, e.strerror))\n except:\n logger.error(\"Unexpected error:{}\".format(sys.exc_info()[0]))\n raise\n\n run(cfg)\n","sub_path":"Processes/dlpredictor/tests/scripts/script_1.py","file_name":"script_1.py","file_ext":"py","file_size_in_byte":10469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"287435442","text":"import time\nimport datetime\nimport os\nimport pprint\nimport pickle\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport gobject\n\nclass TimeState:\n def __init__(self):\n self.timesheet = {}\n self.current = None\n\n def track(self, task):\n self.stopTracking()\n self.current = task\n\n if task in self.timesheet.keys():\n previous, start = self.timesheet[task]\n if start is None:\n self.timesheet[task] = (previous, int(time.time()))\n else:\n self.timesheet[task] = (int(time.time()) - start + previous, int(time.time()))\n else:\n self.timesheet[task] = (0, int(time.time()))\n\n def stopTracking(self):\n # switching time tracking\n if self.current is not None:\n oldTask = self.current\n self.current = None\n previous, start = self.timesheet[oldTask]\n self.timesheet[oldTask] = (int(time.time()) - start + previous, None)\n \n def getTasks(self, rebase=None):\n if rebase is not None:\n items = self.rebase(self.timesheet.items(), rebase)\n else:\n items = self.timesheet.items()\n\n return map(lambda v: (v[0], float(v[1][0])/60/60), items)\n\n\n def getTaskAtPosition(self, position):\n key = dict(zip(range(len(self.timesheet)), self.timesheet))[position]\n return (key, self.timesheet[key])\n\n def alterTaskAtPosition(self, position, alterFunction):\n key = dict(zip(range(len(self.timesheet)), self.timesheet))[position]\n self.timesheet[key] = alterFunction(self.timesheet[key])\n\n def rebase(self, items, rebase):\n current_sum = sum(map(lambda x: x[1][0], items))\n return map(lambda x: (x[0], (float(x[1][0])/current_sum * rebase, x[1][1])), items)\n\n\nclass TimeTracker:\n\n def delete_event(self, widget, event, data=None):\n return False\n\n def destroy(self, widget, data=None):\n path = os.path.expanduser(\"~/.ttt.s\")\n pickle.dump(self.timestate, open(path, 'w'))\n gtk.main_quit()\n\n def continue_or_new(self):\n path = os.path.expanduser(\"~/.ttt.s\")\n return pickle.load(open(path)) if os.path.exists(path) else TimeState()\n\n def new(self):\n path = os.path.expanduser(\"~/.ttt.s\")\n if os.path.exists(path):\n os.remove(path)\n\n def redisplayList(self, rebase=None):\n self.taskList.clear()\n for v in self.timestate.getTasks(rebase):\n self.taskList.append(v)\n\n\n def __init__(self):\n self.timestate = self.continue_or_new()\n\n window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n window.connect(\"delete_event\", self.delete_event)\n window.connect(\"destroy\", self.destroy)\n window.set_border_width(10)\n window.set_default_size(300, 400)\n window.set_resizable(True)\n window.set_title(\"Tricksterish time tracker\")\n \n vbox = gtk.VBox(False, 10)\n entryBox = gtk.HBox(False, 10)\n rebaseBox = gtk.HBox(False, 10)\n\n self.taskList = gtk.ListStore(str, float)\n taskListView = gtk.TreeView(self.taskList)\n taskListView.set_rules_hint(True)\n taskListView.append_column(gtk.TreeViewColumn(\"Task\", gtk.CellRendererText(), text=0))\n taskListView.append_column(gtk.TreeViewColumn(\"Time\", gtk.CellRendererText(), text=1))\n def adjustTime(t, iteration, p, u):\n _taskName, _timeRecord = self.timestate.getTaskAtPosition(iteration[0])\n _taskLabel = gtk.Label(\"Task {}\".format(_taskName))\n _taskLabel.show()\n _taskTime = gtk.Entry()\n _taskTime.show()\n _taskTime.set_text(str(float(_timeRecord[0])/60/60))\n dialog = gtk.Dialog(\"Adjust time\",\n None,\n gtk.DIALOG_DESTROY_WITH_PARENT,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,\n gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))\n dialog.vbox.pack_start(_taskLabel)\n dialog.vbox.pack_start(_taskTime)\n dialog.show()\n response = dialog.run()\n if response == gtk.RESPONSE_ACCEPT:\n self.timestate.alterTaskAtPosition(iteration[0], lambda x: (float(_taskTime.get_text()) * 60 * 60, x[1]))\n self.redisplayList()\n dialog.destroy()\n taskListView.connect('row-activated', adjustTime, None)\n\n def trackTimeState(w, d):\n self.timestate.track(taskName.get_text())\n taskName.set_text('')\n self.redisplayList()\n taskName = gtk.Entry()\n taskName.connect('activate', trackTimeState, None)\n\n def stopTimeState(w, d):\n self.timestate.stopTracking()\n self.redisplayList()\n stopTracking = gtk.Button(\"Stop\")\n stopTracking.connect('clicked', stopTimeState, None)\n\n\n def newTimeState(w, d):\n self.new()\n self.timestate = TimeState()\n self.redisplayList()\n\n newTracking = gtk.Button(\"New\")\n newTracking.connect('clicked', newTimeState, None)\n\n entryBox.add(taskName)\n entryBox.add(stopTracking)\n entryBox.add(newTracking)\n vbox.pack_start(entryBox, False)\n vbox.add(taskListView)\n\n\n rebaseLabel = gtk.Label('Hours should total')\n rebaseTime = gtk.Entry()\n rebaseButton = gtk.Button('Rebase')\n def rebaseAndShowTime(w,d):\n rt = float(rebaseTime.get_text()) * 60 * 60\n self.redisplayList(rt)\n\n rebaseButton.connect('clicked', rebaseAndShowTime, None)\n\n rebaseBox.add(rebaseLabel)\n rebaseBox.add(rebaseTime)\n rebaseBox.add(rebaseButton)\n\n vbox.pack_end(rebaseBox, False)\n\n if len(self.timestate.getTasks()):\n self.redisplayList()\n\n completion = gtk.EntryCompletion()\n completion.set_model(self.taskList)\n completion.set_text_column(0)\n taskName.set_completion(completion)\n\n window.add(vbox)\n window.show_all()\n \n def main(self):\n gtk.main()\n\n\nif __name__ == \"__main__\":\n tracker = TimeTracker()\n tracker.main()\n\n","sub_path":"TimeState.py","file_name":"TimeState.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"634417486","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\nimport evenimente.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Eveniment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nume', models.CharField(max_length=255)),\n ('full_name', models.CharField(max_length=1024, null=True, blank=True)),\n ('slug', models.SlugField()),\n ('data_inceput', models.DateTimeField()),\n ('data_sfarsit', models.DateTimeField()),\n ('facebook_event', models.URLField(null=True, blank=True)),\n ('url', models.URLField(null=True, blank=True)),\n ('header_a4', models.ImageField(null=True, upload_to=evenimente.models.upload_to_eveniment, blank=True)),\n ('header_a4_landscape', models.ImageField(null=True, upload_to=evenimente.models.upload_to_eveniment, blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EvenimentSettings',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('key', models.CharField(max_length=255)),\n ('value', models.CharField(max_length=255)),\n ('event', models.ForeignKey(to='evenimente.Eveniment')),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ResursaGrafica',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('image', models.ImageField(upload_to=evenimente.models.upload_to_resursagrafica)),\n ('slug', models.SlugField()),\n ('description', models.TextField(null=True, blank=True)),\n ('event', models.ForeignKey(to='evenimente.Eveniment')),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"evenimente/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141633723","text":"from django.shortcuts import render\nfrom .models import Product, Favorites\nfrom django.core.paginator import Paginator\n\n\ndef home(request):\n \"\"\"Function to display the home page template\"\"\"\n\n return render(request, 'food/home.html')\n\n\ndef search(request):\n \"\"\"Function to manage the search and its display\"\"\"\n\n research = request.GET['search']\n\n if not research:\n return render(request, 'food/home.html')\n\n query = Product.objects.filter(name__icontains=research)\n if query:\n categories = query[0].category.all()\n name = query[0].name\n image = query[0].image_url\n nutriscore = query[0].nutrition_grade_fr\n\n liste_prod = []\n for cat in categories:\n liste_prod = cat.product_set.filter(\n nutrition_grade_fr__lt=nutriscore\n ).order_by('nutrition_grade_fr')\n\n if not liste_prod:\n return render(\n request,\n 'food/nosubstitute.html',\n {'research': research, 'name': name, 'image': image}\n )\n\n else:\n query = None\n return render(request, 'food/noproduct.html', {'research': research})\n\n paginator = Paginator(liste_prod, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n return render(\n request,\n 'food/search.html',\n {\n 'research': research,\n 'name': name,\n 'image': image,\n 'search': page_obj\n }\n )\n\n\ndef show(request, id):\n \"\"\"Function to display the food specific information page\"\"\"\n\n article = Product.objects.get(id=id)\n return render(request, 'food/show.html', {'article': article})\n\n\ndef save(request):\n \"\"\"Function which allows the user to save a substitute in his database\"\"\"\n\n if request.method == \"POST\":\n current_user = request.user\n food = request.POST.get('elt')\n food_saved = Product.objects.get(id=food)\n Favorites.objects.get_or_create(\n user=current_user,\n substitute=food_saved\n )\n return render(request, 'food/home.html')\n\n\ndef legals(request):\n \"\"\"Function to display the legals template\"\"\"\n\n return render(request, 'food/legals.html')\n","sub_path":"pur_beurre/food/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"426631713","text":"import time\nimport unittest\n\nimport mock\nimport pytest\nimport redis\n\nfrom limits import RateLimitItemPerSecond, RateLimitItemPerMinute\nfrom limits.storage import RedisStorage, storage_from_string\nfrom limits.strategies import (\n FixedWindowRateLimiter, MovingWindowRateLimiter\n)\n\n\n@pytest.mark.unit\nclass SharedRedisTests(object):\n def test_fixed_window(self):\n limiter = FixedWindowRateLimiter(self.storage)\n per_second = RateLimitItemPerSecond(10)\n start = time.time()\n count = 0\n while time.time() - start < 0.5 and count < 10:\n self.assertTrue(limiter.hit(per_second))\n count += 1\n self.assertFalse(limiter.hit(per_second))\n while time.time() - start <= 1:\n time.sleep(0.1)\n [self.assertTrue(limiter.hit(per_second)) for _ in range(10)]\n\n def test_reset(self):\n limiter = FixedWindowRateLimiter(self.storage)\n for i in range(0, 10):\n rate = RateLimitItemPerMinute(i)\n limiter.hit(rate)\n self.assertEqual(self.storage.reset(), 10)\n\n def test_fixed_window_clear(self):\n limiter = FixedWindowRateLimiter(self.storage)\n per_min = RateLimitItemPerMinute(1)\n limiter.hit(per_min)\n self.assertFalse(limiter.hit(per_min))\n limiter.clear(per_min)\n self.assertTrue(limiter.hit(per_min))\n\n def test_moving_window_clear(self):\n limiter = MovingWindowRateLimiter(self.storage)\n per_min = RateLimitItemPerMinute(1)\n limiter.hit(per_min)\n self.assertFalse(limiter.hit(per_min))\n limiter.clear(per_min)\n self.assertTrue(limiter.hit(per_min))\n\n def test_moving_window_expiry(self):\n limiter = MovingWindowRateLimiter(self.storage)\n limit = RateLimitItemPerSecond(2)\n self.assertTrue(limiter.hit(limit))\n time.sleep(0.9)\n self.assertTrue(limiter.hit(limit))\n self.assertFalse(limiter.hit(limit))\n time.sleep(0.1)\n self.assertTrue(limiter.hit(limit))\n last = time.time()\n while time.time() - last <= 1:\n time.sleep(0.05)\n self.assertTrue(\n self.storage.storage.keys(\"%s/*\" % limit.namespace) == []\n )\n\n\n@pytest.mark.unit\nclass RedisStorageTests(SharedRedisTests, unittest.TestCase):\n def setUp(self):\n self.storage_url = \"redis://localhost:7379\"\n self.storage = RedisStorage(self.storage_url)\n redis.from_url(self.storage_url).flushall()\n\n def test_init_options(self):\n with mock.patch(\n \"limits.storage.redis.get_dependency\"\n ) as get_dependency:\n storage_from_string(self.storage_url, connection_timeout=1)\n self.assertEqual(\n get_dependency().from_url.call_args[1]['connection_timeout'], 1\n )\n\n\n@pytest.mark.unit\nclass RedisUnixSocketStorageTests(SharedRedisTests, unittest.TestCase):\n def setUp(self):\n self.storage_url = \"redis+unix:///tmp/limits.redis.sock\"\n self.storage = RedisStorage(self.storage_url)\n redis.from_url('unix:///tmp/limits.redis.sock').flushall()\n\n def test_init_options(self):\n with mock.patch(\n \"limits.storage.redis.get_dependency\"\n ) as get_dependency:\n storage_from_string(self.storage_url, connection_timeout=1)\n self.assertEqual(\n get_dependency().from_url.call_args[1]['connection_timeout'], 1\n )","sub_path":"tests/storage/test_redis.py","file_name":"test_redis.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"381425148","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.home),\n path('accounts/register/', views.register, name='register'),\n path('accounts/profile/user_leagues/', views.profile, name='user_leagues'),\n path('accounts/profile/user_details/', views.user_details, name='user_details'),\n path('terms_of_use/', views.terms_of_use, name='terms_of_use'),\n path('privacy_policy/', views.privacy_policy, name='privacy_policy'),\n path('cookies/', views.cookies, name='cookies'),\n path('paginate/', views.download_db, name='paginate')\n]\n","sub_path":"mrgit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"525741224","text":"## @package cs110graphics\n# @mainpage CS 110 Graphics\n# A Tkinter based graphics library for introductory computer science.\n#\n#

Usage

\n#
\n# All files that use the CS 110 Graphics package must have the following line\n# at the top of the file.\n# @code\n# from cs110graphics import *\n# @endcode\n# A simple implementation using the CS 110 Graphics package is shown below.\n# The shown code will create a window and add a rectangle. StartGraphicsSystem\n# must be used in all files to create the window and begin the main function.\n# @code\n# from cs110graphics import *\n#\n# def main(window):\n# rectangle = Rectangle(window)\n# window.add(rectangle)\n#\n# if __name__ == \"__main__\":\n# StartGraphicsSystem(main)\n# @endcode\n# @authors Paul Magnus '18\n# @authors Ines Ayara '20\n# @authors Matthew R. Jenkins '20\n# @version 1.2\n# @date Summer 2017\n\nfrom tkinter import * # for pretty much everything graphics related\nimport math # for rotate\nimport inspect\nfrom PIL import Image as image # for Image class\nfrom PIL import ImageTk as itk # for Image class\n\n## @file cs110graphics.py\n# The main cs110graphics file\n\n\n#-------------------------------------------------------------------------------\n#\n# Window\n#\n#-------------------------------------------------------------------------------\n\n## Window acts as a canvas which other objects can be put onto.\n#\n# The standard size of window created by StartGraphicsSystem is\n# width = 400, height = 400.\nclass Window:\n ## @param width - int - The width of the canvas\n # @param height - int - The height of the canvas\n # @param background - str - Background color of canvas. Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n # @param name - str - The title of the window\n # @param first_function - proc(Window) - (default: None) When the\n # window is created, it runs this function.\n # @param master - unkown type - (default: None) The parent widget.\n # @warning Unless you understand how Tkinter works do not change master\n def __init__(self, width, height, background, name, first_function=None,\n master=None):\n # type checking\n assert isinstance(width, int) and isinstance(height, int) and \\\n isinstance(background, str) and isinstance(name, str), \\\n \"Make sure width is an int, height is an int, background is a \" + \\\n \"string, and name is a string.\"\n # saving the given variables\n self._width = width\n self._height = height\n self._background = background\n self._name = name\n self._first_function = first_function\n # self._graphics contains a running tally of what objects are on the\n # canvas\n # [0] = depth, [1] = tag, [2] = object ID\n self._graphics = []\n # initalizing a frame and canvas using tkinter\n self._root = Tk()\n self._frame = Frame(master)\n self._frame.pack()\n self._canvas = Canvas(self._frame)\n self._canvas.pack()\n self._canvas.focus_set()\n # using our built in functions to set height, width, and background\n self.set_height(height)\n self.set_width(width)\n self.set_title(name)\n self.set_background(background)\n # running first function\n self._first_function(self)\n\n ## Adds an object to the Window.\n # @param graphic - GraphicalObject\n def add(self, graphic):\n # type checking\n assert isinstance(graphic, GraphicalObject), \\\n \"Make sure graphic is a GraphicalObject.\"\n # deferring to each object since each object requires a different\n # method of construction\n graphic._add_to()\n\n ## Removes an object from the Window object, assuming\n # the object being deleted exists.\n # @param graphic - GraphicalObject\n def remove(self, graphic):\n # type checking and making sure the object is in the list\n assert isinstance(graphic, GraphicalObject) and \\\n [graphic._depth, graphic._tag, graphic] in self._graphics, \\\n \"Make sure graphic is a GraphicalObject and the graphic has \" + \\\n \"been added to the board.\"\n # removes from the window, then the list, then sets the tag to None and\n # disables the object (for readding later)\n graphic._remove_from(self)\n self._graphics.remove([graphic._depth, graphic._tag, graphic])\n graphic._tag = None\n graphic._enabled = False\n\n ## Returns the height of the window as an integer.\n # @return height - int\n def get_height(self):\n return self._height\n\n ## Returns the width of the window as an integer.\n # @return width - int\n def get_width(self):\n return self._width\n\n ## Sets the background color of the canvas.\n # @param background - string - Background color of canvas. Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n def set_background(self, background):\n # type checking\n assert isinstance(background, str), \\\n \"Make sure the background color is a string.\"\n self._background = background\n self._canvas.configure(bg=background)\n\n ## Sets the height of the canvas.\n # @param height - int\n def set_height(self, height):\n # type checking\n assert isinstance(height, int), \\\n \"Make sure the height is an int.\"\n self._height = height\n self._canvas.configure(height=height)\n\n ## Sets the title of the window holding the canvas.\n # @param name - string\n def set_title(self, name):\n # type checking\n assert isinstance(name, str), \\\n \"Make sure the window title is a string.\"\n self._name = name\n self._root.title(name)\n\n ## Sets the width of the canvas.\n # @param width - height\n def set_width(self, width):\n # type checking\n assert isinstance(width, int), \\\n \"Make sure the width is an int.\"\n self._width = width\n self._canvas.configure(width=width)\n\n # Whenever an object is updated through external functions, its tag is\n # overwritten. This function goes into self._graphics and replaces the old\n # tag with a newer one, as well as replacing its depth with a newer one.\n def _update_tag(self, graphic):\n # goes through every item in self._graphics, then saves the object's\n # tag and depth if it's found\n for item in self._graphics:\n if item[2] == graphic:\n item[1] = graphic._tag\n item[0] = graphic._depth\n\n\n#-------------------------------------------------------------------------------\n#\n# StartGraphicsSystem\n#\n#-------------------------------------------------------------------------------\n \n## This initalizes the graphics system.\n# @param first_function - func\n# @param width - int - (default: 400)\n# @param height - int - (default: 400)\n# @param background - string - (default: \"white\")\n# Background color of canvas. Can be either the\n# name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n# @param name - string - (default: \"Graphics Window\")\n# The title of the window\ndef StartGraphicsSystem(first_function, width=400, height=400,\n background=\"white\", name=\"Graphics Window\"):\n # creates a window with each parameter\n win = Window(width, height, background, name, first_function)\n # this emulates a mainloop tkinter instance, and allows for quieter\n # exception handling. it still won't handle tk.afters too well. TODO\n try:\n while True:\n win._canvas.update()\n win._canvas.after(200)\n except TclError:\n pass\n\n\n#-------------------------------------------------------------------------------\n#\n# Event\n#\n#-------------------------------------------------------------------------------\n \n## An object representing an action from the user. Used by EventHandler objects.\n# User actions that create Event objects include:\n# - Pressing/Releasing a key on the keyboard\n# - Pressing/Releasing a button on the mouse while on a GraphicalObject with an\n# event handler\n# - Moving the mouse while on a GraphicalObject with an event handler\n#\n# Each of these actions will call their corresponding methods in EventHandler\n# automatically and give an instance of Event to the method called.\nclass Event:\n \n def __init__(self, event):\n # converting each necessary tkinter event parameter to something easier\n # to get access to and easier to understand\n self._type = event.type\n self._location = (event.x, event.y)\n self._rootLocation = (event.x_root, event.y_root)\n self._keysym = event.keysym\n self._num = event.num\n\n ## Returns the mouse button that is attached to the event. Returns\n # None if\n # the button fails to exist (like if the Event handles a key press).\n # @return button - str\n #\n # Possible returns are:\n # - \"Left Mouse Button\"\n # - \"Right Mouse Button\"\n # - \"Middle Mouse Button\"\n # - None\n def get_button(self):\n # this is mostly to handle user stupidity - why would you put\n # get_button in a handle_key function if get_key exists?\n if self._num == \"??\":\n return None\n # dictionary to translate each number to a string\n numTranslation = {\n 1: \"Left Mouse Button\",\n 2: \"Middle Mouse Button\",\n 3: \"Right Mouse Button\"\n }\n return numTranslation[self._num]\n\n ## Returns the description of the event.\n # @return description - str\n #\n # Possible returns are:\n # - \"Key Press\"\n # - \"Key Release\"\n # - \"Mouse Press\"\n # - \"Mouse Release\"\n # - \"Mouse Move\"\n # - \"Mouse Enter\"\n # - \"Mouse Leave\"\n def get_description(self):\n # dictionary to translate each number to a string\n descriptionTranslation = {\n '2': \"Key Press\",\n '3': \"Key Release\",\n '4': \"Mouse Press\",\n '5': \"Mouse Release\",\n '6': \"Mouse Move\",\n '7': \"Mouse Enter\",\n '8': \"Mouse Leave\",\n }\n return descriptionTranslation[self._type]\n\n ## Returns the keyboard key that is attached to the event. Returns None if\n # the key fails to exist (like if the Event handles a mouse press).\n # @return key - str\n #\n # Most keys will evaluate to a single character (eg. pressing the a-key will\n # result in \"a\" while pressing shift-a will result in \"A\").\n def get_key(self):\n # this is mostly to handle user stupidity - why would you put\n # get_key in a handle_mouse function if get_button exists?\n if self._keysym == \"??\":\n return None\n return self._keysym\n\n ## Returns a tuple of the x and y coordinates of the mouse\n # location in the canvas.\n # @return location - tuple of (int * int) - (e.g. (200, 200))\n def get_mouse_location(self):\n return self._location\n\n ## Returns a tuple of the x and y coordinates of the mouse location in the\n # window. Typically using get_mouse_location is more applicable.\n # @return location - tuple of (int * int) - (e.g. (200, 200))\n def get_root_mouse_location(self):\n return self._rootLocation\n\n\n#-------------------------------------------------------------------------------\n#\n# EventHandler\n#\n#-------------------------------------------------------------------------------\n\n## The EventHandler class should be extended by any class that reacts to user\n# input in the form of some action with the computer mouse or the keyboard.\n# Each method inherited from the EventHandler class takes an Event object as\n# a parameter. The methods available to Event can be useful for interpreting\n# how a call to each method should be handled. For example usage of\n# event.get_key() can be used to destinguish between the keys used in navigating\n# a character in a game.\n#\n# A sample program using the EventHandler is shown below.\n# @code\n# from cs110graphics import *\n#\n# class Bot(EventHandler):\n# \"\"\" A bot made up of a square that detects interaction from the user. \"\"\"\n#\n# def __init__(self, window):\n# \"\"\" Creates the bot which is comprised of one square and adds the Bot\n# as the event handler for the square body. \"\"\"\n# self._window = window\n#\n# # create the body of the Bot and add this class\n# # as the handler\n# self._body = Square(window)\n# self._body.add_handler(self)\n#\n# def add_to_window(self):\n# \"\"\" This method adds the graphical representation of the bot\n# to the window. \"\"\"\n# self._window.add(self._body)\n#\n# ##########################################################################\n# # Event handling methods \n# ##########################################################################\n#\n# def handle_key_press(self, event):\n# \"\"\" Prints what key was pressed. This is called whenever a key is\n# pressed regardless of the mouse position. \"\"\"\n# print(event.get_key(), \"was pressed\")\n#\n# def handle_key_release(self, event):\n# \"\"\" Prints what key was released. This is called whenever a key is\n# pressed regardless of the mouse position. \"\"\"\n# print(event.get_key(), \"was released\")\n#\n# def handle_mouse_enter(self, event):\n# \"\"\" Prints where the mouse entered the Bot. \"\"\"\n# print(\"The mouse entered the bot at\", event.get_mouse_location())\n#\n# def handle_mouse_leave(self, event):\n# \"\"\" Prints where the mouse left the Bot. \"\"\"\n# print(\"The mouse left the bot at\", event.get_mouse_location())\n#\n# def handle_mouse_move(self, event):\n# \"\"\" Prints when the mouse moves while on the Bot. \"\"\"\n# print(\"The mouse moved to\", event.get_mouse_location())\n#\n# def handle_mouse_press(self, event):\n# \"\"\" Prints where the mouse was pressed while on the Bot. \"\"\"\n# print(\"The mouse was pressed at\", event.get_mouse_location())\n#\n# def handle_mouse_release(self, event):\n# \"\"\" Prints where the mouse was released while on the Bot. \"\"\"\n# print(\"The mouse was released at\", event.get_mouse_location())\n#\n# def main(window):\n# bot = Bot(window)\n# bot.add_to_window()\n#\n# if __name__ == \"__main__\":\n# StartGraphicsSystem(main)\n# @endcode\nclass EventHandler:\n def __init__(self):\n pass\n \n ## Handles a key press.\n # This function will be called whenever a key is pressed while the window is\n # active. The event parameter can be used to determine which key was\n # pressed. For example:\n # @code\n # class Handler(EventHandler):\n # def handle_key_press(self, event):\n # if \"a\" == event.get_key():\n # # do something when a is pressed...\n # else:\n # # do something else...\n # @endcode\n # @param event - Event - the event that occurred\n def handle_key_press(self, event):\n pass\n\n ## Handles a key release.\n # This method will be called whenever a key is released while the window is\n # active. The event parameter can be used to determine which key was\n # pressed. For example:\n # @code\n # class Handler(EventHandler):\n # def handle_key_release(self, event):\n # if \"a\" == event.get_key():\n # # do something when a is released...\n # else:\n # # do something else...\n # @endcode\n # @param event - Event - the event that occurred\n def handle_key_release(self, event):\n pass\n\n ## Handles when a mouse enters an object.\n # This is called by the system when the mouse enters the GraphicalObject\n # that this handler is an event handler for. The event parameter can be used\n # to determine the location at which the mouse entered the object.\n # @code\n # class Handler(EventHandler):\n # def handle_mouse_enter(self, event):\n # mouse_location = event.get_mouse_location()\n # @endcode\n # @param event - Event - the event that occurred\n def handle_mouse_enter(self, event):\n pass\n\n ## Handles when a mouse leaves an object.\n # This is called by the system when the mouse leaves the GraphicalObject\n # that this handler is an event handler for. The event parameter can be used\n # to determine the location at which the mouse left the object.\n # @code\n # class Handler(EventHandler):\n # def handle_mouse_leave(self, event):\n # mouse_location = event.get_mouse_location()\n # @endcode\n # @param event - Event - the event that occurred\n def handle_mouse_leave(self, event):\n pass\n\n ## Handles a mouse move.\n # This is called by the system when the mouse moves within the\n # GraphicalObject that this handler is an event handler for. The event\n # parameter can be used to determine the location that the mouse moved to.\n # @code\n # class Handler(EventHandler):\n # def handle_mouse_move(self, event):\n # mouse_location = event.get_mouse_location()\n # @endcode\n # @param event - Event - the event that occurred\n def handle_mouse_move(self, event):\n pass\n\n ## Handles a mouse press.\n # This is called by the system when a mouse button is pressed while the\n # mouse is on the GraphicalObject that this handler is an event handler for.\n # The event parameter can be used to determine the location at which the\n # mouse button was pressed and which mouse button was pressed.\n # @code\n # class Handler(EventHandler):\n # def handle_mouse_press(self, event):\n # mouse_location = event.get_mouse_location()\n # mouse_button = event.get_button()\n # @endcode\n # @param event - Event - the event that occurred\n def handle_mouse_press(self, event):\n pass\n\n ## Handles a mouse release.\n # This is called by the system when a mouse button is released while the\n # mouse is on the GraphicalObject that this handler is an event handler for.\n # The event parameter can be used to determine the location at which the\n # mouse button was released and which mouse button was released.\n # @code\n # class Handler(EventHandler):\n # def handle_mouse_release(self, event):\n # mouse_location = event.get_mouse_location()\n # mouse_button = event.get_button()\n # @endcode\n # @param event - Event - the event that occurred\n def handle_mouse_release(self, event):\n pass\n\n\n# \"Overwrites\" the event handler and calls an external EventHandler.\ndef _call_handler(handler, event):\n # checks if argument count is > 1 and then appends the event to the handler\n # if it is\n arg_count = len(inspect.getargs(handler.__code__)[0])\n if arg_count == 1:\n handler()\n else:\n handler(event)\n\n\n#-------------------------------------------------------------------------------\n#\n# GraphicalObject\n#\n#-------------------------------------------------------------------------------\n\n## This is a parent class of any object which can be put into Window. No\n# constructor exists in this class, but its methods are used by other objects\n# that extend/inherit this class.\n#\n# Default values:\n# - depth = 50\n# - center = (200, 200)\nclass GraphicalObject:\n def __init__(self):\n self._depth = 50\n self._center = (200, 200)\n self._has_handlers = False\n\n ## Adds a handler to the graphical object.\n # @param handler_object - EventHandler - the object that handles\n # the events for this GraphicalObject\n def add_handler(self, handler_object):\n def key_press(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_key_press, tkEvent)\n\n def key_release(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_key_release, tkEvent)\n\n def mouse_enter(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_mouse_enter, tkEvent)\n\n def mouse_leave(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_mouse_leave, tkEvent)\n\n def mouse_move(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_mouse_move, tkEvent)\n\n def mouse_press(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_mouse_press, tkEvent)\n\n def mouse_release(event):\n tkEvent = Event(event)\n _call_handler(handler_object.handle_mouse_release, tkEvent)\n\n # this is to enable readding handlers after each object's tag is\n # changed\n self._parent_object = handler_object\n self._has_handlers = True\n # the duplicates are necessary to allow support for multiple mouse\n # buttons\n types = [\"\", \"\", \"\", \"\",\n \"\", \"\", \"\", \"\",\n \"\", \"\", \"\"]\n funcs = [key_press, key_release, mouse_enter, mouse_leave, mouse_move,\n mouse_press, mouse_press, mouse_press,\n mouse_release, mouse_release, mouse_release]\n # goes through each bind and binds it to canvas if it's a key based\n # object and binds it to the graphical object if it's not a key based\n # object\n for i in range(len(types)):\n if \"Key\" in types[i]:\n self._window._canvas.bind(types[i], funcs[i])\n else:\n self._window._canvas.tag_bind(self._tag, types[i], funcs[i])\n\n ## Returns the center of the object.\n # @return center - tuple\n def get_center(self):\n return self._center\n\n ## Returns the depth of the object.\n # @return depth - int\n def get_depth(self):\n return self._depth\n\n ## Moves the object dx pixels horizontally and dy pixels vertically.\n # @param dx - int\n # @param dy - int\n def move(self, dx, dy):\n # type checking\n assert isinstance(dx, int) and isinstance(dy, int), \\\n \"Make sure dx and dy are both ints.\"\n self._center = (self._center[0] + dx, self._center[1] + dy)\n # goes through each point and increments it by dx or dy depending if\n # its index is even or odd\n for i in range(len(self._points)):\n self._points[i] = (self._points[i][0] + dx,\n self._points[i][1] + dy)\n self._refresh()\n\n ## Moves a graphical object to a point.\n # @param point - tuple of (int * int)\n def move_to(self, point):\n # type checking\n assert isinstance(point, tuple) and len(point) == 2 and \\\n isinstance(point[0], int) and isinstance(point[1], int), \\\n \"Make sure point is a tuple of (int * int).\"\n difference = (self._center[0] - point[0], self._center[1] - point[1])\n self._center = point\n # goes through each point and increments it by dx or dy depending if\n # its index is even or odd\n for i in range(len(self._points)):\n self._points[i] = (self._points[i][0] - difference[0],\n self._points[i][1] - difference[1])\n self._refresh()\n\n # Removes and adds an object after it's been changed.\n def _refresh(self):\n # since this is run for every object we need a special case if the\n # object is a graphical object and not a fillable\n # in that case, we remove it and readd it without using any canvas\n # operators, add handlers if they exist, and return\n if isinstance(self, Text) or isinstance(self, Image):\n self._remove_from(self._window)\n self._add_to()\n self._window._update_tag(self)\n if self._has_handlers:\n self.add_handler(self._parent_object)\n else:\n # from here on out we're assuming fillables only.\n # we remove the object from the window, and then if the object is\n # disabled we readd it with the HIDDEN state, otherwise just readd\n # it\n self._remove_from(self._window)\n if self._enabled is False:\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n else:\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color()\n )\n # we then update the tag, and then readd handlers if they exist\n # if we don't then the event will only run once and then not again\n self._window._update_tag(self)\n if self._has_handlers:\n self.add_handler(self._parent_object)\n\n ## Removes a graphical object from the canvas.\n def _remove_from(self, window):\n window._canvas.delete(self._tag)\n\n ## Sets the depth of the GraphicalObject.\n # @param depth - int\n def set_depth(self, depth):\n # type checking\n assert isinstance(depth, int), \\\n \"Make sure depth is an int.\"\n self._depth = depth\n self._window._update_tag(self)\n self._window._graphics.sort()\n # get rid of all objects and readd them in depth order\n for graphic in reversed(self._window._graphics):\n graphic[2]._refresh()\n\n\n#-------------------------------------------------------------------------------\n#\n# Fillable\n#\n#-------------------------------------------------------------------------------\n\n## This is a parent class of any object which can have its colors\n# modified. No constructor exists in this class, but its methods are used by\n# other objects that extend/inherit this class.\n#\n# Default values:\n# - border color = \"black\"\n# - border width = 2\n# - fill color = \"white\"\n# - pivot = center\nclass Fillable(GraphicalObject):\n def __init__(self):\n GraphicalObject.__init__(self)\n # default values - otherwise when an object is changed later it reverts\n # any changes that were made\n self._border_color = \"black\"\n self._border_width = 2\n self._fill_color = \"white\"\n self._pivot = self._center\n\n ## Returns the border color.\n # @return border_color - str - Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n def get_border_color(self):\n return self._border_color\n\n ## Returns the border width.\n # @return border_width - int\n def get_border_width(self):\n return self._border_width\n\n ## Returns fill color.\n # @return color - int - Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n def get_fill_color(self):\n return self._fill_color\n\n ## Returns the pivot point.\n # @return pivot - tuple (int * int)\n def get_pivot(self):\n return self._pivot\n\n ## Rotates the object.\n # @param degrees - int\n def rotate(self, degrees):\n # type checking\n # print(\"DEBUG: before rotate: \" + str(self._center))\n assert isinstance(degrees, int), \\\n \"Make sure degrees is an int.\"\n # calculates radians, runs _rotate_helper, moves back to its center and\n # refreshes\n radians = (math.pi / 180) * degrees\n for i in range(len(self._points)):\n self._points[i] = _rotate_helper(self._points[i],\n radians,\n self._pivot)\n # print(\"DEBUG: after rotate: \" + str(self._center))\n self.move_to(self._center)\n self._refresh()\n\n ## Scales the object up or down depending on the factor.\n # @param factor - float\n def scale(self, factor):\n # type checking\n assert isinstance(factor, float), \\\n \"Make sure the scale factor is a float.\"\n # saves the center, moves the object to the origin, modifies every\n # point so it's scaled, moves it back to the center and refreshes\n temp_center = self._center\n self.move_to((0, 0))\n for i in range(len(self._points)):\n temp_tuple = (int(self._points[i][0] * factor),\n int(self._points[i][1] * factor))\n self._points[i] = temp_tuple\n self._pivot = (round(self._pivot[0] * factor),\n round(self._pivot[1] * factor))\n self.move_to(temp_center)\n self._center = temp_center\n self._refresh()\n\n def move(self, dx, dy):\n GraphicalObject.move(self, dx, dy)\n\n # update pivot\n self._pivot = (self._pivot[0] + dx, self._pivot[1] + dy)\n\n def move_to(self, point):\n difference = (self._pivot[0] - self._center[0],\n self._pivot[1] - self._center[1])\n \n GraphicalObject.move_to(self, point)\n\n self._pivot = (self._center[0] + difference[0],\n self._center[1] + difference[1])\n\n ## Sets the border color.\n # @param color - string - Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n def set_border_color(self, color):\n # type checking\n assert isinstance(color, str), \\\n \"Make sure the border color is a string.\"\n self._border_color = color\n self._window._canvas.itemconfigure(self._tag, outline=color)\n\n ## Sets the border width.\n # @param width - int\n def set_border_width(self, width):\n # type checking\n assert isinstance(width, int), \\\n \"Make sure the border width is an int.\"\n self._border_width = width\n self._window._canvas.itemconfigure(self._tag, width=width)\n\n ## Sets the fill color.\n # @param color - string - Can be either the\n # name of a color (\"yellow\"), or a hex code (\"#FFFF00\")\n def set_fill_color(self, color):\n # type checking\n assert isinstance(color, str), \\\n \"Make sure the fill color is a string.\"\n self._fill_color = color\n self._window._canvas.itemconfigure(self._tag, fill=color)\n\n ## Sets the pivot point.\n # @param pivot - tuple of (int * int)\n def set_pivot(self, pivot):\n # type checking\n assert isinstance(pivot, tuple) and len(pivot) == 2 and \\\n isinstance(pivot[0], int) and isinstance(pivot[1], int), \\\n \"Make sure the pivot is a tuple of (int * int).\"\n self._pivot = pivot\n\n\n# Aids in rotation.\ndef _rotate_helper(point, angle, pivot):\n # type checking\n # print(\"DEBUG: point = \" + str(point) + \", angle = \" + str(angle) + \", pivot = \" + str(pivot))\n assert isinstance(point, tuple) and len(point) == 2 and \\\n isinstance(angle, float) and isinstance(pivot, tuple) and \\\n len(pivot) == 2 and isinstance(point[0], int) and \\\n isinstance(point[1], int) and isinstance(pivot[0], int) and \\\n isinstance(pivot[1], int), \\\n \"Make sure point is a tuple of (int * int), angle is a float, \" + \\\n \"and pivot is a tuple of (int * int).\"\n point = (point[0] - pivot[0], point[1] - pivot[1])\n newX = round(point[0] * math.cos(angle) + point[1] * math.sin(angle))\n newY = round(point[1] * math.cos(angle) - point[0] * math.sin(angle))\n return (newX + pivot[0], newY + pivot[1])\n\n\n#-------------------------------------------------------------------------------\n#\n# Image\n#\n#-------------------------------------------------------------------------------\n\n## An image, which can be added to a Window object.\nclass Image(GraphicalObject):\n ## @param window - Window - the window which the object will be added to\n # @param image_loc - str- The file location for an image, see below for\n # instructions regarding file locations\n # @param width - int - (default: 100) the width of the image\n # @param height - int - (default: 100) the height of the image\n # @param center - tuple of (int * int) - (default: (200, 200)) the\n # center location for the image\n #\n # File locations:\n # - If a file is in the same folder/directory as the program, just use the\n # name of the file\n # - Otherwise use a file path: eg. \"~/110/bots/images/bot.jpg\" or\n # \"./images/bot.jpg\"\n #\n # Note that \".\" represents the current directory and \"..\" represents the\n # parent directory.\n def __init__(self, window, image_loc, width=100, height=100,\n center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and image_loc is not \"\" \\\n and isinstance(width, int) and isinstance(height, int) \\\n and isinstance(center, tuple) and len(center) == 2 and \\\n isinstance(center[0], int) and isinstance(center[1], int), \\\n \"Make sure window is a Window, image location is not blank, \" + \\\n \"width is an int, height is an int, and center is a tuple of \" + \\\n \"(int * int).\"\n # setting up inheritance\n GraphicalObject.__init__(self)\n # saving variables\n self._window = window\n self._image_loc = \"./\" + image_loc\n self._center = center\n self._width = width\n self._height = height\n # necessary for rotation - it's handled differently than the default\n # rotate function\n self._angle = 0\n # generating image based on image location\n self._img = _image_gen(self._image_loc, self._width, self._height)\n # creating object as hidden and adding it to window._graphics\n self._enabled = False\n self._tag = self._window._canvas.create_image(self._center[0],\n self._center[1],\n image=self._img,\n state=HIDDEN)\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._tag = self._window._canvas.create_image(self._center[0],\n self._center[1],\n image=self._img)\n self._enabled = True\n\n self._window._update_tag(self)\n\n def move(self, dx, dy):\n # type checking\n assert isinstance(dx, int) and isinstance(dy, int), \\\n \"Make sure dx and dy are both ints.\"\n self._center = (self._center[0] + dx, self._center[1] + dy)\n self._remove_from(self._window)\n self._img = _image_gen(self._image_loc, self._width, self._height)\n self._refresh()\n\n def move_to(self, point):\n # type checking\n assert isinstance(point, tuple) and len(point) == 2 and \\\n isinstance(point[0], int) and isinstance(point[1], int), \\\n \"Make sure point is a tuple of (int * int).\"\n self._center = point\n self._remove_from(self._window)\n self._img = _image_gen(self._image_loc, self._width, self._height)\n self._refresh()\n\n ## Resizes the Image.\n # @param width - int\n # @param height - int\n def resize(self, width, height):\n # type checking\n assert isinstance(width, int) and isinstance(height, int), \\\n \"Make sure width and height are both ints.\"\n self._width = width\n self._height = height\n # depending on if the object is rotated or not, it will either be\n # re-rotated at whatever self._angle is, or it will be removed and\n # readded\n if self._angle != 0:\n self.rotate(0)\n else:\n self._remove_from(self._window)\n self._img = _image_gen(self._image_loc, width, height)\n self._refresh()\n\n ## Rotates an object.\n # @param degrees - int\n def rotate(self, degrees):\n # type checking\n assert isinstance(degrees, int), \\\n \"Make sure degrees is an int.\"\n # adds degrees to angle, checks whether angle >= 360 and modulos it if\n # it is\n self._angle += degrees\n if self._angle >= 360:\n self._angle = self._angle % 360\n # removes object from window, converts it to a format which can be\n # rotated, resizes it, then rotates it, makes a photo image,\n # and refreshes it\n # this needs a special version of _image_gen since we're handling\n # rotation. _image_gen doesn't handle rotation.\n self._remove_from(self._window)\n img_temp = image.open(self._image_loc)\n img_temp = img_temp.convert('RGBA')\n img_temp = img_temp.resize((self._width, self._height),\n image.ANTIALIAS)\n img_temp = img_temp.rotate(self._angle)\n self._img = itk.PhotoImage(img_temp)\n self._refresh()\n\n ## Scales the image according to the factor.\n # @param factor - float\n def scale(self, factor):\n # type checking\n assert isinstance(factor, float), \\\n \"Make sure the scale factor is a float.\"\n self._width = int(self._width * factor)\n self._height = int(self._height * factor)\n # depending on whether the object is rotated, resize or rotate is run\n # with the new width and height values saved\n if self._angle != 0:\n self.rotate(self._angle)\n else:\n self.resize(self._width, self._height)\n\n ## Returns a tuple of the width and height of the image.\n # @return size - tuple of (int * int)\n def size(self):\n return (self._width, self._height)\n\n\n# Creates a resized image and returns an image of type itk.PhotoImage.\ndef _image_gen(image_loc, width, height):\n # opens and resizes an object based on the width and height\n img_temp = image.open(image_loc)\n img_temp = img_temp.resize((width, height), image.ANTIALIAS)\n return itk.PhotoImage(img_temp)\n\n\n#-------------------------------------------------------------------------------\n#\n# Text\n#\n#-------------------------------------------------------------------------------\n\n## Text which can be added to a Window object.\nclass Text(GraphicalObject):\n ## @param window - Window - the window which the object will be added to\n # @param text - str - The text which is displayed\n # @param size - int - (default: 12) sets the size of the text\n # @param center - tuple of int * int - (default: (200, 200))\n # sets the center of the Image\n def __init__(self, window, text, size=12, center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and isinstance(size, int) \\\n and isinstance(center, tuple) and len(center) == 2 and \\\n isinstance(center[0], int) and isinstance(center[1], int), \\\n \"Make sure the window is a Window, the size is an int, and \" + \\\n \"the center is a tuple of (int * int).\"\n # for inheritance\n GraphicalObject.__init__(self)\n # setting variables, creating object and adding it to window._graphics\n self._window = window\n self._text = text\n self._center = center\n self._size = size\n self._enabled = False\n self._tag = self._window._canvas.create_text(self._center[0],\n self._center[1],\n text=str(self._text),\n font=(\"Helvetica\",\n self._size),\n state=HIDDEN)\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._tag = self._window._canvas.create_text(self._center[0],\n self._center[1],\n text=str(self._text),\n font=(\"Helvetica\",\n self._size))\n self._enabled = True\n\n self._window._update_tag(self)\n\n def move(self, dx, dy):\n # type checking\n assert isinstance(dx, int) and isinstance(dy, int), \\\n \"Make sure dx and dy are both ints.\"\n self._center = (self._center[0] + dx, self._center[1] + dy)\n # text is special because it does not need to be recreated after each\n # modification\n self._window._canvas.coords(self._tag,\n (self._center[0], self._center[1]))\n\n def move_to(self, point):\n assert isinstance(point, tuple) and len(point) == 2 and \\\n isinstance(point[0], int) and isinstance(point[1], int), \\\n \"Make sure point is a tuple of (int * int).\"\n self._center = point\n # text is special because it does not need to be recreated after each\n # modification\n self._window._canvas.coords(self._tag,\n self._center[0],\n self._center[1])\n\n ## Sets the point size of the text.\n # @param size - int\n def set_size(self, size):\n assert isinstance(size, int), \\\n \"Make sure size is an int.\"\n self._size = size\n # text is special because it does not need to be recreated after each\n # modification\n self._window._canvas.itemconfigure(self._tag, font=(\"Helvetica\",\n self._size))\n\n ## Sets the text.\n # @param text - str\n def set_text(self, text):\n assert isinstance(text, str), \\\n \"Make sure text is a string.\"\n self._text = text\n # text is special because it does not need to be recreated after each\n # modification\n self._window._canvas.itemconfigure(self._tag, text=self._text)\n\n \n#-------------------------------------------------------------------------------\n#\n# Polygon\n#\n#-------------------------------------------------------------------------------\n\n## A Polygon, which can be added to a Window object.\nclass Polygon(Fillable):\n ## @param window - Window - the window which the object will be added to\n # @param points - list of tuples of (int * int) - each tuple corresponds\n # to an x-y point\n def __init__(self, window, points):\n # type checking\n assert isinstance(window, Window) and isinstance(points, list), \\\n \"Make sure window is a Window and points is a list of tuples \" + \\\n \"of (int * int).\"\n # checking whether each point in the list of points is a tuple of\n # length 2\n for point in points:\n if len(point) is not 2 or type(point[0]) != int or \\\n type(point[1]) != int:\n raise AssertionError(\"One of the points in your polygon \" +\n \"does not have a length of two.\" +\n \"Make sure every tuple in your list \" +\n \"has a length of two.\")\n # establishing inheritance\n Fillable.__init__(self)\n # setting all variables, creating object, and adding it to\n # window._graphics\n self._window = window\n self._points = points\n self._center = _list_average(self._points)\n self._pivot = self._center\n self._enabled = False\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._window._canvas.itemconfigure(self._tag, state=NORMAL)\n self._enabled = True\n\n\n# Averages each x value and each y value in the list and returns it.\ndef _list_average(points):\n # this is used to gauge the center from all of the given points of the\n # polygon\n # the points are turned into a list of ints, then each even one is put into\n # its own list and each odd one is put into its own list and then both are\n # summed, divided, and put into a tuple and returned\n points = [i[j] for i in points for j in range(len(i))]\n pointsX = points[0:len(points):2]\n pointsY = points[1:len(points):2]\n return (int(sum(pointsX) / len(pointsX)),\n int(sum(pointsY) / len(pointsY)))\n\n\n#-------------------------------------------------------------------------------\n#\n# Circle\n#\n#-------------------------------------------------------------------------------\n\n## A circle, which can be added to a Window object.\nclass Circle(Fillable):\n ## @param window - Window - the window which the object will be added to\n # @param radius - int - (default: 40) the radius of the circle\n # @param center - tuple of (int * int) - (default: (200, 200))\n # sets the center of the circle\n def __init__(self, window, radius=40, center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and isinstance(radius, int) \\\n and isinstance(center, tuple) and len(center) == 2 and \\\n isinstance(center[0], int) and isinstance(center[1], int), \\\n \"Make sure window is a window, radius is an int, and center \" + \\\n \"is a tuple of (int * int).\"\n # setting inheritance\n Fillable.__init__(self)\n # setting variables\n self._window = window\n self._width = radius\n self._height = radius\n self._center = center\n # these are necessary for _circle_gen\n self._top_left = (self._center[0] - self._width,\n self._center[1] - self._height)\n self._bottom_right = (self._center[0] + self._width,\n self._center[1] + self._height)\n\n # creating the circle, adding it to the window and then adding it to\n # window._graphics\n self._points = []\n self._circle_gen()\n self._enabled = False\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._window._canvas.itemconfigure(self._tag, state=NORMAL)\n self._enabled = True\n\n # Generates a circle.\n def _circle_gen(self):\n # generates the x axis and y axis of the object\n xAxis = round(self._bottom_right[0] - self._top_left[0]) / 2\n yAxis = round(self._bottom_right[1] - self._top_left[1]) / 2\n\n # 200 can be anything but I thought it was a good mix between precise\n # and efficient\n for i in range(200):\n # generates angle, calculates x and y using some trig i don't know.\n # this is probably the only time i'm going to say this, but if you\n # want to understand how this works, email pmagnus@hamilton.edu\n theta = (math.pi * 2) * float(i) / 200\n x1 = xAxis * math.cos(theta)\n y1 = yAxis * math.sin(theta)\n x = round((x1 * math.cos(0)) + (y1 * math.sin(0)))\n y = round((y1 * math.cos(0)) - (x1 * math.sin(0)))\n self._points.append((x + self._center[0], y + self._center[1]))\n\n ## Sets the radius of the Circle.\n # @param radius - int\n def set_radius(self, radius):\n # type checking\n assert isinstance(radius, int), \\\n \"Make sure radius is an int.\"\n self._width = radius\n self._height = radius\n self._top_left = (self._center[0] - self._width,\n self._center[1] - self._height)\n self._bottom_right = (self._center[0] + self._width,\n self._center[1] + self._height)\n # redraws circle\n self._points = []\n self._circle_gen()\n self._refresh()\n\n \n#-------------------------------------------------------------------------------\n#\n# Oval\n#\n#-------------------------------------------------------------------------------\n\n## An oval, which can be added to a Window object.\nclass Oval(Fillable):\n ## @param window - Window - the window which the object will be added to\n # @param radiusX - int - (default: 40) the radius in the x-direction\n # @param radiusY - int - (default: 60) the radius in the y-direction\n # @param center - tuple of (int * int) - (default: (200, 200))\n # the center of the oval\n def __init__(self, window, radiusX=40, radiusY=60, center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and isinstance(radiusX, int) \\\n and isinstance(radiusY, int) and isinstance(center, tuple) \\\n and len(center) == 2 and isinstance(center[0], int) and \\\n isinstance(center[1], int), \\\n \"Make sure window is a window, radiusX and radiusY are both \" + \\\n \"ints, and center is a tuple of (int * int).\"\n # setting inheritance\n Fillable.__init__(self)\n # setting variables\n self._window = window\n self._width = radiusX\n self._height = radiusY\n self._center = center\n # this is necessary for _circle_gen\n self._top_left = (self._center[0] - self._width,\n self._center[1] - self._height)\n self._bottom_right = (self._center[0] + self._width,\n self._center[1] + self._height)\n # creating points, then adding it to canvas and window._graphics\n self._points = []\n self._circle_gen()\n self._enabled = False\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._window._canvas.itemconfigure(self._tag, state=NORMAL)\n self._enabled = True\n\n # Generates a circle.\n def _circle_gen(self):\n # generates the x axis and y axis of the object\n xAxis = round(self._bottom_right[0] - self._top_left[0]) / 2\n yAxis = round(self._bottom_right[1] - self._top_left[1]) / 2\n\n # 200 can be anything but I thought it was a good mix between precise\n # and efficient\n for i in range(200):\n # generates angle, calculates x and y using some trig i don't know.\n # this is probably the only time i'm going to say this, but if you\n # want to understand how this works, email pmagnus@hamilton.edu\n theta = (math.pi * 2) * float(i) / 200\n x1 = xAxis * math.cos(theta)\n y1 = yAxis * math.sin(theta)\n x = round((x1 * math.cos(0)) + (y1 * math.sin(0)))\n y = round((y1 * math.cos(0)) - (x1 * math.sin(0)))\n self._points.append((x + self._center[0], y + self._center[1]))\n\n ## Sets the horizontal and vertical radii of the oval.\n # @param radiusX - int\n # @param radiusY - int\n def set_radii(self, radiusX, radiusY):\n # type checking\n assert isinstance(radiusX, int) and isinstance(radiusY, int), \\\n \"Make sure radiusX and radiusY are both ints.\"\n self._width = radiusX\n self._height = radiusY\n self._top_left = (self._center[0] - self._width,\n self._center[1] - self._height)\n self._bottom_right = (self._center[0] + self._width,\n self._center[1] + self._height)\n\n self._points = []\n self._circle_gen()\n self._refresh()\n\n\n#-------------------------------------------------------------------------------\n#\n# Square\n#\n#-------------------------------------------------------------------------------\n \n## A square, which can be added to a Window object.\nclass Square(Fillable):\n ## @param window - Window - the window which the object will be added to\n # @param side_length - int - (default: 40) the side length\n # @param center - tuple of (int * int) - (default: (200, 200))\n # the center of the square\n def __init__(self, window, side_length=80, center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and isinstance(side_length, int) \\\n and isinstance(center, tuple) and len(center) == 2 and \\\n isinstance(center[0], int) and isinstance(center[1], int), \\\n \"Make sure window is a window, the side length is an int, \" + \\\n \"and the center is a tuple of (int * int).\"\n # setting inheritance\n Fillable.__init__(self)\n # setting variables\n self._window = window\n self._width = side_length\n self._height = side_length\n self._center = center\n # creating points and then adding object to the canvas and\n # window._graphics\n self._points = [(self._center[0] - self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] + self._height // 2),\n (self._center[0] - self._width // 2,\n self._center[1] + self._height // 2)]\n self._enabled = False\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._window._canvas.itemconfigure(self._tag, state=NORMAL)\n self._enabled = True\n\n ## Sets the side length of the Square.\n # @param side_length - int\n def set_side_length(self, side_length):\n # type checking\n assert isinstance(side_length, int)\n self._width = side_length\n self._height = side_length\n # re-rendering each point\n self._points = [(self._center[0] - self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] + self._height // 2),\n (self._center[0] - self._width // 2,\n self._center[1] + self._height // 2)]\n self._refresh()\n\n#-------------------------------------------------------------------------------\n#\n# Rectangle\n#\n#-------------------------------------------------------------------------------\n \n## A rectangle, which can be added to a Window object.\nclass Rectangle(Fillable):\n ## @param window - Window - the window which the object will be added to\n # @param width - int - (default: 80) the width of the rectangle\n # @param height - int - (default: 120) the height of the rectangle\n # @param center - tuple of (int * int) - (default: (200, 200))\n # the center of the rectangle\n def __init__(self, window, width=80, height=120, center=(200, 200)):\n # type checking\n assert isinstance(window, Window) and isinstance(width, int) \\\n and isinstance(height, int) and isinstance(center, tuple) \\\n and len(center) == 2 and isinstance(center[0], int) and \\\n isinstance(center[1], int), \\\n \"Make sure window is a Window, width and height are both ints, \" + \\\n \"and center is a tuple of (int * int).\"\n # enabling inheritance\n Fillable.__init__(self)\n # setting variables\n self._window = window\n self._width = width\n self._height = height\n self._center = center\n # rendering each corner point\n self._points = [(self._center[0] - self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] - self._height // 2),\n (self._center[0] + self._width // 2,\n self._center[1] + self._height // 2),\n (self._center[0] - self._width // 2,\n self._center[1] + self._height // 2)]\n # adding object to canvas and then to window._graphics\n self._enabled = False\n self._tag = self._window._canvas.create_polygon(\n *self._points,\n width=self.get_border_width(),\n fill=self.get_fill_color(),\n outline=self.get_border_color(),\n state=HIDDEN\n )\n self._window._graphics.append([self._depth, self._tag, self])\n\n # Adds a graphical object to the canvas.\n def _add_to(self):\n self._window._canvas.itemconfigure(self._tag, state=NORMAL)\n self._enabled = True\n\n ## Sets the width and height of the Rectangle.\n # @param width - int\n # @param height - int\n def set_side_lengths(self, width, height):\n # type checking\n assert isinstance(width, int) and isinstance(height, int), \\\n \"Make sure width and height are both ints.\"\n self._width = width\n self._height = height\n # re-rendering each corner point and refreshing\n self._points = [(self._center[0] - self._width / 2,\n self._center[1] - self._height / 2),\n (self._center[0] + self._width / 2,\n self._center[1] - self._height / 2),\n (self._center[0] + self._width / 2,\n self._center[1] + self._height / 2),\n (self._center[0] - self._width / 2,\n self._center[1] + self._height / 2)]\n self._refresh()\n\n#-------------------------------------------------------------------------------\n#\n# Timer\n#\n#-------------------------------------------------------------------------------\n \n## A class which continually runs a function after a delay.\nclass Timer:\n ## @param window - Window - the window which the timer will use to start\n # and stop the animation\n # @param interval - int - the time (in milliseconds) that that the timer\n # will wait\n # @param func - function - the function which will be run\n def __init__(self, window, interval, func):\n # type checking\n # i haven't found a good way of checking whether a func is a function\n assert isinstance(window, Window) and isinstance(interval, int), \\\n \"Make sure window is a Window, the interval is an int, and \" + \\\n \"the function is a function or process.\"\n self._window = window\n self._func = func\n self._interval = interval\n\n ## Sets the function which is going to be run.\n # @param func - function\n def set_function(self, func):\n # i haven't found a good way of checking whether a func is a function\n self._func = func\n\n ## Sets the interval between executions of the function.\n # @param interval - int\n def set_interval(self, interval):\n assert isinstance(interval, int), \\\n \"Make sure the interval is an int.\"\n self._interval = interval\n\n ## Starts the timer.\n def start(self):\n self._func()\n self._tag = self._window._root.after(self._interval, self.start)\n\n ## Stops the timer.\n def stop(self):\n self._window._root.after_cancel(self._tag)\n\n\n#-------------------------------------------------------------------------------\n#\n# RunWithYieldDelay\n#\n#-------------------------------------------------------------------------------\n\n## Begins an animation loop.\n# @param window - Window\n# @param func - function which returns a generator of int\n#\n# The function given must use yield statements to indicate moments in the code\n# when the system should stop and refresh the window. The system will pause for\n# the number of milliseconds given to yield. This allows for the creation of\n# animation systems by refreshing the window between movements.\ndef RunWithYieldDelay(window, func):\n # type checking\n # i haven't found a good way of checking whether a func is a function\n assert isinstance(window, Window), \\\n \"Make sure the window is a Window and the function is a func() -> \" + \\\n \"generator of int.\"\n _RunWithYieldDelay(window, func)\n\n\n# A class which uses a function which returns a generator to rerun until the\n# generator stops generating numbers.\n#\n# NOTE: DO NOT INITALIZE THIS CLASS ANYWHERE IN YOUR PROGRAM. THE WRAPPER\n# FUNCTION RunWithYieldDelay SHOULD BE USED INSTEAD.\n#\n# Required Parameters:\n# - window - Window - the window which the object with yield delay is on.\n# - func - function which returns a generator of int - a function with a few\n# necessary parameters which allow it to run with yield delay. A function needs\n# to return a generator of int, needs a yield statement with an int which \n# represents the delay (in milliseconds), and it needs a raise StopIteration\n# statement at the end of the function.\nclass _RunWithYieldDelay:\n def __init__(self, window, func):\n assert isinstance(window, Window), \"Make sure the window is a \" + \\\n \"Window and the function is a function that returns a \" + \\\n \"generator of int.\"\n self._func = func\n self._window = window\n self._run()\n\n # Starts the run with yield delay.\n def _run(self):\n # this will keep running with yield delay until a StopIteration is\n # raised, at which point it will stop\n try:\n delay = next(self._func)\n if delay is None:\n delay = 1000\n except StopIteration:\n delay = 0\n\n if delay > 0:\n self._tag = self._window._root.after(delay, self._run)\n else:\n self._window._root.after_cancel(self._tag)\n","sub_path":"cs110graphics.py","file_name":"cs110graphics.py","file_ext":"py","file_size_in_byte":63089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"134407001","text":"import turtle\nimport time\n\nbob = turtle.Turtle()\n\n# bob is an object with type Turtle as defined in the turtle module:\nprint(bob)\ntime.sleep(3)\n\n# drawing a square:\nbob.fd(100)\nbob.lt(90)\nbob.fd(100)\nbob.lt(90)\nbob.fd(100)\nbob.lt(90)\nbob.fd(100)\n\n\n# reset screen after 3 second pause:\ntime.sleep(3)\nturtle.reset()\nprint('resetting screen')\nturtle.resetscreen()\n\n\n# drawing a square with a \"for\" loop:\nfor i in range(4):\n\tbob.fd(100)\n\tbob.lt(90)\n\n\n# start drawing/moving:\nturtle.mainloop()\n# NOTE: mainloop() must be the last thing called in a Turtle program!\n","sub_path":"Units/Unit 4 - Case Study - Interface Design/mypolygon.py","file_name":"mypolygon.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"431168932","text":"import turtle\n\ndef draw_square(some_turtle):\n i=1\n while i <= 4:\n some_turtle.forward(100)\n some_turtle.right(90)\n i = i + 1\n\ndef draw_circle(some_turtle):\n some_turtle.circle(100)\n\ndef draw_triangle(some_turtle):\n i=1\n while i <= 3:\n some_turtle.forward(100)\n some_turtle.right(120)\n i = i + 1\n\ndef draw_shapes():\n window = turtle.Screen()\n window.bgcolor(\"red\")\n\n #brad = turtle.Turtle()\n #brad.shape(\"turtle\")\n #brad.color(\"yellow\")\n #brad.speed(1)\n #draw_square(brad)\n\n angie = turtle.Turtle()\n angie.shape(\"arrow\")\n angie.color(\"blue\")\n angie.speed(10)\n\n # 360 dergrees in 10 degrees steps means 36 loops\n num_square = 1\n max_square = 36\n \n while num_square <= max_square:\n draw_square(angie)\n angie.right(10)\n num_square = num_square + 1\n\n\n #fred = turtle.Turtle()\n #fred.color(\"green\")\n #draw_triangle(fred)\n\n\n window.exitonclick()\n \ndraw_shapes()\n","sub_path":"python_course/mindstorm.py","file_name":"mindstorm.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"207574202","text":"\"\"\"\nTest signal reporting when debugging with linux core files.\n\"\"\"\n\nfrom __future__ import print_function\n\n\nimport lldb\nfrom lldbsuite.test.decorators import *\nfrom lldbsuite.test.lldbtest import *\nfrom lldbsuite.test import lldbutil\n\n\nclass GCoreTestCase(TestBase):\n NO_DEBUG_INFO_TESTCASE = True\n\n mydir = TestBase.compute_mydir(__file__)\n def setUp(self):\n super(GCoreTestCase, self).setUp()\n self._initial_platform = lldb.DBG.GetSelectedPlatform()\n\n def tearDown(self):\n lldb.DBG.SetSelectedPlatform(self._initial_platform)\n super(GCoreTestCase, self).tearDown()\n\n _i386_pid = 5586\n _x86_64_pid = 5669\n\n @skipIf(oslist=['windows'])\n @skipIf(triple='^mips')\n def test_i386(self):\n \"\"\"Test that lldb can read the process information from an i386 linux core file.\"\"\"\n self.do_test(\"linux-i386\", self._i386_pid)\n\n @skipIf(oslist=['windows'])\n @skipIf(triple='^mips')\n def test_x86_64(self):\n \"\"\"Test that lldb can read the process information from an x86_64 linux core file.\"\"\"\n self.do_test(\"linux-x86_64\", self._x86_64_pid)\n\n def do_test(self, filename, pid):\n target = self.dbg.CreateTarget(\"\")\n process = target.LoadCore(filename + \".core\")\n self.assertTrue(process, PROCESS_IS_VALID)\n self.assertEqual(process.GetNumThreads(), 3)\n self.assertEqual(process.GetProcessID(), pid)\n\n for thread in process:\n reason = thread.GetStopReason()\n self.assertEqual(reason, lldb.eStopReasonSignal)\n signal = thread.GetStopReasonDataAtIndex(1)\n # Check we got signal 19 (SIGSTOP)\n self.assertEqual(signal, 19)\n\n self.dbg.DeleteTarget(target)\n","sub_path":"packages/Python/lldbsuite/test/functionalities/postmortem/elf-core/gcore/TestGCore.py","file_name":"TestGCore.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"301203506","text":"# Copied from https://gist.github.com/Tetsuya3850/fe841bf1f1088fe1f804c189db4c9daf with minor adjustments\n\nclass HashNode:\n def __init__(self, key, value):\n self.next = None\n self.key = key\n self.value = value\n\n\nclass HashTable:\n def __init__(self):\n self.table = [None] * 101\n\n def hash(self, key):\n # Generate hash from key.\n # Time O(N), Space O(1), where N is the length of key.\n hashed = 0\n for i in range(len(key)):\n hashed = (256 * hashed + key[i]) % 101\n return hashed\n\n def add(self, key, value):\n # Add key, value.\n # Time O(1), Space O(1), where N is the num of elements in hashtable.\n bucket = self.hash(key)\n if not self.table[bucket]:\n self.table[bucket] = HashNode(key, value)\n else:\n temp = self.table[bucket]\n while temp.next:\n temp = temp.next\n temp.next = HashNode(key, value)\n\n def find(self, key):\n # Find value from key.\n # Time O(1), Space O(1), where N is the num of elements in hashtable.\n bucket = self.hash(key)\n if not self.table[bucket]:\n return False\n else:\n temp = self.table[bucket]\n while temp:\n if temp.key == key:\n return temp.value\n temp = temp.next\n return False\n\n def delete(self, key):\n # Delete key, value.\n # Time O(1), Space O(1), where N is the num of elements in hashtable.\n bucket = self.hash(key)\n if not self.table[bucket]:\n return False\n else:\n if self.table[bucket].key == key:\n self.table[bucket] = None\n else:\n temp = self.table[bucket]\n while temp:\n if temp.next.key == key:\n temp.next = temp.next.next\n return\n temp = temp.next\n return False","sub_path":"20220219-mocsctf/hashtable/src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"570127823","text":"#!/usr/bin/env python\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError as e:\n from distutils.core import setup\n\nrequirements = [\n'ruamel.yaml>=0.15.22',\n'stimela>=0.3.1',\n'numpy>=1.13.1',\n'scipy>=0.19.1',\n'pysolr>=3.4.0',\n'progressbar2>=3.11.0',\n'nbconvert>=5.3.1',\n'aplpy>=1.1.1',\n'matplotlib>=2.1.0',\n'jupyter>=1.0.0',\n]\n\nPACKAGE_NAME = 'meerkathi'\n__version__ = '0.1.0'\n\nsetup(name = PACKAGE_NAME,\n version = __version__,\n description = \"MeerKAT end-to-end data reduction pipeline\",\n author = \"MeerKATHI peeps\",\n author_email = \"sphemakh@gmail.com\",\n url = \"https://github.com/sphemakh/meerkathi\",\n packages=[PACKAGE_NAME],\n install_requires = requirements,\n include_package_data = True,\n scripts = [\"bin/\" + j for j in os.listdir(\"bin\")],\n license=[\"GNU GPL v2\"],\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Topic :: Scientific/Engineering :: Astronomy\"\n ]\n )\n","sub_path":"pypi_install_script/meerkathi-0.1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"248446429","text":"# -*- coding: utf-8 -*\r\n\r\n\"\"\"\r\nMain module.\r\n@author: Dimitri Justeau \r\n\"\"\"\r\n\r\nimport sys\r\n\r\nfrom PySide.QtGui import QApplication\r\nfrom PySide.QtCore import QTranslator\r\n\r\nfrom gui.mainwindow import MainWindow\r\nimport constants\r\nimport utils\r\nimport texts\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n app = QApplication(sys.argv)\r\n\r\n translator = QTranslator()\r\n translator.load(constants.QM_PATH)\r\n app.installTranslator(translator)\r\n\r\n mainwindow = MainWindow()\r\n\r\n def excepthook(excType, excValue, tracebackobj):\r\n msg_box = utils.getCriticalMessageBox(texts.GENERAL_ERROR_TITLE,\r\n texts.GENERAL_ERROR_MSG)\r\n msg_box.exec_()\r\n app.exit()\r\n\r\n sys.excepthook = excepthook\r\n\r\n try:\r\n from data.indicators.aggregation_indicators import *\r\n load_aggregation_operators()\r\n mainwindow.showMaximized()\r\n app.exec_()\r\n except AggregationIndicatorsError:\r\n t = \"Impossible de charger les indicateurs agrégés\"\r\n m = \"\"\"\r\n Assurez vous d'avoir correctement configuré les indicateurs\r\n agrégés. Si le problème persiste, contactez Solthis.\r\n \"\"\"\r\n msg_box = utils.getCriticalMessageBox(t, m)\r\n msg_box.exec_()\r\n except KeyboardInterrupt:\r\n pass\r\n except:\r\n t = \"Une erreur est survenue pendant le démarrage du programme\"\r\n m = \"\"\"\r\n Assurez vous d'avoir correctement configuré l'outil, si le\r\n problème persiste, contactez Solthis.\r\n \"\"\"\r\n msg_box = utils.getCriticalMessageBox(t, m)\r\n msg_box.exec_()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"15154695","text":"'''\n gamemap.py\n 01 - Added Flow Field\n 02 - Adding distance map\n Versions are not backwards compatible\n\n\n map representation passible == 0\n'''\n\nimport heapq\nimport collections\nimport random\n\n#\n# Map\n#\nclass GameMap:\n def __init__(self, width=0, height=0, gc=None):\n\n self.width = width\n self.height = height\n self.tiles = [[0 for y in range(self.height)] for x in range(self.width)]\n self.flow = None\n self.goal = (-1,-1)\n self.distxy = [[0 for y in range(self.height)] for x in range(self.width)]\n self.gc = gc # graphics component\n\n if self.gc: self.gc.owner = self\n\n\n def read_from_file(self, fname='map.dat'):\n with open(fname, \"r\") as reader:\n txt_map = reader.readlines()\n\n self.width = int(txt_map[0][1:])\n y = 0\n for line in txt_map:\n if line[0] != '#':\n for x in range(self.width):\n self.tiles[x][y] = 1\n y += 1\n self.height = y\n\n def make_map_from(self, width, height, map_str):\n self.width = width\n self.height = height\n self.tiles = [[0 for y in range(self.height)] for x in range(self.width)]\n n = 0\n for y in range(self.height):\n for x in range(self.width):\n if map_str[n] == '.':\n self.tiles[x][y] = 0\n elif map_str[n] == '#':\n self.tiles[x][y] = 1\n else:\n self.tiles[x][y] = -1\n n += 1\n\n #\n # Generic Routines\n #\n def make_map(self):\n self.dumb()\n pass\n\n def dumb(self):\n self.width = 20\n self.height = 10\n self.tiles = [[0 for y in range(self.height)] for x in range(self.width)]\n for x in range(5, 15):\n self.tiles[x][3] = 1\n self.tiles[x][8] = 1\n\n def dump(self,t=None, path=None):\n for y in range(self.height):\n for x in range(self.width):\n if t=='dist':\n ch = \"{:3d}\".format(self.distxy[x][y])\n else:\n if (x,y) == self.goal: ch = 'S'\n elif self.tiles[x][y] == 0: ch = '.'\n elif self.tiles[x][y] == 1: ch = '#'\n else: ch = '?'\n if path and (x,y) in path:\n ch = \"x\"\n print (ch, end=\"\")\n print()\n\n\n def set_goal(self, pt):\n self.goal = pt\n\n '''\n def make_distance_map_original(self):\n frontier = Queue()\n frontier.put(self.goal)\n self.distance = dict()\n self.distance[self.goal] = 0\n\n while not frontier.empty():\n current = frontier.get()\n for next in self.neighbors(current):\n if next not in self.distance:\n frontier.put(next)\n self.distance[next] = 1 + self.distance[current]\n '''\n\n def make_distance_map(self):\n self.distxy = [[-1 for y in range(self.height)] for x in range(self.width)]\n\n frontier = Queue()\n frontier.put(self.goal)\n self.distxy[self.goal[0]][self.goal[1]] = 0\n\n while not frontier.empty():\n current = frontier.get()\n for next in self.neighbors(current):\n if self.distxy[next[0]][next[1]] == -1:\n frontier.put(next)\n self.distxy[next[0]][next[1]] = 1 + self.distxy[current[0]][current[1]]\n\n #\n # Pretend and real setters / getters\n #\n\n #\n # Pathfinding Routines \n #\n def build_a_path(self, start, maxn=1000):\n ndist, nx, ny = 10000000, -1, -1\n imat = start\n path = []\n ntimes = maxn # punch out if we can't find the goal\n \n while imat != self.goal:\n neighs = self.neighbors(imat)\n for nei in neighs:\n x, y = nei\n d = self.distxy[x][y]\n if d < ndist:\n ndist, nx, ny = d, x, y\n if d == ndist:\n if random.random() > 0.5:\n ndist, nx, ny = d, x, y\n path.append((nx, ny))\n imat = (nx, ny)\n ntimes -= 1\n if ntimes < 0: break\n\n return path\n\n def cost(self, from_node, to_node):\n x, y = to_node\n return self.tiles[x][y]\n\n def passable(self, id):\n x,y = id\n #return self.tiles[x][y] > 0\n return self.tiles[x][y] == 0\n \n def in_bounds(self, id):\n x,y = id\n return 0 <= x < self.width and 0 <= y < self.height\n\n def neighbors(self, id):\n x,y = id\n results = [(x+1, y), (x,y-1), (x-1,y), (x,y+1)]\n # if (x+y) % 2 == 0: results.reverse() # aestethics\n results = filter(self.in_bounds, results)\n results = filter(self.passable, results)\n return results\n\n def path(self, start, goal):\n frontier = PriorityQueue()\n frontier.put(start, 0)\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = 0\n\n while not frontier.empty():\n current = frontier.get()\n\n if current == goal:\n break\n\n for next in self.neighbors(current):\n #print ('{}=[{}]'.format('next', next))\n new_cost = cost_so_far[current] + self.cost(current, next)\n if next not in cost_so_far or new_cost < cost_so_far[next]:\n cost_so_far[next] = new_cost\n priority = new_cost\n frontier.put (next, priority)\n came_from[next] = current\n\n # cme added because combining find and path creation\n if goal not in came_from:\n return []\n\n # Create the path\n current = goal\n path = []\n while current != start:\n #print (\"Path: {} | {}\".format(str(current), str(path)))\n path.append(current)\n current = came_from[current]\n path.append(start)\n path.reverse()\n return path\n\n\n def make_flow(self, goalxy=None):\n self.flow = [[(0,0) for y in range(self.height)] for x in range(self.width)]\n if not goalxy:\n goalxy = self._goal\n if not goalxy:\n print (\"ERROR: No goal\")\n return\n frontier = Queue()\n frontier.put(goalxy)\n came_from = dict()\n came_from[goalxy] = None\n\n #print (\"frontier={} {} \".format(frontier.empty(), frontier))\n\n while not frontier.empty():\n current = frontier.get()\n #print (\"Current = \", current)\n #print (\"Neighbors = \", self.neighbors(current))\n #for next in graph.neighbors(current):\n for next in self.neighbors(current):\n #print (\"next={}\".format(next))\n if next not in came_from:\n frontier.put(next)\n came_from[next] = current\n\n #came_from[goalxy] = \"goal\"\n #print (\"came_from = {}\".format(came_from))\n flow = [[' ' for y in range(self.height)] for x in range(self.width)]\n #for k,v in came_from.items():\n # x,y = k\n # flow[x][y] = v\n\n x,y = goalxy\n flow[x][y] = \"G\"\n\n for y in range(self.height):\n for x in range(self.width):\n if (x,y) in came_from and came_from[(x,y)]:\n xc, yc = came_from[(x,y)]\n if x == xc: # vertical change\n if y < yc:\n self.flow[x][y] = (0,1) #\"v\"\n else:\n self.flow[x][y] = (0,-1) #\"^\"\n else:\n if x < xc:\n self.flow[x][y] = (1, 0) #\">\"\n else:\n self.flow[x][y] = (-1, 0) #\"<\"\n\n\n#\n# Queues for Pathfinding\n#\nclass Queue:\n def __init__(self):\n self.elements = collections.deque()\n \n def empty(self):\n return len(self.elements) == 0\n \n def put(self, x):\n self.elements.append(x)\n \n def get(self):\n return self.elements.popleft()\n\nclass PriorityQueue:\n def __init__(self):\n self.elements = []\n def empty(self):\n return len(self.elements) == 0\n def put(self, item, priority):\n heapq.heappush(self.elements, (priority, item))\n def get(self):\n return heapq.heappop(self.elements)[1]\n\n\nif __name__ == '__main__':\n print (\"Self Test\\n\")\n\n # '....5....0\n # '0123456789\n map_str = '......###.'\\\n '........#.'\\\n '...###..#.'\\\n '.##.....#.'\\\n '..........' # 04\n\n world = GameMap()\n #world.make_map()\n world.make_map_from(10, 5, map_str)\n world.set_goal((3, 1))\n world.make_distance_map()\n\n world.dump()\n print()\n\n world.dump('dist')\n print()\n\n path = world.build_a_path(( 7, 3))\n print()\n world.dump(path=path)\n\n print (\"\\nFini\")\n","sub_path":"Routes/gamemap.py","file_name":"gamemap.py","file_ext":"py","file_size_in_byte":9114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"292330084","text":"\n# DEFINE FUNCTION\ndef find_factorial(n):\n\n\tfactorial = 1\n\n\tfor i in range(1, n+1):\n\t\t factorial *= i\n\n\treturn factorial\n\nprint('\\n')\np = 10\nfor i in range(1, p+1):\n\n\tprint(find_factorial(i))\n\nwhile True:\n\n\ttry:\n\t\tnum = int(input('Enter a number for which you want the factorial: '))\n\t\t\n\t\tif num == 0:\n\t\t\tprint('The factorial of 0 is 1')\n\t\t\tquit()\n\n\t\telif num < 0:\n\t\t\tprint('Factorials do not exist for negative numbers. ')\n\t\t\tquit()\n\n\t\telif num > 0:\n\t\t\tbreak\n\n\texcept:\n\t\tprint('-------------------------')\n\nprint(find_factorial(num))\n\n","sub_path":"Factorial.py","file_name":"Factorial.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"649128600","text":"\"\"\"\nrotation参数能够帮助我们将日志记录以大小、时间等方式进行分割或划分\n\"\"\"\n\nfrom loguru import logger\nimport os\n\n# LOG_DIR = os.path.expanduser(\"~/logs\") # will expand ~ to user path\nLOG_DIR = \"./logs\"\nLOG_FILE = os.path.join(LOG_DIR, \"file_{time}.log\")\n\nif not os.path.exists(LOG_DIR):\n os.mkdir(LOG_DIR)\n\nlogger.add(LOG_FILE, rotation=\"10KB\")\n\nfor n in range(500):\n logger.info(f\"info: {n}\")\n","sub_path":"log_systems/loguru/loguru_examples/02_rotation.py","file_name":"02_rotation.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"144335643","text":"\"\"\"Thread-based objects that manage data as it arrives from the scanner.\"\"\"\nfrom __future__ import print_function, division\nfrom threading import Thread\nfrom Queue import Empty\nfrom time import sleep\nimport logging\n\nimport numpy as np\nfrom dcmstack import DicomStack\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Finder(Thread):\n \"\"\"Base class that uses a slightly different approach to thread control.\"\"\"\n def __init__(self, interval):\n \"\"\"Initialize the Finder.\"\"\"\n super(Finder, self).__init__()\n\n self.interval = interval\n self.alive = True\n\n def halt(self):\n \"\"\"Make it so the thread will halt within a run method.\"\"\"\n self.alive = False\n\n\nclass SeriesFinder(Finder):\n \"\"\"Manage a queue of series directories on the scanner.\n\n The queue will only be populated with series that look like they\n are timeseries, because that is what is useful for real-time analysis.\n\n \"\"\"\n def __init__(self, scanner, queue, interval=1):\n \"\"\"Initialize the queue.\"\"\"\n super(SeriesFinder, self).__init__(interval)\n\n self.scanner = scanner\n self.current_series = None\n\n self.queue = queue\n self.alive = True\n\n def run(self):\n \"\"\"This function gets looped over repetedly while thread is alive.\"\"\"\n while self.alive:\n\n if self.current_series is None:\n logger.debug(\"Starting series collection\")\n\n # Load up all series for the current exam\n for series in self.scanner.series_dirs():\n\n logger.debug(\"Checking series {}\".format(series))\n\n # We are only interested in timeseries data\n latest_info = self.scanner.series_info(series)\n if latest_info[\"NumTimepoints\"] > 6:\n logger.debug((\"Series appears to be 4D; \"\n \"adding to series queue\"))\n self.queue.put(series)\n\n self.current_series = series\n else:\n # Only do anything if there's a new series\n latest_series = self.scanner.latest_series\n if self.current_series != latest_series:\n\n logger.debug(\"Found new series: {}\".format(series))\n\n # Update what we think the current series is\n self.current_series = latest_series\n\n # Get a dictionary of information about it\n # Be explicit to avoid possible race condition\n latest_info = self.scanner.series_info(latest_series)\n\n # We are only interested in timeseries data\n if latest_info[\"NumTimepoints\"] > 1:\n logger.debug((\"Series appears to be 4D; \"\n \"adding to series queue\"))\n self.queue.put(latest_series)\n\n sleep(self.interval)\n\n\nclass DicomFinder(Finder):\n \"\"\"Manage a queue of DICOM files on the scanner.\n\n This class talks to the scanner and to a separately-managed series queue.\n\n Note\n ----\n\n The queue order will reflect the timestamps and filenames of the dicom\n files on the scanner. This is *not* guaranteed to order the files in the\n actual order of acquisition. Downstream components of the processing\n pipeline should inspect the files for metadata that can be used to\n put them in the right order.\n\n \"\"\"\n def __init__(self, scanner, series_q, dicom_q, interval=1):\n \"\"\"Initialize the queue.\"\"\"\n super(DicomFinder, self).__init__(interval)\n\n # Referneces to the external objects we need to talk to\n self.scanner = scanner\n self.series_q = series_q\n self.dicom_q = dicom_q\n\n # We'll want to keep track of the current series\n self.current_series = None\n\n # A set to keep track of files we've added onto the queue\n # (This is needed because we'll likely be running over the same\n # series directory multiple times, so we need to know what's in\n # the queue). We use a set because the relevant operations are\n # quite a bit faster than they would be with lists.\n self.dicom_files = set()\n\n def run(self):\n \"\"\"This function gets looped over repetedly while thread is alive.\"\"\"\n while self.alive:\n\n if self.current_series is not None:\n\n # Find all the dicom files in this series\n series_files = self.scanner.series_files(self.current_series)\n\n # Compare against the set of files we've already placed\n # in the queue, keep only the new ones\n new_files = [f for f in series_files\n if f not in self.dicom_files]\n\n if new_files:\n logger.debug((\"Putting {:d} files into dicom queue\"\n .format(len(new_files))))\n\n # Place each new file onto the queue\n for fname in new_files:\n self.dicom_q.put(self.scanner.retrieve_dicom(fname))\n\n # Update the set of files on the queue\n self.dicom_files.update(set(new_files))\n\n if not self.series_q.empty():\n\n # Grab the next series path off the queue\n self.current_series = self.series_q.get()\n\n logger.debug((\"Beginning DICOM collection for new series: {}\"\n .format(self.current_series)))\n\n # Reset the set of dicom files. Once we've moved on to\n # the next series, we don't need to track these any more\n # and this keeps it from growing too large\n self.dicom_files = set()\n\n sleep(self.interval)\n\n\nclass Volumizer(Finder):\n \"\"\"Reconstruct MRI volumes and manage a queue of them.\n\n This class talks to the Dicom queue, but does not need to talk to\n the scanner.\n\n \"\"\"\n def __init__(self, dicom_q, volume_q, interval=1):\n \"\"\"Initialize the queue.\"\"\"\n super(Volumizer, self).__init__(interval)\n\n # The external queue objects we are talking to\n self.dicom_q = dicom_q\n self.volume_q = volume_q\n\n def dicom_esa(self, dcm):\n \"\"\"Extract the exam, series, and acquisition metadata.\n\n These three values will uniquely identiy the scanner run.\n\n \"\"\"\n exam = int(dcm.StudyID)\n series = int(dcm.SeriesNumber)\n acquisition = int(dcm.AcquisitionNumber)\n\n return exam, series, acquisition\n\n def assemble_volume(self, slices):\n \"\"\"Put each dicom slice together into a nibabel nifti image object.\"\"\"\n # Build a DicomStack from each of the slices\n stack = DicomStack()\n for f in slices:\n stack.add_dcm(f)\n\n # Convert into a Nibabel Nifti object\n nii_img = stack.to_nifti(voxel_order=\"\")\n\n # Build the volume dictionary we will put in the dicom queue\n dcm = slices[0]\n exam, series, acquisition = self.dicom_esa(dcm)\n volume = dict(\n exam=exam,\n series=series,\n acquisition=acquisition,\n patient_id=dcm.PatientID,\n series_description=dcm.SeriesDescription,\n tr=float(dcm.RepetitionTime) / 1000,\n ntp=float(dcm.NumberOfTemporalPositions),\n image=nii_img,\n )\n\n return volume\n\n def run(self):\n \"\"\"This function gets looped over repetedly while thread is alive.\"\"\"\n # Initialize the list we'll using to track progress\n instance_numbers_needed = None\n instance_numbers_gathered = []\n current_esa = None\n current_slices = []\n\n while self.alive:\n\n try:\n dcm = self.dicom_q.get(timeout=1)\n except Empty:\n sleep(self.interval)\n continue\n\n try:\n # This is the dicom tag for \"Number of locations\"\n slices_per_volume = dcm[(0x0021, 0x104f)].value\n except KeyError:\n # TODO In theory, we shouldn't get to here, because the\n # series queue should only have timeseries images in it.\n # Need to figure out under what circumstances we'd get a\n # file that doesn't have a \"number of locations\" tag,\n # and what we should do with it when we do.\n # The next line is just taken from the original code.\n slices_per_volume = getattr(dcm, \"ImagesInAcquisition\")\n slices_per_volume = int(slices_per_volume)\n\n # Determine if this is a slice from a new acquisition\n this_esa = self.dicom_esa(dcm)\n if current_esa is None or this_esa != current_esa:\n # Begin tracking the slices we need for the first volume\n # from this acquisition\n instance_numbers_needed = np.arange(slices_per_volume) + 1\n current_esa = this_esa\n logger.debug((\"Collecting slices for new scanner run - \"\n \"(exam: {} series: {} acquisition: {})\"\n .format(*current_esa)))\n\n # Get the DICOM instance for this volume\n # This is an incremental index that reflects position in time\n # and space (i.e. the index is the same for interleaved or\n # not sequential acquisitisions) so we can trust it to put\n # the volumes in the correct order.\n current_slice = int(dcm.InstanceNumber)\n\n # Add this slice index and dicom object to current list\n instance_numbers_gathered.append(current_slice)\n current_slices.append(dcm)\n\n if set(instance_numbers_needed) <= set(instance_numbers_gathered):\n\n # Files are not guaranteed to enter the DICOM queue in any\n # particular order. If we get here, then we have picked up\n # all the slices we need for this volume, but they might be\n # out of order, and we might have other slices that belong to\n # the next volume. So we need to figure out the correct order\n # and then extract what we need, leaving the rest to be dealt\n # with later.\n\n volume_slices = []\n for slice_number in instance_numbers_needed:\n slice_index = instance_numbers_gathered.index(slice_number)\n volume_slices.append(current_slices.pop(slice_index))\n instance_numbers_gathered.pop(slice_index)\n\n # Assemble all the slices together into a nibabel object\n logger.debug((\"Assembling full volume for slices {:d}-{:d}\"\n .format(min(instance_numbers_needed),\n max(instance_numbers_needed))))\n volume = self.assemble_volume(volume_slices)\n\n # Put that object on the dicom queue\n self.volume_q.put(volume)\n\n # Update the array of slices we need for the next volume\n instance_numbers_needed += slices_per_volume\n","sub_path":"rtfmri/queuemanagers.py","file_name":"queuemanagers.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"614267660","text":"import json\nimport re\nfrom collections import defaultdict, Counter\nfrom itertools import combinations, groupby\n\n\nclass API(object):\n def __init__(self, idx, method, uri, func_name):\n self.idx = idx\n self.method = method\n self.uri = uri\n self.func_name = func_name\n\n def __str__(self):\n return f\"Idx: {self.idx}, Method: {self.method}, URI: {self.uri}, func_name: {self.func_name}\"\n\n def __eq__(self, rhs):\n return self.method == rhs.method and self.uri == rhs.uri\n\n\nclass APIManager(object):\n api_map = {}\n idx_map = {}\n count = 0\n\n def register(self, method, uri, func_name):\n if (method, uri) in self.api_map: return\n self.count += 1\n api = API(self.count, method, uri, func_name)\n self.idx_map[self.count] = api\n self.api_map[(method, uri)] = api\n\n def find_by_idx(self, idx):\n if idx in self.idx_map: return self.idx_map[idx]\n return None\n\n def find_by_uri(self, method, uri):\n for key in self.api_map:\n m, u = key\n if method == m and re.search(u, uri):\n return self.api_map[key]\n print('----------fail', method, uri)\n return API(None, method, uri, None)\n\nAPIS = [\n ('GET', '^/$', 'get_main'),\n ('GET', '^/main/$', 'get_main'),\n ('GET', '^/session/$', 'session'),\n ('GET', '^/session/login/$', 'session_login'),\n ('GET', '^/session/login/callback/$', 'session_login_callback'),\n ('GET', '^/session/logout/$', 'session_logout'),\n ('GET', '^/session/unregister/$', None),\n ('GET', '^/session/language/$', 'session_language'),\n ('GET', '^/session/settings/$', 'session_setting_get'),\n ('POST', '^/session/settings/$', 'session_setting_post'),\n ('GET', '^/api/subject/semesters/$', None),\n ('GET', '^/api/subject/courses/$', None),\n ('GET', '^/api/subject/courses/([0-9]*)/$', None),\n ('GET', '^/api/subject/courses/autocomplete/$', None),\n ('GET', '^/api/subject/courses/([0-9]*)/lectures/$', None),\n ('GET', '^/api/subject/lectures/$', None),\n # ('GET', '^/subject/lectures/([0-9])/$'),\n ('GET', '^/api/lectures', 'get_lectures'),\n ('GET', '^/api/lectures/autocomplete/$', 'get_Lectures_auto_complete'),\n ('GET', '^/api/users/([0-9]*)/taken-courses/$', 'get_taken_courses'),\n ('GET', '^main', 'get_main'),\n ('GET', '^/credits/$', 'get_credits'),\n ('GET', '^/licenses/$', 'get_licenses'),\n ('GET', '^/review/$', 'get_review'),\n ('GET', '^/review/refresh/$', 'refresh_review'),\n ('GET', '^/review/insert/$', 'insert_review'),\n ('GET', '^/review/json/([0-9]*)/$', 'get_last_comment_json'),\n ('GET', '^/review/result/comment/([0-9]*)/$', 'get_comment'),\n ('GET', '^/review/result/professor/([0-9]*)/([^/]+)/$', 'get_professor_review'),\n ('GET', '^/review/result/professor/([^/]+)/json/([^/]+)/([^/]+)/$', 'get_professor_review_json'),\n ('GET', '^/review/result/course/([0-9]*)/$', 'get_course_review'),\n ('GET', '^/review/result/course/([1-9][0-9]*)/([^/]+)/$', 'get_course_review'),\n ('GET', '^/review/result/course/([^/]+)/([^/]+)/json/([^/]+)/$', 'get_course_review_json'),\n ('GET', '^/review/result/$', 'get_result'),\n ('GET', '^/review/result/json/(?P[0-9]+)/$', 'get_result_json'),\n\n # ('GET', '^/subject/courses/([0-9])/reviews/$'),\n # ('GET', '^/subject/lectures/([0-9])/reviews/$'),\n # ('GET', '^/subject/lectures/([0-9])/related-reviews/$'),\n # ('GET', '^/review/latest/([0-9])/$'),\n # ('GET', '^/review/insert/([0-9])/$'),\n # ('GET', '^/review/like/$'),\n # ('GET', '^/review/read/$'),\n ('GET', '^/timetable/$', 'get_table'),\n ('POST', '^/timetable/api/table_update/$', 'table_update'),\n ('POST', '^/timetable/api/table_create/$', 'table_create'),\n ('POST', '^/timetable/api/table_delete/$', 'table_delete'),\n ('POST', '^/timetable/api/table_copy/$', 'table_copy'),\n ('POST', '^/timetable/api/table_load/$', 'table_load'),\n ('POST', '^/timetable/api/autocomplete/$', 'table_autocomplete'),\n ('POST', '^/timetable/api/search/$', 'table_search'),\n ('POST', '^/timetable/api/comment_load/$', 'comment_load'),\n ('POST', '^/timetable/api/list_load_major/$', 'major_load'),\n ('POST', '^/timetable/api/list_load_humanity/$', 'humanity_load'),\n ('POST', '^/timetable/api/wishlist_load/$', 'wishlist_load'),\n ('POST', '^/timetable/api/wishlist_update/$', 'wishlist_update'),\n ('DELETE', '^/timetable/api/wishlist_update', 'wishlist_update_lecture_delete'), # DELETE인데 사실 POST임\n ('GET', '^/timetable/api/share_image/$', 'share_image'),\n ('GET', '^/timetable/api/share_calendar/$', 'share_calander'),\n ('GET', '^/timetable/google_auth_return/$', 'google_auth_return'),\n]\n\nAPI_MANAGER = APIManager()\ndef init():\n for api in APIS:\n API_MANAGER.register(api[0], api[1], api[2])\n\n\ndef validate(line):\n d = json.loads(line)\n return not d['URI'].endswith('.css') and not d['URI'].endswith('.js') and not d['URI'].endswith('&filter=HSS') and not d['URI'].endswith('.ico') and not 'media' in d['URI']\n\n\ndef extract_pattern1(user_logs, min_length = 10, max_length = 20):\n candidates = []\n keys = user_logs.keys()\n for key in keys:\n logs = user_logs[key]\n if len(logs) < min_length: continue\n for length in range(min_length, max_length + 1):\n p = []\n for api, _ in logs:\n # p.append(api.idx)\n p.append(api.func_name)\n if len(p) == length:\n candidates.append(tuple(p))\n p.pop(0)\n\n return sorted(dict(Counter(candidates)).items(), key=lambda item: (item[1], len(item[0])), reverse=True)\n\n\ndef getLCS(log1, log2):\n N = len(log1)\n M = len(log2)\n\n D = [[-1] * (M + 1)]\n P = [[0] * (M + 1)]\n for i in range(N):\n D.append([0] * (M + 1))\n P.append([0] * (M + 1))\n for j in range(M):\n if log1[i] == log2[j] and D[i + 1][j + 1] < D[i][j] + 1:\n D[i + 1][j + 1] = D[i][j] + 1\n P[i + 1][j + 1] = 1\n if D[i + 1][j + 1] < D[i + 1][j]:\n D[i + 1][j + 1] = D[i + 1][j]\n P[i + 1][j + 1] = 2\n if D[i + 1][j + 1] < D[i][j + 1]:\n D[i + 1][j + 1] = D[i][j + 1]\n P[i + 1][j + 1] = 3\n\n i = N\n j = M\n lcs = []\n while i > 0 and j > 0:\n if P[i][j] == 1:\n # lcs = [log1[i - 1].idx] + lcs\n lcs = [log1[i - 1].func_name] + lcs\n i -= 1\n j -= 1\n elif P[i][j] == 2:\n j -= 1\n elif P[i][j] == 3:\n i -= 1\n else:\n break\n\n return lcs\n\n\ndef extract_pattern2(user_logs):\n candidates = []\n keys = list(user_logs.keys())\n N = len(keys)\n for i in range(N):\n for j in range(i+1, N):\n result = (tuple(getLCS([api for api, _ in user_logs[keys[i]]], [api for api, _ in user_logs[keys[j]]])))\n if len(result) > 1:\n candidates.append(result)\n\n return sorted(dict(Counter(candidates)).items(), key=lambda item: (item[1], len(item[0])), reverse=True)\n\n\ndef extract_pattern3(user_logs):\n candidates = []\n for user, api_logs in user_logs.items():\n\n for api, log in api_logs:\n withins = [a for a, l in api_logs if log['timestamp'] <= l['timestamp'] < log['timestamp'] + 5 * 60 * 1000]\n if len(withins) >= 5:\n p = []\n for within in withins:\n p.append(within.func_name)\n candidates.append(tuple(p))\n\n return sorted(dict(Counter(candidates)).items(), key=lambda item: (item[1], len(item[0])), reverse=True)\n\n\ndef print_mat_2d(mat):\n for i in range(len(mat)): print(mat[i])\n\n\ndef extract_pattern4(user_logs):\n candidates = []\n apis = []\n for user, api_logs in user_logs.items():\n # 연속한 같은 api는 하나로 처리 (e.g. AABBA -> ABA)\n apis.append([x[0] for x in groupby([a.func_name for a, _ in api_logs])])\n\n combis = list(combinations(apis, 2))\n for a, b in combis:\n la = len(a)\n lb = len(b)\n\n d = [[0 for _ in range(lb+1)] for _ in range(la+1)]\n for i in range(0, la):\n for j in range(0, lb):\n d[i][j] = max(d[i-1][j], d[i][j-1], d[i-1][j-1]+1) if a[i] == b[j] else max(d[i][j-1], d[i-1][j])\n\n if d[la-1][lb-1] >= 5 and (d[la-1][lb-1] / min(la, lb)) >= 0.8:\n if la >= lb:\n candidates.append(tuple(a))\n else:\n candidates.append(tuple(b))\n\n return sorted(dict(Counter(candidates)).items(), key=lambda item: (item[1], len(item[0])), reverse=True)\n\n\ndef get_pattern_by_log_and_rule(log_file_name, rule):\n init()\n\n f = open(log_file_name, 'r')\n raw_logs = f.readlines()\n logs = []\n for log in raw_logs:\n if not validate(log): continue\n logs.append(json.loads(log))\n f.close()\n\n user_logs = defaultdict(list)\n for log in logs:\n if 'csrftoken' not in log['cookie']: continue\n key = log['cookie']['csrftoken']\n api = API_MANAGER.find_by_uri(log['method'], log['URI'])\n if api: user_logs[key].append((api, log))\n \n extract_func = None\n if (rule == 0):\n extract_func = extract_pattern1\n elif (rule == 1):\n extract_func = extract_pattern2\n elif (rule == 2):\n extract_func = extract_pattern3\n elif (rule == 3):\n extract_func = extract_pattern4\n else:\n print(\"Invalid rule\")\n exit(-1)\n\n return extract_func(user_logs)\n\n\nif __name__ == '__main__':\n init()\n\n f = open('./otlplus.log', 'r')\n raw_logs = f.readlines()\n logs = []\n for log in raw_logs:\n if not validate(log): continue\n logs.append(json.loads(log))\n f.close()\n\n user_logs = defaultdict(list)\n for log in logs:\n if 'csrftoken' not in log['cookie']: continue\n key = log['cookie']['csrftoken']\n api = API_MANAGER.find_by_uri(log['method'], log['URI'])\n if api: user_logs[key].append((api, log))\n\n print(extract_pattern4(user_logs))\n # extract_pattern2(user_logs)","sub_path":"locust/extract_patterns.py","file_name":"extract_patterns.py","file_ext":"py","file_size_in_byte":10164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"563262304","text":"import cherrypy\nimport logging\n\nfrom cherrypy import HTTPError, HTTPRedirect\n\nfrom blueberrypy.util import to_collection\n\nfrom oauthlib.oauth2.rfc6749.errors import (MissingCodeError,\n MismatchingStateError)\n\nfrom .api import find_admin_by_email\nfrom .lib.utils.url import url_for_class\nfrom .lib.utils.signals import pub\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass AuthController:\n \"\"\"AuthController implements authentication via Google's OAuth2\"\"\"\n\n # TODO: decide whether to keep it here or move to test suite\n @cherrypy.expose\n def fake_login(self):\n \"\"\"This is a method to be used while testing secured area\n\n It requires `bypass_auth` option to be enabled in global config\n section and sets fake data about the user into session\n \"\"\"\n\n if not cherrypy.config.get('global', {}).get('bypass_auth'):\n raise HTTPError(403)\n\n req = cherrypy.request\n orm_session = req.orm_session\n\n cherrypy.session['google_user'] = {\n \"given_name\": \"Petryk\",\n \"gender\": \"male\",\n \"link\": \"https://plus.google.com/+SvyatoslavSydorenko\",\n \"picture\": \"https://www.wired.com/wp-content/uploads/blogs\"\n \"/wiredenterprise/wp-content/uploads/2012/06\"\n \"/Screen-shot-2012-06-18-at-10.32.45-AM.png\",\n \"name\": \"Petryk Piatochkin\",\n \"hd\": \"gdg.org.ua\",\n \"email\": \"test@gdg.org.ua\",\n \"id\": \"133555540822907599802\",\n \"locale\": \"uk\",\n \"verified_email\": True,\n \"family_name\": \"Piatochkin\"\n }\n cherrypy.session['admin_user'] = to_collection(find_admin_by_email(\n orm_session,\n cherrypy.session['google_user']['email']))\n\n HTTPRedirect(url_for_class('controller.Root'))\n\n @cherrypy.expose\n @cherrypy.tools.json_out()\n def google(self, **kwargs):\n req = cherrypy.request\n orm_session = req.orm_session\n try:\n # Aquire API token internally\n pub('oauth-token')\n\n # Aquire OAuth2Session instance, built with token\n google_api = pub('google-api')\n\n cherrypy.session['google_user'] = google_api.get(\n 'https://www.googleapis.com/oauth2/v1/userinfo').json()\n\n cherrypy.session['admin_user'] = to_collection(find_admin_by_email(\n orm_session,\n cherrypy.session['google_user']['email']))\n cherrypy.session['google_oauth'] = kwargs\n\n if cherrypy.session.get('auth_redirect'):\n print('redirect after auth')\n logger.debug('redirect after auth')\n raise HTTPRedirect(cherrypy.session['auth_redirect'])\n else:\n raise HTTPRedirect(url_for_class('controller.Root'))\n\n return cherrypy.session['admin_user']\n except MissingCodeError as mce:\n raise HTTPError(401,\n 'Error: {}'.format(kwargs.get('error'))) from mce\n except (MismatchingStateError, KeyError) as wrong_state:\n raise HTTPRedirect(\n url_for_class('controller.Root.auth')) from wrong_state\n\n # index = google\n\n @cherrypy.expose\n def index(self, return_url=None):\n return_url = (return_url\n if return_url\n else cherrypy.request.headers.get('Referer'))\n\n if return_url is not None and \\\n return_url.stratswith(['/', 'https://', 'http://']) \\\n and not return_url.startswith('/auth'):\n cherrypy.session['auth_redirect'] = return_url\n\n authorization_url = pub('oauth-url')\n\n raise HTTPRedirect(authorization_url)\n\n @cherrypy.expose\n def logout(self, return_url=None):\n for key in ['google_oauth', 'google_user',\n 'admin_user', 'auth_redirect']:\n if cherrypy.session.get(key):\n del cherrypy.session[key]\n\n return_url = (return_url\n if return_url\n else cherrypy.request.headers.get('Referer', '/'))\n\n if (any(return_url.startswith(_)\n for _ in ['/', 'https://', 'http://']) and\n not return_url.startswith('/auth')):\n raise HTTPRedirect(return_url)\n\n raise HTTPRedirect(url_for_class('controller.Root'))\n","sub_path":"src/GDGUkraine/auth_controller.py","file_name":"auth_controller.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"628672490","text":"\"\"\"\nThis module contains a class that helps keep the order of dependencies\n(it's helpful when you need to install apps that have dependencies for\nexample)\n\n>>> dependency_order = DependencyOrder()\n>>> dependency_order.append('kitkat', dependencies=('snickers', 'nesquik'))\n>>> dependency_order\n['snickers', 'nesquik', 'kitkat']\n>>> dependency_order.append('snickers', dependencies=('nesquik', 'milkyway'))\n>>> dependency_order\n['nesquik', 'milkyway', 'snickers', 'kitkat']\n>>> dependency_order.append('mars')\n>>> dependency_order\n['mars', 'nesquik', 'milkyway', 'snickers', 'kitkat']\n>>> dependency_order.append('coffee', dependencies=('sugar', 'nesquik'))\n>>> dependency_order\n['mars', 'nesquik', 'milkyway', 'snickers', 'kitkat', 'sugar', 'coffee']\n\"\"\"\n\n\nclass DependencyOrder(list):\n \"\"\"\n List that keeps the order of dependencies\n \"\"\"\n\n def append(self, node, dependencies=tuple()) -> None:\n \"\"\"Override the append method\"\"\"\n\n if node not in self:\n if not dependencies:\n # if there are no dependencies, we can just put the element\n # at the beginning of the list\n self.insert(0, node)\n\n else:\n for dependency in dependencies:\n # if dependency is already in a list\n if dependency not in self:\n self.insert(len(self), dependency)\n\n # add the node the end of the list\n self.insert(len(self), node)\n else:\n # we can do something about this node only in the case it has\n # dependencies\n if dependencies:\n for dependency in dependencies:\n if dependency not in self:\n # add this dependency before the node\n self.insert(self.index(node), dependency)\n else:\n # if dependency is already in the list, we need to\n # make sure, that it's before the node\n if self.index(dependency) > self.index(node):\n # first, we're gonna remove that node from\n # its old position\n self.remove(node)\n # and then insert it after the dependency\n self.insert(self.index(dependency) + 1, node)\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"sort_app_inc.py","file_name":"sort_app_inc.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"177379192","text":"import lib\n\ndef nb(testT, trainT, hypotheses, k, m):\n ck = testT['0'].klass[0] #locate the index for class col\n total = acc = 0.0 \n total += len(trainT['0'].data[ck])\n for t in range(len(testT['0'].data[ck])):\n want = testT['0'].data[ck][t]\n row = []\n for i in range(len(testT['0'].data)):\n row += [testT['0'].data[i][t]]\n got = likelihood(row, trainT, total, hypotheses, k, m)\n acc += want == got\n return 100 * acc/len(testT['0'].data[ck])\n \ndef likelihood(row, trainT, total, hypotheses, k, m):\n like = lib.NINF\n total += k * len(hypotheses)\n best = ''\n for h in hypotheses:\n nh = len(trainT[h].data[trainT['0'].klass[0]])\n prior = float(nh + k)/total\n tmp = prior\n for c in trainT[h].nump:\n i = trainT[h].nump.index(c)\n x = row[c]\n if x == \"?\": continue\n y = lib.norm(float(x), float(trainT[h].mu[i]), float(trainT[h].sd[i]))\n tmp *= y\n for c in trainT[h].term:\n x = row[c]\n if x == \"?\": continue\n y = 0.0\n for i in range(len(trainT[h].data[c])):\n if trainT[h].data[c][i] == x: y+= 1\n tmp *= (y + m*prior) / (nh +m)\n if tmp >= like: \n like = tmp\n best = h\n \"\"\"\n # log version\n tmp = math.log(prior)\n for c in trainT[h].num:\n x = row[c]\n if x == \"?\": continue\n y = lib.norm(x, trainT[h].mu[c], trainT[h].sd[c])\n tmp += math.log(y)\n for c in trainT[h].term:\n x = row[c]\n if x == \"?\": continue\n y = 0.0\n for i in range(len(trainT[h].data[c])):\n if trainT[h].data[c][i] == x: y+= 1\n tmp += math.log((y + m*prior) / (nh +m))\n if tmp >= like: \n like = tmp\n best = h\n \"\"\"\n return best\n ","sub_path":"CS573_DataMining_Python/Proj1e_KNearestNeighbor/nb.py","file_name":"nb.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"288378644","text":"import requests\nimport logging as LOG\nimport re\nfrom datetime import datetime\nfrom util.alignment import Alignment\nfrom util import io\n\n\"\"\"\nThis script aims to consume EBI rest webservice for the needle\nalignment algorithm\n\n\"\"\"\n\n\n#EBI URLS\nEBI_RUN_URL = \"http://www.ebi.ac.uk/Tools/services/rest/emboss_water/run/\"\nEBI_RESULT_URL = \"http://www.ebi.ac.uk/Tools/services/rest/emboss_water/result/\"\nREGEX = \"(?<=\\d )[AGVLYETDFQHICSMKPRNW\\-]{1,50}\"\n\n#EXAMPLE OF REQUEST\ndata = {\"email\":\"up201711183@fc.up.pt\",\n \"matrix\":\"EBLOSUM62\",\n \"gapopen\":\"10.0\",\n \"gapext\":\"0.5\",\n \"endweight\":\"false\",\n \"endopen\":\"10.0\",\n \"endextend\":\"0.5\",\n \"format\":\"pair\",\n \"stype\":\"protein\",\n \"asequence\":io.read_file(\"../inputs/default1.fasta\"),\n \"bsequence\":io.read_file(\"../inputs/default2.fasta\")\n }\n \n\ndef get_alignment(string):\n \"\"\"\n summary: This fuctions receives a string returned by EBI and parses it \n to get just the two sequences aligned.\n return: An alignment object\n \"\"\"\n \n string = re.sub(re.compile(\"#.*?\\n\" ) ,\"\" ,string) ##removing all comments\n p = re.compile(REGEX) #getting the REGEX variable\n m = p.findall(string) #returns all list of strings that match with that regex\n string1 = m[0::2] #gets all the even itens on the list (i.e the first sequence)\n string2 = m[1::2] #gets all the odds items on the list (i.e the second sequence)\n string1 = ''.join(string1) #join all items in a single string with '' sepring them\n string2 = ''.join(string2) #the same as above\n \n result = Alignment(string1,string2,\"DEFAULT\")\n result.calculate_mat_mis_gaps()\n \n return result\n\n\nif __name__ == '__main__':\n #CONFIG\n LOG.basicConfig(filename='../log/run_on_ebi.log',level=LOG.INFO)\n LOG.info(\"----------\\n\")\n\n # RUN\n LOG.info(\"[{0}] Requesting the URL = {1}...\".format(datetime.now(),EBI_RUN_URL))\n r = requests.post(EBI_RUN_URL,data)\n LOG.info(\"[{0}] Request made and the code returned was {1}\".format(datetime.now(),r.status_code))\n LOG.info(\"Nome do job gerado = {}\".format(r.text))\n\n #RESULT\n LOG.info(\"[{0}] Requesting the URL = {1}...\".format(datetime.now(),EBI_RESULT_URL))\n #Addind the jobid\n result = requests.get(EBI_RESULT_URL+\"{jobID}/aln\".format(jobID=r.text))\n \n #Trying again until 200 is returned\n while (result.status_code is not 200):\n LOG.info(\"[{0}] Result not ready yet...\".format(datetime.now()))\n LOG.info(\"[{0}] Requesting the URL = {1}...\".format(datetime.now(),EBI_RESULT_URL))\n result = requests.get(EBI_RESULT_URL+\"{jobID}/aln\".format(jobID=r.text))\n \n LOG.info(\"[{0}] Results got = {1}...\".format(datetime.now(),result.text))\n\n alignment = get_alignment(result.text)\n\n io.write_file(\"../outputs/ebi_local_output.txt\",str(alignment))\n \n #print(str(alignment))\n\n\n\n\n","sub_path":"src/LocalEBI.py","file_name":"LocalEBI.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"148549299","text":"#Creating the plot of the cumulative average of the uneven time spaced series of the KInetic montecarlo simulation\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nnum_lev=21\nnum_mut=31\ndef readrow(row, cols):\n data = np.fromstring(row, sep=' ')\n data.resize((cols,))\n return data\ndummy='0'\nid_mu='8.0e-06'\nalpha='0.01'\nbeta='0.50'\n#id_mu='mu_8.1e-06_'\nid_epsilon='0.80'\n#='exp_1.50'\nid_rho='.'\ndirectory_name='final_'+'alpha_'+alpha+'_beta_'+beta+'_mu_'+id_mu+'_test_'+id_epsilon+'/'\nfile_bm=directory_name+'bone_marrow_'+dummy\nfile_blood=directory_name+'blood_'+dummy\nfile_delta=directory_name+'delta_'+dummy\nfile_ratios=directory_name+'ratios_'+dummy\nfile=file_delta\nnum_col=4\nbeta=2\nleak_par=5e-9\nbm_original_cellularity=10485750000\nmod_cellularity=bm_original_cellularity/0.5\nx_axis=np.logspace(8,12,num=10000)\nleaking_function=np.zeros_like(x_axis)\nfor i in np.arange(0,np.size(x_axis)):\n leaking_function[i]=1/(1+math.exp(-leak_par*(x_axis[i]-mod_cellularity)))\nrho=np.zeros_like(x_axis)\nfor i in np.arange(0,np.size(x_axis)):\n if x_axis[i]-bm_original_cellularity<=0:\n rho[i]=1\n else:\n rho[i]=np.exp(-0.5*beta*((x_axis[i]-bm_original_cellularity)/bm_original_cellularity))\nwith open(file+'.txt', 'rb') as f:\n data = np.array([readrow(row, num_col) for row in f])\ntime=data[:,0]/365.0\n#print(data[:,2])\ndef delta():\n plt.figure(1)\n# plt.ylim(1e-1,1e1)\n# plt.yscale('log')\n# plt.ylim(2000,3000)\n# plt.scatter(time,data[:,1],label='delta')\n plt.scatter(time,data[:,1],label='leaking')\n# plt.scatter(time,data[:,2],label='cells')\n plt.legend(loc='best', borderaxespad=0, fontsize=10)\n plt.show()\n \ndef cells():\n plt.figure(3)\n plt.scatter(time,data[:,2],label='cells')\n plt.legend(loc='best', borderaxespad=0, fontsize=10)\n plt.show()\n \ndef analytic():\n# plt.ylim(0,1)\n plt.grid('True')\n# plt.xscale('log')\n# plt.yscale('log')\n plt.scatter(x_axis,leaking_function)\n# plt.scatter(x_axis,rho)\n plt.show()\n \n#cells()\n#delta()\n#analytic()\n##################################################################################################\nwith open(file_ratios+'.txt', 'rb') as f:\n data_ratios = np.array([readrow(row, (num_mut+1)*num_lev+1) for row in f])\n\ndef ratios(lev_initiate,lev_final,num_mutation):\n plt.figure(2)\n for i in range(lev_initiate,lev_final):\n plt.scatter(time,data_ratios[:,num_mutation*num_lev+i+1],label=str(i%num_lev))\n plt.grid('True',which='both')\n plt.show()\n plt.ylim(-5,2)\n plt.legend(bbox_to_anchor=(1.0,1.0), borderaxespad=0, fontsize=10)\nratios(16,num_lev,5)","sub_path":"cell_difference_analysis.py","file_name":"cell_difference_analysis.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"539444169","text":"# Yuxin Zhou CMPE285 HW2\nfrom flask import Flask, render_template, request\nimport time\nfrom time import ctime\nfrom time import time as ti\nimport yfinance as yf\nfrom datetime import datetime\nimport pytz\nfrom pytz import timezone\nimport urllib.request\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET', 'POST'])\ndef login():\n error = None\n time_info = None\n name_info = None\n prince_info = None\n \n if request.method == 'POST':\n if request.form['symbol']:\n if connect_internet():\n symbol = request.form['symbol']\n info = get_stock_info(symbol)\n if info:\n time_info = get_time_info()\n name_info = info[0]\n prince_info = info[1]\n else:\n error = \"Input stock symbol does not exisit. Please try again!\"\n else:\n error = \"No internet connection. Please connect to the internet!\"\n else:\n error = \"Empty input. Please try again!\"\n return render_template('index.html', error=error, time_info=time_info, name_info = name_info, prince_info = prince_info)\n\n\ndef get_time_info():\n timezone = pytz.timezone('US/Pacific')\n utc_time = datetime.utcnow()\n time_in_seconds = int(pytz.utc.localize(utc_time, is_dst=None).astimezone(timezone).strftime('%s'))\n current_time = ctime(time_in_seconds)\n current_time_info = current_time.rsplit(\" \", 1)[0]\n year = current_time.rsplit(\" \", 1)[1]\n time_zone_abbr = datetime.now(timezone).strftime(\"%Z\")\n time_print_out = current_time_info + \" \" + time_zone_abbr + \" \" + year\n return time_print_out\n\ndef get_stock_info(symbol):\n ticker = yf.Ticker(symbol)\n info = ticker.info\n todays_data = ticker.history(period='1d')\n if info:\n if 'longName' in info:\n name = info['longName'] + \" (\" + symbol.upper() + \")\"\n current_price = round(todays_data['Close'][0], 2)\n prev_close = info['previousClose']\n value_change = current_price - prev_close\n percentage_change = (value_change / prev_close)*100\n value_change = round(value_change, 2)\n percentage_change = round(percentage_change, 2)\n value_change_str = str(value_change)\n percentage_change_str = str(percentage_change)\n if (value_change > 0):\n value_change_str = \"+\" + str(value_change)\n if (percentage_change > 0):\n percentage_change_str = \"+\" + str(percentage_change)\n price_output = str(current_price) + \" \" + value_change_str + \" (\" + percentage_change_str + \"%)\"\n return [name, price_output]\n else:\n None\n else:\n return None\n\n\n\ndef connect_internet():\n try:\n urllib.request.urlopen('http://google.com') \n return True\n except:\n return False\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256882371","text":"from selenium import webdriver\n\nfrom pages.training_ground_page import TrainingGroundPage\nfrom pages.trial_page import TrialPage\n\n# Test Setup\nbrowser = webdriver.Chrome()\n\n# Trial Page\ntrial_page = TrialPage(driver=browser)\ntrial_page.go()\ntrial_page.stone_input.input_text(\"rock\")\ntrial_page.stone_button.click()\ntrial_page.secret_input.input_text(trial_page.stone_result.text)\ntrial_page.secret_button.click()\nassert trial_page.secret_result.text == 'Success!', \"Unexpected text\"\n\ninput()\n\n# Training Grounds\ntrng_page = TrainingGroundPage(driver=browser)\ntrng_page.go()\nassert trng_page.button1.text == 'Button1', \"Unexpected button1 text\"\n\ninput()\nbrowser.quit()\n","sub_path":"tests/pom_test.py","file_name":"pom_test.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"217215187","text":"from RemoteControl.ControllerReceiver import *\nfrom MotorControl.skidSteering import *\nfrom MotorControl.stickSteering import *\nfrom CameraControl.Streamer import *\nfrom CameraControl.Record import *\nfrom Adafruit_BNO055 import BNO055\nfrom PID.imuPolling import *\nfrom threading import Lock\nfrom threading import Condition\nfrom threading import Event\nfrom picamera import PiCamera\nimport signal\nimport socket\nimport time\n\ninputMap = {\n \"LX\": 0.0,\n \"LY\": 0.0,\n \"RX\": 0.0,\n \"RY\": 0.0,\n \"x_button\": 0.0,\n \"circle\": 0.0,\n \"triangle\": 0.0,\n \"square\": 0.0,\n \"L1\": 0.0,\n \"R1\": 0.0,\n \"L2\": 0.0,\n \"R2\": 0.0,\n \"Select\": 0.0,\n \"Start\": 0.0,\n \"PS_Button\": 0.0,\n \"L3\": 0.0,\n \"R3\": 0.0,\n \"D_Up\": 0.0,\n \"D_Down\": 0.0,\n \"D_Left\": 0.0,\n \"D_Right\": 0.0\n }\n\nimuData = {\n \"pitch\": 0.0,\n \"roll\": 0.0,\n \"heading\": 0.0\n }\n\n\ninputMutex = Lock()\nreaders = 0\npendingWriters = 0\nwriters = 0\nreadLock = Condition(inputMutex)\nwriteLock = Condition(inputMutex)\n\nimuMutex = Lock()\nimuReadLock = Condition(imuMutex)\nimuWriteLock = Condition(imuMutex)\n\nevent = Event()\n\ninputMonitor = {\n \"inputMutex\": inputMutex,\n \"readers\": 0,\n \"writers\": 0,\n \"pendingWriters\": 0,\n \"pendingReaders\": 0,\n \"inputMap\": inputMap,\n \"readLock\": readLock,\n \"writeLock\": writeLock,\n \"imuMutex\": imuMutex,\n \"imuReadLock\": imuReadLock,\n \"imuWriteLock\": imuWriteLock,\n \"imuData\": imuData,\n \"event\": event\n }\n\n\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\nbno = BNO055.BNO055(serial_port='/dev/serial0', rst=18)\nif not bno.begin():\n raise RuntimeError('Failed to initialize BNO055! Is the sensor connected?')\n\ndef handler(signum, handler):\n print(\"signal handler\")\n sock.close()\nsignal.signal(signal.SIGTERM, handler)\n\ndef launcher():\n '''\n Launches peripheral threads with relevant input data\n and synchronization objects. Waits until all threads\n are dead to exit.\n '''\n print(\"Commencing Launcher\\n\")\n rcRcvr = ControllerReceiver(inputMonitor, sock)\n rcRcvr.start()\n\n imuPoll = IMU(inputMonitor, bno)\n imuPoll.start()\n\n skidSteer = SkidSteering(inputMonitor)\n skidSteer.start()\n\n stickSteer = StickSteering(inputMonitor)\n stickSteer.start()\n\n camera = PiCamera(resolution='640x480', framerate=24)\n\n streamer = StreamThread(camera)\n streamer.start()\n\n camCorder = VideoRecorder(inputMonitor, camera)\n camCorder.start()\n\n print('about to wait on join')\n skidSteer.join()\n print('Exited skidSteer')\n stickSteer.join()\n print('Exited stickSteer')\n camCorder.join()\n print('Exited camCorder')\n imuPoll.join()\n print('Exited imuPoll')\n rcRcvr.join()\n print('Exited rcRcvr')\n streamer.server.shutdown()\n print(\"Exited Streamer\")\n if event.is_set():\n exit()\nif __name__=='__main__':\n launcher();\n exit()\n","sub_path":"launcherProgram.py","file_name":"launcherProgram.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"28867520","text":"#!/usr/bin/env python\n\nimport unittest\n\nimport amulet\n\n\nclass TestDeployment(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.d = amulet.Deployment(series='xenial')\n cls.d.add('snapweb-bash')\n cls.d.expose('snapweb-bash')\n cls.d.setup()\n cls.d.sentry.wait()\n\n\n def test_sanity(self):\n self.assertTrue(True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_hello.py","file_name":"test_hello.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"54409072","text":"from selenium import webdriver\nfrom Utilities.readconfigfile import Getinfoconfig\nfrom Objref.Paraobjreferences import Registration\nimport time\nimport pytest\nfrom Utilities import xlutils\nimport os.path\nfrom Utilities.CustomLogger import Logsetup\n\nclass Testbank:\n weburl = Getinfoconfig.wedurlget()\n firstname = Getinfoconfig.firstnameget()\n lastname = Getinfoconfig.lastnameget()\n address = Getinfoconfig.addressget()\n city = Getinfoconfig.cityget()\n state = Getinfoconfig.stateget()\n zipcode = Getinfoconfig.zipcodeget()\n phonenumber = Getinfoconfig.phoneget()\n ssn = Getinfoconfig.phoneget()\n username = Getinfoconfig.usernameget()\n password = Getinfoconfig.passwordget()\n payeename = Getinfoconfig.payeenameget()\n payeeaddress = Getinfoconfig.payeeaddressget()\n payeecity = Getinfoconfig.payeecityget()\n payeestate = Getinfoconfig.payeestateget()\n payeezip = Getinfoconfig.payeezipget()\n payeeph = Getinfoconfig.payeephget()\n payeeaccount = Getinfoconfig.payeeaccountget()\n amount = Getinfoconfig.payeeamount()\n logger = Logsetup.getlogparabank()\n\n @pytest.fixture()\n def browserhandling(self,web):\n self.Openbrowser = web\n self.Openbrowser.get(self.weburl)\n self.logger.info(\"Browser Opening\")\n self.Openbrowser.maximize_window()\n self.refobj = Registration(self.Openbrowser)\n # yield self.refobj.logout()\n\n def testcleardb(self,browserhandling):\n self.refobj.adminpagelink()\n time.sleep(3)\n result= self.refobj.cleardatabase()\n self.Openbrowser.close()\n if result == True:\n assert True\n else:\n assert False\n\n\n def testregister(self,browserhandling):\n self.refobj.registerpage()\n time.sleep(3)\n self.refobj.fillfirsname(self.firstname)\n self.refobj.filllastname(self.lastname)\n self.refobj.filladdress(self.address)\n self.refobj.fillcity(self.city)\n self.refobj.fillstate(self.state)\n self.refobj.fillzipcode(self.zipcode)\n self.refobj.fillphone(self.phonenumber)\n self.refobj.fillssn(self.ssn)\n self.refobj.fillusername(self.username)\n self.refobj.fillpassword(self.password)\n self.refobj.fillpasswordagain(self.password)\n self.refobj.registersubmit()\n title = self.Openbrowser.title\n time.sleep(3)\n self.refobj.logout()\n Act_title = \"ParaBank | Customer Created\"\n if Act_title==title:\n assert True\n else:\n assert False\n\n\n def testlogin(self,browserhandling):\n\n self.refobj = Registration(self.Openbrowser)\n result = self.refobj.login(self.username,self.password)\n time.sleep(5)\n self.refobj.logout()\n if result == True:\n assert True\n else:\n assert False\n\n def testaccountoverview(self,browserhandling):\n\n self.refobj = Registration(self.Openbrowser)\n self.refobj.login(self.username, self.password)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n self.refobj.logout()\n time.sleep(3)\n if os.path.exists(filename) == True:\n assert True\n else:\n assert False\n\n def testcheckingaccont(self,browserhandling):\n\n self.refobj = Registration(self.Openbrowser)\n self.refobj.login(self.username,self.password)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n newaccount = self.refobj.accountcreation(\"checking\",filename)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n self.refobj.logout()\n rows= xlutils.getrowcount(filename,\"Sheet1\")\n for row in range(2,rows):\n accountnumber= xlutils.readfromxl(filename,\"Sheet1\",row,1)\n #print(accountnumber, newaccount)\n if newaccount==accountnumber:\n mark = \"sucess\"\n break\n else:\n mark = \"not found\"\n continue\n if mark == \"sucess\":\n print (\"Checking account- \",newaccount,\" created sucessfully\")\n self.logger.info(\"Checking account created\")\n assert True\n else:\n print (\"failure to create a new account\")\n self.logger(\"Checking account not created\")\n assert False\n\n\n def testsavingsaccont(self,browserhandling):\n\n self.refobj = Registration(self.Openbrowser)\n self.refobj.login(self.username,self.password)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n newaccount = self.refobj.accountcreation(\"savings\",filename)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n self.refobj.logout()\n rows= xlutils.getrowcount(filename,\"Sheet1\")\n for row in range(2,rows):\n accountnumber= xlutils.readfromxl(filename,\"Sheet1\",row,1)\n #print(accountnumber,newaccount)\n if newaccount==accountnumber:\n mark = \"sucess\"\n break\n else:\n mark = \"not found\"\n continue\n if mark == \"sucess\":\n print (\"Savings account- \",newaccount,\" created sucessfully\")\n self.logger.info(\"Savings account created\")\n assert True\n else:\n print (\"failure to create a new account\")\n self.logger.info(\"Saving account not created\")\n assert False\n\n def testpaybill(self,browserhandling):\n\n self.refobj.login(self.username,self.password)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n self.refobj.clickpaybill()\n time.sleep(3)\n self.refobj.inputpayeename(self.payeename)\n self.refobj.inputpayeeaddres(self.payeeaddress)\n self.refobj.inputpayeecity(self.payeecity)\n self.refobj.inputpayeestate(self.payeestate)\n self.refobj.inputpayeezipcode(self.payeezip)\n self.refobj.inputpayeeph(self.payeeph)\n self.refobj.inputpayeeaccount(self.payeeaccount)\n self.refobj.inputpayeeverify(self.payeeaccount)\n self.refobj.inputpayeeamount(self.amount)\n time.sleep(3)\n accountnumber= xlutils.readfromxl(filename,\"Sheet1\",2,1)\n self.refobj.selectbillpayaccount(accountnumber)\n time.sleep(3)\n self.refobj.clickpaymentbutton()\n time.sleep(3)\n msg = self.Openbrowser.find_element_by_xpath(\"//h1[contains(text(),'Bill Payment Complete')]\").text\n time.sleep(3)\n self.refobj.logout()\n if msg == \"Bill Payment Complete\":\n self.logger.info(\"Bill pay sucessful\")\n print (\"Bill Payment to \",self.payeename, \"in the amount of \",self.amount, \"from account \",accountnumber,\" was successful.\")\n assert True\n else:\n print(\"Payment failure\")\n self.logger.info(\"Bill payment failed\")\n assert False\n\n def testamounttransfer(self,browserhandling):\n\n self.refobj.login(self.username,self.password)\n filename = self.refobj.accountoverview()\n time.sleep(3)\n result = self.refobj.transferaccount(filename)\n time.sleep(3)\n self.refobj.logout()\n if result == True:\n assert True\n self.logger.info(\"Account transfer sucessful\")\n else:\n self.logger.info(\"Account transfer not sucessful\")\n assert False\n\n","sub_path":"Testcases/test_parabanktesting.py","file_name":"test_parabanktesting.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"336811683","text":"from PIL import Image\nimport glob\nimport re\nimport os\nimport numpy as np\n\nmode = \"test\"\npath_to_segmented_images = \"/home/ghadeer/Projects/Datasets/Sber2400/\"+mode+\"/Semantic\"\npath_to_floor_labels_folders = \"/home/ghadeer/Projects/Datasets/Sber2400/\"+mode+\"/All_Floor\"\npath_to_all_and_floor_labels_folders = \"/home/ghadeer/Projects/Datasets/Sber2400/\"+mode+\"/All_and_Floor\"\nsegmented_images = []\n\nfor img_path in glob.glob(path_to_segmented_images+'/*'):\n segmented_images.append(img_path)\nos.makedirs(path_to_floor_labels_folders, exist_ok=True)\n\nlabels = open(\"labelmap.txt\", \"r\")\n# remove the header line from the file.\nx = labels.readline()\n\n# get the labels in the image with the corresponding color for each label\nlabels_dict = {}\nfor x in labels:\n x = re.split('[:]', x)\n name = x[0]\n vals = re.split('[,]', x[1])\n vals_int = [int(s) for s in vals]\n labels_dict[name] = vals_int\n\nfor class_ in labels_dict.keys():\n if class_ == \"Trash\" or class_ == \"Background\" or class_ == \"background\":\n continue\n\n\nfor img_path in segmented_images:\n img = Image.open(img_path)\n img_name = re.split('/',img_path)[-1]\n img_size = img.size\n img = img.convert(\"RGB\")\n masks = {}\n for key in labels_dict.keys():\n if key == \"Trash\" or key == \"Background\" or key == \"background\":\n continue\n masks[key] = []\n all_optical = []\n datas = img.getdata()\n # print(masks.keys())\n\n\n img_np = np.array(img)[:,:,0]\n for key in masks.keys():\n masks[key] = np.array(img_np==labels_dict[key][0])\n glass_and_mirror = np.logical_or(masks[\"Glass\"], masks[\"Mirror\"])\n all_optical = np.logical_or(glass_and_mirror, masks[\"Other optical surface\"])\n all_floor = np.logical_or(masks[\"Floor under obstacle\"], masks[\"Floor\"])\n\n\n curr_mask = Image.fromarray(all_floor)\n curr_mask = curr_mask.convert('1')\n curr_mask = curr_mask.convert('RGB')\n curr_mask.save(path_to_floor_labels_folders+\"/\"+img_name)\n","sub_path":"useful code/get_floor_mask.py","file_name":"get_floor_mask.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"169479651","text":"import time\nimport serial\n\n# configure the serial connections (the parameters differs on the device you are connecting to)\nser = serial.Serial(\n port='/dev/tty.usbmodem1422',\n baudrate=9600,\n stopbits=serial.STOPBITS_TWO,\n bytesize=serial.EIGHTBITS\n)\n\noutput_bin_file='/desktop/testouput.bin'\ninput_bin_file='/desktop/testinput.bin'\n\nser.isOpen()\n\ndef write_back(buffered_data):\n with open(in_bin_file, \"rb\") as f:\n f.write(buffered_data)\n f.close()\n\ndef open_file(out_bin_file):\n with open(out_bin_file, \"rb\") as f:\n byte = f.read(1)\n while byte != \"\":\n write_data(byte)\n byte = f.read(1)\n byte = 'exit'\n\ndef write_data(binary_string):\n if binary_string == 'exit':\n ser.close()\n exit()\n else:\n ser.write(binary_string + '\\r\\n')\n out = ''\n time.sleep(0.00000868)\n while ser.inWaiting() > 0:\n buffered_data += ser.read(1)\n\ndef main():\n open_file(bin_file)\n","sub_path":"Python/Serial_Server/serial-python.py","file_name":"serial-python.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"345986426","text":"#!/usr/bin/python3\n# _*_ coding:utf-8 _*_\n\ndef main():\n a = int(input())\n for i in range(a):\n b=input()\n if len(b) <= 10:\n print(b)\n else:\n print(b[0]+str(len(b)-2)+b[len(b)-1])\n\n\ndef main2():\n b=int(input())\n for i in range(b):\n b=input()\n print(b if len(b) < 11 else b[0]+str(len(b)-2)+b[len(b)-1])\n\n\n\n\nif __name__ == \"__main__\":\n #main()\n main2()\n","sub_path":"Way_Too_Long_Words.py","file_name":"Way_Too_Long_Words.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"102707765","text":"import os\nimport time\nimport pdb\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom kalman_filter import KalmanFilter\nfrom os import path\n\nDOWNLOAD = 'wget https://data.nvision2.eecs.yorku.ca/PIE_dataset/PIE_clips/set01/video_0001.mp4 -P dataset/'\nDATASET = 'dataset/video_0001.mp4'\n\ndef downloadDataset():\n print(\"Checking for\", DATASET)\n print(\"Exists:\", path.exists(DATASET))\n\n if not path.exists(DATASET):\n print(\"Dataset does not exist. Downloading.\\n\\n\")\n os.system(DOWNLOAD)\n \n\ndef loadFrames(vid_name):\n return cv2.VideoCapture(vid_name)\n\ndef DrawRectangle(img, bbox, color=(255, 0, 0), thickness=2):\n # Draw rectangle given XYWH bounding box\n X, Y, W, H = bbox[0,0], bbox[1,0], bbox[2,0], bbox[3,0]\n return cv2.rectangle(img, (X, Y), (X+W, Y+H), color, thickness)\n\ndef SkipToInteresting(cap):\n # Movement doesn't start until around 27s on video 1\n # 27s * 30fps = frame (27 * 30)\n clear_frames = 27 * 30\n for i in range(clear_frames):\n is_frame_good, frame = video.read()\n if not is_frame_good:\n return\n\nclass StaticCapture:\n # Emulates the VideoCapture interface, but on a set of static images\n # Seems to run a bit quicker than loading from the mp4\n def __init__(self):\n self.iteration = 0\n \n def read(self):\n if self.iteration > 500:\n return False, None\n self.iteration += 1\n img = cv2.imread(f'outimgs/out{self.iteration}.jpg')\n return True, img\n\ndef DrawBoundingBox(frame):\n # Function to let you quickly draw bounding boxes\n calib_win = 'bbox'\n cv2.namedWindow(calib_win)\n x_val = 0\n y_val = 0\n w_val = 0\n h_val = 0\n def x_cb(val): nonlocal x_val; x_val = val\n def y_cb(val): nonlocal y_val; y_val = val\n def w_cb(val): nonlocal w_val; w_val = val\n def h_cb(val): nonlocal h_val; h_val = val\n cv2.createTrackbar('X', calib_win, 0, frame.shape[0], x_cb)\n cv2.createTrackbar('Y', calib_win, 0, frame.shape[1], y_cb)\n cv2.createTrackbar('W', calib_win, 0, frame.shape[0], w_cb)\n cv2.createTrackbar('H', calib_win, 0, frame.shape[1], h_cb)\n original_frame = frame.copy()\n while True:\n bbox = np.array([ [x_val], [y_val], [w_val], [h_val]])\n frame = original_frame.copy()\n DrawRectangle(frame, bbox)\n cv2.imshow(calib_win, frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nclass Sift():\n def __init__(self, img_color, bbox):\n self.img_prev = None\n self.keypoints_prev = None\n self.desc_prev = None\n self.bbox_prev = None\n\n self.img_curr = None\n self.keypoints_curr = None\n self.desc_curr = None\n self.bbox_curr = None\n self.sift_obj = cv2.SIFT_create()\n\n # Setup initial images\n self.ProcessImg(img_color, bbox)\n\n def ProcessImg(self, img_color, bbox):\n # Convert to grayscale\n img = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)\n\n # Store previous img, kp, desc, and bbox\n self.img_prev = self.img_curr\n self.keypoints_prev = self.keypoints_curr\n self.desc_prev = self.desc_curr\n self.bbox_prev = self.bbox_curr\n\n # Set current img, kp, desc, and bbox\n self.img_curr = img\n self.bbox_curr = bbox\n self.keypoints_curr, self.desc_curr = self.GetKpAndDesc(self.img_curr, bbox)\n\n if self.img_prev is None:\n return\n\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(self.desc_curr, self.desc_prev, k=2)\n good = []\n for m, n in matches:\n # TODO: tune this parameter\n if m.distance < 0.8 * n.distance:\n good.append([m])\n # Least Squares\n # Currently using weighted least squares, biased towards center since \n # that seems to help a bit with avoiding the tracking getting \n # attached to a building\n num_match = len(good)\n A_x = np.ones((num_match, 2), dtype=np.float64)\n A_y = np.ones((num_match, 2), dtype=np.float64)\n b_x = np.ones((num_match), dtype=np.float64)\n b_y = np.ones((num_match), dtype=np.float64)\n X, Y, W, H = self.bbox_prev[0,0], self.bbox_prev[1,0], self.bbox_prev[2,0], self.bbox_prev[3,0]\n w_vals = np.ones((num_match), dtype=np.float64)\n cx = X + W/2.0\n cy = Y + H/2.0\n for i in range(len(good)):\n m, = good[i]\n #print(keypoints[m.queryIdx].pt, self.keypoints_prev[m.trainIdx].pt)\n b_x[i] = self.keypoints_curr[m.queryIdx].pt[0]\n b_y[i] = self.keypoints_curr[m.queryIdx].pt[1]\n w_vals[i] = (b_x[i] - cx) ** 2.0 + (b_y[i] - cy) ** 2.0\n A_x[i,1] = (self.keypoints_prev[m.trainIdx].pt[0] - X) / float(W)\n A_y[i,1] = (self.keypoints_prev[m.trainIdx].pt[1] - Y) / float(H)\n w_vals = np.max(w_vals) - w_vals\n A_x = A_x * w_vals[:,np.newaxis]\n A_y = A_y * w_vals[:,np.newaxis]\n b_x = b_x * w_vals\n b_y = b_y * w_vals\n # Least squares solutions, [X, W].T, and [Y, H].T\n lst_sln_x = np.linalg.lstsq(A_x, b_x, rcond=None)\n lst_sln_y = np.linalg.lstsq(A_y, b_y, rcond=None)\n pred_bb = np.array([ [lst_sln_x[0][0]], [lst_sln_y[0][0]], [lst_sln_x[0][1]], [lst_sln_y[0][1]]])\n\n # Draw Matches and show\n # matched_img2 = np.zeros_like(self.img_curr)\n # matched_img = cv2.drawMatchesKnn(self.img_curr, self.keypoints_curr, self.img_prev, self.keypoints_prev, good, flags=2, outImg=matched_img2)\n # cv2.imshow('matched_img', matched_img)\n\n pred_bb = pred_bb.astype(np.int64)\n return pred_bb\n\n def GetKpAndDesc(self, img, bbox):\n # TODO: Figure out what to do about bounding box collapse\n # SIFTING the whole 1080p image takes a very long time,\n # but the bounding box collapses pretty easily if you only search\n # inside of it due to the nature of least squares only searching\n # within the box\n mask_img = np.ones_like(img)\n # Only use bounding box region as mask\n # X, Y, W, H = bbox[0,0], bbox[1,0], bbox[2,0], bbox[3,0]\n # margin = 0.0\n # X = X - margin * W\n # Y = Y - margin * H\n # W = W + W * 2.0 * margin\n # H = H + H * 2.0 * margin\n # mask_bbox = np.array([[X], [Y], [W], [H]], dtype=np.int64)\n # mask_img = np.zeros_like(img)\n # DrawRectangle(mask_img, mask_bbox, color=(255), thickness=-1)\n return self.sift_obj.detectAndCompute(img, mask=mask_img)\n\n\nif __name__ == '__main__':\n downloadDataset()\n # XYWH\n # bounding_box = np.array([ [867], [714], [394], [328]])\n bounding_box = np.array([ [915], [742], [298], [229]])\n\n # Initialize KF\n kf = KalmanFilter(initial_bb=bounding_box, \n dt=0.1, covar=0.1, \n proc_noise=0.0, alpha=0.98, \n r_1_xy=10.0, r_1_wh=5.0, \n r_2_xy=0.0, r_2_wh=5.0)\n # Load from MP4. Movement starts at around 27-28s for video 1\n video = loadFrames(DATASET)\n SkipToInteresting(video)\n\n # It seems to run a bit faster running off of static images\n # plus you can skip frames to see movement more quickly\n #video = StaticCapture()\n\n is_frame_good, initial_frame = video.read()\n\n # Use this for getting bounding box information\n # DrawBoundingBox(initial_frame)\n \n # Initialize SIFT\n sift = Sift(initial_frame, bounding_box)\n\n # While testing, don't run on too many frames\n iteration = 0\n while is_frame_good and iteration <= 200:\n # Read a frame\n is_frame_good, frame = video.read()\n if not is_frame_good:\n break\n # To generate static image directory for use with StaticCapture\n # cv2.imwrite(f'outimgs/out{iteration}.jpg', frame)\n # iteration += 1\n # continue\n\n # Compute Sift predicted\n bounding_box = sift.ProcessImg(frame, bounding_box)\n\n # Apply Kalman Filter\n bounding_box = kf.update(bounding_box)\n\n # Convert to int\n bounding_box = bounding_box.astype(np.int64)\n\n # Draw bounding box\n frame = DrawRectangle(frame, bounding_box)\n\n # Show image\n cv2.imshow('Frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n iteration += 1\n","sub_path":"motion_driver2.py","file_name":"motion_driver2.py","file_ext":"py","file_size_in_byte":8413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"532117720","text":"from random import seed\r\n\r\n# fix randomness; DO NOT CHANGE THIS\r\nseed(1234)\r\n\r\n\r\ndef naive_bayes(train_path, test_path):\r\n \"\"\"\r\n Performs naive Bayes classification\r\n :param train_path: path of the training set, a string\r\n :param test_path: path of the test set, a string\r\n :return: percent accuracy value for the test set, e.g., 85.43\r\n \"\"\"\r\n label_array = []\r\n feature_array = []\r\n probability_array = []\r\n\r\n test_data = open_input_file(test_path)\r\n train_data = open_input_file(train_path)\r\n\r\n first_line = train_data[0]\r\n first_line_splitted = first_line.split(',')\r\n feature_number = len(first_line_splitted) - 1\r\n\r\n for i in range(feature_number):\r\n tmp_list = []\r\n feature_array.append(tmp_list)\r\n\r\n # Checking test data to find all possible labels\r\n for line in test_data:\r\n if line[-1] == '\\n':\r\n line = line[:-1]\r\n tmp_line_splitted = line.split(',')\r\n tmp_label = tmp_line_splitted[-1]\r\n if not is_in_list(label_array, tmp_label):\r\n tmp_list = []\r\n tmp_list.append(tmp_label)\r\n tmp_list.append(0)\r\n label_array.append(tmp_list)\r\n\r\n # Checking train data to find possible all labels\r\n for line in train_data:\r\n if line[-1] == '\\n':\r\n line = line[:-1]\r\n tmp_line_splitted = line.split(',')\r\n tmp_label = tmp_line_splitted[-1]\r\n if not is_in_list(label_array, tmp_label):\r\n tmp_list = []\r\n tmp_list.append(tmp_label)\r\n tmp_list.append(1)\r\n label_array.append(tmp_list)\r\n else:\r\n for label in label_array:\r\n if label[0] == tmp_label:\r\n label[1] = label[1] + 1\r\n # Checking test data to find all possible feature values\r\n for line in test_data:\r\n if line[-1] == '\\n':\r\n line = line[:-1]\r\n tmp_line_splitted = line.split(',')\r\n tmp_label = tmp_line_splitted[-1]\r\n for index in range(feature_number):\r\n for each_label in label_array:\r\n if not is_in_feature_list(feature_array, tmp_line_splitted[index], each_label[0], index):\r\n tmp_list = []\r\n tmp_list.append(index)\r\n tmp_list.append(tmp_line_splitted[index])\r\n tmp_list.append(each_label[0])\r\n tmp_list.append(0)\r\n feature_array[index].append(tmp_list)\r\n # Checking train data to find all possible feature values\r\n for line in train_data:\r\n if line[-1] == '\\n':\r\n line = line[:-1]\r\n tmp_line_splitted = line.split(',')\r\n tmp_label = tmp_line_splitted[-1]\r\n for index in range(feature_number):\r\n for each_label in label_array:\r\n if not is_in_feature_list(feature_array, tmp_line_splitted[index], each_label[0], index):\r\n tmp_list = []\r\n tmp_list.append(index)\r\n tmp_list.append(tmp_line_splitted[index])\r\n tmp_list.append(each_label[0])\r\n tmp_list.append(0)\r\n feature_array[index].append(tmp_list)\r\n if not is_in_feature_list(feature_array, tmp_line_splitted[index], tmp_label, index):\r\n tmp_list = []\r\n tmp_list.append(index)\r\n tmp_list.append(tmp_line_splitted[index])\r\n tmp_list.append(tmp_label)\r\n tmp_list.append(1)\r\n feature_array[index].append(tmp_list)\r\n else:\r\n tmp_list = feature_array[index]\r\n for list_item in tmp_list:\r\n if list_item[0] == index and list_item[1] == tmp_line_splitted[index] and list_item[2] == tmp_label:\r\n list_item[3] = list_item[3] + 1\r\n\r\n # For each entry in test data, calculate the probabilities according to data above and make guess\r\n number_of_correct_guess = 0\r\n for test_instance in test_data:\r\n possibility_array = []\r\n for each_label in label_array:\r\n tmp_label = each_label[0]\r\n tmp_label_probability = 1\r\n tmp_probability_array = [tmp_label, tmp_label_probability]\r\n possibility_array.append(tmp_probability_array)\r\n\r\n p_temp = 1\r\n if test_instance[-1] == '\\n':\r\n test_instance = test_instance[:-1]\r\n tmp_line_splitted = test_instance.split(',')\r\n real_label = tmp_line_splitted[-1]\r\n for index in range(feature_number):\r\n for feature_order in feature_array[index]:\r\n for pos in possibility_array:\r\n if feature_order[0] == index and feature_order[1] == tmp_line_splitted[index] and pos[0] == feature_order[2]:\r\n label_number = 1\r\n for each_label in label_array:\r\n if each_label[0] == pos[0]:\r\n label_number = each_label[1]\r\n\r\n pos[1] = pos[1] * (feature_order[3] / label_number)\r\n\r\n dummy_index = 1\r\n for each_pos in possibility_array:\r\n for each_label in label_array:\r\n if each_pos[0] == each_label[0]:\r\n dummy_index = dummy_index + 1\r\n possibilit_of_class = each_label[1] / len(train_data)\r\n each_pos[1] = each_pos[1] * possibilit_of_class\r\n\r\n highest_probability = - 1\r\n model_guess = 'dummy'\r\n\r\n for guess in possibility_array:\r\n if guess[1] > highest_probability:\r\n highest_probability = guess[1]\r\n model_guess = guess[0]\r\n\r\n if model_guess == real_label:\r\n number_of_correct_guess = number_of_correct_guess + 1\r\n accuracy = (number_of_correct_guess / len(test_data)) * 100\r\n print(round(accuracy, 2))\r\n\r\n\r\ndef open_input_file(file_path):\r\n file = open(file_path, 'r')\r\n lines = file.readlines()\r\n return lines\r\n\r\n\r\ndef is_in_list(list_input, item):\r\n if len(list_input) == 0:\r\n return False\r\n for list_item in list_input:\r\n if item == list_item[0]:\r\n return True\r\n return False\r\n\r\n\r\ndef is_in_feature_list(feature_array_input, item, label, feature_number):\r\n tmp_list = feature_array_input[feature_number]\r\n if len(tmp_list) == 0:\r\n return False\r\n for list_item in tmp_list:\r\n if list_item[1] == item and list_item[2] == label:\r\n return True\r\n return False\r\n\r\n\r\ndef is_in_possibility_array(p_array, key):\r\n if len(p_array) == 0:\r\n return False\r\n for entry in p_array:\r\n if entry[0] == key:\r\n return True\r\n\r\n return False\r\n\r\n\r\nnaive_bayes('task1_data/train.txt', 'task1_data/test.txt')","sub_path":"task1_new.py","file_name":"task1_new.py","file_ext":"py","file_size_in_byte":6815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"649699118","text":"import pandas as pd\nimport sqlalchemy as db\nfrom sqlalchemy.engine.url import URL\n\nfrom siamese.io.path_definition import get_project_dir\nfrom siamese.settings import MYSQL_APPAREL_DATABASE_CONFIG, MYSQL_SHOE_DATABASE_CONFIG\n\ndef set_db_connection(fashion: str) -> URL:\n\n # %% CHECK24 Credentials\n\n database_config = eval(f'MYSQL_{fashion}_DATABASE_CONFIG')\n db_connect_live_slave = URL(database_config['drivername'],\n host=database_config['host'],\n port=database_config['port'],\n username=database_config['username'],\n password=database_config['password'])\n\n return db_connect_live_slave\n\n\ndef load_image(fashion: str) -> pd.DataFrame:\n \"\"\"\n\n Args:\n fashion: fashion type for the server\n\n Returns:\n A dataframe containing image paths and the corresponding metadata\n \"\"\"\n\n sql_query = \"\"\"\n SELECT p.id as 'inventory_product_id',\n va.variation_id,\n mo.category_id, \n IFNULL(JSON_UNQUOTE(JSON_EXTRACT(JSON_MERGE_PATCH(JSON_OBJECTAGG(IFNULL(pa.name, ''), pa.value), JSON_OBJECTAGG(IFNULL(va.name, ''), va.value), JSON_OBJECTAGG(IFNULL(ma.name, ''), ma.value)), '$.brand')), '') AS manufacturer_brand\n FROM backofficeinventory_products.product p \n JOIN backofficeinventory_products.variation v ON (p.variation_id = v.id)\n JOIN backofficeinventory_products.model mo ON (v.model_id = mo.id)\n LEFT JOIN backofficeinventory_products.attribute pa ON (pa.product_id = p.id)\n LEFT JOIN backofficeinventory_products.attribute va ON (va.variation_id = v.id)\n LEFT JOIN backofficeinventory_products.attribute ma ON (ma.model_id = mo.id)\n group by p.id\n \"\"\"\n\n db_connect_live_slave = set_db_connection(fashion)\n engine = db.create_engine(db_connect_live_slave)\n\n with engine.connect() as connection:\n db2_manufacturer = pd.read_sql(sql_query, connection)\n\n db2_manufacturer = db2_manufacturer.dropna(how='any').drop(labels=['product_id'], axis=1).\\\n drop_duplicates(subset=['variation_id'])\n\n sql_query = \"\"\"\n SELECT m.variation_id, m.legacy_cdn_url, m.view_angle\n FROM backofficeinventory_products.media m\n WHERE m.view_angle in ('side_r', 'front_r', 'side_l', 'front_l', 'back_r', 'back_l')\n \"\"\"\n\n with engine.connect() as connection:\n db2_media = pd.read_sql(sql_query, connection)\n\n db2_media = db2_media.merge(db2_manufacturer, on='variation_id')\n\n # since we are going to use straitified process for sampling, drop all images without brand and category\n\n db2_media.dropna(subset=['category_id', 'manufacturer_brand'], inplace=True)\n\n return db2_media.merge(db2_manufacturer, on='variation_id')\n\n\nif __name__ == \"__main__\":\n\n db2 = load_image(fashion='SHOE')\n\n db2.to_csv(f\"{get_project_dir()}/data/train/shoe_image_index.csv\")\n\n\n\n","sub_path":"siamese/io/sql_connection_definition.py","file_name":"sql_connection_definition.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"186554744","text":"import numpy as np\nimport pylab as plt\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom collections import deque\nfrom collections import defaultdict\nfrom tjays import spaces\nimport seeding\nimport math\nimport random\nfrom random import randint\nfrom numpy import random, dstack\nimport time\n\nclass FogIoT:\n def __init__(self, deltaval, pw1, pw2, pw3, pw4, pw5, pw6):\n ##Paremeters of actions\n self.cdelta = deltaval#0.000001#0.25 # in meters\n self.p1 = pw1 #0.001 # in watts\n self.p2 = pw2 #0.01\n self.p3 = pw3 #0.15\n self.p4 = pw4 #0.2\n self.p5 = pw5 #0.25\n self.p6 = pw6 #0.3\n #self.plev = [0.001, 0.01, 0.15, 0.2, 0.25, 0.3]\n\n ## energy drain J expressed as percentage\n self.ed1 = 0.006\n self.ed2 = 0.004\n self.ed3 = 0.001\n self.ed4 = 0.002\n self.ed5 = 0.003\n self.ed6 = 0.005\n self.ed7 = 0.007\n self.ed8 = 0.009\n self.ed9 = 0 #not moving or transmiting\n\n\n self.min_outage = 0\n self.max_outage = 100\n self.min_energy_fog = 0\n self.max_energy_fog = 100\n self.min_energy_IoT = 0\n self.max_energy_IoT = 100\n self.min_delta = -35\n self.max_delta = 35\n self.goal_outage = 5 # 5% tolerable outage\n self.goal_ef = 0\n self.goal_ei = 0\n\n self.min_nebo = 0\n self.max_nebo = 2 #means greater than one nebo\n\n #new attributes\n self.obs = np.array([np.random.randint(0, 80), np.random.randint(95, 100), np.random.randint(0, 3)])\n self.ECI = 0\n self.ECF = 0\n self.sum_pack = 0\n self.final_pack = 0\n self.deltak = np.random.randint(-5, 5)\n self.sensorpower= random.uniform(0, 0.3)\n self.packets_holder = []\n self.fog_energy_holder = []\n self.final_packets_holder = []\n self.outage, self.ef, self.neigbour_support = self.obs\n self.done = bool(self.outage< self.goal_outage and self.ef>self.goal_ef and self.neigbour_support == 0)\n self.dead = bool(self.ef == 0)\n\n\n self.low = np.array([self.min_outage, self.min_energy_fog, self.min_nebo])\n self.high = np.array([self.max_outage, self.max_energy_fog, self.max_nebo])\n\n self.action_space = spaces.Discrete(3)\n self.trigger_space = spaces.Discrete(5)\n self.observation_space = spaces.Box(self.low, self.high, dtype=np.float32)\n\n self.iteration_steps = 100000\n self.episodes=100\n\n self.alpha = 0.1\n self.gamma =0.9\n\n #len_action=8\n #len_states =100\n self.buckets =(3,3,3,) # learn\n\n #Q = np.zeros(shape=[len_states, len_action], dtype=np.float32)\n self.Q = np.zeros(self.buckets + (self.action_space.n,))\n\n #Q = defaultdict(lambda: np.zeros(action_space.n))\n\n\n\n\n def step(self, action, IoTTrigger):\n assert self.action_space.contains(action), \"%r (%s) invalid\" % (action, type(action))\n assert self.trigger_space.contains(IoTTrigger), \"%r (%s) invalid\" % (IoTTrigger, type(IoTTrigger))\n \n #global self.obs:#, self.ECF, self.ECI, self.deltak, self.delta, self.sensorpower\n self.outage, self.ef, self.neigbour_support = self.obs \n if action==0:\n self.delta = self.cdelta\n self.ECF= self.ed1 #Energy consumed by fog node\n #self.ef -= self.ECF\n elif action==1:\n self.delta = -self.cdelta\n self.ECF= self.ed2\n #self.ef -= self.ECF\n elif action==2: #not moving or transmiting\n self.ECF= self.ed9\n self.ef -= self.ECF\n\n if IoTTrigger==0:\n self.sensorpower = self.p1\n self.ECI= self.ed3\n self.redundant = 0\n elif IoTTrigger==1:\n self.sensorpower = self.p2\n self.ECI= self.ed4\n self.redundant = 1\n elif IoTTrigger==2:\n self.sensorpower = self.p3\n self.ECI= self.ed5\n self.redundant = 2\n elif IoTTrigger==3:\n self.sensorpower = self.p4\n self.ECI= self.ed6\n self.redundant = 3\n elif IoTTrigger==4:\n self.sensorpower = self.p5\n self.ECI= self.ed7\n self.redundant = 4\n elif IoTTrigger==5:\n self.sensorpower = self.p6\n self.ECI= self.ed8\n self.redundant = 5\n\n if action==0 or action==1:\n self.Power_sensor = 0.1\n self.Power_relay = 0.30 \n self.alpha = 3\n self.Noise = 2*(10**-7)\n self.gamma = 1\n\n self.deltak += self.delta\n self.deltak = np.clip(self.deltak, self.min_delta, self.max_delta)\n self.PP= np.sqrt((self.Noise * self.gamma)/(self.Power_relay *(35 + self.deltak)**(-self.alpha)))\n self.ZZ = (-self.Noise * self.gamma)/(self.Power_sensor *(40+self.deltak)**(-self.alpha))\n self.p_out = 100*(1 - (1 + 2* (self.PP**2) * np.log(2))*(np.exp(self.ZZ)))\n self.outage = np.max([0,self.p_out])\n elif action == 2:\n self.p_out = 100\n self.outage = np.max([0,self.p_out])\n\n\n if self.ef==0:\n self.outage = self.max_outage\n \n self.outage = np.clip(self.outage, self.min_outage, self.max_outage)\n\n\n self.ef -= self.ECF\n \n self.ef = np.clip(self.ef, self.min_energy_fog, self.max_energy_fog)\n \n self.neigbour_support = self.redundant\n \n self.done = bool(self.outage< self.goal_outage and self.ef>self.goal_ef)\n self.dead = bool(self.ef == 0)\n if self.done:\n rew = 100\n else:\n rew = 0\n self.reward = rew\n\n\n self.obs = (self.outage, self.ef, self.neigbour_support)\n return np.array(self.obs), self.reward, self.done, self.dead, {}\n \n\n \n def grouping(self, obs):\n upper_bounds = [self.observation_space.high[0], self.observation_space.high[1], self.observation_space.high[2]]\n lower_bounds = [self.observation_space.low[0], self.observation_space.low[1], self.observation_space.low[2]]\n ratios = [(obs[i] + abs(lower_bounds[i]))/ (upper_bounds[i] - lower_bounds[i]) for i in range(len(obs))]\n new_obs = [int(round((self.buckets[i]-1)*ratios[i])) for i in range(len(obs))]\n new_obs = [min(self.buckets[i] - 1, max(0, new_obs[i])) for i in range(len(obs))]\n return tuple(new_obs)\n\n\n\n\n def update_q(self, current_state, new_state, action, reward, alpha, gamma):\n self.Q[current_state][action] = (1- alpha)*self.Q[current_state][action] + alpha*(reward + self.gamma* max(self.Q[new_state]))\n \n\n\n def select_action(self, epsilon, state):\n '''\n If the random number is greater than epsilon\n then we exploit else we explore.\n '''\n \n if random.random() < epsilon:\n action = self.action_space.sample() # Explore action space\n else:\n action = np.argmax(self.Q[state]) # Exploit learned values\n return action\n\n\n def runCentral(self,colorx, cutoff, labelx):\n self.packets_holder = []\n self.final_packets_holder = []\n self.fog_energy_holderk = []\n\n for epi in range(self.episodes):\n\n #cutoff is to minimize\n\n\n self.ECI = 0\n self.ECF = 0\n self.deltak = np.random.randint(-5, 5)\n self.sensorpower= random.uniform(0, 0.3)\n #self.delta=0.1\n self.dd=0\n #np.random.randint() --discrete uniform distribution\n self.obs = np.array([np.random.randint(0, 80), np.random.randint(95, self.max_energy_fog), np.random.randint(0, 5)])\n \n\n cur_action = self.action_space.sample()\n trigger = self.trigger_space.sample()\n obs, reward, done, dead, _ = self.step(cur_action, trigger)\n #print(obs)\n\n current_state = self.grouping(obs)\n #print('state before',current_state)\n \n \n\n \n iter=0\n self.sum_pack = 0\n self.final_pack = 0\n while ((iter < self.iteration_steps) and not done):#(current_state[0]>=8 and current_state[1]>0 and current_state[2]> 0)): #current_state[0]!= 0):\n\n iter+=1\n \n #linear\n #epsilon =1-(epi/1000)\n\n #exp decay\n self.epsilon =1#float(np.exp(-0.009*epi))\n alpha=0.1\n gamma =0.9\n\n #print(epsilon)\n action = self.select_action(self.epsilon, current_state)\n triggerx = self.trigger_space.sample()\n obs, reward, done, dead, _ = self.step(action, triggerx)\n \n \n\n #do the mapping from obs to state\n\n \n new_state = self.grouping(obs)\n reward_tj = reward#self.map_reward(new_state)\n #print(obs[0])\n #print(new_state)\n #self.sum_pack+=(100 - obs[0])\n \n \n # do learning thingy\n\n \n \n \n #save current state\n current_state = new_state\n \n\n if done:\n #print(\"Reached goal state\")\n #print(reward_tj)\n break\n if dead:\n #print(\"No more communications\")\n break\n if epi>59:\n #self.ave_pack = self.sum_pack/iter\n self.final_pack = (100 - obs[0])\n self.fog_cons = 100 - obs[1]\n #print(\"End of episode #\",epi, \" in \", iter , \"iterations\")\n #self.packets_holder.append(self.ave_pack)\n self.final_packets_holder.append(self.final_pack)\n self.fog_energy_holderk.append(self.fog_cons)\n #print(self.final_packets_holder) \n #self.line2, =plt.plot(self.packets_holder, label=labelx)\n #self.line1, =plt.plot(self.final_packets_holder, label=labelx)\n #plt.setp(self.line1, color= colorx, linewidth=1.0)\n #plt.setp(self.line2, color= colory, linewidth=1.0, linestyle='dashed')\n \n\n def runRL(self,colorx, cutoff, labelx):\n self.packets_holder = []\n \n self.final_packets_holder = []\n self.fog_energy_holder = []\n\n for epi in range(self.episodes):\n\n #cutoff is to minimize\n\n\n self.ECI = 0\n self.ECF = 0\n self.deltak = np.random.randint(-5, 5)\n self.sensorpower= random.uniform(0, 0.3)\n #self.delta=0.1\n self.dd=0\n #np.random.randint() --discrete uniform distribution\n self.obs = np.array([np.random.randint(0, 80), np.random.randint(95, self.max_energy_fog), np.random.randint(0, 5)])\n \n\n cur_action = self.action_space.sample()\n trigger = self.trigger_space.sample()\n obs, reward, done, dead, _ = self.step(cur_action, trigger)\n #print(obs)\n\n current_state = self.grouping(obs)\n #print('state before',current_state)\n \n \n\n \n iter=0\n self.sum_pack = 0\n self.final_pack = 0\n while ((iter < self.iteration_steps) and not done):#(current_state[0]>=8 and current_state[1]>0 and current_state[2]> 0)): #current_state[0]!= 0):\n\n iter+=1\n \n #linear\n #epsilon =1-(epi/1000)\n\n #exp decay\n self.epsilon =float(np.exp(-0.009*epi))\n alpha=0.1\n gamma =0.9\n\n #print(epsilon)\n action = self.select_action(self.epsilon, current_state)\n triggerx = self.trigger_space.sample()\n obs, reward, done, dead, _ = self.step(action, triggerx)\n \n \n\n #do the mapping from obs to state\n\n \n new_state = self.grouping(obs)\n reward_tj = reward#self.map_reward(new_state)\n #print(obs[0])\n #print(new_state)\n #self.sum_pack+=(100 - obs[0])\n \n \n # do learning thingy\n\n \n if epi< (2*self.episodes/3):\n # update q values\n self.update_q(current_state, new_state, action, reward_tj, alpha, gamma)\n\n \n #save current state\n current_state = new_state\n \n\n if done:\n #print(\"Reached goal state\")\n #print(reward_tj)\n break\n if dead:\n #print(\"No more communications\")\n break\n if epi>59:\n #self.ave_pack = self.sum_pack/iter\n self.final_pack = (100 - obs[0])\n self.fog_cons = 100 - obs[1]\n #print(\"End of episode #\",epi, \" in \", iter , \"iterations\")\n #self.packets_holder.append(self.ave_pack)\n self.final_packets_holder.append(self.final_pack)\n self.fog_energy_holder.append(self.fog_cons)\n #print(self.final_packets_holder) \n #self.line2, =plt.plot(self.packets_holder, label=labelx)\n #self.line1, =plt.plot(self.final_packets_holder, label=labelx)\n #plt.setp(self.line1, color= colorx, linewidth=1.0)\n #plt.setp(self.line2, color= colory, linewidth=1.0, linestyle='dashed')\n \n#print('RLdecentralized', '|', 'Rule-based + Centralized', '|', 'Rule-based + Random', '|', 'Rule-based + Round Robin', '|', 'Energy Centralized', '|', 'Energy RL decentralized')\nboxcontainer1 =[]\nboxcontainer2 =[]\ntimekeeper = []\n\nfor experiments in range(50):\n pp=0\n ppenergy=0\n print('Experiment #',experiments + 1)\n kk1 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data1 = kk1.runCentral('b', 1000, \"Agent - 1\")\n\n kk2 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data2 = kk2.runCentral('g', 1000, \"Agent - 2\")\n\n kk3 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data3 = kk3.runCentral('g', 1000, \"Agent - 3\")\n\n \n\n arr_fog1= kk1.final_packets_holder\n arr_fog2= kk2.final_packets_holder\n arr_fog3= kk3.final_packets_holder\n \n\n energy_arr_fog1= kk1.fog_energy_holderk\n energy_arr_fog2= kk2.fog_energy_holderk\n energy_arr_fog3= kk3.fog_energy_holderk\n \n\n central_stacked_array = dstack((arr_fog1, arr_fog2, arr_fog3))\n central_sa = central_stacked_array.max(2)\n central = central_sa[0]\n #########\n energy_central_stacked_array = dstack((energy_arr_fog1, energy_arr_fog2, energy_arr_fog3))\n energy_central_sa = energy_central_stacked_array.min(2)\n energy_central = energy_central_sa[0]\n\n \n \n store =[]\n store_e = []\n for inde in range(40):\n met = np.random.randint(1,7)\n if met==1 or met==2:\n ffa =arr_fog1[inde]\n eea = energy_arr_fog1[inde]\n elif met==3 or met==4:\n ffa=arr_fog2[inde]\n eea = energy_arr_fog2[inde]\n elif met==5 or met==6:\n ffa=arr_fog3[inde]\n eea = energy_arr_fog3[inde]\n \n store.append(ffa)\n store_e.append(eea)\n\n roundy =[]\n roundy_e =[]\n for indr in range(40):\n \n if indr%3==0:\n ffc =arr_fog1[indr]\n eec = energy_arr_fog1[indr]\n elif indr%5==1:\n ffc=arr_fog2[indr]\n eec = energy_arr_fog2[indr]\n elif indr%5==2:\n ffc=arr_fog3[indr]\n eec = energy_arr_fog3[indr]\n \n roundy.append(ffc)\n roundy_e.append(eec)\n\n ###################\n startRL = time.time()\n dc1 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data1 = dc1.runRL('b', 1000, \"Agent - 1\")\n\n dc2 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data2 = dc2.runRL('g', 1000, \"Agent - 2\")\n\n dc3 = FogIoT(0.25, 0.001, 0.01, 0.15, 0.2, 0.25, 0.3)\n data3 = dc3.runRL('g', 1000, \"Agent - 3\")\n endRL = time.time()\n\n \n arr_fogdc1= dc1.final_packets_holder\n arr_fogdc2= dc2.final_packets_holder\n arr_fogdc3= dc3.final_packets_holder\n\n \n energy_arr_fogdc1 = dc1.fog_energy_holder\n energy_arr_fogdc2 = dc2.fog_energy_holder\n energy_arr_fogdc3 = dc3.fog_energy_holder\n\n \n #print(arr_fog1)\n #print(arr_fog2)\n\n decentralized_stacked_array = dstack((arr_fogdc1, arr_fogdc2, arr_fogdc3))\n \n decentralized_sa = decentralized_stacked_array.max(2)\n decentralized = decentralized_sa[0] #packets received successfully\n\n\n energy_decentralized_stacked_array = dstack((energy_arr_fogdc1, energy_arr_fogdc2, energy_arr_fogdc3))\n energy_decentralized_sa = energy_decentralized_stacked_array.min(2)\n energy_decentralized = energy_decentralized_sa[0]\n\n \n \n\n RLdecentralized = np.sum(decentralized)\n\n\n sumRandselect = np.sum(store)\n sumCentral = np.sum(central)\n sumRound = np.sum(roundy)\n sumCentralEnergy = np.sum(energy_central)\n sumDecentralizedEnergy = np.sum(energy_decentralized)\n sumRandselectEnergy = np.sum(store_e)\n sumRoundEnergy = np.sum(roundy_e)\n\n #print(\"Sum of packets fog 1#\", sumfog1)\n #print(\"Sum of packets fog 2#\", sumfog2)\n## print(\"Sum of packets Decentralized RL scheme#\", RLdecentralized)\n## print(\"Sum of packets Rule-based + Centralized selection scheme#\", sumCentral)\n## print(\"Sum of packets Rule-based + Random selection scheme#\", sumRandselect)\n## print(\"Sum of packets Rule-based + Round Robin scheme#\", sumRound)\n## print(\"Energy consumed in centralized system with 2 agents#\", sumCentralEnergy)\n## print(\"Energy consumed in RL decentralized system with 2 agents#\", sumDecentralizedEnergy)\n## print(RLdecentralized, sumCentral, sumRandselect, sumRound, sumCentralEnergy, sumDecentralizedEnergy)\n pp = [RLdecentralized/40, sumCentral/40, sumRandselect/40, sumRound/40]\n ppenergy = [sumDecentralizedEnergy/40, sumCentralEnergy/40, sumRandselectEnergy/40, sumRoundEnergy/40]\n boxcontainer1.append(pp)\n boxcontainer2.append(ppenergy)\n timekeeper.append(endRL - startRL)\nprint(boxcontainer1)\nprint(boxcontainer2)\nprint(timekeeper)\n#print(boxcontainer1)\n#print(boxcontainer2)\n \nplt.subplot(2,1,1)\nplt.boxplot(np.row_stack(boxcontainer1), notch =True, patch_artist =True, labels = ['RL', 'RB-CS', 'RB-R', 'RB-RR'])\nplt.ylabel('Packets delivered(%)')\n#plt.xlabel('RL vs. Baselines')\nplt.title('(a)')\n\nplt.subplot(2,1,2)\nplt.boxplot(np.row_stack(boxcontainer2), notch =True, patch_artist =True, labels = ['RL', 'RB-CS', 'RB-R', 'RB-RR'])\nplt.ylabel('Energy consumed (%)')\nplt.xlabel('RL vs. Baselines')\nplt.title('(b)')\n\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n \n","sub_path":"Python practice/my_env and agent/MAS_fogIoT_network_working_3agent.py","file_name":"MAS_fogIoT_network_working_3agent.py","file_ext":"py","file_size_in_byte":18999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"385248717","text":"import tensorflow as tf\n\nx_data = [1, 3, 5]\ny_data = [1, 3, 5]\n\nW = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\nb = tf.Variable(tf.random_uniform([1], -1.0, 1.0))\n\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\nhypothesis = W * X + b\n\ncost = tf.reduce_mean(tf.square(hypothesis - Y))\n\nlearning_rate = tf.Variable(0.05)\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\ntrain = optimizer.minimize(cost)\n\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init)\n\nprint(\"-- start learning --\")\ndata = {X : x_data, Y : y_data}\nfor step in range(2001):\n sess.run(train, feed_dict=data)\n if step % 20 == 0:\n print(\"Step {0} : cost = {1}, W = {2}, b = {3}\".\n format(step, sess.run(cost, feed_dict=data), sess.run(W), sess.run(b)))\nprint(\"-- learning finished --\")\n\nprint(\"-- start test --\")\ntest_x_data = [0.5, 1.5, 5.0, 10.3, -12.0, -9.68]\nfor x in test_x_data:\n print(\"When X = {0} : prediction = {1}, real = {2}\".\n format(x, sess.run(hypothesis, feed_dict={X : x}), x))","sub_path":"linear-regression/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"382137813","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Company',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('name', models.CharField(max_length=512)),\n ],\n ),\n migrations.CreateModel(\n name='Question',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('text', models.TextField()),\n ('difficulty_level', models.CharField(default=b'3', max_length=1)),\n ('company', models.ForeignKey(to='app1.Company', null=True)),\n ],\n ),\n migrations.CreateModel(\n name='QuestionAnswer',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('text', models.CharField(max_length=1024)),\n ('question', models.ForeignKey(to='app1.Question')),\n ],\n ),\n migrations.CreateModel(\n name='Test',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('company', models.ForeignKey(to='app1.Company')),\n ],\n ),\n migrations.CreateModel(\n name='TestCandidateQuestionHistory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('answer_dateTime', models.DateTimeField(null=True)),\n ('duration', models.SmallIntegerField(default=0)),\n ('status', models.SmallIntegerField(default=0)),\n ('score', models.SmallIntegerField(default=0)),\n ('answer', models.ForeignKey(to='app1.QuestionAnswer', null=True)),\n ('question', models.ForeignKey(to='app1.Question')),\n ],\n ),\n migrations.CreateModel(\n name='TestSectionDef',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('company', models.ForeignKey(to='app1.Company')),\n ],\n ),\n migrations.CreateModel(\n name='TestSectionQuestions',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('duration', models.IntegerField(null=True, blank=True)),\n ('questions', models.ManyToManyField(to='app1.Question')),\n ('section', models.ForeignKey(to='app1.TestSectionDef')),\n ('test', models.ForeignKey(to='app1.Test')),\n ],\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=255)),\n ('last_name', models.CharField(max_length=255)),\n ('phone', models.CharField(max_length=15)),\n ('company', models.ForeignKey(to='app1.Company')),\n ],\n ),\n migrations.AddField(\n model_name='testcandidatequestionhistory',\n name='section',\n field=models.ForeignKey(to='app1.TestSectionDef'),\n ),\n migrations.AddField(\n model_name='testcandidatequestionhistory',\n name='test',\n field=models.ForeignKey(to='app1.Test'),\n ),\n ]\n","sub_path":"app1/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"467038089","text":"from .. import backend as T\n\ndef Sequence(data, max_length=None):\n batch_size = data.batch_size\n var = T.make_sequence(data.get_data(), max_length)\n data = data.next(var, data.get_shape_out())\n data.sequence = True\n data.sequence_length = max_length\n data.batch_size = batch_size\n return data\n\n","sub_path":"deepx/rnn/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"438642113","text":"class Car:\r\n #mem = 4\r\n #tire = 4\r\n def run(self):\r\n self.mem = 4 #클래스의 속성 생성\r\n self.tire = 4\r\n print('run')\r\n def stop(self):\r\n print('stop')\r\n\r\nobj1 = Car()\r\nobj2 = Car()\r\n\r\n\r\nobj1.run()\r\nprint(obj1.mem)\r\nobj2.run()\r\nprint(obj2.tire)\r\nobj2.stop()\r\n","sub_path":"09_01.08/Jan_08_01.py","file_name":"Jan_08_01.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"159215232","text":"import json\nimport sys\nimport traceback\n\nfrom twisted.internet import reactor\nfrom twisted.internet.endpoints import TCP4ServerEndpoint\nfrom twisted.internet.protocol import Factory\nfrom twisted.protocols.basic import LineReceiver\n\nMAX_NUMBER_OF_USERS = 1\n\n\nclass Chat:\n def __init__(self):\n self.users = {}\n self.messages = []\n\n @property\n def name(self):\n return \"[Server]\"\n\n def has_free_slots(self):\n return len(self.users) < MAX_NUMBER_OF_USERS\n\n def user_connect(self, user):\n self.users[user.addr] = user\n print(\"Client connected: {}\".format(user.name))\n self._broadcast(self, \"{} has entered the chat\".format(user.name))\n\n def user_disconnect(self, user):\n del self.users[user.addr]\n print(\"Client disconnected: {}\".format(user.name))\n self._broadcast(self, \"{} has left the chat\".format(user.name))\n\n def user_rename(self, oldname, name):\n msg = \"{} renamed to {}\".format(oldname, name)\n print(msg)\n self._broadcast(self, msg)\n\n def post_message(self, user, msg):\n assert user.addr in self.users\n self.messages.append(msg)\n print(\"{}: {}\".format(user.name, msg))\n self._broadcast(user, msg)\n\n def _broadcast(self, source, msg):\n try:\n for receiver in self.users.values():\n receiver.on_message(source, msg)\n except:\n traceback.print_exc()\n\n\nclass ChatProtocol(LineReceiver):\n def __init__(self, chat, addr):\n super().__init__()\n self.chat = chat\n self.addr = addr\n self.name = \"{}:{}\".format(addr.host, addr.port)\n self.delimiter = b\"\\n\"\n\n def on_message(self, source, msg):\n self.sendLine(json.dumps({\n \"type\": \"message\",\n \"data\": {\n \"source\": source.name,\n \"message\": msg\n }\n }).encode())\n\n def lineReceived(self, line):\n try:\n message = json.loads(line.strip())\n if message[\"type\"] == \"message\":\n self.chat.post_message(self, message[\"data\"])\n elif message[\"type\"] == \"set-name\":\n self.chat.user_rename(self.name, message[\"data\"])\n self.name = message[\"data\"]\n else:\n print(\"Unknown message type {} from {}\".format(message[\"type\"], self.name))\n except Exception as e:\n print(\"Client {} error: {}\".format(self.addr, e))\n\n def connectionMade(self):\n super().connectionMade()\n self.chat.user_connect(self)\n\n def connectionLost(self, reason=None):\n super().connectionLost(reason)\n self.chat.user_disconnect(self)\n\n\nclass ChatFactory(Factory):\n def __init__(self, chat):\n self.chat = chat\n\n def buildProtocol(self, addr):\n if self.chat.has_free_slots():\n return ChatProtocol(self.chat, addr)\n return None\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: python server.py \")\n exit(1)\n\n PORT = int(sys.argv[1])\n\n print(\"Server listening on 127.0.0.1:{}\".format(PORT))\n\n chat = Chat()\n endpoint = TCP4ServerEndpoint(reactor, PORT)\n endpoint.listen(ChatFactory(chat))\n reactor.run()\n","sub_path":"labs/08/server_twisted.py","file_name":"server_twisted.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"430237181","text":"#!/usr/bin/env python3\n\nimport logging\n\n\nfrom bottle import Bottle, run, request, response, static_file, template, TEMPLATE_PATH\n\nimport rodocs.auth as auth\nimport rodocs.config as config\nimport rodocs.controllers.echo as echo\nimport rodocs.controllers.projects as controller_projects\nimport rodocs.controllers.update as update\nimport rodocs.log as log\n\nlogger = logging.getLogger('rodocs.main')\n\n\nSCRIPT_PATH = config.basedir\nVIEW_PATH = SCRIPT_PATH / 'views'\nSTATIC_PATH = SCRIPT_PATH / 'static'\nTEMPLATE_PATH.append(str(VIEW_PATH))\nlogger.debug('View Path %s', VIEW_PATH)\n\nrod_root = application = Bottle()\n\n@rod_root.route('/docs/')\ndef docs(rel_path):\n log_info = log.init_log_info(request)\n logger.debug('Getting doc file', extra=log_info)\n try:\n return static_file(rel_path, root=str(config.documents_path))\n except Exception as e:\n logging.exception('Error fetching %s', rel_path, extra=log_info)\n\n@rod_root.route('/static/')\ndef static(rel_path):\n log_info = log.init_log_info(request)\n logger.debug('Getting static', extra=log_info)\n try:\n return static_file(rel_path, root=str(STATIC_PATH))\n except Exception as e:\n logging.exception('Error fetching %s', rel_path, extra=log_info)\n\n@rod_root.route('')\n@rod_root.route('/')\ndef index():\n log_info = log.init_log_info(request)\n search = request.params.get('search')\n projects = sorted(controller_projects.query_projects(search), key=lambda p: p.name)\n logger.info('Index Page', extra=log_info)\n return template('index.tpl', projects=projects, search=search, is_logged_in=auth.is_logged_in(request))\n\n@rod_root.route('/login')\n@rod_root.route('/login/')\ndef login():\n log_info = log.init_log_info(request)\n logger.info('Login Page', extra=log_info)\n return template('login.tpl', is_logged_in=auth.is_logged_in(request))\n\n@rod_root.post('/test_login')\n@auth.needs_login\ndef test_login():\n log_info = log.init_log_info(request)\n logger.info('Login OK', extra=log_info)\n return 'Ok'\n\n@rod_root.route('/do_logout')\ndef do_logout():\n log_info = log.init_log_info(request)\n logger.info('Generating 401', extra=log_info)\n response.status = 401\n response.set_header('Www-Authenticate', 'Basic realm=\"private\"')\n return 'Ok'\n\n@rod_root.route('/admin')\n@rod_root.route('/admin/')\n@auth.needs_login\ndef add_project():\n log_info = log.init_log_info(request)\n logger.info('Admin Page', extra=log_info)\n return template('admin.tpl', is_logged_in=auth.is_logged_in(request))\n\n@rod_root.route('/admin/add_project')\n@auth.needs_login\ndef add_project():\n log_info = log.init_log_info(request)\n logger.info('Add Project Page', extra=log_info)\n return template('add_project.tpl', is_logged_in=auth.is_logged_in(request))\n\nrod_root.mount('/rest/projects', controller_projects.rest_app)\nrod_root.mount('/rest/update', update.rest_app)\nrod_root.mount('/rest/echo', echo.app)\n\nrun(rod_root,\n host=config.server_host,\n port=config.server_port,\n server='gunicorn',\n workers=config.gunicorn_workers,\n debug=config.server_debug)","sub_path":"rodocs/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"126377931","text":"# Encoding: utf-8\r\n'''\r\nCreated on 13.04.2013\r\n\r\n@author: Los\r\n\r\n@version: 0.0.1\r\n'''\r\nimport sys\r\nimport time\r\nimport math\r\n\r\n#MAX=1000\r\nMAX=100000000000000\r\n#MAX=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\r\n\r\nMAKE_DB=0\r\nUSE_DB=0\r\n\r\ndef isFair(x):\r\n s=str(x)\r\n if s==s[::-1] :\r\n return True\r\n else :\r\n return False\r\n\r\ndef main(argv=None):\r\n if argv==None : argv=sys.argv\r\n\r\n import locale\r\n locale.setlocale(locale.LC_ALL, '')\r\n\r\n fns=list()\r\n if USE_DB==0 :\r\n ctime=time.time()\r\n for x in range(1, MAX+1):\r\n if isFair(x):\r\n sq=x*x\r\n if sq>MAX :\r\n break\r\n if isFair(sq) :\r\n fns.append(sq)\r\n if time.time()-ctime > 60 :\r\n print (sq, int(math.log10(sq)))\r\n ctime=time.time()\r\n #print(fns)\r\n else :\r\n f=open('pc_db.db','r')\r\n EOF=False\r\n while not EOF :\r\n l=f.readline()\r\n if l=='' :\r\n EOF=True\r\n break\r\n l=l.strip()\r\n if l != '' :\r\n fns.append(int(l))\r\n f.close()\r\n \r\n if MAKE_DB==1 :\r\n f=open('pc_db.db','w')\r\n for x in fns:\r\n print(x, file=f)\r\n f.close()\r\n \r\n \r\n T=int(input())\r\n for i in range (1,T+1):\r\n l=input().strip().split()\r\n A=int(l[0])\r\n B=int(l[1])\r\n count=0\r\n for x in fns :\r\n if A<=x<=B :\r\n count+=1\r\n print('Case #{}: {}'.format(i,count))\r\n \r\n \r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"solutions_2463486_1/Python/weirdlos/pc.py","file_name":"pc.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"303244411","text":"fuel = 0\r\ncurrentFuel = 0\r\ntotalFuel = 0\r\narray1 = []\r\narray2 = []\r\nwith open(r\"C:\\Users\\mpn42\\Documents\\code advent 2019\\Day 1\\input_01.txt\",\"r\") as f:\r\n for val in f.read().split():\r\n array1.append(int(val))\r\n \r\n\r\nfor (i) in array1:\r\n x = 0\r\n currentFuel = 0\r\n massToCalcFrom = i\r\n while massToCalcFrom > 6:\r\n x = (massToCalcFrom//3)-2\r\n currentFuel = currentFuel + x\r\n massToCalcFrom = x\r\n \r\n \r\n array2.append(currentFuel)\r\n \r\n\r\nfor (j) in array2:\r\n totalFuel = totalFuel + j\r\n\r\n \r\n\r\nprint (totalFuel)\r\n\r\n\r\n","sub_path":"01_02.py","file_name":"01_02.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"600161401","text":"import cv2\r\nimport numpy as np\r\nfrom threading import Thread\r\nimport time\r\nimport os\r\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\n\r\n#os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\r\n\r\n#print(os.environ)\r\n\r\nnet = cv2.dnn.readNet('config/yolov4.weights', 'config/yolov4.cfg')\r\n#net = cv2.dnn.readNet('yolov3-spp.weights', 'yolov3.cfg')\r\nclasses = []\r\nwith open('coco.names', 'r') as f:\r\n classes = f.read().splitlines()\r\n\r\n#url = 'http://admin:admin@10.47.156.160:8081/'\r\ncapture = cv2.VideoCapture(0)#0为默认摄像头x\r\n\r\ndef object_detection():\r\n while True:\r\n start = time.clock()\r\n ret, img = capture.read()\r\n # fps = \r\n # img = cv2.imread('image.jpg')\r\n\r\n hight, width, _ = img.shape\r\n width = int(2 * width)\r\n hight = int(2 * hight)\r\n img = cv2.resize(img, (width,hight))\r\n\r\n blob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)\r\n\r\n net.setInput(blob)\r\n\r\n output_layers_names = net.getUnconnectedOutLayersNames()\r\n layerOutputs = net.forward(output_layers_names)\r\n\r\n boxes = []\r\n confidences = []\r\n class_ids = []\r\n\r\n for output in layerOutputs:\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]*hight)\r\n w = int(detection[2] * width)\r\n h = int(detection[3] * hight)\r\n \r\n x = int(center_x - w / 2)\r\n y = int(center_y - h / 2)\r\n \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 indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\n\r\n font = cv2.FONT_HERSHEY_PLAIN\r\n colors = np.random.uniform(0, 255, size=(len(boxes),3))\r\n\r\n if len(indexes) > 0:\r\n for i in indexes.flatten():\r\n x, y, w, h = boxes[i]\r\n label = str(classes[class_ids[i]])\r\n confidence = str(round(confidences[i], 2))\r\n color = colors[i]\r\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 4)\r\n cv2.putText(img, label+\" \"+confidence, (x,y-10), font, 1, color, 2)\r\n\r\n cv2.imshow('Image', img)\r\n end = time.clock()\r\n print(end - start)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n capture.release()\r\n cv2.destroyAllWindows()\r\n\r\nThread(target=object_detection).start()\r\n'''\r\n\r\n\r\n#ret, img = capture.read()\r\n# fps = \r\nimg = cv2.imread('image.jpg')\r\n\r\nhight, width, _ = img.shape\r\n#width = int(0.5 * width)\r\n#hight = int(0.5 * hight)\r\nimg = cv2.resize(img, (width,hight))\r\nstart = time.clock()\r\nblob = cv2.dnn.blobFromImage(img, 1 / 255, (416, 416), (0, 0, 0), swapRB=True, crop=False)\r\n\r\nnet.setInput(blob)\r\n\r\noutput_layers_names = net.getUnconnectedOutLayersNames()\r\nlayerOutputs = net.forward(output_layers_names)\r\n\r\nboxes = []\r\nconfidences = []\r\nclass_ids = []\r\n\r\nfor output in layerOutputs:\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]*hight)\r\n w = int(detection[2] * width)\r\n h = int(detection[3] * hight)\r\n \r\n x = int(center_x - w / 2)\r\n y = int(center_y - h / 2)\r\n \r\n boxes.append([x, y, w, h])\r\n confidences.append(float(confidence))\r\n class_ids.append(class_id)\r\n\r\nindexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\r\n\r\nfont = cv2.FONT_HERSHEY_PLAIN\r\ncolors = np.random.uniform(0, 255, size=(len(boxes),3))\r\n\r\nif len(indexes) > 0:\r\n for i in indexes.flatten():\r\n x, y, w, h = boxes[i]\r\n label = str(classes[class_ids[i]])\r\n confidence = str(round(confidences[i], 2))\r\n color = colors[i]\r\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\r\n cv2.putText(img, label+\" \"+confidence, (x,y-10), font, 1, color, 1)\r\nend = time.clock()\r\nprint(end - start)\r\ncv2.imshow('Image', img)\r\ncv2.waitKey(0)\r\n'''\r\ndef run_inference_for_single_image(image, graph):\r\n with graph.as_default():\r\n with tf.compat.v1.Session() as sess:\r\n # Get handles to input and output tensors\r\n ops = tf.compat.v1.get_default_graph().get_operations()\r\n all_tensor_names = {output.name for op in ops for output in op.outputs}\r\n tensor_dict = {}\r\n for key in [\r\n 'num_detections', 'detection_boxes', 'detection_scores',\r\n 'detection_classes', 'detection_masks'\r\n ]:\r\n tensor_name = key + ':0'\r\n if tensor_name in all_tensor_names:\r\n tensor_dict[key] = tf.compat.v1.get_default_graph().get_tensor_by_name(\r\n tensor_name)\r\n if 'detection_masks' in tensor_dict:\r\n # The following processing is only for single image\r\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\r\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\r\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\r\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\r\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\r\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\r\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\r\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\r\n detection_masks_reframed = tf.cast(\r\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\r\n # Follow the convention by adding back the batch dimension\r\n tensor_dict['detection_masks'] = tf.expand_dims(\r\n detection_masks_reframed, 0)\r\n image_tensor = tf.compat.v1.get_default_graph().get_tensor_by_name('image_tensor:0')\r\n\r\n # Run inference\r\n output_dict = sess.run(tensor_dict,\r\n feed_dict={image_tensor: np.expand_dims(image, 0)})\r\n\r\n # all outputs are float32 numpy arrays, so convert types as appropriate\r\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\r\n output_dict['detection_classes'] = output_dict[\r\n 'detection_classes'][0].astype(np.uint8)\r\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\r\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\r\n if 'detection_masks' in output_dict:\r\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\r\n return output_dict","sub_path":"2018202096/src/scripts/object_detection/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"71641722","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n#@created: 07.09.2011\r\n#@author: Aleksey Komissarov\r\n#@contact: ad3002@gmail.com \r\n\r\nfrom PyExp import AbstractModel\r\nfrom trseeker.seqio.tab_file import sc_iter_tab_file\r\n\r\nclass GFF3Model(AbstractModel):\r\n ''' Class for gff3 data.\r\n '''\r\n\r\n dumpable_attributes = [\"seqid\",\r\n \"source\",\r\n \"ftype\",\r\n \"start\",\r\n \"end\",\r\n \"score\",\r\n \"strand\",\r\n \"phase\",\r\n \"attributes\",\r\n ]\r\n\r\n int_attributes = [ \"start\",\r\n \"end\",\r\n ]\r\n\r\n float_attributes = [ \"score\",\r\n ]\r\n\r\n def set_with_bed_obj(self, bed_obj, **kwargs):\r\n ''' Set object with BED object.\r\n '''\r\n self.seqid = bed_obj.seqid\r\n self.start = bed_obj.start\r\n self.end = bed_obj.end\r\n if not \"source\" in kwargs:\r\n kwargs[\"source\"] = \".\"\r\n self.source = kwargs[\"source\"]\r\n if not \"ftype\" in kwargs:\r\n kwargs[\"ftype\"] = \".\"\r\n self.ftype = kwargs[\"ftype\"]\r\n if not \"score\" in kwargs:\r\n kwargs[\"score\"] = \".\"\r\n self.score = kwargs[\"score\"]\r\n if not \"strand\" in kwargs:\r\n kwargs[\"strand\"] = \".\"\r\n self.strand = kwargs[\"strand\"]\r\n if not \"phase\" in kwargs:\r\n kwargs[\"phase\"] = \".\"\r\n self.phase = kwargs[\"phase\"]\r\n if not \"attributes\" in kwargs:\r\n kwargs[\"attributes\"] = \".\"\r\n self.attributes = kwargs[\"attributes\"]\r\n\r\n\r\nclass BEDModel(AbstractModel):\r\n ''' Class for BED data.\r\n '''\r\n\r\n dumpable_attributes = [\"seqid\",\r\n \"start\",\r\n \"end\",\r\n ]\r\n\r\n int_attributes = [ \"start\",\r\n \"end\",\r\n ]\r\n","sub_path":"trseeker/models/annotation_models.py","file_name":"annotation_models.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"75544109","text":"\nimport os\nimport sys\n\nif sys.version_info[0] != 3:\n print(\"Use Python3.\")\n sys.exit(255)\n\nACCOUNT = {\n \"tensorflow-onboarding\": \"814778702491-compute@developer.gserviceaccount.com\",\n \"google.com:tensorflow-performance\": \"283123161091-compute@developer.gserviceaccount.com\",\n \"ctpu-2017-09-01\": \"855031184363-compute@developer.gserviceaccount.com\",\n}\n\nUSER = os.getlogin()\nif USER != os.getenv(\"USER\"):\n env_user = os.getenv(\"USER\")\n print(\"Overriding user {} to {}\".format(USER, env_user))\n USER = env_user\n\nPROFILE = \"~/.cloud/.profile\"\nGCLOUD = \"/usr/bin/gcloud\"\nSANDBOX_TEMPLATE = \"{user}-sandbox-{id}\"\n\ndef populate_template(user, id):\n id_str = str(id).zfill(3)\n return SANDBOX_TEMPLATE.format(user=user, id=id_str)\n\nROOT = os.path.dirname(os.path.abspath(__file__))\n\n\n# Projects are given terse letter assignments to allow concise CLI commands\nPROJECTS = {\n \"a\": \"tensorflow-onboarding\",\n \"b\": \"google.com:tensorflow-performance\",\n \"c\": \"ctpu-2017-09-01\",\n}\n\nZONES = {\n \"tensorflow-onboarding\": [\"us-central1-c\", \"us-central1-f\", \"us-central1-a\", \"us-central1-b\"],\n \"google.com:tensorflow-performance\": [\"us-west1-b\"],\n \"ctpu-2017-09-01\": [\"us-central1-c\"],\n}\n\nREZONE = {\n \"tensorflow-onboarding\": True,\n \"google.com:tensorflow-performance\": False,\n \"ctpu-2017-09-01\": False,\n}\n\nSNAPSHOTS = {\n \"tensorflow-onboarding\": \"ubuntu-1604-lts-drawfork-with-cuda-20190113\",\n \"google.com:tensorflow-performance\": \"ubuntu-1604-lts-drawfork-with-cuda-20180924\",\n}\n\nIMAGENET = {\n \"tensorflow-onboarding\": {\"us-central1-a\": \"imagenet-copy-1a\",\n \"us-central1-b\": \"imagenet-copy-1b\",\n \"us-central1-c\": \"imagenet-copy-1c\",\n \"us-central1-f\": \"imagenet-copy-1f\"},\n}\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"233858542","text":"def wrap_latex(input, max_length=75, **kwargs):\n if len(input)>max_length:\n # remove double dollars, as they don't allow word wrap\n if len(input) > 3:\n if input[0:2]=='$$' and input[-2:]=='$$':\n input = input[1:-1]\n # change \\left( and \\right) to \\bigg( and \\bigg), as they allow word wrap\n input = input.replace(r'\\left(',r'\\big(')\n input = input.replace(r'\\right)',r'\\big)')\n \n return input\n\nc = get_config() \nc.NbConvertApp.export_format = 'latex' \nc.TemplateExporter.filters = c.Exporter.filters = {'wrap_latex': wrap_latex}\nc.Exporter.template_file = 'latex_input_in_frame.tplx'","sub_path":"nbconvert/latex_input_in_frame.py","file_name":"latex_input_in_frame.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"568656987","text":"from datetime import datetime, timedelta\n\nmonth = 1\nyear = 2016\n\ndef return_first_friday_of_month(date):\n for i in range(7):\n if date.strftime('%A') == 'Friday':\n return date.day\n # date = date + date.timedelta(1)\n\nselected_month = datetime.date(year, month, 1)\nfirst_friday = return_first_friday_of_month(selected_month)\nprint(first_friday)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"511675933","text":"#%%\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nhistory = pd.read_csv(\"project.csv\")\n\n\n#%%\nexperiments = history['problem'].unique().tolist()\nexperiments\n# %%\nfor exp in experiments:\n print(exp)\n exp_history = history[history['problem'] == exp]\n exp_history['model'] = 'a' + exp_history['attention-depth'].astype(str) + ' d' + exp_history['graph-depth'] .astype(str)\n\n ax = sns.lineplot(x='train-size', y='test-auc', hue='model', #alpha = 0.4,\n data=exp_history)\n leg = ax.legend(loc=\"lower right\").get_lines()\n styles = ['solid', '--', ':']\n colors = ['r', 'c', 'y']\n for i in range(0, 9):\n ax.lines[i].set_linestyle(styles[int(i % 3)])\n leg[i].set_linestyle(styles[int(i % 3)])\n ax.lines[i].set_color(colors[int(i/3)])\n leg[i].set_color(colors[int(i/3)])\n ax.set(ylabel='AUC-test', title=exp)\n plt.grid(axis='y')\n plt.savefig(exp + '.png')\n plt.show()\n# %%\n","sub_path":"nodegraphtree/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"215661966","text":"# coding: utf-8\n\n'''\nauthor : Jet Vayne\ndate: 2019-10-28\n'''\n\n\nclass Solution(object):\n # 程式主要動作控制區\n def heap_sort(self, nums):\n result = [] # 最終要輸出的排過的 list\n self.heapify(nums) # 先將輸入的 list 變成 heap 結構\n while len(nums) != 0: # 迴圈控制丟出 root 做 sort 的動作\n result.append(nums.pop(0)) # 將剛剛丟出的 root append 到最終結果 list 裡面\n self.heapify(nums) # 此時,少了一個 element 的 list 不見得是heap結構了,所以我們再重新將它整理成 heap 結構,並重複上述動作\n\n return result # 回傳最終結果\n\n # 將輸入的 list 變成 heap 結構,heap型態為 min heap\n def heapify(self, array: list):\n for i in reversed(range(len(array))): # 使用 reverse 將 index 由大到小 iter\n self.climber(i, array) # 透過 index 往上找 parent ,並做值的比較,必要時會換值\n\n # 由下往上爬取數值,並比較 self(child) and parent\n def climber(self, index: int, array: list):\n pi = self.get_pix(index) # 取得 parent index\n if pi is None:\n return\n\n self_val = array[index] # 自己的值\n par_val = array[pi] # parent 的值\n\n # 若 parent 的值大於 自己的值,則做 index 換值的動作\n if par_val > self_val:\n array[index] = par_val\n array[pi] = self_val\n\n self.climber(pi, array) # check parent 和它的 parent 是否也符合 heap 結構,並用 recursive 去實現\n\n # tool-function,回傳該 index 的 parent index\n def get_pix(self, index: int):\n if index <= 0:\n return\n return int((index + 1) / 2 - 1)\n\n","sub_path":"HW2/heap_sort_06170123.py","file_name":"heap_sort_06170123.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"541615653","text":"from optparse import OptionParser\nfrom socket import *\nimport os, sys, threading\nimport selectors\nimport logging\nimport types\n\n\nclass CRCClient(object):\n \n def __init__(self, options, run_on_localhost=False):\n self.request_terminate = False\n\n self.serveraddr = options.serverhost\n self.serverport = options.serverport\n\n if run_on_localhost:\n self.serveraddr = \"127.0.0.1\"\n\n self.nick = options.nick\n self.hostname = options.hostname\n self.servername = options.serverhost\n self.realname = options.realname\n \n # Options to help with debugging and logging\n self.log_file = options.log_file\n self.logger = None\n\n self.init_logging()\n\n def run(self):\n self.print_info(\"Launching client %s@%s...\" % (self.nick, self.hostname))\n self.connect_to_server()\n\n # Send the registration message to the server\n self.send_message_to_server(\"USER %s %s %s :%s\" % (self.nick, self.hostname, self.servername, self.realname))\n\n # Wait for a response from the server telling us if we registered, or if there was a problem\n rsp = self.sock.recv(2048).decode().replace(\"\\r\\n\", \"\\\\r\\\\n\")\n self.print_info(\"Received registration message: \" + rsp)\n \n\n def start_listening_to_server(self):\n x = threading.Thread(target=self.listen_for_server_input)\n x.start() \n\n\n ######################################################################\n # This function should create a socket and connect to the server this client is directly linked to\n def connect_to_server(self):\n self.sock = socket(AF_INET, SOCK_STREAM)\n self.sock.connect((self.serveraddr, int(self.serverport)))\n\n\n def listen_for_server_input(self):\n while not self.request_terminate:\n rcvd = self.sock.recv(2048).decode()\n if not rcvd:\n self.print_info(\"Server has disconnected!\")\n self.request_terminate = True\n\n\n ######################################################################\n # This block of functions ...\n def send_message_to_server(self, message):\n self.sock.send(message.encode())\n\n\n\n ######################################################################\n # The remaining functions are command handlers. Each command handler is documented\n # with the functionality that must be supported\n \n ######################################################################\n # Quit message\n # Command: QUIT\n # Parameters: \n # {[]}: an optional message from the user who has quit. If no message is provided, \n # use the default message: has quit \n # Examples: \n # QUIT # A message without a quit message\n # QUIT :shot with an arrow in the chest # A message with a quit message\n # Expected numeric replies: \n # None\n def quit(self, quit_message=None):\n msg = \"QUIT\"\n if quit_message:\n msg += \" :%s\" % quit_message\n self.send_message_to_server(msg)\n\n \n\n ######################################################################\n # This block of functions enables logging of info, debug, and error messages\n # Do not edit these functions. init_logging() is already called by the template code\n # You are encouraged to use print_info, print_debug, and print_error to log\n # messages useful to you in development\n\n def init_logging(self):\n # If we don't include a log file name, then don't log\n if not self.log_file:\n return\n\n # Get a reference to the logger for this program\n self.logger = logging.getLogger(\"IRCServer\")\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n # Create a file handler to store the log files\n fh = logging.FileHandler(os.path.join(__location__, 'Logs', '%s' % self.log_file), mode='w')\n\n # Set up the logging level. It defaults to INFO\n log_level = logging.INFO\n\n # Define a formatter that will be used to format each line in the log\n formatter = logging.Formatter(\n (\"%(asctime)s - %(name)s[%(process)d] - \"\n \"%(levelname)s - %(message)s\"))\n\n # Assign all of the necessary parameters\n fh.setLevel(log_level)\n fh.setFormatter(formatter)\n self.logger.setLevel(log_level)\n self.logger.addHandler(fh)\n\n def print_info(self, msg):\n print(\"[%s] \\t%s\" % (self.nick,msg))\n if self.logger:\n self.logger.info(msg)","sub_path":"CRCClient.py","file_name":"CRCClient.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"182481214","text":"def totalVolume(*box):\n vol = 0\n for i in box:\n vol = vol + (i[0]*i[1]*i[2])\n return vol\n\n\nprint(totalVolume([4,2,4],[3,3,3],[1,1,2],[2,1,1]))\nprint(totalVolume([2,2,2],[2,1,1]))\nprint(totalVolume([1,1,1]))","sub_path":"test/total_Volume.py","file_name":"total_Volume.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640364747","text":"# Fast Api App\n\n## requirements\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom numpy import sign\n#from nameko.rpc import rpc\n#from nameko.standalone.rpc import ClusterRpcProxy\n\n\nclass eliminate(BaseModel):\n A:list\n b:list\n\nclass interpolation(BaseModel):\n x:int\n xi:list\n yi:list\n\nclass differentiation(BaseModel):\n h:float\n p:int\n\nclass integration(BaseModel):\n a:int\n b:int\n\nclass rootFinding(BaseModel):\n a:float\n b:float\n dx:float\n\n# class Student(BaseModel):\n# firstname:str\n# lastname:str\n# email:str\n\napp = FastAPI() # FlaskApp()\n# class Body(BaseModel):\n# bitstring : str\n\n\norigins = [\n \"*\",\n \"http://localhost\",\n \"http://localhost:80\",\n \"http://localhost:8000\",\n \"http://localhost:8000/b2s\",\n \"http://localhost:8000/elimination\",\n \"http://localhost:8000/interpolation\",\n \"http://localhost:8000/differentiation\",\n \"http://localhost:8000/integration\",\n \"http://localhost:8000/root-finding\"\n\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@app.get(\"/\")\ndef hello():\n return {\"Hello\": \"World\"}\n \n@app.get(\"/b2s/{text}\")\ndef bit2int(text:str):\n s = int(text[0])\n e = int(text[1:9], 2)\n f = [ int(x) for x in text[9:]]\n x = 1 + sum([ int(f[i])*2**(-(i+1)) for i in range(len(f)) ])\n result = (-1)**s * 2**(e-127) * x \n return result\n\n# @app.post(\"/b2s/\")\n# async def test(body: Body):\n# b = body.bitstring\n# s = int(b[0])\n# e = int(b[1:9], 2)\n# f = [ int(x) for x in b[9:] ]\n# f = sum( [ f[i]*2**(-(i+1)) for i in range(len(f)) ] )\n# x = 1 + f\n# v = (-1)**s * 2**(e-127) * x\n# return {\"Result\": v}\n\n@app.post(\"/elimination\")\ndef api(data:eliminate):\n lam = int(data.A[1][0]) / int(data.A[0][0])\n data.A[1] = [ int(x)-lam*int(y) for x,y in zip(data.A[1],data.A[0]) ]\n data.b[1] = int(data.b[1]) - lam*int(data.b[0])\n \n lam = int(data.A[2][0]) / int(data.A[0][0])\n data.A[2] = [ int(x)-lam*int(y) for x,y in zip(data.A[2],data.A[0]) ]\n data.b[2] = int(data.b[2]) - lam*int(data.b[0])\n \n lam = int(data.A[2][1]) / int(data.A[1][1])\n data.A[2] = [ int(x)-lam*int(y) for x,y in zip(data.A[2],data.A[1]) ]\n data.b[2] = int(data.b[2]) - lam*int(data.b[1])\n\n x2 = int(data.b[2])/int(data.A[2][2])\n x1 = (int(data.b[1]) - int(data.A[1][2])*x2)/int(data.A[1][1])\n x0 = (int(data.b[0]) - int(data.A[0][1])*x1 - int(data.A[0][2])*x2)/int(data.A[0][0])\n\n result = [x0,x1,x2]\n return result\n\n@app.post(\"/interpolation\")\ndef api(data:interpolation):\n def Li(i, x, xi, yi):\n L = 1\n for j in range(len(xi)):\n if j != i:\n L = L*(x-int(xi[j]))/(int(xi[i])-int(xi[j]))\n return L\n def lin(x, xi, yi):\n return sum([ int(yi[i])*Li(i,x,xi,yi) for i in range(len(xi)) ])\n \n return lin(int(data.x),data.xi,data.yi)\n\n\n@app.post(\"/differentiation\")\ndef api(data:differentiation):\n def g(h):\n cda = {\n 0.64: 0.380610 ,\n 0.32: 0.371035 ,\n 0.16: 0.368711 ,\n 0.08: 0.368281 ,\n 0.04: 0.36875 ,\n 0.02: 0.37 ,\n 0.01: 0.38 ,\n 0.005: 0.40 ,\n 0.0025: 0.48 ,\n 0.00125: 1.28 ,\n }\n return cda[h]\n\n def richex(h, p):\n return ((2**p)* g(h/2)- g(h))/(2**p - 1)\n \n return richex(float(data.h),int(data.p))\n\n@app.post(\"/integration\")\ndef api(data:integration):\n def f(x): return 3*x**2 + 9*x + 2\n def simpson(f, a, b):\n n = 4\n x0 = a\n h = (b-a)/n\n return (f(x0+0*h) + 4*f(x0+1*h) + 2*f(x0+2*h) + 4*f(x0+3*h) + f(x0+4*h))*h/3\n \n return simpson(f, int(data.a), int(data.b))\n\n\n@app.post(\"/root-finding\")\ndef api(data:rootFinding):\n def f(x):\n return x**3 - 10.0*x**2 + 5.0\n\n def rootsearch(f,a,b,dx):\n x1, f1 = a, f(a)\n x2, f2 = a+dx, f(a+dx)\n while sign(f1) == sign(f2):\n if x1 >= b: return None,None\n x1 = x2; f1 = f2\n x2 = x1 + dx; f2 = f(x2)\n\n return \"(\"+str(x1)+\", \"+str(x2)+\")\"\n return rootsearch(f,float(data.a),float(data.b),float(data.dx))","sub_path":"backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"135491604","text":"# _*_ coding: utf-8 _*_\n# @Time : 2019/10/2 19:48\n# @Author : Ole211\n# @Site : \n# @File : get_access_token.py \n# @Software : PyCharm\n\nimport urllib.request\nimport sys\nimport json\nimport ssl\n\n'''\n# .百度账号:18668183817 API\nAPP_ID = \"17516199\"\nAPI_KEY = \"4cHuY83mlSV0k6pybfOyQSc3\"\nSECRET_KEY = \"mFM5ydm42txh94Uehys0rZu69SN1nVuY\"\n'''\n# 百度账号:594542251@qq.com API\nAPP_ID = '17413508'\nAPI_KEY = 'crxCtxVjGgPcHxwUcYEMoyws'\nSECRET_KEY = 'SBdNH6ZHHpqdNw5kobNI4w2lslAgjQUS'\n\n\ndef get_access_token():\n \n # client_id = 'a1oiSUfK3pmnUkay7zP5cbIy'\n # client_secret = 'yp6ogvjeZkoYBqLiB5UkWAyEpKKcgBdI'\n \n client_id = API_KEY\n client_secret = SECRET_KEY\n host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(client_id, client_secret)\n request = urllib.request.Request(host)\n request.add_header('Content-Type', 'application; charset=UTF-8')\n response = urllib.request.urlopen(request)\n content = response.read()\n if content:\n data = json.loads(content)\n return data['access_token']\n return None\n\nif __name__ == '__main__':\n print(get_access_token())","sub_path":"baidu-api/get_access_token.py","file_name":"get_access_token.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"271880506","text":"#coding=utf-8\nimport os\nimport h5py\nimport numpy as np\nimport matplotlib\nfrom keras.preprocessing import image\n\ndef load_inputdata():\n\n RESU_X, RESU_Y =960., 540.\n\n rootdir = \"/home/cherry/kaki_extracted/\"\n\n f=h5py.File(\"/home/cherry/kaki_extracted/train.h5\",\"w\")\n\n file = open(rootdir + 'label.txt')\n\n list = os.listdir(rootdir + 'augmented')\n\n train_data = np.zeros((len(list),224,224,3))\n label_data = np.zeros((len(list),10))\n\n lines = file.readlines()\n\n for line in lines:\n\n img = image.load_img(line.split()[0],target_size=(224,224))\n train_data[lines.index(line),:,:,:] = img\n number = line.split()\n label_data[lines.index(line),:] = [float(number[1]),float(number[2]),float(number[3]),float(number[4]),float(number[5]),float(number[6]),float(number[7]),float(number[8]),float(number[9]),float(number[10])]\n ####for test\n print(label_data[12])\n f.create_dataset('train_x', data = train_data)\n f.create_dataset('label_x', data = label_data)\n\n train_set_x = h5py.File('/home/cherry/kaki_extracted/train.h5', \"r\")\n X_train = np.array(train_set_x['train_x'][:])\n Y_train = np.array(train_set_x['label_x'][:])\n Y_train = Y_train.reshape(len(list),1,1,10)\n '''\n f=h5py.File(\"/home/cherry/keras/data/test.h5\",\"w\")\n\n file = open(rootdir + 'test.txt')\n\n list = os.listdir(rootdir + 'test/image2')\n\n train_data = np.zeros((len(list),224,224,3))\n label_data = np.zeros((len(list),4))\n\n lines = file.readlines()\n\n for line in lines:\n\n img = image.load_img(rootdir + line[0:19],target_size=(224,224))\n train_data[lines.index(line),:,:,:] = img\n number = line.split(' ')\n label_data[lines.index(line),:] = [int(number[1])/RESU_X,int(number[2])/RESU_Y,int(number[3])/RESU_X,int(number[4])/RESU_Y]\n\n f.create_dataset('text_x', data = train_data)\n f.create_dataset('label_y', data = label_data)\n\n train_set_y = h5py.File(rootdir + 'test.h5', \"r\")\n X_test_orig = np.array(train_set_y['text_x'][:])\n Y_test_orig = np.array(train_set_y['label_y'][:])\n Y_test_orig = Y_test_orig.reshape(len(list),1,1,4)\n\n print(Y_test_orig)\n ''' \n\n \n\n \n\n # X_test = X_test_orig/255.\n # Y_test = Y_test_orig\n\n print (\"number of training examples = \" + str(X_train.shape[0]))\n #print (\"number of training examples = \" + str(X_test.shape[0]))\n print (\"X_train shape: \" + str(X_train.shape))\n print (\"Y_train shape: \" + str(Y_train.shape))\n #print (\"X_test shape: \" + str(X_test.shape))\n #print (\"Y_test shape: \" + str(Y_test.shape))\n\n\n return X_train,Y_train\n###X_train shape: (n, 224, 224, 3)\n###Y_train shape: (n, 4)\n\nif __name__ == '__main__':\n load_inputdata()\n\n\n\n\n \n","sub_path":"kaki_extracted/h5_gener.py","file_name":"h5_gener.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"21673061","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom openerp import SUPERUSER_ID\nfrom openerp import http\nfrom openerp.tools.translate import _\nfrom openerp.http import request\nfrom lxml import etree\nfrom urlparse import urlparse\n# from datetime import timedelta\n# from openerp import fields\n# from openerp.addons.website.models.website import slug\n\nimport locale\nimport ast\n# import re\n\n# import copy\n# import requests\n\n# To get a new db connection:\n# from openerp.modules.registry import RegistryManager\n\n# import the base controller class to inherit from\nfrom openerp.addons.website_sale.controllers.main import website_sale\nfrom openerp.addons.website_sale.controllers.main import QueryURL\nfrom openerp.addons.fso_forms.controllers.controller import FsoForms\n\n_logger = logging.getLogger(__name__)\n\n\nclass website_sale_donate(website_sale):\n # List of Tuple (GET-Param, QContext-Field) to map\n # which GET Parameters are mapped to the qcontext\n # in order to pre-fill the form with parameters\n _product_page_parameter_pass_through = [\n ('price_donate', 'price_donate', lambda d: d),\n ('payment_interval', 'payment_interval_id', lambda d: int(d)),\n ]\n\n # Sort countries and states by website language\n # HINT: Sort by \"language in context\" for name field is not implemented in o8 fixed in o9 and up!\n # https://github.com/odoo/odoo/issues/5283\n def _locale_sorted_country_and_states(self, countries_on_top=('AT', 'DE', 'CH')):\n start_locale = locale.getlocale()\n\n # Set locale by website language for correct unicode sorting by name of countries\n try:\n locale.setlocale(locale.LC_ALL, request.env.context.get(\"lang\", \"de_AT\") + \".UTF-8\")\n except Exception as e:\n logging.error(\"Could not set locale for country and state sorting by website lang!\")\n pass\n\n # Sorted Countries (add Austria, Germany and Swiss to the top)\n # HINT: It is NO Problem if they are twice in the list :)\n countries_obj = request.env['res.country'].sudo()\n countries = countries_obj.search([])\n countries_sorted = sorted(countries, cmp=locale.strcoll, key=lambda c: c.name)\n countries_sorted_ids = [c.id for c in countries_sorted]\n # Add some countries on top of the list\n # HINT: They may be twice in the list but this does not matter in the web form selection field!\n countries_on_top_reversed = countries_on_top[::-1]\n for country_code in countries_on_top_reversed:\n country = countries_obj.search([('code', '=', country_code)])\n if country:\n countries_sorted_ids = [country.id] + countries_sorted_ids\n countries = countries_obj.browse(countries_sorted_ids)\n\n # Sorted States\n states_obj = request.env['res.country.state']\n states = states_obj.sudo().search([])\n states_sorted = sorted(states, cmp=locale.strcoll, key=lambda s: s.name)\n states = states_obj.sudo().browse([s.id for s in states_sorted])\n\n # Revert to original locale\n try:\n locale.setlocale(locale.LC_ALL, start_locale)\n except Exception as e:\n logging.error(\"Could not revert to initial locale after country and state sorting by website lang!\")\n pass\n\n return countries, states\n\n # Get custom billing fields from product of current product page or from product in sale.order\n def get_fso_forms_billing_fields(self, product=None):\n fso_forms_billing_fields = None\n\n if product:\n fso_forms_billing_fields = product.checkout_form_id.field_ids if product.checkout_form_id else None\n else:\n order = request.website.sale_get_order()\n if order and order.website_order_line:\n for line in order.website_order_line:\n if line.product_id and line.product_id.checkout_form_id:\n fso_forms_billing_fields = line.product_id.checkout_form_id.field_ids\n\n return fso_forms_billing_fields\n\n # Get custom giftee fields from product of current product page or from product in sale.order\n def get_fso_forms_giftee_fields(self, product=None):\n fso_forms_giftee_fields = None\n\n if product:\n fso_forms_giftee_fields = product.giftee_form_id.field_ids if product.giftee_form_id else None\n else:\n order = request.website.sale_get_order()\n if order and order.website_order_line:\n for line in order.website_order_line:\n if line.product_id and line.product_id.giftee_form_id:\n fso_forms_giftee_fields = line.product_id.giftee_form_id.field_ids\n\n return fso_forms_giftee_fields\n\n def _get_payment_interval_id(self, product):\n payment_interval_id = False\n\n # 1. Website-Settings global default payment interval\n if request.website.payment_interval_default:\n payment_interval_id = request.website.payment_interval_default.id\n # 2. DEPRECATED! (but still there for old database-backups compatibility)\n if product.payment_interval_ids:\n payment_interval_id = product.payment_interval_ids[0].id\n # 3. Products first payment_interval_line id\n if product.payment_interval_lines_ids:\n payment_interval_id = product.payment_interval_lines_ids[0].payment_interval_id.id\n # 4. Products default payment interval\n if product.payment_interval_default:\n payment_interval_id = product.payment_interval_default.id\n\n return payment_interval_id\n\n # SHOP PAGE: Add last_shop_page to the session\n @http.route()\n def shop(self, page=0, category=None, search='', **post):\n try:\n _logger.warning(\"shop(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"shop(): START\")\n\n base_url = str(urlparse(request.httprequest.base_url).path)\n request.session['last_shop_page'] = base_url + ('?category='+str(category.id) if category else '')\n request.session['last_page'] = request.session['last_shop_page']\n\n _logger.warning(\"shop(): END, return super(website_sale_donate, self).shop(...)\")\n return super(website_sale_donate, self).shop(page=page, category=category, search=search, **post)\n\n # PRODUCT PAGE: Extend the product page render request to include price_donate and payment_interval\n # so we have the same settings for arbitrary price and payment interval as already set by the user in the so line\n # Todo: Would need to update the Java Script of Website_sale to select the correct product variante if it\n # is already in the current sales order (like i do it for price_donate and payment_interval)\n # ALSO i need to update the java script that loads the product variant pictures\n # /shop/product/\n @http.route()\n def product(self, product, category='', search='', **kwargs):\n try:\n _logger.warning(\"product(): START %s kwargs: \\n%s\\n\" % (request.httprequest, kwargs or None))\n except:\n _logger.warning(\"product(): START\")\n\n # Make sure category is a valid int or an empty string!\n try:\n category = int(category)\n except:\n category = ''\n\n # Check visibility\n if not product.active or (not request.website.is_publisher() and not product.website_visible):\n #return request.render('website.page_404', {'path': product.website_url, 'code': '404'})\n return request.registry['ir.http']._handle_exception(AttributeError, 404)\n\n # Store the current request url in the session for possible returns\n # HINT: html escaping is done by request.redirect so not needed here!\n query = {'category': category, 'search': search}\n query = '&'.join(\"%s=%s\" % (key, val) for (key, val) in query.iteritems() if val)\n request.session['last_page'] = request.httprequest.base_url + '?' + query\n\n cr, uid, context = request.cr, request.uid, request.context\n\n # -----------------\n # ONE PAGE CHECKOUT Start\n # -----------------\n\n # ATTENTION: cart_update() expect a product.product id (a product variant id).\n # On a 'normal' shop product page this is always correct since the product variant id is given in\n # the checkoutbox (todo: check if this is true by checking the checkoutbox field product_id)\n\n # !!! GET REQUEST !!! (= Regular load of product page for the OPC product.template)\n # If this product has a custom billing field or style configuration we must add it right now to the sale order\n # because checkout_values() can only get the custom config from the sale order! .\n #\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # WARNING: This was disabled again because it causes WAY TOO MUCH side effects!!! It was only added for\n # the GL2K project with the custom themes and custom checkout fields ... so no big deal to disable it!\n # THIS MEANS THAT CUSTOM CHECKOUT FIELDS WILL CURRENTLY NOT WORK WITH OPC PAGES\n # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n # if request.httprequest.method != 'POST' \\\n # and product.product_page_template == u'website_sale_donate.ppt_opc' \\\n # and 'json_cart_update' not in request.session:\n #\n # sale_order = request.website.sale_get_order()\n # if sale_order and len(product.product_variant_ids) >= 1:\n # # WARNING: !!! 'product' is product.template but cart_update expects a product.product id !!!\n # product_variant_ids = product.product_variant_ids.ids\n #\n # # Check if any product.product ids of this product.template is already in the sale order\n # so_product_variant_ids = sale_order.order_line.mapped('product_id.id')\n # if not any(pv_id in so_product_variant_ids for pv_id in product_variant_ids):\n # _logger.warning(\"product(): ADD OPC PRODUCT TO SALE ORDER BECAUSE OF POSSIBLE CUSTOM CONFIG!\")\n # self.cart_update(product_id=product_variant_ids[0], set_qty=1)\n\n # INSTEAD OF ADDING THE OPC PRODUCT TO THE CART WE WILL CLEAR THE CART FROM OTHER PRODUCTS\n # IF WE ARE ON AN OPC PAGE\n if request.httprequest.method != 'POST' \\\n and product.product_page_template == u'website_sale_donate.ppt_opc' \\\n and 'json_cart_update' not in request.session:\n\n sale_order = request.website.sale_get_order()\n if sale_order and len(product.product_variant_ids) >= 1:\n # WARNING: !!! 'product' is product.template but cart_update expects a product.product id !!!\n product_variant_ids = product.product_variant_ids.ids\n\n # Remove all products from the sale order except variants of this product\n for l in sale_order.website_order_line:\n if l.product_id.id not in product_variant_ids:\n _logger.warning('Remove sale order line (ID: %s) from SO (ID: %s) because '\n 'we are on a ONE PAGE CHECKOUT product page!'\n '' % (l.id, sale_order.id))\n l.unlink()\n\n # !!! POST REQUEST !!! (OPC form was submitted)\n # HINT: This is needed since the regular route cart_update is not called in case of one-page-checkout\n if request.httprequest.method == 'POST' \\\n and product.product_page_template == u'website_sale_donate.ppt_opc' \\\n and 'json_cart_update' not in request.session:\n\n # CHECK FOR HONEY POT FIELD\n if self.tapped_into_honeypot(kwargs):\n return None\n\n # Create or Update sales Order\n # and set the Quantity to the value of the qty selector in the checkoutbox\n if 'add_qty' in kwargs and not 'set_qty' in kwargs:\n kwargs['set_qty'] = kwargs['add_qty']\n\n # Fallback if product_id is missing in kwargs\n # ATTENTION: The 'product_id' in the kwargs is always a product.product id an not a product.template id!\n if not kwargs.get('product_id'):\n first_product_variant_id = product.product_variant_ids.ids[0]\n _logger.error(\"product(): No product_id in kwargs! Using first product variant id from product template\"\n \" as a fallback! (product_template_id: %s, first_product_variant_id: %s)\"\n \"\" % (product.id, first_product_variant_id))\n kwargs['product_id'] = first_product_variant_id\n\n _logger.warning(\"product(): self.cart_update(**kwargs)\")\n\n cu_res = self.cart_update(**kwargs)\n # ATTENTION: Cart Update will always return an redirect no matter if there was an error or not!\n # but in case of an error we would need to stop here and return the redirect!\n # This is an ugly hack to fix this - it would be much better to add a new attrib to\n # cart_update(raise_on_errors=False) and catch the exception!\n if cu_res and hasattr(cu_res, 'location') and 'warnings' in cu_res.location:\n return cu_res\n # -----------------\n # ONE PAGE CHECKOUT End\n # -----------------\n\n # small_cart_update by json request: Remove json_cart_update in session\n # HINT: See 'def cart_update_json' below\n if 'json_cart_update' in request.session:\n request.session.pop('json_cart_update')\n\n # Render the regular product page (just to run the logic behind it)\n productpage = super(website_sale_donate, self).product(product, category, search, **kwargs)\n\n # Add Information that the product page controller was called\n productpage.qcontext['product_controller_called'] = True\n productpage.qcontext['ast'] = ast\n\n # Render Custom Product Template based on the product_page_template field if any set\n # Add One-Page-Checkout qcontext if template is ppt_opc\n if product.product_page_template:\n productpage = request.website.render(product.product_page_template, productpage.qcontext)\n\n # -----------------\n # ONE PAGE CHECKOUT Start\n # -----------------\n if product.product_page_template == u'website_sale_donate.ppt_opc':\n _logger.warning(\"product(): self.checkout(one_page_checkout=True ...\")\n\n # Render the checkout page\n if request.httprequest.method == 'POST':\n checkoutpage = self.checkout(one_page_checkout=True, product=product, **kwargs)\n else:\n checkoutpage = self.checkout(one_page_checkout=True, product=product,)\n\n # Add individual acquirer config to the qcontext of the checkout page\n if product.product_acquirer_lines_ids:\n _logger.info(\"One page checkout product %s (ID %s) with individual payment acquirer config!\" %\n (product.name, product.id))\n\n # HINT: all acquirers with \"globally_hidden\" set are moved to acquirers_hidden in opc_payment()\n acquirers = checkoutpage.qcontext.get('acquirers', [])\n acquirers_hidden = checkoutpage.qcontext.get('acquirers_hidden', [])\n all_acquires = acquirers + acquirers_hidden\n\n product_acquirers = []\n acquirer_dict = {acq.id: acq for acq in all_acquires}\n\n # HINT: product_acquirer_lines_ids is already correctly sorted by sequence\n for line in product.product_acquirer_lines_ids:\n if line.acquirer_id.id in acquirer_dict:\n product_acquirers.append(acquirer_dict[line.acquirer_id.id])\n checkoutpage.qcontext['acquirers'] = product_acquirers\n\n # Add the updated checkoutpage qcontext to the productpage qcontext\n productpage.qcontext.update(checkoutpage.qcontext)\n # -----------------\n # ONE PAGE CHECKOUT End\n # -----------------\n\n # Add Warnings if the page is called (redirected from cart_update) with warnings in GET request\n productpage.qcontext['warnings'] = kwargs.get('warnings')\n kwargs['warnings'] = None\n\n # Find selected payment interval\n # 1. Set payment interval from form post data\n for get_param, qcontext_field, convert_func in self._product_page_parameter_pass_through:\n if kwargs.get(get_param):\n productpage.qcontext[qcontext_field] = convert_func(kwargs.get(get_param))\n\n # 2. Or Set payment interval from defaults (only if not already set in productpage.qcontext)\n if not productpage.qcontext.get('payment_interval_id'):\n payment_interval_id = self._get_payment_interval_id(product)\n if payment_interval_id:\n productpage.qcontext['payment_interval_id'] = payment_interval_id\n\n # Get values from existing sale-order-line for price_donate and payment_interval_id\n sale_order_id = request.session.sale_order_id\n if sale_order_id:\n # Search for a sale-order-line for the current product in the sales order of the current session\n sol_obj = request.registry['sale.order.line']\n # Get sale-order-line id if product or variant of product is in active sale order\n sol = sol_obj.search(cr, SUPERUSER_ID,\n [['order_id', '=', sale_order_id],\n ['product_id', 'in', product.ids + product.product_variant_ids.ids]],\n context=context)\n if len(sol) == 1:\n # Get the sale.order.line\n sol = sol_obj.browse(cr, SUPERUSER_ID, sol[0], context=context)\n if sol.exists():\n\n # Add the Arbitrary Price to the qweb template context\n if sol.price_donate:\n productpage.qcontext['price_donate'] = sol.price_donate\n\n # Add the Payment Interval to the qweb template context\n if sol.payment_interval_id and sol.payment_interval_id in sol.product_id.payment_interval_ids:\n productpage.qcontext['payment_interval_id'] = sol.payment_interval_id.id\n\n # Add last_product to add product information to the body and to enable specific css themes\n # HINT: The information about the last_product is added to the in the template\n # 'website_sale_donate_product_data'\n # ATTENTION: You must prevent the settings of individual product themes for products that are in a\n # 'category' - in this case you must do the individual css design by the category!\n # productpage.qcontext['last_product'] = product\n\n _logger.warning(\"product(): END\")\n return productpage\n\n # SHOPPING CART: add keep to the values of qcontext\n # /shop/cart\n @http.route()\n def cart(self, **post):\n try:\n _logger.warning(\"cart(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"cart(): START\")\n\n cartpage = super(website_sale_donate, self).cart(**post)\n cartpage.qcontext['keep'] = QueryURL(attrib=request.httprequest.args.getlist('attrib'))\n\n # Add Information that the cart page controller was called\n cartpage.qcontext['cart_controller_called'] = True\n\n # One-Page-Checkout\n if request.website['one_page_checkout']:\n\n _logger.warning(\"cart(): END, opc redirect to /shop/checkout\")\n return request.redirect(\"/shop/checkout\")\n\n _logger.warning(\"cart(): END\")\n return cartpage\n\n # NEW ROUTE: SIMPLE CHECKOUT:\n # Add an alternative route for products to directly add them to the shopping cart and DIRECTLY go to the checkout\n # This is useful if you want to create buttons to directly pay / donate for a product\n # HINT: We have to use product.product because otherwise we could not directly check out product variants AND\n # _cart_update expects an product.product id anyway\n @http.route(['/shop/simplecheckout/',\n '/shop/simple_checkout/'],\n auth=\"public\", website=True)\n def simple_checkout(self, product, **kw):\n try:\n _logger.warning(\"simple_checkout(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"simple_checkout(): START\")\n\n kw.update(simple_checkout=True)\n _logger.warning(\"simple_checkout(): END, return self.cart_update(product, **kw)\")\n return self.cart_update(product, **kw)\n\n # SHOPPING CART UPDATE\n # /shop/cart/update\n # HINT: can also be called by Products-Listing Category Page if add-to-cart is enabled\n @http.route(['/shop/cart/update'])\n def cart_update(self, product_id, add_qty=1, set_qty=0, **kw):\n # ATTENTION: !!! product_id is meant to be a product.product id !!! (and !NOT! a product_template id!)\n try:\n _logger.warning(\"cart_update(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"cart_update(): START\")\n\n cr, uid, context = request.cr, request.uid, request.context\n product = request.registry['product.product'].browse(cr, SUPERUSER_ID, [int(product_id)], context=context)\n referrer = None\n\n if request.session.get('last_page'):\n referrer = request.session.get('last_page')\n _logger.info(\"Use REFERER (from session last_page): %s\" % referrer)\n else:\n referrer = '/shop/product/%s' % product.product_tmpl_id.id\n _logger.info(\"Use REFERER (from product.product_tmpl_id Point 1): %s\" % referrer)\n\n if '?' not in referrer:\n referrer = referrer + '?'\n\n # Validate (donation) Arbitrary Price\n warnings = None\n\n # Check price_donate\n if 'price_donate' in kw:\n price_donate = kw.get('price_donate')\n _logger.info('cart_update(): price_donate in kwargs: %s' % str(price_donate))\n\n # TODO: Try to convert price_donate string to a valid number (amount)\n # TODO: rethink if the fallback to list_price of price is good - This is not done here but in\n # _cart_update() if price_donate seems invalid\n # TODO: Find a way to prevent loosing the form data if price_donate is not ok\n # TODO: use jqueryvalidate to validate the price_donate field also! (Just numbers!)\n # This may be a bit tricky because some browser add an ,00 to the number and we dont want 4,00 > 400!\n\n price = kw.get('price_donate') or product.list_price or product.price\n # HINT: If price_donate is not a valid number it will be empty and so the product.list_price is used!\n # Therefore the try statement is not really needed (but kept for safety).\n try:\n if product.price_donate_min and float(product.price_donate_min) > float(price):\n warnings = _('Der Betrag muss %s oder hoeher sein.' % float(product.price_donate_min))\n except ValueError:\n warnings = _('Der Betrag muss eine Zahl sein!')\n pass\n if warnings:\n # ATTENTION! Remove kwargs to avoid calling OPC product pages with all kwargs again!\n if \"/product\" in referrer:\n referrer = '/shop/product/%s?' % product.product_tmpl_id.id\n _logger.info(\"Use REFERER (from product.product_tmpl_id Point 2): %s\" % referrer)\n\n # Add the warning to the referer page\n referrer = referrer + '&warnings=' + warnings\n _logger.error(\"cart_update(): END, arbitrary price (%s) ERROR! Warnings: %s! Redirecting to referrer: %s\"\n \"\" % (price or \"\", str(warnings), str(referrer)))\n return request.redirect(referrer)\n\n # PAYMENT INTERVAL\n # INFO: This is only needed if products are directly added to cart on shop pages (product listings)\n if 'payment_interval_id' not in kw:\n payment_interval_id = self._get_payment_interval_id(product)\n if payment_interval_id:\n kw['payment_interval_id'] = payment_interval_id\n\n # ARBITRARY PRICE (price_donate)\n # HINT: price_donate= can already be set! See _cart_update in website_sale_donate.py\n\n # Call Super\n # INFO: Pass kw to _cart_update to transfer all post variables to _cart_update\n # This is needed to get the Value of the arbitrary price from the input field\n order_line = request.website.sale_get_order(force_create=1)._cart_update(product_id=int(product_id),\n add_qty=float(add_qty),\n set_qty=float(set_qty),\n context=context,\n **kw)\n\n # Attention: It is very important to call sale_get_order again after the order_line creation above to make\n # sure fs_ptoken is updated also for the new sale order line\n order = request.website.sale_get_order()\n _logger.warning(\"cart_update(): sale order number %s\" % order.name)\n\n # EXIT A) Simple Checkout\n if product.simple_checkout or kw.get('simple_checkout'):\n kw.pop('simple_checkout', None)\n\n # Redirect to the product page if product-page-layout is one-page-checkout\n if product.product_page_template == u'website_sale_donate.ppt_opc':\n _logger.warning(\"cart_update(): END, EXIT A) Simple Checkout, redirect to /shop/product/... \")\n return request.redirect('/shop/product/' + str(product.product_tmpl_id.id))\n\n # Redirect to the checkout page\n # return request.redirect('/shop/checkout' + '?' + request.httprequest.query_string)\n _logger.warning(\"cart_update(): END, EXIT A) Simple Checkout, redirect to /shop/checkout\")\n return request.redirect('/shop/checkout')\n\n # EXIT B) Stay on the current page if \"Add to cart and stay on current page\" is set AND\n # we come from a category page (product listing page)\n # TODO: Check what happens if we come from a category page where the URL was changed by SEO URL!!\n if kw.get('add_to_cart_stay_on_page', False):\n _logger.warning(\"cart_update(): END, EXIT B) Stay on the current page\")\n return request.redirect(referrer)\n\n # EXIT C) Redirect to the shopping cart\n _logger.warning(\"cart_update(): END, EXIT C) Redirect to the shopping cart\")\n return request.redirect(\"/shop/cart\")\n\n # /shop/cart/update_json\n @http.route()\n def cart_update_json(self, product_id, line_id, add_qty=None, set_qty=None, display=True):\n try:\n _logger.warning(\"cart_update_json(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"cart_update_json(): START\")\n\n request.session['json_cart_update'] = 'True'\n _logger.warning(\"cart_update_json(): END, super(website_sale_donate, self).cart_update_json(...)\")\n return super(website_sale_donate, self).cart_update_json(product_id, line_id,\n add_qty=add_qty, set_qty=set_qty, display=display)\n\n # Add Shipping and Billing Fields to values (= the qcontext for the checkout template)\n # HINT: The calculated values for the fields can be found in the qcontext dict in key 'checkout'\n def checkout_values(self, data=None, product=None):\n # Add geoip to session if not there\n if 'geoip' not in request.session:\n request.session['geoip'] = {}\n\n # Call super\n values = super(website_sale_donate, self).checkout_values(data=data)\n\n # Update countries and states in values with countries and states sorted by website locale\n countries, states = self._locale_sorted_country_and_states(countries_on_top=('AT', 'DE', 'CH'))\n if values.get('countries', False) and countries:\n values['countries'] = countries\n if values.get('states', False) and states:\n values['states'] = states\n\n # Add billing fields from the product linked fson.form (fso_forms)\n fso_forms_billing_fields = self.get_fso_forms_billing_fields(product=product)\n if fso_forms_billing_fields:\n values['fso_forms_billing_fields'] = fso_forms_billing_fields\n\n # Parse form data to match odoo field data types = preparation for checkout_form_save()\n if values.get('checkout') and data:\n fso_forms_obj = FsoForms()\n parsed_form_values = fso_forms_obj._prepare_field_data(form=fso_forms_billing_fields[0].form_id,\n form_field_data=data)\n values['checkout'].update(parsed_form_values)\n\n # Append the mail message fields and data\n for f_field in fso_forms_billing_fields:\n if f_field.type == 'mail_message':\n f_name = f_field.name\n if f_name in data:\n values['checkout'][f_name] = data[f_name]\n\n # Add billing fields from the website\n else:\n billing_fields_obj = request.env['website.checkout_billing_fields']\n billing_fields = billing_fields_obj.search([])\n values['billing_fields'] = billing_fields\n\n # Fix website billing fields 'boolean' and 'date' field type values in the 'checkout' dict!\n for field in billing_fields:\n f_name = field.res_partner_field_id.name\n f_type = field.res_partner_field_id.ttype\n # FIX: Set value to python True or False for all boolean fields (instead of true or false)\n if f_type == 'boolean':\n if values['checkout'].get(f_name) == 'True' or values['checkout'].get(f_name):\n values['checkout'][f_name] = True\n else:\n values['checkout'][f_name] = False\n # Fix for Date fields: convert '' to None\n elif f_type == 'date':\n values['checkout'][f_name] = values['checkout'].get(f_name).strip() if values['checkout'].get(f_name)\\\n else None\n\n # Add Shipping Fields to values dict\n # ----------------------------------\n shipping_fields = request.env['website.checkout_shipping_fields']\n shipping_fields = shipping_fields.search([])\n values['shipping_fields'] = shipping_fields\n\n for field in shipping_fields:\n f_name = 'shipping_' + field.res_partner_field_id.name\n f_type = field.res_partner_field_id.ttype\n if f_type == 'boolean':\n if values['checkout'].get(f_name) == 'True' or values['checkout'].get(f_name):\n values['checkout'][f_name] = True\n else:\n values['checkout'][f_name] = False\n elif f_type == 'date':\n values['checkout'][f_name] = values['checkout'].get(f_name).strip() if values['checkout'].get(f_name) \\\n else None\n\n # Add option-tag attributes for shipping-address-selector for wsd_checkout_form_billing_fields template\n # -----------------------------------------------------------------------------------------------------\n if values.get('shippings'):\n shippings_selector_attrs = dict()\n # Render the dict for every shipping res.partner\n for shipping in values.get('shippings'):\n field_data = dict()\n for field in shipping_fields:\n f_name = field.res_partner_field_id.name\n field_data['data-shipping_' + f_name] = shipping[f_name]\n shippings_selector_attrs[shipping.id] = field_data\n values['shippings_selector_attrs'] = shippings_selector_attrs\n\n # Add values['fso_forms_giftee_fields'] for form rendering\n # Add giftee fields to values['checkout'] for checkout_form_save()\n # --------------------------------\n # HINT: The field prefix is set by the template: wsd_checkout_form_gifting_fields\n # \n fso_forms_giftee_fields = self.get_fso_forms_giftee_fields(product=product)\n if fso_forms_giftee_fields:\n # Append the fso_forms giftee field definitions for form rendering\n values['fso_forms_giftee_fields'] = fso_forms_giftee_fields\n\n # Prepare and append giftee form data to values['checkout'] if the giftee checkbox is enabled\n if data and data.get('enable_giftee_checkbox', None):\n #values['enable_giftee_checkbox'] = data.get('enable_giftee_checkbox', None)\n\n # Extract giftee data from the form data\n giftee_form_data = {}\n giftee_mail_message_form_data = {}\n\n for gf_field in fso_forms_giftee_fields:\n if gf_field.type not in ['model', 'mail_message']:\n continue\n f_name = gf_field.name\n gf_name = 'giftee_' + f_name\n if gf_field.type == 'model':\n giftee_form_data[f_name] = data.get(gf_name, None)\n if gf_field.type == 'mail_message':\n giftee_mail_message_form_data[f_name] = data.get(gf_name, None)\n\n # Prepare the giftee form data for the odoo record\n fso_forms_obj = FsoForms()\n odoo_ready_giftee_form_data = fso_forms_obj._prepare_field_data(\n form=fso_forms_giftee_fields[0].form_id,\n form_field_data=giftee_form_data)\n\n # Add the prefix again and add the giftee field data to the checkout dict in the values\n giftee_data = {'giftee_'+k: v for k, v in odoo_ready_giftee_form_data.iteritems()}\n\n # Add the giftee mail message data to checkout to be used in form_save\n giftee_data.update({'giftee_'+k: v for k, v in giftee_mail_message_form_data.iteritems()})\n\n values['checkout'].update(giftee_data)\n\n return values\n\n def checkout_form_save(self, checkout):\n super(website_sale_donate, self).checkout_form_save(checkout)\n\n order = request.website.sale_get_order(force_create=1, context=request.env.context)\n\n # Post messages to the sale order for mail_message field types\n # ------------------------------------------------------------\n fso_form_checkout_fields = self.get_fso_forms_billing_fields()\n if fso_form_checkout_fields:\n mail_message_data = {}\n for f_field in fso_form_checkout_fields:\n if f_field.type == 'mail_message':\n f_name = f_field.name\n form_f_name = f_name\n if form_f_name in checkout:\n mail_message_data[f_name] = checkout[form_f_name]\n\n if mail_message_data:\n checkout_form = fso_form_checkout_fields[0].form_id\n try:\n FsoForms().post_messages(form=checkout_form, form_field_data=mail_message_data, record=order)\n except Exception as e:\n _logger.error(\"Could not post messages %s to order %s:\\n%s\"\n \"\" % (mail_message_data, order, repr(e)))\n pass\n\n # Save giftee data to giftee partner, update sale order and post giftee mail_messages to sale order\n # -------------------------------------------------------------------------------------------------\n giftee_fields = self.get_fso_forms_giftee_fields(product=None)\n if giftee_fields:\n\n odoo_ready_giftee_data = {}\n giftee_mail_message_data = {}\n\n # Get the giftee data from the 'checkout' dict\n for gf_field in giftee_fields:\n if gf_field.type in ['model', 'mail_message']:\n f_name = gf_field.name\n form_f_name = 'giftee_' + f_name\n if form_f_name in checkout:\n if gf_field.type == 'model':\n odoo_ready_giftee_data[f_name] = checkout[form_f_name]\n if gf_field.type == 'mail_message':\n giftee_mail_message_data[f_name] = checkout[form_f_name]\n\n # Remove the giftee from the sale order if no giftee data is available and return!\n if not odoo_ready_giftee_data:\n if order.giftee_partner_id:\n # giftee = order.giftee_partner_id\n order.sudo().write({'giftee_partner_id': False})\n # if giftee.fs_origin == 'giftee order id: ' + order.id:\n # try:\n # giftee.sudo().unlink()\n # except:\n # _logger.info(\"Could not delete giftee %s\" % giftee.id)\n # pass\n return\n\n # Append the lang\n partner_lang = request.lang if request.lang in [lang.code for lang in request.website.language_ids] else None\n if odoo_ready_giftee_data and partner_lang:\n odoo_ready_giftee_data['lang'] = partner_lang\n\n # TODO: Append the FRST CDS (origin) if any to the partner\n\n if order.giftee_partner_id:\n order.giftee_partner_id.sudo().write(odoo_ready_giftee_data)\n _logger.info(\"Update giftee %s of sale order %s with data %s\"\n % (order.giftee_partner_id.id, order.id, odoo_ready_giftee_data))\n else:\n # if order:\n # odoo_ready_giftee_data['fs_origin'] = 'giftee order id: ' + order.id\n giftee = request.env['res.partner'].sudo().create(odoo_ready_giftee_data)\n order.sudo().write({'giftee_partner_id': giftee.id})\n _logger.info(\"Created giftee %s for sale order %s with data %s\"\n % (giftee.id, order.id, odoo_ready_giftee_data))\n\n # Post giftee messages to the sale order for mail_message field types\n if giftee_mail_message_data:\n giftee_form = giftee_fields[0].form_id\n try:\n FsoForms().post_messages(form=giftee_form, form_field_data=giftee_mail_message_data,\n record=order)\n except Exception as e:\n _logger.error(\"Could not post giftee messages %s to order %s:\\n%s\"\n \"\" % (giftee_mail_message_data, order, repr(e)))\n pass\n\n # Set mandatory billing and shipping fields\n def _get_mandatory_billing_fields(self):\n fso_forms_billing_fields = self.get_fso_forms_billing_fields()\n if fso_forms_billing_fields:\n mandatory_enabled_mapped_form_fields = fso_forms_billing_fields.filtered(\n lambda f: f.show and f.type == 'model' and f.mandatory)\n return [field.name for field in mandatory_enabled_mapped_form_fields]\n else:\n billing_fields = request.env['website.checkout_billing_fields']\n billing_fields = billing_fields.search([('res_partner_field_id', '!=', False),\n ('show', '=', True),\n ('mandatory', '=', True)])\n return [field.res_partner_field_id.name for field in billing_fields]\n\n def _get_optional_billing_fields(self):\n fso_forms_billing_fields = self.get_fso_forms_billing_fields()\n if fso_forms_billing_fields:\n nonmandatory_enabled_mapped_form_fields = fso_forms_billing_fields.filtered(\n lambda f: f.show and f.type == 'model' and not f.mandatory)\n return [field.name for field in nonmandatory_enabled_mapped_form_fields]\n else:\n billing_fields = request.env['website.checkout_billing_fields']\n billing_fields = billing_fields.search([('res_partner_field_id', '!=', False),\n ('show', '=', True),\n ('mandatory', '=', False)])\n return [field.res_partner_field_id.name for field in billing_fields]\n\n def _get_mandatory_shipping_fields(self):\n shipping_fields = request.env['website.checkout_shipping_fields']\n shipping_fields = shipping_fields.search([('res_partner_field_id', '!=', False),\n ('show', '=', True),\n ('mandatory', '=', True)])\n mandatory_ship = [field.res_partner_field_id.name for field in shipping_fields]\n return mandatory_ship\n\n def _get_optional_shipping_fields(self):\n shipping_fields = request.env['website.checkout_shipping_fields']\n shipping_fields = shipping_fields.search([('res_partner_field_id', '!=', False),\n ('show', '=', True),\n ('mandatory', '=', False)])\n optional_ship = [field.res_partner_field_id.name for field in shipping_fields]\n return optional_ship\n\n # =================\n # ONE PAGE CHECKOUT\n # =================\n\n # Render the payment page with an additional dictionary acquirers_opc for One-Page-Checkout\n def opc_payment(self, **post):\n _logger.warning(\"opc_payment(): START\")\n opc_warnings = list()\n\n # ---------------\n # UPDATE DELIVERY\n # ---------------\n # Update the delivery and then remove carrier_id from post to not always generate a redirection!\n # HINT: self.payment(**post) will basically just call _check_carrier_quotation() ir a carrier_id is in post\n # and return a redirection to the payment page again.\n # ATTENTION: _check_carrier_quotation() was completely rewritten to avoid unnecessary writes to the SO!\n # HINT: with carrier id website_sale_delivery payment() would update the SO and therefore the acquierer buttons\n # would never be rendered. this is why we need to run it twice if a carrier_id is found in post!\n # HINT: This basically runs _check_carrier_quotation() and returns a redirect to /shop/payment if carrier_id is\n # in post!\n # TODO: check what we should do with errors at this stage\n # ATTENTION: Input names are delivery_type which is normally remapped by java script to a call to\n # window.location.href = '/shop/payment?carrier_id=' + carrier_id;\n carrier_id = post.get('delivery_type')\n if carrier_id:\n post['carrier_id'] = int(carrier_id)\n _logger.warning(\"opc_payment(): 'delivery_type' = 'carrier_id' found in post (ID: %s)\" % carrier_id)\n _logger.warning(\"opc_payment(): Run original payment() to update SO for delivery method\")\n super(website_sale_donate, self).payment(**post)\n _logger.warning(\"opc_payment(): Pop carrier_id from post to render acquirer forms in next step\")\n post.pop('carrier_id')\n\n # --------------------------------------------------------\n # CREATE THE PAYMENT TRANSACTION AND UPDATE THE SALE ORDER\n # --------------------------------------------------------\n # TODO: Maybe this needs to be done before UPDATE DELIVERY?\n acquirer_id = post.get('acquirer')\n if acquirer_id:\n acquirer_id = int(acquirer_id)\n _logger.warning(\"opc_payment(): 'acquirer' (ID: %s) found in post\" % acquirer_id)\n _logger.warning(\"opc_payment(): add 'acquirer' to session\")\n request.session['acquirer_id'] = acquirer_id\n _logger.warning(\"opc_payment(): CREATE THE PAYMENT TRANSACTION AND UPDATE THE SALE ORDER\")\n tx = self.payment_transaction_logic(acquirer_id=acquirer_id)\n if not tx:\n _logger.error(\"opc_payment(): ERROR payment_transaction_logic() returned nothing! WHAT NOW?\")\n opc_warnings.append(_('Please add at least one product'))\n\n # --------------------------------------------------\n # CALL ORIGINAL payment() TO RENDER ACQUIRER BUTTONS\n # --------------------------------------------------\n _logger.warning(\"opc_payment(): run super().payment(**post)\")\n payment_page = super(website_sale_donate, self).payment(**post)\n\n # Add Information that the payment page controller was called\n if hasattr(payment_page, 'qcontext'):\n payment_page.qcontext['payment_controller_called'] = True\n\n # ----------------\n # CHECK FOR ERRORS\n # ----------------\n _logger.warning(\"opc_payment(): CHECK FOR ERRORS\")\n # TODO: Check if this works with INTEGRATE LOGIC FROM PAYMENT ...\n # TODO: Check what we should do if we have a carrier id\n # Check for Errors or just redirect triggered by payment() overwrite from website_sale_delivery\n if not hasattr(payment_page, 'qcontext') or not payment_page.qcontext:\n _logger.error('opc_payment(): Orig payment page has NO QCONTEXT!')\n return payment_page\n if opc_warnings:\n payment_page.qcontext['opc_warnings'] = opc_warnings\n _logger.error('opc_payment(): opc_warnings found')\n return payment_page\n if payment_page.qcontext.get('errors'):\n _logger.error('opc_payment(): qcontext.errors found in original payment page')\n return payment_page\n\n # ---------------------------\n # ADD acquirer_id TO QCONTEXT\n # ---------------------------\n # HINT: This is not needed for payment() but for checkout() if OPC\n _logger.warning(\"opc_payment(): ADD acquirer_id TO QCONTEXT\")\n if acquirer_id:\n _logger.warning('opc_payment(): add \"acquirer_id\" to qcontext')\n payment_page.qcontext.update({'acquirer_id': int(acquirer_id)})\n\n # ----------------------------------------------------------------\n # CHECK IF THERE IS ALREADY A PAYMENT TRANSACTION LINKED TO THE SO\n # ----------------------------------------------------------------\n # Odoo changed the rendering of the pay-now-button forms and only add the payment transaction reference\n # in the function payment_transaction(). This is a problem for our payment providers where we want the user\n # to add custom information like IBAN or BIC or the checkbox for the payment slips. Therefore we re-add it here\n _logger.warning(\"opc_payment(): CHECK IF THERE IS ALREADY A PAYMENT TRANSACTION LINKED TO THE SO\")\n tx = request.website.sale_get_transaction()\n if tx:\n cr, uid, context = request.cr, request.uid, request.context\n payment_obj = request.registry.get('payment.acquirer')\n order = request.website.sale_get_order(context=context)\n # Get the order as Superuser again to gain access to all fields\n order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, order.id, context=context)\n for acquirer in payment_page.qcontext['acquirers']:\n if tx.acquirer_id.id == acquirer.id:\n # Render the acquirer button again but now with correct payment transaction reference\n _logger.warning(\"opc_payment(): Render the acquirer button again but now with \"\n \"correct payment transaction reference: %s\" % tx.reference)\n acquirer.button = payment_obj.render(\n cr, SUPERUSER_ID, acquirer.id,\n tx.reference,\n order.amount_total,\n order.pricelist_id.currency_id.id,\n partner_id=order.partner_shipping_id.id or order.partner_invoice_id.id,\n tx_values={\n 'return_url': '/shop/payment/validate',\n },\n context=dict(context, submit_class='btn btn-primary', submit_txt=_('Pay Now')))\n\n # ---------------------------------------------------\n # ADD EXTRA INFORMATION TO QCONTEXT FOR OPC TEMPLATES\n # ---------------------------------------------------\n _logger.warning(\"opc_payment(): ADD EXTRA INFORMATION TO QCONTEXT FOR OPC TEMPLATES\")\n payment_qcontext = payment_page.qcontext\n\n # ATTENTION: Always use one page checkout for the payment page\n payment_qcontext['one_page_checkout'] = True\n\n # Add Billing Fields to qcontext for address display\n billing_fields_obj = request.env['website.checkout_billing_fields']\n payment_qcontext['billing_fields'] = billing_fields_obj.search([])\n\n # Add Shipping Fields qcontext for address display\n shipping_fields_obj = request.env['website.checkout_shipping_fields']\n payment_qcontext['shipping_fields'] = shipping_fields_obj.search([])\n\n # Ugly hack to make getattr available in the payment page qweb templates\n payment_qcontext['getattr'] = getattr\n\n # ------------------------------------------------------------------------------------------------------\n # CHANGE ORIGINAL ACQUIRER BUTTON FORMS AND ADD A SECOND SET OF BUTTONS WITHOUT A FORM FOR OPC TEMPLATES\n # ------------------------------------------------------------------------------------------------------\n _logger.warning(\"opc_payment(): CHANGE ORIGINAL ACQUIRER BUTTON FORMS\")\n for acquirer in payment_qcontext['acquirers']:\n\n # SET ORIGINAL INPUT TAGS TO POST DATA IF ANY\n # HINT: right now this is only useful for the iban and bic field from the pp \"payment_frst\"\n # HINT: \"target\"=\"_top\" for iframes is already set in website_sale_donate.payment_acquirer.xml\n # HINT: The values of the input fields would only be available in **post as the prefixed names\n # HINT: We do change the content of the \"value\" attribute but NOT the content of the \"name\" attribute here!\n button = etree.fromstring(acquirer.button)\n assert button.tag == 'form', \"ERROR: One Page Checkout: Payment Button has not
as root tag!\"\n for form_input in button.iter(\"input\"):\n if form_input.get('name'):\n prefixed_input_name = \"aq\" + str(acquirer.id) + '_' + str(form_input.get('name'))\n if not form_input.get('value') and prefixed_input_name in post:\n form_input.set('value', post.get(prefixed_input_name))\n # For checkboxes:\n if form_input.get('type') == 'checkbox' and post.get(prefixed_input_name, False):\n form_input.set('checked', 'checked')\n acquirer.button = etree.tostring(button, encoding='UTF-8', pretty_print=True)\n\n # CREATE A SECOND VERSION OFF THE ACQUIRER BUTTONS FOR OPC (stored in 'button_opc' instead of 'button')\n # http://lxml.de/lxmlhtml.html\n # http://lxml.de/tutorial.html\n # Changes:\n # - Prefix the content of the \"name\" attribute for input tags with aq[id]_[originalname]\n # - Set post value (The value of input fields from **post was already set above. So nothing to do here.)\n # - Remove surrounding \"form\" tag\n # - Remove submit button\n # HINT: See templates_60_checkout_steps.xml > wsd_opc_payment for details\n # HINT: We have to do it this way because any PP inherits from the template payment.acquirer_form.xml\n # Therefore we can not just change one template but would need to modificate all templates of PP's.\n # To avoid this we change the rendered content here after all template merging and rendering is done.\n button = etree.fromstring(acquirer.button)\n # Prefix input tag 'name' attribute value with aq[id]_[originalname]\n # HINT: This is needed because for OPC Pages all input fields of all acquirer buttons are in one form\n # Therefore we have to make sure that all input tag names are unique\n for form_input in button.iter(\"input\"):\n if form_input.get('name'):\n form_input.set('name', \"aq\" + str(acquirer.id) + '_' + str(form_input.get('name')))\n # Remove the Pay-Now button\n # HINT: Element tree functions will return None if an element is not found, but an empty element\n # will have a boolean value of False because it acts like a container\n if button.find(\".//button\") is not None:\n button.find(\".//button\").getparent().remove(button.find(\".//button\"))\n\n # Store the form tag attributes in extra input fields\n # HINT: For debug only right now. Maybe we need them in them in the future e.g.: in java script\n for item in ['action', 'method', 'target']:\n child = etree.SubElement(button, \"input\")\n child.set('name', \"aq\" + str(acquirer.id) + '_form_' + item)\n child.set('type', 'hidden')\n # HINT: There may be no target attribute set in the acquirer button!\n child.set('value', button.get(item) if button.get(item) else '')\n\n # Replace the form tag with a div tag\n button_new = etree.Element('div')\n button_new.set('id', \"aq\" + str(acquirer.id))\n for child in button:\n button_new.append(child)\n button = button_new\n\n # Convert the button etree back to a string and store it in button_opc\n # print(etree.tostring(button, encoding='UTF-8', pretty_print=True))\n acquirer.button_opc = etree.tostring(button, encoding='UTF-8', pretty_print=True)\n\n # ---------------------------------\n # ACQUIRER SELECTION AND VALIDATION\n # ---------------------------------\n if post.get('acquirer'):\n _logger.warning(\"opc_payment(): ACQUIRER SELECTION AND VALIDATION\")\n # Set the current acquirer to be correctly pre selected on subsequent renders of the checkout page\n payment_qcontext['acquirer_id'] = post.get('acquirer')\n\n # Validate if the current acquirer matches the sales order payment interval\n order = request.website.sale_get_order()\n acquirer = request.env['payment.acquirer']\n acquirer = acquirer.search([('id', '=', post.get('acquirer'))])\n if order and acquirer and (order.has_recurring and not acquirer.recurring_transactions):\n msg = _('The selected payment method does not support recurring payments!')\n _logger.warning(msg)\n # HINT that the qcontext has no errors is checked above already\n payment_qcontext['errors'] = {'pm_recurring': [_('Wrong payment method'), msg]}\n\n # TODO: Validate acquirer input fields e.g.: iban and bic\n # Maybe add a new method to payment providers: e.g.: _[paymentmethod]_pre_send_form_validate()\n\n # --------------------------------------\n # ADD \"acquirer_auto_submit\" TO QCONTEXT\n # --------------------------------------\n acquirer_active = False\n if acquirer_id:\n _logger.warning(\"opc_payment(): ADD 'acquirer_auto_submit' TO QCONTEXT\")\n for acquirer in payment_qcontext['acquirers']:\n if int(acquirer.id) == acquirer_id:\n acquirer_active = acquirer\n break\n if not acquirer_active:\n _logger.error('opc_payment(): ERROR selected acquirer not found in acquirers!')\n if not payment_qcontext.get('opc_warnings'):\n payment_qcontext['opc_warnings'] = list()\n payment_qcontext['opc_warnings'].append(_('Please select an other acquirer.'))\n payment_qcontext['acquirer_auto_submit'] = acquirer_active\n\n # -------------------------------------------------------\n # MOVE ACQUIRERS WITH globally_hidden TO acquirers_hidden\n # -------------------------------------------------------\n _logger.warning(\"opc_payment(): MOVE ACQUIRERS WITH globally_hidden TO acquirers_hidden\")\n # HINT: This is for individual payment acquirer configuration per one page checkout product\n # https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating\n payment_qcontext['acquirers_hidden'] = [acq for acq in payment_qcontext['acquirers'] if acq.globally_hidden]\n payment_qcontext['acquirers'][:] = [acq for acq in payment_qcontext['acquirers'] if not acq.globally_hidden]\n\n _logger.warning(\"opc_payment(): END\")\n # TODO: Remove the parts added here from checkout() and payment()\n return payment_page\n\n # payment_transaction controller method (json route) gets replaced with this method\n # (see below for /shop/payment/transaction/ and in checkout controller for one-page-checkout)\n # This is called either by the json route after the pay-now button is pressed or during the one-page-checkout\n # HINT: We can not directly call payment_transaction e.g.:\n def payment_transaction_logic(self, acquirer_id, checkout_page=None, **post):\n _logger.warning(\"payment_transaction_logic(): START\")\n\n # TODO: CREATE totally new logic how we deal with cancelations on and returns from the PP\n # To make sure we have not problem we should:\n # duplicate the SO (so it is without related tx) so we have a new one for later\n # - Create a new TX with the SO Number as the reference\n # - Update the Sale Order\n # - Add the newly created draft tx and the related acquirer (payment_acquirer_id, payment_tx_id)\n # - Set the sale order to state \"send\" (= No further changes possible except by an pp answer)\n # - Activate the duplicated SO in the current session so if there is a return from the pp without an pp answer\n # one could even change the SO and retry it again so he has a new SO and will generate a new TX if he submits\n # it again to the PP - which is ideal ;) - we could even store this in the session and delete the duplicate\n # if there are no changes compared to the original so in \"sent\" state in the form feedback when we process the\n # Answer from the pp\n\n # TODO: Use the same behaviour for the regular payment page!\n # (use opc_buttons and just one submit button and submit to /payment again - no java script needed!)\n # ATTENTION: Don't forget to change the original payment page template to use the special buttons and\n # only one submit button just like for any opc page - so it is more or less the same behaviour.\n # The only drawback is that also on the payment page it will submitt its data to itself instead\n # direclty submitting it to the pp BUT because of this we will get any additional from info\n # of non hidden fields like IBAN, BIC or not payment forms needed for fsotransfer\n\n # TODO: Remove the call to the original controller after the stuff from above is done!\n # ATTENTION: This call to the json controller may destroy the session: Carefully test this !!!\n # HINT: If there was no order or no order-line or no acquirer_id \"pt\" would be a redirect to \"/shop/checkout\"\n _logger.info(\"payment_transaction_logic(): call original payment_transaction()\")\n pt = super(website_sale_donate, self).payment_transaction(acquirer_id=int(acquirer_id))\n\n # TODO: 'return_url': '/shop/payment/validate', check if this prevents our custom return urls!\n return pt\n\n # /shop/payment/transaction/\n # Overwrite the Json controller for the pay now button\n @http.route()\n def payment_transaction(self, acquirer_id, **post):\n _logger.warning(\"payment_transaction(): START post data: \\n%s\\n\" % post or None)\n _logger.info(_('Call of json route /shop/payment/transaction/%s will start payment_transaction_logic()')\n % acquirer_id)\n # HINT: payment_transaction_logic() will only run the original payment_transaction().\n # This is only done so \"akward\" not to kill the session if the checkout page needs to call this logic\n # on the server instead of the browser of the user calling it. With this trick the call to\n # payment_transaction_logic() inside of checkout (see step 3) will not create a new session.\n pay_now_button_form = self.payment_transaction_logic(acquirer_id)\n return pay_now_button_form\n\n # Checkout Page\n @http.route()\n def checkout(self, one_page_checkout=False, **post):\n try:\n _logger.warning(\"checkout(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"checkout(): START\")\n\n cr, uid, context = request.cr, request.uid, request.context\n\n # Render the Checkout Page\n checkout_page = super(website_sale_donate, self).checkout(**post)\n if not hasattr(checkout_page, 'qcontext'):\n _logger.warning(\"checkout(): END, checkout_page has no qcontext. Most likely a redirection after error!\")\n return checkout_page\n\n # Add Information that the checkout page controller was called\n checkout_page.qcontext['checkout_controller_called'] = True\n\n # Add the acquirer id to the checkoutpage qcontext\n if post and post.get('acquirer'):\n checkout_page.qcontext.update({'acquirer_id': post.get('acquirer')})\n\n # -----------------------\n # NOT A ONE PAGE CHECKOUT\n # -----------------------\n if not (request.website['one_page_checkout'] or one_page_checkout):\n _logger.warning(\"checkout(): END\")\n return checkout_page\n\n # -----------------\n # ONE PAGE CHECKOUT\n # -----------------\n _logger.warning(\"checkout(): One-Page-Checkout is enabled and checkout_page is not just a redirection\")\n\n # Make sure one one_page_checkout is true and in the qcontext\n checkout_page.qcontext['one_page_checkout'] = True\n\n # Checkout-Page was called for the first time\n # -------------------------------------------\n if request.httprequest.method != 'POST':\n\n # FSO_forms Custom Checkout Fields: Run checkout_values again but with the product to get the correct fields\n product = post.get('product', None)\n opc_checkout_vals = self.checkout_values(product=product)\n checkout_page.qcontext.update(opc_checkout_vals)\n\n # Add Payment page qcontext\n payment_page = self.opc_payment()\n checkout_page.qcontext.update(payment_page.qcontext)\n _logger.warning(\"checkout(): END, GET request (without post data)\")\n return checkout_page\n\n # Checkout-Page was already called and now submits it's form data\n # ---------------------------------------------------------------\n if request.httprequest.method == 'POST':\n\n # STEP 1: UPDATE DELIVERY\n # HINT: self.payment(**post) will basically just call _check_carrier_quotation() ir a carrier_id is in post\n # and return a redirection to the payment page again.\n # ATTENTION: _check_carrier_quotation() was completely rewritten to avoid unnecessary writes to the SO!\n # ATTENTION: Input names are delivery_type which is normally remapped by java script to a call to\n # window.location.href = '/shop/payment?carrier_id=' + carrier_id;\n # TODO: Test if we should directly call _check_carrier_quotation() instead of self.payment(**post)\n _logger.warning(\"checkout(): OPC STEP 1: UPDATE DELIVERY\")\n carrier_id = post.get('delivery_type')\n if carrier_id:\n post['carrier_id'] = int(carrier_id)\n super(website_sale_donate, self).payment(**post)\n # ATTENTION: carrier_id must be removed or payment() will always return the redirection to /shop/payment\n post.pop('carrier_id')\n\n # STEP 2: CONFIRM ORDER\n # - Check if a sale order exists\n # - run checkout_redirection()\n # - run checkout_values()\n # - run checkout_form_validate()\n # - run checkout_form_save()\n # - run sale_get_order(update_pricelist=True)\n # HINT: Will not change the sale order state\n # HINT: Will return render(\"website_sale.checkout\", values) if any errors are found\n # Else it will return a redirection\n _logger.warning(\"checkout(): OPC STEP 2: RUN CONFIRM ORDER\")\n confirm_order = self.confirm_order(**post)\n\n # STEP 3: RUN THE ORIGINAL CHECKOUT CONTROLLER AGAIN TO HONOR POSSIBLE CHANGES BY DELIVERY\n # - run sale_get_order(force_create=1)\n # - run checkout_redirection()\n # - run checkout_values()\n # - render(\"website_sale.checkout\", values)\n _logger.warning(\"checkout(): OPC STEP 3: RUN THE ORIGINAL CHECKOUT CONTROLLER AGAIN\")\n checkout_page = super(website_sale_donate, self).checkout(**post)\n # ATTENTION: Always use one page checkout for the checkout_page\n checkout_page.qcontext['one_page_checkout'] = True\n # Add opc_warnings used in opc templates to display errors\n checkout_page.qcontext['opc_warnings'] = list()\n # Add errors from confirm_order if any\n # ATTENTION: If confirm_order has a qcontext it means checkout_form_validate() returned errors\n # ATTENTION: Errors in confirm_order may shadow errors in the checkoutpage therefore we add it to\n # opc_warnings before we add the qcontext to the checkoutpage\n if hasattr(confirm_order, 'qcontext'):\n checkout_page.qcontext['opc_warnings'].append(confirm_order.qcontext.get('errors', []))\n checkout_page.qcontext.update(confirm_order.qcontext)\n\n # STEP 4: RENDER THE PAYMENT BUTTONS (Forms)\n _logger.warning(\"checkout(): OPC STEP 4: RENDER THE PAYMENT BUTTONS (opc_payment())\")\n payment_page = self.opc_payment(**post)\n # ATTENTION: Errors in the payment page may shadow errors in the checkoutpage therefore we add it to\n # opc_warnings before we add the qcontext to the checkoutpage\n if payment_page.qcontext.get('errors'):\n checkout_page.qcontext['opc_warnings'].append(payment_page.qcontext.get('errors', []))\n # Add the payment page qcontext to the checkoutpage qcontext\n checkout_page.qcontext.update(payment_page.qcontext)\n\n # STEP 5: CHECK FOR ERRORS\n # HINT: We redirect so late to make sure qcontext of the payment page is already in the checkoutpage\n # because it is needed in OPC templates.\n # ATTENTION: If confirm_order has a qcontext it means checkout_form_validate() returned errors\n # ATTENTION: Errors in the qcontext for confirm order may shadow errors from the payment- and checkoutpage\n _logger.warning(\"checkout(): OPC STEP 5: CHECK FOR ERRORS\")\n if checkout_page.qcontext.get('error') or confirm_order.location != '/shop/payment':\n _logger.warning(\"checkout(): ERRORS FOUND RETURNING CHECKOUTPAGE\")\n return checkout_page\n\n _logger.warning(\"checkout(): SUCCESS! RETURNING CHECKOUTPAGE WITH 'acquirer_auto_submit' FOR PP REDIRECT!\")\n return checkout_page\n\n # One-Page-Checkout: Payment Page Redirection\n # HINT: Shopping Cart Redirection is done above around line 92\n @http.route()\n def payment(self, **post):\n try:\n _logger.warning(\"payment(): START %s\" % request.httprequest)\n except:\n _logger.warning(\"payment(): START\")\n\n # OPC enabled for the whole website = redirect to checkout page\n # HINT: If one_page_checkout is enabled globally for the webshop the payment page is not\n # used because the payment templates are displayed already on the checkout page (= shop OPC)\n if request.website['one_page_checkout']:\n _logger.warning(\"payment(): END, opc in session therefore redirect to /shop/checkout\")\n return request.redirect(\"/shop/checkout\")\n\n _logger.warning(\"payment(): END: RETURN self.opc_payment(**post)\")\n return self.opc_payment(**post)\n\n # Override of /shop/payment/validate\n # ATTENTION: All payment providers will redirect after its [name]_form_feedback() to /shop/payment/validate\n # HINT: Overwrite was necessary because of unwanted redirects e.g.: to /shop in orig. controller\n @http.route()\n def payment_validate(self, transaction_id=None, sale_order_id=None, **post):\n _logger.info('/shop/payment/validate: START for sale_order_id: %s, transaction_id: %s' % (sale_order_id, transaction_id))\n cr, uid, context = request.cr, request.uid, request.context\n sale_order_obj = request.registry['sale.order']\n\n # Redirect URL\n # TODO: check if last_shop_page and last_page is really a good idea or if /shop/confirmation_static is enough\n redirect_url_after_form_feedback = (request.registry.get('last_shop_page') or\n request.registry.get('last_page') or '/shop/confirmation_static')\n\n # Update redirect_url_after_form_feedback from global website setting\n if request.website and request.website.redirect_url_after_form_feedback:\n redirect_url_after_form_feedback = request.website.redirect_url_after_form_feedback\n\n # Find payment transaction (from current session)\n if transaction_id is None:\n tx = request.website.sale_get_transaction_include_cancelled()\n else:\n tx = request.registry['payment.transaction'].browse(cr, uid, transaction_id, context=context)\n\n if tx:\n _logger.info('/shop/payment/validate: tx.id: %s state: %s' % (tx.id, tx.state))\n else:\n _logger.info('/shop/payment/validate: tx was None')\n\n # Update redirect_url_after_form_feedback from payment provider if set\n if tx and tx.acquirer_id and tx.acquirer_id.redirect_url_after_form_feedback:\n # From Payment Provider\n redirect_url_after_form_feedback = tx.acquirer_id.redirect_url_after_form_feedback\n\n # Update redirect_url_after_form_feedback from sale-order-root_cat\n if tx and tx.sale_order_id \\\n and tx.sale_order_id.cat_root_id \\\n and tx.sale_order_id.cat_root_id.redirect_url_after_form_feedback:\n redirect_url_after_form_feedback = tx.sale_order_id.cat_root_id.redirect_url_after_form_feedback\n\n # Update redirect_url_after_form_feedback from the sale_order_line (by product)\n if tx and tx.sale_order_id and tx.sale_order_id.website_order_line:\n for line in tx.sale_order_id.website_order_line:\n if line.product_id and line.product_id.redirect_url_after_form_feedback:\n redirect_url_after_form_feedback = line.product_id.redirect_url_after_form_feedback\n\n # Find sale order (from current session)\n if sale_order_id is None:\n order = request.website.sale_get_order(context=context)\n else:\n order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, sale_order_id, context=context)\n assert order.id == request.session.get('sale_last_order_id')\n\n # EXIT if no sale order can be found\n if not order:\n _logger.error('/shop/payment/validate: No sale order found!')\n return request.redirect(redirect_url_after_form_feedback)\n\n # Confirm free sale orders or cancel sale_orders\n # HINT: No payment transaction BUT a sale order with 0 total amount\n if not order.amount_total and (not tx or tx and tx.state in ['pending', 'done']):\n # Orders are confirmed by payment transactions, but there is none for free orders,\n # (e.g. free events), so confirm immediately\n order.action_button_confirm()\n # TODO: Send e-mail like in addons-own/website_sale_donate/models/payment_transaction.py\n # HINT: This may be redundant because sale order will normally already cancelled in form_feedback()\n elif tx and tx.state == 'cancel' and order.state != 'cancel':\n sale_order_obj.action_cancel(cr, SUPERUSER_ID, [order.id], context=request.context)\n\n # CLEAN CURRENT SESSION\n _logger.info('/shop/payment/validate: Clean session data to start with an empty cart.')\n request.website.sale_reset(context=context)\n\n # Add sale.order order_id to the redirect_url_after_form_feedback for external thank-you-pages\n divider = '?' if '?' not in redirect_url_after_form_feedback else '&'\n redirect_url_after_form_feedback = redirect_url_after_form_feedback+divider+'order_id='+str(order.id)\n\n # Redirect\n _logger.info('/shop/payment/validate: redirect to redirect_url_after_form_feedback: %s'\n % redirect_url_after_form_feedback)\n return request.redirect(redirect_url_after_form_feedback)\n\n # Alternative confirmation page for Dadi Payment-Providers (Acquirers ogonedadi and frst for now)\n # HINT this rout is called by the payment_provider routes e.g.: ogonedadi_form_feedback or frst_form_feedback\n @http.route(['/shop/confirmation_static'], type='http', auth=\"public\", website=True)\n def payment_confirmation_static(self, order_id=None, **post):\n _logger.warning(\"payment_confirmation_static(): START\")\n if not order_id:\n _logger.error('payment_confirmation_static(): order_id missing!')\n cr, uid, context = request.cr, request.uid, request.context\n try:\n order_id = int(order_id)\n order = request.registry['sale.order'].browse(cr, SUPERUSER_ID, order_id, context=context)[0]\n if order and order.name and order.payment_tx_id:\n return request.website.render(\"website_sale_donate.confirmation_static\",\n {'order': order,\n 'confirmation_controller_called': True\n })\n else:\n _logger.error('payment_confirmation_static(): Sale Order or corresponding Payment Transaction missing!')\n raise ValueError\n except Exception as e:\n _logger.error('payment_confirmation_static(): EXCEPTION: %s' % repr(e))\n return request.website.render(\"website_sale_donate.confirmation_static\",\n {\n 'order': None,\n 'confirmation_controller_called': True\n })\n\n # For (small) cart JSON updates use arbitrary price (price_donate) if set sale.order.line\n @http.route()\n def get_unit_price(self, product_ids, add_qty, use_order_pricelist=False, **kw):\n product_prices = super(website_sale_donate,\n self).get_unit_price(product_ids, add_qty, use_order_pricelist, **kw)\n # Get current Sales Order Lines for arbitrary price\n order = request.website.sale_get_order()\n if order and order.order_line:\n order_line_prices = {line.product_id.id: line.price_donate\n for line in order.order_line\n if line.product_id.price_donate}\n product_prices.update(order_line_prices)\n # Cycle through products and return arbitrary price if set\n return product_prices\n\n # Extra Route for Sales Order Information\n @http.route('/shop/order/get_data/', type='json', auth=\"user\", website=True)\n def order_get_status(self, sale_order_id, **post):\n #cr, uid, context = request.cr, request.uid, request.context\n\n try:\n #order = request.env['sale.order'].sudo().search([('id', '=', sale_order_id)])\n order = request.env['sale.order'].search([('id', '=', sale_order_id)])\n assert order.ensure_one(), 'Multiple Sales Order Found!'\n except:\n order = False\n\n if not order:\n return {\n 'error': 'None or multiple Sale Order found for the given id: %s' % sale_order_id,\n }\n\n try:\n data = {\n 'id': order.id,\n 'name': order.name,\n 'state': order.state,\n 'amount_total': order.amount_total,\n 'order_lines': dict(),\n }\n if order.partner_id:\n data.update(partner_id={\n 'id': order.partner_id.id,\n 'name': order.partner_id.name,\n #\n 'firstname': order.partner_id.firstname if hasattr(order.partner_id, 'firstname') else '',\n 'lastname': order.partner_id.lastname if hasattr(order.partner_id, 'lastname') else '',\n 'donation_deduction_optout_web': order.partner_id.donation_deduction_optout_web if hasattr(\n order.partner_id, 'donation_deduction_optout_web') else '',\n 'gender': order.partner_id.gender if hasattr(order.partner_id, 'gender') else '',\n #\n 'company_name_web': order.partner_id.company_name_web,\n 'email': order.partner_id.email,\n 'newsletter_web': order.partner_id.newsletter_web,\n 'donation_receipt_web': order.partner_id.donation_receipt_web,\n 'opt_out': order.partner_id.opt_out,\n 'lang': order.partner_id.lang,\n })\n if order.partner_invoice_id:\n data.update(partner_invoice_id={\n 'id': order.partner_invoice_id.id,\n 'name': order.partner_invoice_id.name,\n #\n 'firstname': order.partner_invoice_id.firstname if hasattr(order.partner_invoice_id,\n 'firstname') else '',\n 'lastname': order.partner_invoice_id.lastname if hasattr(order.partner_invoice_id,\n 'lastname') else '',\n 'donation_deduction_optout_web': order.partner_invoice_id.donation_deduction_optout_web if hasattr(\n order.partner_invoice_id, 'donation_deduction_optout_web') else '',\n 'gender': order.partner_invoice_id.gender if hasattr(order.partner_invoice_id, 'gender') else '',\n #\n 'company_name_web': order.partner_invoice_id.company_name_web,\n 'email': order.partner_invoice_id.email,\n 'newsletter_web': order.partner_invoice_id.newsletter_web,\n 'donation_receipt_web': order.partner_invoice_id.donation_receipt_web,\n 'opt_out': order.partner_invoice_id.opt_out,\n 'lang': order.partner_invoice_id.lang,\n })\n if order.partner_shipping_id:\n data.update(partner_shipping_id={\n 'id': order.partner_shipping_id.id,\n 'name': order.partner_shipping_id.name,\n #\n 'firstname': order.partner_shipping_id.firstname if hasattr(order.partner_shipping_id,\n 'firstname') else '',\n 'lastname': order.partner_shipping_id.lastname if hasattr(order.partner_shipping_id,\n 'lastname') else '',\n 'donation_deduction_optout_web': order.partner_invoice_id.donation_deduction_optout_web if hasattr(\n order.partner_shipping_id, 'donation_deduction_optout_web') else '',\n 'gender': order.partner_shipping_id.gender if hasattr(order.partner_shipping_id, 'gender') else '',\n #\n 'company_name_web': order.partner_shipping_id.company_name_web,\n 'email': order.partner_shipping_id.email,\n 'newsletter_web': order.partner_shipping_id.newsletter_web,\n 'donation_receipt_web': order.partner_shipping_id.donation_receipt_web,\n 'opt_out': order.partner_shipping_id.opt_out,\n 'lang': order.partner_shipping_id.lang,\n })\n for line in order.order_line:\n data['order_lines']['line_'+str(line.id)] = {\n 'id': line.id,\n 'name': line.name,\n 'price_subtotal': line.price_subtotal,\n 'price_unit': line.price_unit,\n 'price_donate': line.price_donate,\n 'product_id': line.product_id.id,\n 'product_name': line.product_id.name,\n 'cat_root_id': line.cat_root_id.id if line.cat_root_id else 'None',\n 'cat_root_id_name': line.cat_root_id.name if line.cat_root_id else 'None',\n 'cat_id': line.cat_id.id if line.cat_id else 'None',\n 'cat_id_name': line.cat_id.name if line.cat_id else 'None',\n }\n return data\n except:\n return {\n 'error': 'Could not get Data for Sale-Order %s. Maybe you have the wrong user rights?' % sale_order_id,\n }\n\n @http.route(['/shop/confirm_order'], type='http', auth=\"public\", website=True)\n def confirm_order(self, **post):\n # CHECK FOR HONEY POT FIELD\n if self.tapped_into_honeypot(post):\n return None\n\n res = super(website_sale_donate, self).confirm_order(**post)\n return res\n\n def tapped_into_honeypot(self, data):\n if data.get(\"hpf-1\", \"\") != \"\":\n _logger.warning(\"Honey pot: Cancelling /shop/confirm_order because a honey pot field had a value.\")\n return True\n\n return False\n","sub_path":"addons-own/website_sale_donate/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":84000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"375842742","text":"from threading import Thread, Condition\nfrom random import choice\nfrom time import sleep\n\nbuffer = 5\nmutex = Condition()\n\ndef adicionar(buff):\n mutex.acquire()\n while len(buff) >= buffer:\n mutex.wait()\n buff.append(10)\n print(\"Produced X\", len(buff))\n sleep(1)\n mutex.notifyAll()\n mutex.release()\n\ndef remover(buff):\n mutex.acquire()\n while len(buff) <= 0:\n mutex.wait()\n buff.pop()\n print(\"Consumed X\", len(buff))\n sleep(1)\n mutex.notifyAll()\n mutex.release()\n\nthreads = []\nbuff = []\n\nwhile (True):\n if choice([1,2]) == 1:\n threads.append(Thread(target=adicionar, args=[buff]))\n else:\n threads.append(Thread(target=remover, args=[buff]))\n sleep(1) #tempo para criar uma thread\n threads[-1].start()\n","sub_path":"Atividades SO/SO.py","file_name":"SO.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"513877524","text":"import tensorflow as tf\nimport numpy as np\n\n# 构造一元二次方程的函数:测试TensorFlow\n# 运行有问题\n\n# 1. 数据生成:以[x,y]作为特征,此外还有xx, yy, xy, sin(x), sin(y)等\n# 300个点,等差分布在-1和1之间,并转化为300x1的二维数组\nx_data = np.linspace(-1, 1, 300)[:, np.newaxis]\n\n# 加入噪声点,方差为0.05的正态分布\nnoise = np.random.normal(0, 0.05, x_data.shape)\n\n# y = x^2 - 0.5\ny_data = np.square(x_data) - 0.5 + noise\n\n# 创建图? 定义x和y的占位符,作为输入神经网络的变量\n# placeholder临时替代任意操作的张量(即数据),在调用Session对象的run()方法时使用填充数据作为调用的参数, [None,1]为shape,表明为“none x 1”数组?\n'''\nxs = tf.placeholder(tf.float32, [None,1])\nys = tf.placeholder(tf.float32, [None,1])\n'''\nxs = x_data\nys = y_data\n\n# 2. 构建网络模型\n\n# 定义隐藏层和输出层: 输入数据,输入数据的维度,输出数据的维度和激活函数,每一层经过向量化y=weights*x = biases的处理,经过激活函数的非线性化处理后,得到最终输出结果\ndef add_layer(inputs, in_size, out_size, activation_function = None):\n # 构建权重:隐藏层之间(或隐藏层与输出层)的连接线表示权重,连接线的粗细与深浅表示权重的绝对值大小\n weights = tf.Variable(tf.random_normal([in_size, out_size]))\n # 构建偏置:\n biases = tf.Variable(tf.zeros(1, out_size) + 0.1)\n # 矩阵相乘:matmul为矩阵操作运算\n Wx_plus_b = tf.matmul(inputs, weights) + biases\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\n\n# 构建隐藏层:隐藏层有20个神经单元\n# relu为激活函数,运行时激活神经网络中某一部分神经元,将激活信息向后传入下一层神经网络,定义为f(x) = max(x,0), 加入非线性因素,弥补线性模型的表达力。\n# 常见的激活函数有sigmoid, tanh, relu,softplus这4种\nh1 = add_layer(xs, 1, 20, activation_function = tf.nn.relu)\n\n# 构建输出层:输出有1个神经元\nprediction = add_layer(h1, 20, 1, activation_function = None)\n\n# 构建损失函数:对预测值和真实值差的平方求和再取平均\nloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices = [1]))\n\n# 运用剃度下降法,以0.1的学习速率最小化损失\ntrain_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\n# 3. 训练模型\n\n# 训练1000次, 每50次输出损失值\ninit = tf.global_variables_initializer()\n\n# 创建会话\nsess = tf.Session()\n\nsess.run(init)\n\nfor i in range(1000):\n sess.run(train_step, feed_dict={xs: x_data, ys: y_data})\n if i % 50 == 0:\n print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))\n","sub_path":"QuadraticDemo.py","file_name":"QuadraticDemo.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440558738","text":"import cv2\nimport numpy as np\n\n\ndef dominant_color_in_square(img, x, y, r):\n # Making r smaller to ignore white part of image\n r -= 40\n\n x1 = int(x - r / 2)\n x2 = int(x + r / 2)\n y1 = int(y - r / 2)\n y2 = int(y + r / 2)\n\n frame = img[y1:y2, x1:x2]\n\n vectorized = frame.reshape((-1, 3))\n vectorized = np.float32(vectorized)\n\n n_colors = 5\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)\n flags = cv2.KMEANS_RANDOM_CENTERS\n\n _, labels, palette = cv2.kmeans(vectorized, n_colors, None, criteria, 10, flags)\n _, counts = np.unique(labels, return_counts=True)\n\n # cv2.imshow(str(palette[np.argmax(counts)]) + \"::size:\" + str(r), cv2.resize(frame, (300, 300)))\n\n return palette[np.argmax(counts)]\n\n\ndef color_in_range(color, condition, margin):\n return (condition[0] - margin < color[0]) & (color[0] < condition[0] + margin) & \\\n (condition[1] - margin < color[1]) & (color[1] < condition[1] + margin) & \\\n (condition[2] - margin < color[2]) & (color[2] < condition[2] + margin)\n\n\ndef get_frame_from_image(img, x, y, r):\n d = int(r / 2)\n x1 = int(x - d)\n x2 = int(x + d)\n y1 = int(y - d)\n y2 = int(y + d)\n\n return img[y1:y2, x1:x2]\n\n\ndef replace_part_img_with_frame(img, frame, x, y, r):\n d = int(r / 2)\n x1 = int(x - d)\n x2 = int(x + d)\n y1 = int(y - d)\n y2 = int(y + d)\n\n img[y1:y2, x1:x2] = frame\n\n\ndef find_and_draw_contour(img, x, y, r, color):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray_frame = get_frame_from_image(gray, x, y, r)\n frame = get_frame_from_image(img, x, y, r)\n\n contours, _ = cv2.findContours(gray_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # draw contours over original image\n cv2.drawContours(frame, contours, -1, color, 5)\n\n replace_part_img_with_frame(img, frame, x, y, r)\n\n return img\n","sub_path":"op4/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263644427","text":"\"\"\"\r\n\n\nThis challenge concerns strings such as:\n\n \"repeatedrepeatedrepeated\"\n\n... that are obtained by repeating a smaller string, which in this case is the\nstring `\"repeated\"`.\n\nOn a related note, since the string above is made of 3 repetitions, one way to\nproduce this string is via the code `3 * \"repeated\"`.\n\nWrite a function that, given a string, either:\n\n * Returns `False` if the string isn't made by repeating a smaller string or ...\n * Returns **the number of repetitions** if the string repeats a smaller string.\n\n### Examples\n\n is_repeated(\"repeatedrepeatedrepeated\") ➞ 3\n \n is_repeated(\"overintellectualizations\") ➞ False\n \n is_repeated(\"nononononononononononono\") ➞ 12\n \n is_repeated(\"moremoremoremoremoremore\") ➞ 6\n \n is_repeated(\",,,,,,,,,,,,,,,,,,,,,,,,\") ➞ 24\n\n### Notes\n\nTo keep things a little simpler, all strings in the tests will have length\nexactly 24, just as in all the examples above. In particular, the answers will\nalways be divisors of 24.\n\n\"\"\"\r\n\ndef is_repeated(strn):\n if strn[0] == strn[1]:\n return 24\n if strn[0] == strn[2]:\n return 12\n if strn[0] == strn[3]:\n return 8\n if strn[0] == strn[4]:\n return 6\n if strn[0] == strn[6]:\n return 4\n if strn[0] == strn[8]:\n return 3\n if strn[0] == strn[12]:\n return 2\n return False\n\n","sub_path":"6rztMMwkt6ijzqcF6_20.py","file_name":"6rztMMwkt6ijzqcF6_20.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"115224622","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\ndef count_words(filename):\n \"\"\"计算一个文件大致包含多少个单词\"\"\"\n\n try:\n with open(filename) as file_object:\n contents = file_object.read()\n except FileNotFoundError:\n print(\"The file does not exist.\")\n else:\n # 文件已读取数据,开始统计\n words = contents.split()\n num_words = len(words)\n print(\"The file \" + filename + \" has about \" + str(num_words) + \" words.\")\n\n\nif __name__ == '__main__':\n count_words('guest_inputed.txt')","sub_path":"pythonlearning/practice_book/chapter10/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"70024612","text":"#-*- coding: UTF-8 -*- \nimport os, datetime, bson.objectid\nfrom flask import Blueprint, request, redirect, render_template, url_for, flash\nfrom flask.views import MethodView\nfrom wtforms import Form, TextField, validators, SelectField, TextAreaField, BooleanField\nfrom flask.ext.principal import Principal, Permission, RoleNeed\n\nfrom app.db_query import query_server, query_script, query_idc, query_module\nfrom app.models import db\nfrom app import app\n\nmyscript = Blueprint('script', __name__, template_folder='templates')\nWTF_CSRF_SECRET_KEY = 'QPo3QVT0UyBrPmoqhf'\n\nclass userForm(Form):\n user_name = TextField(u'脚本名称', [validators.Required(), validators.Length(min=4, max=25)])\n user_email = TextField(u'脚本参数')\n user_telphone = TextAreaField(u'脚本内容')\n user_passwd = TextAreaField(u'脚本内容')\n\nclass script(MethodView):\n def get(self):\n db_script = db.Script.find()\n #app.logger.warning('A warning occurred (%d apples)', 42)\n return render_template('script/index.html', title=(u'脚本管理'), scripts=list(db_script))\n\nclass script_add(MethodView):\n def get(self):\n form = ScriptForm(request.form)\n return render_template('script/add.html', title=(u'脚本管理'), form=form)\n\n def post(self):\n form = ScriptForm(request.form)\n if form.validate():\n db_script = db.Script.find({\"script_name\": form.script_name.data})\n if not db_script.count():\n db_script = db.Script()\n db_script[\"script_name\"] = form.script_name.data\n db_script[\"script_argument\"] = form.script_argument.data\n db_script[\"script_content\"] = form.script_content.data.replace(\"\\r\", \"\")\n db_script[\"script_type\"] = form.script_type.data\n db_script[\"desc\"] = form.desc.data\n db_script[\"creation\"] = datetime.datetime.now()\n db_script[\"modify\"] = datetime.datetime.now()\n\n #write script file\n with open((\"script/\" + db_script[\"script_name\"]), 'wb') as f:\n f.write(db_script[\"script_content\"]) \n db_script.save()\n flash(db_script[\"script_name\"] + (u'添加成功!'))\n else:\n flash(form.script_name.data + (u'重复!'))\n else:\n flash(u\"添加脚本错误,请检查相关字段!\")\n return render_template('script/add.html', title=(u'脚本管理'), form=form)\n\nclass script_edit(MethodView):\n def get(self, slug):\n form = ScriptForm(request.form)\n db_script = db.Script.find({\"_id\": bson.objectid.ObjectId(slug)})\n if db_script.count():\n form.script_name.data = db_script[0][\"script_name\"]\n form.script_argument.data = db_script[0][\"script_argument\"]\n form.script_content.data = db_script[0][\"script_content\"]\n form.script_type.data = db_script[0][\"script_type\"]\n form.desc.data = db_script[0][\"desc\"]\n else:\n flash(u'您编辑的脚本不存在!')\n return render_template('script/edit.html', title=(u'脚本管理'), slug=slug, form=form)\n\n def post(self, slug):\n form = ScriptForm(request.form)\n if form.validate() :\n db_script = db.Script()\n db_script[\"script_name\"] = form.script_name.data\n db_script[\"script_argument\"] = form.script_argument.data\n db_script[\"script_content\"] = form.script_content.data.replace(\"\\r\", \"\")\n db_script[\"script_type\"] = form.script_type.data\n db_script[\"desc\"] = form.desc.data\n db_script[\"modify\"] = datetime.datetime.now()\n\n #write script file\n with open((\"script/\" + db_script[\"script_name\"]), 'wb') as f:\n f.write(db_script[\"script_content\"])\n db.Script.find_and_modify({\"_id\": bson.objectid.ObjectId(slug)}, {'$set': db_script})\n #app.logger.warning(dir(db_script.update.__doc__))\n #db_script.update({'$set': {\"_id\": bson.objectid.ObjectId(slug)}})\n flash(form.script_name.data + (u'更新成功!'))\n else:\n flash(u\"更新脚本错误,请检查相关字段!\")\n return redirect(url_for('script.script_edit', slug=slug))\n\nclass script_del(MethodView):\n def get(self, slug):\n db_script = db.Script.find({\"_id\": bson.objectid.ObjectId(slug)})\n script_name = db_script[0][\"script_name\"]\n if db_script.count():\n db.script.remove({\"_id\": bson.objectid.ObjectId(slug)})\n flash(u'删除脚本' + script_name + u'成功!')\n else:\n flash(u'您要删除的脚本' + script_name + u'不存在!')\n return redirect(url_for('script.script'))\n\n# Register the urls\nmyscript.add_url_rule('/script/', view_func=script.as_view('script'))\nmyscript.add_url_rule('/script/add', view_func=script_add.as_view('script_add'))\nmyscript.add_url_rule('/script/edit_', view_func=script_edit.as_view('script_edit'))\nmyscript.add_url_rule('/script/del_', view_func=script_del.as_view('script_del'))\n","sub_path":"app/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"344274707","text":"\"\"\"\nMaximum Consecutive Gap\n=======================\n\nGiven an unsorted array, find the maximum difference between the successive elements in its sorted form.\n\nTry to solve it in linear time/space.\n\nExample :\n\n Input : [1, 10, 5]\n Output : 5 \n\n\nSolution\n--------\n\nThe constraints of the problem can be met with sorting an array with radix sort, but there exists more elegant solution.\n\n1. Find min and max of an array\n2. If we divide segment [min; max] in N+1 equal parts:\nd = (max-min)/(N+1), [min+i*d; min+d*(i+1)] for i in 0..N,\nthen according to the Dirichlet's principle at least on of the inner segments\nwould contain no point from the array. Therefore maximum gap can not be shorter than d.\nThus difference between two points from the same segment the can not be the greatest.\nIt can happen only between points from different segments.\n\nConsecutive gaps are formed between max elem of the segment and min elem of the next nonempty segment.\n\nIf we keep arrays of segment mins and maxs we solve the problem in linear time, linear space.\n\"\"\"\n\nfrom __future__ import print_function\n\n\ndef max_gap(arr):\n n = len(arr)\n if n == 1:\n return 0\n arr_min = min(arr)\n arr_max = max(arr)\n d = (arr_max - arr_min)/(n+1.)\n\n # arr_max+1, arr_min-1 are used for empty buckets\n # We could use None or MAX_INT, MIN_INT instead\n mins = [arr_max+1]*(n+1)\n maxs = [arr_min-1]*(n+1)\n\n for el in arr:\n index = int((el-arr_min)/d)\n # max elem goes into last bucket\n if el == arr_max:\n index = n\n mins[index] = min(mins[index], el)\n maxs[index] = max(maxs[index], el)\n\n # skip empty segments\n mins = [m for m in mins if m != arr_max+1]\n maxs = [m for m in maxs if m != arr_min-1]\n\n gap = 0\n for i in range(len(mins)-1):\n gap = max(gap, mins[i+1] - maxs[i])\n\n return gap\n\n\nprint(max_gap([1, 10, 5, 7, 4]))\n","sub_path":"InterviewBit/Arrays/MaximumConsecutiveGap.py","file_name":"MaximumConsecutiveGap.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"562306019","text":"from entity import CONSTANT\nimport pandas as pd\n\n\nclass CapFlow:\n\n def __init__(self, ori_df):\n self.df = ori_df\n\n @staticmethod\n def get_ori_df(first_index, holding=0, holding_value=0, total_cost_once=0, total_cost_borrow=0, riskfee=0,\n cash=CONSTANT.ORI_CAP_VALUE, capital_value=CONSTANT.ORI_CAP_VALUE, rreturn=0):\n data = {'datetime': [first_index],\n 'action': [CONSTANT.TRANS_HOLD],\n 'holding': [holding],\n 'holding_value': [holding_value],\n 'total_cost_once': [total_cost_once],\n 'total_cost_borrow': [total_cost_borrow],\n 'riskfee': [riskfee],\n 'realized_profit': [0],\n 'cash': [cash],\n 'capital_value': [capital_value],\n 'rreturn': [rreturn]}\n ori_df = pd.DataFrame(data)\n return ori_df\n\n def insert(self, datetime, row, dsl, tran=None):\n action = CONSTANT.TRANS_HOLD if tran is None else tran['type'][0]\n holding = self.get_last_value('holding') if tran is None else tran['cur'][0]\n holding_value = holding * row['low'] * CONSTANT.DEPOSIT\n total_cost_once = self.get_last_value('total_cost_once') + (0 if tran is None else tran['cost_once'][0])\n total_cost_borrow = self.get_last_value('total_cost_borrow') + dsl.df['cost_borrow'].sum()\n riskfee = self.get_last_value('riskfee') + self.get_last_value('cash') * CONSTANT.RF_RATE\n realized_profit = self.get_last_value('realized_profit') + (0 if tran is None else tran['realized_profit'][0])\n cash = CONSTANT.ORI_CAP_VALUE + riskfee + realized_profit - total_cost_borrow - total_cost_once\n capital_value = holding_value + cash\n rreturn = (capital_value - CONSTANT.ORI_CAP_VALUE) / CONSTANT.ORI_CAP_VALUE\n\n data = {'datetime': [datetime],\n 'action': [action],\n 'holding': [holding],\n 'holding_value': [holding_value],\n 'total_cost_once': [total_cost_once],\n 'total_cost_borrow': [total_cost_borrow],\n 'riskfee': [riskfee],\n 'realized_profit': [realized_profit],\n 'cash': [cash],\n 'capital_value': [capital_value],\n 'rreturn': [rreturn]}\n\n data_df = pd.DataFrame(data)\n self.df = self.df.append(data_df, ignore_index=True)\n\n return rreturn\n\n def get_last_value(self, col_name, default_value=0):\n value = default_value if self.df.shape[0] == 0 else self.df[col_name][self.df.shape[0] - 1]\n return value\n","sub_path":"capflow/CapFlow.py","file_name":"CapFlow.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"535038871","text":"from cdiagrams.protocol2 import Protocol2\n\nprotocol = Protocol2(1200, 170)\nparties = []\nparties.append(\"Prover knows a secret s such that h1=g1^s % p and h2=g2^s % p, \\n and wants to prove that he knows dlog of h1 and h2,\\n and that it is the same. \\n At the beginning \\n he chooses random r from Z_q\")\nparties.append(\"Verifier \\n at the end verifies \\n that g1^y = g1^r * (g1^s)^c % p and g2^y = g2^r * (g2^s)^c % p\")\n\nconnections = []\nconnections.append(\"g1^r % p, g2^r % p\")\nconnections.append(\"random c\")\nconnections.append(\"y = (r + s*c) % q\")\n\nprotocol.draw_protocol(parties, connections, box_height=100)\nprotocol.save(\"../img/dlog_equality.png\")\n\n\n\n\n\n","sub_path":"test1/dlog_equality.py","file_name":"dlog_equality.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"479744064","text":"import numpy as np\n\ndef normalize_features(X, mean_vector=None, std_vector=None):\n \"\"\"\n :param X : two-dimensional array of our dataset, with shape NxD. N is the number of rows (each row is a sample) and D is the number of columns\n :param mean_vector : optionally given, precomputed vector of mean values.\n :param std_vector : optionally given, precomputed vector of standard deviation values.\n \n If the function is called passing *only X* as input argument, then the mean and std values will be computed from X, and then X will be normalized using these values.\n If the function is called passing *all three* input arguments, X array will be normalized using the precomputed mean and std values that were passed as input arguments.\n \n Normalization is performed by subtracting the mean and dividing by the standard deviation: x_normalized = (x - x_mean)/(x_std+ε)\n \"\"\"\n \n if (mean_vector is None) and (std_vector is None):\n return_mean_std = True\n # get the mean for every column\n mean_vector = np.mean(X, axis=0)\n # get the std for every column\n std_vector = np.std(X, axis=0)\n \n # insert extra singleton dimension, to obtain 1xD shape\n mean_vector = np.expand_dims(mean_vector, axis=0)\n std_vector = np.expand_dims(std_vector, axis=0)\n else:\n return_mean_std = False\n \n # get the number of samples in the dataset\n N = X.shape[0]\n \n # repeat N times across first dimension, to obtain NxD shape\n repeated_mean = np.repeat(mean_vector, N, axis=0)\n repeated_std = np.repeat(std_vector, N, axis=0)\n \n #if np.sum(1.0*(repeated_std==0))>0:\n if np.any(repeated_std==0):\n print('Adding epsilon to avoid division by zero during normalization')\n repeated_std += np.finfo(float).eps\n # subtract column mean and divide each element by column standard deviation\n X_normalized = (X - repeated_mean) / repeated_std\n print('Dataset normalization complete.')\n \n if return_mean_std==True:\n return X_normalized, mean_vector, std_vector\n else:\n return X_normalized\n \n \n","sub_path":"assgn_1_part_2/2_neural_network/normalize_features.py","file_name":"normalize_features.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"361389710","text":"import unittest \nfrom appium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport time, random, string, csv, logging, logging.config\nfrom time import sleep\n\nCON_LOG = '../config/log.conf'\nlogging.config.fileConfig(CON_LOG)\nlogging = logging.getLogger()\n\nclass TestAccountEdit(unittest.TestCase):\n def setUp(self):\n desired_caps={}\n desired_caps['platformName'] = 'ios'\n desired_caps['deviceName'] = 'iPhone X'\n desired_caps['platformVersion'] = '12.0'\n desired_caps['bundleID'] = 'com.castlery.dev'\n desired_caps['app'] = '/Users/alex/Documents/Castlery_ios_test.app'\n desired_caps['launchTimeout'] = '30000'\n desired_caps['autoAcceptAlerts'] = 'True'\n desired_caps['noReset'] = 'False'\n desired_caps['unicodekeyboard'] = 'True'\n desired_caps['resetkeyboard'] = 'True'\n self.driver = webdriver.Remote('http://127.0.0.1:1086/wd/hub', desired_caps)\n self.driver.implicitly_wait(18)\n\n def test_account_edit(self):\n driver = self.driver\n driver.find_element_by_name(\"Account\").click()\n sleep(2)\n driver.find_element_by_name(\"Login\").click()\n sleep(5)\n driver.find_element_by_xpath(\"//XCUIElementTypeTextField\").send_keys(\"alex.ac@qq.com\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath(\"//XCUIElementTypeSecureTextField\").send_keys(\"7787782\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"Login\"]').click()\n sleep(3)\n driver.find_element_by_name(\"Account\").click()\n sleep(2)\n driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"Edit\"]').click()\n sleep(3)\n\n logging.info(\"Start account_edit test_Case1: check page title Edit Profile\")\n try:\n title_edit = driver.find_element_by_xpath('//XCUIElementTypeOther[@name=\"Edit Profile\"]').text\n self.assertEqual(title_edit, \"Edit Profile\")\n logging.debug(\"title is correct, test_case1 passed\")\n except AssertionError as e:\n logging.warning(\"title wrong! test_case1 failed\")\n logging.info(\"test_case1 finished\")\n sleep(3)\n #\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').send_keys(\"ios\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').send_keys(\"test\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').send_keys(\"test_ios@qq.com\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_accessibility_id(\"Save\").click()\n sleep(3)\n\n logging.info(\"Start account_edit test_case2: edit_email must be not exist in kinght\")\n alert_msg = driver.find_element_by_xpath('(//XCUIElementTypeStaticText)[4]').text\n alert_text = \"Validation failed: Email has already been taken\"\n try:\n self.assertEqual(alert_msg, alert_text)\n logging.debug(\"get correct alert message, test_case2 passed\")\n except AssertionError as e:\n logging.warning(\"alert message wrong!, test_case2 failed\")\n logging.info(\"test_case2 finished\")\n sleep(3) \n driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"OK\"]').click()\n sleep(1)\n #\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').send_keys(\"alex\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').send_keys(\"xia\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').send_keys(\"alex_ac@163com\")\n sleep(1)\n driver.hide_keyboard()\n sleep(2)\n #driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"Toolbar Done Button\"]').click()\n sleep(1)\n driver.find_element_by_accessibility_id(\"Save\").click()\n sleep(30)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[1]').send_keys(\"test\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[2]').send_keys(\"ios\")\n sleep(1)\n driver.hide_keyboard()\n sleep(1)\n\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').clear()\n sleep(1)\n driver.find_element_by_xpath('(//XCUIElementTypeTextField)[3]').send_keys(\"alex_ac@163com\")\n sleep(1)\n driver.hide_keyboard()\n sleep(2)\n #driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"Toolbar Done Button\"]').click()\n sleep(1)\n driver.find_element_by_accessibility_id(\"Save\").click()\n sleep(30)\n\n logging.info(\"Start account_edit test_case3: get success message\")\n saved_msg = driver.find_element_by_xpath('(//XCUIElementTypeStaticText)[4]').text\n saved_text = \"Changes Saved!\"\n try:\n self.assertEqual(saved_msg, saved_text)\n logging.debug(\"get correct success save message, test_Case3 passed\")\n except AssertionError as e:\n logging.warning(\"saved message wrong! test_case3 failed\")\n logging.info(\"test_case3 finished\")\n sleep(1)\n driver.find_element_by_xpath('//XCUIElementTypeButton[@name=\"OK\"]').click()\n sleep(1)\n\n\n logging.info(\"Start account_edit test_case7: last name should be changed to test\")\n last_name_changed = driver.find_element_by_xpath('(//XCUIElementTypeStaticText)[1]').text\n last_name_text = \"Test\"\n try:\n self.assertEqual(last_name_changed, last_name_text)\n logging.debug(\"last name has been changed, test_case7 passed\")\n except AssertionError as e:\n logging.warning(\"last name wrong! test_case7 failed\")\n logging.info(\"test_case7 finished\")\n sleep(3)\n\n logging.info(\"Start account_edit test_case8: email has been changed to alex_ac@163.com\")\n changed_email = driver.find_element_by_xpath('(//XCUIElementTypeStaticText)[2]').text\n email_text = \"alex_ac@163.com\"\n try:\n self.assertEqual(changed_email, email_text)\n logging.debug(\"email has been changed, test_case8 passed\")\n except AssertionError as e:\n logging.warning(\"email wrong! test_case8 failed\")\n logging.info(\"test_case8 finished\")\n \n def tearDown(self):\n self.driver.close_app()\n self.driver.quit()\nif __name__ == '__main__':\n unittest.main()\n \n","sub_path":"appium_ios/test_case/temp_account_edit.py","file_name":"temp_account_edit.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"226776690","text":"import cnn_model\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport shutil\nimport tensorflow as tf\n\nfrom sklearn import metrics\n\nlearn = tf.contrib.learn\n\nREMOVE_PREVIOUS_MODEL = True\n\nMODEL_OUTPUT_DIR = './model/'\nDATA_SET_FILE = './labeled_news.csv'\nVARS_FILE = './vars'\nVOCAB_PROCESSOR_SAVE_FILE = './vocab_procesor_save_file'\nMAX_DOCUMENT_LENGTH = 100\nN_CLASSES = 8\n\nSTEPS = 200\n\ndef main(unused_argv):\n if REMOVE_PREVIOUS_MODEL:\n print(\"Delete old models...\")\n shutil.rmtree(MODEL_OUTPUT_DIR)\n os.mkdir(MODEL_OUTPUT_DIR)\n\n # Load data\n df = pd.read_csv(DATA_SET_FILE, header=None)\n train_df = df[0:400]\n test_df = df.drop(train_df.index)\n\n # x is feature 'title', Y is class\n x_train = train_df[1]\n Y_train = train_df[0]\n x_test = test_df[1]\n Y_test = test_df[0]\n\n # Process the document with VocabularyProcessoro\n vocab_processor = learn.preprocessing.VocabularyProcessor(MAX_DOCUMENT_LENGTH)\n x_train = np.array(list(vocab_processor.fit_transform(x_train)))\n x_test = np.array(list(vocab_processor.transform(x_test)))\n\n n_words = len(vocab_processor.vocabulary_)\n print('Total words after VocabularyProcessor: %d' % n_words)\n\n with open(VARS_FILE, 'wb') as f:\n pickle.dump(n_words, f)\n\n vocab_processor.save(VOCAB_PROCESSOR_SAVE_FILE)\n\n # Initialize new Moodel!\n classifier = learn.Estimator(\n model_fn=cnn_model.generate_cnn_model(N_CLASSES, n_words),\n model_dir=MODEL_OUTPUT_DIR)\n\n # Fit\n classifier.fit(x_train, Y_train, steps=STEPS)\n\n # Evaluate \n Y_predicted = [\n p['class'] for p in classifier.predict(x_test, as_iterable=True)\n ]\n\n score = metrics.accuracy_score(Y_test, Y_predicted)\n print('Accuracy is: {0:f}'.format(score))\n\nif __name__ == '__main__':\n tf.app.run(main=main)","sub_path":"news-modeling-and-training/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"441889447","text":"from Lab_4 import mnist\nimport numpy as np\n\n\ndef load(data_set):\n if data_set == \"mnist\":\n x_train, y_train, x_test, y_test = mnist.load()\n return x_train, y_train, x_test, y_test\n\n elif data_set == \"gamma_ray\":\n x = []\n y = []\n infile = open(\"magic04.txt\", \"r\")\n for line in infile:\n y.append(int(line[-2:-1] == 'g'))\n x.append(np.fromstring(line[:-2], dtype=float, sep=','))\n infile.close()\n\n xa = np.zeros((len(x), len(x[0])))\n for i in range(len(xa)):\n xa[i] = x[i]\n x = xa\n\n x = np.array(x).astype(np.float32)\n y = np.array(y)\n\n # Split data into training and testing\n ind = np.random.permutation(len(y))\n split_ind = int(len(y) * 0.8)\n x_train = x[ind[:split_ind]]\n x_test = x[ind[split_ind:]]\n y_train = y[ind[:split_ind]]\n y_test = y[ind[split_ind:]]\n\n return x_train, y_train, x_test, y_test\n\n elif data_set == \"solar\":\n x_train = np.load('x_ray_data_train.npy')\n y_train = np.load('x_ray_target_train.npy')\n x_test = np.load('x_ray_data_test.npy')\n y_test = np.load('x_ray_target_test.npy')\n\n return x_train, y_train, x_test, y_test","sub_path":"Lab_4/data_set.py","file_name":"data_set.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"416918657","text":"from room import Room\nfrom player import Player\nfrom world import World\n\nimport random\nfrom ast import literal_eval\n\n# Load world\nworld = World()\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph = literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n# Create new player to start world\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n\n\n# helper function to reverse movement of each direction\ndef convert_direction(direction):\n if direction == \"n\":\n return \"s\"\n if direction == \"s\":\n return \"n\"\n if direction == \"w\":\n return \"e\"\n if direction == \"e\":\n return \"w\"\n\n\n# helper function to retrieve the number of unexplored exits for a room\ndef get_number_of_unexplored_paths(room):\n rooms_left = 0\n\n for direction in room:\n if room[direction] == \"?\":\n rooms_left += 1\n\n return rooms_left\n\n\n# helper function to build initial visited dict entry. Ex ouput -> visited[room_id] = { \"n\": ?, \"s\": ?, \"e\": ?, \"w\": ? }\ndef build_initial_dict_entry_value(visited, room):\n exits = room.get_exits()\n\n visited[room.id] = {}\n\n for move in exits:\n visited[room.id][move] = \"?\"\n\n\n# Main function to traverse maze -> output is an array containing the final directions to traverse maze\ndef get_traversal_directions(maze):\n final_directions = []\n reverse_directions = []\n new_player = Player(maze.starting_room)\n visited = {}\n # Create an entry for the starting room in the visited dict\n build_initial_dict_entry_value(visited, new_player.current_room)\n # Loop will run until all rooms have been visited\n while len(visited) < len(room_graph):\n # Loop thru available exits in current room\n for move in new_player.current_room.get_exits():\n # If exit is unexplored\n if visited[new_player.current_room.id][move] == \"?\":\n # Store current room id to fill in visited[next_room_id] = { reverse_of_move : prev_room_id }\n prev_room_id = new_player.current_room.id\n # Store the opposite of each movement in reverse_directions array to simplify backtracking\n backtrack_move = convert_direction(move)\n # Move player\n new_player.travel(move)\n # Append the opposite of the move to reverse_directions arr\n final_directions.append(move)\n # Append the actual move into the final_directions arr\n reverse_directions.append(convert_direction(move))\n # Replace the question mark at visited[prev_room_id] = { move: new_room_id }\n visited[prev_room_id][move] = new_player.current_room.id\n # Check if the new room has been visited already\n if new_player.current_room.id not in visited:\n # If not, create an entry for it in the visited dict and then break out of loop\n build_initial_dict_entry_value(\n visited, new_player.current_room)\n visited[new_player.current_room.id][backtrack_move] = prev_room_id\n break\n\n # If there are no unexplored exits in the current room, it's time to backtrack to a room with unexplored exits\n if get_number_of_unexplored_paths(visited[new_player.current_room.id]) == 0 and len(visited) < len(room_graph):\n # Last element of backtrack_array will be next move\n backtrack_move = reverse_directions.pop()\n # Move player back to the previous room\n new_player.travel(backtrack_move)\n # Append the backtrack move to the final_directions arr\n final_directions.append(backtrack_move)\n # Return final directions array\n return final_directions\n\n\n# traversal_path = ['n', 'n']\ntraversal_path = get_traversal_directions(world)\n\n\n# TRAVERSAL TEST\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room)\n\nif len(visited_rooms) == len(room_graph):\n print(\n f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms\")\n\n\n#######\n# UNCOMMENT TO WALK AROUND\n#######\n# player.current_room.print_room_description(player)\n# while True:\n# cmds = input(\"-> \").lower().split(\" \")\n# if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n# player.travel(cmds[0], True)\n# elif cmds[0] == \"q\":\n# break\n# else:\n# print(\"I did not understand that command.\")\n","sub_path":"lecture-notes/adv-solutions/adv_solution1.py","file_name":"adv_solution1.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"64241995","text":"#!/usr/local/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n@author: \n@file: 343. 整数拆分.py\n@time: 2020/7/30 09:51\n@desc: \n\"\"\"\nfrom typing import List\n\"\"\"\n给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。\n\n示例 1:\n\n输入: 2\n输出: 1\n解释: 2 = 1 + 1, 1 × 1 = 1。\n示例 2:\n\n输入: 10\n输出: 36\n解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。\n说明: 你可以假设 n 不小于 2 且不大于 58。\n\"\"\"\n\nclass Solution:\n def integerBreak(self, n: int) -> int:\n # if n == 2:\n # return 1\n # elif n == 3:\n # return 2\n # elif n == 4:\n # return 4\n # elif n == 5:\n # return 6\n # ans = 1\n # while n > 4:\n # ans *= 3\n # n -= 3\n # ans *= n\n # return ans\n # dp = [1, 1, 1, 2, 4, 6, 9]\n # if n <= 6:\n # return dp[n]\n # for i in range(7, n + 1):\n # dp.append(dp[i - 3] * 3)\n # return dp[-1]\n\n dp = [1, 1, 2, 4]\n if n <= 4:\n return dp[n-1]\n ans = 1\n while n > 4:\n ans *= 3\n n -= 3\n ans *= n\n return ans\n\na = Solution().integerBreak(10)\nprint(a)\n\n\n","sub_path":"A daily topic/2020/July/30_343. 整数拆分.py","file_name":"30_343. 整数拆分.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"136984669","text":"import tkinter as tk\nfrom tkinter import *\n\n\n\n\nclass ParentWindow(Frame):\n def __init__(self, master, *args, **kwargs):\n Frame.__init__(self, master, *args, **kwargs)\n\n self.master = master\n self.master.minsize(530,190)\n self.master.maxsize(530,190)\n self.master.title(\"Check files\")\n self.master.configure(bg='#F0F0F0')\n\n # Frame.grid_rowconfigure((0,1,2), weight=1)\n # Frame.grid_columnconfigure((0,1,2,3), weight=1)\n\n self.btnBrowse1 = Button(self.master, text='Browse...', width=12)\n self.btnBrowse1.grid(row=0, column=0, padx=(20, 20), pady=(50, 15), sticky=W) # ipadx=(19),\n self.txtBrowse1 = Entry(self.master, text='', width=60)\n self.txtBrowse1.grid(row=0, column=1, columnspan=3, padx=(15, 15), pady=(50, 15), sticky=N+E+W)\n\n self.btnBrowse2 = Button(self.master, text='Browse...', width=12)\n self.btnBrowse2.grid(row=1, column=0, padx=(20, 20), pady=(0, 15), sticky=W) # ipadx=(19),\n self.txtBrowse1 = Entry(self.master, text='', width=60)\n self.txtBrowse1.grid(row=1, column=1, columnspan=3, padx=(15, 15), pady=(0, 15), sticky=N+E+W)\n\n self.btnCheck = Button(self.master, text='Check for files...', width=12)\n self.btnCheck.grid(row=2, column=0, padx=(20, 20), ipady=(8), pady=(0, 15), sticky=W)\n\n self.btnClose = Button(self.master, text='Close Program', width=12)\n self.btnClose.grid(row=2, column=3, ipady=(8), padx=(0,15), pady=(0, 15), sticky=E)\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n App = ParentWindow(root)\n root.mainloop()","sub_path":"inputGUI/inputGUI_main.py","file_name":"inputGUI_main.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"328322220","text":"from flask import flash\n\n__all__ = ['FlaskInform', 'Attention']\n\nclass Attention:\n danger = 'danger'\n success = 'success'\n warning = 'warning'\n\nclass FlaskInformMeta(type):\n def __new__(cls, name, bases, attrs):\n attrs['message'] = attrs['m'] = attrs['__annotations__']['m']\n attrs['l'] = attrs['__annotations__'].get('l', Attention.danger)\n attrs['d'] = attrs['__annotations__'].get('d', ': ')\n del attrs['__annotations__']\n return super().__new__(cls, name, bases, attrs)\n\nclass FlaskInform(Exception, metaclass=FlaskInformMeta):\n \"\"\"Subclass this class and define:\n m: message,\n l: level (optional, default = 'danger'),\n d: delimiter (optional, default = ': '),\n \"\"\"\n\n m: ''\n\n def __str__(self):\n return self.message\n\n def __repr__(self):\n return f'{self.__class__.__name__}()'\n\n @classmethod\n def flash(cls, suppl=None):\n if suppl:\n flash(f'{cls.m}{cls.d}{suppl}', cls.l)\n else:\n flash(cls.m, cls.l)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"36092771","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 27 13:07:43 2020\n\n@author: RaizQuadrada\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n\n# Importing the datasets\ndataset_angola = pd.read_csv('WPOV-AGO_SI_POV_NOP5.csv')\ndataset_brazil = pd.read_csv('WPOV-BRA_SI_POV_NOP5.csv')\ndataset_china = pd.read_csv('WPOV-CHN_SI_POV_NOP5.csv')\ndataset_mexico = pd.read_csv('WPOV-MEX_SI_POV_NOP5.csv')\ndataset_usa = pd.read_csv('WPOV-USA_SI_POV_NOP5.csv')\n\n# Separating the dependent and independent variables\n# Angola\nX_a = dataset_angola.iloc[:, 0].values\ny_ang = dataset_angola.iloc[:, 1].values\n\n# Brazil\nX_b = dataset_brazil.iloc[:, 0].values\ny_bra = dataset_brazil.iloc[:, 1].values\n\n# China\nX_c = dataset_china.iloc[:, 0].values\ny_chi = dataset_china.iloc[:, 1].values\n\n# Mexico\nX_m = dataset_mexico.iloc[:, 0].values\ny_mex = dataset_mexico.iloc[:, 1].values\n\n# United States of America\nX_u = dataset_usa.iloc[:, 0].values\ny_usa = dataset_usa.iloc[:, 1].values\n\n# Cleaning the date (collecting only the year)\nX_ang = [int(i[:4]) for i in X_a]\nX_bra = [int(i[:4]) for i in X_b]\nX_chi = [int(i[:4]) for i in X_c]\nX_mex = [int(i[:4]) for i in X_m]\nX_usa = [int(i[:4]) for i in X_u]\n\n# Coverting the year list into an array\nX_ang = np.array(X_ang)\nX_bra = np.array(X_bra)\nX_chi = np.array(X_chi)\nX_mex = np.array(X_mex)\nX_usa = np.array(X_usa)\n\n# Reshaping the data (dependent variable)\nX_ang = X_ang.reshape(-1, 1)\nX_bra = X_bra.reshape(-1, 1)\nX_chi = X_chi.reshape(-1, 1)\nX_mex = X_mex.reshape(-1, 1)\nX_usa = X_usa.reshape(-1, 1)\n\n# Reshaping the data (independent variable)\ny_ang = y_ang.reshape(-1, 1)\ny_bra = y_bra.reshape(-1, 1)\ny_chi = y_chi.reshape(-1, 1)\ny_mex = y_mex.reshape(-1, 1)\ny_usa = y_usa.reshape(-1, 1)\n\n# Changing the order of the data in the matrix of features (from oldest to newest)\nX_ang = np.flip(X_ang)\nX_bra = np.flip(X_bra)\nX_chi = np.flip(X_chi)\nX_mex = np.flip(X_mex)\nX_usa = np.flip(X_usa)\n\n# Changing the order of the data in the dependent vector variable (from oldest to newest)\ny_ang = np.flip(y_ang)\ny_bra = np.flip(y_bra)\ny_chi = np.flip(y_chi)\ny_mex = np.flip(y_mex)\ny_usa = np.flip(y_usa)\n\n# Creating the simple linear models\nang_regressor = LinearRegression()\nbra_regressor = LinearRegression()\nchi_regressor = LinearRegression()\nmex_regressor = LinearRegression()\nusa_regressor = LinearRegression()\n\n# Training the models\nang_regressor.fit(X_ang, y_ang)\nbra_regressor.fit(X_bra, y_bra)\nchi_regressor.fit(X_chi, y_chi)\nmex_regressor.fit(X_mex, y_mex)\nusa_regressor.fit(X_usa, y_usa)\n\n# Comparing the model with the real data\nplt.scatter(X_ang, y_ang, color = 'blue')\nplt.plot(X_ang, y_ang, color = 'purple', label = 'Real data')\nplt.plot(X_ang, ang_regressor.predict(X_ang), color = 'black', label = 'Linear model')\nplt.title('US$5 earning in Angola')\nplt.xlabel('Year')\nplt.ylabel('Millions of people')\nplt.legend()\nplt.show()\n\nplt.scatter(X_bra, y_bra, color = 'blue')\nplt.plot(X_bra, y_bra, color = 'purple', label = 'Real data')\nplt.plot(X_bra, bra_regressor.predict(X_bra), color = 'black', label = 'Linear model')\nplt.title('US$5 earning in Brazil')\nplt.xlabel('Year')\nplt.ylabel('Millions of people')\nplt.legend()\nplt.show()\n\nplt.scatter(X_chi, y_chi, color = 'blue')\nplt.plot(X_chi, y_chi, color = 'purple', label = 'Real data')\nplt.plot(X_chi, chi_regressor.predict(X_chi), color = 'black', label = 'Linear model')\nplt.title('US$5 earning in China')\nplt.xlabel('Year')\nplt.ylabel('Millions of people')\nplt.legend()\nplt.show()\n\nplt.scatter(X_mex, y_mex, color = 'blue')\nplt.plot(X_mex, y_mex, color = 'purple', label = 'Real data')\nplt.plot(X_mex, mex_regressor.predict(X_mex), color = 'black', label = 'Linear model')\nplt.title('US$5 earning in Mexico')\nplt.xlabel('Year')\nplt.ylabel('Millions of people')\nplt.legend()\nplt.show()\n\nplt.scatter(X_usa, y_usa, color = 'blue')\nplt.plot(X_usa, y_usa, color = 'purple', label = 'Real data')\nplt.plot(X_usa, usa_regressor.predict(X_usa), color = 'black', label = 'Linear model')\nplt.title('US$5 earning in USA')\nplt.xlabel('Year')\nplt.ylabel('Millions of people')\nplt.legend()\nplt.show()\n\n# Conclusion: if a linear model doesn't fit the data pretty well\n# it can be very useful to show the tendency of it because\n# this model is simple and, therefore, requires relatively\n# few computational power to be trained.\n","sub_path":"linear_models/global_poverty/global_poverty_model.py","file_name":"global_poverty_model.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"150233720","text":"from python2latex import TexFile, TexEnvironment, TexCommand, build\nfrom python2latex.utils import open_file_with_default_program\n\n\nclass Document(TexEnvironment):\n \"\"\"\n Tex document class.\n Has a body, a preamble and a dict of packages updated recursively with other TexEnvironment nested inside the body.\n The 'build' method writes all text to a .tex file and compiles it to pdf.\n \"\"\"\n def __init__(self, filename, filepath='.', doc_type='article', options=(), **kwoptions):\n r\"\"\"\n Args:\n filename (str): Name of the file without extension.\n filepath (str): Path where the files will be saved and compiled to pdf.\n doc_type (str): Any document type LaTeX supports, like 'article', 'standalone', etc.\n options (Union[Tuple[str], str, TexObject]): Any options that goes between brackets. See template further.\n kwoptions (keyword options of the document type): Options should be strings. The dict is converted to string\n when building to tex. See template below.\n\n The doc_type, options and kwoptions arguments will be compiled in the following way:\n \\documentclass[*options, **kwoptions]{doc_type}\n \"\"\"\n super().__init__('document')\n self.filename = filename\n self.filepath = filepath\n self.file = TexFile(filename, filepath)\n\n self.doc_class = TexCommand('documentclass',\n doc_type,\n options=options,\n options_pos='first',\n **kwoptions)\n\n self.add_package('inputenc', 'utf8')\n self.set_margins('2.5cm')\n\n def __repr__(self):\n return f'Document {self.filename}'\n\n def set_margins(self, margins='2.5cm', top=None, bottom=None, left=None, right=None):\n \"\"\"\n Sets margins of the document. Default is 2.5cm on all sides.\n\n Args:\n margins (str): Default value for all sides.\n top, bottom, left, right (str, any valid LaTeX length): Overrides the 'margins' argument with the specified\n length.\n \"\"\"\n top = top or margins\n bottom = bottom or margins\n left = left or margins\n right = right or margins\n\n self.add_package('geometry', top=top, bottom=bottom, left=left, right=right)\n\n def new_section(self, name, label=''):\n \"\"\"\n Create a new LaTeX section.\n\n Args:\n name (str): Name of the section.\n label (str): Label of the section to refer to.\n \"\"\"\n return self.new(Section(name, label=label))\n\n def build(self, save_to_disk=True, compile_to_pdf=True, show_pdf=True):\n \"\"\"\n Builds the document to a tex file and optionally compiles it into tex and show the output pdf in the default\n pdf reader of the system.\n\n Args:\n save_to_disk (bool): If True, the built tex will be save to disk automatically. Else, one can recover the\n tex string from the return of the current method.\n compile_to_pdf (bool): If True, automatically call pdflatex to compile the generated tex file to pdf.\n show_pdf (bool): If True, the default pdf reader will be called to show the compiled pdf. This may not work\n well with non-read-only pdf viewer such as Acrobat Reader or Foxit Reader.\n\n Returns:\n The tex string of the file.\n \"\"\"\n tex = super().build()\n\n tex = build(self.doc_class) + '\\n' + self.build_preamble() + '\\n' + tex\n if save_to_disk:\n self.file.save(tex)\n\n if compile_to_pdf:\n self.file.save(tex)\n self.file.compile_to_pdf()\n\n if show_pdf:\n open_file_with_default_program(self.filename, self.filepath)\n\n return tex\n\n\nclass Section(TexEnvironment):\n \"\"\"\n Implements a LaTeX section.\n \"\"\"\n def __init__(self, name, label=''):\n \"\"\"\n Args:\n name (str): Name of the section.\n label (str): Label of the section to refer to.\n \"\"\"\n super().__init__('section', name, label=label)\n\n def new_subsection(self, name, label=''):\n \"\"\"\n Args:\n name (str): Name of the subsection.\n label (str): Label of the subsection to refer to.\n \"\"\"\n return self.new(Subsection(name, label=label))\n\n\nclass Subsection(TexEnvironment):\n \"\"\"\n Implements a LaTeX subsection.\n \"\"\"\n def __init__(self, name, label=''):\n \"\"\"\n Args:\n name (str): Name of the subsection.\n label (str): Label of the subsection to refer to.\n \"\"\"\n super().__init__('subsection', name, label=label)\n\n def new_subsubsection(self, name, label=''):\n \"\"\"\n Args:\n name (str): Name of the subsubsection.\n label (str): Label of the subsubsection to refer to.\n \"\"\"\n return self.new(TexEnvironment('subsubsection', name, label=label))\n","sub_path":"python2latex/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":5058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"502215106","text":"from datetime import datetime\nfrom dateutil import parser\nfrom dateutil import tz\nfrom os import listdir, makedirs, path\nfrom flask import Blueprint, abort, jsonify, request, send_file\nfrom flask.ext.login import login_required\nfrom werkzeug import secure_filename\n\nfrom .. import app, db\nfrom ..user.model import User\nfrom .model import Activity, Weight\n\napi = Blueprint('api', __name__, url_prefix='/api')\n\n#@app.before_request\n#def log():\n# app.logger.debug(request.headers)\n# app.logger.debug(request.form)\n# app.logger.debug(request.files)\n\n@api.route('/upload', methods=['POST'])\ndef upload():\n # Check Authorization\n auth = request.authorization\n user = User.authorize(auth.username, auth.password) if auth else None\n if user is None:\n abort(401)\n # Save the file; process the file\n file = request.files['file']\n if file:\n timestamp = parser.parse(request.values['datetime'])\n filename = secure_filename(file.filename)\n dir = app.config['UPLOAD_FOLDER']\n if not path.exists(dir):\n makedirs(dir)\n filepath = path.join(dir, filename)\n file.save(filepath)\n activity = Activity(timestamp, filepath)\n db.session.add(activity)\n db.session.commit()\n return ''\n\n@api.route('/weight', methods=['POST'])\ndef add_weight():\n timestamp = request.form.get('datetime')\n if timestamp:\n timestamp = parser.parse(timestamp)\n else:\n timestamp = datetime.now()\n if timestamp.tzinfo is None:\n timestamp = timestamp.replace(tzinfo=tz.tzlocal())\n qty = request.form['qty']\n unit = request.form.get('unit') or 'lb'\n weight = Weight(timestamp, qty, unit)\n db.session.add(weight)\n db.session.commit()\n return ''\n \n@api.route('/weight', methods=['GET'])\n@login_required\ndef get_weight():\n start = request.args.get('start')\n if start is not None:\n start = parser.parse(request.args.get('start'))\n if start.tzinfo is None:\n start = start.replace(tzinfo=tz.tzlocal())\n \n end = request.args.get('end')\n if end is not None:\n end = parser.parse(request.args.get('end'))\n if end.tzinfo is None:\n end = end.replace(tzinfo=tz.tzlocal())\n \n return jsonify(weight=[i.serialize for i in Weight.find(start, end)])\n \n@api.route('/query')\n@login_required\ndef query():\n # todo: none handling\n start = parser.parse(request.args.get('start'))\n end = parser.parse(request.args.get('end'))\n if start.tzinfo is None:\n start = start.replace(tzinfo=tz.tzlocal())\n if end.tzinfo is None:\n end = end.replace(tzinfo=tz.tzlocal())\n return jsonify(activities=[i.serialize for i in Activity.find(start, end)])\n '''\n dir = app.config['UPLOAD_FOLDER']\n files = [ f for f in listdir(dir) if path.isfile(path.join(dir,f)) ]\n return jsonify({'car' : files})\n '''\n \n# http://stackoverflow.com/questions/13706382/how-to-get-static-files-in-flask-without-url-forstatic-file-name-xxx\n@api.route('/img/')\n@login_required\ndef img(filename):\n if '..' in filename or '/' in filename:\n abort(404)\n dir = app.config['UPLOAD_FOLDER']\n return send_file('../' + dir + '/' + filename, mimetype=\"image/png\")\n\n","sub_path":"flask/tracking/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"204607240","text":"# each day you either make or serve food\n# you need 8 making and 10 serving per day\n\n\ndays = {'Saturday':([],[]), 'Sunday':([],[]), 'Monday':([],[])}\n\n\n# I assume day is a string\n# Session is an integer {0,1}\n# Session 0 is afternoon, Session 1 is Evening\ndef is_full(day, session):\n if session == 0:\n if len(days[day][session]) >= 8:\n return True\n else:\n if len(days[day][session]) >= 10:\n return True\n return False\n\n\ndef add_to_roster(name, day, session):\n days[day][session].append(name)\n print(days)\n\n\n# add line where it tells user about alternatives\ndef check_input(name, day, session):\n if not is_full(day, session):\n if day not in ['Monday', 'Sunday', 'Saturday']:\n print(\"invalid day!\")\n else:\n add_to_roster(name, day, session)\n else:\n print(\"session \" + str(session) + \" on \" + day + \" is full!\")\n \ndef take_input():\n\n while(1):\n name = input(\"Who?\")\n day = input(\"What day?\")\n session = int(input(\"Which session? (0 for afternoon, 1 for evening, 2 for both)\"))\n #session = set_session(session)\n\n if session == 1 or session == 0:\n check_input(name, day, session) \n elif session == 2:\n check_input(name, day, 0)\n check_input(name, day, 1)\n \n\n\ndef add_a_man():\n man=1\n\ndef load_days():\n a = 1\n\ndef main():\n load_days()\n\nmain()\n","sub_path":"roster.py","file_name":"roster.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125721021","text":"#!/usr/bin/env python3\n\nimport logging\nimport re\nimport os\nimport math\n\nimport yaml\nfrom telegram import ReplyKeyboardMarkup\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n ConversationHandler,\n MessageHandler,\n Filters,\n)\n\nfrom definitions import CONFIG_PATH, LANG_PATH, CHATID_PATH, ADMIN_PATH\nimport radarr as radarr\nimport sonarr as sonarr\nimport logger\n\n__version__ = \"0.3\"\n\nconfig = yaml.safe_load(open(CONFIG_PATH, encoding=\"utf8\"))\n\n# Set up logging\nlogLevel = logging.DEBUG if config.get(\"debugLogging\", False) else logging.INFO\nlogger = logger.getLogger(\"addarr\", logLevel, config.get(\"logToConsole\", False))\nlogger.debug(f\"Addarr v{__version__} starting up...\")\n\nSERIE_MOVIE_AUTHENTICATED, READ_CHOICE, GIVE_OPTION, GIVE_PATHS, TSL_NORMAL = range(5)\n\nupdater = Updater(config[\"telegram\"][\"token\"], use_context=True)\ndispatcher = updater.dispatcher\nlang = config[\"language\"]\n\ntranscript = yaml.safe_load(open(LANG_PATH, encoding=\"utf8\"))\ntranscript = transcript[lang]\n\n\ndef main():\n auth_handler_command = CommandHandler(config[\"entrypointAuth\"], authentication)\n auth_handler_text = MessageHandler(\n Filters.regex(\n re.compile(r\"\" + config[\"entrypointAuth\"] + \"\", re.IGNORECASE)\n ),\n authentication,\n )\n allSeries_handler_command = CommandHandler(config[\"entrypointAllSeries\"], allSeries)\n allSeries_handler_text = MessageHandler(\n Filters.regex(\n re.compile(r\"\" + config[\"entrypointAllSeries\"] + \"\", re.IGNORECASE)\n ),\n allSeries,\n )\n addMovieserie_handler = ConversationHandler(\n entry_points=[\n CommandHandler(config[\"entrypointAdd\"], startSerieMovie),\n CommandHandler(transcript[\"Movie\"], startSerieMovie),\n CommandHandler(transcript[\"Serie\"], startSerieMovie),\n MessageHandler(\n Filters.regex(\n re.compile(r\"\" + config[\"entrypointAdd\"] + \"\", re.IGNORECASE)\n ),\n startSerieMovie,\n ),\n ],\n states={\n SERIE_MOVIE_AUTHENTICATED: [MessageHandler(Filters.text, choiceSerieMovie)],\n READ_CHOICE: [\n MessageHandler(\n Filters.regex(f'^({transcript[\"Movie\"]}|{transcript[\"Serie\"]})$'),\n searchSerieMovie,\n )\n ],\n GIVE_OPTION: [\n MessageHandler(Filters.regex(f'({transcript[\"Add\"]})'), pathSerieMovie),\n MessageHandler(\n Filters.regex(f'({transcript[\"Next result\"]})'), nextOption\n ),\n MessageHandler(\n Filters.regex(f'({transcript[\"New\"]})'), startSerieMovie\n ),\n ],\n GIVE_PATHS: [\n MessageHandler(\n Filters.regex(re.compile(r\"^(Path: )(.*)$\", re.IGNORECASE)),\n addSerieMovie,\n ),\n ],\n },\n fallbacks=[\n CommandHandler(\"stop\", stop),\n MessageHandler(Filters.regex(\"^(Stop|stop)$\"), stop),\n ],\n )\n changeTransmissionSpeed_handler = ConversationHandler(\n entry_points=[\n CommandHandler(config[\"entrypointTransmission\"], transmission),\n MessageHandler(\n Filters.regex(\n re.compile(\n r\"\" + config[\"entrypointTransmission\"] + \"\", re.IGNORECASE\n )\n ),\n transmission,\n ),\n ],\n states={TSL_NORMAL: [MessageHandler(Filters.text, changeSpeedTransmission)]},\n fallbacks=[\n CommandHandler(\"stop\", stop),\n MessageHandler(Filters.regex(\"^(Stop|stop)$\"), stop),\n ],\n )\n\n dispatcher.add_handler(auth_handler_command)\n dispatcher.add_handler(auth_handler_text)\n dispatcher.add_handler(allSeries_handler_command)\n dispatcher.add_handler(allSeries_handler_text)\n dispatcher.add_handler(addMovieserie_handler)\n dispatcher.add_handler(changeTransmissionSpeed_handler)\n\n logger.info(transcript[\"Start chatting\"])\n updater.start_polling()\n updater.idle()\n\n\n# Check if Id is authenticated\ndef checkId(update):\n authorize = False\n with open(CHATID_PATH, \"r\") as file:\n firstChar = file.read(1)\n if not firstChar:\n return False\n file.close()\n with open(CHATID_PATH, \"r\") as file:\n for line in file:\n if line.strip(\"\\n\") == str(update.effective_message.chat_id):\n authorize = True\n file.close()\n if authorize:\n return True\n else:\n return False\n\n\n# Check if user is an admin\ndef checkAdmin(update):\n admin = False\n user = update.message.from_user\n with open(ADMIN_PATH, \"r\") as file:\n for line in file:\n if line.strip(\"\\n\") == str(user[\"username\"]) or line.strip(\"\\n\") == str(\n user[\"id\"]\n ):\n admin = True\n file.close()\n if admin:\n return True\n else:\n return False\n\n\ndef transmission(\n update, context,\n):\n if config[\"transmission\"][\"enable\"]:\n if checkId(update):\n if checkAdmin(update):\n reply_keyboard = [\n [\n transcript[\"Transmission\"][\"TSL\"],\n transcript[\"Transmission\"][\"Normal\"],\n ]\n ]\n markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n update.message.reply_text(\n transcript[\"Transmission\"][\"Speed\"], reply_markup=markup\n )\n return TSL_NORMAL\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"NotAdmin\"],\n )\n return TSL_NORMAL\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"Authorize\"]\n )\n return TSL_NORMAL\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Transmission\"][\"NotEnabled\"],\n )\n return ConversationHandler.END\n\n\ndef changeSpeedTransmission(update, context):\n if not checkId(update):\n if (\n authentication(update, context) == \"added\"\n ): # To also stop the beginning command\n return ConversationHandler.END\n else:\n choice = update.message.text\n if choice == transcript[\"Transmission\"][\"TSL\"]:\n if config[\"transmission\"][\"authentication\"]:\n auth = (\n \" --auth \"\n + config[\"transmission\"][\"username\"]\n + \":\"\n + config[\"transmission\"][\"password\"]\n )\n os.system(\n \"transmission-remote \"\n + config[\"transmission\"][\"host\"]\n + auth\n + \" --alt-speed\"\n )\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Transmission\"][\"ChangedToTSL\"],\n )\n return ConversationHandler.END\n\n elif choice == transcript[\"Transmission\"][\"Normal\"]:\n if config[\"transmission\"][\"authentication\"]:\n auth = (\n \" --auth \"\n + config[\"transmission\"][\"username\"]\n + \":\"\n + config[\"transmission\"][\"password\"]\n )\n os.system(\n \"transmission-remote \"\n + config[\"transmission\"][\"host\"]\n + auth\n + \" --no-alt-speed\"\n )\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Transmission\"][\"ChangedToNormal\"],\n )\n return ConversationHandler.END\n\n\ndef authentication(update, context):\n chatid = update.effective_message.chat_id\n with open(CHATID_PATH, \"r\") as file:\n if(str(chatid) in file.read()):\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Chatid already allowed\"],\n ) \n file.close()\n else:\n file.close()\n password = update.message.text\n if(\"/auth\" in password):\n password = password.replace(\"/auth \", \"\")\n if password == config[\"telegram\"][\"password\"]:\n with open(CHATID_PATH, \"a\") as file:\n file.write(str(chatid) + \"\\n\")\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Chatid added\"],\n )\n file.close()\n return \"added\"\n else:\n logger.warning(\n f\"Failed authentication attempt by [{update.message.from_user.username}]. Password entered: [{password}]\"\n )\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"Wrong password\"]\n )\n return ConversationHandler.END # This only stops the auth conv, so it goes back to choosing screen\n \n\n\ndef stop(update, context):\n clearUserData(context)\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"End\"]\n )\n return ConversationHandler.END\n\n\ndef startSerieMovie(update, context):\n if checkId(update):\n if update.message.text[1:].lower() in [\n transcript[\"Serie\"].lower(),\n transcript[\"Movie\"].lower(),\n ]:\n logger.debug(\n f\"User issued {update.message.text} command, so setting user_data[choice] accordingly\"\n )\n context.user_data.update(\n {\n \"choice\": transcript[\"Serie\"]\n if update.message.text[1:].lower() == transcript[\"Serie\"].lower()\n else transcript[\"Movie\"]\n }\n )\n elif update.message.text.lower() == transcript[\"New\"].lower():\n logger.debug(\"User issued New command, so clearing user_data\")\n clearUserData(context)\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"Title\"]\n )\n return SERIE_MOVIE_AUTHENTICATED\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"Authorize\"]\n )\n return SERIE_MOVIE_AUTHENTICATED\n\n\ndef choiceSerieMovie(update, context):\n if not checkId(update):\n if (\n authentication(update, context) == \"added\"\n ): # To also stop the beginning command\n return ConversationHandler.END\n else:\n text = update.message.text\n if text[1:].lower() not in [\n transcript[\"Serie\"].lower(),\n transcript[\"Movie\"].lower(),\n ]:\n context.user_data[\"title\"] = text\n if context.user_data.get(\"choice\") in [\n transcript[\"Serie\"],\n transcript[\"Movie\"],\n ]:\n logger.debug(\n f\"user_data[choice] is {context.user_data['choice']}, skipping step of selecting movie/series\"\n )\n return searchSerieMovie(update, context)\n else:\n reply_keyboard = [[transcript[\"Movie\"], transcript[\"Serie\"]]]\n markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n update.message.reply_text(transcript[\"What is this?\"], reply_markup=markup)\n return READ_CHOICE\n\n\ndef searchSerieMovie(update, context):\n title = context.user_data[\"title\"]\n if context.user_data.get(\"title\"):\n context.user_data.pop(\"title\")\n if not context.user_data.get(\"choice\"):\n choice = update.message.text\n context.user_data[\"choice\"] = choice\n else:\n choice = context.user_data[\"choice\"]\n context.user_data[\"position\"] = 0\n\n service = getService(context)\n\n position = context.user_data[\"position\"]\n\n searchResult = service.search(title)\n if searchResult:\n context.user_data[\"output\"] = service.giveTitles(searchResult)\n\n reply_keyboard = [\n [transcript[choice.lower()][\"Add\"], transcript[\"Next result\"]],\n [transcript[\"New\"], transcript[\"Stop\"]],\n ]\n markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[choice.lower()][\"This\"],\n )\n context.bot.sendPhoto(\n chat_id=update.effective_message.chat_id,\n photo=context.user_data[\"output\"][position][\"poster\"],\n )\n text = f\"{context.user_data['output'][position]['title']} ({context.user_data['output'][position]['year']})\"\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=text, reply_markup=markup\n )\n return GIVE_OPTION\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=transcript[\"No results\"],\n )\n clearUserData(context)\n return ConversationHandler.END\n\n\ndef nextOption(update, context):\n position = context.user_data[\"position\"] + 1\n context.user_data[\"position\"] = position\n\n choice = context.user_data[\"choice\"]\n\n if position < len(context.user_data[\"output\"]):\n reply_keyboard = [\n [transcript[choice.lower()][\"Add\"], transcript[\"Next result\"]],\n [transcript[\"New\"], transcript[\"Stop\"]],\n ]\n markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[choice.lower()][\"This\"],\n )\n context.bot.sendPhoto(\n chat_id=update.effective_message.chat_id,\n photo=context.user_data[\"output\"][position][\"poster\"],\n )\n text = (\n context.user_data[\"output\"][position][\"title\"]\n + \" (\"\n + str(context.user_data[\"output\"][position][\"year\"])\n + \")\"\n )\n context.bot.send_message(\n chat_id=update.effective_message.chat_id, text=text, reply_markup=markup\n )\n return GIVE_OPTION\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Last result\"],\n reply_markup=markup,\n )\n clearUserData(context)\n return ConversationHandler.END\n\n\ndef pathSerieMovie(update, context):\n service = getService(context)\n paths = service.getRootFolders()\n context.user_data.update({\"paths\": [p[\"path\"] for p in paths]})\n if len(paths) == 1:\n # There is only 1 path, so use it!\n logger.debug(\"Only found 1 path, so proceeding with that one...\")\n context.user_data[\"path\"] = paths[0][\"path\"]\n return addSerieMovie(update, context)\n formattedPaths = [f\"Path: {p['path']}\" for p in paths]\n\n if len(paths) % 2 > 0:\n oddItem = formattedPaths.pop(-1)\n reply_keyboard = [\n [formattedPaths[i], formattedPaths[i + 1]]\n for i in range(0, len(formattedPaths), 2)\n ]\n if len(paths) % 2 > 0:\n reply_keyboard.append([oddItem])\n markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[\"Select a path\"],\n reply_markup=markup,\n )\n return GIVE_PATHS\n\n\ndef addSerieMovie(update, context):\n position = context.user_data[\"position\"]\n choice = context.user_data[\"choice\"]\n idnumber = context.user_data[\"output\"][position][\"id\"]\n\n if not context.user_data.get(\"path\"):\n # Path selection should be in the update message\n if update.message.text.replace(\"Path: \", \"\").strip() in context.user_data.get(\n \"paths\", {}\n ):\n context.user_data[\"path\"] = update.message.text.replace(\n \"Path: \", \"\"\n ).strip()\n else:\n logger.debug(\n f\"Message text [{update.message.text.replace('Path: ', '').strip()}] doesn't match any of the paths. Sending paths for selection...\"\n )\n return pathSerieMovie(update, context)\n\n path = context.user_data[\"path\"]\n service = getService(context)\n\n if not service.inLibrary(idnumber):\n if service.addToLibrary(idnumber, path):\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[choice.lower()][\"Success\"],\n )\n clearUserData(context)\n return ConversationHandler.END\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[choice.lower()][\"Failed\"],\n )\n clearUserData(context)\n return ConversationHandler.END\n else:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=transcript[choice.lower()][\"Exist\"],\n )\n clearUserData(context)\n return ConversationHandler.END\n\ndef allSeries(update, context):\n if not checkId(update):\n if (\n authentication(update, context) == \"added\"\n ): # To also stop the beginning command\n return ConversationHandler.END\n else:\n result = sonarr.allSeries()\n string = \"\"\n for serie in result:\n string += \"• \" \\\n + serie[\"title\"] \\\n + \" (\" \\\n + str(serie[\"year\"]) \\\n + \")\" \\\n + \"\\n\" \\\n + \" status: \" \\\n + serie[\"status\"] \\\n + \"\\n\" \\\n + \" monitored: \" \\\n + str(serie[\"monitored\"]).lower() \\\n + \"\\n\"\n \n #max length of a message is 4096 chars\n if len(string) <= 4096:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=string,\n )\n #split string if longer then 4096 chars\n else: \n neededSplits = math.ceil(len(string) / 4096)\n positionNewLine = []\n index = 0\n while index < len(string): #Get positions of newline, so that the split will happen after a newline\n i = string.find(\"\\n\", index)\n if i == -1:\n return positionNewLine\n positionNewLine.append(i)\n index+=1\n\n #split string at newline closest to maxlength\n stringParts = []\n lastSplit = timesSplit = 0\n i = 4096\n while i > 0 and len(string)>4096: \n if timesSplit < neededSplits:\n if i+lastSplit in positionNewLine:\n stringParts.append(string[0:i])\n string = string[i+1:]\n timesSplit+=1\n lastSplit = i\n i = 4096\n i-=1\n stringParts.append(string)\n\n #print every substring\n for subString in stringParts:\n context.bot.send_message(\n chat_id=update.effective_message.chat_id,\n text=subString,\n )\n return ConversationHandler.END\n\ndef getService(context):\n if context.user_data.get(\"choice\") == transcript[\"Serie\"]:\n return sonarr\n elif context.user_data.get(\"choice\") == transcript[\"Movie\"]:\n return radarr\n else:\n raise ValueError(\n f\"Cannot determine service based on unknown or missing choice: {context.user_data.get('choice')}.\"\n )\n\n\ndef clearUserData(context):\n logger.debug(\n \"Removing choice, title, position, paths, and output from context.user_data...\"\n )\n for x in [\n x\n for x in [\"choice\", \"title\", \"position\", \"output\", \"paths\", \"path\"]\n if x in context.user_data.keys()\n ]:\n context.user_data.pop(x)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"addarr.py","file_name":"addarr.py","file_ext":"py","file_size_in_byte":20764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"453286575","text":"import sys,os,socket,ssl\nimport bjoern\ncurrent_path = os.path.abspath('./')\nsys.path.append(current_path)\nfrom ppaa import create_app\n\nif __name__ == \"__main__\":\n default_ip = \"0.0.0.0\"\n default_port = 8080\n ip = default_ip\n port = default_port\n #create app\n app = create_app(DEBUG=False,proxy_fix=True)\n print(\"----------------new start----------------\")\n print(\"server start on {}\".format(current_path))\n bjoern.run(app,ip,port)\n\n \n\n","sub_path":"bjoern_run.py","file_name":"bjoern_run.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"222191756","text":"import numpy as np\nimport argparse\nimport pandas as pd\nimport randomInitializer as randInit\nimport optimizeFuncLoop as ofl\nimport optimizeFuncNoLoop as ofnl\nimport matplotlib.pyplot as plt\nimport actFunc as af\nimport outputFunc as of\nimport normaliseData as nod\nimport nag\nimport adam\nimport gradientDescent as gd\nimport momentum as mom\nimport pickle\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--lr\", help=\"learning rate\", type=float)\nparser.add_argument(\"--momentum\", help=\"parameter for using the histrory\", type=float)\nparser.add_argument(\"--num_hidden\", help=\"number of hidden layers\", type=int)\nparser.add_argument(\"--sizes\", help=\"string of number with number of neurons in each hidden layer\", type=str)\nparser.add_argument(\"--activation\", help=\"activation function\", type=str)\nparser.add_argument(\"--loss\", help=\"loss function such as squared error(sq) and cross entropy(ce)\", type=str)\nparser.add_argument(\"--opt\", help=\"Optimazation functions such as adam, gd, momentum\", type=str)\nparser.add_argument(\"--batch_size\", help=\"Size of the batch\", type=int)\nparser.add_argument(\"--anneal\", help=\"If true then half the learning rate\", type=bool)\nparser.add_argument(\"--save_dir\", help=\"Directory in which the file of weights and biases will be saved\", type=str)\nparser.add_argument(\"--expt_dir\", help=\"Diectory in which log files wil be saved\", type=str)\nparser.add_argument(\"--train\", help=\"The training data file name\", type=str)\nparser.add_argument(\"--test\", help=\"The testing data file name\", type=str)\nparser.add_argument(\"--val\", help=\"The validation data file name\", type=str)\n\narg = parser.parse_args()\n\n# Mannualy Initializing the parameters\nhidden_layer_sizes = [int(i) for i in arg.sizes.split(',')]\nnum_hidden = arg.num_hidden\nactivation = arg.activation\nbatch_size = arg.batch_size\nloss = arg.loss\nopt = arg.opt\nlr = arg.lr\nanneal = arg.anneal\nmomentum = arg.momentum\nsave_dir = arg.save_dir\nexpt_dir = arg.expt_dir\ntrain = arg.train\ntest = arg.test\nval = arg.val\n\n# Unpacking of the data\ntrain_data_csv = pd.read_csv(train)\ntest_data_csv = pd.read_csv(test)\nval_data_csv = pd.read_csv(val)\n\ntrain_data = train_data_csv.values\ntest_data = test_data_csv.values\nval_data = val_data_csv.values\n\n# Further dividing the data in to label and input data\ntrain_input = train_data[:, 1:train_data.shape[1] - 1]\ntrain_label = train_data[:, train_data.shape[1] - 1]\n\nval_input = val_data[:, 1:val_data.shape[1] - 1]\nval_label = val_data[:, val_data.shape[1] - 1]\n\ntest_input = test_data[:, 1:]\n\n# This part of code is for the normalization of the data\n# 1. Mean Normalize, 2. Mean and Variance Normalize, 3. Max-Min\n# \"feature\" or \"image\" or \"255\"\ntype_normalize = 2\ntype_fea_image = \"feature\"\nmeans = np.mean(train_input, axis=0).reshape(1, train_input.shape[1])\nstds = np.std(train_input, axis=0).reshape(1, train_input.shape[1])\ntrain_input = nod.normaliseData(train_input, type_normalize, type_fea_image, means, stds)\nval_input = nod.normaliseData(val_input, type_normalize, type_fea_image, means, stds)\ntest_input = nod.normaliseData(test_input,type_normalize, type_fea_image, means, stds)\n\ninputs_num = train_input.shape[1]\noutputs_num = 10\nepochs = 15\nlayers = num_hidden+1\n\n# Initializing of the Weights and Biases\nweights = [0] * layers\nbiases = [0] * layers\n\nweights, biases = randInit.randomInitializer(weights, biases, inputs_num, outputs_num, layers,\n hidden_layer_sizes)\n\n\nif opt == \"gd\":\n total_loss_train, total_loss_val, train_weights, train_biases = gd.gradientDescent(train_input, train_label,\n val_input, val_label, layers,\n biases, weights, activation,\n batch_size,\n loss,\n epochs,\n lr, anneal, momentum, expt_dir)\nelif opt == \"momentum\":\n total_loss_train, total_loss_val, train_weights, train_biases = mom.momentum(train_input, train_label,\n val_input, val_label, layers,\n biases, weights, activation,\n batch_size,\n loss,\n epochs,\n lr, anneal, momentum, expt_dir)\nelif opt == \"nag\":\n total_loss_train, total_loss_val, train_weights, train_biases = nag.nag(train_input, train_label,\n val_input, val_label, layers,\n biases, weights, activation,\n batch_size,\n loss,\n epochs,\n lr, anneal, momentum, expt_dir)\nelif opt == \"adam\":\n total_loss_train, total_loss_val, train_weights, train_biases = adam.adam(train_input, train_label,\n val_input, val_label, layers,\n biases, weights, activation,\n batch_size,\n loss,\n epochs,\n lr, anneal, momentum, expt_dir)\n# For making the file on putting the weights and biases\nfilename = save_dir + \"Parameters_neurons\"+str(hidden_layer_sizes[0])+\"_ecpochs\"+str(epochs)+\"_\"+opt+\"_lr\"+str(lr)+\"_act\"+activation+\"_layer\"+str(num_hidden)+\"_loss\"+loss+\"_.pickle\"\nwith open(filename, \"wb\") as output_file:\n pickle.dump([train_weights, train_biases], output_file)\n\n\n# For storing the test sample\ntrail_ones = np.ones((1, test_input.shape[0]))\nmodified_test_data = np.append(test_input.T, trail_ones, axis=0)\npre_act = [0]\nfor i in range(0, layers):\n modified_w_b = np.append(train_weights[i].T, train_biases[i], axis=1)\n pre_act = np.matmul(modified_w_b, modified_test_data)\n act = af.actFunc(activation, pre_act)\n modified_test_data = np.append(act, np.ones((1, act.shape[1])), axis=0)\n\npred_test_outputs = of.outputFunc(pre_act)\npred_test_labels = np.argmax(pred_test_outputs, axis=0)\nids = np.arange(test_input.shape[0])\n\nheaders = [\"id\", \"label\"]\ntest_filename = \"sample_sub.csv\"\ndf = pd.DataFrame([ids, pred_test_labels])\ndf = df.transpose()\ndf.to_csv(expt_dir+test_filename, index=False, header=headers)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"340562516","text":"# -*- encoding: utf-8 -*-\n'''\n@File : q1.py\n@Time : 2020/04/27 09:52:06\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\n'''\n 有100个同学的分数:数据请用随机函数生成;\n A 利用多线程程序(比如,5个线程,每个线程负责输出20条记录),快速输出这100个同学的信息;\n B 利用线程池来实现;\n\n'''\n\nfrom random import randint\nfrom threading import Thread\nimport queue,time\n\ndef work1():\n global it\n for i in range(20):\n try:\n print(next(it))\n except StopIteration:\n return\n\nclass ThreadPool(object):\n def __init__(self,maxsize):\n self.maxsize = maxsize\n self._q = queue.Queue(self.maxsize)\n for i in range(self.maxsize):\n self._q.put(Thread)\n \n def getThread(self):\n return self._q.get()\n \n def addThread(self):\n self._q.put(Thread)\n\ndef work2(p):\n global it\n for i in range(20):\n try:\n\n print(next(it))\n except StopIteration:\n return \n p.addThread()\n \n \nif __name__=='__main__':\n score_list=[randint(20,100) for a in range(100)]\n it=iter(score_list)\n\n print('多线程输出:')\n for i in range(5):\n t=Thread(target=work1)\n t.start()\n time.sleep(2)\n \n print('线程池:')\n it=iter(score_list)\n pool = ThreadPool(3)\n for i in range(5):\n t = pool.getThread()\n a = t(target = work2,args=(pool,))\n a.start()\n\n","sub_path":"homework8/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360889180","text":"from person import Person\nimport json\n\ndef main():\n with open(\"person_records.json\") as file:\n json_data = json.load(file)\n \n toggle = True\n while toggle:\n print(\"1: Create Record\")\n print(\"2: Exit\")\n command = input(\"Select a Number: \")\n if command == \"1\":\n print(\"Create and entry\")\n print(\"\")\n first_name = input(\"Enter first name: \")\n last_name = input(\"Enter last name: \")\n person = Person(first_name, last_name)\n for field in vars(person):\n if (field != '_first_name') and (field != '_last_name'):\n new_field = input(f\"Enter {field.replace('_','',1)}: \")\n setattr(person, field, new_field)\n json_data[\"person_records\"].append(vars(person))\n \n with open(\"person_records.json\", \"w\") as file:\n json.dump(json_data, file)\n else:\n toggle = False\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"episodes/ep12/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"27717255","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'jobs'\n\nurlpatterns = [\n\turl(r'^$', views.index, name='index'),\n\turl(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n\turl(r'^new/', views.new_job, name='new'),\t\n]\n\n","sub_path":"jobs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"225470035","text":"'''\nCreated on Jan 23, 2018\n\n@author: Justin Veyna\n\nReferences:\n https://docs.python.org/3.6/library/xml.etree.elementtree.html\n'''\n\nimport xml.etree.ElementTree as ET\nfrom collections import defaultdict\nimport pickle\nimport os\n\nBASE_DIR = 'S:/workspace/WSD/'\nDATA_DIR = BASE_DIR + 'jsemcor-2012-01/'\nSAVE_DIR = BASE_DIR + \"jsemcor-2012-01-pickled/\"\nSAVE_DIR_ENDING = \".pkl\"\n\nDEFAULT_FILE_PATH = \"jsemcor-2012-01/br-a01.xml\"\n\n\nclass XMLDoc():\n '''\n A wrapper class for the XML documents.\n '''\n def __init__(self, xml_file = \"jsemcor-2012-01/br-a01.xml\", debug = False):\n '''\n xml_file = path of xml file to open. ie:\"jsemcor-2012-01/br-a01.xml\" \n '''\n self.debug = debug\n \n self.tree = ET.parse(xml_file)\n self.root = self.tree.getroot()\n \n if self.debug:\n print(\"Initialized\")\n print(self.tree)\n print(self.root)\n \n def get_terms(self):\n return self.root.iter(\"term\")\n def get_words(self):\n return self.root.iter(\"wf\")\n def get_word_sense_by_id(self, wid):\n sense = self.root.find(\".//*[@id=\\'\"+wid+\"\\']/../../externalReferences/externalRef/externalRef\")\n if sense != None:\n SKIP = len(\"jpn-11-\")\n sense = sense.attrib[\"reference\"][SKIP:]\n return sense\n\n\ndef ddict():\n return defaultdict(dict)\ndef dddict():\n return defaultdict(ddict)\ndef ddddict():\n return defaultdict(dddict)\n \ndef get_sense_linked_terms(xml_file = DEFAULT_FILE_PATH):\n slt = ddddict()\n docu = XMLDoc(xml_file)\n for word in docu.get_words():\n #print(word.attrib)\n wid = word.attrib[\"wid\"]\n split_wid = wid[1:].split(\".\")\n p, s, w = map(int, split_wid)\n slt[p][s][w][\"wid\"] = wid\n #print(word.text)\n slt[p][s][w][\"text\"] = word.text\n ref = docu.get_word_sense_by_id(wid)\n #print(ref)\n slt[p][s][w][\"sense\"] = ref\n return slt\n\ndef original_doc(xml_file = DEFAULT_FILE_PATH, t=list):\n '''\n Prints the original document without any of the XML tags or labels\n t = return type (list or string)\n '''\n orig = t()\n docu = XMLDoc(xml_file)\n for term in docu.get_words():\n if term.text != None:\n orig += t(term.text)\n return orig\n\ndef print_original_doc(xml_file = DEFAULT_FILE_PATH):\n '''Prints the original document without any of the XML tags or labels'''\n print(original_doc(xml_file, t=str))\n\nif __name__ == \"__main__\":\n for f in os.listdir(DATA_DIR):\n print(f)\n words = get_sense_linked_terms(DATA_DIR+f)\n #print(words)\n with open(SAVE_DIR + f + SAVE_DIR_ENDING, \"wb\") as s:\n pickle.dump(words,s)\n ","sub_path":"xml_parser.py","file_name":"xml_parser.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"19942459","text":"import mqtt_remote_method_calls as com\nimport robot_controller as robo\nimport ev3dev.ev3 as ev3\nimport time\nimport math\n\n\ndef main():\n print(\"--------------------------------------------\")\n print(\"Final Project\")\n print(\"--------------------------------------------\")\n robot = robo.Snatch3r()\n ev3.Sound.speak(\"Beacon Radar\").wait()\n global mqtt_client\n mqtt_client = com.MqttClient(Delegate)\n mqtt_client.connect_to_pc(\"mosquitto.csse.rose-hulman.edu\", 3)\n robot.loop_forever()\n\n\nclass Delegate(object):\n def __init__(self):\n self.robot = robo.Snatch3r\n\n def seek_beacons(self, turn_speed, forward_speed):\n print(\"seeking...\")\n\n target = 3\n\n b1_pos = [0, 0]\n b2_pos = [0, 0]\n\n bc1 = 0\n bc2 = 0\n\n btn = ev3.Button()\n\n beacon_1 = ev3.BeaconSeeker(channel=1)\n # beacon_2 = ev3.BeaconSeeker(channel=2)\n robot = robo.Snatch3r()\n\n robot.arm_calibration()\n\n while bc1 < 1:\n if beacon_1.distance != -128 and bc1 < 1:\n b1_pos = [beacon_1.heading, beacon_1.distance]\n print(\"found 1\")\n print(beacon_1.heading_and_distance)\n print(btn.backspace)\n # print(beacon_1.distance)\n bc1 += 1\n target = 1\n ev3.Sound.beep().wait()\n\n # if beacon_2.distance != -128 and bc2 < 1:\n # b2_pos = [beacon_2.heading, beacon_2.distance]\n # print(\"found 2\")\n # print(beacon_2.heading_and_distance)\n # # print(beacon_1.distance)\n # bc2 += 1\n # target = 2\n # ev3.Sound.beep().wait()\n # global mqtt_client\n # mqtt_client.send_message(\"update_b2\", [b2_pos[0], b2_pos[1]])\n\n\n beacon = ev3.BeaconSeeker(channel=1)\n while btn.backspace is False and forward_speed > 0 and turn_speed > 0:\n current_heading = beacon.heading # use the beacon_seeker heading\n current_distance = beacon.distance\n if current_distance == -128:\n # If the IR Remote is not found just sit idle for this program until it is moved.\n print(\"IR Remote not found. Distance is -128\")\n else:\n if math.fabs(current_heading) < 2:\n # Close enough of a heading to move forward\n print(\"On the right heading. Distance: \", current_distance)\n # You add more!\n if current_distance == 0:\n print('You found it')\n robot.stop()\n break\n if current_distance > 0:\n robot.forward(forward_speed, forward_speed)\n if current_distance <= 1:\n robot.stop()\n robot.drive_inches(3, forward_speed)\n robot.stop()\n ev3.Sound.speak('beacon found')\n time.sleep(3)\n break\n if math.fabs(current_heading) > 2 and math.fabs(current_heading) < 10:\n print(\"Adjusting heading: \", current_heading)\n if current_heading > 0:\n robot.left_move(turn_speed, turn_speed)\n if math.fabs(current_heading) < 2:\n robot.stop()\n if current_heading < 0:\n robot.right_move(turn_speed, turn_speed)\n if math.fabs(current_heading) < 2:\n robot.stop()\n if math.fabs(current_heading) > 10:\n robot.right_move(turn_speed, turn_speed)\n time.sleep(0.2)\n\n # The touch_sensor\n # was pressed to abort the attempt if this code runs.\n robot.stop()\n mqtt_client.send_message(\"update_b1\", [b1_pos[0], b1_pos[1]])\n return False\n\n def halt(self):\n robot = robo.Snatch3r()\n robot.stop()\n beacon_1 = ev3.BeaconSeeker(channel=1)\n time.sleep(1)\n print(beacon_1.heading_and_distance)\n global mqtt_client\n mqtt_client.send_message(\"update_b1\", [beacon_1.heading, beacon_1.distance])\n\n def up(self, forward):\n robot = robo.Snatch3r()\n robot.forward(forward, forward)\n\n def left(self, turn):\n robot = robo.Snatch3r()\n robot.left_move(-1 * turn, -1 * turn)\n\n def right(self, turn):\n robot = robo.Snatch3r()\n robot.right_move(-1*turn, -1 * turn)\n\n def back(self, forward):\n robot = robo.Snatch3r()\n robot.backward(forward, forward)\n\n\nmain()\n","sub_path":"projects/kammerrr/kammerrr_ev3_project.py","file_name":"kammerrr_ev3_project.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"258535259","text":"from math import sqrt\n\ndef norm(n): return \"\".join(sorted(ch for ch in str(n)))\n\nN = 10000001\ndiv = [1] * N\n\nfor i in range(2, int(sqrt(N))):\n if div[i] != 1: continue\n for j in range(i*2, N, i): div[j] = i\n\ndef factor(n):\n if div[n] == 1: return set([n])\n facts = factor(n // div[n])\n facts.add(div[n])\n return facts\n\ndef divisors(N, facts, mul=1, i=0, sign = 1):\n if i == len(facts):\n if mul < N: yield sign*(N//mul-1)\n else:\n yield from divisors(N, facts, mul, i+1, sign)\n yield from divisors(N, facts, facts[i] * mul, i+1, -sign)\n\ndef phi(n):\n return sum(divisors(n, list(factor(n))))\n\nbest = (2, 2, 1)\n\nfor n in range(2,10000001):\n ph = phi(n)\n if norm(n) != norm(ph): continue\n best = min(best, (n/ph, n, ph))\nprint(best)\n","sub_path":"p70.py","file_name":"p70.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"361272989","text":"import torch.nn as nn\n\nclass vgg16(nn.Module):\n def __init__(self, num_classes):\n super(vgg16, self).__init__()\n\n cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']\n\n self.feature = self.make_feature_layer(cfg=cfg)\n\n self.classifier = nn.Sequential(\n nn.Linear(25088, 512),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(512, 512),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(512, num_classes),\n )\n\n def forward(self, x):\n x = self.feature(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def make_feature_layer(self, cfg, batch_noram=False):\n layers = []\n in_channels = 3\n\n for v in cfg:\n if v == 'M':\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n else:\n if batch_noram == True:\n layers.append(\n nn.Conv2d(in_channels=in_channels, out_channels=v, kernel_size=3, stride=1, padding=1))\n layers.append(nn.BatchNorm2d(v))\n layers.append(nn.ReLU(inplace=True))\n else:\n layers.append(\n nn.Conv2d(in_channels=in_channels, out_channels=v, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU(inplace=True))\n in_channels = v\n\n return nn.Sequential(*layers)","sub_path":"classification/model/backbone/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"106376519","text":"import argparse\nimport pandas as pd\nimport requests\nimport re\nfrom io import StringIO\nimport os\n\n# API credentials and config\nCLIENT_ID = \"331fd22f-e045-4e6f-bfcd-c5562770e815\"\nCLIENT_SECRET = \"6a8bf10a-0f28-44e1-9bc0-babac1c975be\"\nAPI_URL = \"https://frost.met.no/observations/v0.csv\"\n\n# Frost location IDs\nGARDERMOEN_SOURCE_ID = \"SN4780\"\nVAERNES_SOURCE_ID = \"SN69100\"\n\n# File names\nRAW_PATH = \"../../../data/raw/weather\"\nRAW_FILE_NAME_AIR_TEMPERATURE = \"air_temperature.csv\"\nRAW_FILE_NAME_PRECIPITATION = \"precipitation.csv\"\nRAW_FILE_NAME_VISIBILITY = \"visibility.csv\"\nRAW_FILE_NAME_WIND_DIRECTION = \"wind_direction.csv\"\nRAW_FILE_NAME_WIND_SPEED = \"wind_speed.csv\"\n\n\ndef main():\n args = parse_args()\n\n time_interval = args.date_interval\n time_interval = time_interval[:10] + \\\n \"T00:00:00.000Z\" + time_interval[10:] + \"T23:59:59Z\"\n\n request_builder = newRequestBuilder(args.source_id, time_interval)\n saveFn = newFileSaver(args.source_id)\n\n getWindSpeed(request_builder, saveFn)\n getWindDirection(request_builder, saveFn)\n getAirTemp(request_builder, saveFn)\n getRainfall(request_builder, saveFn)\n getVisibility(request_builder, saveFn, args.source_id)\n\n\ndef parse_args():\n \"\"\"Returns the command line arguments.\"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"Fetch some observations.\"\n )\n parser.add_argument(\"date_interval\",\n help=\"e.g. 2020-01-01/2020-05-05\"\n )\n parser.add_argument(\"-s\", \"--source_id\",\n default=\"SN4780\",\n help=\"Default Gardermoen. Source ID of the desired location from api.met.no e.g. SN4780\"\n )\n\n return parser.parse_args()\n\n\ndef getWindSpeed(request_builder, save):\n \"\"\"Fetches, parses, and saves wind speed data.\n\n Args:\n request_builder (function): The request builder.\n save (function): The save function to run to save the data.\n\n \"\"\"\n\n req = request_builder(\"wind_speed\", \"PT20M\", \"PT30M\")\n df = runRequest(req)\n\n save(df, RAW_FILE_NAME_WIND_SPEED)\n\n\ndef getWindDirection(request_builder, save):\n \"\"\"Fetches, parses, and saves wind direction data.\n\n Args:\n request_builder (function): The request builder.\n save (function): The save function to run to save the data.\n\n \"\"\"\n\n req = request_builder(\"wind_from_direction\", \"PT20M\", \"PT30M\")\n df = runRequest(req)\n\n save(df, RAW_FILE_NAME_WIND_DIRECTION)\n\n\ndef getAirTemp(request_builder, save):\n \"\"\"Fetches, parses, and saves air temperature data.\n\n Args:\n request_builder (function): The request builder.\n save (function): The save function to run to save the data.\n\n \"\"\"\n\n req = request_builder(\"air_temperature\", \"PT20M\", \"PT30M\")\n df = runRequest(req)\n\n save(df, RAW_FILE_NAME_AIR_TEMPERATURE)\n\n\ndef getRainfall(request_builder, save):\n \"\"\"Fetches, parses, and saves rainfall data.\n\n Args:\n request_builder (function): The request builder.\n save (function): The save function to run to save the data.\n\n \"\"\"\n\n req = request_builder(\"accumulated(precipitation_amount)\", \"PT0H\", \"PT1H\")\n req[\"referencetime\"] = re.sub('T.+?Z', '', req[\"referencetime\"])\n df = runRequest(req)\n\n save(df, RAW_FILE_NAME_PRECIPITATION)\n\n\ndef getVisibility(request_builder, save, source_id):\n \"\"\"Fetches, parses, and saves visibility data.\n\n Args:\n request_builder (function): The request builder.\n save (function): The save function to run to save the data.\n source_id (str): The source id for the location.\n\n \"\"\"\n\n req = None\n\n if source_id == GARDERMOEN_SOURCE_ID:\n req = request_builder(\n \"visibility_in_air_poorest_direction\", \"PT0H\", \"PT6H\")\n elif source_id == VAERNES_SOURCE_ID:\n req = request_builder(\"visibility_in_air_mor\", \"PT0H\", \"PT1H\")\n else:\n return\n\n df = runRequest(req)\n print(df)\n\n save(df, RAW_FILE_NAME_VISIBILITY)\n\n\ndef runRequest(request):\n \"\"\"Fetches a request and returns the data\n\n Args:\n request (dict): A dict containing request parameters.\n\n Returns:\n pandas DataFrame: The fetched data as a dataframe.\n\n \"\"\"\n\n url = \"https://frost.met.no/observations/v0.csv\"\n print(\"Downloading %s...\" % request['elements'])\n response = requests.get(url, request, auth=(CLIENT_ID, ''))\n\n if(response.status_code != 200):\n print(\"Error! Returned status code {} for the parameter: {}\".format(\n response.status_code, request['elements']))\n print(\"Message: {}\".format(response.json()['error']['message']))\n print(\"Reason: {}\".format(response.json()['error']['reason']))\n return None\n\n df = pd.read_csv(StringIO(response.text))\n\n if df is None:\n print(\"There was an error\")\n os.exit(1)\n\n return df\n\n\ndef newRequestBuilder(sources, time_interval):\n \"\"\"Creates a new request builder\n\n Args:\n sources (str): The sources parameter for Frost.\n time_interval (str): The time interval parameter for Frost.\n\n Returns:\n function: A request builder.\n\n \"\"\"\n\n def builder(element, offset, interval):\n \"\"\"Builds a Frost request in the current source and time interval scope.\n\n Args:\n element (str): The element parameter for Frost.\n offset (str): The offset parameter for Frost.\n interval (str): The interval parameter for Frost.\n\n Returns:\n dict: The Frost request.\n\n \"\"\"\n\n return {\n 'sources': sources,\n 'elements': element,\n 'referencetime': time_interval, # note that this != column_names.reference_time\n 'timeoffsets': offset,\n 'timeresolutions': interval,\n }\n\n return builder\n\n\ndef newFileSaver(source_id):\n \"\"\"Creates a new file saver\n\n Args:\n source_id (str): The directory name for the files.\n\n Returns:\n function: A save function to save a dataframe to the directory.\n\n \"\"\"\n\n def save(df, file_name):\n location = source_id\n if(location == GARDERMOEN_SOURCE_ID):\n location = \"OSL\"\n elif(location == VAERNES_SOURCE_ID):\n location = \"TRD\"\n\n file_dir = '%s/%s' % (RAW_PATH, location)\n\n if not os.path.exists(file_dir):\n os.makedirs(file_dir, exist_ok=True)\n\n df.to_csv('%s/%s' % (file_dir, file_name), index=False)\n\n return save\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/data/weather/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":6513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"33735738","text":"# 4. Написать программу, которая генерирует в указанных пользователем границах:\n# ● случайное целое число,\n# ● случайное вещественное число,\n# ● случайный символ.\n# Для каждого из трех случаев пользователь задает свои границы диапазона.\n# Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы.\n# Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно.\n# Обусловлено считать пользователя идеальным, проверок на ошибки не делаем\n\n# --случайное целое число\nimport random\ns = round(float(input(\"Введите границы (целые числа) для случайного целого числа\\nНачало: \"))) # round на случай если введено не целое число\ne = round(float(input(\"Конец: \")))\ni = random.randint(s, e)\nprint(\"Случайное целое число в вашем диапазоне:\", i)\n\n# -- случайное вещественное число\ns = float(input(\"Введите границы (целые числа или вещественные числа через точку) для случайного вещественного числа\\nНачало: \"))\ne = float(input(\"Конец: \"))\nf = round(random.uniform(s, e), 2)\nprint(\"Случайное вещественное число в вашем диапазоне:\", f)\n\n# --с лучайный символ\ns = (input(\"Введите границы (буквы латинского алфавита в нижнем регистре) для случайного символа\\nНачало: \"))\ne = (input(\"Конец: \"))\ns = ord(s)\ne = ord(e)\nu = chr(random.randint(s, e))\nprint(\"Случайный символ в вашем диапазоне:\", u)\n","sub_path":"Lesson_1/Task_4.py","file_name":"Task_4.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"178092765","text":"#!/usr/bin/python\n# _*_ coding: utf-8 _*_\n\nimport sys\n\nyomikomi = open(sys.argv[1], \"r\")\nkakikomi_1 = open(\"col1.txt\", \"w\")\nkakikomi_2 = open(\"col2.txt\", \"w\")\n\nfirst = []\nsecond = []\n\nfor line in yomikomi:\n words = line.split(\"\\t\")\n first=words[0]\n second=words[1]\n\n kakikomi_1.write(\"%s\\n\" %first)\t\n kakikomi_2.write(\"%s\\n\" %second)\n\nkakikomi_1.close() \nkakikomi_2.close() \n","sub_path":"SatoTaka/12knock.py","file_name":"12knock.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"242926713","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/idapload/inspectlocust.py\n# Compiled at: 2020-04-15 05:33:11\n# Size of source mod 2**32: 1617 bytes\nimport inspect\nfrom .core import Locust, TaskSet\nfrom .log import console_logger\n\ndef print_task_ratio(idaploads, total=False, level=0, parent_ratio=1.0):\n d = get_task_ratio_dict(idaploads, total=total, parent_ratio=parent_ratio)\n _print_task_ratio(d)\n\n\ndef _print_task_ratio(x, level=0):\n for k, v in x.items():\n padding = ' ' * level\n ratio = v.get('ratio', 1)\n console_logger.info(' %-10s %-50s' % (padding + '%-6.1f' % (ratio * 100), padding + k))\n if 'tasks' in v:\n _print_task_ratio(v['tasks'], level + 1)\n\n\ndef get_task_ratio_dict(tasks, total=False, parent_ratio=1.0):\n \"\"\"\n Return a dict containing task execution ratio info\n \"\"\"\n if hasattr(tasks[0], 'weight'):\n divisor = sum((t.weight for t in tasks))\n else:\n divisor = len(tasks) / parent_ratio\n ratio = {}\n for task in tasks:\n ratio.setdefault(task, 0)\n ratio[task] += task.weight if hasattr(task, 'weight') else 1\n\n ratio_percent = dict(((k, float(v) / divisor) for k, v in ratio.items()))\n task_dict = {}\n for idapload, ratio in ratio_percent.items():\n d = {'ratio': ratio}\n if inspect.isclass(idapload):\n if issubclass(idapload, Locust):\n T = idapload.task_set.tasks\n else:\n if issubclass(idapload, TaskSet):\n T = idapload.tasks\n elif total:\n d['tasks'] = get_task_ratio_dict(T, total, ratio)\n else:\n d['tasks'] = get_task_ratio_dict(T, total)\n task_dict[idapload.__name__] = d\n\n return task_dict","sub_path":"pycfiles/idaploadio-0.15.0-py3.7/inspectlocust.cpython-37.py","file_name":"inspectlocust.cpython-37.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45941657","text":"import numpy as np\nimport torch\nimport os\nimport copy\nimport Network\nimport helpers\n\nclass Agent(object):\n def __init__(self, id, obs_dim, action_dim, optimizer_function, learning_rate, config: dict):\n '''\n Base Attributes of Agent\n id = given by the learner\n obs_dim\n act_dim\n policy = Neural Network Policy\n target_policy = Target Neural Network Policy\n optimizer = Optimier Function\n learning_rate = Learning Rate\n '''\n self.id = id\n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.policy = None\n self.optimizer_function = optimizer_function\n self.learning_rate = learning_rate\n self.config = config\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n def __str__(self):\n return \"<{}:id={}>\".format(self.__class__, self.id)\n \n def save(self, save_path, step):\n torch.save(self.policy, save_path + '/policy.pth')\n\n def load_net(self, load_path):\n self.policy = torch.load(load_path)\n\n def find_best_action(self, network, observation) -> np.ndarray:\n '''\n Iterates over the action space to find the one with the highest Q value\n\n Input\n network policy network to be used\n observation observation from the environment\n \n Returns\n A one-hot encoded list\n '''\n obs_v = torch.tensor(observation).float().to(self.device)\n best_q, best_act_v = float('-inf'), torch.zeros(self.action_dim).to(self.device)\n for i in range(self.action_dim):\n act_v = helpers.action2one_hot_v(self.action_dim, i)\n q_val = network(torch.cat([obs_v, act_v.to(self.device)]))\n if q_val > best_q:\n best_q = q_val\n best_act_v = act_v\n best_act = best_act_v.tolist()\n return best_act\n\nclass DQAgent(Agent):\n def __init__(self, id, obs_dim, action_dim, optimizer, learning_rate, config: dict):\n super(DQAgent,self).__init__(id, obs_dim, action_dim, optimizer, learning_rate, config)\n network_input = obs_dim + action_dim\n network_output = 1\n self.policy = Network.initialize_network(network_input, network_output, config['network'])\n self.target_policy = copy.deepcopy(self.policy)\n self.optimizer = self.optimizer_function(params=self.policy.parameters(), lr=learning_rate)\n \n def get_action(self, obs):\n '''\n This method iterates over all the possible actions to find the one with the highest Q value\n '''\n return self.find_best_action(self.policy, obs)\n\n def get_action_target(self, obs):\n '''\n Same as above but using the Target network\n '''\n return self.find_best_action(self.target_policy, obs)\n\n\nclass DDPGAgent(Agent):\n def __init__(self, id, obs_dim, action_dim, optimizer, learning_rate, config: dict):\n super(DDPGAgent,self).__init__(id, obs_dim, action_dim, optimizer, learning_rate, config)\n network_input = obs_dim + action_dim\n network_output = 1\n self.policy = Network.initialize_network(network_input, network_output, config['network'])\n self.target_policy = copy.deepcopy(self.policy)\n self.optimizer = self.optimizer_function(params=self.policy.parameters(), lr=learning_rate)\n\n\nclass ImitationAgent(Agent):\n def __init__(self, id, obs_dim, action_dim, optimizer, learning_rate, config: dict):\n super(ImitationLearnerAgent,self).__init__(id, obs_dim, action_dim, optimizer, learning_rate, config)\n network_input = obs_dim + action_dim\n network_output = 1\n self.policy = Network.initialize_network(network_input, network_output, config['network'])\n self.target_policy = copy.deepcopy(self.policy)\n self.optimizer = self.optimizer_function(params=self.policy.parameters(), lr=learning_rate)\n","sub_path":"shiva/archive/_olds/modules/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"238285762","text":"#!/usr/bin/env python\n\n\"\"\"General helpers.\"\"\"\n\nfrom __future__ import absolute_import\n\nfrom collections import Mapping, namedtuple\nfrom ConfigParser import SafeConfigParser\nfrom copy import deepcopy\nfrom csv import DictReader\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom json import loads\nfrom re import sub\nfrom sqlalchemy.orm import Query\n\n\ndef convert(value, rtype=None, allow_json=False):\n \"\"\"Converts a string to another value.\n\n :param value: the value to be converted\n :type value: str\n :param rtype: string representation of the type the value should be\n converted to. Accepted values are ``['int', 'float', 'bool', 'unicode',\n 'str', 'json']``.\n :type rtype: str\n :param allow_json: allow loading of json strings\n :type allow_json: bool\n :rtype: int, float, bool, str, unicode\n\n If ``rtype`` isn't specified, the following conversions are attempted in\n order: ``int``, ``float``, ``bool`` and finally ``json.loads`` (only if\n ``allow_json`` is ``True``). If all fail, the method returns the\n string ``value`` unchanged.\n\n Boolean conversions convert ``'true', '1'`` to ``True``, and ``'false', '0'``\n to ``False`` (case insensitive) and otherwise raises an error.\n\n \"\"\"\n value = value.strip()\n if rtype:\n if rtype == 'int':\n return int(value)\n elif rtype == 'float':\n return float(value)\n elif rtype == 'bool':\n if value.lower() == 'true' or value == '1':\n return True\n elif not value or value.lower() == 'false' or value == '0':\n return False\n else:\n raise ValueError('Can\\'t convert %s to boolean.' % value)\n elif rtype == 'unicode':\n return unicode(value, encoding='utf-8', errors='replace')\n elif rtype == 'str':\n return value\n elif rtype == 'json':\n return loads(value)\n # if we get here, something has gone wrong\n raise ValueError('Invalid conversion type: %s' % rtype)\n else:\n try:\n return int(value)\n except ValueError:\n try:\n return float(value)\n except ValueError:\n if value.lower() == 'true':\n return True\n elif value.lower() == 'false':\n return False\n elif value == 'None':\n return None\n else:\n if allow_json:\n try:\n return loads(value)\n except ValueError:\n pass\n return value\n\ndef uncamelcase(name):\n \"\"\"Transforms CamelCase to underscore_case.\n\n :param name: string input\n :type name: str\n :rtype: str\n \n \"\"\"\n s1 = sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\ndef to_json(value, depth=1):\n \"\"\"Serialize an object.\n\n :param value: the object to be serialized.\n :type value: varies\n :param depth: used when serializing nested objects with a ``to_json``\n method. In that case, the ``depth`` parameter is decremented by one each\n call. This paramater sets the initial value.\n :type depth: int\n :rtype: varies\n\n \"\"\"\n if hasattr(value, 'to_json'):\n return value.to_json(depth - 1)\n if isinstance(value, dict):\n return {k: to_json(v, depth) for k, v in value.items()}\n if isinstance(value, list):\n return [to_json(v, depth) for v in value]\n if isinstance(value, (float, int, long, str, unicode, tuple)):\n return value\n if value is None:\n return None\n if isinstance(value, datetime):\n return str(value)\n if isinstance(value, Decimal):\n return float(value)\n raise ValueError('Not jsonifiable')\n\ndef parse_config(file_or_filepath, default=None, allow_json=False,\n case_sensitive=False, parser_type=SafeConfigParser):\n \"\"\"Returns a dictionary of values from a configuration file.\n\n :param file_or_filepath: file or filepath to configuration file\n :type file_or_filepath: str or file\n :param default: dictionary of default values to use\n :type default: dict\n :param allow_json: allow loading of json options\n :type allow_json: bool\n :param case_sensitive: keep option names' case\n :type case_sensitive: bool\n :param parser_type: base parser type to use for parsing the file\n :type parser_type: ConfigParser.RawConfigParser\n :rtype: dict\n\n \"\"\"\n parser = parser_type()\n if case_sensitive:\n parser.optionxform = str\n if isinstance(file_or_filepath, str):\n with open(file_or_filepath) as f:\n parser.readfp(f)\n else:\n parser.readfp(file_or_filepath)\n conf = {\n s: {\n k: convert(v, allow_json=allow_json)\n for (k, v) in parser.items(s)\n }\n for s in parser.sections()\n }\n\n if default:\n # nested dictionary update function\n def update(a, b):\n for k, v in b.iteritems():\n if isinstance(v, Mapping):\n a[k] = update(a.get(k, {}), v)\n else:\n a[k] = b[k]\n return a\n\n conf = update(deepcopy(default), conf)\n\n return conf\n\nPart = namedtuple('Part', ['offset', 'limit'])\n\ndef partition(collection, parts=0, size=0):\n \"\"\"Split an iterable into several pieces.\n\n :param collection: the iterable that will be partitioned. Note that\n ``partition`` needs to be able to compute the total length of the iterable\n so generators won't work.\n :type collection: list, query or file\n :param parts: number of parts to split the collection into\n :type parts: int\n :param size: number of items (lines if ``collection`` is a file) per\n part\n :type size: int\n :rtype: generator\n\n Only one of ``parts`` and ``size`` can be specified at a time.\n\n ``partition`` returns a generator that yields a tuple ``(batch, part)``\n on each iteration. ``batch`` is of the same type as ``collection``, filtered\n to the corresponding partition and ``part`` is a named tuple with two \n properties:\n\n * ``offset``, the first index of the partition (if ``collection`` is a file\n it will be the first line number instead)\n * ``limit``, the max-length of the partition (the last one might be shorter)\n\n \"\"\"\n if (parts and size) or (not parts and not size):\n raise ValueError('Exactly one of parts and size must be specified.')\n offset = 0\n limit = size\n if isinstance(collection, Query):\n # collection is a SQLAlchemy query\n # count won't be very efficient, but only run once so it's ok\n total = collection.count()\n if parts:\n limit = int(ceil(float(total) / parts))\n while offset < total:\n yield collection.offset(offset).limit(limit), Part(offset, limit)\n offset += limit\n elif isinstance(collection, list):\n total = len(collection)\n if parts:\n limit = int(ceil(float(total) / parts))\n while offset < total:\n yield collection[offset:offset + limit], Part(offset, limit)\n offset += limit\n elif isinstance(collection, file):\n total = sum(1 for line in collection)\n if parts:\n limit = int(ceil(float(total) / parts))\n while offset < total:\n collection.seek(0)\n yield islice(collection, offset, offset+limit), Part(offset, limit)\n offset += limit\n\ndef prod(iterable, key=None):\n \"\"\"Cumulative product function (the equivalent of ``sum``).\n\n :param key: function called on each element of the iterable, if none then\n identity is assumed\n :type key: callable\n :rtype: int, float\n\n \"\"\"\n rv = 1\n for elem in iterable:\n if key is None:\n rv *= elem\n else:\n rv *= key(elem)\n return rv\n\n\nclass SmartDictReader(DictReader):\n\n \"\"\"``DictReader`` with built-in value conversion.\n\n :param csvfile: open file instance.\n :type csvfile: file\n :param fields: list of ``fieldnames`` or list of tuples\n ``(fieldname, fieldtype)``. If specified, the ``fieldtype`` will be passed\n as second argument to the ``convert`` function.\n :type fields: list\n :param silent: whether or not to silence errors while processing the file.\n :type silent: bool\n :param allow_json: allow loading of json strings\n :type allow_json: bool\n :param kwargs: keyword arguments to forward to the undelying\n ``csv.DictReader`` object.\n :rtype: iterable\n\n Interesting values for kwargs can be:\n\n * delimiter = '\\t'\n * quotechar = '\\x07'\n\n The following attributes are also available:\n\n * ``rows_imported``, the total number of rows successfully imported\n * ``errors``, a list of tuples ``(e, row)`` where ``e`` is error and ``row``\n the full row for each error raised\n\n \"\"\"\n\n def __init__(self, csvfile, fields=None, silent=False, allow_json=False,\n **kwargs):\n self.csvfile = csvfile\n self.rows_imported = 0\n self.errors = []\n self.silent = silent\n self.allow_json = allow_json\n if fields:\n if isinstance(fields[0], (list, tuple)):\n kwargs['fieldnames'] = [field[0] for field in fields]\n self.field_types = dict(fields)\n else:\n kwargs['fieldnames'] = fields\n self.field_types = dict.fromkeys(fields, None)\n DictReader.__init__(self, csvfile, **kwargs)\n else:\n DictReader.__init__(self, csvfile, **kwargs)\n self.field_types = dict.fromkeys(self.fieldnames, None)\n\n def next(self):\n row = DictReader.next(self)\n try:\n processed_row = dict(\n (key, convert(value, self.field_types[key], self.allow_json))\n for key, value in row.iteritems()\n )\n except ValueError as e:\n self.errors.append((e, row))\n if not self.silent:\n raise e\n else:\n self.rows_imported += 1\n return processed_row\n\n","sub_path":"venv/Lib/site-packages/flasker/util/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":9303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"308475800","text":"#'给出数据文件,想办法用代码找出每个选手最快的三个时间'\nimport os\nos.getcwd()\nos.chdir('/SoftWare/python3/libs/headfirstpython/chapter1')#'给出打开文件的路径'\nos.getcwd()\n#'定义的函数作用为:转换不一样的符号'\ndef sanitize(time_string):#'定义函数'\n if '-' in time_string:\n splitter = '-'\n elif ':' in time_string:\n splitter = ':'\n else:\n return(time_string)\n (mins, secs) = time_string.split(splitter)#'分割分钟和秒并赋值'\n return(mins + '.' + secs)#\"返回分钟和秒中间加'.'号\"\nclass Athlete:#'定义'Athlete'类'\n def __init__(self, a_name, a_dob = None, a_times = []):#'实例化’\n self.name = a_name\n self.dob = a_dob\n self.times = a_times\n def top(self):#'创建另一个方法返回最快的三个时间'\n return(str(sorted(set([sanitize(each_t) for each_t in self.times]))[0:3]))\n\n#'定义一个读取文件并统一符号的函数'\ndef get_coach_data(filename):\n #'增加异常处理'\n try:\n with open(filename) as f:#'打开文件并读取'\n data = f.readline()\n datas = data.strip().split(',')#'给整理好的数据赋值' \n#'用\"Athlete'对象创建代码\"\n return(Athlete(datas.pop(0), datas.pop(0), datas))\n except IOError as ioerr:\n print('File error:' + str(ioerr))#'如有异常给出通知并返回None'\n return(None)\n #'下面四行除了调用函数还可以显示储存位置'\njames = get_coach_data('james2.txt')\njulie = get_coach_data('julie2.txt')\nmikey = get_coach_data('mikey2.txt')\nsarah = get_coach_data('sarah2.txt')\n #'下面的为 打印每个人所对应的最快时间'\nprint(james.name + \"'s fastest times are:\" + james.top())\nprint(julie.name + \"'s fastest times are:\" + julie.top())\nprint(mikey.name + \"'s fastest times are:\" + mikey.top())\nprint(sarah.name + \"'s fastest times are:\" + sarah.top())\n","sub_path":"class .py","file_name":"class .py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"170636260","text":"# Общий объем продаж.\n\n# Дней в недели\nWEEK = 7\n\ndef main():\n print('Сумма продаж за неделю:', total_sale(sales_input()))\n\n\ndef sales_input():\n\n # Список продаж\n sales_week = [0] * WEEK\n\n for index in range(WEEK):\n print('Введите продажи за ', index + 1, ': ',\n sep='', end='')\n sales_week[index] = float(input())\n\n return sales_week\n\ndef total_sale(total):\n\n dig_total = 0\n\n for num in total:\n dig_total += num\n return dig_total\n\nmain()","sub_path":"7/tasks/7.2.py","file_name":"7.2.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"489837271","text":"\"\"\"\nhttps://wikileaks.org/ciav7p1/cms/page_2621767.html\n\t\nWindows contains a service called \"Distributed Transaction Coordinator\" that is\nconfigured to \"Manual\" start by default. This service causes a DLL called\n\"C:\\Windows\\System32\\wbem\\oci.dll\" to load into the \"Network Services\" group.\nBy placing our own DLL in this location and configuring the service to start\nautomatially, we have a persistence mechanism with system privileges. The service\nruns under the \"Network Service\" account, which is a restricted account that has\nprivileges to access the network.\n\"\"\"\nimport os\nimport requests\n\ndef oci_dll_hijack(url,rename_dll):\n\tdll = \"oci.dll\"\n\tdll_path = \"C:\\Windows\\System32\\wbem\"\n\t\n\tif (rename_dll == 1):\n\t\tif (os.path.isfile(os.path.join(dll_path,dll)) == True):\n\t\t\ttry:\n\t\t\t\tos.rename(os.path.join(dll_path,dll),os.path.join(dll_path,\"oci.dll.old\"))\n\t\t\texcept Exception as e:\n\t\t\t\treturn False\n\n\ttry:\n\t\tdownload = requests.get(url)\n\t\tif (len(download.content) > 1):\n\t\t\twith open(os.path.join(dll_path,dll),\"wb\") as dll_file:\n\t\t\t\tdll_file.write(download.content)\n\t\t\t\tdll_file.close()\n\t\t\tif (os.path.isfile(os.path.join(dll_path,dll)) == True):\n\t\t\t\ttry:\n\t\t\t\t\tpopen = os.popen(\"sc qc msdtc & sc config msdtc start=auto & sc qc msdtc\")\n\t\t\t\t\treturn True\n\t\t\t\texcept Exception as e:\n\t\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\texcept Exception as e:\n\t\treturn False\n","sub_path":"oci_dll_hijack.py","file_name":"oci_dll_hijack.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"253047640","text":"from urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\nimport urllib.request\nimport urllib.parse\n\n\n#let's create a file that we will want later to write parsed data to\nfilename=\"NFL_ScrapedData_Rush.csv\"\nf=open(filename,'w')\nheaders=\"Name,Team,Pos.,Rushes,TDs,Target %\\n\"\nf.write(headers)\n\nmy_url=\"http://www.nflsavant.com/index.php\"\nnetloc = urllib.parse.urlparse(my_url).netloc\n\nreq=urllib.request.Request(my_url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}) #sends GET request to URL\nuClient = urllib.request.urlopen(req)\npage_html = uClient.read()\nuClient.close() #close the connection\n\n#now for the good stuff... let's use BeautifulSoup to parse the webpage\npage_soup=soup(page_html,\"html.parser\") #applying BeautifulSoup to the obtained html\n\nresult = []\nfor anchor in page_soup.find('div').findAll('a'):\n if len(anchor.get('href')) > 50:\n result += ['http://'+netloc+'/'+anchor.get('href')]\n\nfor url in result:\n req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}) # sends GET request to URL\n uClient = urllib.request.urlopen(req)\n page_html = uClient.read()\n uClient.close() # close the connection\n\n # now for the good stuff... let's use BeautifulSoup to parse the webpage\n page_soup = soup(page_html, \"html.parser\") # applying BeautifulSoup to the obtained html\n\n containers = page_soup.findAll(\"tr\", {\"class\", \"tblRushes_loadPxP\"})\n\n for container in containers:\n\n All_Tags=container.findAll(\"td\")\n name = All_Tags[0].text\n team = All_Tags[1].text\n pos = All_Tags[2].text\n rushes = All_Tags[3].text\n tds = All_Tags[4].text\n target_perc = All_Tags[5].text\n\n f.write(name.replace(\",\", \";\") + ',')\n f.write(team + ',')\n f.write(pos + ',')\n f.write(rushes + ',')\n f.write(tds + ',')\n f.write(target_perc + '\\n')\n\n\nf.close()\n\n\n","sub_path":"NFL_RushScrapper.py","file_name":"NFL_RushScrapper.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579772005","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 27 12:10:46 2017\n\n@author: Diogo Leite\n\"\"\"\n\nfrom SQL_obj_new.Family_sql_new import _Family_sql_new\n\nclass Family(object):\n \"\"\"\n This class treat the Family object has it exists in FAMILIES table database\n By default, all FK are in the lasts positions in the parameters declaration\n \"\"\"\n def __init__(self, id_family = -1, designation = \"\"):\n \"\"\"\n Constructor of the Family object. All the parameters have a default value\n\n :param id_family: id of the family - -1 if unknown\n :param designation: designation of the family\n\n :type id_family: int - no required\n :type designation: text - required \n \"\"\"\n self.id_family = id_family\n self.designation = designation\n \n def get_all_Families():\n \"\"\"\n return an array with all the Families in the database\n\n :return: array of families\n :rtype: array(Family)\n \"\"\"\n listOfFamilies = []\n sqlObj = _Family_sql_new()\n results = sqlObj.select_all_families_all_attributes()\n for element in results:\n listOfFamilies.append(Family(element[0], element[1]))\n return listOfFamilies\n \n def create_family(self):\n \"\"\"\n Insert a family in the database if it not already exits\n The family contain a :\n - designation\n\n :return: id of the family\n :rtype int\n \"\"\"\n sqlObj = _Family_sql_new()\n value_fam = sqlObj.insert_family_if_not_exist(self.designation)\n self.id_family = value_fam\n return value_fam\n\n def get_family_by_id(id_family):\n \"\"\"\n Get a family by its id\n \n :return: Family object\n :rtype: Family\n \"\"\"\n sqlObj = _Family_sql_new()\n family_result = sqlObj.get_family_by_id(id_family)\n family_obj = Family(family_result[0], family_result[1])\n return family_obj\n\n def __str__(self):\n \"\"\"\n Overwrite of the str method\n \"\"\"\n message_str = \"ID: {0:d} Family: {1}\".format(self.id_family, self.designation)\n return message_str\n \n\n ","sub_path":"objects_new/Families_new.py","file_name":"Families_new.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"305738908","text":"import os\nfrom base64 import b64encode, b64decode\nfrom typing import AnyStr, List, Dict\nfrom collections import Counter\n\nimport numpy as np\nimport cv2 as cv\nimport keras\nimport tensorflow as tf\nfrom yolo4.model import yolo4_body\n\nfrom decode_np import Decode\n\n__all__ = (\"DetectJapan\", \"detect_japan_obj\")\n\nsession = tf.Session()\nkeras.backend.set_session(session)\n\n\ndef get_class(classes_path):\n classes_path = os.path.expanduser(classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n\ndef get_anchors(anchors_path):\n anchors_path = os.path.expanduser(anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(\",\")]\n return np.array(anchors).reshape(-1, 2)\n\n\nclass DetectJapan:\n model_path = \"JPY_weight.h5\" # Keras model or weights must be a .h5 file.\n anchors_path = \"model_data/yolo4_anchors.txt\"\n classes_path = \"model_data/JPY_classes.txt\"\n jpy_classes = ('JPY_500', 'JPY_100', 'JPY_50', 'JPY_10', 'JPY_1', 'JPY_5')\n\n def __init__(self, conf_thresh: float = 0.8, nms_thresh: float = 0.8):\n class_names = get_class(self.classes_path)\n anchors = get_anchors(self.anchors_path)\n model_image_size = (416, 416)\n self._model: keras.Model = yolo4_body(\n inputs=keras.Input(shape=model_image_size + (3,)),\n num_anchors=len(anchors) // 3,\n num_classes=len(class_names),\n )\n self._model.load_weights(os.path.expanduser(self.model_path))\n self._decoder: Decode = Decode(\n obj_threshold=conf_thresh,\n nms_threshold=nms_thresh,\n input_shape=model_image_size,\n _yolo=self._model,\n all_classes=class_names,\n )\n\n @property\n def model(self) -> keras.Model:\n return self._model\n\n @property\n def decoder(self) -> Decode:\n return self._decoder\n\n def detect(self, image_b64: AnyStr, *, fmt: str = \".png\") -> Dict:\n image_bin: bytes = b64decode(image_b64)\n image = cv.imdecode(np.frombuffer(image_bin, np.uint8), cv.IMREAD_COLOR)\n image = cv.resize(image, dsize=(1080, 1080), interpolation=cv.INTER_AREA)\n with session.as_default():\n with session.graph.as_default():\n detect_image, *_, classes = self._decoder.detect_image(image, True)\n is_success, buffer = cv.imencode(fmt, detect_image)\n\n return {\n \"img\": b64encode(buffer.tobytes()).decode(),\n \"count\": self.count(classes)\n }\n\n def count(self, classes: List[int]):\n counter = Counter(classes)\n for key in tuple(counter.keys()): # 딕셔너리 키 이름 변경\n counter[self.jpy_classes[key]] = counter.pop(key)\n\n # for class_ in tuple(counter):\n # counter[self.jpy_classes[class_]] = counter.pop(class_)\n return counter\n\n\ndetect_japan_obj = DetectJapan()\n","sub_path":"detection.py","file_name":"detection.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"290779552","text":"import socket\r\nserver_socket = socket.socket()\r\nip = socket.gethostbyname(socket.gethostname())\r\nport =1234\r\nserver_socket.bind((ip,port))\r\nserver_socket.listen()\r\nprint(\"Server is listening to theri client\")\r\nclient_socket,client_addr = server_socket.accept()\r\nprint(\"Got Connected With Client\")\r\nwhile True:\r\n smsg = input(\"Server --> \")\r\n client_socket.send(smsg.encode())\r\n if smsg.strip().lower() == \"bye\":\r\n print(\"Socket was closed by You!!!\")\r\n client_socket.close()\r\n server_socket.close()\r\n break\r\n msg = client_socket.recv(1024)\r\n if msg.decode().lower().strip() == 'bye':\r\n print(\"Socket was closed by the Client\")\r\n break\r\n client_socket.close()\r\n server_socket.close()\r\n else:\r\n print(\"Client --> \",msg.decode())\r\n \r\n","sub_path":"Chat Application/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"328873740","text":"#\n# @lc app=leetcode.cn id=547 lang=python\n#\n# [547] 朋友圈\n#\n\n# @lc code=start\n\nclass Solution(object):\n def findCircleNum(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: int\n \"\"\"\n # 构造并查集\n if not M:\n return 0\n\n n = len(M)\n p = [i for i in range(n)]\n\n for i in range(n):\n for j in range(n):\n if M[i][j] == 1:\n self.union(p, i, j)\n \n # wrong answer\n # return len(set([p[i] for i in range(n)]))\n\n # correct answer\n return len(set([self.findParent(p, i) for i in range(n)]))\n\n def union(self, p, i, j):\n p1 = self.findParent(p, i)\n p2 = self.findParent(p, j)\n p[p2] = p1\n\n def findParent(self, p, i):\n root = i\n while p[root] != root:\n root = p[root]\n # 路径压缩\n while p[i] != i:\n x = i\n i = p[i]\n p[x] = root\n return root\n# @lc code=end\n\n","sub_path":"Week_07/547.朋友圈.py","file_name":"547.朋友圈.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"454381382","text":"\"\"\"\nUse this to do a small denial of service attack\n\nFor example:\n\n url = https://google.com\n down_it(url, 1000,read = False)\n\n\"\"\"\n\n# For legal purpose only\n\nimport http.client\nimport header\nimport threading\nimport tor\nfrom http_manager import parse_http\nimport urllib.request\nimport random\ntor.connect()\n\nbot = [\n \"https://validator.w3.org/check?uri=%s\",\n \"https://www.facebook.com/sharer/sharer.php?u=%s\",\n \"https://plus.google.com/share?url=%s\",\n \"https://www.linkedin.com/shareArticle?mini=true&url=&title=&summary=&source=%s\",\n \"https://pinterest.com/pin/create/button/?url=%s&media=&description=\"\n\n]\n\n\nclass RedirectedException(Exception):\n \"An exception showing that the page was redirected\"\n\n def __init__(self, description: str, value: str) -> None:\n self.link = value\n self.description = description\n\n def __str__(self) -> str:\n return repr(self.description)\n\n\ndef persistent_request(url: parse_http, read: bool=False) -> None:\n \"requests until no error occurs\"\n try:\n client = url.mode(url.host)\n client.request(\"GET\", \"/\", headers=header.random_header())\n if read:\n client.getresponse().read()\n # client.close()\n except:\n persistent_request(url, read=read)\n\n\ndef hammer(url: parse_http, read: bool=False) -> None:\n \"requests continuously and print on the console\"\n while True:\n persistent_request(url, read)\n print(\"<--thread %s: request sent directly --> \\033[F\" %\n threading.get_ident()) # \\033[F\n\n\ndef persistent_bots(url: parse_http, read: bool=True) -> None:\n \"continuously request with bots until no exceptions are raised\"\n try:\n link = random.choice(bot)\n req = urllib.request.Request(\n link % url.url, headers=header.random_header())\n urllib.request.urlopen(req)\n\n except:\n persistent_bots(url, read=read)\n\n\ndef hammer_bot(url: parse_http, threads: int=500, read: str=False) -> None:\n \"use bots to request continuously\"\n while True:\n persistent_bots(url, read=read)\n print(\"<--thread %s: request sent indirectly--> \\033[F\" %\n threading.get_ident())\n\n\ndef get_response(string_url: str) -> http.client.HTTPResponse:\n \"get response from a url\"\n url = parse_http(string_url)\n client = url.mode(url.host)\n client.request(\"GET\", \"/\", headers=header.false_header())\n return client.getresponse()\n\n\ndef connection_success(string_url: str) -> bool:\n \"check if the requests successfully connects\"\n url = parse_http(string_url)\n client = url.mode(url.host)\n client.request(\"GET\", \"/\", headers=header.false_header())\n response = client.getresponse()\n\n if response.status // 100 == 4 or response.status // 100 == 5:\n raise http.client.HTTPException(\n \"HTTP error %s: %s\" % (response.status, response.reason), response)\n\n elif response.status // 100 == 3:\n link = response.headers['Location']\n if not link.lower().startswith(\"http\"):\n link = url.security + url.host + link\n raise RedirectedException(\"redirected to %s\" % link, link)\n\n elif response.status % 100 == 2:\n return True\n return False\n\n\ndef follow_redirect(string_url: str) -> str:\n \"follows redirects and returns the direct url\"\n try:\n connection_success(string_url)\n except RedirectedException as link:\n string_url = follow_redirect(link.link)\n return string_url\n\n\ndef direct_dos(url: str, threads: int=500, read: bool=False) -> None:\n \"directly send requests through server continuously\"\n url = parse_http(url)\n attack = lambda: hammer(url, read)\n for i in range(threads):\n t = threading.Thread(target=attack)\n #t.daemon = True\n t.start()\n\n\ndef indirect_dos(url: str, threads: int=500, read: bool=False) -> None:\n \"continuously send requests through bots\"\n url = parse_http(url)\n attack = lambda: hammer_bot(url, read)\n for i in range(threads):\n t = threading.Thread(target=attack)\n #t.daemon = True\n t.start()\n\n\ndef down_it(url: str, n: int, read: bool=False) -> None:\n \"attack a url\"\n url = follow_redirect(url)\n indirect_dos(url, n // 5, read=True)\n direct_dos(url, n, read=read)\n","sub_path":"denyservice.py","file_name":"denyservice.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"109300981","text":"\n\n#calss header\nclass _ENTRANT():\n\tdef __init__(self,): \n\t\tself.name = \"ENTRANT\"\n\t\tself.definitions = [u'a person who becomes a member of a group or organization: ', u'a person who takes part in a competition or an exam: ', u'a company that starts selling a particular product or service, or selling in a particular place, for the first time: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_entrant.py","file_name":"_entrant.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"633845252","text":"\"\"\"BSD 2-Clause License\n\nCopyright (c) 2019, Allied Vision Technologies GmbH\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport copy\nimport ctypes\nfrom typing import Callable, Any, Tuple\nfrom ctypes import c_void_p, c_char_p, byref, sizeof, POINTER as c_ptr, c_char_p as c_str\nfrom ..util import TraceEnable\nfrom ..error import VimbaSystemError\nfrom .vimba_common import Uint32Enum, Int32Enum, VmbInt32, VmbUint32, VmbInt64, VmbUint64, \\\n VmbHandle, VmbBool, VmbDouble, VmbError, VimbaCError, VmbPixelFormat, \\\n fmt_enum_repr, fmt_repr, fmt_flags_repr, load_vimba_lib\n\n__version__ = None\n\n__all__ = [\n 'VmbPixelFormat',\n 'VmbInterface',\n 'VmbAccessMode',\n 'VmbFeatureData',\n 'VmbFeaturePersist',\n 'VmbFeatureVisibility',\n 'VmbFeatureFlags',\n 'VmbFrameStatus',\n 'VmbFrameFlags',\n 'VmbVersionInfo',\n 'VmbInterfaceInfo',\n 'VmbCameraInfo',\n 'VmbFeatureInfo',\n 'VmbFeatureEnumEntry',\n 'VmbFrame',\n 'VmbFeaturePersistSettings',\n 'G_VIMBA_C_HANDLE',\n 'VIMBA_C_VERSION',\n 'EXPECTED_VIMBA_C_VERSION',\n 'call_vimba_c',\n 'build_callback_type'\n]\n\n\n# Types\nclass VmbInterface(Uint32Enum):\n \"\"\"\n Camera Interface Types:\n Unknown - Interface is not known to this version of the API\n Firewire - 1394\n Ethernet - GigE\n Usb - USB 3.0\n CL - Camera Link\n CSI2 - CSI-2\n \"\"\"\n Unknown = 0\n Firewire = 1\n Ethernet = 2\n Usb = 3\n CL = 4\n CSI2 = 5\n\n def __str__(self):\n return self._name_\n\n\nclass VmbAccessMode(Uint32Enum):\n \"\"\"\n Camera Access Mode:\n None_ - No access\n Full - Read and write access\n Read - Read-only access\n Config - Configuration access (GeV)\n Lite - Read and write access without feature access (only addresses)\n \"\"\"\n None_ = 0\n Full = 1\n Read = 2\n Config = 4\n Lite = 8\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureData(Uint32Enum):\n \"\"\"\n Feature Data Types\n Unknown - Unknown feature type\n Int - 64 bit integer feature\n Float - 64 bit floating point feature\n Enum - Enumeration feature\n String - String feature\n Bool - Boolean feature\n Command - Command feature\n Raw - Raw (direct register access) feature\n None_ - Feature with no data\n \"\"\"\n Unknown = 0\n Int = 1\n Float = 2\n Enum = 3\n String = 4\n Bool = 5\n Command = 6\n Raw = 7\n None_ = 8\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeaturePersist(Uint32Enum):\n \"\"\"\n Type of features that are to be saved (persisted) to the XML file\n when using VmbCameraSettingsSave\n\n All - Save all features to XML, including look-up tables\n Streamable - Save only features marked as streamable, excluding\n look-up tables\n NoLUT - Save all features except look-up tables (default)\n \"\"\"\n All = 0\n Streamable = 1\n NoLUT = 2\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureVisibility(Uint32Enum):\n \"\"\"\n Feature Visibility\n Unknown - Feature visibility is not known\n Beginner - Feature is visible in feature list (beginner level)\n Expert - Feature is visible in feature list (expert level)\n Guru - Feature is visible in feature list (guru level)\n Invisible - Feature is not visible in feature list\n \"\"\"\n Unknown = 0\n Beginner = 1\n Expert = 2\n Guru = 3\n Invisible = 4\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureFlags(Uint32Enum):\n \"\"\"\n Feature Flags\n None_ - No additional information is provided\n Read - Static info about read access.\n Current status depends on access mode, check with\n VmbFeatureAccessQuery()\n Write - Static info about write access.\n Current status depends on access mode, check with\n VmbFeatureAccessQuery()\n Volatile - Value may change at any time\n ModifyWrite - Value may change after a write\n \"\"\"\n None_ = 0\n Read = 1\n Write = 2\n Undocumented = 4\n Volatile = 8\n ModifyWrite = 16\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFrameStatus(Int32Enum):\n \"\"\"\n Frame transfer status\n Complete - Frame has been completed without errors\n Incomplete - Frame could not be filled to the end\n TooSmall - Frame buffer was too small\n Invalid - Frame buffer was invalid\n \"\"\"\n Complete = 0\n Incomplete = -1\n TooSmall = -2\n Invalid = -3\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFrameFlags(Uint32Enum):\n \"\"\"\n Frame Flags\n None_ - No additional information is provided\n Dimension - Frame's dimension is provided\n Offset - Frame's offset is provided (ROI)\n FrameID - Frame's ID is provided\n Timestamp - Frame's timestamp is provided\n \"\"\"\n None_ = 0\n Dimension = 1\n Offset = 2\n FrameID = 4\n Timestamp = 8\n\n def __str__(self):\n return self._name_\n\n\nclass VmbVersionInfo(ctypes.Structure):\n \"\"\"\n Version Information\n Fields:\n major - Type: VmbUint32, Info: Major version number\n minor - Type: VmbUint32, Info: Minor version number\n patch - Type: VmbUint32, Info: Patch version number\n \"\"\"\n _fields_ = [\n (\"major\", VmbUint32),\n (\"minor\", VmbUint32),\n (\"patch\", VmbUint32)\n ]\n\n def __str__(self):\n return '{}.{}.{}'.format(self.major, self.minor, self.patch)\n\n def __repr__(self):\n rep = 'VmbVersionInfo'\n rep += '(major=' + repr(self.major)\n rep += ',minor=' + repr(self.minor)\n rep += ',patch=' + repr(self.patch)\n rep += ')'\n return rep\n\n\nclass VmbInterfaceInfo(ctypes.Structure):\n \"\"\"\n Interface information. Holds read-only information about an interface.\n Fields:\n interfaceIdString - Type: c_char_p\n Info: Unique identifier for each interface\n interfaceType - Type: VmbInterface (VmbUint32)\n Info: Interface type, see VmbInterface\n interfaceName - Type: c_char_p\n Info: Interface name, given by transport layer\n serialString - Type: c_char_p\n Info: Serial number\n permittedAccess - Type: VmbAccessMode (VmbUint32)\n Info: Used access mode, see VmbAccessMode\n \"\"\"\n _fields_ = [\n (\"interfaceIdString\", c_char_p),\n (\"interfaceType\", VmbUint32),\n (\"interfaceName\", c_char_p),\n (\"serialString\", c_char_p),\n (\"permittedAccess\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbInterfaceInfo'\n rep += fmt_repr('(interfaceIdString={}', self.interfaceIdString)\n rep += fmt_enum_repr(',interfaceType={}', VmbInterface, self.interfaceType)\n rep += fmt_repr(',interfaceName={}', self.interfaceName)\n rep += fmt_repr(',serialString={}', self.serialString)\n rep += fmt_flags_repr(',permittedAccess={}', VmbAccessMode, self.permittedAccess)\n rep += ')'\n return rep\n\n\nclass VmbCameraInfo(ctypes.Structure):\n \"\"\"\n Camera information. Holds read-only information about a camera.\n Fields:\n cameraIdString - Type: c_char_p\n Info: Unique identifier for each camera\n cameraName - Type: c_char_p\n Info: Name of the camera\n modelName - Type: c_char_p\n Info: Model name\n serialString - Type: c_char_p\n Info: Serial number\n permittedAccess - Type: VmbAccessMode (VmbUint32)\n Info: Used access mode, see VmbAccessMode\n interfaceIdString - Type: c_char_p\n Info: Unique value for each interface or bus\n \"\"\"\n _fields_ = [\n (\"cameraIdString\", c_char_p),\n (\"cameraName\", c_char_p),\n (\"modelName\", c_char_p),\n (\"serialString\", c_char_p),\n (\"permittedAccess\", VmbUint32),\n (\"interfaceIdString\", c_char_p)\n ]\n\n def __repr__(self):\n rep = 'VmbCameraInfo'\n rep += fmt_repr('(cameraIdString={}', self.cameraIdString)\n rep += fmt_repr(',cameraName={}', self.cameraName)\n rep += fmt_repr(',modelName={}', self.modelName)\n rep += fmt_repr(',serialString={}', self.serialString)\n rep += fmt_flags_repr(',permittedAccess={}', VmbAccessMode, self.permittedAccess)\n rep += fmt_repr(',interfaceIdString={}', self.interfaceIdString)\n rep += ')'\n return rep\n\n\nclass VmbFeatureInfo(ctypes.Structure):\n \"\"\"\n Feature information. Holds read-only information about a feature.\n Fields:\n name - Type: c_char_p\n Info: Name used in the API\n featureDataType - Type: VmbFeatureData (VmbUint32)\n Info: Data type of this feature\n featureFlags - Type: VmbFeatureFlags (VmbUint32)\n Info: Access flags for this feature\n category - Type: c_char_p\n Info: Category this feature can be found in\n displayName - Type: c_char_p\n Info: Feature name to be used in GUIs\n pollingTime - Type: VmbUint32\n Info: Predefined polling time for volatile\n features\n unit - Type: c_char_p\n Info: Measuring unit as given in the XML file\n representation - Type: c_char_p\n Info: Representation of a numeric feature\n visibility - Type: VmbFeatureVisibility (VmbUint32)\n Info: GUI visibility\n tooltip - Type: c_char_p\n Info: Short description, e.g. for a tooltip\n description - Type: c_char_p\n Info: Longer description\n sfncNamespace - Type: c_char_p\n Info: Namespace this feature resides in\n isStreamable - Type: VmbBool\n Info: Indicates if a feature can be stored\n to / loaded from a file\n hasAffectedFeatures - Type: VmbBool\n Info: Indicates if the feature potentially\n affects other features\n hasSelectedFeatures - Type: VmbBool\n Info: Indicates if the feature selects other\n features\n \"\"\"\n _fields_ = [\n (\"name\", c_char_p),\n (\"featureDataType\", VmbUint32),\n (\"featureFlags\", VmbUint32),\n (\"category\", c_char_p),\n (\"displayName\", c_char_p),\n (\"pollingTime\", VmbUint32),\n (\"unit\", c_char_p),\n (\"representation\", c_char_p),\n (\"visibility\", VmbUint32),\n (\"tooltip\", c_char_p),\n (\"description\", c_char_p),\n (\"sfncNamespace\", c_char_p),\n (\"isStreamable\", VmbBool),\n (\"hasAffectedFeatures\", VmbBool),\n (\"hasSelectedFeatures\", VmbBool)\n ]\n\n def __repr__(self):\n rep = 'VmbFeatureInfo'\n rep += fmt_repr('(name={}', self.name)\n rep += fmt_enum_repr(',featureDataType={}', VmbFeatureData, self.featureDataType)\n rep += fmt_flags_repr(',featureFlags={}', VmbFeatureFlags, self.featureFlags)\n rep += fmt_repr(',category={}', self.category)\n rep += fmt_repr(',displayName={}', self.displayName)\n rep += fmt_repr(',pollingTime={}', self.pollingTime)\n rep += fmt_repr(',unit={}', self.unit)\n rep += fmt_repr(',representation={}', self.representation)\n rep += fmt_enum_repr(',visibility={}', VmbFeatureVisibility, self.visibility)\n rep += fmt_repr(',tooltip={}', self.tooltip)\n rep += fmt_repr(',description={}', self.description)\n rep += fmt_repr(',sfncNamespace={}', self.sfncNamespace)\n rep += fmt_repr(',isStreamable={}', self.isStreamable)\n rep += fmt_repr(',hasAffectedFeatures={}', self.hasAffectedFeatures)\n rep += fmt_repr(',hasSelectedFeatures={}', self.hasSelectedFeatures)\n rep += ')'\n return rep\n\n\nclass VmbFeatureEnumEntry(ctypes.Structure):\n \"\"\"\n Info about possible entries of an enumeration feature:\n Fields:\n name - Type: c_char_p\n Info: Name used in the API\n displayName - Type: c_char_p\n Info: Enumeration entry name to be used in GUIs\n visibility - Type: VmbFeatureVisibility (VmbUint32)\n Info: GUI visibility\n tooltip - Type: c_char_p\n Info: Short description, e.g. for a tooltip\n description - Type: c_char_p\n Info: Longer description\n sfncNamespace - Type: c_char_p\n Info: Namespace this feature resides in\n intValue - Type: VmbInt64\n Info: Integer value of this enumeration entry\n \"\"\"\n _fields_ = [\n (\"name\", c_char_p),\n (\"displayName\", c_char_p),\n (\"visibility\", VmbUint32),\n (\"tooltip\", c_char_p),\n (\"description\", c_char_p),\n (\"sfncNamespace\", c_char_p),\n (\"intValue\", VmbInt64)\n ]\n\n def __repr__(self):\n rep = 'VmbFeatureEnumEntry'\n rep += fmt_repr('(name={}', self.name)\n rep += fmt_repr(',displayName={}', self.displayName)\n rep += fmt_enum_repr(',visibility={}', VmbFeatureVisibility, self.visibility)\n rep += fmt_repr(',tooltip={}', self.tooltip)\n rep += fmt_repr(',description={}', self.description)\n rep += fmt_repr(',sfncNamespace={}', self.sfncNamespace)\n rep += fmt_repr(',intValue={},', self.intValue)\n rep += ')'\n return rep\n\n\nclass VmbFrame(ctypes.Structure):\n \"\"\"\n Frame delivered by Camera\n Fields (in):\n buffer - Type: c_void_p\n Info: Comprises image and ancillary data\n bufferSize - Type: VmbUint32_t\n Info: Size of the data buffer\n context - Type: c_void_p[4]\n Info: 4 void pointers that can be employed by the user\n (e.g. for storing handles)\n\n Fields (out):\n receiveStatus - Type: VmbFrameStatus (VmbInt32)\n Info: Resulting status of the receive operation\n receiveFlags - Type: VmbFrameFlags (VmbUint32)\n Info: Flags indicating which additional frame\n information is available\n imageSize - Type: VmbUint32\n Info: Size of the image data inside the data buffer\n ancillarySize - Type: VmbUint32\n Info: Size of the ancillary data inside the\n data buffer\n pixelFormat - Type: VmbPixelFormat (VmbUint32)\n Info: Pixel format of the image\n width - Type: VmbUint32\n Info: Width of an image\n height - Type: VmbUint32\n Info: Height of an image\n offsetX - Type: VmbUint32\n Info: Horizontal offset of an image\n offsetY - Type: VmbUint32\n Info: Vertical offset of an image\n frameID - Type: VmbUint64\n Info: Unique ID of this frame in this stream\n timestamp - Type: VmbUint64\n Info: Timestamp set by the camera\n \"\"\"\n _fields_ = [\n (\"buffer\", c_void_p),\n (\"bufferSize\", VmbUint32),\n (\"context\", c_void_p * 4),\n (\"receiveStatus\", VmbInt32),\n (\"receiveFlags\", VmbUint32),\n (\"imageSize\", VmbUint32),\n (\"ancillarySize\", VmbUint32),\n (\"pixelFormat\", VmbUint32),\n (\"width\", VmbUint32),\n (\"height\", VmbUint32),\n (\"offsetX\", VmbUint32),\n (\"offsetY\", VmbUint32),\n (\"frameID\", VmbUint64),\n (\"timestamp\", VmbUint64)\n ]\n\n def __repr__(self):\n rep = 'VmbFrame'\n rep += fmt_repr('(buffer={}', self.buffer)\n rep += fmt_repr(',bufferSize={}', self.bufferSize)\n rep += fmt_repr(',context={}', self.context)\n rep += fmt_enum_repr('receiveStatus: {}', VmbFrameStatus, self.receiveStatus)\n rep += fmt_flags_repr(',receiveFlags={}', VmbFrameFlags, self.receiveFlags)\n rep += fmt_repr(',imageSize={}', self.imageSize)\n rep += fmt_repr(',ancillarySize={}', self.ancillarySize)\n rep += fmt_enum_repr(',pixelFormat={}', VmbPixelFormat, self.pixelFormat)\n rep += fmt_repr(',width={}', self.width)\n rep += fmt_repr(',height={}', self.height)\n rep += fmt_repr(',offsetX={}', self.offsetX)\n rep += fmt_repr(',offsetY={}', self.offsetY)\n rep += fmt_repr(',frameID={}', self.frameID)\n rep += fmt_repr(',timestamp={}', self.timestamp)\n rep += ')'\n return rep\n\n def deepcopy_skip_ptr(self, memo):\n result = VmbFrame()\n memo[id(self)] = result\n\n result.buffer = None\n result.bufferSize = 0\n result.context = (None, None, None, None)\n\n setattr(result, 'receiveStatus', copy.deepcopy(self.receiveStatus, memo))\n setattr(result, 'receiveFlags', copy.deepcopy(self.receiveFlags, memo))\n setattr(result, 'imageSize', copy.deepcopy(self.imageSize, memo))\n setattr(result, 'ancillarySize', copy.deepcopy(self.ancillarySize, memo))\n setattr(result, 'pixelFormat', copy.deepcopy(self.pixelFormat, memo))\n setattr(result, 'width', copy.deepcopy(self.width, memo))\n setattr(result, 'height', copy.deepcopy(self.height, memo))\n setattr(result, 'offsetX', copy.deepcopy(self.offsetX, memo))\n setattr(result, 'offsetY', copy.deepcopy(self.offsetY, memo))\n setattr(result, 'frameID', copy.deepcopy(self.frameID, memo))\n setattr(result, 'timestamp', copy.deepcopy(self.timestamp, memo))\n return result\n\n\nclass VmbFeaturePersistSettings(ctypes.Structure):\n \"\"\"\n Parameters determining the operation mode of VmbCameraSettingsSave\n and VmbCameraSettingsLoad\n Fields:\n persistType - Type: VmbFeaturePersist (VmbUint32)\n Info: Type of features that are to be saved\n maxIterations - Type: VmbUint32\n Info: Number of iterations when loading settings\n loggingLevel - Type: VmbUint32\n Info: Determines level of detail for load/save\n settings logging\n \"\"\"\n _fields_ = [\n (\"persistType\", VmbUint32),\n (\"maxIterations\", VmbUint32),\n (\"loggingLevel\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbFrame'\n rep += fmt_enum_repr('(persistType={}', VmbFeaturePersist, self.persistType)\n rep += fmt_repr(',maxIterations={}', self.maxIterations)\n rep += fmt_repr(',loggingLevel={}', self.loggingLevel)\n rep += ')'\n return rep\n\n\nG_VIMBA_C_HANDLE = VmbHandle(1)\n\nVIMBA_C_VERSION = None\nEXPECTED_VIMBA_C_VERSION = '1.9.0'\n\n# For detailed information on the signatures see \"VimbaC.h\"\n# To improve readability, suppress 'E501 line too long (> 100 characters)'\n# check of flake8\n_SIGNATURES = {\n 'VmbVersionQuery': (VmbError, [c_ptr(VmbVersionInfo), VmbUint32]),\n 'VmbStartup': (VmbError, None),\n 'VmbShutdown': (None, None),\n 'VmbCamerasList': (VmbError, [c_ptr(VmbCameraInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]),\n 'VmbCameraInfoQuery': (VmbError, [c_str, c_ptr(VmbCameraInfo), VmbUint32]),\n 'VmbCameraOpen': (VmbError, [c_str, VmbAccessMode, c_ptr(VmbHandle)]),\n 'VmbCameraClose': (VmbError, [VmbHandle]),\n 'VmbFeaturesList': (VmbError, [VmbHandle, c_ptr(VmbFeatureInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbFeatureInfoQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeatureInfo), VmbUint32]),\n 'VmbFeatureListAffected': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeatureInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbFeatureListSelected': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeatureInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbFeatureAccessQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool), c_ptr(VmbBool)]),\n 'VmbFeatureIntGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureIntSet': (VmbError, [VmbHandle, c_str, VmbInt64]),\n 'VmbFeatureIntRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64), c_ptr(VmbInt64)]), # noqa: E501\n 'VmbFeatureIntIncrementQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureFloatGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbDouble)]),\n 'VmbFeatureFloatSet': (VmbError, [VmbHandle, c_str, VmbDouble]),\n 'VmbFeatureFloatRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbDouble), c_ptr(VmbDouble)]),\n 'VmbFeatureFloatIncrementQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool), c_ptr(VmbDouble)]), # noqa: E501\n 'VmbFeatureEnumGet': (VmbError, [VmbHandle, c_str, c_ptr(c_str)]),\n 'VmbFeatureEnumSet': (VmbError, [VmbHandle, c_str, c_str]),\n 'VmbFeatureEnumRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(c_str), VmbUint32, c_ptr(VmbUint32)]), # noqa: E501\n 'VmbFeatureEnumIsAvailable': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureEnumAsInt': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureEnumAsString': (VmbError, [VmbHandle, c_str, VmbInt64, c_ptr(c_str)]),\n 'VmbFeatureEnumEntryGet': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbFeatureEnumEntry), VmbUint32]), # noqa: E501\n 'VmbFeatureStringGet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32, c_ptr(VmbUint32)]), # noqa: E501\n 'VmbFeatureStringSet': (VmbError, [VmbHandle, c_str, c_str]),\n 'VmbFeatureStringMaxlengthQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbUint32)]),\n 'VmbFeatureBoolGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureBoolSet': (VmbError, [VmbHandle, c_str, VmbBool]),\n 'VmbFeatureCommandRun': (VmbError, [VmbHandle, c_str]),\n 'VmbFeatureCommandIsDone': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureRawGet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32, c_ptr(VmbUint32)]),\n 'VmbFeatureRawSet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32]),\n 'VmbFeatureRawLengthQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbUint32)]),\n 'VmbFeatureInvalidationRegister': (VmbError, [VmbHandle, c_str, c_void_p, c_void_p]), # noqa: E501\n 'VmbFeatureInvalidationUnregister': (VmbError, [VmbHandle, c_str, c_void_p]),\n 'VmbFrameAnnounce': (VmbError, [VmbHandle, c_ptr(VmbFrame), VmbUint32]),\n 'VmbFrameRevoke': (VmbError, [VmbHandle, c_ptr(VmbFrame)]),\n 'VmbFrameRevokeAll': (VmbError, [VmbHandle]),\n 'VmbCaptureStart': (VmbError, [VmbHandle]),\n 'VmbCaptureEnd': (VmbError, [VmbHandle]),\n 'VmbCaptureFrameQueue': (VmbError, [VmbHandle, c_ptr(VmbFrame), c_void_p]),\n 'VmbCaptureFrameWait': (VmbError, [VmbHandle, c_ptr(VmbFrame), VmbUint32]),\n 'VmbCaptureQueueFlush': (VmbError, [VmbHandle]),\n 'VmbInterfacesList': (VmbError, [c_ptr(VmbInterfaceInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbInterfaceOpen': (VmbError, [c_str, c_ptr(VmbHandle)]),\n 'VmbInterfaceClose': (VmbError, [VmbHandle]),\n 'VmbAncillaryDataOpen': (VmbError, [c_ptr(VmbFrame), c_ptr(VmbHandle)]),\n 'VmbAncillaryDataClose': (VmbError, [VmbHandle]),\n 'VmbMemoryRead': (VmbError, [VmbHandle, VmbUint64, VmbUint32, c_str, c_ptr(VmbUint32)]),\n 'VmbMemoryWrite': (VmbError, [VmbHandle, VmbUint64, VmbUint32, c_str, c_ptr(VmbUint32)]),\n 'VmbRegistersRead': (VmbError, [VmbHandle, VmbUint32, c_ptr(VmbUint64), c_ptr(VmbUint64), c_ptr(VmbUint32)]), # noqa: E501\n 'VmbRegistersWrite': (VmbError, [VmbHandle, VmbUint32, c_ptr(VmbUint64), c_ptr(VmbUint64), c_ptr(VmbUint32)]), # noqa: E501\n 'VmbCameraSettingsSave': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeaturePersistSettings), VmbUint32]), # noqa: E501\n 'VmbCameraSettingsLoad': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeaturePersistSettings), VmbUint32]) # noqa: E501\n}\n\n\ndef _attach_signatures(lib_handle):\n global _SIGNATURES\n\n for function_name, signature in _SIGNATURES.items():\n fn = getattr(lib_handle, function_name)\n fn.restype, fn.argtypes = signature\n fn.errcheck = _eval_vmberror\n\n return lib_handle\n\n\ndef _check_version(lib_handle):\n global EXPECTED_VIMBA_C_VERSION\n global VIMBA_C_VERSION\n\n v = VmbVersionInfo()\n lib_handle.VmbVersionQuery(byref(v), sizeof(v))\n\n VIMBA_C_VERSION = str(v)\n\n loaded_version = (v.major, v.minor, v.patch)\n expected_version = tuple(map(int, EXPECTED_VIMBA_C_VERSION.split(\".\")))\n # major and minor version must be equal, patch version may be equal or greater\n if not(loaded_version[0:2] == expected_version[0:2] and\n loaded_version[2] >= expected_version[2]):\n msg = 'Invalid VimbaC Version: Expected: {}, Found:{}'\n raise VimbaSystemError(msg.format(EXPECTED_VIMBA_C_VERSION, VIMBA_C_VERSION))\n\n return lib_handle\n\n\ndef _eval_vmberror(result: VmbError, func: Callable[..., Any], *args: Tuple[Any, ...]):\n if result not in (VmbError.Success, None):\n raise VimbaCError(result)\n\n\n_lib_instance = _check_version(_attach_signatures(load_vimba_lib('VimbaC')))\n\n\n@TraceEnable()\ndef call_vimba_c(func_name: str, *args):\n \"\"\"This function encapsulates the entire VimbaC access.\n\n For Details on valid function signatures see the 'VimbaC.h'.\n\n Arguments:\n func_name: The function name from VimbaC to be called.\n args: Varargs passed directly to the underlaying C-Function.\n\n Raises:\n TypeError if given are do not match the signature of the function.\n AttributeError if func with name 'func_name' does not exist.\n VimbaCError if the function call is valid but neither None or VmbError.Success was returned.\n\n The following functions of VimbaC can be executed:\n VmbVersionQuery\n VmbStartup\n VmbShutdown\n VmbCamerasList\n VmbCameraInfoQuery\n VmbCameraOpen\n VmbCameraClose\n VmbFeaturesList\n VmbFeatureInfoQuery\n VmbFeatureListAffected\n VmbFeatureListSelected\n VmbFeatureAccessQuery\n VmbFeatureIntGet\n VmbFeatureIntSet\n VmbFeatureIntRangeQuery\n VmbFeatureIntIncrementQuery\n VmbFeatureFloatGet\n VmbFeatureFloatSet\n VmbFeatureFloatRangeQuery\n VmbFeatureFloatIncrementQuery\n VmbFeatureEnumGet\n VmbFeatureEnumSet\n VmbFeatureEnumRangeQuery\n VmbFeatureEnumIsAvailable\n VmbFeatureEnumAsInt\n VmbFeatureEnumAsString\n VmbFeatureEnumEntryGet\n VmbFeatureStringGet\n VmbFeatureStringSet\n VmbFeatureStringMaxlengthQuery\n VmbFeatureBoolGet\n VmbFeatureBoolSet\n VmbFeatureCommandRun\n VmbFeatureCommandIsDone\n VmbFeatureRawGet\n VmbFeatureRawSet\n VmbFeatureRawLengthQuery\n VmbFeatureInvalidationRegister\n VmbFeatureInvalidationUnregister\n VmbFrameAnnounce\n VmbFrameRevoke\n VmbFrameRevokeAll\n VmbCaptureStart\n VmbCaptureEnd\n VmbCaptureFrameQueue\n VmbCaptureFrameWait\n VmbCaptureQueueFlush\n VmbInterfacesList\n VmbInterfaceOpen\n VmbInterfaceClose\n VmbAncillaryDataOpen\n VmbAncillaryDataClose\n VmbMemoryRead\n VmbMemoryWrite\n VmbRegistersRead\n VmbRegistersWrite\n VmbCameraSettingsSave\n VmbCameraSettingsLoad\n \"\"\"\n global _lib_instance\n getattr(_lib_instance, func_name)(*args)\n\n\ndef build_callback_type(*args):\n global _lib_instance\n\n lib_type = type(_lib_instance)\n\n if lib_type == ctypes.CDLL:\n return ctypes.CFUNCTYPE(*args)\n\n elif lib_type == ctypes.WinDLL:\n return ctypes.WINFUNCTYPE(*args)\n\n else:\n raise VimbaSystemError('Unknown Library Type. Abort.')\n","sub_path":"vimba/c_binding/vimba_c.py","file_name":"vimba_c.py","file_ext":"py","file_size_in_byte":30454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"101763626","text":"from murphy.automation import Feedback\n\nfrom murphy.automation.vnc import VNCFactory, VNCScreen\nfrom murphy.automation.libvirt import LibvirtFactory, LibvirtLoad\nfrom murphy.automation.virtualbox import VirtualboxFactory\nfrom murphy.automation.virtualbox import VirtualboxLoad, VirtualboxScreen\n\n\nclass LibvirtFeedback(Feedback):\n \"\"\"Libvirt based Feedback implementation.\"\"\"\n def __init__(self, vnc_server: str, domain_identifier: (int, str)):\n self._load = None\n self._screen = None\n self._vnc = VNCFactory(vnc_server)\n self._libvirt = LibvirtFactory(domain_identifier)\n\n @property\n def screen(self) -> VNCScreen:\n if self._screen is None:\n self._screen = VNCScreen(self._vnc)\n\n return self._screen\n\n @property\n def load(self) -> LibvirtLoad:\n if self._load is None:\n self._load = LibvirtLoad(self._libvirt)\n\n return self._load\n\n\nclass VirtualboxFeedback(Feedback):\n \"\"\"Virtualbox based Feedback implementation.\"\"\"\n def __init__(self, machine_identifier: str):\n self._load = None\n self._screen = None\n self._virtualbox = VirtualboxFactory(machine_identifier)\n\n @property\n def screen(self) -> VirtualboxScreen:\n if self._screen is None:\n self._screen = VirtualboxScreen(self._virtualbox)\n\n return self._screen\n\n @property\n def load(self) -> VirtualboxLoad:\n if self._load is None:\n self._load = VirtualboxLoad(self._virtualbox)\n\n return self._load\n","sub_path":"murphy/automation/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"423876491","text":"class Solution(object):\n def verifyPreorder(self, preorder):\n \"\"\"\n :type preorder: List[int]\n :rtype: bool\n \"\"\"\n level = -1 << 31\n stack = [] # stack to store candiate levels in the future, they must come from node vals\n for x in preorder:\n if x <= level: # stack[-1] is not the current level\n return False\n while stack and x > stack[-1]:\n level = stack.pop() # remove all smaller numbers\n stack.append(x) # add the final one back, this is the new current level\n return True\n","sub_path":"verify_preorder_seq_in_BST/prac_n_space.py","file_name":"prac_n_space.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"392456174","text":"import sys\n\nimport numpy as np\nfrom fse import IndexedList\nfrom fse.models import SIF\nfrom gensim import matutils\nfrom gensim.models.keyedvectors import KeyedVectors\nfrom sklearn.cluster import KMeans\n\nfrom utils.datas import Data\nfrom utils.util import output\nfrom .chain import Chain_withid\n\ndatapath = '/hri/localdisk/nnabizad/toolpreddata/'\n# sentence_embedding = MeanEmbedding(lang=\"en\")\nsentsembs = dict()\n# simdic = load_obj(datapath + 'ngram-similarities')\nsimdic = dict()\n\ndef cossim(vec1, vec2):\n sim = np.dot(matutils.unitvec(vec1), np.transpose(matutils.unitvec(vec2)))\n return sim\n\n\ndef average_len(l):\n return int(sum(map(len, [i[0] for i in l])) / len(l)) + 1\n\n\nclass Mittul():\n def __init__(self, extracted):\n self.mydata = Data(seed, title=True, extracted=extracted)\n self.sifmodel = self.siftrain()\n self.sent_classes = self.cluster(self.mydata.titles_train, class_number)\n self.write_result()\n\n def write_result(self):\n model = Chain_withid(self.mydata.train, 1)\n self.bigram, self.unigrams = self.creat_table(model)\n preds, acc = self.accu_all(self.mydata.test)\n print('{}, {}, {}'.format(seed, class_number, acc))\n output('{}, {}, {}'.format(seed, class_number, acc), filename=filename, func='write')\n\n def predict(self, lis, id):\n sum = np.zeros([len(self.mydata.decodedic)])\n for clas in range(class_number):\n first = self.unigrams[clas][lis[0]-1]\n for i in range(len(lis)-1):\n first *= self.bigram[clas][lis[i]-1][lis[i+1]-1]\n second = cossim(self.sifembed(self.mydata.titles_test[id]), self.sent_classes.cluster_centers_[clas])\n for t in self.mydata.decodedic:\n first *= self.bigram[clas][lis[-1]-1][t-1]\n sum[t-1] += (first*second)\n # probs[t]= sum\n\n self.prediction = np.argmax(sum)+1\n return self.prediction\n\n def accu_all(self, test):\n corr = total = 0\n preds = []\n for id, manual in enumerate(test):\n # print(id)\n tmppred = []\n oldtool = [1]\n for tool in manual[1:]:\n self.predict(oldtool, id)\n total += 1\n if self.prediction == tool:\n corr += 1\n oldtool.append(tool)\n tmppred.append(self.prediction)\n preds.append(tmppred)\n return preds, (corr) / (total)\n\n def creat_table(self, model):\n bigrams = np.zeros([class_number, len(self.mydata.encodedic), len(self.mydata.encodedic)])\n unigrams = np.zeros([class_number,len(self.mydata.encodedic)])\n for t in model.titles:\n ids = model.titles[t]\n for id in ids:\n title = self.sifembed(self.mydata.titles_train[id])\n p = self.sent_classes.predict(title.reshape(1, -1))[0]\n unigrams[p][t-1] += 1\n for clas in range(class_number):\n unigrams[clas] = self.smooth(unigrams[clas])\n\n for t1 in model.model:\n for t2 in model.model[t1]:\n ids = model.model[t1][t2][1]\n for id in ids:\n title = self.sifembed(self.mydata.titles_train[id])\n p = self.sent_classes.predict(title.reshape(1, -1))[0]\n bigrams[p, t1[0]-1, t2-1] +=1\n\n for clas in range(class_number):\n for t in range(len(bigrams[clas])):\n bigrams[clas][t] = self.smooth(bigrams[clas][t])\n\n return bigrams, unigrams\n \n def smooth(self, lis):\n su = sum(lis)\n if su != 0:\n nonzeros = np.count_nonzero(lis)\n zeros = len(lis) - nonzeros\n if zeros > 0:\n for i in range(len(lis)):\n if lis[i] == 0:\n lis[i] = ((alpha * nonzeros) / zeros) / su\n else:\n lis[i] = (lis[i] - alpha) / su\n else:\n for i in range(len(lis)):\n lis[i]/= su\n else:\n lis = [1 / len(lis) for _ in range(len(lis))]\n return lis\n\n def sifembed(self, text):\n sent = ' '.join(text)\n if sent not in sentsembs:\n sentsembs[sent] = self.sifmodel.infer([(text, 0)])[0]\n return sentsembs[sent]\n\n def siftrain(self):\n glove = KeyedVectors.load(\"/hri/localdisk/nnabizad/w2v/glove100_word2vec1\")\n model = SIF(glove, workers=1, lang_freq=\"en\")\n sentences = IndexedList(self.mydata.titles_train)\n model.train(sentences)\n return model\n\n def cluster(self, sents, class_number):\n X = []\n for text in sents:\n X.append(self.sifembed(text))\n km = KMeans(n_clusters=class_number, init='k-means++', random_state=0)\n kmeans = km.fit(X)\n return kmeans\n\n\nif __name__ == '__main__':\n filename = '/home/nnabizad/code/toolpred/res/Emittul.csv'\n seed = int(sys.argv[1])\n class_number = int(sys.argv[2])\n alpha = 0.001\n print('Training with seed:{}, classes {}'.format(seed, class_number), flush=True)\n Mittul(extracted=True)\n sys.exit()\n","sub_path":"sspace/mittul.py","file_name":"mittul.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"317599253","text":"from System.Windows import Application, Thickness\nfrom System.Windows.Controls import (\n Button, Orientation, TextBlock,\n StackPanel, TextBox\n)\nfrom System.Windows.Input import Key\n\nroot = StackPanel() \ntextblock = TextBlock()\ntextblock.Margin = Thickness(20)\ntextblock.FontSize = 18\ntextblock.Text = 'Stuff goes here'\nroot.Children.Add(textblock)\n\npanel = StackPanel()\npanel.Margin = Thickness(20)\npanel.Orientation = Orientation.Horizontal\n\nbutton = Button()\nbutton.Content = 'Push Me'\nbutton.FontSize = 18\nbutton.Margin = Thickness(10)\n\ntextbox = TextBox()\ntextbox.Text = \"Type stuff here...\"\ntextbox.FontSize = 18\ntextbox.Margin = Thickness(10)\ntextbox.Width = 200\n#textbox.Watermark = 'Type Something Here'\n\ndef onClick(s, e):\n textblock.Text = textbox.Text\n textbox.Text = \"\"\n \ndef onKeyDown(sender, e):\n if e.Key == Key.Enter:\n e.Handled = True\n onClick(None, None)\n \nbutton.Click += onClick\ntextbox.KeyDown += onKeyDown\n\npanel.Children.Add(button)\npanel.Children.Add(textbox)\n\nroot.Children.Add(panel)\nApplication.Current.RootVisual = root\n","sub_path":"trunk/TestA/IronPythonWebAppEx/ex4/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"68991832","text":"\"\"\"\nLab 4\n\"\"\"\nimport re\nfrom ngrams.ngram_trie import NGramTrie\n\n\ndef split_into_sentences(text: str) -> tuple:\n if not isinstance(text, str):\n return ()\n for sign in ['?', '!']:\n text = text.replace(sign, '.') # unify ending symbols\n potential_sentences = re.split(r'\\.\\s', text)\n proven_sentences = []\n solved_indexes = [] # for cases with ambuguous separation\n for index, sentence in enumerate(potential_sentences):\n if index in solved_indexes:\n continue\n try:\n if potential_sentences[index + 1][0].isupper():\n proven_sentences.append(sentence)\n continue\n solved = False\n while not solved:\n index += 1\n sentence += potential_sentences[index]\n try:\n if potential_sentences[index + 1][0].isupper():\n sentence = ' ' + sentence # чтобы потом было удобно парсить слова\n proven_sentences.append(sentence)\n solved = True\n except IndexError:\n proven_sentences.append(sentence)\n solved = True\n solved_indexes.append(index)\n except IndexError:\n proven_sentences.append(sentence)\n return tuple(proven_sentences)\n\n\ndef tokenize_by_words(text: str) -> tuple:\n \"\"\"\n Splits sentences into tokens, converts the tokens into lowercase, removes punctuation\n :param text: the initial text\n :return: a list of lowercased tokens without punctuation\n e.g. text = 'The weather is sunny, the man is happy.'\n --> ['the', 'weather', 'is', 'sunny', 'the', 'man', 'is', 'happy']\n \"\"\"\n for sign in ['?', '!', '.']:\n text = text.replace(sign, ' ')\n text_output = re.sub('[^a-z \\n]', '', text.lower()).split() + ['']\n return tuple(text_output)\n\n\ndef tokenize_by_sentence(text: str) -> tuple:\n if not isinstance(text, str):\n raise ValueError\n if not len(re.findall('[A-Za-z]', text)) > 0:\n return ()\n sentences = split_into_sentences(text)\n tokenized = [tokenize_by_words(sentence) for sentence in sentences]\n result = []\n for sentence in tokenized:\n result += sentence\n return tuple(result)\n\n\nclass WordStorage:\n def __init__(self):\n self.storage = {}\n\n def _put_word(self, word: str):\n if not isinstance(word, str) or len(word) < 1:\n raise ValueError\n if word not in self.storage:\n self.storage[word] = len(self.storage) + 1\n return len(self.storage)\n return self.storage[word]\n\n def get_id(self, word: str) -> int:\n if not isinstance(word, str):\n raise ValueError\n if word not in self.storage:\n raise KeyError\n return self.storage[word]\n\n def get_word(self, word_id: int) -> str:\n if not isinstance(word_id, int):\n raise ValueError\n if word_id not in self.storage.values():\n raise KeyError\n key = None\n for key in self.storage:\n if self.storage[key] == word_id:\n return key\n return key\n\n def update(self, corpus: tuple):\n if not isinstance(corpus, tuple):\n raise ValueError\n for token in corpus:\n self._put_word(token)\n\n\ndef encode_text(storage: WordStorage, text: tuple) -> tuple:\n if not isinstance(text, tuple) or not isinstance(storage, WordStorage):\n raise ValueError\n encoded = [storage.get_id(word) for word in text]\n return tuple(encoded)\n\n\nclass NGramTextGenerator:\n def __init__(self, word_storage: WordStorage, n_gram_trie: NGramTrie):\n # _word_storage is a dictionary { word : word_id }\n # trie includes arguments:\n # trie.n_grams - size of ngrams\n # trie.n_gram_frequencies - {ngram : frequency}\n # trie.uni_grams - {unigram : frequency)\n self._word_storage = word_storage\n self._n_gram_trie = n_gram_trie\n self.public_thing = 'i hope lint will love it'\n\n def _generate_next_word(self, context: tuple) -> int:\n if not isinstance(context, tuple):\n raise ValueError\n if not len(context) == len(self._n_gram_trie.n_grams[0]) - 1:\n raise ValueError\n context = [str(i) for i in context]\n context = ''.join(context)\n chosen = []\n for ngram, freq in self._n_gram_trie.n_gram_frequencies.items():\n ngram = [str(i) for i in ngram]\n ngram = ''.join(ngram)\n if context in ngram[:-1]:\n chosen.append((ngram[-1], freq))\n if len(chosen) > 0:\n chosen.sort(key=lambda x: x[1], reverse=True)\n return int(chosen[0][0])\n unis = list(self._n_gram_trie.uni_grams.items())\n unis.sort(key=lambda x: x[1], reverse=True)\n return int(unis[0][0][0])\n\n def _generate_sentence(self, context: tuple) -> tuple:\n if not isinstance(context, tuple):\n raise ValueError\n if not len(context) == len(self._n_gram_trie.n_grams[0]) - 1:\n raise ValueError\n stop_word = self._word_storage.get_id('')\n sentence = list(context)\n for _ in range(19):\n sentence.append(self._generate_next_word(context))\n if sentence[-1] == stop_word:\n break\n context = tuple(sentence[-len(self._n_gram_trie.n_grams[0]) + 1:])\n if sentence[len(context) - 1] == stop_word:\n sentence = sentence[2:]\n if len(sentence) == 20 and not sentence[-1] == stop_word:\n sentence.append(stop_word)\n return tuple(sentence)\n\n def generate_text(self, context: tuple, number_of_sentences: int) -> tuple:\n if not isinstance(number_of_sentences, int) or not isinstance(context, tuple):\n raise ValueError\n text = []\n for _ in range(number_of_sentences):\n sentence = self._generate_sentence(context)\n context = sentence[-len(self._n_gram_trie.n_grams[0])+1:]\n text += sentence\n return tuple(text)\n\n def another_public_method(self):\n pass\n\n\nclass LikelihoodBasedTextGenerator(NGramTextGenerator):\n\n def _calculate_maximum_likelihood(self, word: int, context: tuple) -> float:\n if not isinstance(context, tuple):\n raise ValueError\n if not len(context) == len(self._n_gram_trie.n_grams[0]) - 1:\n raise ValueError\n try:\n ngram_freq = self._n_gram_trie.n_gram_frequencies[tuple(list(context) + [word])]\n except KeyError:\n return 0.0\n context = [str(i) for i in context]\n context = ''.join(context)\n total = 0\n for ngram, freq in self._n_gram_trie.n_gram_frequencies.items():\n ngram = [str(i) for i in ngram]\n ngram = ''.join(ngram)\n if context in ngram[:-1]:\n total += freq\n return ngram_freq / total\n\n def _generate_next_word(self, context: tuple) -> int:\n if not isinstance(context, tuple):\n raise ValueError\n if not len(context) == len(self._n_gram_trie.n_grams[0]) - 1:\n raise ValueError\n for word in context:\n try:\n self._word_storage.get_word(word)\n except KeyError as key_error:\n raise ValueError from key_error\n\n smart_frequencies = {}\n for word in self._word_storage.storage.values():\n smart_frequencies[word] = self._calculate_maximum_likelihood(word, context)\n if sum(list(smart_frequencies.values())) == 0:\n unis = list(self._n_gram_trie.uni_grams.items())\n unis.sort(key=lambda x: x[1], reverse=True)\n return int(unis[0][0][0])\n items = list(smart_frequencies.items())\n items.sort(key=lambda x: x[1], reverse=True)\n return items[0][0]\n\n\nclass BackOffGenerator(NGramTextGenerator):\n\n def __init__(self, word_storage: WordStorage, n_gram_trie: NGramTrie, *args):\n super().__init__(word_storage, n_gram_trie)\n self._word_storage = word_storage\n self._n_gram_tries = [n_gram_trie] + list(args)\n\n def _generate_next_word(self, context: tuple) -> int:\n if not isinstance(context, tuple):\n raise ValueError\n\n if len(context) < 1:\n unis = list(self._n_gram_trie.uni_grams.items())\n unis.sort(key=lambda x: x[1], reverse=True)\n return int(unis[0][0][0])\n\n trie = None\n for trie in self._n_gram_tries:\n if len(context) == len(trie.n_grams[0]) - 1:\n break\n\n context = [str(i) for i in context]\n context = ''.join(context)\n chosen = []\n for ngram, freq in trie.n_gram_frequencies.items():\n j_ngram = [str(i) for i in ngram]\n j_ngram = ''.join(j_ngram)\n if context in j_ngram[:-1]:\n chosen.append((ngram[-1], freq))\n if len(chosen) > 0:\n chosen.sort(key=lambda x: x[1], reverse=True)\n return int(chosen[0][0])\n return self._generate_next_word(context[1:])\n\n\ndef decode_text(storage: WordStorage, encoded_text: tuple) -> tuple:\n if not isinstance(encoded_text, tuple) or not isinstance(storage, WordStorage):\n raise ValueError\n sentences = []\n sentence = []\n stop_word = storage.get_id('')\n for word in encoded_text:\n if not word == stop_word:\n word = storage.get_word(word)\n sentence.append(word)\n else:\n sentences.append(sentence)\n sentence = []\n sentences = [' '.join([sentence[0][0].upper() + sentence[0][1:]] + sentence[1:]) for sentence in sentences]\n return tuple(sentences)\n\n\ndef save_model(model: NGramTextGenerator, path_to_saved_model: str):\n pass\n\n\ndef load_model(path_to_saved_model: str) -> NGramTextGenerator:\n pass\n","sub_path":"lab_4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"605138509","text":"import logging\n\nlogging.basicConfig(\n level=logging.DEBUG,\n filename='ex1.log',\n filemode='w',\n format='%(asctime)s -- %(levelname)s:%(levelno)s -- %(message)s'\n)\n\ntest_message = 'hello'\n\nlogging.debug(f'debug message : {test_message}')\nlogging.info('info')\nlogging.warning('warning')\nlogging.error('error')\nlogging.critical('critical')\n","sub_path":"week12/todo_project/python-logging/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"291917281","text":"## Program that computes and displays the Scrabble score for a word (ignoring\n# tile bonus.) ##\n\nscrabble = {\n1:[\"A\", \"E\", \"I\", \"L\", \"N\", \"O\", \"R\", \"S\", \"T\", \"U\"],\n2:[\"D\", \"G\"],\n3:[\"B\", \"C\", \"M\", \"P\"],\n4:[\"F\", \"H\", \"V\", \"W\", \"Y\"],\n5:[\"K\"],\n8:[\"J\", \"X\"],\n10:[\"Q\", \"Z\"]\n}\n\ntotal = 0\nword = input(\"Enter a word: \").upper()\n\nfor c in word:\n for num, letters in scrabble.items():\n if c in letters:\n total += num\n\nprint(\"The scrabble score for this word is:\", total)\n","sub_path":"6 Dictionary exercises/Ex_137.py","file_name":"Ex_137.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"387335112","text":"# coding: utf-8\n\nimport bs4\nimport re\nfrom flask import Flask, Response, request\nimport requests\n\napp = Flask(__name__)\n\nTARGET_PATTERN = re.compile(r\"\\b(\\w{6})\\b\", re.U)\nTARGET_HOST = 'habrahabr.ru'\n\n\n@app.route('/')\n@app.route('/')\ndef home(url=''):\n url = 'https://%s/%s' % (TARGET_HOST, url) \\\n if not url.startswith('http') else url\n\n resp = requests.request(\n method=request.method,\n url=url,\n headers={key: value for (key, value) in\n request.headers if key != 'Host'},\n cookies=request.cookies\n )\n\n excluded_headers = ['content-encoding',\n 'content-length',\n 'transfer-encoding',\n 'connection']\n\n headers = [(name, value) for (name, value) in resp.raw.headers.items()\n if name.lower() not in excluded_headers]\n\n # it's a html page?\n if resp.headers.get('content-type') == 'text/html; charset=UTF-8':\n soup = bs4.BeautifulSoup(resp.content, 'html.parser')\n\n # replace links\n for a in soup.findAll('a',\n href=re.compile('^https://%s' % TARGET_HOST)):\n a['href'] = a['href'].replace(\"https://%s\" % TARGET_HOST, '')\n\n # let's find an article\n for article in soup.findAll('div', {'class': 'post'}):\n # now let's find a text block inside the article which contains of\n # words with certain length\n for text_block in article.findAll(text=TARGET_PATTERN):\n # and using lambda with re.sub trying to modify these words in\n # each text block\n modified_text_block = re.sub(\n TARGET_PATTERN, lambda x: x.group() + '\\u2122',\n text_block.string\n )\n # replace the old block\n text_block.replace_with(modified_text_block)\n\n return Response(soup.encode(formatter=None), resp.status_code, headers)\n\n return Response(resp.content, resp.status_code, headers)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"habraproxy/standalone_proxy_server/habraproxyserver.py","file_name":"habraproxyserver.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"297347388","text":"from django.http import HttpResponse\n\nfrom .models import Tuote\n\nETUSIVU_HTML = \"\"\"\n\n\n

Kauppa

\nOsta täältä\n
\n{}\n\n\n\"\"\"\n\n\n\ndef etusivu(request):\n tuotelinkit = []\n for tuote in Tuote.objects.all():\n linkki = '{nimi}'.format(\n id=tuote.id,\n nimi=tuote.nimi,\n )\n # linkki = f'{tuote.nimi}' # Toinen esim\n tuotelinkit.append(linkki)\n linkkiteksti = '
'.join(tuotelinkit)\n return HttpResponse(ETUSIVU_HTML.format(linkkiteksti))\n\n\ndef tuotesivu(request, tuote_id):\n tuotteet = Tuote.objects.filter(id=tuote_id)\n tuote = tuotteet.get()\n print(tuote)\n print(tuotteet)\n return HttpResponse(TUOTESIVU_HTML.format(\n nimi=tuote.nimi,\n hinta=tuote.hinta\n ))\n\n\nTUOTESIVU_HTML = \"\"\"\n\n\n

Kauppa

\n

{nimi}

\n{hinta} € \n

\nNyt tarjouksessa. Osta heti!\n

\n

\n[etusivu]\n

\n\n\n\"\"\"","sub_path":"kauppa/kauppa/views2.py","file_name":"views2.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"328638925","text":"# Open the js0 device as if it were a file in read mode.\nimport serial\nimport time\nser = serial.Serial('/dev/ttyUSB0', 9600)\nser.flush()\n\npipe = open('/dev/input/js0', 'r')\n\n# Create an empty list to store read characters.\nmsg = []\n\n# Loop forever.\nwhile 1:\n # For each character read from the /dev/input/js0 pipe...\n for char in pipe.read(1):\n \n # append the integer representation of the unicode character read to the msg list.\n msg += [ord(char)]\n \n # If the length of the msg list is 8...\n if len(msg) == 8:\n\n if msg[6] == 2:\n if (msg[7] == 1 or msg[7] == 0):\n dataString = str(msg[7]) + ',' + str(msg[5])\n ser.write(dataString)\n ser.write('\\n')\n #receivedmsg = ser.readline()\n #print receivedmsg\n print(dataString)\n ser.flush()\n \n # Reset msg as an empty list.\n msg = []","sub_path":"Battlebot/pneumatic_battlebot/write_js.py","file_name":"write_js.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"37057546","text":"import json, sys, os, shutil, http.client\nfrom urllib import request, error, parse, robotparser\nfrom datetime import *\nfrom Penalty import *\nfrom DatabaseManager import *\nimport ssl\n\ndef formatDate(*args):\n '''\n Looks at the system to determine the date\n Converts the date to the proper format...\n\n This is to safe guard the NHL changing the date format again.\n\n DateTimes format is YYYY-MM-DD\n Returns: String in the format of YYYY-MM-DD\n '''\n if len(args) == 0: #This allows me to specify dates for testing / in case the script misses a date.\n today = date.today()- timedelta(1)\n dateAsString = str(today)\n else:\n dateAsString = args[0]\n return dateAsString\n\ndef processGame(game, date):\n '''\n This function will parse game URL's JSON Stream.\n\n Inputs:\n game - string - This is the URL of the game.\n date - The date of the game.\n\n Returns:\n gamePenaltyList - List of Penalty Objects - This is the list of penalties that occur during the game.\n '''\n #Establishing and clearing the list of Penalties\n gamePenaltyList = []\n gamePenaltyList[:] = []\n\n #Getting the JSON data from the NHL website\n context = ssl._create_unverified_context()\n response = request.urlopen(game, context=context).read().decode('UTF-8')\n jsonData = json.loads(response)\n\n #Added a special case for Montreal because they have an accent.\n awayTeam = jsonData[\"gameData\"][\"teams\"][\"away\"][\"name\"]\n if (awayTeam.lower().find(\"canadiens\") != -1):\n awayTeam = \"Montreal Canadiens\"\n homeTeam = jsonData[\"gameData\"][\"teams\"][\"home\"][\"name\"]\n if (homeTeam.lower().find(\"canadiens\") != -1):\n homeTeam = \"Montreal Canadiens\"\n\n #Establishing and clearing the list of Referees\n refs = []\n refs[:] = []\n\n #Getting the referees for the game.\n for i in jsonData[\"liveData\"][\"boxscore\"][\"officials\"]:\n if i[\"officialType\"].lower() == \"referee\":\n refs.append(i[\"official\"][\"fullName\"])\n\n #Getting the Penalty Data from the JSON stream.\n penaltyPlays = []\n penaltyPlays[:] = []\n for i in jsonData[\"liveData\"][\"plays\"][\"penaltyPlays\"]:\n penaltyPlays.append(i)\n for j in penaltyPlays:\n penaltyEvent = jsonData[\"liveData\"][\"plays\"][\"allPlays\"][j]\n playerName = penaltyEvent[\"players\"][0][\"player\"][\"fullName\"]\n penaltyName = penaltyEvent[\"result\"][\"secondaryType\"]\n playerTeamName = penaltyEvent[\"team\"][\"name\"]\n if (playerTeamName.lower().find(\"canadiens\") != -1):\n playerTeamName = \"Montreal Canadiens\"\n\n if playerTeamName == awayTeam:\n location = False\n opponentTeamName = homeTeam\n else:\n location = True\n opponentTeamName = awayTeam\n\n #Checking to see if it was a penalty shot. At this time, the NHL does not consider Penalty Shots to count towards the team totals.\n if \"PS-\" not in penaltyName and \"PS - \" not in penaltyName:\n newPenalty = Penalty(playerName, playerTeamName, penaltyName, location, opponentTeamName, date, refs)\n gamePenaltyList.append(newPenalty)\n\n return gamePenaltyList\n\n\ndef getData(date):\n '''\n Looks for game entries on the NHL data stream\n Ideally it is looking for the \"live\" link because that contains all the penalty data.\n\n Input param : String : Formatted by the \"formatDate\"\n '''\n beginning_url = \"https://statsapi.web.nhl.com/api/v1/schedule?startDate=\"\n middle_url=\"&endDate=\"\n end_url=\"&expand=schedule.teams,schedule.linescore,schedule.broadcasts,schedule.ticket,schedule.game.content.media.epg&leaderCategories=&site=en_nhl&teamId=\"\n full_url = beginning_url + date + middle_url + date + end_url\n\n gameDataURLprefix = \"https://statsapi.web.nhl.com\"\n\n try:\n context = ssl._create_unverified_context()\n websiteData = request.urlopen(full_url, context=context).read().decode('UTF-8')\n jsonData = json.loads(websiteData)\n except:\n print(\"Error\")\n sys.exit(-1) #If we can't load the page, exit with an error.\n\n gameURLS = [] # This list is going to contain the URLs pointing to games as strings.\n gameURLS[:] = []\n try:\n numberOfDates = len(jsonData['dates'])\n for date in range(0, numberOfDates):\n gameDay = jsonData['dates'][date][\"date\"]\n for i in jsonData['dates'][date]['games']:\n gameURLS.append( (gameDataURLprefix + i[\"link\"], gameDay) )\n except IndexError:\n # If there are no games, there is no sense in updating anything, so it should exit.\n print(\"No games today!\")\n sys.exit(0)\n\n return gameURLS\n\ndef run(**kwargs):\n if \"dbLoc\" not in kwargs:\n dbLoc = \"/home/roymond/Website/RoymondNET/PenaltyTracker/static/penaltytracker/season.db\"\n else:\n dbLoc = kwargs[\"dbLoc\"]\n\n if \"timePeriod\" not in kwargs:\n timePeriod = \"Regular_19_20\"\n else:\n timePeriod = kwargs[\"timePeriod\"]\n\n #Create the DatabaseManager\n dbManager = DatabaseManager(dbLoc, timePeriod)\n\n if \"date\" in kwargs:\n date = formatDate( kwargs[\"date\"] )\n else:\n date = formatDate()\n\n gameURLS = getData(date)\n if ( len(gameURLS) ) > 0:\n for game in gameURLS:\n gameURL = game[0]\n date = game[1]\n penaltyList = processGame(gameURL,date)\n for penalty in penaltyList:\n dbManager.insertData(penalty.formatForSQL())\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"PenaltyTracker.py","file_name":"PenaltyTracker.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"80944622","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Note\nfrom .forms import NoteModelForm\n# Create your views here.\ndef note_list_view(request):\n form = NoteModelForm()\n if request.method == \"POST\":\n form = NoteModelForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('notes')\n todo_list = Note.objects.filter(finished=False)\n finished_list = Note.objects.filter(finished=True)\n context = {\n \"todo_list\": todo_list,\n \"finished_list\": finished_list,\n 'form': form\n }\n return render(request, \"note_list.html\", context)\n\ndef finish_item(request, id):\n todo = get_object_or_404(Note, id=id)\n print(todo)\n todo.finished = True\n todo.label = 'S'\n todo.save()\n return redirect('notes')\n\ndef uncheck_item(request, id):\n todo = get_object_or_404(Note, id=id)\n print(todo)\n todo.finished = False\n todo.label = 'SE'\n todo.save()\n return redirect('notes')\n\ndef delete_item(request, id):\n todo = get_object_or_404(Note, id=id)\n todo.delete()\n return redirect('notes')","sub_path":"src/notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"542398984","text":"\"\"\"\n测试各种小功能模块用的\n\n\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\nfrom BikeNN import BikeNetWork\n\n# ==========1 观察数据==========\n\n\ndata_path = 'Bike-Sharing-Dataset/hour.csv'\nrides = pd.read_csv(data_path) # 给一个csv的路径即可\n# rides[:24*10].plot(x='dteday',y='cnt')\n# plt.show()\n# 转换成one-hot编码的变量,把非连续变量转换成01的编码\ndummy_fields = ['season','weathersit','mnth','hr','weekday']\nfor each in dummy_fields:\n dummies = pd.get_dummies(rides[each],prefix=each,drop_first=False)\n rides = pd.concat([rides,dummies],axis=1)\n\nfields_to_drop = ['instant', 'dteday', 'season', 'weathersit',\n 'weekday', 'atemp', 'mnth', 'workingday', 'hr']\ndata = rides.drop(fields_to_drop,axis=1)\nprint(data.head())\n\n# 标准化每个连续变量,均值为0,标准差为1\nquant_features = ['casual','registered','cnt','temp','hum','windspeed']\nscaled_features = {}\nfor each in quant_features:\n mean,std = data[each].mean(),data[each].std()\n scaled_features[each] = [mean,std]\n data.loc[:,each] = (data[each]-mean)/std\n\n# 拆分训练集、测试集(最后21天)、验证集\ntest_data = data[-21*24:]\ndata = data[:-21*24]\n\n# 数据拆分成特征features和targets\ntargets_fields = ['cnt','casual','registered'] #target fields [租赁自行车给的总用户数,临时用户数,注册用户数]\nfeatures,targets = data.drop(targets_fields,axis=1),data[targets_fields]\ntest_features,test_targets = test_data.drop(targets_fields,axis=1),test_data[targets_fields]\n\n# 再将训练集中的数据拆分成训练集和验证集,因为数据是有时间序列的,所以用历史数据训练,尝试预测未来的验证集\ntrain_features,train_targets = features[:-60*24], targets[:-60*24]\nval_features,val_targets = features[-60*24:], targets[-60*24:]\n\n# print(train_features.head())\n# print(train_targets.head())\n\n# ==========2 构建网络==========\n# 见BikeNN\n\n# ==========3 训练网络==========\n\ndef MSE(y, Y):\n return np.mean((y-Y)**2)\n\niterations = 2000\nlearning_rate = 0.8\nhidden_nodes = 12\noutput_nodes = 1\n\nN_i = train_features.shape[1]\nnetwork = BikeNetWork(input_nodes=N_i,hidden_nodes=hidden_nodes,\n output_nodes=output_nodes,learning_rate=learning_rate)\nlosses = {'train':[],'validation':[]}\nfor ii in range(iterations):\n batch = np.random.choice(train_features.index,size=128)\n X,y = train_features.ix[batch].values,train_targets.ix[batch]['cnt']\n\n network.train(X,y)\n\n # Printing out the training progress\n train_loss = MSE(network.run(train_features).T, train_targets['cnt'].values)\n val_loss = MSE(network.run(val_features).T, val_targets['cnt'].values)\n sys.stdout.write(\"\\rProgress: {:2.1f}\".format(100 * ii / float(iterations)) \\\n + \"% ... Training loss: \" + str(train_loss)[:5] \\\n + \" ... Validation loss: \" + str(val_loss)[:5])\n sys.stdout.flush()\n\n losses['train'].append(train_loss)\n losses['validation'].append(val_loss)\n\n\nplt.plot(losses['train'], label='Training loss')\nplt.plot(losses['validation'], label='Validation loss')\nplt.legend()\n_ = plt.ylim()\nplt.show()","sub_path":"01BikeShareProject/run_codes.py","file_name":"run_codes.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"290477890","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\nimport paramiko\nclass sshconnet(object):\n\tdef __init__(self,host,port,name,pkey):\n\t\tself.host=host\n\t\tself.port=port\n\t\tself.name=name\n\t\tself.pkey=pkey\n\t\tself.ssh=paramiko.SSHClient()\n\t\tself.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\t\tself.ssh.connect(self.host, self.port,self.name,self.pkey)\n\tdef ifconfig(self):\n\t\tstdin,stdout,stderr=self.ssh.exec_command('ifconfig')\n\t\tres_out = stdout.read()\n\t\tprint(res_out.decode())\n#\t\tself.ssh.close()\n\tdef ls(self):\n\t\tstdin,stdout,stderr=self.ssh.exec_command('ls -l')\n\t\tres_out = stdout.read()\n\t\tprint(res_out.decode())\n#\t\tself.ssh.close()\ntest=sshconnet('192.168.3.217','22','root','/root/.ssh/id_rsa')\ntest.ifconfig()\ntest.ls()\n","sub_path":"class/ssh.py","file_name":"ssh.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"140500675","text":"import sys\nsys.path.insert(0, '../..')\n\nimport generatorUtils as gu\nimport random\nfrom base import Decision\n\nclass Program(Decision):\n\tdef registerChoices(self):\n\t\t'''\n\t\tWe add a dummy RV with only one value \n\t\tto make the RNN code easier.\n\t\t'''\t\t\t\t\n\t\tself.addChoice(self.ROOT_RV_NAME, {\n\t\t\tself.ROOT_RV_VAL: 1\n\t\t})\n\n\tdef renderCode(self):\n\t\t# a few data lists that other expands could add to\n\t\tself.addState('methodList', [])\n\t\tself.addState('constants', {})\n\t\tself.addState('instanceVars', [])\n\n\t\t# this is an example of rendering out of order\n\t\t# you need to expand methods first (and in particular)\n\t\t# the run method. Then you can expand ivars etc\n\t\ttemplateVars = {\n\t\t\t'Solution':self.expand('Solution'),\n\t\t\t'HelperMethods':self.expand('HelperMethods'),\n\t\t\t'Constants':self.expand('Constants')\n\t\t}\n\t\ttemplate = '''\n\t\t\t{Constants}\n\t\t\tpublic void run() {{\n\t\t\t\t{Solution}\n\t\t\t}}\n\t\t\t{HelperMethods}\n\t\t'''\n\t\treturn gu.format(template, templateVars)","sub_path":"src/rubricsampling/grammars/drawCircles/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"599089338","text":"#!/usr/bin/env python3\nimport tkinter as tk\nimport pickle\nimport os.path\nimport os\nimport time, datetime\nimport csv\n\nfrom datetime import date\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\ndefault_font = \"Times 16\"\nsecondary_font = \"Times 14\"\n\nclass GCal:\n\n fn_pickle = 'token.pickle'\n fn_credentials = 'credentials.json'\n service = None\n SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']\n\n def check_token_existance(self):\n creds = None\n if os.path.exists(self.fn_pickle):\n with open(self.fn_pickle, 'rb') as token:\n creds = pickle.load(token)\n\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(fn_credentials, self.SCOPES)\n creds = flow.run_local_server()\n with open(self.fn_pickle, 'wb') as token:\n pickle.dump(creds, token)\n\n self.service = build('calendar', 'v3', credentials=creds)\n\n def fetch_events(self, n):\n page_token = None\n id = 'primary' # defaults to primary calendar\n calendar_list = self.service.calendarList().list(pageToken=page_token).execute()\n for calendar_list_entry in calendar_list['items']:\n # print(calendar_list_entry['summary'])\n if calendar_list_entry['summary'] == \"TestDev1\": # retrieves the ID of the calendar\n id = calendar_list_entry['id']\n # print(calendar_list_entry['summary'])\n\n now = datetime.datetime.utcnow().isoformat() + 'Z'\n # print(\"Fetching {} events.\".format(n))\n events_result = self.service.events().list(\n calendarId=id,\n timeMin = now,\n maxResults = n,\n singleEvents = True,\n orderBy = 'startTime'\n ).execute()\n\n return events_result.get('items', [])\n\nclass Window(tk.Frame):\n\n def __init__(self, master=None):\n super().__init__(master)\n super().grid(sticky=tk.N+tk.S+tk.E+tk.W)\n self.master = master\n master.columnconfigure(0, weight=1)\n master.rowconfigure(0, weight=1)\n\n # Find today's date\n self.today = date.today()\n self.new_today = self.today.strftime(\"%Y-%m-%dT00:00:00-04:00\")\n self.default_today = self.today.strftime(\"%Y-%m-%dT88:88:88-04:00\")\n\n # Create text file\n self.write_file = open(\"file1.txt\", \"w+\")\n\n # Set up all frames\n fr_tasks = tk.Frame(self)\n fr_tasks.grid(padx=5, pady=5, row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\n fr_today = tk.Frame(self)\n fr_today.grid(padx=5, pady=5, row=0, column=1, sticky=tk.N+tk.S+tk.E+tk.W)\n\n fr_tasks.rowconfigure(0, weight=5)\n fr_tasks.columnconfigure(0, weight=1)\n\n fr_form = tk.Frame(fr_tasks)\n fr_form.grid(padx=5, pady=5, row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\n fr_tasks_list = tk.Frame(fr_tasks)\n fr_tasks_list.grid(padx=5, pady=5, row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)\n\n fr_notes = tk.Frame(self)\n fr_notes.grid(padx=5, pady=5, row=1, sticky=tk.N+tk.S+tk.E+tk.W)\n\n self.columnconfigure(0, weight=5)\n self.columnconfigure(1, weight=3)\n self.rowconfigure(0, weight=1)\n\n # ---------------------------------------------------------------------------\n # Right side - Today tasks\n l_today = tk.Label(fr_today, text='Today', font=default_font)\n l_today.pack(side='top', fill=tk.X)\n\n scrollbar = tk.Scrollbar(fr_today)\n scrollbar.pack(side='right', fill='y')\n\n self.lb_today = tk.Listbox(fr_today, yscrollcommand=scrollbar.set, font=secondary_font)\n self.lb_today.pack(fill=tk.BOTH, expand=True)\n\n # ---------------------------------------------------------------------------\n # Left side - Tasks list\n l_tasks_list = tk.Label(fr_tasks_list, text='Tasks', font=default_font)\n l_tasks_list.pack(side='top', fill=tk.X)\n\n scrollbar = tk.Scrollbar(fr_tasks_list)\n scrollbar.pack(side='right', fill='y')\n\n self.lb_tasks = tk.Listbox(fr_tasks_list, yscrollcommand=scrollbar.set, font=secondary_font)\n self.lb_tasks.pack(fill=tk.BOTH, expand=True)\n\n # ---------------------------------------------------------------------------\n # Entry form\n fr_form.columnconfigure(1, weight=1)\n\n tk.Label(fr_form, text='TYPE*', font=default_font).grid(row=0, sticky=tk.W+tk.E)\n self.type_input = tk.StringVar(self)\n self.type_input.set(\"\")\n self.om_type = tk.OptionMenu(fr_form, self.type_input, \"Event\", \"Reminder\")\n self.om_type.grid(row=0, column=1, sticky=tk.W+tk.E)\n\n tk.Label(fr_form, text='TASK*', font=default_font).grid(row=1, sticky=tk.W+tk.E)\n self.e_task_name = tk.Entry(fr_form, font=default_font)\n self.e_task_name.grid(row=1, column=1, sticky=tk.W+tk.E)\n\n tk.Label(fr_form, text='TAGS*', font=default_font).grid(row=2, sticky=tk.W+tk.E)\n self.e_tags = tk.Entry(fr_form, font=default_font)\n self.e_tags.grid(row=2, column=1, sticky=tk.W+tk.E)\n\n tk.Label(fr_form, text='START', font=default_font).grid(row=3, sticky=tk.W+tk.E)\n self.e_st_time = tk.Entry(fr_form, font=default_font)\n self.e_st_time.grid(row=3, column=1, sticky=tk.W+tk.E)\n\n tk.Label(fr_form, text='END', font=default_font).grid(row=4, sticky=tk.W+tk.E)\n self.e_end_time = tk.Entry(fr_form, font=default_font)\n self.e_end_time.grid(row=4, column=1, sticky=tk.W+tk.E)\n\n tk.Button(fr_form, text='OK', command=self.create_event, font=default_font).grid(row=5, sticky=tk.W)\n tk.Button(fr_form, text='Refresh', command=self.update_event, font=default_font).grid(row=5, column=1, sticky=tk.E)\n\n tk.Label(fr_notes, text='Please note: ', font=default_font).grid(row=0, column=0, sticky=tk.W+tk.N)\n tk.Label(fr_notes, text='* These fields are REQUIRED\\n \\'Start\\' and \\'End\\' are optional', font=default_font).grid(row=0, column=1, sticky=tk.W)\n\n # ---------------------------------------------------------------------------\n # Google Calendar object\n self.g = GCal()\n self.g.check_token_existance()\n self.add_events(self.g.fetch_events(20))\n\n def add_events(self, events): # from Google Calendar\n for e in events:\n start = e['start'].get('dateTime', e['start'].get('date'))\n end = e['end'].get('dateTime', e['end'].get('date'))\n s = start + '\\t' + end + '\\t' + e['summary']\n print(s)\n # Format is XXXX-XX-XX (Year-Month-Day)\n if start[0:10] == '2019-05-08': # self.new_today[0:10]:\n self.lb_today.insert(tk.END, self.get_start_time2(s) + ' - ' + self.get_end_time2(s) + ': ' + e['summary'])\n self.write_file.write(s + '\\n')\n self.write_file.flush()\n\n def create_event(self): # from User Input\n s_type = self.type_input.get()\n s_task = self.e_task_name.get()\n s_st_time = self.e_st_time.get()\n s_end_time = self.e_end_time.get()\n self.send_line = \"\"\n if s_type == \"Event\":\n s_tags = \"#event \" + self.e_tags.get()\n if s_st_time != \"\":\n if s_end_time != \"\":\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) Start time: {} End time: {}'.format(s_type, s_task, s_tags, s_st_time, s_end_time))\n self.send_line = self.time_template(s_st_time) + '\\t' + self.time_template(s_end_time) + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) Start time: {}'.format(s_type, s_task, s_tags, s_st_time))\n self.send_line = self.time_template(s_st_time) + '\\t' + self.default_today + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n if s_end_time != \"\":\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) End time: {}'.format(s_type, s_task, s_tags, s_end_time))\n self.send_line = self.default_today + '\\t' + self.time_template(s_end_time) + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {})'.format(s_type, s_task, s_tags))\n self.send_line = self.default_today + '\\t' + self.default_today + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n s_tags = \"#reminder \" + self.e_tags.get()\n if s_st_time != \"\":\n if s_end_time != \"\":\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) Start time: {} End time: {}'.format(s_type, s_task, s_tags, s_st_time, s_end_time))\n self.send_line = self.time_template(s_st_time) + '\\t' + self.time_template(s_end_time) + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) Start time: {}'.format(s_type, s_task, s_tags, s_st_time))\n self.send_line = self.time_template(s_st_time) + '\\t' + self.default_today + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n if s_end_time != \"\":\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {}) End time: {}'.format(s_type, s_task, s_tags, s_end_time))\n self.send_line = self.default_today + '\\t' + self.time_template(s_end_time) + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n else:\n self.lb_tasks.insert(tk.END, '{}: {} (Tag: {})'.format(s_type, s_task, s_tags))\n self.send_line = self.default_today + '\\t' + self.default_today + '\\t' + '{}\\t(Tag: {}) \\n'.format(s_task, s_tags)\n self.write_file.write(self.send_line)\n self.write_file.flush()\n self.clear_text()\n\n def update_event(self):\n __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n # f = open(os.path.join(__location__, 'Makefile'))\n #print(__location__)\n #os.system(\"ls\")\n # HELP HELP HELP\n os.system('make run')\n #\n # os.system('make clean')\n\n read_file = open(\"file2.txt\", \"r\")\n self.delete_event()\n temp = read_file.readlines()\n for x in temp:\n if(len(x) != 1):\n start_time = self.get_start_time2(x)\n end_time = self.get_end_time2(x)\n event_name = self.get_event_name(x)\n returnable = start_time + ' - ' + end_time + ': ' + event_name\n self.lb_today.insert(tk.END, returnable)\n\n def delete_event(self):\n for i in range(self.lb_today.size()):\n # print(i)\n self.lb_today.delete(0)\n\n def get_start_time(self, time_string):\n return time_string[11:19]\n\n def get_end_time(self, time_string):\n return time_string[37:45]\n\n def get_start_time2(self, time_string):\n return time_string[11:16]\n\n def get_end_time2(self, time_string):\n return time_string[37:42]\n\n def get_event_name(self, time_string):\n return time_string[52:len(time_string)-1]\n\n def time_template(self, time_string):\n return self.today.strftime(\"%Y-%m-%dT\" + time_string + \":00-04:00\")\n\n def clear_text(self):\n self.type_input.set(\"\")\n self.e_task_name.delete(0, 'end')\n self.e_tags.delete(0, 'end')\n self.e_st_time.delete(0, 'end')\n self.e_end_time.delete(0, 'end')\n\ndef main():\n root = tk.Tk()\n root.geometry(\"1100x600\")\n root.title(\"Calendar App\")\n app = Window(root)\n\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Test_Run/prog.py","file_name":"prog.py","file_ext":"py","file_size_in_byte":12057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"137668040","text":"import os\nimport subprocess\n\nfrom django.conf import settings\nfrom django.core.files import File\n\nfrom wagtail import VERSION as WAGTAIL_VERSION\n\n\nif WAGTAIL_VERSION < (2, 5):\n from wagtail.utils.pagination import paginate\nelse:\n from django.core.paginator import Paginator\n\n DEFAULT_PAGE_KEY = \"p\"\n\n def paginate(request, items, page_key=DEFAULT_PAGE_KEY, per_page=20):\n paginator = Paginator(items, per_page)\n page = paginator.get_page(request.GET.get(page_key))\n return paginator, page\n\n\ndef convert_gif(media):\n # 1) save the FieldFile data as a temp file for ffmpeg\n tmp_src_path = os.path.join(settings.WAGTAILMEDIA_TMP_DIRECTORY, media.filename)\n with open(tmp_src_path, \"wb+\") as tmp_src_file:\n for chunk in media.file.chunks():\n tmp_src_file.write(chunk)\n\n # 2) run ffmpeg to convert the .gif into an .mp4 temp video file\n mp4_name = os.path.splitext(media.filename)[0] + \".mp4\"\n tmp_dest_path = os.path.join(settings.WAGTAILMEDIA_TMP_DIRECTORY, mp4_name)\n process = [\n \"ffmpeg\",\n \"-y\",\n \"-i\",\n tmp_src_path,\n \"-b:v\",\n \"500k\",\n \"-crf\",\n \"25\",\n \"-f\",\n \"mp4\",\n \"-vcodec\",\n \"libx264\",\n \"-pix_fmt\",\n \"yuv420p\",\n \"-vf\",\n \"scale=trunc(iw/2)*2:trunc(ih/2)*2\",\n tmp_dest_path,\n ]\n subprocess.run(process)\n\n # 3) save a copy of the temp video file in the correct django storage location\n # by associating it with the model\n media.file = File(open(tmp_dest_path, \"rb\"))\n media.file.name = mp4_name\n\n # 4) delete temp files\n os.unlink(tmp_src_path)\n os.unlink(tmp_dest_path)\n","sub_path":"wagtailmedia/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"524998068","text":"# File: t (Python 2.2)\n\nfrom direct.showbase.ShowBaseGlobal import *\nfrom toontown.distributed.ToontownMsgTypes import *\nfrom otp.otpbase import OTPGlobals\nfrom direct.directnotify import DirectNotifyGlobal\nfrom direct.showbase import PandaObject\nfrom direct.fsm import StateData\nfrom direct.fsm import ClassicFSM\nfrom direct.fsm import State\nimport ZoneUtil\n\nclass QuietZoneState(PandaObject.PandaObject, StateData.StateData):\n notify = DirectNotifyGlobal.directNotify.newCategory('QuietZoneState')\n \n def __init__(self, doneEvent):\n StateData.StateData.__init__(self, doneEvent)\n self.fsm = ClassicFSM.ClassicFSM('QuietZoneState', [\n State.State('off', self.enterOff, self.exitOff, [\n 'waitForQuietZoneResponse']),\n State.State('waitForQuietZoneResponse', self.enterWaitForQuietZoneResponse, self.exitWaitForQuietZoneResponse, [\n 'waitForZoneRedirect']),\n State.State('waitForZoneRedirect', self.enterWaitForZoneRedirect, self.exitWaitForZoneRedirect, [\n 'waitForSetZoneResponse']),\n State.State('waitForSetZoneResponse', self.enterWaitForSetZoneResponse, self.exitWaitForSetZoneResponse, [\n 'waitForSetZoneComplete']),\n State.State('waitForSetZoneComplete', self.enterWaitForSetZoneComplete, self.exitWaitForSetZoneComplete, [\n 'off'])], 'off', 'off')\n self.fsm.enterInitialState()\n\n \n def load(self):\n self.notify.debug('load()')\n\n \n def unload(self):\n self.notify.debug('unload()')\n del self.fsm\n\n \n def enter(self, requestStatus):\n self.notify.debug('enter(requestStatus=' + str(requestStatus) + ')')\n base.transitions.fadeScreen(1.0)\n self.fsm.request('waitForQuietZoneResponse', [\n requestStatus])\n\n \n def exit(self):\n self.notify.debug('exit()')\n base.transitions.noFade()\n self.fsm.request('off')\n\n \n def handleWaitForQuietZoneResponse(self, msgType, di):\n self.notify.debug('handleWaitForQuietZoneResponse(' + 'msgType=' + str(msgType) + ', di=' + str(di) + ')')\n if msgType == CLIENT_GET_STATE_RESP:\n di.skipBytes(12)\n zoneId = di.getUint32()\n if zoneId == OTPGlobals.QuietZone:\n self.fsm.request('waitForZoneRedirect', [\n base.cr.handlerArgs])\n \n elif msgType == CLIENT_CREATE_OBJECT_REQUIRED:\n base.cr.handleQuietZoneGenerateWithRequired(di)\n elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:\n base.cr.handleQuietZoneGenerateWithRequiredOther(di)\n elif msgType in QUIET_ZONE_IGNORED_LIST:\n self.notify.debug('ignoring unwanted message from previous zone')\n else:\n base.cr.handlePlayGame(msgType, di)\n\n \n def handleWaitForZoneRedirect(self, msgType, di):\n self.notify.debug('handleWaitForZoneRedirect(' + 'msgType=' + str(msgType) + ', di=' + str(di) + ')')\n if msgType == CLIENT_CREATE_OBJECT_REQUIRED:\n base.cr.handleQuietZoneGenerateWithRequired(di)\n elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:\n base.cr.handleQuietZoneGenerateWithRequiredOther(di)\n else:\n base.cr.handlePlayGame(msgType, di)\n\n \n def handleWaitForSetZoneResponse(self, msgType, di):\n self.notify.debug('handleWaitForSetZoneResponse(' + 'msgType=' + str(msgType) + ', di=' + str(di) + ')')\n if msgType == CLIENT_GET_STATE_RESP:\n di.skipBytes(12)\n zoneId = di.getUint32()\n wantZoneId = base.cr.handlerArgs['zoneId']\n if zoneId == wantZoneId:\n self.notify.debug('handleWaitForSetZoneResponse: response for zoneId: %s' % zoneId)\n self.fsm.request('waitForSetZoneComplete', [\n base.cr.handlerArgs])\n else:\n self.notify.warning('handleWaitForSetZoneResponse: unwanted zoneId: %s, waiting for: %s' % (zoneId, wantZoneId))\n elif msgType == CLIENT_CREATE_OBJECT_REQUIRED:\n base.cr.handleQuietZoneGenerateWithRequired(di)\n elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:\n base.cr.handleQuietZoneGenerateWithRequiredOther(di)\n else:\n base.cr.handlePlayGame(msgType, di)\n\n \n def handleWaitForSetZoneComplete(self, msgType, di):\n self.notify.debug('handleWaitForSetZoneComplete(' + 'msgType=' + str(msgType) + ', di=' + str(di) + ')')\n if msgType == CLIENT_DONE_SET_ZONE_RESP:\n zoneId = di.getUint32()\n wantZoneId = base.cr.handlerArgs['zoneId']\n if zoneId == wantZoneId:\n self.notify.debug('handleWaitForSetZoneComplete: completed zoneId: %s' % zoneId)\n base.localAvatar.startChat()\n messenger.send('setZoneComplete', [\n zoneId])\n messenger.send(self.doneEvent)\n else:\n self.notify.warning('handleWaitForSetZoneComplete: unwanted zoneId: %s, waiting for: %s' % (zoneId, wantZoneId))\n else:\n base.cr.handlePlayGame(msgType, di)\n\n \n def enterOff(self):\n self.notify.debug('enterOff()')\n\n \n def exitOff(self):\n self.notify.debug('exitOff()')\n\n \n def enterWaitForQuietZoneResponse(self, doneStatus):\n self.notify.debug('enterWaitForQuietZoneResponse(doneStatus=' + str(doneStatus) + ')')\n base.cr.handler = self.handleWaitForQuietZoneResponse\n base.cr.handlerArgs = doneStatus\n base.cr.sendQuietZoneRequest()\n\n \n def exitWaitForQuietZoneResponse(self):\n self.notify.debug('exitWaitForQuietZoneResponse()')\n base.cr.handler = base.cr.handlePlayGame\n base.cr.handlerArgs = None\n\n \n def enterWaitForZoneRedirect(self, requestStatus):\n self.notify.debug('enterWaitForZoneRedirect(requestStatus=' + str(requestStatus) + ')')\n base.cr.handler = self.handleWaitForZoneRedirect\n base.cr.handlerArgs = requestStatus\n zoneId = requestStatus['zoneId']\n avId = requestStatus.get('avId', -1)\n allowRedirect = requestStatus.get('allowRedirect', 1)\n if avId != -1:\n allowRedirect = 0\n \n if not (base.cr.welcomeValleyManager):\n newZoneId = ZoneUtil.getCanonicalZoneId(zoneId)\n if newZoneId != zoneId:\n self.gotZoneRedirect(newZoneId)\n return None\n \n \n if allowRedirect and ZoneUtil.isWelcomeValley(zoneId):\n self.notify.info('Requesting AI redirect from zone %s.' % zoneId)\n base.cr.welcomeValleyManager.requestZoneId(zoneId, self.gotZoneRedirect)\n else:\n self.fsm.request('waitForSetZoneResponse', [\n base.cr.handlerArgs])\n\n \n def gotZoneRedirect(self, zoneId):\n self.notify.info('Redirecting to zone %s.' % zoneId)\n base.cr.handlerArgs['zoneId'] = zoneId\n base.cr.handlerArgs['hoodId'] = ZoneUtil.getHoodId(zoneId)\n self.fsm.request('waitForSetZoneResponse', [\n base.cr.handlerArgs])\n\n \n def exitWaitForZoneRedirect(self):\n self.notify.debug('exitWaitForZoneRedirect()')\n base.cr.handler = base.cr.handlePlayGame\n base.cr.handlerArgs = None\n\n \n def enterWaitForSetZoneResponse(self, requestStatus):\n self.notify.debug('enterWaitForSetZoneResponse(requestStatus=' + str(requestStatus) + ')')\n messenger.send('enterWaitForSetZoneResponse', [\n requestStatus])\n base.cr.handler = self.handleWaitForSetZoneResponse\n base.cr.handlerArgs = requestStatus\n zoneId = requestStatus['zoneId']\n base.cr.sendSetZoneMsg(zoneId)\n if base.cr.welcomeValleyManager:\n base.cr.welcomeValleyManager.d_clientSetZone(zoneId)\n \n\n \n def exitWaitForSetZoneResponse(self):\n self.notify.debug('exitWaitForSetZoneResponse()')\n base.cr.handler = base.cr.handlePlayGame\n base.cr.handlerArgs = None\n\n \n def enterWaitForSetZoneComplete(self, requestStatus):\n self.notify.debug('enterWaitForSetZoneComplete(requestStatus=' + str(requestStatus) + ')')\n base.cr.handler = self.handleWaitForSetZoneComplete\n base.cr.handlerArgs = requestStatus\n\n \n def exitWaitForSetZoneComplete(self):\n self.notify.debug('exitWaitForSetZoneComplete()')\n base.cr.handler = base.cr.handlePlayGame\n base.cr.handlerArgs = None\n\n\n","sub_path":"toontown/hood/QuietZoneState.py","file_name":"QuietZoneState.py","file_ext":"py","file_size_in_byte":8541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"282116848","text":"import copy\nimport pexpect\nimport queue\nimport threading\nimport time\nimport subprocess\n\nfrom .fake_pexpect import FakeSpawn\nfrom ... import keypress\n\n# Host status\nSSHABLE = 4 # Can ssh to host\nSSH_NOT_REJECT = 3 # ssh times out\nPINGABLE = 2 # Can ping host, but not ssh\nPOWERED = 1 # Host is on, but no network (might be shutdown)\nPOWER_OFF = 0 # Host is powered off\n\nclass FakeHost(threading.Thread):\n \"\"\"Fake host used for tests. Also includes SSH session, tdtool and ping.\n Containers count as on if they were on when host shut down, since they\n would turn on at boot in that case.\"\"\"\n\n # TODO: Containers are hardcoded here, see if it can be done more elegantly\n def __init__(self, containers=(\"some_container\", \"another_container\")):\n super().__init__()\n self._to_session_queue = queue.Queue()\n self._from_session_queue = queue.Queue()\n self._pressed_keys = queue.Queue()\n self._ssh_session_active = threading.Event()\n # Host status\n self._host_status_lock = threading.Lock()\n self._host_status_events = {POWERED: threading.Event(),\n PINGABLE: threading.Event(),\n SSH_NOT_REJECT: threading.Event(),\n SSHABLE: threading.Event()}\n self._host_status_inverse_events = {POWERED: threading.Event(),\n PINGABLE: threading.Event(),\n SSH_NOT_REJECT: threading.Event(),\n SSHABLE: threading.Event()}\n self._host_status = None\n self._dm_on_flag = threading.Event()\n self._dm_off_flag = threading.Event()\n self._dm_off_flag.set()\n self._dm_lock = threading.Lock()\n self._x_on = threading.Event()\n self._x_off = threading.Event()\n self._x_off.set()\n self._x_lock = threading.Lock()\n self._set_host_status(POWER_OFF)\n self._containers_lock = threading.Lock()\n self._containers = {}\n self._containers_inverse = {}\n for container in containers:\n self._containers[container] = threading.Event()\n self._containers_inverse[container] = threading.Event()\n self._containers_inverse[container].set()\n self._files = {}\n self._files_lock = threading.Lock()\n self._stoprequest = threading.Event()\n self.fakes = {\"pexpect_spawn\": self._pexpect_spawn_fake,\n \"ping\": self._ping_fake,\n \"ssh_test\": self._ssh_test_fake,\n \"shutdown\": self._shutdown_fake,\n \"power_off\": self._tdtool_off_fake,\n \"power_on\": self._tdtool_on_fake,\n \"lxc_start\": self._lxc_start_fake,\n \"lxc_stop\": self._lxc_stop_fake,\n \"lxc_list\": self._lxc_list_fake,\n \"ssh_cmd\": self._ssh_cmd_fake,\n \"start_lightdm\": self._start_lightdm_fake,\n \"stop_lightdm\": self._stop_lightdm_fake,\n \"start_x\": self._start_x_fake,\n \"stop_x\": self._stop_x_fake}\n \n def _pexpect_spawn_fake(self, *args, **kwargs):\n \"\"\"Use this to replace pexpect.spawn of ssh.\"\"\"\n fake_session = FakeSpawn(self._to_session_queue, self._from_session_queue)\n status = self._get_host_status()\n if status >= SSHABLE:\n self._to_session_queue.put(keypress.COMPUTER_PROMPT)\n self._ssh_session_active.set()\n elif status >= SSH_NOT_REJECT:\n self._to_session_queue.put(pexpect.TIMEOUT)\n else:\n self._to_session_queue.put(pexpect.EOF)\n return fake_session\n \n def _ping_fake(self, cmd):\n if self._get_host_status() >= PINGABLE:\n return 0\n else:\n return 1\n \n def _ssh_test_fake(self, cmd):\n status = self._get_host_status()\n if status >= SSHABLE:\n return 0\n elif status >= SSH_NOT_REJECT:\n return 124\n else:\n return 255\n\n def _ssh_cmd_fake(self, cmd):\n status = self._get_host_status()\n remote_cmd = cmd[4]\n if remote_cmd.startswith(\"echo\"):\n if status >= SSHABLE:\n name = remote_cmd.split(\" \")[-1]\n contents = remote_cmd.strip(\"echo '\").strip(\"' > \" + name)\n self._write_file(name, contents)\n return 0\n elif status >= SSH_NOT_REJECT:\n return 124\n else:\n return 255\n elif remote_cmd.startswith(\"cat\"):\n if status >= SSHABLE:\n name = remote_cmd.split(\" \")[-1]\n try:\n contents = self._read_file(name)\n return (contents + \"\\n\").encode(\"utf-8\")\n except KeyError:\n raise subprocess.CalledProcessError(\"File doesn't exist\", cmd)\n else:\n raise subprocess.CalledProcessError(\"Not sshable\", cmd)\n \n def _lxc_list_fake(self, cmd):\n output = \"\"\n for container in self._get_all_containers():\n if self._get_container_on(container):\n status = \"RUNNING\"\n else:\n status = \"STOPPED\"\n output += container + \",\" + status + \"\\n\"\n return output.encode(\"utf-8\")\n\n \n def _shutdown_fake(self, cmd):\n status = self._get_host_status()\n if status >= SSHABLE:\n self._shut_down()\n return 0\n elif status >= SSH_NOT_REJECT:\n return 124\n else:\n return 255 \n \n def _tdtool_off_fake(self, cmd):\n self._power_off()\n return 0\n\n def _tdtool_on_fake(self, cmd):\n self._power_on()\n return 0\n \n def _lxc_start_fake(self, cmd):\n container = cmd[4]\n try:\n self._set_container_status(container, True)\n except RuntimeError:\n return 1\n return 0\n\n def _lxc_stop_fake(self, cmd):\n container = cmd[4]\n try:\n self._set_container_status(container, False)\n except RuntimeError:\n return 1\n return 0\n \n def _start_lightdm_fake(self, cmd):\n self._start_dm()\n return 0\n\n def _stop_lightdm_fake(self, cmd):\n self._stop_dm()\n return 0\n \n def _start_x_fake(self, cmd):\n self._start_standalone_x()\n return 0\n\n def _stop_x_fake(self, cmd):\n self._stop_standalone_x()\n return 0\n \n def _write_file(self, name, contents):\n with self._files_lock:\n self._files[name] = contents\n \n def _read_file(self, name):\n with self._files_lock:\n contents = self._files[name]\n return contents\n \n def _shut_down(self):\n self._set_host_status(POWERED)\n \n def _power_off(self):\n self._set_host_status(POWER_OFF)\n \n def _power_on(self):\n if self._get_host_status() == POWER_OFF:\n self._start_dm()\n self._set_host_status(SSHABLE)\n \n def _start_dm(self):\n if self._get_host_status() >= SSHABLE and not self._x_on.is_set():\n with self._dm_lock:\n self._dm_on_flag.set()\n self._dm_off_flag.clear()\n \n def _stop_dm(self):\n if self._get_host_status() >= SSHABLE:\n with self._dm_lock:\n self._dm_on_flag.clear()\n self._dm_off_flag.set()\n \n def _start_standalone_x(self):\n if self._get_host_status() >= SSHABLE and not self._dm_on_flag.is_set():\n with self._x_lock:\n self._x_on.set()\n self._x_off.clear()\n \n def _stop_standalone_x(self):\n if self._get_host_status() >= SSHABLE:\n with self._x_lock:\n self._x_on.clear()\n self._x_off.set()\n \n def _set_host_status(self, status):\n self._host_status_lock.acquire()\n if status < SSH_NOT_REJECT:\n self._ssh_session_active.clear()\n if status < POWERED:\n with self._dm_lock:\n self._dm_on_flag.clear()\n self._dm_off_flag.set()\n for level, event in self._host_status_events.items():\n if level > status:\n event.clear()\n else:\n event.set()\n for level, event in self._host_status_inverse_events.items():\n if level > status:\n event.set()\n else:\n event.clear()\n self._host_status = status\n self._host_status_lock.release()\n \n def _get_host_status(self):\n self._host_status_lock.acquire()\n status = self._host_status\n self._host_status_lock.release()\n return status\n \n def _wait_for_status(self, status, inverse, timeout):\n if inverse:\n return self._host_status_inverse_events[status].wait(timeout=timeout)\n else:\n return self._host_status_events[status].wait(timeout=timeout)\n\n def _set_container_status(self, container, on):\n self._containers_lock.acquire()\n if not container in self._containers:\n self._containers_lock.release()\n raise RuntimeError(\"No such container\")\n if on:\n self._containers[container].set()\n self._containers_inverse[container].clear()\n else:\n self._containers[container].clear()\n self._containers_inverse[container].set()\n self._containers_lock.release()\n\n def _wait_container_status(self, container, on, timeout):\n self._containers_lock.acquire()\n if not container in self._containers:\n self._containers_lock.release()\n raise RuntimeError(\"No such container\")\n self._containers_lock.release()\n if on:\n return self._containers[container].wait(timeout=timeout)\n else:\n return self._containers_inverse[container].wait(timeout=timeout)\n \n def _get_all_containers(self):\n with self._containers_lock:\n return self._containers.keys()\n\n def _get_container_on(self, container):\n with self._containers_lock:\n return self._containers[container].is_set()\n\n def run(self):\n while not self._stoprequest.is_set():\n try:\n event = self._from_session_queue.get(timeout=0.05)\n status = self._get_host_status()\n if not self._ssh_session_active.is_set() or status < SSH_NOT_REJECT:\n self._to_session_queue.put(pexpect.EOF)\n elif status == SSH_NOT_REJECT:\n self._to_session_queue.put(pexpect.TIMEOUT)\n else:\n if event.startswith(keypress.XDOTOOL_PREFIX):\n key = event[len(keypress.XDOTOOL_PREFIX):]\n self._pressed_keys.put(key)\n self._to_session_queue.put(keypress.COMPUTER_PROMPT)\n else:\n raise NotImplementedError\n except queue.Empty:\n pass\n \n def join(self, timeout=None):\n self._stoprequest.set()\n super().join(timeout)\n \n def turn_off(self):\n self._power_off()\n\n def turn_on(self):\n self._power_on()\n \n def start_container(self, name):\n self._set_container_status(name, True)\n \n def stop_container(self, name):\n self._set_container_status(name, False)\n \n def pressed_key(self, timeout=1):\n try:\n return self._pressed_keys.get(timeout=timeout)\n except queue.Empty:\n return False\n \n def sshable(self, timeout=1):\n return self._wait_for_status(SSHABLE, False, timeout)\n \n def ssh_not_reject(self, timeout=1):\n return self._wait_for_status(SSH_NOT_REJECT, False, timeout)\n\n def pingable(self, timeout=1):\n return self._wait_for_status(PINGABLE, False, timeout)\n \n def powered(self, timeout=1):\n return self._wait_for_status(POWERED, False, timeout)\n \n def not_sshable(self, timeout=1):\n return self._wait_for_status(SSHABLE, True, timeout)\n \n def ssh_reject(self, timeout=1):\n return self._wait_for_status(SSH_NOT_REJECT, True, timeout)\n\n def not_pingable(self, timeout=1):\n return self._wait_for_status(PINGABLE, True, timeout)\n \n def not_powered(self, timeout=1):\n return self._wait_for_status(POWERED, True, timeout)\n \n def container_on(self, container, timeout=1):\n return self._wait_container_status(container, True, timeout)\n \n def container_off(self, container, timeout=1):\n return self._wait_container_status(container, False, timeout)\n \n def dm_on(self, timeout=1):\n return self._dm_on_flag.wait(timeout=timeout)\n\n def dm_off(self, timeout=1):\n return self._dm_off_flag.wait(timeout=timeout)\n \n def standalone_x_on(self, timeout=1):\n return self._x_on.wait(timeout=timeout)\n\n def standalone_x_off(self, timeout=1):\n return self._x_off.wait(timeout=timeout)","sub_path":"controlpi/test/fakes/fake_host.py","file_name":"fake_host.py","file_ext":"py","file_size_in_byte":13401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"521250888","text":"from discord_slash import SlashCommand\nfrom discord_slash import SlashContext\nfrom discord.ext import commands\n\nimport discord\n\nclass Slash(commands.Cog):\n def __init__(self, client):\n self.client = client\n self.slash = SlashCommand(client, override_type=True)\n\n @self.slash.slash(name=\"ping\")\n async def _ping(ctx: SlashContext):\n embed = discord.Embed(color=discord.Colour.from_rgb(255, 130, 53))\n embed.add_field(name=\"**Ping**\", value=f\":table_tennis: Pong! {self.client.latency * 1000} ms\")\n await ctx.send(embeds=[embed])\n\n def cog_unload(self):\n self.slash.remove()\n\n\ndef setup(bot):\n bot.add_cog(Slash(bot))","sub_path":"cogs/slash-commands.py","file_name":"slash-commands.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"629136501","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 27 10:22:21 2016\r\n\r\n@author: BTeillant\r\n\"\"\"\r\n\r\nfrom geopy.distance import great_circle\r\nimport utm\r\n\r\n\r\ndef distance(UTM_ini, UTM_fin):\r\n \"\"\"\r\n distance returns the calculated distance (in kms) between two points\r\n defined in the UTM coordinate system\r\n \"\"\"\r\n\r\n UTM_ini_x = UTM_ini[0]\r\n UTM_ini_y = UTM_ini[1]\r\n UTM_ini_zone = UTM_ini[2]\r\n\r\n UTM_fin_x = UTM_fin[0]\r\n UTM_fin_y = UTM_fin[1]\r\n UTM_fin_zone = UTM_fin[2]\r\n\r\n [LAT_INI, LONG_INI] = utm.to_latlon(UTM_ini_x, UTM_ini_y, int(UTM_ini_zone[0:2]), str(UTM_ini_zone[3])) # to get dd.dd from utm\r\n [LAT_FIN, LONG_FIN] = utm.to_latlon(UTM_fin_x, UTM_fin_y, int(UTM_fin_zone[0:2]), str(UTM_fin_zone[3])) # to get dd.dd from utm\r\n\r\n point_i = (LAT_INI, LONG_INI)\r\n point_f = (LAT_FIN, LONG_FIN)\r\n\r\n distance = great_circle(point_i, point_f).kilometers # gives you a distance (in kms) between two coordinate in dd.dd\r\n\r\n return distance","sub_path":"Logistics/ancillaries/dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"442251979","text":"# 22.Дан список чисел. Посчитайте, сколько в нем пар элементов, равных друг\n# другу. Считается, что любые два элемента, равные друг другу образуют\n# одну пару, которую необходимо посчитать.(input: 1, 2, 3, 2, 3 output: 2)\n\nlist_ =[\"aktan\", 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 1]\n\ncounter = 0\nfor num in list_:\n\n list_.count(num)\n if list_.count(num) == 2 :\n counter +=1\n elif list_.count(num) == 4 and list_.count(num) % 2 == 0 :\n while list_.count(num) == 2:\n list_.count(num)/2\n counter +=2\n print(counter)\n if list_.count(num)/2 == 3:\n list_.count(num)+1\n continue\n\nnew_counter = int(counter)\nprint(new_counter)\nprint(list_[0])\n# for nums in list_ :\n# counted = list_.count[nums]\n# print(counted)\n\n\n\n\n# counter = 0\n# for nums in range(len(list_)):\n# for num in range(nums, len(list_)):\n# if list_[nums] == list_[num]:\n# counter += 1\n# print(counter)\n","sub_path":"task.22.22.py","file_name":"task.22.22.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"326741229","text":"import pickle\nimport numpy as np\nimport pandas as pd\nfrom datum import Datum\nimport networkx as nx\nimport graph\nfrom gensim.models import Word2Vec\n\nimport pickle\n\n\ndef load_obj(name): \n if '.pkl' not in name:\n name+='.pkl'\n with open( name , 'rb') as f:\n return pickle.load(f)\n\nf = '../data/fund_data.pkl'\nd = load_obj(f)\n\n\nimport numpy as np\n\ndata_dir = '../data/'\nfundhold=d[((d['rpt_date']=='2018-06-30') | (d['rpt_date']=='2018-12-31'))]\nfund=fundhold[['fund_code','rpt_date','stock_code','proportiontototalstockinvestments']]\n\nfund_values = fund.values\n\nlist_funds = pd.Series(fund['fund_code'].unique())\nlist_dates = pd.Series(fund['rpt_date'].unique())\nlist_stocks = pd.Series(fund['stock_code'].unique())\n\nweight_matrix = np.zeros((len(list_dates), len(list_funds), len(list_stocks))) \nfor ind in range(len(fund_values)):\n fund_index = list_funds.index[list_funds==fund_values[ind,0]][0]\n time_index = list_dates.index[list_dates==fund_values[ind,1]][0]\n stock_index = list_stocks.index[list_stocks==fund_values[ind,2]][0]\n weight_matrix[time_index, fund_index, stock_index] = fund_values[ind,3]\nselect_date=list_dates.values\n\nweight_matrix = np.copy(weight_matrix)\nweight_matrix_total = np.sum(weight_matrix, axis=0)\n\narr_tmp = []\nfor fund_index in range(len(list_funds)):\n a_edge_index = np.where(weight_matrix_total[fund_index] != 0)[0]\n for edge_index in a_edge_index:\n arr_tmp.append([fund_index, len(list_funds) + edge_index, weight_matrix_total[fund_index, edge_index]])\narr_tmp = np.array(arr_tmp)\npd_tmp = pd.DataFrame(arr_tmp)\npd_tmp[0] = pd_tmp[0].astype(int)\npd_tmp[1] = pd_tmp[1].astype(int)\noutput_name='fund'\npath = data_dir + 'graph/{}.csv'.format(output_name)\npd_tmp.to_csv(path, index=False, sep=' ')\n\nnx_G = nx.read_edgelist(path, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph())\nnx_G = nx_G.to_undirected()\nG = graph.Graph(nx_G, False, 1, 1)\nG.preprocess_transition_probs()\n\nwalks = G.simulate_walks(200, 200)\nwalks = [list(map(str, walk)) for walk in walks]\n\nfrom gensim.models import Word2Vec\n\nmodel = Word2Vec(walks, size=32, window=6, min_count=0, sg=1, workers=2, iter=30)\nmodel.wv.save_word2vec_format(data_dir + 'embedding/{}.emb'.format(output_name))\n\ntotal_embedding = np.array(pd.read_csv(data_dir+'embedding/'+output_name+'.emb', header=None, sep=' ', skiprows=1))\nembedding = np.zeros((len(list_funds), total_embedding.shape[1]-1))\nuse_index = []\nfor emb in total_embedding:\n if int(emb[0]) < len(list_funds):\n embedding[int(emb[0])] = emb[1:]\n use_index.append(int(emb[0]))\nuse_index = np.array(use_index)\n\nresult=[]\ntmp=embedding\nfor i in range(embedding.shape[0]):\n result.append(np.corrcoef(tmp[0],tmp[i])[0][1])\n\nresult_df=pd.DataFrame({'fund_code':list_funds,'corrcoef':result})\nresult_df.merge(fundhold[['fund_code','sec_name']].drop_duplicates(),on='fund_code',how='left').sort_values('corrcoef',ascending=False).to_csv('fund_corrcoef.csv',index=False,encoding=\"utf_8_sig\")","sub_path":"code/fund_similar.py","file_name":"fund_similar.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"238490568","text":"#!/usr/bin/env python\n\"\"\"Rover state using the Phidgets 8/8/8\n\nMeasure and report the battery voltage, whether it's\nconsidered to be depleted or not and the front and back\nrange to an obstacle.\n\"\"\"\n\n__author__ = 'Bill Mania '\n__version__ = '1'\n\nimport roslib; roslib.load_manifest('RoverState')\nimport rospy\nfrom RoverState.msg import Battery, Range\nfrom ctypes import *\nfrom Phidgets.Devices.InterfaceKit import InterfaceKit\nfrom Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException\nfrom Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs, InputChangeEventArgs, OutputChangeEventArgs, SensorChangeEventArgs\n\ninterfaceKit = None\nbatteryInfo = Battery(batteryVoltagePercentage = 100, depleted = False)\nrangeInfo = Range() \nbatteryPublisher = None\nrangePublisher = None\nbatteryVoltageChannel = None\nbatteryFullLevel = 1024\nbatteryDepletedLevel = 100\nbatteryRange = 0\nfrontRangeChannel = None\nbackRangeChannel = None\n\ndef attachHandler(event):\n return\n\ndef detachHandler(event):\n return\n\ndef errorHandler(event):\n return\n\ndef inputChangeHandler(event):\n return\n\ndef outputChangeHandler(event):\n return\n\ndef sensorChangeHandler(event):\n global batteryInfo, rangeInfo\n\n# rospy.logdebug('Sensor channel %d, value %d' % (event.index, event.value))\n\n if event.index == batteryVoltageChannel:\n sendBattery()\n elif event.index == frontRangeChannel:\n sendRange()\n elif event.index == backRangeChannel:\n sendRange()\n else:\n pass\n\n return\n\ndef calculateRange(sensorReading):\n \"\"\"Return the range in centimeters based on the sensor reading\"\"\"\n\n if sensorReading < 200:\n # beyond the range of the IR sensor\n return 100\n\n if sensorReading < 300:\n return 20\n\n if sensorReading < 500:\n return 10\n\n if sensorReading < 600:\n return 5\n\n return 0\n\ndef sendRange():\n global rangeInfo\n\n newFrontRangeCm = calculateRange(interfaceKit.getSensorValue(frontRangeChannel))\n newBackRangeCm = calculateRange(interfaceKit.getSensorValue(backRangeChannel))\n\n publishUpdate = False\n\n if ((newFrontRangeCm - rangeInfo.frontRangeCm) ** 2) > 24:\n rangeInfo.frontRangeCm = newFrontRangeCm\n publishUpdate = True\n\n if ((newBackRangeCm - rangeInfo.backRangeCm) ** 2) > 24:\n rangeInfo.backRangeCm = newBackRangeCm\n publishUpdate = True\n\n if publishUpdate:\n rangePublisher.publish(rangeInfo)\n\n return\n\ndef sendBattery():\n global batteryInfo\n\n rospy.logdebug('raw battery sensor value %d' % (interfaceKit.getSensorValue(batteryVoltageChannel)))\n currentBatteryLevel = int(interfaceKit.getSensorValue(batteryVoltageChannel))\n newBatteryVoltagePercentage = int(((currentBatteryLevel - batteryDepletedLevel) / batteryRange) * 100)\n\n publishUpdate = False\n\n if newBatteryVoltagePercentage != batteryInfo.batteryVoltagePercentage:\n batteryInfo.batteryVoltagePercentage = newBatteryVoltagePercentage\n publishUpdate = True\n\n if (currentBatteryLevel <= batteryDepletedLevel):\n batteryInfo.depleted = True\n publishUpdate = True\n else:\n batteryInfo.depleted = False\n \n if publishUpdate:\n batteryPublisher.publish(batteryInfo)\n\n return\n\ndef setupSensorHandlers():\n global interfaceKit, batteryPublisher, rangePublisher\n global batteryVoltageChannel, batteryFullLevel, batteryDepletedLevel, batteryRange, frontRangeChannel, backRangeChannel\n global batteryInfo, rangeInfo\n\n try:\n interfaceKit = InterfaceKit()\n\n except RuntimeError as e:\n rospy.logfatal('Failed to create InterfaceKit: %s' % (e.details))\n rospy.signal_shutdown('Failed to connect to InterfaceKit')\n\n try:\n interfaceKit.setOnAttachHandler(attachHandler)\n interfaceKit.setOnDetachHandler(detachHandler)\n interfaceKit.setOnErrorhandler(errorHandler)\n interfaceKit.setOnInputChangeHandler(inputChangeHandler)\n interfaceKit.setOnOutputChangeHandler(outputChangeHandler)\n interfaceKit.setOnSensorChangeHandler(sensorChangeHandler)\n\n except PhidgetException as e:\n rospy.logfatal('Failed to set handlers: %i, %s' % (e.code, e.details))\n rospy.signal_shutdown('Failed to connect to InterfaceKit')\n\n try:\n interfaceKit.openPhidget()\n\n except PhidgetException as e:\n rospy.logfatal(\"Failed to openPhidget() %i: %s\" % (e.code, e.details))\n rospy.signal_shutdown('Failed to openPhidget()')\n\n try:\n interfaceKit.waitForAttach(10000)\n\n except PhidgetException as e:\n rospy.logfatal(\"Failed on waitForAttach() %i: %s\" % (e.code, e.details))\n interfaceKit.closePhidget()\n rospy.signal_shutdown('Failed on waitForAttach()')\n\n for sensor in range(interfaceKit.getSensorCount()):\n try:\n interfaceKit.setDataRate(sensor, 16)\n\n except PhidgetException as e:\n rospy.logwarn(\"Failed to setDateRate() %i: %s\" % (e.code, e.details))\n\n batteryPublisher = rospy.Publisher('batteryInfo', Battery)\n rangePublisher = rospy.Publisher('rangeInfo', Range)\n\n batteryVoltageChannel = rospy.get_param('RoverState/battery/channel')\n batteryFullLevel = float(rospy.get_param('RoverState/battery/fullCharge'))\n batteryDepletedLevel = rospy.get_param('RoverState/battery/depletedCharge')\n batteryRange = batteryFullLevel - batteryDepletedLevel\n frontRangeChannel = rospy.get_param('RoverState/range/front/channel')\n backRangeChannel = rospy.get_param('RoverState/range/back/channel')\n\n sendRange()\n sendBattery()\n\n return\n\ndef processSensorInputs():\n\n while not rospy.is_shutdown():\n sendRange()\n sendBattery()\n rospy.sleep(5)\n\n interfaceKit.closePhidget()\n\n return\n\nif __name__ == \"__main__\":\n rospy.init_node(\n 'RoverState',\n log_level = rospy.DEBUG\n )\n\n setupSensorHandlers()\n\n processSensorInputs()\n","sub_path":"ros/RoverState/node/RoverState.py","file_name":"RoverState.py","file_ext":"py","file_size_in_byte":5991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"69429173","text":"def get_LCS(iv_string_1, iv_string_2):\n #for an absolutely unknown god damn reason, this declares first the columns and then the lines.\n lv_previous_results = [ [ None for i in range(len(iv_string_2)) ] \n for j in range(len(iv_string_1)) ] \n\n return get_LCS_helper(iv_string_1, iv_string_2, 0, 0, lv_previous_results);\n\n\ndef get_LCS_helper(iv_string_1, iv_string_2, index_1, index_2, iv_previous_results):\n if (index_1 >= len(iv_string_1) or \n index_2 >= len(iv_string_2) ):\n return \"\";\n\n if (iv_previous_results[index_1][index_2] != None):\n return iv_previous_results[index_1][index_2];\n \n if (iv_string_1[index_1] == iv_string_2[index_2]):\n iv_previous_results[index_1][index_2] = iv_string_1[index_1] + get_LCS_helper(iv_string_1, iv_string_2, index_1 + 1, index_2 + 1, iv_previous_results);\n return iv_previous_results[index_1][index_2];\n\n result_1 = get_LCS_helper(iv_string_1, iv_string_2, index_1+1, index_2, iv_previous_results);\n result_2 = get_LCS_helper(iv_string_1, iv_string_2, index_1, index_2+1, iv_previous_results);\n\n iv_previous_results[index_1][index_2] = result_1 if len(result_1) > len(result_2) else result_2;\n return iv_previous_results[index_1][index_2];\n\n\ndef test():\n print(\n get_LCS(\n input(\"1: \"),\n input(\"2: \")\n )\n );","sub_path":"code/exercises/longest_comm_sub.py","file_name":"longest_comm_sub.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295445335","text":"# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase, RequestFactory\n\nfrom factory import Faker\n\nfrom hikers.forms import (HikerRegistrationForm, HikerBasicInfoForm,\n HikerPhotoForm, HikerStatsForm)\nfrom hikers.models import Hiker\nfrom hikers.tests.factories import UserFactory, HikerFactory\n\n\nclass HikersFormsTests(TestCase):\n\n def setUp(self): # noqa\n self.user = UserFactory()\n self.user1 = UserFactory(first_name=Faker('first_name'),\n last_name=Faker('last_name'),\n email=Faker('safe_email'))\n self.hiker1 = HikerFactory(hiker=self.user1)\n self.request = RequestFactory().get('/fake-path')\n self.tz = 'US/Eastern'\n self.info_form_data = {'first_name': 'Bob',\n 'last_name': 'Brown',\n 'email': 'bob.brown@yyy.cc',\n 'timezone': self.tz}\n\n def test_hiker_registration(self):\n self.assertFalse(Hiker.objects.filter(hiker=self.user).exists())\n form_data = {'zipcode': '97219',\n 'city': 'Portland',\n 'state': 'OR',\n 'timezone': self.tz}\n hiker_form = HikerRegistrationForm(data=form_data)\n self.assertTrue(hiker_form.is_valid())\n hiker_form.signup(request=self.request, user=self.user)\n self.assertTrue(Hiker.objects.filter(hiker=self.user).exists())\n\n def test_hiker_basic_info_init(self):\n with self.assertRaises(ValueError):\n HikerBasicInfoForm(data=self.info_form_data)\n info_form = HikerBasicInfoForm(data=self.info_form_data,\n instance=self.hiker1)\n self.assertEquals(info_form.initial['first_name'],\n self.user1.first_name)\n\n def test_hiker_basic_save(self):\n info_form = HikerBasicInfoForm(data=self.info_form_data,\n instance=self.hiker1)\n self.assertNotEquals(self.user1.last_name,\n self.info_form_data['last_name'])\n info_form.is_valid()\n info_form.save()\n self.assertEquals(self.user1.last_name,\n self.info_form_data['last_name'])\n\n def test_hiker_photo_init(self):\n photo_form = HikerPhotoForm()\n self.assertTrue(photo_form.fields['photo'].required)\n\n def test_hiker_stats_init(self):\n stats_form = HikerStatsForm()\n self.assertTrue(stats_form.fields['avg_walking_pace'].localize)\n","sub_path":"hikers/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"171577693","text":"from urllib.request import urlopen, Request\nimport re\nimport sys\n\nuser_agent = 'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko' # User-Agent for IE 11\nhref_links = []\n\t\t\ndef getLinks(doc, home, parent):\n global href_links\n href_pattern = [r'href=\\S+\"', r'href=\\S+ ', r'href=\\S+\\'']\n tmp_urls = []\n \n # Save HTML URL in the given URL\n for n in range(len(href_pattern)):\n tmp_urls += re.findall(href_pattern[n], doc, re.I)\n \n for url in tmp_urls:\n url = url.strip()\t\t\n url = url.replace('\\'', '\"')\n \n if url[-1] is ' ' or url.find('\"') is -1: # quotation mark missed\n url = url.split('=')[1]\n else:\n url = url.split('\"')[1]\n \n if len(url) is 0:\n continue\n \n if url.find('http://') is -1:\n if url[0] == '/':\n url = home + url\n elif url[:2] == './':\n url = 'http://' + parent + url[1:]\t\n else:\n url = 'http://' + parent + '/' + url\n \n if url in href_links:\n continue\n \n if '.html' not in url: \n href_links.append(url)\n continue\n \n runCrawler(home, url)\t\n\t\ndef readHtml(url):\t\t\t\t\n try:\n req = Request(url)\n req.add_header('User-Agent', user_agent)\n h = urlopen(req) \n doc = h.read()\n h.close()\n except Exception as e:\n print('ERROR: %s' %url)\n print(e)\n return None\t\t\n \n return doc.decode()\n\t\n\t\ndef runCrawler(home, url):\n global href_links\n href_links.append(url)\n \n print ('GETTING ALL LINKS in [%s]' %url)\t\t\n try:\n doc = readHtml(url)\n if doc is None:\n return \n \n tmp = url.split('/')\n #if '.' in tmp[-1]:\n # tmp = tmp[:-1]\n \n parent = '/'.join(tmp[2:]) \n getLinks(doc, home, parent)\n except KeyboardInterrupt:\n print('Terminated by USER..Saving Crawled Links')\n finalize()\n sys.exit(0)\n \n return\t\n\t\ndef finalize():\n with open('crawled_links.txt', 'w+') as f:\n for href_link in href_links:\n f.write(href_link+'\\n')\t\n print('+++ CRAWLED TOTAL LINKS: [%s]' %len(href_links))\n\t\ndef main():\n targeturl = 'http://www.google.com' # URL \n home = 'http://' + targeturl.split('/')[2]\n \n print('+++ WEB LINK CRAWLER START > [%s]' %targeturl)\n runCrawler(home, targeturl)\n finalize()\n\t\t\n\nmain()\n","sub_path":"webHacking/Code/webLinkCrawler.py","file_name":"webLinkCrawler.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"545927544","text":"data1 = \"Data1.txt\"\n\ndef readData(data1):\n\tx = []\n\twith open(data1) as data :\n\t for line in data :\n\t \tx = line.split()\n\treturn x\n\n\nteks1 = readData(data1)\n\nisi = []\nfor i in teks1 :\n\tif i == 'I' :\n\t\tisi.append('*')\n\telif i == 'and' or i == 'The' or i=='you':\n\t\tisi.append('*'*3)\n\telse :\n\t\tisi.append(i)\n\nasd = ' '.join(isi)\nprint (asd)\n","sub_path":"DataLatihan/answer1.py","file_name":"answer1.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"87413945","text":"from multiprocessing import Process\nimport csv\nimport gpsd\nimport glob\nfrom smbus2 import SMBus\nimport time\n\ndef gps():\n # setup csv file\n file = \"gps_log.csv\"\n fields = ['time', 'lon', 'lat', 'speed']\n countdown = 1800 * 2 # countdown is how many seconds we will gather data for\n\n # connect to GPS module\n gpsd.connect()\n\n with open(file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(fields)\n count = 0\n \n while count < countdown:\n now = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", now)\n packet = gpsd.get_current()\n csvwriter.writerow([current_time, \"{:.4f}\".format(packet.lon), \"{:.4f}\".format(packet.lat), \"{:.4f}\".format(packet.hspeed)])\n count = count +1\n time.sleep(0.5) # frequency of data acquisition is .5 second\n \ndef read_temp_raw():\n base_dir = '/sys/bus/w1/devices/'\n device_folder = glob.glob(base_dir + '28*')[0]\n device_file = device_folder + '/w1_slave'\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close()\n return lines\n\ndef read_temp():\n lines = read_temp_raw()\n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.2)\n lines = read_temp_raw()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp_c = float(temp_string) / 1000.0\n temp_f = temp_c * 9.0 / 5.0 + 32.0\n return temp_c, temp_f\n\ndef ds18b20():\n # setup csv file\n file = \"ds18b20_log.csv\" \n fields = ['time', 'temperature']\n countdown = 1800 * 1\n \n with open(file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(fields)\n count = 0\n while count < countdown:\n now = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", now)\n temp_c, temp_f = read_temp()\n csvwriter.writerow([current_time, \"{:.4f}\".format(temp_c)])\n count = count + 1\n time.sleep(.2)\n \ndef si7021():\n # setup csv file\n file = \"si7021_log.csv\"\n fields = ['time', 'humidity', 'temperature']\n countdown = 1800 * 10\n\n # setup bus connection\n bus = SMBus(1)\n\n with open(file, 'w') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(fields)\n count = 0\n \n while count < countdown:\n now = time.localtime()\n current_time = time.strftime(\"%H:%M:%S\", now)\n bus.write_byte(0x40, 0xE5)\n data0 = bus.read_byte(0x40, 0x40)\n data1 = bus.read_byte(0x40, 0x40)\n humidity = ((data0 * 256 + data1) * 125 / 65536.0) - 6\n bus.write_byte(0x40, 0xE0)\n data0 = bus.read_byte(0x40, 0x40)\n data1 = bus.read_byte(0x40, 0x40)\n tempc = ((data0 * 256 + data1) * 175.72 / 65536.0) - 46.85\n csvwriter.writerow([current_time, \"{:.4f}\".format(humidity), \"{:.4f}\".format(tempc)])\n count = count + 1\n time.sleep(.082)\n\ndef main():\n p1 = Process(target=gps)\n p2 = Process(target=ds18b20)\n p3 = Process(target=si7021)\n p1.start()\n p2.start()\n p3.start()\n\n p1.join()\n p2.join()\n p3.join()\n print(\"Finished\")\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"gather.py","file_name":"gather.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640343275","text":"import numpy as np\nimport os\nimport sys\nimport tensorflow as tf\n\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport time\nimport functools\nimport cv2\nfrom datetime import datetime\n\nfrom object_detection.builders import model_builder\nfrom object_detection.protos import pipeline_pb2\nfrom google.protobuf import text_format\nfrom utils import visualization_utils as vis_util\nfrom utils import label_map_util\n\nslim = tf.contrib.slim\n\nsys.path.append(\"..\")\n\n#pipeline_config_path = 'samples/configs/ssd_mobilenet_v1_voc.config'\npipeline_config_path = 'samples/configs/ssd_inception_v2_coco.config'\n#checkpoint_dir = '../data/output/ssd_mobilenet_v1_voc_1.0'\ncheckpoint_dir = '../data/pre_model/ssd_inception_v2_coco_11_06_2017'\n\ntest_image_path = 'test_images'\n\n\nclass SSD_MobileNet_Detection:\n def __init__(self):\n self.PATH_TO_LABELS = os.path.join('data', 'pascal_label_map.pbtxt')\n self.NUM_CLASSES = 20\n self.label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)\n self.categories = label_map_util.convert_label_map_to_categories(self.label_map,\n max_num_classes=self.NUM_CLASSES,\n use_display_name=True)\n self.category_index = label_map_util.create_category_index(self.categories)\n self.IMAGE_SIZE = (12, 8)\n\n #get model config from config file\n pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()\n with tf.gfile.GFile(pipeline_config_path, 'r') as f:\n text_format.Merge(f.read(), pipeline_config)\n model_config = pipeline_config.model\n\n #get model from config file model_name\n create_model_fn = functools.partial(\n model_builder.build,\n model_config=model_config,\n is_training=False)\n self.model = create_model_fn()\n\n #placeholder image data and do predict.\n self.img_data = tf.placeholder(tf.uint8, shape=(None, None, 3))\n expand_image = tf.expand_dims(self.img_data, 0)\n preprocessed_image = self.model.preprocess(tf.to_float(expand_image))\n prediction_dict = self.model.predict(preprocessed_image)\n self.detections = self.model.postprocess(prediction_dict)\n\n #restore graph model from ckpt file\n variables_to_restore = tf.global_variables()\n global_step = slim.get_or_create_global_step()\n variables_to_restore.append(global_step)\n saver = tf.train.Saver(variables_to_restore)\n self.sess = tf.Session()\n latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)\n saver.restore(self.sess, latest_checkpoint)\n\n def load_image_into_numpy_array(self, image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)\n\n def detect_img(self):\n for img_name in os.listdir(test_image_path):\n if '.jpg' in img_name:\n image = Image.open(os.path.join(test_image_path,img_name))\n #image = image.resize((224, 224))\n start_time = time.time()\n print('@ailias')\n # result image with boxes and labels on it.\n image_data = self.load_image_into_numpy_array(image)\n\n detections = self.sess.run(self.detections, feed_dict={self.img_data: image_data})\n\n # # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_data,\n np.squeeze(detections['detection_boxes']),\n np.squeeze(detections['detection_classes']).astype(np.int32),\n np.squeeze(detections['detection_scores']),\n self.category_index,\n use_normalized_coordinates=True,\n line_thickness=4)\n plt.figure(figsize=self.IMAGE_SIZE)\n plt.imshow(image_data)\n #plt.waitforbuttonpress()\n print('tot time:', time.time() - start_time)\n #print(detections)\n\n def detect_video(self, video_name=None):\n if video_name is None:\n capture = cv2.VideoCapture(0)\n else:\n capture = cv2.VideoCapture(video_name)\n while True:\n ret, image_data = capture.read()\n if not ret: # no img data\n break\n start_time = time.time()\n detections = self.sess.run(self.detections, feed_dict={self.img_data: image_data})\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_data,\n np.squeeze(detections['detection_boxes']),\n np.squeeze(detections['detection_classes']).astype(np.int32)+1,\n np.squeeze(detections['detection_scores']),\n self.category_index,\n use_normalized_coordinates=True,\n line_thickness=4)\n cv2.imshow('Detected', image_data)\n cv2.waitKey(1)\n print(\"detect time(ms):%f\" % (time.time() - start_time))\n\nif __name__ == '__main__':\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n detect = SSD_MobileNet_Detection()\n detect.detect_video()\n","sub_path":"object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"355496686","text":"#SQuADのデータ処理\n#必要条件:CoreNLP\n#Tools/core...で\n#java -mx4g -cp \"*\" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000\n\nimport os\nimport sys\nsys.path.append(\"../\")\nimport json\nimport gzip\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom nltk.tokenize import word_tokenize,sent_tokenize\nimport pickle\nimport collections\n\nfrom func.tf_idf import tf_idf,cos_sim\n\n\ndef head_find(tgt):\n q_head=[\"what\",\"how\",\"who\",\"when\",\"which\",\"where\",\"why\",\"whose\",\"whom\",\"is\",\"are\",\"was\",\"were\",\"do\",\"did\",\"does\"]\n tgt_tokens=word_tokenize(tgt)\n true_head=\"\"\n for h in q_head:\n if h in tgt_tokens:\n true_head=h\n break\n return true_head\n\ndef modify(sentence,question_interro):\n #head=head_find(question)\n \"\"\"\n if answer in sentence:\n sentence=sentence.replace(answer,\" ans_rep_tag \")\n \"\"\"\n #sentence=\" \".join([sentence,\"ans_pos_tag\",answer,\"interro_tag\",question_interro])\n sentence=\" \".join([sentence,\"interro_tag\",question_interro])\n return sentence\n\ndef modify_history(history,now):\n #head=head_find(question)\n \"\"\"\n if answer in sentence:\n sentence=sentence.replace(answer,\" ans_rep_tag \")\n \"\"\"\n #sentence=\" \".join([sentence,\"ans_pos_tag\",answer,\"interro_tag\",question_interro])\n sentence=\" \".join([history,\"history_append_tag\",now])\n return sentence\n\ndef history_maker(neg_interro,question_interro):\n interro_list=[\"what\",\"where\",\"who\",\"why\",\"which\",\"whom\",\"how\",\"\"]\n while True:\n index=random.randrange(len(interro_list))\n if interro_list[index]!=question_interro.split()[0]:\n break\n question=interro_list[index]+\" \"+neg_interro\n return question\n\n\ndef c2wpointer(context_text,context,answer_start,answer_end):#answer_start,endをchara単位からword単位へ変換\n #nltk.tokenizeを使って分割\n #ダブルクオテーションがなぜか変化するので処理\n token_id={}\n cur_id=0\n for i,token in enumerate(context):\n start=context_text.find(token,cur_id)\n token_id[i]=(start,start+len(token))\n cur_id=start+len(token)\n for i in range(len(token_id)):\n if token_id[i][0]<=answer_start and answer_start<=token_id[i][1]:\n answer_start_w=i\n break\n for i in range(len(token_id)):\n if token_id[i][0]<=answer_end and answer_end<=token_id[i][1]:\n answer_end_w=i\n break\n return answer_start_w,answer_end_w\n\n#sentenceを受け取り、tokenizeして返す\ndef tokenize(sent):\n return [token.replace('``','\"').replace(\"''\",'\"') for token in word_tokenize(sent)]\n\n#context_textを文分割して、answer_start~answer_end(char単位)のスパンが含まれる文を返す\n#やってることはc2iと多分同じアルゴリズム\ndef answer_find(context_text,answer_start,answer_end,answer_replace):\n context=sent_tokenize(context_text)\n sent_start_id=-1\n sent_end_id=-1\n start_id_list=[context_text.find(sent) for sent in context]\n end_id_list=[start_id_list[i+1] if i+1!=len(context) else len(context_text) for i,sent in enumerate(context)]\n for i,sent in enumerate(context):\n start_id=start_id_list[i]\n end_id=end_id_list[i]\n if start_id<=answer_start and answer_start<=end_id:\n sent_start_id=i\n if start_id<=answer_end and answer_end<=end_id:\n sent_end_id=i\n\n\n #print(sent_start_id,sent_end_id)\n\n\n if sent_start_id==-1 or sent_end_id==-1:\n #sys.exit(-1)\n print(\"error\")\n #sys.exit(-1)\n answer_sent=\" \".join(context[sent_start_id:sent_end_id+1])\n #ここで答えを置換する方法。ピリオドが消滅した場合などに危険なので止める。\n\n return answer_sent,sent_start_id\n\n\ndef data_process(input_path,src_path,tgt_path,dict_path,test=True):\n with open(input_path,\"r\") as f:\n data=json.load(f)\n with open(dict_path,\"r\") as f:\n corenlp_data=json.load(f)\n contexts=[]\n questions=[]\n answer_starts=[]\n answer_ends=[]\n answer_texts=[]\n answers=[]\n sentences=[]\n ids=[]\n answer_replace=False\n count=-1\n answer_count=[]\n\n #path=\"data/glove.840B.300d.txt\"\n path=\"/home/6/15B06641/data/glove.840B.300d.txt\"\n\n w2vec={}\n\n with open(path,\"r\")as f:\n print(path)\n for i,line in tqdm(enumerate(f)):\n line_split=line.split()\n w2vec[\" \".join(line_split[0:-300]).lower()]=[float(i) for i in line_split[-300:]]\n if i==50000:\n break\n\n print(\"end\")\n\n\n\n for paragraph in tqdm(data[\"data\"]):\n context_text=paragraph[\"story\"].lower()\n question_history=[]\n for i in range(len(paragraph[\"questions\"])):\n count+=1\n\n question_dict=paragraph[\"questions\"][i]\n answer_dict=paragraph[\"answers\"][i]\n question_text=question_dict[\"input_text\"].lower()\n answer_text=answer_dict[\"input_text\"].lower()\n question_history.append((question_text,answer_text))\n\n span_start=answer_dict[\"span_start\"]\n span_end=answer_dict[\"span_end\"]\n span_text=answer_dict[\"span_text\"]\n turn_id=paragraph[\"questions\"][i][\"turn_id\"]\n\n d=corenlp_data[count]\n if d[\"vb_check\"]==False and d[\"question_interro\"]!=\"none_tag\":\n if test==False:\n start=0\n sentence=tf_idf(context_text,\" \".join(question_history[-2:]),num_canditate=1)\n if span_start!=-1:\n sentence=answer_find(context_text,span_start,span_end,answer_replace)\n else:\n if span_start==-1:\n continue\n start=0\n if len(question_history)>=2:\n join_text=\" \".join([question_history[-2][0],question_history[-2][1],question_history[-1][0]])\n else:\n join_text=question_history[-1][0]\n sentence,answer_id=answer_find(context_text,span_start,span_end,answer_replace)\n\n\n para_vec=[np.average([w2vec[word] for word in word_tokenize(s) if word in w2vec],axis=0)\n for s in sent_tokenize(context_text)]\n\n sent_vec=np.average([w2vec[word] for word in word_tokenize(join_text) if word in w2vec],axis=0)\n\n cos={i:cos_sim(v,sent_vec) for i,v in enumerate(para_vec)}\n cos=sorted(cos.items(),key=lambda x:-x[1])\n tf_id=[c[0] for c in cos[0:1]]\n\n sent=sent_tokenize(context_text)[0]\n \"\"\"\n print(np.average([1 if word in w2vec else 0 for word in word_tokenize(sent)]))\n print(sent)\n \"\"\"\n\n answer_count.append(answer_id in tf_id)\n\n\n sentence=modify(sentence,question_text)\n sentence=\" \".join(tokenize(sentence))\n question_text=\" \".join(tokenize(question_text))\n sentences.append(sentence)\n questions.append(question_text)\n\n \"\"\"\n if span_start!=-1:\n sentence=answer_find(context_text,span_start,span_end,answer_replace)\n else:\n sentence=tf_idf(context_text,\" \".join(question_history[-2:]),num_canditate=1)\n span_count+=1\n sentence=modify(sentence,question_text)\n sentence=\" \".join(tokenize(sentence))\n question_text=\" \".join(tokenize(question_text))\n sentences.append(sentence)\n questions.append(question_text)\n else:\n sentence=modify(context_text,question_text)\n sentence=\" \".join(tokenize(sentence))\n question_text=\" \".join(tokenize(question_text))\n sentences.append(sentence)\n questions.append(question_text)\n else:\n #break\n if len(question_history)>0:\n q_his=question_history[-1]\n sentence=modify_history(q_his,question_text)\n sentence=\" \".join(tokenize(sentence))\n question_text=\" \".join(tokenize(question_text))\n sentences.append(sentence)\n questions.append(question_text)\n else:\n sentence=\" \".join(tokenize(question_text))\n question_text=\" \".join(tokenize(question_text))\n sentences.append(sentence)\n questions.append(question_text)\n question_history.append(question_text)\n \"\"\"\n\n print(np.average(answer_count),len(answer_count))\n print(len(questions),len(sentences))\n \"\"\"\n para_vec=np.sum([w2vec[word] for word in word_tokenize(\"I love a dog.\") if word in w2vec])\n sent_vec=np.sum([w2vec[word] for word in word_tokenize(\"I love a cat.\") if word in w2vec])\n sent2_vec=np.sum([w2vec[word] for word in word_tokenize(\"You have a pencil.\") if word in w2vec])\n print(cos_sim(para_vec,sent_vec))\n print(cos_sim(para_vec,sent2_vec))\n \"\"\"\n\n\n\n#main\nversion=\"1.1\"\ntype=\"interro_cand1\"\nquestion_modify=True\nquestion_interro=True\n\n\"\"\"\ndata_process(input_path=\"data/coqa-train-v1.0.json\",\n src_path=\"data/coqa-src-train-{}.txt\".format(type),\n tgt_path=\"data/coqa-tgt-train-{}.txt\".format(type),\n dict_path=\"data/coqa-train-corenlp.json\"\n )\n\"\"\"\ndata_process(input_path=\"data/coqa-dev-v1.0.json\",\n src_path=\"data/coqa-src-dev-{}.txt\".format(type),\n tgt_path=\"data/coqa-tgt-dev-{}.txt\".format(type),\n dict_path=\"data/coqa-dev-corenlp.json\",\n test=True\n )\n","sub_path":"exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":9932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"547797758","text":"import boto3\r\nimport os\r\nimport sys\r\nimport json\r\nimport re\r\nfrom base64 import b64decode\r\nfrom fos_restapi import FortiOSREST\r\nimport urllib3\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\n### set variables such as debug, fgt IP + creds, etc\r\naddripPREFIX = os.environ['addripPREFIX']\r\naddrfqdnPREFIX = os.environ['addrfqdnPREFIX']\r\naddrgrpPREFIX = os.environ['addrgrpPREFIX']\r\nplaceholderNAME = os.environ['placeholderaddrNAME']\r\naggaddrgrpNAME = os.environ['aggaddrgrpNAME']\r\naddrgrpBATCHcreate = os.environ['addrgrpBATCHcreate']\r\nfgtLOGINinfo = os.environ['fgtLOGINinfo']\r\nfgtTIMEOUT = os.environ['fgtapiTIMEOUT']\r\nfgtDEBUG = os.environ['fgtapiDEBUG']\r\nfgtLOGINlist = []\r\nlogininfoerrors = 0\r\nfgt = ''\r\n\r\n### map original AWS Guard Duty Finding Types to sanitized FortiOS address groups\r\ngd2fgtTYPE = {\r\n 'Backdoor:EC2/XORDDOS' : 'BackdoorEC2-XORDDOS',\r\n 'Backdoor:EC2/Spambot' : 'BackdoorEC2-Spambot',\r\n 'Backdoor:EC2/C&CActivity.B!DNS' : 'BackdoorEC2-CnCActivityBDNS',\r\n 'Behavior:IAMUser/InstanceLaunchUnusual' : 'BehaviorIAMUser-InstanceLaunchUnusual',\r\n 'Behavior:EC2/NetworkPortUnusual' : 'BehaviorEC2-NetworkPortUnusual',\r\n 'Behavior:EC2/TrafficVolumeUnusual' : 'BehaviorEC2-TrafficVolumeUnusual',\r\n 'CryptoCurrency:EC2/BitcoinTool.B!DNS' : 'CryptoCurrencyEC2-BitcoinToolBDNS',\r\n 'PenTest:IAMUser/KaliLinux' : 'PenTestIAMUser-KaliLinux',\r\n 'Persistence:IAMUser/NetworkPermissions' : 'PersistenceIAMUser-NetworkPermissions',\r\n 'Persistence:IAMUser/ResourcePermissions' : 'PersistenceIAMUser-ResourcePermissions',\r\n 'Persistence:IAMUser/UserPermissions' : 'PersistenceIAMUser-UserPermissions',\r\n 'Recon:EC2/PortProbeUnprotectedPort' : 'ReconEC2-PortProbeUnprotectedPort',\r\n 'Recon:IAMUser/TorIPCaller' : 'ReconIAMUser-TorIPCaller',\r\n 'Recon:IAMUser/MaliciousIPCaller.Custom' : 'ReconIAMUser-MaliciousIPCallerCustom',\r\n 'Recon:IAMUser/MaliciousIPCaller' : 'ReconIAMUser-MaliciousIPCaller',\r\n 'Recon:EC2/Portscan' : 'ReconEC2-Portscan',\r\n 'Recon:IAMUser/NetworkPermissions' : 'ReconIAMUser-NetworkPermissions',\r\n 'Recon:IAMUser/ResourcePermissions' : 'ReconIAMUser-ResourcePermissions',\r\n 'Recon:IAMUser/UserPermissions' : 'ReconIAMUser-UserPermissions',\r\n 'ResourceConsumption:IAMUser/ComputeResources' : 'ResourceConsumptionIAMUser-ComputeResources',\r\n 'Stealth:IAMUser/PasswordPolicyChange' : 'StealthIAMUser-PasswordPolicyChange',\r\n 'Stealth:IAMUser/CloudTrailLoggingDisabled' : 'StealthIAMUser-CloudTrailLoggingDisabled',\r\n 'Stealth:IAMUser/LoggingConfigurationModified' : 'StealthIAMUser-LoggingConfigurationModified',\r\n 'Trojan:EC2/BlackholeTraffic' : 'TrojanEC2-BlackholeTraffic',\r\n 'Trojan:EC2/DropPoint' : 'TrojanEC2-DropPoint',\r\n 'Trojan:EC2/BlackholeTraffic!DNS' : 'TrojanEC2-BlackholeTrafficDNS',\r\n 'Trojan:EC2/DriveBySourceTraffic!DNS' : 'TrojanEC2-DriveBySourceTrafficDNS',\r\n 'Trojan:EC2/DropPoint!DNS' : 'TrojanEC2-DropPointDNS',\r\n 'Trojan:EC2/DGADomainRequest.B' : 'TrojanEC2-DGADomainRequestB',\r\n 'Trojan:EC2/DGADomainRequest.C!DNS' : 'TrojanEC2-DGADomainRequestCDNS',\r\n 'Trojan:EC2/DNSDataExfiltration' : 'TrojanEC2-DNSDataExfiltration',\r\n 'Trojan:EC2/PhishingDomainRequest!DNS' : 'TrojanEC2-PhishingDomainRequestDNS',\r\n 'UnauthorizedAccess:IAMUser/TorIPCaller' : 'UnauthorizedAccessIAMUser-TorIPCaller',\r\n 'UnauthorizedAccess:IAMUser/MaliciousIPCaller.Custom' : 'UnauthorizedAccessIAMUser-MaliciousIPCallerCustom',\r\n 'UnauthorizedAccess:IAMUser/ConsoleLoginSuccess.B' : 'UnauthorizedAccessIAMUser-ConsoleLoginSuccessB',\r\n 'UnauthorizedAccess:IAMUser/MaliciousIPCaller' : 'UnauthorizedAccessIAMUser-MaliciousIPCaller',\r\n 'UnauthorizedAccess:IAMUser/UnusualASNCaller' : 'UnauthorizedAccessIAMUser-UnusualASNCaller',\r\n 'UnauthorizedAccess:EC2/TorIPCaller' : 'UnauthorizedAccessEC2-TorIPCaller',\r\n 'UnauthorizedAccess:EC2/MaliciousIPCaller.Custom' : 'UnauthorizedAccessEC2-MaliciousIPCallerCustom',\r\n 'UnauthorizedAccess:EC2/SSHBruteForce' : 'UnauthorizedAccessEC2-SSHBruteForce',\r\n 'UnauthorizedAccess:EC2/RDPBruteForce' : 'UnauthorizedAccessEC2-RDPBruteForce',\r\n 'UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration' : 'UnauthorizedAccessIAMUser-InstanceCredentialExfiltration',\r\n 'UnauthorizedAccess:IAMUser/ConsoleLogin' : 'UnauthorizedAccessIAMUser-ConsoleLogin'\r\n }\r\n\r\nclass search_obj(object):\r\n def __init__(self, searchSTRING, objTYPE, objNAME):\r\n self.searchSTRING = searchSTRING\r\n self.objTYPE = objTYPE\r\n self.objNAME = objNAME\r\n self.hit = False\r\n self.json_resp = json.loads( fgt.get('cmdb', 'firewall', self.searchSTRING) )\r\n\r\n def function(self):\r\n if (self.objTYPE == 'placeholder'): pass\r\n elif (self.objTYPE == 'aggaddrgrp'): pass\r\n elif (self.objTYPE == 'aggaddrgrpmember'): pass\r\n elif (self.objTYPE == 'address'): print ('--> searching for duplicate address: %s' % self.objNAME)\r\n elif (self.objTYPE == 'addrgrp'): print ('--> searching for existing addrgrp: %s' % self.objNAME)\r\n elif (self.objTYPE == 'addrgrpmember'): print ('--> searching for existing addrgrp member: %s' % self.objNAME)\r\n\r\n if (self.json_resp['http_status'] == 200): \r\n self.hit = True\r\n if (self.objTYPE == 'placeholder'): pass\r\n elif (self.objTYPE == 'aggaddrgrp'): pass\r\n elif (self.objTYPE == 'aggaddrgrpmember'): pass\r\n elif (self.objTYPE == 'address'): print ('<-- duplicate address found')\r\n elif (self.objTYPE == 'addrgrp'): print ('<-- existing addrgrp found')\r\n elif (self.objTYPE == 'addrgrpmember'): print ('<-- duplicate addrgrp member found')\r\n\r\nclass create_obj(object):\r\n def __init__(self, objTYPE, objNAME, objVAL1, objVAL2):\r\n self.objTYPE = objTYPE\r\n self.objNAME = objNAME\r\n self.objVAL1 = objVAL1\r\n self.objVAL2 = objVAL2\r\n\r\n def function(self):\r\n if (self.objTYPE == 'ipv4'):\r\n print('--> creating IPv4 address: %s' % self.objNAME)\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', 'address', data={'name':self.objNAME, 'type':'ipmask', 'subnet':self.objVAL1, 'comment':self.objVAL2}) )\r\n elif (self.objTYPE == 'fqdn'):\r\n print('--> creating FQDN address: %s' % self.objNAME)\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', 'address', data={'name':self.objNAME, 'type':'fqdn', 'fqdn':self.objVAL1, 'comment':self.objVAL2}) )\r\n elif (self.objTYPE == 'addrgrp'):\r\n print('--> creating addrgrp: %s' % self.objNAME)\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', 'addrgrp', data={'name':self.objNAME, 'member':[{'name':self.objVAL1}]}) )\r\n elif (self.objTYPE == 'addrgrpmember'):\r\n print('--> appending address: %s to addrgrp: %s' % (self.objVAL1, self.objVAL2))\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', self.objNAME, data={'name':self.objVAL1}) )\r\n elif (self.objTYPE == 'aggaddrgrp'):\r\n print('--> creating aggregate addrgrp: %s' % self.objNAME)\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', 'addrgrp', data={'name':self.objNAME, 'member':[{'name':self.objVAL1}]}) )\r\n elif (self.objTYPE == 'aggaddrgrpmember'):\r\n print('--> appending addrgrp: %s to aggregate addrgrp: %s' % (self.objVAL1, self.objVAL2))\r\n self.json_resp = json.loads( fgt.post('cmdb', 'firewall', self.objNAME, data={'name':self.objVAL1}) )\r\n\r\n if (self.json_resp['http_status'] == 200): print('<-- http_status: %s' % self.json_resp['http_status'])\r\n else:\r\n if (self.objTYPE == 'ipv4'): print('<--!! failed to create IPv4 address, dumping response: %s' % json.dumps(self.json_resp))\r\n elif (self.objTYPE == 'fqdn'): print('<--!! failed to create FQDN address, dumping response: %s' % json.dumps(self.json_resp))\r\n elif (self.objTYPE == 'addrgrp'): print('<--!! failed to create addrgrp, dumping response: %s' % json.dumps(self.json_resp))\r\n elif (self.objTYPE == 'addrgrpmember'): print('<--!! failed to append address to addrgrp, dumping response: %s' % json.dumps(self.json_resp))\r\n elif (self.objTYPE == 'aggaddrgrp'): print('<--!! failed to create aggregate addrgrp, dumping response: %s' % json.dumps(self.json_resp))\r\n elif (self.objTYPE == 'aggaddrgrpmember'): print('<--!! failed to append addrgrp to aggregate addrgrp, dumping response: %s' % json.dumps(self.json_resp))\r\n\r\ndef logininfo_check():\r\n global fgtLOGINinfo\r\n global fgtLOGINlist\r\n global logininfoerrors\r\n ### check if fgtLOGINinfo is an encrypted value or not by searching for commas\r\n cleartext=(bool(re.match('.*,.*', fgtLOGINinfo)))\r\n if cleartext is False:\r\n ### decrypt the encrypted environment variable in transit with the KMS key used to encrypt it\r\n print('>> decrypting fgtLOGINinfo environment variable with KMS key')\r\n try:\r\n fgtLOGINinfo = boto3.client('kms').decrypt(CiphertextBlob=b64decode(os.environ['fgtLOGINinfo']))['Plaintext'].decode('utf-8')\r\n except TypeError as malformedERROR: print('<--!! encyrpted string is truncated or malformed: %s' % malformedERROR)\r\n except Exception as generalERROR: print('<--!! general error: %s' % generalERROR)\r\n ### split the single string of fgt login information into each fgt's entry\r\n fgtLOGINlist=fgtLOGINinfo.split('|')\r\n ### for each entry, count the total number of attributes and divide by 1\r\n for entry in fgtLOGINlist:\r\n fgtLOGINattributes=entry.split(',')\r\n fgtLOGINtuples=(len(fgtLOGINattributes)/1)\r\n ### if the result is 3, then assume the entries are the fgt ip, admin, and password\r\n if (fgtLOGINtuples == 3):\r\n fgtIP,fgtADMIN,fgtPASS=entry.split(',')\r\n ### if the result is not 3, then print that we are missing a login attribute for this fgt\r\n else:\r\n print('<--!! missing a login attribute for one of the FGT entries')\r\n logininfoerrors+=1\r\n\r\ndef addrgrp_batch_check():\r\n global fgt\r\n for entry in fgtLOGINlist:\r\n print ('-=-' * 20)\r\n fgtIP,fgtADMIN,fgtPASS=entry.split(',')\r\n try:\r\n print('--> logging into fgtIP %s with user %s' % (fgtIP, fgtADMIN))\r\n fgt = FortiOSREST()\r\n fgt.debug(fgtDEBUG)\r\n fgt.login(fgtIP, fgtADMIN, fgtPASS)\r\n ### check if the placeholder address exists already, if not create it\r\n addrSEARCH = 'address/'+placeholderNAME+'?format=name'\r\n search1 = search_obj(addrSEARCH, 'placeholder', placeholderNAME)\r\n search1.function()\r\n if search1.hit is False:\r\n \tcreate1 = create_obj('ipv4', placeholderNAME, '0.0.0.0/32', 'placeholder object for creation of dynamic address groups')\r\n \tcreate1.function()\r\n ### check if the aggregate addrgrp exists already, if not create it\r\n aggaddrgrpSEARCH = 'addrgrp/'+aggaddrgrpNAME+'?format=name'\r\n search2 = search_obj(aggaddrgrpSEARCH, 'aggaddrgrp', aggaddrgrpNAME)\r\n search2.function()\r\n if search2.hit is False:\r\n\t create2 = create_obj('aggaddrgrp', aggaddrgrpNAME, placeholderNAME, None)\r\n\t create2.function()\r\n ### check if each target addrgrp exists already, if not create it and append to the aggregate addrgrp\r\n print('>> checking if each target addrgrp exists')\r\n for key, value in gd2fgtTYPE.iteritems():\r\n addrgrpSEARCH = 'addrgrp/'+addrgrpPREFIX+value+'?format=name'\r\n addrgrpNAME = addrgrpPREFIX+value\r\n aggaddrgrpPATH = 'addrgrp/'+aggaddrgrpNAME+'/member'\r\n search3 = search_obj(addrgrpSEARCH, 'addrgrp', addrgrpNAME)\r\n search3.function()\r\n if search3.hit is False:\r\n create3 = create_obj('addrgrp', addrgrpNAME, placeholderNAME, None)\r\n create3.function()\r\n create4 = create_obj('aggaddrgrpmember', aggaddrgrpPATH, addrgrpNAME, aggaddrgrpNAME)\r\n create4.function()\r\n print('--> logging out of fgtIP: %s' % fgtIP)\r\n fgt.logout()\r\n except Exception as generalERROR:\r\n print('<--!! general error: %s' % generalERROR)\r\n\r\ndef process_event(event, context):\r\n global fgt\r\n ### if the event is not null, parse general event values \r\n if (event is not None):\r\n print('-=-' * 20)\r\n print('>> parsing GD event details')\r\n print('Id: %s' % event['detail']['id'])\r\n print('Title: %s' % event['detail']['title'])\r\n print('Type: %s' % event['detail']['type'])\r\n ### use regex to remove special characters from the event type field for use as an addrgrp name\r\n origTYPE = event['detail']['type']\r\n sanitizedTYPE = re.sub(r':|\\.|!|', '', origTYPE)\r\n sanitizedTYPE = re.sub(r'\\/', '-', sanitizedTYPE)\r\n sanitizedTYPE = re.sub(r'&', 'n', sanitizedTYPE)\r\n grpNAME = addrgrpPREFIX+sanitizedTYPE\r\n print('Sanitized Type: %s' % sanitizedTYPE)\r\n print('Target Addrgrp: %s' % grpNAME)\r\n ### each address object will have the finding id and title of the related event in the comments of the object\r\n addrCOMMENT = 'FindingId-'+event['detail']['id']+'. '+event['detail']['title']\r\n ### based on the action type, different fields will be parsed as the event format is different\r\n print('ActionType: %s' % event['detail']['service']['action']['actionType'])\r\n try:\r\n if (event['detail']['service']['action']['actionType'] == 'AWS_API_CALL'):\r\n addrIPv4 = event['detail']['service']['action']['awsApiCallAction']['remoteIpDetails']['ipAddressV4']\r\n print('IPv4: %s' % addrIPv4)\r\n elif (event['detail']['service']['action']['actionType'] == 'NETWORK_CONNECTION'):\r\n resourceIPv4 = event['detail']['resource']['instanceDetails']['networkInterfaces'][0]['privateIpAddress']\r\n remoteIPv4 = event['detail']['service']['action']['networkConnectionAction']['remoteIpDetails']['ipAddressV4']\r\n if (event['detail']['service']['resourceRole'] == 'ACTOR'):\r\n addrIPv4 = resourceIPv4\r\n else:\r\n addrIPv4 = remoteIPv4\r\n print('ResourceRole: %s' % event['detail']['service']['resourceRole'])\r\n print('Resource IPv4: %s' % resourceIPv4)\r\n print('Remote IPv4: %s' % remoteIPv4)\r\n elif (event['detail']['service']['action']['actionType'] == 'DNS_REQUEST'):\r\n addrFQDN = event['detail']['service']['action']['dnsRequestAction']['domain']\r\n addrIPv4 = ''\r\n print('domain: %s' % addrFQDN)\r\n elif (event['detail']['service']['action']['actionType'] == 'PORT_PROBE'):\r\n resourceIPv4 = event['detail']['resource']['instanceDetails']['networkInterfaces'][0]['privateIpAddress']\r\n remoteIPv4 = event['detail']['service']['action']['portProbeAction']['portProbeDetails'][0]['remoteIpDetails']['ipAddressV4']\r\n if (event['detail']['service']['resourceRole'] == 'ACTOR'):\r\n addrIPv4 = resourceIPv4\r\n else:\r\n addrIPv4 = remoteIPv4\r\n print('ResourceRole: %s' % event['detail']['service']['resourceRole'])\r\n print('Resource IPv4: %s' % resourceIPv4)\r\n print('Remote IPv4: %s' % remoteIPv4)\r\n else:\r\n print('<--!! unknown event action type: %s' % event['detail']['service']['action']['actionType'])\r\n print('<--!! exiting now')\r\n sys.exit()\r\n except KeyError: pass\r\n\r\n ### login to each FGT and push the address object to it based on the event parsing above\r\n print('>> preparing GD address based on event details.')\r\n for entry in fgtLOGINlist:\r\n fgtIP,fgtADMIN,fgtPASS=entry.split(',')\r\n print('--' * 20)\r\n try:\r\n print('--> logging into fgtIP %s with user %s' % (fgtIP, fgtADMIN))\r\n fgt = FortiOSREST()\r\n fgt.debug(fgtDEBUG)\r\n fgt.login(fgtIP, fgtADMIN, fgtPASS)\r\n ### if there is an IPv4 value, set the variables for the object name and search value\r\n if (addrIPv4 != ''):\r\n addrIPv4host = addrIPv4+'/32'\r\n addrNAME = addripPREFIX+addrIPv4\r\n addrSEARCH = 'address/'+addrNAME+'?format=name'\r\n search1 = search_obj(addrSEARCH, 'address', addrNAME)\r\n search1.function()\r\n if search1.hit is False:\r\n create1 = create_obj('ipv4', addrNAME, addrIPv4host, addrCOMMENT)\r\n create1.function()\r\n ### if there is an FQDN value, set the variables for the object name and search value\r\n elif (addrFQDN != ''):\r\n addrNAME = addrfqdnPREFIX+addrFQDN\r\n addrSEARCH = 'address/'+addrNAME+'?format=name'\r\n search1 = search_obj(addrSEARCH, 'address', addrNAME)\r\n search1.function()\r\n if search1.hit is False:\r\n create1 = create_obj('fqdn', addrNAME, addrFQDN, addrCOMMENT)\r\n create1.function()\r\n ### skip creating an address object if both the IPv4 and FQDN values are empty\r\n else:\r\n print('<--!! Skipping address, missing either a valid IPv4 or FQDN value to use!')\r\n print('--> logging out of fgtIP: %s' % fgtIP)\r\n fgt.logout()\r\n continue\r\n ### if the addrgrpBATCHcreate is turned off, verify the target addrgrp exists, if it does not exist then create it\r\n if (addrgrpBATCHcreate == 'off'):\r\n addrgrpSEARCH = 'addrgrp/'+grpNAME+'?format=name'\r\n search2 = search_obj(addrgrpSEARCH, 'addrgrp', grpNAME)\r\n search2.function()\r\n if search2.hit is False:\r\n create2 = create_obj('addrgrp', grpNAME, placeholderNAME, None)\r\n create2.function()\r\n ### append address object to the target addrgrp\r\n addrgrpmemberSEARCH = 'addrgrp/'+grpNAME+'/member/'+addrNAME+'?format=name'\r\n search3 = search_obj(addrgrpmemberSEARCH, 'addrgrpmember', addrNAME)\r\n search3.function()\r\n if search3.hit is False:\r\n grpPATH = 'addrgrp/'+grpNAME+'/member'\r\n create3 = create_obj('addrgrpmember', grpPATH, addrNAME, grpNAME)\r\n create3.function()\r\n print('--> logging out of fgtIP: %s' % fgtIP)\r\n fgt.logout()\r\n except Exception as generalERROR:\r\n print('<--!! general error: %s' % generalERROR)\r\n print('-=-' * 20)\r\n\r\ndef lambda_handler(event, context):\r\n print('-=-' * 20)\r\n print('>> Function triggered!')\r\n print('>> addripPREFIX: %s' % addripPREFIX)\r\n print('>> addrfqdnPREFIX: %s' % addrfqdnPREFIX)\r\n print('>> addrgrpPREFIX: %s' % addrgrpPREFIX)\r\n print('>> placeholderaddrNAME: %s' % placeholderNAME)\r\n print('>> aggaddrgrpNAME: %s' % aggaddrgrpNAME)\r\n print('>> addrgrpBATCHcreate: %s' % addrgrpBATCHcreate)\r\n print('>> fgtapiTIMOUET: %s' % fgtTIMEOUT)\r\n print('>> fgtapiDEBUG: %s' % fgtDEBUG)\r\n print('>> raw guard duty event: %s' % json.dumps(event))\r\n logininfo_check()\r\n if (logininfoerrors != 0):\r\n print('<--!! correct the errors in the fgt login info for the function to run successfully')\r\n print('-=-' * 20)\r\n elif (addrgrpBATCHcreate != 'on') and (addrgrpBATCHcreate != 'off'):\r\n print('<--!! set the addrgrpBATCHcreate environment variable to either on or off for the function to run successfully')\r\n print('-=-' * 20)\r\n elif (fgtDEBUG != 'on') and (fgtDEBUG != 'off'):\r\n print('<--!! set the fgtapiDEBUG environment variable to either on or off for the function to run successfully')\r\n print('-=-' * 20)\r\n elif (addrgrpBATCHcreate == 'on'):\r\n addrgrp_batch_check()\r\n process_event(event, context)\r\n elif (addrgrpBATCHcreate == 'off'):\r\n process_event(event, context)\r\n#\r\n# end of script\r\n#","sub_path":"Templates/Lab/aws-gd-fgt.py","file_name":"aws-gd-fgt.py","file_ext":"py","file_size_in_byte":20673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"621375414","text":"# -*- coding: utf-8 -*-\n\"\"\"\ncsvファイルに対して処理を行うmodule\n\"\"\"\n\nimport pandas\nimport re\nimport constants as const\nfrom os import path\nfrom csv import QUOTE_ALL\nfrom pandas.io.common import EmptyDataError\n\n\"\"\"\n機能 : csvファイルを読み込み、DataFrameに変換する\n csvファイルにヘッダが無い場合、DataFrame(newData)のheaderには、1から始まる列番号を自動的に設定する\n引数 :\n string : csvファイのfull path\n int : csvファイルにheader行が存在するかを表すflag (0 = header行が無い、 1 = header行が有る)\n戻り値 :\n int : ステータス\n string : メッセージ\n DataFrame : DataFrameに変換したデータ\n int : csvファイル内のデータの行数\n int : csvファイル内のデータの列数\n\"\"\"\ndef csvfl_csvToDataFrame (csvFullPath, existHeaderFlag):\n result = const.RESULT_COMPLETE # ステータス\n msg = const.MSG_COMPLETE # メッセージ\n newData = pandas.DataFrame() # DataFrameに変換したデータ\n countRows = 0 # csvファイル内のデータの行数\n countColumns = 0 # csvファイル内のデータの列数\n\n try:\n # [csvFullPath]が[string]のデータ型以外の場合\n if type(csvFullPath) is not str:\n raise Exception\n\n # [existHeaderFlag]が[int]のデータ型以外、または [existHeaderFlag]が[int]のデータ型であり、且つ0、1以外の場合\n if type(existHeaderFlag) is not int or (existHeaderFlag != 0 and existHeaderFlag != 1):\n raise Exception\n\n csvFullPath = csvFullPath.strip()\n # CSVファイルがない\n if not path.isfile(csvFullPath):\n result = const.RESULT_ERR\n msg = const.MSG_ERR_NOT_EXIST_FILE.format(csvFullPath)\n return\n\n file_extension = path.splitext(path.basename(csvFullPath))[1]\n # CSVファイルのフォーマットが不正\n if (str.lower(file_extension) != const.CSV_EXTENSION):\n result = const.RESULT_ERR\n msg = const.MSG_ERR_INVALID_FORMAT_FILE\n return\n\n # csvファイルにヘッダが無い場合、DataFrame(newData)のheaderには、1から始まる列番号を自動的に設定する\n if existHeaderFlag == 0:\n tp = pandas.read_csv(csvFullPath, sep=const.CSV_SEP, encoding=const.CSV_ENCODING, dtype=str, header=None,\n skipinitialspace=True, keep_default_na=False, low_memory=False, chunksize=10000)\n newData = pandas.concat(tp, ignore_index=True)\n newData.set_axis(1, range(1, newData.shape[1] + 1))\n else:\n tp = pandas.read_csv(csvFullPath, sep=const.CSV_SEP, encoding=const.CSV_ENCODING, dtype=str, header=0,\n skipinitialspace=True, keep_default_na=False, low_memory=False, chunksize=10000)\n newData = pandas.concat(tp, ignore_index=True)\n\n countRows = newData.shape[0] + 1\n countColumns = newData.shape[1]\n\n # CSVファイルがない\n except OSError:\n result = const.RESULT_ERR\n msg = const.MSG_ERR_NOT_OPEN_FILE.format(csvFullPath)\n\n # CSVファイルのフォーマットの中身がNULL\n except EmptyDataError:\n result = const.RESULT_ERR\n msg = const.MSG_ERR_EMPTY_FILE\n\n # 予期しなかったError\n except Exception:\n result = const.RESULT_ERR_UNEXPECTED\n msg = const.MSG_ERR_UNEXPECTED\n\n finally:\n return result, msg, newData, countRows, countColumns\n\n\"\"\"\n機能 : DataFrame形式のデータをcsvファイルに出力する\n header行を出力するかどうかを選択することが出来る\n引数 :\n DataFrame : DataFrame形式のデータ\n int : header行を出力するかを表すflag (0 = header行を出力しない、 1 = header行を出力する)\n int : 上書き保存するかどうかのflag\n string : csvファイルの出力先\n string : 出力するcsvファイの名前\n戻り値 :\n int : ステータス\n string : メッセージ\n string : 出力したcsvファイルの名前\n\"\"\"\ndef csvfl_dataFrameToCsv (source, existHeaderFlag, ovwFlag, directory, csvName):\n result = const.RESULT_COMPLETE # ステータス\n msg = const.MSG_COMPLETE # メッセージ\n newName = csvName # 出力したcsvファイルの名前\n\n try:\n # sourceのformatが不正\n if type(source) is not pandas.core.frame.DataFrame:\n result = const.RESULT_ERR\n msg = const.MSG_ERR_INVALID_FORMAT_SOURCE\n return\n\n # [existHeaderFlag]が[int]のデータ型以外、または [existHeaderFlag]が[int]のデータ型であり、且つ0、1以外の場合\n if type(existHeaderFlag) is not int or (existHeaderFlag != 0 and existHeaderFlag != 1):\n raise Exception\n\n # [ovwFlag]が[bool]のデータ型以外の場合\n if type(ovwFlag) is not bool:\n # [ovwFlag]が[int]のデータ型以外、または [ovwFlag]が[int]のデータ型であり、且つ0、1以外の場合\n if type(ovwFlag) is not int or (ovwFlag != 0 and ovwFlag != 1):\n raise Exception\n\n # [directory]が[string]のデータ型以外の場合\n if type(directory) is not str:\n raise Exception\n\n # [csvName]が[string]のデータ型以外の場合\n if type(csvName) is not str:\n raise Exception\n\n directory = directory.strip()\n newName = csvName.strip()\n\n # sourceがNULL\n if not source.shape[0] and not source.shape[1]:\n result = const.RESULT_ERR\n msg = const.MSG_ERR_EMPTY_SOURCE\n return\n\n # [newName]が空白の場合\n # ファイル名が不正 (¥ / : * ? \" < > |が含まれる)\n if newName == \"\" or re.match(r'.*[\\\\\\¥\\/\\:\\*\\?\\\"\\<\\>\\|].*', newName):\n result = const.RESULT_ERR\n msg = const.MSG_ERR_INVALID_FILE_NAME_CSV.format(newName)\n return\n\n file_extension = path.splitext(newName)[1]\n # 拡張子がないファイル名の場合\n if (str.lower(file_extension) != const.CSV_EXTENSION):\n newName+=const.CSV_EXTENSION\n\n # 指定されたdirectoryがない\n if not path.isdir(directory):\n result = const.RESULT_ERR\n msg = const.MSG_ERR_NOT_EXIST_DIRECTORY.format(directory)\n return\n\n csvFullPath = path.join(directory, newName)\n fileName = path.splitext(newName)[0]\n # ovwFlag(上書き保存flag)=Falseが設定され\n # ovwFlag(上書き保存flag)=0が設定され\n if(ovwFlag == False or ovwFlag == 0):\n i = 1;\n # ファイルが既に存在している場合\n while (path.isfile(csvFullPath)):\n newName = fileName + '(' + str(i) + ')'+ const.CSV_EXTENSION\n csvFullPath = path.join(directory, newName)\n i+=1\n\n # CSVファイル出力\n if existHeaderFlag == 0: # header行を出力しない\n source.to_csv(csvFullPath, sep=const.CSV_SEP, index=False, header=False, line_terminator=const.CSV_LINE_TERMINATOR,\n quotechar=const.CSV_QUOTECHAR, quoting=QUOTE_ALL, encoding=const.CSV_ENCODING, chunksize=10000)\n else:\n source.to_csv(csvFullPath, sep=const.CSV_SEP, index=False, header=True, line_terminator=const.CSV_LINE_TERMINATOR,\n quotechar=const.CSV_QUOTECHAR, quoting=QUOTE_ALL, encoding=const.CSV_ENCODING, chunksize=10000)\n\n # CSV ファイルが保存できない\n except PermissionError:\n result = const.RESULT_ERR\n msg = const.MSG_ERR_CREATE_FILE.format(csvFullPath)\n\n # 予期しなかったError\n except Exception:\n result = const.RESULT_ERR_UNEXPECTED\n msg = const.MSG_ERR_UNEXPECTED\n\n finally:\n return result, msg, newName\n\nif __name__=='__main__':\n pass","sub_path":"src/csv_file.py","file_name":"csv_file.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"304477686","text":"#!python3\n\nimport os, pickle, sys\n\n'''\n scirpt: creatOffRec.py\n date: 2016-02-17\n author: jianblog\n note: when local disk with saved logs need plug off, we create a offline dict file to save log detail, \n dict saved in same partition with log directory, and use relative path \n example: creatOffDic.py /datb/dicts/192.168.1.231_a6click.dic /datb/backup/ios/offerwall/accesslog/5logs\n it will scan target logpath and create this new dict file and use relative path:\n [('192.168.1.231', 'iowa5', '../backup/ios/offerwall/accesslog/5logs')] \n'''\n\nAPP_DIR = os.path.dirname(os.path.abspath(__file__))\nDICT_DIR = os.path.join(APP_DIR, 'rconf')\n\nif __name__ == '__main__':\n dict = {}\n fullname = ''\n log_path = ''\n if len(sys.argv) >2:\n fullname = sys.argv[1]\n log_path = os.path.normpath(sys.argv[2])\n \n else:\n print(\"useage: creatOffDic.py target_dict log_path\")\n exit(1)\n\n # use dict_name to load original dict file\n target_path, dict_name = os.path.split(fullname)\n source_ip, source_mod = os.path.splitext(dict_name)[0].split('_')\n\n # use relative path to show find logs directory from dict\n logpath_rel = os.path.relpath(log_path, start=target_path)\n dict['group'] = []\n dict['group'].append( (source_ip, source_mod, logpath_rel) )\n dict['records'] = {}\n \n\n for path, subpath, files in os.walk(log_path):\n relpath = os.path.relpath(path, start=log_path)\n for file in files:\n dict['records'][os.path.join(relpath, file)] = 1\n\n \n with open(fullname, 'wb') as f:\n pickle.dump(dict, f)\n\n","sub_path":"managerSync/creatOffRec.py","file_name":"creatOffRec.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"346714809","text":"# -*- coding: utf-8 -*-\r\nimport random\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx= random.sample(range(0,90),10)\r\nSIN= np.tile(0.0,10)\r\nCOSIN= np.tile(0.0,10)\r\nfor i in range(0,10):\r\n SIN[i]= math.sin(x[i])\r\nfor i in range(0,10):\r\n COSIN[i]= math.cos(x[i]) \r\n \r\nplt.plot(x,SIN,'ro') \r\nplt.xlabel('random numbers')\r\nplt.ylabel('SIN x(red) & COSIN x (blue)')\r\nplt.plot(x,COSIN,'bo')\r\n \r\n \r\n ","sub_path":"Romeo_assigment1/assigment1.py","file_name":"assigment1.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"483024219","text":"from turtle import *\nfrom random import *\nfrom math import *\n\ndef tree(n,l):\n pd()#下笔\n #阴影效果\n t = cos(radians(heading()+45))/8+0.25\n pencolor(t,t,t)\n pensize(n/3)\n forward(l)#画树枝\n\n if n>0:\n b = random()*15+10 #右分支偏转角度\n c = random()*15+10 #左分支偏转角度\n d = l*(random()*0.25+0.7) #下一个分支的长度\n #右转一定角度,画右分支\n right(b)\n tree(n-1,d)\n #左转一定角度,画左分支\n left(b+c)\n tree(n-1,d)\n #转回来\n right(c)\n else:\n #画叶子\n right(90)\n n=cos(radians(heading()-45))/4+0.5\n pencolor(n,n*0.8,n*0.8)\n circle(3)\n left(90)\n #添加0.3倍的飘落叶子\n if(random()>0.7):\n pu()\n #飘落\n t = heading()\n an = -40 +random()*40\n setheading(an)\n dis = int(800*random()*0.5 + 400*random()*0.3 + 200*random()*0.2)\n forward(dis)\n setheading(t)\n #画叶子\n pd()\n right(90)\n n = cos(radians(heading()-45))/4+0.5\n pencolor(n*0.5+0.5,0.4+n*0.4,0.4+n*0.4)\n circle(2)\n left(90)\n pu()\n #返回\n t=heading()\n setheading(an)\n backward(dis)\n setheading(t)\n pu()\n backward(l)#退回\n\nbgcolor(0.5,0.5,0.5)#背景色\nht()#隐藏turtle\nspeed(0)#速度 1-10渐进,0 最快\ntracer(0,0)\npu()#抬笔\nbackward(100)\nleft(90)#左转90度\npu()#抬笔\nbackward(300)#后退300\ntree(12,100)#递归7层\n# penup()\n# left(500)\n# fd(200)\n# pendown()\n# right(300)\nprinter = Turtle()\n# printer.hideturtle()\nprinter.penup()\nprinter.back(-300)\nprinter.right(90)\nprinter.back(-200)\n# printer.goto(500, 500)\n\n# printer.write(\"Every time you say \\\"I love you\\\",\\n\\nmy world blossoms.\\n\\n\", align=\"left\", font=(\"Arial\", 16, \"bold\"))\nprinter.write(\"Every time you say \\\"I love you\\\",\\n\\nmy world blossoms.\\n\\nCandice, Love You Three Thousand, always~\\n\\n\", align=\"center\", font=(\"Arial\", 16, \"bold\"))\nprinter.write(\" ———— from Vincent\", align=\"left\", font=(\"Arial\", 14, \"normal\"))\n\ndone()","sub_path":"网络爬虫/tree2.py","file_name":"tree2.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"599771084","text":"import numpy as np\nimport copy\nfrom amalearn.agent import AgentBase\n\nSTATES_COUNT = 20000\nNOTHING = 3\nB = 0\nC = 1\nD = 2\nACTIONS = [NOTHING, B, C, D, (B, C), (B, D), (C, D)]\n\nclass StockAgent(AgentBase):\n def __init__(self, id, environment, discount_factor):\n super(StockAgent, self).__init__(id, environment)\n self.discount_factor = discount_factor\n self.tetha = 0.01\n self.state_value = [0 for _ in range(STATES_COUNT)]\n # Because we now that optimal policy is greedy\n self.policy = [0 for _ in range(STATES_COUNT)]\n\n def evaluate_policy(self):\n stock_values = [index * 5 for index in range(1, 11)]\n wealth_values = [index * 5 for index in range(1, 21)]\n while True:\n delta = 0\n for wealth_index, wealth_value in enumerate(wealth_values):\n for b_index, b_value in enumerate(stock_values):\n for c_index, c_value in enumerate(stock_values):\n for d_index, d_value in enumerate(stock_values):\n if self.environment.is_terminal(wealth_value):\n continue\n state_index = wealth_index * 1000 + b_index * 100 + c_index * 10 + d_index\n old_state_value = self.state_value[state_index]\n optimal_action = self.policy[state_index]\n next_state_probability_reward = self.environment.get_probability_and_reward(wealth_value, b_value, c_value, d_value, optimal_action)\n new_state_value = 0\n for state_probability_reward in next_state_probability_reward:\n next_state_index, reward, probability = state_probability_reward\n new_state_value += (probability * (reward + self.discount_factor * self.state_value[next_state_index]))\n new_diff = abs(new_state_value - old_state_value)\n if new_diff > delta:\n delta = new_diff\n self.state_value[state_index] = new_state_value\n print(\"Delta: {}\".format(delta))\n if delta < self.tetha:\n break\n\n def improve_policy(self):\n policy_stable = True\n stock_values = [index * 5 for index in range(1, 11)]\n wealth_values = [index * 5 for index in range(1, 21)]\n for wealth_index, wealth_value in enumerate(wealth_values):\n for b_index, b_value in enumerate(stock_values):\n for c_index, c_value in enumerate(stock_values):\n for d_index, d_value in enumerate(stock_values):\n state_index = wealth_index * 1000 + b_index * 100 + c_index * 10 + d_index\n old_action = self.policy[state_index]\n action_values = []\n for action_index in range(len(ACTIONS)):\n next_state_probability_reward = self.environment.get_probability_and_reward(wealth_value, b_value, c_value, d_value, action_index)\n new_action_value = 0\n for state_probability_reward in next_state_probability_reward:\n next_state_index, reward, probability = state_probability_reward\n new_action_value += (probability * (reward + self.discount_factor * self.state_value[next_state_index]))\n action_values.append(new_action_value)\n if state_index == 3021:\n print(\"Action values:\\n {}\".format(action_values))\n new_optimal_action = np.argmax(np.array(action_values))\n self.policy[state_index] = new_optimal_action\n if new_optimal_action != old_action:\n policy_stable = False\n return policy_stable\n \n\n def iterate_policy(self):\n iteration_count = 0\n while True:\n iteration_count += 1\n print(\"Iteration #: {}\".format(iteration_count))\n self.evaluate_policy()\n policy_stable = self.improve_policy()\n print(\"__________________________________________\")\n if policy_stable:\n break\n \n def take_action(self) -> (object, float, bool, object):\n return None, 0, False, None\n\n def print_optimal_policy(self, initial_state_index):\n optimal_action_index = self.policy[initial_state_index]\n optimal_action = ACTIONS[optimal_action_index]\n print(\"Optimal Action:\")\n if optimal_action == NOTHING:\n print(\"Nothing\")\n if optimal_action == B or (type(optimal_action) is tuple and B in optimal_action):\n print(\"B\")\n if optimal_action == C or (type(optimal_action) is tuple and C in optimal_action):\n print(\"C\")\n if optimal_action == D or (type(optimal_action) is tuple and D in optimal_action):\n print(\"D\")\n","sub_path":"code/amalearn/agent/stock_agent.py","file_name":"stock_agent.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"280198787","text":"#######################################################################################################################################\n# \n#\n#\n#\n#\n#######################################################################################################################################\n\nimport logging\nimport sys\nimport boto3\nimport time\nimport csv\nimport json\n\nfrom datetime import datetime, timedelta, date\nfrom pyspark.sql import SparkSession\n#from pyspark.sql.functions import *\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.types import *\n \n#===================================================================================================\ndef getJsonLocalData(i_fileFullPath):\n \n try:\n f = open(i_fileFullPath)\n data = json.load(f)\n except Exception as e:\n raise e\n \n print(json.dumps(data, indent=2, sort_keys=False))\n return data\n\n#===================================================================================================\ndef getJsonS3Data(i_s3Bucket, i_s3Key):\n \n try:\n s3 = boto3.client('s3')\n data = s3.get_object(Bucket=i_s3Bucket, Key=i_s3Key)\n json_data = data['Body'].read().decode('utf-8')\n data = json.loads(json_data)\n except Exception as e:\n raise e\n \n print(json.dumps(data, indent=2, sort_keys=False))\n return data\n\n#===================================================================================================\ndef processInputs(i_spark, i_inputMetaData):\n \n dfDict = {}\n try:\n for item1 in i_inputMetaData:\n print(item1)\n path = \"s3a://\"\n if \"Location\" in item1:\n location = item1[\"Location\"]\n if location == 'hdfs':\n path = \"hdfs:///\"\n elif location == 'file':\n path = \"file:///\"\n\n fileName = path + item1[\"formatted_path\"] + \"/\" + item1[\"formatted_key\"]\n print('fileName : ', fileName)\n \n sourceFormat = item1[\"SourceFormat\"] if \"SourceFormat\" in item1 else \"csv\"\n inferSchema = item1[\"InferSchema\"] if \"InferSchema\" in item1 else \"true\"\n csvHeader = item1[\"CsvHeader\"] if \"CsvHeader\" in item1 else \"true\"\n \n if sourceFormat == 'csv':\n tempDf = i_spark.read.format(sourceFormat)\\\n .option(\"inferSchema\",inferSchema)\\\n .option(\"header\",csvHeader)\\\n .load(fileName)\n else:\n tempDf = i_spark.read.format(sourceFormat).load(fileName)\n \n viewName = item1[\"ViewName\"]\n dfDict[viewName] = tempDf\n \n if \"PartitionKeys\" in item1 and \"NumPartitions\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(int(item1[\"NumPartitions\"]), *item1[\"PartitionKeys\"])\n elif \"NumPartitions\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(int(item1[\"NumPartitions\"]))\n elif \"PartitionKeys\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(*item1[\"PartitionKeys\"])\n \n if \"Cache\" in item1:\n if item1[\"Cache\"]:\n dfDict[viewName].cache()\n \n dfDict[viewName].createOrReplaceTempView(viewName)\n \n except Exception as e:\n raise e\n \n return dfDict\n\n#===================================================================================================\ndef processOutputs(i_spark, i_dataframes, i_outputMetaData):\n \n try:\n for item1 in i_outputMetaData:\n print(item1)\n \n viewName = item1[\"ViewName\"]\n tempDf = i_dataframes[viewName]\n \n fileFormat = \"csv\"\n if \"TargetFormat\" in item1:\n fileFormat = item1[\"TargetFormat\"]\n \n writeMode = \"error\"\n if \"SparkSaveMode\" in item1:\n writeMode = item1[\"SparkSaveMode\"]\n \n path = \"s3a://\"\n if \"Location\" in item1:\n location = item1[\"Location\"]\n if location == 'hdfs':\n path = \"hdfs:///\"\n elif location == 'file':\n path = \"file:///\"\n\n fileName = path + item1[\"formatted_path\"] + \"/\" + item1[\"formatted_key\"]\n print('fileName : ', fileName)\n #tempDf.write.format(fileFormat).mode(writeMode).save(fileName)\n \n except Exception as e:\n raise e\n\n#===================================================================================================\ndef buildJsonDF(i_spark, i_dataframes, i_transformMetaData):\n \n dfDict = i_dataframes\n try:\n for idx1 in i_transformMetaData:\n print(idx1)\n item1 = i_transformMetaData[idx1]\n \n viewName = item1[\"ViewName\"]\n if \"SparkQuery\" in item1:\n dfDict[viewName] = i_spark.sql(item1[\"SparkQuery\"])\n elif \"SparkTransform\" in item1:\n exec(item1[\"SparkTransform\"])\n else:\n raise ValueError('SparkQuery or SparkTransform are missing. One of the option is needed.') \n \n if \"PartitionKeys\" in item1 and \"NumPartitions\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(int(item1[\"NumPartitions\"]), *item1[\"PartitionKeys\"])\n elif \"NumPartitions\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(int(item1[\"NumPartitions\"]))\n elif \"PartitionKeys\" in item1:\n dfDict[viewName] = dfDict[viewName].repartition(*item1[\"PartitionKeys\"])\n \n if \"Cache\" in item1:\n if item1[\"Cache\"]:\n dfDict[viewName].cache()\n \n dfDict[viewName].createOrReplaceTempView(viewName)\n \n \n except Exception as e:\n raise e\n \n return dfDict\n\n#===================================================================================================\nLOGGER = logging.getLogger()\nLOGGER.setLevel(logging.INFO)\n\nLOGGER.info('Starting ak-spark-etl-transform : ', datetime.now().strftime('%m/%d/%Y %H:%M:%S'))\n#---------------------------------------------------------------------------------------------------\nprocess_status=\"Successful\"\n\nmeta_bucket = 'bucketname'\nmeta_key = 'metadata/some_meta.json'\ntry:\n #meta_data = getJsonS3Data(meta_bucket, meta_key)\n meta_data = getJsonLocalData('D:/xxx/json_gen_meta.json')\n\n spark = SparkSession.builder \\\n .appName(\"Spark ETL\") \\\n .getOrCreate()\n\n #spark.sparkContext.setLogLevel('WARN') \n '''\n # to get default credentials \n # to specify credentials \n spark._jsc.hadoopConfiguration().set(\"fs.s3a.awsAccessKeyId\", \"[ACCESS KEY]\")\n spark._jsc.hadoopConfiguration().set(\"fs.s3a.awsSecretAccessKey\", \"[SECRET KEY]\")\n # SSE-KMS doesn't work in 2.8.5\n spark._jsc.hadoopConfiguration().set(\"fs.s3a.server-side-encryption-algorithm\", \"SSE-KMS\")\n spark._jsc.hadoopConfiguration().set(\"fs.s3a.server-side-encryption.key\", \"arn:aws:kms:us-east-1:nnnnnn:key/xxx-xxx-xxx\")\n '''\n spark._jsc.hadoopConfiguration().set(\"f3.s3a.impl\", \"org.apache.hadoop.fs.s3a.S3AFileSystem\")\n spark._jsc.hadoopConfiguration().set(\"f3.s3a.region\", \"us-east-1\")\n spark._jsc.hadoopConfiguration().set(\"mapreduce.fileoutputcommitter.algorithm.version\", \"2\")\n spark._jsc.hadoopConfiguration().set(\"fs.s3a.aws.credentials.provider\", \"com.amazonaws.auth.DefaultAWSCredentialsProviderChain\")\n \n dataframes = {}\n \n if \"inputs\" in meta_data:\n dataframes = processInputs(spark, meta_data[\"inputs\"])\n else:\n raise Exception(\"Atleast one input is required exception\")\n \n '''\n for key1 in dataframes:\n dataframes[key1].printSchema()\n dataframes[key1].show(10)\n \n if \"output_json\" in meta_data:\n dataframes = buildJsonDF(spark, dataframes, meta_data[\"transformations\"])\n \n for key1 in dataframes:\n dataframes[key1].printSchema()\n dataframes[key1].show(10)\n \n if \"outputs\" in meta_data:\n processOutputs(spark, dataframes, meta_data[\"outputs\"])\n else:\n raise Exception(\"Atleast one input is required exception\")\n '''\n \nexcept Exception as e:\n LOGGER.fatal(\"Encountered and Error: \" + str(error))\n process_status=\"Failure\"\n raise e\nfinally:\n LOGGER.info(process_status, ' ak-spark-etl-transform : ', datetime.now().strftime('%m/%d/%Y %H:%M:%S'))\n#---------------------------------------------------------------------------------------------------\n\n\n","sub_path":"PyTest/test/ak-spark-json.py","file_name":"ak-spark-json.py","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"169698812","text":"#!/usr/bin/env python3\n# 一个简单的爬虫程序 抓取页面上的英雄联盟英雄信息并存到数据库中去\n\nfrom bs4 import BeautifulSoup\n\nimport pymysql\nimport requests\n\n\ndef get_html_text():\n \"\"\"获取html\"\"\"\n url = \"http://lol.duowan.com/hero/\"\n html = requests.get(url).text\n soup = BeautifulSoup(html, \"html.parser\")\n data = soup.find(id='champion_list').findAll('li')\n return data\n\n\ndef open_mysql():\n \"\"\"打开数据库\"\"\"\n return pymysql.connect(user='root', password='', database='semye', charset='utf8')\n\n\ndef get(data, conn):\n cursor = conn.cursor()\n try:\n for li in data:\n hero_name = li.find('h2').getText()\n hero_nick_name = li.find('h3').getText()\n print(hero_name)\n print(hero_nick_name)\n sql = 'insert into semye_characters (name,nick_name,sex) values (%s,%s,%s)'\n cursor.execute(sql, (hero_name, hero_nick_name, '男'))\n conn.commit()\n\n except:\n conn.rollback()\n cursor.close()\n conn.close()\n\n\ndef get_hero():\n data = get_html_text()\n conn = open_mysql()\n get(data, conn)\n\n\nif __name__ == '__main__':\n get_hero()\n","sub_path":"lol/hero.py","file_name":"hero.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"111729994","text":"prompt = \"\\nPlease enter the name of city you have visited: \"\nprompt += \"\\n(Enter 'quit' when you are finished.)\"\n\n\n# the loop that start with \"while True:\" will run forever until it reaches \"break\" statement\nwhile True:\n city = input(prompt)\n if city == 'quit':\n break\n else:\n print(f\"I'd love to go to {city.title()}!\")\n","sub_path":"chapter_7_user_input_and_while_loops/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"563491446","text":"import requests\nimport json\n\nclass Requester:\n def __init__(self, date, ticker):\n self.marketData = []\n self.date = date\n self.ticker = ticker\n self.getData()\n\n def getData(self):\n requestURL = \"https://api.iextrading.com/1.0/stock/{}/chart/date/{}\".format(self.ticker, self.date)\n print(requestURL)\n request = requests.get(requestURL)\n self.marketData = json.loads(request.text)\n\n def getMarketAverageColours(self):\n marketAverages = []\n for time in self.marketData:\n marketAverages.append(time[\"marketAverage\"])\n\n minValue = min(marketAverages)\n maxValue = max(marketAverages)\n\n marketAverageColours = []\n for marketAverage in marketAverages:\n marketAverageColours.append((marketAverage-minValue)/(maxValue-minValue))\n\n return marketAverageColours\n","sub_path":"Requester.py","file_name":"Requester.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"574831352","text":"'''\nCreated on Mar 27, 2010\nThis module is designed to populate the jobs database for sourceforge.net.\n\nRUN INSTRUCTIONS\nRun this module from command line with the following format:\n[Interpreter] GoogleCodeJobs.py [datasource_id] [Test T/F]\nTest is a string variable. Be sure to use a capital 'T' to denote test mode. \nOtherwise use 'F'.\n\n@author: StevenNorris\n'''\n\nimport sys\nfrom GCutils import GoogleCodeUtils\nimport traceback\nimport socket\n\n#adds the jobs to the sf_jobs table in the selected database\ndef main(argv):\n \n #set variables\n try:\n datasource_id=argv[1]\n test=argv[2]\n except:\n print (\"\"\"RUN INSTRUCTIONS\\n\n Run this module from command line with the following format:\\n\n [Interpreter] GoogleCodeJobs.py [datasource_id] [Test T/F]\\n\n Test is a string variable. Be sure to use a capital 'T' to denote test mode.\\n \n Otherwise use 'F'.\"\"\")\n sys.exit()\n \n #checks for test mode\n if(test=='T'):\n try:\n print(\"TEST MODE ACTIVATED\")\n utils=GoogleCodeUtils()\n except:\n print(\"Please create the dbInfo.txt and the dbInfoTest.txt files. See ReadMe for formatting.\")\n sys.exit()\n else:\n try:\n utils=GoogleCodeUtils('dbInfo.txt')\n except:\n print(\"Please create the dbInfo.txt and the dbInfoText.txt files. See ReadMe for formatting.\")\n sys.exit() \n \n #gathering project unixnames\n try:\n print(\"Gathering unixnames.\")\n projects_list=utils.get_projects(datasource_id)\n print(len(projects_list))\n \n #checks test mode for project amount to be collected\n if(test=='T'):\n end=50\n else:\n end=len(projects_list)\n \n #adds jobs to database\n try:\n print(\"Creating Jobs\")\n for project in projects_list:\n project=project[0]\n print(\"Creating job for \"+project)\n try:\n insert='''INSERT INTO gc_jobs (unixname,datasource_id,status,last_modified,modified_by)\n VALUES(%s,%s,'gather_home',NOW(),%s)'''\n utils.db_insert(insert,project,datasource_id,socket.gethostname())\n except:\n print('!!!!WARNING!!!! Job creation failed for '+project+'.')\n print(traceback.format_exc())\n except:\n print('!!!!WARNING!!!! Jobs did not create succesfully')\n print(traceback.format_exc())\n except:\n print('!!!!WARNING!!!! Projects unixnames not collected properly.')\n print(traceback.format_exc())\n \ndef test(argv):\n utils=GoogleCodeUtils('dbInfoTest.txt') \n\nmain(sys.argv)\n \n\n\n","sub_path":"GCjobs/GCjobs.py","file_name":"GCjobs.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"133731791","text":"from util import *\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import MaxNLocator\nfrom collections import namedtuple\n\n\nresult = []\n\ngesture = ['beats', 'metaphoric', 'deictics', 'iconic']\n# VID_SCORE = [[13, 15, 14, 16, 19, 4],[10, 14, 14, 13, 18, 8],[18, 14, 16, 11, 6, 6]]\n# VID_SCORE_TOTAL = [[20, 20, 20, 20, 20, 20], [20, 20, 20, 20, 20, 20], [20, 20, 20, 20, 20, 20]]\n\n\n# VID_SCORE_DUAL = [[16, 12, 10, 14, 13, 10],[17, 17, 19, 11, 20, 4],[16, 17, 14, 13, 8, 7]]\n\n# VID_SCORE_SINGLE = [[20, 13, 12, 14, 19, 9],[12, 15, 10, 8, 16, 3],[12, 18, 14, 12, 2, 7]]\n\n\n# bi = [\n# 'metaphoric',\n# 'beats',\n# 'beats',\n# 'deictics',\n# 'deictics',\n# 'iconic'\n# ]\n\n# ps = [\n# 'metaphoric',\n# 'metaphoric',\n# 'deictics',\n# 'iconic',\n# 'metaphoric',\n# 'beats'\n# ]\n\n# ta = ['metaphoric',\n# 'metaphoric',\n# 'beats',\n# 'beats',\n# 'beats',\n# 'metaphoric']\n\n# %%\nVID_SCORE = [[13, 14, 13, 15, 18, 4], [\n 10, 14, 13, 12, 17, 8], [17, 14, 15, 11, 6, 6]]\n\nVID_SCORE_DUAL = [[15, 11, 10, 13, 12, 9], [\n 16, 16, 18, 10, 19, 4], [16, 17, 13, 13, 8, 7]]\n\nVID_SCORE_SINGLE = [[17, 11, 12, 12, 17, 9], [\n 9, 13, 8, 7, 13, 3], [10, 15, 14, 10, 1, 6]]\n\n\nbi = [\n 'metaphoric',\n 'beats',\n 'beats',\n 'deictics',\n 'deictics',\n 'iconic'\n]\n\nps = [\n 'metaphoric',\n 'metaphoric',\n 'deictics',\n 'iconic',\n 'metaphoric',\n 'beats'\n]\n\nta = ['metaphoric',\n 'metaphoric',\n 'beats',\n 'beats',\n 'beats',\n 'metaphoric']\n\nTYPE = [['recall', 'recall', 'infer', 'recall', 'recall', 'infer'],\n ['recall', 'infer', 'recall', 'recall', 'infer', 'recall'],\n ['recall', 'recall', 'infer', 'infer', 'recall', 'recall']]\n\nfig, ax = plt.subplots()\nindex = np.arange(4)\nfig, ax = plt.subplots()\nbar_width = 0.2\nopacity = 0.4\n\n\ndef flatmap(array):\n return [e for l in array for e in l]\n\n\nall_ges = bi + ps + ta\nall_score = flatmap(VID_SCORE)\n\nresult = {g: 0 for g in gesture}\ntotal = {g: 0 for g in gesture}\nfor i, g in enumerate(all_ges):\n result[g] += all_score[i]\n total[g] += 20\n\nfor k in result:\n result[k] = result[k]/total[k]\n\n\nrects1 = ax.bar(index, list(result.values()), bar_width,\n alpha=opacity, color='b',\n label='Full')\n\n\nall_score = flatmap(VID_SCORE_DUAL)\n\nresult = {g: 0 for g in gesture}\ntotal = {g: 0 for g in gesture}\nfor i, g in enumerate(all_ges):\n result[g] += all_score[i]\n total[g] += 21\n\nfor k in result:\n result[k] = result[k]/total[k]\n\nrects2 = ax.bar(index + bar_width, list(result.values()), bar_width,\n alpha=opacity, color='r',\n label='Dual')\n\nall_score = flatmap(VID_SCORE_SINGLE)\n\nresult = {g: 0 for g in gesture}\ntotal = {g: 0 for g in gesture}\nfor i, g in enumerate(all_ges):\n result[g] += all_score[i]\n total[g] += 22\n\nfor k in result:\n result[k] = result[k]/total[k]\n\nrects2 = ax.bar(index + bar_width + bar_width, list(result.values()), bar_width,\n alpha=opacity, color='g',\n label='Single')\n\nax.set_xlabel('Gestures')\nax.set_ylabel('Scores')\nax.set_title('Gestures & Scores')\nax.set_xticks(index + bar_width / 2)\nax.set_xticklabels([*result])\nax.legend()\n\nfig.tight_layout()\nplt.show()\n","sub_path":"twoSeriesAnalysis/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"26034572","text":"from flask import Flask, jsonify\nfrom routes.v1 import app, cache\n\n@app.route(\"/\")\n@cache.cached(timeout=app.config['CACHE_DURATION'])\ndef index():\n\t# Logger(request.method, request.endpoint, request.url, 'Welcome to ', request.headers.get('User-Agent'), request.accept_languages)\n\treturn jsonify({'message':'Hello world. Welcome to '})\n\n\n@app.errorhandler(404)\ndef page_not_found():\n\tresponseObject ={\n\t\t'message' : 'This is not the page you are looking for. Move along.'\n\t}\n\treturn make_response(jsonify(responseObject)), 404\n\n@app.errorhandler(500)\ndef internal_error(error):\n\tdb.session.rollback()\n\tLogger(request.method,request.endpoint, request.url, error, request.headers.get('User-Agent'), request.accept_languages)\n\treturn jsonify({'message' : str(error)}), 500","sub_path":"flaskcli/base_templates/versioned/app/routes/v1/base_urls.py","file_name":"base_urls.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652903067","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2012- Ursa Information Systems\n# .\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport time\nfrom operator import itemgetter\nfrom openerp.report import report_sxw\n\nN = 6\nSTARS = 70\n\n\nclass report_print_check(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(report_print_check, self).__init__(cr, uid, name, context)\n self.localcontext.update({\n 'time': time,\n 'get_zip_line': self.get_zip_line,\n 'get_data': self.get_vouchers,\n })\n\n def _chunks(self, l, n):\n return [l[i:i + n] for i in range(0, len(l), n)]\n\n def _prepare_line(self, line, credit=False):\n sign = credit and -1 or 1\n return {\n 'date_due': line.date_due,\n 'date_original': line.date_original,\n 'name': line.move_line_id and line.move_line_id.ref or line.name,\n 'amount_original': line.amount_original and sign * line.amount_original or False,\n 'amount_due': line.amount_unreconciled and sign * line.amount_unreconciled or False,\n 'amount': line.amount and sign * line.amount or False,\n }\n\n def _prepare_pages(self, voucher, lines, n, stars):\n '''\n Prepare page info for check, can be inherited or overridden\n '''\n return [{'lines': chunk,\n 'amount': voucher.amount,\n 'amount_words': False,\n 'number': self._get_check_number(voucher),\n 'name': voucher.name,\n 'use_preprint_check': voucher.journal_id.use_preprint_check,\n 'date': voucher.date,\n 'partner': voucher.partner_id.name,\n 'address': voucher.partner_id}\n for chunk in self._chunks(lines, n)]\n\n def _get_check_number(self, voucher):\n '''\n Wrapper function for special case where customisation may require\n getting check number elsewhere in child parser\n '''\n return voucher.journal_id.use_preprint_check and '' \\\n or voucher.check_number\n\n def _prepare_first_page(self, voucher, stars):\n '''\n Change amounts on first page of check, can be inherited or overridden\n '''\n return {\n 'chk_amount': voucher.amount,\n 'amount_words': voucher.amount_in_word and\n voucher.amount_in_word.ljust(stars, '*') or\n ''.ljust(stars, '*')\n }\n\n def get_vouchers(self, objects, n=N, stars=STARS):\n '''\n Wrapper function to get RML formatting right without it.\n Basically takes a list of objects and returns a list of pages as a dict.\n '''\n res = []\n for voucher in objects:\n res.extend(self._get_data(voucher, n, stars))\n return res\n\n def _get_data(self, voucher, n=N, stars=STARS):\n '''\n Parses the voucher and chunks it in to a dictionary for the report.\n '''\n credit_section = voucher.company_id.credit_section\n suppress_unpaid = voucher.company_id.suppress_unpaid\n # first chunk up the lines\n dr_lines = [self._prepare_line(line) for line in voucher.line_dr_ids\n if line.amount or not suppress_unpaid]\n cr_lines = [self._prepare_line(line, 1) for line in voucher.line_cr_ids\n if line.amount or not suppress_unpaid]\n\n # This section just arranges the items\n if credit_section:\n dr_lines.sort(key=itemgetter('date_original'))\n cr_lines.sort(key=itemgetter('date_original'))\n # This could be improved to optional check length and pad\n # credits to next page if needed\n lines = ([{ 'date_original': \"\",\n 'date_due': \"\",\n 'name': \"Invoices\",\n 'amount_original': \"\",\n 'amount_due': \"\",\n 'amount': \"\",\n }] + dr_lines + \n (cr_lines and [{\n 'date_original': \"\",\n 'date_due': \"\",\n 'name': \"Credits\",\n 'amount_original': \"\",\n 'amount_due': \"\",\n 'amount': \"\",\n }] + cr_lines or []))\n else:\n lines = dr_lines + cr_lines\n lines.sort(key=itemgetter('date_original'))\n # just pad up the lines -\n # only 1 field really necessary RML will handle rest\n lines.extend([{\n 'date_original': \"\",\n 'date_due': \"\",\n 'name': \"\",\n 'amount_original': \"\",\n 'amount_due': \"\",\n 'amount': \"\",\n } for i in range(n - len(lines) % n)])\n pages = self._prepare_pages(voucher, lines, n, stars)\n # now add the check amounts to first page\n pages[0].update(self._prepare_first_page(voucher, stars))\n if not voucher.company_id.multi_stub:\n return [pages[0]]\n return pages\n\n def get_zip_line(self, address):\n '''\n Get the address line\n '''\n ret = ''\n if address:\n ret += address and address.city or ''\n ret += (address.state_id and ret) and ', ' or ''\n ret += address.state_id and address.state_id.name or ''\n ret += (address.zip and ret) and ', ' or ''\n ret += address and address.zip or ''\n return ret\n\n\nreport_sxw.report_sxw(\n 'report.account.print.check.top',\n 'account.voucher',\n 'addons/ao_account_check_writing/report/check_print_top.rml',\n parser=report_print_check,\n header=False\n)\n\nreport_sxw.report_sxw(\n 'report.account.print.check.middle',\n 'account.voucher',\n 'addons/ao_account_check_writing/report/check_print_middle.rml',\n parser=report_print_check,\n header=False\n)\n\nreport_sxw.report_sxw(\n 'report.account.print.check.bottom',\n 'account.voucher',\n 'addons/ao_account_check_writing/report/check_print_bottom.rml',\n parser=report_print_check,\n header=False\n)\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"8.0/ao_account_check_writing/reports/check_print.py","file_name":"check_print.py","file_ext":"py","file_size_in_byte":7152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"222403447","text":"from tlm.model.base import *\n\n\nclass BertModelWithLabelInner(BertModelInterface):\n def __init__(self,\n config,\n is_training,\n input_ids,\n input_mask=None,\n token_type_ids=None,\n use_one_hot_embeddings=True,\n scope=None,\n label_ids=None,\n ):\n super(BertModelWithLabelInner, self).__init__()\n\n config = copy.deepcopy(config)\n self.config = config\n if not is_training:\n config.hidden_dropout_prob = 0.0\n config.attention_probs_dropout_prob = 0.0\n\n num_labels = 3\n input_shape = get_shape_list(input_ids, expected_rank=2)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n label_ids_repeat = tf.tile(label_ids, [1, seq_length])\n\n if input_mask is None:\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\n\n if token_type_ids is None:\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\n\n with tf.compat.v1.variable_scope(scope, default_name=\"bert\"):\n with tf.compat.v1.variable_scope(\"embeddings\"):\n # Perform embedding lookup on the word ids.\n (self.embedding_output, self.embedding_table) = embedding_lookup(\n input_ids=input_ids,\n vocab_size=config.vocab_size,\n embedding_size=config.hidden_size,\n initializer_range=config.initializer_range,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # Add positional embeddings and token type embeddings, then layer\n # normalize and perform dropout.\n self.embedding_output = embedding_postprocessor(\n input_tensor=self.embedding_output,\n use_token_type=True,\n token_type_ids=token_type_ids,\n token_type_vocab_size=config.type_vocab_size,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=config.initializer_range,\n max_position_embeddings=config.max_position_embeddings,\n dropout_prob=config.hidden_dropout_prob)\n\n self.embedding_output = embedding_postprocessor(\n input_tensor=self.embedding_output,\n use_token_type=True,\n token_type_ids=label_ids_repeat,\n token_type_vocab_size=num_labels,\n token_type_embedding_name=\"label_embedding\",\n use_position_embeddings=False,\n position_embedding_name=None,\n initializer_range=config.initializer_range,\n max_position_embeddings=config.max_position_embeddings,\n dropout_prob=config.hidden_dropout_prob)\n\n with tf.compat.v1.variable_scope(\"encoder\"):\n attention_mask = create_attention_mask_from_input_mask(\n input_ids, input_mask)\n\n self.all_encoder_layers = transformer_model(\n input_tensor=self.embedding_output,\n attention_mask=attention_mask,\n input_mask=input_mask,\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n is_training=is_training,\n intermediate_size=config.intermediate_size,\n intermediate_act_fn=get_activation(config.hidden_act),\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n initializer_range=config.initializer_range,\n do_return_all_layers=True)\n\n self.sequence_output = self.all_encoder_layers[-1]\n with tf.compat.v1.variable_scope(\"pooler\"):\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\n self.pooled_output = tf.keras.layers.Dense(config.hidden_size,\n activation=tf.keras.activations.tanh,\n kernel_initializer=create_initializer(config.initializer_range))(\n first_token_tensor)\n\n\nclass BertModelWithLabel(BertModelWithLabelInner):\n def __init__(self,\n config,\n is_training,\n input_ids,\n input_mask=None,\n token_type_ids=None,\n use_one_hot_embeddings=True,\n scope=None,\n features=None,\n ):\n super(BertModelWithLabel, self).__init__(config,\n is_training,\n input_ids,\n input_mask,\n token_type_ids,\n use_one_hot_embeddings,\n scope,\n features['input_ids'],\n )\n","sub_path":"src/tlm/model/bert_with_label.py","file_name":"bert_with_label.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"447216991","text":"# www.NeatChange.com\r\n# Make a difference in your life !\r\n#\r\n# Poplar Sep 24 2016\r\n# 模拟在格子里随意行走\r\n\r\n\r\nimport time\r\nimport turtle\r\nfrom random import randint\r\n\r\n\r\ndef g():\r\n turtle.speed(100)\r\n turtle.color(\"gray\")\r\n x = -400\r\n\r\n for y in range(-400, 400+1, 25):\r\n turtle.penup()\r\n turtle.goto(x, y)\r\n turtle.pendown()\r\n turtle.forward(800)\r\n \r\n turtle.right(270)\r\n y = -400\r\n\r\n for x in range(-400, 400+1, 25):\r\n turtle.penup()\r\n turtle.goto(x, y)\r\n turtle.pendown()\r\n turtle.forward(800)\r\n\r\n turtle.pensize(3)\r\n turtle.color(\"red\")\r\n turtle.penup()\r\n turtle.goto(0, 0)\r\n turtle.pendown()\r\n\r\n\r\ndef s():\r\n turtle.speed(3)\r\n x = 0\r\n y = 0\r\n while abs(x) < 400 and abs(y) < 400:\r\n r = randint(0, 3)\r\n # Walk right\r\n if r == 0:\r\n x += 25\r\n turtle.setheading(0)\r\n turtle.forward(25)\r\n # Walk left\r\n if r == 1:\r\n x -= 25\r\n turtle.setheading(180)\r\n turtle.forward(25)\r\n # Walk up\r\n if r == 2:\r\n y += 25\r\n turtle.setheading(90)\r\n turtle.forward(25)\r\n if r == 3:\r\n y -= 25\r\n turtle.setheading(270)\r\n turtle.forward(25)\r\n\r\n\r\ndef main():\r\n g()\r\n s()\r\n time.sleep(2)\r\n\r\nmain()\r\n","sub_path":"Study/Python/Python库/标准库/Tkinter库/应用/模拟在格子里随意行走.py","file_name":"模拟在格子里随意行走.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"605539236","text":"'''\n# Домашнее задание к лекции 2.4 «Database. Mongo. ORM»\n\n1. Вы реализуете приложение для поиска билетов н�� концерт. \nЗаполните коллекцию в Монго данными о предстоящих концертах и \nреализуйте следующие функции:\n\n- `read_data`: импорт данных из csv [файла](https://github.com/netology-code/py-homework-advanced/blob/master/2.4.DB.Mongo.ORM/artists.csv);\n- `find_cheapest`: отсортировать билеты из базы по возрастанию цены;\n- `find_by_name`: найти билеты по исполнителю, где имя исполнителя \nможет быть задано не полностью, и вернуть их по возрастанию цены.\n\n\n## Дополнительное задание\n\n- Реализовать сортировку по дате мероприятия. Для этого вам потребуется \nстроку с датой в csv-файле приводить к объекту datetime (можете считать,\n что все они текущего года) и сохранять его.\n\nПример поиска: найти все мероприятия с 1 по 30 июля.\n\n\npython\n'''\n\nimport csv\nimport re\nimport bson\n\nfrom pymongo import MongoClient\n\n\ndef mk_mongodb(dbname, collname):\n client = MongoClient('localhost')\n db = client.dbname\n db.collname\n return db\n\ndef read_data(csv_file, db):\n \"\"\"\n Загрузить данные в бд из CSV-файла\n \"\"\"\n result = []\n with open(csv_file, encoding='utf8') as csvfile:\n # прочитать файл с данными и записать в коллекцию\n reader = csv.DictReader(csvfile)\n for row in reader:\n db.art_collection.insert(row)\n return db.name\n\ndef find_cheapest(db, collname):\n \"\"\"\n Отсортировать билеты из базы по возрастанию цены\n Документация: https://docs.mongodb.com/manual/reference/method/cursor.sort/\n \"\"\"\n result = mydb.collname.find().sort('Price', 1)\n return result\n\n\ndef find_by_name(db, collname):\n \"\"\"\n Найти билеты по имени исполнителя (в том числе – по подстроке, например \"Seconds to\"),\n и вернуть их по возрастанию цены\n \"\"\"\n search_name = input('Введите регулярное выражение для поиска: ')\n prep_regexp = re.sub('[^A-Za-zА-Яа-я0-9- ]+', '', search_name)\n regex = bson.regex.Regex(prep_regexp)\n result = db.collname.find({'Исполнитель' : regex}).sort('Price', 1)\n return result\n\n\ndef clear_db(dbname, collname):\n client = MongoClient('localhost')\n db = client[dbname]\n mycol = db[collname]\n mycol.drop()\n\n\nif __name__ == '__main__':\n mydb = mk_mongodb()\n mydb_name = read_data('artists.csv', mydb)\n for k in mydb.art_collection.find():\n print('ispolnitel:', k['Исполнитель'],'cena',k['Price'])\n searched_names = find_by_name(mydb)\n print(searched_names)\n clear_db(mydb_name)\n\n\n","sub_path":"datamongo.py","file_name":"datamongo.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"55660644","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys\nimport codecs\n\ndef main():\n s = ''.join(sys.argv[1:]).decode('utf-8')\n print (s)\n\n \n# Standard boilerplate to call the main() function.\nif __name__ == '__main__':\n main()\n","sub_path":"uni_console.py","file_name":"uni_console.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"459115922","text":"# Сжать список, удалив из него все 0 и заполнить освободившиеся справа элементы значениями -1.\n\n\ndef inp():\n number = int(input('Input the list size: '))\n return [int(input('Input number: ')) for i in range(number)]\n\n\ndef remove_zero(my_list):\n while my_list.count(0) != 0:\n my_list.remove(0)\n my_list.append(-1)\n return my_list\n\n\nif __name__ == '__main__':\n print(remove_zero(inp()))\n","sub_path":"homework/homework_4/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"192467848","text":"import cv2\r\nimport glob\r\n\r\nimages=glob.glob(\"*.jpg\") #glob finds the path of files given a certain pattern ie jpg files\r\n#create a list containing the image file paths and then iterated through the list.\r\nfor image in images:\r\n img=cv2.imread(image,0)\r\n re=cv2.resize(img,(100,100))\r\n cv2.imshow(\"Hey\",re)\r\n cv2.waitKey(500)\r\n cv2.destroyAllWindows()\r\n cv2.imwrite(\"resized_\"+image,re)\r\n\r\n#The loop reads each image, resizes, displays the image, waits for the user input key, closes the window once the key is pressed, and writes the resized image\r\n#The name of the resized image will be \"resized\" plus the existing file name of the original image.","sub_path":"Motion sensing/batch_image_processing/batch_img.py","file_name":"batch_img.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}