', '').replace(' ', ' ').replace('’', \"'\")\r\n # write to html\r\n newFile.write('' + title + ' ')\r\n # get description of new\r\n if newArray[0] == '')\r\n # close and save news html\r\n newFile.close()\r\n ","sub_path":"CST205/Lab 16/lab16.py","file_name":"lab16.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"306162974","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport base64\nimport re\nimport requests\nimport json\n\nfrom odoo import _, api, fields, models, SUPERUSER_ID, tools\nfrom odoo.tools.safe_eval import safe_eval\nfrom odoo.exceptions import UserError\n\n_logger = logging.getLogger(__name__)\n\nclass mail_custom_0(models.TransientModel):\n\n _inherit = 'mail.compose.message'\n\n\n def get_mail_values(self, res_ids):\n \"\"\"Generate the values that will be used by send_mail to create mail_messages\n or mail_mails. \"\"\"\n self.ensure_one()\n results = dict.fromkeys(res_ids, False)\n rendered_values = {}\n mass_mail_mode = self.composition_mode == 'mass_mail'\n\n # render all template-based value at once\n if mass_mail_mode and self.model:\n rendered_values = self.render_message(res_ids)\n # compute alias-based reply-to in batch\n reply_to_value = dict.fromkeys(res_ids, None)\n if mass_mail_mode and not self.no_auto_thread:\n records = self.env[self.model].browse(res_ids)\n reply_to_value = self.env['mail.thread']._notify_get_reply_to_on_records(default=self.email_from, records=records)\n\n blacklisted_rec_ids = []\n if mass_mail_mode and issubclass(type(self.env[self.model]), self.pool['mail.thread.blacklist']):\n BL_sudo = self.env['mail.blacklist'].sudo()\n blacklist = set(BL_sudo.search([]).mapped('email'))\n if blacklist:\n targets = self.env[self.model].browse(res_ids).read(['email_normalized'])\n # First extract email from recipient before comparing with blacklist\n blacklisted_rec_ids.extend([target['id'] for target in targets\n if target['email_normalized'] and target['email_normalized'] in blacklist])\n\n for res_id in res_ids:\n # static wizard (mail.message) values\n \n ##########################\n reply_follower = \"\"\n # ADD REPLY FOLLOWERS\n if(self.model == 'sale.order'):\n sale_order = self.env['sale.order'].search([('id','=', self.res_id)])\n \n emails_follower = []\n if(sale_order.message_follower_ids):\n for partner in sale_order.message_follower_ids.partner_id:\n if(partner.email):\n emails_follower.append(partner.email)\n\n if(emails_follower):\n reply_follower = ','.join(emails_follower)\n \n ##########################\n\n mail_values = {\n 'subject': self.subject,\n 'body': self.body or '',\n 'parent_id': self.parent_id and self.parent_id.id,\n 'partner_ids': [partner.id for partner in self.partner_ids],\n 'attachment_ids': [attach.id for attach in self.attachment_ids],\n 'author_id': self.author_id.id,\n 'email_from': self.email_from,\n 'record_name': self.record_name,\n 'no_auto_thread': self.no_auto_thread,\n 'mail_server_id': self.mail_server_id.id,\n 'mail_activity_type_id': self.mail_activity_type_id.id,\n 'reply_to': reply_follower ###########################\n }\n\n # mass mailing: rendering override wizard static values\n if mass_mail_mode and self.model:\n record = self.env[self.model].browse(res_id)\n mail_values['headers'] = record._notify_email_headers()\n # keep a copy unless specifically requested, reset record name (avoid browsing records)\n mail_values.update(notification=not self.auto_delete_message, model=self.model, res_id=res_id, record_name=False)\n # auto deletion of mail_mail\n if self.auto_delete or self.template_id.auto_delete:\n mail_values['auto_delete'] = True\n # rendered values using template\n email_dict = rendered_values[res_id]\n mail_values['partner_ids'] += email_dict.pop('partner_ids', [])\n mail_values.update(email_dict)\n if not self.no_auto_thread:\n mail_values.pop('reply_to')\n if reply_to_value.get(res_id):\n mail_values['reply_to'] = reply_to_value[res_id]\n if self.no_auto_thread and not mail_values.get('reply_to'):\n mail_values['reply_to'] = mail_values['email_from']\n # mail_mail values: body -> body_html, partner_ids -> recipient_ids\n mail_values['body_html'] = mail_values.get('body', '')\n mail_values['recipient_ids'] = [(4, id) for id in mail_values.pop('partner_ids', [])]\n\n # process attachments: should not be encoded before being processed by message_post / mail_mail create\n mail_values['attachments'] = [(name, base64.b64decode(enc_cont)) for name, enc_cont in email_dict.pop('attachments', list())]\n attachment_ids = []\n for attach_id in mail_values.pop('attachment_ids'):\n new_attach_id = self.env['ir.attachment'].browse(attach_id).copy({'res_model': self._name, 'res_id': self.id})\n attachment_ids.append(new_attach_id.id)\n attachment_ids.reverse()\n mail_values['attachment_ids'] = self.env['mail.thread']._message_post_process_attachments(\n mail_values.pop('attachments', []),\n attachment_ids,\n {'model': 'mail.message', 'res_id': 0}\n )['attachment_ids']\n # Filter out the blacklisted records by setting the mail state to cancel -> Used for Mass Mailing stats\n if res_id in blacklisted_rec_ids:\n mail_values['state'] = 'cancel'\n # Do not post the mail into the recipient's chatter\n mail_values['notification'] = False\n\n results[res_id] = mail_values\n return results\n\n @api.onchange('template_id')\n def onchange_template_id_wrapper(self):\n self.ensure_one()\n values = self.onchange_template_id(self.template_id.id, self.composition_mode, self.model, self.res_id)['value']\n for fname, value in values.items():\n setattr(self, fname, value)\n\n def onchange_template_id(self, template_id, composition_mode, model, res_id):\n \"\"\" - mass_mailing: we cannot render, so return the template values\n - normal mode: return rendered values\n /!\\ for x2many field, this onchange return command instead of ids\n \"\"\"\n if template_id and composition_mode == 'mass_mail':\n template = self.env['mail.template'].browse(template_id)\n fields = ['subject', 'body_html', 'email_from', 'reply_to', 'mail_server_id']\n values = dict((field, getattr(template, field)) for field in fields if getattr(template, field))\n if template.attachment_ids:\n values['attachment_ids'] = [att.id for att in template.attachment_ids]\n if template.mail_server_id:\n values['mail_server_id'] = template.mail_server_id.id\n if template.user_signature and 'body_html' in values:\n signature = self.env.user.signature\n values['body_html'] = tools.append_content_to_html(values['body_html'], signature, plaintext=False)\n elif template_id:\n values = self.generate_email_for_composer(template_id, [res_id])[res_id]\n # transform attachments into attachment_ids; not attached to the document because this will\n # be done further in the posting process, allowing to clean database if email not send\n\n attachment_ids = []\n ##########################\n if(model == 'sale.order'):\n sale_order = self.env['sale.order'].search([('id','=', self.res_id)])\n \n if(sale_order and sale_order.x_studio_oportunidad):\n crm_lead = self.env['crm.lead'].search([('id','=',sale_order.x_studio_oportunidad.id)])\n if(crm_lead):\n \n crm_attachment_ids = self.env['ir.attachment'].search(['&',('res_model','=','crm.lead'),('res_id', '=', crm_lead.id)])\n if(crm_attachment_ids):\n for line in crm_attachment_ids:\n attachment_ids.append(line.id)\n \n # sale_order_attachment_ids = self.env['ir.attachment'].search(['&',('res_model','=','sale.order'),('res_id', 'in', crm_lead.order_ids.ids)])\n # if(sale_order_attachment_ids):\n # attachment_ids.append(sale_order_attachment_ids.ids)\n\n for line in crm_lead.order_ids:\n if(line.state == 'draft' and line.id != res_id):\n template_values = self.env['mail.template'].with_context(tpl_partners_only=True).browse(template_id).generate_email(line.id, fields=['attachment_ids'])\n values['attachments'].append(template_values['attachments'][0])\n\n\n ##########################\n\n Attachment = self.env['ir.attachment']\n for attach_fname, attach_datas in values.pop('attachments', []):\n data_attach = {\n 'name': attach_fname,\n 'datas': attach_datas,\n 'res_model': 'mail.compose.message',\n 'res_id': 0,\n 'type': 'binary', # override default_type from context, possibly meant for another model!\n }\n attachment_ids.append(Attachment.create(data_attach).id)\n if values.get('attachment_ids', []) or attachment_ids:\n values['attachment_ids'] = [(6, 0, values.get('attachment_ids', []) + attachment_ids)]\n else:\n default_values = self.with_context(default_composition_mode=composition_mode, default_model=model, default_res_id=res_id).default_get(['composition_mode', 'model', 'res_id', 'parent_id', 'partner_ids', 'subject', 'body', 'email_from', 'reply_to', 'attachment_ids', 'mail_server_id'])\n values = dict((key, default_values[key]) for key in ['subject', 'body', 'partner_ids', 'email_from', 'reply_to', 'attachment_ids', 'mail_server_id'] if key in default_values)\n\n if values.get('body_html'):\n values['body'] = values.pop('body_html')\n\n # This onchange should return command instead of ids for x2many field.\n values = self._convert_to_write(values)\n\n return {'value': values}\n\n @api.model\n def generate_email_for_composer(self, template_id, res_ids, fields=None):\n \"\"\" Call email_template.generate_email(), get fields relevant for\n mail.compose.message, transform email_cc and email_to into partner_ids \"\"\"\n multi_mode = True\n if isinstance(res_ids, int):\n multi_mode = False\n res_ids = [res_ids]\n\n if fields is None:\n fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to', 'attachment_ids', 'mail_server_id']\n returned_fields = fields + ['partner_ids', 'attachments']\n values = dict.fromkeys(res_ids, False)\n\n template_values = self.env['mail.template'].with_context(tpl_partners_only=True).browse(template_id).generate_email(res_ids, fields=fields)\n for res_id in res_ids:\n res_id_values = dict((field, template_values[res_id][field]) for field in returned_fields if template_values[res_id].get(field))\n res_id_values['body'] = res_id_values.pop('body_html', '')\n values[res_id] = res_id_values\n\n return multi_mode and values or values[res_ids[0]]\n\n\n\nclass mail_custom_1(models.Model):\n \n _inherit = 'mail.template'\n\n def generate_email(self, res_ids, fields=None):\n \"\"\"Generates an email from the template for given the given model based on\n records given by res_ids.\n\n :param res_id: id of the record to use for rendering the template (model\n is taken from template definition)\n :returns: a dict containing all relevant fields for creating a new\n mail.mail entry, with one extra key ``attachments``, in the\n format [(report_name, data)] where data is base64 encoded.\n \"\"\"\n self.ensure_one()\n multi_mode = True\n if isinstance(res_ids, int):\n res_ids = [res_ids]\n multi_mode = False\n if fields is None:\n fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to', 'scheduled_date']\n\n res_ids_to_templates = self.get_email_template(res_ids)\n\n # templates: res_id -> template; template -> res_ids\n templates_to_res_ids = {}\n for res_id, template in res_ids_to_templates.items():\n templates_to_res_ids.setdefault(template, []).append(res_id)\n\n results = dict()\n for template, template_res_ids in templates_to_res_ids.items():\n Template = self.env['mail.template']\n # generate fields value for all res_ids linked to the current template\n if template.lang:\n Template = Template.with_context(lang=template._context.get('lang'))\n for field in fields:\n Template = Template.with_context(safe=field in {'subject'})\n generated_field_values = Template._render_template(\n getattr(template, field), template.model, template_res_ids,\n post_process=(field == 'body_html'))\n for res_id, field_value in generated_field_values.items():\n results.setdefault(res_id, dict())[field] = field_value\n # compute recipients\n if any(field in fields for field in ['email_to', 'partner_to', 'email_cc']):\n results = template.generate_recipients(results, template_res_ids)\n # update values for all res_ids\n for res_id in template_res_ids:\n values = results[res_id]\n # body: add user signature, sanitize\n if 'body_html' in fields and template.user_signature:\n signature = self.env.user.signature\n if signature:\n values['body_html'] = tools.append_content_to_html(values['body_html'], signature, plaintext=False)\n if values.get('body_html'):\n values['body'] = tools.html_sanitize(values['body_html'])\n # technical settings\n values.update(\n mail_server_id=template.mail_server_id.id or False,\n auto_delete=template.auto_delete,\n model=template.model,\n res_id=res_id or False,\n attachment_ids=[attach.id for attach in template.attachment_ids],\n )\n\n # Add report in attachments: generate once for all template_res_ids\n if template.report_template:\n for res_id in template_res_ids:\n attachments = []\n report_name = self._render_template(template.report_name, template.model, res_id)\n report = template.report_template\n report_service = report.report_name\n\n if report.report_type in ['qweb-html', 'qweb-pdf']:\n result, format = report.render_qweb_pdf([res_id])\n else:\n res = report.render([res_id])\n if not res:\n raise UserError(_('Unsupported report type %s found.') % report.report_type)\n result, format = res\n\n # TODO in trunk, change return format to binary to match message_post expected format\n result = base64.b64encode(result)\n\n ###########################################################\n\n if(self.model == \"account.move\" and self.name == \"Invoice: Send by email\"):\n sign_pdf_api = self.env['ir.config_parameter'].sudo().get_param('x_sign_pdf_url_api')\n api_token = self.env['ir.config_parameter'].sudo().get_param('x_api_token')\n paramaters = {\n 'api_token': str(api_token),\n 'pdf_file': result.decode('utf-8') \n }\n #.decode('utf-8')\n\n pdf_sign = requests.post(\\\n sign_pdf_api, \n headers={'Content-type': 'application/json', 'Accept': 'application/json'}, \\\n data=json.dumps(paramaters))\n\n if(pdf_sign):\n if(pdf_sign.status_code == 200):\n response_sign = json.loads(pdf_sign.text)\n result = response_sign['certified_file']\n \n ###########################################################\n\n\n if not report_name:\n report_name = 'report.' + report_service\n ext = \".\" + format\n if not report_name.endswith(ext):\n report_name += ext\n attachments.append((report_name, result))\n results[res_id]['attachments'] = attachments\n\n return multi_mode and results or results[res_ids[0]]","sub_path":"custom_modules/sale_mail_attachment_custom/models/sale_mail_attachment.py","file_name":"sale_mail_attachment.py","file_ext":"py","file_size_in_byte":17933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"362415006","text":"'''\nName: Prachi Santosh kolte\n\nFile description: This file contains the graph plotter user need to provide a,b,c cordinates of the equation which calculates values of\nY based on X range [-5,5] and plot the graph in the form of line and points\nsteps to run:\n1. intially program starts with some basic values which respresents the simple equation\n2.User need to click on new equation or select from menu to get graph of new equation\n3. There are certain mathematical validations provided to input of the a,b,c values\n4. After inputing the value and sucessful submission select the option from radio button the way you want to display the graph\n5. Also can choose to clear the current graph or can change the graph from dotted to direct line also\n6. you can also save your graph .ps in current directory\n\n\n'''\n\n\n\n\n\n\n\n\n\nfrom tkinter import *\nimport tkinter\nimport tkinter.messagebox\nfrom tkinter import messagebox\n\n\nclass CoefficientsDialog:\n def __init__(self, master):\n self.parent = master\n self.coefficients = None # Default value, to say its not been set yet\n\n self.master = Toplevel(self.parent)\n self.master.transient(self.parent)\n\n self.master.title(\"Coefficients \")\n self.lbl1 = Label(self.master, text=\"X^2 +\").grid(row=0, column=1, sticky=E)\n self.lbl2 = Label(self.master, text=\"X +\").grid(row=1, column=1, sticky=E)\n self.lbl3 = Label(self.master, text=\" +\").grid(row=2, column=1, sticky=E)\n self.ent1 = Entry(self.master)\n self.ent1.grid(row=0, column=0)\n self.ent2 = Entry(self.master)\n self.ent2.grid(row=1, column=0)\n self.ent3 = Entry(self.master)\n self.ent3.grid(row=2, column=0)\n btn1 = tkinter.Button(self.master, text=\"Submit\", command=self.submit, image=None)\n btn1.grid()\n\n def submit(self, event=None):\n '''\n Handle submit button action\n '''\n\n try:\n data = int(self.ent1.get())\n if data == 0:\n raise Exception\n data2 = int(self.ent2.get())\n data3 = int(self.ent3.get())\n print (data)\n print (data2)\n print (data3)\n self.coefficients={'a':data,'b':data2,'c':data3}\n self.master.destroy()\n\n except ValueError:\n\n error_window = tkinter.Tk()\n error_window.title(\"Error\")\n error_window.geometry(\"200x200\")\n label = Label(error_window, text=\"Please enter integer\", height=0, width=100)\n b = Button(error_window, text=\"Ok\", width=20, command=error_window.destroy)\n label.pack()\n b.pack(side='bottom', padx=0, pady=0)\n except Exception as e:\n error_window = tkinter.Tk()\n error_window.title(\"Error\")\n error_window.geometry(\"100x100\")\n label = Label(error_window, text=\"X^2 value can not be 0\", height=0, width=100)\n b = Button(error_window, text=\"Ok\", width=20, command=error_window.destroy)\n label.pack()\n b.pack(side='bottom', padx=0, pady=0)\n def show(self):\n self.toplevel.deiconify()\n self.toplevel.wait_window()\n value = self.var.get()\n return value\n\n\nclass QuadEQPlot:\n def __init__(self,a,b,c):\n self.a = a\n self.b = b\n self.c = c\n self.x_values = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]\n self.y_values = []\n # print(self.x_values)\n self.init_widget()\n\n self.window.mainloop()\n\n def hello(self):\n print(\"hello!\")\n\n def init_widget(self):\n self.coefficientsDialog = None\n self.window = tkinter.Tk()\n # self.window.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n self.window.title(\"Function Plot\")\n self.eqation = \"No Equation\"\n self.height = 700\n self.width = 700\n self.window.geometry(\"{}x{}\".format(self.width, self.height))\n\n self.root = tkinter.Frame(self.window)\n self.root.pack(expand=True, fill=\"both\")\n\n self.new_equation = Button(self.root, text=\"New Equation\", width=20, command=self.get_new_coefficient)\n self.new_equation.pack()\n\n self.labelframe = LabelFrame(self.root)\n self.labelframe.pack(expand=True, fill=\"both\")\n\n self.eqationLabel = Label(self.labelframe, text=self.eqation)\n self.eqationLabel.pack(side='left')\n\n self.canvas = tkinter.Canvas(self.root, width=500, height=500, bg=\"white\")\n self.canvas.pack()\n\n self.plot_axis()\n self.plot_equation()\n\n #################radiobutton###################\n R1 = Radiobutton(self.window, text=\"Points\", command=self.plot_points)\n R1.pack(side='right')\n\n R2 = Radiobutton(self.window, text=\"Lines\", command=self.plot_line)\n R2.pack(side='right')\n ################## Menu##################\n menubar = Menu(self.window)\n\n # create a pulldown menu, and add it to the menu bar\n filemenu = Menu(menubar, tearoff=0)\n filemenu.add_command(label=\"New Equation\", command=self.get_new_coefficient)\n filemenu.add_command(label=\"Save plot .ps\", command=self.save_canvas)\n filemenu.add_separator()\n filemenu.add_command(label=\"Clear\", command=self.clear_canvas)\n filemenu.add_command(label=\"Exit\", command=self.exit_window)\n\n menubar.add_cascade(label=\"File\", menu=filemenu)\n\n helpmenu = Menu(menubar, tearoff=0)\n helpmenu.add_command(label=\"About\", command=self.show_help_about)\n menubar.add_cascade(label=\"Help\", menu=helpmenu)\n\n # display the menu\n self.window.config(menu=menubar)\n ##########################\n\n\n\n def plot_axis(self):\n self.canvas.create_line(250, 50, 250, 450, width=2, fill=\"blue\")\n self.canvas.create_line(50, 250, 450, 250, width=2, fill=\"blue\")\n\n def plot_equation(self):\n self.clear_canvas()\n\n self.plot_axis()\n for i in self.x_values:\n self.y_values.append(self.a * i * i + self.b * i + self.c)\n\n\n print(\"########################################\")\n print (self.y_values)\n print(\"########################################\")\n ################################\n x_x0 = 50 # x axis\n y_x0 = 250 # for x axis\n\n x_y0 = 250 # for y axis\n y_y0 = 50 # for y axis\n d = 40\n\n for i in range(-5, 6):\n self.canvas.create_line(x_x0, y_x0, x_x0 + 1, y_x0 + 1, fill='darkblue') ## for x axis\n self.canvas.create_line(x_y0, y_y0, x_y0 + 1, y_y0 + 1, fill='darkblue') ## for y axis\n\n x_x0 = x_x0 + d\n y_y0 = y_y0 + d\n x_x0 = 50 # x axis\n y_x0 = 250 # x axis\n for value in self.x_values:\n self.canvas.create_text(x_x0, y_x0 + 5, fill=\"Black\", font=\"Times 10 italic bold\", text=value)\n print(\"x_x0:\", x_x0, value)\n x_x0 = x_x0 + d\n\n x_y0 = 250 # for y axis\n y_y0 = 50 # for y axis\n d = 40\n\n for value in self.y_values[:5]:\n print(\"*****\")\n print(value)\n self.canvas.create_text(x_y0 + 10, y_y0, fill=\"darkblue\", font=\"Times 10 italic bold\", text=value)\n\n y_y0 = y_y0 + d\n\n x_y0 = 250 # for y axis\n y_y0 = 450 # for y axis\n d = 40\n for value in self.y_values[:5]:\n print(value * (-1))\n self.canvas.create_text(x_y0 + 10, y_y0, fill=\"darkblue\", font=\"Times 10 italic bold\",\n text=value * (-1))\n\n\n y_y0 = y_y0 - d\n ########## #################################\n\n self.y_values = []\n for i in self.x_values:\n self.y_values.append(self.a * i * i + self.b * i + self.c)\n\n self.eqationLabel[\n \"text\"] = self.get_a_coeff_expression() + self.get_b_coeff_expression() + self.get_c_coeff_expression()\n\n def get_new_coefficient(self):\n if self.coefficientsDialog == None:\n self.coefficientsDialog = CoefficientsDialog(self.root)\n self.coefficientsDialog.parent.wait_window(self.coefficientsDialog.master)\n self.a = self.coefficientsDialog.coefficients['a']\n self.b = self.coefficientsDialog.coefficients['b']\n self.c = self.coefficientsDialog.coefficients['c']\n # print (self.a)\n # print (self.b)\n # print (self.c)\n self.plot_axis()\n self.plot_equation()\n self.coefficientsDialog = None\n\n\n def plot_points(self):\n self.clear_canvas()\n self.plot_axis()\n self.plot_equation()\n try:\n y_min = abs(min(self.y_values))\n y_max = abs(max(self.y_values))\n\n y_final = y_min if y_min > y_max else y_max\n y_ratio = y_final / 5\n print(y_final)\n\n for i in range(len(self.x_values)):\n x_ax = (self.x_values[i] + 5) * 40 + 50\n y_ax = (-1 * self.y_values[i] / y_ratio * 40) + 250\n #print(x_ax, y_ax)\n self.canvas.create_oval(x_ax - 2, y_ax - 2, x_ax + 2, y_ax + 2, outline=\"red\", fill=\"yellow\")\n except:\n pass\n\n\n\n def plot_line(self):\n self.clear_canvas()\n self.plot_axis()\n self.plot_equation()\n y_min = abs(min(self.y_values))\n y_max = abs(max(self.y_values))\n\n y_final = y_min if y_min > y_max else y_max\n y_ratio = y_final / 5\n print(y_final)\n lines_cordionates={}\n\n for i in range(len(self.x_values)):\n x_ax = (self.x_values[i] + 5) * 40 + 50\n y_ax = (-1 * self.y_values[i] / y_ratio * 40) + 250\n lines_cordionates[i]=x_ax,y_ax\n try:\n\n for i in range(len(self.x_values)):\n self.canvas.create_line(lines_cordionates[i][0], lines_cordionates[i][1], lines_cordionates[i+1][0], lines_cordionates[i+1][1], fill='darkblue')\n except:\n pass\n def exit_window(self):\n if messagebox.askyesno(\"Exit\", \"Do you want to quit the application?\"):\n self.window.destroy()\n\n def clear_canvas(self):\n\n self.canvas.delete(\"all\")\n\n def new_equation(self):\n self.plot_axis()\n self.y_values = []\n for i in self.x_values:\n self.y_values.append(self.a * i * i + self.b * i + self.c)\n self.plot_points()\n self.eqationLabel[\n \"text\"] = self.get_a_coeff_expression() + self.get_b_coeff_expression() + self.get_c_coeff_expression()\n\n def get_new_coefficient(self):\n if self.coefficientsDialog == None:\n self.coefficientsDialog = CoefficientsDialog(self.root)\n self.coefficientsDialog.parent.wait_window(self.coefficientsDialog.master)\n self.a = self.coefficientsDialog.coefficients['a']\n self.b = self.coefficientsDialog.coefficients['b']\n self.c = self.coefficientsDialog.coefficients['c']\n\n self.plot_axis()\n self.plot_equation()\n self.coefficientsDialog = None\n\n def get_a_coeff_expression(self):\n if self.a > 1 or self.a < -1:\n return str(self.a) + \"X\" + u\"\\u00B2\"\n elif self.a == -1:\n return \"-X\" + u\"\\u00B2\"\n else:\n return \"X\" + u\"\\u00B2\"\n\n def get_b_coeff_expression(self):\n coeef = self.b\n if coeef > 1:\n return \"+\" + str(coeef) + \"X\"\n elif coeef < -1:\n return str(coeef) + \"X\"\n elif coeef == 1:\n return \"+\" + \"X\"\n elif coeef == -1:\n return \"-\" + \"X\"\n else:\n return \"\"\n\n def get_c_coeff_expression(self):\n coeef = self.c\n if coeef > 0:\n return \"+\" + str(coeef)\n elif coeef < 0:\n return str(coeef)\n else:\n return \"\"\n\n def save_canvas(self):\n self.canvas.postscript(file=\"1017665.ps\", colormode='color')\n\n def show_help_about(self):\n top = Toplevel()\n top.title(\"About this application...\")\n\n msg = Message(top, text=\"Created by Prachi Kolte \\n UB ID: 1017665\")\n msg.pack()\n\n button = Button(top, text=\"Dismiss\", command=top.destroy)\n button.pack()\n\n\nobj = QuadEQPlot(1, 0, 0)\n\n","sub_path":"Graph_window.py","file_name":"Graph_window.py","file_ext":"py","file_size_in_byte":12327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"16231270","text":"#!/usr/bin/env python3\n\n\nimport os\nimport cv2\nimport shutil\n\nfrom utils import load_pickle_file\n\nallowed_width = 256\nallowed_height = 192 \n\nimages, labels = load_pickle_file(\"pickles/image_data_normalized.p\")\n\nif not os.path.exists(\"test_images\"):\n os.makedirs(\"test_images\")\n\nfor img_path in images:\n img = cv2.imread(img_path)\n resized_img = cv2.resize(img,(allowed_width,allowed_height))\n \n parts = img_path.split(\"/\")\n save_path = os.path.join(\"test_images\",\"_\".join(parts[-2:]))\n cv2.imwrite(save_path,resized_img)","sub_path":"build_test_images.py","file_name":"build_test_images.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"237140007","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nfrom scipy.stats import zscore\nimport statsmodels.api as sm\nfrom sklearn.model_selection import cross_val_score,GridSearchCV,train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression, Lasso, Ridge\nfrom sklearn.decomposition import NMF,PCA\nfrom sklearn.metrics import accuracy_score, r2_score\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[2]:\n\n\n#Here, we're importing out 500_Cities datasets\ndf = pd.read_csv('500_Cities__Local_Data_for_Better_Health__2018_release.zip')\n\n# we only need non-adusted numbers, and only for cities not electoral areas\nhealth = df[(df.Data_Value_Type=='Crude prevalence') & \n (df.GeographicLevel.isin(['City','US'])) ]\n\n# pivot so that we have Columns for all the Health Measures, instead of a Row\nhealth_pivot = pd.pivot_table(health, values='Data_Value', index=['StateDesc', 'CityName'], \n columns=['Short_Question_Text'], aggfunc=np.sum).reset_index()\n\n# Pivot table on cities & multi index categories & short question text (short for measure). average on Data Value. \ncategory = df['Category'] == 'Health Outcomes'\ndfPiv = df.pivot_table(index='CityName',columns=['Category','Short_Question_Text'],values='Data_Value',aggfunc=np.mean)\n#Create zscore for all columns to standardize data\ndfPivZscore = dfPiv.apply(zscore)\n\n#Spliting the original data into 3 parts -\n#1. Location dataset 2. Data Definition dataset 3. Data Values\ncolumns_locations = ['UniqueID','StateAbbr','StateDesc','CityName','GeographicLevel', 'TractFIPS','CityFIPS','GeoLocation']\ncolumns_data_definition = ['Category', 'CategoryID', 'Measure','MeasureId','Data_Value_Type','Short_Question_Text']\ncolumns_data = ['Data_Value','DataValueTypeID','Data_Value_Footnote_Symbol', 'Data_Value_Footnote','CategoryID',\n 'GeoLocation','Low_Confidence_Limit', 'High_Confidence_Limit','PopulationCount','StateAbbr',\n 'UniqueID','MeasureId','Year']\n\n\n#Since the column Location has 2 values(latitude, longtitude) in a column, we are splitting them into 2 different columns.\ndf_locations = df[columns_locations].copy()\nlat = []\nlong =[]\nfor row in df_locations['GeoLocation']:\n try:\n # Split the row by comma and append everything before the comma to lat\n latitude = row.split(',')[0]\n latitude = latitude[1:]\n lat.append(latitude)\n # Split the row by comma and append everything after the comma to lon\n longitude = row.split(',')[1]\n longitude = longitude[:-1]\n long.append(longitude)\n except:\n # append a missing value to lat\n lat.append(np.NaN)\n # append a missing value to lon\n long.append(np.NaN)\n# Create two new columns from lat and lon\ndf_locations['Latitude'] = lat\ndf_locations['Longitude'] = long\n\ndel df_locations['GeoLocation']\ndf_locations = df_locations.drop_duplicates().sort_values('UniqueID')\ndf_locations.to_csv('locations.csv')\n\n","sub_path":"cs418_phak/cleanDataframe_locations.py","file_name":"cleanDataframe_locations.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"458443995","text":"import requests\nfrom bs4 import BeautifulSoup\n# Take the code from the How To Decode A Website exercise\n# (if you didn’t do it or just want to play with some different code, use the code from the solution),\n# and instead of printing the results to a screen, write the results to a txt file.\n# In your code, just make up a name for the file you are saving to.\n#\n# Extras:\n#\n# Ask the user to specify the name of the output file that will be saved.\n# Discussion\n#\n# Topics:\n#\n# Writing to a file\n# Gotchas and warnings\n\n\ndef web_spider(p_f_name):\n url = \"https://www.nytimes.com/\"\n r = requests.get(url)\n r_html = r.text\n soup = BeautifulSoup(r_html, \"lxml\")\n f_path = \"c:/tmp/\"+p_f_name+\".txt\"\n f = open(f_path, \"w\", encoding='utf-8')\n for story_heading in soup.find_all(class_=\"story-heading\"):\n if story_heading.a:\n f.write(story_heading.a.text.replace(\"\\n\", \" \").strip())\n f.write(\"\\n\")\n else:\n f.write(story_heading.contents[0].strip())\n f.write(\"\\n\")\n f.close()\n print(\"all information has been done in \" + f_path)\n\nf_name = str(input(\"please input to save file name as below:\\n\"))\nweb_spider(f_name)\n","sub_path":"org/practicepython/21WriteToAFile.py","file_name":"21WriteToAFile.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"344040813","text":"N = [ int(n) for n in \"\".join([ input() for _ in range(20) ]) ]\n\nfrom functools import reduce\n\nmax_product = -1\ni = 0\nwhile i < len(N) - 13:\n print(i)\n product = 1\n A = N[i:i+13]\n \n if 0 in A:\n zero = A[::-1].index(0)\n i += 13-zero\n else:\n product = reduce(lambda x, y: x*y, A)\n if product > max_product:\n max_product = product\n\n i += 1\n\nprint(max_product)","sub_path":"python/problem_008.py","file_name":"problem_008.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"293651642","text":"import random\n\ncards = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']\ncards_pos = []\npos = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\n\nfor i in range(8):\n for j in range(2):\n cards_pos.append(cards[i])\n\nrandom.shuffle(cards_pos)\n\nevent = len(cards)\nmoves = 0\nwhile event > 0:\n x = random.choice(pos)\n choice_1 = cards_pos[x]\n t_pos = pos[:]\n t_pos.remove(x)\n y = random.choice(t_pos)\n choice_2 = cards_pos[y]\n moves += 1\n print(choice_1+\" \"+choice_2)\n if choice_1 == choice_2:\n print(\"Trafione\")\n event -=1\n pos.remove(x)\n pos.remove(y)\n\n\nprint(\"Liczba wszystkich ruchów: \"+str(moves))\n\n# while end == False:\n#\n# if move == 1:\n# if event.type == pygame.locals.MOUSEBUTTONDOWN:\n# x, y = pygame.mouse.get_pos()\n# pole = self.board.cards_pos\n# for pos in pole:\n# if pos.collidepoint(x, y):\n# t_pos = pos\n# choice_1 = self.board.unhide(pos)\n# pygame.display.update()\n# move+=1\n# elif move == 2:\n# if event.type == pygame.locals.MOUSEBUTTONDOWN:\n# x, y = pygame.mouse.get_pos()\n# pole = self.board.cards_pos\n# for pos in pole:\n# if pos.collidepoint(x, y):\n# choice_2 = self.board.unhide(pos)\n# pygame.display.update()\n# if choice_1 == choice_2:\n# print(\"trafione\")\n# else:\n# move = 1\n# self.hide(pos)\n# self.hide(t_pos)\n","sub_path":"count_rules.py","file_name":"count_rules.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"634391103","text":"\"\"\"\nAuthor: Bruno Luca\nDate: 18-08-2020\nTitle: Scrivere una funziona di nome usa_tutte che richieda una parola e \nuna stringa di lettere richieste e che restituisca True se la parola utilizza \ntutte le lettere richeiste almeno una volta\n\"\"\"\n\ndef usa_tutte(word, letter_list):\n for letter in letter_list:\n if not (letter in word):\n return False\n return True\n\nletters = input(\"Insert letters...\\n\")\nfin = open(\"words.txt\")\ncounter = 0\n\nfor line in fin:\n if usa_tutte(line.strip(), letters):\n print(line.strip())\n counter = counter + 1\n\nprint(f\"\\n\\n{counter}\") #598 words use all vocals\n\n\n","sub_path":"tpsit_IV/summer_works/es9_5.py","file_name":"es9_5.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"518290496","text":"from django.test import TestCase\nfrom django.test import Client\nimport datetime\n\n# Create your tests here.\n\nfrom .models import Rankinglist, Player, Match, Ranking\n\nclass ViewsTest(TestCase):\n def setUp(self):\n # Every test needs a client.\n self.client = Client()\n r = Rankinglist.objects.create(name=\"herren\")\n \n roger = Player.objects.create(firstname=\"Roger\",lastname=\"Federer\")\n boris = Player.objects.create(firstname=\"Boris\",lastname=\"Becker\")\n ivan = Player.objects.create(firstname=\"Ivan\",lastname=\"Lendl\")\n\n Ranking.objects.create(position=1,rankinglist=r,player=ivan)\n Ranking.objects.create(position=2,rankinglist=r,player=roger)\n Ranking.objects.create(position=3,rankinglist=r,player=boris)\n\n Match.objects.create(rankinglist=r,playerone=boris,playertwo=ivan,playedat=datetime.datetime(2020, 5, 17)) \n Match.objects.create(rankinglist=r,playerone=boris,playertwo=roger,playedat=datetime.datetime(2020, 5, 16))\n Match.objects.create(rankinglist=r,playerone=boris,playertwo=ivan,playedat=datetime.datetime(2020, 5, 15))\n\n def test_rankingliststats(self): \n r = Rankinglist.objects.get(name=\"herren\")\n\n # Issue a GET request.\n response = self.client.get('/rankinglist/rankinglist/%s/stats' %(r.id))\n\n # Check that the response is 200 OK.\n self.assertEqual(response.status_code, 200)\n\n # Check that the rendered context contains 5 customers.\n self.assertEqual(response.context['rankinglist'].name,\"herren\")\n playersList = response.context['players']\n self.assertEqual(len(playersList),3)\n for i in range(len(playersList)):\n entry = playersList[i]\n if i == 0:\n self.assertEqual(entry[0].firstname,\"Boris\")\n self.assertEqual(entry[1],3)\n elif i == 1:\n self.assertEqual(entry[0].firstname,\"Ivan\")\n self.assertEqual(entry[1],2)\n elif i == 2:\n self.assertEqual(entry[0].firstname,\"Roger\")\n self.assertEqual(entry[1],1)\n else:\n self.assertTrue(False)","sub_path":"rankinglist/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"560083309","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSimple examples demonstrating the use of GLMeshItem.\n\n\"\"\"\n\n## Add path to library (just for examples; you do not need this)\n\n\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\n\napp = QtGui.QApplication([])\nw = gl.GLViewWidget()\nw.show()\nw.setWindowTitle('pyqtgraph example: GLMeshItem')\nw.setCameraPosition(distance=20)\n\ng = gl.GLGridItem()\ng.scale(1, 1, 1)\nw.addItem(g)\n\nimport numpy as np\n\n\n## Example 1:\n## Array of vertex positions and array of vertex indexes defining faces\n## Colors are specified per-face\n\nverts = np.array([\n [0, 0, 0], # 0\n [2, 0, 0], # 1\n [2, 5, 0], # 2\n [0, 5, 0], # 3\n [0, 0, 1], # 4\n [2, 0, 1], # 5\n [2, 5, 1], # 6\n [0, 5, 1], # 7\n])\nfaces = np.array([\n # bottom face\n [0, 1, 2],\n [2, 3, 0],\n # top face\n [4, 5, 6],\n [6, 7, 4],\n # back face\n [0, 1, 5],\n [0, 4, 5],\n # front face\n [2, 3, 7],\n [2, 6, 7],\n # right face\n [1, 2, 6],\n [1, 5, 6],\n # left face\n [0, 3, 7],\n [0, 4, 7],\n])\ncolors = np.array([\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0],\n [1, 0, 0, 1.0]\n])\n\n## Mesh item will automatically compute face normals.\nm1 = gl.GLMeshItem(vertexes=verts, faces=faces, smooth=False, shader='shaded', glOptions='opaque')\nm1.translate(5, 5, 0)\nm1.setGLOptions('additive')\nw.addItem(m1)\n\n#\n# ## Example 2:\n# ## Array of vertex positions, three per face\n# verts = np.empty((36, 3, 3), dtype=np.float32)\n# theta = np.linspace(0, 2*np.pi, 37)[:-1]\n# verts[:,0] = np.vstack([2*np.cos(theta), 2*np.sin(theta), [0]*36]).T\n# verts[:,1] = np.vstack([4*np.cos(theta+0.2), 4*np.sin(theta+0.2), [-1]*36]).T\n# verts[:,2] = np.vstack([4*np.cos(theta-0.2), 4*np.sin(theta-0.2), [1]*36]).T\n#\n# ## Colors are specified per-vertex\n# colors = np.random.random(size=(verts.shape[0], 3, 4))\n# m2 = gl.GLMeshItem(vertexes=verts, vertexColors=colors, smooth=False, shader='balloon',\n# drawEdges=True, edgeColor=(1, 1, 0, 1))\n# m2.translate(-5, 5, 0)\n# w.addItem(m2)\n\n\n\n\n \n\n\n## Start Qt event loop unless running in interactive mode.\nif __name__ == '__main__':\n import sys\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()\n","sub_path":"three_dim_plotting/example_GLMeshItem_box_w_shading.py","file_name":"example_GLMeshItem_box_w_shading.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"420277044","text":"\"\"\" Evaluate the baselines ont ROUGE/METEOR\"\"\"\n\"\"\" Adapted from https://github.com/ChenRocks/fast_abs_rl \"\"\"\nimport argparse\nimport json\nimport os\nfrom os.path import join, exists\nimport bert_score\nimport re\nimport torch\n\n\ndef _count_data(path):\n \"\"\" count number of data in the given path\"\"\"\n matcher = re.compile(r'[0-9]+\\.ref')\n match = lambda name: bool(matcher.match(name))\n names = os.listdir(path)\n n_data = len(list(filter(match, names)))\n return n_data\n\n\ndef _read_file(filename):\n # print(dec_fname)\n summary_sent_list_lower = []\n with open(filename) as f:\n for _, l in enumerate(f):\n summary_sent_list_lower.append(l.strip().lower())\n summary_str_lower = ' '.join(summary_sent_list_lower)\n return summary_str_lower\n\n\ndef _construct_list(dec_dir, ref_dir):\n print(dec_dir)\n print(ref_dir)\n n_data = _count_data(ref_dir)\n output_summary_str_list = []\n ref_summary_str_list = []\n for i in range(n_data):\n dec_fname = join(dec_dir, '{}.dec'.format(i))\n output_summary_str_lower = _read_file(dec_fname)\n output_summary_str_list.append(output_summary_str_lower)\n ref_fname = join(ref_dir, '{}.ref'.format(i))\n ref_summary_str_lower = _read_file(ref_fname)\n ref_summary_str_list.append(ref_summary_str_lower)\n return output_summary_str_list, ref_summary_str_list\n\n\ndef main():\n torch.multiprocessing.set_sharing_strategy('file_system')\n\n parser = argparse.ArgumentParser('Calculate BERTScore')\n parser.add_argument('--lang', type=str, default=None,\n help='two-letter abbreviation of the language (e.g., en) or \"en-sci\" for scientific text')\n parser.add_argument('-m', '--model', default=None,\n help='BERT model name (default: bert-base-uncased) or path to a pretrain model')\n parser.add_argument('-l', '--num_layers', type=int, default=None, help='use first N layer in BERT (default: 8)')\n parser.add_argument('-b', '--batch_size', type=int, default=64, help='batch size (default: 64)')\n parser.add_argument('--nthreads', type=int, default=4, help='number of cpu workers (default: 4)')\n parser.add_argument('--idf', action='store_true', help='BERT Score with IDF scaling')\n parser.add_argument('--rescale-with-baseline', action='store_true', help='Rescaling the numerical score with precomputed baselines')\n #parser.add_argument('-s', '--seg_level', action='store_true', help='show individual score of each pair')\n parser.add_argument('-v', '--verbose', action='store_true', help='increase output verbosity')\n parser.add_argument('--decode_dir', action='store', required=True, help='directory of decoded summaries')\n parser.add_argument('--data', action='store', required=True, help='directory of decoded summaries')\n\n args = parser.parse_args()\n\n dec_dir = join(args.decode_dir, 'output')\n with open(join(args.decode_dir, 'log.json')) as f:\n split = json.loads(f.read())['split']\n ref_dir = join(args.data, 'refs', split)\n print(ref_dir)\n assert exists(ref_dir)\n\n output_summary_str_list, ref_summary_str_list = _construct_list(dec_dir, ref_dir)\n all_preds, hash_code = bert_score.score(cands=output_summary_str_list, refs=ref_summary_str_list, model_type=args.model, num_layers=args.num_layers,\n verbose=args.verbose, idf=args.idf, batch_size=args.batch_size,\n lang=args.lang, return_hash=True,\n rescale_with_baseline=args.rescale_with_baseline)\n avg_scores = [s.mean(dim=0) for s in all_preds]\n P = avg_scores[0].cpu().item()\n R = avg_scores[1].cpu().item()\n F1 = avg_scores[2].cpu().item()\n msg = hash_code + \\\n f' R: {R:.6f} P: {P:.6f} F1: {F1:.6f}'\n print(msg)\n \"\"\"\n if args.seg_level:\n ps, rs, fs = all_preds\n for p, r, f in zip(ps, rs, fs):\n print('{:.6f}\\t{:.6f}\\t{:.6f}'.format(p, r, f))\n \"\"\"\n\n f1_all = all_preds[2]\n f1_all_list = f1_all.cpu().tolist()\n with open(join(args.decode_dir, 'bertscore.txt'), 'w') as f:\n for f1 in f1_all_list:\n f.write(\"{:.6f}\\n\".format(f1))\n print(\"Finish!\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"evaluate_bert_score.py","file_name":"evaluate_bert_score.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"132201576","text":"import os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nexperiment_base_folder = '/itet-stor/baumgach/net_scratch/logs/phiseg/lidc/'\nexperiment_list = ['probunet',\n 'phiseg_7_1',\n 'phiseg_7_5',\n 'probunet_1annot',\n 'phiseg_7_1_1annot',\n 'phiseg_7_5_1annot']\nexperiment_names = ['probunet','phiseg_7_1', 'phiseg_7_5', 'probunet_1annot', 'phiseg_7_1_1annot', 'phiseg_7_5_1annot']\nfile_list = ['ged100_best_ged.npz']*len(experiment_list)\n\n\nged_list = []\n\nfor folder, exp_name, file in zip(experiment_list, experiment_names, file_list):\n\n experiment_path = os.path.join(experiment_base_folder, folder, file)\n\n ged_arr = np.load(experiment_path)['arr_0']\n\n ged_list.append(ged_arr)\n\nged_tot_arr = np.asarray(ged_list).T\n\nprint('significance')\nprint('REMINDER: are you checking the right methods?')\nprint(stats.ttest_rel(ged_list[0], ged_list[1]))\n\nprint('Results summary')\nmeans = ged_tot_arr.mean(axis=0)\nstds= ged_tot_arr.std(axis=0)\n\nfor i in range(means.shape[0]):\n print('Exp. name: %s \\t %.4f +- %.4f' % (experiment_names[i], means[i], stds[i]))\n\ndf = pd.DataFrame(ged_tot_arr, columns=experiment_names)\ndf = df.melt(var_name='experiments', value_name='vals')\n\nsns.boxplot(x='experiments', y='vals', data=df)\nplt.show()","sub_path":"eval_ged_plot.py","file_name":"eval_ged_plot.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"228589745","text":"N, X = list(map(int, input().split()))\nA = ['dummy'] + list(map(int, input().split()))\n\n# dp[i][j][k]\n# i: i番目まで見た\n# j: j個選んだ\n# k: jで割ったあまりがk\ndp = [[[0]*N for _ in range(N+1)] for _ in range(N+1)]\nfor i in range(N):\n for j in range(N):\n for k in range(N):\n # i+1番目を選ぶ\n new_val = dp[i][j][k] + A[i+1]\n # print(i+1, j+1, new_val%(j+1), dp[i+1][j+i][new_val%(j+1)])\n dp[i+1][j+1][new_val%(j+1)] = max(new_val, dp[i+1][j+1][new_val%(j+1)])\n # i+1番目を選ばない\n dp[i+1][j][k] = max(dp[i][j][k], dp[i+1][j][k])\n\nprint(*dp, sep='\\n')\nans = N*X\nfor j in range(1, N+1):\n k = X%j\n print(N, j, k)\n if dp[N][j][k] == 0:\n continue\n ans = min((X-dp[N][j][k])//j, ans)\n\nprint(ans)","sub_path":"old/ABC192/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"595541248","text":"#!/usr/bin/env python3\n# coding: utf-8\n\"\"\"\nTwinleaf Generic Device Control\nCopyright 2017 Twinleaf LLC\nLicense: MIT\n\n\"\"\"\nimport binascii\nimport struct\n\nSLIP_END = 0xC0\nSLIP_END_CHAR = b\"\\xC0\"\nSLIP_ESC = 0xDB\nSLIP_ESC_END = 0xDC\nSLIP_ESC_ESC = 0xDD\nSLIP_MAX_LEN = 2048\n\nclass SLIPEncodingError(IOError):\n pass\n\ndef decode(slipbuf):\n if len(slipbuf) < 4:\n raise SLIPEncodingError(\"Packet too short\")\n msg = bytearray()\n rx_esc_next = False\n for byte in slipbuf:\n if rx_esc_next:\n rx_esc_next = False\n if byte == SLIP_ESC_END:\n msg.append(SLIP_END)\n elif byte == SLIP_ESC_ESC:\n msg.append(SLIP_ESC)\n else:\n raise SLIPEncodingError(\"Corrupt SLIP stream: SLIP_ESC not followed by valid escape code\")\n elif byte == SLIP_ESC:\n rx_esc_next = True\n elif byte == SLIP_END:\n # Should have already been framed by SLIP_END\n #raise SLIPEncodingError(\"Corrupt SLIP stream: SLIP_END in packet\")\n pass\n else:\n msg.append(byte)\n msg_checksum = struct.unpack(\"= 27 and vm <= 107:\n\t\tvc = vm - 7\n\telif vm >= 108 and vm <= 121:\n\t\tvc = vm - 8\n\telif vm >= 122 and vm <= 135:\n\t\tvc = vm - 9\n\telif vm >= 136 and vm <= 150:\n\t\tvc = vm - 10\n\telif vm >= 151 and vm <= 161:\n\t\tvc = vm - 11\n\telse:\n\t\tvc = vm\n\n\tvinte = int (vr + ((20*40)/100))\t\n\tcinquenta = vr + ((50*40)/100)\n\n\tif vc >= vr and vc <= vinte:\n\t\tinfracao1 = 1\n\t\tpenalidade = True\n\n\telif vc > vinte and vc <= cinquenta:\n\t\tinfracao1 = 2\n\t\tpenalidade = True\n\n\telif vc > cinquenta:\n\t\tinfracao1 = 3\n\t\tpenalidade = True\n\telse:\n\t\tinfracao = 0\n\t\tpenalidade = 0\t\n\tlista = [vm, vc, infracao1, penalidade,vr]\n\treturn lista\n\n","sub_path":"Testes_Individuais/controle_infracao.py","file_name":"controle_infracao.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"398311018","text":"import pybullet as p\nimport time\nimport pybullet_data\nimport os \n\npath = \"C:/Users/Faga/Desktop/Nathan/ENSTA/Cours/2A/PRe/PRe/burg-toolkit/data/tmp/table.urdf\"\n\n\nphysicsClient = p.connect(p.GUI)#or p.DIRECT for non-graphical version\n\np.setAdditionalSearchPath(pybullet_data.getDataPath()) #optionally\np.loadURDF(\"plane.urdf\")\np.setGravity(0,0,-9.81)\n\nstartPosBox = [0,0,2]\nstartOrientationBox = p.getQuaternionFromEuler([0,0,0])\nboxId = p.loadURDF(\"r2d2.urdf\",startPosBox, startOrientationBox)\n\nstartPosTable = [5,0,0]\nstartOrientationTable = p.getQuaternionFromEuler([0,0,0])\nTableId = p.loadURDF(path, startPosTable, startOrientationTable)\n\n#numJoints = p.getNumJoints(boxId)\n#print(numJoints)\n\n#print(p.getJointInfo(boxId, 2))\n#print(p.getJointInfo(boxId, 3))\n#print(p.getJointInfo(boxId, 6))\n#print(p.getJointInfo(boxId, 7))\n\nmaxForce = 500\ntargetVel = -0.01\n#p.setJointMotorControl2(bodyUniqueId = boxId, jointIndex = 2, controlMode = p.VELOCITY_CONTROL, targetVelocity = targetVel, force = maxForce)\n#p.setJointMotorControl2(bodyUniqueId = boxId, jointIndex = 3, controlMode = p.VELOCITY_CONTROL, targetVelocity = targetVel, force = maxForce)\n#p.setJointMotorControl2(bodyUniqueId = boxId, jointIndex = 6, controlMode = p.VELOCITY_CONTROL, targetVelocity = targetVel, force = maxForce)\n#p.setJointMotorControl2(bodyUniqueId = boxId, jointIndex = 7, controlMode = p.VELOCITY_CONTROL, targetVelocity = targetVel, force = maxForce)\n\n#p.setJointMotorControlArray(bodyIndex = boxId, jointIndices = [2,3,6,7], controlMode = p.VELOCITY_CONTROL, targetVelocities = [targetVel, targetVel, targetVel, targetVel], forces = [maxForce,maxForce,maxForce,maxForce])\n#p.applyExternalForce(objectUniqueId = boxId, linkIndex = -1, forceObj = [-10,0,0], posObj = [1,0,0], flags = p.WORLD_FRAME)\n\n#set the center of mass frame (loadURDF sets base link frame) startPos/Ornp.resetBasePositionAndOrientation(boxId, startPos, startOrientation)\nfor i in range (10000):\n #print(p.getJointState(bodyUniqueId = boxId, jointIndex = 2))\n p.setJointMotorControlArray(bodyIndex = boxId, jointIndices = [2,3,6,7], controlMode = p.VELOCITY_CONTROL, targetVelocities = [i*targetVel, i*targetVel, i*targetVel, i*targetVel], forces = [maxForce,maxForce,maxForce,maxForce])\n p.stepSimulation()\n time.sleep(1./240.)\n\ncubePos, cubeOrn = p.getBasePositionAndOrientation(boxId)\nprint(cubePos,cubeOrn)\n\np.disconnect()\n","sub_path":"burg-toolkit/entrainement.py","file_name":"entrainement.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"552789879","text":"from PIL import Image\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass myConv2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size=1):\n super(myConv2d, self).__init__()\n padding = (kernel_size-1)//2\n self.conv = nn.Conv2d(in_channels, out_channels,\n kernel_size=kernel_size, padding=padding)\n\n def forward(self, x):\n return self.conv(x)\n\n\nclass dilatedConv(nn.Module):\n ''' stride == 1 '''\n\n def __init__(self, in_channels, out_channels, kernel_size=3, dilation=1):\n super(dilatedConv, self).__init__()\n # f = (kernel_size-1) * d +1\n # new_width = (width - f + 2 * padding)/stride + stride\n padding = (kernel_size-1) * dilation // 2\n self.conv = nn.Conv2d(in_channels, out_channels,\n kernel_size, dilation=dilation, padding=padding)\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n return self.relu(self.bn(self.conv(x)))\n\n\nclass globalNet(nn.Module):\n def __init__(self, in_channels, out_channels, scale_factor=0.25, kernel_size=3, dilations=None):\n super(globalNet, self).__init__()\n self.scale_factor = scale_factor\n if not isinstance(in_channels, list):\n in_channels = [in_channels]\n if not isinstance(out_channels, list):\n out_channels = [out_channels]\n mid_channels = 128\n if dilations is None:\n dilations = [1, 2, 5]\n for i, n_chan in enumerate(in_channels):\n setattr(self, 'in{i}'.format(i=i),\n myConv2d(n_chan, mid_channels//2, 3))\n for i, n_chan in enumerate(out_channels):\n setattr(self, 'in_local{i}'.format(i=i),\n myConv2d(n_chan, (mid_channels+1)//2, 3))\n setattr(self, 'out{i}'.format(i=i),\n myConv2d(mid_channels, n_chan, 1))\n convs = [dilatedConv(mid_channels, mid_channels,\n kernel_size, dilation) for dilation in dilations]\n convs = nn.Sequential(*convs)\n setattr(self, 'convs{}'.format(i), convs)\n\n def forward(self, x, local_feature, task_idx=0):\n size = x.size()[2:]\n sf = self.scale_factor\n x = F.interpolate(x, scale_factor=sf)\n local_feature = F.interpolate(local_feature, scale_factor=sf)\n x = getattr(self, 'in{}'.format(task_idx))(x)\n local_feature = getattr(\n self, 'in_local{}'.format(task_idx))(local_feature)\n fuse = torch.cat((x, local_feature), dim=1)\n x = getattr(self, 'convs{}'.format(task_idx))(fuse)\n x = getattr(self, 'out{}'.format(task_idx))(x)\n x = F.interpolate(x, size=size)\n return torch.sigmoid(x)\n\n\nclass GLN(nn.Module):\n ''' global and local net '''\n\n def __init__(self, localNet, localNet_params, globalNet_params):\n super(GLN, self).__init__()\n self.localNet = localNet(**localNet_params)\n in_channels = localNet_params['in_channels']\n out_channels = localNet_params['out_channels']\n globalNet_params['in_channels'] = in_channels\n globalNet_params['out_channels'] = out_channels\n self.globalNet = globalNet(**globalNet_params)\n\n def forward(self, x, task_idx=0):\n local_feature = self.localNet(x, task_idx)['output']\n global_feature = self.globalNet(x, local_feature, task_idx)\n return {'output': global_feature*local_feature}\n","sub_path":"universal_landmark_detection/model/networks/gln.py","file_name":"gln.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"575892948","text":"import logging\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] ====> %(message)s')\n\"\"\"启动与停止线程\"\"\"\nimport time\nfrom threading import Thread\n\ndef countdown(n):\n while n > 0:\n n -= 1\n time.sleep(5)\n\nif __name__ == '__main__':\n t = Thread(target=countdown, args=(10,))\n t.start() # 启动线程\n if t.is_alive():\n logging.info('Still running')\n else:\n logging.info('Completed')\n\n # 将一个线程加入当前线程,并等待它终止\n t.join()\n # 对于长时间运行的线程或者需要一直运行的后台任务,可以考虑使用后台线程\n # 后台线程无法等待,会在主线程终止时自动销毁\n Thread(target=countdown, args=(10, ), daemon=True)\n","sub_path":"高级特性/chapter12/12_1.py","file_name":"12_1.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"653442706","text":"from Modules.object import object\nfrom math import sin,cos,radians,degrees\nfrom Modules.collision import rect2rect\nimport pygame\n\nclass portal(object):\n\n def __init__(self,p1,angle):\n self.frames = [pygame.image.load(f'Assets\\\\gravPortal\\\\gravPortal{i+1}.png') for i in range(8)]\n for i,frame in enumerate(self.frames):\n self.frames[i] = pygame.transform.rotate(frame,-angle)\n\n self.index = 0\n self.time = 0\n self.surf = self.frames[0]\n\n self.angle = radians(angle)\n\n self.rect = self.surf.get_rect()\n self.rect.center = p1\n\n self.pts = [(p1[0]-sin(-self.angle+radians(90))*50,p1[1]-cos(-self.angle+radians(90))*50),(p1[0]+sin(-self.angle+radians(90))*50,p1[1]+cos(-self.angle+radians(90))*50)]\n\n def update(self,dtime,objects):\n\n for obj in objects:\n if type(obj).__name__ == 'player':\n if rect2rect(self.pts+[self.pts[1],self.pts[0]],obj.pts):\n obj.angle = self.angle\n\n self.time += dtime\n if self.time > 100:\n self.time -= 100\n self.index += 1\n self.index %= len(self.frames)\n\n self.surf = self.frames[self.index]\n\n def draw(self,root):\n root.blit(self.surf,self.rect)\n #pygame.draw.polygon(root, (0,0,255), self.pts+self.pts,3)\n #pygame.draw.rect(root,(0,255,0),self.rect,4)\n #pygame.draw.circle(root,(0,255,0),self.rect.center,10)\n pass","sub_path":"compilation2/Modules/portal.py","file_name":"portal.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"138010573","text":"import warnings\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport os\nfrom sklearn.preprocessing import StandardScaler\n\nfrom autoscalingsim.scaling.policiesbuilder.metric.forecasting.forecasting_model import ForecastingModel\nfrom autoscalingsim.utils.error_check import ErrorChecker\n\n@ForecastingModel.register('lstm')\nclass LSTM(ForecastingModel):\n\n \"\"\" Long short-term memory (LSTM) recurrent neural network (RNN) for time series forecasting \"\"\"\n\n def __init__(self, config : dict):\n\n super().__init__(config)\n\n if self._model_fitted is None:\n\n forecasting_model_params = ErrorChecker.key_check_and_load('config', config)\n self.lags = ErrorChecker.key_check_and_load('lags', forecasting_model_params, self.__class__.__name__, default = 1)\n self.n_epochs = ErrorChecker.key_check_and_load('n_epochs', forecasting_model_params, self.__class__.__name__, default = 10)\n self.d = ErrorChecker.key_check_and_load('differencing_order', forecasting_model_params, self.__class__.__name__, default = 0)\n\n neurons_count = ErrorChecker.key_check_and_load('neurons_count', forecasting_model_params, self.__class__.__name__)\n loss_function = ErrorChecker.key_check_and_load('loss_function', forecasting_model_params, self.__class__.__name__, default = 'mean_squared_error')\n optimizer = ErrorChecker.key_check_and_load('optimizer', forecasting_model_params, self.__class__.__name__, default = 'adam')\n\n self.scaler = StandardScaler()\n\n self._model_fitted = tf.keras.models.Sequential([\n tf.keras.layers.LSTM(neurons_count, batch_input_shape = (1, 1, self.lags), stateful = True),\n tf.keras.layers.Dense(units = 1)\n ])\n self._model_fitted.compile(loss = loss_function, optimizer = optimizer)\n\n def load_from_location(self, path_to_models_dir : str):\n\n path_to_model_file = os.path.join(path_to_models_dir, self._construct_model_filepath())\n if os.path.isfile(path_to_model_file):\n self._model_fitted = tf.keras.models.model_load( path_to_model_file )\n\n def save_to_location(self):\n\n if not self.dir_to_store_models is None:\n if not os.path.exists(self.dir_to_store_models):\n os.makedirs(self.dir_to_store_models)\n\n path_to_model_file = os.path.join(self.dir_to_store_models, self._construct_model_filepath())\n if not self._model_fitted is None:\n self._model_fitted.save( path_to_model_file )\n\n def _internal_fit(self, data : pd.DataFrame):\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n\n if data.shape[0] > self.lags:\n lagged_data = self._introduce_explicit_lags(data)\n differenced_data = self._difference_timeseries(lagged_data)\n scaled_data = self._scale(differenced_data)\n self._fit_model(scaled_data)\n return True\n\n else:\n return False\n\n def _internal_predict(self, metric_vals : pd.DataFrame, cur_timestamp : pd.Timestamp, future_adjustment_from_others : pd.DataFrame = None):\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n forecast_interval = self._construct_future_interval(cur_timestamp)\n forecast = self._forecast(metric_vals, forecast_interval)\n forecast_unscaled = [ self._unscale(fc) for fc in forecast ]\n forecast_restored = self._undifference_timeseries(metric_vals, forecast_unscaled)\n\n return pd.DataFrame({ metric_vals.index.name : forecast_interval, 'value': forecast_restored } ).set_index(metric_vals.index.name)\n\n def _introduce_explicit_lags(self, data : pd.DataFrame):\n\n result = data.copy()\n for lag in range(0, self.lags):\n result[f'value-{lag + 1}'] = result.value.shift(lag + 1)\n\n return result.fillna(0)\n\n def _difference_timeseries(self, data : pd.DataFrame, d : int = 1):\n\n return data.diff().fillna(0)\n\n def _undifference_timeseries(self, historical_data : pd.DataFrame, forecasted_data : list):\n\n return np.cumsum(historical_data.tail(1).value.to_list() + forecasted_data).tolist()[1:]\n\n def _restore_df(self, matrix_of_numbers : np.ndarray, original_df : pd.DataFrame):\n\n data = dict()\n for i in range(matrix_of_numbers.shape[1]):\n data[original_df.columns[i]] = matrix_of_numbers[:,i]\n\n return pd.DataFrame(data, index = original_df.index)\n\n def _scale(self, data : pd.DataFrame):\n\n return self._restore_df(self.scaler.fit_transform(data), data)\n\n def _unscale(self, value : float):\n\n array = np.array([value] + [0] * (len(self.scaler.scale_) - 1))\n array = array.reshape(1, len(array))\n inverted = self.scaler.inverse_transform(array)\n\n return inverted[0, -1]\n\n def _fit_model(self, train : pd.DataFrame):\n\n X, y = train[train.columns[train.columns != 'value']].to_numpy(), train['value'].to_numpy()\n X = X.reshape(X.shape[0], 1, X.shape[1])\n\n for i in range(self.n_epochs):\n self._model_fitted.fit(X, y, epochs = 1, batch_size = 1, verbose=0, shuffle=False)\n self._model_fitted.reset_states()\n\n def _forecast(self, measurements : pd.DataFrame, forecast_interval : pd.Series):\n\n last = measurements[-self.lags:]['value'].to_numpy().flatten().tolist()\n\n predicted = list()\n for i in range(len(forecast_interval)):\n X = np.asarray(last).astype('float32')\n X = X.reshape(1, 1, self.lags)\n yhat = self._model_fitted.predict(X, batch_size = 1).flatten()\n predicted.extend(yhat)\n last = last[1:]\n last.extend(yhat)\n\n return predicted\n","sub_path":"autoscalingsim/scaling/policiesbuilder/metric/forecasting/models/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"553723164","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Software : nothing\n# @File : zaniu_task.py\n# @Author : zaniu (Zzaniu@126.com)\n# @Date : 2019/3/21 11:29 \n# @Description : route 实现了queue 和 timeout, timeout还有点问题,终结进程不能终结进程里面产生的子进程\n# 采用 subprocess.Popen(\"cmd.exe /k taskkill /F /T /PID %i\" % process.pid, shell=True)\n# 的方式结束子进程以及孙子进程会导致后续的任务无法执行\nfrom lib.erweima import make_code\nfrom redis_publish.redis_base import MyRq\n\nzaniu = MyRq()\n\n\n@zaniu.route(queue='LevelLow', timeout=5)\ndef add_1():\n print('沙雕')\n return 2\n\n\n@zaniu.route(queue='LevelLow', timeout=20)\ndef get_serialno_spider():\n import os\n os.system(r\"python E:\\HGSpider\\run.py\")\n\n\n@zaniu.route(queue='LevelLow')\ndef generate_code():\n text = '沙雕'\n make_code(text)\n\n\n@zaniu.route(queue='LevelLow', timeout=10)\ndef add_3(x, retry=0):\n print(\"retry = \", retry)\n if x > 3: return\n if retry > 1: raise Exception('沙雕')\n return add_3(x + 1, retry=retry + 1)\n","sub_path":"redis_publish/zaniu_task.py","file_name":"zaniu_task.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"77044185","text":"import os\n\nos.environ['MIGRATION'] = '1'\n\nif not os.getenv('FLASK_ENV') == 'production':\n print(\"Loading environment variables from .env\")\n from dotenv import load_dotenv\n\n load_dotenv()\n\nimport random\nfrom pathlib import Path\nfrom difflib import get_close_matches\nfrom werkzeug.security import generate_password_hash\nfrom werkzeug.utils import secure_filename\nfrom services.database import db\n\nfrom models.model_comment import Comment\nfrom models.model_equipment import Equipment\nfrom models.model_ingredient import Ingredient\nfrom models.model_recipe import Recipe\nfrom models.model_step import Step\nfrom models.model_tag import Tag\nfrom models.model_user import User\nfrom models.relation_like import LikeRelation\nfrom models.relation_recipe_equipment import RecipeEquipmentRelation\nfrom models.relation_recipe_ingredient import RecipeIngredientRelation\nfrom models.relation_recipe_tag import RecipeTagRelation\nfrom models.relation_step_equipment import StepEquipmentRelation\nfrom models.relation_step_ingredient import StepIngredientRelation\nfrom models.relation_subscription import SubscriptionRelation\nimport pandas as pd\n\nall_models = [User, Recipe, Comment, Equipment, Ingredient, Step, Tag,\n LikeRelation, SubscriptionRelation, RecipeEquipmentRelation, RecipeIngredientRelation,\n RecipeTagRelation,\n StepEquipmentRelation, StepIngredientRelation]\n\n# Step 1: Delete all existing data\ndb.drop_tables(all_models)\ndb.create_tables(all_models)\n\n# Step 2: User\npassword = 'Test1234'\nusers_df = pd.read_csv(\"data/users.csv\", sep=';')\nusers = []\nfor user_id, user in users_df.iterrows():\n random.seed(1992 + user_id)\n userId = secure_filename(user['name'].strip()).lower().replace(\"_\", \"\") + (\"%02d\" % random.randint(0, 99))\n users.append(User(userId=userId, name=user['name'].strip(), email=user['email'].strip(),\n pw_hash=generate_password_hash(password), imgName=\"user-%s.png\" % userId\n ))\n\nUser.bulk_create(users)\n\n# Step 3: Tags\ntags_df = pd.read_csv(\"data/tags.csv\", sep=';')\ntags = []\ntag_names = []\nfor tag_id, tag in tags_df.iterrows():\n tags.append(Tag(text=tag['text'].strip()))\n tag_names.append(tag['text'].strip().lower().replace(' ', ''))\nTag.bulk_create(tags)\n\n# Step 4: Ingredients\ningredients_df = pd.read_csv(\"data/ingredients.csv\", sep=';')\ningredients = []\ningredient_names = []\nfor ingredient_id, ingredient in ingredients_df.iterrows():\n ingredients.append(Ingredient(name=ingredient['name'].strip()))\n ingredient_names.append(ingredient['name'].strip().lower().replace(' ', ''))\n\nIngredient.bulk_create(ingredients)\n\n# Step 5: Recipes\nwith Path(\"data/recipes.txt\").open('r') as f:\n lines = f.readlines()\n\nrecipes = []\nrecipe_ingredients = []\nsteps = []\nrecipe_tags = []\nrecipe_id = 0\nstep_no = 1\nfor line in lines[1:]:\n d = line.split('\\t')\n if len(d) <= 1:\n continue\n recipe_name = d[1].strip()\n ingredient_name = d[9].strip()\n step = d[12].strip() if len(d) > 12 else ''\n tag_name = d[14].strip() if len(d) > 14 else ''\n\n if recipe_name:\n recipe_serving = int(d[2]) if d[2] else 0\n recipe_prep_time = int(d[3])\n recipe_cook_time = int(d[4])\n recipe_desc = str(d[5]).strip()\n recipes.append(\n Recipe(user=users[0], name=recipe_name, serving=recipe_serving,\n preparation_time=recipe_prep_time, cooking_time=recipe_cook_time, description=recipe_desc,\n imgName=\"recipe-img.png\"))\n step_no = 1\n\n if ingredient_name:\n ingredient_name_parsed = ingredient_name.strip().lower().replace(' ', '')\n ingredient_searchs = get_close_matches(word=ingredient_name_parsed, possibilities=ingredient_names,\n cutoff=0.6)\n assert len(ingredient_searchs) > 0\n\n ingredient = ingredients[ingredient_names.index(ingredient_searchs[0])]\n\n ingredient_qty = d[7]\n ingredient_unit = d[8].strip()\n ingredient_remark = d[10].strip() if len(d) > 10 else ''\n\n recipe_ingredients.append(\n RecipeIngredientRelation(recipe=len(recipes), ingredient=ingredient,\n qty=ingredient_qty, unit=ingredient_unit, remark=ingredient_remark)\n )\n\n if step:\n steps.append(Step(no=step_no, text=step, recipe=len(recipes)))\n step_no += 1\n\n if tag_name:\n tag_name_parsed = tag_name.strip().lower().replace(' ', '')\n tag_searchs = get_close_matches(word=tag_name_parsed, possibilities=tag_names, cutoff=0.6)\n assert len(tag_searchs) > 0\n\n tag = tags[tag_names.index(tag_searchs[0])]\n recipe_tags.append(RecipeTagRelation(recipe=len(recipes), tag=tag))\n step_no += 1\n\nRecipe.bulk_create(recipes)\nRecipeIngredientRelation.bulk_create(recipe_ingredients)\nStep.bulk_create(steps)\nRecipeTagRelation.bulk_create(recipe_tags)\n\n# Step 6: Subscriptions\nsubscriptions = []\nrandom.seed(1993)\nsubscription_id = 0\nfor toUserId in range(len(users)):\n if toUserId == 20:\n fromUserIds = [i for i in range(len(users)) if i != 20]\n else:\n random.seed(1993 + toUserId)\n numFromUserId = random.randint(0, len(users) - 1)\n random.seed(1993 + toUserId + 10)\n fromUserIds = random.sample(range(len(users)), numFromUserId)\n\n if 0 not in fromUserIds:\n fromUserIds.append(0)\n\n if toUserId in fromUserIds:\n fromUserIds.remove(toUserId)\n\n for fromUserId in fromUserIds:\n subscriptions.append(SubscriptionRelation(from_user=fromUserId + 1, to_user=toUserId + 1))\n subscription_id += 1\n\nSubscriptionRelation.bulk_create(subscriptions)\n\n# Step 7: Likes\nlikes = []\nrandom.seed(1993)\nfor fromUserId in range(len(users)):\n random.seed(1993 + fromUserId)\n numLikeRecipe = random.randint(0, len(recipes) - 1)\n random.seed(1993 + fromUserId + 10)\n likeRecipes = random.sample(range(len(recipes)), numLikeRecipe)\n\n for likeRecipe in likeRecipes:\n likes.append(LikeRelation(user=fromUserId + 1, recipe=likeRecipe + 1))\n\nLikeRelation.bulk_create(likes)\n\n# Step 8: Comments\nwith Path('data/comments.txt').open('r') as f:\n comment_texts = f.readlines()\n comment_texts = [c.strip() for c in comment_texts if c.strip()]\n\ncomment_now_texts = comment_texts\ncomments = []\nfor fromUserId in range(len(users)):\n for recipeId in range(len(recipes)):\n random.seed(1993 + fromUserId + recipeId)\n haveComment = random.randint(0, 10)\n if haveComment > 8:\n random.seed(2993 + fromUserId)\n numCommentTexts = random.randint(1, 3)\n random.seed(5993 + fromUserId)\n if numCommentTexts > len(comment_now_texts):\n comment_now_texts = comment_texts\n\n comment_selected_idxs = random.sample(range(len(comment_now_texts)), numCommentTexts)\n for c in comment_selected_idxs:\n comments.append(Comment(user=fromUserId + 1, recipe=recipeId + 1, text=comment_texts[c]))\n comment_now_texts.remove(comment_texts[c])\n\nComment.bulk_create(comments)\n","sub_path":"back-end/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":7136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"526687248","text":"'''\n\n\nSherlock Holmes suspects his archenemy Professor Moriarty is once again plotting something diabolical. Sherlock's companion, Dr. Watson, suggests Moriarty may be responsible for MI6's recent issues with their supercomputer, The Beast.\n\nShortly after resolving to investigate, Sherlock receives a note from Moriarty boasting about infecting The Beast with a virus. He also gives him a clue: an integer. Sherlock determines the key to removing the virus is to find the largest Decent Number having that number of digits.\n\nA Decent Number has the following properties:\n\nIts digits can only be 3's and/or 5's.\nThe number of 3's it contains is divisible by 5.\nThe number of 5's it contains is divisible by 3.\nIt is the largest such number for its length.\nMoriarty's virus shows a clock counting down to The Beast's destruction, and time is running out fast. Your task is to help Sherlock find the key before The Beast is destroyed!\n\nFor example, the numbers and are both decent numbers because there are 's and 's in the first, and 's in the second. They are the largest values for those length numbers that have proper divisibility of digit occurrences.\n\nFunction Description\n\nComplete the decentNumber function in the editor below.\n\ndecentNumber has the following parameter(s):\n\nint n: the length of the decent number to create\nPrints\n\nPrint the decent number for the given length, or if a decent number of that length cannot be formed. No return value is expected.\n\nInput Format\n\nThe first line is an integer, , the number of test cases.\n\nThe next lines each contain an integer , the number of digits in the number to create.\n\nConstraints\n\n\n\nSample Input\n\nSTDIN Function\n----- --------\n4 t = 4\n1 n = 1 (first test case)\n3 n = 3 (second test case)\n5\n11\nSample Output\n\n-1\n555\n33333\n55555533333\n\n'''\n\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the decentNumber function below.\ndef decentNumber(n):\n if n % 3 == 0:\n print('5' * n) \n elif n % 3 == 1 and n >= 10:\n print( '5'* (n - 10) + '3' * (10))\n elif n % 3 == 2 and n >= 5: \n print('5' *(n - 5) + '3' * (5))\n else:\n print(-1) \n return \nif __name__ == '__main__':\n t = int(input().strip())\n\n for t_itr in range(t):\n n = int(input().strip())\n\n decentNumber(n)\n","sub_path":"Day 96/SherlockAndTheBeast.py","file_name":"SherlockAndTheBeast.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"66739727","text":"# 11 Feb 2005\tFix update of summary table\n\nimport mx.DateTime\nimport iemdb\nIEM = iemdb.connect('iem')\nicursor = IEM.cursor()\n\ntoday = mx.DateTime.now()\nsql = \"\"\"update summary_%s s SET max_gust = 0 \n FROM stations t WHERE t.iemid = s.iemid and day = 'TODAY' and max_gust_ts < '%s 00:05' and\n t.network in ('KCCI','KIMT','KELO')\"\"\" % (\n today.year, today.strftime(\"%Y-%m-%d\"),)\nicursor.execute(sql)\nicursor.close()\nIEM.close()\n","sub_path":"scripts/qc/correctGusts.py","file_name":"correctGusts.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"34499069","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nimport uuid\n\nfrom unittest import TestCase\n\nfrom hestia.tz_utils import local_now\nfrom marshmallow import ValidationError\nfrom tests.utils import assert_equal_dict\n\nfrom polyaxon_schemas.api.experiment import ExperimentConfig\nfrom polyaxon_schemas.api.group import GroupConfig\nfrom polyaxon_schemas.api.project import ProjectConfig\n\n\nclass TestProjectConfigs(TestCase):\n def test_validate_project_name_config(self):\n config_dict = {'name': 'test sdf', 'description': '', 'is_public': True}\n with self.assertRaises(ValidationError):\n ProjectConfig.from_dict(config_dict)\n\n def test_project_config(self):\n config_dict = {\n 'name': 'test',\n 'description': '',\n 'is_public': True,\n 'has_code': True,\n 'has_tensorboard': True,\n 'tags': ['foo'],\n 'num_experiments': 0,\n 'num_independent_experiments': 0,\n 'num_experiment_groups': 0,\n 'num_jobs': 0,\n 'num_builds': 0,\n 'created_at': local_now().isoformat(),\n 'updated_at': local_now().isoformat()\n }\n config = ProjectConfig.from_dict(config_dict)\n config_to_dict = config.to_dict()\n config_to_dict.pop('id', None)\n config_to_dict.pop('experiment_groups', None)\n config_to_dict.pop('experiments', None)\n config_to_dict.pop('has_notebook', None)\n config_to_dict.pop('unique_name', None)\n config_to_dict.pop('user', None)\n config_to_dict.pop('owner', None)\n config_to_dict.pop('uuid', None)\n assert config_to_dict == config_dict\n config_dict.pop('description')\n config_dict.pop('updated_at')\n config_dict.pop('has_code')\n config_to_dict = config.to_light_dict()\n config_to_dict.pop('has_notebook', None)\n config_to_dict.pop('unique_name', None)\n assert config_to_dict == config_dict\n\n config_to_dict = config.to_dict(humanize_values=True)\n assert config_to_dict.pop('created_at') == 'a few seconds ago'\n assert config_to_dict.pop('updated_at') == 'a few seconds ago'\n\n config_to_dict = config.to_light_dict(humanize_values=True)\n assert config_to_dict.pop('created_at') == 'a few seconds ago'\n\n def test_project_experiments_and_groups_config(self):\n uuid_value = uuid.uuid4().hex\n config_dict = {'name': 'test',\n 'description': '',\n 'is_public': True,\n 'experiment_groups': [\n GroupConfig(content='content',\n uuid=uuid_value,\n project=uuid_value).to_dict()],\n 'experiments': [\n ExperimentConfig(uuid=uuid_value,\n project=uuid_value).to_dict()]}\n config = ProjectConfig.from_dict(config_dict)\n assert_equal_dict(config_dict, config.to_dict())\n\n config_dict.pop('description')\n config_dict.pop('experiment_groups')\n config_dict.pop('experiments')\n assert_equal_dict(config_dict, config.to_light_dict())\n","sub_path":"tests/test_api/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87866020","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\nfrom setuptools.command.install import install as _install\n\nclass install(_install):\n def pre_install_script(self):\n pass\n\n def post_install_script(self):\n pass\n\n def run(self):\n self.pre_install_script()\n\n _install.run(self)\n\n self.post_install_script()\n\nif __name__ == '__main__':\n setup(\n name = 'aws-monocyte',\n version = '0.3.509-312',\n description = '''Monocyte - Search and Destroy unwanted AWS Resources relentlessly.''',\n long_description = '''\n Monocyte is a bot for destroying AWS resources in non-EU regions written in Python using Boto.\n It is especially useful for companies that are bound to European privacy laws\n and for that reason don't want to process user data in non-EU regions.\n ''',\n author = \"Jan Brennenstuhl, Arne Hilmann\",\n author_email = \"jan@brennenstuhl.me, arne.hilmann@gmail.com\",\n license = 'Apache License 2.0',\n url = 'https://github.com/ImmobilienScout24/aws-monocyte',\n scripts = ['scripts/monocyte'],\n packages = [\n 'monocyte',\n 'monocyte.plugins',\n 'monocyte.handler'\n ],\n py_modules = [],\n classifiers = [\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Programming Language :: Python',\n 'Topic :: System :: Networking',\n 'Topic :: System :: Software Distribution',\n 'Topic :: System :: Systems Administration'\n ],\n entry_points = {},\n data_files = [],\n package_data = {},\n install_requires = [\n 'boto',\n 'boto3',\n 'docopt',\n 'mock',\n 'pils',\n 'python-cloudwatchlogs-logging',\n 'yamlreader'\n ],\n dependency_links = [],\n zip_safe=True,\n cmdclass={'install': install},\n )\n","sub_path":"pypi_install_script/aws-monocyte-0.3.509.post312.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"302648572","text":"import paho.mqtt.client as mqtt\nimport json\n\nimport sys\n\ndef on_connect(client, userdata, flags, rc):\n # 연결이 성공적으로 된다면 완료 메세지 출력\n if rc == 0:\n print(\"completely connected\")\n else:\n print(\"Bad connection Returned code=\", rc)\n\n# 연결이 끊기면 출력\ndef on_disconnect(client, userdata, flags, rc=0):\n print(str(rc))\n\n\ndef on_publish(client, userdata, mid):\n print(\"In on_pub callback mid= \", mid)\n\n# 새로운 클라이언트 생성\nclient = mqtt.Client()\n\n# 콜백 함수 설정 on_connect(브로커에 접속), on_disconnect(브로커에 접속중료), on_publish(메세지 발행)\nclient.on_connect = on_connect\nclient.on_disconnect = on_disconnect\nclient.on_publish = on_publish\n\n# address : localhost\n# port: 1883 에 연결\nclient.connect('localhost', 1883)\nclient.loop_start()\n\n# topic 으로 메세지 발행\nprint(str(sys.argv))\ncommand = sys.argv[1]\nclient.publish('test', command, 1)\nclient.loop_stop()\n\n# 연결 종료\nclient.disconnect()","sub_path":"face_recog_mqtt_pub.py","file_name":"face_recog_mqtt_pub.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"239910867","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n My third task for Assignment 11 where a user inputs a text file from which words representing each letter of the alphabet are compiled into their own dictionary. Each dictionary output is printed into a new, tab-delineated text file...giving a total of 26 files (one per letter in alphabet).\n\n Created by A.J. Turner on March 1, 2016. Helpful instructions/hints provided by S. Shakya.\n Copyright 2016 A.J. Turner. All rights reserved.\n\n\"\"\"\n\nimport argparse\nimport re\nimport os.path\nimport string\n\n\ndef user_files():\n\t\"\"\" adding user input that includes the name of the file to read and the name of the output file they write\"\"\"\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--file_in\", help=\"Type into command line: --file_in \", type=str)\n\targs = parser.parse_args()\n\treturn args\n\n\ndef all_letters(file,letter):\n\t\"\"\" separating words in input file by alphabetic letter and keeping associated counts\"\"\"\n\t#alphabetically grouped word\\tcount lists\n\tget_letter = re.findall(r'\\b['+letter+']\\w+\\t\\d+', file)\n\tlets = {} #dictionary placeholder for below\n\tfor word_num in get_letter: #iterate over each word in alphabetic list grouping\n\t\tsplit_word = word_num.split('\\t')\n\t\tlets[split_word[0]] = split_word[1]#creating dictionary with word/count\\\n\t\t#for each alphabetic group\n\treturn lets\n\n\ndef main():\n\targs = user_files()\n\twith open(args.file_in, 'r') as file_in:\n\t\tf = file_in.read()\n\t\tfile_in.close()\n\t\talphabet = list(string.ascii_lowercase) #getting all letts of alphabet as list\n\t\tfor letter in alphabet: #iterating over the alphabet, one letter at a time\n\t\t\tlets = all_letters(f, letter) #calling dictionaries from function two\n\t\t\tout_file = os.path.join(os.getcwd(), letter.upper()+'-words-'+args.file_in)\n\t\t\twith open(out_file, 'w') as out_file:\n\t\t\t#putting dictionary for each word grouping into a file\n\t\t\t\tfor key,value in lets.items():\n\t\t\t\t\tout_file.write(\"{}\\t{}\\n\".format(key, value))\n\t\t\t\tout_file.close()\t\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"answers/turneraj/a11task3.py","file_name":"a11task3.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"90051584","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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.win-amd64\\egg\\UnityPy\\classes\\MonoBehaviour.py\n# Compiled at: 2020-03-30 16:40:06\n# Size of source mod 2**32: 288 bytes\nfrom .Behaviour import Behaviour\nfrom .PPtr import PPtr\n\nclass MonoBehaviour(Behaviour):\n\n def __init__(self, reader):\n super().__init__(reader=reader)\n self.script = PPtr(reader)\n self.name = reader.read_aligned_string()\n self.read_type_tree()","sub_path":"pycfiles/UnityPy-1.3.0-py3.6/MonoBehaviour.cpython-36.py","file_name":"MonoBehaviour.cpython-36.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"408378322","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\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.linux-x86_64/egg/lazy_slides/download.py\n# Compiled at: 2012-03-17 18:14:01\nimport contextlib, logging, os, urllib2, urlparse, uuid\nlog = logging.getLogger(__name__)\n\ndef download(url, directory):\n \"\"\"Download a file specified by a URL to a local file.\n\n This generates a unique name for the downloaded file and saves\n into that.\n\n :param url: The URL to download.\n :param directory: The directory into which to save the file.\n \"\"\"\n parsed = urlparse.urlparse(url)\n filename = os.path.split(parsed.path)[1]\n filename_comps = os.path.splitext(filename)\n filename = ('{}_{}{}').format(filename_comps[0], uuid.uuid4(), filename_comps[1])\n filename = os.path.join(directory, filename)\n log.info(('Downloading {} to {}').format(url, filename))\n with contextlib.closing(urllib2.urlopen(url)) as (infile):\n with open(filename, 'wb') as (outfile):\n outfile.write(infile.read())\n return filename","sub_path":"pycfiles/lazy_slides-0.3-py2.7/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"471871105","text":"import serial\nimport cv2\nimport math\nimport wiringpi\nimport RPi.GPIO as GPIO\nimport socket\nimport time\nimport pdb\n\nGPIO.setwarnings(False)\n\n# referring to the pins by GPIO numbers\nGPIO.setmode(GPIO.BCM)\n\n# define pi GPIO\nGPIO_TRIGGER = 23\nGPIO_ECHO = 24\n\n# output pin: Trigger\nGPIO.setup(GPIO_TRIGGER,GPIO.OUT)\n# input pin: Echo\nGPIO.setup(GPIO_ECHO,GPIO.IN)\n# initialize trigger pin to low\nGPIO.output(GPIO_TRIGGER, False)\n\ntime.sleep(2)\n\nclass RCControl(object):\n\n\tdef __init__(self):\n\n\t\tself.server_socket = socket.socket()\n\t\tself.server_socket.bind(('192.168.0.114', 1234)) #pi\n\t\tself.server_socket.listen(0)\n\t\tself.connection= self.server_socket.accept()[0]\n\n\t\twiringpi.wiringPiSetup()\n\t\twiringpi.pinMode(21, 1) \n\t\twiringpi.pinMode(22, 1)\n\t\twiringpi.pinMode(23, 1)\n\t\twiringpi.pinMode(24, 1)\n\t\t\n\t\tGPIO.setwarnings(False)\n\t\tGPIO.setmode(GPIO.BCM)\n\t\tGPIO.setup(8, GPIO.OUT, initial= GPIO.LOW) #left\n\t\tGPIO.setup(4, GPIO.OUT, initial= GPIO.LOW) #red\n\t\tGPIO.setup(7, GPIO.OUT, initial= GPIO.LOW) #right\n\n\tdef steer(self):\n\t\ttry:\n\t\t\twhile(True):\n\t\t\t\tsep = ' '\n\t\t\t\tbuf = b''\n\t\t\t\twhile sep not in buf:\n\t\t\t\t\tbuf+=self.connection.recv(1024)\n\t\t\t\t\n\t\t\t\tprediction = str(buf)\n\t\t\t\tdistance = self.measure()\n\t\t\t\tprint(distance)\n\t\t\t\t\n\t\t\t\tif distance > 30.0 :\n\t\t\t\t\tif prediction == \"2 \":\n\t\t\t\t\t\tprint(\"Forward\")\n\t\t\t\t\t\twiringpi.digitalWrite(21, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(22, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(23, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(24, 1)\n\t\t\t\t\t\t\n\t\t\t\t\t\tGPIO.output(8, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(7, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(4, GPIO.LOW)\n\n\t\t\t\t\telif prediction == \"0 \":\n\t\t\t\t\t\tprint(\"Left\")\n\t\t\t\t\t\twiringpi.digitalWrite(21, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(22, 1)\n\t\t\t\t\t\twiringpi.digitalWrite(23, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(24, 0)\n\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\tGPIO.output(8, GPIO.HIGH) # Turn on\n\t\t\t\t\t\tGPIO.output(7, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(4, GPIO.LOW)\n\n\t\t\t\t\telif prediction == \"1 \":\n\t\t\t\t\t\tprint(\"Right\")\n\t\t\t\t\t\twiringpi.digitalWrite(21, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(22, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(23, 1)\n\t\t\t\t\t\twiringpi.digitalWrite(24, 1)\n\t\t\t\t\t\t\n\t\t\t\t\t\tGPIO.output(8, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(7, GPIO.HIGH) # Turn on\n\t\t\t\t\t\tGPIO.output(4, GPIO.LOW)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.stop()\n\t\t\t\t\t\tprint(\"Stop\")\n\t\t\t\t\t\twiringpi.digitalWrite(21, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(22, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(23, 0)\n\t\t\t\t\t\twiringpi.digitalWrite(24, 0)\n\n\t\t\t\t\t\tGPIO.output(8, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(7, GPIO.LOW) # Turn on\n\t\t\t\t\t\tGPIO.output(4, GPIO.HIGH)\n\n\t\t\t\telse:\n\t\t\t\t\tself.stop()\n\t\t\t\t\tprint(\"Obstacle ahead!\")\n\t\t\t\t\t\n\t\tfinally:\n\t\t\t#self.connection.close()\n\t\t\tself.server_socket.close()\n\t\t\tGPIO.cleanup()\n\n\tdef stop(self):\n\t\twiringpi.digitalWrite(21, 0)\n\t\twiringpi.digitalWrite(22, 0)\n\t\twiringpi.digitalWrite(23, 0)\n\t\twiringpi.digitalWrite(24, 0)\n\n\t\tGPIO.output(8, GPIO.LOW) # Turn on\n\t\tGPIO.output(7, GPIO.LOW) # Turn on\n\t\tGPIO.output(4, GPIO.HIGH)\n\n\tdef measure(self):\n\t\t\"\"\"\n\t\tmeasure distance\n\t\t\"\"\"\n\t\tGPIO.output(GPIO_TRIGGER, True)\n\t\ttime.sleep(0.00001)\n\t\tGPIO.output(GPIO_TRIGGER, False)\n\t\tstart = time.time()\n\n\t\twhile GPIO.input(GPIO_ECHO)==0:\n\t\t\tstart = time.time()\n\n\t\twhile GPIO.input(GPIO_ECHO)==1:\n\t\t\tstop = time.time()\n\n\t\telapsed = stop-start\n\t\tdistance = (elapsed * 34300)/2\n\t\tdistance = round(distance, 1)\n\t\treturn distance\n\n\nif __name__ == '__main__':\n\trc=RCControl()\n\trc.steer()\n","sub_path":"neural networks/test/pitest.py","file_name":"pitest.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"350869527","text":"import math\n\nn = int(input().strip())\n\ndef isPalindromic(num):\n num_str = str(num)\n if num_str == num_str[::-1]:\n return True\n return False\n\ndef doesFactorize(num):\n start_factor = math.floor(math.sqrt(num))\n for i in range(start_factor,99,-1):\n if num % i == 0:\n other_factor = num // i\n if 100 < i < 1000 and 100 < other_factor < 1000:\n return True\n return False\n\nfor i in range(n):\n N = int(input().strip())\n for num in range(N,101100,-1):\n if isPalindromic(num) and doesFactorize(num):\n print(num)\n break\n\n\n\n\n\n\n\n\n","sub_path":"Project Euler/ProjectEuler_4.py","file_name":"ProjectEuler_4.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"19120960","text":"from src.data_struc.deque.deque import Deque\n\n\n# Example realization palindrome checker\ndef palindrome(a_string):\n\n d = Deque() # Create deque\n\n for char in a_string:\n d.add_rear(char) # Add string char by char to deque\n\n equal = True\n\n while equal and d.size() > 1:\n first = d.remove_front() # Pop element from front\n last = d.remove_rear() # Pop element from rear\n if first != last: # Compare elements\n equal = False\n\n return equal\n\n\nprint(palindrome('madam'))","sub_path":"src/data_struc/deque/palindrome_checker.py","file_name":"palindrome_checker.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"255826060","text":"from django.urls import path\nfrom bowling.views import (\n RowListView,\n RowDetailView,\n RowSessionDetailView,\n RowSessionCreateView,\n RowSessionUpdateView,\n PlayerCreateView,\n PlayerUpdateView,\n make_throws\n)\nurlpatterns = [\n path(\"row/\", RowListView.as_view(), name=\"row-list\" ),\n path(\n \"row/\",\n RowDetailView.as_view(),\n name=\"row-detail\"\n ),\n path(\n \"row_session/create\",\n RowSessionCreateView.as_view(),\n name=\"row_session-create\"\n ),\n path(\n \"row_session//update\",\n RowSessionUpdateView.as_view(),\n name=\"row_session-update\"\n ),\n path(\"row_session/\",\n RowSessionDetailView.as_view(),\n name=\"row_session-detail\"\n ),\n path(\"row_session//throws\",\n make_throws,\n name=\"row_session-throws\"\n ),\n path(\"player/create\",\n PlayerCreateView.as_view(),\n name=\"player-create\"\n ),\n path(\"player//update\",\n PlayerUpdateView.as_view(),\n name=\"player-update\"\n ),\n # path(\"car/\", CarDetailView.as_view(), name=\"car-detail\" ),\n]\n","sub_path":"bowling/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"606663242","text":"#assignment 3: STOPWATCH\n\n#http://www.codeskulptor.org/#user40_pzrY0uGl4PsTfgp_24.py\n\n# template for \"Stopwatch: The Game\"\nimport simplegui\n# define global variables\ntime = 0\nclick_counter = 0\npoint_counter = 0\n\n# define helper function format that converts time\n# in tenths of seconds into formatted string A:BC.D\ndef format(t):\n A = t / 600\n B = ((t / 10) % 60) // 10\n C = ((t / 10) % 60) % 10\n D = (t % 60) % 10\n \n return str(A) + \":\" + str(B) + str(C) + \".\" + str(D)\n \n \n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\ndef start():\n timer.start()\ndef stop():\n global click_counter\n global point_counter\n if timer.is_running() == True:\n timer.stop()\n click_counter += 1\n if time % 10 == 0:\n point_counter += 1\n else:\n timer.stop()\n \ndef play():\n global click_counter\n global point_counter\n if timer.is_running() == True:\n timer.stop()\n click_counter += 1\n if time % 10 == 0:\n point_counter += 1\n elif timer.is_running() == False:\n timer.start()\n \n \n \n \n \ndef reset(): \n global time\n global click_counter\n global point_counter\n timer.stop()\n time = 0\n click_counter = 0\n point_counter = 0\n \n\n \n# define event handler for timer with 0.1 sec interval\ndef timer_handler():\n global time\n time += 1 \n \n \n \n \n# define draw handler\ndef draw(canvas):\n global time\n canvas.draw_text(str(format(time)), [100, 200], 80, \"White\")\n canvas.draw_text(str(point_counter) + \"/\" + str(click_counter),\\\n [300, 50], 25, \"White\") \n \n# create frame\nframe = simplegui.create_frame(\"Stopwatch_the_Game\", 400, 400)\ntimer = simplegui.create_timer(100, timer_handler)\n\n\n# register event handlers\nframe.add_button('Play', play, 200)\n\nframe.add_button('Start', start, 200)\nframe.add_button('Stop', stop, 200)\nframe.add_button('Reset', reset, 200)\nframe.set_draw_handler(draw)\nframe.set_canvas_background('Black')\n\n# start frame\nframe.start()\n\n\n\n\n\n\n","sub_path":"Stopwatch.py","file_name":"Stopwatch.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"605609618","text":"'''\nDocker host and client utilities\n'''\nfrom datetime import datetime\n\nfrom fabric.api import *\nfrom fabric.contrib import *\n\n# needed for adding users\n# from confighelper import ConfigHelper\n\n@task\ndef create_and_install_certs(do_client_certs=False, do_server_certs=False, hostname=''):\n '''\n This create and install client and server (host) keys for TLS auth and crypto for docker client.\n\n Default for the two install operations is false, add :true,true to do it for real.\n\n Example:\n fab docker.create_and_install_certs --hosts=atomic-v1-aws.tinisi.local -u centos\n '''\n if ( not hostname ):\n hostname = env.host_string\n\n working_dir = _create_working_dir()\n\n # always create these, should be safe\n create_host_certs(working_dir=working_dir, hostname=hostname)\n create_client_certs(working_dir=working_dir, hostname=hostname)\n\n if do_client_certs:\n install_client_certs(working_dir=working_dir, hostname=hostname)\n\n if do_server_certs:\n install_server_certs(working_dir=working_dir, hostname=hostname)\n\n@task\ndef create_host_certs(working_dir='', hostname=''):\n '''\n This will set up a CA and server (docker host) keys.\n '''\n\n if ( not hostname ):\n hostname = env.host_string\n\n # this is from:\n # https://docs.docker.com/engine/security/https/\n\n if ( not working_dir ):\n working_dir = _create_working_dir()\n\n with cd(working_dir):\n # this creates the private key for our CA\n run('openssl genrsa -aes256 -out ca-key.pem 4096')\n # Enter pass phrase for ca-key.pem:\n # Verifying - Enter pass phrase for ca-key.pem:\n\n # this creates the public key for our CA\n # TODO: deal with prompt\n run('openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem')\n\n # this creates a server key and CSR\n # TODO: deal with prompt\n run('openssl genrsa -out server-key.pem 4096')\n\n # this makes a CSR\n run('openssl req -subj \"/CN={hostname}\" -sha256 -new -key server-key.pem -out server.csr'.format(hostname=hostname))\n\n # create a conf file with allowed IP's\n # add a second such as IP:10.10.10.20,IP:127.0.0.1 to specify more than one IP\n # not actually sure this is needed\n run('echo subjectAltName = IP:10.10.10.20,IP:127.0.0.1 > extfile.cnf')\n\n # it signs the key\n run('openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \\\n-CAcreateserial -out server-cert.pem -extfile extfile.cnf')\n\n # this is the config to make the demon use tlsverify\n # docker daemon --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem -H=0.0.0.0:2376\n\n@task\ndef create_client_certs(working_dir='', hostname=''):\n '''\n This creates certs to be used for a client.\n '''\n\n if ( not hostname ):\n hostname = env.host_string\n\n if ( not working_dir ):\n working_dir = _create_working_dir()\n\n with cd(working_dir):\n\n run('openssl genrsa -out key.pem 4096')\n\n run('openssl req -subj \\'/CN=client\\' -new -key key.pem -out client.csr')\n\n run('echo extendedKeyUsage = clientAuth > client_extfile.cnf')\n\n run('openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile client_extfile.cnf')\n\n run('rm -v client.csr server.csr')\n\n run('chmod -v 0400 ca-key.pem key.pem server-key.pem')\n\n run('chmod -v 0444 ca.pem server-cert.pem cert.pem')\n\n@task\ndef install_server_certs(working_dir='', hostname=''):\n\n if ( not hostname ):\n hostname = env.host_string\n\n install_dir = '/etc/docker/certs.d'\n host_cert_dir = '{install_dir}/{hostname}'.format(install_dir=install_dir,hostname=hostname)\n \n with settings(warn_only=True):\n sudo('mkdir {install_dir}'.format(install_dir=install_dir))\n\n sudo('mkdir %(host_cert_dir)s' % {\"host_cert_dir\": host_cert_dir})\n\n with cd(working_dir):\n sudo('cp ca-key.pem server-key.pem server-cert.pem %(host_cert_dir)s' % {\"host_cert_dir\": host_cert_dir})\n\n with settings(warn_only=True):\n sudo('sudo service docker stop')\n sudo('sudo service docker start')\n\n@task\ndef install_client_certs(working_dir, hostname=''):\n\n if ( not hostname ):\n hostname = env.host_string\n\n install_dir = '~/.docker'\n\n with settings(warn_only=True):\n _create_client_hostname_dir(install_dir, hostname)\n\n tmp_dir = './tmp'\n\n with cd(working_dir):\n get('ca.pem', tmp_dir)\n get('cert.pem', tmp_dir)\n get('key.pem', tmp_dir)\n\n with lcd(tmp_dir):\n local('cp ca.pem {install_dir}/{hostname}/'.format(install_dir=install_dir, hostname=hostname))\n local('cp cert.pem {install_dir}/{hostname}/'.format(install_dir=install_dir, hostname=hostname))\n local('cp key.pem {install_dir}/{hostname}/'.format(install_dir=install_dir, hostname=hostname))\n\n@task\ndef pre_install_docker(os='ubuntu', hostname=''):\n\n if ( not hostname ):\n hostname = env.host_string\n\n if ( os == 'ubuntu' ):\n _pre_install_docker_ubuntu(hostname=hostname)\n\n@task\ndef install_docker(os='ubuntu', hostname=''):\n\n if ( not hostname ):\n hostname = env.host_string\n\n if ( os == 'ubuntu' ):\n _install_docker_ubuntu(hostname=hostname)\n\n# private helpers\n\ndef _pre_install_docker_ubuntu(hostname=''):\n docker_source_list_path = '/etc/apt/sources.list.d/docker.list'\n\n sudo('apt-get update')\n sudo('apt-get --assume-yes install apt-transport-https ca-certificates')\n sudo('apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D')\n with settings(warn_only=True):\n sudo('rm {docker_source_list_path}'.format(docker_source_list_path=docker_source_list_path))\n sudo(\"echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' > {docker_source_list_path}\".format(docker_source_list_path=docker_source_list_path))\n sudo('apt-get update')\n sudo('sudo apt-get purge lxc-docker')\n sudo('apt-cache policy docker-engine')\n sudo('apt-get --assume-yes install linux-image-extra-$(uname -r)')\n sudo('apt-get --assume-yes install apparmor')\n # turn off firewall\n # TODO: replace this with commands to open fw ports\n sudo('ufw disable')\n sudo('sudo reboot')\n\ndef _install_docker_ubuntu(hostname=''):\n # the initial install\n sudo('sudo apt-get --assume-yes install docker-engine')\n with settings(warn_only=True):\n sudo('sudo service docker stop')\n\n # and configure the service for TLS\n docker_service_config_file = '/etc/default/docker'\n docker_opts = 'DOCKER_OPTS=~--dns 8.8.8.8 --dns 8.8.4.4 --tls=true --tlscacert=/etc/docker/certs.d/{hostname}/ca.pem --tlscert=/etc/docker/certs.d/{hostname}/server-cert.pem --tlskey=/etc/docker/certs.d/{hostname}/server-key.pem -H=0.0.0.0:2376~'.format(hostname=hostname)\n with settings(warn_only=True):\n sudo('echo \"{docker_opts}\" > {docker_service_config_file}'.format(\n docker_service_config_file=docker_service_config_file,\n docker_opts=docker_opts))\n # the positional arguments for this are file, search, replace\n files.sed(docker_service_config_file, '~', '\"', use_sudo=True, backup='.grosgrain_bak')\n\ndef _create_time_stamp():\n now = datetime.now()\n return now.strftime(\"%Y_%m_%d_%H_%M_%S\")\n\ndef _create_working_dir(time_stamp=_create_time_stamp()):\n\n working_dir = 'docker_certs_working_%(time_stamp)s' % { \"time_stamp\": time_stamp }\n\n run('mkdir %(working_dir)s' % { \"working_dir\": working_dir })\n\n return working_dir\n\ndef _create_client_hostname_dir(install_dir, hostname):\n\n local('mkdir {install_dir}/{hostname}'.format(install_dir=install_dir, hostname=hostname))\n","sub_path":"grosgrain/fabfile/docker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"390807907","text":"'''\nThis file is the gevent launcher for local / development use.\n\nSimply run it on the command line:\npython ycdl_flask_dev.py [port]\n'''\nimport gevent.monkey; gevent.monkey.patch_all()\n\nimport logging\nhandler = logging.StreamHandler()\nlog_format = '{levelname}:ycdl.{module}.{funcName}: {message}'\nhandler.setFormatter(logging.Formatter(log_format, style='{'))\nlogging.getLogger().addHandler(handler)\n\nimport argparse\nimport gevent.pywsgi\nimport sys\n\nfrom voussoirkit import pathclass\nfrom voussoirkit import vlogging\n\nimport bot\nimport ycdl\n\nimport backend\n\n####################################################################################################\n\nsite = backend.site\n\nHTTPS_DIR = pathclass.Path(__file__).parent.with_child('https')\nLOG_LEVEL = vlogging.NOTSET\n\ndef ycdl_flask_launch(\n *,\n create,\n localhost_only,\n port,\n refresh_rate,\n use_https,\n ):\n if use_https is None:\n use_https = port == 443\n\n if use_https:\n http = gevent.pywsgi.WSGIServer(\n listener=('0.0.0.0', port),\n application=site,\n keyfile=HTTPS_DIR.with_child('ycdl.key').absolute_path,\n certfile=HTTPS_DIR.with_child('ycdl.crt').absolute_path,\n )\n else:\n http = gevent.pywsgi.WSGIServer(\n listener=('0.0.0.0', port),\n application=site,\n )\n\n if localhost_only:\n site.localhost_only = True\n\n youtube_core = ycdl.ytapi.Youtube(bot.get_youtube_key())\n backend.common.init_ycdldb(youtube_core, create=create, log_level=LOG_LEVEL)\n ycdl.ytrss.log.setLevel(LOG_LEVEL)\n\n if refresh_rate is not None:\n backend.common.start_refresher_thread(refresh_rate)\n\n message = f'Starting server on port {port}'\n if use_https:\n message += ' (https)'\n print(message)\n\n try:\n http.serve_forever()\n except KeyboardInterrupt:\n pass\n\ndef ycdl_flask_launch_argparse(args):\n return ycdl_flask_launch(\n create=args.create,\n localhost_only=args.localhost_only,\n port=args.port,\n refresh_rate=args.refresh_rate,\n use_https=args.use_https,\n )\n\ndef main(argv):\n global LOG_LEVEL\n (LOG_LEVEL, argv) = vlogging.get_level_by_argv(argv)\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n parser.add_argument('port', nargs='?', type=int, default=5000)\n parser.add_argument('--dont_create', '--dont-create', '--no-create', dest='create', action='store_false', default=True)\n parser.add_argument('--https', dest='use_https', action='store_true', default=None)\n parser.add_argument('--localhost_only', '--localhost-only', dest='localhost_only', action='store_true')\n parser.add_argument('--refresh_rate', '--refresh-rate', dest='refresh_rate', type=int, default=None)\n parser.set_defaults(func=ycdl_flask_launch_argparse)\n\n args = parser.parse_args(argv)\n return args.func(args)\n\nif __name__ == '__main__':\n raise SystemExit(main(sys.argv[1:]))\n","sub_path":"frontends/ycdl_flask/ycdl_flask_dev.py","file_name":"ycdl_flask_dev.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"274051853","text":"#!/usr/bin/env python2.7\n\nfrom one import *\n\n# Ex 3.1\n\ndef compute_qda(trainingy, trainingx):\n def estimate_normal(features):\n mean = np.mean(features, axis=0)\n cov = np.cov(features, rowvar=0)\n return (mean, cov)\n \n x0 = trainingx[trainingy == 0]\n x1 = trainingx[trainingy == 1]\n\n assert trainingx.size == x0.size + x1.size\n\n (mu0, covmat0) = estimate_normal(x0)\n (mu1, covmat1) = estimate_normal(x1)\n\n p0 = x0.size / float(trainingx.size)\n p1 = x1.size / float(trainingx.size)\n\n return (mu0, mu1, covmat0, covmat1, p0, p1)\n\n\n# Ex 3.2\n\nfrom scipy.stats import multivariate_normal\n\ndef perform_qda(mu0, mu1, covmat0, covmat1, p0, p1, testx):\n dist0 = multivariate_normal(mean=mu0, cov=covmat0)\n dist1 = multivariate_normal(mean=mu1, cov=covmat1)\n\n result = np.zeros(testx.shape[0], dtype=np.int)\n\n for i in xrange(0, len(result)):\n x = testx[i]\n x0_prob = p0 * dist0.pdf(x)\n x1_prob = p1 * dist1.pdf(x)\n if x0_prob > x1_prob:\n result[i] = 0\n else:\n result[i] = 1\n\n return result\n\n# bind the first six parameters in perform_qda\ndef qda_classifier(m0, m1, covmat0, covmat1, p0, p1):\n return lambda testx: perform_qda(m0, m1, covmat0, covmat1, p0, p1, testx)\n\n# Ex 3.3 + 3.4\n\n# Misclassifications on training data using QDA stems from modelling error and inherent randomness:\n# QDA assumes normally distributed data.\n# As is the case when using linear regression on a nonlinear sequence of observations, QDA may yield bad results because the modelled phenomenon may be a different kind of random variable, e.g. one with an exponential distribution.\n# In contrast to NN, QDA accounts for some randomness in the approximated function, i.e. X \\mapsto Y may be not deterministic.\n# Whereas NN overfits in these cases, the QDA model assumes that some very unlikely observations are in the training data.\n# For example, consider a training instance (X_i, Y_i) whose feature X_i is very close to the features of training instances with a common different label Z.\n# In that case, the observation (X_i, Y_i) may be extremely unlikely, because the (X_i, Z) may be much more common.\n# NN fails in these cases, whereas QDA correctly (in most cases) assigns the label Z to observation X_i.\n# This also means that when QDA is used on the training data, it will sometimes yield wrong results if the observation is sufficiently 'unlikely'.\n\n\n# apply classifier on testx and show results in figure\n# the classifiers results are compared to testy in the figure\ndef visualizeClassification(classifier, testy, testx, show_correctness=True):\n plt.gca().set_position((.1, .3, .8, .6)) # to make a bit of room for extra text\n\n plt.xlabel('absolute value norm')\n plt.ylabel('euclidean norm')\n\n estimatedy = classifier(testx)\n\n correct_classification_rate = float(len(estimatedy[estimatedy == testy])) / len(testy) \n\n colors = np.where(testy == estimatedy, \"b\", \"r\")\n\n x0 = testx[estimatedy == 0][ : , 0]\n y0 = testx[estimatedy == 0][ : , 1]\n c0 = colors[estimatedy == 0]\n\n x1 = testx[estimatedy == 1][ : , 0]\n y1 = testx[estimatedy == 1][ : , 1]\n c1 = colors[estimatedy == 1]\n\n size = 20\n\n plt.scatter(x0, y0, marker=\"o\", c=c0, s=size)\n plt.scatter(x1, y1, marker=\"x\", c=c1, s=size)\n\n plt.figtext(0.02, 0.02, \n '''\n o: Classified as 1\n x: Classified as 7\n ''')\n\n if show_correctness:\n plt.figtext(0.7, 0.02, \n '''\n Correct Classification Rate: %.2f\n Blue: Correct Classification\n Red: Wrong Classification\n ''' % correct_classification_rate)\n\n plt.show()\n\ndef makeGridValues(absmax, euclidmax):\n absvals = (absmax / 100) * np.array(xrange(0, 100))\n euclidvals = (euclidmax / 100) * np.array(xrange(0, 100))\n\n return np.array([[absval, euclidval] for euclidval in euclidvals for absval in absvals])\n\nif __name__ == \"__main__\":\n mu0, mu1, covmat0, covmat1, p0, p1 = compute_qda(Y_train, X_train)\n\n classifier = qda_classifier(mu0, mu1, covmat0, covmat1, p0, p1)\n plt.title('Classification Results on Training Data')\n visualizeClassification(classifier, Y_train, X_train)\n plt.clf()\n\n absmax = np.max(X_train[ : , 0])\n euclidmax = np.max(X_train[ : , 1])\n\n grid_values = makeGridValues(absmax, euclidmax)\n\n plt.title('Decision Regions')\n # choose classifier(grid_values) as 'correct' Y so every classification is painted blue\n visualizeClassification(classifier, classifier(grid_values), grid_values, show_correctness=False)\n plt.clf()\n\n # Ex 3.5\n plt.title('Classification Results on Test Data')\n visualizeClassification(classifier, Y_test, X_test)\n plt.clf()\n","sub_path":"blatt03/corrected-lda/three.py","file_name":"three.py","file_ext":"py","file_size_in_byte":4795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"365693513","text":"import datetime\n\nimport trainer.corpora as crp\nimport trainer.features as ftr\nimport trainer.classifier_test as cls\nimport os\n\n# vars\ntype = \"inf-20k\"\nnltk_run = True\nsklearn_run = False\nCOUNT = 20000\ncut = int((COUNT / 2) * 3 / 4)\narray = [5000, 10000, 15000, 20000, 25000, 30000, 150000]\n\ndef run(dataset):\n\n nlt = dict()\n skl = dict()\n\n dir = \"output/\" + dataset + \"/\" + type + \"/\"\n os.makedirs(dir, exist_ok=True)\n\n # file\n for variable in array:\n var_name = str(variable)\n\n if nltk_run:\n nlt_file = dir + dataset + \"-\" + type + \"-\" + var_name + \"-nlt.csv\"\n nlt[var_name] = open(nlt_file, 'a')\n nlt[var_name].write(str(datetime.datetime.today()) + \"\\n\")\n\n if sklearn_run:\n skl_file = dir + dataset + \"-\" + type + \"-\" + var_name + \"-skl.csv\"\n skl[var_name] = open(skl_file, 'a')\n skl[var_name].write(str(datetime.datetime.today()) + \"\\n\")\n\n # cycle\n for x in range(0, 10):\n print(x)\n corpora = crp.Corpora(dataset, count=COUNT, shuffle=True)\n\n for variable in array:\n print(str(variable))\n var_name = str(variable)\n features = ftr.Features(corpora, total=COUNT, bigram=True, stop=False, stem=\"porter\", lower=True, inf_count=variable)\n\n posfeats = features.get_features_pos()\n negfeats = features.get_fearures_neg()\n\n trainfeats = negfeats[:cut] + posfeats[:cut]\n testfeats = negfeats[cut:] + posfeats[cut:]\n\n nlt_output, skl_output = cls.train(trainfeats, testfeats, nlt=nltk_run, skl=sklearn_run)\n\n if nltk_run:\n print(str(nlt_output))\n nlt[var_name].write(nlt_output)\n nlt[var_name].flush()\n if sklearn_run:\n print(str(skl_output))\n skl[var_name].write(skl_output)\n skl[var_name].flush()\n\n\n\ndataset_array = [\"stanford\"]\n\nfor dataset in dataset_array:\n run(dataset)","sub_path":"trainer/tests/inf.py","file_name":"inf.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"620295435","text":"import time\nimport torch\nimport numpy as np\nfrom Losses import *\nfrom ObjectModel import ObjectModel\nfrom CodeUtil import *\n\ncode, idx = get_obj_code_random(1)\nobj_model = ObjectModel()\nfc_loss = FCLoss(obj_model)\n\nn_cps = [3,5,10,20,100,1000]\ntimes = []\n\nfor n_cp in n_cps:\n pts = torch.rand([10000, 1, n_cp, 3], device='cuda', requires_grad=True)\n t = []\n p = pts[0]\n dist = obj_model.distance(code, p)\n grad = obj_model.gradient(p, dist, retain_graph=True, allow_unused=True)\n loss = fc_loss.fc_loss(pts[0], grad, code)\n for i in range(len(pts)):\n p = pts[i]\n t0 = time.time()\n dist = obj_model.distance(code, p)\n grad = obj_model.gradient(p, dist, retain_graph=True, allow_unused=True)\n loss = fc_loss.fc_loss(pts[i], grad, code)\n t.append(time.time() - t0)\n times.append(np.mean(t))\n print(n_cp, np.mean(t))\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.rc('xtick', labelsize=15) \nmatplotlib.rc('ytick', labelsize=15) \n\n_ = plt.plot(n_cps,times,linewidth=3, markersize=10)\n_ = plt.xlabel('# Contact Points', fontsize=20)\n_ = plt.ylabel('Time per 1000 FC Calls (s)', fontsize=20)\n_ = plt.xscale('log')\n_ = plt.show()\n","sub_path":"ForceClosure/fig_force_closure_time.py","file_name":"fig_force_closure_time.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"43923455","text":"# least unique -> most unique\n\nimport numpy as np\n\nlambda_lya_min = 1045\nlambda_lya_max = 1185\nlambda_lya = 1215.67\nc_kms = 2.99792458e5\n\nlambda_lyb_min = 978\nlambda_lyb_max = 1014\nlambda_lyb = 1025.7\n\nzmin = 3.0\nzmax = 4.4\ndz = 0.2\nzbinlen = int((zmax-zmin)/dz+0.5) #reduced_zbinlen = int(((zmax-zmin)/dz+1)-1)\nzmin_bin = 0.0\nzmax_bin = 5.0\n\nkmin = 0 #3e-3 #0.0\nkmax = 0.06 #- 3e-3#0.06 #0.06\ndlogk = 3e-3\nkbinlen = int((kmax - kmin)/dlogk + 0.5) #reduced_kbinlen = int(((kmax-kmin)/dlogk+1)-1)\nlog_binning = 0\n\ndloglambda = 3e-5\ndv = c_kms * dloglambda * np.log(10)\n\nDLAcat_file = \"../Data/XQ-100_DLA_catalogue.txt\"\ncatalog = \"../Data/XQ-100_catalogue.txt\"\nnqso = 100\nmin_pix = 100\nmin_flux = -1e-15\nmin_trans = -100","sub_path":"demonstration/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49829135","text":"import os.path as osp\n\nimport argparse\nimport numpy as np\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\nfrom torch_sparse import SparseTensor\nfrom torch_geometric.datasets import Reddit\nfrom torch_geometric.nn.inits import glorot, zeros\n\nfrom utils import Logger\n\nclass SAGEConv(nn.Module):\n def __init__(self,\n in_feats,\n out_feats,\n aggr,\n feat_drop=0.,\n activation=None):\n super(SAGEConv, self).__init__()\n\n self._in_feats = in_feats\n self._out_feats = out_feats\n self._aggr = aggr\n self.feat_drop = nn.Dropout(feat_drop)\n self.activation = activation\n\n self.weight = Parameter(torch.Tensor(in_feats, out_feats))\n self.root_weight = Parameter(torch.Tensor(in_feats, out_feats))\n self.bias = Parameter(torch.Tensor(out_feats))\n\n self.reset_parameters()\n\n def reset_parameters(self):\n glorot(self.weight)\n glorot(self.root_weight)\n zeros(self.bias)\n\n def forward(self, x, adj):\n x = self.feat_drop(x)\n if self._aggr == 'sum':\n out = adj.matmul(x) @ self.weight\n elif self._aggr == 'mean':\n out = adj.matmul(x, reduce=\"mean\") @ self.weight\n else:\n return ValueError(\"Expect aggregation to be 'sum' or 'mean', got {}\".format(self._aggr))\n out = out + x @ self.root_weight + self.bias\n if self.activation is not None:\n out = self.activation(out)\n return out\n\nclass GraphSAGE(nn.Module):\n def __init__(self,\n in_feats,\n n_hidden,\n n_classes,\n aggr,\n activation=F.relu,\n dropout=0.):\n super(GraphSAGE, self).__init__()\n self.layers = nn.ModuleList()\n self.layers.append(SAGEConv(in_feats, n_hidden, aggr, activation=activation))\n self.layers.append(SAGEConv(n_hidden, n_classes, aggr, feat_drop=dropout, activation=None))\n\n def reset_parameters(self):\n for layer in self.layers:\n layer.reset_parameters()\n\n def forward(self, x, edge_index):\n h = x\n for layer in self.layers:\n h = layer(h, edge_index)\n return h\n\ndef calc_acc(logits, labels, mask):\n logits = logits[mask]\n labels = labels[mask]\n _, indices = torch.max(logits, dim=1)\n correct = torch.sum(indices == labels)\n return correct.item() * 1.0 / len(labels)\n\ndef evaluate(model, features, adj, labels, train_mask, val_mask, test_mask):\n model.eval()\n with torch.no_grad():\n logits = model(features, adj)\n train_acc = calc_acc(logits, labels, train_mask)\n val_acc = calc_acc(logits, labels, val_mask)\n test_acc = calc_acc(logits, labels, test_mask)\n return train_acc, val_acc, test_acc\n\ndef main(args):\n device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu'\n device = torch.device(device)\n\n path = osp.join('dataset', 'Reddit')\n dataset = Reddit(path)\n data = dataset[0]\n\n features = data.x.to(device)\n labels = data.y.to(device)\n edge_index = data.edge_index.to(device)\n adj = SparseTensor(row=edge_index[0], col=edge_index[1])\n train_mask = torch.BoolTensor(data.train_mask).to(device)\n val_mask = torch.BoolTensor(data.val_mask).to(device)\n test_mask = torch.BoolTensor(data.test_mask).to(device)\n\n model = GraphSAGE(dataset.num_features,\n args.n_hidden,\n dataset.num_classes,\n args.aggr,\n F.relu,\n args.dropout).to(device)\n\n loss_fcn = nn.CrossEntropyLoss()\n\n logger = Logger(args.runs, args)\n dur = []\n for run in range(args.runs):\n model.reset_parameters()\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n for epoch in range(1, args.epochs + 1):\n model.train()\n if epoch >= 3:\n t0 = time.time()\n # forward\n logits = model(features, adj)\n loss = loss_fcn(logits[train_mask], labels[train_mask])\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if epoch >= 3:\n dur.append(time.time() - t0)\n print('Training time/epoch {}'.format(np.mean(dur)))\n\n if not args.eval:\n continue\n\n train_acc, val_acc, test_acc = evaluate(model, features, adj, labels, train_mask, val_mask, test_mask)\n logger.add_result(run, (train_acc, val_acc, test_acc))\n\n print(\"Run {:02d} | Epoch {:05d} | Loss {:.4f} | Train {:.4f} | Val {:.4f} | Test {:.4f}\".format(run, epoch, loss.item(), train_acc, val_acc, test_acc))\n\n if args.eval:\n logger.print_statistics(run)\n\n if args.eval:\n logger.print_statistics()\n\n\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='GraphSAGE')\n parser.add_argument(\"--device\", type=int, default=0)\n parser.add_argument(\"--dropout\", type=float, default=0.5,\n help=\"dropout probability\")\n parser.add_argument(\"--lr\", type=float, default=1e-2,\n help=\"learning rate\")\n parser.add_argument(\"--epochs\", type=int, default=200,\n help=\"number of training epochs\")\n parser.add_argument(\"--n-hidden\", type=int, default=16,\n help=\"number of hidden gcn units\")\n parser.add_argument(\"--aggr\", type=str, choices=['sum', 'mean'], default='mean',\n help='Aggregation for messages')\n parser.add_argument(\"--weight-decay\", type=float, default=5e-4,\n help=\"Weight for L2 loss\")\n parser.add_argument(\"--eval\", action='store_true',\n help='If not set, we will only do the training part.')\n parser.add_argument(\"--runs\", type=int, default=10)\n args = parser.parse_args()\n print(args)\n\n main(args)\n","sub_path":"end_to_end/full_graph/node_classification/main_pyg_reddit_sage.py","file_name":"main_pyg_reddit_sage.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"573821394","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 25 21:27:41 2020\n\n@author: loris\n\nDesenvolva um programa que faça a tabuada de um número qualquer inteiro que será digitado pelo \nusuário, mas a tabuada não deve necessariamente iniciar em 1 e terminar em 10, o valor inicial e \nfinal devem ser informados também pelo usuário, conforme exemplo abaixo:\n \n \nMontar a tabuada de: 5\nComeçar por: 4\nTerminar em: 7\n\nVou montar a tabuada de 5 começando em 4 e terminando em 7:\n5 X 4 = 20\n5 X 5 = 25\n5 X 6 = 30\n5 X 7 = 35\n\n\nObs: Você deve verificar se o usuário não digitou o final menor que o inicial.\n\n\"\"\"\n\n\nprint(\"Tabuada do seu jeito!\")\n\nvalidado = False\n\nwhile validado == False: \n tabuada = int(input(\"Mostrar tabuada de: \"))\n comeco = int(input(\"Começar de: \"))\n fim = int(input(\"Terminar em: \"))\n if comeco < fim and comeco != fim:\n validado = True\n\nfor n in range(comeco, fim+1):\n print(str(tabuada)+\" x \"+str(n)+\" = \"+str(tabuada*n))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"3 - Estrutura de Repetição/36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"497279417","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='Message',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')),\n ('title', models.CharField(max_length=100)),\n ('date', models.DateField(null=True, blank=True)),\n ('text', models.TextField(max_length=3000)),\n ],\n ),\n ]\n","sub_path":"blogblog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"583885657","text":"from urllib.parse import quote\r\nfrom requests import Session\r\nfrom uuid import uuid4\r\nimport sys\r\n\r\n# Modify\r\n\r\nIDENTIFIER = 'bot_id'\r\nAUTHORIZATION = 'bot_key'\r\n\r\n# Do not modify\r\n\r\nCOMMANDS_URL = 'https://http.msging.net/commands'\r\nSET_METHOD = 'set'\r\n\r\nERROR_ATTENDANTS = []\r\n\r\nif len(sys.argv) < 2:\r\n print('uso: python add_attendants.py ')\r\n exit(-1)\r\n\r\nattendants_csv = open(sys.argv[1], 'r', encoding='utf8')\r\n\r\ncsv_data = None\r\n\r\ntry:\r\n csv_data = attendants_csv.read().split('\\n')[1:]\r\n attendants_csv.close()\r\nexcept Exception as ex:\r\n print('Error while parsing csv')\r\n attendants_csv.close()\r\n exit(-1)\r\n\r\n\r\ndef create_set_attendant_command(email, teams):\r\n return {\r\n 'id': str(uuid4()),\r\n 'to': 'postmaster@desk.msging.net',\r\n 'method': SET_METHOD,\r\n 'uri': '/attendants',\r\n 'type': 'application/vnd.iris.desk.attendant+json',\r\n 'resource': {\r\n 'identity': f'{quote(email)}@blip.ai',\r\n 'teams': teams\r\n }\r\n }\r\n\r\n\r\ndef get_email_teams_from_line(line):\r\n splited_line = line.split(',')\r\n email = splited_line[0]\r\n teams = splited_line[1:]\r\n return email, teams\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(f'Starting session for {IDENTIFIER}')\r\n session = Session()\r\n session.headers = {\r\n 'Authorization': AUTHORIZATION\r\n }\r\n print(f'Found {len(csv_data)} attendants')\r\n for attendant in csv_data:\r\n email, teams = get_email_teams_from_line(attendant)\r\n command_body = create_set_attendant_command(email, teams)\r\n\r\n command_res = session.post(COMMANDS_URL, json=command_body)\r\n command_res = command_res.json()\r\n\r\n if command_res['status'] != 'success':\r\n print(f'Error adding {email}')\r\n ERROR_ATTENDANTS.append(attendant)\r\n else:\r\n print(f'Added {email}')\r\n if len(ERROR_ATTENDANTS) > 0:\r\n print(\r\n f'Saving {len(ERROR_ATTENDANTS)} not added attendants to error_{IDENTIFIER}.csv'\r\n )\r\n with open(f'error_{IDENTIFIER}.csv', 'w', encoding='utf8') as error_file:\r\n error_file.write('\\n'.join(ERROR_ATTENDANTS))\r\n error_file.close()\r\n print('Done')\r\n","sub_path":"add_attendants.py","file_name":"add_attendants.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"344484198","text":" ## - *** GAME *** -\n ##Rock | Paper | Scissors\n\nimport random\nfrom time import sleep\nimport time\n\n# Defined the countdown module:\ndef countdown(n) :\n while n > 0:\n print (n)\n sleep(1)\n n = n - 1\n if n ==0:\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>START<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\")\n\n# Assigned 0 as the starting point for the score:\nscore_Player = 0\nscore_Computer = 0\n\n# Introduce the game and ask for the gamer's name as an 'input':\nprint(str(input(\"Hello player :) Welcole to the Rock | Paper | Scissors GAME!!!\\n\\n\\t\\tPress >ENTER< to continue.\")))\nsleep(0.5)\nPlayer_One = str(input(\"Before we start; what shoul I be calling you?\\nEnter the name here: \"))\nsleep(0.4)\nprint(\"Good luck %s. Computer is known to be very lucky at this game!!!\"%(Player_One))\nsleep(1.3)\ncountdown(3)\n\n#Started the game in a while loop:\nwhile True:\n Player_Choice = str(input(\"Choose one: [Rock / Paper / Scissors]\\n(R) for Rock\\t (P) for Paper\\t (S) for Scissors: \"))\n Choice = [\"Rock\", \"Paper\", \"Scissors\"]\n Computer = (random.choice(Choice))\n \n if ((Player_Choice == \"R\" and Computer == \"Rock\") or (Player_Choice == \"P\" and Computer == \"Paper\") or (Player_Choice == \"S\" and Computer == \"Scissors\")):\n print(\"\\nComputer's Cohice: %s\\n\"%(Computer))\n print(\"It's a tie!\")\n sleep(1.6)\n score_Player = score_Player + 1\n score_Computer = score_Computer + 1\n print(\"%s: %d | Computer: %d\"%(Player_One,score_Player,score_Computer))\n \n elif((Player_Choice == \"R\" and Computer == \"Scissors\") or (Player_Choice == \"P\" and Computer == \"Rock\") or (Player_Choice == \"S\" and Computer == \"Paper\")):\n print(\"\\nComputer's Cohice: %s\\n\"%(Computer))\n print(\"%s WINS!!!\"%(Player_One))\n sleep(1.6)\n score_Player = score_Player+ 1\n print(\"%s: %d | Computer: %d\"%(Player_One,score_Player,score_Computer))\n \n else:\n print(\"\\nComputer's Cohice: %s\"%(Computer))\n print(\"Computer WINS!!!\\n\")\n sleep(1.6)\n score_Computer = score_Computer + 1\n print(\"%s: %d | Computer: %d\"%(Player_One,score_Player,score_Computer))\n# When the total score reaches to '5', it ends the game; announces the winner; and asks whether you want to try again:\n total_score = score_Computer + score_Player\n if total_score >= 5:\n sleep(0.5)\n if score_Computer > score_Player:\n print(\"\\nComputer WINS the Round!!!\")\n elif score_Computer == score_Player:\n print(\"\\nIT IS A TIE!!!\")\n else:\n print(\"\\n%s WINS the Round!!!\"%(Player_One))\n willRepeat = str(input(\"Do you want to try again? [Y / N] : \"))\n if willRepeat == \"Y\":\n score_Player = 0\n score_Computer = 0\n sleep(0.4)\n continue\n elif willRepeat == \"N\":\n sleep(0.3)\n break \n \n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"71848217","text":"\"\"\"\nRun Tests on the Categories Endpoint\n\"\"\"\n\nimport logging\n\nfrom lunchable import LunchMoney\nfrom lunchable.models.categories import CategoriesObject\nfrom tests.conftest import lunchable_cassette\n\nlogger = logging.getLogger(__name__)\n\n\n@lunchable_cassette\ndef test_get_categories(lunch_money_obj: LunchMoney):\n \"\"\"\n Get Categories and Assert that they're categories\n \"\"\"\n categories = lunch_money_obj.get_categories()\n assert len(categories) >= 1\n for category in categories:\n assert isinstance(category, CategoriesObject)\n logger.info(\"%s Categories returned\", len(categories))\n\n\n@lunchable_cassette\ndef test_create_category(lunch_money_obj: LunchMoney):\n \"\"\"\n Get Categories and Assert that they're categories\n \"\"\"\n name = \"Test Category\"\n category = lunch_money_obj.insert_category(name=name,\n description=\"Test Category Description\",\n exclude_from_budget=True)\n logger.info(\"Category ID # %s was just created: %s\", category, name)\n assert isinstance(category, int)\n","sub_path":"tests/models/test_categories.py","file_name":"test_categories.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225670132","text":"import time\nfrom mrq.job import Job\nimport pytest\n\n\n@pytest.mark.parametrize([\"p_service\"], [[\"mongodb\"], [\"redis\"]])\ndef test_disconnects_service_during_task(worker, p_service):\n \"\"\" Test what happens when mongodb disconnects during a job\n \"\"\"\n\n worker.start()\n\n if p_service == \"mongodb\":\n service = worker.fixture_mongodb\n elif p_service == \"redis\":\n service = worker.fixture_redis\n\n service_pid = service.process.pid\n\n job_id1 = worker.send_task(\"tests.tasks.general.Add\", {\n \"a\": 41, \"b\": 1, \"sleep\": 5}, block=False, queue=\"default\")\n\n time.sleep(2)\n\n service.stop()\n service.start()\n\n service_pid2 = service.process.pid\n\n # Make sure we did restart\n assert service_pid != service_pid2\n\n time.sleep(5)\n\n # Result should be there without issues\n assert Job(job_id1).fetch().data[\"result\"] == 42\n","sub_path":"tests/test_disconnects.py","file_name":"test_disconnects.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"59355599","text":"from random import randint\n\ndef main () :\n path = run ()\n\n print (\"The sortest path is : \" , end = '') ;\n\n for city in range (len (path)) :\n if city == (len (path) - 1) :\n print (path [city])\n\n else :\n print (path [city] , \"---> \" , end = '')\n\ndef run () :\n cities = ['A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G']\n map = createMap ()\n population = startingPopulation (map , cities)\n\n previous = list ()\n condition = True\n\n # The argument of range function is the number of evolution\n # you may change the number of evolution. It's up to you.\n\n for i in range (1000) :\n best_chromosome = findPurposeValue (map , population)\n\n # This \"if\" statement for comparing previous with best chromosome\n # and just execute once.\n\n if condition :\n previous = [i for i in best_chromosome]\n condition = False\n\n else :\n if calculateDistance (map , best_chromosome) < calculateDistance (map , previous) :\n previous = [i for i in best_chromosome]\n\n # At this point the best chromosome has to remove from population.\n # Otherwise it will do crossing over with itself.\n\n population.remove (best_chromosome)\n population = crossingOver (population , best_chromosome , cities)\n\n # Finally the best chromosome has to append to the population.\n # Otherwise the population will evanesce approximately at 6 generation.\n # (The iteration of evanesce is changeable according as your number of city)\n\n population.append (best_chromosome)\n\n # The previous variable is contain the shortest path (in other words the best chromosome).\n\n return previous\n\ndef createMap () :\n map = dict ()\n\n # At this point we have to create a map to apply our genetic algorithm.\n # There is 7 city and their ways from each one to other one.\n # You may set up distance according to your problem.\n\n map ['A'] = {'B' : 3 , 'C' : 7 , 'D' : 12 , 'E' : 9 , 'F' : 4 , 'G' : 15}\n map ['B'] = {'A' : 3 , 'C' : 2 , 'D' : 6 , 'E' : 5 , 'F' : 8 , 'G' : 13}\n map ['C'] = {'A' : 7 , 'B' : 2 , 'D' : 4 , 'E' : 3 , 'F' : 1 , 'G' : 5}\n map ['D'] = {'A' : 12 , 'B' : 6 , 'C' : 4 , 'E' : 11 , 'F' : 9 , 'G' : 5}\n map ['E'] = {'A' : 9 , 'B' : 5 , 'C' : 3 , 'D' : 11 , 'F' : 4 , 'G' : 1}\n map ['F'] = {'A' : 4 , 'B' : 8 , 'C' : 1 , 'D' : 9 , 'E' : 4 , 'G' : 7}\n map ['G'] = {'A' : 15 , 'B' : 13 , 'C' : 5 , 'D' : 5 , 'E' : 1 , 'F' : 7}\n\n return map\n\ndef startingPopulation (map , list_of_cities) :\n population = list ()\n\n # For 7 cities there is 7! possible population at the beginning.\n # This means you can select your number of population between 1 and 5,040.\n\n number_of_population = randint (5 , 10)\n\n for count in range (number_of_population) :\n chromosome = list ()\n\n while len (chromosome) < 7 :\n\n # \"randint\" method generate a random number\n # between starting parameter (inclusive) and ending parameter (inclusive).\n # So the range has to decrease once.\n\n random_index = randint (0 , (len (list_of_cities) - 1))\n\n if list_of_cities [random_index] not in chromosome :\n chromosome.append (list_of_cities [random_index])\n\n population.append (chromosome)\n\n return population\n\ndef findPurposeValue (map , population) :\n results = dict ()\n\n for chromosome in population :\n results [calculateDistance (map , chromosome)] = chromosome\n\n value = min (results)\n\n return results [value]\n\ndef calculateDistance (map , chromosome) :\n distance = 0\n\n for city in range (len (chromosome) - 1) :\n neighbors = map [chromosome [city]]\n distance += neighbors [chromosome [city + 1]]\n\n return distance\n\ndef crossingOver (population , best_chromosome , cities) :\n\n # \"split pieces\" variable is determine the number of gene swap for crossing over\n\n split_pieces = randint (1 , (len (population [0]) // 2))\n\n i = 0\n\n while i < len (population) :\n j = -1\n\n while j >= (-1 * split_pieces) :\n population [i][j] = best_chromosome [j]\n j -= 1\n\n population [i] = checkDuplicates (population [i] , cities)\n\n # After the crossing over, there may be a mutation.\n # This means the realize condition have to be randomly to mutation.\n # And the solution is the \"randint\" method again.\n\n if randint (1 , 15) % 3 == 0 :\n population [i] = mutation (population [i])\n\n i += 1\n\n return population\n\ndef checkDuplicates (chromosome , cities) :\n for city in cities :\n if city not in chromosome :\n i = 0\n while i < len (chromosome) :\n j = i + 1\n while j < len (chromosome) :\n if chromosome [i] == chromosome [j] :\n chromosome [i] = city\n\n j += 1\n i += 1\n\n return chromosome\n\ndef mutation (chromosome) :\n\n # The mutation operation needs to two genes for swapping genes with each other.\n\n first = 0 # first gene index\n second = 0 # second gene index\n\n while first == second :\n\n # These genes are chosen randomly\n\n first = randint (1 , len (chromosome) - 1)\n second = randint (1 , len (chromosome) - 1)\n\n # Genes are moved simultaneously,\n\n chromosome [first] , chromosome [second] = chromosome [second] , chromosome [first]\n\n # and returned where called function is.\n\n return chromosome\n\nif __name__ == \"__main__\" :\n main ()","sub_path":"Source.py","file_name":"Source.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"589269071","text":"# Copyright 2018 Onestein ()\n# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).\n\nfrom odoo import api, fields, models\n\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n\n transus_gln = fields.Char(string='GLN')\n\n _sql_constraints = [\n ('name_uniq', 'unique(transus_gln, company_id)', 'Partner GLN must be unique per company!'),\n ]\n\n @api.multi\n def check_gln(self):\n is_correct = True\n for partner in self:\n if partner.transus_gln and len(partner.transus_gln) != 13:\n is_correct = False\n return is_correct\n\n _constraints = [\n (check_gln, \"The entered GLN is not correct.\", [\"transus_gln\"])\n ]\n","sub_path":"transus/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"121842872","text":"import datetime\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils import timezone\nfrom django.db.models import Sum\nfrom .models import ReadCounter, VisitorCounter\n\n\ndef add_read_cnt_once(request, model_obj):\n ct = ContentType.objects.get_for_model(model_obj)\n key = \"{}_pk_{}\".format(str(ct.model), str(model_obj.pk))\n\n if not request.COOKIES.get(key):\n # if ReadCounter.objects.filter(content_type=ct, object_id=model_obj.pk).count():\n # readcounter = ReadCounter.objects.get(content_type=ct, object_id=model_obj.pk)\n # else:\n # # 不存在记录\n # readcounter = ReadCounter(content_type=ct, object_id=model_obj.pk)\n # # 阅读计数器加1\n # readcounter.read_cnt += 1\n readcounter, created = ReadCounter.objects.get_or_create(content_type=ct, object_id=model_obj.pk)\n readcounter.read_cnt += 1\n readcounter.save()\n\n # 访客数加1\n date = timezone.now().date()\n visitorcounter, created = VisitorCounter.objects.get_or_create(content_type=ct, object_id=model_obj.pk, date=date)\n visitorcounter.visitor_cnt += 1\n visitorcounter.save()\n\n return key\n\ndef get_latest_week_visit(content_type):\n today = timezone.now().date()\n visitor_cnt_list = []\n dates_list = []\n\n for i in range(7, 0, -1):\n date = today - datetime.timedelta(days=i)\n dates_list.append(date.strftime('%m-%d'))\n visitorcounter = VisitorCounter.objects.filter(content_type=content_type, date=date)\n result = visitorcounter.aggregate(visitor_sum=Sum('visitor_cnt'))\n visitor_cnt_list.append(result['visitor_sum'] or 0)\n return dates_list, visitor_cnt_list\n\ndef get_today_hot_blogs(content_type):\n today = timezone.now().date()\n visitor_cnt = VisitorCounter.objects.filter(content_type=content_type,\\\n date=today).order_by('-visitor_cnt')\n return visitor_cnt[:7]\n\ndef get_yesterday_hot_blogs(content_type):\n today = timezone.now().date()\n yesterday = today - datetime.timedelta(days=1)\n visitor_cnt = VisitorCounter.objects.filter(content_type=content_type,\\\n date=today).order_by('-visitor_cnt')\n return visitor_cnt[:7]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"reader/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"122845835","text":"#!/usr/bin/env python3\r\n\"\"\"\r\nThis is the server for the server-client-update-application.\r\nIf a client connects to this server, it checks for an update of the required software and if found, streams it to the client.\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\nfrom flask import Flask, request, session\r\nfrom datetime import datetime\r\nimport platform\r\nimport json\r\n\r\n\r\napp = Flask(__name__)\r\n# set the secret key. keep this really secret:\r\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\r\n\r\n\r\n@app.route('/start_connection', methods = ['POST'])\r\ndef start_connection():\r\n\t\"\"\"\r\n\tStarts the connection of server and client.\r\n\tIn order to do so, stores everything in the session object. Starts the checking for update afterwards.\r\n\t\"\"\"\r\n\t# setup data\r\n\tsession['name'] = request.form['name']\r\n\tsession['date'] = request.form['date']\r\n\tsession['ip'] = request.remote_addr\r\n\tsession['processor'] = request.form['processor']\r\n\tsession['ram'] = request.form['ram']\r\n\tsession['platform'] = request.form['platform']\r\n\tsession['program'] = request.form['program']\r\n\tsession['version'] = request.form['version']\r\n\treturn (check_for_update())\r\n\r\n\r\ndef check_for_update():\r\n\t\"\"\"\r\n\tCompares the current version of the program with the one stored on the server.\r\n\tLoads the data of the updates stored on the server as json string and compares it. If update is available, starts downloading it.\r\n\t\"\"\"\r\n\twith open('packages.json') as json_string:\r\n\t\tjson_obj = json.load(json_string);\r\n\r\n\tif session['program'] not in json_obj:\r\n\t\treturn 'no update available for this software.'\r\n\r\n\tif session['version'] == json_obj[session['program']]['version']:\r\n\t\treturn 'software is up to date.'\r\n\telse :\r\n\t\treturn (get_update())\r\n\r\n# searches for the update package\r\ndef get_update():\r\n\t\"\"\"\r\n\tSearches for update package.\r\n\tIf found, stream it as binary to the client.\r\n\t\"\"\"\r\n\twith open('packages/' + session['program'] + '/' + session['program'] + '.zip', 'rb') as f:\r\n\t\tmy_file = f.read()\r\n\treturn my_file","sub_path":"py/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"5289534","text":"from bs4 import BeautifulSoup as bs\nimport requests\nimport re\nimport pandas as pd\nimport numpy as np\n\nr = requests.get(\"https://kuckjwi0928.github.io/pythoncodingprogram/\").text\nsoup = bs(r, 'html.parser')\ntexts = soup.find_all('td')\n\nDF = pd.DataFrame(columns=['Name', 'Phone', 'Value'])\nfor P in range(0, 4):\n if (P % 2 == 0):\n DF.loc[(P//2), ['Name']] = re.split('/', texts[P].text)[0]\n DF.loc[(P//2), ['Phone']] = re.split('/', texts[P].text)[1]\n else:\n pattern = re.compile('[A-Z가-힣]')\n DF.loc[(P//2), ['Value']] = ', '.join(pattern.findall(texts[P].text))\n\nprint(DF)\n","sub_path":"Group members/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"255480498","text":"#import boto3\nimport random\nimport multiprocessing\nimport time\n\n\n\n\ndef sleeper (n, name):\n print('Hi, I am Process {}. Sleeping for 3 seconds.'.format(name))\n time.sleep(3)\n print('{} is now awake'.format(name))\n\n\ndef inserter(name):\n sqs = boto3.client('sqs')\n #response = sqs.list_queues()\n #print(response['QueueUrls'])\n\n # Fifo queues have different requirements for keys inside sqs.send_message than Standard Q's.\n queue_url = 'https://queue.amazonaws.com/308303745136/SL-test-FQ.fifo'\n\n # Send message to SQS queue\n count = 0\n while count < 3:\n count_str = str(count)\n response = sqs.send_message(\n MessageGroupId=count_str,\n MessageDeduplicationId='{0}{1}{2}'.format(name, count, random.randint(1,1000000)),\n QueueUrl=queue_url,\n MessageBody=(\n 'Information'\n )\n )\n\n count += 1\n #if response['ResponseMetadata']['HTTPStatusCode'] != 200:\n print(name, response)\n\n\nif __name__ == '__main__':\n jobs = []\n for i in range(5):\n p = multiprocessing.Process(target=sleeper, args=(i, i))\n jobs.append(p)\n p.start()\n","sub_path":"Python/sqs.fifo.multiprocess.inserter.py","file_name":"sqs.fifo.multiprocess.inserter.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"17269226","text":"from grab import Grab\nfrom grab.spider import Spider, Task\nfrom urllib.parse import urljoin\nimport re\n\n\nclass OoqiaSpider(Spider):\n def prepare(self):\n self.initial_urls = ['https://attorneys.superlawyers.com/divorce/new-york-metro/new-york/']\n self.attorneys = []\n self.current_page = 1\n self.current_att = 1\n super(OoqiaSpider, self).prepare()\n\n def task_initial(self, grab, task):\n print('Current page: %s' % self.current_page)\n container = grab.doc.select('//*[@id=\"browse_view\"]')\n selector = './/*[contains(@class,\"search_result\")]'\n for attorney in container.select(selector):\n # att = dict()\n # img_tag = attorney.select('.//*[@class=\"image\"]//img')\n # if img_tag:\n # att['picture'] = img_tag.attr('src')\n card = attorney.select('.//*[@class=\"text_container\"]')\n # att['name'] = card.select('.//h2').text()\n url = card.select('.//*[@class=\"indigo_text\"]//a').attr('href') \n #import pdb; pdb.set_trace()\n yield Task('attorney_detail', self.get_attorney_url(url)) \n # self.attorneys.append(att)\n\n pagination = grab.doc.select('//*[@class=\"pagination\"]')\n next_page = pagination.select('.//a[@rel=\"next\"]')\n if next_page:\n url = next_page.attr('href')\n self.current_page += 1\n yield Task('initial', grab.make_url_absolute(url))\n\n def task_attorney_detail(self, grab, task): \n att = dict()\n name = grab.doc.select('//*[@id=\"lawyer_bio_block\"]//*[@id=\"lawyer_name\"]').text()\n practice_areas = grab.doc.select('//*[@id=\"lawyer_bio_block\"]//*[@id=\"practice_areas\"]').text()\n img_tag = attorney.select('.//*[@class=\"image\"]//img')\n if (name is not None and practice_areas is not None):\n self.current_att += 1\n print(' (%s) Current Attorney: %s' % (self.current_att, name))\n print(' (%s) Practice Areas: %s' % (self.current_att, practice_areas))\n\n def get_attorney_url(self, url):\n g = Grab()\n g.setup(follow_location=True, connect_timeout=10) \n g.go(url)\n if g.doc.code == 200: \n return g.doc.url\n\n def make_url_absolute(grab, href, force_https=False):\n if grab.config['url']:\n base_url = grab.doc.url\n url = urljoin(base_url, href)\n else:\n url = href\n if force_https and url.startswith('http://'):\n url = re.sub('^http:\\/\\/', 'https://', url)\n return url\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"565101342","text":"import os\nimport os.path\nimport numpy as np\nimport torch.utils.data as data\nfrom dataloaders.associate import read_file_list, associate\nfrom path import Path\nimport dataloaders.custom_transforms as custom_transforms\nimport cv2\n\n_EPS = np.finfo(float).eps * 4.0\n\n\ndef transform34(l):\n \"\"\"\n Generate a 3x4 homogeneous transformation matrix from a 3D point and unit quaternion.\n\n Input:\n l -- tuple consisting of (stamp,tx,ty,tz,qx,qy,qz,qw) where\n (tx,ty,tz) is the 3D position and (qx,qy,qz,qw) is the unit quaternion.\n\n Output:\n matrix -- 4x4 homogeneous transformation matrix\n \"\"\"\n t = l[:3]\n q = np.array(l[3:7], dtype=np.float64, copy=True)\n nq = np.dot(q, q)\n if nq < _EPS:\n return np.array((\n (1.0, 0.0, 0.0, t[0]),\n (0.0, 1.0, 0.0, t[1]),\n (0.0, 0.0, 1.0, t[2]),\n (0.0, 0.0, 0.0, 1.0)\n ), dtype=np.float64)\n q *= np.sqrt(2.0 / nq)\n q = np.outer(q, q)\n return np.array((\n (1.0 - q[1, 1] - q[2, 2], q[0, 1] - q[2, 3], q[0, 2] + q[1, 3], t[0]),\n (q[0, 1] + q[2, 3], 1.0 - q[0, 0] - q[2, 2], q[1, 2] - q[0, 3], t[1]),\n (q[0, 2] - q[1, 3], q[1, 2] + q[0, 3], 1.0 - q[0, 0] - q[1, 1], t[2])\n ), dtype=np.float64)\n\ndef read_calib_file(path):\n # taken from https://github.com/hunse/kitti\n float_chars = set(\"0123456789.e+- \")\n data = {}\n with open(path, 'r') as f:\n for line in f.readlines():\n key, value = line.split(':', 1)\n value = value.strip()\n data[key] = value\n if float_chars.issuperset(value):\n # try to cast to float array\n try:\n data[key] = np.array(list(map(float, value.split(' '))))\n except ValueError:\n # casting error: data[key] already eq. value, so pass\n pass\n\n return data\n\n\ndef make_dataset(dir, sequence_length=1, used_only_left_images=False, used_sequences=None):\n sequences = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n split = str(d).split('/')\n if not os.path.isdir(d) or (used_sequences is not None and not split[-1] in used_sequences):\n continue\n\n root = Path(d)\n\n rgb_list = read_file_list(root / \"rgb.txt\")\n depth_list = read_file_list(root / \"depth.txt\")\n pose_list = read_file_list(root / \"groundtruth.txt\")\n\n rgbd_matches = dict(associate(rgb_list, depth_list, offset=list(rgb_list)[0] - list(depth_list)[0]))\n rgbdt_matches = associate(rgbd_matches, pose_list, offset=list(rgb_list)[0] - list(pose_list)[0])\n\n rgb_files = [root / rgb_list[a][0] for a, b in rgbdt_matches]\n depth_files = [root / depth_list[rgbd_matches[a]][0] for a, b in rgbdt_matches]\n poses = [transform34(pose_list[b]) for a,b in rgbdt_matches]\n poses = np.array(poses)\n\n assert len(rgb_files) == len(depth_files) == len(poses)\n\n intrinsics = np.loadtxt(root / \"intrinsics.txt\").reshape(3, 3)\n\n for i in range(len(rgb_files) - sequence_length + 1):\n sequence = {'reset': i == 0, 'rgb_images': [], 'depth_images': [], 'intrinsics': intrinsics, 'poses': None}\n\n if sequence_length == 1:\n sequence['poses'] = poses[i].reshape(1, 3, 4)\n else:\n first_pose = poses[i]\n current_poses = np.copy(poses[i:i + sequence_length])\n current_poses[:, :, -1] -= first_pose[:, -1]\n current_poses = np.linalg.inv(first_pose[:, :3]) @ current_poses\n sequence['poses'] = current_poses\n\n for j in range(sequence_length):\n sequence['rgb_images'].append(rgb_files[i + j])\n sequence['depth_images'].append(depth_files[i + j])\n sequences.append(sequence)\n\n return sequences\n\n\nclass TUMLoader(data.Dataset):\n def __init__(self, root, type, sequence_length=1, output_size=(320, 384), use_only_left_images=False, sequences=None):\n self.samples = make_dataset(Path(root) / type, sequence_length, use_only_left_images, used_sequences=sequences)\n assert len(self.samples) > 0, \"Found 0 images in subfolders of: \" + root + \"\\n\"\n self.root = root\n self.type = type\n self.output_size = output_size\n self.sequence_length = sequence_length\n\n def train_transform(self, rgb_images, depth_images, intrinsics, poses):\n jitter = custom_transforms.ColorJitter.get_params(0.4, 0.4, 0.4, 0.0)\n train_transform = custom_transforms.Compose([\n custom_transforms.RandomRotate(5.0),\n custom_transforms.CenterCrop(self.output_size),\n custom_transforms.RandomHorizontalFlip(),\n custom_transforms.RandomReverseOrder(),\n jitter,\n custom_transforms.ArrayToTensor()\n ])\n\n return train_transform(rgb_images, depth_images, intrinsics, poses)\n\n\n def val_transform(self, rgb_images, depth_images, intrinsics, poses):\n valid_transform = custom_transforms.Compose([\n custom_transforms.CenterCrop(self.output_size),\n custom_transforms.ArrayToTensor()\n ])\n\n return valid_transform(rgb_images, depth_images, intrinsics, poses)\n\n def __getitem__(self, index):\n sample = self.samples[index]\n\n rgb_files = sample[\"rgb_images\"]\n depth_files = sample[\"depth_images\"]\n\n rgb_images = [cv2.imread(f) for f in rgb_files]\n depth_images = [cv2.imread(f, cv2.IMREAD_UNCHANGED).astype(np.float32) / 5000.0 for f in depth_files]\n intrinsics = np.copy(sample[\"intrinsics\"]).astype(np.float32)\n poses = np.copy(sample[\"poses\"]).astype(np.float32)\n\n if self.type == \"train\":\n image_tensors, depth_tensors, intrinsics, transformed_poses = self.train_transform(rgb_images, depth_images,\n intrinsics,\n poses)\n elif self.type == \"val\":\n image_tensors, depth_tensors, intrinsics, transformed_poses = self.val_transform(rgb_images, depth_images,\n intrinsics,\n poses)\n else:\n raise Exception(\"Invalid dataloader type! (Needs to be either 'train' or 'val'.\")\n\n if poses is None:\n poses = np.zeros((self.sequence_length, 3, 4), dtype=np.float32)\n if transformed_poses is None:\n transformed_poses = np.zeros((self.sequence_length, 3, 4), dtype=np.float32)\n\n return sample[\"reset\"], image_tensors, depth_tensors, intrinsics, np.linalg.inv(intrinsics), poses, transformed_poses\n\n def __len__(self):\n return len(self.samples)\n","sub_path":"dataloaders/tum_rgbd_loader.py","file_name":"tum_rgbd_loader.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"297547541","text":"from django.contrib import admin\nfrom django.urls import path\nfrom .views import *\n\nurlpatterns = [\n \n path('', home, name=\"home\"),\n path('honor/',honor, name=\"honor\"),\n path('honorRegister1/',honorRegister1, name=\"honorRegister1\"),\n path('honorRegister2/',honorRegister2, name=\"honorRegister2\"),\n path('honorRegistered//',honorRegistered, name=\"honorRegistered\"),\n path('free/', free, name=\"free\"),\n path('freeRegister1/',freeRegister1, name=\"freeRegister1\"),\n path('freeRegister2/',freeRegister2, name=\"freeRegister2\"),\n path('freeRegistered/',freeRegistered, name=\"freeRegistered\"),\n path('aboutUs/',aboutUs, name=\"aboutUs\"),\n path('searchMap/',searchMap,name=\"searchMap\"),\n path('searchResult/',searchResult, name='searchResult'),\n \n path('mypage/',mypage,name=\"mypage\"),\n \n path('mypageDiary/',mypageDiary,name=\"mypageDiary\"),\n path('mypageDiaryCreate/',mypageDiaryCreate,name=\"mypageDiaryCreate\"),\n \n path('mypagePhoto/',mypagePhoto,name=\"mypagePhoto\"),\n path('mypagePhotoCreate/',mypagePhotoCreate,name=\"mypagePhotoCreate\"),\n \n path('mypageVisitorBook/',mypageVisitorBook,name=\"mypageVisitorBook\"),\n path('mypageVisitorBookCreate/',mypageVisitorBookCreate,name=\"mypageVisitorBookCreate\"),\n \n \n path('mypageOption/',mypageOption,name=\"mypageOption\"),\n path('mypageUpdate/',mypageUpdate,name=\"mypageUpdate\"),\n \n \n path('enroll/',enroll, name=\"enroll\"),\n path('enroll2/',enroll2, name=\"enroll2\"),\n path('enrolled/',enrolled, name=\"enrolled\"),\n path('caaard/', caaard, name=\"caaard\"),\n path('csCenter/', csCenter, name=\"csCenter\"),\n path('q_and_a/', q_and_a, name=\"q_and_a\"),\n path('idFind/', idFind, name=\"idFind\"),\n path('pwFind/', pwFind, name=\"pwFind\"),\n path('normal/',normal, name=\"normal\"),\n path('animal_delete/',delete,name=\"delete\"),\n]","sub_path":"dbgproject/dbg/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"119055847","text":"from sys import stdin, setrecursionlimit\nfrom collections import defaultdict\nfrom heapq import heapify, heappush, heappushpop\n\n\ndef main():\n input = stdin.buffer.readline\n n, m = map(int, input().split())\n ab = [list(map(int, input().split())) for _ in range(n)]\n\n dic = defaultdict(list)\n for a, b in ab:\n dic[a].append(b)\n\n q = []\n heapify(q)\n\n for i in sorted(dic.keys(), reverse=True):\n for j in sorted(dic[i], reverse=True):\n if len(q) <= m - i:\n heappush(q, j)\n elif q and q[0] < j:\n heappushpop(q, j)\n\n print(sum(q))\n\n\nif __name__ == \"__main__\":\n setrecursionlimit(10000)\n main()\n","sub_path":"Python_codes/p02948/s990116518.py","file_name":"s990116518.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"544177016","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 13 21:54:55 2016\n\n@author: Kapythone\n\"\"\"\n\ndef wordBreak(s, wordDict):\n hashmap = {}\n for w in wordDict:\n hashmap[w] = 1\n \n return f(s, hashmap)\n \ndef f(s, hashmap):\n if s == '':\n return True\n\n pres = []\n for i in range(1, len(s) + 1):\n pres.append(s[:i])\n \n for p in pres:\n if p in hashmap:\n if f(s[len(p):], hashmap) == True:\n return True\n \n return False","sub_path":"Word Break.py","file_name":"Word Break.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"168161900","text":"from typing import Dict\n\nimport MySentrySettings\nimport requests\nimport traceback\n\n\nclass ErrorLogSender:\n\n def __init__(self, app_id: int, app_token: str):\n assert isinstance(app_id, int), f'id not int'\n assert isinstance(app_token, str) and len(app_token) != 0, f'token is empty or not string'\n self.id = app_id\n self.token = app_token\n\n def sender(self, error_log: Dict) -> None:\n assert len(error_log) == 3 and ['error_type', 'error_message', 'error_stack_trace'] == list(error_log.keys()), \\\n f'error_log is invalid'\n url = f'http://127.0.0.1:8000/apps/{self.id}/error_log/'\n requests.post(url, data=error_log, headers={'token': self.token})\n\n\ndef error_searcher(fun):\n def wrapper():\n app = ErrorLogSender(MySentrySettings.settings['id'], MySentrySettings.settings['token'])\n try:\n return fun()\n except Exception as error:\n error_dict_for_sender = {\n 'error_type': error.__class__.__name__,\n 'error_message': error.__str__(),\n 'error_stack_trace': ''.join(traceback.format_stack())\n }\n app.sender(error_dict_for_sender)\n\n return wrapper\n\n","sub_path":"sdk_for_MySentry/sdk_for_mysentry_pgk/sdk.py","file_name":"sdk.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"550264025","text":"# -*- coding: utf-8 -*-\nimport time\nfrom website.core import ObjectType\n\nclass Client(object):\n CLIENT_ANDROID = 1\n CLIENT_IOS = 2\n CLIENT_WX = 3\n\n @classmethod\n def gen_id(cls, db):\n obj_type = ObjectType.CLIENT\n result = db.execute(\"INSERT INTO _object (`type`) VALUES (%s)\", obj_type)\n return result.lastrowid\n\n\n @classmethod\n def create_client(cls, db, client_id, appid, developer_id, platform_type, platform_identity):\n now = int(time.time())\n sql = \"INSERT INTO client(id, app_id, developer_id, platform_type, platform_identity, ctime, utime) VALUES(%s, %s, %s, %s, %s, %s, %s)\"\n r = db.execute(sql, (client_id, appid, developer_id, platform_type, platform_identity, now, now))\n return r.lastrowid\n\n @classmethod\n def create_wx(cls, db, client_id, gh_id, wx_appid, refresh_token, store_id):\n sql = \"INSERT INTO client_wx(client_id, gh_id, wx_app_id, refresh_token, store_id, is_authorized) VALUES(%s, %s, %s, %s, %s, %s)\"\n r = db.execute(sql, (client_id, gh_id, wx_appid, refresh_token, store_id, 1))\n return r.lastrowid\n\n @classmethod\n def get_app(cls, db, gh_id):\n sql = \"SELECT app.id as id, app.name as name, app.developer_id as developer_id FROM client_wx, client, app WHERE gh_id=%s and client_wx.client_id=client.id and client.app_id=app.id\"\n r = db.execute(sql, gh_id)\n obj = r.fetchone()\n return obj\n\n @classmethod\n def get_wx_app(cls, db, appid):\n sql = \"SELECT app.id as id, app.name as name FROM app, client, client_wx WHERE app.id=%s AND client.app_id=app.id AND client.id=client_wx.client_id\"\n r = db.execute(sql, appid)\n return r.fetchone()\n\n @classmethod\n def get_wx(cls, db, wx_appid):\n sql = \"SELECT client_id, gh_id, wx_app_id, refresh_token, store_id, is_authorized FROM client_wx WHERE wx_app_id=%s\"\n r = db.execute(sql, wx_appid)\n return r.fetchone()\n\n @classmethod\n def get_wx_count(cls, db, store_id):\n sql = \"SELECT count(client.id) as count FROM client_wx, client WHERE client_wx.client_id=client.id AND client_wx.store_id=%s\"\n r = db.execute(sql, store_id)\n obj = r.fetchone()\n return obj['count']\n\n\n\n\n @classmethod\n def get_wx_page(cls, db, store_id, offset, limit):\n sql = \"SELECT app.id as id, app.name as name, client_wx.gh_id as gh_id, client_wx.wx_app_id as wx_app_id, client_wx.store_id as store_id, client_wx.is_authorized as is_authorized FROM client_wx, client, app WHERE client_wx.client_id=client.id AND client_wx.store_id=%s AND client.app_id=app.id LIMIT %s, %s\"\n r = db.execute(sql, (store_id, offset, limit))\n return list(r.fetchall())\n\n @classmethod\n def get_store_id(cls, db, gh_id):\n sql = \"SELECT store_id FROM client_wx WHERE client_wx.gh_id=%s\"\n r = db.execute(sql, gh_id)\n obj = r.fetchone()\n if not obj:\n return 0\n return obj['store_id']\n\n\n @classmethod\n def set_wx_unauthorized(cls, db, wx_appid):\n sql = \"UPDATE client_wx SET is_authorized=%s WHERE wx_app_id=%s\"\n r = db.execute(sql, (0, wx_appid))\n return r.rowcount\n\n @classmethod\n def set_wx_authorized(cls, db, wx_appid):\n sql = \"UPDATE client_wx SET is_authorized=%s WHERE wx_app_id=%s\"\n r = db.execute(sql, (1, wx_appid))\n return r.rowcount\n\n @classmethod\n def update_wx(cls, db, wx_appid, refresh_token, is_authorized):\n sql = \"UPDATE client_wx SET refresh_token=%s, is_authorized=%s WHERE wx_app_id=%s\"\n \n is_auth = 1 if is_authorized else 0\n r = db.execute(sql, (refresh_token, is_auth, wx_appid))\n return r.rowcount\n\n","sub_path":"models/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"616165263","text":"import math\r\ndef findfactors(n):\r\n f=[]\r\n for i in range(1,int(math.sqrt(n)+1)):\r\n if n%i==0:\r\n if(n/i==i):\r\n f=f+[i]\r\n else:\r\n f=f+[i]+[int(n/i)]\r\n return f\r\nx=int(input(\"Enter number: \"))\r\nprint(\"factors of \",x,\": \",findfactors(x))\r\n","sub_path":"assignments/pythonpgms/factorsofNumber.py","file_name":"factorsofNumber.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"24444966","text":"import math\nd = 11\nstart = int((10**d)**(1.0/3))\nend = int((10**(d+1))**(1.0/3))\nseq = range(start, end)\n\nseq_cub = [a**3 for a in seq]\nseq_cub_digit = [''.join(sorted([b for b in str(a)])) for a in seq_cub]\n\nfrom collections import Counter\ncc = Counter(seq_cub_digit).most_common(10)\ndigit = cc[1][0]\n#aa=[a== cc[0][0] for a in seq_cub_digit]\nprint([a for a, b in zip(seq_cub, seq_cub_digit) if b == digit])\n","sub_path":"python/Q62.py","file_name":"Q62.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"639068393","text":"#!/usr/bin/python\r\nimport sys\r\nfrom collections import Counter\r\n\r\n\r\nclass op_stack:\r\n def __init__(self, op, items):\r\n self.op = op\r\n self.items = Counter(items)\r\n self.items[0 if op == '+' else 1] = 0\r\n\r\n def is_empty(self):\r\n return sum(self.items.values()) == 0\r\n\r\n def is_reaper(self):\r\n return (self.items[0] > 0) and (self.op == '*')\r\n\r\n def __eq__(self, other):\r\n if isinstance(other, op_stack):\r\n if self.op == other.op:\r\n return sum((self.items - other.items).values()) == 0\r\n return False\r\n\r\n\r\nclass op_pendulum:\r\n def __init__(self, definition):\r\n reader = 0\r\n self.stacks = []\r\n while reader < len(definition):\r\n op = definition[reader]\r\n items = []\r\n while definition[reader] == op:\r\n reader += 1\r\n next_reader = min(\r\n len(definition) \r\n if definition.find('+', reader) == -1 else\r\n definition.find('+', reader),\r\n len(definition) \r\n if definition.find('*', reader) == -1 else\r\n definition.find('*', reader),\r\n )\r\n if next_reader < len(definition):\r\n items.append(int(definition[reader:next_reader]))\r\n reader = next_reader\r\n else:\r\n items.append(int(definition[reader:]))\r\n reader = len(definition)\r\n break\r\n self.stacks.append(op_stack(op, items))\r\n if self.stacks[-1].is_empty():\r\n self.stacks.pop()\r\n elif self.stacks[-1].is_reaper():\r\n self.stacks = []\r\n items = []\r\n op = '*' if op == '+' else '+'\r\n\r\n def __eq__(self, other):\r\n if isinstance(other, op_pendulum):\r\n if len(self.stacks) == len(other.stacks):\r\n for a, b in zip(self.stacks, other.stacks):\r\n if not (a == b):\r\n return False\r\n return True\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n a = op_pendulum(sys.argv[1])\r\n b = op_pendulum(sys.argv[2])\r\n sys.stdout.write(str(a == b))\r\n sys.stdout.flush()\r\n sys.exit(0)\r\n","sub_path":"ops_equivalence.py","file_name":"ops_equivalence.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"431061","text":"import numpy as np\nimport os\n\n\ndef calcMops(true_positives, false_negatives, false_positives):\n s = {\n 'recall': true_positives / (true_positives + false_negatives),\n 'precision': true_positives / (true_positives + false_positives),\n 'jaccardIndex': true_positives / (true_positives + false_negatives + false_positives),\n 'branchingFactor': false_positives / true_positives,\n 'missFactor': false_negatives / true_positives,\n }\n s['completeness'] = s['recall']\n s['correctness'] = s['precision']\n s['fscore'] = (2 * s['recall'] * s['precision']) / (s['recall'] + s['precision'])\n return s\n\n\ndef run_threshold_geometry_metrics(refDSM, refDTM, refMask, testDSM, testDTM, testMask,\n tform, ignoreMask):\n refHgt = (refDSM - refDTM)\n refObj = refHgt\n refObj[~refMask] = 0\n\n testHgt = (testDSM - testDTM)\n testObj = np.copy(testHgt)\n testObj[~testMask] = 0\n\n # Make metrics\n refOnlyMask = refMask & ~testMask\n testOnlyMask = testMask & ~refMask\n overlapMask = refMask & testMask\n\n # Apply ignore mask\n refOnlyMask = refOnlyMask & ~ignoreMask\n testOnlyMask = testOnlyMask & ~ignoreMask\n overlapMask = overlapMask & ~ignoreMask\n\n # Determine evaluation units.\n unitArea = abs(tform[1] * tform[5])\n\n # --- Hard Error ------------------------------------------------------\n # Regions that are 2D False Positives or False Negatives, are\n # all or nothing. These regions don't consider overlap in the\n # underlying terrain models\n\n # -------- False Positive ---------------------------------------------\n unitCountFP = np.sum(testOnlyMask)\n oobFP = np.sum(testOnlyMask * testObj) * unitArea\n\n # -------- False Negative ---------------------------------------------\n unitCountFN = np.sum(refOnlyMask)\n oobFN = np.sum(refOnlyMask * refObj) * unitArea\n\n # --- Soft Error ------------------------------------------------------\n # Regions that are 2D True Positive\n\n # For both below:\n # Positive values are False Positives\n # Negative values are False Negatives\n deltaTop = testDSM - refDSM\n deltaBot = refDTM - testDTM\n\n # Regions that are 2D True Positives\n unitCountTP = np.sum(overlapMask)\n overlap = overlapMask * (testObj - refObj)\n overlap[np.isnan(overlap)] = 0\n\n # -------- False Positive -------------------------------------------------\n false_positives = np.nansum((deltaTop > 0) * deltaTop * overlapMask) * unitArea + \\\n np.nansum((deltaBot > 0) * deltaBot * overlapMask) * unitArea\n\n # -------- False Negative -------------------------------------------------\n false_negatives = -np.nansum((deltaTop < 0) * deltaTop * overlapMask) * unitArea + \\\n -np.nansum((deltaBot < 0) * deltaBot * overlapMask) * unitArea\n\n # -------- True Positive ---------------------------------------------------\n true_positives = np.nansum(refObj * overlapMask) * unitArea - false_negatives\n tolFP = false_positives + oobFP\n tolFN = false_negatives + oobFN\n tolTP = true_positives\n\n metrics = {\n '2D': calcMops(unitCountTP, unitCountFN, unitCountFP),\n '3D': calcMops(tolTP, tolFN, tolFP),\n }\n\n return metrics\n","sub_path":"core3dmetrics/geometrics/threshold_geometry_metrics.py","file_name":"threshold_geometry_metrics.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604468824","text":"#查看缺少实参的错误提示\n#罗旭阳,2019/01/30\ndef pet(pet_name, animal_type = \"dog\"):\n\tprint(\"My pet name is \" + pet_name.title() + \".\" )\n\tprint(\"And it is a \" + animal_type + \".\")\n\n#位置形参,加默认值实参\npet(\"alice\")\n\n#缺少一个参数\n#pet()\n\n#关键字参数对\npet(animal_type = \"cat\", pet_name = \"jack\")\n","sub_path":"pet_function.py","file_name":"pet_function.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"172540757","text":"from flask import Flask, request, jsonify\r\nfrom flask_restful import Resource, Api, reqparse, abort\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\n\r\n\r\n\"\"\"\r\nTest Code\r\nurl = 'curl -i -H \\\"Content-Type: application/json\\\" -X POST -d ' + '\\'' + total_request + '\\'' + ' http://127.0.0.1:5050/Test'\r\ncurl -i -H \"Content-Type: application/json\" -X POST -d '{\"Hello\":\"hi\"}' http://127.0.0.1:7070/MECrcaserver\r\nos.system(url)\r\n\"\"\"\r\n@app.route('/MECrcaserver',methods=['POST','PUT'])\r\ndef rca_server():\r\n if not request.json:\r\n abort(400)\r\n data = request.json\r\n print(data)\r\n # api_handler.start_action(data['action'],data)\r\n return ''\r\n\r\nif __name__ == '__main__':\r\n app.run(host='192.168.11.11',port = 7071,debug = True)\r\n","sub_path":"rca_server.py","file_name":"rca_server.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"379924968","text":"import aiosqlite\nimport os\nimport logging\nfrom pathlib import Path\n\nlog = logging.getLogger(__name__)\n\nclass Database:\n __slots__ = ('sql_path', 'db_path', 'cxn')\n\n def __init__(self, dynamic: Path, static: Path) -> None:\n self.sql_path = (static / 'build.sql').resolve()\n self.db_path = (dynamic / 'database.db').resolve()\n\n async def connect(self) -> aiosqlite.Connection:\n self.cxn = await aiosqlite.connect(self.db_path)\n await self.cxn.executescript(self.sql_path.read_text())\n await self.cxn.commit()\n return self.cxn\n\n async def commit(self) -> None:\n await self.cxn.commit()\n\n async def close(self) -> None:\n await self.cxn.close()\n\n async def execute(self, query: str, *args) -> None:\n try:\n await self.cxn.execute(query, args)\n except Exception as e:\n log.error(f\"❌ {e}\")\n raise e\n\n async def fetchall(self, query: str, *args) -> list:\n try:\n return await self.cxn.execute(query, args).fetchall()\n except Exception as e:\n log.error(f\"❌ {e}\")\n raise e\n\n async def fetchone(self, query: str, *args) -> tuple:\n try:\n return await self.cxn.execute(query, args).fetchone()\n except Exception as e:\n log.error(f\"❌ {e}\")\n raise e\n\n ","sub_path":"permafrost/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"288245285","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef forward (x,w1,b1,w2,b2):\r\n z = 1/(1+np.exp(-x.dot(w1)-b1))\r\n a = z.dot(w2) + b2\r\n aexp = np.exp(a)\r\n y = aexp/aexp.sum(axis=1, keepdims=True)\r\n return y, z\r\n \r\ndef classification_error(y,p):\r\n n_crct = 0 \r\n n_total = 0\r\n for i in range(len(y)):\r\n n_total += 1\r\n if y[i] == p[i]:\r\n n_crct += 1\r\n return float(n_crct)/ n_total\r\n\r\ndef cost(T, output):\r\n t = T* np.log(output)\r\n return t.sum()\r\n \r\ndef derivative_w2(hidden, T, output):\r\n re = hidden.T.dot(T - output)\r\n return re\r\n \r\ndef derivative_w1(x, hidden, T, output, w2):\r\n dZ = (T - output).dot(w2.T) * hidden * (1 - hidden)\r\n ret2 = x.T.dot(dZ)\r\n return ret2\r\n \r\ndef derivative_b2(T, output):\r\n re = (T-output).sum(axis=0)\r\n return re\r\n \r\ndef derivative_b1(T, Y, W2, Z):\r\n return ((T - Y).dot(W2.T) * Z * (1 - Z)).sum(axis=0)\r\n \r\n \r\n\r\ndef main():\r\n N = 500\r\n x1 = np.random.randn(N,2) + np.array([0,-2])\r\n x2 = np.random.randn(N,2) + np.array([2,2])\r\n x3 = np.random.randn(N,2) + np.array([-2,2])\r\n x = np.vstack([x1, x2, x3])\r\n \r\n \r\n D = 2#DIMENSIONS\r\n M = 3#NO OF NEURONS IN HIDDEN LAYER\r\n K = 3#NO OF CLASSES\r\n \r\n y = np.array([0]*N +[1]*N + [2]*N)\r\n N = len(y)\r\n T = np.zeros((N, K))\r\n for i in range(N):\r\n T[i, y[i]] = 1\r\n\r\n plt.scatter(x[:,0], x[:,1], c=y, alpha=0.5)\r\n plt.show()\r\n \r\n\r\n w1 = np.random.randn(D, M)\r\n b1 = np.random.randn(M)\r\n w2 = np.random.randn(M, K)\r\n b2 = np.random.randn(K)\r\n\r\n learning_rate = 10e-7\r\n costs = []\r\n for epoch in range(1000):\r\n output, hidden = forward(x,w1,b1,w2,b2)\r\n if epoch%500 == 0 :\r\n c = cost(T, output)\r\n P = np.argmax(output, axis =1)\r\n r = classification_error(y, P)\r\n print(\"cost:\", c, \"classification_rate:\", r)\r\n costs.append(c)\r\n print(w2.shape,derivative_w2(hidden, T, output).shape,T.shape,hidden.shape)\r\n \r\n w2 += learning_rate * derivative_w2(hidden, T, output)\r\n b2 += learning_rate * derivative_b2(T, output)\r\n w1 += learning_rate * derivative_w1(x, hidden, T, output, w2)\r\n b1 += learning_rate * derivative_b1(T, output, w2, hidden)\r\n\r\n plt.plot(costs)\r\n plt.show() \r\n \r\nif __name__=='__main__':\r\n main()","sub_path":"Deep_learning/backpropg.py","file_name":"backpropg.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"545678562","text":"from __future__ import annotations\n\nimport json\nfrom logging import Formatter, LogRecord\n\n\nclass JSONFormatter(Formatter):\n \"\"\"\n JSON log formatter\n\n Configuration::\n\n from tiger.logs import JSONFormatter\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(JSONFormatter())\n logger = logging.getLogger('tiger')\n logger.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n\n Usage::\n\n logger.info('Connection established')\n logger.error('Could not connect to server', exc_info=True)\n\n Output::\n\n {\n \"tag\": \"tiger\",\n \"level\": \"INFO\",\n \"created\": 1551819415.017764,\n \"message\": \"Connection established\"\n }\n\n {\n \"tag\": \"tiger\",\n \"level\": \"ERROR\",\n \"created\": 1551819292.640645,\n \"message\": \"Could not connect to server\",\n \"exception\": \"Traceback (most recent call last): ... Connection refused by the server\"\n }\n \"\"\"\n\n def format(self, record: LogRecord) -> str:\n json_record = {\n \"tag\": record.name,\n \"level\": record.levelname,\n \"created\": record.created,\n \"message\": record.getMessage(),\n }\n\n if record.exc_info:\n json_record[\"exception\"] = self.formatException(record.exc_info)\n\n return json.dumps(json_record, ensure_ascii=False)\n","sub_path":"tiger/logging/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"474656480","text":"import pandas\n\nfrom . import feature\n\nSOURCE = \"transcript_utils\"\nMISSING_VALUE = \".\"\n\n\nclass GtfRow(object):\n SEQNAME_COL = 0\n FEATURE_COL = 2\n START_COL = 3\n END_COL = 4\n STRAND_COL = 6\n ATTRIBUTES_COL = 8\n\n EXON_FEATURE = \"exon\"\n\n GENE_ID_ATTRIBUTE = \"gene_id\"\n TRANSCRIPT_ID_ATTRIBUTE = \"transcript_id\"\n\n @classmethod\n def from_file(cls, row_data):\n strip_quotes = lambda x: x.replace('\"', '')\n attr_str = row_data[GtfRow.ATTRIBUTES_COL]\n attr_dict = {attr: strip_quotes(val) for attr, val in\n [av.split(\" \", 1) for av in attr_str.split(\"; \")]}\n\n return GtfRow(row_data, attr_dict)\n\n @classmethod\n def from_values(cls, seqname, feature_type, start, end,\n strand, gene, transcript):\n\n row_data = [seqname, SOURCE, feature_type, start, end,\n MISSING_VALUE, strand, MISSING_VALUE]\n attr_dict = {GtfRow.GENE_ID_ATTRIBUTE: gene,\n GtfRow.TRANSCRIPT_ID_ATTRIBUTE: transcript}\n\n return GtfRow(row_data, attr_dict)\n\n def __init__(self, row_data, attr_dict):\n self.row_data = row_data\n self.attr_dict = attr_dict\n\n def get_seqname(self):\n return self.row_data[GtfRow.SEQNAME_COL]\n\n def get_feature(self):\n return self.row_data[GtfRow.FEATURE_COL]\n\n def get_start(self):\n return self.row_data[GtfRow.START_COL]\n\n def get_end(self):\n return self.row_data[GtfRow.END_COL]\n\n def get_strand(self):\n return self.row_data[GtfRow.STRAND_COL]\n\n def get_gene(self):\n return self.attr_dict[GtfRow.GENE_ID_ATTRIBUTE]\n\n def get_transcript(self):\n return self.attr_dict[GtfRow.TRANSCRIPT_ID_ATTRIBUTE]\n\n def is_exon(self):\n return self.get_feature() == GtfRow.EXON_FEATURE\n\n def __str__(self):\n fields = list(self.row_data)\n\n attr_str = \"; \".join([\"{k} \\\"{v}\\\"\".format(k=k, v=v)\n for k, v in iter(self.attr_dict.items())])\n\n fields.append(attr_str)\n\n return \"\\t\".join([str(field) for field in fields])\n\n\nclass GtfInfo(object):\n def __init__(self, gtf_file, logger):\n self.gtf_file = gtf_file\n self.data = pandas.read_csv(\n gtf_file, sep=\"\\t\", header=None, comment=\"#\")\n self.logger = logger\n\n def rows(self):\n for index, row in self.data.iterrows():\n yield GtfRow.from_file(row)\n\n def get_transcript_info(self):\n self.logger.info(\"Reading transcript info...\")\n\n transcript_info = {}\n lines_processed = 0\n\n for row in self.rows():\n lines_processed += 1\n if lines_processed % 10000 == 0:\n self.logger.debug(\"Processed {l} GTF lines.\".format(l=lines_processed))\n\n if not row.is_exon():\n continue\n\n gene_name = row.get_gene()\n\n gene = None\n if gene_name in transcript_info:\n gene = transcript_info[gene_name]\n else:\n gene = feature.Gene(row)\n transcript_info[gene_name] = gene\n\n transcript = gene.add_transcript(row)\n transcript.add_exon(row)\n\n self.logger.info(\"...read transcript information for {g} genes\".format(\n g=len(transcript_info)))\n\n return transcript_info\n","sub_path":"transcript_utils/gtf.py","file_name":"gtf.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"503945077","text":"'''backtest\nstart: 2020-02-22 00:00:00\nend: 2020-04-06 00:00:00\nperiod: 1h\nexchanges: [{\"eid\":\"Futures_OKCoin\",\"currency\":\"BTC_USD\"}]\n'''\nimport sys\nimport pandas as pd\nimport datetime\n# from fmz import *\n# task = VCtx(__doc__)\n\ninit_counter = exchange.GetPosition()[0]\nmax_price = 7000\nmin_price = 6000\nmid_price = min_price + (max_price - min_price)/2\nnet_sum = 40\nnet_price = ((max_price - min_price)/2)/net_sum\nnet_position = (init_counter * 3) / (100 * net_sum)\nif (max_price - min_price)/min_price > 0.2:\n print(\"[-- 价格区间设置错误,区间差价大于20% --]\")\n sys.exit(0)\n\nclass Exchange:\n # 交易回测引擎\n def __init__(self, trade_symbols, leverage=20, commission=0.00005, initial_balance=10000, log=False):\n self.initial_balance = initial_balance # 初始的资产\n self.commission = commission\n self.leverage = leverage\n self.trade_symbols = trade_symbols\n self.date = ''\n self.log = log\n self.df = pd.DataFrame(columns=['margin', 'total', 'leverage', 'realised_profit', 'unrealised_profit'])\n self.account = {'USDT': {'realised_profit': 0, 'margin': 0, 'unrealised_profit': 0, 'total': initial_balance,\n 'leverage': 0}}\n for symbol in trade_symbols:\n self.account[symbol] = {'amount': 0, 'hold_price': 0, 'value': 0, 'price': 0, 'realised_profit': 0,\n 'margin': 0, 'unrealised_profit': 0}\n\n def Trade(self, symbol, direction, price, amount, msg=''):\n if self.date and self.log:\n print('%-20s%-5s%-5s%-10.8s%-8.6s %s' % (\n str(self.date), symbol, 'buy' if direction == 1 else 'sell', price, amount, msg))\n\n cover_amount = 0 if direction * self.account[symbol]['amount'] >= 0 else min(\n abs(self.account[symbol]['amount']), amount)\n open_amount = amount - cover_amount\n\n self.account['USDT']['realised_profit'] -= price * amount * self.commission # 扣除手续费\n\n if cover_amount > 0: # 先平仓\n self.account['USDT']['realised_profit'] += -direction * (\n price - self.account[symbol]['hold_price']) * cover_amount # 利润\n self.account['USDT']['margin'] -= cover_amount * self.account[symbol]['hold_price'] / self.leverage # 释放保证金\n\n self.account[symbol]['realised_profit'] += -direction * (\n price - self.account[symbol]['hold_price']) * cover_amount\n self.account[symbol]['amount'] -= -direction * cover_amount\n self.account[symbol]['margin'] -= cover_amount * self.account[symbol]['hold_price'] / self.leverage\n self.account[symbol]['hold_price'] = 0 if self.account[symbol]['amount'] == 0 else self.account[symbol][\n 'hold_price']\n\n if open_amount > 0:\n total_cost = self.account[symbol]['hold_price'] * direction * self.account[symbol][\n 'amount'] + price * open_amount\n total_amount = direction * self.account[symbol]['amount'] + open_amount\n\n self.account['USDT']['margin'] += open_amount * price / self.leverage\n self.account[symbol]['hold_price'] = total_cost / total_amount\n self.account[symbol]['amount'] += direction * open_amount\n self.account[symbol]['margin'] += open_amount * price / self.leverage\n\n self.account[symbol]['unrealised_profit'] = (price - self.account[symbol]['hold_price']) * self.account[symbol][\n 'amount']\n self.account[symbol]['price'] = price\n self.account[symbol]['value'] = abs(self.account[symbol]['amount']) * price\n\n return True\n\n def Buy(self, symbol, price, amount, msg=''):\n self.Trade(symbol, 1, price, amount, msg)\n\n def Sell(self, symbol, price, amount, msg=''):\n self.Trade(symbol, -1, price, amount, msg)\n\n def Update(self, date, close_price): # 对资产进行更新\n self.date = date\n self.close = close_price\n self.account['USDT']['unrealised_profit'] = 0\n for symbol in self.trade_symbols:\n if np.isnan(close_price[symbol]):\n continue\n self.account[symbol]['unrealised_profit'] = (close_price[symbol] - self.account[symbol]['hold_price']) * \\\n self.account[symbol]['amount']\n self.account[symbol]['price'] = close_price[symbol]\n self.account[symbol]['value'] = abs(self.account[symbol]['amount']) * close_price[symbol]\n self.account['USDT']['unrealised_profit'] += self.account[symbol]['unrealised_profit']\n if self.date.hour in [0, 8, 16]:\n pass\n self.account['USDT']['realised_profit'] += -self.account[symbol]['amount'] * close_price[\n symbol] * 0.01 / 100\n\n self.account['USDT']['total'] = round(\n self.account['USDT']['realised_profit'] + self.initial_balance + self.account['USDT']['unrealised_profit'],\n 6)\n self.account['USDT']['leverage'] = round(self.account['USDT']['margin'] / self.account['USDT']['total'],\n 4) * self.leverage\n self.df.loc[self.date] = [self.account['USDT']['margin'], self.account['USDT']['total'],\n self.account['USDT']['leverage'], self.account['USDT']['realised_profit'],\n self.account['USDT']['unrealised_profit']]\n\nclass StopPolicy(object):\n # 止盈止损策略\n def __init__(self):\n pass\n\n def stop_loss(self):\n pass\n\n def stop_profit(self):\n pass\n\nkongtou_trade_list = []\nduotou_trade_list = []\nwhile True:\n ticker = exchange.GetTicker()\n price = ticker['Last']\n if (price >= mid_price) and (price < max_price): # 空头\n if len(kongtou_trade_list) > 0:\n last_trade = kongtou_trade_list[-1]\n if price - last_trade['open_price'] >= net_price: # 开空\n exchange.SetDirection(\"sell\")\n exchange.Sell(price - 10, net_position)\n Log(\"[== 开空头仓 ==]: 开仓价格:{} 网格id:{}\".format((price+0.2), len(kongtou_trade_list)))\n kongtou_trade_list.append({\"open_price: \": (price + 0.2),\n \"net_id: \": len(kongtou_trade_list),\n \"direction: \": \"kong\"})\n if last_trade['open_price'] - price > net_price: # 平空\n exchange.SetDirection(\"closesell\")\n exchange.Buy((price+0.2), net_position)\n Log(\"[== 平空头仓 ==]:平仓价格:{} 网格id:{}\".format((price+0.2), len(kongtou_trade_list)))\n del kongtou_trade_list[-1]\n if len(kongtou_trade_list) == 0:\n if (price - mid_price) > net_price:\n exchange.SetDirection(\"sell\")\n exchange.Sell(price - 0.2, net_position)\n Log(\"[== 开空头仓 ==]: 开仓价格:{} 网格id:{}\".format((price-0.2), len(kongtou_trade_list)))\n\n if (price < mid_price) and (price > min_price): # 多头\n if len(duotou_trade_list) > 0:\n last_trade = duotou_trade_list[-1]\n if last_trade['open_price'] - price >= net_price: # 开多\n exchange.SetDirection(\"buy\")\n exchange.Buy(price+0.2, net_position)\n Log(\"[== 开多头仓 ==]: 开仓价格:{} 网格id:{}\".format((price+0.2), len(duotou_trade_list)))\n duotou_trade_list.append({\"open_price: \": (price + 0.2),\n \"net_id: \": len(duotou_trade_list),\n \"direction: \": \"duo\"})\n if price - last_trade['open_price'] > net_price: # 平多\n exchange.SetDirection(\"closebuy\")\n exchange.Sell(price-0.2, net_position)\n Log(\"[== 平多头仓 ==]:平仓价格:{} 网格id:{}\".format((price-0.2), len(duotou_trade_list)))\n del duotou_trade_list[-1]\n if len(duotou_trade_list) == 0:\n if (mid_price - price) > net_price:\n exchange.SetDirection(\"buy\")\n exchange.Buy(price+0.2, net_position)\n Log(\"[== 开多头仓 ==]: 开仓价格:{} 网格id:{}\".format((price+0.2), len(duotou_trade_list)))\n\n if (price > max_price) or (price < min_price):\n Log(\"[-- 价格已经突破了区间,所有仓位都将平掉。程序也将退出 --]\")\n if len(kongtou_trade_list) > 0:\n exchange.SetDirection(\"closesell\")\n exchange.Buy((price + 10), net_position*len(kongtou_trade_list))\n if len(duotou_trade_list) > 0:\n exchange.SetDirection(\"closebuy\")\n exchange.Sell(price - 10, net_position*len(duotou_trade_list))\n sys.exit(0)\n Sleep(1000*3)","sub_path":"Easy_net.py","file_name":"Easy_net.py","file_ext":"py","file_size_in_byte":8968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"46207091","text":"# Import Libraries\nimport torch\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\n# Specify transforms using torchvision.transforms as transforms library\ntransformations = transforms.Compose([\n transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n\n# Load in each dataset and apply transformations using the torchvision.datasets as datasets library\ntrain_set = datasets.ImageFolder(\"RDDC_Train\", transform=transformations)\nval_set = datasets.ImageFolder(\"RDDC_Test\", transform=transformations)\n\nprint('The class labels are:', train_set.classes, '\\n')\n\n# Put into a Dataloader using torch library\nbatch_size = 32\ntrain_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True)\nval_loader = torch.utils.data.DataLoader(val_set, batch_size=batch_size, shuffle=True)\n\n# Get pretrained model using torchvision.models as models library\nmodel = models.densenet161(pretrained=True)\n\n# Turn off training for their parameters\nfor param in model.parameters():\n param.requires_grad = False\n\n# Create new classifier for model using torch.nn as nn library\nclassifier_input = model.classifier.in_features\nnum_labels = 8\nclassifier = nn.Sequential(nn.Linear(classifier_input, 64),\n nn.ReLU(),\n nn.Linear(64, 32),\n nn.ReLU(),\n nn.Linear(32, num_labels),\n nn.LogSoftmax(dim=1))\n\n# Replace default classifier with new classifier\nmodel.classifier = classifier\n\n# Find the device available to use using torch library\nif torch.cuda.is_available():\n device = 'cuda'\nelse:\n device = 'cpu'\n\n# Move model to the device specified above\nmodel.to(device)\n\n# Set the error function using torch.nn as nn library\ncriterion = nn.NLLLoss()\n# Set the optimizer function using torch.optim as optim library\noptimizer = optim.Adam(model.classifier.parameters())\n\n# Training the Model\nepochs = 50\nstart_train = time.time()\nepoch_array = []\naccu_array = []\nD00_TPR_array = []\nD00_FPR_array = []\nD01_TPR_array = []\nD01_FPR_array = []\nD10_TPR_array = []\nD10_FPR_array = []\nD11_TPR_array = []\nD11_FPR_array = []\nD20_TPR_array = []\nD20_FPR_array = []\nD40_TPR_array = []\nD40_FPR_array = []\nD43_TPR_array = []\nD43_FPR_array = []\nD44_TPR_array = []\nD44_FPR_array = []\nD00_TPR_array.append(0)\nD00_FPR_array.append(0)\nD01_TPR_array.append(0)\nD01_FPR_array.append(0)\nD10_TPR_array.append(0)\nD10_FPR_array.append(0)\nD11_TPR_array.append(0)\nD11_FPR_array.append(0)\nD20_TPR_array.append(0)\nD20_FPR_array.append(0)\nD40_TPR_array.append(0)\nD40_FPR_array.append(0)\nD43_TPR_array.append(0)\nD43_FPR_array.append(0)\nD44_TPR_array.append(0)\nD44_FPR_array.append(0)\n\nfor epoch in range(epochs):\n display_epoch = epoch + 1\n print('Epoch:', display_epoch)\n epoch_array.append(display_epoch)\n train_loss = 0\n val_loss = 0\n accuracy = 0\n\n # Training the model\n model.train()\n counter = 0\n for inputs, labels in train_loader:\n # Move to device\n inputs, labels = inputs.to(device), labels.to(device)\n # Clear optimizers\n optimizer.zero_grad()\n # Forward pass\n output = model.forward(inputs)\n # Loss\n loss = criterion(output, labels)\n # Calculate gradients (backpropogation)\n loss.backward()\n # Adjust parameters based on gradients\n optimizer.step()\n # Add the loss to the training set's rnning loss\n train_loss += loss.item() * inputs.size(0)\n\n # Print the progress of our training\n counter += 1\n print(\"Batch:\", counter, \"out of\", len(train_loader))\n\n end_train = time.time()\n print('Finished Epoch', epoch + 1, 'Training in %0.2f minutes' % ((end_train - start_train) / 60))\n\n # Evaluating the model\n start_valid = time.time()\n model.eval()\n counter = 0\n\n total_classes = 8\n output = torch.randn(batch_size, total_classes) # refer to output after softmax\n target = torch.randint(0, total_classes, (batch_size,)) # labels\n confusion_matrix = torch.zeros(total_classes, total_classes)\n\n # Tell torch not to calculate gradients\n with torch.no_grad():\n for inputs, labels in val_loader:\n # Move to device\n inputs, labels = inputs.to(device), labels.to(device)\n # Forward pass\n output = model.forward(inputs)\n # Calculate Loss\n valloss = criterion(output, labels)\n # Add loss to the validation set's running loss\n val_loss += valloss.item() * inputs.size(0)\n\n # Since our model outputs a LogSoftmax, find the real\n # percentages by reversing the log function\n output = torch.exp(output)\n # Get the top class of the output\n top_p, top_class = output.topk(1, dim=1)\n # See how many of the classes were correct?\n equals = top_class == labels.view(*top_class.shape)\n # Calculate the mean (get the accuracy for this batch)\n # and add it to the running accuracy for this epoch\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n # Print the progress of our evaluation\n counter += 1\n print(\"Batch:\", counter, \"out of\", len(val_loader))\n\n _, preds = torch.max(output, 1)\n\n for p, t in zip(preds.view(-1), labels.view(-1)):\n confusion_matrix[p.long(), t.long()] += 1\n\n print(confusion_matrix)\n\n TP = confusion_matrix.diag()\n\n for c in range(total_classes):\n idx = torch.ones(total_classes).byte()\n idx[c] = 0\n TN = confusion_matrix[idx.nonzero()[:, None], idx.nonzero()].sum()\n FP = confusion_matrix[c, idx].sum()\n FN = confusion_matrix[idx, c].sum()\n\n sensitivity = (TP[c] / (TP[c] + FN))\n specificity = (TN / (TN + FP))\n FPR = 1 - specificity\n # re_call = (TP[c] / (TP[c] + FP))\n pre_cision = (TP[c] / (TP[c] + FN))\n f1_score = 2 * ((pre_cision * sensitivity) / (pre_cision + sensitivity))\n checking_c = c + 1\n if (checking_c == 1):\n D00_TPR_array.append(sensitivity)\n D00_FPR_array.append(FPR)\n elif (checking_c == 2):\n D01_TPR_array.append(sensitivity)\n D01_FPR_array.append(FPR)\n elif (checking_c == 3):\n D10_TPR_array.append(sensitivity)\n D10_FPR_array.append(FPR)\n elif (checking_c == 4):\n D11_TPR_array.append(sensitivity)\n D11_FPR_array.append(FPR)\n elif (checking_c == 5):\n D20_TPR_array.append(sensitivity)\n D20_FPR_array.append(FPR)\n elif (checking_c == 6):\n D40_TPR_array.append(sensitivity)\n D40_FPR_array.append(FPR)\n elif (checking_c == 7):\n D43_TPR_array.append(sensitivity)\n D43_FPR_array.append(FPR)\n else:\n D44_TPR_array.append(sensitivity)\n D44_FPR_array.append(FPR)\n\n print('Class {}\\nTP {}, TN {}, FP {}, FN {}'.format(c + 1, TP[c], TN, FP, FN))\n print('Sensitivity or Recall = {}'.format(sensitivity))\n print('Specificity = {}'.format(specificity))\n # print('Recall = {}'.format(re_call))\n print('Precision = {}'.format(pre_cision))\n print('F1 Score = {}'.format(f1_score))\n\n end_valid = time.time()\n print('Finished Epoch', epoch + 1, 'Validating in %0.2f minutes' % ((end_valid - start_valid) / 60))\n\n # Get the average loss for the entire epoch\n train_loss = train_loss / len(train_loader.dataset)\n valid_loss = val_loss / len(val_loader.dataset)\n\n record_accuracy = (accuracy / len(val_loader)) * 100\n print(\"Record Accuracy\", record_accuracy, \" in epoch\", display_epoch)\n accu_array.append(record_accuracy)\n\n # Print out the information\n print('Accuracy: %0.3f %%' % (accuracy / len(val_loader) * 100))\n print('Training Loss: {:.6f} ' '\\tValidation Loss: {:.6f}'.format(train_loss, valid_loss), '\\n')\n\n print('Total Time is %0.2f minutes' % ((end_valid - start_train) / 60))\n\nD00_TPR_array.append(1)\nD00_FPR_array.append(1)\nD01_TPR_array.append(1)\nD01_FPR_array.append(1)\nD10_TPR_array.append(1)\nD10_FPR_array.append(1)\nD11_TPR_array.append(1)\nD11_FPR_array.append(1)\nD20_TPR_array.append(1)\nD20_FPR_array.append(1)\nD40_TPR_array.append(1)\nD40_FPR_array.append(1)\nD43_TPR_array.append(1)\nD43_FPR_array.append(1)\nD44_TPR_array.append(1)\nD44_FPR_array.append(1)\n\nD00_TPR_array.sort()\nD00_FPR_array.sort()\nD01_TPR_array.sort()\nD01_FPR_array.sort()\nD10_TPR_array.sort()\nD10_FPR_array.sort()\nD11_TPR_array.sort()\nD11_FPR_array.sort()\nD20_TPR_array.sort()\nD20_FPR_array.sort()\nD40_TPR_array.sort()\nD40_FPR_array.sort()\nD43_TPR_array.sort()\nD43_FPR_array.sort()\nD44_TPR_array.sort()\nD44_FPR_array.sort()\n\n# Title\nplt.title('ROC Plot for DenseNet161')\n# Axis labels\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.plot(D00_FPR_array, D00_TPR_array, color='blue', linewidth=3, label='D00')\nplt.plot(D01_FPR_array, D01_TPR_array, color='green', linewidth=3, label='D01')\nplt.plot(D10_FPR_array, D10_TPR_array, color='orange', linewidth=3, label='D10')\nplt.plot(D11_FPR_array, D11_TPR_array, color='black', linewidth=3, label='D11')\nplt.plot(D20_FPR_array, D20_TPR_array, color='cyan', linewidth=3, label='D20')\nplt.plot(D40_FPR_array, D40_TPR_array, color='lavender', linewidth=3, label='D40')\nplt.plot(D43_FPR_array, D43_TPR_array, color='lime', linewidth=3, label='D43')\nplt.plot(D44_FPR_array, D44_TPR_array, color='coral', linewidth=3, label='D44')\nplt.legend()\nplt.show()\n\n# Title\nplt.title('Epoch Vs Accuracy for DenseNet161')\n# Axis labels\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.plot(epoch_array, accu_array)\nplt.show()","sub_path":"Image_Classification/DenseNet161_Model.py","file_name":"DenseNet161_Model.py","file_ext":"py","file_size_in_byte":10260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"33291547","text":"import numpy as np\nimport dask.array as da\n\ndef pad_arrays(arrays, constant_values, stack=True):\n \"\"\"\n Pad arrays with variable axis sizes. A bounding box is calculated across all the arrays and each sub-array is\n padded to fit within the bounding box. This is a light wrapper around dask.array.pad. If `stack` is True,\n the arrays will be combined into a larger array via da.stack.\n\n Parameters\n ----------\n arrays : An iterable collection of dask arrays\n constant_values : The value to fill when padding images\n\n constant_values : A number which specifies the fill value / mode to use when padding.\n\n stack: boolean that determines whether the result is a single dask array (stack=True) or a list of dask arrays (stack=False).\n\n Returns padded arrays and a list of paddings.\n -------\n\n \"\"\"\n\n shapes = np.array([a.shape for a in arrays])\n bounds = shapes.max(0)\n pad_extent = [\n list(zip([0] * shapes.shape[1], (bounds - np.array(a.shape)).tolist()))\n for a in arrays\n ]\n\n # pad elements of the first axis differently\n def padfun(array, pad_width, constant_values):\n return np.stack([np.pad(a, pad_width, constant_values=cv) for a, cv in zip(array, constant_values)])\n # If all the shapes are identical no padding is needed.\n if np.unique(shapes, axis=0).shape[0] == 1:\n padded = arrays\n else:\n padded = [\n a.map_blocks(padfun,\n pad_width=pad_extent[ind][1:],\n constant_values=constant_values,\n chunks=tuple(c + p[1] - p[0] for c, p in zip(a.chunksize, pad_extent[ind])),\n dtype=a.dtype)\n for ind, a in enumerate(arrays)]\n\n return padded, pad_extent\n\n\ndef arrays_from_delayed(args, shapes=None, dtypes=None):\n \"\"\"\n\n Parameters\n ----------\n args: a collection of dask.delayed objects representing lazy-loaded arrays.\n\n shapes: a collection of tuples specifying the shape of each array in args, or None. if None, the first array will be loaded\n using local computation, and the shape of that arrays will be used for all subsequent arrays.\n\n dtypes: a collection of strings specifying the datatype of each array in args, or None. If None, the first array will be loaded\n using local computation and the dtype of that array will be used for all subsequent arrays.\n\n Returns a list of dask arrays.\n -------\n\n \"\"\"\n\n if shapes is None or dtypes is None:\n sample = args[0].compute(scheduler=\"threads\")\n if shapes is None:\n shapes = (sample.shape,) * len(args)\n if dtypes is None:\n dtypes = (sample.dtype,) * len(args)\n\n assert len(shapes) == len(args) and len(dtypes) == len(args)\n\n arrays = [\n da.from_delayed(args[ind], shape=shapes[ind], dtype=dtypes[ind])\n for ind in range(len(args))\n ]\n return arrays\n\n\n","sub_path":"fst/io/ingest.py","file_name":"ingest.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"635787034","text":"import keras\nimport numpy as np\nimport tensorflow as tf\nfrom glob import glob\nimport pandas as pd\nfrom tqdm import tqdm\nimport keras.backend as K\nfrom keras.utils import np_utils\nfrom keras.models import load_model\n\nclass Ablation():\n\t\"\"\"\n\n\tA class for conducting an ablation study on a trained keras model instance\n\t\n\t\"\"\"\n\n\tdef __init__(self, model, weights_pth, metric, layer_name, test_image, gt, classes, nclasses=4):\n\t\t\n\t\t\"\"\"\n\t\tmodel : keras model architecture (keras.models.Model)\n\t\tweights_pth : saved weights path (str)\n metric : metric to compare prediction with gt, for example dice, CE\n layer_name : name of the layer which needs to be ablated\n test_img : test image used for ablation\n gt : ground truth for comparision\n classes : class informatiton which needs to be considered, class label as \n\t\t\t\tkey and corresponding required values \n\t\t\t\tin a tuple: {'class1': (1,), 'whole': (1,2,3)}\n nclasses : number of unique classes in gt\n\t\t\"\"\"\t\t\n\n\t\tself.model = model\n\t\tself.weights = weights_pth\n\t\tself.metric = metric\n\t\tself.test_image = test_image\n\t\tself.layer = layer_name\n\t\tself.gt = gt\n\t\tself.classinfo = classes\n\t\tself.nclasses = nclasses\n\n\n\n\tdef ablate_filter(self, step=1):\n\t\t\"\"\"\n\t\tDrops individual weights from the model, makes the prediction for the test image,\n\t\tand calculates the difference in the evaluation metric as compared to the non-\n\t\tablated case. For example, for a layer with a weight matrix of shape 3x3x64, \n\t\tindividual 3x3 matrices are zeroed out at the interval given by the step argument.\n\t\t\n\t\tArguments:\n\t\tstep: The interval at which to drop weights\n\n\t\tOutputs: A dataframe containing the importance scores for each individual weight matrix in the layer\n\t\t\"\"\"\n\n\t\tlayer_idx = 0\n\t\tfor idx, layer in enumerate(self.model.layers):\n\t\t\tif layer.name == self.layer:\n\t\t\t\tfilters_to_ablate = np.arange(0, layer.get_weights()[0].shape[-1], step)\n\t\t\t\tlayer_idx = idx\n\t\t \n\t\t#print('Layer = %s' %self.model.layers[self.layer].name)\n\t\tself.model.load_weights(self.weights, by_name = True)\n\n\t\t#predicts each volume and save the results in np array\n\t\tprediction_unshaped = self.model.predict(self.test_image, batch_size=1, verbose=0)\n\n\t\tdice_json = {}\n\t\tdice_json['feature'] = []\n\t\tfor class_ in self.classinfo.keys():\n\t\t\tdice_json[class_] = []\n\n\t\tfor j in tqdm(filters_to_ablate):\n\t\t\t#print('Perturbed_Filter = %d' %j)\n\t\t\tself.model.load_weights(self.weights, by_name = True)\n\t\t\tlayer_weights = np.array(self.model.layers[layer_idx].get_weights())\n\n\t\t\toccluded_weights = layer_weights.copy()\n\t\t\toccluded_weights[0][:,:,:,j] = 0\n\t\t\toccluded_weights[1][j] = 0\n\n\t\t\tself.model.layers[layer_idx].set_weights(occluded_weights)\t\t\t\n\t\t\tprediction_unshaped_occluded = self.model.predict(self.test_image,batch_size=1, verbose=0) \n\n\t\t\tdice_json['feature'].append(j)\n\t\t\tfor class_ in self.classinfo.keys():\n\t\t\t\tdice_json[class_].append(self.metric(self.gt, prediction_unshaped.argmax(axis = -1), self.classinfo[class_]) - \\\n\t\t\t\t\t \t\tself.metric(self.gt, prediction_unshaped_occluded.argmax(axis = -1), self.classinfo[class_]))\n\n\n\t\tdf = pd.DataFrame(dice_json)\n\t\treturn df\n\n","sub_path":"BioExp/spatial/ablation.py","file_name":"ablation.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"373411515","text":"\"\"\"\n\n源码地址: https://github.com/rmax/scrapy-redis\n\n本笔记包含:\n1.Scrapy-redis配置\n2.Scrapy-redis分布式组件\n3.改造为分布式爬虫\n4.持久化存储\n\n\n\"\"\"\n\n\n###################\n# 1.Scrapy-redis配置\n###################\n\n\"\"\"\n\nwindows下, 进行Redis安装步骤\n\n1.下载程序并解压\n2.修改配置文件, 如果链接服务器为本地, 注释掉\n3.配置环境变量, 管理员方式启动cmd并输入 redis-server即可开启\n\nLinux下\n\n1. sudo vi /etc/redis/redis.conf 注释本地连接, 允许远程链接\n2. sudo redis-server /etc/redis/redis.conf 启动\n\n链接:\n\n主机端: redis-cli\n非主机端: redis-cli -h master_ip\n\n链接后开启分布式爬虫:\n运行分布式爬虫文件 scrapy runspider ****.py\n将起始的url和key扔进队列中:\n\nlpush key(文件中设置) 起始���url\n\n\"\"\"\n\n\n########################\n# 2.Scrapy-redis分布式组件\n########################\n\n\"\"\"\n\n由多台机器来完成一个任务, 从而缩短任务的执行时间\n\n优点在于: 提升速度, 单个节点不稳定不会影响整个任务的执行\n\n分布式组件结合了redis数据库和scrapy框架, 弥补了scrapy框架不能做分布式的缺点\n\nscrapy和scrapy-redis组件区别\n\n scrapy scrapy-redis\nscheduler(调度器): 请求在调度器中执行 将数据放到redis数据库队列中处理\nDuplication Filter\n(重复过滤器): 请求指纹,用python集合 在redis数据库的set中去重\nitempipeline: 决定数据如何处理的中间件 将数据存放到redis数据库队列中\nSpider: 普通的scrapy爬虫类 可以从redis中获取url\n\n\"\"\"\n\n#################\n# 3.改造为分布式爬虫\n#################\n\n\"\"\"\n\n步骤:\n1.导入分布式爬虫类\nfrom scrapy_redis.spiders import RedisSpider\n\n2.修改爬虫的继承\nclass XXXX(RedisSpider)\n\n3.注销allowed_domains和start_urls\n\n4.动态获取允许的域\ndef __init__(self, *args, **kwargs):\n domain = kwargs.pop('domain', '')\n self.allowed_domains = list(filter(None, domain.split(',')))\n super(XXXX, self).__init__(*args, **kwargs)\n\n5.添加redis_key\nredis_key = '随意写值'\n\n6.修改配置文件\n\n(1)# 指定调度器中的重复过滤器使用scrapy_redis的重复过滤器\nDUPEFILTER_CLASS = \"scrapy_redis.dupefilter.RFPDupeFilter\"\n(2)# 指定调度器为scapy_redis中的调度器\nSCHEDULER = \"scrapy_redis.scheduler.Scheduler\"\n(3)# 调度器是否保持任务队列, 开启支持断点续传\nSCHEDULER_PERSIST = True\n\n# SCHEDULER_QUEUE_CLASS = \"scrapy_redis.queue.SpiderPriorityQueue\" # 优先队列, 默认\n# SCHEDULER_QUEUE_CLASS = \"scrapy_redis.queue.SpiderQueue\" # 普通队列\n# SCHEDULER_QUEUE_CLASS = \"scrapy_redis.queue.SpiderStack\" # 栈\n\n(4)ITEM_PIPELINES = {\n # 'XXXX.pipelines.ExamplePipeline': 300,\n # 负责将数据传输到redis数据库中数据队列\n 'scrapy_redis.pipelines.RedisPipeline': 400,\n}\n(5)# 链接数据库\nREDIS_URL = \"redis://172.16.123.128:6379\"\n\n\n\"\"\"\n\n############\n# 4.持久化储存\n############\n\n\"\"\"\n\n将redis中存储的item数据存储到其他数据库中\n\n原因: redis内存数据库, 容量有限, 并且容易丢失数据, 一般存储数据都用MongoDB或者SQL\n\n存入MongoDB中的demo:\n\n\"\"\"\n\nimport redis\nfrom pymongo import MongoClient\nimport json\n\n# 链接redis数据库\nredis_cli = redis.Redis(host='主机ip', port=6379, db=0)\n# 链接mongo\nmongo_cli = MongoClient('127.0.0.1', 27017)\ndb = mongo_cli['xxx']\ncol = db['xx']\n\nwhile 1:\n # 从redis中读取数据\n source, data = redis_cli.blpop(['xxx:items']) # 返回一个元组, 前者为键, 后者为数据\n # 我们想要的数据存在data中, 转成字典存入mongodb\n dict_data = json.loads(data)\n col.insert(dict_data)","sub_path":"python库/Scrapy/Scrapy-redis分布式.py","file_name":"Scrapy-redis分布式.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"447584231","text":"# Linked List, Two Pointers\n\n# Given a singly linked list, determine if it is a palindrome.\n#\n# Example 1:\n#\n# Input: 1->2\n# Output: false\n# Example 2:\n#\n# Input: 1->2->2->1\n# Output: true\n# Follow up:\n# Could you do it in O(n) time and O(1) space?\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if head is None or head.next is None:\n return True\n slow, fast = head, head\n # get the middle element\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next.next\n\n # reverse the first half of the linked list\n p1 = None\n p2 = head\n while p2 != slow:\n p3 = p2.next\n p2.next = p1\n p1 = p2\n p2 = p3\n\n # odd number case\n if fast != None:\n slow = slow.next\n\n # check first half and second half\n while p1 != None and slow != None:\n if p1.val != slow.val:\n return False\n p1 = p1.next\n slow = slow.next\n return True\n","sub_path":"LeetCode/234 Palindrome Linked List.py","file_name":"234 Palindrome Linked List.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"500303695","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import *\nfrom .models import *\n\n# Create your views here.\ndef homm(request,id):\n\n biz = Business.objects.all()\n\n post = Post.objects.filter(hood_id=id)\n\n activ = Activities.objects.all()\n\n post = Post.objects.filter(hood_id=id)\n return render(request, 'home.html', locals())\n\ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('login')\n else:\n form = UserCreationForm()\n\n return render(request,'signup.html',locals())\n\ndef search_business(request):\n \n if 'business' in request.GET and request.GET[\"business\"]:\n search_term = request.GET.get(\"business\")\n searched_business = Business.search_by_name(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html',locals())\n\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',locals())\n\n\ndef hood(request):\n if request.method == 'POST':\n form = NeighbourHoodForm(request.POST,request.FILES)\n\n if form.is_valid():\n form.save()\n return redirect('location')\n else:\n form = NeighbourHoodForm()\n return render(request,'hood.html',locals())\n\ndef location(request):\n post = Post.objects.all()\n hood = NeighbourHood.objects.all()\n return render(request,'location.html')\n\n@login_required\ndef post(request):\n if request.method == 'POST':\n form = MakePostForm(request.POST,request.FILES)\n\n if form.is_valid():\n post=form.save(commit=False)\n post.save()\n return redirect('home',1)\n else:\n form = MakePostForm()\n return render(request,'post.html',locals())\n\n# @login_required\n# def search_business(request):\n\n# if 'business' in request.GET and request.GET[\"business\"]:\n# search_term = request.GET.get(\"business\")\n# searched_business = Business.search_by_business_name(search_term)\n# message = f\"{search_term}\"\n\n# return render(request, 'search.html',locals())\n\n# else:\n# message = \"You haven't searched for any term\"\n# return render(request, 'search.html',locals())\n\ndef profile(request):\n profile=Profile.objects.filter(user_id=request.user)\n \n return render(request, 'profile.html',{'profile':profile})\n\n\ndef update(request):\n all_profile = Profile.objects.all()\n profile = Profile.objects.get(user_id = request.user)\n if request.method == 'POST':\n form = UploadForm(request.POST,request.FILES)\n\n if form.is_valid():\n form.save()\n return redirect('profile')\n else:\n form = ProfileForm()\n\n return render(request,'new_profile.html', locals())\n\n\ndef editprofile(request):\n \n if request.method == 'POST':\n form = ProfileForm(request.POST,request.FILES)\n \n if form.is_valid():\n profile=form.save(commit=False)\n profile.user_id=request.user\n profile.save()\n return redirect('profile',request.user.id)\n else:\n form =ProfileForm()\n \n return render(request,'editprofile.html',locals())\n\n\ndef update_index(request):\n # all_profile = Profile.objects.all()\n profile = UserProfile.objects.get(user_id = request.user)\n if request.method == 'POST':\n form = UploadForm(request.POST,request.FILES)\n\n if form.is_valid():\n form.save()\n return redirect('profile')\n else:\n form = UploadForm()\n\n return render(request,'new.html', locals())\n\ndef biz(request):\n if request.method == 'POST':\n form = BizForm(request.POST,request.FILES)\n\n if form.is_valid():\n form.save()\n return redirect('home',1)\n else:\n form = BizForm()\n return render(request,'business.html',locals())\n\n\ndef activ(request):\n if request.method == 'POST':\n form = ActivForm(request.POST,request.FILES)\n\n if form.is_valid():\n form.save()\n return redirect('home',1)\n else:\n form = ActivForm()\n return render(request,'activities.html',locals())","sub_path":"hoodies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"79846476","text":"from guizero import App, Text, Combo, PushButton, info, TextBox,ButtonGroup\nfrom smbus import SMBus\nfrom time import sleep\nfrom firebase import firebase\naddr = 0x8\nbus = SMBus(1)\nids=[\"13322865231\"]\ndef tobytes(wrd):\n for c in wrd:\n bus.write_byte(addr,ord(c))\n\ndef dets(wrd):\n tobytes(wrd)\n if(wrd==\"id\"):\n x=11\n elif(wrd==\"SOC\"):\n x=5\n sleep(10)\n elif(wrd==\"START\"):\n x=8\n elif(wrd==\"STOP\"):\n x=7\n sleep(3)\n resp=\"\".join(map(chr, bus.read_i2c_block_data(addr,0,x)))\n return resp\n\ndef done():\n stopped=dets(\"STOP\")\n print(stopped)\n print(\"SOC:\"+\"{}\".format(r)+\"%\")\n info(\"Completed\", \" Charged to {}\".format(fs.value)+\"%\")\n fb_id=firebase.FirebaseApplication('https://caas-soc.firebaseio.com/')\n result=fb_id.post(\"https://caas-soc.firebaseio.com/{}\".format(id),{\"Charge Consumed:\":float(fs.value)-float(soc_init)})\n print(result)\n quit()\ndef check():\n global final\n global r\n final=fs.value\n r=float(dets(\"SOC\"))\n print(\"{}\".format(r)+\"%\")\n if(r=float(fs.value)):\n info(\"STATUS\",\"Already charged upto or more than {}\".format(fs.value)+\"%\")\n elif(r>=100):\n info(\"STATUS\", \"Charge Full\")\n done()\n\ndef get_charge(id,soc):\n global soc_final\n global charge\n global fs\n app1.hide()\n app.show()\n model = Text(app, text=\"ID:\"+id, grid=[1, 0], align=\"left\")\n charge=Text(app, text=\"State of charge: \"+\"{}\".format(float(soc))+\"%\",grid=[1,1], align=\"left\")\n final=Text(app,text=\"Desired final SOC:\",grid=[1,2],align=\"left\")\n fs=TextBox(app,grid=[2,2],align=\"left\")\n ch = PushButton(app,command=check, text=\"Charge\", grid=[1,3])\n\ndef do_check():\n if user_in.value == \"caas\":\n if pas_in.value == \"caas\":\n info(\"LOGIN\",\"Successfully logged in\")\n get_charge(id,soc_init)\nid=\"NA\"\nwhile(id not in ids):\n id=dets(\"id\")\n print(id)\nsoc_init=float(dets(\"SOC\"))\napp1 = App(title=\"Coimbatore Charging Station\")\nuser = Text (app1,text=\"Enter your Username\")\nuser_in = TextBox(app1)\npas = Text(app1,text=\"Enter your Password\")\npas_in = TextBox(app1)\nlogin = PushButton(app1,command = do_check,text=\"LOGIN\")\napp = App(title=\"Coimbatore Charging Station\", layout=\"grid\")\napp.hide()\napp1.display()\n\n\n\n\n\n","sub_path":"py_main.py","file_name":"py_main.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"369173860","text":"from flask import (Flask,render_template,\n redirect,url_for,request)\nfrom flask_mail import Mail\nfrom itsdangerous import URLSafeTimedSerializer\nfrom flask.ext.mail import Message\nfrom flask_wtf.csrf import CsrfProtect\nimport os\nimport logging\nimport forms\nimport sys\n\n\n\n\n\n##mail server \nMAIL_SERVER ='smtp.mail.yahoo.com'\nMAIL_PORT =465\nMAIL_USE_TLS = False\nMAIL_USE_SSL = True\n#\nMAIL_USERNAME = \"basuddem\"\nMAIL_PASSWORD = \"qwerasdzx01!\"\n\n\nDEFAULT_MAIL_SENDER = \"basuddem@yahoo.co.uk\"\n\n\nSECRET_KEY = \"tightly_guarded\"\n\n\nDEBUG = True\nPORT = 80\nHOST = \"127.0.0.1\"\n\n##create the app\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nmail = Mail(app)\nCsrfProtect(app)\n#add a secret key since we be using sessions(for cryptographic signing of cookies)\napp.secret_key = os.urandom(24)\n##app.config['SECRET_KEY']\nts = URLSafeTimedSerializer(app.secret_key)\n\n\n\n##add the route to the registration form,\n##takes two methods post and get(able to load the view,\n##so they can see the form and\n##also post back to process the fom\n@app.route('/',methods=('GET','POST'))\ndef index():\n\n \n form = forms.Form()\n \n ##check if the form is submitted and valid\n if form.validate_on_submit():\n ##redirect user to the main page\n ##abstract form data\n name = form.name.data\n email = form.email.data\n phone_number = form.phone_number.data\n budget = form.budget.data\n choice = form.myField.data\n post = form.post.data\n \n subject = \"client information\"\n html = render_template(\n 'information.html',name = name, email= email ,phone_number = phone_number,\n budget = budget , choice = choice , post = post)\n msg = Message(\n subject= subject,\n recipients=['basuddem@yahoo.co.uk'],\n sender =DEFAULT_MAIL_SENDER,\n html=html\n )\n mail.send(msg)\n return redirect(url_for(\"index\"))\n ##if we don't redirect then\n return render_template(\"index.html\",form=form)\n\n@app.route('/index_fr',methods=('GET','POST'))\ndef index_fr():\n\n \n form = forms.Form()\n \n ##check if the form is submitted and valid\n if form.validate_on_submit():\n ##redirect user to the main page\n ##abstract form data\n name = form.name.data\n email = form.email.data\n phone_number = form.phone_number.data\n budget = form.budget.data\n choice = form.myField.data\n post = form.post.data\n \n subject = \"client information\"\n html = render_template(\n 'information.html',name = name, email= email ,phone_number = phone_number,\n budget = budget , choice = choice , post = post)\n msg = Message(\n subject= subject,\n recipients=['basuddem@yahoo.co.uk'],\n sender =DEFAULT_MAIL_SENDER,\n html=html\n )\n mail.send(msg)\n return redirect(url_for(\"index\"))\n ##if we don't redirect then\n return render_template(\"index_fr.html\",form=form)\n\n@app.route(\"/Team\",methods=('GET','POST'))\ndef team():\n form = forms.Form()\n \n ##check if the form is submitted and valid\n if form.validate_on_submit():\n ##redirect user to the main page\n subject = \"client information\"\n html = render_template(\n 'information.html')\n msg = Message(\n subject,\n recipients='basuddem@yahoo.co.uk',\n sender =DEFAULT_MAIL_SENDER,\n html=html\n )\n mail.send(msg)\n return redirect(url_for(\"team\"))\n ##if we don't redirect then\n return render_template(\"team.html\",form=form)\n \n\n\n@app.route(\"/address\",methods=('GET','POST'))\ndef address():\n form = forms.Form()\n \n ##check if the form is submitted and valid\n if form.validate_on_submit():\n ##redirect user to the main page\n subject = \"client information\"\n html = render_template(\n 'information.html')\n msg = Message(\n subject,\n recipients='basuddem@yahoo.co.uk',\n sender = DEFAULT_MAIL_SENDER,\n html=html\n )\n mail.send(msg)\n return redirect(url_for(\"address\"))\n return render_template(\"address.html\",form=form)\n\n\napp.logger.addHandler(logging.StreamHandler(sys.stdout))\napp.logger.setLevel(logging.ERROR) \n\nif __name__ == '__main__':\n ##initialize the models\n \n app.run(debug=DEBUG,host=HOST,port=PORT)\n \n \n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"446386926","text":"'''\n#模块:hashlib\n大纲:加密说明、加密算法、加密步骤\n加密说明:\n 1.该加密模块加密后的内容不可解密\n 2.用法:存储密码,用户每次输入密码后,都进行加密操作,在与数据库加密内容进行比对验证\n加密算法:\n md5 sha256\n加密步骤:\n 1.m = hashlib.md5() #获取加密算法对象\n 2.m.update(bytes类型) #加密数据\n 3.value = m.hexdigest() #获取加密后数据\n'''\nimport hashlib\nm = hashlib.md5()\n#m = hashlib.sha256()\nm.update(\"你好\".encode(\"utf8\"))\n#print(m.hexdigest())\nvalue = m.hexdigest()\nprint(value)","sub_path":"03常用模块整理/07hashlib模块.py","file_name":"07hashlib模块.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"635978674","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom luckycommon.utils.decorator import sql_wrapper\nfrom luckycommon.model.iap_receipt import IAPReceipt, IAPInvalidReceipt\nfrom luckycommon.model import orm\n\n@sql_wrapper\ndef get_receipt_by_transaction_id(transaction_id):\n return IAPReceipt.query.filter(IAPReceipt.id == transaction_id).first()\n\n@sql_wrapper\ndef get_invalid_receipt_by_hash_text(text):\n return IAPInvalidReceipt.query.filter(IAPInvalidReceipt.id == text).first()\n\n\n\nSTATUS_CODE_DESCRIPTION= {\n # App Store status code\n '21000': 'The App Store could not read the JSON object you provided.',\n '21002': 'The data in the receipt-data property was malformed or missing.',\n '21003': 'The receipt could not be authenticated.',\n '21004': '''The shared secret you provided does not match the shared secret on file for your account.\nOnly returned for iOS 6 style transaction receipts for auto-renewable subscriptions.''',\n '21005': 'The receipt server is not currently available.',\n '21006': '''This receipt is valid but the subscription has expired. When this status code\nis returned to your server, the receipt data is also decoded and returned as\npart of the response. Only returned for iOS 6 style transaction receipts for\nauto-renewable subscriptions.''',\n '21007': '''This receipt is from the test environment, but it was sent to the production\nenvironment for verification. Send it to the test environment instead.''',\n '21008': '''This receipt is from the production environment, but it was sent to the test\nenvironment for verification. Send it to the production environment instead.''',\n # Custom status code\n '30000': 'bundle id not match.',\n '30001': 'production id not match',\n}\n\n\n@sql_wrapper\ndef save_receipt(user_id, pay_id,receipt_data, result_info):\n iap_receipt = IAPReceipt()\n in_app = result_info['receipt']['in_app'][0]\n transaction_id = in_app['transaction_id']\n product_id = in_app['product_id']\n env = result_info.get(\"environment\", \"production\")\n iap_receipt.id = transaction_id\n iap_receipt.user_id = user_id\n iap_receipt.pay_id = pay_id\n iap_receipt.receipt = receipt_data\n iap_receipt.receipt_info = str(result_info)\n iap_receipt.product_id = product_id\n iap_receipt.environment = env\n iap_receipt.provide_status = 0\n iap_receipt.updated_at = datetime.utcnow()\n iap_receipt.save()\n\n\n@sql_wrapper\ndef save_invalid_receipt(hash_text, receipt_data, status_code):\n iap_invalid_receipt = IAPInvalidReceipt()\n iap_invalid_receipt.id = hash_text\n iap_invalid_receipt.receipt = receipt_data\n iap_invalid_receipt.status = status_code\n iap_invalid_receipt.extend = STATUS_CODE_DESCRIPTION.get(str(status_code), 'Other reasons')\n iap_invalid_receipt.updated_at = datetime.utcnow()\n iap_invalid_receipt.save()\n\n\n@sql_wrapper\ndef update_receipt_provide_success(transaction_id):\n res = IAPReceipt.query.filter(IAPReceipt.id == transaction_id).filter(IAPReceipt.provide_status == 0).update(\n {\n 'provide_status': 1,\n 'updated_at': datetime.utcnow()\n }\n )\n if res:\n orm.session.commit()\n return True\n else:\n res = IAPReceipt.query.filter(IAPReceipt.id == transaction_id).filter(IAPReceipt.provide_status == 2).update(\n {\n 'provide_status': 1,\n 'updated_at': datetime.utcnow()\n }\n )\n if res:\n orm.session.commit()\n return True\n else:\n return False\n\n\n@sql_wrapper\ndef update_receipt_provide_fail(transaction_id):\n res = IAPReceipt.query.filter(IAPReceipt.id == transaction_id).filter(IAPReceipt.provide_status == 0).update(\n {\n 'provide_status': 2,\n 'updated_at': datetime.utcnow()\n }\n )\n if res:\n orm.session.commit()\n return True\n else:\n return False\n\n\n\n\n\n\n","sub_path":"luckycommon/db/iap_receipt.py","file_name":"iap_receipt.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"200084704","text":"import sys\r\nfrom PIL.ImageQt import ImageQt\r\nfrom PIL import Image\r\nfrom PyQt5.QtGui import QPixmap\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import QLabel, QApplication, QWidget, QScrollArea, QGridLayout\r\n\r\nfrom a3d_class import *\r\n\r\n\r\nclass Window(QScrollArea):\r\n def __init__(self, filenames):\r\n super(Window, self).__init__()\r\n self.row = 0\r\n widget = QWidget()\r\n self.layout = QGridLayout(widget)\r\n self.layout.setAlignment(Qt.AlignTop)\r\n self.populate(filenames)\r\n self.setWidget(widget)\r\n self.setWidgetResizable(True)\r\n self.show()\r\n\r\n def append_row(self, name, value):\r\n label1 = QLabel(name)\r\n self.layout.addWidget(label1, self.row, 0)\r\n if type(value) == str:\r\n label2 = QLabel(value)\r\n self.layout.addWidget(label2, self.row, 1)\r\n elif type(value) == Image.Image:\r\n label2 = QLabel(\"\")\r\n image_qt = ImageQt(value)\r\n pixmap = QPixmap.fromImage(image_qt)\r\n pixmap.detach()\r\n # https://stackoverflow.com/questions/35204123/python-pyqt-pixmap-update-crashes\r\n label2.setPixmap(pixmap)\r\n self.layout.addWidget(label2, self.row, 1)\r\n else:\r\n raise ValueError()\r\n self.row += 1\r\n\r\n def populate(self, filenames):\r\n pages = []\r\n for filename in filenames:\r\n print('loading: %s' % filename)\r\n page = ScenarioPage.open(filename)\r\n pages.append(page)\r\n\r\n print('processing...')\r\n scenario = Scenario.frompages(*pages)\r\n\r\n author = str(scenario.body.author)\r\n title = str(scenario.header.title)\r\n filename = f\"{author}_{title}.dat\"\r\n with open(filename, mode=\"wb\") as f:\r\n f.write(scenario.body)\r\n\r\n self.append_row(\"作者名\", str(scenario.body.author))\r\n self.append_row(\"シナリオ名\", str(scenario.header.title))\r\n self.append_row(\"シナリオ説明文\", str(scenario.header.description))\r\n\r\n # height map\r\n height_map_im = scenario.body.height_map.to_image()\r\n self.append_row(\"Height map\", height_map_im)\r\n\r\n # building?\r\n building_map_im = scenario.body.building_map.to_image()\r\n self.append_row(\"Building map?\", building_map_im)\r\n\r\n # layers?\r\n for i in range(len(scenario.body.layers)):\r\n name = \"Layer \" + str(i).zfill(2)\r\n layer_im = scenario.body.layers[i].to_image()\r\n self.append_row(name, layer_im)\r\n\r\n # area name\r\n for i in range(len(scenario.body.areas)):\r\n name = \"地名 \" + str(i).zfill(2)\r\n area = scenario.body.areas[i]\r\n self.append_row(name, str(area.name))\r\n\r\n # scene\r\n for i in range(40):\r\n for j in range(50):\r\n mes_struct = scenario.body.messages[i][j]\r\n data = mes_struct.data\r\n if len(data) > 0 and data[0] != ord('%'):\r\n mes = str(mes_struct)\r\n self.append_row(\"シーン %02d, %02d\" % (i+1, j), mes)\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n main = Window(sys.argv[1:])\r\n sys.exit(app.exec_())\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"236535828","text":"import asyncio\nimport click\n\n@click.group(\"lw\", short_help=\"Light Wallet\")\ndef lw_cmd():\n \"\"\"Accounting functions without synching the wallet\"\"\"\n\n@lw_cmd.command(\"show\", short_help=\"Show the summary wallet balances for all configured keys. Good luck approach for first 500 puzzle hashes.\")\n@click.option(\n \"--puzzle-search\",\n \"-p\",\n default=500,\n help=\"Enter the amount of puzzle hashes to search for.\",\n type=int,\n required=True,\n)\n@click.option(\n \"--show-csv\",\n help=\"Show all transactions for all configured keys.\",\n default=False,\n show_default=True,\n is_flag=True\n)\n@click.pass_context\ndef show_cmd(ctx: click.Context, puzzle_search: int, show_csv: bool):\n from .lw_funcs import show_balance_summary, show_csv_export\n from pathlib import Path\n\n root_path: Path = ctx.obj[\"root_path\"]\n\n loop = asyncio.get_event_loop()\n try:\n if show_csv:\n loop.run_until_complete(show_csv_export(root_path, puzzle_search))\n else:\n loop.run_until_complete(show_balance_summary(root_path, puzzle_search))\n finally:\n loop.close()\n\n","sub_path":"chia/cmds/lw.py","file_name":"lw.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603556701","text":"#-*- coding: utf-8 -*-\nfrom typing import List\nimport math\n\nimport time\ndef timeit(func):\n def wrapped(*args, **kwargs):\n start = time.time()\n ret = func(*args, **kwargs)\n elapsed = time.time() - start\n print(\"elapsed: %s\" % elapsed)\n return ret\n return wrapped\n\nclass Solution:\n # @param n, an integer\n # @return an integer\n def reverseBits(self, n):\n x = n\n ans = 0\n for i in range(32):\n ans |= ((x & 1) << (31 - i))\n x >>= 1\n return ans\n\n\n\n\nsamples = [\n # 1958pm start\n (43261596, 964176192),\n (4294967293, 3221225471),\n]\n\n# for s, t, expected in samples:\n# ans = Solution().isAnagram(s, t)\n# print(ans)\n\nfor S, expected in samples:\n ans = Solution().reverseBits(S)\n print(ans)\n","sub_path":"lc/esy/20190923_esy_190_reverse_bits.py","file_name":"20190923_esy_190_reverse_bits.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604768480","text":"from metaknight.piece import PieceType, Piece, Color\nfrom metaknight.square import Square\nfrom typing import List\n\n\nclass Board:\n def __init__(self):\n self.squares: List[List[Square]] = [[Square(file + rank) for file in Square.files] for rank in Square.ranks]\n self.set_up()\n\n def __repr__(self):\n return self.board_as_str(Color.WHITE)\n\n def board_as_str(self, perspective: Color):\n \"\"\"\n Prints the current state of the board\n :param perspective: prints from either white's perspective or black's perspective\n :return: string representation of the current board state\n \"\"\"\n output = ''\n if perspective is Color.WHITE:\n for rank in range(7, -1, -1):\n for file in range(0, 8):\n piece = self.squares[rank][file].piece\n if piece:\n output += f'{repr(piece)} '\n else:\n output += '. '\n output += '\\n'\n if perspective is Color.BLACK:\n for rank in range(0, 8):\n for file in range(7, -1, -1):\n piece = self.squares[rank][file].piece\n if piece:\n output += f'{repr(piece)} '\n else:\n output += '. '\n output += '\\n'\n return output[:-1] # This removes the last \\n character\n\n def clear(self):\n \"\"\" This method will only be used for debugging purposes\n \"\"\"\n self.squares = [[Square(file + rank) for file in Square.files] for rank in Square.ranks]\n\n def set_board_state(self, board_state: List[str]):\n \"\"\"\n Sets self.squares to the format given by board_state\n :param board_state: the pieces on each square\n \"\"\"\n self.clear()\n for i in range(0, 8):\n for j in range(0, 8):\n piece = board_state[i][j]\n if piece == '.':\n piece = None\n elif piece == 'p':\n piece = Piece(PieceType.PAWN, Color.WHITE)\n elif piece == 'n':\n piece = Piece(PieceType.KNIGHT, Color.WHITE)\n elif piece == 'b':\n piece = Piece(PieceType.BISHOP, Color.WHITE)\n elif piece == 'r':\n piece = Piece(PieceType.ROOK, Color.WHITE)\n elif piece == 'q':\n piece = Piece(PieceType.QUEEN, Color.WHITE)\n elif piece == 'k':\n piece = Piece(PieceType.KING, Color.WHITE)\n elif piece == 'P':\n piece = Piece(PieceType.PAWN, Color.BLACK)\n elif piece == 'N':\n piece = Piece(PieceType.KNIGHT, Color.BLACK)\n elif piece == 'B':\n piece = Piece(PieceType.BISHOP, Color.BLACK)\n elif piece == 'R':\n piece = Piece(PieceType.ROOK, Color.BLACK)\n elif piece == 'Q':\n piece = Piece(PieceType.QUEEN, Color.BLACK)\n elif piece == 'K':\n piece = Piece(PieceType.KING, Color.BLACK)\n self.squares[7-i][j].piece = piece\n\n def set_up(self):\n # Pawns\n for i in range(8):\n self.squares[1][i].piece = Piece(PieceType.PAWN, Color.WHITE)\n self.squares[6][i].piece = Piece(PieceType.PAWN, Color.BLACK)\n\n # Rooks\n for i in (0, 7):\n self.squares[0][i].piece = Piece(PieceType.ROOK, Color.WHITE)\n self.squares[7][i].piece = Piece(PieceType.ROOK, Color.BLACK)\n\n # Knights\n for i in (1, 6):\n self.squares[0][i].piece = Piece(PieceType.KNIGHT, Color.WHITE)\n self.squares[7][i].piece = Piece(PieceType.KNIGHT, Color.BLACK)\n\n # Bishops\n for i in (2, 5):\n self.squares[0][i].piece = Piece(PieceType.BISHOP, Color.WHITE)\n self.squares[7][i].piece = Piece(PieceType.BISHOP, Color.BLACK)\n\n # Kings and queens\n self.squares[0][3].piece = Piece(PieceType.QUEEN, Color.WHITE)\n self.squares[0][4].piece = Piece(PieceType.KING, Color.WHITE)\n self.squares[7][3].piece = Piece(PieceType.QUEEN, Color.BLACK)\n self.squares[7][4].piece = Piece(PieceType.KING, Color.BLACK)\n\n def get_square(self, location=None, square=None) -> Square:\n \"\"\"\n :param location: string coordinates of a square. For example: 'a3' or 'c8'\n :param square: a square object that is not located in this board\n :return: the square at location in this board\n \"\"\"\n if location == '00' or square == Square('00'):\n return Square('00')\n\n if location:\n file = Square.files.index(location[0])\n rank = Square.ranks.index(location[1])\n elif square:\n file = Square.files.index(square.file)\n rank = Square.ranks.index(square.rank)\n else:\n raise ValueError('Must enter either a string location, or a Square object')\n return self.squares[rank][file]\n\n def get_moves(self, location=None, square=None) -> List[List[Square]]:\n square = self.get_square(location=location, square=square)\n if square.piece.piece_type is PieceType.PAWN:\n return self._pawn_moves(square=square)\n elif square.piece.piece_type is PieceType.KNIGHT:\n return self._knight_moves(square=square)\n elif square.piece.piece_type is PieceType.BISHOP:\n return self._bishop_moves(square=square)\n elif square.piece.piece_type is PieceType.ROOK:\n return self._rook_moves(square=square)\n elif square.piece.piece_type is PieceType.QUEEN:\n return self._queen_moves(square=square)\n elif square.piece.piece_type is PieceType.KING:\n return self._king_moves(square=square)\n\n def _pawn_moves(self, square: Square) -> List[List[Square]]:\n moves = []\n square = self.get_square(square=square)\n color = square.piece.color\n forward = Square.up\n rank = '2'\n if square.piece.color is Color.BLACK:\n forward = Square.down\n rank = '7'\n\n forward_square = self.get_square(square=forward(square))\n if forward_square.piece is None:\n moves.append([forward_square])\n forward_square = self.get_square(square=forward(forward_square))\n if square.rank == rank and forward_square.piece is None:\n moves[0].append(forward_square)\n if square.file != 'a':\n diagonal = self.get_square(square=forward(square).left())\n if diagonal.piece and diagonal.piece.color is not color:\n moves.append([diagonal])\n if square.file != 'h':\n diagonal = self.get_square(square=forward(square).right())\n if diagonal.piece and diagonal.piece.color is not color:\n moves.append([diagonal])\n return moves\n\n def _knight_moves(self, square: Square) -> List[List[Square]]:\n original = self.get_square(square=square)\n color = original.piece.color\n moves = [\n self.get_square(square=original.up().up().left()),\n self.get_square(square=original.up().up().right()),\n self.get_square(square=original.down().down().left()),\n self.get_square(square=original.down().down().right()),\n self.get_square(square=original.left().left().up()),\n self.get_square(square=original.left().left().down()),\n self.get_square(square=original.right().right().up()),\n self.get_square(square=original.right().right().down())\n ]\n possible_moves = []\n for move in moves:\n if move != Square('00') and (not move.piece or move.piece.color is not color):\n possible_moves.append([move])\n return possible_moves\n\n def _bishop_moves(self, square: Square) -> List[List[Square]]:\n moves = []\n original = self.get_square(square=square)\n color = original.piece.color\n for func1 in (Square.up, Square.down):\n for func2 in (Square.left, Square.right):\n diagonal = []\n square = original\n while True:\n square = self.get_square(square=func2(func1(square)))\n if square == Square('00'):\n break\n if not square.piece and square != Square('00'):\n diagonal.append(square)\n elif square.piece.color is not color:\n diagonal.append(square)\n break\n else:\n break\n if len(diagonal) >= 1:\n moves.append(diagonal.copy())\n return moves\n\n def _rook_moves(self, square: Square) -> List[List[Square]]:\n moves = []\n original = self.get_square(square=square)\n color = original.piece.color\n for func in (Square.up, Square.down, Square.left, Square.right):\n line = []\n square = original\n while True:\n square = self.get_square(square=func(square))\n if square == Square('00'):\n break\n if not square.piece and square != Square('00'):\n line.append(square)\n elif square.piece.color is not color:\n line.append(square)\n break\n else:\n break\n if len(line) >= 1:\n moves.append(line.copy())\n return moves\n\n def _queen_moves(self, square: Square) -> List[List[Square]]:\n return self._rook_moves(square) + self._bishop_moves(square)\n\n def _king_moves(self, square: Square) -> List[List[Square]]:\n original = self.get_square(square=square)\n color = original.piece.color\n moves = [\n self.get_square(square=original.up().left()),\n self.get_square(square=original.up()),\n self.get_square(square=original.up().right()),\n self.get_square(square=original.right()),\n self.get_square(square=original.right().down()),\n self.get_square(square=original.down()),\n self.get_square(square=original.down().left()),\n self.get_square(square=original.left())\n ]\n possible_moves = []\n for move in moves:\n if move != Square('00') and (not move.piece or move.piece.color is not color):\n possible_moves.append([move])\n return possible_moves\n\n def in_check(self, color: Color) -> bool:\n \"\"\"\n Checks if the king of the specified color is in check\n :param color: the color of the king under inspection\n :return: true if the king is in check, of the specified color\n \"\"\"\n king_location: Square = None\n for row in self.squares:\n for square in row:\n if square.piece == Piece(PieceType.KING, color):\n king_location = square\n break\n\n for row in self.squares:\n for square in row:\n if square.piece and square.piece.color != color:\n # The piece on this square is of the opposite color, and could possible pose a check\n moves = self.get_moves(square=square)\n for direction in moves:\n for move in direction:\n if move == king_location:\n return True\n return False\n\n def evaluate(self) -> float:\n \"\"\"\n returns index representing what player is doing better. Negative number for black and positive for white\n 1 point indicates a pawn, so if evaluate() returns -2, black is 2 pawns ahead\n certain tactics will be used in this function, for example pins and doubled pawns\n \"\"\"\n # TODO: finish\n return self.evaluate_by_material()\n\n def evaluate_by_material(self) -> float:\n \"\"\"\n returns index representing what player is ahead in material using the standard value for pieces\n \"\"\"\n index: float = 0\n for row in self.squares:\n for square in row:\n if square.piece:\n color = 1 if square.piece.color is Color.WHITE else -1\n if square.piece.piece_type == PieceType.PAWN:\n index += color * 1\n elif square.piece.piece_type == PieceType.KNIGHT:\n index += color * 3\n elif square.piece.piece_type == PieceType.BISHOP:\n index += color * 3\n elif square.piece.piece_type == PieceType.ROOK:\n index += color * 5\n elif square.piece.piece_type == PieceType.QUEEN:\n index += color * 9\n return index\n\n\n","sub_path":"metaknight/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":13084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"220222032","text":"\"\"\"\n> Understanding the question..\nWe are trying to find continuous sub segments.\nminimum number of zeroes to erase to make it continuous sub-segments\n\"\"\"\n\nfrom collections import deque\n\ndef count_minimum(strs):\n if strs.count('1') == 0:\n return 0\n\n idx = strs.find('1')\n ns = strs[idx:]\n q = deque(ns)\n cnt = 0\n\n while q:\n ch = q.popleft()\n if ch == '0' and q.count('1') > 0:\n cnt += 1\n return cnt\n\n\nif __name__ == '__main__':\n t = int(input())\n while t:\n string = input()\n result = count_minimum(string)\n print(result)\n t -= 1","sub_path":"contests/1303A-Erazing-Zeroes.py","file_name":"1303A-Erazing-Zeroes.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"619757678","text":"from collections import abc, namedtuple\n\n\nclass _Type:\n fields = tuple()\n\n def __init__(self, **kwargs):\n for f in self.fields:\n if type(f) is str:\n setattr(self, f, kwargs.get(f, None))\n elif type(f) is tuple:\n setattr(self, f[1], kwargs.get(f[0], None))\n\n\nclass Response(_Type):\n fields = (\"status\", \"version\")\n\n def __init__(self, data, **kwargs):\n self.data = data\n\n for f in self.fields:\n setattr(self, f, kwargs.get(f, None))\n\n def pretty(self):\n return self.status\n\n\nclass MusicFolders(list):\n def pretty(self):\n print(\"\\n\".join([f\"{e.id}\\t{e.name}\" for e in self]))\n\n\nclass Album(_Type):\n fields = (\n \"id\",\n \"name\",\n \"artist\",\n \"artistId\",\n \"coverArt\",\n \"created\",\n \"duration\",\n \"songCount\",\n (\"song\", \"tracks\"),\n )\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n s = f\"\"\"Name: {self.name}\nID: {self.id}\n\nTracks\n\"\"\"\n return s + \"\\n\".join([t.pretty() for t in self.tracks])\n\n\nclass Artist(_Type):\n fields = (\"id\", \"name\", (\"album\", \"albums\"))\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n s = f\"\"\"Name: {self.name}\nID: {self.id}\n\nAlbums\n\"\"\"\n return s + \"\\n\".join([a.pretty() for a in self.albums])\n\n\nclass ArtistAlbum(_Type):\n fields = (\n \"id\",\n \"name\",\n \"artist\",\n \"artistId\",\n \"coverArt\",\n \"created\",\n \"duration\",\n \"songCount\",\n )\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n return f\"{self.id}\\t{self.name}\\t{self.artist}\\t{self.created}\"\n\n\nclass Genres(list):\n def pretty(self):\n return \"\\n\".join(self)\n\n\nclass Indexes(list):\n def pretty(self):\n return \"\\n\".join(\n [f\"{i.name}\\t{a.id}\\t{a.name}\" for i in self for a in i.artists]\n )\n\n\nclass MusicDirectory(_Type):\n fields = (\"id\", \"name\", \"parent\", (\"child\", \"children\"))\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n s = f\"\"\"Name: {self.name}\nID: {self.id}\nParent ID: {self.parent}\n\nContents\n\"\"\"\n\n return s + \"\\n\".join([c.pretty() for c in self.children])\n\n\nclass Child(_Type):\n fields = (\"id\", \"title\", \"parent\", \"isDir\", \"isVideo\", \"album\", \"artist\", \"created\")\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n\nclass Subdirectory(Child):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n return f\"Subdir\\t{self.id}\\t{self.title}\\t{self.parent}\\t{self.album}\\t{self.artist}\\t{self.created}\"\n\n\nclass Track(Child):\n fields = (\n \"album\",\n \"albumId\",\n \"artist\",\n \"artistId\",\n \"bitRate\",\n \"contentType\",\n \"coverArt\",\n \"created\",\n \"discNumber\",\n \"duration\",\n \"genre\",\n \"id\",\n \"isDir\",\n \"isVideo\",\n \"parent\",\n \"path\",\n \"size\",\n \"suffix\",\n \"title\",\n \"track\",\n \"type\",\n \"year\",\n )\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def pretty(self):\n return f\"Track\\t{self.id}\\t{self.title}\\t{self.parent}\\t{self.album}\\t{self.artist}\\t{self.created}\"\n\n\nIdName = namedtuple(\"IdName\", (\"id\", \"name\"))\nIndex = namedtuple(\"Index\", (\"name\", \"artists\"))\n","sub_path":"subsonic_client/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":3501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"348183501","text":"#\n# example of an acceptance test for a command-line app\n#\n\nimport os\n\nPROGRAM = '../mobydick/word_counter.py'\nTEXT_FILE = '../test_data/mobydick_summary.txt'\nOUTPUT = 'out.tmp'\n\nclass TestWordCounterAcceptanceTests:\n\n def test_commandline(self):\n \"\"\"Count words in a short text\"\"\"\n # remove output file if it is already there\n if os.path.exists(OUTPUT):\n os.remove(OUTPUT)\n\n # run the command line app\n cmd = 'python %s %s white > %s' % (PROGRAM, TEXT_FILE, OUTPUT)\n os.system(cmd)\n \n # check the output\n out = open(OUTPUT).read()\n self.assertTrue('white:\\t2' in out)\n\n","sub_path":"test/test_acceptance.py","file_name":"test_acceptance.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"488712257","text":"import sys\nimport hashlib\nimport base64\nimport json\n\nfrom PyQt4.QtGui import *\n\nimport merkle\nimport hbss_utilities\n\n\nclass QuantumSignatureGUI(QMainWindow):\n width = 380\n height = 200\n \n def __init__(self, parent=None):\n super(QuantumSignatureGUI, self).__init__(parent)\n self.init_ui()\n\n def init_ui(self):\n self.setFixedSize(self.width, self.height)\n self.setWindowTitle(\"Quantum Subscriber\")\n\n # Sign label\n userLabel = QLabel(self)\n userLabel.move(20, 15)\n userLabel.setText('File to SIGN:')\n # Sign textbox\n self.fileTextbox = QLineEdit(self)\n self.fileTextbox.move(20, 45)\n self.fileTextbox.resize(self.width - 40, 20)\n # Browse button\n buttonBrowse = QPushButton('Browse', self)\n buttonBrowse.move(20, 100)\n buttonBrowse.clicked.connect(self.browse_click)\n # Sign button\n buttonSign = QPushButton('Sign', self)\n buttonSign.move(260, 100)\n buttonSign.clicked.connect(self.sign_click)\n\n def browse_click(self):\n filename = QFileDialog.getOpenFileName(self, 'Open File', '/')\n self.fileTextbox.setText(filename)\n\n def sign_click(self):\n fname = self.fileTextbox.text()\n\n hashFromFile = hbss_utilities.calculate_hash_from_file(open(fname, 'rb'),\n hashlib.sha512())\n\n mytree = merkle.MerkleTree(4)\n publicKey = str(base64.b64encode(mytree.tree_public_key()),'utf-8')\n dictofPK = {}\n dictofPK[\"public_key: \"] = publicKey\n\n mysig = mytree._sign_message(hashFromFile)\n mysig.update(dictofPK)\n\n with open(\"signature.sig\",mode='w') as SigOut:\n SigOut.write(json.dumps(mysig, indent=2))\n\n finalMessage = QMessageBox(self)\n finalMessage.information(self,\n \"Message\",\n \"File was signed and signature was saved into \\\"signature.sig\\\"\")\n # print(\"Sprava bola podpisana\")\n\n\ndef main():\n app = QApplication(sys.argv)\n myApp = QuantumSignatureGUI()\n myApp.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hbss.pyw","file_name":"hbss.pyw","file_ext":"pyw","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"191744260","text":"#!/usr/bin/python3\n\nimport argparse\nimport urllib.request\nimport json\nimport datetime\nimport requests\nfrom time import sleep\n\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlencode\nfrom collections import OrderedDict\nfrom get_url import parse_property_page, parse_property_page_sr, property_filepath, property_filepath_sr\nfrom slackclient import SlackClient\nimport trolly\n\nimport re\n\n\ndef mdlinks(text):\n return re.sub(r'\\<(.+?)\\|(.+?)\\>', r'[\\2](\\1)', text)\n\n\ndef create_card(title, description):\n description = mdlinks(description)\n description = description.replace(\"*\", \"**\")\n c2 = l2.add_card({'name': title, \"desc\": description})\n\n\nimport os\n\nwith open(os.path.join(os.path.dirname(os.path.realpath(__file__)),\n \"config.json\")) as f:\n config = json.load(f)\n sc_token = config[\"slack_token\"]\n tr_token = config[\"trello_token\"]\n tr_key = config[\"trello_key\"]\n tr_board = config[\"trello_board\"]\n work_addr1 = config[\"work_addr1\"]\n work_addr2 = config[\"work_addr2\"]\n radius = config.get(\"radius\", 20)\n areas = [work_addr1, work_addr2]\n # searchid1 = config[\"sr_searchid1\"]\n # searchid2 = config.get(\"sr_searchid2\", None)\n # searchids = [searchid1, searchid2]\n max_value = config.get(\"max_value\", 1500)\n min_value = config.get(\"min_value\", 1000)\n avail_from = config.get(\"avail_from\", datetime.datetime.today())\n avail_from = datetime.datetime.strptime(avail_from, \"%Y-%m-%d\") if not isinstance(avail_from, datetime.datetime) else avail_from\n delta = datetime.timedelta(days=config.get(\"delta_days\", 30))\n\nsc = SlackClient(sc_token)\n\nclient = trolly.client.Client(tr_key, tr_token)\nb2 = client.get_board(tr_board) # househunting\nb2.update_board()\nl2 = [_ for _ in b2.get_lists()][0] # first list on the left\nl2.update_list()\n\n\ndef directions_link(prop):\n def maps_link(start_addr, end_addr):\n query_string = urlencode(\n OrderedDict(f=\"d\",\n saddr=start_addr,\n daddr=end_addr,\n dirflg=\"r\"))\n\n return \"http://maps.google.co.uk/?%s\" % query_string\n\n if 'latlong' in prop:\n start_addr = prop[\"latlong\"]\n else:\n start_addr = \",\".join(prop['title'].split(\",\")[1:])\n\n return \"*Directions* 1: <{}|to {}> and 2: <{}|to {}>\".format(\n maps_link(start_addr, work_addr1), work_addr1,\n maps_link(start_addr, work_addr2), work_addr2)\n\n\ndef links_filepath():\n outdir = os.path.dirname(os.path.realpath(__file__))\n return os.path.join(outdir, 'links.json')\n\n\ndef should_notify(prop):\n price = prop['price']\n title = prop['title']\n desc = prop['description']\n epc = prop['EPC']\n try:\n av = datetime.datetime.strptime(prop['available_from'], '%Y-%m-%d')\n except ValueError:\n av = datetime.datetime.today()\n\n if price > max_value:\n return False, \"too expensive: {} > {}\".format(price, max_value)\n if price < min_value:\n return False, \"too cheap: {} < {}\".format(price, min_value)\n\n if \"Note: This OpenRent Property Is No Longer Available For Rent\" in desc:\n return False, \"already let\"\n\n # if \"studio\" in desc.lower():\n # return False, \"studio\"\n\n # if \"studio\" in title.lower():\n # return False, \"studio\"\n\n if \"shared flat\" in desc.lower():\n return False, \"shared flat\"\n\n if \"shared flat\" in title.lower():\n return False, \"shared flat\"\n\n if epc and (epc.upper() in list(\"EFG\")):\n return False, \"EPC is too low: {}\".format(epc.upper())\n\n if av < avail_from:\n return False, \"Available date ({:%Y-%m-%d}) is too early\".format(av)\n if av > avail_from + delta:\n return False, \"Available date ({:%Y-%m-%d}) is too late\".format(av)\n\n return True, \"\"\n\n\ndef notify(property_id):\n print(\"Notifying about %s...\" % property_id)\n\n def make_link(property_id):\n return (\"https://www.openrent.co.uk/%s\" % property_id)\n\n sc.api_call(\"api.test\")\n sc.api_call(\"channels.info\", channel=\"1234567890\")\n\n with open(property_filepath(property_id)) as f:\n prop = json.load(f)\n\n should_notify_, reason = should_notify(prop)\n if not should_notify_:\n print(\"Skipping notification: %s...\" % reason)\n return\n\n if not len(prop['location']) > 0:\n prop['location'].append(['unknown'] * 2)\n text = (\"<{link}|{title}> close to {location} ({walk_duration}):\\n\"\n \"*Price:* {price}. *Available from:* {av}. *EPC:* {epc}. {has_garden}\\n\"\n \"{directions}.\\n*Description:*\\n{desc}\").format(\n location=prop['location'][0][0],\n walk_duration=prop['location'][0][1],\n link=make_link(property_id),\n price=prop['price'],\n desc=prop['description'][:1000],\n av=prop['available_from'],\n title=prop['title'],\n epc=prop['EPC'],\n directions=directions_link(prop),\n has_garden=\"With garden. \" if prop['has_garden'] else \"\")\n\n sc.api_call(\"chat.postMessage\", channel=\"#general\",\n text=text, username='propertybot',\n icon_emoji=':new:')\n create_card(\"{} - {}\".format(prop['title'], prop['price']), text)\n\n\ndef update_list(should_notify=True, area=work_addr1):\n query_string = urlencode(\n OrderedDict(term=area,\n within=str(radius),\n prices_min=min_value,\n prices_max=max_value,\n bedrooms_min=0,\n bedrooms_max=3,\n isLive=\"true\"))\n\n url = (\"http://www.openrent.co.uk/properties-to-rent/?%s\" % query_string)\n\n html_doc = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(html_doc, 'html.parser')\n\n if os.path.isfile(links_filepath()):\n with open(links_filepath()) as f:\n existing_links = json.load(f)\n else:\n existing_links = {}\n\n with open(links_filepath(), 'w') as f:\n latest_links = [x['href'][1:] for x\n in soup.find_all(\"a\", class_=\"banda pt\")]\n print(\"Received %s property links...\" % len(latest_links))\n latest_and_old = list(set(latest_links) | set(existing_links.get('openrent', [])))\n all_data = existing_links.copy()\n all_data['openrent'] = latest_and_old\n json.dump(all_data, f, indent=4)\n\n new_links = list(set(latest_links) - set(existing_links.get('openrent',[])))\n print(\"Found %s new links!...\" % len(new_links))\n\n for property_id in new_links:\n test = parse_property_page(property_id)\n if should_notify and test is not None:\n notify(property_id)\n else:\n print(\"Found a property %s but notifications are disabled.\"\n % property_id)\n\n\ndef notify_sr(property_id):\n print(\"Notifying about %s...\" % property_id)\n\n def make_link(property_id):\n return (\"https://www.spareroom.co.uk/%s\" % property_id)\n\n sc.api_call(\"api.test\")\n sc.api_call(\"channels.info\", channel=\"1234567890\")\n\n with open(property_filepath_sr(property_id)) as f:\n prop = json.load(f)\n\n should_notify_, reason = should_notify(prop)\n if not should_notify_:\n print(\"Skipping notification: %s...\" % reason)\n return\n\n if not len(prop['location']) > 0:\n prop['location'].append(['unknown'] * 2)\n text = (\"<{link}|{title}> close to {location} ({walk_duration}):\\n\"\n \"*Price:* {price:.2f}. *Available from:* {av}. *EPC:* {epc}. {has_garden}\\n\"\n \"{directions}.\\n*Description:*\\n{desc}\").format(\n location=prop['location'][0][0],\n walk_duration=prop['location'][0][1],\n link=make_link(property_id),\n price=prop['price'],\n desc=prop['description'][:1000],\n av=prop['available_from'],\n title=prop['title'],\n epc=prop['EPC'],\n directions=directions_link(prop),\n has_garden=\"With garden. \" if prop['has_garden'] else \"\")\n\n sc.api_call(\"chat.postMessage\", channel=\"#general\",\n text=text, username='propertybot',\n icon_emoji=':new:')\n create_card(\"{} - {:.2f}\".format(prop['title'], prop['price']), text)\n\n\ndef update_list_sr(should_notify=True, area=work_addr1, search_id=None):\n\n headers = {'User-Agent': 'SpareRoomUK 3.1'}\n cookies = {'session_id': '00000000', 'session_key': '000000000000000'}\n api_location = 'http://iphoneapp.spareroom.co.uk'\n api_search_endpoint = 'flatshares'\n api_details_endpoint = 'flatshares'\n\n def make_get_request(url=None, headers=None, cookies=None, proxies=None, sleep_time=0.3):\n # if DEBUG:\n print('Sleeping for {secs} seconds'.format(secs=sleep_time))\n sleep(sleep_time)\n return requests.get(url, cookies=cookies, headers=headers).text\n\n if search_id is None:\n params = OrderedDict(format='json',\n max_rent=max_value,\n per='pcm',\n page=1,\n max_per_page=100,\n where=area.lower(),\n miles_from_max=str(radius),\n posted_by=\"private_landlords\",\n showme_1beds='Y',\n available_from='{:%Y-%m-%d}'.format(avail_from),\n )\n\n else:\n params = OrderedDict(format='json',\n search_id=search_id,\n page=1)\n\n sr_results = list()\n page = 1\n total_pages = 100\n pages_left = 100\n while pages_left:\n url = '{location}/{endpoint}?{params}'.format(location=api_location,\n endpoint=api_search_endpoint,\n params=urlencode(params))\n try:\n results = json.loads(make_get_request(url=url,\n cookies=cookies,\n headers=headers))\n page = results['page']\n total_pages = results['pages']\n pages_left = total_pages - page\n sr_results.extend(results['results'])\n # if VERBOSE:\n # print('Parsing page {page}/{total} flats in {area}'.format(page=results['page'], total=results['pages'], area=area))\n except Exception as e:\n print(e)\n return None\n params['page'] += 1\n\n # Add results to the list\n if os.path.isfile(links_filepath()):\n with open(links_filepath()) as f:\n existing_links = json.load(f)\n else:\n existing_links = {}\n\n with open(links_filepath(), 'w') as f:\n latest_links = [r['advert_id'] for r in sr_results]\n print(\"Received %s property links...\" % len(latest_links))\n print(\" saved links {}\".format(len(set(existing_links.get('spareroom', [])))))\n latest_and_old = list(set(latest_links) | set(existing_links.get('spareroom',[])))\n all_data = existing_links.copy()\n all_data['spareroom'] = latest_and_old\n json.dump(all_data, f, indent=4)\n\n new_links = list(set(latest_links) - set(existing_links.get('spareroom', [])))\n print(\"Found %s new links!...\" % len(new_links))\n new_links = [r for r in sr_results if r['advert_id'] in new_links]\n\n # === Check each property and create notification\n for property_prop in new_links:\n property_id = property_prop['advert_id']\n test = parse_property_page_sr(property_prop)\n if should_notify and test is not None:\n notify_sr(property_id)\n else:\n print(\"Found a property %s but notifications are disabled.\"\n % property_id)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--nonotify\", help=\"don't notify\", action='store_true',\n default=False)\n args = parser.parse_args()\n\n should_notify_ = not args.nonotify\n if not os.path.isfile(links_filepath()):\n should_notify_ = False\n print(\"No links.json detected. This must be the first run: not\"\n \" notifying about all suitable properties.\")\n for area in areas:\n update_list(should_notify=should_notify_, area=area)\n update_list_sr(should_notify=should_notify_, area=area)\n# TODO: MAX TERM IN SR\n","sub_path":"get_properties.py","file_name":"get_properties.py","file_ext":"py","file_size_in_byte":12367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"511067648","text":"import pygame\npygame.init()\n\npygame.display.set_mode(size=(300, 500))\n\n # for event in pygame.event.get():\nkey = pygame.key.get_pressed()\n # print(key)\nif key[pygame.K_RIGHT]:\n print(\"向右……\")\n print(key)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"576146116","text":"import json\nimport os\nfrom Twitter_Utils.TweetProcessing import TweetProcessor\nfrom Gnip_Client.IBMToneAnalysis import ToneAnalyzer\n\n\nclass DataTrimmer:\n def __init__(self):\n self.tweet_processor = TweetProcessor()\n self.tone_analyzer = ToneAnalyzer()\n\n @staticmethod\n def get_file_location(index):\n return os.getcwd() + '/Gnip_Client/Gnip_Searches/Gnip_Search_' + str(index) + '.json'\n\n def load_json_blob(self, counter):\n file_path = self.get_file_location(counter)\n with open(file_path) as data_file:\n return json.load(data_file)\n\n def get_tweets(self, s, r):\n tweet_set = set([])\n for i in range(s, r):\n try:\n print('At index ' + str(i))\n json_file = self.load_json_blob(i)\n for result in json_file['results']:\n tweet = self.tweet_processor.standardize_tweet(result['body'])\n emotions = self.tone_analyzer.query_ibm_for_tone(tweet)\n tweet_set.add(tweet)\n with open('output.csv', 'a+b') as analyzed_tweets:\n if emotions[0] and emotions[1] and emotions[2] and emotions[3] and emotions[4]:\n analyzed_tweets.write(tweet + ', ' + emotions[0] + ', ' + emotions[1] + ', '\n + emotions[2] + ', ' + emotions[3] + ', ' + emotions[4] + '\\n')\n return tweet_set\n\n except:\n print('Key \"body\" not found.')\n return None\n\n\nd = DataTrimmer()\nd.get_tweets(2,4)\n","sub_path":"Gnip_Client/GNIPDataTrimmer.py","file_name":"GNIPDataTrimmer.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"89122692","text":"#!/usr/bin/python3\nimport requests\nimport sys\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n email = {}\n email['email'] = sys.argv[2]\n\n r = requests.post(url, email)\n print(r.content.decode('utf-8'))\n","sub_path":"0x11-python-network_1/6-post_email.py","file_name":"6-post_email.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"627052726","text":"from pitch_utils import get_avg_pitch\nimport os\nfrom scipy import stats\nimport numpy as np\n\ninfiledir = \"data_highpitched_distr/train/woman\"\nnewdir = \"higher_pitched\"\npitches = []\nfor dirpath, dirnames, filenames in os.walk(infiledir):\n for filename in [f for f in filenames if f.endswith(\".wav\")]:\n filepath = os.path.join(dirpath, filename)\n pitches.append(get_avg_pitch(filepath))\n\n# remove values lower than 65Hz (that's about the lowest freq for male voice)\npitches = list(filter(lambda bigval: bigval >= 65, pitches))\n\ntot_avg_pitch = np.mean(pitches)\n\nprint(\"Average pitch for directory, \" + infiledir + \", is \" + str(tot_avg_pitch))\nprint(stats.describe(pitches))\n","sub_path":"get_dir_avg_pitch.py","file_name":"get_dir_avg_pitch.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"230472705","text":"import os\nimport gdown\nimport zipfile\nimport tensorflow\nfrom keras.models import Model, model_from_json\nfrom keras.layers import Activation, Dense, Input, \\\n Conv2DTranspose, Dense, Flatten\nfrom keras.optimizers import Adam\nimport numpy as np\nimport cv2\nimport gradio\n\ntry:\n from keras_contrib.layers.normalization import \\\n InstanceNormalization\nexcept Exception:\n from keras_contrib.layers.normalization.instancenormalization\\\n import \\\n InstanceNormalization\n\nCHECKPOINT_PATH = 'checkpoint/'\nCHECKPOINT_LINK = 'https://drive.google.com/u/0/uc?' \\\n 'export=download&confirm=a7YF&id=' \\\n '1MfXsRwjx5CTRGBoLx154S0h-Q3rIUNH0'\n\nINPUT_SHAPE = (256, 256, 3)\n# 25% i.e 64 width size will be mask from both side\nMASK_PERCENTAGE = .25\n\ng_input_shape = (INPUT_SHAPE[0], int(INPUT_SHAPE[1] * (MASK_PERCENTAGE * 2)),\n INPUT_SHAPE[2])\n\n\nEPSILON = 1e-9\nALPHA = 0.0004\n\ndef dcrm_loss(y_true, y_pred):\n return -tensorflow.reduce_mean(tensorflow.log(tensorflow.maximum(y_true, EPSILON)) +\n tensorflow.log(tensorflow.maximum(1. - y_pred, EPSILON)))\n\nd_input_shape = (INPUT_SHAPE[0], int(INPUT_SHAPE[1] * (MASK_PERCENTAGE *2)), INPUT_SHAPE[2])\nd_dropout = 0.25\nDCRM_OPTIMIZER = Adam(0.0001, 0.5)\n\nGEN_OPTIMIZER = Adam(0.001, 0.5)\n\ndef load_model():\n # Checking if all the model exists\n model_names = ['DCRM', 'GEN']\n files = os.listdir(CHECKPOINT_PATH)\n for model_name in model_names:\n if model_name + \".json\" not in files or \\\n model_name + \".hdf5\" not in files:\n print(\"Models not Found\")\n return\n # global DCRM, GEN, COMBINED, IMAGE, GENERATED_IMAGE, CONF_GENERATED_IMAGE\n\n # load DCRM Model\n model_path = CHECKPOINT_PATH + \"%s.json\" % 'DCRM'\n weight_path = CHECKPOINT_PATH + \"%s.hdf5\" % 'DCRM'\n with open(model_path, 'r') as f:\n DCRM = model_from_json(f.read())\n DCRM.load_weights(weight_path)\n DCRM.compile(loss=dcrm_loss, optimizer=DCRM_OPTIMIZER)\n\n # load GEN Model\n model_path = CHECKPOINT_PATH + \"%s.json\" % 'GEN'\n weight_path = CHECKPOINT_PATH + \"%s.hdf5\" % 'GEN'\n with open(model_path, 'r') as f:\n GEN = model_from_json(f.read(), custom_objects={\n 'InstanceNormalization': InstanceNormalization()})\n GEN.load_weights(weight_path)\n\n # Combined Model\n DCRM.trainable = False\n IMAGE = Input(shape=g_input_shape)\n GENERATED_IMAGE = GEN(IMAGE)\n CONF_GENERATED_IMAGE = DCRM(GENERATED_IMAGE)\n\n COMBINED = Model(IMAGE, [CONF_GENERATED_IMAGE, GENERATED_IMAGE])\n COMBINED.compile(loss=['mse', 'mse'], optimizer=GEN_OPTIMIZER)\n\n print(\"loaded model\")\n return GEN\n\n\ndef get_demask_images(original_images, generated_images):\n demask_images = []\n for o_image, g_image in zip(original_images, generated_images):\n print(g_image.shape)\n width = g_image.shape[1] // 2\n x_image = g_image[:, :width]\n y_image = g_image[:, width:]\n o_image = np.concatenate((x_image,o_image, y_image), axis=1)\n demask_images.append(o_image)\n return np.asarray(demask_images)\n\ndef mask_width(img):\n image = img.copy()\n height = image.shape[0]\n width = image.shape[1]\n new_width = int(width * MASK_PERCENTAGE)\n mask = np.ones([height, new_width, 3])\n missing_x = img[:, :new_width]\n missing_y = img[:, width - new_width:]\n missing_part = np.concatenate((missing_x, missing_y), axis=1)\n image = image[:, :width - new_width]\n image = image[:, new_width:]\n return image, missing_part\n\n\ndef get_masked_images(images):\n mask_images = []\n missing_images = []\n for image in images:\n mask_image, missing_image = mask_width(image)\n mask_images.append(mask_image)\n missing_images.append(missing_image)\n return np.array(mask_images), np.array(missing_images)\n\n\ndef recursive_paint(GEN, image, factor=3):\n final_image = None\n gen_missing = None\n for i in range(factor):\n demask_image = None\n if i == 0:\n x, y = get_masked_images([image])\n gen_missing = GEN.predict(x)\n final_image = get_demask_images(x, gen_missing)[0]\n else:\n gen_missing = GEN.predict(gen_missing)\n final_image = get_demask_images([final_image], gen_missing)[0]\n return final_image\n\n\ndef load():\n if not os.path.exists(CHECKPOINT_PATH):\n os.makedirs(CHECKPOINT_PATH)\n gdown.download(CHECKPOINT_LINK, CHECKPOINT_PATH + 'checkpoint_24.zip')\n with zipfile.ZipFile(CHECKPOINT_PATH + 'checkpoint_24.zip', 'r') as \\\n zip_ref:\n zip_ref.extractall('./')\n GEN = load_model()\n graph = tensorflow.get_default_graph()\n return GEN, graph\n\nGEN, graph = load()\n\ndef predict(image, model):\n image = Image.fromarray(image.astype('uint8'), 'RGB')\n GEN, graph = model\n image = image.convert('RGB')\n image = np.array(image)\n image = cv2.resize(image, (256, 256))\n cropped_image = image[:, 65:193]\n input_image = image / 127.5 - 1\n # input_image = np.expand_dims(input_image, axis=0)\n with graph.as_default():\n # predicted_image = GEN.predict(input_image)\n predicted_image = recursive_paint(GEN, input_image)\n # predicted_image = get_demask_images(input_image, predicted_image)[0]\n predicted_image = (predicted_image + 1) * 127.5\n predicted_image = predicted_image.astype(np.uint8)\n\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n # predicted_image = cv2.cvtColor(predicted_image, cv2.COLOR_BGR2RGB)\n return predicted_image\n\n\nINPUTS = gradio.inputs.ImageIn()\nOUTPUTS = gradio.outputs.Image()\nINTERFACE = gradio.Interface(fn=predict, inputs=INPUTS, \n outputs=OUTPUTS,\n title='Image Outpainting', \n description='Restore missing parts of an image!', \n thumbnail='https://camo.githubusercontent.com/1374c4a783e9a1b3f31cda08e84fd1c39ebb618d/687474703a2f2f692e696d6775722e636f6d2f704455707a63592e6a7067')\n\nINTERFACE.launch(inbrowser=True)\n\n","sub_path":"run-gradio.py","file_name":"run-gradio.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"285746667","text":"#!/usr/bin/python3\n# Python 3 json rpc client module, with cookie support\n\nimport os.path\nimport urllib.request\nfrom http.cookiejar import LWPCookieJar\nimport json, types\n\n# this cookie jar will work with lib-www too\ncookiejar = LWPCookieJar( '/tmp/session_cookie.lwp' )\n\ncookie = urllib.request.HTTPCookieProcessor( cookiejar )\nopener = urllib.request.build_opener(cookie)\nurllib.request.install_opener(opener)\n\ntype_map = {\n 'string': str,\n 'number': float,\n 'boolean' : bool,\n 'object': dict,\n 'array': list\n}\n\nclass JsonRPC:\n def __init__( self, url ):\n if os.path.isfile( cookiejar.filename ):\n cookiejar.load()\n\n self._method = {}\n self._seq_id = 0\n self._base_url = url\n\n self._load_services()\n self._cookiejar = cookiejar\n\n def __del__( self ):\n self._cookiejar.save()\n\n def _load_services( self ):\n r = urllib.request.urlopen( self._base_url + '/service.smd' ).read().decode( 'utf8' )\n\n d = json.loads( r )\n\n for name in d[ 'services' ]:\n m = d[ 'services' ][ name ]\n\n self._method[ name ] = d[ 'services' ][ name ]\n\n def __getattr__( self, method_name ):\n mdata = self._method[ method_name ]\n\n def jsonrpc_call( *args ):\n idx = 0\n self._seq_id += 1\n seq_id = self._seq_id\n\n # We need argument checking here !\n params = []\n for a in args:\n if 'parameters' in mdata:\n p = mdata['parameters'][ idx ]\n\n if p[ 'type' ] in type_map:\n if type_map[ p[ 'type' ] ] != type( a ):\n raise Exception( \"bad param type: %s = %s for method %s \" % (p['type'], type( a ), method_name))\n else:\n raise Exception( 'unknown definition type \\'%s\\' as it should have been a \\'%s\\' in method : %s ' % (type( a ), p[ 'type' ], method_name) )\n\n idx += 1\n params.append( a )\n\n payload = {\n 'method' : method_name,\n 'params' : params,\n 'jsonrpc': \"2.0\",\n 'id' : seq_id\n }\n\n req = urllib.request.Request( self._base_url, data=json.dumps( payload ).encode())\n req.add_header('Content-Type', 'application/json')\n r = json.loads( urllib.request.urlopen(req).read().decode( 'utf8̈́' ))\n\n if r[ 'id' ] == seq_id:\n if 'result' in r:\n return r[ 'result' ]\n elif 'error' in r:\n raise Exception( 'Error \"%s\" in method %s' % (r[ 'error' ][ 'message' ], method_name) )\n else:\n raise Exception( 'Unknown error in method %s' % method_name )\n\n raise Exception( 'bad PRC responce for method %s' % method_name )\n\n return jsonrpc_call\n\nif __name__ == '__main__':\n r = JsonRPC( 'http://localhost:8080/json' )\n r.domain_open( 'essens' )\n print( r.status('kat') )\n","sub_path":"py_print/json_client.py","file_name":"json_client.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"170520447","text":"import itertools\nimport random\nfrom urllib.parse import urlencode\n\nimport requests\nfrom irc3.plugins.command import command\nimport irc3\nimport ircmessage\nfrom lxml import html\nimport re\n\nfrom .redflare_client import RedflareClient\n\n\n@irc3.plugin\nclass RELBotPlugin:\n def __init__(self, bot):\n self.bot = bot\n self.redflare_url = self.bot.config.get(\"relbot\", dict()).get(\"redflare_url\", None)\n\n @command(permission=\"view\")\n def matches(self, mask, target, args):\n \"\"\"List interesting Red Eclipse matches\n\n %%matches\n \"\"\"\n\n if not self.redflare_url:\n yield \"Redflare URL not configured\"\n return\n\n rfc = RedflareClient(self.redflare_url)\n servers = rfc.servers()\n\n # i: Server\n non_empty_legacy_servers = [s for s in servers if s.players_count > 0 and not s.version.startswith(\"2.\")]\n\n if not non_empty_legacy_servers:\n yield \"No legacy matches running at the moment.\"\n return\n\n for server in sorted(non_empty_legacy_servers, key=lambda s: s.players_count, reverse=True):\n players = [p.name for p in server.players]\n\n # the colors we use to format player names\n colors = [\"red\", \"pink\", \"green\", \"teal\", \"orange\", None]\n # make things a bit more interesting by randomizing the order\n random.shuffle(colors)\n # however, once the order is defined, just apply those colors in the ever same order to nicks in the list\n # it'd be nice to assign some sort of \"persistent\" colors derived from the nicks\n colors = itertools.cycle(colors)\n\n # this is the \"freem exception\"\n # freem doesnt like to be pinged on IRC whenever !matches is called while they are playing\n # the easiest way to fix this is to just change the name in the listing\n # ofc this only works until freem decides to use another nickname\n players = [\"_freem_\" if p == \"freem\" else p for p in players]\n\n message = \"%s on %s (%s): %s %s on %s\" % (\n ircmessage.style(str(server.players_count), fg=\"red\"),\n ircmessage.style(\"%s\" % server.description, fg=\"orange\"),\n \", \".join((ircmessage.style(p, fg=next(colors)) for p in players)),\n ircmessage.style(\"-\".join(server.mutators), fg=\"teal\"),\n ircmessage.style(server.game_mode, fg=\"green\"),\n ircmessage.style(server.map_name, fg=\"pink\"),\n )\n\n print(repr(message))\n\n yield message\n\n @command(permission=\"view\")\n def rivalry(self, mask, target, args):\n \"\"\"Show player counts on legacy and 2.x servers\n\n %%rivalry\n \"\"\"\n\n if not self.redflare_url:\n yield \"Redflare URL not configured\"\n return\n\n rfc = RedflareClient(self.redflare_url)\n servers = rfc.servers()\n\n # i: Server\n non_legacy_servers = [s for s in servers if s.version.startswith(\"2.\")]\n legacy_servers = [s for s in servers if not s in non_legacy_servers]\n\n non_legacy_players_count = sum([s.players_count for s in non_legacy_servers])\n legacy_players_count = sum([s.players_count for s in legacy_servers])\n\n message = \"%d legacy vs. %d non-legacy players\" % (legacy_players_count, non_legacy_players_count)\n\n if non_legacy_players_count == 0:\n if legacy_players_count == 0:\n ratio = None\n else:\n # with no matches running, legacy wins\n # over 9000!\n ratio = 9001\n else:\n ratio = float(legacy_players_count) / float(non_legacy_players_count)\n\n if ratio is None:\n message += \" -- no matches running o_O\"\n elif ratio > 2:\n message += \" -- WOOHOO!!!111!1!!11\"\n elif ratio > 1:\n message += \" -- awesome!\"\n elif ratio == 1:\n message += \"... meh...\"\n else:\n message += \"... urgh...\"\n\n yield message\n\n @command(name=\"reload-plugin\", permission=\"view\")\n def reload_plugin(self, mask, target, args):\n \"\"\"Reloads this plugin\n\n %%reload-plugin\n \"\"\"\n\n self.bot.reload(\"relbot.chat_plugin\")\n\n yield \"Done!\"\n\n @command(name=\"rp\", permission=\"view\")\n def rp(self, *args, **kwargs):\n \"\"\"Reloads this plugin\n\n %%rp\n \"\"\"\n return self.reload_plugin(*args, **kwargs)\n\n @command(name=\"lmgtfy\", permission=\"view\")\n def lmgtfy(self, mask, target, args):\n \"\"\"Let me google that for you!\n\n %%lmgtfy ...\n \"\"\"\n\n querystring = urlencode({\n \"q\": \" \".join(args[\"\"]),\n })\n\n yield \"https://lmgtfy.com/?{}\".format(querystring)\n\n @command(name=\"chuck\", permission=\"view\")\n def chuck(self, mask, target, args):\n \"\"\"Tell a Chuck Norris joke from the Internet Chuck Norris Database (icndb.com)\n\n %%chuck\n \"\"\"\n\n proxies = {\n \"http\": \"socks5://127.0.0.1:9050\",\n \"https\": \"socks5://127.0.0.1:9050\",\n }\n\n url = \"http://api.icndb.com/jokes/random\"\n\n response = requests.get(url, allow_redirects=True, proxies=proxies)\n\n yield response.json()[\"value\"][\"joke\"]\n\n @irc3.event(irc3.rfc.PRIVMSG)\n def github_integration(self, mask, target, data, **kwargs):\n \"\"\"Check every message if it contains GitHub references (i.e., some #xyz number), and provide a link to GitHub\n if possible.\n Uses web scraping instead of any annoying\n Note: cannot use yield to send replies; it'll fail silently then\n \"\"\"\n\n # skip all commands\n if any((data.strip(\" \\r\\n\").startswith(i) for i in [self.bot.config[\"cmd\"], self.bot.config[\"re_cmd\"]])):\n return\n\n # some things can't be done easily by a regex\n # we have to intentionally terminate the data with a space\n # that way, we can check that the #123 like patters stand alone using a regex that makes sure there's at least\n # a whitespace character after the interesting bit, ensuring that strings like #123abc are not matched\n # this should prevent some false and unnecessary checks\n data += \" \"\n\n matches = re.findall(r\"#([0-9]+)\\s+\", data)\n\n print(matches)\n\n for match in matches:\n # we just check the issues URL; GitHub should automatically redirect to pull requests\n url = \"https://github.com/blue-nebula/base/issues/{}\".format(match)\n\n proxies = {\n \"http\": \"socks5://127.0.0.1:9050\",\n \"https\": \"socks5://127.0.0.1:9050\",\n }\n\n response = requests.get(url, allow_redirects=True, proxies=proxies)\n\n if response.status_code != 200:\n if response.status_code == 404:\n self.bot.notice(target, \"[GitHub] Could not find anything for #{}\".format(match))\n\n else:\n self.bot.notice(target, \"[GitHub] Request to GitHub failed\")\n\n return\n\n tree = html.fromstring(response.content)\n title = tree.cssselect(\".gh-header-title .js-issue-title\")[0].text.strip(\" \\r\\n\")\n\n url_parts = response.url.split(\"/\")\n if \"pull\" in url_parts:\n type = \"PR\"\n elif \"issues\" in url_parts:\n type = \"Issue\"\n else:\n type = \"Unknown Entity\"\n\n notice = \"[GitHub] {} #{}: {} ({})\".format(type, match, title, response.url)\n\n self.bot.notice(target, notice)\n\n @classmethod\n def reload(cls, old):\n return cls(old.bot)\n","sub_path":"relbot/chat_plugin.py","file_name":"chat_plugin.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310180227","text":"import os, sys\nfrom pandac.PandaModules import ConfigVariableBool\nfrom pandac.PandaModules import ConfigVariableInt\n\nfrom direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import *\n\nif 0:\n wp = WindowProperties()\n #wp.setFullscreen(1)\n #wp.setSize(1024, 768)\n\nif 0:\n\n base.openMainWindow()\n base.win.requestProperties(wp)\n base.graphicsEngine.openWindows()\n \nif 1:\n class MyApp(ShowBase):\n def __init__(self):\n ShowBase.__init__(self)\n self.accept(\"escape\",sys.exit)\n self.setBackgroundColor(0,0,0)\n\n if 0:\n wp = WindowProperties()\n wp.setFullscreen(1)\n wp.setSize(1920, 1080)\n \n self.openMainWindow()\n self.win.requestProperties(wp)\n self.graphicsEngine.openWindows()\n\n self.wp1 = WindowProperties()\n self.wp1.setSize(800, 600)\n self.wp1.setOrigin(100, 100)\n self.win1 = base.openWindow(props=self.wp1, aspectRatio=1)\n \n self.wp2 = WindowProperties()\n self.wp2.setSize(800, 600)\n self.wp2.setOrigin(900, 100)\n self.win2 = base.openWindow(props=self.wp2, aspectRatio=1)\n\n self.disableMouse()\n\n if 0:\n text = TextNode('node name')\n text.setText(\"Every day in every way I'm getting better and better.\")\n textNodePath = aspect2d.attachNewNode(text)\n cmr12 = loader.loadFont('cmr12.egg')\n text.setAlign(TextNode.ACenter)\n\n text.setFont(cmr12)\n textNodePath.setScale(0.1)\n\n app = MyApp()\n app.run()\n\n","sub_path":"pandastest/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"177372488","text":"# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import Column\nfrom sqlalchemy import String, Integer, DateTime\nfrom sqlalchemy.orm import declarative_base\n\nBase = declarative_base()\n\n\nclass Wallet(Base):\n __tablename__ = \"wallet\"\n\n idx = Column(\n Integer,\n unique=True,\n primary_key=True,\n nullable=False\n )\n\n owner = Column(\n String(50),\n nullable=False\n )\n\n name = Column(\n String(30),\n nullable=False\n )\n\n count = Column(\n Integer,\n nullable=False,\n default=0\n )\n\n def __repr__(self):\n return f\"\"\n\n\nclass Coin(Base):\n __tablename__ = \"coin\"\n\n name = Column(\n String(30),\n unique=True,\n primary_key=True,\n nullable=False\n )\n\n price = Column(\n Integer,\n nullable=False\n )\n\n def __repr__(self):\n return f\"\"\n\n\nclass Point(Base):\n __tablename__ = \"point\"\n\n owner = Column(\n String(50),\n unique=True,\n primary_key=True,\n nullable=False\n )\n\n point = Column(\n Integer,\n nullable=False\n )\n\n def __repr__(self):\n return f\"\"\n\n\nclass Gift(Base):\n __tablename__ = \"gift\"\n\n idx = Column(\n Integer,\n unique=True,\n primary_key=True,\n nullable=False\n )\n\n owner = Column(\n String(50),\n nullable=False\n )\n\n type = Column(\n String(30),\n nullable=False\n )\n\n date = Column(\n DateTime,\n nullable=False\n )\n\n def __repr__(self):\n return f\"\"\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"566478759","text":"# Using Cosine Distance to train a matching network\n\nimport tensorflow as tf\nimport numpy as np\nimport getopt\nimport random\nimport math\nimport sys\nimport os\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"../../../testing-data/MNIST_data/\",\n one_hot=True)\n\ndef help_message():\n exit(1)\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\n# Graph Constants\nsize = [28, 28, 1]\nnKernels = [64, 64,64]\nfully_connected_nodes = 128\npoolS = 2\n\n# Training information\nnIt = 5000\ncheck = 1000\nbatchS = 32\nlearning_rate = 1e-4\ntensorboard = False\ndropout = False\nbatch_norm = False\n\n# Support and testing infromation\nclassList = [1,2,3,4,5,6,7,8,9,0]\nnumbers = []\nnumbersTest = []\nnClasses = 3\nnImgsSuppClass = 5\n\nbase = \"/tmp/mnist-cosine-\"\n\nopts, args = getopt.getopt(sys.argv[1:], \"hmnodL:c:i:b:s:\", [\"help\", \n \"num_classes=\", \"num_supports=\", \"base_path=\", \"num_iterations=\",\n \"dropout\", \"batch_norm\", \"num_layers=\"])\n\nfor o, a in opts:\n if o in (\"-c\", \"--num_classes\"):\n nClasses = int(a)\n elif o in (\"-s\", \"--num_supports\"):\n nImgsSuppClass = int(a)\n elif o in (\"-b\", \"--base_path\"):\n base = a\n if a[-1] != \"/\":\n base += \"/\"\n base += \"mnist-cosine-\"\n elif o in (\"-i\", \"--num_iterations\"):\n nIt = int(a)\n elif o in (\"-d\", \"--data\"):\n train_file_path = \"../../../testing-data/omniglot-rotate/\"\n elif o in (\"-m\", \"--meta_tensorboard\"):\n tensorboard = True\n elif o in (\"-o\", \"--dropout\"):\n dropout = True\n elif o in (\"-n\", \"--batch_norm\"):\n batch_norm = True\n elif o in (\"-L\", \"--num_layers\"):\n nKernels = [64 for x in range(int(a))]\n elif o in (\"-h\", \"--help\"):\n help_message()\n else:\n print(\"unhandled option: \"+o)\n help_message()\n\nnumbers = classList[:nClasses]\nnumbersTest = classList[10-nClasses:]\n\nSAVE_PATH = base\nif batch_norm:\n SAVE_PATH += \"norm-\"\nif dropout:\n SAVE_PATH += \"dropout-\"\n\nSAVE_PATH += str(len(nKernels)) + \"-\" + str(nClasses) + \"-\" + str(nImgsSuppClass)\n\nLOG_DIR = \"./mnist_network_training/cosine/\"\nif batch_norm:\n LOG_DIR += \"norm/\"\nif dropout:\n LOG_DIR += \"dropout/\"\nLOG_DIR += str(len(nKernels)) + \"/\" + str(nClasses) + \"/\" + str(nImgsSuppClass) \n\n# Collecting sample both for query and for testing\ndef get_samples(mnistNum, nSupportImgs, testing = False):\n one_hot_list = [0.] * 10\n one_hot_list[mnistNum] = 1.\n samples = 0\n if not testing:\n imageNum = random.randint(0, mnist.train.images.shape[0] - 1)\n else:\n imageNum = random.randint(0, mnist.test.images.shape[0] - 1)\n pickedImages = []\n pickedLabels = []\n while samples < nSupportImgs:\n if (imageNum == len(mnist.train.images) and not testing):\n imageNum = 0\n elif (imageNum == len(mnist.test.images) and testing):\n imageNum = 0\n if not testing:\n labelThis = mnist.train.labels[imageNum, :]\n else:\n labelThis = mnist.test.labels[imageNum, :]\n if np.all(labelThis == one_hot_list):\n if not testing:\n imgReshape = np.reshape(mnist.train.images[imageNum,:], size)\n pickedLabels.append(mnist.train.labels[imageNum, :])\n else:\n imgReshape = np.reshape(mnist.test.images[imageNum,:], size)\n pickedLabels.append(mnist.test.labels[imageNum, :])\n pickedImages.append(imgReshape)\n samples += 1\n imageNum += 1\n return pickedImages, pickedLabels\n\n# Get several images\ndef get_support(test=False):\n supportImgs = []\n \n choices = numbers\n \n for support in choices:\n newSupportImgs, newSupportLabels = get_samples(support, nImgsSuppClass,\n test)\n supportImgs.append(newSupportImgs)\n \n return supportImgs\n\n# Get a single query value\ndef get_query(test=False):\n\n choices = numbers\n\n imageInd = random.randint(0, len(choices) - 1)\n imageNum = choices[imageInd]\n img, label = get_samples(imageNum, 1, test)\n l=np.zeros(len(choices))\n l[imageInd]=1\t\t\n return img[0], l\n\ntf.reset_default_graph()\n\n# Support information - matrix\n# Dimensions: batch size, n classes, n supp imgs / class\ns_imgs = tf.placeholder(tf.float32, [batchS, nClasses, nImgsSuppClass]+size)\n\n# Query Information - vector\nq_img = tf.placeholder(tf.float32, [batchS]+size) # batch size, size\n# batch size, number of categories\nq_label = tf.placeholder(tf.int32, [batchS, len(numbers)])\n\n# Network Function\n# Call for each support image (row of the support matrix) and for the query \n# image.\n\ndef create_network(img, size, First = False):\n currInp = img\n layer = 0\n currFilt = size[2]\n \n with tf.name_scope(\"run_network\"):\n for k in nKernels:\n with tf.variable_scope('conv'+str(layer), \n reuse=tf.AUTO_REUSE) as varscope:\n layer += 1\n weight = tf.get_variable('weight', [3,3,currFilt,k])\n currFilt = k\n if batch_norm:\n convR = tf.nn.conv2d(currInp, weight, strides=[1,1,1,1], padding=\"SAME\")\n beta = tf.get_variable('beta', [k], initializer = tf.constant_initializer(0.0))\n gamma = tf.get_variable('gamma', [k], initializer=tf.constant_initializer(1.0))\n mean, variance = tf.nn.moments(convR, [0,1,2])\n PostNormalized = tf.nn.batch_normalization(convR,mean,variance,beta,gamma,1e-10)\n reluR = tf.nn.relu(PostNormalized)\n else:\n bias = tf.get_variable('bias', [k], initializer = \n tf.constant_initializer(0.0))\n convR = tf.nn.conv2d(currInp, weight, strides=[1,1,1,1], padding=\"SAME\")\n convR = tf.add(convR, bias)\n reluR = tf.nn.relu(convR)\n poolR = tf.nn.max_pool(reluR, ksize=[1,poolS,poolS,1], \n strides=[1,poolS,poolS,1], padding=\"SAME\")\n currInp = poolR\n\n if dropout:\n currInp = tf.nn.dropout(currInp,0.8); \n return currInp\n\n# Call the network created above on the qury\nquery_features = create_network(q_img, size, First = True)\n\nsupport_list = []\nquery_list = []\n\n# Go through each class and each support image in that class\nfor k in range(nClasses):\n slist=[]\n qlist=[]\n for i in range(nImgsSuppClass):\n slist.append(create_network(s_imgs[:, k, i, :, :, :], size))\n qlist.append(query_features)\n slist = tf.stack(slist)\n qlist = tf.stack(qlist) \n support_list.append(slist)\n query_list.append(qlist)\n\n# Make a stack to compare the query to every support\nquery_repeat = tf.stack(query_list)\nsupports = tf.stack(support_list)\n\n# Loss\n# Cosine distance calculation \n# Application of softmax \n# Minimize loss\n\nwith tf.name_scope(\"loss\"):\n dotProduct = tf.reduce_sum(tf.multiply(query_repeat, supports), [3,4,5])\n supportsMagn = tf.sqrt(tf.reduce_sum(tf.square(supports), [3,4,5]))\n cosDist = dotProduct / tf.clip_by_value(supportsMagn, 1e-10, float(\"inf\"))\n \n cosDist = tf.transpose(cosDist,[2,0,1])\n\n # Find the average cosine distance per class\n MeanCosDist= tf.reduce_mean(cosDist,2)\n # fnd the maximum cosine distance per class\n MaxCostDist = tf.reduce_max(cosDist,2)\n\n loss = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits_v2(\n logits = MeanCosDist, labels = q_label))\n\n# Optimizer\nwith tf.name_scope(\"optimizer\"):\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\n# Accuracy and Equality Distribution\n\nwith tf.name_scope(\"accuracy\"):\n # Find the closest class\n max_class = tf.argmax(MaxCostDist, 1)\n # Find whihc class was supposed to be the closest\n max_label = tf.argmax(q_label, 1) \n \n # Compare the values\n total = tf.equal(max_class, max_label) \n # Find on average, how many were correct\n accuracy = tf.reduce_mean(tf.cast(total, tf.float32))\n\ndef get_next_batch(test = False):\n suppImgs = []\n suppLabels = []\n # Get support values for each batch \n for j in range(batchS):\n suppImgsOne = get_support(test)\n suppImgs.append(suppImgsOne)\n suppImgs = np.asarray(suppImgs)\n # Get query value for each batch\n queryImgBatch = []\n queryLabelBatch = []\n for i in range(batchS):\n qImg, qLabel = get_query(test)\n queryImgBatch.append(qImg)\n queryLabelBatch.append(qLabel)\n queryLabelBatch = np.asarray(queryLabelBatch)\n queryImgBatch = np.asarray(queryImgBatch)\n\n return suppImgs, suppLabels, queryImgBatch, queryLabelBatch\n\n# Session\n\n# Initialize the variables we start with\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as session:\n session.run(init)\n \n # Create a save location\n Saver = tf.train.Saver()\n\n step = 1\n while step < nIt:\n step = step + 1\n\n suppImgs, suppLabels, queryImgBatch, queryLabelBatch = get_next_batch()\n \n # Run the session with the optimizer\n if tensorboard and step == 2:\n writer = tf.summary.FileWriter(LOG_DIR + \"/\" + str(step), session.graph)\n runOptions = tf.RunOptions(trace_level = tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n ACC, LOSS, OPT = session.run([accuracy, loss, optimizer], feed_dict\n ={s_imgs: suppImgs, \n q_img: queryImgBatch,\n q_label: queryLabelBatch,\n }, options = runOptions, run_metadata=run_metadata)\n writer.add_run_metadata(run_metadata, 'step%d' % i)\n else:\n ACC, LOSS, OPT = session.run([accuracy, loss, optimizer], feed_dict\n ={s_imgs: suppImgs, \n q_img: queryImgBatch,\n q_label: queryLabelBatch,\n })\n \n # Observe Values\n if (step%100) == 0:\n print(\"ITER: \"+str(step))\n print(\"ACC: \"+str(ACC))\n print(\"LOSS: \"+str(LOSS))\n print(\"------------------------\")\n \n # Run an additional test set \n if (step % check) == 0:\n TotalAcc=0.0\n #run ten batches to test accuracy\n BatchToTest=10\n for repeat in range(BatchToTest):\n\n suppImgs, suppLabels, queryImgBatch, queryLabelBatch = get_next_batch(True)\n \n # Run session for test values\n ACC, LOSS = session.run([accuracy, loss], feed_dict\n ={s_imgs: suppImgs, \n q_img: queryImgBatch,\n q_label: queryLabelBatch,\n })\n TotalAcc += ACC\n print(\"Accuracy on the independent test set is: \"+str(TotalAcc/float(BatchToTest)) )\n \n # Save out the model once complete\n save_path = Saver.save(session, SAVE_PATH, step)\n print(\"Model saved in path: %s\" % SAVE_PATH)\n \n # Use the test set\n '''sumAcc = 0.0\n for k in range(0,100):\n # Get test support values \n suppImgs, suppLabels, queryImgBatch, queryLabelBatch = get_next_batch(True)\n\n a = session.run(accuracy, feed_dict = {s_imgs: suppImgs, \n q_img: queryImgBatch,\n q_label: queryLabelBatch\n })\n sumAcc += a\n \n print(\"Independent Test Set: \"+str(float(sumAcc)/100))'''\n","sub_path":"src/matching-network/mnist/mnist_matching_network_cosine.py","file_name":"mnist_matching_network_cosine.py","file_ext":"py","file_size_in_byte":10615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"139154670","text":"import sys\nimport os\nimport subprocess\n\nif(len(sys.argv) < 3):\n\tprint(\"Usage: python3 parse_video_info.py path_to_video mode\")\n\texit(1)\n\nvideo_ = sys.argv[1]\nfilename, _ = os.path.splitext(sys.argv[1])\nfile_ = filename+\"_faces.txt\"\nmode = sys.argv[2]\n\n\n#### UTILS FUNCTIONS\n# base and high of the two images\ndef area_ratio(b1, h1, b2, h2):\n\ta1 = b1*h1\n\ta2 = b2*h2\n\tif(a1 == 0 or a2 == 0):\n\t\treturn 0\n\tif(a1 > a2):\n\t\treturn a2/a1\n\treturn a1/a2\n\n\n\n# coordinates is an array of 4 points: (x_top, y_top, x_bottom, y_bottom)\ndef on_head(coordinates, h, n_split=3, h_ratio_limit=0.7):\n\tlower_limit_h = h/n_split\n\ty1_down = coordinates[3]\n\th_ratio = (coordinates[3]-coordinates[1])/(lower_limit_h)\n\treturn (y1_down <= lower_limit_h and h_ratio >= h_ratio_limit)\n\n# coordinates is an array of 4 points: (x_top, y_top, x_bottom, y_bottom)\n# b and h are the dimensions of th original frame\n# n_split is the number of \"split\" on which the frame will be divided into\n# large_split is to decide if we want only the center split, or to esclude only the first and last\ndef on_center(coordinates, b, h, n_split=3, large_split=True, h_ratio_limit=0.4):\n\tif large_split:\n\t\tupper_limit_h = h/n_split\n\t\tlower_limit_h = h*(n_split-1)/n_split\n\telse:\n\t\tif(n_split % 2 == 0):\n\t\t\tmid = n_split / 2\n\t\t\tupper_limit_h = h*(mid-1)/n_split\n\t\t\tlower_limit_h = h*(mid+1)/n_split\n\t\telse:\n\t\t\tmid = n_split // 2\n\t\t\tupper_limit_h = h*mid/n_split\n\t\t\tlower_limit_h = h*(mid+1)/n_split\n\th_ratio = (coordinates[3]-coordinates[1])/(lower_limit_h-upper_limit_h)\n\treturn (coordinates[1] >= upper_limit_h and coordinates[3] <= lower_limit_h and h_ratio >= h_ratio_limit)\n\n\n\n#### MAIN ###\n\n# read video dimensions first\ncmd_ = \"./get_video_info.sh \"+video_\np = subprocess.Popen(cmd_ , shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = p.communicate()\ndim = stdout.strip().split(\"\\n\") # dim[0] = b, dim[1] = h\n\n# parse input file\nframes = {}\nwith open(file_, \"r\") as f:\n\tfor line in f:\n\t\twords = line.split()\n\t\tframe = int(words[0])\n\t\tx_top = int(words[1])\n\t\t#if(x_top < 0): x_top = 0\n\t\ty_top = int(words[2])\n\t\t#if(y_top < 0): y_top = 0\n\t\tx_down = int(words[3])\n\t\t#if(x_down > int(dim[0])): x_down = int(dim[0])\n\t\ty_down = int(words[4])\n\t\t#if(y_down > int(dim[1])): y_down = int(dim[1])\n\t\t\n\t\tif frame not in frames.keys():\n\t\t\tframes[frame] = [(x_top, y_top, x_down, y_down)]\n\t\telse:\n\t\t\tframes[frame].append((x_top, y_top, x_down, y_down))\n\nold_key = -1\nfrms = {'plan_moyen':[], 'plan_rapproche':[], 'plan_americain':[], 'gros_plan':[], 'plan_large':[], 'other':[], 'unknown':[i for i in range(int(dim[2])) if i not in frames.keys() and i % 25 == 0]}\nfor key, value in sorted(frames.items()):\n\tif(old_key == -1): old_key = key\n\telif(key < old_key+20): continue\n\tif(len(value) == 1):\n\t\tcoordinates = value[0]\n\t\tratio = area_ratio(abs(coordinates[2]-coordinates[0]), abs(coordinates[1]-coordinates[3]), int(dim[0]), int(dim[1]))\n\t\t# GROS PLAN\n\t\tif ratio > 0.135:\n\t\t\tfrms['gros_plan'].append(key)\n\t\t# PLAN MOYEN (0.006 0.01) -> 0 < h < 154\n\t\telif ratio > 0.006 and ratio < 0.0068 and coordinates[3] < 384-250 and coordinates[3] > 384-340:\n\t\t\tfrms['plan_moyen'].append(key)\n\t\t# PLAN RAPPROCHE (0.03 and 0.08) -> 164 < h < 254\n\t\telif ratio > 0.05 and ratio < 0.06 and coordinates[3] < 384-130 and coordinates[3] > 384-220:\n\t\t\tfrms['plan_rapproche'].append(key)\n\t\t# PLAN AMERICAIN (0.01 and 0.03) -> \n\t\t#elif ratio > 0.02 and ratio < 0.027 and coordinates[3] < 384-160:# and coordinates[3] > 384-220:\n\t\t#\tfrms['plan_americain'].append(key)\n\t\t# PLAN LARGE (0 and 0.006)\n\t\t#elif ratio < 0.006 and ratio >= 0:\n\t\t#\tfrms['plan_large'].append(key)\n\t\telse:\n\t\t\tfrms['other'].append(key)\n\t\t\tcontinue #if not chosen, do not update key\n\telse:\n\t\t#coordinates = value[0]\n\t\t#ratio = area_ratio(abs(coordinates[2]-coordinates[0]), abs(coordinates[1]-coordinates[3]), int(dim[0]), int(dim[1]))\n\t\t#if ratio >= 0 and ratio < 0.006:\n\t\t#\tfrms['plan_large'].append(key)\n\t\tfrms['other'].append(key)\n\t\t\n\told_key = key\nprint(\" \".join(str(x) for x in frms[mode]))\n","sub_path":"parse_video_info.py","file_name":"parse_video_info.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"111146925","text":"from pybeats.api import BeatsAPI\nfrom pybeats.model import Collection,SearchResult,LoggedInUser\nimport json\n\nCLIENT_ID = \"7fw6kmzz8qb4pt8g6zg7ud6x\"\nCLIENT_SECRET = \"JvRD23GQDVbCxGPaBvDNeM9a\"\n\n# USERNAME = \"your-beats-username\"\n# PASSWORD = \"your-beats-password\"\n\n# set up your api instance\napi = BeatsAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)\n\n\n#searching\ndef search_beats(the_query):\n\tsearch_results = api.get_predictive_search_results(the_query)\n\tfor result in search_results['data']:\n\t\treturn json.dumps(search_results['data'])\n\n\tget_audio(result['id'])\n\n#search and only return track\ndef search_tr(tq):\n\tresp = api.get_search_results(query=tq, search_type='track')\n\tfor result in resp['data']:\n\t\treturn json.dumps(resp['data'])\n\n\ndef get_audio(track_id):\n\taudio_results = api.get_audio_asset(track_id)\n\treturn audio_results\n","sub_path":"app/beats_api.py","file_name":"beats_api.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"158517107","text":"# -*- coding: utf-8 -*-\nimport pandas as pd \nimport os \nfrom shutil import copyfile\ncsv_file_name = input('input xception csv kmeans : ')\ndata = pd.read_csv(csv_file_name)\ndata = data.drop(['xception','Unnamed: 0'],axis=1)\ndata = data.sort_values(by=['cluster'])\n\n\nfor row in data.iterrows():\n path = os.path.join(\"clusters/{}\".format(row[1][1]))\n print(path)\n if not os.path.exists(path):\n os.mkdir(path)\n print(path,'created')\n \n if os.path.exists(path):\n print(path + ' : exists')\n dst = path+'/'+row[1][0].split('/')[-1]\n copyfile(row[1][0], dst)\n","sub_path":"xception/results_to_dir.py","file_name":"results_to_dir.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"341375886","text":"from __future__ import print_function\nimport jira.client\nfrom jira.client import JIRA\nfrom jira import JIRA, JIRAError\nimport dateutil.parser\nfrom datetime import datetime, timedelta\nimport time\nimport csv\nimport pyodbc\nimport sys\nimport logging\nimport config\nimport re\n\nimport pprint\n\n#Get 3 inputs from the user client, name, source\n#Alternately this can also be pulled from the order form. but have a check in the middle to confirm by a user\n\nimport logging\nLOG_FILENAME = 'JIRA_BUlkUploadCR.log'\nlogging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)\n\nlogging.debug('This message should go to the log file')\nclient='MODA'\ncrname='Test Change Req v9'\ncontext='Sample context...'\nsource='MCHD'\nehr='Custom or Unknown'\nimpround='InitialBuild'\nbuildtype='Analytics Implementation:951'\n\n\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\ncnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=QDWSQLOPS01;DATABASE=AnalyticsMonitoring;Trusted_Connection=TRUE')\ncursor = cnxn.cursor()\n\noptions = {'server': 'https://jira.arcadiasolutions.com'}\njira = JIRA(options, basic_auth=(config.username, config.password))\n\nrecent_issue = jira.search_issues(\n \"reporter = dinesh.jayapathy and summary~'Initial Build Kick off' ORDER BY createdDate DESC\",\n maxResults=2)\n\n# recentcount=0\nfor issueq in recent_issue:\n # if recentcount==0:\n\n try:\n exidraw = issueq.fields.customfield_11005\n except:\n exidraw = None\n # recentcount+=1\n\nprint('this is the recent exidraw: ' + str(exidraw))\n\nif exidraw is not None:\n # exid=re.match('^[^\\d]*(\\d+)',exidraw,1)\n p = re.match(r'^[^\\d]*(\\d+)', exidraw)\n exid = p.group(1)\n print('this is the exid ' + str(exid))\n\nelse:\n print('Exid is empty: ' + str(exidraw))\n\ncursor.execute(\n \"\"\"\n select Client_Acronym, Data_Source_Acronym,Important_Context,Arcadia_Implementation_Lead_Email_Address,id \n , CASE WHEN Arcadia_Implementation_Type LIKE '%Direct Feed%' THEN 'Direct Feed'\n WHEN [Data_Extraction_Connection_Type] LIKE '%Flat File%' THEN 'Flat File'\n WHEN Source_System_Software NOT LIKE '%Flat File%' AND Source_System_Software NOT LIKE '%Other%' THEN Source_System_Software\n ELSE 'Custom or Unknown' END AS EHR\n ,TRY_CONVERT(date,insert_timestamp)\n \n from ARC_OrderFormValues where ID in ('211')\n \"\"\")\n\norderform = cursor.fetchall()\n\n\n\nfor i in orderform:\n\n exid = int(exid)+1\n # print (c,i)\n client = i[0]\n source = i[1]\n context = 'Test description. Will come from excel template later on.'\n email = i[3]\n idO = i[4]\n ehr = i[5]\n impround = 'Initial Build'\n buildtype = 'Analytics Implementation:951'\n print(exid, client, source, context, email, idO)\n\n watcher = 'dinesh.jayapathy@arcadiasolutions.com'\n watcher = watcher.replace('@arcadiasolutions.com', '')\n # watcher=email.replace('@arcadiasolutions.com','')\n\n\n issue_list = [\n\n # {\n # 'project': {'key': 'AAI'},\n #\n # 'summary': client+' '+source+' '+ehr+' '+impround,#\n #\n # 'customfield_11601': {'value': client}, #this is client\n # 'customfield_11609': {'value': source },#this is the data source. It should be an existing value. Else it will error out.Works now\n # 'customfield_11626':impround, #this is impround field\n # 'description':context,\n # 'issuetype': {'name': 'Epic'},\n # 'customfield_11618':{'value':'Custom or Unknown'},\n # 'customfield_11630': {'value': 'Unknown'}, # customer contract id. manadatory For all new tickets.\n # 'customfield_10301': client+' '+source+' '+ehr+' '+impround, # Epic name. Mandatory field. For all new tickets.\n # 'assignee': {'name': watcher},\n # },\n\n { # story gets created with this setup. ClientName field casuses issue in upload.\n 'project': {'key': 'AAI'},\n # 'projectname': 'Arcadia Analytics Implementation',\n 'summary': client + ' ' + source + ' ' + ehr + ' ' + impround + ' Kick off', #\n\n # 'customfield_11601': client, #this is client. This is causing issue.\n 'customfield_11603': {'value': 'Kick off'},\n 'customfield_11609': {'value': source}, # this is the data source.\n # 'customfield_11626':{'value':impround}, #this is impround field. This is causing issue in upload.\n 'description': context,\n 'issuetype': {'name': 'Story'},\n 'customfield_11618': {'value': ehr},\n 'customfield_11630': {'value': 'Unknown'}, # customer contract id. manadatory For all new tickets.\n # 'customfield_10301': client+' '+source+' '+ehr+' '+impround, # Epic name. Mandatory field. For all new tickets.\n 'assignee': {'name': watcher},\n # 'customfield_10300': issueEpic,\n 'customfield_11005': str(exid)+str(client)+str(source)+str(ehr)+str(impround)+'Kick off' #this is the issue id it has to have proper exid\n # You can pull the exid from JIRA. Run a JQL to pull the most recent Kick off ticket uploaded by DJ. Pull the exid from that, increment it and assign it to the variable exid. For each ticket it gets incremented.\n # add epic link field after checking . Add this to story\n\n # this is a sample issue id . The first part os exid which has to be unique\n # customfield_11005': u'1604CCC NEWHOther | v. 0Initial BuildKick off',\n }\n\n ]\n\n pprint.pprint(issue_list)\n try:\n\n issues = jira.create_issues(field_list=issue_list)\n print('These are the created issues :' + str(issues))\n\n\n\n\n except Exception as e:\n\n if 'EXIST' in e.message:\n print('The issue does not exist')\n\n\n exit(1)\n else:\n print(e)","sub_path":"Projects/tet2.py","file_name":"tet2.py","file_ext":"py","file_size_in_byte":5846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"78073036","text":"from numpy import array, random\n\nfrom neural import NeuralNetwork\n\n\nclass Individual:\n \"\"\" defines individual of a population \"\"\"\n def __init__(self, layers=None, weights=None):\n self.score = 0\n # creating new random object\n if weights is None:\n self.nn = NeuralNetwork(layers=layers)\n # mutation\n else:\n self.nn = NeuralNetwork(layers=layers, weights=weights)\n \n def find_fitness(self):\n return self.score\n \n def reset(self):\n \"\"\" used during evolution of population \"\"\"\n self.score = 0\n\nclass Population:\n \"\"\" defines functions related to population of genetic algorithm \"\"\"\n def __init__(self, pop_size=1000, mutate_prob=0.03, retain_unfit_prob=0.01, select=0.333, layers=None):\n self.pop_size = pop_size # number of individuals consisiting population\n self.mutate_prob = mutate_prob # probability that a gene is mutated \n self.retain_unfit_prob = retain_unfit_prob # propability of retaining unfit individuals\n self.select = select # fraction of fittest population being selected\n self.layers = layers # layers used in neural network\n self.fitness_history = [] # stores fitness values for each generation\n\n self.generation = 1 # holds current generation number\n # population initialization\n self.individuals = [Individual(layers=layers) for i in range(self.pop_size)] \n \n def grade(self):\n \"\"\" finds population fitness \"\"\"\n self.pop_fitness = max([i.find_fitness() for i in self.individuals])\n self.fitness_history.append(self.pop_fitness)\n \n def select_parents(self):\n \"\"\" selects fittest parents with few unfittest as well \"\"\"\n self.individuals = sorted(self.individuals, key=lambda i: i.find_fitness(), reverse=True)\n # selecting fittest parents\n parents_selected = int(self.select * self.pop_size)\n self.parents = self.individuals[:parents_selected]\n # including some unfittest parents\n unfittest = self.individuals[parents_selected:]\n for i in unfittest:\n if self.retain_unfit_prob > random.rand():\n self.parents.append(i)\n \n # reset properties of parents\n for individual in self.parents:\n individual.reset()\n\n \n def crossover(self, weights1, weights2):\n \"\"\" combines the genes of two parent to form genes of child \"\"\"\n weights = []\n\n for w1, w2 in zip(weights1, weights2):\n w = []\n for column1, column2 in zip(w1, w2):\n column = []\n for theta1, theta2 in zip(column1, column2):\n # selecting randomly from father or mother genes\n choosen = random.choice((theta1, theta2)) \n column.append(choosen)\n w.append(column)\n weights.append(array(w))\n return weights\n\n def breed(self):\n \"\"\" creates new children for populating the population using fittest parents \"\"\"\n children_size = self.pop_size - len(self.parents)\n children = []\n if len(self.parents) > 0:\n while len(children) < children_size:\n father = random.choice(self.parents)\n mother = random.choice(self.parents)\n if father != mother:\n child_weights = self.crossover(father.nn.weights, mother.nn.weights)\n child = Individual(layers=self.layers, weights=child_weights)\n children.append(child)\n \n self.individuals = self.parents + children\n\n def evolve(self):\n \"\"\" define process of evolution \"\"\"\n self.grade()\n self.select_parents()\n self.breed()\n\n print(f'{self.generation} --> {self.fitness_history[-1]}') \n self.generation += 1","sub_path":"genetic.py","file_name":"genetic.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"645026288","text":"import math\n\nfrom ..data_structures.source_shared import SourceVector\n\n\ndef convert_rotation_matrix_to_degrees(m0, m1, m2, m3, m4, m5, m8):\n angle_y = -math.asin(round(m2, 6))\n c = math.cos(angle_y)\n if abs(c) > 0.005:\n translate_x = m8 / c\n translate_y = -m5 / c\n angle_x = (math.atan2(translate_y, translate_x))\n translate_x = m0 / c\n translate_y = -m1 / c\n angle_z = (math.atan2(translate_y, translate_x))\n else:\n angle_x = 0\n translate_x = m4\n translate_y = m3\n angle_z = (math.atan2(translate_y, translate_x))\n return angle_x, angle_y, angle_z\n\ndef vector_i_transform(input: SourceVector,\n matrix_c0: SourceVector, \n matrix_c1: SourceVector,\n matrix_c2: SourceVector,\n matrix_c3: SourceVector):\n temp = SourceVector()\n output = SourceVector()\n\n temp.x = input.x - matrix_c3.x\n temp.y = input.y - matrix_c3.y\n temp.z = input.z - matrix_c3.z\n\n output.x = temp.x * matrix_c0.x + temp.y * matrix_c0.y + temp.z * matrix_c0.z\n output.y = temp.x * matrix_c1.x + temp.y * matrix_c1.y + temp.z * matrix_c1.z\n output.z = temp.x * matrix_c2.x + temp.y * matrix_c2.y + temp.z * matrix_c2.z\n\n return output\n","sub_path":"All_In_One/addons/SourceIO/utilities/math_utilities.py","file_name":"math_utilities.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"335086521","text":"import json\nimport unittest\nimport warnings\n\nfrom parameterized import parameterized\n\nfrom data.Get_TestData.Get_D1_AM_Data import Get_SM_TestData\nfrom lib.D1_UserList_Action import UL_Action\nfrom tools.service import Service\nfrom tools.util import Utility\n\nclass AM_Test(unittest.TestCase):\n\n def setUp(self) -> None:\n Utility.initialize_DB()\n warnings.simplefilter('ignore', ResourceWarning)\n self.ul = UL_Action(Service.get_session_tm())\n\n # 查询演员\n @parameterized.expand(Get_SM_TestData.get_login_excel_data_query_actor(1))\n def test_SurroundingMall_query_actor(self, url, res_method, cases_name, expected):\n edit_data = {\"CASENAME\": cases_name, \"URL\": url, \"METHOD\": res_method, \"EXPECTED\": expected}\n result = self.ul.doGet(edit_data['URL'])\n\n if edit_data['CASENAME'] == \"查询存在的电影名\":\n if edit_data['METHOD'] == \"GET\":\n actual = str(json.loads(result)['count'])\n\n elif edit_data['CASENAME'] == \"查询不存在的电影名\":\n if edit_data['METHOD'] == \"GET\":\n actual = str(json.loads(result)['count'])\n\n elif edit_data['CASENAME'] == \"查询不存在的page\":\n if edit_data['METHOD'] == \"GET\":\n actual = str(json.loads(result)['count'])\n\n else:\n edit_data['CASENAME'] = '用例名错误'\n\n Utility.logger(edit_data['CASENAME'], actual, actual, expected)\n self.assertEqual(actual, edit_data['EXPECTED'])\n\n # 删除演职演员\n @parameterized.expand(Get_SM_TestData.get_login_excel_data_delete_actor(1))\n def test_SurroundingMall_delete_actor(self, url, res_method, cases_name, expected):\n delete_data = {\"CASENAME\": cases_name, \"URL\": url, \"METHOD\": res_method, \"EXPECTED\": expected}\n result = self.ul.doDelete(delete_data['URL'])\n if delete_data['CASENAME'] == \"删除存在的演职人员ID\":\n if delete_data['METHOD'] == \"DELETE\":\n actual = json.loads(result)['msg']\n\n elif delete_data['CASENAME'] == \"删除不存在的演职人员ID\":\n if delete_data['METHOD'] == \"DELETE\":\n actual = json.loads(result)['msg']\n\n else:\n delete_data['CASENAME'] = '用例名错误'\n\n Utility.logger(delete_data['CASENAME'], actual, actual, expected)\n self.assertEqual(actual, delete_data['EXPECTED'])\n\n # 增加演职演员\n @parameterized.expand(Get_SM_TestData.get_login_excel_data_add_actor(1))\n def test_SurroundingMall_add_actor(self, url, res_method, mid, realName, actorType, role, actorPic, cases_name,\n expected):\n add_data = {\"CASENAME\": cases_name, \"URL\": url, \"METHOD\": res_method,\n \"DATA\": {\"mid\": mid, \"realName\": realName, \"actorType\": actorType, \"role\": role,\n \"actorPic\": actorPic}, \"EXPECTED\": expected}\n\n actual = \"\"\n if add_data['CASENAME'] == \"添加演职人员ID\":\n if add_data['METHOD'] == \"POST\":\n result = self.ul.doPost(add_data['URL'], add_data['DATA'])\n actual = json.loads(result)['msg']\n\n elif add_data['CASENAME'] == \"添加不存在的演职人员ID\":\n if add_data['METHOD'] == \"DELETE\":\n result = self.ul.doPost(add_data['URL'], add_data['DATA'])\n actual = json.loads(result)['msg']\n\n elif add_data['CASENAME'] == \"添加重复的演职人员ID\":\n if add_data['METHOD'] == \"POST\":\n result = self.ul.doPost(add_data['URL'], add_data['DATA'])\n actual = json.loads(result)['msg']\n else:\n add_data['CASENAME'] = '用例名错误'\n Utility.logger(add_data['CASENAME'], actual, actual, expected)\n self.assertEqual(actual, add_data['EXPECTED'])\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"2.Travel_Request/cases/D1_ActorManagement_Test.py","file_name":"D1_ActorManagement_Test.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"591628783","text":"#!/usr/bin/env python\n\"\"\"\n_User.GetAssociation_\n\nRetrieve a user/group association\n\n\"\"\"\n\n\n\n\nfrom WMCore.Database.DBFormatter import DBFormatter\n\n\nclass GetAssociation(DBFormatter):\n \"\"\"\n _GetAssociation_\n\n Get the associations between a requestor and groups given the\n requestor DB id.\n A list of group IDs is returned.\n\n \"\"\"\n\n def execute(self, requestorId, conn = None, trans = False):\n \"\"\"\n _execute_\n\n\n\n \"\"\"\n self.sql = \"SELECT group_id FROM reqmgr_group_association \"\n self.sql += \" WHERE requestor_id = :requestor_id\"\n binds = {\"requestor_id\": requestorId}\n result = self.dbi.processData(self.sql, binds,\n conn = conn, transaction = trans)\n values = [ x[0] for x in self.format(result)]\n return values\n","sub_path":"src/python/WMCore/RequestManager/RequestDB/MySQL/Requestor/GetAssociation.py","file_name":"GetAssociation.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"269497314","text":"from system.models import UserProfile\n\n\ndef datos_globales(request):\n\n try:\n profile = UserProfile.objects.get(user=request.user)\n grupo = profile.get_grupo_display()\n except Exception:\n grupo = \"\"\n\n contexto = {\n 'grupo': grupo\n }\n\n return contexto\n","sub_path":"hermespy/global_settings.py","file_name":"global_settings.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"601492163","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 15 22:36:12 2017\r\n\r\n@author: Anton Varfolomeev\r\n\"\"\"\r\n\r\nimport pickle\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport os\r\nfrom skimage.feature import hog\r\n\r\nfrom extract_features import *\r\nfrom process_image import *\r\nimport time\r\n\r\n\r\n\r\nos.chdir('D:\\\\WORK\\\\CarND\\\\p5\\\\CarND-P5')\r\ntest_dir = './test_images/'\r\nout_dir = './out/'\r\n\r\n\r\n#%%\r\n\r\nimages = []\r\nfor entry in os.scandir(test_dir):\r\n if entry.is_file():\r\n print(entry.path)\r\n img = cv2.imread(entry.path)\r\n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n images.append(img)\r\n\r\n\r\n#%%\r\n# Read in our vehicles and non-vehicles\r\n\r\ndef get_image_list(path):\r\n images = [os.path.join(dirpath, f)\r\n for dirpath, dirnames, files in os.walk(path)\r\n for f in files if f.endswith('.png')]\r\n return images\r\n \r\npath = 'e:/data/carnd/p5/'\r\ncars = get_image_list(path+'vehicles')\r\nnotcars = get_image_list(path+'non-vehicles')\r\n\r\nmyPath = 'e:/data/carnd/p5/my/'\r\nmyCars = get_image_list(myPath + 'Car')\r\nmyNotCars = get_image_list(myPath + 'NotCars')\r\n\r\n#%%\r\ncolorspace = 'HLS' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\r\norient = 11\r\npix_per_cell = 8\r\ncell_per_block = 2\r\nhog_channel = 'ALL' #(1,2) # Can be 0, 1, 2, or \"ALL\"\r\n\r\nt=time.time()\r\n\r\ncar_features = extract_features(cars, cspace=colorspace, orient=orient, \r\n pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, \r\n hog_channel=hog_channel)\r\nnotcar_features = extract_features(notcars, cspace=colorspace, orient=orient, \r\n pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, \r\n hog_channel=hog_channel)\r\nt2 = time.time()\r\nprint(round(t2-t, 2), 'Seconds to extract HOG features...')\r\n# Create an array stack of feature vectors\r\nX = np.vstack((car_features, notcar_features)).astype(np.float64) \r\n# Fit a per-column scaler\r\nX_scaler = StandardScaler().fit(X)\r\n# Apply the scaler to X\r\nscaled_X = X_scaler.transform(X).astype(np.float32)\r\n\r\n# Define the labels vector\r\ny = np.hstack((np.ones(len(car_features)), \r\n np.zeros(len(notcar_features)))).astype(np.int32)\r\n\r\n\r\n# Split up data into randomized training and test sets\r\nrand_state = np.random.randint(0, 100)\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n scaled_X, y, test_size=0.2, random_state=rand_state)\r\n\r\nprint('Using:',orient,'orientations',pix_per_cell,\r\n 'pixels per cell and', cell_per_block,'cells per block')\r\nprint('Feature vector length:', len(X_train[0]))\r\n# Use a linear SVC \r\n\r\n\r\n#%% \r\n# Check the training time for the SVC\r\nuSvm = cv_svm (X_train, X_test, y_train, y_test)\r\n#%%\r\n# Check the prediction time for a single sample\r\n\r\nidx = np.arange(len(y_test))\r\nnp.random.shuffle(idx)\r\n\r\nt=time.time()\r\nn_predict = 1000\r\nyr = np.zeros(n_predict)\r\n\r\n#for i in range (n_predict):\r\nyr = uSvm.predict(X_test[idx[:n_predict]])[1].ravel()\r\nprint(sum( yr != y_test[idx[0:n_predict]]), \" mistakes from \", n_predict)\r\n#print('For these',n_predict, 'labels: ', y_test[0:n_predict])\r\nt2 = time.time()\r\nprint(round(t2-t, 5), 'Seconds to predict', n_predict,'labels with SVC')\r\n\r\n\r\n#%%\r\nt=time.time()\r\nmyCarFeatures = extract_features(myCars, cspace=colorspace, orient=orient, \r\n pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, \r\n hog_channel=hog_channel)\r\nmyNotCarFeatures = extract_features(myNotCars, cspace=colorspace, orient=orient, \r\n pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, \r\n hog_channel=hog_channel)\r\nt2 = time.time()\r\nprint(round(t2-t, 2), 'Seconds to extract HOG features...')\r\n# Create an array stack of feature vectors\r\nmyX = np.vstack((myCarFeatures, myNotCarFeatures)).astype(np.float64) \r\n# Fit a per-column scaler\r\nX_scaler = StandardScaler().fit(myX)\r\n# Apply the scaler to X\r\nscaled_X = X_scaler.transform(myX).astype(np.float32)\r\n\r\n# Define the labels vector\r\nmyY = np.hstack((np.ones(len(myCarFeatures)), \r\n np.zeros(len(myNotCarFeatures)))).astype(np.int32)\r\n\r\n\r\n# Split up data into randomized training and test sets\r\nrand_state = np.random.randint(0, 100)\r\nmyX_train, myX_test, myY_train, myY_test = train_test_split(\r\n scaled_X, myY, test_size=0.1, random_state=rand_state)\r\n#%%\r\nmySvm = cv_svm (myX_train, myX_test, myY_train, myY_test)\r\n\r\n# Check the score of the SVC\r\nprint('Test Accuracy of mySVC on my data = ', round(score(mySvm,myX_test, myY_test), 4))\r\nprint('Test Accuracy of uSVC on my data = ', round(score(uSvm,myX_test, myY_test), 4))\r\nprint('Test Accuracy of mySVC on u data = ', round(score(mySvm,X_test, y_test), 4))\r\nprint('Test Accuracy of uSVC on u data = ', round(score(uSvm,X_test, y_test), 4))\r\n\r\n#%%\r\nidx = np.arange(len(myY_test))\r\nnp.random.shuffle(idx)\r\n\r\nt=time.time()\r\nn_predict = 1000\r\nyr = uSvm.predict(myX_test[idx[0:n_predict]])[1].ravel()\r\n#print('For these',n_predict, 'labels: ', y_test[0:n_predict])\r\nt2 = time.time()\r\nprint(\"u on my\",sum( yr != myY_test[idx[0:n_predict]]), \" mistakes from \", n_predict)\r\nprint(round(t2-t, 5), 'Seconds to predict', n_predict,'labels with SVC')\r\n\r\nt=time.time()\r\nyr = mySvm.predict(myX_test[idx[0:n_predict]])[1].ravel()\r\n#print('For these',n_predict, 'labels: ', y_test[0:n_predict])\r\nt2 = time.time()\r\nprint(\"my on my\",sum( yr != myY_test[idx[0:n_predict]]), \" mistakes from \", n_predict)\r\nprint(round(t2-t, 5), 'Seconds to predict', n_predict,'labels with SVC')\r\n\r\n#%%\r\nunX_train = np.vstack((myX_train, X_train));\r\nunY_train = np.hstack((myY_train, y_train));\r\nunX_test = np.vstack((X_test, myX_test));\r\nunY_test = np.hstack((y_test, myY_test));\r\n\r\nfrom sklearn.utils import shuffle\r\n\r\nunX_train, unY_train = shuffle(unX_train, unY_train)\r\n\r\nunX_test, unY_test = shuffle(unX_test, unY_test)\r\n\r\n#%%\r\nunSvm = cv_svm (unX_train, unX_test, unY_train, unY_test)\r\n\r\nprint('Test Accuracy of unSvm on my data = ', round(score(unSvm,myX_test, myY_test), 4))\r\nprint('Test Accuracy of unSvm on u data = ', round(score(unSvm,X_test, y_test), 4))\r\n\r\n#%%\r\n#grid-search for optimal SVM parameters\r\n\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import RandomizedSearchCV\r\ndo_fit = False;\r\n\r\nif (do_fit):\r\n parameters = {'C': np.arange(0.5, 2.4, .1), 'gamma': np.arange(6.4e-4, 6.6e-4, 1e-5)}\r\n svr = svm.SVC()\r\n clf = GridSearchCV(svr, parameters)\r\n np.random.shuffle(idx)\r\n X_tr = unX_train[idx[:1000]]\r\n y_tr = unY_train[idx[:1000]]\r\n \r\n clf.fit(X_tr, y_tr)\r\n \r\n print(clf.best_params_, clf.best_score_)\r\n\r\n#%%-\r\nfrom moviepy.editor import VideoFileClip\r\n\r\nthr = 18\r\ntau = 0.95\r\nscales = [3, 4, 5]\r\nheat = np.zeros_like(img[:,:,0]).astype(np.float)\r\nscales = [3, 4, 5]\r\n\r\n \r\nvideo_output = 'out/p5C08sc%d_%.2f_%.1f.mp4' % (345, tau, thr)\r\nclip = VideoFileClip('project_video.mp4')#.subclip(30,45)\r\n#clip = VideoFileClip('E:\\\\Data\\\\USA\\\\Video\\\\cuts\\\\multiple_01.avi') \r\nfirst_clip = clip.fl_image(process_image)\r\nget_ipython().magic('time first_clip.write_videofile(video_output, audio=False)')\r\n\r\n\r\n","sub_path":"p5.py","file_name":"p5.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"435123575","text":"from itertools import combinations\n\nN = int(input())\nS = list(input().split())\nK = int(input())\n\ncombos = list(combinations(S,K))\n\ntrue_count = 0\n\nfor element in combos:\n\tfound = False\n\tfor j in element:\n\t\tif j == 'a':\n\t\t\ttrue_count += 1\n\t\t\tfound = True\n\t\t\tbreak\n\nprint(\"{0:.4f}\".format( true_count/len(combos)))\n","sub_path":"Python/Itertools/IterablesAndIterators.py","file_name":"IterablesAndIterators.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"482779082","text":"import sys\nfrom translate import translate\n\n\"\"\"\nFirst element is three letter representation of amino acid\nSecond element: one letter representaion of amino acid\nThird element: kdHydrophobicity\nFourth element: wwHydrophobicity\nFifth element: hhHydrophobicity\n\"\"\"\n\nhydrophobicity = [\n (\"Ile\", \"I\", 4.5, 0.31, -0.60 ),\n (\"Val\", \"V\", 4.2, -0.07, -0.31),\n (\"Leu\", \"L\", 3.8, 0.56, -0.55),\n (\"Phe\", \"F\", 2.8, 1.13, -0.32),\n (\"Cys\", \"C\", 2.5, 0.24, -0.13),\n (\"Met\", \"M\", 1.9, 0.23, -0.10),\n (\"Ala\", \"A\", 1.8, -0.17, 0.11),\n (\"Gly\", \"G\", -0.4, -0.01, 0.74),\n (\"Thr\", \"T\", -0.7, -0.14, 0.52),\n (\"Ser\", \"S\", -0.8, -0.13, 0.84),\n (\"Trp\", \"W\", -0.9, 1.85, 0.30),\n (\"Tyr\", \"Y\", -1.3, 0.94, 0.68),\n (\"Pro\", \"P\", -1.6, -0.45, 2.23),\n (\"His\", \"H\", -3.2, -0.96, 2.06),\n (\"Glu\", \"E\", -3.5, -2.02, 2.68),\n (\"Gln\", \"Q\", -3.5, -0.58, 2.36),\n (\"Asp\", \"D\", -3.5, -1.23, 3.49),\n (\"Asn\", \"N\", -3.5, -1.23, 3.49),\n (\"Lys\", \"K\", -3.9, -0.99, 2.71),\n (\"Arg\", \"R\", -4.5, -0.81, 2.58)\n]\n\n\"\"\"\nget the total hydrophobicity given the region length\nprint out the regions that have high hydrophobicity\n@param aminoAcid \n@param minLen minimal length of region\n@param maxLen maximum length of region\n\"\"\"\ndef getHdyroRegion(aminoAcid, minLen, maxLen):\n acid = aminoAcid[0 : len(aminoAcid) - 4] # remove \"stop\" codon\n print(acid)\n results = [] #store potential region\n resultsIndex = [] #store region index\n preI = -999\n preLen = 0\n for i in range(0, len(acid) - minLen + 1): #loop through amino acid with given length\n for j in range(minLen, maxLen): #try different length of region: from min to max\n hydroSum = 0 \n if((i + j) < len(acid)): #aviod out of bound\n region = acid[i : i + j] #get subregion \n for k in range(0, j ): #sum up the hydro. \n hydroSum += getHydro(region[k])\n flag = (i - preI) >= preLen #the start index of second region should at least j away from the start of previous region\n if (hydroSum >= 45) and flag: # if the sum is greater than a critical value, then it is a transport potein \n results.append(region) # store subregion\n preLen = len(region)\n preI = i\n index = (i, i + j)\n resultsIndex.append(index)\n break #once find a high hydro. stop increasing the length of region \n else:\n continue #continue increase the size of region\n print(resultsIndex, end=\"\\n\")\n print(results, end=\"\\n\\n\") #print subregion. Will decide how to highlight the region\n\n\"\"\"\nget the individual hydrophobicity\n@param acid individual aminio acid\n@return hhHydrophobicity by default\n\"\"\"\ndef getHydro(acid): #get individual hydro. given an acid\n for acidHydro in hydrophobicity:\n if acid in acidHydro[1]: \n return acidHydro[4]\n\n\n\ndef main(argv):\n\t\"\"\"\n\t\tGiven a FASTA file, translate from RNA to amino acids\n\t\t\n\t\tUsage:\n\t\tpython main.py fasta.txt\n\t\"\"\"\n\tif(len(argv) < 2):\n\t\tprint(\"Translates RNA sequences in a FASTA file into an amino acid sequence\")\n\t\tprint(\"Usage: python\", argv[0], \"fasta.txt\")\n\t\treturn\n\t\n\tfile = open(argv[1], \"r\")\n\tfor line in file:\n\t\tif line[0] == \">\":\n\t\t\tname = line[1:-1] #Omits the > and the newline character\n\t\t\tsequence = file.readline()[:-1] #Omits the newline character\n\t\t\tprint(name)\n\t\t\ttranslation = translate(sequence)\n \n\t\t\tgetHdyroRegion(str(translation), 17, 22)\n \n\t\t\t\nif __name__ == \"__main__\":\n\tmain(sys.argv)","sub_path":"getHydro.py","file_name":"getHydro.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"281400088","text":"import datetime as dt\nfrom tkinter import *\n\nimport pymongo\n\n\ndef get_mongo():\n global get_data\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n mydb = myclient[\"Sensor_Record\"]\n mycol = mydb[\"data1\"]\n for get_data in mycol.find({}, {\"_id\": 0, \"Sensor No\": 1}):\n print(get_data)\n return get_data\n\n\ndef drag_start(event):\n widget = event.widget\n widget.startX = event.x\n widget.startY = event.y\n\n\ndef drag_motion(event):\n widget = event.widget\n x = widget.winfo_x() - widget.startX + event.x\n y = widget.winfo_y() - widget.startY + event.y\n widget.place(x=x, y=y)\n\n\ndef time_func():\n time_data = dt.datetime.now().strftime('%Y-%m-%d %X')\n return time_data\n\n\nroot = Tk()\nroot.title(\"DragTable\")\nroot.geometry(\"800x600\")\nroot.state('zoomed')\n\n# root.configure(bg='white')\n\n\nhello_button = Button(root, text=\"Hello\", pady=6)\n\nhello_button.pack()\n\nlabel = Label(root, bg=\"red\", width=8, height=4, text=time_func(), fg='blue', pady=10, padx=10, font=10)\nlabel.place(x=150, y=150)\n# label.config(text=print_func())\n\nlabel2 = Label(root, bg=\"blue\", width=8, height=4, text=\"BLUE\")\nlabel2.place(x=300, y=300)\n\nlabel3 = Label(root, bg=\"green\", width=8, height=4, text=\"GREEN\")\nlabel3.place(x=450, y=450)\n\nrectangle1 = Canvas(root, width=500, height=200)\nrectangle1.pack()\n\nrectangle1.create_rectangle(20, 140, 120, 180, fill=\"red\")\nrectangle1.create_text(70, 130, text=\"Projects--20%\")\nrectangle1.create_rectangle(140, 160, 240, 180, fill=\"blue\")\nrectangle1.create_text(190, 150, text=\"Quizzes--10%\")\nrectangle1.create_rectangle(260, 120, 360, 180, fill=\"green\")\nrectangle1.create_text(310, 110, text=\"Midterm--30%\")\nrectangle1.create_rectangle(380, 100, 480, 180, fill=\"orange\")\nrectangle1.create_text(430, 90, text=\"Final--40%\")\nrectangle1.create_line(0, 180, 500, 180)\n\nrect2 = Canvas(root, width=250, height=250)\nrect2.pack()\nrect2.create_rectangle(40, 180, 160, 220, fill=\"black\")\nrect2.create_text(70, 130, text=time_func())\n\nrectangle1.bind(\"\", drag_start)\nrectangle1.bind(\"\", drag_motion)\n\nrect2.bind(\"\", drag_start)\nrect2.bind(\"\", drag_motion)\n\nlabel.bind(\"\", drag_start)\nlabel.bind(\"\", drag_motion)\n\nlabel2.bind(\"\", drag_start)\nlabel2.bind(\"\", drag_motion)\n\nlabel3.bind(\"\", drag_start)\nlabel3.bind(\"\", drag_motion)\n\nhello_button.bind(\"\", drag_start)\nhello_button.bind(\"\", drag_motion)\n\nget_mongo()\nroot.mainloop()\n","sub_path":"version4.py","file_name":"version4.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"637784473","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author:\n Lucas Yuki Imamura\n Maria Fernanda Bittelbrunn Toniasso\n Vitor Hugo Homem Marzarotto\n\"\"\"\nimport images\nfrom pygame.sprite import Sprite\nfrom core import RSurface\nimport pygame as pg\nimport math\nimport os\n\n\nclass GameObject(Sprite):\n __bounce_dist = 30\n\n def __init__(self, image_dict: dict, sound_dict: dict, ang: float,\n screen_size: tuple, vel=(0, 0), groups=None):\n \"\"\"\n Parameters\n ----------\n radius : float\n Raio do Ator (para bounding box).\n image_dict : dict\n Dicionario com os sprites do Ator.\n size : tuple\n Tamanho do Ator.\n framerate : float\n Quantidade de frames por segundo\n vel : TYPE, optional\n Velocidade inicial. The default is (0, 0).\n groups : TYPE, optional\n Grupo inicial. The default is None.\n \"\"\"\n self.__rect = pg.Rect(0, 0, 0, 0)\n self.__center = [0, 0]\n\n self.__image_dict = {key: self.load_img(\n **args) for key, args in image_dict.items()}\n self.vel = vel\n self.ang = ang\n self.__screen_size = screen_size\n\n self.__state = list(self.__image_dict.keys())[0]\n self.__image = self.__image_dict[self.__state]\n\n self.state = self.__state\n\n super().__init__(groups)\n\n self.__new_angle = True\n self.__moving = True\n self.__savedgroup = groups\n\n @property\n def radius(self):\n return self.__radius\n\n @radius.setter\n def radius(self, radius: float):\n self.__radius = radius\n self.__radius2 = radius*radius\n\n @property\n def radius2(self):\n return self.__radius2\n\n @property\n def vel(self):\n return self.__vel\n\n @vel.setter\n def vel(self, vel):\n self.__vel = vel\n if abs(self.__vel[0]) + abs(self.__vel[1]) > 0:\n self.__moving = True\n else:\n self.__moving = False\n\n @property\n def ang(self):\n return self.__ang\n\n @ang.setter\n def ang(self, ang):\n self.__ang = ang\n self.__new_angle = True\n self.calc_angle_vector()\n\n @property\n def angle_vector(self):\n return self.__angle_vector\n\n def calc_angle_vector(self):\n ang = math.radians(self.ang)\n self.__angle_vector = (math.cos(ang), -math.sin(ang))\n\n @property\n def screen_size(self):\n return self.__screen_size\n\n @property\n def rect(self):\n return self.__rect\n\n @rect.setter\n def rect(self, position):\n self.__rect.x = position[0]\n self.__rect.y = position[1]\n\n @property\n def center(self):\n return self.__center\n\n @center.setter\n def center(self, pos: list):\n try:\n pos = list(pos)\n assert len(pos) == 2\n except (TypeError, AssertionError) as e:\n print(\"'pos' must be an iterable with x in the first\" +\n \"position and y in the second\")\n raise e\n\n self.__center = pos\n self.__centralize_image()\n\n @property\n def image(self):\n return self.__image\n\n @property\n def state(self):\n return self.__state\n\n @state.setter\n def state(self, new_state):\n self.__state = new_state\n self.__image = self.__image_dict[self.__state]\n\n self.__centralize_image()\n self.radius = self.__image.radius\n\n self.__lim_x_inf = self.__radius + self.__bounce_dist\n self.__lim_y_inf = self.__radius + self.__bounce_dist\n temp = self.__radius + self.__bounce_dist\n self.__lim_x_sup = self.__screen_size[0] - temp\n self.__lim_y_sup = self.__screen_size[1] - temp\n\n @property\n def lim_x_inf(self):\n return self.__lim_x_inf\n\n @property\n def lim_y_inf(self):\n return self.__lim_y_inf\n\n @property\n def lim_x_sup(self):\n return self.__lim_x_sup\n\n @property\n def lim_y_sup(self):\n return self.__lim_y_sup\n\n def load_img(self, R=None, path=None, size=None, image=None):\n\n if image is not None:\n return image\n\n superficie = RSurface(R, size, pg.SRCALPHA)\n\n image = pg.image.load(path)\n image.set_colorkey((255, 255, 255))\n image = image.convert_alpha()\n image = pg.transform.scale(image, size)\n superficie.blit(image, (0, 0))\n return superficie\n\n def revive(self):\n for g in self.__savedgroup:\n g.add(self)\n\n def __centralize_image(self):\n img_size = self.__image.get_size()\n h_size = (img_size[0]/2, img_size[1]/2,)\n self.__rect.update(self.__center[0]-h_size[0],\n self.__center[1]-h_size[1],\n *img_size)\n\n def __rotate(self):\n self.__image = pg.transform.rotate(self.__image_dict[self.state],\n self.ang)\n self.__centralize_image()\n self.__new_angle = False\n\n def move(self, x, y):\n self.__center[0] += x\n self.__center[1] += y\n\n # melhorar dps espelhando o excesso\n if self.__center[0] < self.lim_x_inf:\n self.__center[0] = self.lim_x_inf\n self.vel = (-self.vel[0], self.vel[1])\n elif self.__center[0] > self.lim_x_sup:\n self.__center[0] = self.lim_x_sup\n self.vel = (-self.vel[0], self.vel[1])\n\n # melhorar dps espelhando o excesso\n if self.__center[1] < self.lim_y_inf:\n self.__center[1] = self.lim_y_inf\n self.vel = (self.vel[0], -self.vel[1])\n elif self.__center[1] > self.lim_y_sup:\n self.__center[1] = self.lim_y_sup\n self.vel = (self.vel[0], -self.vel[1])\n\n self.__centralize_image()\n\n def update(self, dt):\n \"\"\"\n Parameters\n ----------\n new_pos : TYPE, optional\n Forçar nova posição do autor, se nada for passado, é calculado\n com base na posição antiga e velocidade atual.\n The default is None.\n\n Returns\n -------\n new_pos: tuple\n Nova posição do Ator.\n\n \"\"\"\n if self.__moving:\n self.move(*self.vel)\n\n if self.__new_angle:\n self.__rotate()\n","sub_path":"core/GameObject.py","file_name":"GameObject.py","file_ext":"py","file_size_in_byte":6329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"278259892","text":"import tensorflow as tf\nimport numpy as np\n\nclass CNN_LSTM:\n \n def __init__(self,x,weights,biases,num_filters):\n self.x = x \n self.weights = weights\n self.biases = biases\n self.num_filters = num_filters\n\n def CNN_(self):\n x = tf.transpose(self.x,[0,2,1])\n print(x.get_shape)\n conv1 = tf.nn.conv1d(x,self.weights['conv1'],1,'SAME')\n conv1 = tf.nn.bias_add(conv1,self.biases['conv1'])\n conv1 = tf.keras.layers.BatchNormalization()(conv1)\n conv1 = tf.nn.relu(conv1)\n print(np.array(conv1))\n # 第二层卷积\n conv2 = tf.nn.conv1d(conv1,self.weights['conv2'],1,'SAME')\n conv2 = tf.nn.bias_add(conv2,self.biases['conv2'])\n conv2 = tf.keras.layers.BatchNormalization()(conv2)\n conv2 = tf.nn.relu(conv2)\n print(np.array(conv2))\n # # 第三层卷积\n conv3 = tf.nn.conv1d(conv2,self.weights['conv3'],1,'SAME')\n conv3 = tf.nn.bias_add(conv3,self.biases['conv3'])\n conv3 = tf.keras.layers.BatchNormalization()(conv3)\n conv3 = tf.nn.relu(conv3)\n print(np.array(conv3))\n # 第四层\n conv4 = tf.nn.conv1d(conv3,self.weights['conv4'],1,'SAME')\n conv4 = tf.nn.bias_add(conv4,self.biases['conv4'])\n conv4 = tf.keras.layers.BatchNormalization()(conv4)\n conv4 = tf.nn.relu(conv4)\n print(np.array(conv4))\n # 第五层\n conv5 = tf.nn.conv1d(conv4,self.weights['conv5'],1,'SAME')\n conv5 = tf.nn.bias_add(conv5,self.biases['conv5'])\n conv5 = tf.keras.layers.BatchNormalization()(conv5)\n conv5 = tf.nn.relu(conv5)\n print(np.array(conv5))\n\n conv6 = tf.nn.conv1d(conv5,self.weights['conv6'],1,'SAME')\n conv6 = tf.nn.bias_add(conv6,self.biases['conv6'])\n conv6 = tf.keras.layers.BatchNormalization()(conv6)\n conv6 = tf.nn.relu(conv6)\n print(np.array(conv6))\n\n conv7 = tf.nn.conv1d(conv6,self.weights['conv7'],1,'SAME')\n conv7 = tf.nn.bias_add(conv7,self.biases['conv7'])\n conv7 = tf.keras.layers.BatchNormalization()(conv7)\n conv7 = tf.nn.relu(conv7)\n print(np.array(conv7))\n # 第五层\n conv8 = tf.nn.conv1d(conv7,self.weights['conv8'],1,'SAME')\n conv8 = tf.nn.bias_add(conv8,self.biases['conv8'])\n conv8 = tf.keras.layers.BatchNormalization()(conv8)\n conv8 = tf.nn.relu(conv8)\n print(np.array(conv8))\n\n conv9 = tf.nn.conv1d(conv8,self.weights['conv9'],1,'SAME')\n conv9 = tf.nn.bias_add(conv9,self.biases['conv9'])\n conv9 = tf.keras.layers.BatchNormalization()(conv9)\n conv9 = tf.nn.relu(conv9)\n print(np.array(conv9))\n conv9 = tf.keras.layers.GlobalAveragePooling1D()(conv9)\n return conv9\n\n def LSTM_(self):\n cnn_out = self.CNN_()\n lstm = tf.keras.layers.LSTM(self.num_filters)(cnn_out)\n return lstm\n\n def Return_out(self):\n # lstm_out = self.LSTM_()\n cnn_out = self.CNN_()\n return_out = tf.add(tf.matmul(cnn_out,self.weights['out_w']),self.biases['out_b'])\n\n return return_out","sub_path":"FCN_LSTM/C-LSTM/cnn_lstm_model9.py","file_name":"cnn_lstm_model9.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"354630299","text":"import logging\nimport logging.handlers\n\n_LOG_FMT = '%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s'\n\nlogger = logging.getLogger('i3-workspace-groups')\n\ndef init_logger(name: str) -> None:\n syslog_handler = logging.handlers.SysLogHandler(address='/dev/log')\n stdout_handler = logging.StreamHandler()\n stdout_formatter = logging.Formatter(_LOG_FMT)\n stdout_handler.setFormatter(stdout_formatter)\n syslog_formatter = logging.Formatter('{}: {}'.format(name, _LOG_FMT))\n syslog_formatter.ident = name\n syslog_handler.setFormatter(syslog_formatter)\n logger.addHandler(syslog_handler)\n logger.addHandler(stdout_handler)\n","sub_path":"i3wsgroups/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"130963803","text":"\"\"\"Some functions from R-base\n\nIf a function uses DataFrame/DataFrameGroupBy as first argument, it may be\nregistered by `register_verb` and should be placed in `./verbs.py`\n\"\"\"\nimport itertools\nfrom typing import Any, Iterable, Optional\n\nimport pandas\nfrom pandas import Categorical, DataFrame\nfrom pipda import register_func\n\nfrom ..core.middlewares import WithDataEnv\nfrom ..core.types import NumericType\nfrom ..core.contexts import Context\n\n@register_func(None, context=Context.EVAL)\ndef cut(\n x: Iterable[NumericType],\n breaks: Any,\n labels: Optional[Iterable[Any]] = None,\n include_lowest: bool = False,\n right: bool = True,\n precision: int = 2,\n ordered_result: bool = False\n) -> Categorical:\n \"\"\"Divides the range of x into intervals and codes the values in x\n according to which interval they fall. The leftmost interval corresponds\n to level one, the next leftmost to level two and so on.\n\n Args:\n x: a numeric vector which is to be converted to a factor by cutting.\n breaks: either a numeric vector of two or more unique cut points or\n a single number (greater than or equal to 2) giving the number of\n intervals into which x is to be cut.\n labels: labels for the levels of the resulting category. By default,\n labels are constructed using \"(a,b]\" interval notation.\n If labels = False, simple integer codes are returned instead\n of a factor.\n include_lowest: bool, indicating if an ‘x[i]’ equal to the lowest\n (or highest, for right = FALSE) ‘breaks’ value should be included.\n right: bool, indicating if the intervals should be closed on the right\n (and open on the left) or vice versa.\n precision:integer which is used when labels are not given. It determines\n the precision used in formatting the break numbers. Note, this\n argument is different from R's API, which is dig.lab.\n ordered_result: bool, should the result be an ordered categorical?\n\n Returns:\n A categorical object with the cuts\n \"\"\"\n if labels is None:\n ordered_result = True\n\n return pandas.cut(\n x,\n breaks,\n labels=labels,\n include_lowest=include_lowest,\n right=right,\n precision=precision,\n ordered=ordered_result\n )\n\n@register_func(None, context=Context.EVAL)\ndef identity(x: Any) -> Any:\n \"\"\"Return whatever passed in\n\n Expression objects are evaluated using parent context\n \"\"\"\n return x\n\n@register_func(None, context=Context.EVAL)\ndef expandgrid(*args: Iterable[Any], **kwargs: Iterable[Any]) -> DataFrame:\n \"\"\"Expand all combinations into a dataframe. R's `expand.grid()`\"\"\"\n iters = {}\n for i, arg in enumerate(args):\n name = getattr(\n arg,\n 'name',\n getattr(arg, '__name__', f'Var{i}')\n )\n iters[name] = arg\n iters.update(kwargs)\n\n return DataFrame(\n list(itertools.product(*iters.values())),\n columns=iters.keys()\n )\n\n# ---------------------------------\n# Plain functions\n# ---------------------------------\n\ndef data_context(data: DataFrame) -> Any:\n \"\"\"Evaluate verbs, functions in the\n possibly modifying (a copy of) the original data.\n\n It mimic the `with` function in R, but you have to write it in a python way,\n which is using the `with` statement. And you have to use it with `as`, since\n we need the value returned by `__enter__`.\n\n Args:\n data: The data\n func: A function that is registered by\n `pipda.register_verb` or `pipda.register_func`.\n *args: Arguments for func\n **kwargs: Keyword arguments for func\n\n Returns:\n The original or modified data\n \"\"\"\n return WithDataEnv(data)\n","sub_path":"datar/base/funs.py","file_name":"funs.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"647118750","text":"\nimport json\nimport os\nimport six\nfrom avro import schema\n\nif six.PY3:\n from io import StringIO\nelse:\n from cStringIO import StringIO\n\n\nif six.PY3:\n from avro.schema import SchemaFromJSONData as make_avsc_object\nelse:\n from avro.schema import make_avsc_object\n\nfrom .core_writer import generate_namespace_modules, clean_fullname\nfrom .tabbed_writer import TabbedWriter\nfrom .core_writer import write_preamble, start_namespace, write_schema_record, write_enum, write_read_file\nfrom .core_writer import write_get_schema, write_reader_impl\nimport logging\n\nlogger = logging.getLogger('avrogen.schema')\nlogger.setLevel(logging.INFO)\n\n\ndef generate_schema(schema_json, use_logical_types=False, custom_imports=None, avro_json_converter=None):\n \"\"\"\n Generate file containing concrete classes for RecordSchemas in given avro schema json\n :param str schema_json: JSON representing avro schema\n :param list[str] custom_imports: Add additional import modules\n :param str avro_json_converter: AvroJsonConverter type to use for default values\n :return Dict[str, str]:\n \"\"\"\n\n if avro_json_converter is None:\n avro_json_converter = 'avrojson.AvroJsonConverter'\n\n if '(' not in avro_json_converter:\n avro_json_converter += '(use_logical_types=%s, schema_types=__SCHEMA_TYPES)' % use_logical_types\n\n custom_imports = custom_imports or []\n names = schema.Names()\n make_avsc_object(json.loads(schema_json), names)\n\n names = [k for k in six.iteritems(names.names) if isinstance(k[1], (schema.RecordSchema, schema.EnumSchema))]\n names = sorted(names, key=lambda x: x[0])\n\n main_out = StringIO()\n writer = TabbedWriter(main_out)\n\n write_preamble(writer, use_logical_types, custom_imports)\n write_schema_preamble(writer)\n write_get_schema(writer)\n write_populate_schemas(writer)\n\n writer.write('\\n\\n\\nclass SchemaClasses(object):')\n writer.tab()\n writer.write('\\n\\n')\n\n current_namespace = tuple()\n\n for name, field_schema in names: # type: str, schema.Schema\n name = clean_fullname(name)\n namespace = tuple(name.split('.')[:-1])\n if namespace != current_namespace:\n start_namespace(current_namespace, namespace, writer)\n current_namespace = namespace\n if isinstance(field_schema, schema.RecordSchema):\n logger.debug('Writing schema: %s', clean_fullname(field_schema.fullname))\n write_schema_record(field_schema, writer, use_logical_types)\n elif isinstance(field_schema, schema.EnumSchema):\n logger.debug('Writing enum: %s', field_schema.fullname)\n write_enum(field_schema, writer)\n writer.write('\\npass\\n')\n writer.set_tab(0)\n writer.write('\\n__SCHEMA_TYPES = {\\n')\n writer.tab()\n\n for name, field_schema in names:\n writer.write(\"'%s': SchemaClasses.%sClass,\\n\" % (clean_fullname(field_schema.fullname), clean_fullname(field_schema.fullname)))\n\n writer.untab()\n writer.write('\\n}\\n')\n\n writer.write('_json_converter = %s\\n\\n' % avro_json_converter)\n\n value = main_out.getvalue()\n main_out.close()\n return value, [clean_fullname(name[0]) for name in names]\n\n\ndef write_schema_preamble(writer):\n \"\"\"\n Writes a schema-specific preamble: __get_names_and_schema() which is used by concrete classes to resolve\n their own RecordSchema\n :param writer:\n :return:\n \"\"\"\n write_read_file(writer)\n writer.write('\\n\\ndef __get_names_and_schema(file_name):')\n with writer.indent():\n writer.write('\\nnames = avro_schema.Names()')\n writer.write('\\nschema = make_avsc_object(json.loads(__read_file(file_name)), names)')\n writer.write('\\nreturn names, schema')\n writer.write('\\n\\n__NAMES, SCHEMA = __get_names_and_schema(os.path.join(os.path.dirname(__file__), \"schema.avsc\"))')\n\n\ndef write_populate_schemas(writer):\n \"\"\"\n Writes out a __SCHEMAS dict which contains all RecordSchemas by their full name. Used by get_schema_type\n :param writer:\n :return:\n \"\"\"\n writer.write('\\n__SCHEMAS = dict((n.fullname.lstrip(\".\"), n) for n in six.itervalues(__NAMES.names))')\n\n\ndef write_namespace_modules(ns_dict, output_folder):\n \"\"\"\n Writes content of the generated namespace modules. A python module will be created for each namespace\n and will import concrete schema classes from SchemaClasses\n :param ns_dict:\n :param output_folder:\n :return:\n \"\"\"\n for ns in six.iterkeys(ns_dict):\n with open(os.path.join(output_folder, ns.replace('.', os.path.sep), \"__init__.py\"), \"w+\") as f:\n currency = '.'\n if ns != '':\n currency += '.' * len(ns.split('.'))\n f.write('from {currency}schema_classes import SchemaClasses\\n'.format(currency=currency))\n for name in ns_dict[ns]:\n f.write(\"{name} = SchemaClasses.{ns}{name}Class\\n\".format(name=name, ns=ns if not ns else (ns + \".\")))\n\n\ndef write_specific_reader(record_types, output_folder, use_logical_types):\n \"\"\"\n Writes specific reader for a avro schema into generated root module\n :param record_types:\n :param output_folder:\n :return:\n \"\"\"\n with open(os.path.join(output_folder, \"__init__.py\"), \"a+\") as f:\n writer = TabbedWriter(f)\n writer.write('\\n\\nfrom .schema_classes import SchemaClasses, SCHEMA as my_schema, get_schema_type')\n writer.write('\\nfrom avro.io import DatumReader')\n if use_logical_types:\n writer.write('\\nfrom avrogen import logical')\n\n write_reader_impl(record_types, writer, use_logical_types)\n\n\ndef write_schema_files(schema_json, output_folder, use_logical_types=False, custom_imports=None):\n \"\"\"\n Generates concrete classes, namespace modules, and a SpecificRecordReader for a given avro schema\n :param str schema_json: JSON containing avro schema\n :param str output_folder: Folder in which to create generated files\n :param list[str] custom_imports: Add additional import modules\n :return:\n \"\"\"\n schema_py, names = generate_schema(schema_json, use_logical_types, custom_imports)\n names = sorted(names)\n\n if not os.path.isdir(output_folder):\n os.mkdir(output_folder)\n\n with open(os.path.join(output_folder, \"schema_classes.py\"), \"w+\") as f:\n f.write(schema_py)\n\n with open(os.path.join(output_folder, \"schema.avsc\"), \"w+\") as f:\n f.write(schema_json)\n\n ns_dict = generate_namespace_modules(names, output_folder)\n\n with open(os.path.join(output_folder, \"__init__.py\"), \"w+\") as f:\n pass # make sure we create this file from scratch\n\n write_namespace_modules(ns_dict, output_folder)\n write_specific_reader(names, output_folder, use_logical_types)\n","sub_path":"avrogen/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319236022","text":"from output_data import *\nfrom process_data import *\nfrom read_data import *\nimport argparse\n\nmetadata = ()\n\n\ndef main():\n \"\"\"Main function to use user inputs and run all functions\n\n \"\"\"\n args = parser_cli()\n\n RFbinaryFilename = args.RFbinaryFilename\n JSONFilename = args.JSONFilename\n display = args.display\n save = args.save\n\n data = readBinary(RFbinaryFilename)\n fs, c, axial_samples, num_beams, beam_spacing = readJSON(JSONFilename)\n\n centered_data = center_data(data)\n rectified_data = rectify_data(centered_data)\n\n filtered_data = low_pass_filter(rectified_data, 15)\n data_compress = log_compression(filtered_data)\n\n processed_data = reshape_process(data_compress, axial_samples, num_beams)\n\n if display:\n Display(processed_data, num_beams, beam_spacing, axial_samples, fs, c)\n if save:\n Save(processed_data, num_beams, beam_spacing, axial_samples, fs, c)\n\n\ndef parser_cli():\n \"\"\"Argparser to take user input arguments\n\n :param argument 0: RF binary filename\n :param argument 1: JSON binary filename\n :param argument 2: display boolean option\n :param argument 3: save boolean option\n :returns: RFbinaryFilename(string), JSONFilename(string)\n \"\"\"\n parser = argparse.ArgumentParser(description='B-mode Ultrasound Imaging.')\n parser.add_argument('--RFbinaryFilename',\n dest=\"RFbinaryFilename\",\n default='rfdat.bin')\n\n parser.add_argument('--JSONFilename',\n dest=\"JSONFilename\",\n default='bmode.json')\n\n parser.add_argument('--display', default=False,\n type=bool, dest=\"display\",\n help='Boolean input argument to render B-mode image')\n\n parser.add_argument('--save', default=True,\n type=bool, dest=\"save\",\n help='Boolean input argument to save PNG B-mode image')\n\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"argparse_func.py","file_name":"argparse_func.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"221084632","text":"import numpy as np\nimport codecs\nfrom faker import Faker\n\nfrom mlxtend.preprocessing import one_hot\nName = []\nAge = np.arange(60,90)\nGender = np.arange(0,2)\nHeight = np.arange(150,190,5)\nWeight = np.arange(60,120,5)\nAddress = np.arange(4000,5000,1)\nPhoneNum = []\nEmail = []\nBSN = []\nOccupation = []\nMarital = np.arange(0,7)\ntime = np.arange(1,100)\nbloodP = np.arange(70,190,10)\nGlucose = np.arange(3,8)\nMedicalHist = []\nWearable = np.arange(1000,7000,200)\nPreSensorK = np.arange(0,2)\nPreSensorB = np.arange(0,2)\nPreSensorBa = np.arange(0,2)\nPreSensorL = np.arange(0,2)\nTemperature = np.arange(18,26)\nLights = np.arange(0,2)\nWindow = np.arange(0,2)\nIntruder = np.arange(0,2)\nElectricity = np.arange(1000,7000,200)\nExternalGate = np.arange(0,2)\n\n\n# f = open('source.txt', encoding='utf-8', errors='ignore')\n# lines = f.readlines()\n# name = []\n# for xx in lines:\n#\n# print(xx)\n# input(\"wait\")\n\nf = codecs.open('name.txt', encoding='utf-8', errors='ignore')\nlines = f.readlines()\nname = []\nfor xx in lines:\n\n name.append(xx.lstrip().rstrip().lower())\n\nf = codecs.open('diseases.txt', encoding='utf-8', errors='ignore')\nlines = f.readlines()\ndis = []\nfor xx in lines:\n\n dis.append(xx.rstrip())\n\n\n\ndef myround(x, base=5):\n return int(base * round(float(x)/base))\n\n\nusers = []\nuser = \"\"\nuser1 =\"\"\nuser2 = \"\"\nuser3 = \"\"\nuser4 = \"\"\nmaxl = 0\n\nf0 = open('source.txt', 'w')\nf1 = open('view1.txt', 'w')\nf2 = open('view2.txt', 'w')\nf3 = open('view3.txt', 'w')\nf4 = open('view4.txt', 'w')\nf00 = open('sourceTest.txt', 'w')\nf11 = open('view1Test.txt', 'w')\nf22 = open('view2Test.txt', 'w')\nf33 = open('view3Test.txt', 'w')\nf44 = open('view4Test.txt', 'w')\nfake = Faker()\n# for nn in range(len(name)):\nfor numg in range(20000):\n # print(fake.name())\n\n gname = fake.name()\n user = user + \"n\" + \":\"+ gname + \"|\"\n user1 = user1 + \"n\" + \":\"+ \"*\" + \"|\"\n user2 = user2 + \"n\" + \":\"+ gname + \"|\"\n user3 = user3 + \"n\" + \":\"+ \"*\" + \"|\"\n user4 = user4 + \"n\" + \":\" + gname + \"|\"\n\n\n\n age = np.random.randint(60,90)\n user = user+ \"a\" + \":\"+str(age) + \"|\"\n user1 = user2 + \"a\" + \":\" + str(age) + \"|\"\n user2 = user2 + \"a\" + \":\" + str(int(age/10)) +\"*\" + \"|\"\n user3 = user3 + \"a\" + \":\" + str(int(age/10)) +\"*\" + \"|\"\n user4 = user4 + \"a\" + \":\" + str(myround(age)) + \"|\"\n\n\n\n\n\n\n gen = [\"m\",\"f\"]\n gender = np.random.randint(0,2)\n user = user+ \"g\" + \":\"+ str(gen[gender]) + \"|\"\n user1 = user1 + \"g\" + \":\" + str(gen[gender]) + \"|\"\n user2 = user2 + \"g\" + \":\" + str(gen[gender]) + \"|\"\n user3 = user3 + \"g\" + \":\" + str(gen[gender]) + \"|\"\n user4 = user4 + \"g\" + \":\" + str(gen[gender]) + \"|\"\n\n\n\n\n height = np.random.randint(150,190)\n user = user+ \"h\" + \":\"+str(height) + \"|\"\n user1 = user1 + \"h\" + \":\" + str(height) + \"|\"\n user2 = user2 + \"h\" + \":\" + str(height) + \"|\"\n user3 = user3 + \"h\" + \":\" + str(myround(height)) + \"|\"\n user4 = user4 + \"h\" + \":\" + str(myround(height)) + \"|\"\n\n\n weight = np.random.randint(60,120)\n user = user+ \"w\" + \":\"+ str(weight) + \"|\"\n\n user1 = user1 + \"w\" + \":\" + str(weight) + \"|\"\n user2 = user2 + \"w\" + \":\" + str(weight) + \"|\"\n user3 = user3 + \"w\" + \":\" + str(myround(weight)) + \"|\"\n user4 = user4 + \"w\" + \":\" + str(myround(weight)) + \"|\"\n\n\n zip = np.random.randint(10000,99000)\n user = user+ \"ad\" + \":\"+str(zip) + \"|\"\n\n user1 = user1 + \"ad\" + \":\" + str(zip) + \"|\"\n user2 = user2 + \"ad\" + \":\" + str(myround(weight,1000)) + \"|\"\n user3 = user3 + \"ad\" + \":\" + str(zip) + \"|\"\n user4 = user4 + \"ad\" + \":\" + str(myround(weight,1000)) + \"|\"\n\n\n phone = np.random.randint(1000000,9999999)\n user = user+ \"ph\" + \":\"+str(phone) + \"|\"\n user1 = user1 + \"ph\" + \":\" + str(phone) + \"|\"\n user2 = user2 + \"ph\" + \":\" + str(phone) + \"|\"\n user3 = user3 + \"ph\" + \":\" + str(phone) + \"|\"\n user4 = user4 + \"ph\" + \":\" + \"unk\" + \"|\"\n\n\n mar = np.random.randint(0,7)\n user = user+ \"m\" + \":\"+ str(mar) + \"|\"\n\n user1 = user1+ \"m\" + \":\"+ str(mar) + \"|\"\n if mar >0:\n mar = 1\n user2 = user2+ \"m\" + \":\"+ str(mar) + \"|\"\n user3 = user3+ \"m\" + \":\"+ str(mar) + \"|\"\n user4 = user4+ \"m\" + \":\"+ str(mar) + \"|\"\n\n\n\n occ = np.random.randint(0,20)\n user = user+ \"oc\" + \":\"+ str(occ) + \"|\"\n user1 = user1 + \"oc\" + \":\" + str(occ) + \"|\"\n user2 = user2 + \"oc\" + \":\" + str(occ%5) + \"|\"\n user3 = user3 + \"oc\" + \":\" + str(occ%5) + \"|\"\n user4 = user4 + \"oc\" + \":\" + str(occ%5) + \"|\"\n\n\n nn = np.random.randint(0,len(dis))\n user = user+ \"ds\" + \":\"+ dis[nn] + \"|\"\n user1 = user1 + \"ds\" + \":\" + dis[nn] + \"|\"\n user2 = user2 + \"ds\" + \":\" + dis[nn] + \"|\"\n user3 = user3 + \"ds\" + \":\" + dis[nn] + \"|\"\n diss = dis[nn]\n if nn >0 and nn<6:\n diss = \"heart\"\n if nn >6 and nn<11:\n diss = \"lung\"\n if nn >11 and nn<15:\n diss = \"dementia\"\n\n\n user4 = user4 + \"ds\" + \":\" + diss + \"|\"\n\n\n tuser = user\n tuser1 = user1\n tuser2 = user2\n tuser3 = user3\n tuser4 = user4\n\n # for i in range(1,2500):\n\n # user = tuser\n # user1 = tuser1\n # user2 = tuser2\n # user3 = tuser3\n # user4 = tuser4\n\n # user = user + \"ts\" + \":\" + str(i) + \"|\"\n # user1 = user1 + \"ts\" + \":\" + str(i) + \"|\"\n # user2 = user2 + \"ts\" + \":\" + str(i) + \"|\"\n # user3 = user3 + \"ts\" + \":\" + str(i) + \"|\"\n # user4 = user4 + \"ts\" + \":\" + str(i) + \"|\"\n\n bp = np.random.randint(70, 190)\n user = user + \"bp\" + \":\" + str(bp) + \"|\"\n user1 = user1 + \"bp\" + \":\" + str(130) + \"|\"\n user2 = user2 + \"bp\" + \":\" + str(bp) + \"|\"\n user3 = user3 + \"bp\" + \":\" + str(bp) + \"|\"\n user4 = user4 + \"bp\" + \":\" + str(130) + \"|\"\n\n\n gc = np.random.randint(3, 8)\n user = user + \"gc\" + \":\" + str(gc) + \"|\"\n user1 = user1 + \"gc\" + \":\" + str(5) + \"|\"\n user2 = user2 + \"gc\" + \":\" + str(gc) + \"|\"\n user3 = user3 + \"gc\" + \":\" + str(gc) + \"|\"\n user4 = user4 + \"gc\" + \":\" + str(5) + \"|\"\n\n we = np.random.randint(1000,7000)\n user = user + \"we\" + \":\" + str(we) + \"|\"\n user1 = user1 + \"we\" + \":\" + str(we) + \"|\"\n user2 = user2 + \"we\" + \":\" + str(we) + \"|\"\n user3 = user3 + \"we\" + \":\" + str(we) + \"|\"\n user4 = user4 + \"we\" + \":\" + str(we) + \"|\"\n\n sen = np.random.randint(1, 5)\n user = user + \"ss\" + \":\" + str(sen) + \"|\"\n user1 = user1 + \"ss\" + \":\" + str(sen) + \"|\"\n user2 = user2 + \"ss\" + \":\" + \"unk\" + \"|\"\n user3 = user3 + \"ss\" + \":\" + str(sen) + \"|\"\n user4 = user4 + \"ss\" + \":\" + str(sen) + \"|\"\n\n\n temp = np.random.randint(16, 30)\n user = user + \"tp\" + \":\" + str(temp) + \"|\"\n user1 = user1 + \"tp\" + \":\" + str(temp) + \"|\"\n user2 = user2 + \"tp\" + \":\" + str(temp) + \"|\"\n user3 = user3 + \"tp\" + \":\" + str(temp) + \"|\"\n user4 = user4 + \"tp\" + \":\" + str(myround(temp)) + \"|\"\n\n light = np.random.randint(1, 5)\n user = user + \"l\" + \":\" + str(light) + \"|\"\n user1 = user1 + \"l\" + \":\" + str(light) + \"|\"\n user2 = user2 + \"l\" + \":\" + \"unk\" + \"|\"\n user3 = user3 + \"l\" + \":\" + \"unk\" + \"|\"\n user4 = user4 + \"l\" + \":\" + str(light) + \"|\"\n\n window = np.random.randint(1, 3)\n user = user + \"win\" + \":\" + str(window) + \"|\"\n\n user1 = user1 + \"wn\" + \":\" + str(window) + \"|\"\n user2 = user2 + \"wn\" + \":\" + \"unk\" + \"|\"\n user3 = user3 + \"wn\" + \":\" + str(window) + \"|\"\n user4 = user4 + \"wn\" + \":\" + \"unk\" + \"|\"\n\n\n # i = np.random.randint(0, 2)\n # user = user + \"int\" + \":\" + str(i) + \"|\"\n # user1 = user1 + \"int\" + \":\" + str(i) + \"|\"\n # user2 = user2 + \"int\" + \":\" + \"unk\" + \"|\"\n # user3 = user3 + \"int\" + \":\" + str(i) + \"|\"\n # user4 = user4 + \"int\" + \":\" + \"unk\" + \"|\"\n\n\n el = np.random.randint(1000,7000)\n user = user + \"el\" + \":\" + str(el) + \"|\"\n user1 = user1 + \"el\" + \":\" + str(myround(el,500)) + \"|\"\n user2 = user2 + \"el\" + \":\" + \"unk\" + \"|\"\n user3 = user3 + \"el\" + \":\" + \"unk\" + \"|\"\n user4 = user4 + \"el\" + \":\" + str(myround(el,500)) + \"|\"\n\n\n\n\n ext = np.random.randint(0, 2)\n user = user + \"ex\" + \":\" + str(ext) + \"|\"\n user1 = user1 + \"ex\" + \":\" + str(ext) + \"|\"\n user2 = user2 + \"ex\" + \":\" + \"unk\" + \"|\"\n user3 = user3 + \"ex\" + \":\" + str(ext) + \"|\"\n user4 = user4 + \"ex\" + \":\" + \"unk\" + \"|\"\n\n user = user + \"eos\"\n user1 = user1 + \"eos\"\n user2 = user2 + \"eos\"\n user3 = user3 + \"eos\"\n user4 = user4 + \"eos\"\n\n\n if len(user)>maxl:\n maxl = len(user)\n\n\n if numg<100000:\n\n #print(user ,file = f0)\n print(f0),user\n\n\n #print(user1 , file=f1)\n print(f1), user1\n\n #print(user2 , file=f2)\n print(f2), user2\n\n #print(user3 , file=f3)\n print(f3), user3\n\n #print(user4, file=f4)\n print(f4), user4\n else:\n #print(user ,file = f00)\n print(f00), user\n\n\n #print(user1 , file=f11)\n print(f11), user1\n\n #print(user2 , file=f22)\n print(f22), user2\n\n\n #print(user3 , file=f33)\n print(f33), user3\n\n #print(user4, file=f44)\n print(f44), user4\n\n\n\n\n user = \"\"\n user1 = \"\"\n user2 = \"\"\n user3 = \"\"\n user4 = \"\"\nprint(maxl)\nf0.close()\nf1.close()\nf2.close()\nf3.close()\nf4.close()\n\nf00.close()\nf11.close()\nf22.close()\nf33.close()\nf44.close()","sub_path":"Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"631122542","text":"import info\n\n\nclass subinfo(info.infoclass):\n def setTargets(self):\n for ver in [\"3.4\", \"3.5\"]:\n self.targets[ver] = f\"http://deb.debian.org/debian/pool/main/x/x265/x265_{ver}.orig.tar.gz\"\n self.targetInstSrc[ver] = f\"x265_{ver}/source\"\n self.patchToApply[ver] = [(\"mingw-no-pdb.patch\", 1)]\n self.targetDigests[\"3.4\"] = ([\"c2047f23a6b729e5c70280d23223cb61b57bfe4ad4e8f1471eeee2a61d148672\"], CraftHash.HashAlgorithm.SHA256)\n self.targetDigests[\"3.5\"] = ([\"e70a3335cacacbba0b3a20ec6fecd6783932288ebc8163ad74bcc9606477cae8\"], CraftHash.HashAlgorithm.SHA256)\n self.description = \"H.265/HEVC video stream encoder\"\n self.defaultTarget = \"3.5\"\n\n def setDependencies(self):\n self.runtimeDependencies[\"virtual/base\"] = None\n self.buildDependencies[\"dev-utils/nasm\"] = None\n\n\nfrom Package.CMakePackageBase import *\n\n\nclass Package(CMakePackageBase):\n def __init__(self, **args):\n CMakePackageBase.__init__(self)\n self.subinfo.options.configure.args = \"-DEXPORT_C_API=ON -DENABLE_SHARED=ON -DENABLE_ASSEMBLY=ON -DENABLE_CLI=OFF\"\n","sub_path":"libs/x265/x265.py","file_name":"x265.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"365276405","text":"from jinja2 import Environment, FileSystemLoader\nimport os \nimport glob\nroot = os.path.dirname(os.path.abspath(__file__))\ntemplates_dir = os.path.join(root, 'templates')\nenv = Environment( loader = FileSystemLoader(templates_dir) )\ntemplate = env.get_template('imageview.html')\n \n \nfilename = os.path.join(root,'upload/static','imageview_updated.html')\nslitted_path = root.split(\"/\")\nimage_path = os.path.join(\"/\".join(slitted_path[:-1]),'instance/images/')\nimage_path2 = '../../../instance/images/'\nlocations = []\nfor folder in glob.glob(image_path + \"*/\"):\n\tprint(folder.split(\"/\")[-2])\n\tlocations.append(image_path2 + folder.split(\"/\")[-2] + \"/thumbnail.png\")\n\tprint(locations)\n\nwith open(filename, 'w') as fh:\n fh.write(template.render(\n paths = locations,\n ))\n #https://code-maven.com/minimal-example-generating-html-with-python-jinja","sub_path":"app/gen_image_views.py","file_name":"gen_image_views.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"111591780","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport torch.nn.functional as F\n\nclass Encoder(nn.Module):\n \"\"\"\n Encodes a node's using 'convolutional' GraphSage approach\n \"\"\"\n def __init__(self, feature_dim, \n embed_dim, adj_lists, aggregator, \n feature_transform=False): \n super(Encoder, self).__init__()\n\n self.feat_dim = feature_dim\n self.adj_lists = adj_lists\n self.aggregator = aggregator\n\n self.embed_dim = embed_dim\n self.weight = nn.Parameter(\n torch.FloatTensor(feature_dim, embed_dim))\n init.xavier_uniform(self.weight)\n \n self.bn = nn.BatchNorm1d(embed_dim)\n self.relu = nn.LeakyReLU()\n\n def forward(self, raw_features, nodes):\n \"\"\"\n Generates embeddings for a batch of nodes.\n\n nodes -- list of nodes\n \"\"\"\n\n neigh_feats = self.aggregator.forward(raw_features, nodes, [self.adj_lists[node] for node in nodes])\n\n x = neigh_feats.mm(self.weight)\n x = self.bn(x)\n x = self.relu(x)\n return x\n","sub_path":"graphsage/parcellation_encoders.py","file_name":"parcellation_encoders.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"145062801","text":"import pandas as pd\nfrom sklearn.metrics import mean_squared_error as mse\n\nwsp = pd.read_csv('../tmp/wqs_2017-12-21-11-02-16-0.0432.csv',header=None)\nlgb = pd.read_csv('../result/result_20171225.csv',header=None)\nresult = pd.DataFrame()\n\nresult['ID'] = wsp[0]\nresult['Y'] = 2.0 / (1.0 / wsp[1] + 1.0/lgb[1])\n\nresult[['ID','Y']].to_csv('../result/result_20171227_h_lgb_xgb.csv',index=False,header=False)\n","sub_path":"201704TO201802CodeBackup-master/201704TO201802CodeBackup-master/201801_Tianchi_工业AI第一赛季/code/2.simply_merge.py","file_name":"2.simply_merge.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"56475640","text":"import pandas as pd\nimport numpy as np\n\ndata = np.array([\n [1, 1, 0],\n [1, 1, 0],\n [1, 1, 1],\n [0, 0, 2],\n [0, 1, 0],\n [0, 0, 2]])\n\ndf = pd.DataFrame(data, columns=['EdibleOrPoisonous', 'RedColor', 'CapSurface'])\nprint(df)\n\ntrain_df = df.copy()\ncol = np.array(['RedColor', 'CapSurface'])\nfor f in range(1, df.shape[1]):\n for elem in df.iloc[:, f].unique():\n train_df[col[f-1]+'_'+str(elem) ] = (train_df.iloc[:, f]==elem)+0.0\n\ntrain_df = train_df.drop(columns=col)\nprint(train_df)\n\n\nX = train_df.iloc[:, 1:].values\ny = train_df.iloc[:, 0].values\n\nfrom sklearn.naive_bayes import MultinomialNB\nclf = MultinomialNB(alpha=0)\nclf.fit(X, y)\nclf.predict_proba(np.array( [[1,0,1,0,0]] ))\n\nclf = MultinomialNB(alpha=0)\nclf.fit(X, y)\np = clf.predict_proba(np.array([[1,0,0,1,0]]))\nprint(p)\n\nfrom sklearn.naive_bayes import MultinomialNB\nclf=MultinomialNB(alpha=1)\nclf.fit(X, y)\np = clf.predict_proba(np.array( [[1,0,0,1,0]] ) )\nprint(p)\n\n\n#*********************REAL Example*****************\ndf = pd.read_csv('./mushrooms.csv')\nfrom sklearn.utils import shuffle\n\ndf = shuffle(df, random_state=42)\nprint(df)\n\n\ntrain_df = df[:7000]\ntest_df = df[7000:]\n\nprint(train_df)\n\n\n# from this we can derive the accuracy of the majority class classifier\nprint(train_df['class'].value_counts(normalize=1))\n\ntarget = []\nfor i in range(len(train_df['class'].values)):\n if train_df['class'].values[i]=='e':\n target.append(0)\n if train_df['class'].values[i]=='p':\n target.append(1)\n if train_df['class'].values[i]=='u':\n target.append(2)\n\ntarget = np.array(target)\nprint(target)\n\ndel train_df['class']\n\n#we transform inputs for multinomialNB\ncols = list(train_df)\nprint(\"cols--->\", cols)\nfor f in cols:\n for elem in df[f].unique():\n train_df[f+'_'+str(elem)] = (train_df[f]==elem)\n\n#we delete old columns\nprint(\"Before deleting---->\", train_df)\nfor f in cols:\n del train_df[f]\nprint(\"after deleting----->\", train_df)\ntrain_df.head()\ntrain_df=train_df+0.0\nprint(\"after adding 0.0.----->\", train_df)\n\n\nfrom sklearn.naive_bayes import MultinomialNB\n\nclf = MultinomialNB()\ntrain_x = train_df.values\nclf.fit(train_x, target)\n\nfrom sklearn.metrics import accuracy_score\ny_pred = clf.predict(train_x)\na = accuracy_score(y_pred, target)\nprint(a)\n\n\ntest_y = test_df['class']\ndel test_df['class']\nfor f in cols:\n for elem in df[f].unique():\n test_df[f+'_'+str(elem)] = (test_df[f]==elem)\n\nfor f in cols:\n del test_df[f]\n\nprint(test_df)\n\ntest_x = test_df.values\n\ntest_y1=[]\nfor i in range(len(test_y)):\n if test_y.values[i] == 'e':\n test_y1.append(0)\n if test_y.values[i] == 'p':\n test_y1.append(1)\n if test_y.values[i] == 'u':\n test_y1.append(2)\n\ntest_y1 = np.array(test_y1)\n\ny_pred = clf.predict(test_x)\naccuracy_score(y_pred, test_y1)\n\nfrom sklearn.metrics import confusion_matrix\nCC = confusion_matrix(test_y1, y_pred)\nprint(CC)\n\n\n\n\n\n\n","sub_path":"mushroom_classification/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"264410710","text":"#!/usr/bin/env python\n\nimport sys\nfrom csv import reader\n\n\nparking = sc.textFile(sys.argv[1], 1)\nparking = parking.mapPartitions(lambda x: reader(x))\n\nplateid_state = parking.map(lambda x: ((x[14], x[16]), 1))\ntotal_plateid_state = plateid_state.reduceByKey(lambda x, y: x + y)\n\n# get the top 20 vehicles with the greatest number of violations\nsorted_list = total_plateid_state.sortBy(lambda x: (-x[1], x[0][0]))\ngreatest = sc.parallelize(sorted_list.take(20))\ngreatest = greatest.map(lambda x: (x[0][0], x[0][1], x[1]))\n\n# output\noutput = greatest.map(lambda x: x[0] + ', ' + x[1] + '\\t' + str(x[2]))\noutput.saveAsTextFile('task6.out')","sub_path":"task6/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"325340965","text":"import configparser\nimport json\nimport time\nimport zipfile\nimport io\nimport copy\nimport os\nimport logging\nimport requests\nimport pandas as pd\nimport xmltodict\nfrom tqdm import tqdm\nfrom dict2xml import dict2xml\n\n\nclass DownloadTools:\n \"\"\"Generic tools for retrieving literature\"\"\"\n\n def __init__(self, api):\n \"\"\"[summary]\n\n :param api: [description]\n :type api: [type]\n \"\"\"\n with open(\n os.path.join(os.path.dirname(__file__), \"config.ini\")\n ) as file_handler:\n config_file = file_handler.read()\n config = configparser.RawConfigParser(allow_no_value=True)\n config.read_string(config_file)\n\n self.posturl = config.get(api, \"posturl\")\n self.citationurl = config.get(api, \"citationurl\")\n self.referencesurl = config.get(api, \"referencesurl\")\n self.xmlurl = config.get(api, \"xmlurl\")\n self.zipurl = config.get(api, \"zipurl\")\n self.suppurl = config.get(api, \"suppurl\")\n\n def postquery(self, headers, payload):\n \"\"\"\n\n :param headers: headers that will be sent to eupmc rest api\n :param payload: payload that will be sent to eupmc rest api\n :returns: Python dictionary containting the output got from eupmc rest api\n\n \"\"\"\n logging.debug(\"*/RESTful request for fulltext.xml (D)*/\")\n start = time.time()\n request_handler = requests.post(\n self.posturl, data=payload, headers=headers)\n stop = time.time()\n logging.debug(\"*/Got the Query Result */\")\n logging.debug(\"Time elapsed: %s\", (stop - start))\n return xmltodict.parse(request_handler.content)\n\n @staticmethod\n def check_or_make_directory(directory_url):\n \"\"\"Checks if the directory exists. If not, makes the directory\n\n :param directory_url: directory url to check\n\n \"\"\"\n if not os.path.isdir(directory_url):\n os.makedirs(directory_url)\n\n @staticmethod\n def buildquery(\n cursormark,\n page_size,\n query,\n synonym=True,\n ):\n \"\"\"\n\n :param cursormark: the cursonmark for the rest api page.\n :param page_size: the size of each page in the output.\n :param query: the query passed on to payload\n :param synonym: whether synonym should be or not (Default value = True)\n :returns: headers': headers, 'payload': payload}\n :rtype: Python dictionary containting headers and payload in the format\n\n \"\"\"\n\n headers = {\"Content-type\": \"application/x-www-form-urlencoded\"}\n payload = {\n \"query\": query,\n \"resultType\": \"core\",\n \"cursorMark\": cursormark,\n \"pageSize\": page_size,\n \"synonym\": synonym,\n \"format\": \"xml\",\n \"sort_PMCID\": \"y\",\n }\n logging.debug(\"*/submitting RESTful query (I)*/\")\n return {\"headers\": headers, \"payload\": payload}\n\n @staticmethod\n def write_or_append_to_csv(df_transposed, name=\"europe_pmc.csv\"):\n \"\"\"Writes the csv file or appends to an existing one\n\n :param df_transposed: dataframe to write\n :param name: Default value = 'europe_pmc.csv')\n\n \"\"\"\n path = os.path.join(str(os.getcwd()), name)\n if os.path.exists(path):\n df_transposed.to_csv(path, mode=\"a\", header=False)\n else:\n df_transposed.to_csv(path)\n\n @staticmethod\n def writexml(directory_url, destination_url, content):\n \"\"\"writes xml to the destination\n\n :param directory_url: directory containg destination\n :param destination_url: path to write the xml to\n :param content: xml content\n\n \"\"\"\n if not os.path.isdir(directory_url):\n os.makedirs(directory_url)\n with open(destination_url, \"wb\") as file_handler:\n file_handler.write(content)\n\n @staticmethod\n def make_dict_for_csv(resultant_dict):\n \"\"\"removes the fields downloaded, pdfdownloaded,csvmade for the resultant_dict\n\n :param resultant_dict: dictionary to remove the fields\n :returns: resultant_dict_for_csv\n\n \"\"\"\n resultant_dict_for_csv = copy.deepcopy(resultant_dict)\n for paper in resultant_dict_for_csv:\n paper_dict = resultant_dict_for_csv[paper]\n if \"downloaded\" in paper_dict:\n paper_dict.pop(\"downloaded\")\n if \"pdfdownloaded\" in paper_dict:\n paper_dict.pop(\"pdfdownloaded\")\n if \"jsondownloaded\" in paper_dict:\n paper_dict.pop(\"jsondownloaded\")\n if \"csvmade\" in paper_dict:\n paper_dict.pop(\"csvmade\")\n if \"htmlmade\" in paper_dict:\n paper_dict.pop(\"htmlmade\")\n return resultant_dict_for_csv\n\n @staticmethod\n def write_content_to_destination(url, destination):\n \"\"\"Writes content from url to destination\n\n :param url: Url to get content from\n :param destination: destination to write content to\n\n \"\"\"\n with open(destination, \"wb\") as file:\n response = requests.get(url)\n file.write(response.content)\n\n @staticmethod\n def makejson(path, final_xml_dict):\n \"\"\"Writes json of final_xml_dict to path\n\n :param path: path to write json to\n :param final_xml_dict: python dictionary to make the json from\n\n \"\"\"\n append_write = \"w\"\n with open(path, append_write, encoding=\"utf-8\") as file_handler:\n json.dump(final_xml_dict, file_handler)\n\n @staticmethod\n def clean_dict_for_csv(paperdict):\n \"\"\"Removes the fields pdfdownloaded , jsondownloaded , csvmade from dictionary of paper\n\n :param paperdict: dictionary to remove fields from\n\n \"\"\"\n dict_to_write = dict(paperdict)\n dict_to_write.pop(\"pdfdownloaded\")\n dict_to_write.pop(\"jsondownloaded\")\n dict_to_write.pop(\"csvmade\")\n return dict_to_write\n\n @staticmethod\n def make_dataframe_for_paper_dict(result, return_dict):\n \"\"\"\n\n :param result: \n :param return_dict:\n\n \"\"\"\n dict_for_df = {k: [v] for k, v in return_dict[result].items()}\n df_for_paper = pd.DataFrame(dict_for_df)\n return df_for_paper\n\n @staticmethod\n def conditions_to_download(paperdict):\n \"\"\"Writes the conditions to download pdf, json and csv\n\n :param paperdict: dictionary to write rules for\n\n \"\"\"\n condition_to_down = False\n condition_to_download_pdf = False\n condition_to_download_json = False\n condition_to_download_csv = False\n condition_to_html = False\n if not paperdict[\"downloaded\"]:\n condition_to_down = True\n if not paperdict[\"pdfdownloaded\"]:\n condition_to_download_pdf = True\n if not paperdict[\"jsondownloaded\"]:\n condition_to_download_json = True\n if not paperdict[\"csvmade\"]:\n condition_to_download_csv = True\n if not paperdict[\"htmlmade\"]:\n condition_to_html = True\n return (\n condition_to_down,\n condition_to_download_csv,\n condition_to_download_json,\n condition_to_download_pdf,\n condition_to_html,\n )\n\n @staticmethod\n def make_clickable(link):\n \"\"\"Returns a Html String\n\n :param link: link for href\n\n \"\"\"\n tag_to_return = f' Link '\n if str(link) == \"nan\":\n tag_to_return = \"Not Found\"\n return tag_to_return\n\n def getcitations(self, pmcid, source):\n \"\"\"Gets citations for the paper of pmcid\n\n :param pmcid: pmcid to get the citations\n :param source: source to get the citations from\n :returns: citations xml\n\n \"\"\"\n request_handler = requests.get(\n self.citationurl.format(source=source, pmcid=pmcid)\n )\n return request_handler.content\n\n def getreferences(self, pmcid, source):\n \"\"\"Gets references for the paper of pmcid\n\n :param pmcid: pmcid to get the references\n :param source: source to get the references from\n :returns: references xml\n\n \"\"\"\n request_handler = requests.get(\n self.referencesurl.format(source=source, pmcid=pmcid)\n )\n return request_handler.content\n\n @staticmethod\n def add_scrollbar(text):\n \"\"\"Makes div scrollable\n\n :param text: text to wrap\n\n \"\"\"\n return f'{text}
'\n\n def make_html_from_dataframe(self, dataframe, url):\n \"\"\"Writes html from pandas dataframe\n\n :param dataframe: Dataframe to make html from\n :param url: URL to write html to\n\n \"\"\"\n dataframe = dataframe.T\n try:\n dataframe = dataframe.drop(columns=[\"full\", \"htmlmade\"])\n except Exception as exception:\n logging.debug(exception)\n if \"htmllinks\" in dataframe:\n try:\n dataframe[\"htmllinks\"] = dataframe[\"htmllinks\"].apply(\n lambda x: self.make_clickable(x)\n )\n except Exception as exception:\n logging.debug(exception)\n if \"pdflinks\" in dataframe:\n try:\n dataframe[\"pdflinks\"] = dataframe[\"pdflinks\"].apply(\n lambda x: self.make_clickable(x)\n )\n except Exception as exception:\n logging.debug(exception)\n try:\n dataframe[\"abstract\"] = dataframe[\"abstract\"].apply(\n lambda x: self.add_scrollbar(x)\n )\n except Exception as exception:\n logging.debug(exception)\n base_html = \"\"\"\n \n \n \n \n \n \n \n \n \n %s\n \n \n \"\"\"\n html = dataframe.to_html(escape=False)\n html_with_pagination = base_html % html\n with open(url, \"w\", encoding=\"utf-8\") as file_handler:\n file_handler.write(html_with_pagination)\n\n def make_html_from_dict(self, dict_to_write_html_from, url):\n \"\"\"Writes html from python dictionary\n\n :param dict_to_write_html_from: dict to make html from\n :param url: URL to write html to\n\n \"\"\"\n df = pd.Series(dict_to_write_html_from).to_frame(\n dict_to_write_html_from[\"full\"][\"pmcid\"]\n )\n self.make_html_from_dataframe(df, url)\n\n def make_references(self, directory_url, paperid, source, referenceurl):\n \"\"\"Downloads the references for the paper with pmcid (paperid) to reference url\n\n :param directory_url: directory containing referenceurl\n :param paperid: pmc id of the paper\n :param source: source to get the citations from\n :param referenceurl: path to write the references to\n\n \"\"\"\n getreferences = self.getreferences(paperid, source)\n self.writexml(directory_url, referenceurl, getreferences)\n\n def make_citations(self, source, citationurl, directory_url, paperid):\n \"\"\"Downloads the citations for the paper with pmcid (paperid) to citation url\n\n :param source: source to get the citations from\n :param citationurl: path to write the citations to\n :param directory_url: directory containing citationurl\n :param paperid: pmc id of the paper\n\n \"\"\"\n getcitations = self.getcitations(paperid, source)\n self.writexml(directory_url, citationurl, getcitations)\n\n @staticmethod\n def readjsondata(path):\n \"\"\"Reads json from path and returns python dictionary\n\n :param path: path to read the json from\n :returns: python dictionary for the json\n\n \"\"\"\n with open(path) as file_handler:\n dict_from_json = json.load(file_handler)\n return dict_from_json\n\n @staticmethod\n def log_making_xml():\n \"\"\"Logs that the xmls are being written\"\"\"\n\n logging.debug(\n \"*/saving xml to per-document directories (CTrees) (D)*/\")\n loggingurl = os.path.join(str(os.getcwd()), \"*\", \"fulltext.xml\")\n logging.info(\"Saving XML files to %s\", loggingurl)\n logging.debug(\"*/Making the Request to get full text xml*/\")\n\n def getxml(self, pmcid):\n \"\"\"Makes a query for the pmcid xml to eupmc rest.\n\n :param pmcid: pmcid of the paper to query for\n :returns: query result\n\n \"\"\"\n request_handler = requests.get(self.xmlurl.format(pmcid=pmcid))\n return request_handler.content\n\n def getsupplementaryfiles(\n self, pmcid, directory_url, destination_url, from_ftp_end_point=False\n ):\n \"\"\"Downloads the supplemetary marks for the paper having pmcid\n\n :param pmcid: pmcid to get the supplementary files\n :param directory_url: directory containg destination\n :param destination_url: path to write the supplementary files to\n :param from_ftp_end_point: Default value = False)\n\n \"\"\"\n\n log_key = \"supplementary\"\n if from_ftp_end_point:\n key = \"PMCxxxx\" + pmcid[-3:]\n path = self.zipurl.format(key=key, pmcid=pmcid)\n log_key = \"zip\"\n else:\n path = self.suppurl.format(pmcid=pmcid)\n request_handler = requests.get(path)\n if not os.path.isdir(directory_url):\n os.makedirs(directory_url)\n file_exits = False\n for chunk in request_handler.iter_content(chunk_size=128):\n if len(chunk) > 0:\n file_exits = True\n break\n if file_exits:\n self.extract_zip_files(\n request_handler, destination_url, log_key, pmcid)\n else:\n logging.warning(\"%s files not found for %s\", log_key, pmcid)\n\n def extract_zip_files(self, request_handler, destination_url, log_key, pmcid):\n \"\"\"\n\n :param request_handler: param destination_url:\n :param log_key: param pmcid:\n :param destination_url: param pmcid:\n :param pmcid:\n\n \"\"\"\n try:\n z = zipfile.ZipFile(io.BytesIO(request_handler.content))\n self.check_or_make_directory(destination_url)\n z.extractall(destination_url)\n logging.info(\"Wrote %s files for %s\", log_key, log_key)\n except Exception as exception:\n logging.warning(\"%s files not found for %s\", log_key, pmcid)\n logging.debug(exception)\n\n def make_initial_columns_for_paper_dict(self, key_for_dict, resultant_dict):\n \"\"\"Writes the json and csv for searchvaraible dict\n\n :param key_for_dict: id of the paper for which fields will be created\n :param resultant_dict: dict in which the fields will be created\n :returns: dict with the initial fields created for pmcid\n\n \"\"\"\n resultant_dict[key_for_dict] = {}\n self.add_keys_for_conditions(key_for_dict, resultant_dict)\n return resultant_dict\n\n @staticmethod\n def add_keys_for_conditions(key_for_dict, resultant_dict):\n \"\"\"[summary]\n\n :param key_for_dict: [description]\n :type key_for_dict: [type]\n :param resultant_dict: [description]\n :type resultant_dict: [type]\n \"\"\"\n resultant_dict[key_for_dict][\"downloaded\"] = False\n resultant_dict[key_for_dict][\"pdfdownloaded\"] = False\n resultant_dict[key_for_dict][\"jsondownloaded\"] = False\n resultant_dict[key_for_dict][\"csvmade\"] = False\n resultant_dict[key_for_dict][\"htmlmade\"] = False\n\n def make_csv_for_dict(self, df, return_dict, output_main, output_paper):\n \"\"\"\n\n :param df:\n :param return_dict:\n :param output_main:\n :param output_paper:\n\n \"\"\"\n logging.info(\"Making csv files for metadata at %s\", os.getcwd())\n paper = 0\n self.write_or_append_to_csv(df, output_main)\n dict_to_use = self.make_dict_for_csv(return_dict)\n for result in tqdm(dict_to_use):\n paper += 1\n result_encoded = self.url_encode_id(result)\n url = os.path.join(os.getcwd(), result_encoded, output_paper)\n self.check_or_make_directory(\n os.path.join(os.getcwd(), result_encoded))\n df_for_paper = self.make_dataframe_for_paper_dict(\n result, dict_to_use)\n self.write_or_append_to_csv(df_for_paper, url)\n return_dict[result][\"csvmade\"] = True\n logging.debug(\"Wrote csv files for paper %s\", paper)\n\n def make_html_for_dict(self, df, return_dict, output_main, output_paper):\n \"\"\"\n\n :param df:\n :param return_dict:\n :param output_main:\n :param output_paper:\n\n \"\"\"\n logging.info(\"Making html files for metadata at %s\", os.getcwd())\n paper = 0\n htmlurl = os.path.join(os.getcwd(), output_main)\n self.make_html_from_dataframe(df, htmlurl)\n for result in tqdm(return_dict):\n paper += 1\n result_encoded = self.url_encode_id(result)\n url = os.path.join(os.getcwd(), result_encoded, output_paper)\n self.check_or_make_directory(\n os.path.join(os.getcwd(), result_encoded))\n df_for_paper = self.make_dataframe_for_paper_dict(\n result, return_dict)\n self.make_html_from_dataframe(df_for_paper, url)\n return_dict[result][\"htmlmade\"] = True\n logging.debug(\"Wrote xml files for paper %s\", paper)\n\n def make_xml_for_dict(self, return_dict, output_main, output_paper):\n \"\"\"\n\n :param return_dict:\n :param output_main:\n :param output_paper:\n\n \"\"\"\n dict_to_use = self.make_dict_for_csv(return_dict)\n total_xml = dict2xml(dict_to_use, wrap=\"root\", indent=\" \")\n logging.info(\"Making xml files for metadata at %s\", os.getcwd())\n xmlurl = os.path.join(os.getcwd(), output_main)\n with open(xmlurl, \"w\", encoding=\"utf-8\") as file_handler:\n file_handler.write(total_xml)\n paper = 0\n for result in tqdm(dict_to_use):\n paper += 1\n total_xml_of_paper = dict2xml(\n dict_to_use[result], wrap=\"root\", indent=\" \"\n )\n result_encoded = self.url_encode_id(result)\n xmlurl_of_paper = os.path.join(\n os.getcwd(), result_encoded, output_paper)\n\n self.check_or_make_directory(\n os.path.join(os.getcwd(), result_encoded))\n\n with open(xmlurl_of_paper, \"w\", encoding=\"utf-8\") as file_handler:\n file_handler.write(total_xml_of_paper)\n\n logging.debug(\"Wrote xml files for paper %s\", paper)\n\n def handle_creation_of_csv_html_xml(\n self, makecsv, makehtml, makexml, return_dict, name\n ):\n \"\"\"[summary]\n\n :param makecsv: [description]\n :type makecsv: [type]\n :param makehtml: [description]\n :type makehtml: [type]\n :param makexml: [description]\n :type makexml: [type]\n :param return_dict: [description]\n :type return_dict: [type]\n :param name: [description]\n :type name: [type]\n \"\"\"\n dict_to_use = self.make_dict_for_csv(return_dict)\n df = pd.DataFrame.from_dict(dict_to_use)\n if makecsv:\n self.make_csv_for_dict(\n df, return_dict, f\"{name}s.csv\", f\"{name}.csv\")\n if makehtml:\n self.make_html_for_dict(\n df, return_dict, f\"{name}s.html\", f\"{name}.html\")\n if makexml:\n self.make_xml_for_dict(return_dict, f\"{name}s.xml\", f\"{name}.xml\")\n\n @staticmethod\n def url_encode_id(doi_of_paper):\n \"\"\"[summary]\n\n :param doi_of_paper: [description]\n :type doi_of_paper: [type]\n :return: [description]\n :rtype: [type]\n \"\"\"\n url_encoded_doi_of_paper = doi_of_paper.replace(\n \"\\\\\", \"_\").replace(\"/\", \"_\")\n return url_encoded_doi_of_paper\n\n @staticmethod\n def get_version():\n with open(\n os.path.join(os.path.dirname(__file__), \"config.ini\")\n ) as file_handler:\n config_file = file_handler.read()\n config = configparser.RawConfigParser(allow_no_value=True)\n config.read_string(config_file)\n version = config.get(\"pygetpapers\", \"version\")\n return version\n\n @staticmethod\n def make_dict_from_returned_list(total_json_output, key_in_dict):\n \"\"\"[summary]\n\n :param total_json_output: [description]\n :type total_json_output: [type]\n :param key_in_dict: [description]\n :type key_in_dict: [type]\n :return: [description]\n :rtype: [type]\n \"\"\"\n json_return_dict = {}\n for paper in total_json_output:\n json_return_dict[paper[key_in_dict]] = paper\n return json_return_dict\n\n def make_json_files_for_paper(self, returned_dict, key_in_dict, name_of_file):\n \"\"\"[summary]\n\n :param returned_dict: [description]\n :type returned_dict: [type]\n :param key_in_dict: [description]\n :type key_in_dict: [type]\n :param name_of_file: [description]\n :type name_of_file: [type]\n \"\"\"\n self.makejson(f\"{name_of_file}s.json\", returned_dict)\n logging.info(\"Wrote metadata file for the query\")\n paper_numer = 0\n logging.info(\"Writing metadata file for the papers at %s\",\n str(os.getcwd()))\n total_dict = returned_dict[\"total_json_output\"]\n for paper in tqdm(total_dict):\n dict_of_paper = total_dict[paper]\n if not dict_of_paper[\"jsondownloaded\"]:\n paper_numer += 1\n doi_of_paper = dict_of_paper[key_in_dict]\n url_encoded_doi_of_paper = self.url_encode_id(doi_of_paper)\n self.check_or_make_directory(url_encoded_doi_of_paper)\n path_to_save_metadata = os.path.join(\n str(os.getcwd()\n ), url_encoded_doi_of_paper, f\"{name_of_file}.json\"\n )\n dict_of_paper[\"jsondownloaded\"] = True\n self.makejson(path_to_save_metadata, dict_of_paper)\n logging.debug(\n \"Wrote metadata file for the paper %s\", paper_numer)\n\n def make_dict_to_return(\n self, cursor_mark, json_return_dict, total_number_of_results, update\n ):\n \"\"\"[summary]\n\n :param cursor_mark: [description]\n :type cursor_mark: [type]\n :param json_return_dict: [description]\n :type json_return_dict: [type]\n :param total_number_of_results: [description]\n :type total_number_of_results: [type]\n :param update: [description]\n :type update: [type]\n :return: [description]\n :rtype: [type]\n \"\"\"\n dict_to_return = {\n \"total_json_output\": json_return_dict,\n \"total_hits\": total_number_of_results,\n \"cursor_mark\": cursor_mark,\n }\n if update:\n dict_to_return[\"total_json_output\"] = update[\"total_json_output\"].update(\n dict_to_return[\"total_json_output\"]\n )\n return dict_to_return\n","sub_path":"pygetpapers/download_tools.py","file_name":"download_tools.py","file_ext":"py","file_size_in_byte":23962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"38537450","text":"\"\"\"Story child elements\"\"\"\n\nimport logging\nimport re\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils.models import TimeStampedModel\nfrom requests import request\nfrom requests.exceptions import MissingSchema, Timeout\nfrom slugify import Slugify\n\nfrom apps.photo.models import ImageFile\nfrom utils.decorators import cache_memoize\n\nfrom .mixins import MarkupCharField, MarkupModelMixin, TextContent\n\nslugify = Slugify(max_length=50, to_lower=True)\nlogger = logging.getLogger(__name__)\n\nTOP = 'head'\nDEFAULT_IMAGE_SIZE = (1200, 675) # 16:9 ratio\n\n\nclass ElementQuerySet(models.QuerySet):\n def top(self):\n \"\"\" Elements that are placed at the start of the parent article \"\"\"\n return self.published().filter(placement=TOP)\n\n def inline(self):\n \"\"\" Elements that are placed inside the story \"\"\"\n return self.published().exclude(placement=TOP)\n\n def published(self):\n return self.filter(placement__isnull=False)\n\n def unpublished(self):\n return self.filter(placement__isnull=True)\n\n\nclass StoryChild(TimeStampedModel):\n \"\"\" Models that are placed somewhere inside an article \"\"\"\n objects = ElementQuerySet.as_manager()\n\n class Meta:\n abstract = True\n ordering = ['index']\n\n ordering = models.SmallIntegerField(\n default=0,\n blank=True,\n null=True,\n help_text=_('Internal order within placement'),\n verbose_name=_('ordering'),\n )\n placement = models.CharField(\n max_length=100,\n default='head',\n blank='true',\n help_text=_('Placement of this element'),\n verbose_name=_('placement'),\n )\n\n index = models.PositiveSmallIntegerField(\n default=0,\n blank=True,\n null=True,\n help_text=_('Leave blank to unpublish'),\n verbose_name=_('index'),\n )\n\n @property\n def top(self):\n return self.placement == TOP\n\n @property\n def published(self):\n return bool(self.placement)\n\n def siblings(self):\n return self.__class__.objects.filter(parent_story=self.parent_story)\n\n\nclass Pullquote(TextContent, StoryChild): # type: ignore\n \"\"\" A quote that is that is pulled out of the content. \"\"\"\n\n parent_story = models.ForeignKey(\n 'Story',\n related_name='pullquotes',\n on_delete=models.CASCADE,\n )\n\n class Meta:\n verbose_name = _('Pullquote')\n verbose_name_plural = _('Pullquotes')\n\n\nclass Aside(TextContent, StoryChild): # type: ignore\n \"\"\" Fact box or other information typically placed in side bar \"\"\"\n parent_story = models.ForeignKey(\n 'Story',\n related_name='asides',\n on_delete=models.CASCADE,\n )\n\n class Meta:\n verbose_name = _('Aside')\n verbose_name_plural = _('Asides')\n\n\nclass InlineHtml(StoryChild):\n \"\"\" Inline html code \"\"\"\n\n parent_story = models.ForeignKey(\n 'Story',\n related_name='inline_html_blocks',\n on_delete=models.CASCADE,\n )\n bodytext_html = models.TextField()\n\n class Meta:\n verbose_name = _('Inline HTML block')\n verbose_name_plural = _('Inline HTML blocks')\n\n def get_html(self):\n \"\"\" Returns text content as html. \"\"\"\n return mark_safe(self.bodytext_html)\n\n\ndef ratio(w, h):\n \"\"\"Calculate ratio as float\"\"\"\n return round(h / w, 4)\n\n\nclass StoryMedia(StoryChild, MarkupModelMixin):\n \"\"\" Video, photo or illustration connected to a story \"\"\"\n\n AUTO_RATIO = 0.0\n\n ASPECT_RATIO_CHOICES = [\n (AUTO_RATIO, _('auto')),\n (ratio(5, 2), _('5:2 landscape')),\n (ratio(2, 1), _('2:1 landscape')),\n (ratio(16, 9), _('16:9 landscape (youtube)')),\n (ratio(3, 2), _('3:2 landscape')),\n (ratio(4, 3), _('4:3 landscape')),\n (ratio(1, 1), _('1:1 square')),\n (ratio(3, 4), _('3:4 portrait')),\n (ratio(2, 3), _('2:3 portrait')),\n (ratio(1, 2), _('1:2 portrait')),\n ]\n\n class Meta:\n abstract = True\n\n caption = MarkupCharField(\n max_length=1000,\n help_text=_('Text explaining the media.'),\n verbose_name=_('caption'),\n )\n\n creditline = MarkupCharField(\n max_length=100,\n help_text=_('Extra information about media attribution and license.'),\n verbose_name=_('credit line'),\n )\n\n size = models.PositiveSmallIntegerField(\n default=1,\n help_text=_('Relative image size.'),\n verbose_name=_('image size'),\n )\n\n aspect_ratio = models.FloatField(\n verbose_name=_('aspect ratio'),\n help_text=_('height / width'),\n choices=ASPECT_RATIO_CHOICES,\n default=AUTO_RATIO,\n )\n\n def original_ratio(self):\n \"\"\" Width:Height ratio of the original media file. \"\"\"\n return 2 / 1\n\n def get_height(self, width, height):\n \"\"\" Calculate pixel height based on builtin ratio \"\"\"\n\n if self.aspect_ratio == self.AUTO_RATIO:\n height = height\n else:\n height = width * self.aspect_ratio\n return int(height)\n\n\nclass StoryImage(StoryMedia):\n \"\"\" Photo or illustration connected to a story \"\"\"\n\n class Meta:\n verbose_name = _('Image')\n verbose_name_plural = _('Images')\n unique_together = [('parent_story', 'imagefile')]\n ordering = ['-ordering']\n\n parent_story = models.ForeignKey(\n 'Story',\n related_name='images',\n on_delete=models.CASCADE,\n )\n\n imagefile = models.ForeignKey(\n ImageFile,\n help_text=_('Choose an image by name or upload a new one.'),\n verbose_name=('image file'),\n on_delete=models.CASCADE,\n )\n\n def __str__(self):\n return f'[{self.imagefile}]'\n\n def original_ratio(self):\n try:\n return self.imagefile.full_height / self.imagefile.full_width\n except TypeError:\n logger.warn(\n 'cannot calculate ratio for image %s' % (self.imagefile, )\n )\n return super().original_ratio()\n\n @property\n def filename(self):\n try:\n return str(self.imagefile)\n except ObjectDoesNotExist:\n return '[no image]'\n\n @property\n def small(self):\n return self.imagefile.small\n\n @cache_memoize()\n def large(self):\n return self.imagefile.large.url\n\n @property\n def crop_size(self):\n width, height = DEFAULT_IMAGE_SIZE\n im = self.imagefile\n if self.aspect_ratio == self.AUTO_RATIO:\n if not im.is_photo:\n height = width * self.original_ratio()\n else:\n height = width * self.aspect_ratio\n return int(width), int(height)\n\n @cache_memoize()\n def cropped(self):\n width, height = self.crop_size\n im = self.imagefile\n return im.thumbnail(\n f'{width}x{height}', crop_box=im.get_crop_box(), expand=1\n ).url\n\n\nclass StoryVideo(StoryMedia):\n \"\"\" Video content connected to a story \"\"\"\n\n VIDEO_HOSTS = (\n ('vimeo', _('vimeo')),\n ('youtu', _('youtube')),\n )\n\n class Meta:\n verbose_name = _('Video')\n verbose_name_plural = _('Videos')\n\n parent_story = models.ForeignKey(\n 'Story',\n related_name='videos',\n on_delete=models.CASCADE,\n )\n video_host = models.CharField(\n max_length=20,\n default=VIDEO_HOSTS[0][0],\n choices=VIDEO_HOSTS,\n )\n\n host_video_id = models.CharField(\n max_length=100,\n verbose_name=_('id for video file.'),\n help_text=_(\n 'the part of the url that identifies this particular video'\n )\n )\n\n def embed(self, width=\"100%\", height=\"auto\"):\n \"\"\" Returns html embed code \"\"\"\n if self.video_host == 'vimeo':\n # \n embed_pattern = (\n ''\n )\n elif self.video_host == 'youtu':\n # \n embed_pattern = (\n ''\n )\n else:\n raise Exception('unknown hosting site.')\n\n return embed_pattern.format(\n height=height,\n width=width,\n host_video_id=self.host_video_id,\n )\n\n @property\n def link(self):\n pk = self.host_video_id\n if self.video_host == 'youtu':\n return f'https://www.youtube.com/watch?v={pk}'\n elif self.video_host == 'vimeo':\n return f'https://vimeo.com/{pk}'\n return ''\n\n @classmethod\n def create_from_url(cls, url, parent_story):\n \"\"\" create video object from input url \"\"\"\n\n # url formats:\n # https://www.youtube.com/watch?v=roHl3PJsZPk\n # http://youtu.be/roHl3PJsZPk\n # http://vimeo.com/105149174\n\n def check_link(url, method='head', timeout=2):\n \"\"\" Does a http request to check the status of the url. \"\"\"\n # TODO: check_link() er omtrent lik som metode med samme navn i\n # InlineLink\n try:\n status_code = str(\n request(method, url, timeout=timeout).status_code\n )\n except Timeout:\n status_code = 408 # HTTP Timout\n except MissingSchema:\n status_code = 0 # not a HTTP url\n return status_code\n\n for host in cls.VIDEO_HOSTS:\n hostname = host[0]\n if hostname in url:\n video_host = hostname\n break\n else:\n video_host = None\n\n if not check_link(url) == 200:\n # something is wrong with the url?\n return None\n\n id_regex = r'[a-zA-Z0-9]+$'\n host_video_id = re.search(id_regex, url)\n\n try:\n new_video = cls(\n parent_story=parent_story,\n video_host=video_host,\n host_video_id=host_video_id,\n )\n\n new_video.save()\n return new_video\n except Exception as e:\n logger.debug(e)\n return None\n\n\n@receiver(models.signals.post_save)\ndef story_modified(sender, instance, **kwargs):\n if not issubclass(sender, StoryChild):\n return\n from apps.stories.models import Story\n Story.objects.filter(pk=instance.parent_story.pk\n ).update(modified=instance.modified)\n","sub_path":"django/apps/stories/models/storychildren.py","file_name":"storychildren.py","file_ext":"py","file_size_in_byte":11386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"341529735","text":"#coding: utf-8\n##\n#\n# @author : Olga Maslova, Licence DIM, IUT Annecy le Vieux, FRANCE\n# @brief : a set of generic functions for data management\n\n\"\"\"\n# a variable\na=1 # default type : int\n\n# an empty list\nmylist=[]\n\n#a filled list\nmylist2=[1,2,3]\n\n#append to a list\nmylist.append(10)\n\n#a buggy list\nmybuggylist=[1, 'a', \"Hi\"]\n\n#operators\nb=a+2\nmylist_sum=mylist+mylist2\n\"\"\"\n\ndef average_above_zero(input_list):\n\n #init critical variable\n positive_values_sum=0\n positive_values_count=0\n \n first_item=input_list[0]\n \n #compute the average of positive elements of a list\n for item in input_list:\n #select only positive items \n if item>0:\n positive_values_sum+=item\n positive_values_count+=1\n elif item==0:\n print('This value is null:'+str(item))\n raise ValueError('Zero value is not accepted')\n else:\n print('This value is negative:'+str(item)) \n raise ValueError('Negative value is not accepted')\n #compute the final average\n average=float(positive_values_sum)/float(positive_values_count)\n print('Positive elements average is '+str(average))\n return float(average)\n\"\"\" \n#testing average_above_zero function:\nmylist=[1,2,3,4,-7]\nresult= average_above_zero(mylist)\nprint(str(result))\nmessage='The average of positive items of {list_value) is {res}'.format(list_value=mylist,res=result)\nprint(message)\n\"\"\"\n\n \ndef max_value(input_list):\n ##\n # basic function able to return the max value of a list\n # @param input_list: the input list to be scanned\n # @throws an exception (ValueError) on an empty list\n \n #first check if provided list is not empty\n if len(input_list)==0:\n raise ValueError('provided list is empty')\n \n #init max_value and its index\n max_value=input_list[0]\n max_idx=0\n \n \"\"\" \n #generic style : iterate over the range of list indexes\n for idx in range(len(input_list)):\n if max_value idx: \n index_max-=1\n input_list[idx]=input_list[index_max]\n input_list[index_max]=item\n return input_list\n \n\"\"\"\n#Reverse a table : another way\ndef reverse_table(input_list):\n lastidx=len(input_list)\n for idx in range(len(input_list)/2):\n lastidx-=1\n popped=input_list[idx]\n input_list[idx]=input_list[lastidx]\n input_list[lastidx]=popped\n \n\"\"\"\n\n\"\"\" \n#testing reverse_table\nimport copy\nmylist=[1,5,4,-7]\nlistsave=copy.deepcopy(mylist)\nreverse_table(mylist)\nprint(listsave)\nprint('The reversed list is {newlist}'.format(newlist=mylist))\n\"\"\"\n\n\nimport numpy\nimport time\n\n##Bounding Box\n# calculates the coordinates of the non-zero area in the 2D matrix\n# @param my_mat: the input 2D matrix to be analyzed\n# @throws an exception (ValueError) on an empty matrix, an exception (ValueError) if the matrix does not contain any ones to calculate\n\ndef roi_bbox(my_mat):\n #first check if the input matrix is of certain size\n if len(my_mat) == 0:\n raise ValueError(\"Your matrix is empty!\")\n \n #output coordinates matrix\n bbox_coords=numpy.zeros([4,2],dtype=int)\n a=len(my_mat)\n c=0\n b=len(my_mat[0])\n d=0\n #check if there are ones to counter\n item = 1\n if item in my_mat:\n print(\"You are ok, continue!\")\n else: \n raise ValueError(\"Fill in you matrix first!\")\n \n #check every element of myMat \n for row in range(0,a):\n for col in range(0,b):\n item = my_mat[row,col]\n #if the element is 1, save its index(i,j)\n if item==1:\n if rowc:\n c=row\n if cold:\n d=col \n #populate the coordinates matrix with the values\n bbox_coords[0]=[a,b] \n bbox_coords[1]=[a,d] \n bbox_coords[2]=[c,b] \n bbox_coords[3]=[c,d] \n \n return bbox_coords \n\"\"\"\n##testing roi_bbox\nsize_rows=6\nsize_cols=6\nmyMat=numpy.zeros([size_rows,size_cols], dtype=int)\n#filling the matrix: better way\nmyMat[0:1,4:5]=1\nmyMat[2:4,0:4]=numpy.ones([2,4])\nprint(myMat)\ninit_time=time.time()\nresult_coordinates=roi_bbox(myMat)\nfinish_time=time.time()\nalltime=finish_time-init_time\nprint(result_coordinates)\n\"\"\"\n##Random filling of the matrix\n# fill random K positions with 'X'\n# @param my_mat: the input 2D matrix of type char, K: number of positions to fill \n# @throws an exception (ValueError) on an bad type matrix, an exception (ValueError) on an empty matrix, an exception (ValueError) on negative or superior to matrix's size value of K\ndef random_fill_sparse(my_mat,K): \n #check if the input matrix is of type char\n if str(my_mat.dtype)[:2] != '|S' and str(my_mat.dtype)[:2] != ' len(my_mat) :\n raise ValueError(\"Cannot fill negative nmber of cells or superior of the matrix's size!\")\n #the size of the array \n size_array=len(my_mat) \n #init iteration \n i = 0\n while i myList[ind]:\n min_idx = ind\n #swap two items of the list\n p+=1 \n myList[idx] , myList[min_idx] = myList[min_idx], myList[idx]\n #number of iterations does not depends on the content of the initial vector, but on its length (n) precisely (b)\n #(n²+n)/2 = 28 iterations (where n is the length of the list) needed to sort this list (c)\n #13 of permutations performed it depends on the order of initial list (d), \n #(n²+n)/2 = 28 comparisons applied (e)\n #the complexity is O(n²) \n return myList, i, p\n\"\"\" \n##testing sort_Selective\n#myList = [10, 15, 7, 1, 3, 3, 9]\nmyList = []\nfor i in range(100):\n item = alea(100)\n myList.append(item)\nshuffle(myList)\nprint(myList)\nresults_tuple = sort_Selective(myList)\nprint('Number of iterations is {i}, number of permutations is {p}'.format(i=results_tuple[1], p=results_tuple[2]))\n\n# (g) for n = 50, comparisons = 1275, permutaions : varied\n# for n = 100, comparisons = 5050, permutaions : varied\n# for n = 500, comparisons = 125250, permutaions : varied\n\"\"\"\n\n##\n#Illustration of bubble sorting (a)\ndef sort_bubble(myList):\n #check if the inputlist is not empty\n if len(myList) == 0:\n raise ValueError(\"Your list is empty!\")\n #itirations\n i = 0\n #permutation\n p = 0\n #comparison\n c = 0\n is_sorted = False\n #correction to reduce the length of the list for each outer loop\n m=0\n while is_sorted == False:\n i += 1 \n is_sorted = True\n for idx in range(len(myList)-1-m):\n i += 1\n c += 1\n if myList[idx]>myList[idx+1]:\n is_sorted = False\n #swap two items of the list\n p += 1\n myList[idx], myList[idx+1] = myList[idx+1], myList[idx]\n #print(myList, idx, i, c, p)\n m += 1 \n #number of iterations depends on the content of the initial vector, on its length (n) precisely (b)\n #28 iterations needed to sort this list (c)\n #13 of permutations performed it depends on the order of initial list (d), \n #24 comparisons applied (e)\n #the complexity is O(n²) \n return myList, i, p, c \n\n\"\"\"\n##testing sort_bubble\n#myList = [10, 15, 7, 1, 3, 3, 9]\nmyList = []\nfor i in range(100):\n item = alea(1000)\n myList.append(item)\nshuffle(myList)\nresults_tuple = sort_bubble(myList)\nprint(results_tuple[3])\nprint('Number of iterations is {i}, number of permutations is {p}'.format(i=results_tuple[1], p=results_tuple[2]))\n\n# (g) for n = 50, comparisons varied, permutaions : varied, max is n*(n-1)/2= 1225\n# for n = 100, comparisons varied, permutaions : varied, max is n*(n-1)/2 = 4950\n# for n = 500, comparisons varied, permutaions : varied, max is n*(n-1)/2 = 124750\n\"\"\"\n\n\n\n\n\n\n","sub_path":"assignments/Session1/S1_algotools.py","file_name":"S1_algotools.py","file_ext":"py","file_size_in_byte":11003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"140732978","text":"#!/usr/bin/env python\n\nimport sys\n\ndef print_freqs(set): # for debug\n print([x[0] for x in set])\n\n# get the two lowest frequencies from the set\ndef get_huffman_encoding(set):\n while len(set) > 1:\n lowest, scnd_lowest = (float('inf'),), (float('inf'),)\n # get lowest\n for node in set:\n if node[0] < lowest[0]:\n lowest = node\n elif node[0] < scnd_lowest[0]:\n scnd_lowest = node\n new_node = (lowest[0]+scnd_lowest[0], lowest, scnd_lowest)\n new_list = []\n for node in set:\n if node is not lowest and node is not scnd_lowest:\n new_list.append(node)\n new_list.append(new_node)\n set = new_list\n return set\n\ndef main():\n\tset = []\n\tfor line in sys.stdin.readlines():\n\t\tl = line.split()\n\t\t# we want freq to be first and numeric\n\t\tt = (float(l[1]), l[0])\n\t\tset.append(t)\n\tprint(get_huffman_encoding(set))\n\nif __name__ == \"__main__\": main()\n","sub_path":"huff.py","file_name":"huff.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"216429105","text":"#!/usr/bin/env python-2.4.3\n#\n# October 19 2010, Christian E. Hopps\n#\n# Copyright (c) 2010 by cisco Systems, Inc.\n# All rights reserved.\n\n# Standard Preamble\nimport pdb, sys, os, time\nos.environ['PY_XRUT_ROOT'] = os.path.dirname(os.path.dirname(os.path.abspath(sys.path[0])))\nsys.path[1:1] = [os.environ.get('PY_XRUT_ROOT') + '/modules']\n\n# Import modules we'll use.\nimport xrut, utng, pre, isis\n\n#\n# Topology common to all demos\n#\n# [ one ] --- net1 --- [ two ]\n#\ntopology = xrut.ng_topology_t( { 'net1': ( 'one', 'two' ) },\n toponame=\"demotopo\" )\none = topology.routers['one']\ntwo = topology.routers['two']\n\n#\n# Define a test suite that causes a core to demonstrate it being found\n#\nclass code_cov_suite (utng.test_suite_t):\n gcov_components = [ \"clns/isis\" ]\n gcov_processes = [ \"isis_show\" ]\n\n def test_000_config_isis (self):\n topology.config_topology( {\n 'all-iox': \"\"\"\n router isis ring\n net ${self.net}\n ${self.generate_interface_config(\"address-family ipv4 unicast\")}\n \"\"\"\n })\n preq = pre.prerequisite_t(isis.adjacency_up_pred_t(one, two, one.netifs['net1']), 60)\n preq.assert_test_case()\n\n one.send_command(\"show isis database summary\")\n\n# Execute the test suite.\ntopology.execute_test(code_cov_suite())\n","sub_path":"X-COPY/infra/test/xrut/examples/demo/demo-code-cov.py","file_name":"demo-code-cov.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"636268825","text":"import hmm_decoding_module\nimport hmm_changepoints_module\nimport hmm_outputs_module\nimport hmm_simulation_module\nimport hmm_forward_backwards_module\nimport hmm_BaumWelch_module\nimport numpy as np\n\ndef baum_welch_plus_analysis(smoothers, viterbi, time, data, max_num_bins_composite_bead, max_iterations, concentration, bin_width,\n fraction_of_photons_for_subset, arrayPi, arrayMeanCounts, matrixA, row, final_info_array,\n array_of_composite_bead_arrays, n, max_n, num_for_bead_geometric, max_num_for_bead_geometric, arrayPi_arraytosave, arrayMeanCounts_arraytosave, matrixA_arraytosave):\n print(\"row0 \", row)\n final_info_array, array_of_composite_bead_arrays, row, arrayPi_alliters, arrayMeanCounts_alliters, matrixA_alliters, loglikelihood_alliters = hmm_BaumWelch_module.with_decoding(\n smoothers, viterbi, time, data, max_num_bins_composite_bead, max_iterations, concentration, bin_width,\n fraction_of_photons_for_subset, arrayPi, arrayMeanCounts, matrixA, row, final_info_array,\n array_of_composite_bead_arrays, n, max_n, num_for_bead_geometric)\n matrixA_arraytosave, arrayMeanCounts_arraytosave, arrayPi_arraytosave = hmm_outputs_module.add_hmm_inputs_to_array(\n row, arrayPi_arraytosave, arrayMeanCounts_arraytosave, matrixA_arraytosave, arrayPi_alliters,\n arrayMeanCounts_alliters, matrixA_alliters, num_for_bead_geometric, max_num_for_bead_geometric)\n print(\"row1 \", row)\n\n return arrayPi_alliters, arrayMeanCounts_alliters, matrixA_alliters, loglikelihood_alliters, final_info_array, array_of_composite_bead_arrays, row, arrayPi_arraytosave, arrayMeanCounts_arraytosave, matrixA_arraytosave\n\n\ndef decode_changepoints_compositebead_statistics_savingarrays(smoothers, viterbi, n, forward_likelihood, backwards_likelihood, time, data, max_num_bins_bead, background_mean_counts, row, final_info_array, array_of_composite_bead_arrays, bin_width, concentration, fraction_of_photons_for_subset, loglikelihood, matrixA, arrayMeanCounts, arrayPi, num_iterations, max_iterations, num_for_bead_geometric):\n print(\"Decode, Changepoints, Composite Bead, Statistics, Add to Arrays\")\n if smoothers == 1:\n decoded = hmm_decoding_module.by_smoothers(n, forward_likelihood, backwards_likelihood)\n row, final_info_array, array_of_composite_bead_arrays = changepoints_compositebead_statistics_savingarrays(1, 0, decoded, time, data, max_num_bins_bead,\n background_mean_counts, row, final_info_array,\n array_of_composite_bead_arrays, bin_width, concentration,\n fraction_of_photons_for_subset, loglikelihood, matrixA, arrayMeanCounts,\n num_iterations, max_iterations, num_for_bead_geometric)\n\n if viterbi == 1:\n decoded = hmm_decoding_module.by_viterbi(data, matrixA, arrayMeanCounts, arrayPi)\n row, final_info_array, array_of_composite_bead_arrays = changepoints_compositebead_statistics_savingarrays(0, 1, decoded, time, data, max_num_bins_bead,\n background_mean_counts, row, final_info_array,\n array_of_composite_bead_arrays, bin_width, concentration,\n fraction_of_photons_for_subset, loglikelihood, matrixA, arrayMeanCounts,\n num_iterations, max_iterations, num_for_bead_geometric)\n\n return row, final_info_array, array_of_composite_bead_arrays\n\ndef changepoints_compositebead_statistics_savingarrays(smoothers, viterbi, decoded, time, data, max_num_bins_bead, background_mean_counts, row, final_info_array, array_of_composite_bead_arrays, bin_width, concentration, num_photons_subset, loglikelihood, matrixA, arrayMeanCounts, num_iterations, max_iterations, num_for_bead_geometric):\n changepoint_index = hmm_changepoints_module.get_changepoint_time_index_direction(decoded, time)\n all_beads_plus_dwell, composite_bead_array, num_beads_array = hmm_outputs_module.composite_bead(data,\n max_num_bins_bead,\n background_mean_counts,\n changepoint_index,\n num_iterations,\n num_for_bead_geometric)\n stats_all_transitions = hmm_outputs_module.statistics_all_transitions(changepoint_index, bin_width)\n row, final_info_array, array_of_composite_bead_arrays = hmm_outputs_module.add_to_holding_arrays(smoothers, viterbi, row,\n final_info_array,\n array_of_composite_bead_arrays,\n stats_all_transitions,\n bin_width,\n concentration,\n num_photons_subset,\n loglikelihood,\n matrixA,\n arrayMeanCounts,\n num_beads_array,\n num_iterations,\n max_iterations,\n num_for_bead_geometric,\n composite_bead_array)\n\n return row, final_info_array, array_of_composite_bead_arrays\n\ndef find_beads_detected_in_background_simulation(num_data_points, bin_width, row_b, arrayPi_alliters, arrayMeanCounts_alliters, matrixA_alliters, smoothers, viterbi, n, max_num_bins_bead, final_info_array, array_of_composite_bead_arrays, num_for_bead_geometric, concentration, fraction_of_photons_for_subset, max_iterations):\n print(\"Find Beads Detected in Background Simulation\")\n total_iterations = len(arrayMeanCounts_alliters)\n for i in range(total_iterations):\n arrayPi = arrayPi_alliters[i]\n arrayMeanCounts = arrayMeanCounts_alliters[i]\n matrixA = matrixA_alliters[i]\n\n num_iterations = i + 1\n\n time, background = hmm_simulation_module.simulate_background(arrayMeanCounts[0], num_data_points, bin_width)\n\n forward_likelihood, backwards_likelihood, loglikelihood = hmm_forward_backwards_module.run_algorithms_scaled_for_numba(len(arrayMeanCounts), len(background), background, arrayPi, matrixA, arrayMeanCounts)\n\n row_b, final_info_array, array_of_composite_bead_arrays = decode_changepoints_compositebead_statistics_savingarrays(smoothers, viterbi, n, forward_likelihood,\n backwards_likelihood, time, background, max_num_bins_bead,\n arrayMeanCounts[0], row_b, final_info_array,\n array_of_composite_bead_arrays, bin_width,\n concentration, fraction_of_photons_for_subset, loglikelihood,\n matrixA, arrayMeanCounts, arrayPi,\n num_iterations, max_iterations,\n num_for_bead_geometric)\n\n return final_info_array, array_of_composite_bead_arrays, background, row_b\n\ndef get_composite_bead_from_simulation(row, array_of_composite_bead_arrays_sim, array_of_num_beads_array, matrixA, arrayMeanCounts, time, num_for_bead_geometric, max_num_bins_bead):\n print(\"Composite Bead from Simulation\")\n total_iterations = len(arrayMeanCounts)\n for i in range(total_iterations):\n num_iterations = i + 1\n row1 = int(row/2) - total_iterations + i\n state, data = hmm_simulation_module.simulation(matrixA[i], arrayMeanCounts[i], len(time))\n changepoint_index = hmm_changepoints_module.get_changepoint_time_index_direction(state, time)\n all_beads_plus_dwell, composite_bead_array, num_beads_array = hmm_outputs_module.composite_bead(data, max_num_bins_bead, arrayMeanCounts[i, 0], changepoint_index, num_iterations, num_for_bead_geometric)\n array_of_composite_bead_arrays_sim = hmm_outputs_module.add_composite_bead_to_array(0, 0, row1, array_of_composite_bead_arrays_sim, composite_bead_array)\n num_beads_array = np.append(num_beads_array, np.array([num_iterations, num_for_bead_geometric]))\n array_of_num_beads_array[row1, :] = num_beads_array\n\n return array_of_num_beads_array, array_of_composite_bead_arrays_sim, data\n","sub_path":"hmm_analysis_module.py","file_name":"hmm_analysis_module.py","file_ext":"py","file_size_in_byte":10001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"382208929","text":"from __future__ import absolute_import, unicode_literals\nimport os\nfrom celery import Celery\nfrom celery.schedules import crontab\n\n# set the default Django settings module for the 'celery' program. Should be the same as in wsgi.py\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_time_tasks.settings')\n\napp = Celery('proj')\n\n# Using a string here means the worker don't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\n\napp.config_from_object('django.conf:settings', namespace='CELERY')\n\n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n\n\napp.conf.beat_schedule = {\n 'every-minute': {\n 'task': 'rand_quote',\n 'schedule': crontab()\n # 'args': (16, 16),\n },\n 'every-5-seconds': {\n 'task': 'multiply_two_numbers',\n 'schedule': 5.0,\n 'args': (16, 16)\n },\n 'delete-every-5-seconds': {\n 'task': 'delete_invoice',\n 'schedule': 5.0,\n },\n # 'add-every-3-seconds': {\n # 'task': 'tasks.add',\n # 'schedule': 3.0,\n # 'args': (16, 16)\n # },\n}","sub_path":"dj_time_tasks/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"646722974","text":"\n\nfrom xai.brain.wordbase.verbs._transmit import _TRANSMIT\n\n#calss header\nclass _TRANSMITS(_TRANSMIT, ):\n\tdef __init__(self,): \n\t\t_TRANSMIT.__init__(self)\n\t\tself.name = \"TRANSMITS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"transmit\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_transmits.py","file_name":"_transmits.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"580938434","text":"import os\nfrom plotnine import ggplot, aes, geom_boxplot, labs, theme, element_text, facet_wrap, facet_grid, geom_violin, ggtitle\nfrom plotnine.themes.elements import Margin\n\nfrom config import Config\nimport pandas as pd\nfrom projects import ProjectName\n\nprojects = list(map(lambda x: x.github(), list(ProjectName)))\nworking_projects = dict()\nfor project in projects:\n try:\n designite_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"designite\", project, \"scores.csv\"))\n designite_scores_df = pd.read_csv(designite_scores_path)\n designite_scores_df['dataset'] = 'Designite'\n designite_scores_df['project'] = project\n\n fowler_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"fowler\", project, \"scores.csv\"))\n fowler_scores_df = pd.read_csv(fowler_scores_path)\n fowler_scores_df['dataset'] = 'Fowler'\n fowler_scores_df['project'] = project\n\n # traditional_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"traditional\", project, \"scores.csv\"))\n # traditional_scores_df = pd.read_csv(traditional_scores_path)\n # traditional_scores_df['dataset'] = 'Traditional'\n # traditional_scores_df['project'] = project\n\n traditional_fowler_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"fowler_traditional\", project, \"scores.csv\"))\n traditional_fowler_scores_df = pd.read_csv(traditional_fowler_scores_path)\n traditional_fowler_scores_df['dataset'] = 'Traditional +\\n Fowler'\n traditional_fowler_scores_df['project'] = project\n\n # traditional_designite_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"traditional_designite\", project, \"scores.csv\"))\n # traditional_designite_scores_df = pd.read_csv(traditional_designite_scores_path)\n # traditional_designite_scores_df['dataset'] = 'Traditional +\\n Designite'\n # traditional_designite_scores_df['project'] = project\n\n designite_fowler_scores_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"designite_fowler\", project, \"scores.csv\"))\n designite_fowler_scores_df = pd.read_csv(designite_fowler_scores_path )\n designite_fowler_scores_df['dataset'] = 'Designite +\\n Fowler'\n designite_fowler_scores_df['project'] = project\n\n traditional_designite_fowler_path = Config.get_work_dir_path(os.path.join(\"paper\", \"analysis\", \"designite_fowler_traditional\", project, \"scores.csv\"))\n traditional_designite_fowler_scores_df = pd.read_csv(traditional_designite_fowler_path)\n traditional_designite_fowler_scores_df['dataset'] = 'Traditional +\\n Designite +\\n Fowler'\n traditional_designite_fowler_scores_df['project'] = project\n\n datasets = [\n designite_scores_df,\n fowler_scores_df,\n # traditional_scores_df,\n traditional_fowler_scores_df,\n # traditional_designite_scores_df,\n designite_fowler_scores_df,\n traditional_designite_fowler_scores_df\n ]\n\n scores_df = pd.concat(datasets, ignore_index=True)\n working_projects[project] = scores_df\n except Exception:\n continue\n\nscore_types = [\"precision\", \"recall\", \"f1-measure\", \"auc-roc\", \"brier score\"]\nfeatures_methods = [\"all\", \"chi2_20p\", \"chi2_50p\", \"f_classif_20\", \"f_classif_50\", \"mutual_info_classif_20p\", \"mutual_info_classif_50p\", \"recursive_elimination\", \"mutual_info_classif_50p\", \"recursive_elimination\"]\ncalculations = [\"mean\", \"max\"]\n\nfor score_type in score_types:\n for features_method in features_methods:\n for calculation in calculations:\n scores_df = pd.concat(list(map(lambda x: x.drop(['estimator', 'configuration'], axis=1)\n .groupby(['dataset', 'feature_selection'])\n .aggregate({score_type: calculation})\n .reset_index(), working_projects.values())))\n scores = scores_df.loc[scores_df['feature_selection'] == features_method]\n\n g = (ggplot(scores,\n aes(x='dataset',\n y=score_type))\n + geom_violin()\n + geom_boxplot(width=0.2)\n + labs(title=\"{0} Score with features from {1}\".format(score_type.capitalize(), features_method.capitalize()),\n x=\"Score Measure: {}\".format(score_type.capitalize()),\n y=\"Feature Selection Method: {}\".format(features_method.capitalize()))\n + theme(\n plot_title=element_text(size=30, lineheight=.8, vjust=1,\n family=\"Fira Code\", face=\"bold\", margin={'b': 25}),\n axis_text_x=element_text(size=15, family=\"Fira Code\"),\n axis_text_y=element_text(size=15, family=\"Fira Code\"),\n axis_title_x=element_text(size=20, family=\"Fira Code\"),\n axis_title_y=element_text(size=20, family=\"Fira Code\")\n )\n )\n pdf_dir = Config.get_work_dir_path(os.path.join(\"paper\", \"graphics\", \"ggplot\", \"images\", \"pdf\"))\n png_dir = Config.get_work_dir_path(os.path.join(\"paper\", \"graphics\", \"ggplot\", \"images\", \"png\"))\n csv_dir = Config.get_work_dir_path(os.path.join(\"paper\", \"graphics\", \"ggplot\", \"images\", \"csv\"))\n Config.assert_dir_exists(pdf_dir)\n Config.assert_dir_exists(png_dir)\n Config.assert_dir_exists(csv_dir)\n formatted_score_type = score_type.replace(\" \", \"_\")\n formatted_score_type = formatted_score_type.replace(\" \", \"_\")\n pdf_path = os.path.join(pdf_dir, \"{0}_{1}_{2}\".format(formatted_score_type, features_method, calculation))\n png_path = os.path.join(png_dir, \"{0}_{1}_{2}\".format(formatted_score_type, features_method, calculation))\n csv_path = os.path.join(csv_dir, \"{0}_{1}_{2}\".format(formatted_score_type, features_method, calculation))\n g.save(pdf_path, width=50, height=28.12, units=\"cm\")\n g.save(png_path, width=50, height=28.12, units=\"cm\")\n scores_df.to_csv(csv_path, index=False)\n","sub_path":"paper/graphics/ggplot/create_graphs.py","file_name":"create_graphs.py","file_ext":"py","file_size_in_byte":6304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"358798848","text":"import pandas as pd\nfrom bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\nimport re\n\ndef get_soup(url_link):\n req = Request(url_link, headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n soup_html = BeautifulSoup(webpage, 'html.parser') \n return soup_html\n\ndef game_score_array_single(game_score, match_soup):\n # Player 1 id\n p1_chunk = match_soup.findAll('div', {'class':'player1-name'})\n if len(p1_chunk)==1:\n url_p1 = re.search('href=\"(.*)\">', str(p1_chunk)).group(1)\n p1_split = url_p1.split('/')\n p1_pid = p1_split[4]\n else:\n p1_pid=''\n\n # Player 2 id\n p2_chunk = match_soup.findAll('div', {'class':'player2-name'})\n if len(p2_chunk)==1:\n url_p2 = re.search('href=\"(.*)\">', str(p2_chunk)).group(1)\n p2_split = url_p2.split('/')\n p2_pid = p2_split[4]\n else:\n p2_pid=''\n \n game_det = match_soup.findAll('div', {'class':'game-completed-wrap'}) \n games_played = len(game_det)\n for c, games in enumerate(game_det, 1):\n games_split = games.find_all('div')\n p1_score = games_split[2].text\n p1_score = p1_score.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n p2_score = games_split[4].text\n p2_score = p2_score.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n scores = {\n 't_id': tourney_id,\n 't_date': tourney_date,\n 'games_played': games_played,\n 'p1a_pid': p1_pid,\n 'p1b_pid': '',\n 'p2a_pid': p2_pid,\n 'p2b_pid': '',\n 'game': c,\n 'p1_score': p1_score,\n 'p2_score': p2_score}\n game_score.append(scores) \n return game_score\n\ndef game_score_array_double(game_score, match_soup):\n \n # Player 1 id \n p1_chunk = match_soup.findAll('div', {'class':'player1-name'}) \n if len(p1_chunk)==2: \n url_p1a = re.findall('href=\"(.*)\">', str(p1_chunk))[0]\n url_p1b = re.findall('href=\"(.*)\">', str(p1_chunk))[1] \n p1_split = url_p1a.split('/')\n p1a_pid = p1_split[4] \n p1_split = url_p1b.split('/')\n p1b_pid = p1_split[4]\n else:\n p1a_pid=''\n p1b_pid=''\n\n # Player 1 id \n p2_chunk = match_soup.findAll('div', {'class':'player2-name'}) \n if len(p2_chunk)==2: \n url_p2a = re.findall('href=\"(.*)\">', str(p2_chunk))[0]\n url_p2b = re.findall('href=\"(.*)\">', str(p2_chunk))[1] \n p2_split = url_p2a.split('/')\n p2a_pid = p2_split[4] \n p2_split = url_p2b.split('/')\n p2b_pid = p2_split[4]\n else:\n p2a_pid=''\n p2b_pid=''\n \n game_det = match_soup.findAll('div', {'class':'game-completed-wrap'}) \n games_played = len(game_det)\n for c, games in enumerate(game_det, 1):\n games_split = games.find_all('div')\n p1_score = games_split[2].text\n p1_score = p1_score.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n p2_score = games_split[4].text\n p2_score = p2_score.replace(\"\\t\",\"\").replace(\"\\n\",\"\")\n scores = {\n 't_id': tourney_id,\n 't_date': tourney_date,\n 'games_played': games_played,\n 'p1a_pid': p1a_pid,\n 'p1b_pid': p1b_pid,\n 'p2a_pid': p2a_pid,\n 'p2b_pid': p2b_pid,\n 'game': c,\n 'p1_score': p1_score,\n 'p2_score': p2_score}\n game_score.append(scores) \n return game_score\n\n# Load tourney list\ntourney_list = pd.read_csv('../../data/01_raw/tournament_year.csv', sep=\"|\")\n\nt_step = 1947\nurl_hit = 'https://bwfbadminton.com/results/1947/china-masters-gpg-2014/2014-04-17'\ni = 2\n\n#for t_step in range(47, len(tourney_list)):\nfor t_step in (range(734,47,-1)):\n game_score = []\n print(\"Tourney \" + str(t_step+1) + \" of \" + str(len(tourney_list)))\n url_hit = tourney_list['t_web_link'][t_step]\n print(url_hit)\n if url_hit != 'none': \n url_split = url_hit.split('/')\n tourney_id = url_split[4]\n \n # Hit podium page of tourney \n soup_html = get_soup(url_hit+'podium')\n ajax_table = soup_html.findAll('div', attrs={'class':'wrapper-content-results'}) \n ajax_el = ajax_table[0].findAll('ul', attrs={'class':'content-tabs'}) \n href_split = ajax_el[0].findAll('a', href=True)\n \n # All tournament days\n for i in range(1,len(href_split)-1):\n print(\"Day \" + str(i) + \" of \" + str(len(href_split)))\n get_id = str(href_split[i])\n # Url page of day i-th of tourney\n url_day = re.search('href=\"(.*)\">', get_id).group(1)\n day_soup = get_soup(url_day)\n game_table = day_soup.findAll('ul', attrs={'class':'list-sort-time'}) \n if len(game_table) != 0:\n game_table_split = game_table[0].find_all('li')\n \n game_count=1\n for get_game_details in range(1, len(game_table_split), 2):\n print(\"Game \" + str(game_count) + \" of \" + str(len(game_table_split)/2))\n game_count+=1\n get_id = str(game_table_split[get_game_details])\n if re.search('href=\"(.*)\">', get_id) is not None: \n url_match = re.search('href=\"(.*)\" id', get_id).group(1)\n url_match = url_match.replace(\"&\", \"&\") \n match_soup = get_soup(url_match)\n \n get_date = url_match.split('/')\n tourney_date = get_date[6]\n \n check_match_type = match_soup.findAll('div', {'class':'player1-name'})\n \n if len(check_match_type) == 2:\n match_type='doubles'\n game_score = game_score_array_double(game_score, match_soup)\n else:\n match_type='singles'\n game_score = game_score_array_single(game_score, match_soup) \n\n tourney_scores_df = pd.DataFrame(game_score) \n filename = \"../../data/01_raw/tourney_details_{}.csv\".format(tourney_id)\n tourney_scores_df.to_csv(filename, index=False, sep='|', header=True)","sub_path":"munge/01_raw/06_tourney_details.py","file_name":"06_tourney_details.py","file_ext":"py","file_size_in_byte":6525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"522607640","text":"import os\nimport cv2\nimport numpy as np\nimport random\nfrom vgt2 import find_contact_region, get_outline_and_normal\nfrom visulize_trajectory import plot_grasp_path\n\n\ndef get_object_pixels(mask_img):\n object_pixels = []\n r, c = mask_img.shape\n for i in range(r):\n for j in range(c):\n if mask_img[i, j] == 1:\n object_pixels.append([i, j])\n return object_pixels\n\n\ndef grasp_features(contact_region, outline_pixels, normals, gripper_center, theta): # gripper_center(row,col)\n \"\"\"\n\n :param contact_region: nx[row,col,side]\n :param outline_pixels:\n :param normals: nx[row0,col0,row1,col1]\n :param gripper_center: [row,col]\n :param theta: gripper roll\n :return: x_loss, y_loss, theta_loss\n \"\"\"\n normal_sum = np.array([0.0, 0.0])\n vector_sum = np.array([0.0, 0.0])\n left_sum = np.array([0.0, 0.0])\n right_sum = np.array([0.0, 0.0])\n gripper_center = np.array(gripper_center)\n if contact_region.shape[0] > 60:\n for contact_marker in contact_region:\n contact = outline_pixels[contact_marker[0]]\n vector_sum += contact - gripper_center # [row, col]\n normal_sum += normals[contact_marker[0]]\n if contact_marker[1] == 0:\n # left side\n left_sum += normals[contact_marker[0]] # [row, col]\n else:\n # right side\n right_sum += normals[contact_marker[0]] # [row, col]\n x_loss = (vector_sum[0] ** 2 + vector_sum[1] ** 2)**0.5\n y_loss = (normal_sum[0] ** 2 + normal_sum[1] ** 2)**0.5\n r_normal = np.array([np.sin(np.deg2rad(theta)), np.cos(np.deg2rad(theta))]) # [row, col]\n l_normal = np.array([-np.sin(np.deg2rad(theta)), -np.cos(np.deg2rad(theta))]) # [row, col]\n if left_sum.all() == 0:\n alpha = 180\n beta = 180\n elif right_sum.all() == 0:\n beta = 180\n alpha = 180\n else:\n c_alpha = np.dot(l_normal, left_sum) / (left_sum[0]**2+left_sum[1]**2)**0.5\n c_beta = np.dot(r_normal, right_sum) / (right_sum[0]**2 + right_sum[1]**2)**0.5\n alpha = np.rad2deg(np.arccos(c_alpha))\n beta = np.rad2deg(np.arccos(c_beta))\n theta_loss = alpha + beta\n return x_loss, y_loss, theta_loss\n else:\n return -1, -1, -1\n\n\ndef gather_data(mask_img, obj_pt, center_id, grasp_angles):\n outline_pixels, outline_normals, index_array = get_outline_and_normal(mask_img[:, :, 0], 0, 0, 7)\n results = np.ndarray((0, 7), dtype=np.float16)\n # interrupted = False\n for i in center_id:\n # if interrupted:\n # break\n for a in grasp_angles:\n # x = input('press q to quit...')\n # if x == 'q':\n # interrupted = True\n # break\n contact = find_contact_region(outline_pixels, index_array, obj_pt[i], a)\n l1, l2, l3 = grasp_features(contact, outline_pixels, outline_normals, obj_pt[i], a)\n data = [0, obj_pt[i][0], obj_pt[i][1], a, l1, l2, l3] # current grasp data\n if results.size == 0:\n new_results = np.append(results, [data], axis=0)\n # add first one\n else:\n left = 0\n right = len(results) - 1\n\n ci = results[left]\n img1 = np.copy(mask_img*255)\n img2 = np.copy(mask_img*255)\n plot_grasp_path(obj_pt[i], a, 19, 130, img1)\n plot_grasp_path([int(round(ci[1])), int(round(ci[2]))], ci[3], 19, 130, img2)\n img3 = cv2.hconcat([img1, img2])\n img3_s = cv2.resize(img3, (1280, 400))\n cv2.imshow('choose the better grasp', img3_s)\n print(f'compare with {left}')\n usr_input = cv2.waitKeyEx(0)\n cv2.destroyAllWindows()\n if usr_input == 2424832:\n # case 3\n print('left side is better')\n cv2.destroyAllWindows()\n ci = results[right]\n img1 = np.copy(mask_img*255)\n img2 = np.copy(mask_img*255)\n plot_grasp_path(obj_pt[i], a, 19, 130, img1)\n plot_grasp_path([int(round(ci[1])), int(round(ci[2]))], ci[3], 19, 130, img2)\n img3 = cv2.hconcat([img1, img2])\n img3_s = cv2.resize(img3, (1280, 400))\n cv2.imshow('choose the better grasp', img3_s)\n print(f'compare with {right}')\n usr_input = cv2.waitKeyEx(0)\n cv2.destroyAllWindows()\n if usr_input == 2555904:\n # case 31\n print('right side is better')\n while True:\n mid = int((left + right) / 2)\n if mid == left:\n print(f'left {left}, right {right}')\n data[0] = results[right, 0]\n results[right:, 0] += 1\n new_results = np.concatenate([results[:right], [data], results[right:]])\n break\n else:\n ci = results[mid]\n img1 = np.copy(mask_img*255)\n img2 = np.copy(mask_img*255)\n plot_grasp_path(obj_pt[i], a, 19, 130, img1)\n plot_grasp_path([int(round(ci[1])), int(round(ci[2]))], ci[3], 19, 130, img2)\n img3 = cv2.hconcat([img1, img2])\n img3_s = cv2.resize(img3, (1280, 400))\n cv2.imshow('choose the better grasp', img3_s)\n print(f'compare with {mid}')\n usr_input = cv2.waitKeyEx(0)\n cv2.destroyAllWindows()\n if usr_input == 2424832:\n print('left side is better')\n left = mid\n elif usr_input == 2555904:\n print('right side is better')\n right = mid\n else:\n print('same quality')\n data[0] = ci[0]\n better_side = mid\n for n in range(mid, len(results)):\n if results[n, 0] > ci[0]:\n better_side = n\n break\n results[better_side:, 0] += 1\n new_results = np.concatenate([results[:mid], [data], results[mid:]])\n break\n\n elif usr_input == 2424832:\n # case 32\n print('current pose is the best so far')\n data[0] = ci[0] + 1 # update grasp quality\n new_results = np.concatenate([results, [data]]) # add current grasp to the array\n else:\n # case 33\n print('current pose is equally good as the best one')\n data[0] = ci[0]\n new_results = np.concatenate([results, [data]])\n\n elif usr_input == 2555904:\n print('right side is better')\n # case 1\n results[:, 0] += 1 # update grasp quality of all grasps that are better that current grasp\n new_results = np.concatenate([[data], results]) # add current grasp to the array\n else:\n # case 2\n print('same grasp quality')\n new_results = np.concatenate([[data], results])\n\n results = new_results\n print(results.shape)\n np.savetxt('grasp_feature_study.txt', results, fmt='%1.4f')\n return results\n\n\nif __name__ == '__main__':\n path = os.path.dirname(os.getcwd())\n img_rgb = 'spoon3.png'\n img_mask = 'spoon3_mask.png'\n I = cv2.imread(os.path.join(path, 'pictures', img_rgb))\n Im = cv2.imread(os.path.join(path, 'pictures', img_mask))\n Ip = get_object_pixels(Im[:, :, 0])\n while True:\n sample_indices = random.sample(range(len(Ip)), 20)\n sample_check = np.copy(Im)*255\n for ii in sample_indices:\n cv2.circle(sample_check, (Ip[ii][1], Ip[ii][0]), 2, (0, 0, 255))\n cv2.imshow('sample check', sample_check)\n print('press k if the sample is good')\n xx = cv2.waitKey(0)\n cv2.destroyAllWindows()\n if xx == ord('k') or xx == ord('K'):\n break\n sample_angles = np.arange(-90, 90, 10)\n\n gf_data = gather_data(Im, Ip, sample_indices, sample_angles)\n np.savetxt('grasp_feature_study.txt', gf_data, fmt='%1.4f')\n\n # arr = np.arange(9).reshape((3, 3))\n # new_arr = np.concatenate([arr[:2], [[8,3,3]], arr[2:]])\n # print(new_arr)\n\n # path = os.path.dirname(os.getcwd())\n # img_rgb = 'spoon3.png'\n # img_mask = 'spoon3_mask.png'\n # I = cv2.imread(os.path.join(path, 'pictures', img_rgb))\n # print('press a key')\n # cv2.imshow('test', I)\n # c = cv2.waitKeyEx(0)\n # print('you pressed', c)\n # if c == 2621440:\n # print('you pressed down')\n # if c == 2424832:\n # print('you pressed left')\n # if c == 2555904:\n # print('you pressed '\n # 'right')","sub_path":"daniel/Grasp_Tuning/code/grasp_feature_test.py","file_name":"grasp_feature_test.py","file_ext":"py","file_size_in_byte":9837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"119494283","text":"def Decryption(string): #Encrypted String -> string\r\n\t\r\n\tfile = open(\"Library/decrypted.txt\",\"r\") #Retrieves a string of letters, which are in order: abcdefg...\r\n\tDC = file.read()\r\n\tfile.close()\r\n\t\r\n\tfile = open(\"Library/encrypted.txt\",\"r\") #Retrieves a string of letters, which are in random order: the encryption key\r\n\tEC = file.read()\r\n\tfile.close()\r\n\t\r\n\tstringLength = len(string) #Length of the string\r\n\tlength = len(EC) #Number of characters in the key\r\n\tindex = 0 #Sets index to 0, in order to start from the first character\r\n\tdecryptedString = \"\"\r\n\taddition = 0\r\n\r\n\twhile index != stringLength: #Will repeat until entire string is handeled\r\n\r\n\t\tstringLetter = string[index] #Takes the index letter\r\n\r\n\t\tspot = EC.index(stringLetter) #Finds the index of the letter in the key\r\n\r\n\t\tdecryptedLetter = DC[(spot + addition) % length] #Finds the letter in the order that corresponds to the index of the letter in the key. Reverses encryption\r\n\r\n\t\tindex = index + 1 #Continues to the next letter\r\n\t\taddition = addition - 1 #Allows reversing the encryption\r\n\r\n\t\tdecryptedString = decryptedString + decryptedLetter #Adds the decrypted letter to the string\r\n\t\r\n\treturn(decryptedString) #Returns the decrypted string \r\n\t\r\n\r\nprint(\"\\nString Decryption\")\r\nprint(\"-----------------\")\r\nprint(Decryption(input(\"Text:\")))\r\n","sub_path":"Decryption.py","file_name":"Decryption.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"16514657","text":"\"\"\"create dataset and dataloader\"\"\"\nimport logging\nimport torch\nimport torch.utils.data\n\n\ndef create_dataloader(dataset, dataset_opt, opt=None, sampler=None):\n phase = dataset_opt['phase']\n if phase == 'train':\n num_workers = dataset_opt['n_workers'] * len(opt['gpu_ids'])\n batch_size = dataset_opt['batch_size']\n # shuffle = True\n shuffle = dataset_opt['use_shuffle']\n return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers, sampler=sampler,\n pin_memory=True)\n else:\n batch_size = dataset_opt['batch_size']\n # shuffle = dataset_opt['use_shuffle']\n shuffle = False\n return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=0,\n pin_memory=False)\n\n\ndef create_dataset(opt,dataset_opt):\n mode = dataset_opt['mode']\n # datasets for image restoration\n if mode == 'SIEN_train':\n from data.SIEN_dataset import DatasetFromFolder as D\n\n dataset = D(upscale_factor=opt['scale'], data_augmentation=dataset_opt['augment'],\n group_file=dataset_opt['filelist'],\n patch_size=dataset_opt['IN_size'], black_edges_crop=False, hflip=True, rot=True)\n\n elif mode == 'SIEN_val':\n from data.SIEN_dataset import DatasetFromFolder as D\n dataset = D(upscale_factor=opt['scale'], data_augmentation=False,\n group_file=dataset_opt['filelist'],\n patch_size=None, black_edges_crop=False, hflip=False, rot=False)\n\n else:\n raise NotImplementedError('Dataset [{:s}] is not recognized.'.format(mode))\n\n\n logger = logging.getLogger('base')\n logger.info('Dataset [{:s} - {:s}] is created.'.format(dataset.__class__.__name__,\n dataset_opt['name']))\n return dataset\n","sub_path":"data/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"278873972","text":"N, M = map(int, input().split())\nA = list(map(int, input().split()))\n\nA = sorted(A)\n\n#番兵追加\nA.insert(0, 0)\nA.append(N+1)\n\nans = 0\nwhite_box = []\nfor i in range(M+1):\n box_length = A[i+1]-A[i]-1\n if (box_length != 0):\n white_box.append(box_length)\n\ntry:\n k = min(white_box)\nexcept ValueError:\n print(ans)\n exit()\n\nfor j in white_box:\n ans += -(-j // k)\nprint(ans)\n","sub_path":"python/Stamp.py","file_name":"Stamp.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"368903200","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 31 16:50:13 2017\n\n@author: Owner\n\"\"\"\n#Functions\n############################################################################### \nimport random\nimport math\nimport networkx as nx\n\ndef WriteResults(list):\n \"\"\"writes out elements of a list to text\"\"\"\n with open(\"Output.txt\", \"w\") as text_file:\n for j in range(len(list)):\n text_file.write(str(list[j]) + \"\\n\") \n text_file.close()\n \ndef readFasta(fileName):\n f = open(fileName)\n seqs = {}\n for line in f:\n line = line.rstrip()\n if line[0] == '>':\n words = line.split()\n name = words[0][1:]\n seqs[name] = ''\n else:\n seqs[name] = seqs[name] + line\n f.close()\n return seqs\n \ndef readSequenceArray(fileName):\n f = open(fileName)\n seqs = []\n for line in f:\n line = line.rstrip()\n seqs.append(line)\n f.close()\n return seqs\n \ndef readGapSeparatedSequenceArray(fileName):\n f = open(fileName)\n seqs = []\n for line in f:\n line = line.rstrip()\n lines = line.split(' ')\n for l in lines:\n seqs.append(l)\n f.close()\n return seqs\n \ndef getLongestSequenceInFasta(dic):\n maxLength = 0\n longest = 0\n for k, v in dic.items():\n longest = len(v)\n if longest > maxLength:\n maxLength = longest\n return maxLength\n \ndef getsequenceLengthsInFasta(dic):\n sequenceL = []\n for k, v in dic.items():\n sequenceL.append(len(v)) \n return sequenceL \n\ndef getLengthsDicInFasta(dic):\n sequenceL = {}\n for k, v in dic.items():\n l = len(v)\n sequenceL.update({k:l}) \n return sequenceL \n\n\ndef reverseComplement(s):\n \"\"\"computes the reverse complement of a DNA string\"\"\"\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}\n t = ''\n for base in s:\n t = complement[base] + t\n return t\n\n\ndef create_dna(n, alphabet='acgt'):\n \"\"\"creates a random string of DNA\"\"\"\n return ''.join([random.choice(alphabet) for i in range(n)])\n \ndef naive(p, t):\n #Given a DNA sequence (t) search for the number of occurences of an exact \n #match (p)\n occurrences = []\n for i in range(len(t) - len(p) + 1): # loop over alignments\n match = True\n for j in range(len(p)): # loop over characters\n if t[i+j] != p[j]: # compare characters\n match = False\n break\n if match:\n occurrences.append(i) # all chars matched; record\n return occurrences \n \ndef kmerCount(k,t):\n #Counts the number if occurences if a k-mer in a dna sequence (naive)\n d = {}\n occurrences = []\n count = 0\n for j in range(len(t) - k + 1):\n p = t[j:j+k]\n for i in range(len(t) - len(p) + 1): \n if(p == t[i: i + len(p)]):\n count+= 1\n occurrences.append(i) \n d.update({p:occurrences})\n occurrences = []\n return d\n \ndef patternCount(t,p):\n #Counts the number if occurences if a k-mer in a dna sequence (naive)\n count = 0\n for i in range(len(t) - len(p) + 1): \n if(p == t[i: i + len(p)]):\n count+= 1 \n return count\n\ndef approximatePatternCount(text,pattern,d):\n '''count instances of pattern with at most d mismatches'''\n count = 0\n l = []\n for i in range(len(text) - len(pattern) + 1):\n p = text[i: i + len(pattern)]\n if(hammingDistance(pattern,p) <= d):\n count = count + 1\n l.append(i)\n return count\n \ndef approximatePatternMatch(text,pattern,d):\n '''count instances of pattern with at most d mismatches'''\n l = []\n for i in range(len(text) - len(pattern) + 1):\n p = text[i: i + len(pattern)]\n if(hammingDistance(pattern,p) <= d):\n \n l.append(i)\n return l\n \ndef readGenome(filename):\n genome = ''\n with open(filename, 'r') as f:\n for line in f:\n # ignore header line with genome information\n if not line[0] == '>':\n genome += line.rstrip()\n return genome\n \ndef getSequencingReads(filename):\n reads = []\n with open(filename, 'r') as f:\n for line in f:\n reads.append(line.rstrip())\n return reads\n \n#Hamming Distance - Problem 1\ndef hammingDistance(s1, s2):\n \"\"\"Compute the Hamming distance between two strings\"\"\"\n #test that they have values\n if len(s1) == 0: return len(s2)\n if len(s2) == 0: return len(s1) \n #Convert the int lists to strings\n str1 = ''.join(str(e) for e in s1)\n str2 = ''.join(str(e) for e in s2) \n #Counter set at zero\n hamDist = 0\n for i in range(0, len(str1)):\n #If the values at the specified index aren't equal\n if str1[i] != str2[i]:\n #increment\n hamDist += 1 \n #Return the total count.\n return hamDist\n \ndef distanceBetweenPatternAndStrings(pattern,dna):\n \"\"\"Computes the the sum total distance between kmer and a list of DNA strings\"\"\"\n k = len(pattern)\n distance = 0\n totalDistance = 0\n for text in dna:\n hd = float('inf')\n # generate all kmer pattern' in text\n kmers = kmersFromDNA(text,k)\n for j in kmers:\n distance = hammingDistance(pattern,j)\n if hd > distance:\n hd = distance\n totalDistance += hd \n return totalDistance\n \n \n \n \ndef medianString(dna,k):\n distance = float('inf') \n for i in range(int(4**k)): \n pattern = NumberToPattern(i,k)\n if distance > distanceBetweenPatternAndStrings(pattern,dna):\n distance = distanceBetweenPatternAndStrings(pattern,dna)\n median = pattern \n return median\n\ndef LastSymbol( pattern ):\n return pattern[ -1: ]\n\ndef skew(sequence):\n \"\"\"Find a position in a genome where the skew diagram attains a minimum.\"\"\"\n c = 0\n g = 0\n min_skew = 0\n skew_list = []\n index = 0\n for i in sequence:\n index += 1\n if i == 'C':\n c += 1\n if i == 'G':\n g += 1\n skew = g-c\n if skew < min_skew:\n skew_list = [index]\n min_skew = skew\n if skew == min_skew and index not in skew_list:\n skew_list.append(index) \n print(skew_list)\n\ndef SymbolToNumber( symbol ):\n retVal = 10000\n if symbol == 'A':\n retVal = 0 \n elif symbol == 'C':\n retVal = 1\n elif symbol == 'G':\n retVal = 2\n elif symbol == 'T':\n retVal = 3\n return retVal\n\ndef NumberToSymbol( index ):\n symbol = 'Z'\n if index == 0:\n symbol = 'A'\n elif index == 1:\n symbol = 'C'\n elif index == 2:\n symbol = 'G'\n elif index == 3:\n symbol = 'T'\n return symbol\n\ndef PatternToNumber( pattern ):\n \"\"\"Convert a DNA string to a number\"\"\"\n if pattern == \"\":\n return 0\n if len( pattern ) > 0:\n subStrEndIndex = len( pattern ) - 1\n else:\n subStrEndIndex = 0\n prunedPattern = pattern[ 0: subStrEndIndex ]\n lastSymbol = LastSymbol( pattern )\n #The '4 *' allows the resulting numbers to be unique according to their symbol's positions.\n return 4 * PatternToNumber( prunedPattern ) + SymbolToNumber( lastSymbol )\n\ndef NumberToPattern( index, k ):\n \"\"\"Convert an integer to its corresponding DNA string.\"\"\"\n if k == 1:\n return NumberToSymbol( index )\n prefixIndex = index // 4\n remainder = index % 4\n prefixPattern = NumberToPattern( prefixIndex, k - 1 )\n symbol = NumberToSymbol( remainder )\n return prefixPattern + symbol \n\ndef computingFrequencies(text,k):\n \"\"\"Compute frequency array of kmers\"\"\"\n frequencyArray = []\n for i in range(int(4**k)): \n frequencyArray.append(0) \n for i in range(len(text)- k + 1):\n pattern = text[i:i+k]\n j = PatternToNumber(pattern)\n frequencyArray[j] = frequencyArray[j] + 1\n return frequencyArray\n \ndef frequentWords(text,k):\n \"\"\"Find the most frequent k-mers in a string\"\"\"\n frequentPatterns = []\n count = count = [0] * (len(text) - k + 1)\n for i in range(len(text) - k + 1):\n pattern = text[i:i+k]\n count[i] = patternCount(text,pattern)\n maxCount = max(count)\n for i in range(len(text) - k + 1):\n if(count[i] == maxCount):\n frequentPatterns.append(text[i:i+k])\n fp = set(frequentPatterns)\n result = []\n for i in fp:\n result.append(i)\n return result\n\ndef fasterFrequentWords(text,k):\n \"\"\"Find the most frequent k-mers in a string\"\"\"\n frequentPatterns = []\n frequencyArray = computingFrequencies(text,k)\n maxCount = max(frequencyArray)\n for i in range(int(4**k)): \n if frequencyArray[i] == maxCount:\n pattern = NumberToPattern(i,k)\n frequentPatterns.append(pattern)\n return frequentPatterns \n\ndef clumpFinding(genome,k,t,L):\n \"\"\"Find patterns forming clumps in a string.\"\"\"\n frequentPatterns = [] \n clump = [0] * int(4**k)\n for i in range(len(genome) - L):\n text = genome[i:i + L]\n frequencyArray = computingFrequencies(text,k)\n for index in range(int(4**k)): \n if(frequencyArray[index] >= t):\n clump[index] = 1\n for i in range(int(4**k)):\n if clump[i] == 1:\n pattern = NumberToPattern(i,k)\n frequentPatterns.append(pattern)\n return frequentPatterns\n \ndef neighbors(pattern,d):\n \"\"\"The d-neighborhood Neighbors(Pattern, d) is the set of all k-mers whose Hamming distance from Pattern does not exceed d.\"\"\"\n x = ['A','C','G','T']\n if d == 0:\n return pattern\n if len(pattern) == 1:\n return ['A','C','G','T']\n neighborhood = []\n suffixNeighbors = neighbors(suffix(pattern),d)\n for text in suffixNeighbors:\n if hammingDistance(suffix(pattern),text) < d:\n for nucleotide in x:\n p = nucleotide + text\n neighborhood.append(p)\n else:\n p = firstSymbol(pattern) + text\n neighborhood.append(p)\n return neighborhood\n \ndef suffix(pattern):\n return pattern[1:len(pattern)]\n \ndef prefix(pattern):\n return pattern[0:len(pattern) -1]\n\ndef firstSymbol(pattern):\n return pattern[0]\n \ndef immediateNeighbors(pattern):\n neighborhood = []\n for i in range(pattern):\n symbol = pattern[i]\n for j in range(pattern):\n if j != symbol:\n pattern[i] = j\n neighbor = pattern\n neighborhood.append(neighbor)\n return neighborhood\n\ndef frequentWordsWithMismatches(text,k,d):\n \"\"\"Find the most frequent k-mers with mismatches in a string.\"\"\"\n frequentPatterns = [] \n frequencyArray = [] \n close = []\n for i in range(int(4**k)):\n frequencyArray.append(0)\n close.append(0)\n for i in range(len(text) - k):\n neighborhood = neighbors(text[i:i+k],d)\n for pattern in neighborhood:\n index = PatternToNumber(pattern)\n close[index] = 1\n for i in range(int(4**k)):\n if(close[i] == 1):\n pattern = NumberToPattern(i,k)\n frequencyArray[i] = approximatePatternCount(text,pattern,d) \n maxCount = max(frequencyArray)\n for i in range(int(4**k)):\n if frequencyArray[i] == maxCount:\n pattern = NumberToPattern(i,k)\n frequentPatterns.append(pattern)\n return frequentPatterns \n \ndef motifEnumeration(dna,k,d):\n \"\"\"Gets kmers from all DNA strings, searches them for kmers with at most d mistmatches then looks for d-neighbors that appear on all dna strings\"\"\"\n patterns = []\n primePatterns = []\n counter = 0\n kmers = kmersFromDNAList(dna,k) \n # we get all neighbors of all the kmers of all dna strings\n for kmer in kmers:\n n = neighbors(kmer,d)\n for i in n:\n primePatterns.append(i)\n #now we search for all prime patterns in all string with at most d mismatches\n for j in primePatterns:\n for string in dna:\n l = approximatePatternMatch(string,j,d)\n if len(l) > 0:\n counter += 1\n if counter >= len(dna):\n patterns.append(j) \n counter = 0\n counter = 0 \n return set(patterns)\n \ndef generateKmers(k):\n \"\"\"Generate all possible kmers of length k\"\"\"\n kmers = []\n for i in range(int(4**k)):\n pattern = NumberToPattern(i,k)\n kmers.append(pattern)\n return kmers\n\ndef kmersFromDNA(d,k):\n \"\"\"Retunrs a list of k-mers from a string of DNA\"\"\"\n kmers = []\n for i in range(len(d) - k + 1): \n kmers.append(d[i:i+k]) \n return kmers\n \ndef kmersFromDNAList(dna,k):\n kmers = []\n for i in dna:\n l = kmersFromDNA(i,k)\n for j in l:\n kmers.append(j)\n return kmers\n \ndef searchFrequentWords(d,l):\n max = 0\n key = \"\"\n value = 0\n r = {}\n for k,v in d.items():\n w = kmerCount(l,v)\n #get max\n for k,v in w.items():\n if len(v) > max:\n key = k\n value = v\n max = len(v)\n r.update({key:value}) \n return r\n\ndef genomePath(d):\n seq = d[0]\n for i in d: \n seq += i[-1]\n return seq\n \ndef graphExample():\n G=nx.Graph()\n G.add_node(\"spam\")\n G.add_edge(1,2)\n G.add_edge(2,3)\n return G\n \ndef kmerCompositionLexigographic(s,k):\n kmers = kmersFromDNA(s,k)\n kmers.sort()\n return kmers\n \ndef kmerGraph(s,k):\n d = kmersFromDNA(s,k)\n G=nx.DiGraph()\n for i in d:\n G.add_node(i)\n for j in d:\n if suffix(i) == prefix(j):\n G.add_edge(i,j)\n return G\n\ndef kmerdeBruijnGraph(s,k):\n d = kmersFromDNA(s,k)\n G=nx.DiGraph()\n for i in d:\n G.add_node(prefix(i))\n for j in d:\n if suffix(i) == prefix(j):\n G.add_edge(prefix(i),suffix(i))\n G.add_node(suffix(d[len(d)- 1]))\n return G\n \n \n###############################################################################\n","sub_path":"ProteoGenomics/Genomics/Chapter1_3.py","file_name":"Chapter1_3.py","file_ext":"py","file_size_in_byte":14365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"371585340","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/11/6 14:41\n# @Software: PyCharm Community Edition\n# @Author : Ada\n# @File : do_excel.py\n# 完成excel的读与写\nimport openpyxl\n\nfrom API.API_7.common import http_request\n\n\"\"\"\n测试用例类,每个测试用例,实际上就是它的一个实例\n\"\"\"\nclass Case:\n def __init__(self):\n self.case_id=None\n self.title=None\n self.url=None\n self.data=None\n self.method=None\n self.excepted=None\n self.actual=None\n self.result=None\n self.sql=None\nclass DoExcel:\n\n def __init__(self,file_name,sheet_name):\n self.file_name = file_name\n self.sheet_name = sheet_name\n self.workbook = openpyxl.load_workbook(file_name)\n self.sheet = self.workbook[sheet_name]\n def get_cases(self):\n max_row=self.sheet.max_row#获取最大行数\n\n cases=[]#列表,存放所有的测试用例\n for r in range(2,max_row+1):\n\n case=Case()#实例\n case.case_id=self.sheet.cell(row=r,column=1).value\n case.title=self.sheet.cell(row=r, column=2).value\n case.url=self.sheet.cell(row=r, column=3).value\n case.data=self.sheet.cell(row=r, column=4).value\n case.method=self.sheet.cell(row=r, column=5).value\n case.expected=self.sheet.cell(row=r, column=6).value\n case.sql=self.sheet.cell(row=r,column=9).value#执行的sql\n cases.append(case)\n\n self.workbook.close()\n return cases#返回case列表\n\n def write_result(self,row,actual,result):\n sheet=self.workbook[self.sheet_name]\n sheet.cell(row,7).value= actual\n sheet.cell(row,8).value = result\n self.workbook.save(filename=self.file_name)\n self.workbook.close()\n\nif __name__==\"__main__\":\n from API.API_3.common import contants\n do_excel=DoExcel(contants.case_file,sheet_name='login')\n cases=do_excel.get_cases()\n http_request= http_request.HTTPRequest()\n for case in cases:\n # print(case.case_id)\n # print(case.title)\n # print(case.url)\n # print(case.data)\n # print(case.method)\n # print(case.excepted)\n print(case.__dict__)\n print(type(case.data))\n resp=http_request.request(case.method,case.url,case.data)\n print(resp.status_code)\n print(resp.text)#响应文本\n resp_dict = resp.json()#返回字典\n print(resp_dict)\n\n actual=resp.text\n if case.excepted == actual:#判断期望结果和实际结果是否一致\n do_excel.write_result(case.case_id+1,actual,'PASS')\n\n else:\n do_excel.write_result(case.case_id+1,actual,'FAIL')","sub_path":"common/do_excel.py","file_name":"do_excel.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"138081890","text":"\n\nfrom xai.brain.wordbase.nouns._cure import _CURE\n\n#calss header\nclass _CURED(_CURE, ):\n\tdef __init__(self,): \n\t\t_CURE.__init__(self)\n\t\tself.name = \"CURED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cure\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cured.py","file_name":"_cured.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180525646","text":"\n\nfrom xai.brain.wordbase.nouns._penguin import _PENGUIN\n\n#calss header\nclass _PENGUINS(_PENGUIN, ):\n\tdef __init__(self,): \n\t\t_PENGUIN.__init__(self)\n\t\tself.name = \"PENGUINS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"penguin\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_penguins.py","file_name":"_penguins.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"299662383","text":"import datetime\nimport _thread\nimport time\n\nfrom rx import Observable\nfrom rx import operators as ops\nfrom rx.scheduler import EventLoopScheduler\nfrom smart_home.BlindAction import BlindAction, Blind\nfrom relay import GpioClient\nfrom threading import Timer\n\nimport schedule\n\n\nclass BlindsService(object):\n def __init__(self):\n self.__gpioClient = GpioClient.GpioClient()\n self.__buttonState = {}\n self.__blindUp = {}\n self.__blindUpTimer = {}\n self.__blockTimer = None\n self.__scheduler = EventLoopScheduler()\n self.__relayActiveActions = {\n BlindAction.Blind1Up: self.__gpioClient.blind1UpStart,\n BlindAction.Blind2Up: self.__gpioClient.blind2UpStart,\n BlindAction.Blind3Up: self.__gpioClient.blind3UpStart,\n BlindAction.Blind4Up: self.__gpioClient.blind4UpStart,\n BlindAction.Blind5Up: self.__gpioClient.blind5UpStart,\n BlindAction.AllUp: self.__gpioClient.allBlindsUpStart,\n BlindAction.AllUp2: self.__gpioClient.allBlindsUpStart,\n BlindAction.Blind1Down: self.__gpioClient.blind1DownStart,\n BlindAction.Blind2Down: self.__gpioClient.blind2DownStart,\n BlindAction.Blind3Down: self.__gpioClient.blind3DownStart,\n BlindAction.Blind4Down: self.__gpioClient.blind4DownStart,\n BlindAction.Blind5Down: self.__gpioClient.blind5DownStart,\n BlindAction.AllDown: self.__gpioClient.allBlindsDownStart,\n BlindAction.AllDown2: self.__gpioClient.allBlindsDownStart\n }\n self.__relayInactiveActions = {\n BlindAction.Blind1Up: self.__gpioClient.blind1UpStop,\n BlindAction.Blind2Up: self.__gpioClient.blind2UpStop,\n BlindAction.Blind3Up: self.__gpioClient.blind3UpStop,\n BlindAction.Blind4Up: self.__gpioClient.blind4UpStop,\n BlindAction.Blind5Up: self.__gpioClient.blind5UpStop,\n BlindAction.AllUp: self.__gpioClient.allBlindsUpStop,\n BlindAction.AllUp2: self.__gpioClient.allBlindsUpStop,\n BlindAction.Blind1Down: self.__gpioClient.blind1DownStop,\n BlindAction.Blind2Down: self.__gpioClient.blind2DownStop,\n BlindAction.Blind3Down: self.__gpioClient.blind3DownStop,\n BlindAction.Blind4Down: self.__gpioClient.blind4DownStop,\n BlindAction.Blind5Down: self.__gpioClient.blind5DownStop,\n BlindAction.AllDown: self.__gpioClient.allBlindsDownStop,\n BlindAction.AllDown2: self.__gpioClient.allBlindsDownStop\n }\n\n _thread.start_new_thread(self.__configureAutomations, ())\n\n def addSwitch(self,\n observable: Observable,\n blindAction: BlindAction,\n blind: Blind):\n # Initialize states\n self.__buttonState[blindAction] = False\n self.__blindUp[blind] = False\n\n # Add a handler to the switch state\n observable.pipe(ops.observe_on(self.__scheduler)).subscribe(\n lambda active: self.__pressedHandler(blindAction, blind, active))\n\n def __configureAutomations(self):\n # Special rules\n schedule.every().friday.at(\"06:56\").do(self.__gpioClient.block)\n (schedule.every().friday.at(\"07:05\")\n .do(self.__blockAutomationWhenAllAreUp))\n\n # Never close automatically\n schedule.every().day.at(\"18:26\").do(self.__gpioClient.block)\n (schedule.every().day.at(\"18:34\")\n .do(self.__blockAutomationWhenAllAreUp))\n\n # Do not open on the weekend.\n schedule.every().saturday.at(\"06:56\").do(self.__gpioClient.block)\n (schedule.every().saturday.at(\"07:04\")\n .do(self.__blockAutomationWhenAllAreUp))\n schedule.every().sunday.at(\"06:56\").do(self.__gpioClient.block)\n (schedule.every().sunday.at(\"07:04\")\n .do(self.__blockAutomationWhenAllAreUp))\n\n # Open completly on weekdays.\n schedule.every().monday.at(\"07:06\").do(self.__allBlindsUp)\n schedule.every().tuesday.at(\"07:06\").do(self.__allBlindsUp)\n schedule.every().wednesday.at(\"07:06\").do(self.__allBlindsUp)\n schedule.every().thursday.at(\"07:06\").do(self.__allBlindsUp)\n # schedule.every().friday.at(\"07:06\").do(self.__allBlindsUp)\n\n # Open slightly on weekends.\n schedule.every().saturday.at(\"09:00\").do(self.__openSlightly)\n schedule.every().sunday.at(\"09:00\").do(self.__openSlightly)\n\n # Close at 22:00 on weekdays\n schedule.every().sunday.at(\"22:00\").do(self.__allBlindsDown)\n schedule.every().monday.at(\"22:00\").do(self.__allBlindsDown)\n schedule.every().tuesday.at(\"22:00\").do(self.__allBlindsDown)\n schedule.every().wednesday.at(\"22:00\").do(self.__allBlindsDown)\n schedule.every().thursday.at(\"22:00\").do(self.__allBlindsDown)\n\n # Close at 00:00 on weekends\n schedule.every().friday.at(\"00:00\").do(self.__allBlindsDown)\n schedule.every().saturday.at(\"00:00\").do(self.__allBlindsDown)\n\n while True:\n schedule.run_pending()\n time.sleep(1)\n\n def __openSlightly(self):\n self.__unblockBlinds()\n self.__gpioClient.allBlindsUpStart()\n\n # Virtually press the button for 0.3 seconds\n t = Timer(0.4, self.__gpioClient.allBlindsUpStop)\n t.start()\n\n self.__blockBlinds()\n\n def __allBlindsUp(self):\n self.__unblockBlinds()\n\n # Activate relay\n self.__gpioClient.allBlindsUpStart()\n time.sleep(0.5)\n self.__gpioClient.allBlindsUpStop()\n time.sleep(0.5)\n self.__gpioClient.allBlindsUpStart()\n\n # Virtually press the button for 5 seconds\n t = Timer(5.0, self.__gpioClient.allBlindsUpStop)\n t.start()\n\n # Store all blinds are up\n for group in Blind:\n self.__blindUp[group] = True\n\n self.__blockBlinds()\n\n def __allBlindsDown(self):\n self.__unblockBlinds()\n\n # Store all blinds are down\n for group in Blind:\n self.__blindUp[group] = False\n\n # Activate relay\n self.__gpioClient.allBlindsDownStart()\n time.sleep(0.5)\n self.__gpioClient.allBlindsDownStop()\n time.sleep(0.5)\n self.__gpioClient.allBlindsDownStart()\n\n # Virtually press the button for 5 seconds\n t = Timer(5.0, self.__gpioClient.allBlindsDownStop)\n t.start()\n\n def __pressedHandler(\n self,\n blindAction: BlindAction,\n blind: Blind,\n active: bool):\n # Button State did not change ... skipping\n if self.__buttonState[blindAction] == active:\n return\n\n # Button State changed ... save it\n self.__buttonState[blindAction] = active\n\n # Button is pressed\n if active:\n self.__unblockBlinds()\n\n # Activate relay\n self.__handleRelayActive(blindAction, blind)\n\n # Button is released\n else:\n # Deactivate relay\n self.__handleRelayInactive(blindAction, blind)\n\n self.__blockBlinds()\n\n def __blockBlinds(self):\n # Block Wind/Time automation when all blinds are up\n # Dispose existing timer\n if self.__blockTimer is not None:\n self.__blockTimer.cancel()\n\n # Block the automation after 70 seconds\n self.__blockTimer = Timer(70.0, self.__blockAutomationWhenAllAreUp)\n self.__blockTimer.start()\n\n def __unblockBlinds(self):\n # Dispose existing timer\n if self.__blockTimer is not None:\n self.__blockTimer.cancel()\n\n # Unblock blinds\n self.__gpioClient.unblock()\n time.sleep(0.1)\n\n def __handleRelayActive(self, blindAction: BlindAction, blind: Blind):\n # Forward the signal to the GPIO Client\n self.__relayActiveActions[blindAction]()\n\n # Store the timestamp when the up signal was initiated\n # to detect if the blind is all the way up\n if blindAction in (BlindAction.Blind1Up,\n BlindAction.Blind2Up,\n BlindAction.Blind3Up,\n BlindAction.Blind4Up,\n BlindAction.Blind5Up,\n BlindAction.AllUp,\n BlindAction.AllUp2):\n self.__blindUpTimer[blind] = datetime.datetime.now()\n\n def __handleRelayInactive(self, blindAction: BlindAction, blind: Blind):\n # Forward the signal to the GPIO Client\n self.__relayInactiveActions[blindAction]()\n\n # If the up signal was sent for more than 2 seconds the blind is up\n if blindAction in (BlindAction.Blind1Up,\n BlindAction.Blind2Up,\n BlindAction.Blind3Up,\n BlindAction.Blind4Up,\n BlindAction.Blind5Up,\n BlindAction.AllUp,\n BlindAction.AllUp2):\n blindUp: bool = (datetime.datetime.now() -\n self.__blindUpTimer[blind]).total_seconds() > 2\n\n self.__blindUp[blind] = blindUp\n\n # Change all values in case the group all is triggered\n if (blindAction == BlindAction.AllUp or\n blindAction == BlindAction.AllUp2):\n for group in Blind:\n self.__blindUp[group] = blindUp\n\n # Store that not all blinds are at top\n else:\n self.__blindUp[blind] = False\n\n # Change all values in case the group all is triggered\n if (blindAction == BlindAction.AllDown or\n blindAction == BlindAction.AllDown2):\n for group in Blind:\n self.__blindUp[group] = False\n\n def __blockAutomationWhenAllAreUp(self):\n # Ensure all 5 blinds are registered\n if Blind.Blind1 not in self.__blindUp:\n return\n if Blind.Blind2 not in self.__blindUp:\n return\n if Blind.Blind3 not in self.__blindUp:\n return\n if Blind.Blind4 not in self.__blindUp:\n return\n if Blind.Blind5 not in self.__blindUp:\n return\n\n # Ensure all 5 blinds are up\n if not self.__blindUp[Blind.Blind1]:\n return\n if not self.__blindUp[Blind.Blind2]:\n return\n if not self.__blindUp[Blind.Blind3]:\n return\n if not self.__blindUp[Blind.Blind4]:\n return\n if not self.__blindUp[Blind.Blind5]:\n return\n\n # All blinds are up\n # Block the automation\n self.__gpioClient.block()\n","sub_path":"src/smart_home/BlindsService.py","file_name":"BlindsService.py","file_ext":"py","file_size_in_byte":10677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"426870678","text":"import numpy as np\nimport math\nfrom sympy import solve, Symbol, latex, simplify, symbols, Matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\n# Symbolically find fixpts\nalpha, beta, S, I, N = symbols('alpha beta S I N')\ndSdt = -alpha*S*I/(I+S) + beta*I\ndIdt = alpha*S*I/(I+S) - beta*I\ndIdt_simple = alpha*(N-I)*I/N - beta*I\nsol = solve([dSdt,dIdt],[S,I])\nsol_2 = solve(dIdt_simple, I)\nprint(sol)\nprint(sol_2)\n\n# Bio relevant fp\nsol_bio = sol[1]\nprint(sol_bio)\n\n# Get Jacobian\nX = Matrix([S, I])\nY = Matrix([dSdt, dIdt])\nJ = Y.jacobian(X)\n\n# Get eigs\neigs = list(J.eigenvals().keys())\nprint('eigs' + str(eigs))\n\n# Linear dependence in eqts, use relevant eig..\nprint('eigs2' + str(simplify(eigs[0].subs([(S,sol_bio[0]),(I,sol_bio[1])]))))\n\n\nprint()\n\n\n# Print for latex\n#for j in range(len(sol)):\n #print('(S^*_%i,I^*_%i)&='%(j+1,j+1) + str(latex(sol[j])) + '\\\\\\\\')\n# print(sol[j])\n","sub_path":"2_a.py","file_name":"2_a.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"226911369","text":"#!/usr/bin/env python\n\n'''\n脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它,就这么简单\n\n#!/usr/bin/Python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;\n#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。\n#!/usr/bin/python相当于写死了python路径;\n#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法\n'''\n\n#show me the code(python version)\n\n#No.000 图片右上角加数字\n\n#2017-01-11 Rae Zhang\n\nimport string\nimport PIL\nfrom PIL import ImageFont,ImageDraw,Image\nimport random\n\n#set a random number\nimgNum=str(\"惊呆了\")\n\n#Read image\nim_file=\"/home/mingrui/图片/惊呆了\"\nim=Image.open(im_file)\nw,h=im.size\nwDraw=0.4*w\nhDraw=0.7*h\n\n#Draw image\n\nfont=ImageFont.truetype('SIMYOU',400)\n#设置字体及大小。字体文件位置/home/mingrui/下载/xmind-8-linux/fonts\ndraw=ImageDraw.Draw(im)\ndraw.text((wDraw,hDraw),imgNum,font=font,fill=(200,200,200))\n\n#save image\nim.save('惊呆了.jpg','jpeg')\n#注意jpg格式的全称是jpeg(第二个参数)\n\n\n","sub_path":"0000/000.py","file_name":"000.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"396253790","text":"# Copyright © 2019 Province of British Columbia\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\"\"\"This module holds data for amendment, renewal statement court order information.\"\"\"\nfrom __future__ import annotations\n\nfrom .utils import format_ts, ts_from_date_iso_format\nfrom .db import db\n\n\nclass CourtOrder(db.Model): # pylint: disable=too-many-instance-attributes\n \"\"\"This class manages all of the amendment, renewal statement court order information.\"\"\"\n\n __tablename__ = 'court_orders'\n\n id = db.Column('id', db.Integer, db.Sequence('court_order_id_seq'), primary_key=True)\n order_date = db.Column('order_date', db.DateTime, nullable=False)\n court_name = db.Column('court_name', db.String(256), nullable=False)\n court_registry = db.Column('court_registry', db.String(64), nullable=False)\n file_number = db.Column('file_number', db.String(20), nullable=False)\n effect_of_order = db.Column('effect_of_order', db.String(512), nullable=True)\n\n # parent keys\n registration_id = db.Column('registration_id', db.Integer, db.ForeignKey('registrations.id'), nullable=False,\n index=True)\n\n # Relationships - Registration\n registration = db.relationship('Registration', foreign_keys=[registration_id],\n cascade='all, delete', uselist=False)\n\n @property\n def json(self) -> dict:\n \"\"\"Return the court_order as a json object.\"\"\"\n court_order = {\n 'courtName': self.court_name,\n 'courtRegistry': self.court_registry,\n 'fileNumber': self.file_number,\n 'orderDate': format_ts(self.order_date)\n }\n if self.effect_of_order:\n court_order['effectOfOrder'] = self.effect_of_order\n\n return court_order\n\n @classmethod\n def find_by_id(cls, court_order_id: int = None):\n \"\"\"Return an expiry object by expiry ID.\"\"\"\n expiry = None\n if court_order_id:\n expiry = cls.query.get(court_order_id)\n\n return expiry\n\n @classmethod\n def find_by_registration_id(cls, registration_id: int = None):\n \"\"\"Return a list of expiry objects by registration number.\"\"\"\n expiry = None\n if registration_id:\n expiry = cls.query.filter(CourtOrder.registration_id == registration_id).one_or_none()\n\n return expiry\n\n @staticmethod\n def create_from_json(json_data, registration_id: int = None):\n \"\"\"Create a court order object from a json schema object: map json to db.\"\"\"\n court_order = CourtOrder()\n if registration_id:\n court_order.registration_id = registration_id\n\n court_order.court_name = json_data['courtName']\n court_order.court_registry = json_data['courtRegistry']\n court_order.file_number = json_data['fileNumber']\n court_order.order_date = ts_from_date_iso_format(json_data['orderDate'])\n if 'effectOfOrder' in json_data:\n court_order.effect_of_order = json_data['effectOfOrder']\n\n return court_order\n","sub_path":"ppr-api/src/ppr_api/models/court_order.py","file_name":"court_order.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"563803204","text":"# Copyright 2017 Telstra Open Source\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport time\nimport json\nfrom kafka import KafkaProducer\n\nfrom logger import get_logger\n\nimport config\n\nproducer = KafkaProducer(bootstrap_servers=config.KAFKA_BOOTSTRAP_SERVERS)\nlogger = get_logger()\n\n\ndef get_timestamp():\n return int(round(time.time() * 1000))\n\n\nclass Flow(object):\n def to_json(self):\n return json.dumps(\n self, default=lambda o: o.__dict__, sort_keys=False, indent=4)\n\n\ndef build_ingress_flow(path_nodes, src_switch, src_port, src_vlan,\n bandwidth, transit_vlan, flow_id, output_action,\n cookie, meter_id):\n output_port = None\n\n for path_node in path_nodes:\n if path_node['switch_id'] == src_switch:\n output_port = int(path_node['port_no'])\n\n if not output_port:\n raise ValueError('Output port was not found for ingress flow rule',\n \"path={}\".format(path_nodes))\n\n flow = Flow()\n flow.command = \"install_ingress_flow\"\n flow.transaction_id = 0\n flow.flowid = flow_id\n flow.cookie = cookie\n flow.switch_id = src_switch\n flow.input_port = src_port\n flow.output_port = output_port\n flow.input_vlan_id = src_vlan\n flow.transit_vlan_id = transit_vlan\n flow.output_vlan_type = output_action\n flow.bandwidth = bandwidth\n flow.meter_id = meter_id\n\n return flow\n\n\ndef build_egress_flow(path_nodes, dst_switch, dst_port, dst_vlan,\n transit_vlan, flow_id, output_action, cookie):\n input_port = None\n\n for path_node in path_nodes:\n if path_node['switch_id'] == dst_switch:\n input_port = int(path_node['port_no'])\n\n if not input_port:\n raise ValueError('Input port was not found for egress flow rule',\n \"path={}\".format(path_nodes))\n\n flow = Flow()\n flow.command = \"install_egress_flow\"\n flow.transaction_id = 0\n flow.flowid = flow_id\n flow.cookie = cookie\n flow.switch_id = dst_switch\n flow.input_port = input_port\n flow.output_port = dst_port\n flow.transit_vlan_id = transit_vlan\n flow.output_vlan_id = dst_vlan\n flow.output_vlan_type = output_action\n\n return flow\n\n\ndef build_intermediate_flows(switch, match, action, vlan, flow_id, cookie):\n # output action is always NONE for transit vlan id\n\n flow = Flow()\n flow.command = \"install_transit_flow\"\n flow.transaction_id = 0\n flow.flowid = flow_id\n flow.cookie = cookie\n flow.switch_id = switch\n flow.input_port = match\n flow.output_port = action\n flow.transit_vlan_id = vlan\n\n return flow\n\n\ndef build_one_switch_flow(switch, src_port, src_vlan, dst_port, dst_vlan,\n bandwidth, flow_id, output_action, cookie,\n meter_id):\n flow = Flow()\n flow.command = \"install_one_switch_flow\"\n flow.transaction_id = 0\n flow.flowid = flow_id\n flow.cookie = cookie\n flow.switch_id = switch\n flow.input_port = src_port\n flow.output_port = dst_port\n flow.input_vlan_id = src_vlan\n flow.output_vlan_id = dst_vlan\n flow.output_vlan_type = output_action\n flow.bandwidth = bandwidth\n flow.meter_id = meter_id\n\n return flow\n\n\ndef build_delete_flow(switch, flow_id, cookie, meter_id=0):\n flow = Flow()\n flow.command = \"delete_flow\"\n flow.transaction_id = 0\n flow.flowid = flow_id\n flow.cookie = cookie\n flow.switch_id = switch\n flow.meter_id = meter_id\n\n return flow\n\n\nclass Message(object):\n def to_json(self):\n return json.dumps(\n self, default=lambda o: o.__dict__, sort_keys=False, indent=4)\n\n\ndef send_message(payload, correlation_id, message_type, destination=\"WFM\"):\n message = Message()\n message.payload = payload\n message.type = message_type\n message.destination = destination\n message.timestamp = get_timestamp()\n message.correlation_id = correlation_id\n kafka_message = b'{}'.format(message.to_json())\n logger.debug('Send message: topic=%s, message=%s', config.KAFKA_TOPIC,\n kafka_message)\n message_result = producer.send(config.KAFKA_TOPIC, kafka_message)\n message_result.get(timeout=5)\n\n\ndef send_error_message(correlation_id, error_type, error_message,\n error_description, destination=\"WFM\"):\n data = {\"error-type\": error_type,\n \"error-message\": error_message,\n \"error-description\": error_description}\n send_message(data, correlation_id, \"ERROR\", destination)\n\n\ndef send_install_commands(flow_rules, correlation_id):\n for flow_rule in flow_rules:\n send_message(flow_rule, correlation_id, \"COMMAND\")\n\n\ndef send_delete_commands(nodes, flow_id, correlation_id, cookie):\n for node in nodes:\n data = build_delete_flow(str(node['switch_id']), str(flow_id), cookie)\n send_message(data, correlation_id, \"COMMAND\")\n","sub_path":"services/topology-engine/queue-engine/topologylistener/message_utils.py","file_name":"message_utils.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"354776629","text":"from typing import List\n\n\nclass Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return sets(nums)\n # return sort(nums)\n\n\ndef sets(nums: List[int]) -> bool:\n # 136 ms\t19.2 MB\n if len(nums) <= 1:\n return False\n\n unique = set()\n for _, num in enumerate(nums):\n if num in unique:\n return True\n unique.add(num)\n return False\n\n\ndef sort(nums: List[int]) -> bool:\n # 124 ms\t19.1 MB\n length = len(nums)\n if length <= 1:\n return False\n\n nums = sorted(nums)\n prev = nums[0]\n for i in range(1, length):\n if prev == nums[i]:\n return True\n prev = nums[i]\n return False\n","sub_path":"python/217.py","file_name":"217.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"533553858","text":"'''HW4 Part D1\n Author: Bianca Yang\n This module uses the draw_square function to draw four different colored\n squares in the corners of an 800x800 canvas.'''\n \nfrom Tkinter import * \n\ndef draw_square(canvas, color, size, center):\n '''Draws a square of the given size and color on the given canvas at\n the given coordinates.'''\n corner1 = (center[0]-size/2, center[1]-size/2)\n corner2 = (center[0]+size/2, center[1]+size/2)\n canvas.create_rectangle(corner1[0], corner1[1], corner2[0], \\\n corner2[1], fill=color, outline=color)\n\n if __name__ == '__main__':\n root = Tk()\n root.geometry('800x800')\n c = Canvas(root, width=800, height=800)\n c.pack()\n draw_square(c, 'red', 100, (50, 50))\n draw_square(c, 'blue', 100, (50, 750))\n draw_square(c, 'green', 100, (750, 50))\n draw_square(c, 'yellow', 100, (750, 750)) \n root.mainloop()\n","sub_path":"lab4_d2.py","file_name":"lab4_d2.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"82389613","text":"import numpy as np\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\nimport SpectralAnalysis \n\nimport base\nimport simple_indices.RSI\nimport simple_indices.KD\nimport simple_indices.MACD\n\nimport validate.validate\nimport strategy.KD_simple\nimport strategy.MACD_simple\n\nimport argparse\nimport matplotlib.transforms as transforms\n\nparser = argparse.ArgumentParser(description='Simple analysis of a given stock tick symbol.')\nparser.add_argument('--symbol', type=str, help=\"Symbol of the stock\", required=True) \nparser.add_argument('--database', type=str, help=\"Folder name of the database (in the folder `database`)\", required=True) \nparser.add_argument('--window', type=int, help=\"Window in days\", default=365*3-1) \nparser.add_argument('--begin', type=str, help=\"Date of begin\", default=\"\") \nparser.add_argument('--end', type=str, help=\"Date of end\", default=base.d2s(base.today00am())) \nargs = parser.parse_args()\n\ntarget_ticker = args.symbol\ndatabase = \"database/%s\" % args.database\n\nwindow_days = args.window\n\ninput_file = \"%s/%s.csv\" % (database, target_ticker)\n\nprint(\"Target ticker: %s\" % (target_ticker,))\n\n\ndf = pd.read_csv(input_file)\n\nend_date = base.s2d(args.end)\n\nif args.begin == \"\":\n print(\"Use --window\")\n beg_date = end_date - timedelta(days=window_days)\nelse:\n print(\"Use --begin\")\n beg_date = base.s2d(args.begin)\n\n\nprint(\"Selection beg date: %s\" % (base.d2s(beg_date),))\nprint(\"Selection end date: %s\" % (base.d2s(end_date),))\n\ndf = df.loc[(df[\"Date\"] >= base.d2s(beg_date)) & (df[\"Date\"] <= base.d2s(end_date))]\n\nlow_prices = df['Low'].to_numpy()\nhigh_prices = df['High'].to_numpy()\nclose_prices = df['Close'].to_numpy()\n\ndates = df['Date'].to_numpy()\n\ntimestamps = np.array([base.s2d(dates[i]).timestamp() for i in range(len(dates))])\n\nrsi = simple_indices.RSI.calRSI(close_prices, 14)\nK, D = simple_indices.KD.calKD(close_prices, high_prices, low_prices)\n\nMACD, SIG, EMA_fast, EMA_slow = simple_indices.MACD.calMACD(close_prices, w=2)\n\n#strategy = strategy.KD_simple.strategy_KD_simple()\nstrategy = strategy.MACD_simple.strategy_MACD_simple()\nprofit, transactions = validate.validate.validate_single_share(timestamps, close_prices, high_prices, low_prices, 60, strategy)\n\nprint(\"Profit: %.2f\" % (profit, ))\n\ninterp_timestamps, interp_dates = base.fill_date(beg_date, end_date)\n\nif len(interp_dates) % 2 != 0:\n interp_dates = interp_dates[1:]\n interp_timestamps = interp_timestamps[1:]\n\ninterp_close_prices = base.fill_data(interp_timestamps, timestamps, close_prices)\ninterp_low_prices = base.fill_data(interp_timestamps, timestamps, low_prices)\ninterp_high_prices = base.fill_data(interp_timestamps, timestamps, high_prices)\ninterp_rsi = base.fill_data(interp_timestamps, timestamps, rsi)\ninterp_K = base.fill_data(interp_timestamps, timestamps, K)\ninterp_D = base.fill_data(interp_timestamps, timestamps, D)\n\n\nif np.any(np.isnan(interp_close_prices)):\n raise Exception()\n\n# trend\n\nprice_ma = base.mavg(interp_close_prices, 91, method=\"center\") \nprices_anomaly = interp_close_prices - price_ma\ncoe = np.polyfit(interp_timestamps, prices_anomaly, deg=1)\nprices_detrended = prices_anomaly - (interp_timestamps * coe[0] + coe[1])\n\nvolatility = base.volatility(prices_detrended, 11, method=\"center\")\nvolatility_max = base.volatility_max(prices_detrended, 11, method=\"center\")\n\n# spectral\n\nlowpass_days = 30.0\n\ntruncate_wavenumber = int(np.ceil(len(prices_detrended)/lowpass_days))\n\ndata_filtered, pred, _, _ = SpectralAnalysis.DFT_filter(\n prices_detrended,\n truncate_wavenumber = truncate_wavenumber,\n)\n\nimport prediction.cyclic_1 as p_cyc1\n\n# predict\npred_N = 60\n\npred_dates = [ interp_dates[-1] + timedelta(days=i+1) for i in range(pred_N) ]\n\nprices_predicted, uncertainty = p_cyc1.predict(data_filtered, pred_N, n_per_cycle=60)\n\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as transforms\nimport matplotlib.dates as mdates\n\nplt.rcParams[\"date.autoformatter.month\"] = \"%y-%m-%d\"\n\nfig, ax = plt.subplots(5, 1, sharex=True, figsize=(12, 8))\n\nt = interp_dates\nt_raw = np.array([datetime.fromtimestamp(timestamps[i]) for i in range(len(timestamps))])\n\ntrans = transforms.blended_transform_factory(ax[0].transData, ax[0].transAxes)\nfor i in range(len(transactions) // 2):\n \n _buy = transactions[i*2]\n _sell = transactions[i*2+1]\n _profit = _sell.amount - _buy.amount\n\n if _profit > 0:\n color = \"green\"\n else:\n color = \"red\"\n\n ax[0].fill_between([datetime.fromtimestamp(_buy.time), datetime.fromtimestamp(_sell.time)], [0, 0], [1, 1], facecolor=color, alpha=0.2, transform=trans)\n\nfor transaction in transactions:\n marker = \"o\" if transaction.action == \"buy\" else \"x\"\n ax[0].scatter(datetime.fromtimestamp(transaction.time), transaction.amount, s=20, edgecolors=\"k\", facecolor=\"k\", marker=marker, zorder=99)\n #print(datetime.fromtimestamp(transaction.time), \": \", transaction.amount)\n\n\n\n\nax[0].fill_between(t, interp_low_prices, interp_high_prices, facecolor=\"#aaaaaa\", )\nax[0].plot(t, interp_close_prices, color=\"black\", linewidth=1)\nax[0].plot(t, price_ma, color=\"blue\", linestyle=\"dashed\", linewidth=1)\n\n\n\n#ax[1].fill_between(t, fluct_min, fluct_max, facecolor=\"#dddd55\", )\nax[1].fill_between(t, - volatility_max, volatility_max, facecolor=\"#dddd55\", )\nax[1].fill_between(t, - volatility, volatility, facecolor=\"#aaaa55\", )\nax[1].fill_between(t, interp_low_prices - price_ma, interp_high_prices - price_ma, facecolor=\"#aaaaaa\", )\nax[1].plot(t, prices_detrended, color=\"black\", linewidth=1)\nax[1].plot(t, data_filtered, color=\"red\", linewidth=1)\nax[1].plot(t, interp_timestamps * coe[0] + coe[1], color=\"green\", linewidth=1)\n\n\ntrans = transforms.blended_transform_factory(ax[2].transAxes, ax[2].transData)\nax[2].fill_between([0, 1], [30, 30], [70, 70], facecolor=\"#ffff88\", alpha=0.8, transform=trans)\nax[2].plot(t, interp_rsi, color=\"black\", linewidth=1)\n\nax[3].plot(t, interp_K, color=\"blue\", markersize=10, linewidth=1)\nax[3].plot(t, interp_D, color=\"red\", linewidth=1)\n\n\n\nDIF = MACD - SIG\ntwin = ax[4].twinx()\n#twin.bar(t_raw[pos_mask], MACD[pos_mask], color=\"green\", alpha=0.5)\n#twin.bar(t_raw[neg_mask], MACD[neg_mask], color=\"red\", alpha=0.5)\ntwin.fill_between(t_raw, DIF, where = DIF > 0, color=\"green\", alpha=0.5)\ntwin.fill_between(t_raw, DIF, where = DIF <= 0, color=\"red\", alpha=0.5)\n\n\nax[4].plot(t_raw, MACD, color=\"red\", linewidth=1)\nax[4].plot(t_raw, SIG, color=\"blue\", linewidth=1)\n#twin.plot(t_raw, EMA_fast - EMA_slow, color=\"gray\", linewidth=1)\n\n\n\nax[0].set_title(\"Ticker : %s (%s ~ %s)\" % (target_ticker, base.d2s(beg_date), base.d2s(end_date)))\nax[1].set_title(\"Detrended\")\nax[2].set_title(\"RSI\")\nax[3].set_title(\"KD\")\nax[4].set_title(\"MACD\")\n\n\nax[1].plot(pred_dates, prices_predicted, color=\"blue\", linestyle=\"dashed\", linewidth=1)\n\ntime_ticks = []\ntime_newyear_ticks = []\nfor y in range(beg_date.year, end_date.year + 1):\n\n time_ticks.extend([\n datetime(y, 1, 1),\n datetime(y, 4, 1),\n datetime(y, 7, 1),\n datetime(y, 10, 1),\n ])\n\n time_newyear_ticks.append(datetime(y, 1, 1))\n\n\nmyFmt = mdates.DateFormatter(\"%m/%d\")\nfor _ax in ax:\n _ax.set_xticks(time_ticks)\n _ax.xaxis.set_major_formatter(myFmt)\n _ax.grid(alpha=0.5)\n _ax.set_xlim([beg_date, pred_dates[-1] + timedelta(days=10)])\n _ax.set_xlabel(\"Date\")\n _ax.set_ylabel(\"Price\")\n\n trans = transforms.blended_transform_factory(_ax.transData, _ax.transAxes)\n for time_newyear_tick in time_newyear_ticks:\n _ax.text(time_newyear_tick, 0.95, \"%d\" % (time_newyear_tick.year,) , size=10, va=\"top\", ha=\"center\", transform=trans)\n\n\nplt.show()\n","sub_path":"lab/analysis_one_ticker.py","file_name":"analysis_one_ticker.py","file_ext":"py","file_size_in_byte":7645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"421869673","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Bot config\nBotAPIKey = 'xxx' # API Keythat you get from @BotFather\ntg = xxx # Your id, you can get it by sending command /id to bot @TONTgIDBot\nserverbotpath = '/home//serverbot' # User folder with this bot.\nserverbotpathdb = '/home//serverbot/db' # User folder with bot database. \nsrvping = '1.1.1.1' # Ping test server\ntraceroutetest = '1.1.1.1' # Traceroute test server\n\n# Server config \nmemloadalarm = 90 # RAM Utilization alarm starts at\npingcalarm = 50 # When ping will be more than X ms, you will get alarm.\ncpuutilalarm = 99 # CPU Utilization alarm starts at\nrepeattimealarmsrv = [5,15,25,30,60,90,120,180,320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920] # Notify every x second about high CPU, RAM load and ping\ncfgAlertsNotificationsRam = 1 # RAM Monitoring + history\ncfgAlertsNotificationsCPU = 1 # CPU Monitoring + history\ncfgAlertsNotificationsping = 1 # RAM, Ping & CPU Monitopring\ncfgmonitoringnetwork = 1 # Netowrk Monitopring\ncfgmonitoringdiskio = 1 # Disk I/O Monitopring\n\n# Near config\nnearnetwork = 'betanet' # Choose your network - betanet/testnet/mainnet/guildnet\npoolname = 'xxx' # Your pool name\nsyncalarm = 50 # Blocks diff for alarm\nblocksdiff = 10 # Blocks produced VS expected alarm\nrepeattimealarmnode = [5,15,25,30,60,90,120,180,320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920] # Notify every x second about validator node issues\ncfgAlertsNotificationsNode = 1 # Node pid monitoring\ncfgAlertsNotificationsSync = 1 # Sync status monitoring\ncfgAlertsNotificationsBlocks = 1 # Blocks produced VS expected monitoring\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"475627177","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File : test_collection.py\n@Time : 2021/6/20 9:06\n\"\"\"\nimport pytest\nfrom common.mainTest import BaseRequests as R\nfrom tests.test_project_01 import *\n\n\n# from config.setting import *\n\n\n@pytest.mark.datafile(yaml_dir + 'test_demo.yaml')\ndef test_(parameters: dict):\n url = TEST_HOST + parameters.pop(\"url\")\n method = parameters.pop(\"method\")\n case_desc = parameters.pop(\"case_desc\")\n variables = parameters.pop('jsonpath_exp')\n verification = parameters.pop('verification')\n R.send_request(method, url, case_desc=case_desc, verification=verification, jsonpath_exp=variables, **parameters)\n\n\nif __name__ == '__main__':\n pytest.main(['-s', '-k', 'test_.py'])\n","sub_path":"apitest/tests/test_project_01/test/test_.py","file_name":"test_.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"644861801","text":"from terminaltables import SingleTable\n\n\nclass Border:\n\tdef __init__(self, w, h, title='Game board'):\n\t\tself.w = w\n\t\tself.h = h\n\t\tself.title = title\n\t\tself.m = [['']*(w+1) for i in range(h+1)]\n\t\tself.createIndexies()\n\t\n\tdef createIndexies(self):\n\t\tfor i in range(self.w):\n\t\t\tself.m[0][1+i] = chr(ord('A')+i)\n\t\t\tself.m[1+i][0] = i + 1\n\t\n\tdef draw(self):\n\t\tt = SingleTable(self.m, self.title)\n\t\tt.outer_border = True\n\t\tt.inner_row_border = True\n\t\tt.inner_column_border = True\n\t\tprint(t.table)\n\t\n\tdef set(self, cs, val):\n\t\tcs = cs.upper()\n\t\tx = ord(cs[0]) - ord('A') + 1\n\t\ty = int(cs[1:])\n\t\tself.m[y][x] = val\n\t\t\n\ndef main():\n\ttd = [\n\t[' ', 'A', 'B', 'C'],\n\t['1', 'X', ' ', 'O'],\n\t['2', 'O', 'X', ' '],\n\t['3', 'O', ' ', 'X']\n\t]\n\t\n\tt = SingleTable(td, 'GameBoard')\n\tt.outer_border = False\n\tt.inner_row_border = True\n\tt.inner_column_border = True\n\t\n\tprint(t.table)\n\t\n\tb = Border(5, 5)\n\tb.draw()\n\tb.set('a1', 'x')\n\tb.set('d4', 'o')\n\tb.draw()\n\t\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"archive/06.06.19 4:10/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"197184072","text":"slownik = {\n \"jeden\": \"I\",\n \"dwa\": \"II\",\n \"trzy\": \"III\",\n \"cztery\": \"IV\",\n \"piec\": \"V\",\n \"szesc\": \"VI\",\n \"siedem\": \"VII\",\n \"osiem\": \"VIII\",\n \"dziewiec\": \"IX\",\n \"dziesiec\": \"X\"\n}\n \nfor x, y in slownik.items():\n print(x, y)","sub_path":"zad15.py","file_name":"zad15.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"399234251","text":"def judge_anagram(str1 , str2):\n list_str1 = [char for char in str1]\n list_str2 = [char for char in str2]\n '''\n list_str1.sort\n list_str2.sort\n print(list_str1)\n print(list_str2)\n '''\n if sorted(list_str1) == sorted(list_str2):\n return True\n else:\n return False\n\nif __name__ == \"__main__\":\n print(judge_anagram(\"hoge\",\"geho\"))\n\n","sub_path":"Chapter1/module/judge_anagram.py","file_name":"judge_anagram.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"101711788","text":"from django.urls import path\nfrom curriculo import views\n\napp_name = 'curriculo'\n\nurlpatterns = [\n path('/', views.curso, name=\"curso\"),\n path('/disciplina//', views.disciplina, name=\"disciplina\")\n\n\n\n\n] ","sub_path":"curriculo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"469448036","text":"class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n n = len(nums)\n res = [0] * n\n left, right = 0, n - 1\n\n while (right - left >= 0):\n if (abs(nums[left]) > abs(nums[right])):\n res[right - left] = nums[left] ** 2\n left += 1\n else:\n res[right - left] = nums[right] ** 2\n right -= 1\n\n return res\n\n # n = len(nums)\n\n # res = []\n\n # iOfNumClosestToZero = 0\n\n # i = 1\n # while (i < n and abs(nums[i]) <= abs(nums[i-1])):\n # iOfNumClosestToZero = i\n # i += 1\n\n # res.append(nums[iOfNumClosestToZero] ** 2)\n # left = iOfNumClosestToZero - 1\n # right = iOfNumClosestToZero + 1\n\n # for _ in range(n - 1):\n # if (left < 0):\n # res.append(nums[right] ** 2)\n # right += 1\n # elif (right > n - 1):\n # res.append(nums[left] ** 2)\n # left -= 1\n # else:\n # if (abs(nums[left]) > abs(nums[right])):\n # res.append(nums[right] ** 2)\n # right += 1\n # else:\n # res.append(nums[left] ** 2)\n # left -= 1\n\n # return res\n","sub_path":"LeetCode/977. Squares of a Sorted Array.py","file_name":"977. Squares of a Sorted Array.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"52087363","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.views import View\nfrom django.http import HttpResponse, Http404, JsonResponse\nfrom leave_application.forms import (FacultyLeaveForm,\n StaffLeaveForm,\n StudentLeaveForm,)\n\nfrom user_app.models import Administration, Replacement, ExtraInfo\nfrom leave_application.models import (Leave, CurrentLeaveRequest,\n LeaveRequest, LeavesCount,\n LeaveMigration,)\nfrom django.contrib.auth.models import User\n\nfrom eis.views import render_to_pdf\n\nfrom leave_application.helpers import FormData, get_object_or_none, count_work_days\nfrom django.db.models import Q\nfrom django.db import transaction\nimport datetime\nimport json\nfrom django.contrib.auth.decorators import login_required\n\n\nclass LeaveView(View):\n\n def get(self, request):\n cake = request.GET.get('cake')\n curr_year = datetime.date.today().year\n if not cake:\n leaves_count = LeavesCount.objects.get(user=request.user, year=curr_year)\n applications = GetApplications.get_reps(request)\n message = request.GET.get('message', None)\n leave_id = request.GET.get('leave_id', None)\n form = ApplyLeave.get_form(request) if not message else None\n received_requests = GetApplications.get_count(request)\n context = {\n 'form': form,\n 'leaves_count': leaves_count,\n 'message': message,\n 'show_approve': received_requests,\n 'leave_id': leave_id\n }\n context.update(applications)\n return render(request, 'fusion/leaveModule0/leave.html', context)\n\n elif cake == 'form':\n form = ApplyLeave.get_form(request)\n leaves_count = LeavesCount.objects.get(user=request.user, year=curr_year)\n context = {\n 'form': form,\n 'leaves_count': leaves_count,\n }\n return render(request, 'fusion/leaveModule0/leaveapplicationform.html', context)\n\n elif cake == 'status':\n user_leaves = Leave.objects.filter(applicant=request.user)\n\n context = {\n 'user_leaves': user_leaves\n }\n\n return render(request, 'fusion/leaveModule0/leavestatus.html', context)\n\n elif cake == 'approve':\n context = GetApplications.get_to_approve(request)\n return render(request, 'fusion/leaveModule0/leaveapprove.html', context)\n\n elif cake == 'detail':\n pk = request.GET.get('pk')\n leave = Leave.objects.get(pk=pk)\n\n return render(request, 'fusion/leaveModule0/details.html', {'leave': leave})\n\n else:\n return HttpResponse('You can\\'t see this page.')\n\nclass ApplyLeave(View):\n \"\"\"\n A Class Based View which handles user applying for leave\n \"\"\"\n def get(self, request):\n \"\"\"\n view to handle get request to /leave/apply\n \"\"\"\n # TODO: Check if leave not rejected or accepted and leave instance belongs to user\n # TODO: Take another value as action so that action can specify edit or delete with same\n return redirect('/leave/')\n\n def post(self, request):\n \"\"\"\n view to handle post request to /leave/apply\n \"\"\"\n form = ApplyLeave.get_form(request)\n if form.is_valid():\n type_of_leave = form.cleaned_data.get('type_of_leave', 'casual')\n acad_done = False if form.cleaned_data.get('acad_rep', False) else True\n admin_done = False if form.cleaned_data.get('admin_rep', False) else True\n academic_replacement = get_object_or_none(User, username=form.cleaned_data.get('acad_rep'))\n administrative_replacement = get_object_or_none(User,\n username=form.cleaned_data.get('admin_rep'))\n try:\n leave_obj = Leave.objects.create(\n applicant = request.user,\n type_of_leave = type_of_leave,\n academic_replacement = academic_replacement,\n administrative_replacement = administrative_replacement,\n purpose = form.cleaned_data['purpose'],\n acad_done = acad_done,\n admin_done = admin_done,\n leave_address = form.cleaned_data.get('leave_address', ''),\n start_date = form.cleaned_data['start_date'],\n station_start_date = form.cleaned_data.get('station_start_date'),\n station_end_date = form.cleaned_data.get('station_end_date'),\n end_date = form.cleaned_data['end_date'],\n station = form.cleaned_data.get('station_leave'),\n )\n\n except Exception as e:\n return render(request,\n 'leave_application/apply_for_leave.html',\n {'form': form, 'message': 'Failed'})\n\n return redirect('/leave/?message=success&leave_id={}'.format(leave_obj.id))\n\n else:\n context = {'form': form, 'title': 'Leave', 'action':'Apply'}\n year = datetime.date.today().year\n leaves_count = LeavesCount.objects.get(user=request.user, year=year)\n context['leaves_count'] = leaves_count\n context.update(GetApplications.get_reps(request))\n return render(request, 'fusion/leaveModule0/leave.html', context)\n\n @classmethod\n def get_user_type(cls, request):\n return request.user.extrainfo.user_type\n\n @classmethod\n def get_form(cls, request):\n\n user_type = cls.get_user_type(request)\n\n if user_type == 'faculty':\n form = cls.get_form_object(FacultyLeaveForm, request)\n elif user_type == 'staff':\n form = cls.get_form_object(StaffLeaveForm, request)\n else:\n form = cls.get_form_object(StudentLeaveForm, request)\n\n return form\n\n @classmethod\n def get_form_object(ccls, cls, request):\n\n if request.method == 'GET':\n return cls(initial={}, user=request.user)\n else:\n return cls(request.POST, user=request.user)\n\n\nclass ProcessRequest(View):\n\n def post(self, request, id):\n leave_request = get_object_or_404(CurrentLeaveRequest, id=id)\n\n do = request.POST.get('do')\n\n response = JsonResponse({'response': 'Failed'}, status=400)\n\n rep_user = get_object_or_none(Replacement, replacee=leave_request.requested_from,\n replacement_type='administrative')\n if rep_user:\n rep_user = rep_user.replacer\n\n if request.user in [leave_request.requested_from, rep_user] \\\n and do in ['accept', 'reject', 'forward']:\n\n response = getattr(self, do)(request, leave_request) or response\n\n return response\n\n\n def accept(self, request, leave_request):\n type_of_leave = leave_request.leave.type_of_leave\n sanc_auth = leave_request.applicant.extrainfo.sanctioning_authority\n sanc_officer = leave_request.applicant.extrainfo.sanctioning_officer\n remark = request.POST.get('remark', '')\n response = JsonResponse({'response': 'ok'}, status=200)\n\n if leave_request.permission in ['academic', 'admin']:\n\n if leave_request.permission == 'academic':\n leave_request.leave.acad_done = True\n else:\n leave_request.leave.admin_done = True\n\n leave_request.leave.save()\n leave_request = self.create_leave_request(leave_request, False, accept=True, remark=remark)\n\n if leave_request.leave.replacement_confirm and leave_request.leave.status == 'processing':\n position = leave_request.applicant.extrainfo.sanctioning_authority\n next_user = ExtraInfo.objects.filter(designation=position).first().user\n CurrentLeaveRequest.objects.create(\n applicant = leave_request.applicant,\n requested_from = next_user,\n permission = 'sanc_auth',\n position = position,\n leave = leave_request.leave,\n )\n\n elif sanc_auth == sanc_officer or leave_request.permission == 'sanc_officer':\n leave_request = self.create_leave_request(leave_request, True, accept=True, remark=remark)\n leave_request.leave.status = 'accepted'\n leave_request.leave.save()\n\n elif leave_request.permission == 'sanc_auth':\n if type_of_leave in ['casual', 'restricted']:\n leave_request = self.create_leave_request(leave_request, True, accept=True, remark=remark)\n else:\n response = None\n\n return response\n\n def reject(self, request, leave_request):\n remark = request.POST.get('remark', '')\n\n type_of_leave = leave_request.leave.type_of_leave\n response = JsonResponse({'response': 'ok',}, status=200)\n sanc_auth = leave_request.applicant.extrainfo.sanctioning_authority\n sanc_officer = leave_request.applicant.extrainfo.sanctioning_officer\n\n condition = sanc_officer == sanc_auth\n\n if not leave_request.leave.replacement_confirm or leave_request.permission == 'sanc_officer' \\\n or condition:\n leave_request = self.create_leave_request(leave_request, True, accept=False, remark=remark)\n list(map(lambda x: x.delete(), leave_request.leave.cur_requests.all()))\n\n elif leave_request.permission == 'sanc_auth':\n if type_of_leave in ['casual', 'restricted']:\n leave_request = self.create_leave_request(leave_request, True, accept=False, remark=remark)\n else:\n response = None\n else:\n response = None\n return response\n\n def forward(self, request, leave_request):\n\n remark = request.POST.get('remark', '')\n type_of_leave = leave_request.leave.type_of_leave\n\n response = JsonResponse({'response': 'ok',}, status=200)\n\n if leave_request.permission == 'sanc_auth' and \\\n type_of_leave not in ['casual', 'restricted']:\n\n leave_request = self.create_leave_request(leave_request, False, accept=False, remark=remark)\n\n if leave_request.leave.status == 'processing':\n position = leave_request.applicant.extrainfo.sanctioning_officer\n\n next_user = ExtraInfo.objects.filter(designation=position).first().user\n\n CurrentLeaveRequest.objects.create(\n applicant = leave_request.applicant,\n requested_from = next_user,\n position = position,\n leave = leave_request.leave,\n permission = 'sanc_officer',\n )\n else:\n response = None\n\n return response\n\n\n\n @transaction.atomic\n def create_leave_request(self, cur_leave_request, final, accept=False, remark=''):\n if cur_leave_request.leave.type_of_leave not in ['casual', 'restricted'] and \\\n cur_leave_request.permission == 'sanc_auth':\n status = True\n else:\n status = accept\n\n leave_request = LeaveRequest.objects.create(\n leave = cur_leave_request.leave,\n applicant = cur_leave_request.applicant,\n requested_from = cur_leave_request.requested_from,\n remark = remark,\n permission = cur_leave_request.permission,\n position = cur_leave_request.position,\n status = status,\n )\n\n if not accept and final:\n cur_leave_request.leave.status = 'rejected'\n elif final:\n curr_year = datetime.date.today().year\n start_date = cur_leave_request.leave.start_date\n end_date = cur_leave_request.leave.end_date\n if curr_year == start_date.year and curr_year == end_date.year:\n count = LeavesCount.objects.get(user=cur_leave_request.applicant, year=curr_year)\n\n remain = getattr(count, cur_leave_request.leave.type_of_leave)\n required_leaves = cur_leave_request.leave.count_work_days\n\n if remain < required_leaves:\n cur_leave_request.leave.status = 'rejected'\n else:\n setattr(count, cur_leave_request.leave.type_of_leave,\n remain - required_leaves)\n count.save()\n self.create_migration(cur_leave_request.leave)\n cur_leave_request.leave.status = 'accepted'\n elif curr_year == start_date.year and end_date.year == curr_year + 1:\n final_date = datetime.date(curr_year, 12, 31)\n\n days_in_curr_year = count_work_days(start_date, final_date)\n final_date += datetime.timedelta(days=1)\n days_in_next_year = count_work_days(final_date, end_date)\n curr_count = LeavesCount.objects.get(user=cur_leave_request.applicant,\n year=start_date.year)\n next_count = LeavesCount.objects.get(user=cur_leave_request.applicant,\n year=end_date.year)\n\n curr_remaining = getattr(curr_count, cur_leave_request.leave.type_of_leave)\n next_remaining = getattr(next_count, cur_leave_request.leave.type_of_leave)\n\n if curr_remaining >= days_in_curr_year and next_remaining >= days_in_next_year:\n setattr(curr_count, cur_leave_request.leave.type_of_leave,\n curr_remaining - days_in_curr_year)\n curr_count.save()\n setattr(next_count, cur_leave_request.leave.type_of_leave,\n next_remaining - days_in_next_year)\n next_count.save()\n self.create_migration(cur_leave_request.leave)\n cur_leave_request.leave.status = 'accepted'\n else:\n cur_leave_request.leave.status = 'rejected'\n\n elif start_date.year + 1 == crr_year and end_date.year + 1 == curr_year:\n count = LeavesCount.objects.get(user=cur_leave_request.applicant, year=curr_year+1)\n\n remain = getattr(count, cur_leave_request.leave.type_of_leave)\n required_leaves = cur_leave_request.leave.count_work_days\n if remain < required_leaves:\n cur_leave_request.leave.status = 'rejected'\n else:\n setattr(count, cur_leave_request.leave.type_of_leave,\n remain - required_leaves)\n count.save()\n self.create_migration(cur_leave_request.leave)\n cur_leave_request.leave.status = 'accepted'\n\n\n cur_leave_request.leave.save()\n cur_leave_request.delete()\n return leave_request\n\n\n\n def process_student_request(self, sanc_auth, leave_request, remark, process):\n\n outcome = 'accepted' if process else 'rejected'\n new_leave_request = LeaveRequest.objects.create(\n applicant = leave_request.applicant,\n requested_from = leave_request.requested_from,\n position = leave_request.position,\n leave = leave_request.leave,\n status = process,\n remark = remark,\n )\n new_leave_request.leave.status = outcome\n new_leave_request.leave.save()\n leave_request.delete()\n return JsonResponse({'response': 'ok'}, status=200)\n\n @transaction.atomic\n def create_migration(self, leave):\n\n if leave.start_date <= datetime.date.today():\n\n if leave.applicant.extrainfo.user_type == 'faculty':\n r1 = Replacement.objects.create(\n replacee = leave.applicant,\n replacer = leave.academic_replacement,\n replacement_type = 'academic',\n )\n LeaveMigration.objects.create(\n replacee = leave.applicant,\n replacer = leave.academic_replacement,\n rep = r1,\n start_date = leave.end_date + datetime.timedelta(days=1),\n type = 'del',\n )\n\n r2 = Replacement.objects.create(\n replacee = leave.applicant,\n replacer = leave.administrative_replacement,\n replacement_type = 'administrative',\n )\n LeaveMigration.objects.create(\n replacee = leave.applicant,\n replacer = leave.administrative_replacement,\n rep = r2,\n start_date = leave.end_date + datetime.timedelta(days=1),\n type = 'del',\n )\n\n else:\n if leave.applicant.extrainfo.user_type == 'faculty':\n LeaveMigration.objects.create(\n type = 'add',\n replacee = leave.applicant,\n replacer = leave.academic_replacement,\n start_date = leave.start_date,\n end_date = leave.end_date,\n replacement_type = 'academic',\n )\n\n LeaveMigration.objects.create(\n type = 'add',\n replacee = leave.applicant,\n replacer = leave.administrative_replacement,\n start_date = leave.start_date,\n end_date = leave.end_date,\n replacement_type = 'administrative',\n )\n\n def is_problematic(self, leave):\n #TODO: Add automatic hadling of outdated or problematic leave requests\n pass\n\nclass GetApplications():\n\n @classmethod\n def get_to_approve(cls, request):\n processed_request_list = LeaveRequest.objects.filter(requested_from=request.user).order_by('-id')\n\n replacements = Replacement.objects.filter(Q(replacer=request.user)\n & Q(replacement_type='administrative'))\n reqs = CurrentLeaveRequest.objects.filter(Q(requested_from=request.user)\n & ~(Q(permission='academic')\n | Q(permission='admin')))\n request_list = [cls.should_forward(request, q_obj) for q_obj in reqs]\n for replacement in replacements:\n replacee = replacement.replacee\n reqs = CurrentLeaveRequest.objects.filter((Q(requested_from=request.user)\n | Q(requested_from=replacee))\n & ~(Q(permission='academic')\n | Q(permission='admin')))\n request_list += [cls.should_forward(request, q_obj) for q_obj in reqs]\n\n\n context = {\n 'processed_request_list': processed_request_list,\n 'request_list': request_list,\n }\n return context\n\n @classmethod\n def get_count(cls, request):\n processed_request_list_exists = LeaveRequest.objects.filter(requested_from=request.user).exists()\n\n if processed_request_list_exists:\n return True\n\n replacements = Replacement.objects.filter(Q(replacer=request.user)\n & Q(replacement_type='administrative'))\n reqs = CurrentLeaveRequest.objects.filter(Q(requested_from=request.user)\n & ~(Q(permission='academic')\n | Q(permission='admin'))).exists()\n if reqs:\n return reqs\n\n for replacement in replacements:\n replacee = replacement.replacee\n reqs = CurrentLeaveRequest.objects.filter((Q(requested_from=request.user)\n | Q(requested_from=replacee))\n & ~(Q(permission='academic')\n | Q(permission='admin'))).exists()\n\n if reqs:\n return True\n\n return False\n\n @classmethod\n def get_reps(cls, request):\n rep_requests = CurrentLeaveRequest.objects.filter(Q(requested_from=request.user) &\n (Q(permission='academic') | Q(permission='admin')))\n return {'rep_requests': rep_requests}\n\n @classmethod\n def should_forward(cls, request, query_obj):\n\n obj = FormData(request, query_obj)\n sanc_auth = query_obj.applicant.extrainfo.sanctioning_authority\n sanc_officer = query_obj.applicant.extrainfo.sanctioning_officer\n type_of_leave = query_obj.leave.type_of_leave\n\n designation = query_obj.requested_from.extrainfo.designation\n if sanc_auth == sanc_officer:\n obj.forward = False\n elif (sanc_auth == designation and type_of_leave not in ['casual', 'restricted']) \\\n and query_obj.permission not in ['academic', 'admin']:\n\n obj.forward = True\n\n else:\n obj.forward = False\n return obj\n\n\n@login_required(login_url='/accounts/login')\ndef generate_pdf(request):\n id = request.GET.get('id', None)\n if not id:\n return Http404\n\n leave = get_object_or_404(Leave, pk=id)\n\n if not leave or leave.applicant != request.user:\n return Http404\n date = datetime.date.today()\n # return render(request, 'fusion/leaveModule0/generatePDF.html', {'leave': leave, 'date': date})\n return render_to_pdf('fusion/leaveModule0/generatePDF.html', {'leave': leave, 'request': request, 'date': date})\n\n\nclass GetLeaves(View):\n\n def get(self, request):\n leave_list = Leave.objects.filter(applicant=request.user).order_by('-id')\n count = len(list(leave_list))\n return render(request, 'leave_application/get_leaves.html', {'leaves':leave_list,\n 'count':count,\n 'title':'Leave',\n 'action':'ViewLeaves'})\n","sub_path":"leave_application/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"355633745","text":"# author: ZumbiPy\r\n# E-mail: zumbipy@gmail.com\r\n\"\"\"\r\nExercício 11\r\n\"\"\"\r\n\r\n\r\ndef valida_texto(text, max, min):\r\n char_t = len(text)\r\n if char_t >= max or char_t <= min:\r\n return False\r\n else:\r\n return True\r\n","sub_path":"Capitulo_08/exercicio-11.py","file_name":"exercicio-11.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"46744872","text":"\n\nfrom xai.brain.wordbase.nouns._frippery import _FRIPPERY\n\n#calss header\nclass _FRIPPERIES(_FRIPPERY, ):\n\tdef __init__(self,): \n\t\t_FRIPPERY.__init__(self)\n\t\tself.name = \"FRIPPERIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"frippery\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_fripperies.py","file_name":"_fripperies.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"318889391","text":"\"\"\"Phrase Puzzler main program.\"\"\"\n\nimport random\nfrom typing import List\n\nfrom constants import (VOWEL_PRICE, CONSONANT_BONUS, PLAYER_ONE,\n PLAYER_TWO, CONSONANT, VOWEL, SOLVE, QUIT,\n HUMAN, HUMAN_HUMAN, HUMAN_COMPUTER, EASY, HARD,\n ALL_CONSONANTS, ALL_VOWELS,\n PRIORITY_CONSONANTS, HIDDEN)\n\nimport puzzler_functions as pf\n\n\n################################ The Game: #################################\ndef play_game(puzzle: str, puzzles: List[str], game_type: str) -> None:\n \"\"\"Play the game!\"\"\"\n\n view = make_view(puzzle)\n consonants, vowels = ALL_CONSONANTS, ALL_VOWELS\n player_one_score, player_two_score = 0, 0\n current_player = PLAYER_ONE\n\n if game_type == HUMAN_COMPUTER:\n difficulty = select_computer_difficulty()\n\n move = ''\n while not pf.is_game_over(puzzle, view, move):\n score = pf.current_player_score(player_one_score,\n player_two_score,\n current_player)\n num_occurrences = 0\n\n display_move_prompt(current_player, score, view)\n\n if pf.is_human(current_player, game_type):\n (move, guess) = human_move(score, consonants, vowels)\n else:\n (move, guess) = computer_move(view, puzzles, difficulty,\n consonants)\n\n if move == QUIT:\n print('You chose to quit the game!')\n winner = 'No winner'\n\n if move == SOLVE:\n if guess == puzzle:\n score = compute_score(puzzle, view, consonants, score)\n view = puzzle\n winner = current_player\n else:\n print(\"The solution '{}' is incorrect. Keep playing!\"\n .format(guess))\n\n else: # guess vowel or consonant\n view = update_view(puzzle, view, guess)\n num_occurrences = puzzle.count(guess)\n score = pf.calculate_score(score, num_occurrences, move)\n\n consonants = pf.erase(consonants, consonants.find(guess))\n vowels = pf.erase(vowels, vowels.find(guess))\n\n winner = current_player\n\n print(\"{} guesses {}, which occurs {} time(s) in the puzzle.\"\n .format(current_player, guess, num_occurrences))\n print(\"{}'s score is now {}.\".format(current_player, score))\n\n if current_player == PLAYER_ONE:\n player_one_score = score\n else:\n player_two_score = score\n current_player = pf.next_player(\n current_player, num_occurrences, game_type)\n\n # The game is over.\n display_outcome(winner, puzzle, game_type, player_one_score,\n player_two_score)\n\n\ndef update_view(puzzle: str, view: str, guess: str) -> str:\n \"\"\"Return a new view of puzzle: a view in which each occurrence of\n guessed_letter in puzzle is revealed.\n\n >>> update_view('apple', '^^^le', 'a')\n 'a^^le'\n >>> update_view('apple', '^^^le', 'p')\n '^pple'\n >>> update_view('apple', '^^^le', 'z')\n '^^^le'\n\n \"\"\"\n\n new_view = ''\n for index in range(len(puzzle)):\n new_view += pf.update_char_view(puzzle, view, index, guess)\n return new_view\n\n\ndef compute_score(puzzle: str, view: str, unguessed_consonants: str,\n current_score: int) -> int:\n \"\"\"Return the final score, calculated by adding\n constants.CONSONANT_BONUS points to current_score for each\n occurrence of each letter in unguessed_consonants in puzzle that\n appears as consonants.HIDDEN in view.\n\n >>> compute_score('apple pies', '^pple p^es', 'dfkpqstz', 0)\n 0\n >>> compute_score('apple pies', '^^^le ^^e^', 'dfkpqstz', 0)\n 8\n\n \"\"\"\n\n final_score = current_score\n for letter in unguessed_consonants:\n if pf.is_bonus_letter(letter, puzzle, view):\n final_score += CONSONANT_BONUS * puzzle.count(letter)\n return final_score\n\n\n########################## Game Play: Computer Moves #######################\ndef computer_move(view: str, puzzles: List[str], difficulty: str,\n consonants: str) -> (str, str):\n \"\"\"Return the computer's next move:\n (constants.SOLVE, solution-guess) or (constants.CONSONANT, letter-guess)\n\n If difficulty is constants.HARD, the computer chooses to solve if\n at least half of the letters in view are revealed (not\n constants.HIDDEN). Otherwise, the computer opts to guess a\n consonant.\n\n \"\"\"\n\n if pf.computer_chooses_solve(view, difficulty, consonants):\n move = SOLVE\n guess = get_match(view, puzzles)\n print('\\tI choose to solve: {}.'.format(guess))\n else:\n move = CONSONANT\n guess = computer_guess_letter(consonants, difficulty)\n print('\\tI choose to guess letter: {}.'.format(guess))\n return move, guess\n\n\ndef get_match(view: str, puzzles: List[str]) -> str:\n \"\"\"Return a puzzle from puzzles that could be represented by view. If\n no such puzzle exists, return the empty string.\n\n >>> get_match('^^^ ro^k^', ['abc', 'csc rocks', 'math is cool'])\n 'csc rocks'\n >>> get_match('^^^ ro^ks', ['abc', 'csc rocks', 'math is cool'])\n ''\n \"\"\"\n\n for puzzle in puzzles:\n if is_match(puzzle, view):\n return puzzle\n return ''\n\n\ndef is_match(puzzle: str, view: str) -> bool:\n \"\"\"Return True if and only if view is a valid puzzle-view of puzzle.\n\n >>> is_match('', '')\n True\n >>> is_match('a', 'a')\n True\n >>> is_match('bb', 'b^')\n False\n >>> is_match('abcde', 'ab^^e')\n True\n >>> is_match('axyzb', 'ab^^e')\n False\n >>> is_match('abcdefg', 'ab^^e')\n False\n\n \"\"\"\n\n if len(puzzle) != len(view):\n return False\n\n for index in range(len(puzzle)):\n if (puzzle[index] != view[index] and\n not pf.is_hidden(index, puzzle, view)):\n return False\n return True\n\n\ndef computer_guess_letter(consonants: str, difficulty: str) -> str:\n \"\"\"Return a letter from consonants. If difficulty is constants.EASY,\n select the letter randomly. If difficulty is constants.HARD,\n select the first letter from constants.PRIORITY_CONSONANTS that\n occurs in consonants.\n\n len(consonants) > 0;\n at least one character in consonants is in consonants.PRIORITY_CONSONANTS.\n difficulty in (constants.EASY, constants.HARD)\n\n >>> computer_guess_letter('bcdfg', 'H')\n 'd'\n\n \"\"\"\n\n if difficulty == HARD:\n for consonant in PRIORITY_CONSONANTS:\n if consonant in consonants:\n return consonant\n return random.choice(consonants)\n\n\n########################## Game Play: User Interaction: ####################\ndef human_move(player_score: int, consonants: str, vowels: str) -> tuple:\n \"\"\"Ask the user to make a complete move:\n\n 1) Repeatedly ask to choose a move (constants.CONSONANT,\n constants.VOWEL, constants.SOLVE, or constants.QUIT), until a\n valid input is entered.\n\n 2) Upon receiving constants.VOWEL or constants.CONSONANT,\n repeatedly prompt to choose a corresponding letter, until a valid\n input is entered.\n\n 3) Upon receiving constants.SOLVE, prompt for a solution word.\n\n Return the user input guess, or the empty string is the first\n choice was constants.QUIT.\n\n \"\"\"\n\n move = select_move(player_score, consonants, vowels)\n\n if move == QUIT:\n guess = ''\n if move == VOWEL:\n guess = select_letter(vowels)\n if move == CONSONANT:\n guess = select_letter(consonants)\n if move == SOLVE:\n guess = input('Input your solution guess: ')\n\n return (move, guess)\n\n\ndef select_move(score: int, consonants: str, vowels: str) -> str:\n \"\"\"Repeatedly prompt current_player to choose a move until a valid\n selection is made. Return the selected move. Move validity is\n defined by is_valid_move(selected-move-type, score, consonants,\n vowels).\n\n (Note: Docstring examples not given since result depends on input\n data.)\n\n \"\"\"\n\n prompt = make_move_prompt()\n\n move = input(prompt)\n while not is_valid_move(move.strip(), score, consonants, vowels):\n move = input(prompt)\n\n return move.strip()\n\n\ndef select_letter(letters: str) -> str:\n \"\"\"Repeatedly prompt the user for a letter, until a valid input is\n received. Return the letter. Valid options are characters from\n letters.\n\n (Note: Docstring examples not given since result depends on input\n data.)\n\n \"\"\"\n\n prompt = 'Choose a letter from [{}]: '.format(\n ','.join(['{}'] * len(letters)))\n valid_options = tuple(letters)\n return prompt_for_selection(prompt, valid_options)\n\n\ndef prompt_for_selection(prompt_format: str, valid_options: tuple) -> str:\n \"\"\"Repeatedly ask the user for a selection, until one of valid_options\n is received. The user prompt is created as\n prompt_format.format(valid_option). Return the user input with\n leading and trailing whitespace removed.\n\n (Note: Docstring examples not given since result depends on input\n data.)\n\n \"\"\"\n\n prompt = prompt_format.format(*valid_options)\n\n selection = input(prompt)\n while selection.strip() not in valid_options:\n selection = input('Invalid choice.\\n{}'.format(prompt))\n\n return selection.strip()\n\n\ndef display_move_prompt(current_player: str, player_score: int,\n view: str) -> None:\n \"\"\"Display a prompt for the player to select the next move.\"\"\"\n\n print('=' * 50)\n print('{}, it is your turn. You have {} points.'.format(\n current_player, player_score))\n print('\\n' + view + '\\n')\n\n\ndef make_move_prompt() -> str:\n \"\"\"Return a prompt for the player to select the next move.\"\"\"\n\n prompt = '''Select move type:\n [{}] - Vowel,\n [{}] - Consonant,\n [{}] - Solve,\n [{}] - Quit.\\n'''.format(VOWEL, CONSONANT, SOLVE, QUIT)\n\n return prompt\n\n\ndef is_valid_move(move: str, score: int, consonants: str, vowels: str) -> bool:\n \"\"\"Return whether move is valid. If invalid, print an explanatory\n message. A move is valid when:\n\n 1) move is one of constants.CONSONANT, constants.VOWEL,\n constants.SOLVE, or constants.QUIT;\n\n 2) If move is constants.VOWEL, score is high enough to buy a\n vowel(at least constants.VOWEL_PRICE), and vowels has at least\n one character.\n\n 3) If move is constants.CONSONANT, consonants has at least\n one character.\n\n >>> is_valid_move('X', 0, '', '')\n Valid moves are: C, V, S, and Q.\n False\n >>> is_valid_move('Q', 0, '', '')\n True\n >>> is_valid_move('S', 42, 'bdfrt', 'aeui')\n True\n >>> is_valid_move('C', 2, 'bcdfghjklmnpqstvwxyz', 'aeiou')\n True\n >>> is_valid_move('C', 2, '', 'aeiou')\n You do not have any more consonants to guess!\n False\n >>> is_valid_move('V', 1, 'bcdfghjklmnpqstvwxyz', 'aeiou')\n True\n >>> is_valid_move('V', 0, 'bcdfghjklmnpqstvwxyz', 'aeiou')\n You do not have enough points to reveal a vowel. Vowels cost 1 point(s).\n False\n >>> is_valid_move('V', 42, 'bcdfghjklmnpqstvwxyz', '')\n You do not have any more vowels to guess!\n False\n\n \"\"\"\n\n if move not in (CONSONANT, VOWEL, SOLVE, QUIT):\n print('Valid moves are: {}, {}, {}, and {}.'.format(\n CONSONANT, VOWEL, SOLVE, QUIT))\n return False\n\n if move == VOWEL and score < VOWEL_PRICE:\n print('You do not have enough points to reveal a vowel. '\n 'Vowels cost {} point(s).'.format(VOWEL_PRICE))\n return False\n\n if move == VOWEL and vowels == '':\n print('You do not have any more vowels to guess!')\n return False\n\n if move == CONSONANT and consonants == '':\n print('You do not have any more consonants to guess!')\n return False\n\n return True\n\n\n############################# Game Setup: #############################\ndef select_game_type() -> str:\n \"\"\"Repeatedly prompt the user for game type, until a valid input is\n received. Return the game type. Valid options are constants.HUMAN,\n constants.HUMAN_HUMAN, and constants.HUMAN_COMPUTER.\n\n (Note: Docstring examples not given since result depends on input\n data.)\n\n \"\"\"\n\n prompt = '''Choose the game type:\n [{}] - One Player\n [{}] - Human-human\n [{}] - Human-computer\\n'''\n valid_options = HUMAN, HUMAN_HUMAN, HUMAN_COMPUTER\n return prompt_for_selection(prompt, valid_options)\n\n\ndef select_computer_difficulty() -> str:\n \"\"\"Repeatedly prompt the user for computer difficulty, until a valid\n input is received. Return the computer difficulty. Valid options\n are constants.EASY and constants.HARD.\n\n (Note: Docstring examples not given since result depends on input\n data.)\n\n \"\"\"\n\n prompt = 'Choose the game difficulty ([{}] - Easy or [{}] - Hard): '\n valid_options = EASY, HARD\n return prompt_for_selection(prompt, valid_options)\n\n\ndef make_view(puzzle: str) -> str:\n \"\"\"Return a string that is based on puzzle, with each alphabetic\n character replaced by the constants.HIDDEN character.\n\n >> > make_view('apple cake is great! #csc108')\n '^^^^^ ^^^^ ^^ ^^^^^! #^^^108'\n >> > make_view('108@#$&')\n '108@#$&'\n\n \"\"\"\n\n view = ''\n for char in puzzle:\n if char.isalpha():\n view = view + HIDDEN\n else:\n view = view + char\n return view\n\n\n############################# Game Over: #############################\ndef display_outcome(winner: str, puzzle: str, game_type: str,\n player_one_score: int, player_two_score: int) -> None:\n \"\"\"Display the outcome of game: who won and what the final scores are.\n \"\"\"\n\n print('And the winner is... {}!'.format(winner))\n print('The solution to this game\\'s puzzle is: {}.'.format(puzzle))\n if pf.is_one_player_game(game_type):\n print('In this game, the player scored {} point(s)'.\n format(player_one_score))\n else:\n print('In this game, {} scored {} and {} scored {} point(s)'.\n format(PLAYER_ONE, player_one_score, PLAYER_TWO,\n player_two_score))\n\n\n############################# The Program: #############################\nif __name__ == '__main__':\n\n import doctest\n doctest.testmod()\n\n DATA_FILE = 'puzzles_small.txt'\n\n PUZZLES = []\n with open(DATA_FILE) as data_file:\n for line in data_file:\n PUZZLES.append(line.lower().strip())\n\n PUZZLE = random.choice(PUZZLES)\n\n print('Welcome to Phrase Puzzler!')\n\n print('***' + PUZZLE + '***')\n\n GAME_TYPE = select_game_type()\n play_game(PUZZLE, PUZZLES, GAME_TYPE)\n","sub_path":"a1/puzzler.py","file_name":"puzzler.py","file_ext":"py","file_size_in_byte":14630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"598797378","text":"import random\nn = 10\nm = n**2 - 9\nk = n**2 + n\n\nprint(n) #Dimensión\nprint(\"0.00001\")\nprint(random.randrange(5,n+1)) #numero aleatorio\n\nfor i in range(n):\n endline = \" \" if i != n-1 else \"\\n\"\n print(0,end=endline)\n\nfor i in range(n):\n for j in range(n):\n endline = \" \" if j != n-1 else \"\\n\"\n if i == j:\n print(random.randrange(m,k),end=endline)\n else:\n print(random.randrange(0,n+1),end=endline)\nfor i in range(n):\n endline = \" \" if i != n-1 else \"\"\n print(random.randint(0,2*n),end=endline)\n\n\n\n\n","sub_path":"testcase_maker.py","file_name":"testcase_maker.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"118601523","text":"import numpy as np \nimport matplotlib.pyplot as plt\n\nx = np.linspace(0,5,100)\n\nfig = plt.figure(figsize=(12,6))\nplt.suptitle('Exponential distribution plots',fontsize=14)\n\n##########################################################\n\n# Exponential distribution probability density function\ndef get_density_y(x, RATE):\t\n\treturn RATE*np.exp(-RATE*x)\n\n\nax1 = fig.add_subplot(121,ylim=[0,1.5])\n# Get exponential distribution plot\nax1.plot(x,get_density_y(x, 0.5),'r')\nax1.plot(x,get_density_y(x, 1.5),'b')\n# Preferences of first plot\nax1.grid(axis='both',color='y',linestyle='--',linewidth=1)\nax1.legend([r'$\\lambda=0.5$',r'$\\lambda=1.5$'], fontsize=12)\nax1.set_xlabel('x')\nax1.set_ylabel(r'$P(x)$')\nax1.set_title('Probability density function', fontsize=12)\n\n###########################################################\n\ndef get_cumulative_y(x, RATE):\n\treturn 1-np.exp(-x*RATE)\n\n\nax2 = fig.add_subplot(122)\n# Get exponential distribution plot\nax2.plot(x,get_cumulative_y(x, 0.5),'r')\nax2.plot(x,get_cumulative_y(x, 1.5),'b')\n# Preferences of second plot\nax2.grid(axis='both',color='y',linestyle='--',linewidth=1)\nax2.legend([r'$\\lambda=0.5$',r'$\\lambda=1.5$'], fontsize=12)\nax2.set_xlabel('x')\nax2.set_ylabel(r'$P(X \\leq x)$')\nax2.set_title('Cumulative distribution function', fontsize=12)\n\n############################################################\n\nplt.show()","sub_path":"numpy on python 2.7/dist_exp.py","file_name":"dist_exp.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"632004602","text":"from wsgiref.simple_server import make_server\nfrom pyramid.config import Configurator\nfrom pyramid.response import Response\nfrom webob import Request, Response\nfrom jinja2 import Environment, FileSystemLoader\n\nassets = [\n 'app.js',\n 'react.js',\n 'leaflet.js',\n 'D3.js',\n 'moment.js',\n 'math.js',\n 'main.css',\n 'bootstrap.css',\n 'normalize.css',\n]\n\nSTYLES = []\nSCRIPTS = []\n\nfor item in assets:\n itemsplited = item.split('.')\n if itemsplited[1] == 'js':\n SCRIPTS.append(item)\n elif itemsplited[1] == 'css':\n STYLES.append(item)\n\nclass make_wsgi_app(object):\n def __init__(self, app):\n self.app = app\n\n def __call__(self, environ, start_response):\n response = self.app(environ, start_response).decode()\n\ndef app(request):\n response_code = '200 OK'\n response_type = ('Content-Type', 'text/HTML')\n start_response(response_code, [response_type])\n return ''''''\n\ndef index(request):\n env = Environment(loader=FileSystemLoader('.'))\n template = env.get_template('index.html').render(javascripts=SCRIPTS, styles=STYLES)\n return Response(template)\n\ndef about(request):\n env = Environment(loader=FileSystemLoader('.'))\n template = env.get_template('about/about.html').render(javascripts=SCRIPTS, styles=STYLES)\n return Response(template)\n\nif __name__ == '__main__':\n config = Configurator()\n\n configure.add_route('index', '/index.html')\n config.add_view(index, route_name=\"index\")\n\n # configure.add_route('about', '/about/about.html')\n # config.add_view(about, route_name=\"about\")\n\n app = config.make_wsgi_app()\n make_server('0.0.0.0', 80, app).serve_forever()\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225083018","text":"from .base import *\n\nSECRETS = SECRETS_FULL['dev']\n\nDEBUG = True\nWSGI_APPLICATION = 'config.wsgi.dev.application'\nDATABASES = SECRETS['DATABASES']\nALLOWED_HOSTS += [\n '*',\n]\nINSTALLED_APPS += [\n\n]\n\n# Storage\nAWS_STORAGE_BUCKET_NAME = 'wps-instagram-lhy3'\n","sub_path":"app/config/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"588722411","text":"# Author: Yash Shukla\n# Email: yash.shukla@tufts.edu\n\nimport math\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nfrom matplotlib.cm import get_cmap\nimport time\nimport gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\n\nclass NovelGridworldV0Env(gym.Env):\n\n def __init__(self, map_width=None, map_height=None, items_id=None, items_quantity=None, goal_env = None, is_final = False):\n # NovelGridworldV7Env attributes\n self.env_name = 'Pick and Place'\n self.map_width = 10\n self.map_height = 10\n self.map = np.zeros((self.map_width, self.map_height), dtype=int) # 2D Map\n self.agent_location = (1, 1) # row, column\n # self.direction_id = {'NORTH': 0, 'SOUTH': 1, 'WEST': 2, 'EAST': 3}\n self.direction_id = {'NORTH': 0}\n self.agent_facing_str = 'NORTH'\n self.agent_facing_id = self.direction_id[self.agent_facing_str]\n self.block_in_front_str = 'air'\n self.block_in_front_id = 0 # air\n self.block_in_front_location = (0, 0) # row, column\n self.items = ['wall', 'cube1', 'cube2', 'cube3']\n self.items_id = self.set_items_id(self.items) # {'crafting_table': 1, 'pogo_stick': 2, ...} # air's ID is 0\n # items_quantity when the episode starts, do not include wall, quantity must be more than 0\n self.items_quantity = {'cube1': 1, 'cube2': 1, 'cube3': 1}\n\n self.available_locations = [] # locations that do not have item placed\n self.not_available_locations = [] # locations that have item placed or are above, below, left, right to an item\n\n # Action Space\n self.action_str = {0: 'Forward', 1: 'Left', 2: 'Right', 3: 'Backward', 4: 'PickUp', 5: 'Drop'}\n self.goal_env = 2\n self.action_space = spaces.Discrete(len(self.action_str))\n self.recipes = {}\n self.last_action = 0 # last actions executed\n self.step_count = 0 # no. of steps taken\n\n # Observation Space\n self.num_beams = 8\n self.max_beam_range = 40\n self.items_lidar = ['wall', 'cube1', 'cube2', 'cube3']\n self.items_id_lidar = self.set_items_id(self.items_lidar)\n self.low = np.array([0] * (len(self.items_lidar) * self.num_beams) + [0]*5 )\n self.high = np.array([self.max_beam_range] * (len(self.items_lidar) * self.num_beams) + [2]*5 ) # maximum 5 trees present in the environment\n self.observation_space = spaces.Box(self.low, self.high, dtype=int)\n\n # Reward\n self.last_reward = 0 # last received reward\n self.last_done = False # last done\n self.reward_done = 1000\n self.reward_break = 30\n self.episode_timesteps = 250\n\n if map_width is not None:\n self.map_width = map_width\n if map_height is not None:\n self.map_height = map_height\n if items_id is not None:\n self.items_id = items_id\n if items_quantity is not None:\n self.items_quantity = items_quantity\n if goal_env is not None:\n self.goal_env = goal_env\n if is_final == True:\n self.reward_break = 10\n\n self.current_pickup_state = 0\n self.current_pickup_item = 0 # 0 for cube1, 1 for cube2, 2 for cube3\n self.dropped_items = 0\n self.cube1_priority = 0\n self.cube2_priority = 0\n\n if self.goal_env == 2:\n assert not self.items_quantity['cube3'] == 0, \"Cannot drop. Insert cube 3\"\n\n def reset(self):\n\n # Variables to reset for each reset:\n self.available_locations = []\n self.not_available_locations = []\n self.last_action = 0 # last actions executed\n self.step_count = 0 # no. of steps taken\n self.last_reward = 0 # last received reward\n self.last_done = False # last done\n\n self.current_pickup_state = 0\n self.current_pickup_item = 0 # 0 for cube1, 1 for cube2, 2 for cube 3\n self.dropped_items = 0\n self.target_dropped_items = self.items_quantity['cube1'] + self.items_quantity['cube2']\n self.release_order = []\n\n self.map = np.zeros((self.map_width - 2, self.map_height - 2), dtype=int) # air=0\n self.map = np.pad(self.map, pad_width=1, mode='constant', constant_values=self.items_id['wall'])\n\n \"\"\"\n available_locations: locations 1 block away from the wall are valid locations to place items and agent\n available_locations: locations that do not have item placed\n \"\"\"\n for r in range(2, self.map_width - 2):\n for c in range(2, self.map_height - 2):\n self.available_locations.append((r, c))\n\n # Agent\n idx = np.random.choice(len(self.available_locations), size=1)[0]\n self.agent_location = self.available_locations[idx]\n\n # Agent facing direction\n self.set_agent_facing(direction_str=np.random.choice(list(self.direction_id.keys()), size=1)[0])\n\n for item, quantity in self.items_quantity.items():\n self.add_item_to_map(item, num_items=quantity)\n\n if self.agent_location not in self.available_locations:\n self.available_locations.append(self.agent_location)\n\n # Update after each reset\n self.items_released = [0,0]\n\n self.target_dropped_items = self.items_quantity['cube1'] + self.items_quantity['cube2']\n if self.items_quantity['cube1'] == 1 and self.items_quantity['cube2'] == 0:\n self.target_release_order = [1]\n self.cube1_priority = 1\n if self.items_quantity['cube1'] == 0 and self.items_quantity['cube2'] == 1:\n self.target_release_order = [2]\n self.cube2_priority = 1\n if self.items_quantity['cube1'] == 1 and self.items_quantity['cube2'] == 1:\n self.target_release_order = [1,2]\n self.cube2_priority = 1\n self.cube1_priority = 2\n\n observation = self.get_observation()\n self.update_block_in_front()\n return observation\n\n def add_item_to_map(self, item, num_items):\n\n item_id = self.items_id[item]\n\n count = 0\n while True:\n if num_items == count:\n break\n assert not len(self.available_locations) < 1, \"Cannot place items, increase map size!\"\n\n idx = np.random.choice(len(self.available_locations), size=1)[0]\n r, c = self.available_locations[idx]\n\n if (r, c) == self.agent_location:\n self.available_locations.pop(idx)\n continue\n\n # If at (r, c) is air, and its North, South, West and East are also air, add item\n if (self.map[r][c]) == 0 and (self.map[r - 1][c] == 0) and (self.map[r + 1][c] == 0) and (\n self.map[r][c - 1] == 0) and (self.map[r][c + 1] == 0):\n self.map[r][c] = item_id\n count += 1\n self.not_available_locations.append(self.available_locations.pop(idx))\n\n def get_lidarSignal(self):\n \"\"\"\n Send several beans (self.num_beams) at equally spaced angles in 360 degrees in front of agent within a range\n For each bean store distance (beam_range) for each item in items_id_lidar if item is found otherwise 0\n and return lidar_signals\n \"\"\"\n\n direction_radian = {'NORTH': np.pi, 'SOUTH': 0, 'WEST': 3 * np.pi / 2, 'EAST': np.pi / 2}\n\n # Shoot beams in 360 degrees in front of agent\n angles_list = np.linspace(direction_radian[self.agent_facing_str] - np.pi,\n direction_radian[self.agent_facing_str] + np.pi,\n self.num_beams + 1)[:-1] # 0 and 360 degree is same, so removing 360\n\n lidar_signals = []\n r, c = self.agent_location\n for angle in angles_list:\n x_ratio, y_ratio = np.round(np.cos(angle), 2), np.round((np.sin(angle)), 2)\n beam_signal = np.zeros(len(self.items_id_lidar), dtype=int)#\n\n # Keep sending longer beams until hit an object or wall\n for beam_range in range(1, self.max_beam_range+1):\n r_obj = r + np.round(beam_range * x_ratio)\n c_obj = c + np.round(beam_range * y_ratio)\n obj_id_rc = self.map[int(r_obj)][int(c_obj)]\n\n # If bean hit an object or wall\n if obj_id_rc != 0:\n item = list(self.items_id.keys())[list(self.items_id.values()).index(obj_id_rc)]\n if item in self.items_id_lidar:\n obj_id_rc = self.items_id_lidar[item]\n beam_signal[obj_id_rc - 1] = beam_range\n break\n\n lidar_signals.extend(beam_signal)\n\n return lidar_signals\n\n def set_agent_facing(self, direction_str):\n\n self.agent_facing_str = direction_str\n self.agent_facing_id = self.direction_id[self.agent_facing_str]\n\n '''\n self.agent_facing_str = list(self.direction_id.keys())[list(self.direction_id.values()).index(self.agent_facing_id)]\n '''\n\n def set_items_id(self, items):\n\n items_id = {}\n for item in sorted(items):\n items_id[item] = len(items_id) + 1\n\n return items_id\n\n def get_observation(self):\n \"\"\"\n observation is lidarSignal + inventory_items_quantity\n :return: observation\n \"\"\"\n\n lidar_signals = self.get_lidarSignal()\n # observation = lidar_signals + [self.inventory_items_quantity[item] for item in\n # sorted(self.inventory_items_quantity)]\n\n # if 1 in self.items_released:\n # self.cube1_priority = 0\n # self.\n\n observation = lidar_signals + [self.current_pickup_item] + self.items_released + [self.cube1_priority, self.cube2_priority]\n\n # print(observation)\n # time.sleep(5.0)2\n return np.array(observation)\n\n def step(self, action):\n \"\"\"\n Actions: {0: 'Forward', 1: 'Left', 2: 'Right', 3: 'Break'}\n \"\"\"\n\n self.last_action = action\n r, c = self.agent_location\n\n done = False\n reward = -1 # default reward\n # Forward\n if action == 0:\n if self.agent_facing_str == 'NORTH' and self.map[r-1][c] == 0:\n self.agent_location = (r-1, c)\n # Left\n elif action == 1:\n if self.agent_facing_str == 'NORTH' and self.map[r][c-1] == 0:\n self.agent_location = (r, c-1)\n\n # Right\n elif action == 2:\n if self.agent_facing_str == 'NORTH' and self.map[r][c+1] == 0:\n self.agent_location = (r, c+1)\n\n # Backward\n elif action == 3:\n if self.agent_facing_str == 'NORTH' and self.map[r+1][c] == 0:\n self.agent_location = (r+1, c)\n\n\n # PickUp\n elif action == 4:\n self.update_block_in_front()\n # If block in front is not air and wall, place the block in front in inventory\n if self.block_in_front_str == 'cube1' or self.block_in_front_str == 'cube2':\n if self.current_pickup_state == 0:\n block_r, block_c = self.block_in_front_location\n self.map[block_r][block_c] = 0\n reward = self.reward_break\n self.current_pickup_state = 1\n if self.block_in_front_str =='cube1':\n self.current_pickup_item = 1\n elif self.block_in_front_str == 'cube2':\n self.current_pickup_item = 2\n\n # Release\n elif action == 5:\n self.update_block_in_front()\n if self.block_in_front_str == 'cube3':\n if self.current_pickup_state == 1:\n self.release_order.append(self.current_pickup_item)\n self.items_released[self.current_pickup_item-1] = self.current_pickup_item\n if len(self.release_order) > 1:\n if self.release_order == self.target_release_order:\n reward \n self.current_pickup_state = 0\n self.current_pickup_item = 0\n self.dropped_items += 1\n # flag = 0\n # reward = 0\n # for i in range(len(self.release_order)-1):\n # if self.release_order[i] < self.release_order[i + 1]:\n # flag += 1\n # else:\n # flag += 0\n # self.dropped_items += 1\n # if flag == self.dropped_items-1:\n # reward = self.reward_break\n # else:\n # reward = -20\n # self.current_pickup_state = 0\n # self.current_pickup_item = 0\n\n # Update after each step\n observation = self.get_observation()\n self.update_block_in_front()\n\n if self.goal_env == 0: # If the goal is navigation\n if not self.block_in_front_id == 0 and not self.block_in_front_str == 'wall':\n done = True\n reward = self.reward_done\n\n if self.goal_env == 1: # If the goal is pickup\n if self.current_pickup_item > 0:\n reward = self.reward_done\n done = True\n\n if self.goal_env == 2:\n if self.release_order == self.target_release_order and self.dropped_items == self.target_dropped_items:\n reward = self.reward_done\n done = True\n elif self.dropped_items == self.target_dropped_items:\n reward = -200\n done = True\n\n info = {}\n\n # Update after each step\n self.step_count += 1\n self.last_reward = reward\n self.last_done = done\n\n # if done == False and self.step_count == self.episode_timesteps:\n # done = True\n\n return observation, reward, done, info\n\n def update_block_in_front(self):\n r, c = self.agent_location\n\n\n if self.agent_facing_str == 'NORTH':\n self.block_in_front_id = self.map[r - 1][c]\n self.block_in_front_location = (r - 1, c)\n\n\n if self.block_in_front_id == 0:\n self.block_in_front_str = 'air'\n else:\n self.block_in_front_str = list(self.items_id.keys())[\n list(self.items_id.values()).index(self.block_in_front_id)]\n\n def render(self, mode='human', title=None):\n\n color_map = \"gist_ncar\"\n\n if title is None:\n title = self.env_name\n\n r, c = self.agent_location\n x2, y2 = 0, 0\n if self.agent_facing_str == 'NORTH':\n x2, y2 = 0, -0.01\n elif self.agent_facing_str == 'SOUTH':\n x2, y2 = 0, 0.01\n elif self.agent_facing_str == 'WEST':\n x2, y2 = -0.01, 0\n elif self.agent_facing_str == 'EAST':\n x2, y2 = 0.01, 0\n\n plt.figure(title, figsize=(18, 9))\n plt.imshow(self.map, cmap=color_map, vmin=0, vmax=len(self.items_id))\n # plt.imshow(self.map, cmap=color_map)\n\n plt.arrow(c, r, x2, y2, head_width=0.7, head_length=0.7, color='white')\n plt.title('NORTH', fontsize=20)\n plt.xlabel('SOUTH', fontsize=20)\n plt.ylabel('WEST', fontsize=20)\n # plt.text(self.map_width, self.map_width // 2, 'EAST', rotation=90)\n # plt.text(self.map_size, self.map_size // 2, 'EAST', rotation=90)\n # plt.colorbar()\n # plt.grid()\n\n info = '\\n'.join([\" Info: \",\n \"Env: \"+self.env_name,\n \"Steps: \" + str(self.step_count),\n \"Agent Facing: \" + self.agent_facing_str,\n \"Action: \" + self.action_str[self.last_action],\n \"Reward: \" + str(self.last_reward),\n \"Done: \" + str(self.last_done),\n \"Dropped Items: \" + str(self.dropped_items) + \"/\" + str(self.target_dropped_items)\n ])\n props = dict(boxstyle='round', facecolor='w', alpha=0.2)\n plt.text(-(self.map_width // 2) - 0.5, 2.25, info, fontsize=18, bbox=props) # x, y\n\n # plt.text(-(self.map_size // 2) - 0.5, 2.25, info, fontsize=10, bbox=props) # x, y\n\n if self.last_done:\n you_win = \"You win \"+self.env_name+\"!\"\n props = dict(boxstyle='round', facecolor='w', alpha=1)\n # plt.text(0 - 0.1, (self.map_size // 2), you_win, fontsize=18, bbox=props)\n # plt.text(0 - 0.1, (self.map_width // 2), you_win, fontsize=18, bbox=props)\n\n cmap = get_cmap(color_map)\n\n legend_elements = [Line2D([0], [0], marker=\"^\", color='w', label='agent', markerfacecolor='w', markersize=18,\n markeredgewidth=2, markeredgecolor='k'),\n Line2D([0], [0], color='w', label=\"Legend:\")]\n for item in sorted(self.items_quantity):\n rgba = cmap(self.items_id[item] / len(self.items_id))\n legend_elements.append(Line2D([0], [0], marker=\"s\", color='w',\n label=item + ': ' + str(self.items_quantity[item]),\n markerfacecolor=rgba, markersize=18))\n plt.legend(handles=legend_elements, bbox_to_anchor=(1.55, 1.02), fontsize = 18) # x, y\n\n plt.tight_layout()\n plt.pause(0.01)\n plt.clf()\n\n def close(self):\n return\n","sub_path":"gym_novel_gridworlds/envs/novel_gridworld_v0_env.py","file_name":"novel_gridworld_v0_env.py","file_ext":"py","file_size_in_byte":17616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"255234267","text":"#coding:utf-8\nfrom AMSS.utils.requestor import Requestor\nfrom AMSS.conf.urls import dfcf_headers, url_block, url_bk_kline, url_stocks_block\nimport pandas as pd\nfrom AMSS.utils.timer import get_ts_ms\n\n\nclass Receiver(object):\n def __init__(self, source='dfcf'):\n self.source = source\n\n def get_blocks(self, block_type='gn_block'):\n \"\"\"\n :param block_type:\n :return:\n \"\"\"\n if self.source == 'dfcf':\n url = url_block.format(block_type[0:2].upper())\n r = Requestor(url, headers=dfcf_headers, reg=r'(\\[.*?\\])')\n blocks = r.my_req()\n bk_list = []\n for bk in blocks:\n tmp = bk.split(',')\n bk_tuple = (tmp[1], tmp[2])\n bk_list.append(bk_tuple)\n print(bk_list)\n blocks_df = pd.DataFrame(bk_list, columns=['block_id', 'name'])\n # blocks_df['name'] = blocks_df['name'].to_string\n blocks_df = blocks_df.set_index(['block_id'])\n return blocks_df\n\n\n def get_block_index(self, bk_id, ktype='K'):\n ts = get_ts_ms()\n url = url_bk_kline.format(bk_id, ktype, ts, ts, ts)\n r = Requestor(url, headers=dfcf_headers, reg=r'\\((.*?)\\)')\n index_k = r.my_req()['data']\n # print(index_k)\n data = []\n for day in index_k:\n row_list = day.split(',')\n data.append(row_list)\n index_df = pd.DataFrame(data, columns=('time', 'open', 'close', 'high', 'low', 'vol', 'amount', 'span'))\n index_df['block_id'] = bk_id\n return index_df\n\n def get_stocks(bk_id):\n url = url_stocks_block.format(bk_id)\n r = Requestor(url, headers=dfcf_headers, reg=r'(\\[.*?\\])')\n stocks = r.my_req()\n data = []\n for s in stocks:\n code = s.split(',')[1]\n data.append((bk_id, code))\n df_stock = pd.DataFrame(data, columns=('block_id', 'code'))\n return df_stock\n\n\n\nif __name__ == '__main__':\n # print get_blocks()\n pass\n # for i in get_blocks().index:\n # print(get_stocks(i))\n\n","sub_path":"Automaticic_monitoring_system_for_stocks/AMSS/data/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206703559","text":"import pytest\nfrom aiohttp.test_utils import TestClient\n\nfrom tests import models\nfrom tests.pg_sa.app import get_app\nfrom tests.pg_sa.utils import async_engine_connection\n\n\n@pytest.fixture\nasync def user(loop):\n async with async_engine_connection() as conn:\n query = models.users.select().limit(1)\n return await conn.fetch_one(query)\n\n\n@pytest.fixture\nasync def get_last_created_user(loop):\n async def _get_last_user():\n async with async_engine_connection() as conn:\n query = models.users.select().order_by(models.users.c.created_at.desc()).limit(1)\n return await conn.fetch_one(query)\n\n return _get_last_user\n\n\n@pytest.fixture\nasync def get_user_by_id(loop):\n async def _get_user_by_id(user_id):\n async with async_engine_connection() as conn:\n query = models.users.select(models.users.c.id == user_id)\n return await conn.fetch_one(query)\n\n return _get_user_by_id\n\n\n@pytest.fixture\nasync def client(aiohttp_client):\n client: TestClient = await aiohttp_client(get_app())\n return client\n\n\n@pytest.fixture\nasync def pg_sa_instance(loop):\n async with async_engine_connection() as conn:\n query = models.pg_sa_fields.select().limit(1)\n return await conn.fetch_one(query)\n\n\ndef pytest_runtest_setup(item):\n if \"with_client\" in item.keywords and \"client\" not in item.fixturenames:\n # inject client\n item.fixturenames.append(\"client\")\n","sub_path":"tests/pg_sa/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"114517193","text":"import cea\nimport cea.GUI\nimport cea.GUI.toolbox\n\n__author__ = \"Daren Thomas\"\n__copyright__ = \"Copyright 2016, Architecture and Building Systems - ETH Zurich\"\n__credits__ = [\"Daren Thomas\"]\n__license__ = \"MIT\"\n__version__ = \"0.1\"\n__maintainer__ = \"Daren Thomas\"\n__email__ = \"thomas@arch.ethz.ch\"\n__status__ = \"Production\"\n\nreload(cea)\nreload(cea.GUI)\nreload(cea.GUI.toolbox)\n\nDemandTool = cea.GUI.toolbox.DemandTool\nPropertiesTool = cea.GUI.toolbox.PropertiesTool\nEmissionsTool = cea.GUI.toolbox.EmissionsTool\nEmbodiedEnergyTool = cea.GUI.toolbox.EmbodiedEnergyTool\nHeatmapsTool = cea.GUI.toolbox.HeatmapsTool\nGraphsDemandTool = cea.GUI.toolbox.GraphsDemandTool\nRadiationTool = cea.GUI.toolbox.RadiationTool\nScenarioPlotsTool = cea.GUI.toolbox.ScenarioPlotsTool\nGraphsBenchmarkTool = cea.GUI.toolbox.GraphsBenchmarkTool\nMobilityTool = cea.GUI.toolbox.MobilityTool\n\nclass Toolbox(object):\n def __init__(self):\n self.label = 'City Energy Analyst'\n self.alias = 'cea'\n self.tools = [PropertiesTool, DemandTool, EmissionsTool, EmbodiedEnergyTool, HeatmapsTool, GraphsDemandTool,\n RadiationTool, ScenarioPlotsTool, GraphsBenchmarkTool, MobilityTool]\n","sub_path":"City Energy Analyst.pyt","file_name":"City Energy Analyst.pyt","file_ext":"pyt","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"514180334","text":"import h5py\nimport unittest\nimport numpy as np\n\nfrom QGL import *\nfrom instruments.drivers import APSPattern\n\nclass APSPatternUtils(unittest.TestCase):\n def setUp(self):\n # self.q1gate = Channels.LogicalMarkerChannel(label='q1-gate')\n # self.q1 = Qubit(label='q1', gateChan=self.q1gate)\n self.q1 = Qubit(label='q1')\n self.q1.pulseParams['length'] = 30e-9\n\n Compiler.channelLib = {'q1': self.q1}\n\n def test_unroll_loops_simple(self):\n q1 = self.q1\n seqs = [repeat(2, [qwait(), X(q1), Id(q1)]), repeat(2, [qwait(), Y(q1), Id(q1)])]\n a, b = APSPattern.unroll_loops(seqs)\n assert(a == seqs)\n assert(b == 2)\n\n def test_unroll_loops(self):\n q1 = self.q1\n seqs = [repeat(2, [qwait(), X(q1), Id(q1)]), repeat(3, [qwait(), Y(q1), Id(q1)])]\n a, b = APSPattern.unroll_loops(seqs)\n\n seqUnrolled = [qwait(), X(q1), Id(q1)]*2\n assert(a[0] == seqUnrolled)\n\n seqUnrolled = [qwait(), Y(q1), Id(q1)]*3\n assert(a[1] == seqUnrolled)\n\n assert(b == 0)\n\n def test_unroll_nested_loops(self):\n q1 = self.q1\n seqs = [repeat(2, [X(q1),Y(q1)] + repeat(3, [Z(q1)]) + [Y(q1),X(q1)]), [X(q1), Y(q1)]]\n a, b = APSPattern.unroll_loops(seqs)\n\n loopedZ = Z(q1)\n loopedZ.repeat = 3\n seqUnrolled = ([X(q1),Y(q1), loopedZ, Y(q1),X(q1)])*2\n\n assert(a[0] == seqUnrolled)\n\n assert(b == 0)\n\n def test_unroll_single_entry(self):\n q1 = self.q1\n seqs = [repeat(5, [X(q1)]) + [Y(q1)]]\n a, b = APSPattern.unroll_loops(seqs)\n seqUnrolled = [X(q1), Y(q1)]\n seqUnrolled[0].repeat = 5\n\n assert(a[0] == seqUnrolled)\n assert(b == 0)\n\nif __name__ == \"__main__\": \n unittest.main()\n","sub_path":"tests/test_APSPattern.py","file_name":"test_APSPattern.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180949878","text":"__author__ = 'huergasi'\n\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\nimport theano as t\n\ndef parsefile(filename, targetoffset):\n indices = [1,2,3,4,6,7,8,9,11,12,13,14]\n volume_index = [16]\n original_data = getoriginaldata(filename)\n file = open(filename, 'r')\n start = 0\n previous = []\n x=[]\n y=[]\n i = 0\n for line in file:\n row = np.array(line.split(','))\n current = np.take(row, indices).astype(np.float32)\n if start == 0:\n previous = np.take(row, indices).astype(np.float32)\n previous_volume = np.take(row, volume_index).astype(np.float32)\n start+=1\n else:\n current_volume = np.take(row, volume_index).astype(np.float32)\n sample = np.empty((1,current.size + 1))\n for index in np.arange(current.size):\n sample[0][index] = ((current[index] - previous[index]) / previous[index]) * 100\n sample[0][current.size] = current_volume\n previous = current\n if i < (original_data.size / 13) - targetoffset:\n x .append(sample)\n current_y = ((original_data[(i + targetoffset)*13] - current[0]) / current[0]) * 100\n y.append(current_y)\n i+=1\n return np.array(x),np.array(y)\n\ndef parse_and_normalize_file(filename, targetoffset, mu, sigma, y_max, y_min):\n indices = [1,2,3,4,6,7,8,9,11,12,13,14]\n volume_index = [16]\n original_data = getoriginaldata(filename)\n file = open(filename, 'r')\n start = 0\n previous = []\n x= np.empty([1,13], dtype=np.float32)\n y= np.empty([1], dtype=np.float32)\n i = 0\n for line in file:\n row = np.array(line.split(','))\n current = np.take(row, indices).astype(np.float32)\n if start == 0:\n previous = np.take(row, indices).astype(np.float32)\n previous_volume = np.take(row, volume_index).astype(np.float32)\n start+=1\n else:\n current_volume = np.take(row, volume_index).astype(np.float32)\n sample = np.empty((1,current.size + 1))\n for index in np.arange(current.size):\n sample[0][index] = ((current[index] - previous[index]) / previous[index]) * 100\n sample[0][current.size] = current_volume\n previous = current\n if i < (original_data.size / 13) - targetoffset:\n sample = ((sample - mu )/ sigma).astype(np.float32)\n x = np.vstack((x, sample))\n current_y = (((original_data[(i + targetoffset)*13] - current[0]) / current[0]) * 100).astype(np.float32)\n current_y = ((2 * (current_y - y_min) / (y_max-y_min)) - 1).astype(np.float32)\n y = np.vstack((y,current_y))\n i+=1\n x = np.delete(x, 0, 0)\n y = np.delete(y, 0, 0)\n return x, y\n\n\ndef get_mu_sigma_y(filepath, targetoffset):\n files = [f for f in listdir(filepath) if isfile(join(filepath, f))]\n alldata = []\n ally=[]\n mu = np.zeros((13,), dtype=np.float32)\n sigma = np.zeros((13,), dtype=np.float32)\n y_max = 0\n y_min = 0\n for f in files:\n x,y = (parsefile(join(filepath, f),targetoffset))\n alldata.append(x)\n ally.append(y)\n\n alldata_matrix = alldata[0]\n ally_matrix = ally[0]\n\n start = 0\n for el in alldata:\n if start !=0:\n alldata_matrix=np.vstack((alldata_matrix, el))\n else:\n start+=1\n\n start = 0\n for ey in ally:\n if start !=0:\n ally_matrix=np.hstack((ally_matrix, ey))\n else:\n start+=1\n\n alldata_matrix=np.matrix(alldata_matrix)\n mu = alldata_matrix.mean(0)\n sigma = alldata_matrix.std(0)\n y_max = ally_matrix.max()\n y_min = ally_matrix.min()\n\n return mu, sigma, y_max, y_min\n\ndef getoriginaldata(filename):\n indices = [1,2,3,4,6,7,8,9,11,12,13,14,16]\n file = open(filename, 'r')\n data = []\n start = 0\n for line in file:\n if start>0:\n row = np.array(line.split(','))\n data = np.append(data, np.take(row, indices).astype(np.float))\n start+=1\n return data\n\ndef getdata():\n path_training=r\"C:\\Users\\huergasi\\MLCode\\myCode\\data\\ib\\30sec\\training_sample\"\n path_testing=r\"C:\\Users\\huergasi\\MLCode\\myCode\\data\\ib\\30sec\\testing_sample\"\n path_validation=r\"C:\\Users\\huergasi\\MLCode\\myCode\\data\\ib\\30sec\\validation_sample\"\n\n training_files= [f for f in listdir(path_training) if isfile(join(path_training, f))]\n testing_files= [f for f in listdir(path_testing) if isfile(join(path_testing, f))]\n validation_files=[f for f in listdir(path_validation) if isfile(join(path_validation, f))]\n\n training_data_x = []\n training_data_y = []\n\n testing_data_x = []\n testing_data_y = []\n\n validation_data_x = []\n validation_data_y = []\n\n targetoffset = 4\n\n mu, sigma, y_max, y_min = get_mu_sigma_y(path_training, targetoffset)\n\n for f in training_files:\n x_train,y_train = parse_and_normalize_file(join(path_training, f),targetoffset, mu, sigma, y_max, y_min)\n training_data_x.append(x_train)\n training_data_y.append(y_train)\n\n for ftest in testing_files:\n x_test,y_test = parse_and_normalize_file(join(path_testing, ftest),targetoffset, mu, sigma, y_max, y_min)\n testing_data_x.append(x_test)\n testing_data_y.append(y_test)\n\n for fval in validation_files:\n x_val,y_val = parse_and_normalize_file(join(path_validation, fval),targetoffset, mu, sigma, y_max, y_min)\n validation_data_x.append(x_val)\n validation_data_y.append(y_val)\n\n return (training_data_x, training_data_y), (validation_data_x, validation_data_y), (testing_data_x, testing_data_y)\n\n\n\n\n\n","sub_path":"scripts/preprocessData.py","file_name":"preprocessData.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"18834983","text":"import math\nfrom bisect import bisect, insort\nfrom cocos.batch import BatchNode\n\nfrom cocos.euclid import Vector2, Matrix3\n\nclass Picker(object):\n \"\"\" A picker to find your children quickly \"\"\"\n def __init__(self):\n self.xChildren = {}\n self.yChildren = {}\n self.xs = []\n self.ys = []\n\n def _insert1d (self, child, ps, pChildren, p1, p2):\n p1pos = bisect(ps, p1)\n if p1pos == 0:\n ps.insert(0, p1)\n pChildren[p1] = set()\n elif ps[p1pos - 1] != p1:\n ps.insert(p1pos, p1)\n pChildren[p1] = pChildren[ps[p1pos - 1]].copy()\n else:\n p1pos -= 1\n p2pos = bisect(ps, p2)\n if ps[p2pos - 1] != p2:\n ps.insert(p2pos, p2)\n pChildren[p2] = pChildren[ps[p2pos - 1]].copy()\n else:\n p2pos -= 1\n for i in range(p1pos, p2pos):\n pChildren[ps[i]].add(child)\n\n def insert(self, child, x1, y1, x2, y2):\n \"\"\" Add a child \"\"\"\n self._insert1d(child, self.xs, self.xChildren, x1, x2)\n self._insert1d(child, self.ys, self.yChildren, y1, y2)\n\n def childrenAt(self, x, y):\n xPos = bisect(self.xs, x)\n if xPos == 0: return set()\n yPos = bisect(self.ys, y)\n if yPos == 0: return set()\n\n canditates = self.xChildren[self.xs[xPos-1]].intersection(self.yChildren[self.ys[yPos-1]])\n return [child for child in canditates if self._point_inside_child(x, y, child)]\n\n def _point_inside_child(self, x, y, child):\n \"\"\"\n \"\"\"\n # import pdb; pdb.set_trace()\n point = Vector2(x, y)\n cpos = Vector2(child.x, child.y)\n\n angle = math.radians(child.rotation)\n local_point = (Matrix3.new_rotate(angle) * (point - cpos)) * child.scale\n half_w, half_h = (child.width / 2) * child.scale, (child.height / 2) * child.scale\n\n if abs(local_point.x) < half_w and abs(local_point.y) < half_h:\n return True\n else:\n return False\n\n\n def _delete1d(self, child, ps, pChildren, p1, p2):\n p1Pos = bisect(ps, p1) - 1\n p2Pos = bisect(ps, p2) - 1\n for i in range(p1Pos, p2Pos):\n pChildren[ps[i]].remove(child)\n if pChildren[ps[p1Pos]] == pChildren[ps[p1Pos - 1]]:\n del pChildren[ps[p1Pos]]\n ps.pop(p1Pos)\n p2Pos -=1\n if pChildren[ps[p2Pos]] == pChildren[ps[p2Pos - 1]]:\n del pChildren[ps[p2Pos]]\n ps.pop(p2Pos)\n\n def delete(self, child, x1, y1, x2, y2):\n \"\"\" Delete all occurrences of child between x1, y1, x2, y1 \"\"\"\n self._delete1d(child, self.xs, self.xChildren, x1, x2)\n self._delete1d(child, self.ys, self.yChildren, y1, y2)\n\nfrom cocos.euclid import Matrix3, Vector2\nclass NodePicker(Picker):\n \"\"\" Wrap a CocosNode, and keep its children in a Picker \"\"\"\n def __init__(self):\n self.children = {}\n super(NodePicker, self).__init__()\n\n def hotspot(self, child):\n x = - child.image_anchor_x * child.scale\n y = - child.image_anchor_y * child.scale\n m = Matrix3.new_rotate(child.rotation)\n p1 = m * Vector2(x, y)\n p2 = m * Vector2(x + child.width, y)\n p3 = m * Vector2(x, y + child.height)\n p4 = m * Vector2(x + child.width, y + child.height)\n x1 = min(p1.x, p2.x, p3.x, p4.x)\n y1 = min(p1.y, p2.y, p3.y, p4.y)\n x2 = max(p1.x, p2.x, p3.x, p4.x)\n y2 = max(p1.y, p2.y, p3.y, p4.y)\n return int(child.x + x1), int(child.y + y1), int(child.x + x2), int(child.y + y2)\n\n def add(self, child):\n self.children[child] = self.hotspot(child)\n self.insert(child, *self.children[child])\n\n def remove(self, child):\n self.delete(child, *self.children[child])\n\n def update(self, child):\n self.remove(child)\n self.add(child)\n\nclass PickerBatchNode(BatchNode):\n\n def __init__(self):\n self.picker = NodePicker()\n super(PickerBatchNode, self).__init__()\n\n def add(self, child, z=0, name=None):\n child.register(self, 'x')\n child.register(self, 'y')\n child.register(self, 'position')\n child.register(self, 'rotation')\n child.register(self, 'scale')\n self.picker.add(child)\n super(PickerBatchNode, self).add(child, z, name)\n\n def remove(self, child):\n child.unregister(self, 'x')\n child.unregister(self, 'y')\n child.unregister(self, 'position')\n child.unregister(self, 'rotation')\n child.unregister(self, 'scale')\n self.picker.remove(child)\n super(PickerBatchNode, self).remove(child)\n\n def on_notify(self, node, attribute):\n self.picker.update(node)\n\n def childrenAt(self, x, y):\n return self.picker.childrenAt(x, y)\n\nif __name__ == '__main__':\n import unittest\n class TestPicker(unittest.TestCase):\n def testPicker(self):\n t = Picker()\n t.insert(\"A\", 1, 2, 3, 4)\n t.insert(\"B\", 2, 3, 4, 5)\n t.insert(\"C\", 3, 4, 5, 6)\n t.insert(\"D\", 1, 1, 6, 6)\n self.assertEquals(set([\"A\", \"D\"]), t.childrenAt(2.5, 2.5))\n t.delete(\"D\", 1, 1, 6, 6)\n self.assertEquals(set([\"A\"]), t.childrenAt(2.5, 2.5))\n t.delete(\"B\", 2, 3, 4, 5)\n t.insert(\"B\", 1, 1, 3, 3)\n self.assertEquals(set([\"A\", \"B\"]), t.childrenAt(2.5, 2.5))\n\n unittest.main()\n\n","sub_path":"gamelib/tiless_editor/picker.py","file_name":"picker.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"1768066","text":"import tkinter as tk\nfrom tkinter import ttk\n\nclass Aplicacion:\n def __init__(self):\n #Formulario/ventana\n self.ventana1=tk.Tk()\n \n #Etiqueta/label\n self.label1=tk.Label(self.ventana1, text=\"Hola y saludos: \")\n self.label1.grid(column=0, row=0)\n\n #Caja_texto/entry\n self.entry1=tk.Entry(self.ventana1, width=10)\n self.entry1.grid(column=0, row=1)\n\n #RadioButton\n self.radio1=tk.Radiobutton(self.ventana1,text=\"Selection\")\n self.radio1.grid(column=0, row=2)\n\n #Checkbutton\n self.check1=tk.Checkbutton(self.ventana1, text=\"Python\")\n self.check1.grid(column=0, row=3)\n\n #Listbox\n self.list1=tk.Listbox(self.ventana1)\n self.list1.grid(column=0, row=4)\n self.list1.insert(0,\"galletas\")\n self.list1.insert(1,\"pan\")\n\n #Combobox\n dias=(\"Lunes\", \"Martes\", \"Miercoles\")\n self.combobox1=ttk.Combobox(self.ventana1, width=10, values=dias)\n self.combobox1.current(0)\n self.combobox1.grid(column=0, row=5)\n\n #Menubar\n menubar1=tk.Menu(self.ventana1)\n self.ventana1.config(menu=menubar1)\n opciones1=tk.Menu(menubar1)\n opciones1.add_command(label=\"Abrir\")\n opciones1.add_command(label=\"Guardar\")\n opciones1.add_command(label=\"Salir\")\n menubar1.add_cascade(label=\"Archivo\", menu=opciones1)\n\n\n\n self.ventana1.mainloop()\n\naplicacion1=Aplicacion()","sub_path":"Evidencia 84_VSCode_tk_controles.py","file_name":"Evidencia 84_VSCode_tk_controles.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"517476162","text":"# coding=utf-8\n# Copyright 2018 The TensorFlow Datasets 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\"\"\"Tests for resource module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow_datasets.core.download import resource\n\nNO_EXTRACT = resource.ExtractMethod.NO_EXTRACT\nTAR = resource.ExtractMethod.TAR\nTAR_GZ = resource.ExtractMethod.TAR_GZ\nGZIP = resource.ExtractMethod.GZIP\nZIP = resource.ExtractMethod.ZIP\n\n\nclass GuessExtractMethodTest(tf.test.TestCase):\n\n def test_(self):\n for fname, expected_result in [\n ('bar.tar.gz', TAR_GZ),\n ('bar.gz', GZIP),\n ('bar.tar.zip', ZIP),\n ('bar.gz.strange', NO_EXTRACT),\n ('bar.tar', TAR),\n ]:\n res = resource._guess_extract_method(fname)\n self.assertEqual(res, expected_result, '(%s)->%s instead of %s' % (\n fname, res, expected_result))\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"tensorflow_datasets/core/download/resource_test.py","file_name":"resource_test.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"403861723","text":"import tensorflow as tf\nimport numpy as np\nimport random\nimport tensorflow.contrib.layers as layers\nfrom tensorflow.contrib import rnn\nfrom tqdm import tqdm\n\n\n\nclass Settings(object):\n def __init__(self):\n self.vocab_size = 114042\n self.len_sentence = 70\n self.num_epochs = 3 # 在一个num_epochs中,所有训练集数据使用一次\n self.num_classes = 53\n self.cnn_size = 230\n self.num_layers = 1\n self.pos_size = 5\n self.pos_num = 123\n self.word_embedding = 50\n self.keep_prob = 0.5\n self.batch_size = 300 # 每个批次的大小\n self.num_steps = 10000\n self.lr = 0.001\n\n\nclass CNN():\n\n def __init__(self, word_embeddings, setting):\n\n self.vocab_size = setting.vocab_size\n self.len_sentence = len_sentence = setting.len_sentence\n self.num_epochs = setting.num_epochs\n self.num_classes = num_classes = setting.num_classes\n self.cnn_size = setting.cnn_size\n self.num_layers = setting.num_layers\n self.pos_size = setting.pos_size\n self.pos_num = setting.pos_num\n self.word_embedding = setting.word_embedding\n self.lr = setting.lr\n\n\n # 使用这些参数获取现有变量或创建一个新变量。\n # 定义tf中用到的变量\n word_embedding = tf.get_variable(initializer=word_embeddings, name='word_embedding')\n pos1_embedding = tf.get_variable('pos1_embedding', [self.pos_num, self.pos_size])\n pos2_embedding = tf.get_variable('pos2_embedding', [self.pos_num, self.pos_size])\n # relation_embedding = tf.get_variable('relation_embedding', [self.num_classes, self.cnn_size])\n\n # placeholder和feed_dict绑定,使用placeholder是要在运行时再给tf一个输入的值\n # 使用feed_dict在Session.run()时提供输入值。\n self.input_word = tf.placeholder(dtype=tf.int32, shape=[None, len_sentence], name='input_word')\n self.input_pos1 = tf.placeholder(dtype=tf.int32, shape=[None, len_sentence], name='input_pos1')\n self.input_pos2 = tf.placeholder(dtype=tf.int32, shape=[None, len_sentence], name='input_pos2')\n self.input_y = tf.placeholder(dtype=tf.float32, shape=[None, num_classes], name='input_y')\n self.keep_prob = tf.placeholder(tf.float32)\n\n # 在word_embedding中找到input_word\n self.input_word_ebd = tf.nn.embedding_lookup(word_embedding, self.input_word)\n self.input_pos1_ebd = tf.nn.embedding_lookup(pos1_embedding, self.input_pos1)\n self.input_pos2_ebd = tf.nn.embedding_lookup(pos2_embedding, self.input_pos2)\n\n print(\"input_word_ebd: \", self.input_word_ebd)\n print(\"input_pos1_ebd: \", self.input_pos1_ebd)\n print(\"input_pos2_ebd: \", self.input_pos2_ebd)\n\n # 将values的列表沿维度“axis”连接起来。\n self.inputs = tf.concat(axis=2, values=[self.input_word_ebd, self.input_pos1_ebd, self.input_pos2_ebd])\n\n print(\"inputs: \", self.inputs)\n\n self.inputs = tf.reshape(self.inputs, [-1, self.len_sentence, self.word_embedding + self.pos_size * 2, 1])\n\n print(\"inputs: \", self.inputs)\n\n '''\n 卷积层\n input:张量,必须是 half、float32、float64 三种类型之一。\n kernel_size: 一个整数,或者包含了两个整数的元组/队列,表示卷积窗的高和宽。\n strides:整数列表。长度是 4 的一维向量。输入的每一维度的滑动窗口步幅。必须与指定格式维度的顺序相同。\n padding:可选字符串为 SAME、VALID。要使用的填充算法的类型。卷积方式\n '''\n self.conv = layers.conv2d(inputs=self.inputs, num_outputs=self.cnn_size, kernel_size=[3, 60], stride=[1, 60],\n padding='SAME')\n print(\"conv: \", self.conv)\n '''\n 最大池化\n kernel_size:长度 >=4 的整数列表。输入张量的每个维度的窗口大小。\n strides:长度 >=4 的整数列表。输入张量的每个维度的滑动窗口的步幅。\n '''\n self.max_pool = layers.max_pool2d(self.conv, kernel_size=[70, 1], stride=[1, 1])\n\n print(\"max_pool: \",self.max_pool)\n # 全连接层\n # 将最大池化后的数据转换结构[[0~cnn_size],[0~cnn_size]]\n self.sentence = tf.reshape(self.max_pool, [-1, self.cnn_size])\n\n print(\"sentence: \", self.sentence)\n # 计算sentence的双曲正切,一般和dropout连用\n self.tanh = tf.nn.tanh(self.sentence)\n # tensorflow里面为了防止或减轻过拟合而使用的函数,它一般用在全连接层\n self.drop = layers.dropout(self.tanh, keep_prob=self.keep_prob)\n\n\n # 添加一个完全连接的层。返回运算结果\n self.outputs = layers.fully_connected(inputs=self.drop, num_outputs=self.num_classes, activation_fn=tf.nn.softmax)\n\n print(\"outputs: \", self.outputs)\n print(\"input_y: \", self.input_y)\n\n '''\n self.y_index = tf.argmax(self.input_y,1,output_type=tf.int32)\n self.indexes = tf.range(0, tf.shape(self.outputs)[0]) * tf.shape(self.outputs)[1] + self.y_index\n self.responsible_outputs = - tf.reduce_mean(tf.log(tf.gather(tf.reshape(self.outputs, [-1]),self.indexes)))\n '''\n # loss 损失函数\n # self.cross_loss = -tf.reduce_mean( tf.log(tf.reduce_sum( self.input_y * self.outputs ,axis=1)))\n\n\n # 交叉损失\n self.cross_loss = -tf.reduce_mean(tf.reduce_sum(self.input_y * tf.log(self.outputs), axis=1))\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=self.outputs, labels=self.input_y\n ))\n # 奖励\n self.reward = tf.log(tf.reduce_sum(self.input_y * self.outputs, axis=1))\n\n self.l2_loss = tf.contrib.layers.apply_regularization(regularizer=tf.contrib.layers.l2_regularizer(0.0001),\n weights_list=tf.trainable_variables())\n\n self.final_loss = self.cross_loss + self.l2_loss\n\n # accuracy\n # arg_max 返回一维张量中最大的值所在的位置\n self.pred = tf.argmax(self.outputs, axis=1)\n self.pred_prob = tf.reduce_max(self.outputs, axis=1)\n\n self.y_label = tf.argmax(self.input_y, axis=1)\n # 先比较pred和y_label,结果存放在一个布尔型列表中\n # 将结果转换为float类型\n # 计算所有float类型结果的平均值\n self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.pred, self.y_label), 'float'))\n\n # minimize loss\n # 使用Adam算法最小化损失\n optimizer = tf.train.AdamOptimizer(self.lr)\n self.train_op = optimizer.minimize(self.final_loss)\n\n # 返回所有用' trainable=True '创建的变量。\n self.tvars = tf.trainable_variables()\n\n # manual update parameters 将tvars中的value值转换为index_holder\n # 先将tvars中的数据,转换为一个placeholder,内容为 index_holder,并添加到tvars_holders中\n self.tvars_holders = []\n for idx, var in enumerate(self.tvars):\n placeholder = tf.placeholder(tf.float32, name=str(idx) + '_holder')\n self.tvars_holders.append(placeholder)\n\n # 枚举tvars将value赋值为tvars_holders的值,添加到update_tvar_holder中\n self.update_tvar_holder = []\n for idx, var in enumerate(self.tvars):\n update_tvar = tf.assign(var, self.tvars_holders[idx])\n self.update_tvar_holder.append(update_tvar)\n\n\ndef train(path_train_word, path_train_pos1, path_train_pos2, path_train_y, save_path):\n print('reading wordembedding')\n # 加载词向量嵌入\n wordembedding = np.load('./data/vec.npy', allow_pickle=True)\n\n print('reading training data')\n\n cnn_train_word = np.load(path_train_word)\n cnn_train_pos1 = np.load(path_train_pos1)\n cnn_train_pos2 = np.load(path_train_pos2)\n cnn_train_y = np.load(path_train_y)\n\n settings = Settings()\n settings.vocab_size = len(wordembedding)\n settings.num_classes = len(cnn_train_y[0])\n settings.num_steps = len(cnn_train_word) // settings.batch_size\n\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n\n # 实现权重的初始化\n initializer = tf.contrib.layers.xavier_initializer()\n with tf.variable_scope(\"model\", reuse=None, initializer=initializer):\n model = CNN(word_embeddings=wordembedding, setting=settings)\n\n # 运行tf并初始化所有的变量\n sess.run(tf.global_variables_initializer())\n # 构造函数用于保存和恢复变量,也可以用于保存model\n # saver = tf.train.Saver()\n # saver.restore(sess,save_path=save_path)\n for epoch in range(1, settings.num_epochs + 1):\n\n # 进度条\n bar = tqdm(range(settings.num_steps), desc='epoch {}, loss=0.000000, accuracy=0.000000'.format(epoch))\n\n for _ in bar:\n # 在cnn_train_y中随机选择batch_size个唯一随机元素。\n sample_list = random.sample(range(len(cnn_train_y)), settings.batch_size)\n # 同理\n batch_train_word = [cnn_train_word[x] for x in sample_list]\n batch_train_pos1 = [cnn_train_pos1[x] for x in sample_list]\n batch_train_pos2 = [cnn_train_pos2[x] for x in sample_list]\n batch_train_y = [cnn_train_y[x] for x in sample_list]\n\n # 将训练数据添加到feed_dict中\n feed_dict = {}\n feed_dict[model.input_word] = batch_train_word\n feed_dict[model.input_pos1] = batch_train_pos1\n feed_dict[model.input_pos2] = batch_train_pos2\n feed_dict[model.input_y] = batch_train_y\n feed_dict[model.keep_prob] = settings.keep_prob\n\n # 训练数据。\n _, loss, cross_loss, cost, accuracy = sess.run([model.train_op, model.final_loss, model.cross_loss, model.cost, model.accuracy],\n feed_dict=feed_dict)\n\n conv = sess.run(model.conv, feed_dict=feed_dict)\n max_pool = sess.run(model.max_pool, feed_dict=feed_dict)\n sentence = sess.run(model.sentence, feed_dict=feed_dict)\n tanh = sess.run(model.tanh, feed_dict=feed_dict)\n drop = sess.run(model.drop, feed_dict=feed_dict)\n outputs = sess.run(model.outputs, feed_dict=feed_dict)\n pred = sess.run(model.pred, feed_dict=feed_dict)\n y_label = sess.run(model.y_label, feed_dict=feed_dict)\n\n # print(\"conv: \", conv[0])\n # print(\"max_pool: \", max_pool[0])\n print(\"sentence[0]: \", sentence[0])\n print(\"sentence: \", sentence)\n # print(\"tanh: \", tanh[0])\n # print(\"drop: \", drop[0])\n # print(\"outputs: \", outputs)\n # print(\"pred: \", pred)\n # print(\"y_label: \", y_label)\n\n\n bar.set_description('epoch {} loss={:.6f} accuracy={:.6f}'.format(epoch, loss, accuracy))\n # print('epoch {} cross_loss={:.6f} cost={:.6f}'.format(epoch, cross_loss, cost))\n # break\n # 训练完保存sess\n # saver.save(sess, save_path=save_path)\n # break\n\n\nclass interaction():\n\n def __init__(self, sess, save_path='model/model.ckpt3'):\n\n self.settings = Settings()\n wordembedding = np.load('./data/vec.npy', allow_pickle=True)\n\n self.sess = sess\n with tf.variable_scope(\"model\"):\n self.model = CNN(word_embeddings=wordembedding, setting=self.settings)\n\n self.saver = tf.train.Saver()\n self.saver.restore(self.sess, save_path)\n\n self.train_word = np.load('./data/train_word.npy', allow_pickle=True)\n self.train_pos1 = np.load('./data/train_pos1.npy', allow_pickle=True)\n self.train_pos2 = np.load('./data/train_pos2.npy', allow_pickle=True)\n self.y_train = np.load('data/train_y.npy', allow_pickle=True)\n\n # 测试数据\n self.testall_word = np.load('./data/testall_word.npy', allow_pickle=True)\n self.testall_pos1 = np.load('./data/testall_pos1.npy', allow_pickle=True)\n self.testall_pos2 = np.load('./data/testall_pos2.npy', allow_pickle=True)\n\n # 计算奖励\n def reward(self, batch_test_word, batch_test_pos1, batch_test_pos2, batch_test_y):\n\n feed_dict = {}\n feed_dict[self.model.input_word] = batch_test_word\n feed_dict[self.model.input_pos1] = batch_test_pos1\n feed_dict[self.model.input_pos2] = batch_test_pos2\n feed_dict[self.model.input_y] = batch_test_y\n feed_dict[self.model.keep_prob] = 1\n outputs = (self.sess.run(self.model.reward, feed_dict=feed_dict))\n return (outputs)\n\n # 计算句子的向量嵌入\n def sentence_ebd(self, batch_test_word, batch_test_pos1, batch_test_pos2, batch_test_y):\n feed_dict = {}\n feed_dict[self.model.input_word] = batch_test_word\n feed_dict[self.model.input_pos1] = batch_test_pos1\n feed_dict[self.model.input_pos2] = batch_test_pos2\n feed_dict[self.model.input_y] = batch_test_y\n feed_dict[self.model.keep_prob] = 1\n outputs = self.sess.run(self.model.sentence, feed_dict=feed_dict)\n return (outputs)\n\n # 计算准确率\n def test(self, batch_test_word, batch_test_pos1, batch_test_pos2):\n feed_dict = {}\n feed_dict[self.model.input_word] = batch_test_word\n feed_dict[self.model.input_pos1] = batch_test_pos1\n feed_dict[self.model.input_pos2] = batch_test_pos2\n feed_dict[self.model.keep_prob] = 1\n relation, prob = self.sess.run([self.model.pred, self.model.pred_prob], feed_dict=feed_dict)\n\n return (relation, prob)\n\n def update_cnn(self, update_word, update_pos1, update_pos2, update_y, updaterate):\n\n num_steps = len(update_word) // self.settings.batch_size\n\n with self.sess.as_default():\n\n tvars_old = self.sess.run(self.model.tvars)\n\n for i in tqdm(range(num_steps)):\n batch_word = update_word[i * self.settings.batch_size:(i + 1) * self.settings.batch_size]\n batch_pos1 = update_pos1[i * self.settings.batch_size:(i + 1) * self.settings.batch_size]\n batch_pos2 = update_pos2[i * self.settings.batch_size:(i + 1) * self.settings.batch_size]\n batch_y = update_y[i * self.settings.batch_size:(i + 1) * self.settings.batch_size]\n\n feed_dict = {}\n feed_dict[self.model.input_word] = batch_word\n feed_dict[self.model.input_pos1] = batch_pos1\n feed_dict[self.model.input_pos2] = batch_pos2\n feed_dict[self.model.input_y] = batch_y\n feed_dict[self.model.keep_prob] = self.settings.keep_prob\n # _, loss, accuracy = sess.run([self.model.train_op,self.model.final_loss, self.model.accuracy], feed_dict=feed_dict)\n self.sess.run(self.model.train_op, feed_dict=feed_dict)\n\n # get tvars_new\n tvars_new = self.sess.run(self.model.tvars)\n\n # update old variables of the target network\n tvars_update = self.sess.run(self.model.tvars)\n for index, var in enumerate(tvars_update):\n tvars_update[index] = updaterate * tvars_new[index] + (1 - updaterate) * tvars_old[index]\n\n feed_dict = dictionary = dict(zip(self.model.tvars_holders, tvars_update))\n self.sess.run(self.model.update_tvar_holder, feed_dict)\n\n # 计算每个关系的准确率\n def produce_ac(self):\n\n testall_word = self.testall_word\n testall_pos1 = self.testall_pos1\n testall_pos2 = self.testall_pos2\n dict_ac={}\n len_batch = len(testall_word)\n\n with self.sess.as_default():\n for batch in tqdm(range(len_batch)):\n batch_word = testall_word[batch]\n batch_pos1 = testall_pos1[batch]\n batch_pos2 = testall_pos2[batch]\n\n (tmp_relation, tmp_prob) = self.test(batch_word, batch_pos1, batch_pos2)\n tmp_prob=list(tmp_prob)\n tmp_relation=list(tmp_relation)\n dict_ac.setdefault(tmp_relation[0],[]).append(tmp_prob[0])\n\n for k,v in dict_ac.items():\n dict_ac[k]=np.mean(np.array(v))\n\n return dict_ac\n\n def produce_new_embedding(self):\n\n # produce reward sentence_ebd average_reward\n train_word = self.train_word\n train_pos1 = self.train_pos1\n train_pos2 = self.train_pos2\n y_train = self.y_train\n all_sentence_ebd = []\n all_reward = []\n all_reward_list = []\n len_batch = len(train_word)\n\n with self.sess.as_default():\n for batch in tqdm(range(len_batch)):\n batch_word = train_word[batch]\n batch_pos1 = train_pos1[batch]\n batch_pos2 = train_pos2[batch]\n # batch_y = train_y[batch]\n batch_y = [y_train[batch] for x in range(len(batch_word))]\n\n tmp_sentence_ebd = self.sentence_ebd(batch_word, batch_pos1, batch_pos2, batch_y)\n tmp_reward = self.reward(batch_word, batch_pos1, batch_pos2, batch_y)\n\n all_sentence_ebd.append(tmp_sentence_ebd)\n all_reward.append(tmp_reward)\n all_reward_list += list(tmp_reward)\n\n all_reward_list = np.array(all_reward_list)\n average_reward = np.mean(all_reward_list)\n average_reward = np.array(average_reward)\n\n all_sentence_ebd = np.array(all_sentence_ebd)\n all_reward = np.array(all_reward)\n\n return average_reward, all_sentence_ebd, all_reward\n\n def save_cnnmodel(self, save_path):\n with self.sess.as_default():\n self.saver.save(self.sess, save_path=save_path)\n\n def tvars(self):\n with self.sess.as_default():\n tvars = self.sess.run(self.model.tvars)\n return tvars\n\n def update_tvars(self, tvars_update):\n with self.sess.as_default():\n feed_dict = dictionary = dict(zip(self.model.tvars_holders, tvars_update))\n self.sess.run(self.model.update_tvar_holder, feed_dict)\n\n\n# produce reward sentence_ebd average_reward\ndef produce_rldata(save_path):\n with tf.Graph().as_default():\n sess = tf.Session()\n with sess.as_default():\n # start = time.time()\n interact = interaction(sess, save_path)\n average_reward, all_sentence_ebd, all_reward = interact.produce_new_embedding()\n\n dict_ac = interact.produce_ac()\n\n np.save('data/average_reward.npy', average_reward)\n np.save('data/all_sentence_ebd.npy', all_sentence_ebd)\n np.save('data/all_reward.npy', all_reward)\n\n print(average_reward)\n print(dict_ac)\n\n\nif __name__ == '__main__':\n # train model\n print('train model')\n train('cnndata/cnn_train_word.npy', 'cnndata/cnn_train_pos1.npy', 'cnndata/cnn_train_pos2.npy',\n 'cnndata/cnn_train_y.npy', 'model/origin_cnn_model.ckpt')\n\n # produce reward sentence_ebd average_reward for rlmodel\n print('produce reward sentence_ebd average_reward for rlmodel')\n # produce_rldata(save_path='model/origin_cnn_model.ckpt')\n\n\n\n\n\n","sub_path":"cnnmodel.py","file_name":"cnnmodel.py","file_ext":"py","file_size_in_byte":19813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"96678384","text":"import json\nfrom conf import setting\nfrom common.logger import log\n\n\ndef readJson(filepath):\n '''获取json数据'''\n try:\n with open(filepath,'r') as f :\n data = json.load(f) #loads需要f.read()\n return data\n except Exception as e:\n log.error(e)\n\ndef writeJson(filepath,data):\n try:\n with open(filepath, 'w') as f:\n f.seek(0) # 因为是追加方式打开,默认偏移量再最后面,调整到开头\n dta = json.dumps(data)\n f.write(dta)\n except Exception as e:\n log.error(\"写入JSON前打开文件失败!\")","sub_path":"hsq_InterfaceTest/common/operationJson.py","file_name":"operationJson.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"312047842","text":"import napari\nimport numpy as np\nfrom pathlib import Path\nfrom napari.qt.threading import thread_worker\nfrom qtpy import QtCore\n\nfrom qtpy.QtWidgets import (\n QLabel,\n QFileDialog,\n QGridLayout,\n QGroupBox,\n QWidget,\n)\n\nfrom bg_atlasapi import BrainGlobeAtlas\n\nfrom brainreg_segment.paths import Paths\n\nfrom brainreg_segment.regions.IO import (\n save_label_layers,\n export_label_layers,\n)\n\nfrom brainreg_segment.tracks.IO import save_track_layers, export_splines\n\nfrom brainreg_segment.atlas.utils import (\n get_available_atlases,\n structure_from_viewer,\n)\nfrom brainreg_segment.layout.utils import display_warning\n\n# LAYOUT HELPERS ################################################################################\n\n# from brainreg_segment.layout.utils import (\n# disable_napari_key_bindings,\n# disable_napari_btns,\n# overwrite_napari_roll,\n# )\nfrom brainreg_segment.layout.gui_constants import (\n WINDOW_HEIGHT,\n WINDOW_WIDTH,\n COLUMN_WIDTH,\n SEGM_METHODS_PANEL_ALIGN,\n LOADING_PANEL_ALIGN,\n BOUNDARIES_STRING,\n TRACK_FILE_EXT,\n DISPLAY_REGION_INFO,\n)\n\nfrom brainreg_segment.layout.gui_elements import (\n add_button,\n add_combobox,\n)\n\n# SEGMENTATION ################################################################################\nfrom brainreg_segment.segmentation_panels.regions import RegionSeg\nfrom brainreg_segment.segmentation_panels.tracks import TrackSeg\n\n\nclass SegmentationWidget(QWidget):\n def __init__(\n self,\n viewer: napari.viewer.Viewer,\n boundaries_string=BOUNDARIES_STRING,\n ):\n super(SegmentationWidget, self).__init__()\n\n # general variables\n self.viewer = viewer\n\n # Disable / overwrite napari viewer functions\n # that either do not make sense or should be avoided by the user\n # removed for now, to make sure plugin\n # disable_napari_btns(self.viewer)\n # disable_napari_key_bindings()\n # overwrite_napari_roll(self.viewer)\n\n # Main layers\n self.base_layer = [] # Contains registered brain / reference brain\n self.atlas_layer = [] # Contains annotations / region information\n\n # Other data\n self.hemispheres_data = []\n\n # Track variables\n self.track_layers = []\n\n # Region variables\n self.label_layers = []\n\n # Atlas variables\n self.current_atlas_name = \"\"\n self.atlas = None\n\n self.boundaries_string = boundaries_string\n self.directory = \"\"\n # Set up segmentation methods\n self.region_seg = RegionSeg(self)\n self.track_seg = TrackSeg(self)\n\n # Generate main layout\n self.setup_main_layout()\n\n if DISPLAY_REGION_INFO:\n\n @self.viewer.mouse_move_callbacks.append\n def display_region_info(v, event):\n \"\"\"\n Show brain region info on mouse over in status bar on the right\n \"\"\"\n assert self.viewer == v\n if v.dims.ndisplay == 2:\n if len(v.layers) and self.atlas_layer and self.atlas:\n _, _, _, region_info = structure_from_viewer(\n self.viewer.status, self.atlas_layer, self.atlas\n )\n self.viewer.help = region_info\n else:\n self.viewer.help = \"\"\n\n def setup_main_layout(self):\n \"\"\"\n Construct main layout of widget\n \"\"\"\n self.layout = QGridLayout()\n self.layout.setContentsMargins(10, 10, 10, 10)\n self.layout.setAlignment(QtCore.Qt.AlignTop)\n self.layout.setSpacing(4)\n\n # 3 Steps:\n # - Loading panel\n # - Segmentation methods panel\n # -> Individual segmentation methods (which are invisible at first)\n # - Saving panel\n\n self.add_loading_panel(1)\n self.add_segmentation_methods_panel(1)\n self.track_seg.add_track_panel(2) # Track segmentation subpanel\n self.region_seg.add_region_panel(3) # Region segmentation subpanel\n self.add_saving_panel(4)\n\n # Take care of status label\n self.status_label = QLabel()\n self.status_label.setText(\"Ready\")\n self.layout.addWidget(self.status_label, 5, 0)\n\n self.setLayout(self.layout)\n\n # PANELS ###############################################################\n\n def add_segmentation_methods_panel(self, row, column=1):\n \"\"\"\n Segmentation methods chooser panel:\n Toggle visibility of segmentation\n methods\n \"\"\"\n self.toggle_methods_panel = QGroupBox(\"Segmentation\")\n self.toggle_methods_layout = QGridLayout()\n self.toggle_methods_layout.setContentsMargins(10, 10, 10, 10)\n self.toggle_methods_layout.setSpacing(5)\n self.toggle_methods_layout.setAlignment(QtCore.Qt.AlignBottom)\n\n self.show_trackseg_button = add_button(\n \"Track tracing\",\n self.toggle_methods_layout,\n self.track_seg.toggle_track_panel,\n 0,\n 1,\n minimum_width=COLUMN_WIDTH,\n alignment=SEGM_METHODS_PANEL_ALIGN,\n )\n self.show_trackseg_button.setEnabled(False)\n\n self.show_regionseg_button = add_button(\n \"Region segmentation\",\n self.toggle_methods_layout,\n self.region_seg.toggle_region_panel,\n 1,\n 1,\n minimum_width=COLUMN_WIDTH,\n alignment=SEGM_METHODS_PANEL_ALIGN,\n )\n self.show_regionseg_button.setEnabled(False)\n\n self.toggle_methods_layout.setColumnMinimumWidth(1, COLUMN_WIDTH)\n self.toggle_methods_panel.setLayout(self.toggle_methods_layout)\n self.toggle_methods_panel.setVisible(True)\n\n self.layout.addWidget(self.toggle_methods_panel, row, column, 1, 1)\n\n def add_loading_panel(self, row, column=0):\n \"\"\"\n Loading panel:\n - Load project (sample space)\n - Load project (atlas space)\n - Atlas chooser\n \"\"\"\n self.load_data_panel = QGroupBox(\"Load data\")\n self.load_data_layout = QGridLayout()\n self.load_data_layout.setSpacing(15)\n self.load_data_layout.setContentsMargins(10, 10, 10, 10)\n self.load_data_layout.setAlignment(QtCore.Qt.AlignBottom)\n\n self.load_button = add_button(\n \"Load project (sample space)\",\n self.load_data_layout,\n self.load_brainreg_directory_sample,\n 0,\n 0,\n visibility=False,\n minimum_width=COLUMN_WIDTH,\n alignment=LOADING_PANEL_ALIGN,\n )\n\n self.load_button_standard = add_button(\n \"Load project (atlas space)\",\n self.load_data_layout,\n self.load_brainreg_directory_standard,\n 1,\n 0,\n visibility=False,\n minimum_width=COLUMN_WIDTH,\n alignment=LOADING_PANEL_ALIGN,\n )\n\n self.add_atlas_menu(self.load_data_layout)\n\n self.load_data_layout.setColumnMinimumWidth(0, COLUMN_WIDTH)\n self.load_data_panel.setLayout(self.load_data_layout)\n self.load_data_panel.setVisible(True)\n\n self.layout.addWidget(self.load_data_panel, row, column, 1, 1)\n\n # buttons made visible after adding to main widget, preventing them\n # from briefly appearing in a separate window\n self.load_button.setVisible(True)\n self.load_button_standard.setVisible(True)\n\n def add_saving_panel(self, row):\n \"\"\"\n Saving/Export panel\n \"\"\"\n self.save_data_panel = QGroupBox()\n self.save_data_layout = QGridLayout()\n\n self.export_button = add_button(\n \"To brainrender\",\n self.save_data_layout,\n self.export_to_brainrender,\n 0,\n 0,\n visibility=False,\n )\n self.save_button = add_button(\n \"Save\", self.save_data_layout, self.save, 0, 1, visibility=False\n )\n\n self.save_data_layout.setColumnMinimumWidth(1, COLUMN_WIDTH)\n self.save_data_panel.setLayout(self.save_data_layout)\n self.layout.addWidget(self.save_data_panel, row, 0, 1, 2)\n\n self.save_data_panel.setVisible(False)\n\n # ATLAS INTERACTION ####################################################\n\n def add_atlas_menu(self, layout):\n list_of_atlasses = [\"Load atlas\"]\n available_atlases = get_available_atlases()\n for atlas in available_atlases.keys():\n atlas_desc = f\"{atlas} v{available_atlases[atlas]}\"\n list_of_atlasses.append(atlas_desc)\n atlas_menu, _ = add_combobox(\n layout,\n None,\n list_of_atlasses,\n 2,\n 0,\n label_stack=True,\n callback=self.initialise_atlas,\n width=COLUMN_WIDTH,\n )\n\n self.atlas_menu = atlas_menu\n\n def initialise_atlas(self):\n atlas_string = self.atlas_menu.currentText()\n atlas_name = atlas_string.split(\" \")[0].strip()\n if atlas_name != self.current_atlas_name:\n status = self.remove_layers()\n if not status: # Something prevented deletion\n self.reset_atlas_menu()\n return\n else:\n print(f\"{atlas_string} already selected for segmentation.\")\n self.reset_atlas_menu()\n return\n\n # Get / set output directory\n self.set_output_directory()\n if not self.directory:\n self.reset_atlas_menu()\n return\n\n self.current_atlas_name = atlas_name\n # Instantiate atlas layers\n self.load_atlas()\n\n self.directory = self.directory / atlas_name\n self.paths = Paths(self.directory, atlas_space=True)\n\n self.status_label.setText(\"Ready\")\n # Set window title\n # self.viewer.title = f\"Atlas: {self.current_atlas_name}\"\n self.initialise_segmentation_interface()\n # Check / load previous regions and tracks\n self.region_seg.check_saved_region()\n self.track_seg.check_saved_track()\n self.reset_atlas_menu()\n\n def set_output_directory(self):\n self.status_label.setText(\"Loading...\")\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n self.directory = QFileDialog.getExistingDirectory(\n self,\n \"Select output directory\",\n options=options,\n )\n if self.directory != \"\":\n self.directory = Path(self.directory)\n\n def load_atlas(self):\n atlas = BrainGlobeAtlas(self.current_atlas_name)\n self.atlas = atlas\n self.base_layer = self.viewer.add_image(\n self.atlas.reference,\n name=\"Reference\",\n )\n self.atlas_layer = self.viewer.add_labels(\n self.atlas.annotation,\n name=self.atlas.atlas_name,\n blending=\"additive\",\n opacity=0.3,\n visible=False,\n )\n self.standard_space = True\n\n def reset_atlas_menu(self):\n # Reset menu for atlas - show initial description\n self.atlas_menu.blockSignals(True)\n self.atlas_menu.setCurrentIndex(0)\n self.atlas_menu.blockSignals(False)\n\n # BRAINREG INTERACTION #################################################\n\n def load_brainreg_directory_sample(self):\n self.get_brainreg_directory(standard_space=False)\n\n def load_brainreg_directory_standard(self):\n self.get_brainreg_directory(standard_space=True)\n\n def get_brainreg_directory(self, standard_space):\n \"\"\"\n Shows file dialog to choose output directory\n and sets global directory info\n \"\"\"\n if standard_space:\n self.plugin = \"brainreg-standard\"\n self.standard_space = True\n else:\n self.plugin = \"brainglobe-io\"\n self.standard_space = False\n\n self.status_label.setText(\"Loading...\")\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n brainreg_directory = QFileDialog.getExistingDirectory(\n self,\n \"Select brainreg directory\",\n options=options,\n )\n\n if not brainreg_directory:\n return\n\n if self.directory != brainreg_directory:\n status = self.remove_layers()\n if not status:\n return # Something prevented deletion\n self.directory = Path(brainreg_directory)\n else:\n print(f\"{str(brainreg_directory)} already loaded.\")\n return\n\n # Otherwise, proceed loading brainreg dir\n self.load_brainreg_directory()\n\n def load_brainreg_directory(self):\n \"\"\"\n Opens brainreg folder in napari.\n Calls initialise_loaded_data to set up layers / info.\n Then checks for previously loaded data.\n\n \"\"\"\n try:\n self.viewer.open(str(self.directory), plugin=self.plugin)\n self.paths = Paths(\n self.directory,\n standard_space=self.standard_space,\n )\n self.initialise_loaded_data()\n except ValueError:\n print(\n f\"The directory ({self.directory}) does not appear to be \"\n f\"a brainreg directory, please try again.\"\n )\n return\n\n # Check / load previous regions and tracks\n self.region_seg.check_saved_region()\n self.track_seg.check_saved_track()\n\n def initialise_loaded_data(self):\n \"\"\"\n Set up brainreg layers in napari / fill with new data and info\n\n \"\"\"\n try:\n self.viewer.layers.remove(self.boundaries_string)\n except ValueError:\n pass\n\n self.base_layer = self.viewer.layers[\"Registered image\"]\n self.metadata = self.base_layer.metadata\n self.atlas = self.metadata[\"atlas_class\"]\n self.atlas_layer = self.viewer.layers[self.metadata[\"atlas\"]]\n if self.standard_space:\n self.hemispheres_data = self.atlas.hemispheres\n else:\n self.hemispheres_data = self.viewer.layers[\"Hemispheres\"].data\n\n self.initialise_segmentation_interface()\n\n # Set window title\n # self.viewer.title = (\n # f\"Brainreg: {self.metadata['atlas']} ({self.plugin})\"\n # )\n self.status_label.setText(\"Ready\")\n\n # MORE LAYOUT COMPONENTS ###########################################\n\n def initialise_segmentation_interface(self):\n self.reset_variables()\n self.initialise_image_view()\n self.save_data_panel.setVisible(True)\n self.save_button.setVisible(True)\n self.export_button.setVisible(self.standard_space)\n self.show_regionseg_button.setEnabled(True)\n self.show_trackseg_button.setEnabled(True)\n self.status_label.setText(\"Ready\")\n\n def initialise_image_view(self):\n self.set_z_position()\n\n def set_z_position(self):\n midpoint = int(round(len(self.base_layer.data) / 2))\n self.viewer.dims.set_point(0, midpoint)\n\n def reset_variables(self):\n \"\"\"\n Reset atlas scale dependent variables\n - point_size (Track segmentation)\n - spline_size (Track segmentation)\n - brush_size (Region segmentation)\n \"\"\"\n self.mean_voxel_size = int(\n np.sum(self.atlas.resolution) / len(self.atlas.resolution)\n )\n self.track_seg.point_size = (\n self.track_seg.point_size_default / self.mean_voxel_size\n )\n self.track_seg.spline_size = (\n self.track_seg.spline_size_default / self.mean_voxel_size\n )\n self.region_seg.brush_size = (\n self.region_seg.brush_size_default / self.mean_voxel_size\n )\n return\n\n def remove_layers(self):\n \"\"\"\n TODO: This needs work. Runs into an error currently\n when switching from a annotated project to another one\n \"\"\"\n if len(self.viewer.layers) != 0:\n # Check with user if that is really what is wanted\n if self.track_layers or self.label_layers:\n choice = display_warning(\n self,\n \"About to remove layers\",\n \"All layers are about to be deleted. Proceed?\",\n )\n if not choice:\n print('Preventing deletion because user chose \"Cancel\"')\n return False\n\n # Remove old layers\n for layer in list(self.viewer.layers):\n try:\n self.viewer.layers.remove(layer)\n except IndexError: # no idea why this happens\n pass\n\n # There seems to be a napari bug trying to access previously used slider\n # values. Trying to circument for now\n self.viewer.window.qt_viewer.dims._last_used = None\n\n self.track_layers = []\n self.label_layers = []\n return True\n\n def save(self):\n if self.label_layers or self.track_layers:\n choice = display_warning(\n self,\n \"About to save files\",\n \"Existing files will be will be deleted. Proceed?\",\n )\n if choice:\n print(\"Saving\")\n worker = save_all(\n self.paths.regions_directory,\n self.paths.tracks_directory,\n self.label_layers,\n self.track_layers,\n track_file_extension=TRACK_FILE_EXT,\n )\n worker.start()\n else:\n print('Not saving because user chose \"Cancel\" \\n')\n\n def export_to_brainrender(self):\n choice = display_warning(\n self,\n \"About to export files\",\n \"Existing files will be will be deleted. Proceed?\",\n )\n if choice:\n print(\"Exporting\")\n worker = export_all(\n self.paths.regions_directory,\n self.paths.tracks_directory,\n self.label_layers,\n self.track_seg.splines,\n self.track_seg.spline_names,\n self.atlas.resolution[0],\n )\n worker.start()\n else:\n print('Not exporting because user chose \"Cancel\" \\n')\n\n\n@thread_worker\ndef export_all(\n regions_directory,\n tracks_directory,\n label_layers,\n splines,\n spline_names,\n resolution,\n):\n if label_layers:\n export_label_layers(regions_directory, label_layers, resolution)\n\n if splines:\n export_splines(tracks_directory, splines, spline_names, resolution)\n print(\"Finished!\\n\")\n\n\n@thread_worker\ndef save_all(\n regions_directory,\n tracks_directory,\n label_layers,\n points_layers,\n track_file_extension=\".points\",\n):\n\n if label_layers:\n save_label_layers(regions_directory, label_layers)\n\n if points_layers:\n save_track_layers(\n tracks_directory,\n points_layers,\n track_file_extension=track_file_extension,\n )\n print(\"Finished!\\n\")\n\n\ndef main():\n print(\"Loading segmentation GUI.\\n \")\n with napari.gui_qt():\n viewer = napari.Viewer() # title=\"Segmentation GUI\")\n viewer.window.resize(WINDOW_WIDTH, WINDOW_HEIGHT)\n widget = SegmentationWidget(viewer)\n viewer.window.add_dock_widget(widget, name=\"General\", area=\"right\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"brainreg_segment/segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":19672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"322088597","text":"# Lucas Petersen\n# 12 de Fevereiro de 2021\n\nimport tkinter as tk\nimport warnings\nfrom pycadastros import formatCadastro\n\n\nclass EntryCPF:\n def __init__(self):\n pass\n\n\nclass EntryCNPJ:\n def __init__(self):\n pass\n\n\nclass EntryCadastro:\n def __init__(self, root, truebd='#74c454', falsebd='#c7271c', justify=tk.CENTER, borderwidth=3, mask=True,\n update=True, changeBorder=True, highlightcolor='white', **kwargs):\n # TODO -- CONFIG -- criar opção de dar update no resultado ou não (callback)\n # TODO -- CONFIG -- criar opção de mudar a cor da borda ou não\n # TODO -- WIDGET -- criar opção de mask de cpf, mask de cnpj ou a atual, que serve pros dois\n # TODO -- VALIDAÇÃO -- criar opção de fill leading zeros ou não\n # TODO -- VALIDAÇÃO -- Autodetecção (validação por callback) não considera leading zeros ainda\n\n self.textvar = tk.StringVar()\n self.root = root\n self.borderwidth = borderwidth\n self.validate = 'key'\n self.vcmd = (self.root.register(self.validateNumbers), '%S')\n self.updateEntry = self.callback\n self.justify = justify\n self.truebd = truebd\n self.falsebd = falsebd\n self.mask = mask\n self.update = update\n self.changeBorder = changeBorder\n self.highlightcolor = highlightcolor\n\n self.mywidget = tk.Entry(self.root, validate=self.validate, vcmd=self.vcmd, justify=self.justify,\n highlightthickness=self.borderwidth, textvariable=self.textvar,\n highlightcolor=highlightcolor, **kwargs)\n\n self.x = 0\n self.y = 0\n self.width = 0\n self.height = 0\n\n self.textvar.trace('w', lambda name, index, mode, sv=self.textvar: self.updateEntry())\n self.textvar.trace('w', lambda *args: self.characterLimit())\n\n def callback(self):\n self.mywidget.config(highlightcolor=self.falsebd, highlightbackground=self.falsebd)\n self.mywidget.config(selectbackground=self.mywidget.cget('highlightcolor'))\n cad = self.mywidget.get()\n if cad is not None:\n if len(self.mywidget.get().replace(',', '').replace('.', '').replace('/', '').replace('-', '')) >= 11:\n if self.mask:\n cadmasked = self.get(mask=True)\n else:\n cadmasked = self.get(mask=False)\n if cadmasked is not None:\n self.textvar.set(cadmasked)\n self.mywidget.config(vcmd=self.vcmd)\n self.mywidget.icursor('end')\n\n def characterLimit(self):\n lchars = list(str(self.mywidget.get()))\n for lchar in lchars:\n if lchar not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '/', '.']:\n lchars.remove(lchar)\n\n self.textvar.set(''.join(lchars))\n if len(self.mywidget.get()) > 14:\n self.textvar.set(self.mywidget.get()[:-1])\n\n # TODO -- DEBUG -- Entender pq essa função tá esse Warning\n def validateNumbers(self, n):\n if n in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '/', '-']:\n return True\n else:\n return False\n\n def get(self, mask=False, fill=True):\n if mask and not fill:\n warnings.warn(\"'fill' convertido para True por conta de 'mask' estar como True.\")\n self.mywidget.config(highlightcolor=self.truebd, highlightbackground=self.truebd)\n self.mywidget.config(selectbackground=self.mywidget.cget('highlightcolor'))\n\n cadastro = formatCadastro(self.mywidget.get())\n if cadastro is None:\n self.mywidget.config(highlightcolor=self.falsebd, highlightbackground=self.falsebd)\n return None\n\n else:\n self.mywidget.config(highlightcolor=self.truebd, highlightbackground=self.truebd)\n self.mywidget.config(selectbackground=self.mywidget.cget('highlightcolor'))\n if mask:\n return cadastro[2]\n\n else:\n if fill:\n return cadastro[1]\n else:\n return cadastro[0]\n\n def getType(self):\n return formatCadastro(self.mywidget.get())[3]\n\n def isValid(self):\n return formatCadastro(self.mywidget.get()) is not None\n\n def isCPF(self):\n try:\n cadastro = formatCadastro(self.mywidget.get())[3]\n except:\n return False\n return cadastro == 'CPF'\n\n def isCNPJ(self):\n try:\n cadastro = formatCadastro(self.mywidget.get())[3]\n except:\n return False\n return cadastro == 'CNPJ'\n\n def place(self, **kwargs):\n self.mywidget.place(**kwargs)\n\n def pack(self, **kwargs):\n self.mywidget.pack(**kwargs)\n\n def grid(self, **kwargs):\n self.mywidget.grid(**kwargs)\n\n\nwinW, winH = 600, 300\nw, h = 270, 40\nwindow = tk.Tk()\nwindow.geometry(f'{winW}x{winH}')\nwindow.configure(background='#051d60')\n\nentry = EntryCadastro(window, font=('Century Gothic', '18'), bg='#051d60', borderwidth=1, relief=tk.FLAT, fg='white')\nentry.place(x=(winW-w)//2, y=(winH-h)//2, h=43)\n\nentry2 = EntryCadastro(window, font=('Roboto Medium', '14'), mask=False)\nentry2.place(x=(winW-w)//2, y=(winH-h)//2+h+10, width=w, height=h)\n\n\ndef myf():\n print(entry.isValid())\n print(entry.isCPF())\n print(entry.isCNPJ())\n\n\ndef myf2():\n print(entry2.get(mask=True))\n\n\nb = tk.Button(window, command=myf, text='entry de cima')\nb.place(x=0, y=0, width=100, height=30)\n\nb2 = tk.Button(window, command=myf2, text='entry de baixo')\nb2.place(x=0, y=40, width=100, height=30)\n\nwindow.mainloop()\n","sub_path":"newEntry.py","file_name":"newEntry.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"621407811","text":"import os.path\r\nfrom os import path\r\nimport sys\r\nimport socket\r\nfrom sys import argv\r\nfrom pathlib import Path\r\nfrom _thread import *\r\n\r\nlist_peer = {}\r\nmaster_DB = {}\r\nport_DB = {}\r\n\r\nclass Constants:\r\n LIST = \"LIST\"\r\n NAME = \"NAME\"\r\n REQUEST = \"REQUEST\"\r\n DATA = \"DATA\"\r\n REGISTER = \"REGISTER\"\r\n PEER = \"PEER\"\r\n CLOSE = \"CLOSE\"\r\n BRACE_OPEN = \"[\"\r\n CONNECTION_ESTABLISHED = \"] connection established from \" \r\n PEER_LIST = \"[Owner] Peer list:\" \r\n PEER_U_D = \"[Owner] Transmitting Upload/Download peers\" \r\n OWNER_UP_RUN = \"[Owner] Owner is up and running:\" \r\n OWNER_GETS_MESSAGE = \"[Owner] gets message (\" \r\n FROM = \") from \" \r\n ERROR_OCCURED = \"Error Occurred\" \r\n FILE_OWNER = \"File Owner\" \r\n WAITING_PEER = \" is waiting for peers...\"\r\n CONFIG = \"CONFIG\" \r\n OWNER_DIR = \"OwnerDir\" \r\n OWNER_DIR_1 = \"OwnerDir/\" \r\n BLOCK = \"Block -->\" \r\n BYTES = \" bytes\" \r\n OWNER_TOTAL = \"[Owner] Total \" \r\n BLOCKS = \" Blocks\" \r\n EQUALS = \" = \" \r\n SPACE = \" \" \r\n\r\n\r\n# This class contains all the methods required by the File Owner.\r\nclass OwnerProcess:\r\n # protected ObjectOutputStream object_output_stream\r\n # protected ObjectInputStream input_stream\r\n peer_name = 0\r\n _current_block = {}\r\n file_name = \"\"\r\n peer_id = 0\r\n port = 0\r\n\r\n # Creates the owner process that communicates with peers for all the transactions\r\n # file chunks\r\n # socket class that accepts connections from peer clients\r\n # ObjectOutputStream that writes to the specified OutputStream\r\n # deserialize\r\n\r\n def __init__(self, block, file_name, con, addr, peer_port, thread_number, peer_id, port):\r\n # print(\"Inside init of OwnerProcess\")\r\n self._current_block = block\r\n self.file_name = file_name\r\n self.con = con\r\n self.addr = addr\r\n self.clientId = peer_port\r\n self.peer_name = thread_number\r\n self.peer_id = peer_id\r\n self.port= port\r\n print(Constants.BRACE_OPEN + \"Thread-\" + str(self.peer_name) + Constants.CONNECTION_ESTABLISHED + str(addr[1]))\r\n\r\n # Communicates with peer for transferring messages\r\n # msg message to be transferred\r\n\r\n def transferMessageToPeer(self, msg):\r\n try:\r\n self.con.send(msg.encode())\r\n except:\r\n print(\"Exception in transferMessageToPeer function\")\r\n\r\n _clientId = -1\r\n\r\n # sends reponse to every peer\r\n\r\n # message message to be transferred\r\n # x\r\n\r\n def __replyToIndividualPeerRequest(self,message, x):\r\n if message == Constants.LIST:\r\n self.__performListOperation()\r\n elif message == Constants.NAME:\r\n print(self.file_name)\r\n self.transferMessageToPeer(str(self.file_name))\r\n elif message == Constants.REQUEST:\r\n self.__performRequestOperation(x)\r\n elif message == Constants.DATA:\r\n x = int(self.con.recv(1024).decode())\r\n chunk = self.con.recv(1024)\r\n elif message == Constants.REGISTER:\r\n self.__performRegisterOperation()\r\n elif message == Constants.PEER:\r\n self.__performPeerOperation()\r\n elif message == Constants.CLOSE:\r\n self.__performCloseOperation()\r\n\r\n # List all the blocks\r\n\r\n def __performListOperation(self):\r\n y = len(self._current_block)\r\n arrayList = []\r\n for i in range(0, y):\r\n if i in self._current_block.keys():\r\n arrayList.append(i)\r\n\r\n arrayList = str(arrayList)\r\n arrayList = arrayList.encode()\r\n self.con.send(arrayList)\r\n\r\n\r\n # sends download and upload neighbour to individual peer\r\n\r\n def __performPeerOperation(self):\r\n print(Constants.PEER_LIST)\r\n self.con.send((\"abc\").encode())\r\n peer_id = self.con.recv(1024)\r\n for peer in list_peer.keys():\r\n print(peer , \" \")\r\n\r\n self.con.send((\"abc\").encode())\r\n peer_port = int(self.con.recv(1024).decode())\r\n self.con.send((\"abc\").encode())\r\n download_port = int(self.con.recv(1024).decode())\r\n print(peer_port , \" \" , download_port)\r\n print(Constants.PEER_U_D)\r\n self.con.send(str(list_peer).encode())\r\n self.con.recv(1024)\r\n download_neighbor_id=0\r\n if download_port in master_DB.keys():\r\n download_neighbor_id = master_DB[download_port]\r\n self.transferMessageToPeer(str(download_neighbor_id))\r\n self.con.recv(1024)\r\n upload_neighbor_id = self.getUploadNeighbor(peer_port)\r\n self.transferMessageToPeer(str(upload_neighbor_id))\r\n\r\n\r\n # Gets the upload neighbor of a peer\r\n def getUploadNeighbor(self, peer_port):\r\n upload_neighbor_id = 0\r\n for i in port_DB.keys():\r\n if port_DB[i].getDownload_port() == peer_port:\r\n peer_id = port_DB[i].getPeer_port()\r\n upload_neighbor_id = master_DB[peer_id]\r\n break\r\n return upload_neighbor_id\r\n\r\n def __performCloseOperation(self):\r\n self.con.close()\r\n list_peer.pop(self.clientId)\r\n\r\n def __performRequestOperation(self,x):\r\n self.con.send(bytes(\"yashwant\", 'utf-8'))\r\n x = int(self.con.recv(1024).decode())\r\n self.transferMessageToPeer(str(x))\r\n self.con.recv(1024).decode()\r\n self.con.send(self._current_block[x])\r\n\r\n\r\n def __performRegisterOperation(self):\r\n peer = self.peer_id\r\n list_peer[self.peer_id] = self.port\r\n print(peer)\r\n print(list_peer)\r\n port = self.port\r\n print(port)\r\n self.transferMessageToPeer(str(peer))\r\n self.con.recv(1024).decode()\r\n self.transferMessageToPeer(str(port))\r\n\r\n def __initiate_run(self):\r\n print(Constants.OWNER_UP_RUN)\r\n input_from_peer = \"\"\r\n while True:\r\n try:\r\n input_from_peer = self.con.recv(1024)\r\n break\r\n except:\r\n print(\"Exception at __initiate_run() in OwnerProcess class\")\r\n exit()\r\n break\r\n\r\n msg = str(input_from_peer.decode())\r\n print(Constants.OWNER_GETS_MESSAGE + msg + Constants.FROM + str(self.clientId))\r\n return msg\r\n\r\n\r\n # If this thread was constructed using a separate\r\n # run object, then that\r\n # objects method is called\r\n def run(self):\r\n # print(\"Hello\")\r\n while True:\r\n # try:\r\n message = self.__initiate_run()\r\n print(Constants.OWNER_GETS_MESSAGE + message + Constants.FROM + str(self.clientId))\r\n x = -1\r\n self.__replyToIndividualPeerRequest(message, x)\r\n # except:\r\n # print(Constants.ERROR_OCCURED)\r\n # print(\"Error in run() function in OwnerProcess class\")\r\n # list_peer.pop(self.clientId)\r\n # return\r\n\r\n\r\n# Class maintaining download and upload ports of different peers\r\nclass PortDB:\r\n __peer_port = 0\r\n __download_port = 0\r\n\r\n def __init__(self, peer_port, download_port):\r\n self.__peer_port = peer_port\r\n self.__download_port = download_port\r\n\r\n def getDownload_port(self):\r\n return self.__download_port\r\n\r\n def getPeer_port(self):\r\n return self.__peer_port\r\n\r\n\r\n\r\n\r\n# Class containing all the methods required by a FileOwner.\r\nclass FileOwner:\r\n thread_number = -1\r\n __file_name = \"\"\r\n __owner_port = 0\r\n # ServerSocket = socket.socket()\r\n ServerSocket=socket.socket()\r\n peer_id = 0\r\n port = 0\r\n\r\n # peer configs\r\n FILE_MAX_SIZE = 1024 * 100\r\n read_buffer_size = 1024\r\n\r\n # chunk_id and chunk\r\n file_block_list = {}\r\n peerName = Constants.FILE_OWNER\r\n\r\n # Creates the FileOwner that distributes the file chunks to different peers.\r\n # _owner_port\r\n # _file_name\r\n\r\n def __init__(self, owner_port, file_name):\r\n # print(\"constructor\")\r\n if file_name != None and path.exists(file_name):\r\n self.__file_name = file_name\r\n\r\n self.__owner_port = int(owner_port)\r\n\r\n try:\r\n # host = socket.gethostname()\r\n host = \"localhost\"\r\n self.ServerSocket.bind((host, self.__owner_port))\r\n self.ServerSocket.listen(5)\r\n except:\r\n print(\"program exited\")\r\n sys.exit(1)\r\n\r\n # Init file chunk list\r\n self.__divideFileIntoChunks()\r\n\r\n # Initiates the file owner process\r\n\r\n def initiateOwner(self):\r\n #try:\r\n while True:\r\n self.thread_number+=1\r\n print(self.peerName + Constants.WAITING_PEER)\r\n con, addr = self.ServerSocket.accept()\r\n print(\"A new connection request has been accepted\")\r\n message_from_client = con.recv(1024).decode()\r\n con.send((\"124\").encode())\r\n print(\"message from client :: \" + message_from_client)\r\n if message_from_client.upper().startswith(Constants.CONFIG):\r\n split_string = message_from_client.split(\" \")\r\n id = int(split_string[1])\r\n peer_port = int(split_string[2])\r\n download_port = int(split_string[3])\r\n self.peer_id = id\r\n self.port = peer_port\r\n self.__createDB(id, peer_port, download_port)\r\n\r\n print(self.__file_name)\r\n op = OwnerProcess(self.file_block_list, self.__file_name, con, addr, self.port, self.thread_number, self.peer_id, self.port)\r\n start_new_thread(op.run,())\r\n\r\n # except:\r\n # print(\"An exception occured\")\r\n\r\n\r\n # creates Master database which stores different peers and their ports.\r\n # id peer id\r\n # peer_port peer port\r\n # download_port port of download neighbour\r\n def __createDB(self, id, peer_port, download_port):\r\n master_DB[peer_port] = id\r\n port_DB[id] = PortDB(peer_port, download_port)\r\n\r\n\r\n def _chunk_file(self, file, extension):\r\n current_chunk_size = 0\r\n current_chunk = 0\r\n print(Constants.BLOCK + str(current_chunk) + Constants.EQUALS + \"102400\" + Constants.BYTES)\r\n location = \"OwnerDir/\" + str(current_chunk)\r\n done_reading = False\r\n while not done_reading:\r\n bfr1=None\r\n with open(f'{location}{extension}.chk', 'ab') as chunk:\r\n while True:\r\n bfr = file.read(self.read_buffer_size)\r\n if bfr1==None:\r\n bfr1=bfr\r\n else:\r\n bfr1+=bfr\r\n if not bfr:\r\n done_reading = True\r\n self.file_block_list[current_chunk] = bfr1\r\n print(str(current_chunk) + \" : \", len(self.file_block_list[current_chunk]))\r\n break\r\n\r\n chunk.write(bfr)\r\n current_chunk_size += len(bfr)\r\n\r\n if current_chunk_size + self.read_buffer_size > self.FILE_MAX_SIZE:\r\n self.file_block_list[current_chunk] = bfr1\r\n print(str(current_chunk) + \" : \", len(self.file_block_list[current_chunk]))\r\n current_chunk += 1\r\n location = \"OwnerDir/\" + str(current_chunk)\r\n current_chunk_size = 0\r\n break\r\n\r\n # Divides the file into various chunks\r\n def __divideFileIntoChunks(self):\r\n try:\r\n sepDir = Constants.OWNER_DIR\r\n sepDir = os.path.join(\"D:\\Work\\ComputerNetwork\\P2P\\FileOwner/\" + sepDir)\r\n if not path.exists(sepDir):\r\n os.mkdir(sepDir)\r\n\r\n p = Path.cwd()\r\n file_to_split = None\r\n for f in p.iterdir():\r\n if f.is_file() and f.name == 'test.pdf':\r\n file_to_split = f\r\n break\r\n\r\n if file_to_split:\r\n with open(file_to_split, 'rb') as file:\r\n self._chunk_file(file, file_to_split.suffix)\r\n\r\n except:\r\n print(\"Exception in divide file into chunks\")\r\n exit(1)\r\n\r\n\r\n # def __testConfig(self):\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n n=len(sys.argv)\r\n # print(n)\r\n owner_port = 0\r\n file_name=\"test.pdf\"\r\n if n==2:\r\n owner_port=sys.argv[1]\r\n print(\"\")\r\n print(\"Owner Port: \" + owner_port + \" File name: \" + file_name)\r\n f1 = FileOwner(owner_port, file_name)\r\n f1.initiateOwner()\r\n # f1.test()\r\n elif(n==1):\r\n print(\"Mention Port number\")\r\n else:\r\n print(\"Only one argument is needed, i.e., Port Number\")","sub_path":"FileOwner/FileOwner.py","file_name":"FileOwner.py","file_ext":"py","file_size_in_byte":12797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"489536670","text":"from __future__ import print_function\n\nimport os\nimport gc\nimport sys\nimport time\nimport traceback\nimport subprocess\nimport importlib\n\nclass ShutdownBus():\n def __init__(self):\n self.restart = False\n self.shutdown = False\n\n def bot_shutdown(self):\n self.restart = False\n self.shutdown = True\n\n def bot_restart(self):\n self.restart = True\n self.shutdown = True\n\n def reset(self):\n self.restart = False\n self.shutdown = False\n\nclass GIT(object):\n @classmethod\n def works(cls):\n try:\n return bool(subprocess.check_output('git --version', shell=True))\n except:\n return False\n\n\nclass PIP(object):\n @classmethod\n def run(cls, command, check_output=False):\n if not cls.works():\n raise RuntimeError(\"Could not import pip.\")\n\n try:\n return PIP.run_python_m(*command.split(), check_output=check_output)\n except subprocess.CalledProcessError as e:\n return e.returncode\n except:\n traceback.print_exc()\n print(\"Error using -m method\")\n\n @classmethod\n def run_python_m(cls, *args, **kwargs):\n check_output = kwargs.pop('check_output', False)\n check = subprocess.check_output if check_output else subprocess.check_call\n return check([sys.executable, '-m', 'pip'] + list(args))\n\n @classmethod\n def run_pip_main(cls, *args, **kwargs):\n import pip\n\n args = list(args)\n check_output = kwargs.pop('check_output', False)\n\n if check_output:\n from io import StringIO\n\n out = StringIO()\n sys.stdout = out\n\n try:\n pip.main(args)\n except:\n traceback.print_exc()\n finally:\n sys.stdout = sys.__stdout__\n\n out.seek(0)\n pipdata = out.read()\n out.close()\n\n print(pipdata)\n return pipdata\n else:\n return pip.main(args)\n\n @classmethod\n def run_install(cls, cmd, quiet=False, check_output=False):\n return cls.run(\"install %s%s\" % ('-q ' if quiet else '', cmd), check_output)\n\n @classmethod\n def run_show(cls, cmd, check_output=False):\n return cls.run(\"show %s\" % cmd, check_output)\n\n @classmethod\n def works(cls):\n try:\n import pip\n return True\n except ImportError:\n return False\n\n @classmethod\n def get_module_version(cls, mod):\n try:\n out = cls.run_show(mod, check_output=True)\n\n if isinstance(out, bytes):\n out = out.decode()\n\n datas = out.replace('\\r\\n', '\\n').split('\\n')\n expectedversion = datas[3]\n\n if expectedversion.startswith('Version: '):\n return expectedversion.split()[1]\n else:\n return [x.split()[1] for x in datas if x.startswith(\"Version: \")][0]\n except:\n pass\n\n\ndef main():\n\n sstate = ShutdownBus()\n\n if not sys.version_info >= (3, 5):\n print(\"[PB] Python 3.5+ is required. This version is %s\" % sys.version.split()[0])\n print(\"Attempting to locate python 3.5...\")\n\n pycom = None\n\n\n if sys.platform.startswith('win'):\n try:\n subprocess.check_output('py -3.5 -c \"exit()\"', shell=True)\n pycom = 'py -3.5'\n except:\n\n try:\n subprocess.check_output('python3 -c \"exit()\"', shell=True)\n pycom = 'python3'\n except:\n pass\n\n if pycom:\n print(\"\\nPython 3.5 found. Re-starting PlasmaBot using: \")\n print(\" %s run.py\\n\" % pycom)\n os.system('start cmd /k %s run.py' % pycom)\n sys.exit(0)\n\n else:\n try:\n pycom = subprocess.check_output(['which', 'python3.5']).strip().decode()\n except:\n pass\n\n if pycom:\n print(\"\\nPython 3.5 found. Re-starting PlasmaBot using: \")\n print(\" %s run.py\\n\" % pycom)\n\n os.execlp(pycom, pycom, 'run.py')\n\n print(\"Please run the bot using Python3.5\")\n input(\"Press ENTER to continue . . .\")\n\n return\n\n import asyncio\n\n tried_requirementstxt = False\n tryagain = True\n\n loops = 0\n max_wait_time = 60\n\n import plasmaBot\n\n while tryagain:\n\n try:\n importlib.reload(plasmaBot)\n\n m = plasmaBot.PlasmaBot(sstate)\n print(\"[PB] Connecting to Discord...\", end='', flush=True)\n m.run()\n\n except (KeyboardInterrupt, SystemExit):\n print(\"\\n[PB] Shutting Down...\\n\\nThanks for using PlasmaBot!\\n--------------------------------------------------------\")\n m.shutdown()\n break\n\n except SyntaxError:\n traceback.print_exc()\n break\n\n except ImportError as e:\n if not tried_requirementstxt:\n tried_requirementstxt = True\n\n # TODO: Better output\n print(e)\n print(\"[PB] Attempting to install PlasmaBot dependencies...\")\n\n err = PIP.run_install('--upgrade -r requirements.txt')\n\n if err:\n print(\"\\nYou should %s to install the PlasmaBot dependencies.\" %\n ['use sudo', 'run as admin'][sys.platform.startswith('win')])\n break\n else:\n print(\"\\nDependencies Installed\\n\")\n else:\n traceback.print_exc()\n print(\"[PB] Unknown ImportError, closing.\")\n break\n\n except Exception as e:\n if hasattr(e, '__module__') and e.__module__ == 'plasmaBot.exceptions':\n if e.__class__.__name__ == 'HelpfulError':\n print(e.message)\n break\n else:\n if (sstate.shutdown is True):\n if sstate.restart is True:\n print(\"\\n[PB] Restarting...\\n\\nThanks for using PlasmaBot!\\n\")\n loops = -1\n sstate.reset()\n\n if m:\n del m\n else:\n print(\"\\n[PB] Shutting Down...\\n\\nThanks for using PlasmaBot!\\n--------------------------------------------------------\")\n break\n else:\n traceback.print_exc()\n\n finally:\n asyncio.set_event_loop(asyncio.new_event_loop())\n loops += 1\n\n print(\"Cleaning up... \", end='')\n gc.collect()\n print(\"Done.\")\n\n sleeptime = min(loops * 2, max_wait_time)\n if sleeptime:\n print(\"Restarting in {} seconds...\".format(loops*2))\n time.sleep(sleeptime)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"498459530","text":"import numpy as np\nimport pickle\nimport os\nfrom datetime import datetime, timedelta\nimport pandas as pd\n# todo: this fxn is duplicated in io_support -- reorganize so it gets a single def that is easily imported where needed\n\nclass InitialModelState:\n\n def __init__(self, total_time, interval_per_day, n_age, n_risk, initial_i, metro_pop):\n\n self.total_time = total_time\n self.interval_per_day = interval_per_day\n self.n_age = n_age\n self.n_risk = n_risk\n self.initial_i = initial_i\n self.metro_pop = metro_pop\n self.start_day = None\n self.offset = None\n\n def initialize(self):\n\n if isinstance(self.initial_i, str):\n if os.path.exists(self.initial_i):\n return self.initialize_from_deterministic()\n else:\n raise ValueError('Initial state is provided as a string that does not map to a valid file path.')\n\n elif isinstance(self.initial_i, np.ndarray):\n return self.initialize_from_start()\n\n elif isinstance(self.initial_i, list):\n return self.initialize_from_start()\n\n else:\n print(type(self.initial_i))\n raise ValueError('Initial conditions provided are not supported.')\n\n def instantaneous_state(self, min_hosp=10):\n\n # todo: implement checks to make sure the deterministic solution read in is actually the one you want\n # todo: for example, is it the right city? the right params?\n # todo: this might require packaging the config with the outputs so a few things can be checked easily after loading this file\n with open(self.initial_i, 'rb') as xp:\n data = pickle.load(xp)\n\n if len(data.c_reduction.values) > 1:\n raise ValueError('Instantaneous states are currently only supported for deterministic runs with fixed contact reduction levels.')\n\n dataset = data.to_dataset('compartment')\n\n # todo: this syntax can replace compartment_stack() where resolution == 'point'\n hosp_slice = dataset['Iy'].sel({\n 'beta0': dataset['beta0'].values.item(),\n 'c_reduction': dataset['c_reduction'].values.item(),\n 'g_rate': 'high',\n 'reopen_trigger': dataset['reopen_trigger'].values.item(),\n 'close_trigger': dataset['close_trigger'].values.item()\n }).sum(dim=['age_group', 'risk_group']).to_dataframe().reset_index()\n\n # assume the first date's HH:MM:SS is always 00:00:00\n hosp_slice_daily = hosp_slice.iloc[::self.interval_per_day, :]\n\n # assumption: single peak in hospitalizations; deterministic sim starts at 1 infected person so the\n # beginning of the time series will always be below the threshold\n threshold_slice = hosp_slice_daily[hosp_slice_daily['Iy'] >= min_hosp]\n start_slice = threshold_slice['time'].min()\n self.offset = timedelta(hours = start_slice.hour,\n minutes = start_slice.minute,\n seconds = start_slice.second,\n microseconds= start_slice.microsecond)\n\n # we don't want to start mid-day because that would require a refactor how how the SEIR model handles dates\n # instead, drop day fraction to begin at zero hours of day \n self.start_day = datetime(start_slice.year, start_slice.month, start_slice.day)\n\n compartment_slices = {i: dataset[i].sel({\n 'beta0': dataset['beta0'].values.item(),\n 'c_reduction': dataset['c_reduction'].values.item(),\n 'g_rate': 'high',\n 'reopen_trigger': dataset['reopen_trigger'].values.item(),\n 'close_trigger': dataset['close_trigger'].values.item(),\n 'time': start_slice,\n 'replicate': 0 # possibly irrelevant for deterministic runs\n }).values for i in data.compartment.values}\n\n return compartment_slices\n\n def initialize_empty(self):\n \"\"\" Make an empty numpy array for each compartment, and return as a dictionary. \"\"\"\n\n compt_s = np.zeros(shape=(self.total_time * self.interval_per_day, self.n_age, self.n_risk)) # (t,a,r)\n compt_e, compt_ia, compt_iy, compt_e2compt_i = compt_s.copy(), compt_s.copy(), compt_s.copy(), compt_s.copy()\n compt_ih, compt_r, compt_e2compt_iy, compt_d = compt_s.copy(), compt_s.copy(), compt_s.copy(), compt_s.copy()\n compt_iy2compt_ih, compt_h2compt_d = compt_s.copy(), compt_s.copy()\n\n return {'S': compt_s, 'E': compt_e, 'Ia': compt_ia, 'Iy': compt_iy, 'E2I': compt_e2compt_i, 'Ih': compt_ih,\n 'R': compt_r, 'E2Iy': compt_e2compt_iy, 'D': compt_d, 'Iy2Ih': compt_iy2compt_ih, 'H2D': compt_h2compt_d}\n\n # todo: make a static method\n def update_initial_cond(self, array, t0_value):\n \"\"\" Update the initial condition of a compartment. \"\"\"\n\n array[0] = t0_value\n\n return array\n\n def initialize_infected_only(self, empty):\n \"\"\" Add infected compartment totals from the config and adjust metro pop accordingly. \"\"\"\n\n empty['S'] = self.update_initial_cond(empty['S'], self.metro_pop - self.initial_i)\n empty['Iy'] = self.update_initial_cond(empty['Iy'], self.initial_i)\n\n return empty\n\n def initialize_from_start(self):\n \"\"\" Return a dictionary of compartments, where only infected susceptible compartment contains non-zero entries \"\"\"\n\n # get empty arrays\n initial_comp_dict = self.initialize_empty()\n\n return self.initialize_infected_only(initial_comp_dict)\n\n def initialize_from_deterministic(self):\n \"\"\" Return a dictionary of compartments, each with initial conditions from a deterministic sim at time zero \"\"\"\n\n # get empty arrays\n initial_comp_dict = self.initialize_empty()\n\n # get start conditions from deterministic model\n deterministic_comp_dict = self.instantaneous_state()\n\n # add deterministic start conditions to the empty arrays\n for key, value in initial_comp_dict.items():\n if key not in deterministic_comp_dict.keys():\n # todo: move this error checking to param parser\n raise ValueError('Initial condition for compartment {} missing from input'.format(key))\n initial_cond = deterministic_comp_dict[key]\n initial_comp_dict[key] = self.update_initial_cond(initial_comp_dict[key], initial_cond)\n\n return initial_comp_dict","sub_path":"src/SEIRcity/get_initial_state.py","file_name":"get_initial_state.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"383681018","text":"# 처음 생각한 아이디어는 포인터 두개를 두고 동시에 움직이면서 Partition을 정확하게 절반씩 나누는 방법을 생각했는데, 이렇게되면 log() Time complexity가 나오지 않음.\n\n# Solution : 포인터 하나만 움직이고, 다른 포인터는 무조건 Partition을 절반으로하는 지점을 찾아서 계산하는 방식을 구현.\n# 포인터 크기를 idx의 두배값으로 잡아, 원소 갯수가 홀수/짝수일때에 대한 예외처리를 줄임 \n# Time : O(log(min(M,N))), Space :O(1) \n\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n n1, n2 = len(nums1), len(nums2)\n if n1 < n2:\n return self.findMedianSortedArrays(nums2, nums1)\n l, r = 0, 2*n2\n \n while l <= r:\n m2 = (l + r)//2\n m1 = n1 + n2 - m2\n \n L1 = nums1[(m1-1)//2] if m1 > 0 else float('-inf')\n R1 = nums1[m1//2] if m1 < 2*n1 else float('inf')\n L2 = nums2[(m2-1)//2] if m2 > 0 else float('-inf')\n R2 = nums2[m2//2] if m2 < 2*n2 else float('inf')\n if R1 < L2:\n r = m2 - 1\n elif R2 < L1:\n l = m2 + 1\n else: # L1와 L2 를 기준으로 오른쪽 파티션보다 값이 작은 절반 원소들로 구성되었음.\n return (max(L1, L2) + min(R1, R2)) / 2\n return -1 \n \n","sub_path":"Leetcode/Median_of_Two_Sorted_Arrays.py","file_name":"Median_of_Two_Sorted_Arrays.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"466196315","text":"\nn = int(input())\n\nwhile(n):\n n -= 1\n inp = input().split()\n seq_ch = []\n rat = inp[1]\n\n for b, i in enumerate(rat):\n if i == '/':\n index_slash = b\n\n p = int(rat[:index_slash])\n q = int(rat[index_slash + 1:])\n\n while(p != 1 or q !=1):\n if p > q:\n seq_ch.insert(0,'right_child')\n p = p - q\n elif p < q:\n seq_ch.insert(0,'left_child')\n q = q - p\n\n index = 1\n while(len(seq_ch)):\n if seq_ch[0] == 'left_child':\n index = 2*index\n seq_ch.pop(0)\n elif seq_ch[0] =='right_child':\n index = 2*index + 1\n seq_ch.pop(0)\n print(inp[0],index)\n\n\n\n","sub_path":"arationalsequence.py","file_name":"arationalsequence.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"317069244","text":"import logging\nfrom functools import partial\n\nimport requests\n\nfrom newsapi.newsapi_auth import NewsApiAuth\nfrom newsapi.constants import COUNTRIES, CATEGORIES, LANGUAGES\n\n\nLOGGER = logging.getLogger()\n\n\nclass NewsApi(object):\n \"\"\"Client for NewsApi.org.\n\n An API Key is required, get a free one at https://newsapi.org.\n\n Future\n ======\n\n In the event of API URL, supported languages, countries, or categories\n changes the defaults can be overridden. To add to these constants, import\n them then append to the list and include in the NewsApiClient instancing.\n \"\"\"\n def __init__(self, api_key: str, api_url='https://newsapi.org/v2/',\n timeout=30, countries=COUNTRIES,\n categories=CATEGORIES, languages=LANGUAGES) -> None:\n self._url = api_url.rstrip('/')\n self._get = partial(requests.get,\n auth=NewsApiAuth(api_key=api_key),\n timeout=timeout)\n self._COUNTRIES = countries\n self._CATEGORIES = categories\n self._LANGUAGES = languages\n\n def _validate_country(self, country: str) -> bool:\n if not country:\n return True\n else:\n assert country in self._COUNTRIES, \"Invalid Country specified.\"\n\n def _validate_language(self, language: str) -> bool:\n if not language:\n return True\n else:\n assert language in self._LANGUAGES, \"Invalid Languaged specified.\"\n\n def _validate_category(self, category: str) -> bool:\n if not category:\n return True\n else:\n assert category in self._CATEGORIES, \"Invalid Category specified.\"\n\n def top_headlines(self, q: list=None, sources: list=None,\n language: str=None, country: str=None,\n category: str=None, page_size: int=None, page: int=None):\n \"\"\"Returns live top and breaking headlines for a country, specific\n category in a country, single source, or multiple sources..\n Optional parameters:\n q - return headlines w/ specified keywords.\n sources - return headlines of news sources! some Valid values are:\n 'bbc-news', 'fox-news', for more use NewsApiClient.sources()\n language - 2-letter ISO-639-1 code of the language you want to get\n headlines for. Valid values are:\n ar de en es fr he it nl no pt ru se\n ud zh\n country: The 2-letter ISO 3166-1 code of the country you want\n to get headlines for.\n Valid values are:\n\n ae ar at au be bg br ca ch cn co\n cu cz de eg fr gb gr hk hu id ie\n il in it jp kr lt lv ma mx my ng\n nl no nz ph pl pt ro rs ru sa se\n sg si sk th tr tw ua us\n\n category - The category you want to get headlines for. Valid values:\n 'business','entertainment','general','health','science'\n ,'sports','technology'\n page_size - The number of results to return per page (request).\n 20 is the default, 100 is the maximum.\n page - Use this to page through the results if the total results found\n is greater than the page size.\n \"\"\"\n self._validate_country(country)\n self._validate_language(language)\n self._validate_category(category)\n # Define Payload\n payload = {}\n payload['q'] = ','.join(q) if sources else None\n payload['sources'] = ','.join(sources) if sources else None\n payload['language'] = language\n payload['country'] = country\n payload['category'] = category\n payload['pageSize'] = page_size\n payload['page'] = page\n\n # Send Request\n LOGGER.debug(\"Params %s\", payload)\n return self._get(self._url + '/top-headlines', params=payload).json()\n\n def everything(self, q: list=None, sources: list=None, domains: list=None,\n from_parameter: str=None, to: str=None, language: str=None,\n sort_by: str=None, page: int=None,\n page_size: int=None) -> str:\n \"\"\"Retrieve all headlines with optional filtering.\n Optional parameters:\n\n language - The 2-letter ISO-639-1 code of the language you want\n to get headlines for.\n Valid values:\n 'ar','de','en','es','fr','he','it','nl','no','pt','ru','se','ud','zh'\n\n country - The 2-letter ISO 3166-1 code of the country you want to get\n headlines from.\n Valid values are:\n\n ae ar at au be bg br ca ch cn co\n cu cz de eg fr gb gr hk hu id ie\n il in it jp kr lt lv ma mx my ng\n nl no nz ph pl pt ro rs ru sa se\n sg si sk th tr tw ua us\n\n category - The category you want to get headlines for!\n Valid values:\n 'business','entertainment','general','health','science','sports',\n 'technology'\n \"\"\"\n self._validate_language(language)\n\n # Define Payload\n payload = {}\n payload['q'] = ','.join(q) if q else None\n payload['sources'] = ','.join(sources) if sources else None\n payload['domains'] = ','.join(domains) if domains else None\n payload['from'] = from_parameter\n payload['to'] = to\n payload['language'] = ','.join(language) if language else None\n payload['sortBy'] = sort_by\n payload['page'] = page\n payload['pageSize'] = page_size\n\n # Send Request\n LOGGER.debug(\"Params %s\", payload)\n return self._get(self._url + '/everything', params=payload).json()\n\n def sources(self, category: str=None, language: str=None,\n country: str=None) -> str:\n \"\"\"Retrieve list of source names optionally filtering by category and\n language.\n \"\"\"\n self._validate_country(country)\n self._validate_language(language)\n self._validate_category(category)\n\n # Define Payload\n payload = {}\n payload['category'] = category\n payload['language'] = language\n payload['country'] = country\n\n # Send Request\n LOGGER.debug(\"Params %s\", payload)\n return self._get(self._url + '/sources', params=payload).json()\n","sub_path":"newsapi/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"12422247","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom PIL import Image\nimport os\nimport sys\nimport time\nimport subprocess\nimport shutil\n\nfrom common import macro\nfrom common import utils\n\n\ndef backupSmallImages(path):\n bpath = os.path.join(path, macro.BACKUP_NAME)\n for fname in os.listdir(path):\n filename = os.path.join(path, fname)\n if not utils.isImage(filename):\n continue\n with Image.open(filename) as img:\n width = img.width\n height = img.height\n if width < macro.STAND_WIDTH and height < macro.STAND_HEIGHT:\n os.makedirs(bpath, exist_ok=True)\n shutil.move(filename, os.path.join(bpath, fname))\n\n\ndef filterUpscaledImages(path):\n bpath = os.path.join(path, macro.BACKUP_NAME)\n tpath = os.path.join(path, macro.TMP_NAME)\n if not os.path.exists(bpath) or not os.path.exists(tpath):\n return\n largeImages = os.listdir(tpath)\n for damagedImage in largeImages[-3:]:\n os.remove(os.path.join(tpath, damagedImage))\n applyLargeImages(path)\n largeImages = largeImages[:-3]\n\n for largeImage in largeImages:\n fname, _ = os.path.splitext(largeImage)\n os.remove(os.path.join(bpath, fname))\n\n\ndef applyLargeImages(path):\n tpath = os.path.join(path, macro.TMP_NAME)\n if not os.path.exists(tpath):\n return\n for fname in os.listdir(tpath):\n filename = os.path.join(tpath, fname)\n originalName, extend = os.path.splitext(fname)\n rawName, _ = os.path.splitext(originalName)\n os.rename(filename, os.path.join(path, rawName + extend))\n\n\ndef clear(path):\n applyLargeImages(path)\n bpath = os.path.join(path, macro.BACKUP_NAME)\n tpath = os.path.join(path, macro.TMP_NAME)\n utils.remove(bpath)\n utils.remove(tpath)\n\n\ndef upscaleImages(path):\n if not sys.platform.startswith('win'):\n return\n\n backupSmallImages(path)\n filterUpscaledImages(path)\n\n bpath = os.path.join(path, macro.BACKUP_NAME)\n tasks = os.listdir(bpath) if os.path.exists(bpath) else []\n if not tasks:\n clear(path)\n return\n\n tpath = os.path.join(path, macro.TMP_NAME)\n os.makedirs(tpath, exist_ok=True)\n\n waifu2xPath = os.path.join('tools', 'waifu2x-ncnn-vulkan')\n cmd = [\n os.path.join(waifu2xPath, 'waifu2x-ncnn-vulkan.exe'), '-t', '64', '-i',\n bpath, '-o', tpath\n ]\n p = subprocess.Popen(cmd, cwd=waifu2xPath)\n\n yield len(tasks)\n\n previsouNum = 0\n while previsouNum < len(tasks):\n time.sleep(5) # second\n finishNum = len(os.listdir(tpath))\n for index in range(previsouNum, finishNum):\n yield 'upscaling: ' + os.path.join(path, tasks[index])\n previsouNum = finishNum\n\n p.wait()\n\n clear(path)\n","sub_path":"tools/upscaler.py","file_name":"upscaler.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"139912517","text":"#main.py\n#Copyright (c) 2020 Rachel Lea Ballantyne Draelos\n\n#MIT License\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#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 all\n#copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#SOFTWARE\n\nimport os\nimport copy\nimport pickle\nimport datetime\nimport pandas as pd\nimport numpy as np\n\n#from sentence_classifier import ClassifySentences\nfrom sentence_rules import *\nimport term_search\nimport visualizations\n\ndef run_SARLE_Rules_demo():\n #SARLE-Rules\n #Apply rule-based methods. There are 3 options: 'duke_ct' applies the rules\n #developed for CT scans to the CXR data, just for demo purposes since the\n #CT data could not be made public. 'cxr_amb_neg' applies the rules\n #developed for chest x-rays that consider ambiguous findings negative.\n #'cxr_amb_pos' applies the rules developed for chest x-rays that consider\n #ambiguous findings positive.\n #Here we'll just apply all the rule based methods in sequence,\n #to demo all of them:\n for rules_to_use in ['duke_ct', 'cxr_amb_neg', 'cxr_amb_pos']:\n generate_labels(method='rules',rules_to_use=rules_to_use)\n\ndef run_SARLE_Hybrid_demo():\n #SARLE-Hybrid\n #Apply hybrid approach where the Fasttext classifier is used to distinguish\n #normal and abnormal sentences before the term search.\n #Note that Fasttext is only available on Linux.\n generate_labels(method='hybrid', rules_to_use='')\n \ndef generate_labels(method, rules_to_use):\n \"\"\"Generate labels for the radiology reports using the specified , either\n 'hybrid' for a Fasttext sentence classifier followed by the term search, or\n 'rules' for a rule-based phrase classifier followed by the term search\"\"\"\n assert method in ['hybrid','rules']\n assert rules_to_use in ['duke_ct', 'cxr_amb_neg', 'cxr_amb_pos','']\n if method=='hybrid': assert rules_to_use==''\n \n #Note that to run on CT data, dataset = 'duke_ct'. However CT data is\n #not public, so 'openi_cxr' is the only dataset option here.\n dataset = 'openi_cxr'\n \n #For the openi_cxr data set, there is no 'predict set'\n run_predict=False\n #For the Duke CT data, the predict set consists of the many thousands of\n #reports on which we need to apply the labeler to get a volume ground truth.\n \n #Make results directory\n if not os.path.isdir('results'):\n os.mkdir('results')\n if len(rules_to_use)>0:\n results_dir = os.path.join('results',datetime.datetime.today().strftime('%Y-%m-%d')+'_'+dataset+'_'+method+'_'+rules_to_use)\n else:\n results_dir = os.path.join('results',datetime.datetime.today().strftime('%Y-%m-%d')+'_'+dataset+'_'+method)\n if not os.path.isdir(results_dir):\n os.mkdir(results_dir)\n \n #Extracting Abnormal Sentences (Fasttext) or Abnormal Phrases (Rules):\n if method == 'hybrid': #Sentence Classifier, Fasttext approach\n sent_class_dir = os.path.join(results_dir, '0_sentences')\n if not os.path.isdir(sent_class_dir):\n os.mkdir(sent_class_dir)\n #Safra Fasttext \n #First, just get results to report (but not to use downstream):\n ClassifySentences(dataset,sent_class_dir,'trainfilt_testfilt').run_all()\n ClassifySentences(dataset,sent_class_dir,'trainall_testfilt').run_all()\n #Now get results to report AND use downstream:\n m = ClassifySentences(dataset,sent_class_dir,'trainall_testall')\n m.run_all()\n elif method == 'rules': #Rule-based approach\n m = ApplyRules(dataset, rules_to_use)\n m.run_all()\n \n #Term Search\n term_search_dir = os.path.join(results_dir, '1_term_search')\n if not os.path.isdir(term_search_dir):\n os.mkdir(term_search_dir)\n term_search.RadLabel(dataset, term_search_dir, 'train', m.train_merged)\n term_search.RadLabel(dataset, term_search_dir, 'test', m.test_merged)\n if run_predict:\n term_search.RadLabel(dataset, term_search_dir, 'predict', m.predict_merged)\n if dataset == 'duke_ct' and run_predict is True:\n term_search.combine_imgtrain_files(term_search_dir)\n \n #Visualizations\n generate_visualizations(dataset, results_dir)\n print('Done')\n\ndef generate_visualizations(dataset, results_dir):\n \"\"\"Make visualizations that summarize the extracted labels\"\"\"\n #Results dirs for visualizations\n viz_dir = os.path.join(results_dir, '2_visualizations')\n if not os.path.isdir(viz_dir):\n os.mkdir(viz_dir)\n #Sentence Histograms for the notetrain set only\n visualizations.RepeatedSentenceHistograms(dataset, viz_dir)\n \nif __name__=='__main__':\n run_SARLE_Rules_demo()\n #run_SARLE_Hybrid_demo()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"386458365","text":"from abc import ABCMeta, abstractmethod\nimport unittest\n\n\nclass StrikeError(Exception):\n def __str__(self):\n return 'Некорректные данные. Strike может быть только первым броском фрейма'\n\n\nclass SpareError(Exception):\n def __str__(self):\n return 'Некорректные данные. Spare может быть только вторым броском фрейма'\n\n\nclass FrameCountError(Exception):\n def __str__(self):\n return 'Игра состоит более чем из 10 фреймов'\n\n\nclass TotalScoreError(Exception):\n def __str__(self):\n return 'Некорректные данные. Сумма двух бросков не может превышать 10 очков'\n\n\nclass BadStringError(Exception):\n def __init__(self, string):\n super().__init__()\n self.string = string\n\n def __str__(self):\n return f'Некорректный символ в данных {self.string}. Допустимо использовать Цифры, \\\"-\\\", \\\"/\\\", \\\"Х\\\"'\n\n\nclass UnfinishedFrameWarning(Exception):\n\n def __str__(self):\n return 'Игра закончена на недоигранном фрейме'\n\n\nclass NoSpareWarning(Exception):\n def __init__(self, prev_score, score):\n super().__init__()\n self.prev_score = prev_score\n self.score = score\n\n def __str__(self):\n return f'Некорректные данные. Записано {self.prev_score}{self.score}, ожидается {self.prev_score}/'\n\n\nclass State(metaclass=ABCMeta):\n\n @abstractmethod\n def throw_calculation(self, string, prev_score, frame_count, game_result, string_count, international):\n \"\"\"Расчет очков\"\"\"\n\n\nclass FirstThrow(State):\n def throw_calculation(self, string, prev_score, frame_count, game_result, string_count, international):\n bonus = 0\n if string == 'Х' or string == 'X':\n if international:\n score = 10\n try:\n if game_result[string_count + 1] == '/':\n bonus = 10\n else:\n for i, bonus_string in enumerate(game_result[string_count: string_count + 2]):\n if bonus_string == 'Х' or bonus_string == 'X':\n bonus += 10\n elif bonus_string.isdigit():\n bonus += int(bonus_string)\n except IndexError:\n bonus = 0\n else:\n score = 20\n frame_count += 1\n game_state = FirstThrow()\n return score, game_state, frame_count, bonus\n elif string == '/':\n raise SpareError()\n elif string == '-':\n score = 0\n elif string.isdigit():\n score = int(string)\n else:\n raise BadStringError(string)\n frame_count += 1\n game_state = SecondThrow()\n return score, game_state, frame_count, bonus\n\n\nclass SecondThrow(State):\n def throw_calculation(self, string, prev_score, frame_count, game_result, string_count, international):\n bonus = 0\n if string == 'Х' or string == 'X':\n raise StrikeError()\n elif string == '/':\n if international:\n score = 10 - prev_score\n try:\n bonus_string = game_result[string_count]\n if bonus_string == 'Х' or bonus_string == 'X':\n bonus = 10\n elif bonus_string.isdigit():\n bonus = int(bonus_string)\n except IndexError:\n bonus = 0\n else:\n score = 15 - prev_score\n elif string == '-':\n score = 0\n elif string.isdigit():\n score = int(string)\n if prev_score + score > 10:\n raise TotalScoreError()\n if prev_score + score == 10:\n raise NoSpareWarning(prev_score, score)\n else:\n raise BadStringError(string)\n game_state = FirstThrow()\n return score, game_state, frame_count, bonus\n\n\ndef get_score(game_result, international=True):\n game_score = prev_score = frame_count = string_count = bonus = 0\n game_state = FirstThrow()\n for string in game_result:\n string_count += 1\n game_score += bonus\n score, game_state, frame_count, bonus = game_state.throw_calculation(string, prev_score, frame_count,\n game_result, string_count, international)\n game_score += score\n prev_score = score\n if frame_count > 10:\n raise FrameCountError()\n if isinstance(game_state, SecondThrow):\n raise UnfinishedFrameWarning()\n # print(f'Количество очков для результатов: {game_result} - {game_score}, количество фреймов {frame_count} ')\n # print('===============================================================================')\n return game_score\n\n\nclass ScoreTests(unittest.TestCase):\n\n def test_short_game(self):\n self.assertEqual(get_score('Х4/34-4', international=False), 46)\n\n def test_normal_game(self):\n self.assertEqual(get_score('Х4/34-452Х-/729---', international=False), 106)\n\n def test_short_game_international(self):\n self.assertEqual(get_score('ХXX347/21'), 92)\n\n def test_normal_game_international(self):\n self.assertEqual(get_score('ХXX347/21XXX5/'), 177)\n\n def test_BadStringError(self):\n self.assertRaises(BadStringError, get_score, '141/FA457X')\n\n def test_FrameCountError(self):\n self.assertRaises(FrameCountError, get_score, 'ХХХХХХХХХ111')\n\n def test_StrikeError(self):\n self.assertRaises(StrikeError, get_score, '1ХХХХХХХХХХ')\n\n def test_SpareError(self):\n self.assertRaises(SpareError, get_score, 'ХХХХХХХХХ/1')\n\n def test_TotalScoreError(self):\n self.assertRaises(TotalScoreError, get_score, 'ХХХХХХХХХ56')\n\n def test_NoSpareWarning(self):\n self.assertRaises(NoSpareWarning, get_score, 'ХХХХХХХХХ55')\n\n def test_UnfinishedFrameWarning(self):\n self.assertRaises(UnfinishedFrameWarning, get_score, 'ХХХХХХХХХ1')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"lesson_014/bowling.py","file_name":"bowling.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"381409778","text":"#!/usr/bin/env python\n#-*- encoding:UTF-8 -*-\n\nimport urllib2\nimport os, re\n\nurl = 'http://www.java.com/pt_BR/download/manual.jsp'\nsite = urllib2.urlopen(url)\nhtml = site.readlines()\n\ndef java():\n\turl = 'http://www.java.com/pt_BR/download/manual.jsp' \n\tsite = urllib2.urlopen(url)\n\thtml = site.readlines()\n\tfor line in html:\n\t\tif \"Version\" in line:\n\t\t\tm = re.sub(\"<.*?>\",\"\",line)\n\t\t\tm = m.strip()\n\t\t\tm = re.split('[a-z]+', m, flags=re.IGNORECASE)\n\t\t\tversao = str(m[2]).strip()\n\t\t\tupdate = str(m[3]).strip()\n\treturn versao, update\n\n\nfor line in html:\n\t\tif \"Linux rpm pt JRE\" in line:\n\t\t\trpm = line\n\t\t\tbreak\n\t\t\t\nrpm = str(re.split('[a-z]+', rpm, flags=re.IGNORECASE))\nrpm = re.sub(\"[<,=,:,//,?,\" \",),{,},;,_,>rn,(,..'\\\\','\\\"']\",\"\",rpm)\nrpm = rpm.split()\n\nrpm = str(rpm[1])\t\n#print rpm\n\nfor line in html:\n\t\tif \"Linux pt JRE\" in line:\n\t\t\ttar = line\n\t\t\tbreak\n\t\t\t\n#rpm = rpm.strip()\t\t\t\ntar = str(re.split('[a-z]+', tar, flags=re.IGNORECASE))\ntar = re.sub(\"[<,=,:,//,?,\" \",),{,},;,_,>rn,(,..'\\\\','\\\"']\",\"\",tar)\ntar = tar.split()\n\ntar = str(tar[1])\n#print tar\n\nfor line in html:\n\t\tif \"Linux x64 pt JRE\" in line:\n\t\t\tx64 = line\n\t\t\tbreak\n\nx64 = str(re.split('[a-z]+', x64, flags=re.IGNORECASE))\nx64 = re.sub(\"[<,=,:,//,?,\" \",),{,},;,_,>rn,(,..'\\\\','\\\"']\",\"\",x64)\nx64 = x64.split()\n\nx64 = str(x64[2])\n\n#print x64\n\nfor line in html:\n\t\tif \"Linux x64-rpm pt JRE\" in line:\n\t\t\tx64rpm = line\n\t\t\tbreak\n\nx64rpm = str(re.split('[a-z]+', x64rpm, flags=re.IGNORECASE))\nx64rpm = re.sub(\"[<,=,:,//,?,\" \",),{,},;,_,>rn,(,..'\\\\','\\\"']\",\"\",x64rpm)\nx64rpm = x64rpm.split()\n\nx64rpm = str(x64rpm[2])\n#print x64rpm\n\n#.:.\n","sub_path":"version_java.py","file_name":"version_java.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"552030020","text":"def crearmatriz():\n listaa = []\n fila = int(input())\n columna = int(input())\n if fila > 0 and columna > 0: \n for i in range(fila):\n listaa.append([])\n for j in range(columna):\n n = int(input())\n listaa[i].append(n)\n else: \n print('Error')\n return listaa\n\ndef main():\n matriz = crearmatriz()\n listaa_col = []\n if len(matriz) > 0:\n for i in range(len(matriz[0])):\n count = 0\n for j in range(len(matriz)):\n count += matriz[j][i] \n listaa_col.append(count)\n print(listaa_col)\nif __name__=='__main__':\n main()\n\n","sub_path":"assignments/15SumaColumnas/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"438292637","text":"import argparse\nimport math\nimport numpy as np\n\nfrom pydrake.all import (DiagramBuilder,\n FindResourceOrThrow,\n FloatingBaseType,\n Isometry3,\n RigidBodyTree,\n Simulator,\n VisualElement)\nfrom pydrake.attic.multibody.shapes import Box\nfrom pydrake.examples.rimless_wheel import (RimlessWheel, RimlessWheelParams)\nfrom underactuated import (PlanarRigidBodyVisualizer)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-T\", \"--duration\",\n type=float,\n help=\"Duration to run sim.\",\n default=10.0)\nparser.add_argument(\"-Q\", \"--initial_angle\",\n type=float,\n help=\"Initial angle of the stance leg (in radians).\",\n default=0.0)\nparser.add_argument(\"-V\", \"--initial_angular_velocity\",\n type=float,\n help=\"Initial angular velocity of the stance leg \"\n \"(in radians/sec).\",\n default=5.0)\nparser.add_argument(\"-S\", \"--slope\", type=float,\n help=\"Ramp angle (in radians)\",\n default=0.08)\nargs = parser.parse_args()\n\ntree = RigidBodyTree(FindResourceOrThrow(\n \"drake/examples/rimless_wheel/RimlessWheel.urdf\"),\n FloatingBaseType.kRollPitchYaw)\nparams = RimlessWheelParams()\nparams.set_slope(args.slope)\nR = np.identity(3)\nR[0, 0] = math.cos(params.slope())\nR[0, 2] = math.sin(params.slope())\nR[2, 0] = -math.sin(params.slope())\nR[2, 2] = math.cos(params.slope())\nX = Isometry3(rotation=R, translation=[0, 0, -5.])\ncolor = np.array([0.9297, 0.7930, 0.6758, 1])\ntree.world().AddVisualElement(VisualElement(Box([100., 1., 10.]), X, color))\ntree.compile()\n\nbuilder = DiagramBuilder()\nrimless_wheel = builder.AddSystem(RimlessWheel())\n\nvisualizer = builder.AddSystem(PlanarRigidBodyVisualizer(tree,\n xlim=[-8., 8.],\n ylim=[-2., 3.],\n figsize_multiplier=3))\nbuilder.Connect(rimless_wheel.get_output_port(1), visualizer.get_input_port(0))\n\ndiagram = builder.Build()\nsimulator = Simulator(diagram)\nsimulator.set_target_realtime_rate(1.0)\n\ncontext = simulator.get_mutable_context()\ndiagram.Publish(context) # draw once to get the window open\ndiagram.GetMutableSubsystemContext(\n rimless_wheel, context).get_numeric_parameter(0).set_slope(args.slope)\ncontext.SetAccuracy(1e-4)\ncontext.SetContinuousState([args.initial_angle, args.initial_angular_velocity])\n\nsimulator.AdvanceTo(args.duration)\n","sub_path":"src/rimless_wheel/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"127589056","text":"import sys, os, docutils\n\nproject = 'DyND'\ncopyright = '2016, DyND Developers'\nversion = 'XYZ' # RELEASE_VERSION\nrelease = 'XYZ'\n\nprimary_domain = 'c'\n\nextensions = ['sphinx.ext.ifconfig']\nsource_suffix = '.rst'\nmaster_doc = 'index'\ntemplates_path = ['_templates']\nadd_function_parentheses = False\npygments_style = 'sphinx'\n\nhtml_title = 'DyND-Datashape'\nhtml_logo = '_static/dynd_logo_resized.png'\n#html_favicon = None\nhtml_static_path = ['_static']\nhtml_style = 'dynd-doc.css'\nhtml_domain_indices = False\nhtml_use_index = False\nhtml_show_sourcelink = False\nhtml_add_permalinks = \"\"\nhtml_copy_source = False\nhtml_sidebars = {\n '**': ['localtoc.html'],\n 'index': ['dynd-side.html'],\n 'download': [],\n}\n\ndef setup(app):\n app.add_crossref_type('topic', 'topic', 'single: %s',\n docutils.nodes.strong)\n\n\n\n","sub_path":"datashape/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"427342443","text":"#!/usr/bin/python\r\n# -*- coding:utf-8 -*- \r\n\r\nimport json\r\nimport time\r\nimport requests\r\n\r\n\r\ndef analyze(sentence):\r\n f = open('words.json', encoding='utf-8')\r\n m = open('machines.json')\r\n # dat = f.read()\r\n dat = '''{\"actions\": {\"关\": \"off\", \"开\": \"on\"}, \"devices\": {\"门\": [2, \"2\"], \"灯\": [1, \"1\"]}}'''\r\n # dat = dat.decode('gbk').encode('utf-8')\r\n # dat = dat.encode('utf-8').decode('gbk')\r\n print(dat)\r\n # if dat.startswith(u'\\ufeff'):\r\n # dat = dat.encode('utf8')[3:].decode('utf8')\r\n\r\n # di = json.loads(dat)\r\n di = {\"actions\": {\"关\": \"off\", \"开\": \"on\"}, \"devices\": {\"门\": [2, \"2\"], \"灯\": [1, \"1\"]}}\r\n # dat = m.read()\r\n # dat = dat.decode().encode('utf-8')\r\n # ma = json.loads(dat)\r\n ma = {\"1\": \"192.168.1.101\", \"2\": \"192.168.1.101\"}\r\n machines = []\r\n actions = []\r\n for d in di['devices']:\r\n machines.append(d)\r\n for d in di['actions']:\r\n actions.append(d)\r\n m.close()\r\n f.close()\r\n\r\n #将要发送给分机的数据\r\n send = {'machine':None,'device':None,'action':None}\r\n #判断动词(actions)\r\n for i in actions:\r\n if i in sentence:\r\n send['action'] = di['actions'][i]\r\n #判断设备\r\n for i in machines:\r\n if i in sentence:\r\n send['device'] = di['devices'][i][0]\r\n send['machine'] = ma[di['devices'][i][1]]\r\n if send['machine'] == None or send['device'] == None or send['action'] == None:\r\n send = None\r\n return send\r\n\r\n\r\nhost = 'http://192.168.1.101:8081'\r\n\r\n\r\ndef url_for(s):\r\n if s[0] == '/':\r\n return host + s\r\n else:\r\n return host + '/' + s\r\n\r\n\r\ndef post_data(url, prames):\r\n res = ''\r\n txt = '------WebKitFormBoundary7MA4YWxkTrZu0gW'\r\n for d in prames:\r\n res = res + txt + '\\r\\nContent-Disposition: form-data; name=\\\"' + d + '\\\"\\r\\n\\r\\n' + str(prames[d]) + '\\r\\n'\r\n res = res + txt + '--'\r\n headers = {'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\", 'Cache-Control': \"no-cache\"}\r\n response = requests.request(\"POST\", url, data=res, headers=headers)\r\n return response.text\r\n\r\n\r\ndid = 0\r\ntoken = ''\r\nform = {}\r\n\r\n\r\ndef init():\r\n global did, token, form\r\n # 先注册一个设备,获取设备id\r\n did = 1\r\n\r\n # 获取token\r\n form = {'did': did}\r\n token = post_data(url_for('/get_token'), form)\r\n\r\n print(token)\r\n\r\n # 发送心跳\r\n form['token'] = token\r\n print(post_data(url_for('/beat'), form))\r\n\r\n '''\r\n # 发送数据给设备2\r\n data = 'Data'\r\n dest = '2'\r\n form['dest'] = dest\r\n form['data'] = data\r\n tid = post_data(url_for('/command_new'), form)\r\n print(tid)\r\n form['tid'] = tid\r\n '''\r\n\r\n\r\n#发送一个从字典转换来的str\r\n# PORT = 10492\r\n#端口\r\ndef send_to(send):\r\n '''\r\n import socket\r\n import json\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.connect((send['machine'], PORT))\r\n s.send(json.dumps(send).encode('utf-8'))\r\n s.close()'''\r\n global did, token, form\r\n data = json.dumps(send)\r\n # 发送数据给设备2\r\n dest = '2'\r\n form['dest'] = dest\r\n form['data'] = data\r\n tid = post_data(url_for('/command_new'), form)\r\n print(tid)\r\n form['tid'] = tid\r\n print(form)\r\n tries = 100\r\n while tries > 0:\r\n res = post_data(url_for('/command_task_stat'), form)\r\n print('Waiting...\\tres =', res)\r\n if res == \"FINISH\":\r\n break\r\n tries = tries - 1\r\n time.sleep(1)\r\n if tries < 0:\r\n print(\"Time Out.\")\r\n post_data(url_for('/command_finish'), form)\r\n return\r\n data = post_data(url_for('/command_finish'), form)\r\n print(data)\r\n\r\n print('Finish task.')\r\n\r\n\r\n \r\ndef main(words):\r\n #words = '关灯...'\r\n #words = words.decode('gbk').encode('utf-8')\r\n #words = words.decode('utf-8')\r\n print(words)\r\n send = analyze(words)\r\n print(\"send\", send)\r\n if send != None:\r\n send_to(send)\r\n","sub_path":"Driver1/manege.py","file_name":"manege.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"135772520","text":"from fractions import Fraction\nfrom collections import Counter\nfrom typing import List\n\n\nclass Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n cnt = Counter()\n for w, h in rectangles:\n cnt[Fraction(w, h)] += 1\n ans = 0\n for value in cnt.values():\n ans += value * (value - 1) // 2\n return ans\n","sub_path":"python/cache/5868. 可互换矩形的组数.py","file_name":"5868. 可互换矩形的组数.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"375812385","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef rplot(x,y,color):\n new_x, new_y = zip(*sorted(zip(x, y)))\n plt.plot(new_x, new_y, color+'--')\n plt.plot(new_x, new_y, color+'o')\n \n'''#1) Fizikinis stebėjimas\n\nilgis=np.array([0.78, 0.58, 0.3, 0.2])\nlaiko_f=2*np.pi*(ilgis/9.8)**0.5\nlaikas=np.array([1.73, 1.6, 1.25, 1.06])\n\nrplot(ilgis, laiko_f, 'b')\nplt.plot(ilgis, laikas, 'r')\nplt.ylabel('laikas')\nplt.xlabel('ilgis')'''\n \n#2) Funkcijos braižymas\nA,B=-10, 10\nplt.xlim((A,B))\nplt.xticks(np.arange(A,B+1, (B-A)/20))\na,b=-1,1\nplt.ylim((a,b))\nplt.yticks(np.arange(a,b+1, (b-a)/10))\n\n#x=np.array(np.arange(0,1,0.0001))\n\nx=np.array([-3,-2,4,0,-1])\ny=1/x\n\nrplot(x,y,'b')\n\nPRINTSIZE=6\nprint('x =',''.join([' '*(PRINTSIZE-len(str(n)))+str(n) for n in [round(n,2) for n in x]]))\nprint('y =',''.join([' '*(PRINTSIZE-len(str(n)))+str(n) for n in [round(n,2) for n in y]]))\n#rplot(x,[10, 7, 10, 10, 21],'r')\nplt.show()\n\n","sub_path":"UNCLASSIFIED/concept_vivat_cangaroo/demo - create folder of images problems in pdf/untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"628909676","text":"from flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('//hi/')\ndef greeting(count, name):\n str1 = 'hello'\n for _ in range(0, count):\n str1 += '%s' % name\n return str1\n\n\n@app.route('/training1//')\ndef another(goal, weight):\n str1 = 'my weight=%.2f, goal=%s' % (weight, goal)\n return str1\n\n\nif __name__ == '__main__':\n app.run(port=5432, host='0.0.0.0', debug=True)\n","sub_path":"main24.py","file_name":"main24.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"292484116","text":"# -*- coding: utf-8 -*-\nfrom django.db.models import F, Q\nfrom django.core.management.base import NoArgsCommand\n\nfrom modeltranslation.settings import DEFAULT_LANGUAGE\nfrom modeltranslation.translator import translator\nfrom modeltranslation.utils import build_localized_fieldname\n\n\nclass Command(NoArgsCommand):\n help = ('Updates the default translation fields of all or the specified'\n 'translated application using the value of the original field.')\n\n def handle(self, **options):\n verbosity = int(options['verbosity'])\n if verbosity > 0:\n self.stdout.write(\"Using default language: %s\\n\" % DEFAULT_LANGUAGE)\n for model, trans_opts in translator._registry.items():\n if model._meta.abstract:\n continue\n if verbosity > 0:\n self.stdout.write(\"Updating data of model '%s'\\n\" % model)\n for fieldname in trans_opts.fields:\n def_lang_fieldname = build_localized_fieldname(\n fieldname, DEFAULT_LANGUAGE)\n\n # We'll only update fields which do not have an existing value\n q = Q(**{def_lang_fieldname: None})\n field = model._meta.get_field(fieldname)\n if field.empty_strings_allowed:\n q |= Q(**{def_lang_fieldname: \"\"})\n\n model.objects.filter(q).rewrite(False).update(**{def_lang_fieldname: F(fieldname)})\n","sub_path":"modeltranslation/management/commands/update_translation_fields.py","file_name":"update_translation_fields.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"535424074","text":"while True:\n N = int(input())\n if N == 0:\n break\n\n P = [int(i) for i in input().split(\" \")]\n\n X, Y = [int(i) for i in input().split(\" \")]\n\n r = []\n for i in range(X, Y + 1):\n _i = i\n for _p in P:\n while _i % _p == 0:\n _i = int(_i / _p)\n if _i == 1:\n r.append(i)\n\n if r == []:\n print(\"none\")\n else:\n print(','.join(sorted([str(i) for i in r])))\n","sub_path":"primes/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"280012110","text":"from django.conf.urls import patterns, include, url\n\n\n\nurlpatterns = patterns('todoapp.apps.manager.views',\n url(r'^$','index',name='index'),\n url(r'^lists/(?P\\d+)/$','view_list',name='view_list'),\n url(r'^lists/(?P\\d+)/add_task/$','add_task',name='add_task'),\n url(r'^lists/(?P\\d+)/update_task/$','update_task',name='update_task'),\n url(r'^lists/new/$','new_list',name='new_list'),\n url(r'^lists/(?P\\d+)/monthly/','monthly_view_list',name='monthly_view_list'),\n url(r'^lists/(?P\\d+)/weekly/','weekly_view_list',name='weekly_view_list'),\n url(r'^task/(?P\\d+)/date_change/','date_change',name='date_change'),\n\n)\n","sub_path":"todoapp/apps/manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"261501800","text":"'''\nCreated on Mar 3, 2014\n\n@author: steve\n'''\nimport unittest\nfrom webtest import TestApp\nimport re\nfrom urllib.parse import urlparse\n\nimport bottle\nfrom bottle.ext import sqlite, beaker\nimport os\nimport sqlite3\n\nimport main\n\nimport database\n\n\nDATABASE_NAME = \"test.db\"\nmain.app.install(sqlite.Plugin(dbfile=DATABASE_NAME))\n\n# make sure bottle looks for templates in the main directory, not this one\nbottle.TEMPLATE_PATH = [os.path.join(os.path.dirname(__file__), p) for p in ['../', '../views/']]\n\n\nclass Level2FunctionalTests(unittest.TestCase):\n\n def setUp(self):\n\n session_opts = {\n 'session.type': 'memory',\n }\n beaker_app = beaker.middleware.SessionMiddleware(main.app, session_opts)\n db = sqlite3.connect(DATABASE_NAME)\n database.create_tables(db)\n self.users, self.images = database.sample_data(db)\n self.app = TestApp(beaker_app)\n bottle.debug() # force debug messages in error pages returned by webtest\n\n def tearDown(self):\n pass\n\n def testImagesPresent(self):\n \"\"\"As a visitor to the site, when I load the home page I\n see three images displayed, each\n labelled with a date, a user name and a title. \"\"\"\n\n result = self.app.get('/')\n\n images = result.html.find_all('img')\n\n # expect to find three images\n self.assertEqual(3, len(images), \"Wrong number of images found\")\n\n flowtows = result.html.find_all(class_='flowtow')\n\n image_list = self.images\n\n self.assertEqual(3, len(flowtows))\n\n # each contains the image, date, author and likes\n for index in range(3):\n div = flowtows[index]\n (path, date, user, likes) = image_list[index]\n\n self.assertIn(date, div.text)\n self.assertIn(user, div.text)\n # look for the number of likes\n self.assertIn(str(len(likes)+1), div.text, \"expected to find %d likes mentioned in:\\n\\n%s\" % (len(likes), div))\n\n # look for just one image\n img = div.find_all('img')\n self.assertEqual(1, len(img))\n\n def testLikeImage(self):\n \"\"\"As a visitor to the site, when I click on \"Like\" below an image,\n the page refreshes and has one more like added to the total for that image.\"\"\"\n\n response = self.app.get('/')\n originallikes = get_page_likes(response)\n\n print(originallikes)\n\n # find a form with the action /like\n for i in response.forms:\n form = response.forms[i]\n if form.action == '/like':\n\n self.assertIn('filename', form.fields, 'image like form does not have a filename field')\n\n\n filename = form['filename'].value\n\n formresponse = form.submit()\n\n # response should be a redirect to the main page\n self.assertIn(formresponse.status, ['303 See Other', '302 Found'])\n (_, _, path, _, _, _) = urlparse(formresponse.headers['Location'])\n self.assertEqual('/', path)\n\n # and the main page should now have one more like for this image\n newresponse = self.app.get('/')\n newlikes = get_page_likes(newresponse)\n\n print(newlikes)\n\n for key in originallikes.keys():\n if key == filename:\n self.assertEqual(originallikes[key]+1, newlikes[key])\n else:\n self.assertEqual(originallikes[key], newlikes[key])\n\n # we only need to test one form\n break\n\n\ndef get_page_likes(response):\n \"\"\"Scan a page and create a dictionary of the image filenames\n and displayed like count for each image. Return the\n dictionary.\"\"\"\n\n # find all flowtow divs\n flowtows = response.html.find_all('div', class_='flowtow')\n result = dict()\n for div in flowtows:\n # get the filename from the form hidden input\n input = div.find(\"input\", attrs={'name': \"filename\"})\n\n filename = input['value']\n\n # find the likes element\n likesel = div.find(class_='likes')\n # grab the integer from this element\n m = re.search('\\d+', likesel.text)\n if m:\n likes = int(m.group())\n else:\n likes = 0\n\n result[filename] = likes\n\n return result\n\n\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"tests/level2_functional.py","file_name":"level2_functional.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"333586002","text":"from flask import Flask, render_template, Response\nfrom services.finnkino import FinnKinoXML\nfrom services.leffatykki import LeffaTykkiRSS\nimport json\napp = Flask(__name__)\nfk = FinnKinoXML()\nlt = LeffaTykkiRSS()\n\ndef get_movies_with_reviews(area_code):\n\tmovie_container = {}\n\tmovies = fk.get_movies_from_area(area_code)\n\treviews = lt.get_movie_reviews()\n\tfor id, movie in movies.items():\n\t\treview_link = \"\"\n\t\ttitle = movie['title']\n\t\tif title in reviews:\n\t\t\treview_link = reviews[movie['title']]\n\t\tmovie_container[id] = {\n\t\t\t'title': movie['title'],\n\t\t\t'rating': movie['rating'],\n\t\t\t'genres': \"\".join(movie['genres']),\n\t\t\t'review': review_link\n\t\t}\n\treturn movie_container\n\n@app.route('/')\ndef index():\n\tareas = fk.get_area_codes()\n\tdata = {\n\t\t'areas': areas\n\t}\n\treturn render_template('index.html', data=data)\n\n@app.route('/movies/ ')\ndef get_movies(area):\n\tmovies = get_movies_with_reviews(area)\n\tdata = {\n\t\t'movies': movies\n\t}\n\treturn render_template('_movies.html', data=data)\n\n@app.route('/movies/ /json')\ndef get_movies_json(area):\n\tmovies = get_movies_with_reviews(area)\n\tdata = json.dumps(movies)\n\tresp = Response(response=data, status=200, mimetype=\"application/json\")\n\treturn resp\n\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604308666","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\nfrom core.models.extern import BaseModelKeras\n\n\nclass CartPoleModel(BaseModelKeras):\n\n @staticmethod\n def create_model(input_shape, output_shape, *args, **kwargs):\n \"\"\" Creates the model. \"\"\"\n model = Sequential([\n Dense(input_shape=input_shape,\n name='layer_fc1', units=24, activation='relu'),\n Dense(name='layer_fc2', units=24, activation='relu'),\n Dense(name='layer_fc_out', units=output_shape, activation='linear'),\n ])\n model.compile(optimizer=Adam(lr=1e-2), loss='mse')\n return model\n","sub_path":"agents/cartpole/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"37545942","text":"import FWCore.ParameterSet.Config as cms\n\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\nprocess = cms.Process(\"DISPLACED\")\n\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc')\n\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n \"root://cms-xrd-global.cern.ch//store/mc/RunIISummer16MiniAODv2/SMS-T1qqqq_ctau-1_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_GridpackScan_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/10000/023CA233-4289-E711-9B01-002590FD5A48.root\"\n )\n)\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True),\n allowUnscheduled = cms.untracked.bool(True)\n)\n\nprocess.load('XTag.DisplacedVertex.GenDisplacedVertices_cff')\n\nprocess.MINIAODSIMoutput = cms.OutputModule(\"PoolOutputModule\", \n compressionAlgorithm = cms.untracked.string('LZMA'), \n compressionLevel = cms.untracked.int32(4), \n dataset = cms.untracked.PSet( \n dataTier = cms.untracked.string(''), \n filterName = cms.untracked.string('') \n ), \n dropMetaData = cms.untracked.string('ALL'), \n eventAutoFlushCompressedSize = cms.untracked.int32(15728640), \n fastCloning = cms.untracked.bool(False), \n fileName = cms.untracked.string('BTagging.root'), \n outputCommands = cms.untracked.vstring(\n 'drop *',\n 'keep *_displacedGenVertices_*_DISPLACED',\n ),\n overrideInputFileSplitLevels = cms.untracked.bool(True) \n) \n \n\n\nprocess.endpath = cms.EndPath(process.DisplacedGenVertexSequence*process.MINIAODSIMoutput) \n","sub_path":"DisplacedVertex/test/test_DisplacedGenVertex.py","file_name":"test_DisplacedGenVertex.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"65180055","text":"# -*- coding:utf-8 -*-\n__author__ = 'neo'\n__time__ = '2018/9/5 11:12'\nfrom app import create_app\n\n\napp = create_app()\n\n# app.add_url_rule('/hello',view_func=hello)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',debug=app.config['DEBUG'])","sub_path":"fisher.py","file_name":"fisher.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"543292838","text":"import boto3\nfrom botocore.exceptions import NoCredentialsError\nfrom datetime import datetime\n\n\ndef upload_to_bucket(local_file, bucket, s3_file):\n s3 = boto3.client('s3')\n\n try:\n s3.upload_file(local_file, bucket, s3_file)\n print(\"Upload Successful\")\n return True\n except FileNotFoundError:\n print(\"The file was not found\")\n return False\n except NoCredentialsError:\n print(\"Credentials not available\")\n return False\n\n\n# year = now.strftime(\"%Y\")\n# print(\"year:\", year)\n\n# month = now.strftime(\"%m\")\n# print(\"month:\", month)\n\n# day = now.strftime(\"%d\")\n# print(\"day:\", day)\n\n# time = now.strftime(\"%H:%M:%S\")\n# print(\"time:\", time)\n\n# date_time = now.strftime(\"%m/%d/%Y, %H:%M:%S\")\n# print(\"date and time:\",date_time)\t\n\nvar=0\nwhile var < 100:\n# while True:\n now = datetime.now() # current date and time\n print(now)\n # s3_file_name=\"diagram_\" + now.strftime(\"%H:%M:%S:%f\") + \".png\"\n s3_file_name=now.strftime(\"%f_%H:%M:%S:%f\") + \"_diagram\" + \".png\"\n print(s3_file_name)\n uploaded = upload_to_bucket('/home/ec2-user/environment/Amazon-S3-Bucket-Load-Test/container/diagram.png', 'amazon-s3-bucket-load-test-storagebucket-knlgpd3wpz0n', s3_file_name)\n done = datetime.now()\n # uploaded = upload_to_bucket('/beef/diagram.png', 'amazon-s3-bucket-load-test-storagebucket-knlgpd3wpz0n', s3_file_name)\n var = var + 1\n \n","sub_path":"container/load-test.py","file_name":"load-test.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"455836437","text":"#!/usr/bin/python3\n\"\"\" a script that starts a Flask web application \"\"\"\nfrom flask import Flask\nfrom flask import render_template\nfrom models import storage, State\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef remove_session(exception):\n \"\"\" After each request, it removes the current SQLAlchemy Session \"\"\"\n storage.close()\n\n\n@app.route('/states', strict_slashes=False)\ndef render_states():\n \"\"\" displays all states \"\"\"\n States = storage.all(State).values()\n return render_template(\"9-states.html\", States=States, one=None)\n\n\n@app.route('/states/', strict_slashes=False)\ndef render_one_state(id):\n \"\"\" displays one state if it exists \"\"\"\n key = \"State.\" + id\n one = None\n if key in storage.all(State):\n one = storage.all(State)[key]\n return render_template(\"9-states.html\", States=None, one=one)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"312100880","text":"\n\nfrom datetime import date, timedelta\nfrom itertools import islice\nTODAY = date.today()\n\n\ndef gen_bite_planning(num_bites=1, num_days=1, start_date=TODAY):\n \n delta_days = timedelta(days=num_days)\n poprzedni = 1\n while True:\n final = start_date + delta_days\n yield final\n if poprzedni == num_bites:\n start_date = final\n poprzedni = 1 \n else:\n poprzedni +=1\n\ngen = gen_bite_planning(num_bites=3, num_days=1, start_date=TODAY)\n\nfor _ in range(6):\n print(next(gen))","sub_path":"6_Generator_Exercices_Days_16_18/pybytes219_generator.py","file_name":"pybytes219_generator.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"404649597","text":"#Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:\n\n#Any left parenthesis '(' must have a corresponding right parenthesis ')'.\n#Any right parenthesis ')' must have a corresponding left parenthesis '('.\n#Left parenthesis '(' must go before the corresponding right parenthesis ')'.\n#'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.\n#An empty string is also valid.\n\n#Example 1:\n#Input: \"()\"\n#Output: True\n#Example 2:\n#Input: \"(*)\"\n#Output: True\n#Example 3:\n#Input: \"(*))\"\n#Output: True\n#Note:\n#The string size will be in the range [1, 100].\n\nclass Solution:\n def checkValidString(self, s: str) -> bool:\n if s == \"\":\n return True\n\n stack1 = []\n stack2 = []\n l = len(s)\n\n for i in range(l):\n if s[i] == '(':\n stack1.append(i)\n elif s[i] == '*':\n stack2.append(i)\n else:\n if stack1:\n stack1.pop()\n elif stack2:\n stack2.pop()\n else:\n return False\n\n while stack1:\n if not stack2:\n return False\n else:\n if stack1.pop() >= stack2.pop():\n return False\n\n return True\n\ntest = \"(*)\"\ns = Solution()\ns.checkValidString(test)\n","sub_path":"python_code/678_Valid_Parenthesis_String.py","file_name":"678_Valid_Parenthesis_String.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"378544576","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport os\nimport json\nimport sys\nimport urllib\nimport tarfile\nimport wget\nimport shutil\n\nfrom subprocess import call\n\nfrom rasa_nlu.converters import load_data\nfrom rasa_nlu.config import RasaNLUConfig\nfrom rasa_nlu.model import Trainer\n\ndef main():\n arguments = sys.argv\n if len(arguments) < 2:\n show_hint(arguments)\n else:\n method = arguments[1]\n if method == 'train':\n learn(arguments)\n elif method == 'init':\n init(arguments)\n elif method == 'hint':\n show_hint(arguments)\n elif method == 'run':\n run(arguments)\n elif method == 'build':\n build(arguments)\n elif method == \"download\":\n download(arguments)\n else:\n show_hint(arguments)\n\ndef build(arguments):\n path = os.path.join(os.getcwd(),'actions')\n files = os.listdir(path)\n imps = []\n\n for i in range(len(files)):\n name = files[i].split('.')\n if len(name) > 1:\n if name[1] == 'py' and name[0] != '__init__':\n name = name[0]\n imps.append(name)\n init_path = os.path.join(path,'__init__.py')\n file = open(init_path,'w')\n toWrite = '__all__ = ' + str(imps)\n\n file.write(toWrite)\n file.close()\n\ndef learn(arguments):\n path = os.path.join(os.getcwd(), 'train')\n if (os.path.isdir(path)):\n ac_path = os.path.join(os.getcwd(),'actions')\n files = os.listdir(ac_path)\n imps = []\n\n for i in range(len(files)):\n name = files[i].split('.')\n if len(name) > 1:\n if name[1] == 'py' and name[0] != '__init__':\n name = name[0]\n imps.append(name)\n init_path = os.path.join(ac_path,'__init__.py')\n file = open(init_path,'w')\n toWrite = '__all__ = ' + str(imps)\n\n file.write(toWrite)\n file.close()\n\n files = os.listdir(path)\n\n \n common_examples = []\n\n none_example_1 = {'text':'jshfjdhsfj','intent':'None','entities':[]}\n none_example_2 = {'text':'dfjkhjkfds','intent':'None','entities':[]}\n common_examples.append(none_example_1)\n common_examples.append(none_example_2)\n\n \n for file in files:\n file_data = file.split('.')\n intent_name = file_data[0]\n file_type = file_data[1]\n if file_type != 'txt':\n continue\n else:\n with open(path + '/' + file,'r') as intentFile:\n responses = []\n examples = intentFile.readlines()\n examples = [*map(lambda s: s.strip(), examples)]\n if \"<-responses->\" in examples:\n pos = examples.index(\"<-responses->\")\n responses = examples[pos+1:]\n examples = examples[:pos]\n for sample in examples:\n example = {}\n sample_split = sample.split('<=>')\n sample_text = sample_split[0]\n\n if len(sample_split) == 1:\n example['text'] = sample\n example['intent'] = intent_name\n example['entities'] = []\n else:\n #get list of entities in the sample\n sample_entities = sample_split[1:]\n\n #check if paranthesis match\n open_paran_count = sample_text.count('(')\n close_paran_count = sample_text.count(')')\n\n if open_paran_count != close_paran_count:\n raise ValueError(\"Paranthesis don't match for \" + sample_text)\n \n\n #check if paranthesis and provided entites match\n if open_paran_count != len(sample_entities):\n raise ValueError(\"The entities provided and words marked in entities don't match for \" + sample_text)\n \n \n start_pos = 0\n entities_count = 0\n no_of_entities = len(sample_entities)\n entities = []\n\n while entities_count < no_of_entities:\n start_pos = sample_text.find('(', start_pos, len(sample_text)) + 1\n end_pos = sample_text.find(')', start_pos, len(sample_text))\n \n entityLabel = {}\n\n entityLabel['start'] = start_pos - 1\n entityLabel['end'] = end_pos - 1\n entityLabel['value'] = sample_text[start_pos:end_pos]\n entityLabel['entity'] = sample_entities[entities_count].strip()\n \n entities.append(entityLabel)\n entities_count += 1\n\n example['text'] = sample_text.replace('(','').replace(')','')\n example['intent'] = intent_name\n example['entities'] = entities\n\n common_examples.append(example)\n if len(responses) > 0:\n with open(os.path.join(os.getcwd(),\"actions.json\"),\"r+\") as jsonFile:\n data = json.load(jsonFile)\n data[intent_name] = responses\n jsonFile.seek(0)\n jsonFile.truncate()\n json.dump(data, jsonFile)\n \n nlp_json = {\"rasa_nlu_data\":{\"common_examples\":common_examples}}\n\n with open(os.path.join(path, 'train.json'),\"w\") as trainFile:\n json.dump(nlp_json, trainFile)\n\n with open(os.path.join(os.getcwd(), 'config.json'),\"r\") as jsonFile:\n data = json.load(jsonFile)\n\n jsonFile.close()\n\n training_data = load_data(os.path.join(path, 'train.json'))\n trainer = Trainer(RasaNLUConfig(os.path.join(os.getcwd(), 'config.json')))\n trainer.train(training_data)\n model_directory = trainer.persist('models')\n\n print(model_directory)\n data[\"active_model\"] = str(model_directory)\n\n with open(os.path.join(os.getcwd(), 'config.json'),\"w\") as jsonFile:\n json.dump(data, jsonFile)\n else:\n raise FileNotFoundError(\"No train folder found. Please setup a wizard bot first by running wiz create \")\n\ndef init(arguments):\n #Setup bot name\n main_name = os.getcwd().split(os.sep)[-1]\n if len(arguments) < 3:\n prompt = \"What is the name of the bot? (default: \" + main_name + \"):\"\n bot_name = str(input(prompt))\n if len(bot_name) == 0:\n bot_name = main_name\n else:\n bot_name = ' '.join(arguments[2:])\n print(\"Creating bot: \" + bot_name)\n\n #Setup actions folder\n print(\"Creating actions folder....\")\n directory = os.path.join(os.getcwd(),'actions')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n #Configure actions folder\n print(\"Configuring actions folder....\")\n directory = os.path.join(os.getcwd(),'actions')\n with open(os.path.join(directory,'__init__.py'), \"w\") as initFile:\n initFile.write(\"#It will be initialized at runtime\")\n\n #Setup train folder\n print(\"Creating train folder....\")\n directory = os.path.join(os.getcwd(),'train')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n #Setup config.json file\n print(\"Creating config.json...\")\n file_path = os.path.join(os.getcwd(),'config.json')\n with open(file_path, \"w\") as jsonFile:\n data = {}\n data[\"name\"] = bot_name\n data[\"pipeline\"] = \"mitie_sklearn\"\n data[\"mitie_file\"] = \"./train/total_word_feature_extractor.dat\"\n data[\"channels\"] = {}\n json.dump(data, jsonFile)\n\n #Setup actions.json file\n print(\"Creating actions.json...\")\n file_path = os.path.join(os.getcwd(),'actions.json')\n with open(file_path, \"w\") as jsonFile:\n data = {}\n json.dump(data,jsonFile)\n\n #Setup main.py file\n print(\"Creating main.py...\")\n file_path = os.path.join(os.getcwd(),'main.py')\n with open(file_path, \"w\") as mainFile:\n mainFile.write(\"from flask import Flask\\n\")\n mainFile.write(\"from flask_wizard import Wizard\\n\")\n mainFile.write(\"\\n\")\n mainFile.write(\"app = Flask(__name__)\\n\")\n mainFile.write(\"wizard = Wizard(app)\\n\")\n mainFile.write(\"\\n\")\n mainFile.write(\"if __name__ == '__main__':\\n\")\n mainFile.write(\"\\tapp.run()\")\n\n #Download mitie file\n print(\"Setting up Mitie model file...\")\n print(\"Installing Mitie\")\n\n if os.name == 'nt':\n #windows operating system\n call([\"pip\",\"install\",\"git+https://github.com/mit-nlp/MITIE.git#egg=mitie\"])\n else:\n #linux, unix or macos\n if sys.version_info >= (3,0):\n call([\"pip3\",\"install\",\"git+https://github.com/mit-nlp/MITIE.git#egg=mitie\"])\n else:\n call([\"pip\",\"install\",\"git+https://github.com/mit-nlp/MITIE.git#egg=mitie\"])\n print(\"Choose one of the options below\")\n print(\"1. Download Mitie models (size>400MB, so if you already have the total_word_feature_extractor.dat file use it. You can find it in the train folder if you already set up wiz before\")\n print(\"2. Copy from existing path\")\n choice = str(input(\"Choice (1 default): \"))\n if len(choice)==0 or choice == \"1\":\n directory_path = os.path.join(os.getcwd(),'train')\n file_path = os.path.join(directory_path,'mitie.tar.bz2')\n wget.download(\"https://github.com/mit-nlp/MITIE/releases/download/v0.4/MITIE-models-v0.2.tar.bz2\",'mitie.tar.bz2')\n\n #Extracting mitie file\n print(\"\")\n print(\"Extracting Mitie model (this might take a couple of minutes)\")\n tar = tarfile.open('mitie.tar.bz2',\"r:bz2\")\n tar.extractall()\n tar.close()\n\n #Move files around and only keep total_word_feature_extractor.dat\n current_path = os.path.join(os.getcwd(),'MITIE-models','english','total_word_feature_extractor.dat')\n new_path = os.path.join(os.getcwd(),'train','total_word_feature_extractor.dat')\n os.rename(current_path, new_path)\n os.remove('mitie.tar.bz2')\n shutil.rmtree(os.path.join(os.getcwd(), 'MITIE-models'))\n else:\n path = str(input(\"Enter path of existing total_word_feature_extractor.dat file: \"))\n if path[0] == '~':\n home = os.path.expanduser('~')\n path = path.replace('~',home)\n if os.path.exists(path):\n shutil.copyfile(path,os.path.join(os.getcwd(),'train','total_word_feature_extractor.dat'))\n \n #Download en model for spacy\n print(\"Setting up spacy\")\n if os.name == 'nt':\n #windows operating system\n call([\"python\",\"-m\",\"spacy\",\"download\",\"en\"])\n else:\n #linux, unix, macos\n if sys.version_info >= (3,0):\n call([\"python3\",\"-m\",\"spacy\",\"download\",\"en\"])\n else:\n call([\"python\",\"-m\",\"spacy\",\"download\",\"en\"])\n\ndef run(arguments):\n main_path = os.path.join(os.getcwd(),'main.py')\n if os.name == 'nt':\n #windows operating system\n call([\"python\",\"main.py\"])\n else:\n #linux, unix, macos operating system\n if sys.version_info >= (3,0):\n call([\"python3\",\"main.py\"])\n else:\n call([\"python\",\"main.py\"])\n\ndef download(arguments):\n directory_path = os.path.join(os.getcwd(),'train')\n file_path = os.path.join(directory_path,'mitie.tar.bz2')\n wget.download(\"https://github.com/mit-nlp/MITIE/releases/download/v0.4/MITIE-models-v0.2.tar.bz2\",'mitie.tar.bz2')\n\n #Extracting mitie file\n print(\"\")\n print(\"Extracting Mitie model (this might take a couple of minutes)\")\n tar = tarfile.open('mitie.tar.bz2',\"r:bz2\")\n tar.extractall()\n tar.close()\n\n #Move files around and only keep total_word_feature_extractor.dat\n current_path = os.path.join(os.getcwd(),'MITIE-models','english','total_word_feature_extractor.dat')\n new_path = os.path.join(os.getcwd(),'train','total_word_feature_extractor.dat')\n os.rename(current_path, new_path)\n os.remove('mitie.tar.bz2')\n shutil.rmtree(os.path.join(os.getcwd(), 'MITIE-models'))\n\ndef show_hint(arguments):\n print(\"Please provide the right option or command you want to run\")\n print(\"Accepted commands: \")\n print(\"-------------------------------------------\")\n print(\"wiz hint #to see list of commands\")\n print(\"wiz train #to train the nlp model\")\n print(\"wiz create #to create a new bot\")\n","sub_path":"flask_wizard_cli/command_line.py","file_name":"command_line.py","file_ext":"py","file_size_in_byte":13083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"146340412","text":"from __future__ import print_function\n\nimport enchant\nimport inflect\nimport nltk\nimport pprint\nimport re\nimport string\nfrom __builtin__ import len\nfrom __builtin__ import list\nfrom textblob import TextBlob\n\nenglish = enchant.Dict(\"en_US\")\n\ninflect_engine = inflect.engine()\n\nnoun = ['NN', 'NNS', 'NNP', 'NNPS']\nadj = ['JJ', 'JJR', 'JJS']\n\nstopwords = ['i', 's', 'able', 'isn', \\\n 'doesn', 'only', 'sa', 'mom', 'other', \\\n 'man', 'more', 'months', 'years', \\\n 'weeks', 'week', 'year', 'month', 'time', \\\n 'one', 'night', 'fav', 'girl', 'bye', 'lol'\\\n 'thing', 'son', 'bit', 'day', 'sorry', \\\n 'visit', 'item', 'lil', 'lot', 'eye'\\\n 'fire', 'jar', 'restriction' , 'norm', 'list',\n 'line', 'shape', 'ice', 'nit', 'vist', 'turf']\npp = pprint.PrettyPrinter(depth=6)\n\n\ndef get_type(data_dict):\n if len(data_dict.keys()) == 0:\n return \"other\", None\n max = -99999\n ret = list(data_dict.keys())[0]\n\n for key in data_dict.keys():\n if data_dict[key] > max:\n max = data_dict[key]\n ret = key\n return ret, max\n\n\ndef for_each_review_(review, ret_data_dict, dict_):\n del review['_id']\n scored_terms = review['score']\n\n for term in scored_terms.keys():\n skip = False\n nn = None\n t_list = []\n l_list = []\n nn_count = 0\n aa_count = 0\n term = term.lower().strip().replace(\" \", \" \")\n term_list = term.split(\" \")\n list_words = [] # nltk.pos_tag(term_list)\n try:\n for word in term_list:\n if word in stopwords:\n skip = True\n list_words.append((word, dict_[word]))\n\n except Exception as e:\n # print(\"not in sentence : \" + str(e) + \" : \" + str(term_list))\n skip = True\n\n if len(list_words) > 2:\n\n if dict_[term_list[2]] in noun and dict_[term_list[1]] in adj:\n '''\n Let it be !\n '''\n else:\n print(list_words)\n skip = True\n\n for elem in list_words:\n if len(elem[0]) < 3:\n skip = True\n\n if elem[1] in noun:\n nn_count += 1\n\n item = inflect_engine.singular_noun(elem[0])\n if not item:\n item = elem[0]\n nn = item\n l_list.append(item)\n\n elif elem[1] in adj:\n aa_count += 1\n\n l_list.append(elem[0])\n else:\n l_list.append(elem[0])\n\n term_list = l_list\n term_mod = ' '.join(l_list)\n\n object = {\n 'word_pairs': term,\n 'frequency': {\n\n },\n 'noun': nn,\n 'tagged_text': list_words\n }\n\n for item in term_list:\n object['frequency'][item] = 1\n t_list.append(item)\n\n if len(l_list) > 2:\n # print(\"--\", l_list)\n term_mod = term_list[0] + \"-\" + term_list[1] + \" \" + term_list[2]\n\n object['word_pairs'] = term_mod\n object['type'], object['type_score'] = get_type(scored_terms[term])\n object['polarity'] = TextBlob(term_mod).sentiment.polarity\n object['business_id'] = review['business_id']\n object_type = object['type']\n\n # print (object,skip)\n\n if nn_count == 1 and aa_count > 0 and skip is False and nn is not None:\n try:\n obj = ret_data_dict[object['business_id']][object_type][term_mod]\n object['polarity'] = TextBlob(term_mod).sentiment.polarity\n object['type_score'] = (object['type_score'] + obj['type_score'])\n\n for txt in obj['frequency'].keys():\n object['frequency'][txt] += obj['frequency'][txt]\n\n ret_data_dict[object['business_id']][object_type][term_mod] = object\n\n except:\n try:\n ret_data_dict[object['business_id']][object_type][term_mod] = object\n except:\n try:\n oo = ret_data_dict[object['business_id']]\n except:\n ret_data_dict[object['business_id']] = {}\n\n ret_data_dict[object['business_id']][object_type] = {}\n ret_data_dict[object['business_id']][object_type][term_mod] = object\n\n noun_in_t = ret_data_dict[object['business_id']][object_type][term_mod]['noun']\n ret_data_dict[object['business_id']][object_type][term_mod]['noun_frequency'] = \\\n ret_data_dict[object['business_id']][object_type][term_mod]['frequency'][noun_in_t]\n # else:\n # print(\" - \", \"list : \", list_words, \"noun_count : \", nn_count, \"skip : \", skip, \"noun : \", nn,\n # (nn_count == 1 and skip is False and nn is not None)) # , list(review['text'].keys()))\n\n return ret_data_dict\n\n\ndef get_word_pairs(review_list, mongo_connection):\n query = {\n 'review_id': {\n '$in': review_list\n }\n }\n what = {\n 'review_id': 1,\n 'polarity': 1,\n 'score': 1,\n 'business_id': 1,\n 'stars': 1,\n 'tf_idf': 1,\n 'final': 1,\n }\n\n reviews_text = [x['text'] for x in list(mongo_connection.db.yelp_reviews.find(query))]\n\n final_para = []\n for text in reviews_text:\n text = text.lower(). \\\n replace(\"!\", \" \"). \\\n replace('/', \" \"). \\\n replace(\" \", \" \"). \\\n replace(\"\\t\", \" \"). \\\n replace(\"\\n\", \" \"). \\\n replace(\"~\", \" \"). \\\n lstrip()\n\n regex = re.compile('[%s]' % re.escape(string.punctuation))\n text = regex.sub(' ', text)\n text = text.split(\" \")\n\n ret_text = []\n for word in text:\n if len(word) > 1:\n ret_text.append(word)\n final_para.append(ret_text)\n\n text_tagged = nltk.pos_tag_sents(final_para)\n\n dict_ = {}\n for texxt in text_tagged:\n for word in texxt:\n dict_[word[0]] = word[1]\n # pp.pprint(dict_)\n\n processed = list(mongo_connection.db.yelp_review_scored_pair_all_not_final.find(query, what))\n\n ret_list = {}\n for review in processed:\n ret_list = for_each_review_(review, ret_list, dict_)\n\n ret_list['business_es'] = list(ret_list.keys())\n\n return ret_list\n\n\ndef create_groups(data_types):\n ret_dict = {}\n nouns = []\n for key in data_types.keys():\n\n obj = data_types[key]\n noun_key = obj['noun']\n\n skip = False\n\n if noun_key in ret_dict.keys():\n if ret_dict[noun_key]['count'] > 9:\n skip = True\n\n if skip is False:\n if noun_key in ret_dict.keys():\n ret_dict[noun_key]['count'] += obj['noun_frequency']\n ret_dict[noun_key]['polarity'] += obj['polarity']\n ret_dict[noun_key]['objects'].append(obj)\n else:\n ret_dict[noun_key] = {\n 'count': obj['noun_frequency'],\n 'objects': [obj],\n 'polarity': obj['polarity'],\n 'noun': noun_key\n }\n\n nouns.append(obj['noun'])\n\n final_ret = []\n for key in ret_dict.keys():\n # if (ret_dict[key]['count'] > 1) and (ret_dict[key]['polarity'] < -0.1 or ret_dict[key]['polarity'] > 0.1):\n ret_dict[key]['objects'] = sorted(ret_dict[key]['objects'], key=lambda x: x['noun_frequency'], reverse=True)\n ret_dict[key]['polarity'] = ret_dict[key]['polarity'] / len(ret_dict[key]['objects'])\n\n final_ret.append(ret_dict[key])\n\n final_ret = sorted(final_ret, key=lambda x: x['count'], reverse=True)\n return final_ret\n","sub_path":"server/mod_api/get_word_pairs.py","file_name":"get_word_pairs.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"467258443","text":"# _*_coding:utf-8_*_\n# TCP UDP\n# tcp 三次握手 类似打电话\n\nimport _thread\nimport os\nimport socket\nimport threading\n\nthreadLock = threading.Lock()\n\n\nclass MyThread(threading.Thread):\n\n def __init__(self, isServer):\n threading.Thread.__init__(self)\n self.isServer = isServer\n if isServer:\n self.server = socket.socket()\n else:\n self.client = socket.socket()\n\n def run(self):\n if self.isServer:\n self.server.bind(('127.0.0.1', 8995))\n self.server.listen()\n con, addr = self.server.accept()\n while 1:\n # threadLock.acquire()\n data = con.recv(1024)\n print(\"server recv \", data.decode('utf-8'))\n ret = os.popen(data.decode('utf-8'))\n msg = ret.read()\n if not msg.strip(): msg = \"ok\"\n con.send(msg.encode('utf-8'))\n # threadLock.release()\n\n else:\n self.client.connect(('127.0.0.1', 8995))\n while 1:\n # threadLock.acquire()\n msg = input(\"客户传送:\").strip()\n self.client.send(msg.encode())\n data = self.client.recv(10240)\n print(data.decode('utf-8'))\n # threadLock.release()\n\n\nthread1 = MyThread(True)\nthread2 = MyThread(False)\n# 线程不行,需要使用进程\nthread1.start()\nthread2.start()\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"457943915","text":"\"\"\"These tests make actual orders on the Bodega infrastructure.\n\nThey are not meant to be tested in an automated fashion.\n\"\"\"\n\nimport json\nimport logging\nimport os\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) # noqa\nSCRIPT_NAME = os.path.basename(__file__) # noqa\nSDMAIN_ROOT = \\\n os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..', '..')) # noqa\n\nfrom bodega_commands import BodegaCommands\n\nlog = logging.getLogger(os.path.basename(__name__))\n\n\ndef test_place_order(commands):\n requirements = {\n \"nickname_0\": {\n \"type\": \"rktest_yml\",\n \"requirements\": {\n \"platform\": \"DYNAPOD\"\n }\n },\n }\n order_sid = commands.place_order(requirements)[0]\n assert order_sid\n return order_sid\n\n\ndef test_close_order(commands, order_sid):\n assert commands.close_order(order_sid)\n\n\ndef test_describe_order(commands, order_sid):\n result = json.dumps(commands.describe_order(order_sid), indent=4,\n sort_keys=True)\n log.info(result)\n assert result\n\n\ndef test_extend_order(commands, order_sid):\n result = json.dumps(commands.extend_order(order_sid), indent=4,\n sort_keys=True)\n log.info(result)\n assert result\n\n\ndef test_raw_request(commands):\n result = json.dumps(commands.raw_request('GET', '/profile/'), indent=4,\n sort_keys=True)\n log.info(result)\n assert result\n\n\ndef test_list_orders(commands):\n user_profile = commands.get_current_user_profile()\n result = commands.list_orders(user_email=user_profile['email'],\n status='LIVE')\n result = json.dumps(result, indent=4, sort_keys=True)\n log.info(result)\n assert result\n\nif __name__ == '__main__':\n commands = BodegaCommands()\n\n order_sid = test_place_order(commands)\n test_describe_order(commands, order_sid)\n test_list_orders(commands)\n test_extend_order(commands, order_sid)\n test_close_order(commands, order_sid)\n test_raw_request(commands)\n","sub_path":"lab/bodega/client/bodega_commands_test.py","file_name":"bodega_commands_test.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"280511749","text":"import json\nimport os\nfrom multiprocessing.pool import ThreadPool\nfrom web3 import Web3, IPCProvider\n\nfrom custom_http_provider import CustomHTTPProvider\n\nINFURA_ADDRESS = 'https://mainnet.infura.io/v3/4facf9a657054a2287e6a4bec21046a3'\nDEFAULT_REQUEST_TIMEOUT = 30\n\nweb3_infura = Web3(CustomHTTPProvider(endpoint_uri=INFURA_ADDRESS, request_kwargs={'timeout': DEFAULT_REQUEST_TIMEOUT}))\n\nweb3 = Web3(IPCProvider())\n\nETH = 10 ** 18\n\nUNISWAP_BEGIN_BLOCK = 6627917\n\nHISTORY_BEGIN_BLOCK = 6628000\n\nHISTORY_CHUNK_SIZE = 5000\n\nREORG_PROTECTION_BLOCKS_COUNT = 50\n\nCURRENT_BLOCK = web3.eth.blockNumber - REORG_PROTECTION_BLOCKS_COUNT\n\nLOGS_BLOCKS_CHUNK = 1000\n\nTHREADS = 8\n\npool = ThreadPool(THREADS)\n\nwith open('abi/uniswap_factory.abi') as in_f:\n UNISWAP_FACTORY_ABI = json.load(in_f)\n\nwith open('abi/uniswap_exchange.abi') as in_f:\n UNISWAP_EXCHANGE_ABI = json.load(in_f)\n\nwith open('abi/erc_20.abi') as in_f:\n ERC_20_ABI = json.load(in_f)\n\nwith open('abi/str_erc_20.abi') as in_f:\n STR_ERC_20_ABI = json.load(in_f)\n\nwith open('abi/str_caps_erc_20.abi') as in_f:\n STR_CAPS_ERC_20_ABI = json.load(in_f)\n\nUNISWAP_FACTORY_ADDRESS = '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95'\n\nuniswap_factory = web3.eth.contract(abi=UNISWAP_FACTORY_ABI, address=UNISWAP_FACTORY_ADDRESS)\n\nHARDCODED_INFO = {\n '0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A': ('DGD', 'DGD', 9),\n '0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413': ('TheDAO', 'TheDAO', 16),\n '0x42456D7084eacF4083f1140d3229471bbA2949A8': ('Synth sETH', 'sETH old', 18),\n '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359': ('Sai Stablecoin v1.0', 'SAI', 18),\n}\n\nDIST_DIR = '../dist/uniswap/'\n\nLIQUIDITY_DATA = os.path.join(DIST_DIR, 'data/liquidity.csv')\n\nPROVIDERS_DATA = os.path.join(DIST_DIR, 'data/providers/{}.csv')\n\nROI_DATA = os.path.join(DIST_DIR, 'data/roi/{}.csv')\n\nVOLUME_DATA = os.path.join(DIST_DIR, 'data/volume/{}.csv')\n\nTOTAL_VOLUME_DATA = os.path.join(DIST_DIR, 'data/total_volume.csv')\n\nTOKENS_DATA = os.path.join(DIST_DIR, 'data/tokens.json')\n\nEVENT_TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'\n\nEVENT_TOKEN_PURCHASE = '0xcd60aa75dea3072fbc07ae6d7d856b5dc5f4eee88854f5b4abf7b680ef8bc50f'\n\nEVENT_ETH_PURCHASE = '0x7f4091b46c33e918a0f3aa42307641d17bb67029427a5369e54b353984238705'\n\nEVENT_ADD_LIQUIDITY = '0x06239653922ac7bea6aa2b19dc486b9361821d37712eb796adfd38d81de278ca'\n\nEVENT_REMOVE_LIQUIDITY = '0x0fbf06c058b90cb038a618f8c2acbf6145f8b3570fd1fa56abb8f0f3f05b36e8'\n\nALL_EVENTS = [EVENT_TRANSFER, EVENT_TOKEN_PURCHASE, EVENT_ETH_PURCHASE, EVENT_ADD_LIQUIDITY, EVENT_REMOVE_LIQUIDITY]\n\nINFOS_DUMP = 'infos.dump'\n\nLAST_BLOCK_DUMP = 'last_block.dump'\n\nGRAPHQL_LOGS_QUERY = '''\n{{\n logs(filter: {{fromBlock: {fromBlock}, toBlock: {toBlock}, addresses: {addresses}, topics: {topics}}}) {{\n data account {{ address }} topics index transaction {{ block {{ number }} }}\n }}\n}}'''\n\nGRAPHQL_ENDPOINT = 'http://localhost:8547/graphql'\n","sub_path":"uniswap/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"624265699","text":"import numpy as np\nspeed = np.loadtxt(r'C:\\Users\\CDT\\Desktop\\GUTS\\MSTanks\\speed.csv', delimiter=',')\nspeed2 = np.loadtxt(r'C:\\Users\\CDT\\Desktop\\GUTS\\MSTanks\\speed2.csv', delimiter=',')\nrotation = np.loadtxt(r'C:\\Users\\CDT\\Desktop\\GUTS\\MSTanks\\rotation.csv', delimiter=',')\nd = np.sqrt(((speed[16,0] - speed[0,0])**2) + ((speed[16,1]-speed[0,1])**2))\nd2 = np.sqrt(((speed2[16,0] - speed2[0,0])**2) + ((speed2[16,1]-speed2[0,1])**2))\ntimebetweenpol = 0.358853\nv = d / (16* timebetweenpol)\nv2 = d2 / (16* timebetweenpol)\navv = (v2 + v)/2\n\navpolltime = np.mean(rotation[:,2])\navrotperpoll = rotation[:,3]\n\nfor i in range(len(avrotperpoll)):\n if avrotperpoll[i] < 0:\n avrotperpoll[i] = avrotperpoll[i] + 360\n print(avrotperpoll[i])\n\ndegreepersecond = np.mean(avrotperpoll /0.358853)\n\n\n","sub_path":"speedrotation.py","file_name":"speedrotation.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"520267945","text":"import math\nfrom optparse import OptionParser\nfrom collections import namedtuple\n\npoint = namedtuple('Point', 'x, y')\n\n\n# Длинные читабельные имена функций это хорошо.\n# Короткие не очень читаьбельные - плохо\ndef dist(a, b):\n \"\"\"Calculate distance between two points: a and b.\"\"\"\n return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)\n\n\ndef mycartesian_product(some_list):\n \"\"\"Get cartesian product of a list with itself.\"\"\"\n pr = [] # Плохое имя\n for ind, item1 in enumerate(some_list[:-1], start=1):\n for item2 in some_list[ind:]:\n pr.append((item1, item2))\n\n return pr\n\n\ndef xy_from_file(filename):\n \"\"\"Read in point coordinates from a given file.\"\"\"\n with open(filename) as fobj:\n content = fobj.readlines()\n\n try:\n # ValueError может быть пойман только в момент выполннеия float(number)\n # Потому в try...except лучше заключить только его\n splited = [line.split() for line in content]\n points = [point(float(x), float(y)) for x, y in splited]\n except ValueError:\n return None\n\n return points\n\n\ndef main(filename='test_file.txt'):\n \"\"\"Main function.\"\"\"\n points = xy_from_file(filename)\n cartesian_prod = mycartesian_product(points)\n distances = [dist(p1, p2) for p1, p2 in cartesian_prod]\n\n min_ = min(distances)\n max_ = max(distances)\n\n print('min: %s\\nmax: %s' % (min_, max_))\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n opts, args = parser.parse_args()\n if not args:\n main()\n else:\n main(args[0])\n","sub_path":"homeworks/vlad_yan/1__4__distance/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"212015080","text":"''' File that sets up the parameters for the simulation to be run.\n This is the file that controls the distribution of labeled datapoints\n that both algorithms see, and also the action set with which EXP3 is run.\n'''\n\nimport numpy as np\nimport random\nimport math\nfrom copy import deepcopy\nfrom grinding_polytopes import * \nimport polytope as pc\nimport logging\nlogging.basicConfig()\n\ndef set_params(T, eps_exp3): \n np.random.seed()\n d = 2 # dimension of space\n p = 0.7 \n # variable is controlled by the outside file\n delta = 0.05 #radius of best-responses -- implicitly affects regret\n agent_type = [0]*T\n\n \n agent_type = np.random.binomial(1,p,T)\n\n true_labels = [1 if agent_type[i] else -1 for i in range(T)] \n\n #original feature vectors for agents\n x_real = []\n for i in range(T):\n if agent_type[i]:\n x_real.append(np.array([np.random.normal(0.6, 0.4), np.random.normal(0.4,0.6), 1]))\n else:\n x_real.append(np.array([np.random.normal(0.4, 0.6), np.random.uniform(0.6,0.4), 1]))\n\n calA_size_exp3 = 1000\n\n noise = []\n\n initial = []\n zero = np.array([0, 0, 1])\n one = np.array([1, 1, 1])\n curr_size = 0\n\n while curr_size < calA_size_exp3:\n temp = np.array([np.random.uniform(-1,1), np.random.uniform(-1,1), np.random.uniform(-1,1)])\n dist0 = np.abs(1.0*np.dot(temp,zero)/np.linalg.norm(temp[:d])) \n dist1 = np.abs(1.0*np.dot(temp,one)/np.linalg.norm(temp[:d])) \n if dist0 <= np.sqrt(2) and dist1 <= np.sqrt(2):\n initial.append(temp)\n curr_size += 1\n\n\n calA_size = len(initial)\n\n # construct initial polytope, i.e., [-1,1]^{d+1}\n V = np.array([ np.array([-1, -1, -1]), \n np.array([-1, -1, 1]),\n np.array([-1, 1, -1]),\n np.array([-1, 1, 1]),\n np.array([ 1, -1, -1]),\n np.array([ 1, -1, 1]),\n np.array([ 1, 1, -1]),\n np.array([ 1, 1, 1])])\n\n p_init = pc.qhull(V)\n\n # start with a prob and weight of 1 for the org polytope\n calA_exp3 = [init/np.linalg.norm(init[:d]) for init in initial]\n updated = [0]*T\n initial_polytope = Grind_Polytope(p_init, 1.0, 1.0, 2, T, 0.0, 0.0, updated)\n calA_grind = [initial_polytope] \n\n return (T, d, x_real, calA_exp3, calA_grind, agent_type, true_labels, delta, noise, p)\n \n\n","sub_path":"cont_code/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"531244074","text":"import logging\n\nfrom ..models import Stack, Service\nfrom ..utils import log_get_or_create\n\n\nlogger = logging.getLogger(__name__)\n\n\nROLE_GUESSES = dict(\n postgres='database',\n sql='database',\n mariadb='database',\n mongo='database',\n memcache='cache',\n redis='cache',\n celery='worker',\n worker='worker',\n api='backend',\n frontend='frontend',\n web='backend',\n)\n\nDEFAULT_ROLE = 'backend'\n\n\ndef guess_role_from(item):\n \"\"\"\n >>> guess_role_from('registry.plat2.leonidasoy.fi/leonidas2017-mariadb')\n 'database'\n \"\"\"\n for role_guess, guessed_role in ROLE_GUESSES.items():\n if role_guess in item:\n return guessed_role\n\n\ndef guess_role(service_slug, service_dict, default_role=DEFAULT_ROLE):\n \"\"\"\n Tries to guess role first from service_slug and then service_dict['image'].\n \"\"\"\n role = guess_role_from(service_slug)\n if role:\n return role\n\n role = guess_role_from(service_dict.get('image', ''))\n if role:\n return role\n\n return default_role\n\n\ndef env_list_to_dict(env_list):\n \"\"\"\n >>> env_list_to_dict(['KONTENA_LB_MODE=http', 'KONTENA_LB_VIRTUAL_HOSTS=leonidasoy.fi'])\n {'KONTENA_LB_MODE': 'http', 'KONTENA_LB_VIRTUAL_HOSTS': 'leonidasoy.fi'}\n \"\"\"\n return dict(env_item.split('=', 1) for env_item in env_list)\n\n\ndef get_service_env(service_dict, env_name, default=None):\n environment = service_dict.get('environment', dict())\n\n if isinstance(environment, list):\n environment = env_list_to_dict(environment)\n\n return environment.get(env_name, default)\n\n\ndef import_stack(stack_slug, stack_dict, project, grid, environment='staging'):\n stack, created = Stack.objects.get_or_create(\n slug=stack_slug,\n defaults=dict(\n name=stack_slug,\n project=project,\n grid=grid,\n environment=environment,\n description=stack_dict.get('description', ''),\n )\n )\n\n log_get_or_create(logger, stack, created)\n\n for service_slug, service_dict in stack_dict['services'].items():\n role = guess_role(service_slug, service_dict)\n hostnames = get_service_env(service_dict, 'KONTENA_LB_VIRTUAL_HOSTS', '').split()\n hostname = hostnames[0] if hostnames else ''\n\n service, created = Service.objects.get_or_create(\n stack=stack,\n slug=service_slug,\n defaults=dict(\n name=service_slug,\n description=service_dict.get('description', ''),\n role=role,\n hostname=hostname,\n )\n )\n\n log_get_or_create(logger, service, created)\n\n return stack\n","sub_path":"cmdb/importers/kontena.py","file_name":"kontena.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"31604935","text":"from subprocess import check_output\n\n\ndef get_armada_host_ip():\n output = check_output(['ip', 'route']).decode()\n for line in output.splitlines():\n if line.startswith('default'):\n return line.split()[2]\n return '172.17.0.1'\n\n\nARMADA_API_URL = 'http://{}:8900'.format(get_armada_host_ip())\n","sub_path":"docker-containers/microservice/packaging/microservice/opt/microservice/microservice/defines.py","file_name":"defines.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319651981","text":"import enum\nimport json\nimport os\nimport random\n\nfrom typing import Dict, List\n\n\nUSER_DATA_JSON = \"user_data.json\"\n\nR6_ATK = [\n \"Sledge\",\n \"Thatcher\",\n \"Ash\",\n \"Thermite\",\n \"Mick\",\n \"Tick\",\n \"Blitz\",\n \"IQ\",\n \"Fuze\",\n \"Glaz\",\n \"Buck\",\n \"Blackbeard\",\n \"Capitao\",\n \"Hibana\",\n \"Jackal\",\n \"Ying\",\n \"Zofia\",\n \"Dokkaebi\",\n \"Finka\",\n \"Lion\",\n \"Maverick\",\n \"Nomad\",\n \"Gridlock\",\n \"Spooky bitch atk\",\n \"Amaru\",\n \"Kali\",\n]\nR6_DEF = [\n \"Mute\",\n \"Smonk\",\n \"Castle\",\n \"Pulse\",\n \"Dick\",\n \"Rick\",\n \"Jager\",\n \"Bandit\",\n \"God\",\n \"Kapkan\",\n \"Frost\",\n \"Valkyrie\",\n \"Spooky bitch def\",\n \"Echo\",\n \"Mira\",\n \"Lesion\",\n \"Ela\",\n \"Vigil\",\n \"Alibi\",\n \"Maestro\",\n \"Clash\",\n \"Kaid\",\n \"Mozzie\",\n \"Warden\",\n \"Goyo\",\n \"Wamai\",\n]\n\n\nclass OperatorSide(enum.Enum):\n ATTACK = 0\n DEFENSE = 1\n\n\ndef _init():\n if not os.path.exists(USER_DATA_JSON):\n with open(USER_DATA_JSON, \"w\") as f:\n f.write(\"{}\")\n\n\ndef _get_valid_ops(side: OperatorSide, user_id: str) -> List[str]:\n with open(USER_DATA_JSON) as f:\n disabled_ops = json.load(f)\n\n if user_id not in disabled_ops:\n disabled_ops[user_id] = []\n\n with open(USER_DATA_JSON, \"w\") as f:\n json.dump(disabled_ops, f)\n\n if side == OperatorSide.ATTACK:\n possible_ops = R6_ATK\n else:\n possible_ops = R6_DEF\n return [op for op in possible_ops if op.lower() not in disabled_ops[user_id]]\n\n\ndef pick_attackers(user_id: int, num: int) -> List[str]:\n ops = _get_valid_ops(OperatorSide.ATTACK, str(user_id))\n return random.sample(ops, num)\n\n\ndef pick_defenders(user_id: int, num: int) -> List[str]:\n ops = _get_valid_ops(OperatorSide.DEFENSE, str(user_id))\n return random.sample(ops, num)\n\n\ndef disable_operators(user_id: int, ops: List[str]) -> List[str]:\n ops = [op.lower() for op in ops]\n user_str = str(user_id)\n with open(USER_DATA_JSON) as f:\n operators = json.load(f)\n disabled_ops = set(operators.get(user_str, [])) | set(ops)\n operators[user_str] = list(disabled_ops)\n\n with open(USER_DATA_JSON, \"w\") as f:\n json.dump(operators, f)\n return sorted(op.title() for op in operators[user_str])\n\n\ndef enable_operators(user_id: int, ops: List[str]) -> List[str]:\n ops = [op.lower() for op in ops]\n user_str = str(user_id)\n with open(USER_DATA_JSON) as f:\n operators = json.load(f)\n disabled_ops = set(operators.get(user_str, [])) - set(ops)\n operators[user_str] = list(disabled_ops)\n\n with open(USER_DATA_JSON, \"w\") as f:\n json.dump(operators, f)\n return sorted(op.title() for op in operators[user_str])\n\n\ndef get_available_ops(user_id: int) -> Dict[OperatorSide, List[str]]:\n user_str = str(user_id)\n return {\n OperatorSide.ATTACK: _get_valid_ops(OperatorSide.ATTACK, user_str),\n OperatorSide.DEFENSE: _get_valid_ops(OperatorSide.DEFENSE, user_str),\n }\n\n_init()\n","sub_path":"r6_helper.py","file_name":"r6_helper.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"138009203","text":"#!/usr/bin/env python\n#author: lizhen\n#date:\nimport userlog\nimport login\nimport tools\n\n\n#统计消费, 并写入记录\ndef compute_jine(shopping):\n '''\n shopping: 物品 单价 数量\n '''\n all_money = 0\n zongshu = {}\n for i in shopping:\n if zongshu.get(i[0]): #已购买\n zongshu[i[0]] = [i[1], zongshu[i[0]][1]+ i[2]]\n else:\n zongshu[i[0]] = [i[1], i[2]]\n print(\"您此次的消费记录:\".center(50,'*'))\n for k in zongshu:\n print(\"\\t\\t%s %s %s \" % (k, zongshu[k][1], zongshu[k][0]*zongshu[k][1]))\n all_money += zongshu[k][0]*zongshu[k][1]\n print(\"\".center(50, '*'))\n return all_money\n\n#购物清单, 和 购物操作\ndef menu_list(currentuser):\n exit_flag = False\n shopping_list = []\n gongzi = login.get_balance(currentuser)\n menu = (\n ('家电类',('洗衣机',2000),('台式机(dell)',5600),('mac',8000)),\n ('手机类',('华为',3400), ('小米',2200),('联想',500)),\n ('衣服类', ('皮甲',500),('短裤', 100),('连衣裙', 340)),\n\n )\n while not exit_flag:\n for i in range(len(menu)):\n print(\"%s. %s\" % (i, menu[i][0]))\n selected_cls = input(\"购买类型[(Q)uit,(B)ack,[S]how:\") .strip()\n if selected_cls == '':\n continue\n if selected_cls.lower() == 's':\n compute_jine(shopping_list)\n continue\n if selected_cls.lower() == 'q':\n print(\"正在退出系统........\")\n #此处 需要查看用户是否已购买物品\n if len(shopping_list) != 0:\n sum_money = compute_jine(shopping_list)\n tools.write_money(currentuser, sum_money)\n else:\n exit(0)\n elif selected_cls.lower() == 'b':\n sum_money = compute_jine(shopping_list)\n tools.write_money(currentuser, sum_money)\n exit_flag = True\n\n elif selected_cls.isdigit() and int(selected_cls) < len(menu):\n w_flag = False\n wuping = menu[int(selected_cls)][1:]\n\n while not w_flag:\n for j in range(len(wuping)):\n print(\"%s. %s %s\" % (j, wuping[j][0], wuping[j][1]))\n selected_wp = input(\"购买物品[(Q)uit,(B)ack,[S]how][%s]: \" % ( menu[int(selected_cls)][0] )).strip()\n if selected_wp == '':\n continue\n if selected_wp.lower() == 's':\n compute_jine(shopping_list)\n continue\n if selected_wp.lower() == 'q':\n print(\"正在退出系统......\")\n #此处 需要查看用户是否已购买物品\n if len(shopping_list) != 0:\n sum_money = compute_jine(shopping_list)\n tools.write_money(currentuser, sum_money)\n exit(0)\n elif selected_wp.lower() == 'b':\n w_flag = True\n elif selected_wp.isdigit() and int(selected_wp) < len(wuping):\n print(\"您购买了 [%s],请输入购买数量(默认1)\" % wuping[int(selected_wp) ][0],end=' ')\n shuliang = input()\n if shuliang.isdigit():\n shuliang = int(shuliang)\n else:\n shuliang = 1\n # 计算总钱数, 判断 当前剩余的钱是否 足够购买\n # ���加购物车信息\n zongqian = wuping[int(selected_wp)][1] * shuliang\n if zongqian <= gongzi:\n #wuping[int(selected_wp)格式: 名称 单价\n shopping = (wuping[int(selected_wp)][0], wuping[int(selected_wp)][1], shuliang)\n userlog.shop_log(currentuser, shopping)\n shopping_list.append( shopping )\n gongzi -= zongqian\n #print(shopping_list)\n else:\n print(\"您当前的余额为 %s,请去努力工作吧.\" % gongzi)\n\n else:\n print(\"无法识别您的输入,请不要调戏\")\n continue\n else:\n print(\"无法识别您的输入,请不要调戏\")\n continue\n return shopping_list\n\n\n\nif __name__ == \"__main__\":\n menu_list('lizhen', 200000)","sub_path":"day2/homework/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"386310800","text":"# Enrichment_Report.py\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom functions import *\r\n\r\ndef main():\r\n \r\n Enrichment_Time_Table = \"\"\"{| class=\"wikitable\"\r\n!colspan=\"3\" style=\"background: #7fffd4| Enrichment Time\r\n|-\r\n! Date !! Days !! % On Time\r\n\"\"\" \r\n \r\n for i, b in enumerate(run_sql_statement('Enrichment_Time')):\r\n if i == 0:\r\n try:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Yesterday || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\"\r\n except:\r\n try:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Yesterday || 0 || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\" \r\n except:\r\n try:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Yesterday || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" ||0\r\n\"\"\" \r\n except:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Yesterday || 0 ||0\r\n\"\"\" \r\n\r\n if i == 1:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Last Week || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\"\r\n if i == 2:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| MTD || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\"\r\n if i == 3:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Last Month || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\" \r\n if i == 4:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| This month Last Year || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\"\r\n if i == 5:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| YTD || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\"\r\n\"\"\"\r\n if i == 6:\r\n Enrichment_Time_Table = Enrichment_Time_Table + \"\"\"\r\n|-\r\n| Last Year || \"\"\" + \"{0:.1f}\".format(b[1]) + \"\"\" || \"\"\" + \"{:.0%}\".format(b[2]) + \"\"\" \r\n|}\r\n\"\"\"\r\n\r\n Yesterdays_Enrichment_Table = \"\"\"{| class=\"wikitable sortable\"\r\n! style=\"background: #7fffd4|Order Number !! style=\"background: #7fffd4|Item Number !! style=\"background: #7fffd4|ER Number !! style=\"background: #7fffd4|Order Entered !! style=\"background: #7fffd4|Order Reentered !! style=\"background: #7fffd4|Work Days\r\n\"\"\"\r\n \r\n for h in run_sql_statement('Yesterdays_Enrichment'):\r\n for c in range(6):\r\n if c == 0:\r\n Yesterdays_Enrichment_Table = Yesterdays_Enrichment_Table + \"\"\"\r\n|-\r\n| \"\"\" + str(h[c])\r\n \r\n elif c == 3 or c == 4:\r\n try:\r\n Yesterdays_Enrichment_Table = Yesterdays_Enrichment_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ \"{:%d-%b-%y %H:%M %p}\".format(h[c]) # for a new column\r\n except:\r\n Yesterdays_Enrichment_Table = Yesterdays_Enrichment_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ str(h[c]) # for a new column\r\n else:\r\n Yesterdays_Enrichment_Table = Yesterdays_Enrichment_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ str(h[c]) # for a new column\r\n \r\n\r\n\r\n Yesterdays_Enrichment_Table = Yesterdays_Enrichment_Table + \"\"\"\r\n|}\"\"\"\r\n\r\n\r\n Shiment_History_Table = \"\"\"{| class=\"wikitable sortable\"\r\n! style=\"background: #7fffd4|Order Number !! Priority !! style=\"background: #7fffd4|Item Number !! style=\"background: #7fffd4|ER Number !! style=\"background: #7fffd4|Order Entered !! style=\"background: #7fffd4|Order Shipped !! style=\"background: #7fffd4|Work Days\r\n\"\"\"\r\n \r\n for h in run_sql_statement('Shipment_History'):\r\n for c in range(7):\r\n if c == 0:\r\n Shiment_History_Table = Shiment_History_Table + \"\"\"\r\n|-\r\n| \"\"\" + str(h[c])\r\n \r\n elif c == 3 or c == 4:\r\n try:\r\n Shiment_History_Table = Shiment_History_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ \"{:%d-%b-%y %H:%M %p}\".format(h[c]) # for a new column\r\n except:\r\n Shiment_History_Table = Shiment_History_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ str(h[c]) # for a new column\r\n else:\r\n Shiment_History_Table = Shiment_History_Table + \"\"\"|| style=\"background: #ffffff| \"\"\"+ str(h[c]) # for a new column\r\n \r\n\r\n\r\n Shiment_History_Table = Shiment_History_Table + \"\"\"\r\n|}\"\"\"\r\n\r\n\r\n\r\n\r\n \r\n article = \"\"\"\r\n== Enrichment Time ==\r\n\r\nTurnaround goal is 5 days or under 95% of the time.\r\n\r\n\"\"\" + Enrichment_Time_Table + \"\"\"\r\n== Yesterday's Enrichment ==\r\n\r\n\"\"\" + Yesterdays_Enrichment_Table + \"\"\"\r\n\r\n\r\n== Shipping Pirority Metric ==\r\n\r\nfile:shipments.jpg|Priority Breakdown\r\nfile:agile.jpg|Agile Order Level\r\nFile:total duration.png|Total Durations\r\nFile:Monthly performance.jpg|Monthly FTS Performance\r\nfile:shipdist.jpg|Shipping Duration Distribution (all)\r\nfile:monthshipdist.jpg|Shipping Duration Distribution (month)\r\nfile:sc.png|SC Performance\r\nfile:ftp eng.png|Eng Performance\r\nfile:ftp eng monthly.png|Eng Performance Month\r\nfile:ftp prod.png|Production Performance\r\n \r\n\r\n\r\n\r\n== Shipment History ==\r\n\r\n\"\"\" + Shiment_History_Table + \"\"\"\r\n\r\n \r\n\r\n\r\n\r\n\r\nPrevious \r\nNext \r\n\r\n\r\n[[category:Automated Reports]][[category:Enrichment]][[category:Engineering]]\r\n \"\"\" \r\n update_wiki_page(article)\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"Enrichment_Report.py","file_name":"Enrichment_Report.py","file_ext":"py","file_size_in_byte":6557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"554963720","text":"from CreateDT.ID3 import createID3Tree\nfrom CreateDT.C4_5 import createC4_5Tree\nfrom CreateDT.CART import createCARTTree\nfrom CreateDT.PlotDT import createPlot\nimport matplotlib.pyplot as plt\n\n# 读取数据集文件\ndef loadDataSet(fileName):\n \"\"\"\n :param fileName:数据集文件\n :return:数据集\n \"\"\"\n file = open(fileName) # 打开数据集文件\n line = file.readline() # 读取每行所有元素\n dataSet = [] # 数据集初始化\n while line:\n data = line.strip('\\n').split(',') # 按照','划分数据,并剔除回车符\n dataSet.append(data) # 将每行数据放到数据集\n line = file.readline()\n file.close()\n return dataSet\n\n# 构造原始数据集和属性集合\noriginalDataSet = loadDataSet('DataSet/watermelon.txt')\nlabels = originalDataSet[0]\ndataSet = originalDataSet[1:]\n\ndef showDT(dataSet, labels):\n \"\"\"\n :param dataSet:数据集\n :param labels:属性标签\n \"\"\"\n\n # ID3算法生成分类决策树\n ID3Tree = createID3Tree(list(dataSet), list(labels))\n print('The ID3 Decision Tree is', ID3Tree)\n\n # C4.5算法生成分类决策树\n C4_5Tree = createC4_5Tree(list(dataSet), list(labels))\n print('The C4.5 Decision Tree is', C4_5Tree)\n\n # CART算法生成分类决策树\n CARTTree = createCARTTree(list(dataSet), list(labels))\n print('The CART Decision Tree is', CARTTree)\n\n # 显示各个决策树\n createPlot(ID3Tree, 'ID3 Decision Tree')\n createPlot(C4_5Tree, 'C4.5 Decision Tree')\n createPlot(CARTTree, 'CART Decision Tree')\n plt.show() # 显示决策树\n\nshowDT(dataSet, labels)\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"573145710","text":"import math\nimport dateutil.parser\nimport os\nimport time\nimport logging\nimport boto3\nimport json\n\nimport requests\nfrom requests_aws4auth import AWS4Auth\n\n\nregion = 'us-east-1' # e.g. us-east-1\nservice = 'es'\ncredentials = boto3.Session().get_credentials()\nawsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)\n\nhost = 'https://search-photo-storage-3gex4uqz77gf2abn5bvis25ilm.us-east-1.es.amazonaws.com' # the Amazon ES domain, with https://\nindex = 'photos'\ntype = '_search'\nurl = host + '/' + index + '/' + type + '/'\n\nheaders = { \"Content-Type\": \"application/json\" }\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n\n\"\"\" --- Helpers to build responses which match the structure of the necessary dialog actions --- \"\"\"\n\n\ndef get_slots(intent_request):\n return intent_request['currentIntent']['slots']\n\n\ndef elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):\n return {\n 'sessionAttributes': session_attributes,\n 'dialogAction': {\n 'type': 'ElicitSlot',\n 'intentName': intent_name,\n 'slots': slots,\n 'slotToElicit': slot_to_elicit,\n 'message': message\n }\n }\n\n\ndef close(session_attributes, fulfillment_state, message):\n response = {\n 'sessionAttributes': session_attributes,\n 'dialogAction': {\n 'type': 'Close',\n 'fulfillmentState': fulfillment_state,\n 'message': message\n }\n }\n\n return response\n\n\ndef delegate(session_attributes, slots):\n return {\n 'sessionAttributes': session_attributes,\n 'dialogAction': {\n 'type': 'Delegate',\n 'slots': slots\n }\n }\n\n\n\"\"\" --- Helper Functions --- \"\"\"\n\n\ndef parse_int(n):\n try:\n return int(n)\n except Exception:\n return False\n\n\ndef build_validation_result(is_valid, violated_slot, message_content):\n if message_content is None:\n return {\n \"isValid\": is_valid,\n \"violatedSlot\": violated_slot,\n }\n\n return {\n 'isValid': is_valid,\n 'violatedSlot': violated_slot,\n 'message': {'contentType': 'PlainText', 'content': message_content}\n }\n\n\ndef isvalid_date(date):\n try:\n dateutil.parser.parse(date)\n return True\n except ValueError:\n return False\n\n\ndef validate_searchkey(keyword_1,keyword_2):\n keywords = ['tree', 'person', 'dog', 'glass','milk','coffee cup', 'cup', 'alcohol','human','finger','face', 'wine glass', 'goblet']\n if keyword_1 is not None and keyword_1.lower() not in keywords:\n return build_validation_result(False,\n 'searchkeyone',\n 'Sorry, we only have {}, would you like a different type of photo? '.format(keywords))\n\n if keyword_2 is not None and keyword_2.lower() not in keywords:\n \n return build_validation_result(False,\n 'searchkeytwo',\n 'Sorry, we only have {}, would you like a different type of photo? '.format(keywords))\n\n return build_validation_result(True, None, None)\n\n\n\"\"\" --- Functions that control the bot's behavior --- \"\"\"\n \n \n\n\ndef search_intent(intent_request):\n \"\"\"\n Performs dialog management and fulfillment for ordering flowers.\n Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action\n in slot validation and re-prompting.\n \"\"\"\n \n keyword_1 = get_slots(intent_request)[\"searchkeyone\"]\n keyword_2 = get_slots(intent_request)[\"searchkeytwo\"]\n source = intent_request['invocationSource']\n\n if source == 'DialogCodeHook':\n # Perform basic validation on the supplied input slots.\n # Use the elicitSlot dialog action to re-prompt for the first violation detected.\n slots = get_slots(intent_request)\n\n validation_result = validate_searchkey(keyword_1,keyword_2)\n if not validation_result['isValid']:\n slots[validation_result['violatedSlot']] = None\n return elicit_slot(intent_request['sessionAttributes'],\n intent_request['currentIntent']['name'],\n slots,\n validation_result['violatedSlot'],\n validation_result['message'])\n\n # Pass the price of the flowers back through session attributes to be used in various prompts defined\n # on the bot model.\n \n output_session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}\n\n\n return delegate(output_session_attributes, get_slots(intent_request))\n\n # Order the flowers, and rely on the goodbye message of the bot to define the message to the end user.\n # In a real bot, this would likely involve a call to a backend service.\n \n # sqs = boto3.resource('sqs')\n\n # queue = sqs.get_queue_by_name(QueueName='restaurants_request')\n # msg = {\"location\":location, \"cuisine\": cuisine,\"numberofpeople\":num_people, \"phone\": phone}\n # response = queue.send_message(MessageBody=json.dumps(msg))\n # print(response)\n \n print(keyword_1)\n print(keyword_2)\n print('start searching')\n \n if keyword_2 is not None:\n query ={\n \"query\":{\n \"bool\":{\n \"must\":[\n {\"term\": {\"labels\": keyword_1}},\n {\"term\": {\"labels\": keyword_2}}]\n }\n },\n \"size\": 1000 #number of rows you want to get in the result\n }\n else:\n query ={\n \"query\":{\n \"match\": {\n \"labels\" : keyword_1\n }\n },\n \"size\": 1000 #number of rows you want to get in the result\n }\n \n r = requests.get(url, auth=awsauth, json=query, headers=headers)\n\n results = json.loads(r.text)\n print(results)\n \n ## to do\n n_hits = int(results['hits']['total']['value'])\n print(n_hits)\n \n photo_object = ''\n \n if(len(results['hits']['hits'])==0):\n print(\"No matching photo Found\")\n return close(intent_request['sessionAttributes'],\n 'Fulfilled',\n {'contentType': 'PlainText',\n 'content': 'None'}) \n else:\n for hit in results['hits']['hits']: #loop the data\n photo_object +=(hit['_source']['objectKey'])\n photo_object += ' '\n print(\"photo Data\\n\",hit)\n # use hit['_source'][''] to retreive the required feild data from your lambda\n #print(\"User Name-->\",hit['_source']['id']) \n\n\n #return photo index to frontend\n print(photo_object)\n #return photo_idx\n return close(intent_request['sessionAttributes'],\n 'Fulfilled',\n {'contentType': 'PlainText',\n 'content': photo_object\n })\n\n\n\"\"\" --- Intents --- \"\"\"\n\n\ndef dispatch(intent_request):\n \"\"\"\n Called when the user specifies an intent for this bot.\n \"\"\"\n\n logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))\n\n intent_name = intent_request['currentIntent']['name']\n\n # Dispatch to your bot's intent handlers\n if intent_name == 'SearchIntent':\n return search_intent(intent_request)\n\n raise Exception('Intent with name ' + intent_name + ' not supported')\n\n\n\"\"\" --- Main handler --- \"\"\"\n\n\ndef lambda_handler(event, context):\n \"\"\"\n Route the incoming request based on intent.\n The JSON body of the request is provided in the event slot.\n \"\"\"\n # By default, treat the user request as coming from the America/New_York time zone.\n os.environ['TZ'] = 'America/New_York'\n time.tzset()\n logger.debug('event.bot.name={}'.format(event['bot']['name']))\n \n \n \n print('event is following:')\n print(event)\n\n return dispatch(event)\n\n\n\n","sub_path":"src/search_photos/search_photos.py","file_name":"search_photos.py","file_ext":"py","file_size_in_byte":8170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"566480697","text":"import csv\nimport itertools\n\n# Load data from\ndef load_data(from_file, from_year, to_year):\n # Recupere les matches des dernières saisons\n matches = []\n with open(from_file, 'r', newline='') as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n for r in reader:\n season = int(r['Season'])\n if season not in range(from_year, to_year):\n continue\n row = {}\n for f in ['Date', 'HomeTeam', 'AwayTeam', 'Country', 'League']:\n row[f] = r[f].strip()\n skip = False\n for f in ['FTHG', 'FTAG', 'Season']:\n try:\n row[f] = int(r[f])\n except:\n skip = True\n if not skip:\n matches.append(row)\n\n # Trouve toutes les équipes\n teams = set(r['HomeTeam'] for r in matches) | set(r['AwayTeam'] for r in matches)\n # Liste complète des matches, chaque match apparaisant deux fois, une par équipe,\n # Determine le nombre de matches joués par équipe\n match_list = [r['HomeTeam'] for r in matches] + [r['AwayTeam'] for r in matches]\n teams_count = { t: match_list.count(t) for t in teams}\n total_match = len(match_list)\n # Plus petit et plus grand\n max_score = max(max(r['FTHG'], r['FTAG']) for r in matches)\n min_score = min(min(r['FTHG'], r['FTAG']) for r in matches)\n return matches, total_match, teams, teams_count, min_score, max_score\n\n## Va chercher à séparer les équipes en groupes de meilleurs attaquants et défenseur\ndef split_teams_into_groups(matches, teams, n_cat):\n\n # On crée le meilleur groupe à la main. De niveau n_cat-1\n best_group = set([\"Lyon\", \"Monaco\", \"Paris SG\"])\n best_group = set()\n adjusted_teams = teams - best_group\n\n\n # Les matchs joués par équipe\n played = {t : [] for t in adjusted_teams}\n for r in matches:\n if r['HomeTeam'] in adjusted_teams:\n played[r['HomeTeam']].append(r)\n if r['AwayTeam'] in adjusted_teams:\n played[r['AwayTeam']].append(r)\n # Goals matked and received per team\n goal_marked = {t:0 for t in adjusted_teams}\n goal_received = {t:0 for t in adjusted_teams}\n for r in matches:\n if r['HomeTeam'] in adjusted_teams:\n goal_marked[r['HomeTeam']] += r['FTHG']\n goal_received[r['HomeTeam']] += r['FTAG']\n if r['AwayTeam'] in adjusted_teams:\n goal_marked[r['AwayTeam']] += r['FTAG']\n goal_received[r['AwayTeam']] += r['FTHG']\n # Average using the number of matches playes by a team\n # Nombre de buts moyens données ou recus. Les équipes sont classées par ordre de force croissante\n for t in adjusted_teams:\n goal_marked[t] /= len(played[t])\n goal_received[t] /= len(played[t])\n\n goal_marked_ordered = sorted(goal_marked.items(), key=lambda x:x[1], reverse=False)\n goal_received_ordered = sorted(goal_received.items(), key=lambda x:x[1], reverse=True)\n #print(goal_marked_ordered)\n #print(goal_received_ordered)\n\n # La répartition par groupe se fait de telle sorte que le nombre de matchs joués par groupe soit équivalent\n # sinon, à cause du bas de tableau changeant, on a une mauvaise répartition\n\n # OLD : grpoupes de même taille\n #group_size_old = len(goal_marked_ordered) / n_cat\n #attack_group_old = {t: int(i / group_size_old) for i,(t,_) in enumerate(goal_marked_ordered)}\n #defense_group_old = {t: int(i / group_size_old) for i,(t,_) in enumerate(goal_received_ordered)}\n\n total_match = sum(len(played[t]) for t in adjusted_teams)\n group_size = total_match / (n_cat - (1 if len(best_group) > 0 else 0)) # car j'ai séparé le groupe de tête à la main\n goal_marked_match = [len(played[t]) for t,_ in goal_marked_ordered]\n goal_marked_match = list(itertools.accumulate(goal_marked_match))\n goal_marked_match = [int(g / group_size) for g in goal_marked_match]\n attack_group = {t: min(g, n_cat - 1 - (1 if len(best_group) > 0 else 0)) for (t, _), g in zip(goal_marked_ordered, goal_marked_match)}\n #print(attack_group)\n\n goal_received_match = [len(played[t]) for t,_ in goal_received_ordered]\n goal_received_match = list(itertools.accumulate(goal_received_match))\n goal_received_match = [ int(g / group_size) for g in goal_received_match]\n defense_group = {t: min(g, n_cat - 1 - (1 if len(best_group) > 0 else 0)) for (t, _), g in zip(goal_received_ordered, goal_received_match)}\n #print(defense_group)\n\n # ajout du groupe de tête\n for t in best_group:\n defense_group[t] = n_cat - 1\n attack_group[t] = n_cat - 1\n return attack_group, defense_group\n\ndef compute_base_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat):\n # Regroupement des scores par classes d'attaque\n base_statistics = {} # dictionnaire indexé par (Aa, Ad, Ba, Bd, s1, s2)\n base_2 = {} # dictionnaire indexé par (Aa, Ad, Ba, Bd} = { 's': {(s1,s2):nbre de buts, 'p':(s1,s2):proba, 'l':# échantillons)\n\n # initialise base_2\n ra = range(n_cat)\n sca = range(min_score, max_score + 1)\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n base_2[(Aa, Ad, Ba, Bd)] = {'s': [[0 for _ in list(sca)] for _ in list(sca)], 'l': 0}\n\n for r in matches:\n Aa = attack_group[r['HomeTeam']]\n Ad = defense_group[r['HomeTeam']]\n Ba = attack_group[r['AwayTeam']]\n Bd = defense_group[r['AwayTeam']]\n s1 = r['FTHG']\n s2 = r['FTAG']\n k = (Aa, Ad, Ba, Bd, s1, s2)\n if k not in base_statistics:\n base_statistics[k] = 0\n base_statistics[k] += 1\n base_2[(Aa, Ad, Ba, Bd)]['l'] += 1\n base_2[(Aa, Ad, Ba, Bd)]['s'][s1][s2] += 1\n\n base_statistics = {k: v / len(matches) for k, v in base_statistics.items()}\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n n = base_2[(Aa, Ad, Ba, Bd)]['l']\n if n > 0:\n base_2[(Aa, Ad, Ba, Bd)]['p'] = [[base_2[(Aa, Ad, Ba, Bd)]['s'][i][j] / n for j in list(sca)] for i in list(sca)]\n\n return base_statistics, base_2\n\ndef write_matrices_to_file(rebuilt_matrices, to_file):\n if to_file is not '':\n with open(to_file, 'w', newline='') as csvfile:\n writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['Aa', 'Ad', 'Ba', 'Bd', 'l', 's1', 's2', 'p'])\n writer.writeheader()\n for (Aa, Ad, Ba, Bd), r in rebuilt_matrices.items():\n if 'p' not in r:\n continue\n p = r['p']\n l = r['l']\n for s1, row in enumerate(p):\n for s2, probability in enumerate(row):\n w_r = {'Aa': Aa, 'Ad':Ad, 'Ba':Ba, 'Bd':Bd, 'l':l, 's1':s1, 's2':s2, 'p':probability}\n writer.writerow(w_r)\n\ndef write_matrices_flat_to_file(rebuilt_matrices, to_file):\n if to_file is not '':\n with open(to_file, 'w', newline='') as csvfile:\n first = False\n fieldnames = ['Aa', 'Ad', 'Ba', 'Bd', 'l']\n for (Aa, Ad, Ba, Bd), r in rebuilt_matrices.items():\n if 'pgd' not in r or 'ptg' not in r:\n continue\n pg = r['pgd']\n tg = r['ptg']\n l = r['l']\n if not first:\n for k in pg:\n fieldnames.append(\"GD_{}\".format(k))\n for k in tg:\n fieldnames.append(\"TG_{}\".format(k))\n writer = csv.DictWriter(csvfile, delimiter=',',fieldnames=fieldnames)\n writer.writeheader()\n first = True\n w_r = {'Aa': Aa, 'Ad': Ad, 'Ba': Ba, 'Bd': Bd, 'l': l}\n for k, probability in pg.items():\n w_r[\"GD_{}\".format(k)] = probability\n for k, probability in tg.items():\n w_r[\"TG_{}\".format(k)] = probability\n writer.writerow(w_r)\n\ndef split_teams_by_seasons_into_groups(matches, teams, n_cat):\n\n # On crée le meilleur groupe à la main. De niveau n_cat-1\n # Les matchs joués par équipe\n played = {}\n for r in matches:\n season = r['Season']\n ht = \"{}_{}\".format(r['HomeTeam'], season)\n if ht not in played:\n played[ht] = [r]\n else:\n played[ht].append(r)\n at = \"{}_{}\".format(r['AwayTeam'], season)\n if at not in played:\n played[at] = [r]\n else:\n played[at].append(r)\n\n adjusted_teams = list(played.keys())\n # Goals matked and received per team\n goal_marked = {t:0 for t in adjusted_teams}\n goal_received = {t:0 for t in adjusted_teams}\n for r in matches:\n season = r['Season']\n ht = \"{}_{}\".format(r['HomeTeam'], season)\n at = \"{}_{}\".format(r['AwayTeam'], season)\n goal_marked[ht] += r['FTHG']\n goal_received[ht] += r['FTAG']\n goal_marked[at] += r['FTAG']\n goal_received[at] += r['FTHG']\n # Average using the number of matches playes by a team\n # Nombre de buts moyens données ou recus. Les équipes sont classées par ordre de force croissante\n for t in adjusted_teams:\n goal_marked[t] /= len(played[t])\n goal_received[t] /= len(played[t])\n\n goal_marked_ordered = sorted(goal_marked.items(), key=lambda x:x[1], reverse=False)\n goal_received_ordered = sorted(goal_received.items(), key=lambda x:x[1], reverse=True)\n #print(goal_marked_ordered)\n #print(goal_received_ordered)\n\n # groupes de même taille\n group_size = len(goal_marked_ordered) / n_cat\n attack_group = {t: int(i / group_size) for i,(t,_) in enumerate(goal_marked_ordered)}\n defense_group = {t: int(i / group_size) for i,(t,_) in enumerate(goal_received_ordered)}\n\n return attack_group, defense_group\n\n# distance entre deux Aa, Ad, Ba, Bd\ndef dist_v(a, b):\n Aa, Ad, Ba, Bd = a\n Aa_, Ad_, Ba_, Bd_ = b\n return abs(Aa - Aa_) + abs(Ad - Ad_) + abs(Ba - Ba_) + abs(Bd - Bd_)\n\n# Construit les stats manquantes\ndef build_matrices_rebuilt(stats, threshold_1, threshold_2, filter_threshold):\n stats_rebuilt = {}\n flat = [(k, r['pgd'],r['ptg'], r['l']) for k, r in stats.items() if r['l'] > 0]\n #data_full = sorted([(k, p, l) for k, p, l in flat if l > 0], key=lambda x: x[2], reverse=True)\n for k, r in list(stats.items()):\n if r['l'] >= threshold_1:\n stats_rebuilt[k] = r\n continue\n # ordonne les vecteurs proches par distance croissante\n closest = sorted([(kc, rc['l'], dist_v(k, kc)) for kc, rc in stats.items() if rc['l'] > filter_threshold], key=lambda x:x[2])\n closest_l = list(itertools.takewhile(lambda x: x < threshold_2, itertools.accumulate(l for _, l, _ in closest)))\n closest = closest[:len(closest_l) + 1]\n new_matrix_pg = {k:0 for k,_ in r['gd'].items()}\n new_matrix_tg = {k:0 for k,_ in r['tg'].items()}\n t = 0\n for kc, l, d in closest:\n f = l / (1+d)\n t += f\n new_matrix_pg = {k:x + f * stats[kc]['pgd'][k] for k, x in new_matrix_pg.items()}\n new_matrix_tg = {k:x + f * stats[kc]['ptg'][k] for k, x in new_matrix_tg.items()}\n #t = sum(l for _, l ,_ in closest)\n new_matrix_pg = {k:x / t for k,x in new_matrix_pg.items()}\n new_matrix_tg = {k:x / t for k,x in new_matrix_tg.items()}\n stats_rebuilt[k] = {\n 'pgd': new_matrix_pg,\n 'ptg': new_matrix_tg,\n 'l': sum(l for _, l ,_ in closest)\n }\n return stats_rebuilt\n\n\ndef compute_1N2_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat):\n # Regroupement des scores par classes d'attaque\n base_statistics = {} # dictionnaire indexé par (Aa, Ad, Ba, Bd, s1, s2)\n s_stats = {} # dictionnaire indexé par (Aa, Ad, Ba, Bd} = { 's': {(s1,s2):nbre de buts, 'p':(s1,s2):proba, 'l':# échantillons)\n\n # initialise base_2\n ra = range(n_cat)\n #sca = range(min_score, max_score + 1)\n sca = range(3) # 0-2, 3-5, 6+ (divise par 3)\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n s_stats[(Aa, Ad, Ba, Bd)] = {'s': [[0, 0, 0] for _ in list(sca)], 'l': 0}\n\n for r in matches:\n season = r['Season']\n ht = \"{}_{}\".format(r['HomeTeam'], season)\n at = \"{}_{}\".format(r['AwayTeam'], season)\n Aa = attack_group[ht]\n Ad = defense_group[ht]\n Ba = attack_group[at]\n Bd = defense_group[at]\n s1 = r['FTHG']\n s2 = r['FTAG']\n k = (Aa, Ad, Ba, Bd, s1, s2)\n if k not in base_statistics:\n base_statistics[k] = 0\n base_statistics[k] += 1\n gd = 1 if s1 > s2 else (-1 if s1 < s2 else 0)\n tg = min((s1 + s2) // 3, 2)\n s_stats[(Aa, Ad, Ba, Bd)]['l'] += 1\n s_stats[(Aa, Ad, Ba, Bd)]['s'][tg][gd + 1] += 1\n\n base_statistics = {k: v / len(matches) for k, v in base_statistics.items()}\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n n = s_stats[(Aa, Ad, Ba, Bd)]['l']\n if n > 0:\n s_stats[(Aa, Ad, Ba, Bd)]['p'] = [[s_stats[(Aa, Ad, Ba, Bd)]['s'][i][j] / n for j in range(3)] for i in list(sca)]\n\n return s_stats\n\n\ndef compute_simple_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat):\n # Regroupement des scores par classes d'attaque\n results = {} # dictionnaire indexé par (Aa, Ad, Ba, Bd} = { 'gd': {(gd):nbre de buts de différecence, 'pgd':proba, 'l':# échantillons)\n\n # initialise base_2\n gd_range = range(-2, 3)\n tg_range = range(4)\n ra = range(n_cat)\n sca = range(min_score, max_score + 1)\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n results[(Aa, Ad, Ba, Bd)] = {\n 'gd': {i:0 for i in list(gd_range)},\n 'l': 0,\n 'tg': {i: 0 for i in list(tg_range)}\n }\n\n for r in matches:\n season = r['Season']\n ht = \"{}_{}\".format(r['HomeTeam'], season)\n at = \"{}_{}\".format(r['AwayTeam'], season)\n Aa = attack_group[ht]\n Ad = defense_group[ht]\n Ba = attack_group[at]\n Bd = defense_group[at]\n s1 = r['FTHG']\n s2 = r['FTAG']\n results[(Aa, Ad, Ba, Bd)]['l'] += 1\n gd = s1 - s2\n gd = max(-2, gd)\n gd = min(2, gd) # gd compris entre -2 et 2\n tg = min((s1 + s2) // 2, 3) # Nombre de couples de buts, 0-1, 2-3, 4-5, 6-7 ou plus\n results[(Aa, Ad, Ba, Bd)]['gd'][gd] += 1\n results[(Aa, Ad, Ba, Bd)]['tg'][tg] += 1\n\n for Aa, Ad, Ba, Bd in itertools.product(ra, ra, ra, ra):\n n = results[(Aa, Ad, Ba, Bd)]['l']\n if n > 0:\n results[(Aa, Ad, Ba, Bd)]['pgd'] = {i:results[(Aa, Ad, Ba, Bd)]['gd'][i] / n for i in list(gd_range)}\n results[(Aa, Ad, Ba, Bd)]['ptg'] = {i: results[(Aa, Ad, Ba, Bd)]['tg'][i] / n for i in list(tg_range)}\n return results\n\n\n# =================================================================================================\n## Load data from files, identify teams and number of matches per team\ndef load_compute_matrices(from_year, to_year, threshold_1, threshold_2, filter_threshold, n_cat, from_file):\n matches, total_match, teams, teams_count, min_score, max_score = load_data(from_file, from_year, to_year)\n\n ## Séparer les équipes en groupes de meilleurs attaquants et défenseur\n attack_group, defense_group = split_teams_by_seasons_into_groups(matches, teams, n_cat)\n\n # Première approche : cumuler par Aa,Ad, Ba,Bd,s1,s2\n #_, base_2 = compute_base_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat)\n #s_stats = compute_simple_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat)\n s_stats = compute_1N2_statistics(matches, attack_group, defense_group, min_score, max_score, n_cat)\n\n filtered = {k:v for k, v in s_stats.items() if v['l'] > filter_threshold}\n\n rebuilt = build_matrices_rebuilt(s_stats, threshold_1, threshold_2, filter_threshold)\n\n return s_stats, rebuilt, filtered\n\nif __name__ == \"__main__\":\n n_cat = 4\n stats, rebuilt, filtered = load_compute_matrices(\n 1900, 2020,\n threshold_1=100,\n threshold_2=200,\n filter_threshold=100,\n n_cat=n_cat,\n from_file='paris_sportifs_filtered.csv'\n )\n write_matrices_flat_to_file(stats, 'matrices_flat_cat{}.csv'.format(n_cat))\n write_matrices_flat_to_file(rebuilt, 'matrices_flat_rebuilt_cat{}.csv'.format(n_cat))\n write_matrices_flat_to_file(filtered, 'matrices_flat_filtered_cat{}.csv'.format(n_cat))\n","sub_path":"build_1N2_from_history.py","file_name":"build_1N2_from_history.py","file_ext":"py","file_size_in_byte":16642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"519648700","text":"import unittest\r\nimport os\r\nfrom sdc11073.wsdiscovery import WSDiscoverySingleAdapter\r\nfrom sdc11073 import pmtypes\r\nfrom sdc11073.location import SdcLocation\r\nfrom sdc11073.sdcclient import SdcClient\r\nfrom tests.mockstuff import SomeDevice\r\n\r\nloopback_adapter = 'Loopback Pseudo-Interface 1' if os.name == 'nt' else 'lo'\r\n\"\"\"\r\nBase test to use in all test that require device or a client. This sets up a default device and client\r\nand has connect method.\r\n\"\"\"\r\n\r\nclass BaseTest(unittest.TestCase):\r\n\r\n def setUp(self):\r\n self.wsdiscovery = WSDiscoverySingleAdapter(loopback_adapter)\r\n self.wsdiscovery.start()\r\n self._locValidators = [pmtypes.InstanceIdentifier('Validator', extensionString='System')]\r\n\r\n def tearDown(self):\r\n self.wsdiscovery.stop()\r\n\r\n def setUpCocoDraft10(self):\r\n self.cocoFinalLocation = SdcLocation(fac='tklx', poc='CU1', bed='cocoDraft10Bed')\r\n\r\n self.sdcDeviceCoCoFinal = SomeDevice.fromMdibFile(self.wsdiscovery, None, '70041_MDIB_Final.xml')\r\n self.sdcDeviceCoCoFinal.startAll()\r\n self.sdcDeviceCoCoFinal.setLocation(self.cocoFinalLocation, self._locValidators)\r\n xAddr = self.sdcDeviceCoCoFinal.getXAddrs()\r\n self.sdcClientCocoFinal = SdcClient(xAddr[0],\r\n deviceType=self.sdcDeviceCoCoFinal.mdib.sdc_definitions.MedicalDeviceType,\r\n validate=True)\r\n self.sdcClientCocoFinal.startAll()\r\n\r\n def stopDraft10(self):\r\n self.sdcClientCocoFinal.stopAll()\r\n self.sdcDeviceCoCoFinal.stopAll()\r\n","sub_path":"tests/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"224695693","text":"import sys\nimport os\nimport numpy as np\nimport argparse\nimport glob\nimport time\nsys.path.append('.')\nfrom util.Data import DataLoader\nfrom tkinter import *\n\n\"\"\"\nARG PARSE\n\"\"\"\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--backend', default='pytorch',help='DL backend')\nparser.add_argument('--data_paths', default=[],nargs='*',help='Data paths')\nparser.add_argument('--inference', default=False, help='Real time inference', action='store_true')\nparser.add_argument('--update_interval', default=10, type=int, help='Update interval (ms)')\nargs = parser.parse_args()\n\nbackend = args.backend\ndata_paths = args.data_paths\ninference = args.inference\nupdate_interval = args.update_interval\n\n\"\"\"\nMODEL INIT\n\"\"\"\nsys.path.append('./model')\nif backend == 'tensorflow':\n\n import tensorflow as tf\n from model import Model\n\n sess = tf.Session()\n m = Model()\n m.load(sess)\n\nelif backend == 'pytorch':\n\n from model_pytorch import Model\n\n m = Model()\n m.load()\n\n\ndef drawBoard(board,canvas,b_pix=20):\n canvas.delete('all')\n h, w = board.shape\n for i in range(h):\n for j in range(w):\n _v = board[i][j]\n if _v == 0:\n color = 'black'\n elif _v == 1:\n color = 'white'\n else:\n color = 'gray'\n canvas.create_rectangle(j * b_pix, i * b_pix, (j+1) * b_pix, (i+1) * b_pix, fill=color)\n\ndef drawPolicy(policy,canvas,blocksize=30,offset_x=10,offset_y=100):\n canvas.delete('all')\n for i, v in enumerate(policy):\n color = 'gray' + str(int(100*v))\n canvas.create_rectangle(offset_x+i*blocksize,offset_y,offset_x+(i+1)*blocksize,offset_y+blocksize,fill=color)\n\nindex = 0\n\nif __name__ == '__main__':\n master = Tk()\n master.title('Replay')\n\n list_of_data = []\n for path in data_paths:\n list_of_data += glob.glob(path)\n data = DataLoader(data_paths)\n\n canvas_frame = Frame(master)\n canvas_frame.grid(row=0,column=0,rowspan=10,columnspan=5)\n\n canvas_frame_2 = Frame(master)\n canvas_frame_2.grid(row=3,column=5,rowspan=7,columnspan=5)\n\n info_frame = Frame(master)\n info_frame.grid(row=0,column=5,rowspan=1,columnspan=5)\n\n control_frame = Frame(master)\n control_frame.grid(row=1,column=5,rowspan=1,columnspan=5)\n\n control_frame_2 = Frame(master)\n control_frame_2.grid(row=2,column=5,rowspan=1,columnspan=5)\n\n list_of_updates = []\n\n board_canvas = Canvas(canvas_frame,width=200,height=440)\n board_canvas.grid(row=1,column=1)\n def update_board_canvas(index):\n global data\n board = data.getBoard(index)\n drawBoard(board,board_canvas)\n list_of_updates.append(update_board_canvas)\n\n policy_canvas_label = Label(canvas_frame_2,text='Policy MCTS')\n policy_canvas_label.grid(row=0,column=0)\n policy_canvas = Canvas(canvas_frame_2,width=200,height=50)\n policy_canvas.grid(row=1,column=0)\n policy_canvas_label_2 = Label(canvas_frame_2,text='Policy prediction')\n policy_canvas_label_2.grid(row=2,column=0)\n policy_canvas_2 = Canvas(canvas_frame_2,width=200,height=50)\n policy_canvas_2.grid(row=3,column=0)\n value_label = Label(canvas_frame_2)\n value_label.grid(row=4,column=0)\n class_label = Label(canvas_frame_2)\n class_label.grid(row=5,column=0)\n def update_policy_canvas(index):\n global data\n policy = data.getPolicy(index)\n if inference:\n if backend == 'tensorflow':\n pred = m.inference(sess,[data.getBoard(index)[:,:,None]])\n value_pred = pred[0][0]\n policy_pred = pred[1][0]\n class_pred = np.argmax(pred[2][0])\n elif backend == 'pytorch':\n pred = m.inference(data.getBoard(index)[None,None,:,:])\n value_pred = pred[0][0][0]\n policy_pred = pred[1][0]\n class_pred = 0\n else:\n value_pred = -1\n policy_pred = np.empty((6,)) \n class_pred = 0\n drawPolicy(policy,policy_canvas,offset_y=0)\n drawPolicy(policy_pred,policy_canvas_2,offset_y=0)\n value_label.config(text='Value prediction: %.3f'%value_pred)\n class_label.config(text='Class prediction: %d'%class_pred)\n list_of_updates.append(update_policy_canvas)\n\n current_index_label = Label(info_frame)\n current_index_label.pack()\n def update_current_index_label(index):\n current_index_label.config(text='Current index: %d'%index)\n list_of_updates.append(update_current_index_label)\n\n current_cycle_label = Label(info_frame)\n current_cycle_label.pack()\n def update_current_cycle_label(index):\n global data\n current_cycle_label.config(text='Current cycle: %d'%data.getCycle(index))\n list_of_updates.append(update_current_cycle_label)\n \n current_score_label = Label(info_frame)\n current_score_label.pack()\n def update_current_score_label(index):\n global data\n current_score_label.config(text='Current score: %d'%data.getScore(index))\n list_of_updates.append(update_current_score_label)\n\n def next_index():\n global index\n index = data.bound_index(index+1)\n next_index_button = Button(control_frame,text='Next',command=next_index)\n next_index_button.grid(row=0,column=0)\n\n def prev_index():\n global index\n index = data.bound_index(index-1) \n prev_index_button = Button(control_frame,text='Prev',command=prev_index)\n prev_index_button.grid(row=0,column=1)\n\n play_after_id = None\n def play():\n global index\n global play_after_id\n index = data.bound_index(index+1)\n play_after_id = play_button.after(update_interval,play)\n play_button = Button(control_frame,text='Play',command=play)\n play_button.grid(row=0,column=2)\n\n def stop():\n global play_after_id\n if play_after_id:\n master.after_cancel(play_after_id)\n play_after_id = None\n stop_button = Button(control_frame,text='Stop',command=stop)\n stop_button.grid(row=0,column=3)\n\n\n index_entry_label = Label(control_frame_2,text='Goto index:')\n index_entry_label.grid(row=0,column=0)\n def set_index_entry(e):\n global index\n index = data.bound_index(int(index_entry.get()))\n print(index)\n index_entry = Entry(control_frame_2,width=10)\n index_entry.bind(\"\",set_index_entry)\n index_entry.grid(row=0,column=1)\n \n \"\"\"\n interval_entry_label = Label(control_frame_2,text='Update interval:')\n interval_entry_label.grid(row=1,column=0)\n def set_update_interval(e):\n global update_interval\n update_interval = int(interval_entry.get())\n interval_entry = Entry(control_frame_2,width=10)\n interval_entry.bind(\"\",set_update_interval)\n interval_entry.grid(row=1,column=1)\n \"\"\"\n def global_updater():\n global index\n for u in list_of_updates:\n u(index)\n master.after(update_interval, global_updater) \n master.after(update_interval, global_updater) \n mainloop()\n","sub_path":"tools/replay.py","file_name":"replay.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"297894494","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nimport time\nimport csv\n\nbrowser=webdriver.Firefox()\ntarget=open('2014Part2.csv', 'r')\ntarget=list(csv.reader(target))\ntime.sleep(4)\nfor line in target:\n\tpos=line[0]\n\tname=line[1]\n\tnameAndPos=name+\"_\"+pos+\"_\"\n\tprint(\"Extracting: \"+name)\n\tbrowser.get(line[2])\n\tdelay=3\n\ttry:\n\t\tWebDriverWait(browser, delay).until(EC.presence_of_element_located((By.XPATH, '//*[@id=\"page_content\"]/div[3]/div[1]/div/span[5]')))\n\t\tcsvElement=browser.find_element_by_xpath('//*[@id=\"page_content\"]/div[3]/div[1]/div/span[5]')\n\t\tfileName=nameAndPos+\"2014log.csv\"\n\t\tprint(\"Scraping for \"+fileName)\n\t\tif csvElement:\n\t\t\tcsvElement.click()\n\t\t\tcsvText=browser.find_element_by_xpath('//*[@id=\"csv_stats\"]').text.encode('utf-8')\n\t\t\ttotalCsvText=name+','+pos+csvText\n\t\t\ttarget=open(fileName, 'w')\n\t\t\ttarget.write(totalCsvText)\n\t\t\ttarget.close()\n\t\t\tprint(\"Done Extraction\")\n\texcept TimeoutException:\n\t\tprint(\"Took too long Or Couldnt Find\")","sub_path":"csvDownloader.py","file_name":"csvDownloader.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"191129508","text":"\n# format = '%{l}%[i3workspace]%{c}%[i3windowtitle]%{r}%[battery]%[date]%[time]%[volumestatus]'\nformat_display0 = '%{U#FFD79921}%{l}%[i3workspace]%{c}%[i3windowtitle]%{r}%[cpuload]%[networking]%[battery]%[volumestatus]%[date]%[time]'\nformat_display1 = '%{l}%[i3workspace]%{r}%[date]%[time]'\n#format_display0 = '%{U#FFD79921}%{l}%[bspwmworkspace]%{c}%[bspwmwindowtitle]%{r}%[cpuload]%[networking]%[battery]%[volumestatus]%[date]%[time]'\n#format_display1 = '%{l}%[bspwmworkspace]%{r}%[date]%[time]'\n\n# either i3wm or bspwm\nwm = 'i3wm'\n# sections = ['Battery', 'i3Workspace', 'i3WindowTitle', 'Date',\n# 'Time', 'VolumeStatus', 'Networking', 'CPULoad']\n\nsections = ['Battery', 'Date', 'i3Workspace', 'i3WindowTitle',\n 'Time', 'VolumeStatus', 'Networking', 'CPULoad']\n\nfont1 = 'Droid Sans Mono:size=18'\nfont2 = 'FontAwesome:size=22:charwidth=40'\nfont3 = 'Fontello:size=24:charwidth=40'\n#\n# font2 = 'FontAwesome:size=22:charwidth=40'\n# font3 = 'Fontello:size=24:charwidth=40'\n\ngeometry = 'x50+0+0'\nuoline_height = '4'\n\ngrey1 = '#FF1D1F21'\ngrey2 = '#FF282A2E'\ngrey3 = '#FF454A4F'\ngrey4 = '#FF89984'\nlight_grey = '#FFC5C8C6'\nx = '#FF454A4F'\ndark_green = '#FF8C9440'\nlight_green = '#FFB5BD68'\ndark_red = '#FFCC241D'\nlight_red = '#FFFB4934'\ndark_yellow = '#FFD79921'\nlight_yellow = '#FFFABD2F'\ndark_blue = '#FF458588'\nlight_blue = '#FF83A598'\n\nbg1 = grey1\nbg2 = grey2\nbg3 = grey3\nbg4 = light_grey\nbg5 = dark_green\nbg6 = light_green\nbg7 = dark_red\nbg8 = light_red\nbg9 = dark_yellow\nbg10 = light_yellow\nbg11 = dark_blue\nbg12 = light_blue\n\nfg1 = grey1\nfg2 = grey2\nfg3 = grey3\nfg4 = light_grey\nfg5 = dark_green\nfg6 = light_green\nfg7 = dark_red\nfg8 = light_red\nfg9 = dark_yellow\nfg10 = light_yellow\nfg11 = dark_blue\nfg12 = light_blue\n\ni3workspace_format = '%{T3}%s'\ni3workspace_format_focused = '%[bg6]%[fg1]%%{+u} %s %%{-u}'\ni3workspace_format_urgent = '%[bg9]%[fg1] %s '\ni3workspace_format_default = '%[fg1]%[bg5] %s '\ni3windowtitle_format = '%[fg4]%[bg1] %s '\ni3windowtitle_max_length = 80\n\nbspwmworkspace_format = '%{T3}%s'\nbspwmworkspace_format_focused = '%[bg6]%[fg1]%%{+u} %s %%{-u}'\nbspwmworkspace_format_urgent = '%[bg9]%[fg1] %s '\nbspwmworkspace_format_active = '%[fg1]%[bg5] %s '\nbspwmworkspace_format_inactive = '%[fg4]%[bg2] %s '\nbspwmworkspace_show_inactive = False\nbspwmworkspace_names = ['1 ', '2 ', '3 ', '4 ', '5 ',\n '6 ', '7 ', '8 ', '9 ', '0 ']\n\n\nbspwmwindowtitle_format = '%[fg4]%[bg1] %s '\nbspwmwindowtitle_max_length = 80\n\n\ncpuload_format = '%[bg1]%[fg6]%[fg4]%5s '\ncpuload_action1 = 'urxvt -geometry 200x60 -name htop -e htop'\n\nnetworking_format = '%[bg1]%[fg12] %[icon] %s'\nnetworking_icons_wireless = ['']\nnetworking_icons_wired = ['\\ue818']\nnetworking_action1 = 'nm-connection-editor'\n\nbattery_format = '%[bg1]%[icon_color] %[icon] %[fg4]%-3s '\nbattery_icons = ['', '', '', '', '']\nbattery_icon_colors = ['%[fg7]', '%[fg9]', '%[fg12]', '%[fg5]']\nbattery_action1 = 'xfce4-power-manager-settings'\n\nvolumestatus_format = '%[bg1]%[fg12] %[icon]%[fg4]%-3s '\nvolumestatus_icons = ['\\uf026', '\\uf027', '\\uf028']\nvolumestatus_action1 = 'pavucontrol'\nvolumestatus_action2 = 'pulse.py mute-toggle'\nvolumestatus_action4 = 'pulse.py +'\nvolumestatus_action5 = 'pulse.py -'\n\ndate_format = '%[fg1]%[bg5] %s'\ntime_format = ' %s '\n","sub_path":"lemonbar/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"604441884","text":"'''\nMake some simple test data for looking at the \nvarious transformations used to make more \ncomplex test data and the phaser-ng system \nitself.\n\n@author: Simon Wilshin\n@contact: swilshin@rvc.ac.uk\n@date: Mar 2013\n'''\n\nfrom numpy import arange,cos,sin,array\nfrom numpy.random import randn\n\ndef simpleTestData(s0=0.05, w0=0.05, N=10000,D=2,T=[0.0,0.0]):\n assert D>1, \"Cant make test data less than 2D in this way\"\n y = s0*randn(D,N)\n y = array([(1+y[0])*cos(w0*arange(y.shape[1])+y[1]),(1+y[0])*sin(w0*arange(y.shape[1])+y[1])]).T+T\n return(y)\n","sub_path":"formphase/phaserngutil/simpletestdata.py","file_name":"simpletestdata.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"61201615","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport time\nfrom datetime import timedelta, datetime\n\nfrom textblob import TextBlob\nfrom tqdm import tqdm\n\nimport pygsheets\nimport tweepy\n\n\nclass Deployment:\n\n def __init__(self, base_directory, context):\n\n # Load in the twitter secrets and tokens from the environment variables\n self.consumer_key = os.environ['CONSUMER_KEY']\n self.consumer_secret = os.environ['CONSUMER_SECRET']\n self.access_token = os.environ['ACCESS_TOKEN']\n self.access_token_secret = os.environ['ACCESS_TOKEN_SECRET']\n\n # Set up the connection to twitter\n self.twitter_api = self.setup_twitter()\n\n # Setup the connection to Google, using the environment variable for the GOOGLE_CREDENTIALS\n # This method assumes you have an environment variable loaded with the content of the service account\n # credentials json\n self.google_sheet = pygsheets.authorize(service_account_env_var='GOOGLE_CREDENTIALS')\n\n # Set the spreadsheet_id from the environment variables\n self.spreadsheet_id = os.environ['SPREADSHEET_ID']\n\n # Set the day of today\n self.today = datetime.today()\n\n def setup_twitter(self):\n \"\"\"\n Use the Tweepy package to connect to the twitter API and return the connection object\n \"\"\"\n\n auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)\n auth.set_access_token(self.access_token, self.access_token_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, retry_count=2, retry_delay=240, timeout=120)\n\n try:\n api.verify_credentials()\n print(\"Authentication Twitter OK\")\n except tweepy.error.TweepError as e:\n print(f\"Error during authentication: {e}\")\n raise e\n\n return api\n\n def request(self, data):\n \"\"\"\n Make the request by first collecting the tweets and sentiments of a day and a certain hashtag and then\n inserting them in a Google sheet\n \"\"\"\n\n hashtag = data.get('hashtag', 'MlOps') # If no hashtag is given, use MlOps\n day = data.get('day', 'yesterday') # If no day is given, use 'yesterday'\n\n # Parse the user inputted day and retrieve the end date of the query ('until')\n day, until = self.parse_date(day=day)\n\n # Retrieve tweets from 'day' to 'until'\n texts = self.retrieve_tweets(hashtag=hashtag, day=day, until=until)\n\n # Determine the sentiment over the recovered tweets\n results = self.get_sentiment(texts=texts, day=day)\n\n # Append the values to the specified Google Sheet\n sheet = self.google_sheet.open_by_key(key=self.spreadsheet_id)\n # Open first worksheet of spreadsheet\n wk1 = sheet[0]\n # Values will be appended after the last non-filled row of the table without overwriting\n wk1.append_table(values=results, overwrite=False)\n\n return None\n\n def parse_date(self, day):\n \"\"\"\n Parse the user inputted date to be of yyyy-mm-dd and return the day and until date\n \"\"\"\n\n date_format = \"%Y-%m-%d\"\n\n if day == \"yesterday\":\n # Convert the day and until date to the correct string format\n day = (self.today - timedelta(days=1)).strftime(date_format)\n until = self.today.strftime(date_format)\n\n else:\n # Check if the given date is in the correct format and not longer than 7 days ago\n try:\n day = datetime.strptime(day, date_format)\n if day < (self.today - timedelta(days=8)):\n raise ValueError\n except ValueError:\n raise Exception(\n f\"Input for day is incorrect, it should be in the format of yyyy-mm-dd and should be no longer \"\n f\"than 7 days ago\")\n\n # Convert the day and until date to the correct string format\n until = (day + timedelta(days=1)).strftime(date_format)\n day = day.strftime(date_format)\n\n return day, until\n\n def retrieve_tweets(self, hashtag, day, until):\n \"\"\"\n Return the tweet texts with the hashtag 'hashtag' that were created in one day\n \"\"\"\n\n texts = []\n print(f\"Retrieving tweets between {day} and {until}\")\n\n retry = 0\n done = False\n\n # Query the Twitter api for all tweets on the specified hashtag and day and add them to a list\n while not done:\n try:\n for tweet in tqdm(tweepy.Cursor(\n self.twitter_api.search, q=hashtag, count=20, until=until, lang=\"en\", result_type=\"populair\"\n ).items()):\n if tweet.created_at.strftime(\"%Y-%m-%d\") == day:\n texts.append(tweet.text)\n done = True\n\n except tweepy.error.TweepError as e:\n # Retry after 60 seconds if the connection gets lost\n print(f\"Something went wrong while querying for tweets: {e}\")\n time.sleep(60)\n retry += 1\n if retry < 4:\n # Only make a maximum of 3 retry attempts\n print(f\"Retry attempt: {retry}\")\n continue\n raise e\n\n print(f\"{len(texts)} tweets retrieved\")\n return texts\n\n @staticmethod\n def get_sentiment(texts, day):\n \"\"\"\n Perform sentiment analysis over all retrieved tweets and return the overall results\n \"\"\"\n\n print(\"Calculating sentiment\")\n\n neutral_list = []\n positive_list = []\n negative_list = []\n\n for tweet in tqdm(texts):\n t = TextBlob(tweet).sentiment.polarity\n\n if t > 0.1:\n positive_list.append(t)\n elif t < -0.1:\n negative_list.append(t)\n else:\n neutral_list.append(t)\n\n print(f\"Sentiment calculated over {len(texts)} tweets from day {day}\")\n\n # Convert the day to the exact format necessary for the Tableau dashboard\n day = datetime.strptime(day, \"%Y-%m-%d\").strftime(\"%d-%m-%Y\")\n result = [day, len(positive_list), len(neutral_list), len(negative_list)]\n\n print(f\"Result: {result}\")\n return result\n","sub_path":"twitter-sentiment-analysis/twitter-sentiment-analysis/sentimentanalysis_deployment_package/deployment.py","file_name":"deployment.py","file_ext":"py","file_size_in_byte":6323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"538879678","text":"import re\n# Formatter\n\n#from coding.settings_local import STATIC_URL\nfrom oaa_examples_django.settings import STATIC_URL\n\n\ndef OAAMarkupToHTML(str):\n str1 = \"\"\n \n if str and len(str):\n str = str.replace(\"%s\", \"must\")\n \n code = \"\"\n for c in str:\n if c == '@':\n str1 += code;\n if code == \"\":\n code = \"\"\n else:\n code = \"\"\n else:\n str1 += c \n return str1\n\ndef OAAMarkupToText(str):\n str1 = \"\"\n\n if str and len(str):\n str = str.replace(\"%s\", \"must\")\n \n for c in str:\n if c != '@':\n str1 += c \n \n return str1\n\n\n\ndef HTMLToSourceCodeFormat(text):\n \"\"\"A filter to format the sample HTML for rendering the soruce code\"\"\"\n try:\n out = re.sub(r'&','&', text)\n out = re.sub(r'\\t', ' ', out)\n out = re.sub(r'<', '<', out)\n out = re.sub(r'>', '>', out)\n out = re.sub(r'<HL1>', '', out)\n out = re.sub(r'</HL1>', ' ', out)\n out = re.sub(r'<HL2>', '', out)\n out = re.sub(r'</HL2>', ' ', out)\n out = re.sub(r'\\n', ' \\n', out)\n out = re.sub(r' ', ' ', out)\n out = re.sub(r'{{EXAMPLE_MEDIA}}', STATIC_URL + 'examples/', out)\n return out\n except (TypeError, NameError, AttributeError):\n return ''\n\n\ndef OAAMarkupRemoveHighlightCode(text):\n\n \"\"\"Remove tags for highlighting for rendering the code as HTML.\"\"\"\n\n try:\n out = re.sub(r'', '', text)\n out = re.sub(r' ', '', out)\n out = re.sub(r'', '', out)\n out = re.sub(r' ', '', out)\n out = re.sub(r'{{EXAMPLE_MEDIA}}', STATIC_URL + 'examples/', out)\n return out\n except (TypeError, NameError, AttributeError):\n return ''\n\n ","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"446158615","text":"import numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport math\n\nclass BodyPart:\n def __init__(self, length,mass, CoM, Inertia,distal,proximal,time):\n self.time=time\n self.sample=len(distal[0])\n self.length=length\n self.CoM=CoM\n self.mass=mass\n self.Inertia=Inertia\n self.distal=distal\n self.proximal=proximal\n self.ProximForce=[np.zeros(self.sample),np.zeros(self.sample)]\n self.ProximMoment=np.zeros(self.sample)\n self.angle = np.zeros(self.sample)\n self.omega=np.zeros(self.sample)\n self.alpha=np.zeros(self.sample)\n self.velProxim=[np.zeros(self.sample),np.zeros(self.sample)]\n self.accelProxim=[np.zeros(self.sample),np.zeros(self.sample)]\n self.accelCoM=[np.zeros(self.sample),np.zeros(self.sample)]\n def absangle(self):\n unfil=np.zeros(self.sample)\n for i in range(0,self.sample):\n unfil[i]=np.arctan2((self.proximal[1][i]-self.distal[1][i]),(self.proximal[0][i]-self.distal[0][i]))\n self.angle=filterdata(unfil,5)\n return self.angle\n\n def omega(self): #j1 is joint angle dataframe #n is number of datapoints\n unfil=np.zeros(self.sample)\n BodyPart.absangle(self)\n for i in range(1,self.sample-1):\n unfil[i] = (self.angle[i+1]-self.angle[i-1])/(self.time[i+1]-self.time[i-1])\n self.omega=filterdata(unfil,5)\n return self.omega\n\n def alpha(self): #j1 is joint angle dataframe #n is number of datapoints \n BodyPart.omega(self)\n unfil=np.zeros(self.sample)\n for i in range(1,self.sample-1):\n unfil[i] = (self.omega[i+1]-self.omega[i-1])/(self.time[i+1]-self.time[i-1])\n self.alpha=filterdata(unfil,5)\n return self.alpha\n\n def velProxim(self): #j1 is joint angle dataframe #n is number of datapoints \n unfil=[np.zeros(self.sample),np.zeros(self.sample)]\n for i in range(1,self.sample-1):\n unfil[0][i] = (self.proximal[0][i+1]-self.proximal[0][i-1])/(self.time[i+1]-self.time[i-1])\n unfil[1][i] = (self.proximal[1][i+1]-self.proximal[1][i-1])/(self.time[i+1]-self.time[i-1])\n self.velProxim[0]=filterdata(unfil[0],5)/1000\n self.velProxim[1]=filterdata(unfil[1],5)/1000\n return self.velProxim\n \n def accelProxim(self): #j1 is joint angle dataframe #n is number of datapoin\n BodyPart.velProxim(self)\n unfil=[np.zeros(self.sample),np.zeros(self.sample)]\n for i in range(1,self.sample-1):\n unfil[0][i] = (self.velProxim[0][i+1]-self.velProxim[0][i-1])/(self.time[i+1]-self.time[i-1])\n unfil[1][i] = (self.velProxim[1][i+1]-self.velProxim[1][i-1])/(self.time[i+1]-self.time[i-1])\n self.accelProxim[0]=filterdata(unfil[0],5)\n self.accelProxim[1]=filterdata(unfil[1],5)\n return self.accelProxim\n \n def accelCoM(self):\n r=self.length-self.CoM\n BodyPart.accelProxim(self)\n BodyPart.alpha(self)\n unfil=[np.zeros(self.sample),np.zeros(self.sample)]\n for i in range(1,self.sample):\n unfil[0][i]=self.accelProxim[0][i]-(r*self.alpha[i]*math.sin(self.angle[i])+self.omega[i]*self.omega[i]*r*math.cos(self.angle[i]))\n unfil[1][i]=self.accelProxim[1][i]+r*self.alpha[i]*math.cos(self.angle[i])-self.omega[i]*self.omega[i]*r*math.sin(self.angle[i])\n self.accelCoM[0]=filterdata(unfil[0],5)\n self.accelCoM[1]=filterdata(unfil[1],5)\n return self.accelCoM \n\n def Forces(self,R,M):\n BodyPart.accelCoM(self)\n for i in range(1,self.sample):\n self.ProximForce[0][i]=R[0][i]+self.mass*self.accelCoM[0][i];\n self.ProximForce[1][i]=R[1][i]+self.mass*self.accelCoM[1][i]+self.mass*9.81;\n self.ProximMoment[i]=M[i]+R[0][i]*self.length*math.sin(self.angle[i])-R[1][i]*self.length*math.cos(self.angle[i])-self.mass*9.81*self.CoM*math.cos(self.angle[i])+(self.Inertia+self.mass*self.CoM*self.CoM)*self.alpha[i];\n return self.ProximForce,self.ProximMoment\n \ndef Power(omega1,omega2,M):\n Jw=omega2-omega1\n power=np.multiply(Jw,M)\n return power\n \n \ndef filterdata(y,n):\n from scipy.signal import filtfilt\n b = [1.0 / n] * n\n a = 1\n yy = filtfilt(b,a,y)\n return yy;\n\ndef AnthroData(weight,height):\n data=np.zeros(19)\n misc= (7.8*9.6*9.6*49.5)+(46.84*31.6*31.6*50.3)+2*(2.7*16.4*16.4*32.3)+2*(2.7*13.7*13.7*30.3)+2*(0.6*8.2*8.2*29.7) #sum of Icm of all the upper body parts\n data[0]= weight*68.2/100 #weight of UB\n data[1]= height*14.2/100 #height of com of UB from hip \n data[2]= data[0]*data[1]*data[1]+misc #moment for UB\n data[3]= weight*9.9/100#weight of thigh\n data[4]= height*25.4/100#height of thigh\n data[5]= data[4]*43.3/100#height of com thigh\n data[6]= data[3]*data[4]*data[4]*32.3/100#moment of thigh\n data[7]= weight*4.6/100#weight of shank\n data[8]= height*23.3/100#height of shank\n data[9]= data[8]*43/100 #height of com shank\n data[10]= data[7]*data[8]*data[8]*30.2/100 #moment of shank\n data[11]= weight*(1.4-0.361)/100#weight of foot\n data[12]= height*(11.7-3.53)/100 #height of foot\n data[13]= data[12]*50/100 #height of com foot\n data[14]= data[11]*data[12]*data[12]*47.5/100 #moment of foot\n data[15]=weight*.361/100 #weight of toe\n data[16]=height*3.53/100 #height of toe\n data[17]=data[16]/2 #height of com of toe\n data[18]=data[15]*data[16]*data[16]/12 #moment of toe\n return data","sub_path":"limb.py","file_name":"limb.py","file_ext":"py","file_size_in_byte":5523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"12395018","text":"from django.db import models\r\nfrom uuid import uuid4\r\nfrom .persona import Persona\r\nfrom tools.base import CreatedModifiedModel\r\n\r\n\r\nclass Capacitacion(CreatedModifiedModel):\r\n \"\"\"\r\n Describe una autorización para la utilización de una clase de máquina en\r\n el laboratorio. Una persona puede tener múltiples capacitaciones.\r\n La relación con el capacitador es opcional ya que no se tiene información\r\n de todas las capacitaciones.\r\n \"\"\"\r\n\r\n id = models.UUIDField(primary_key=True, default=uuid4, editable=False)\r\n persona = models.ForeignKey(\r\n Persona,\r\n related_name='capacitaciones',\r\n on_delete=models.CASCADE,\r\n help_text='el perfil de la persona capacitada'\r\n )\r\n\r\n capacitador = models.ForeignKey(\r\n Persona,\r\n related_name='capacitador_de',\r\n on_delete=models.SET_NULL,\r\n null=True,\r\n blank=True,\r\n help_text='la persona que realizó la capacitación'\r\n )\r\n\r\n clase_maquina = models.ForeignKey(\r\n 'maquinas.ClaseMaquina',\r\n verbose_name='clase de máquina',\r\n related_name='capacitaciones',\r\n on_delete=models.CASCADE,\r\n help_text='la clase de equipamiento sobre la que se capacitó'\r\n )\r\n\r\n fecha = models.DateField(\r\n help_text=('la fecha en que se realizó. en caso de que haya durado más '\r\n 'de una sesión, la fecha de la sesión final')\r\n )\r\n\r\n class Meta:\r\n verbose_name = 'capacitación'\r\n verbose_name_plural = 'capacitaciones'\r\n","sub_path":"perfiles/models/capacitacion.py","file_name":"capacitacion.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"328390644","text":"#!/usr/bin/python\n# coding: utf-8\n\n# Author: LE YUAN\n# Date: 2020-08-10\n\n\nimport os\nimport csv\nimport json\n\noutfile = open(\"./substrate_results.tsv\", \"wt\")\ntsv_writer = csv.writer(outfile, delimiter=\"\\t\")\ntsv_writer.writerow(['species', 'expansion', 'contraction', 'rapidly_evolving'])\n\n\nwith open(\"./summary_run_pub.txt\", \"r\") as file :\n lines = file.readlines()[1:]\n\nfor line in lines :\n data = line.strip().split('\\t')\n # print(data)\n species = data[0].replace('&', '_')\n expansion = data[1].split(' (')[0]\n contraction = data[4].split(' (')[0]\n rapidly_evolving = data[1].split(' (')[1][:-1]\n # print(expansion)\n # print(contraction)\n # print(rapidly_evolving)\n tsv_writer.writerow([species,expansion,contraction,rapidly_evolving])\n\noutfile.close()","sub_path":"evolution_analysis/code/gene_expansion_contraction/code/analyze_substrate/substrate_analysis.py","file_name":"substrate_analysis.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"141734718","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2022/9/17 22:14\r\n# File: 1624.py\r\n# Desc: \r\n\r\nclass Solution:\r\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\r\n ma = -1\r\n for idx in range(len(s)):\r\n ma = max(s.rfind(s[idx]) - idx, ma)\r\n return ma-1\r\n","sub_path":"Solutions/1624/1624.py","file_name":"1624.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"328781361","text":"import sys\nsys.path.append('../')\n\nimport numpy as np\nfrom simulation.simulation import *\n\ndef IPMSM_positioning(simulation_time, plant_parameters, control_parameters, external_inputs):\n\n # state parameters and data for plot\n id_data=[]\n iq_data=[]\n qm_data=[]\n dqm_data=[]\n qm_cmd_data=[]\n dqm_cmd_data=[]\n dqm_ref_data=[]\n id_cmd_data=[]\n iq_ref_data=[]\n qm_err_data=[]\n dqm_err_data=[]\n id_err_data=[]\n iq_err_data=[]\n time_data=[]\n\n sampling_time=plant_parameters[0]\n J=plant_parameters[1]\n B=plant_parameters[2]\n R=plant_parameters[3]\n Ld=plant_parameters[4]\n Lq=plant_parameters[5]\n Ke=plant_parameters[6]\n P=plant_parameters[7]\n\n Kpp = control_parameters[0]\n Kpv = control_parameters[1]\n Kiv = control_parameters[2]\n Kpi = control_parameters[3]\n Kii = control_parameters[4]\n\n qm_cmd = external_inputs[0]\n dqm_cmd = external_inputs[1]\n torque_reac = external_inputs[2]\n\n # simulation object\n sim_env = SimulationEnvironment(sampling_time = sampling_time)\n IPMSM_motor = IPMSM(Ld=Ld, Lq=Lq, Ke=Ke, R=R, P=P, sampling_time=sim_env.sampling_time, control_sampling_time=sampling_time)\n rigid_rotor = RigidRotor(J=J, B=B, sampling_time = sim_env.sampling_time, control_sampling_time=sampling_time)\n\n # main loop 10[sec]\n for i in range(int(simulation_time*(1/sim_env.sampling_time))):\n time = i * sim_env.sampling_time\n\n control_delay = (int)(IPMSM_motor.control_sampling_time/sim_env.sampling_time) #[sample]\n if i%control_delay == 0:\n \"\"\" controller \"\"\"\n # definition for control parameters\n if i == 0 :\n id_err_int = 0.0\n iq_err_int = 0.0\n\n # position controller (P position feedback control)\n qm_err = qm_cmd[i] - rigid_rotor.xvec[0]\n dqm_ref = Kpp * qm_err\n\n # velocity controller (P velocity feedback control)\n dqm_err = dqm_ref - rigid_rotor.xvec[1]\n iq_ref = Kpv * dqm_err # + dqm_cmd[i]\n\n # current controller (PI current feedback control)\n # d current control: Id = 0\n id_cmd = 0.0\n id_err = id_cmd - IPMSM_motor.xvec[0]\n id_err_int = id_err_int + id_err * IPMSM_motor.control_sampling_time\n vd = Kpi * id_err + Kii * id_err_int\n # q current control\n iq_err = iq_ref - IPMSM_motor.xvec[1]\n iq_err_int = iq_err_int + iq_err * IPMSM_motor.control_sampling_time\n vq = Kpi * iq_err + Kii * iq_err_int\n\n #data update\n time_data.append(time)\n id_data.append(IPMSM_motor.xvec[0])\n iq_data.append(IPMSM_motor.xvec[1])\n qm_data.append(rigid_rotor.xvec[0])\n dqm_data.append(rigid_rotor.xvec[1])\n qm_cmd_data.append(qm_cmd[i])\n dqm_cmd_data.append(dqm_cmd[i])\n dqm_ref_data.append(dqm_ref)\n id_cmd_data.append(id_cmd)\n iq_ref_data.append(iq_ref)\n qm_err_data.append(qm_err)\n dqm_err_data.append(dqm_err)\n id_err_data.append(id_err)\n iq_err_data.append(iq_err)\n\n \"\"\" controller end \"\"\"\n\n \"\"\" plant \"\"\"\n\n # derivative calculation\n rigid_rotor.dxvec = rigid_rotor.calc_deri(IPMSM_motor.torque, torque_reac[i])\n IPMSM_motor.dxvec = IPMSM_motor.calc_deri(vd, vq, rigid_rotor.xvec[1])\n # euler-integration\n rigid_rotor.update()\n IPMSM_motor.update()\n\n \"\"\" plant end \"\"\"\n\n # data plot\n from matplotlib import pyplot as plt\n plt.figure(figsize=(10, 7))\n plt.subplot(421)\n plt.plot(time_data, qm_cmd_data, label=\"theta motor cmd\")\n plt.plot(time_data, qm_data, label=\"theta motor res\")\n plt.legend()\n plt.grid()\n plt.ylabel('theta [rad]')\n\n plt.subplot(423)\n plt.plot(time_data, dqm_ref_data, label=\"omega motor cmd\")\n plt.plot(time_data, dqm_data, label=\"omega motor res\")\n plt.legend()\n plt.grid()\n plt.ylabel('omega [rad/s]')\n\n plt.subplot(425)\n plt.plot(time_data, id_cmd_data, label=\"id cmd\")\n plt.plot(time_data, id_data, label=\"id res\")\n plt.legend()\n plt.grid()\n plt.ylabel('current [A]')\n\n plt.subplot(427)\n plt.plot(time_data, iq_ref_data, label=\"iq cmd\")\n plt.plot(time_data, iq_data, label=\"iq res\")\n plt.legend()\n plt.grid()\n plt.ylabel('current [A]')\n\n plt.subplot(422)\n plt.plot(time_data, qm_err_data, label=\"theta error\")\n plt.legend()\n plt.grid()\n\n plt.subplot(424)\n plt.plot(time_data, dqm_err_data, label=\"omega error\")\n plt.legend()\n plt.grid()\n\n plt.subplot(426)\n plt.plot(time_data, id_err_data, label=\"id error\")\n plt.legend()\n plt.grid()\n\n plt.subplot(428)\n plt.plot(time_data, iq_err_data, label=\"iq error\")\n plt.legend()\n plt.grid()\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n\n simulation_time = 3.0\n sampling_time = 0.0001 # 100 us\n\n #################################################################\n ### example 2 IPMSM positioning\n #################################################################\n Ld=3.9*0.001\n Lq=7.9*0.001\n Ke=47.21*0.001\n R=154.9*0.001\n P=3\n J=0.1\n B=0.001\n plant_parameters = [sampling_time, J, B, R, Ld, Lq, Ke, P]\n\n # Command\n qm_cmd = []\n dqm_cmd = []\n for i in range(int(simulation_time/sampling_time)):\n time = i * sampling_time\n if time <= 0.5:\n qm_cmd_tmp = 0.0\n dqm_cmd_tmp = 0.0\n else:\n qm_cmd_tmp = 1.0\n dqm_cmd_tmp = 0.0\n qm_cmd.append(qm_cmd_tmp)\n dqm_cmd.append(dqm_cmd_tmp)\n\n # Disturbance\n torque_reac = []\n for i in range(int(simulation_time/sampling_time)):\n time = i * sampling_time\n torque_reac_tmp = 0.0\n torque_reac.append(torque_reac_tmp)\n\n external_inputs = [qm_cmd, dqm_cmd, torque_reac]\n\n # Position gains\n Kpp = 2.0 # P gain for velocity control loop\n Kpv = 10.0 # P gain for velocity control loop\n Kiv = 0.5 # I gain for velocity control loop\n Kpi = 5.0 # P gain for current control loop\n Kii = 1.5 # I gain for current control loop\n control_parameters = [Kpp, Kpv, Kiv, Kpi, Kii]\n\n # Simulation\n IPMSM_positioning(simulation_time, plant_parameters, control_parameters, external_inputs)\n","sub_path":"examples/example_ipmsm_positioning.py","file_name":"example_ipmsm_positioning.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"341367867","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 9 20:11:18 2019\r\n\r\n@author: binxi\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n def moveZeroes(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: None Do not return anything, modify nums in-place instead.\r\n \"\"\"\r\n l = len(nums)\r\n \r\n for i in range(0,l,1):\r\n while nums[i]==0:\r\n if nums[i+1:] == [0]*(l-i-1):\r\n break\r\n nums[i:-1] = nums[i+1:]\r\n nums[-1] = 0\r\n \r\n return nums","sub_path":"Leetcode/#283 Move Zeroes.py","file_name":"#283 Move Zeroes.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"409588639","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nimport os\nimport stat\n\nimport hypothesis\nfrom eden.test_support.hypothesis import FILENAME_STRATEGY\n\nfrom .lib import testcase\n\n\n@testcase.eden_repo_test\nclass HypothesisSimpleTest(testcase.EdenRepoTest):\n def populate_repo(self) -> None:\n self.repo.write_file(\"hello\", \"hola\\n\")\n self.repo.write_file(\"adir/file\", \"foo!\\n\")\n self.repo.write_file(\"bdir/test.sh\", \"#!/bin/bash\\necho test\\n\", mode=0o755)\n self.repo.write_file(\"bdir/noexec.sh\", \"#!/bin/bash\\necho test\\n\")\n self.repo.symlink(\"slink\", \"hello\")\n self.repo.commit(\"Initial commit.\")\n\n @hypothesis.given(FILENAME_STRATEGY)\n def test_create(self, basename: str) -> None:\n filename = os.path.join(self.mount, basename)\n\n # Ensure that we don't proceed if hypothesis has selected a name that\n # conflicts with the names we generated in the repo.\n hypothesis.assume(not os.path.exists(filename))\n\n with open(filename, \"w\") as f:\n f.write(\"created\\n\")\n\n entries = sorted(os.listdir(self.mount))\n self.assertEqual(\n sorted([\".eden\", \"adir\", \"bdir\", \"hello\", basename, \"slink\"]), entries\n )\n\n with open(filename, \"r\") as f:\n self.assertEqual(f.read(), \"created\\n\")\n\n st = os.lstat(filename)\n self.assertEqual(st.st_size, 8)\n self.assertTrue(stat.S_ISREG(st.st_mode))\n","sub_path":"eden/integration/hypothesis_simple_test.py","file_name":"hypothesis_simple_test.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"368347082","text":"import csv \nimport numpy as np\nfrom numpy.linalg import inv\nimport random\nimport math\nimport sys\nimport matplotlib.pyplot as plt\n\n#feature scaling\n#adagrade\n#N-fold cross validation\n#batch\n\ndata = []\nhour = 9\nlambda_w = 0.0001\n\nfor i in range(18):\n data.append([])\n\nn_row = 0\ntext = open('data/train.csv', 'r', encoding='big5') \nrow = csv.reader(text , delimiter=\",\")\nfor r in row:\n if n_row != 0:\n for i in range(3,27):\n if r[i] != \"NR\":\n data[(n_row-1)%18].append(float(r[i]))\n else:\n data[(n_row-1)%18].append(float(0)) \n n_row = n_row+1\ntext.close()\n\nx = []\ny = []\n\nfor i in range(12):\n # 一個月取連續10小時的data可以有471筆\n for j in range(480-hour):\n x.append([])\n # 18種污染物\n for t in range(18):\n # if t!=9:\n # continue\n # 連續9小時\n for s in range(hour):\n x[(480-hour)*i+j].append(data[t][480*i+j+s] )\n # x[(480-hour)*i+j].append(data[t][480*i+j+s]**2 )\n y.append(data[9][480*i+j+hour])\nx = np.array(x)\ny = np.array(y)\n\nprint(x.shape)\n# x_mean = np.reshape(np.repeat(x.mean(axis=0),x.shape[0]),x.shape) \n# x_std = np.reshape(np.repeat(x.std(axis=0),x.shape[0]),x.shape) \n# x = (x-x_mean)/x_std\n\n# add square term\n# x = np.concatenate((x,x**2), axis=1)\n\n# add bias\nx = np.concatenate((np.ones((x.shape[0],1)),x), axis=1)\n\nw = np.zeros(len(x[0]))\nl_rate = 10\nrepeat = int(1e6)\n\nx_t = x.transpose()\ns_gra = np.zeros(len(x[0]))\n\ncosts = []\n# pre_cost = 1e6\n\nfor i in range(repeat):\n hypo = np.dot(x,w)\n loss = hypo - y\n cost = np.sum(loss**2 )/ len(x) + lambda_w*np.sum(w**2) \n # if cost > pre_cost and i>repeat//100:\n # break\n # pre_cost = cost\n cost_a = math.sqrt(cost)\n gra = np.dot(x_t,loss) + lambda_w*w*len(x)\n s_gra += gra**2\n ada = np.sqrt(s_gra)\n w = w - l_rate * gra/ada\n print ('iteration: %d | Cost: %f ' % ( i,cost_a))\n costs.append(cost_a)\n\n#use close form to check whether ur gradient descent is good\n# however, this cannot be used in hw1.sh \nw_closed = np.matmul(np.matmul(inv(np.matmul(x.transpose(),x)),x.transpose()),y)\n\n\n# save model\nnp.save(\"model_linear_all_\"+str(hour)+\"_regularized_\"+str(lambda_w)+\".npy\",w)\n# read model\n\n\nplt.xlabel('epoch', fontsize = 18)\nplt.ylabel('cost', fontsize = 18)\nplt.axis([0, len(costs), 4, 10])\n\nd1p, = plt.plot([i for i in range(len(costs))], costs, linewidth=0.5, color='g', markersize=0.3)\nplt.legend([d1p], [\"traing cost = \"+str(round(costs[-1],6) )])\n\nplt.savefig('result/traing_curve_linear_all_'+str(hour)+\"_regularized_\"+str(lambda_w)+'.png', format='png', dpi=1000)\n# plt.show()","sub_path":"hw1/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"642018205","text":"import cv2\r\nimport numpy as np\r\n\r\n\r\ndef treat_area_palm(hand_localised, palm, palm_center, copy):\r\n\r\n palm_area_draw = np.array([(pts[0], pts[1]) for pts in palm if pts != (0, 0)])\r\n \r\n if palm_area_draw != []: \r\n cv2.drawContours(copy, [palm_area_draw], 0, (0, 255, 0), 1)\r\n palm_area = cv2.contourArea(palm_area_draw)\r\n\r\n if palm_area < 300: print(\"peut etre main non tournée paume et on peut definir la main\", palm_area)\r\n elif palm_area > 300: print(\"main tournée paume et on peut definir la main\", palm_area)\r\n\r\n cv2.circle(copy, palm_center, 2, (255, 255, 255), 1)\r\n [cv2.circle(copy, pts, 2, (0, 0, 0), 1) for pts in palm]\r\n\r\n #cv2.imshow(\"palm\", copy)\r\n #cv2.waitKey(0)\r\n\r\n\r\ndef printing(fingers):\r\n print(\"PALM ANALYSIS\")\r\n print(\"fingers : \", fingers, \"\\n\")\r\n\r\ndef palm_analyse(hand_localised, palm_center, palm, rectangle, crop,\r\n fingers):\r\n\r\n copy = crop.copy()\r\n #printing(fingers)\r\n\r\n treat_area_palm(hand_localised, palm, palm_center, copy)\r\n\r\n\r\n\r\n","sub_path":"hand/palm_analyse.py","file_name":"palm_analyse.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"373864165","text":"import math\nfrom collections import OrderedDict\nfrom lsdj.models.phrase import Phrase\nfrom lsdj.utils import chunks\n\n\ndef get_track_events(track, resolution):\n semi_quaver = (resolution / 2) / 2\n notes_at_tick = {}\n\n # Get time signature events\n time_sigs = [tick for tick in track if tick.name == 'Time Signature']\n notes = [tick for tick in track if tick.name == 'Note On']\n end_of_song = [tick for tick in track if tick.name == 'End of Track'][0]\n tempos = [tick for tick in track if tick.name == 'Set Tempo']\n for tick in range(0, (end_of_song.tick + semi_quaver), semi_quaver):\n notes_at_tick[tick] = []\n\n for index, note in enumerate(notes):\n next_note = notes[index + 1] if index != (\n len(notes) - 1) else end_of_song\n note_delta = next_note.tick - note.tick\n if note_delta % semi_quaver == 0:\n notes_at_tick[note.tick].append(note)\n\n return {\n 'notes': OrderedDict(\n sorted(notes_at_tick.items(), key=lambda t: t[0])\n ),\n 'time_sigs': time_sigs,\n 'end_of_song': end_of_song,\n 'semi_quaver': semi_quaver,\n 'tempos': tempos\n }\n\n\ndef get_phrases(notes, time_sigs, end_of_song, semi_quaver):\n phrases = []\n processed_notes = notes\n for index, time_sig in enumerate(time_sigs):\n next_time_sig = time_sigs[index + 1] if index != (len(time_sigs) - 1) else end_of_song\n fraction_resolution = 16 / time_sig.denominator\n notes_per_phrase = (time_sig.numerator * fraction_resolution)\n time_sig_length = next_time_sig.tick - time_sig.tick\n time_sig_bars = time_sig_length / (notes_per_phrase * semi_quaver)\n for phrase_index in range(0, time_sig_bars):\n start_tick = time_sig.tick + (phrase_index * (notes_per_phrase * semi_quaver))\n end_tick = start_tick + (notes_per_phrase * semi_quaver)\n phrase_count = int(math.ceil(notes_per_phrase / 16)) + 1\n if phrase_count > 1:\n for offset_index, phrase in enumerate(range(0, phrase_count)):\n end_offset = end_tick - ((notes_per_phrase % 16) * semi_quaver)\n new_start_tick = start_tick if offset_index == 0 else end_offset\n new_end_tick = end_offset if offset_index == 0 else end_tick\n note_count = 16 if offset_index == 0 else (notes_per_phrase % 16)\n note_range = range(new_start_tick, new_end_tick, 120)\n phrase_notes = {k: processed_notes[k] for k in note_range}\n notes = OrderedDict(sorted(phrase_notes.items(), key=lambda t: t[0]))\n phrases.append(\n Phrase(\n note_count,\n new_start_tick,\n new_end_tick,\n '{0}/{1}'.format(time_sig.numerator, time_sig.denominator),\n notes\n )\n )\n else:\n note_range = range(start_tick, end_tick, 120)\n phrase_notes = {k: processed_notes[k] for k in note_range}\n notes = OrderedDict(sorted(phrase_notes.items(), key=lambda t: t[0]))\n phrases.append(\n Phrase(\n notes_per_phrase,\n start_tick,\n end_tick,\n '{0}/{1}'.format(time_sig.numerator, time_sig.denominator),\n notes\n )\n )\n\n return phrases\n\n\ndef deduplicate_phrases(phrases, phrase_offset=0):\n b64_phrase_dict = {}\n b64_phrase_keys = []\n\n for phrase in phrases:\n phrase_key = phrase.notes_as_b64\n if not b64_phrase_dict.get(phrase_key, None):\n b64_phrase_dict[phrase_key] = phrase.notes\n b64_phrase_keys.append(phrase_key)\n\n phrase_dict = {}\n phrase_dict_lookup = {}\n phrase_keys = []\n\n for index, key in enumerate(b64_phrase_dict.keys()):\n new_index = index + int(phrase_offset)\n phrase_dict[new_index] = b64_phrase_dict[key]\n phrase_dict_lookup[key] = new_index\n\n for phrase in b64_phrase_keys:\n phrase_keys.append(phrase_dict_lookup[phrase])\n\n return {\n 'phrases': phrase_dict,\n 'keys': phrase_keys\n }\n\n\ndef get_chains(phrase_keys):\n return list(chunks(phrase_keys, 16))\n","sub_path":"lsdj/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":4457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"403739194","text":"def add(a,b):\n c=a+b\n print(c)\ndef prime(n):\n temp=0\n for i in range(1,n+1):\n if(n%i==0):\n temp+=1\n if temp==2:\n return True\n else:\n return False\n","sub_path":"01-10-2019/packeges/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"381632359","text":"# -*- coding: utf-8 -*-\n\nfrom openerp.osv import fields, osv\nimport openerp.addons.decimal_precision as dp\n\nclass comisiones_por_producto(osv.osv):\n _name = 'comisiones.producto'\n\n _columns = {\n 'vendedor_id': fields.many2one('hr.employee', 'Vendedor'),\n 'product_id': fields.many2one('product.product', string='Producto'),\n 'porcentaje_comision': fields.float('% Comision'),\n }\n\nclass comisiones_por_categoria_producto(osv.osv):\n _name = 'comisiones.categoria_producto'\n\n _columns = {\n 'vendedor_id': fields.many2one('hr.employee', 'Vendedor'),\n 'categ_id': fields.many2one('product.category', string='Categoria de producto'),\n 'porcentaje_comision': fields.float('% Comision'),\n }\n\n\nclass comisiones_por_rango(osv.osv):\n _name = 'comisiones.rango'\n\n _columns = {\n 'vendedor_id': fields.many2one('hr.employee', 'Vendedor'),\n 'categ_id': fields.many2one('product.category', string='Categoria de producto'),\n 'minimo': fields.float('Minimo', required=True),\n 'maximo': fields.float('Maximo', required=True),\n 'porcentaje_comision': fields.float('% Comision', required=True),\n }\n _order = 'categ_id, minimo asc'\n","sub_path":"models/comisiones.py","file_name":"comisiones.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"109184293","text":"import pickle\nimport numpy as np\nimport pandas as pd\nimport time\nfrom model.helper_functions import stub_withhold_split, val_test_features\n\n\nstart_time = time.time(), time.ctime()\nprint(f'Start time: {start_time[1]}')\n\n# Build df of playlists to classify in clusters\nval_pids = np.genfromtxt('../data/val_pids.csv', skip_header=1, dtype=int)\n\n# Import data to memory so it is not loaded from disk for every loop iteration\nplaylist_df = pd.read_csv('../data/playlists.csv')\ntrack_df = pd.read_csv('../data/songs_100000_feat_cleaned.csv', index_col='track_uri')\ntop_artists = np.genfromtxt('../data/top_playlist_defining_artists_train.csv', usecols=0,\n skip_header=0, delimiter=',', dtype=str)\n\n# Create output vessels\nval_stub_feat_dfs = [None]*len(val_pids)\nerrors = 0\n\n# Loop through pids and make features\nfor idx, pid in enumerate(val_pids):\n try:\n stub_tracks, withhold_tracks = stub_withhold_split(pid)\n stub_playlist_feats = val_test_features(stub_tracks, track_df=track_df, top_artists=top_artists, pid=pid)\n val_stub_feat_dfs[idx] = stub_playlist_feats\n except Exception as e:\n print(f'Error for pid {pid}: \\n{e}')\n errors += 1\n\n if (idx + 1) % 100 == 0:\n print(f'[{time.ctime()}] Progress {idx+1} playlists and {errors} errors')\n\nplaylist_features_val = pd.concat(val_stub_feat_dfs, axis=0)\n\nend_time = time.time(), time.ctime()\ntime_elapsed = end_time[0]-start_time[0]\ntime_elapsed = time.strftime('%H:%M:%S', time.gmtime(time_elapsed))\nprint(f'End time: {end_time[1]}, Time elapsed: {time_elapsed}')\n\n# Save output\nplaylist_features_val.to_csv('../data/playlist_features_with_artists_val.csv', sep=',', index=True)\n","sub_path":"model/k6_pre-processing_val.py","file_name":"k6_pre-processing_val.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"528308018","text":"from __future__ import print_function\nimport numpy as np\nimport h5py\nimport powderday.config as cfg\n\n'''\n agn_spectrum using Nenkova+ (2008) torus models. Model calculations from CLUMPY (https://www.clumpy.org). Total spectrum is calculated as (Torus Flux) + (probability of AGN photon escape)x(AGN Flux). AGN spectra are assumed to be piecewise power-law (Rowan-Robinson 1995) with spectral breaks from Nenkova et al. Default CLUMPY model parameters taken from Nenkova et al.\n\n CLUMPY returns spectra in lambda * Flambda (arbitrary units). We scale such that the integrated Flambda gives the total IR luminosity.\n\n - Ray Sharma\n'''\n\n\nclass Nenkova2008:\n def __init__(self, params=[5, 30, 0, 1.5, 30, 40]):\n N0, Y, i, q, sig, tv = params\n self.N0 = N0\n self.Y = Y\n self.i = i\n self.q = q\n self.sig = sig\n self.tv = tv\n\n def agn_spectrum(self, log_L_bol):\n try:\n h = h5py.File(cfg.par.BH_modelfile, 'r')\n except:\n raise IOError('Unable to find Nenkova BH model file. '\n 'Check the path in parameters master, or '\n 'download the file here: https://www.clump'\n 'y.org/downloads/clumpy_models_201410_tvav'\n 'g.hdf5')\n\n ix = ((h['N0'][:] == self.N0) &\n (h['Y'][:] == self.Y) &\n (h['i'][:] == self.i) &\n (h['q'][:] == self.q) &\n (h['sig'][:] == self.sig) &\n (h['tv'][:] == self.tv))\n\n nu_vec = 3e14 / h['wave'][:]\n\n frac_AGN_obsc = h['ptype1'][:][ix][0]\n l_band_vec_torus = h['flux_tor'][:][ix][0]\n l_band_vec_AGN = h['flux_toragn'][:][ix][0] - l_band_vec_torus\n l_band_vec = l_band_vec_torus + (frac_AGN_obsc * l_band_vec_AGN)\n\n l_band_vec = self.scale_spectrum(l_band_vec, nu_vec, log_L_bol)\n\n l_band_vec = np.log10(l_band_vec)\n l_band_vec = np.concatenate((l_band_vec, [0, 0, 0, 0]))\n nu_vec = np.log10(nu_vec)\n nu_vec = np.concatenate((nu_vec, [-1, -2, -3, -4]))\n\n to_cgs = np.log10(3.9) + 33\n return nu_vec, l_band_vec + to_cgs\n\n def scale_spectrum(self, l_band_vec, nu_vec, log_L_bol):\n ''' Scale the spectrum by (total IR luminosity) / (integrated spectrum in arb. units)\n '''\n L_IR = 10**self.bol_correct_IR(log_L_bol)\n integrated_spec = np.trapz(l_band_vec / nu_vec, nu_vec)\n norm = L_IR / abs(integrated_spec)\n return l_band_vec * norm\n\n def bol_correct_IR(self, log_L_bol, c1=17.87, k1=0.28, c2=10.03, k2=0.020):\n ''' Return log IR luminosity using bolometric corrections from Hopkins+ (2006). Defaults to 15micron band corrections.\n '''\n L_bol = 10**log_L_bol\n L_IR = L_bol / (c1 * pow(L_bol / 1e10, k1) +\n c2 * pow(L_bol / 1e10, k2))\n return np.log10(L_IR)\n","sub_path":"powderday/agn_models/nenkova.py","file_name":"nenkova.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277316576","text":"import time\nimport networkx as NX\nfrom datetime import timedelta\nfrom multiprocessing import Process, Queue, Value\n\nMETRICS = \"metrics-pattern.txt\"\n\ndef expand(wid, G, K, cand, fini, max_clique_size, calls_made, q_out):\n\n if calls_made is not None:\n with calls_made.get_lock():\n calls_made.value += 1\n\n if len(cand) == 0 and len(fini) == 0:\n with max_clique_size.get_lock():\n if len(K) > max_clique_size.value:\n max_clique_size.value = len(K)\n q_out.put((wid, K.copy()))\n return\n\n pivot = max(cand | fini, key=lambda u: len(cand & set(G.neighbors(u))))\n\n ext = cand - set(G.neighbors(pivot))\n\n for q in ext:\n\n Kq = K | {q}\n\n candq = cand & set(G.neighbors(q))\n finiq = fini & set(G.neighbors(q))\n\n cand = cand - {q}\n fini = fini | {q}\n\n expand(wid, G, Kq, candq, finiq,\n max_clique_size, calls_made, q_out)\n\ndef calc_max_clique(wid, G, max_clique_size, calls_made, q_in, q_out):\n\n quit = False\n\n while not quit:\n\n item = q_in.get()\n\n if item == None:\n quit = True\n continue\n\n if G.degree(item) >= max_clique_size.value:\n\n CAND = {item}\n\n # check if the vertexes\n # verify the clique condition\n for neighbor in G.neighbors(item):\n if G.degree(neighbor) >= max_clique_size.value:\n CAND.add(neighbor)\n\n expand(wid, G, set(), CAND, set(),\n max_clique_size, calls_made, q_out)\n\ndef process_parallel(G, workers_num, calls_made=None):\n\n workers = []\n queues = []\n outq = Queue()\n\n max_clique = []\n max_clique_size = Value('i', 2)\n\n for w in range(workers_num):\n queues.append(Queue())\n\n nodes = G.nodes()\n\n print(\"nodes: {}\".format(nodes))\n\n # Order nodes by its degree\n nodes = list(map(lambda x: (x, G.degree(x)), nodes))\n nodes = sorted(nodes, key=lambda x: x[1])\n nodes = list(map(lambda x: x[0], nodes))\n\n for v in range(len(nodes)):\n queues[v % workers_num].put(nodes[v])\n\n start = time.time()\n\n for w in range(workers_num):\n p = Process(target=calc_max_clique, args=(w, G,\n max_clique_size,\n calls_made,\n queues[w], outq,))\n workers.append(p)\n p.start()\n\n for qw in queues:\n qw.put(None)\n\n for w in workers:\n w.join()\n\n\n count_of_cliques_received = outq.qsize()\n\n # Find the maximum clique\n while not outq.empty(): \n wid, clique = outq.get()\n\n print(\"wid: {}, clique: {}\".format(wid, clique))\n\n if len(clique) > len(max_clique):\n max_clique = clique\n\n return max_clique, count_of_cliques_received\n \n\ndef maxclique(graph, workers_num, loaded=False, metrics=False, name='none'):\n \n if not loaded:\n G = NX.read_edgelist(graph)\n else:\n G = graph\n\n print(\"Graph - Nodes: {}, Edges: {}\".format(\n len(G.nodes()), len(G.edges())))\n\n start = time.time()\n\n max_clique, _ = process_parallel(graph, workers_num)\n \n end = time.time()\n\n d = end - start\n dt = time.strptime(str(timedelta(seconds=d)).split(\".\")[0], \"%H:%M:%S\")\n\n print(\"Delta time: hour: {}, min: {}, sec: {}\".format(\n dt.tm_hour,\n dt.tm_min,\n dt.tm_sec))\n\n # Writes and prints the metrics\n if metrics:\n # Metrics values\n calls_made = Value('i', 0)\n _, count_of_cliques_received = process_parallel(graph, workers_num, calls_made=calls_made)\n \n\n print(\"Cliques found: {}, Calls made: {}\".format(\n count_of_cliques_received, calls_made.value))\n\n result_metrics = \"{},{},{},{},{},{}\\n\".format(\n name,\n len(G.nodes()),\n len(G.edges()),\n count_of_cliques_received,\n calls_made.value, d)\n with open(METRICS, \"a\") as f:\n f.write(result_metrics)\n\n return list(max_clique)\n\n\n","sub_path":"pattern/src/algorithms/TTT/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"9657160","text":"#!/usr/bin/env python3\n\"\"\"List command available with provided API key\"\"\"\n\nimport argparse\nimport dreampylib\n\n\ndef main():\n \"\"\"List command available with provided API key\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('apikey', help='Your dreamhost API key')\n args = parser.parse_args()\n\n connection = dreampylib.DreampyLib(args.apikey)\n if not connection.is_connected():\n raise Exception(\"Unable to connect\")\n\n print(\", \".join(dir(connection)))\n\nif __name__ == '__main__':\n main()\n","sub_path":"dreampylib/tools/dh_list_commands.py","file_name":"dh_list_commands.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"8159827","text":"#!/usr/bin/env python\r\nimport tkinter as tk\r\nimport tkinter.font as tkFont\r\nfrom tkinter import scrolledtext\r\nfrom tkinter import messagebox\r\nimport Hammurabi\r\nimport random\r\n\r\n## First Class is for getting player's name\r\n\r\nBUY = +1\r\nSELL = -1\r\n\r\nWIN_W = 370\r\nWIN_H = 510\r\n\r\nclass Welcome:\r\n '''Class to start the Hammurabi game, asking the user for the Ruler's name.'''\r\n def __init__(self, master):\r\n self.master = master\r\n self.master.geometry(\"300x150\")\r\n self.master.minsize(275, 135)\r\n self.master.title(\"Welcome to Babylon!\")\r\n self.frame = tk.Frame(self.master)\r\n self.l1 = tk.Label(self.frame, \r\n text='Oh great Ruler, welcome to Babylon.',\r\n font=('Arial',13))\r\n self.l2 = tk.Label(self.frame, \r\n text='What is your name?',\r\n font=('Arial',10))\r\n self.currentRuler = tk.StringVar()\r\n self.currentRuler.set('Hammurabi')\r\n self.my_name = tk.Entry(self.frame, textvariable = self.currentRuler, width = 20)\r\n self.button1 = tk.Button(self.frame, text = \"Start\", command = self.game_window)\r\n self.helpBtn1 = tk.Button(self.frame, text = \"Help\", command = self.show_start_help)\r\n self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.close_windows)\r\n self.l1.pack(pady=5)\r\n self.l2.pack()\r\n self.my_name.pack()\r\n self.button1.pack(padx = 5, pady=10, side = tk.LEFT, fill = tk.X, expand = True)\r\n self.helpBtn1.pack(padx = 5, pady=10, side = tk.LEFT, fill = tk.X, expand = True)\r\n self.quitButton.pack(padx = 5, pady=10, side = tk.RIGHT, fill = tk.X, expand = True)\r\n self.frame.pack(pady = 10)\r\n \r\n def show_start_help(self):\r\n msg = ''' To play the game of Hammurabi,\r\n Type your name in the box and click \"Start\".\r\n \r\n You will serve your term in office buying & selling land, \r\n planting & harvesting seed, and feeding your people.\r\n \r\n The default term is 10 years. If you want a different \r\n term, append it to the name with a # mark, followed \r\n by the number of years, as in Hammurabi#15'''\r\n messagebox.Message(parent=self.master,title='Help',message=msg).show()\r\n \r\n def game_window(self):\r\n self.gameWindow = tk.Toplevel(self.master)\r\n self.gameWindow.title('Oracle of Babylon')\r\n self.master.withdraw()\r\n self.master.title(\"Welcome Back!\")\r\n self.app = GoPlay(self.gameWindow, self.master, self.currentRuler.get())\r\n \r\n def close_windows(self):\r\n self.master.destroy()\r\n\r\nclass GoPlay:\r\n '''Class to run the Hammurabi game in a window.'''\r\n def __init__(self, master, parent, ruler_name):\r\n global BUY\r\n global SELL\r\n self.master = master\r\n self.parent = parent\r\n try:\r\n rulerTerm = int(float(ruler_name.split('#')[1]))\r\n except:\r\n rulerTerm = 10\r\n self.Ruler = Hammurabi.Ruler(ruler_name.split('#')[0], rulerTerm)\r\n \r\n self.master.protocol(\"WM_DELETE_WINDOW\", self.close_windows)\r\n self.master.geometry('x'.join((str(WIN_W),str(WIN_H))))\r\n self.master.minsize(340, 250)\r\n self.master.maxsize(500,600)\r\n \r\n # History Window will keep a running total of actions and results\r\n # Be sure red 'X' doesn't destroy the window!\r\n self.historyWin = tk.Toplevel(self.master)\r\n self.historyWin.title(\"{}'s Record as Ruler\".format(self.Ruler.name))\r\n self.historyWin.protocol(\"WM_DELETE_WINDOW\", self.historyWin.withdraw)\r\n self.historyWin.geometry('x'.join((str(WIN_W+65),str(WIN_H-265))))\r\n self.historyWin.minsize(WIN_W+50, WIN_H-320)\r\n self.historyWin.maxsize(500,600)\r\n hist_head = ('\\t\\t\\t ----- G R A I N -----'+\r\n '\\nYear\\tPop\\tAcres\\tStored\\t Fed \\tHarvest'+\r\n '\\n----\\t---\\t-----\\t------\\t-----\\t-------')\r\n \r\n # Set up some string variables to use as active labels\r\n self.yio = tk.StringVar() #years in office\r\n self.pop = tk.StringVar() #population\r\n self.grn = tk.StringVar() #grain in storage\r\n self.acr = tk.StringVar() #acres owned\r\n self.ppa = tk.StringVar() #price per acres\r\n self.plt = tk.StringVar() #amount to plant\r\n self.plt.set('0')\r\n self.hist = tk.StringVar() #text for running history window\r\n self.hist.set(hist_head)\r\n \r\n self.update_labels()\r\n \r\n self.bs = tk.IntVar() # value state for buying / selling land\r\n self.bs.set(BUY) # BUY is +1, SELL is -1 to increase or decrease acreage\r\n \r\n self.oracle_text = tk.StringVar() # Message to be displayed in bottom frame\r\n self.oracle_text.set(Hammurabi.welcome(to_print=False))\r\n \r\n default_font = tkFont.nametofont(\"TkDefaultFont\")\r\n default_font.configure(size=10)\r\n \r\n # top frame for data output\r\n self.frame_top = tk.LabelFrame(self.master, \r\n width = WIN_W, height = 150,\r\n text = \"Ruler: \"+self.Ruler.name,\r\n ) \r\n # middle frame for entry fields\r\n self.frame_mid = tk.LabelFrame(self.master,\r\n width = WIN_W, height = 200,\r\n text = \"Make your commands:\"\r\n ) \r\n \r\n # bottom frame for report message \r\n self.frame_bot = tk.LabelFrame(self.master,\r\n width = WIN_W, height = 300,\r\n text = \"Message from Oracle:\") \r\n \r\n self.frame_top.pack(side=tk.TOP, padx=5, pady=5, fill=tk.BOTH, expand=False)\r\n self.frame_mid.pack(side=tk.TOP, padx=5, pady=5, fill=tk.BOTH, expand=False)\r\n self.frame_bot.pack(side=tk.TOP, padx=5, pady=5, fill=tk.BOTH, expand=False)\r\n \r\n \r\n # Fill in Top frame, then put items\r\n self.lbl_years = tk.Label(self.frame_top, text = \"Years Served:\")\r\n self.val_years = tk.Label(self.frame_top, textvar = self.yio)\r\n self.lbl_pop = tk.Label(self.frame_top, text = \"Population:\")\r\n self.val_pop = tk.Label(self.frame_top, textvar = self.pop)\r\n self.lbl_grain = tk.Label(self.frame_top, text = \"Bushels of Grain:\")\r\n self.val_grain = tk.Label(self.frame_top, textvar = self.grn)\r\n self.lbl_acres = tk.Label(self.frame_top, text = \"Acres of Land:\")\r\n self.val_acres = tk.Label(self.frame_top, textvar = self.acr)\r\n \r\n\r\n self.lbl_years.grid(row=0, column=0, sticky = tk.E)\r\n self.val_years.grid(row=0, column=1, sticky = tk.W)\r\n self.lbl_grain.grid(row=0, column=2, sticky = tk.E)\r\n self.val_grain.grid(row=0, column=3, sticky = tk.W)\r\n self.lbl_pop.grid(row=1, column=0, sticky = tk.E)\r\n self.val_pop.grid(row=1, column=1, sticky = tk.W)\r\n self.lbl_acres.grid(row=1, column=2, sticky = tk.E)\r\n self.val_acres.grid(row=1, column=3, sticky = tk.W)\r\n \r\n # Fill in Middle frame:\r\n self.lbl_landcost = tk.Label(self.frame_mid, text = \"Price of land in bushels per acre:\")\r\n self.val_landcost = tk.Label(self.frame_mid, textvar = self.ppa)\r\n \r\n self.rbn_buy = tk.Radiobutton(self.frame_mid, text=\"Buy\", var=self.bs, value=BUY, command = self.bs_range)\r\n self.rbn_sell = tk.Radiobutton(self.frame_mid, text=\"Sell\", var=self.bs, value=SELL, command = self.bs_range)\r\n maxval = int(self.Ruler.bushels_in_storage / self.Ruler.price_of_land)\r\n self.val_landsale = tk.Spinbox(self.frame_mid, width=5, from_=0, to=maxval, command = self.bs_range)\r\n self.sale_validation = self.frame_mid.register(self.validate_sale)\r\n self.val_landsale.config(validate='all', validatecommand = (self.sale_validation, '%P'))\r\n self.lbl_landsale = tk.Label(self.frame_mid, text=\"acres\")\r\n \r\n self.lbl_feed = tk.Label(self.frame_mid, text=\"Feed the people \")\r\n self.val_feed = tk.Spinbox(self.frame_mid, width=5, from_=0, to=self.grn.get(), increment=5, repeatinterval=20, command = self.bs_range)\r\n self.digit_validation = self.frame_mid.register(self.validate_digit)\r\n self.val_feed.config(validate='all', validatecommand = (self.digit_validation, '%P','%W'))\r\n self.lbl_feed2 = tk.Label(self.frame_mid, text=\"bushels of grain\")\r\n \r\n self.lbl_plant = tk.Label(self.frame_mid, text=\"Plant \")\r\n self.val_plant = tk.Spinbox(self.frame_mid, textvar = self.plt, width=5, from_=0, to=self.get_plant_max(), command = self.bs_range)\r\n self.val_plant.config(validate='all', validatecommand = (self.digit_validation, '%P','%W'))\r\n self.lbl_plant2 = tk.Label(self.frame_mid, text=\"acres\")\r\n \r\n self.goButton = tk.Button(self.frame_mid, \r\n text = ' GO ', \r\n width = 8,\r\n activebackground='green',\r\n highlightcolor='green',\r\n cursor='hand2',\r\n command = self.go_action\r\n )\r\n \r\n self.quitButton = tk.Button(self.frame_mid, \r\n text = 'End', \r\n width = 8,\r\n activebackground='red',\r\n highlightcolor='red',\r\n cursor='hand2',\r\n command = self.close_windows\r\n )\r\n \r\n self.lbl_landcost.grid(row=0, column=0, columnspan = 4, sticky = tk.E + tk.N)\r\n self.val_landcost.grid(row=0, column=4, sticky = tk.W + tk.N)\r\n self.rbn_buy.grid(row=1, column=0, sticky=tk.W)\r\n self.rbn_sell.grid(row=1, column=1, sticky=tk.W)\r\n self.val_landsale.grid(row=1, column=2, sticky=tk.W)\r\n self.lbl_landsale.grid(row=1, column=3, sticky=tk.W)\r\n self.lbl_feed.grid(row=2, column=0, columnspan=2, sticky=tk.E)\r\n self.val_feed.grid(row=2, column=2, sticky=tk.W)\r\n self.lbl_feed2.grid(row=2, column=3, columnspan=2, sticky=tk.W)\r\n self.lbl_plant.grid(row=3, column=0, columnspan=2, sticky=tk.E)\r\n self.val_plant.grid(row=3, column=2, sticky=tk.W)\r\n self.lbl_plant2.grid(row=3, column=3, sticky=tk.W)\r\n self.goButton.grid(row=4, column=4, sticky=tk.E, padx=5, pady=5)\r\n self.quitButton.grid(row=4, column=5, sticky=tk.E, padx=5, pady=5)\r\n \r\n\r\n # Fill in Bottom frame:\r\n self.lbl_oracle_msg = tk.Label(self.frame_bot, \r\n textvariable = self.oracle_text,\r\n fg = '#40f',\r\n wraplength=400,\r\n font=('TkDefaultFont',8),\r\n justify=tk.LEFT\r\n )\r\n \r\n self.lbl_oracle_msg.grid(row=0, column=0, sticky=tk.N+tk.W)\r\n \r\n # Set up History Window with a frame and text for hist variable\r\n self.label_hist = tk.Label(self.historyWin, \r\n text = \"History for Ruler: \"+self.Ruler.name,\r\n font = ('TkDefaultFont',15)\r\n )\r\n hist_font = tkFont.nametofont('TkFixedFont')\r\n self.hist_text_area = scrolledtext.ScrolledText(self.historyWin,\r\n width = 50,\r\n height = 10,\r\n font = hist_font,\r\n )\r\n self.hist_text_area.insert('end',self.hist.get())\r\n self.historyWin.grid_columnconfigure(0,weight=1)\r\n self.historyWin.grid_rowconfigure(1,weight=1)\r\n self.historyWin.resizable(width = True, height = True)\r\n self.label_hist.grid(column=0,row=0, padx=10, pady=10, sticky=tk.W)\r\n self.hist_text_area.grid(column=0, row=1, padx=10, pady=10, sticky=tk.W+tk.N+tk.E+tk.S)\r\n self.hist_text_area.configure(state=\"disabled\")\r\n self.historyWin.withdraw()\r\n\r\n # Create a menu so user can pull up the History Window\r\n self.menubar = tk.Menu(self.master)\r\n self.filemenu = tk.Menu(self.menubar,tearoff=0)\r\n self.filemenu.add_command(label=\"View History\", command=self.historyWin.deiconify)\r\n self.filemenu.add_command(label=\"Quit Reign\", command=self.close_windows)\r\n self.filemenu.add_command(label=\"Quit Game\", command=self.parent.destroy)\r\n self.helpmenu = tk.Menu(self.menubar,tearoff=0)\r\n self.helpmenu.add_command(label=\"Help\", command=self.show_reign_help)\r\n self.menubar.add_cascade(label=\"File\", menu=self.filemenu)\r\n self.menubar.add_cascade(label=\"Help\", menu=self.helpmenu)\r\n self.master.config(menu=self.menubar)\r\n \r\n \r\n\r\n def show_reign_help(self):\r\n self.reignHelpWin = tk.Toplevel(self.master)\r\n self.reignHelpWin.title(\"Rules...\")\r\n self.historyWin.geometry('x'.join((str(WIN_W),str(WIN_H-265))))\r\n self.historyWin.minsize(WIN_W, WIN_H-265)\r\n self.historyWin.maxsize(WIN_W, WIN_H-265)\r\n self.playHelpLbl = tk.Label(self.reignHelpWin, text = Hammurabi.welcome(to_print=False)).pack(padx=5,pady=5)\r\n \r\n def close_windows(self):\r\n self.master.destroy()\r\n self.parent.deiconify()\r\n \r\n \r\n def update_labels(self):\r\n self.yio.set('{:3d}'.format(self.Ruler.years_ruled)) #years in office\r\n self.pop.set(self.Ruler.population) #population\r\n self.grn.set(self.Ruler.bushels_in_storage) #grain in storage\r\n self.acr.set(self.Ruler.acres_of_land) #acres owned\r\n self.ppa.set(self.Ruler.price_of_land) #price per acres\r\n # yio pop acr grn fed harvest\r\n hist_line = \"\\n{:3}\\t{:5}\\t{:5}\\t{:6}\\t{!s:5}\\t{!s:5}\".format(self.yio.get(),self.pop.get(),self.acr.get(),self.grn.get(),self.Ruler.bushels_fed, (self.Ruler.harvested_bushels_per_acre*self.Ruler.acres_planted))\r\n \r\n self.hist.set(self.hist.get() + hist_line)\r\n \r\n def update_history_text(self):\r\n self.hist_text_area.configure(state=\"normal\")\r\n self.hist_text_area.replace(1.0,'end',self.hist.get())\r\n self.hist_text_area.configure(state=\"disabled\")\r\n \r\n def bs_range(self):\r\n # set land sale limits accordingly, ignore feed and plant\r\n if self.bs.get() == BUY:\r\n maxval = int(int(self.grn.get()) / int(self.ppa.get()))\r\n else:\r\n maxval = int(self.acr.get())\r\n self.val_landsale.config(to=maxval)\r\n \r\n # set feed limits accordingly, ignore plant\r\n try:\r\n maxval = int(self.grn.get()) - (int(self.bs.get()) * int(self.val_landsale.get()) * int(self.ppa.get()))\r\n if maxval <= 0:\r\n #self.val_feed.set('0')\r\n self.val_feed.config(to=0)\r\n else:\r\n self.val_feed.config(to=maxval)\r\n except ValueError:\r\n pass\r\n \r\n # set planting limits\r\n tmp = self.get_plant_max()\r\n if tmp == 0:\r\n self.plt.set('0')\r\n self.val_plant.config(to=tmp)\r\n \r\n \r\n def get_plant_max(self):\r\n # the max allowed to plant is the least of \r\n # 1. population * 10\r\n # 2. acres owned (+/- current sale)\r\n # 3. (total bushels available * 2 acres / bushel ) where total is storage +/- sale - feed\r\n m1 = int(self.pop.get()) * 10\r\n try:\r\n m2 = int(self.acr.get()) + (int(self.bs.get()) * int(self.val_landsale.get()))\r\n except:\r\n m2 = m1\r\n try:\r\n tot_grn = int(self.grn.get()) - (int(self.bs.get())*int(self.val_landsale.get())*int(self.ppa.get())) - int(self.val_feed.get())\r\n m3 = tot_grn * 2\r\n except:\r\n m3 = m1\r\n \r\n return max(0,min(m1,m2,m3))\r\n \r\n \r\n def validate_sale(self, user_input):\r\n # first, make sure scrollbox limits are up to date:\r\n self.bs_range()\r\n # ensure input is number\r\n if user_input.isdigit():\r\n minval = int(self.frame_mid.nametowidget(self.val_landsale).config('from')[4])\r\n maxval = int(self.frame_mid.nametowidget(self.val_landsale).config('to')[4])\r\n \r\n if int(user_input) not in range(minval,maxval+1):\r\n return False\r\n return True\r\n \r\n elif user_input is \"\":\r\n return True\r\n \r\n else:\r\n return False\r\n \r\n \r\n def validate_digit(self, user_input, W):\r\n # first, make sure scrollbox limits are up to date:\r\n self.bs_range()\r\n if user_input.isdigit():\r\n minval = int(self.frame_mid.nametowidget(W).config('from')[4])\r\n maxval = int(self.frame_mid.nametowidget(W).config('to')[4])\r\n\r\n if int(user_input) not in range(minval,maxval+1):\r\n return False\r\n return True\r\n \r\n elif user_input is \"\":\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n def final_check(self):\r\n msg = None\r\n # check that there is no blank entry\r\n if self.val_landsale.get()=='' or self.val_feed.get()=='' or self.plt.get()=='':\r\n msg = 'O great {}, please make sure each item has a value!'.format(self.Ruler.name)\r\n return msg\r\n cashOnHand = int(self.grn.get())\r\n # check land sale\r\n ## Is there enough acreage to sell?\r\n ## Is there enough bushels to pay?\r\n if self.bs.get() == BUY:\r\n if cashOnHand < (int(self.ppa.get()) * int(self.val_landsale.get())):\r\n msg = 'O great {}, you do not have enough grain to buy {} acres.'.format(self.Ruler.name, self.val_landsale.get())\r\n return msg\r\n cashOnHand -= int(self.ppa.get()) * int(self.val_landsale.get())\r\n else:\r\n if int(self.acr.get()) < int(self.val_landsale.get()):\r\n msg = 'O great {}, you do not have enough land to sell {} acres.'.format(self.Ruler.name, self.val_landsale.get())\r\n return msg\r\n cashOnHand += int(self.ppa.get()) * int(self.val_landsale.get())\r\n # check feed\r\n ## Is there enough bushels to feed?\r\n if cashOnHand < int(self.val_feed.get()):\r\n msg = 'O great {}, you do not have enough grain to feed {} bushels.'.format(self.Ruler.name, self.val_feed.get())\r\n return msg\r\n cashOnHand -= int(self.val_feed.get())\r\n # check planting\r\n ## Is there enough land to plant\r\n ## Is there enough seed to plant\r\n ## Is population enough to plant\r\n if (int(self.acr.get()) + (int(self.bs.get()) * int(self.val_landsale.get()))) < int(self.plt.get()):\r\n msg = 'O great {}, you do not have enough land to plant {} acres.'.format(self.Ruler.name, self.plt.get())\r\n elif (int(self.grn.get()) * 2) < int(self.grn.get()):\r\n msg = 'O great {}, you do not have enough grain to plant {} acres.'.format(self.Ruler.name, self.plt.get())\r\n elif (int(self.pop.get()) * 10) < int(self.plt.get()):\r\n msg = 'O great {}, you do not have enough people to plant {} acres.'.format(self.Ruler.name, self.plt.get())\r\n return msg\r\n \r\n def go_action(self):\r\n #msg = \"You hit the GO button\\nLand Exchange: {}\\nFeed: {}\\nPlant: {}\".format(str(int(self.val_landsale.get())*int(self.bs.get())),self.val_feed.get(),self.plt.get())\r\n #self.oracle_text.set(msg)\r\n \r\n self.lbl_oracle_msg.config(font=('TkDefaultFont',10))\r\n \r\n msg = self.final_check()\r\n if msg != None:\r\n self.oracle_text.set(msg+'\\n')\r\n return\r\n \r\n # Obviously passed final check\r\n # Process all the calls for the year in office\r\n self.Ruler.exchange_land(int(self.bs.get()) * int(self.val_landsale.get()))\r\n\r\n self.Ruler.feed_people(int(self.val_feed.get()))\r\n \r\n self.Ruler.plant_seed(int(self.plt.get()))\r\n \r\n if not self.Ruler.update_population():\r\n # update_pop returns False if you starved too many\r\n self.oracle_text.set(self.Ruler.impeach(quiet=True))\r\n self.end_reign()\r\n \r\n self.Ruler.update_harvest()\r\n self.Ruler.update_land_price()\r\n self.Ruler.years_ruled += 1\r\n \r\n # Update the \"dashboard\" values and\r\n # Reset the choices back to 0's\r\n self.update_labels()\r\n self.update_history_text()\r\n self.re_init_vals()\r\n \r\n # set the appropriate text, which depends on \r\n # if still in office or not.\r\n if self.Ruler.in_office:\r\n if int(self.yio.get()) < self.Ruler.term:\r\n msg = self.summarize_year()\r\n self.oracle_text.set(msg)\r\n else: \r\n msg = self.Ruler.print_final_summary(mode='return')\r\n msg += '\\n'+self.get_final_score()\r\n self.oracle_text.set(msg)\r\n self.end_reign()\r\n else:\r\n self.end_reign()\r\n \r\n def re_init_vals(self):\r\n self.bs.set(BUY)\r\n self.val_landsale.delete(0,tk.END)\r\n self.val_landsale.insert(0,'0')\r\n self.val_feed.delete(0,tk.END)\r\n self.val_feed.insert(0,'0')\r\n self.val_plant.delete(0,tk.END)\r\n self.val_plant.insert(0,'0')\r\n \r\n \r\n def summarize_year(self):\r\n return self.Ruler.print_summary(mode='return')\r\n \r\n \r\n def get_final_score(self):\r\n avg_starve_rate = self.Ruler.percentage_death_rate\r\n avg_land_wealth = self.Ruler.acres_of_land / self.Ruler.population\r\n \r\n if ((avg_starve_rate > 33) or (avg_land_wealth < 7)):\r\n return self.Ruler.impeach_message\r\n elif ((avg_starve_rate > 10) or (avg_land_wealth < 9)):\r\n return self.Ruler.bad_message\r\n elif ((avg_starve_rate > 3) or (avg_land_wealth < 10)):\r\n return self.Ruler.so_so_message\r\n else:\r\n return self.Ruler.great_message\r\n\r\n \r\n \r\n def end_reign(self):\r\n # Disable all the widgets, especially \"GO\" button\r\n # Setting the oracle_text is not the responsibility of this function!\r\n self.parent.bell()\r\n self.goButton.config(state=tk.DISABLED)\r\n\r\ndef main(): \r\n random.seed()\r\n root = tk.Tk()\r\n app = Welcome(root)\r\n root.mainloop()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Hammurabi_win.pyw","file_name":"Hammurabi_win.pyw","file_ext":"pyw","file_size_in_byte":23186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"328714079","text":"from src.DataCollatorCTCWithPadding import DataCollatorCTCWithPadding\nfrom src.Audio_Processor import Audio_Processor\nfrom transformers import Wav2Vec2ForCTC\nfrom transformers import TrainingArguments\nfrom datasets import load_metric,load_from_disk\nimport numpy as np\nfrom transformers import Trainer\nimport torch\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\ntorch.cuda.set_device(torch.device('cuda:0'))\nprocessor_save_path = './processor'\ndatasets_path = './training_data'\naudio_processor = Audio_Processor(processor_save_path=processor_save_path)\ndata_collator = DataCollatorCTCWithPadding(processor=audio_processor.processor, padding=True)\nwer_metric = load_metric(\"wer\")\n\ndef load_datasets(datasets_path):\n train_datasets = load_from_disk(os.path.join(datasets_path,'train_datasets.ds'))\n test_datasets = load_from_disk(os.path.join(datasets_path, 'test_datasets.ds'))\n return train_datasets,test_datasets\n\ndef compute_metrics(pred):\n\n pred_logits = pred.predictions\n pred_ids = np.argmax(pred_logits, axis=-1)\n\n pred.label_ids[pred.label_ids == -100] = audio_processor.processor.tokenizer.pad_token_id\n\n pred_str = audio_processor.processor.batch_decode(pred_ids)\n # we do not want to group tokens when computing the metrics\n label_str = audio_processor.processor.batch_decode(pred.label_ids, group_tokens=False)\n\n wer = wer_metric.compute(predictions=pred_str, references=label_str)\n\n return {\"wer\": wer}\n\n\ndef remove_long_common_voicedata(dataset, max_seconds=6):\n dftest = dataset.to_pandas()\n dftest['len'] = dftest['input_values'].apply(len)\n maxLength = max_seconds * 16000\n dftest = dftest[dftest['len'] < maxLength]\n dftest = dftest.drop('len', 1)\n dataset = dataset.from_pandas(dftest)\n del dftest\n return dataset\n\n\nif __name__ == '__main__':\n train_datasets, test_datasets = load_datasets(datasets_path=datasets_path)\n train_datasets = remove_long_common_voicedata(train_datasets)\n test_datasets = remove_long_common_voicedata(test_datasets)\n\n model = Wav2Vec2ForCTC.from_pretrained(\n \"facebook/wav2vec2-large-xlsr-53\",\n attention_dropout=0.1,\n hidden_dropout=0.1,\n feat_proj_dropout=0.0,\n mask_time_prob=0.05,\n layerdrop=0.1,\n gradient_checkpointing=True,\n ctc_loss_reduction=\"mean\",\n pad_token_id=audio_processor.processor.tokenizer.pad_token_id,\n vocab_size=len(audio_processor.processor.tokenizer)\n )\n\n training_args = TrainingArguments(\n output_dir=\"./train_model/wav2vec2-large-xlsr-zh_TW-8K-demo\",\n group_by_length=False,\n per_device_train_batch_size=1,\n gradient_accumulation_steps=1,\n evaluation_strategy=\"steps\",\n eval_accumulation_steps= 1,\n num_train_epochs=30,\n fp16=True,\n save_steps=400,\n eval_steps=400,\n logging_steps=400,\n learning_rate=3e-4,\n warmup_steps=500,\n save_total_limit=2,\n )\n\n trainer = Trainer(\n model=model,\n data_collator=data_collator,\n args=training_args,\n compute_metrics=compute_metrics,\n train_dataset=train_datasets,\n eval_dataset=test_datasets,\n tokenizer=audio_processor.feature_extractor,\n )\n import gc\n gc.collect()\n torch.cuda.empty_cache()\n trainer.train()","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"560703514","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSaintMediaJP spider created on the top of ATSSpider\n\nscrapy crawl saintmedia_jp -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.saintmedia.co.jp/work/area.html\"\n\nSample URL:\n http://www.saintmedia.co.jp/work/area.html\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import HtmlFormatter, NormalizedJoin, Prefix\n\npattern = {\n 'ref_id': compile(r'detail-(\\d+)\\.'),\n}\n\n\nclass SaintMediaJP(ATSSpider):\n\n name = 'saintmedia_jp'\n logo_url = ''\n\n def parse(self, response):\n sel = Selector(response)\n # logo url\n if not self.logo_url:\n logo_url = sel.xpath(\n '//div[@id=\"headLogo\"]/a/img/@src'\n ).extract()\n if logo_url:\n self.logo_url = urljoin(response.url, logo_url[0])\n\n \"\"\" Selecting all states \"\"\"\n state_hrefs = sel.xpath(\n '//div[@id=\"search_dotbar\"]/dl[@id=\"area\"]/dd/a/@href'\n ).extract()\n for state_href in state_hrefs:\n yield Request(\n callback=self.parse_state,\n url=urljoin(response.url, state_href)\n )\n\n def parse_state(self, response):\n sel = Selector(response)\n \"\"\" Selecting all cities \"\"\"\n city_hrefs = sel.xpath(\n '//ul[@id=\"pref\"]/li/a/@href'\n ).extract()\n for city_href in city_hrefs:\n yield Request(\n callback=self.parse_jobs_list,\n url=urljoin(response.url, city_href)\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n \"\"\"\n parse all jobs list and call details page\n \"\"\"\n for href in sel.xpath(\n '//div[@id=\"list_wrap\"]/div[@id=\"list_area\"]/div[@id=\"list_ttl\"]/p/a/@href'\n ).extract():\n yield Request(\n callback=self.parse_job_callback(),\n url=urljoin(response.url, href)\n )\n\n next_page = sel.xpath(\n '//div[@id=\"pager\"]/ul/li/span/../following-sibling::li[1]/a/@href'\n ).extract()\n if next_page:\n yield Request(\n callback=self.parse_jobs_list,\n url=urljoin(response.url, next_page[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 '//div[@id=\"detail_area\"]/div[@id=\"detail_ttl\"]/p/text()'\n )\n loader.add_xpath(\n 'location',\n '//tr/th[contains(text(), \"%s\")]/following-sibling::td[1]/text()' % unicode('勤務地', 'utf-8')\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=pattern['ref_id']\n )\n loader.add_value('url', response.url)\n loader.add_xpath(\n 'description',\n '//tr[th[contains(text(), \"%s\")]]' % unicode('お仕事内容', 'utf-8'),\n HtmlFormatter()\n )\n loader.add_xpath(\n 'jobtype',\n '//tr/th[contains(text(), \"%s\")]/following-sibling::td[1]/text()' % unicode('雇用形態', 'utf-8')\n )\n loader.add_xpath(\n 'baseSalary',\n '//tr/th[contains(text(), \"%s\")]/following-sibling::td[1]/text()' % unicode('給与', 'utf-8')\n )\n loader.add_xpath(\n 'workhours',\n '//tr/th[contains(text(), \"%s\")]/following-sibling::td[1]//text()' % unicode('勤務日/時間', 'utf-8'),\n NormalizedJoin(' ')\n )\n loader.add_xpath(\n 'qualifications',\n '//tr[th[contains(text(), \"%s\")]]' % unicode('応募資格', 'utf-8'),\n HtmlFormatter()\n )\n loader.add_xpath(\n 'benefits',\n '//tr[th[contains(text(), \"%s\")]]' % unicode('待遇', 'utf-8'),\n HtmlFormatter()\n )\n loader.add_xpath(\n 'other',\n '//tr[th[contains(text(), \"%s\")]]' % unicode('その他', 'utf-8'),\n HtmlFormatter()\n )\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/saintmedia_jp.py","file_name":"saintmedia_jp.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"350539332","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport os.path\n\nfrom setuptools import setup, find_packages\n\nscript_path = os.path.dirname(__file__)\n\nsetup(\n name='cyclonedx-bom',\n version=open(os.path.join(script_path, 'VERSION')).read(),\n url='https://github.com/CycloneDX/cyclonedx-python',\n author='Steve Springett',\n author_email='steve.springett@owasp.org',\n maintainer='Steve Springett',\n maintainer_email='steve.springett@owasp.org',\n description='CycloneDX Software Bill of Materials (SBOM) generation utility',\n long_description=open(os.path.join(script_path, 'README.md')).read(),\n long_description_content_type=\"text/markdown\",\n keywords=[\"BOM\", \"SBOM\", \"SCA\", \"OWASP\"],\n license='Apache-2.0',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Information Technology',\n 'Intended Audience :: Legal Industry',\n 'Intended Audience :: System Administrators',\n 'Topic :: Security',\n 'Topic :: Software Development',\n 'Topic :: System :: Software Distribution',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9'\n ],\n packages=find_packages(),\n python_requires='>=3.6',\n data_files=[('', ['README.md', 'requirements.txt', 'requirements-test.txt', 'VERSION'])],\n install_requires=open(os.path.join(script_path, 'requirements.txt')).read(),\n entry_points={\n 'console_scripts': [\n 'cyclonedx-py=cyclonedx_py.client:main'\n ]\n },\n zip_safe=False\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"19788884","text":"# from bs4 import BeautifulSoup\nimport requests\nimport random\nfrom datetime import datetime\nfrom datetime import timedelta\n\n\ndef get_date(day):\n\n if day == 'today':\n\n return datetime.today().strftime(\"%d.%m.%Y\")\n\n else:\n\n today_day = datetime.today()\n\n start = today_day - timedelta(days=today_day.weekday())\n choosen_day = start + timedelta(days=day)\n return choosen_day.strftime(\"%d.%m.%Y\")\n\n\ndef get_schedule_dict(day):\n\n date = get_date(day)\n\n url = 'https://www.chsu.ru/raspisanie'\n\n r = requests.post(url, data=get_body(date),\n headers=get_headers(), params=get_params()) # params=get_params())\n\n try:\n return r.json()\n except:\n\n print('Something went wrong!')\n\n\ndef get_body(date):\n\n body = '_TimeTable_WAR_TimeTableportlet_cmd=timeTable&_TimeTable_WAR_TimeTableportlet_typeTimeTable=period&_TimeTable_WAR_TimeTableportlet_group=7%D0%AD%D0%91-01-51%D0%BE%D0%BF&_TimeTable_WAR_TimeTableportlet_semester=1+%D1%81%D0%B5%D0%BC%D0%B5%D1%81%D1%82%D1%80+2016%2F2017&_TimeTable_WAR_TimeTableportlet_type=student&_TimeTable_WAR_TimeTableportlet_startDate=' + \\\n date+'&_TimeTable_WAR_TimeTableportlet_endDate=' + \\\n date # &_TimeTable_WAR_TimeTableportlet_professor=3741'\n\n return body\n\n\ndef get_headers():\n\n headers = {'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin',\n 'Origin': 'https://www.chsu.ru',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Accept': '*/*',\n 'Referer': 'https://www.chsu.ru/raspisanie',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Connection': 'keep-alive'}\n\n return headers\n\n\ndef get_params():\n\n params = {'p_p_id': 'TimeTable_WAR_TimeTableportlet',\n 'p_p_lifecycle': '2',\n 'p_p_state': 'normal',\n 'p_p_mode': 'view',\n 'p_p_cacheability': 'cacheLevelPage',\n 'p_p_col_id': 'column-1',\n 'p_p_col_count': '1',\n }\n\n return params\n\n\ndef get_text(data):\n\n result = ''\n for i in data.get('response')['items']:\n\n time = str(i.get('time'))\n aud = str(i.get('audience'))\n prof_name = str(i.get('professor')['name'])\n disc = str(i.get('discipline'))\n\n result = result + (time+' | '+disc+' | '+aud+' | '+prof_name) + '\\n'\n\n return result if result != '' else 'нет пар'\n\n\ndef get_schedule(day):\n\n return get_text(get_schedule_dict(day))\n\n\n# if __name__ == '__main__':\n\n# print(get_schedule('today'))\n","sub_path":"db_tutorial/mybots/vk_bot/schedule/pars_schedule.py","file_name":"pars_schedule.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"464106710","text":"import tornado.ioloop\nimport tornado.web\nimport os\nimport base64\nimport face_detect\nimport pic_pretreatment\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"main.html\")\n\nclass UpLoadHandler(tornado.web.RequestHandler):\n def post(self):\n # get and save original picture\n data = self.get_argument(\"data\")\n picData = base64.b64decode(data)\n pic_file = open(\"static/original.jpg\", \"w\")\n pic_file.write(picData)\n pic_file.close()\n # face detection\n region = face_detect.process(\"static/original.jpg\", \"static/detected.jpg\")\n # pretreatment\n pic_pretreatment.process(region, \n grayfile = \"static/gray.jpg\", \n smoothfile = \"static/smooth.jpg\",\n equfile = \"static/equ.jpg\",\n )\n self.write(\"uploadok\")\n\n\nclass PicProcessHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"picprocess.html\", \n original = \"static/original.jpg\", \n detected = \"static/detected.jpg\", \n gray = \"static/gray.jpg\", \n smooth = \"static/smooth.jpg\",\n equ = \"static/equ.jpg\",\n )\n\n\nsettings = {\n \"static_path\": os.path.join(os.path.dirname(__file__), \"static\"),\n \"cookie_secret\": \"61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=\",\n \"login_url\": \"/login\",\n \"xsrf_cookies\": False,\n}\n\napplication = tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/upload\", UpLoadHandler),\n (r\"/picprocess\", PicProcessHandler),\n (r\"/(favicon\\.ico)\", tornado.web.StaticFileHandler, dict(path=settings['static_path'])),\n], debug = True, **settings)\n\nif __name__ == \"__main__\":\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"538600672","text":"#!/usr/bin/env python\n\n#function overwrites \"student_answer.py\" file using the 2 passed command line arguments\ndef write_to_py(students_code, test_case):\n f = open('/afs/cad.njit.edu/u/r/l/rl265/public_html/php/student_answer.py', 'w') #opens \"student_answer.py\" to be written to\n f.write(students_code + \"\\n\" + \"print(\" + test_case + \")\") #writes the students code then runs test case in \"student_answer.py\"\n f.close()\n\nif __name__ == '__main__': #accepts arguments from php\n import sys #needed to call arguments\n write_to_py(sys.argv[1], sys.argv[2]) #calls write_to_py() with 1st and 2nd passed arguments\n","sub_path":"4-06-2018/Every File/php/overwrite.py","file_name":"overwrite.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"56381203","text":"from django.core import serializers\nfrom .models import Judge\nfrom .models import Team\nfrom collections import defaultdict\nfrom .models import Mentor\nfrom .models import Mentoring\nfrom .models import Challenge\nfrom django.shortcuts import render\n\nfrom django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nimport logging\nfrom dateutil import parser\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_protect, csrf_exempt\nfrom .models import Student\nfrom .controllers import AuthenticationController as authentication\nimport json\nimport http\n\n\n@csrf_exempt\ndef get_listOf_project(request):\n user_model = request.user\n try:\n Judger_model = Judge.objects.get(user_id=user_model)\n except:\n return HttpResponse(\"O usuário logado não é um jurado, você está tentando burlar o sistema?\")\n lof_teams = Team.objects.filter(\n challenge=Judger_model.challenge,).exclude(link_project=None)\n data = lof_teams.values()\n\n return JsonResponse(list(data), safe=False)\n\n\n@csrf_exempt\ndef sendprojectlink(request):\n try:\n student_model = Student.objects.get(user_id=request.user)\n except:\n return HttpResponse(\"Usuário não é um estudante\")\n team_model = student_model.team_id\n team_model.link_project = request.GET.get(\"link\")\n\n team_model.save()\n return HttpResponse(\"OK\")\n\n\n@csrf_exempt\ndef register__old__Team(request):\n\n data = json.loads(request.body)\n try:\n team_name = data['team_name']\n desafio_id = 0 # O primeiro elemento vai ser um desafio nulo\n\n Team.objects.create(name=team_name, desafio_id=desafio_id)\n\n return JsonResponse({\n \"status\": \"OK\",\n }, safe=False)\n except:\n return JsonResponse({\n \"status\": \"failed\",\n }, safe=False)\n\n\n #authentication.registerTeam(team_name = data[\"team_name\"])\nstate = defaultdict(None)\n\n\ndef get_selections_mentor(request):\n user = request.user\n student = Student.objects.filter(user_id=user)\n student_first = student.first()\n\n if student_first is None:\n # Checando se o valor é de outro tipo\n isMentor = Mentor.objects.filter(user=user).exists()\n isJudger = Judge.objects.filter(user_id=user).exists()\n if isMentor:\n return HttpResponse(\"Usuário é um mentor\")\n elif isJudger:\n return HttpResponse(\"Usuário é um jurado\")\n\n if student_first.team_id is None:\n return HttpResponse(\"O estudante não tem um time\")\n\n mentoring_for_the_team = Mentoring.objects.filter(\n team=student_first.team_id)\n lof_mentoring_for_the_team = list(mentoring_for_the_team.values())\n\n filter_ = [x['mentor_id'] for x in lof_mentoring_for_the_team]\n for ind, id_ in enumerate(filter_):\n mentor = Mentor.objects.get(id=id_)\n lof_mentoring_for_the_team[ind][\"mentor_name\"] = mentor.user.first_name + \\\n \" \" + mentor.user.last_name\n lof_mentoring_for_the_team[ind]['data_meeting'] = lof_mentoring_for_the_team[ind]['time_meeting']\n del lof_mentoring_for_the_team[ind][\"time_meeting\"]\n\n return JsonResponse(lof_mentoring_for_the_team, safe=False)\n\n\n@csrf_exempt\ndef check_user_type(request):\n user_model = request.user\n isStudent = Student.objects.filter(user_id=user_model).exists()\n isMentor = Mentor.objects.filter(user=user_model).exists()\n isJudger = Judge.objects.filter(user_id=user_model).exists()\n\n if isStudent:\n return HttpResponse(\"Student\")\n elif isMentor:\n return HttpResponse(\"Mentor\")\n elif isJudger:\n return HttpResponse(\"Judger\")\n\n\ndef get_mentor_info(request):\n user_model = request.user\n mentor_model = Mentor.objects.get(user=user_model)\n data = dict()\n\n data['user'] = {\n 'name': user_model.first_name + \" \" + user_model.last_name\n }\n\n data['challenge'] = {\n \"id\": mentor_model.challenge.id,\n \"name\": mentor_model.challenge.name,\n \"enterprise\": mentor_model.challenge.empresa_desafiadora,\n \"description\": mentor_model.challenge.description\n }\n data['id'] = mentor_model.id\n data[\"kind\"] = \"Mentor\"\n\n return JsonResponse(data)\n\n\n@csrf_exempt\ndef get_user_info(request):\n user = request.user\n data = dict()\n user_category = Student.objects.filter(user_id=user)\n if user_category.exists():\n user_category_model = user_category.first()\n #team_id = Team.objects.filter(id = user_category_model.team_id)\n team_id = user_category_model.team_id\n\n data['user'] = {\n 'name': user_category_model.user_id.first_name + \" \" + user_category_model.user_id.last_name\n }\n\n if team_id is not None:\n team_id_model = team_id\n data['team'] = {\n \"id\": team_id_model.id,\n \"challenge\": team_id_model.challenge.name,\n }\n else:\n data['team'] = None\n else:\n data['user'] = None\n user_category = Mentor.objects.filter(user=user)\n if user_category.exists():\n return get_mentor_info(request)\n\n data['kind'] = \"Student\"\n return JsonResponse(data)\n\n\n@csrf_exempt\n@login_required\ndef get_teams(request):\n judger = Judge.objects.get(user_id=request.user)\n # Apenas a equipe que contem o desafio do jurado\n teams = Team.objects.filter(challenge_id=judger.challenge_id)\n lofs = list(teams.values())\n challenges_ids = [x['challenge_id'] for x in lofs]\n challenge_list = []\n for x in challenges_ids:\n challenge_unique = Challenge.objects.get(id=x)\n challenge_list.append({\n \"id\": challenge_unique.id,\n \"name\": challenge_unique.name,\n \"challenger_enterprise\": challenge_unique.empresa_desafiadora\n })\n\n for ind, val in enumerate(lofs):\n lofs[ind]['challenge_id'] = challenge_list[ind]\n temp = lofs\n # Retornando os dados no estilo json\n json_format = JsonResponse(temp, safe=False)\n return json_format\n\n\n@csrf_exempt\ndef set_points(request):\n # Receber o juiz\n judger = Judge.objects.get(user_id=request.user)\n # Realizar a inserção da nota\n # Obter o team_id que será enviado pelo sistema\n team_id = request.GET.get(\"team_id\")\n noteJudger = request.GET.get(\"note\")\n team = Team.objects.get(id=int(team_id))\n team.judger_assign = judger\n team.noteJudger = float(noteJudger)\n team.save()\n\n return HttpResponse(\"OK\")\n\n\ndef select_mentor(request):\n \"\"\"\n Esta função já partirá do princípio que a lista dos mentores assim como seu identificado já foi enviado para o front-end, logo o front-end apenas irá realizar uma requisição\n dado o id e o nome do mentor junto com a data da mentoria disponível.\n \"\"\"\n\n # obtendo os dados\n user = request.user\n mentor_name = request.GET.get('mentor_name')\n mentor_id = request.GET.get('mentor_id')\n meeting_data = request.GET.get('data_meeting') # str\n student = Student.objects.get(user_id=request.user)\n team = student.team_id\n\n # Verificar se a mentoria já foi selecionada.\n data_info_formated = parser.parse(meeting_data)\n mentor_model = Mentor.objects.get(id=mentor_id)\n\n try:\n # Captura todas as mentorias disponíveis do mentor\n mentoring_model = Mentoring.objects.get(\n mentor=mentor_model, team=None, time_meeting=data_info_formated)\n except:\n return HttpResponse(\"Mentoria não encontrada\")\n mentoring_model.team = team\n mentoring_model.save()\n return HttpResponse(\"Mentoria registrada!\")\n\n # Inserindo a nova mentoria\n\n newMentoring = Mentoring(mentor=mentor_model,\n team=team, time_meeting=data_info_formated)\n\n newMentoring.save()\n return HttpResponse(\"Meeting made\")\n # return JsonResponse(data, safe = False)\n\n\n@csrf_exempt\ndef show_disposable_mentors(request):\n \"\"\"\n Esta função fará a seleção dos mentores disponível para então mostrar para o usuário\n \"\"\"\n\n # Precisamos checar se a mentorias selecionada faz parte do setor de interesse do usuário.\n user_model = request.user\n team_model = Student.objects.get(user_id=user_model).team_id\n\n if team_model is None:\n return HttpResponse(\"O usuário inserido não possui um time\")\n #challenge_id = mentorias_model.mentor_id.challenge_id\n\n mentorias_model = Mentoring.objects.filter(\n mentor_id__challenge_id=team_model.challenge_id\n ) # filtrando apenas as mentorias que estão livres\n #disposable_meetings = mentorias_model.filter(mentor_id__challenge_id = team_model.challenge_id)\n #values = list(disposable_meetings.objects.values())\n\n # mentor_info = mentorias_model.\n values = list(mentorias_model.values())\n filter_ = [v['mentor_id'] for v in values]\n\n for ind, v in enumerate(filter_):\n first_name = Mentor.objects.get(id=v).user.first_name\n last_name = Mentor.objects.get(id=v).user.last_name\n values[ind][\"name\"] = f\"{first_name} {last_name}\"\n #response = Mentor.objects.get(id__in = filter_)\n\n #mentor_filter = Mentor.objects.filter(id__in = filter_).get(\"user_id\")\n\n # return HttpResponse(\"OK\")\n return JsonResponse(values, safe=False)\n\n\ndef insert_data_meeting(request):\n \"\"\"\n Função que fará a inserção dos horário de mentoria\n \"\"\"\n user_model = request.user # usuário precisa ser um mentor\n meeting_hour = request.GET.get('meeting_hour')\n try:\n mentor_model = Mentor.objects.get(user=user_model)\n except:\n return HttpResponse(\"Usuário não é um mentor\")\n from datetime import datetime\n #datetime_formated = datetime.strptime(date = meeting_hour,format = \"%d/%m/%Y %H:%M:%S\")\n datetime_formated = parser.parse(meeting_hour)\n time_meeting = datetime_formated\n Mentoring.objects.create(\n mentor=mentor_model, team=None, time_meeting=time_meeting)\n\n return HttpResponse(\"WORK!\")\n\n\n@csrf_exempt\ndef integrate_team(request):\n user_model = request.user\n # Ger Json data {\"Team\" : [\"e-mail1\",\"e-mail2\"]}\n data = json.loads(request.body)\n emails = data['email']\n student_model = Student.objects.get(user_id=user_model)\n team_model = student_model.team_id\n lof_status = []\n\n #anothers_user_models = User.objects.filter(email__in = emails)\n\n #students_user_models = Student.objects.filter(user_id__in = anothers_user_models)\n\n #students_user_models_without_team = students_user_models.filter(team_id = None)\n\n # students_user_models_with_team = students_user_models.exclude(team_id = None) # Finalizar esta parte para retornar as pessoas que não foram inseridas na equipe\n #students_user_models_without_team.update(team_id = team_model)\n\n for email in emails:\n # try:\n\n another_user_model = User.objects.get(email=email)\n\n another_student_model = Student.objects.get(user_id=another_user_model)\n\n another_student_model.team_id = team_model\n another_student_model.save()\n\n lof_status.append({\n \"name\": another_user_model.first_name + \" \" + another_user_model.last_name,\n \"status\": \"integrated\"\n })\n\n resposta = JsonResponse(lof_status, safe=False)\n #resposta[\"Access-Control-Allow_Origin\"] = \"*\"\n #resposta[\"Access-Control-Allow_Methods\"] = ['GET','POST','OPTION']\n #resposta[\"Access-Control-Allow_Headers\"] = \"*\"\n\n return resposta\n\n\n@csrf_exempt\ndef getout_team(request):\n user_model = request.user\n student_model = Student.objects.get(user_id=user_model)\n\n if student_model.isLeader:\n QueryStudentSet = Student.objects.filter(team_id=student_model.team_id)\n QueryStudentSet.team_id = None\n student_model.team_id.delete()\n\n student_model.team_id = None\n student_model.save()\n return HttpResponse(\"OK\")\n\n\n@csrf_exempt\ndef create_team(request):\n \"\"\"\n Quando o time é criado, automaticamente este está associado a um desafio\n \"\"\"\n\n user_model = request.user\n challenge_name = request.GET.get(\"challenge\")\n try:\n challenge_model = Challenge.objects.get(name=challenge_name)\n except:\n return JsonResponse({\n \"status\": \"challenge canno't be found\"\n })\n\n student_model = Student.objects.get(user_id=user_model)\n team_model = Team.objects.create(challenge_id=challenge_model.id)\n student_model.team_id = team_model\n student_model.save()\n\n return JsonResponse({\n \"status\": \"OK\"\n })\n\n\ndef create_challenge(request):\n # No momento a criação dos desafios seá feita diretamente na página do administrador\n\n challenge_name = request.GET.get(\"challenge\")\n check_exists = Challenge.objects.filter(name=challenge_name)\n\n if len(check_exists):\n return JsonResponse({\n 'status': 'challenge already exist'\n })\n else:\n\n challenge_model = Challenge.objects.create(name=challenge_name)\n return JsonResponse({\n \"status\": \"ok\"\n })\n\n\n@csrf_exempt\ndef loginUser(request):\n\n username = request.GET.get('username')\n logout(request)\n login_field = login(request, user_authentication,)\n\n if username is not None:\n return JsonResponse({\n \"status\": \"ok\",\n })\n else:\n return JsonResponse({\n })\n\n\n@csrf_exempt\ndef register(request):\n username = request.GET.get('username')\n email = request.GET.get('email')\n first_name = request.GET.get('first_name')\n last_name = request.GET.get('last_name')\n category = request.GET.get('category')\n # será o id do desafio pois na tela de login o jurado recebera o id do desafio\n challenge_id = request.GET.get('challenge')\n challenge = challenge_id\n check_user = User.objects.filter(email=email)\n\n # O usuário já existe?\n if len(check_user):\n # login(request,usuario)\n return JsonResponse({\n 'status': 'User already exist',\n }, safe=False)\n else:\n user_model.first_name = first_name\n user_model.last_name = last_name\n user_model.save()\n\n if category == 'student':\n student_model = Student.objects.create(\n user_id=user_model, team_id=None, isLeader=False)\n elif category == 'judger':\n challenge = Challenge.objects.get(id=challenge_id)\n jugder_mode = Judge.objects.create(\n user_id=user_model, challenge=challenge)\n\n elif category == 'mentor':\n # mentor_model = Mentor.objects.create(user = user_model, challenge)\n challenge = Challenge.objects.get(id=challenge_id)\n mentor_model = Mentor.objects.create(\n user=user_model, challenge=challenge)\n\n return JsonResponse({\n 'status': 'created'\n }, safe=False)\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"441836235","text":"def get_coach_data(filename):\n try:\n with open(filename) as f:\n data = f.readline()\n List = data.strip().split(\",\")\n dic = {}\n dic[\"Name\"] = List.pop(0)\n dic[\"Dob\"] = List.pop(0)\n dic[\"Times\"] = str(sorted(set(sanitize(t) for t in List))[0:3])\n return dic\n except IOError as error:\n print(\"File error\" + str(error))\n return (None)\n\ndef sanitize(item):\n if '-' in item:\n spliter = \"-\"\n elif ':' in item:\n spliter = \":\"\n else:\n return item\n (first, second) = item.split(spliter)\n return (first + \".\" + second)\n\nsarah = get_coach_data(\"sarah2.txt\")\nprint (sarah[\"Name\"] + \"'s fastest time are: \" + sarah[\"Times\"])\n","sub_path":"Head-First Python/Chapter-6/function5.py","file_name":"function5.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"137085731","text":"# Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.\n\n# You may return the answer in any order.\n\n \n\n# Example 1:\n\n# Input: [\"bella\",\"label\",\"roller\"]\n# Output: [\"e\",\"l\",\"l\"]\n# Example 2:\n\n# Input: [\"cool\",\"lock\",\"cook\"]\n# Output: [\"c\",\"o\"]\n\nclass Solution:\n def commonChars(self, A: List[str]) -> List[str]:\n chr_cnt = self.cntChrs(A[0]) \n for w in A:\n new_cnt = {}\n curr_cnt = self.cntChrs(w)\n for c, cnt in curr_cnt.items():\n if c in chr_cnt: \n new_cnt[c] = min(cnt, chr_cnt[c]) \n chr_cnt = new_cnt \n res = [] \n for c, cnt in chr_cnt.items():\n if cnt == 1: \n res.append(c)\n else:\n for _ in range(cnt):\n res.append(c)\n return res \n\n def cntChrs(self, w: str) -> dict: \n d = {}\n for c in w: \n if c not in d:\n d[c] = 0\n d[c] += 1 \n return d\n","sub_path":"dailyProb/prob1002.py","file_name":"prob1002.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"45777154","text":"from typing import Dict\n\nfrom models.test_suite_models.test_suite import TestSuite\n\n\nclass TraceStatistics:\n def __init__(self, test_suite: TestSuite):\n self.ground_truth_cardinality = len(test_suite.logic_methods_faulty)\n self.ground_truth_mid_to_trace_count = test_suite.get_trace_count_for_ground_truth()\n self.ground_truth_trace_count = sum(self.ground_truth_mid_to_trace_count.values())\n self.total_test_methods = len(test_suite.test_methods)\n\n def gen_value_maps(self):\n value_map = {\n 'Ground Truth Total Trace Count': self.ground_truth_trace_count,\n 'Ground Truth Average Trace Count': self.ground_truth_trace_count / len(self.ground_truth_mid_to_trace_count),\n 'Ground Truth Traces Per Method': ','.join(str(v) for v in self.ground_truth_mid_to_trace_count.values()),\n 'Total Number of Tests': self.total_test_methods,\n # 'Total Tests hitting faulty components': ,\n # 'Average Tests hitting faulty components': ,\n }\n return value_map\n","sub_path":"models/test_suite_models/trace_statistics.py","file_name":"trace_statistics.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"331746640","text":"from rng import RNG\n\nclass Trace:\n def __init__(self):\n self.vars = {}\n self.vars_frozen = {}\n self.isOutputFrozen = False\n self.isAllFrozen = False\n self.isNoneFrozen = True\n def __call__(self, *args):\n name = args[0]\n if self.isNoneFrozen:\n if name in self.vars:\n return self.vars[name].getValue()\n else:\n return RNG(name,self)\n elif self.isAllFrozen:\n if name in self.vars_frozen:\n return self.vars[name].getValue()\n else:\n self.vars_frozen[name] = \"\"\n return RNG(name,self,False)\n elif self.isOutputFrozen:\n if name in self.vars_frozen:\n return self.vars[name].getValue()\n elif not self.vars[name].isOutput:\n self.vars_frozen[name] = \"\"\n return RNG(name,self)\n else:\n self.vars_frozen[name] = \"\"\n return RNG(name,self,False)\n else:\n raise\n\n def density(self):\n return reduce(lambda x,y:x*y, [self.vars[x].density() for x in self.vars], 1)\n def get_latent_densities(self):\n return [(x, self.vars[x].density()) for x in self.vars if not self.vars[x].isOutput]\n def get_output_densities(self):\n return [(x, self.vars[x].density()) for x in self.vars if self.vars[x].isOutput]\n def get_latent_values(self):\n return [(x, self.vars[x].getValue()) for x in self.vars if not self.vars[x].isOutput]\n def get_output_values(self):\n return [(x, self.vars[x].getValue()) for x in self.vars if self.vars[x].isOutput]\n\n def tag_random_outputs(self, names):\n for name in names:\n if name not in self.vars:\n raise\n else:\n self.vars[name].isOutput = True\n def freeze_all(self):\n self.vars_frozen = {}\n self.isOutputFrozen = False\n self.isAllFrozen = True\n self.isNoneFrozen = False\n def freeze_output(self):\n self.vars_frozen = {}\n self.isOutputFrozen = True\n self.isAllFrozen = False\n self.isNoneFrozen = False\n def freeze_none(self):\n self.vars_frozen = {}\n self.isOutputFrozen = False\n self.isAllFrozen = False\n self.isNoneFrozen = True\n","sub_path":"code/trace.py","file_name":"trace.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"215916615","text":"#\n# Dependencies:\n# RemoveExtraWhitespace\n#\n\nfrom norlinter.rule import SingleLineRule\n\nMEMORY = [\"copy\", \"strong\", \"weak\", \"assign\"]\nACCESS = [\"readwrite\", \"readonly\"]\n\nclass FixProperties (SingleLineRule):\n def format(self, line):\n formatted = line.strip()\n if not formatted.startswith(\"@property\"): return line\n # Doesn't have attributes\n if formatted.replace(\" \", \"\")[9] != \"(\":\n return \"{};\".format(formatted.strip(\"; \"))\n start = formatted.find(\"(\") # Already checked w/ previous condition\n end = formatted.find(\")\", start)\n assert end != -1, \"property is not properly defined\"\n attributes = formatted[start+1:end]\n attributes = attributes.replace(\" \", \"\").split(\",\")\n ordered = []\n # nonatomic is always first\n if \"nonatomic\" in attributes[:]:\n ordered.append(\"nonatomic\")\n attributes.remove(\"nonatomic\")\n # Put memory first\n for attribute in attributes[:]:\n if attribute in MEMORY:\n ordered.append(attribute)\n attributes.remove(attribute)\n # Access restrictions second\n for attribute in attributes[:]:\n if attribute in ACCESS:\n ordered.append(attribute)\n attributes.remove(attribute)\n # Everything else is last\n for attribute in attributes[:]:\n ordered.append(attribute)\n return \"@property ({}) {};\".format(\", \".join(ordered), formatted[end+1:].strip(\"; \"))\n\n def getErrorDescription(self):\n return \"Invalid formatted property declaration\"\n","sub_path":"norlinter/source/norlinter/rule/FixProperties.py","file_name":"FixProperties.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"164151915","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 2 13:09:20 2017\n\n@author: 凯风\n\"\"\"\n\nfrom gensim.models import Word2Vec\nimport jieba,logging\nimport nltk\nimport numpy as np \nimport pandas as pd \n\n'''\n 通过深度学习,将生成每个词的向量。\n 具体的研究看论文或blog吧\n https://segmentfault.com/a/1190000008173404\n 这是一篇关于官网给出的教程的翻译,感觉还不错\n'''\n\n\n# 日志配置\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n# 读取数据\nfilename = 'C:/Users/dell/Desktop/金瓶梅.txt'\ndata = open(filename,encoding='utf-8',errors='ignore').readlines()\n\n# 特征处理\ndata = data[256:]\ndata = list(filter(lambda s : len(s) > 3 , data))\ndata = list(map(lambda s : s.strip() , data))\nwords = map(lambda s : list(jieba.cut(s)) , data)\nall_words = []\nfor each in words:\n all_words.extend(each)\n\n# 获取停用词清单\nstopwords_english = nltk.corpus.stopwords.words('english')\nfilename = 'D:/mygit/ML_Method_summary/Text_Operation/Basic_Operation/stopword.txt'\nstopwords_chinese = [line.rstrip() for line in open(filename)]\n\n# 停词处理\nword_stoped_middle = [i for i in all_words if i not in stopwords_english]\nword_stoped = [i for i in word_stoped_middle if i not in stopwords_chinese]\n\nn = np.unique(word_stoped,return_counts=True)\ns = pd.Series(data = n[1],index = n[0])\ns = s[6:]\nbook_words = s.sort_values(ascending=False)\nbook_words.values\nbook_words.index\n\n# 出现的词大于100次,且为长度大于1的\nbook_words[book_words > 200]\n\n# word2vec\n# 这里最好传入的是迭代器,不要传入其他类型的数据结构,会训练速度\nmodel = Word2Vec(word_stoped)\nmodel['西']\nmodel.most_similar(positive=['西'],topn=20)\n\n\n# 还有很多方法,可以调用\n\n'''\n sentences 句子,要向量化的对象\n size 每个词的向量维数\n alpha 1 \n window 1\n min_count 忽略一些词,用于修建内部的字典\n max_vocab_size \n sample 1\n seed 1\n workers 装了Cpython有效,用于加快训练\n min_alpha 1\n sg 1\n hs 1\n negative 1\n cbow_mean 1\n iter 1\n null_word 1\n trim_rule 1\n sorted_vocab 1\n batch_words 1\n'''\n","sub_path":"Text_Operation/Basic_Operation/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"178188757","text":"# coding=utf-8\n# author=yphacker\n\nimport numpy as np\nfrom conf import config\nfrom conf import bert_model_config\nfrom utils.bert import tokenization\n\n\ndef get_bert_param_lists(texts):\n \"\"\"\n 将数据转换成Bert能够使用的格式\n input_ids:根据BERT-Base-Chinese checkpoint中的vocabtxt中每个字出现的index,将训练文本中的每一个字替换为vocab.txt中的index,需要添加开始CLS和结束SEP\n input_masks:包含开始CLS和结束SEP有字就填1\n segment_ids:seq2seq类任务同时传入两句训练关联训练数据时,有意义,传入一句训练数据则都为0\n 以上三个list需要用0补齐到max_seq_length的长度\n \"\"\"\n # token 处理器,主要作用就是 分字,将字转换成ID。vocab_file 字典文件路径\n tokenizer = tokenization.FullTokenizer(vocab_file=bert_model_config.bert_vocab_path)\n input_ids_list = []\n input_masks_list = []\n segment_ids_list = []\n for text in texts:\n single_input_id, single_input_mask, single_segment_id = \\\n convert_single_example_simple(config.max_seq_length, tokenizer, text)\n input_ids_list.append(single_input_id)\n input_masks_list.append(single_input_mask)\n segment_ids_list.append(single_segment_id)\n input_ids = np.asarray(input_ids_list, dtype=np.int32)\n input_masks = np.asarray(input_masks_list, dtype=np.int32)\n segment_ids = np.asarray(segment_ids_list, dtype=np.int32)\n return input_ids, input_masks, segment_ids\n\n\ndef bert_bacth_iter(x, y, batch_size=config.batch_size):\n input_ids, input_masks, segment_ids = x\n index = np.random.permutation(len(y))\n n_batches = len(y) // batch_size\n for batch_index in np.array_split(index, n_batches):\n batch_input_ids, batch_input_masks, batch_segment_ids, batch_y = \\\n input_ids[batch_index], input_masks[batch_index], segment_ids[batch_index], y[batch_index]\n yield (batch_input_ids, batch_input_masks, batch_segment_ids), batch_y\n\n\ndef batch_iter(x, y, batch_size=config.batch_size):\n \"\"\"生成批次数据\"\"\"\n data_len = len(x)\n num_batch = int((data_len - 1) / batch_size) + 1\n\n indices = np.random.permutation(np.arange(data_len))\n x_shuffle = x[indices]\n y_shuffle = y[indices]\n\n for i in range(num_batch):\n start_id = i * batch_size\n end_id = min((i + 1) * batch_size, data_len)\n yield x_shuffle[start_id:end_id], y_shuffle[start_id:end_id]\n\n\ndef get_sequence_length(x_batch):\n \"\"\"\n Args:\n x_batch:a batch of input_data\n Returns:\n sequence_lenghts: a list of acutal length of every senuence_data in input_data\n \"\"\"\n sequence_lengths = []\n for x in x_batch:\n actual_length = np.sum(np.sign(x))\n sequence_lengths.append(actual_length)\n return sequence_lengths\n\n\ndef export_word2vec_vectors(vocab):\n \"\"\"\n Args:\n vocab: word_to_id\n word2vec_dir:file path of have trained word vector by word2vec\n trimmed_filename:file path of changing word_vector to numpy file\n Returns:\n save vocab_vector to numpy file\n\n \"\"\"\n infile = open(config.vector_word_filename, 'r')\n voc_size, vec_dim = None, None\n embeddings = None\n for i, line in enumerate(infile):\n if i == 0:\n voc_size, vec_dim = map(int, line.split(' '))\n embeddings = np.zeros([len(vocab), vec_dim])\n continue\n items = line.split(' ')\n word = items[0]\n # vec = np.asarray(items[1:], dtype='float32')\n vec = np.asarray(items[1:])\n if word in vocab:\n word_idx = vocab[word]\n embeddings[word_idx] = np.asarray(vec)\n np.savez_compressed(config.vector_word_npz, embeddings=embeddings)\n infile.close()\n\n\ndef get_training_word2vec_vectors(filename):\n \"\"\"\n Args:\n filename:numpy file\n Returns:\n data[\"embeddings\"]: a matrix of vocab vector\n \"\"\"\n with np.load(filename) as data:\n return data[\"embeddings\"]\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef convert_single_example_simple(max_seq_length,\n tokenizer, text_a, text_b=None):\n tokens_a = tokenizer.tokenize(text_a)\n tokens_b = None\n if text_b:\n tokens_b = tokenizer.tokenize(text_b) # 这里主要是将中文分字\n if tokens_b:\n # 如果有第二个句子,那么两个句子的总长度要小于 max_seq_length - 3\n # 因为要为句子补上[CLS], [SEP], [SEP]\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # 如果只有一个句子,只用在前后加上[CLS], [SEP] 所以句子长度要小于 max_seq_length - 2\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # 转换成bert的输入,注意下面的type_ids 在源码中对应的是 segment_ids\n # (a) 两个句子:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) 单个句子:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # 这里 \"type_ids\" 主要用于区分第一个第二个句子。\n # 第一个句子为0,第二个句子是1。在预训练的时候会添加到单词的的向量中,但这个不是必须的\n # 因为[SEP] 已经区分了第一个句子和第二个句子。但type_ids 会让学习变的简单\n\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n input_ids = tokenizer.convert_tokens_to_ids(tokens) # 将中文转换成ids\n # 创建mask\n input_mask = [1] * len(input_ids)\n # 对于输入进行补0\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n return input_ids, input_mask, segment_ids # 对应的就是创建bert模型时候的input_ids,input_mask,segment_ids 参数\n","sub_path":"英文垃圾信息分类/src/utils/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":7097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"647047319","text":"import bpy\n\n\ndef object_prepare():\n\tops_ob = bpy.ops.object\n\tops_ob.make_single_user(object=True, obdata=True)\n\tops_ob.convert(target=\"MESH\")\n\n\ndef mesh_selection(ob, select_action):\n\tcontext = bpy.context\n\tsce = context.scene\n\tobj = context.active_object\n\tops = bpy.ops\n\tops_me = bpy.ops.mesh\n\tops_ob = ops.object\n\n\n\tdef mesh_cleanup():\n\t\tops_me.select_all(action=\"SELECT\")\n\t\tops_me.delete_loose()\n\t\tops_me.select_all(action=\"SELECT\")\n\t\tops_me.remove_doubles(threshold=0.0001)\n\t\tops_me.fill_holes(sides=0)\n\t\tops_me.normals_make_consistent()\n\n\n\tsce.objects.active = ob\n\tops_ob.mode_set(mode=\"EDIT\")\n\n\tmesh_cleanup()\n\tops_me.select_all(action=select_action)\n\n\tops_ob.mode_set(mode=\"OBJECT\")\n\tsce.objects.active = obj\n\n\ndef modifier_boolean(obj, ob, mode):\n\tmd = obj.modifiers.new('Booltron', 'BOOLEAN')\n\tmd.show_viewport = False\n\tmd.show_render = False\n\tmd.operation = mode\n\tmd.object = ob\n\n\tbpy.ops.object.modifier_apply(modifier=\"Booltron\")\n\tbpy.context.scene.objects.unlink(ob)\n\tbpy.data.objects.remove(ob)\n\n\ndef boolean_optimized(mode):\n\tcontext = bpy.context\n\tobj = context.active_object\n\n\tobject_prepare()\n\n\tobj.select = False\n\tobs = context.selected_objects\n\tob = obs[0]\n\n\tif len(obs) != 1:\n\t\tcontext.scene.objects.active = ob\n\t\tbpy.ops.object.join()\n\t\tcontext.scene.objects.active = obj\n\n\tmesh_selection(obj, 'DESELECT')\n\tmesh_selection(ob, 'SELECT')\n\tmodifier_boolean(obj, ob, mode)\n\tobj.select = True\n\n\ndef boolean_each(mode):\n\tcontext = bpy.context\n\tobj = context.active_object\n\n\tobject_prepare()\n\n\tobj.select = False\n\tobs = context.selected_objects\n\n\tmesh_selection(obj, 'DESELECT')\n\tfor ob in obs:\n\t\tmesh_selection(ob, 'SELECT')\n\t\tmodifier_boolean(obj, ob, mode)\n\tobj.select = True\n\n\n\n\n\n\ndef union():\n\tcontext = bpy.context\n\tmode = 'UNION'\n\n\n\tdef separate():\n\t\tops = bpy.ops\n\t\tops_ob = ops.object\n\t\tops_ob.mode_set(mode=\"EDIT\")\n\t\tops.mesh.separate(type=\"LOOSE\")\n\t\tops_ob.mode_set(mode=\"OBJECT\")\n\n\n\tboolean_optimized(mode)\n\tseparate()\n\tif len(context.selected_objects) != 1:\n\t\tboolean_each(mode)\n\n\ndef intersect():\n\tmode = 'INTERSECT'\n\tboolean_each(mode)\n\n\ndef difference():\n\tmode = 'DIFFERENCE'\n\tboolean_optimized(mode)\n\n\ndef separate():\n\tcontext = bpy.context\n\tsce = context.scene\n\tobj = context.active_object\n\n\n\tdef object_duplicate(ob):\n\t\tops_ob = bpy.ops.object\n\t\tops_ob.select_all(action=\"DESELECT\")\n\t\tops_ob.select_pattern(pattern=ob.name)\n\t\tops_ob.duplicate()\n\t\treturn context.selected_objects[0]\n\n\n\tobject_prepare()\n\n\tobj.select = False\n\tob = context.selected_objects[0]\n\n\tobj_copy = object_duplicate(obj)\n\tob_copy = object_duplicate(ob)\n\n\tmode = 'INTERSECT'\n\tmesh_selection(obj_copy, 'SELECT')\n\tmesh_selection(ob, 'DESELECT')\n\tsce.objects.active = ob\n\tmodifier_boolean(ob, obj_copy, mode)\n\n\tmode = 'DIFFERENCE'\n\tmesh_selection(ob_copy, 'SELECT')\n\tmesh_selection(obj, 'DESELECT')\n\tsce.objects.active = obj\n\tmodifier_boolean(obj, ob_copy, mode)\n\tobj.select = True\n","sub_path":"scripts/addons_extern/blender-addon-booltron-master/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"26439748","text":"import numpy as np\n\nclass StackingFeature(object):\n\tdef __init__(self):\n\t\tpass\n\n\tdef concatArray(self,train,test,train_joint_array,test_joint_array):\n\t\ttemp_train_jointed_array = train_joint_array.reshape(1,len(train_joint_array))\n\t\ttemp_test_jointed_array = test_joint_array.reshape(1,len(test_joint_array))\n\t\tresult_train = np.hstack((train,temp_train_jointed_array))\n\t\tresult_test = np.hstack((test,temp_test_jointed_array))\n\t\treturn result_train,result_test\n\n\tdef mean(self,train,test):\n\t\ttrain_joint_array = np.mean(train,axis=1)\n\t\ttest_joint_array = np.mean(test,axis=1)\n\t\treturn self.concatArray(train, test, train_joint_array, test_joint_array)\n\n\tdef std(self,train,test):\n\t\ttrain_joint_array = np.std(train,axis=1)\n\t\ttest_joint_array = np.std(test,axis=1)\n\t\treturn self.concatArray(train, test, train_joint_array, test_joint_array)\n\n\tdef convert(self,train,test,mean_flag=True,std_flag=True,tsne_flag=True):\n\t\ttrain_array = train\n\t\ttest_array = test\n\t\t\n\t\tif mean_flag:\n\t\t\ttrain_array,test_array = self.mean(train, test)\n\n\t\tif std_flag:\n\t\t\ttrain_array,test_array = self.std(train, test)\n\n\t\treturn train_array,test_array","sub_path":"sample/StackingFeature.py","file_name":"StackingFeature.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"102598010","text":"# coding=utf-8\n# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport logging\n\nfrom pants.backend.jvm.targets.exportable_jvm_library import ExportableJvmLibrary\nfrom pants.base.payload import Payload\nfrom pants.base.payload_field import PrimitiveField\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass JavaWireLibrary(ExportableJvmLibrary):\n \"\"\"Generates a stub Java library from protobuf IDL files.\"\"\"\n\n def __init__(self,\n payload=None,\n service_writer=None,\n service_writer_options=None,\n roots=None,\n registry_class=None,\n enum_options=None,\n no_options=None,\n **kwargs):\n \"\"\"\n :param string service_writer: the name of the class to pass as the --service_writer option to\n the Wire compiler.\n :param list service_writer_options: A list of options to pass to the service writer\n :param list roots: passed through to the --roots option of the Wire compiler\n :param string registry_class: fully qualified class name of RegistryClass to create. If in\n doubt, specify com.squareup.wire.SimpleServiceWriter\n :param list enum_options: list of enums to pass to as the --enum-enum_options option, # optional\n :param boolean no_options: boolean that determines if --no_options flag is passed\n \"\"\"\n payload = payload or Payload()\n payload.add_fields({\n 'service_writer': PrimitiveField(service_writer or None),\n 'service_writer_options': PrimitiveField(service_writer_options or []),\n 'roots': PrimitiveField(roots or []),\n 'registry_class': PrimitiveField(registry_class or None),\n 'enum_options': PrimitiveField(enum_options or []),\n 'no_options': PrimitiveField(no_options or False),\n })\n\n if service_writer_options:\n logger.warn('The service_writer_options flag is ignored.')\n\n super(JavaWireLibrary, self).__init__(payload=payload, **kwargs)\n self.add_labels('codegen')\n","sub_path":"src/python/pants/backend/codegen/targets/java_wire_library.py","file_name":"java_wire_library.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"530491596","text":"import os\r\nimport logging\r\nimport wrapt\r\n\r\n@wrapt.decorator\r\ndef log_args(wrapped, instance, args, kwargs):\r\n log = logging.getLogger() # root logger\r\n log.setLevel(logging.INFO)\r\n return wrapped(*args, **kwargs)\r\n\r\nclass Apihelper:\r\n\r\n def __init__(self):\r\n\r\n with open(os.getcwd() + \"\\\\data.txt\", mode='w') as f:\r\n # print('header')\r\n f.write(\"Name\")\r\n f.write(\",\")\r\n f.write(\"Height\")\r\n f.write(\",\")\r\n f.write(\"Gender\")\r\n f.write(\"\\n\")\r\n\r\n @log_args\r\n def star_wars_characters(self, page_nr):\r\n page_character_list=[]\r\n for character in page_nr['results']:\r\n name_hgt_gen = character['name']+','+character['height']+','+character['gender']\r\n page_character_list.append(name_hgt_gen)\r\n\r\n return (page_character_list)\r\n\r\n\r\n def append_to_file(self, filepath,name,height,gender):\r\n with open(filepath, \"a\")as f:\r\n f.write(\",\".join([name,height,gender]))\r\n f.write(\"\\n\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"apihelper.py","file_name":"apihelper.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"69995191","text":"import os\nfrom setuptools import find_packages, setup\n\nhere = os.path.dirname(os.path.abspath(__file__))\n\nversion_ns = {}\nwith open(os.path.join(here, 'sml_sync', 'version.py')) as f:\n exec(f.read(), {}, version_ns)\n\nsetup(\n name='sml_sync',\n version=version_ns['version'],\n description='SherlockML file synchronizer',\n author='ASI Data Science',\n packages=find_packages(),\n entry_points={\n 'console_scripts': ['sml-sync=sml_sync:run']\n },\n install_requires=[\n 'sml',\n 'daiquiri',\n 'paramiko',\n 'watchdog',\n 'semantic_version',\n 'prompt_toolkit>=2.0'\n ],\n classifiers=[\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"25330452","text":"import sib_api_v3_sdk as sib_sdk\nfrom sib_api_v3_sdk.rest import ApiException\n\nfrom .deps import smtp\n\n\ndef send_new_message_email(from_email, from_name, to_email, to_name, link):\n mail = sib_sdk.SendSmtpEmail(\n sender={\"name\": \"Studio Rubik\", \"email\": \"noreply@studio-rubik.dev\"},\n to=[{\"name\": to_name, \"email\": to_email}],\n template_id=2,\n params={\"from_name\": from_name, \"to_name\": to_name, \"link\": link},\n )\n try:\n smtp.send_transac_email(mail)\n except ApiException as e:\n print(e)\n","sub_path":"api/src/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"534485940","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import Model\ntfkl = tf.keras.layers\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot') # Change the style of the plots to a nicer theme\nimport random\nimport time\n# From IPython.display we import clear_output() in order to be able to clear the print statements after each epoch\nfrom IPython.display import clear_output\nfrom tqdm import tqdm, tqdm_notebook # Show progress bar\nimport gensim\n\n\n\ndef timing(start):\n \"\"\"Function to time the duration of each epoch\n\n Arguments:\n start (time): Start time needed for computation \n \n Returns:\n time_per_training_step (time): Rounded time in seconds \n \"\"\"\n now = time.time()\n time_per_training_step = now - start\n return round(time_per_training_step, 4)\n\n\n\ndef discriminator_loss(real_tweet, fake_tweet):\n \"\"\"Calculate the Wasserstein loss for the discriminator but swapping the sign in order to apply gradient descent.\n\n Arguments:\n real_tweet (tensor): Linear output from discriminator\n fake_tweet (tensor): Linear output from discriminator\n\n Returns:\n x (tensor): Wasserstein Loss\n \"\"\"\n\n loss_real = - tf.reduce_mean(real_tweet)\n loss_fake = tf.reduce_mean(fake_tweet)\n\n return loss_real + loss_fake\n\n\n\ndef generator_loss(fake_tweet):\n \"\"\"Calculate the Wasserstein loss for the generator.\n\n Arguments:\n fake_tweet (tensor): Linear output from discriminator\n\n Returns:\n x (tensor): Wasserstein Loss\n \"\"\"\n\n loss_fake = - tf.reduce_mean(fake_tweet)\n\n return loss_fake\n \n \n \n@tf.function() \ndef gradient_penalty(discriminator, real_tweet, generated_tweet):\n \"\"\"Visualize performance of the Generator by feeding predefined random noise vectors through it.\n \n Arguments:\n discriminator (Discriminator): Discriminator class instance\n real_tweet (tensor): Real tweet embedding from Encoder\n generated_tweet (tensor): Fake tweet embedding from Generator\n\n Return: \n penalty (): Gradient penalty that will be added to discriminator loss\n \"\"\" \n\n # Due to the stacked approach we chose for the Autoencoder we had to alter the gradient\n # penalty by interpolating twice and calculating an average penalty. \n alpha = tf.random.uniform(shape=[real_tweet.shape[0], 1], minval=0, maxval=1)\n\n interpolate = alpha*real_tweet + (1-alpha)*generated_tweet\n\n output = discriminator(interpolate)\n\n gradients = tf.gradients(output, interpolate)\n\n gradient_norm = tf.sqrt(tf.reduce_sum(tf.square(gradients)))\n\n penalty = 10*tf.reduce_mean((gradient_norm-1.)**2)\n\n return penalty\n\n\n\ndef visualize_GAN(autoencoder, word2vec_model, fixed_input, random_input, train_losses_generator, train_losses_discriminator, num_epochs):\n \"\"\"Visualize performance of the Generator by feeding predefined random noise vectors through it.\n \n Arguments:\n autoencoder (AutoEncoder): AutoEncoder class instance\n word2vec_model (gensim.models.word2vec.Word2Vec): Pretrained word2vec model\n fixed_input (tensor): List containing predefined random vectors\n random_input (tensor): List containing predefined random vectors\n train_losses_generator (list): List containing the generator losses\n train_losses_discriminator (list): List containing the discriminator losses \n num_epochs (int): Current Epoch\n \"\"\" \n\n print()\n print(f\"From Fixed Vector: {' '.join([word2vec_model.wv.index2word[i.numpy()[0] -1] for i in autoencoder.Decoder.inference_mode(states=fixed_input[0], training=False) if i.numpy()[0] != 0])}\")\n print(f\"From Fixed Vector: {' '.join([word2vec_model.wv.index2word[i.numpy()[0] -1] for i in autoencoder.Decoder.inference_mode(states=fixed_input[1], training=False) if i.numpy()[0] != 0])}\")\n print()\n print(f\"From Random Vector: {' '.join([word2vec_model.wv.index2word[i.numpy()[0] -1] for i in autoencoder.Decoder.inference_mode(states=random_input[0], training=False) if i.numpy()[0] != 0])}\")\n print(f\"From Random Vector: {' '.join([word2vec_model.wv.index2word[i.numpy()[0] -1] for i in autoencoder.Decoder.inference_mode(states=random_input[1], training=False) if i.numpy()[0] != 0])}\")\n\n plt.style.use('ggplot')\n \n fig1, ax1 = plt.subplots(nrows=1, ncols=1, figsize = (10, 6))\n ax1.plot(train_losses_generator, label='Generator')\n ax1.plot(train_losses_discriminator, label='Discriminator')\n ax1.set(ylabel='Loss', xlabel='Epochs', title=f'Average loss over {num_epochs} epochs')\n if num_epochs>25 and num_epochs<=50:\n ax1.set_ylim([-10,100])\n if num_epochs>50:\n ax1.set_ylim([-5,25])\n ax1.legend()\n \n plt.show()\n\n\n\n@tf.function() \ndef train_step_GAN(generator, discriminator, train_data, optimizer_generator, optimizer_discriminator, train_generator):\n \"\"\"Perform a training step for a given GAN Network by\n 1. Generating random noise for the Generator\n 2. Feeding the noise through the Generator to create fake tweet embeddings for the Discriminator \n 3. Feeding the fake and real tweet embeddings through the Discriminator \n 4. Calculating the loss for the Disriminator and the Generator \n 5. Performing Backpropagation and Updating the trainable variables with the calculated gradients, using the specified optimizers\n\n Arguments:\n generator (Generator): Generator class instance\n discriminator (Discriminator): Discriminator class instance\n word2vec_model (gensim.models.word2vec.Word2Vec): Pretrained word2vec model\n train_data (tf.data.Dataset): Real tweet embedding from Encoder\n optimizer_generator (tf.keras.optimizers): function from keras defining the to be applied optimizer during training\n optimizer_discriminator (tf.keras.optimizers): function from keras defining the to be applied optimizer during training\n train_generator (bool): Whether to update the generator or not\n \n Returns:\n loss_from_generator, loss_from_discriminator (Tupel): Tupel containing the loss of both the Generator and Discriminator\n \"\"\"\n\n # 1.\n noise = tf.random.normal([train_data.shape[0], 100])\n\n # Two Gradient Tapes, one for the Discriminator and one for the Generator \n with tf.GradientTape() as generator_tape, tf.GradientTape() as discriminator_tape:\n # 2.\n generated_tweet = generator(noise)\n\n # 3.\n real = discriminator(train_data)\n fake = discriminator(generated_tweet)\n\n # 4.\n loss_from_generator = generator_loss(fake)\n # Add gradient penalty to enforce lipschitz continuity\n loss_from_discriminator = discriminator_loss(real, fake) + gradient_penalty(discriminator=discriminator, real_tweet=train_data, generated_tweet=generated_tweet)\n\n # 5.\n gradients_from_discriminator = discriminator_tape.gradient(loss_from_discriminator, discriminator.trainable_variables)\n optimizer_discriminator.apply_gradients(zip(gradients_from_discriminator, discriminator.trainable_variables))\n\n # We update the generator once for ten updates to the discriminator\n if train_generator:\n gradients_from_generator = generator_tape.gradient(loss_from_generator, generator.trainable_variables)\n optimizer_generator.apply_gradients(zip(gradients_from_generator, generator.trainable_variables))\n\n return loss_from_generator, loss_from_discriminator\n \n\n\ndef train_GAN(generator, discriminator, autoencoder, word2vec_model: gensim.models.word2vec.Word2Vec, train_dataset_GAN: tf.data.Dataset, num_epochs: int=150, running_average_factor: float=0.95, learning_rate: float=0.0001):\n \"\"\"Function that implements the training algorithm for a GAN.\n\n Arguments:\n generator (Generator): Generator class instance\n discriminator (Discriminator): Discriminator class instance\n autoencoder (AutoEncoder): AutoEncoder class instance\n word2vec_model (gensim.models.word2vec.Word2Vec): Pretrained word2vec model\n train_dataset_GAN (tf.data.Dataset): Dataset to perform training on\n num_epochs (int): Defines the amount of epochs the training is performed\n learning_rate (float): To be used learning rate, per default set to 0.001\n running_average (float): To be used factor for computing the running average of the trainings loss, per default set to 0.95\n \"\"\" \n\n tf.keras.backend.clear_session()\n\n # Two optimizers one for the generator and of for the discriminator\n optimizer_generator=tf.keras.optimizers.Adam(learning_rate=learning_rate)\n optimizer_discriminator=tf.keras.optimizers.Adam(learning_rate=learning_rate)\n\n # Fixed, random vectors for visualization\n fixed_generator_input_1 = tf.random.normal([1, 100])\n fixed_generator_input_2 = tf.random.normal([1, 100])\n\n # Initialize lists for later visualization.\n train_losses_generator = []\n train_losses_discriminator = []\n\n train_generator = False\n\n for epoch in range(num_epochs):\n\n start = time.time()\n running_average_gen = 0\n running_average_disc = 0\n\n with tqdm(total=519) as pbar:\n for batch_no, input in enumerate(train_dataset_GAN):\n\n # Boolean used to train the discriminator 10x more often than the generator\n train_generator = False\n if batch_no % 10 == 0:\n train_generator = True\n\n gen_loss, disc_loss = train_step_GAN(generator, discriminator, train_data=input, optimizer_generator=optimizer_generator, optimizer_discriminator=optimizer_discriminator, train_generator=train_generator)\n running_average_gen = running_average_factor * running_average_gen + (1 - running_average_factor) * gen_loss\n running_average_disc = running_average_factor * running_average_disc + (1 - running_average_factor) * disc_loss\n pbar.update(1)\n\n train_losses_generator.append(float(running_average_gen))\n train_losses_discriminator.append(float(running_average_disc))\n\n clear_output()\n print(f'Epoch: {epoch+1}') \n print()\n print(f'This epoch took {timing(start)} seconds')\n print()\n print(f'The current generator loss: {round(train_losses_generator[-1], 4)}')\n print()\n print(f'The current discriminator loss: {round(train_losses_discriminator[-1], 4)}')\n print()\n\n # Random vectors for visualization that are sampled each epoch\n random_generator_input_1 = tf.random.normal([1, 100])\n random_generator_input_2 = tf.random.normal([1, 100])\n \n visualize_GAN(autoencoder=autoencoder,\n word2vec_model=word2vec_model,\n fixed_input=(generator(fixed_generator_input_1), generator(fixed_generator_input_2)), \n random_input=(generator(random_generator_input_1), generator(random_generator_input_2)), \n train_losses_generator=train_losses_generator, \n train_losses_discriminator=train_losses_discriminator, \n num_epochs=epoch+1)","sub_path":"Modules/standard_latextgan_training.py","file_name":"standard_latextgan_training.py","file_ext":"py","file_size_in_byte":10625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"239513501","text":"import os, requests\nimport datetime\n\nfrom toaster.helper import get_config_path, load_default_id, format_time\n\nwebhook_url = load_default_id()\n\ndef toast(method):\n if webhook_url == '':\n raise UnboundLocalError('You have not configured your Telegram ID. Run set_incoming_webhook() first.')\n\n def insert_toast(*args, **kw):\n try:\n start = datetime.datetime.now()\n result = method(*args, **kw)\n end = datetime.datetime.now()\n diff = end - start\n # Create Message\n msg = \"🍞 Ding! Function {} has completed!\\nStart Time: {}\\nEnd Time: {}\\nTime Taken: {}\".format(\n method.__name__, start.strftime(\"%Y-%m-%d %H:%M:%S\"), end.strftime(\"%Y-%m-%d %H:%M:%S\"), format_time(diff)\n )\n data = {\n 'text':msg\n }\n\n res = requests.post(url = WEBHOOK_URL, data = data, headers={'Content-Type': \"application/json\"})\n return result\n\n except Exception as e:\n msg = '⚠️ An error has occurred with function {} \\nError message: {}'.format(method.__name__, str(e))\n print('Error caught:',e)\n data = {\n 'text':msg\n }\n # Send Telegram Message\n res = requests.post(url = WEBHOOK_URL, data = data, headers={'Content-Type': \"application/json\"})\n\n return insert_toast\n\ndef set_incoming_webhook(webhook_url):\n webhook_url = str(webhook_url)\n config_path = get_config_path()\n with open(config_path,\"w\") as config_file:\n config_file.write(webhook_url)\n global WEBHOOK_URL\n WEBHOOK_URL = webhook_url\n","sub_path":"toaster/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"72896712","text":"# coding=utf-8\nimport unittest\nfrom models.AcousticModel import AcousticModel\nimport util.dataprocessor as dataprocessor\nimport tensorflow as tf\n\n\nclass TestAcousticModel(unittest.TestCase):\n model = None\n sess = None\n\n @classmethod\n def setUpClass(cls):\n with tf.Session() as sess:\n cls.model = AcousticModel(sess, 2, 50, 0.8, 0.5, 3, 0.0003, 0.33, 5, 1800, 600, 120, False,\n forward_only=False, tensorboard_dir=None, tb_run_name=None,\n timeline_enabled=False, language='english')\n\n def test_get_str_labels_and_reverse(self):\n text = \"What ! I'm not looking for... I'll do it...\"\n cleaned_str = dataprocessor.DataProcessor.clean_label(text)\n numeric_label = self.model.get_str_labels(cleaned_str)\n new_text = self.model.get_labels_str(numeric_label)\n self.assertEqual(new_text, cleaned_str)\n\n def test_3_chars_token_in_str_end(self):\n text = \"it'll\"\n cleaned_str = dataprocessor.DataProcessor.clean_label(text)\n numeric_label = self.model.get_str_labels(cleaned_str)\n self.assertEqual(numeric_label, [60, 45, 1, 79])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"models/test_AcousticModel.py","file_name":"test_AcousticModel.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"470752609","text":"#!../.venv3/bin/python\n# coding: utf-8\n\n# # List of users report\n\n# ### Imports\n\n# In[1]:\n\n\nimport sys\nimport psycopg2\nimport pandas as pd\nfrom datetime import datetime\n\n\n# ### Initial setup\n\n# In[2]:\n\n\nconn = psycopg2.connect(host='localhost',\n port='5432',\n user='mffais',\n password='pass',\n database='bigquery')\n\n\n# ### Fetch users\n\n# In[3]:\n\n\ncursor = conn.cursor()\nquery = '''\n SELECT user_pseudo_id AS user_id,\n geo ->> 'country' AS country,\n traffic_source ->> 'source' AS source,\n traffic_source ->> 'name' AS campaign,\n DATE(user_first_touch_timestamp) AS install_date\n FROM events\n WHERE geo ->> 'country' <> ''\n AND user_first_touch_timestamp IS NOT NULL\n GROUP BY user_pseudo_id, country, source, campaign, user_first_touch_timestamp\n ORDER BY country\n'''\ncursor.execute(query)\nlist_of_users = pd.read_sql(query, con=conn)\ncursor.close()\nlist_of_users.rename(columns={ 'user_id':'User ID',\n 'country':'Country',\n 'source':'Source',\n 'campaign':'Campaign',\n 'install_date':'Install date'}, inplace=True)\nlist_of_users.head(20)\n\n\n# ### Calculate uninstalls\n\n# In[4]:\n\n\ncursor = conn.cursor()\nquery = '''\n SELECT user_pseudo_id AS user_id,\n DATE(event_timestamp) AS uninstall_date\n FROM events\n WHERE event_name='app_remove'\n'''\ncursor.execute(query)\nuninstall = pd.read_sql(query, con=conn)\ncursor.close()\nuninstall.rename(columns={ 'user_id':'User ID', 'uninstall_date':'Uninstall date' }, inplace=True)\nuninstall.head(20)\n\n\n# ### Calculate days installed\n\n# In[5]:\n\n\nlist_of_users = pd.merge(list_of_users, uninstall, on='User ID', how='left')\nlist_of_users.head(20)\n\n\n# In[6]:\n\n\ntoday = datetime.date( datetime.now() )\n\ndef cleanNaN(row):\n uninstall_date = row['Uninstall date']\n if str( uninstall_date ) == 'nan':\n return ''\n return uninstall_date\n\ndef date_diff(row):\n install_date = row['Install date']\n if str( row['Uninstall date'] ) == '':\n used_date = today\n else:\n used_date = row['Uninstall date']\n days_installed = int( int( ( used_date - install_date ).total_seconds() ) / 24 / 60 / 60 + 1 )\n return days_installed\n\nlist_of_users['Uninstall date'] = list_of_users.apply(cleanNaN, axis=1)\nlist_of_users['Days installed'] = list_of_users.apply(date_diff, axis=1)\n\nlist_of_users.head(20)\n\n\n# ### Calculate sessions since installed\n\n# In[7]:\n\n\ncursor = conn.cursor()\nquery = '''\n SELECT user_pseudo_id AS user_id,\n COUNT(*) AS sessions\n FROM (\n SELECT event_date,\n user_pseudo_id\n FROM events\n GROUP BY event_date, user_pseudo_id\n ) AS users_by_day\n GROUP BY user_id\n'''\ncursor.execute(query)\nsessions = pd.read_sql(query, con=conn)\nsessions.rename(columns={ 'user_id':'User ID', 'sessions':'Sessions' }, inplace=True)\nsessions.head(20)\n\n\n# In[8]:\n\n\nlist_of_users = pd.merge(list_of_users, sessions, on='User ID', how='left')\nlist_of_users.head(20)\n\n\n# ### Output HTTP Header\n\n# In[9]:\n\n\nprint('Content-type: text/csv')\nprint('Content-Disposition: attachment; filename=\"list_of_users.csv\"')\nprint()\n\n\n# ### Output variables\n\n# In[10]:\n\n\nprint('# Title: List of users report')\n\n\n# ### Ouput result\n\n# In[11]:\n\n\nstr = list_of_users.to_csv(index=False)\nprint(str.encode('ascii','xmlcharrefreplace').decode('utf-8'))\n\n\n# ### Release resources\n\n# In[12]:\n\n\nconn.close()\n\n","sub_path":"cgi/report_list_of_users.py","file_name":"report_list_of_users.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"197308366","text":"n = int(input())\r\ncoins = input().split()\r\ncoins = list(map(int,coins))\r\ncoins.sort(reverse=True)\r\nsum = sum(coins)\r\nm_sum = 0\r\nc = 0\r\nfor i in range(n):\r\n if m_sum <= sum - m_sum :\r\n m_sum +=coins[i]\r\n c+=1\r\n else:\r\n break\r\nprint(c)","sub_path":"python/160A.py","file_name":"160A.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57784317","text":"# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\nfrom datetime import datetime\nimport os.path\n\nimport tensorflow as tf\nimport numpy as np\n\nhe_init = tf.contrib.layers.variance_scaling_initializer()\nlearning_rate=0.01\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"datasets/\")\nX_train1 = mnist.train.images\ny_train1 = mnist.train.labels\n\nX_train2 = mnist.validation.images\ny_train2 = mnist.validation.labels\n\nX_test = mnist.test.images\ny_test = mnist.test.labels\n\n\ndef leaky_relu(alpha=0.01):\n def parametrized_leaky_relu(z, name=None):\n return tf.maximum(alpha * z, z, name=name)\n\n return parametrized_leaky_relu\n\ndef log_dir(prefix=\"\"):\n now = datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n root_logdir = \"tf_logs\"\n if prefix:\n prefix += \"-\"\n name = prefix + \"run-\" + now\n return \"{}/{}/\".format(root_logdir, name)\n\ndef build_dnn(inputs, scope_name, training, n_hidden_layers=5, n_neurons=100, dropout_rate=0, initializer = he_init, activation =leaky_relu()):\n with tf.variable_scope(scope_name, \"dnn\"):\n\n inputs = tf.layers.dropout(inputs, dropout_rate, training=training)\n\n for i in range(n_hidden_layers):\n inputs = tf.layers.dense(inputs, n_neurons, kernel_initializer = initializer, name=\"layer\"+str(i))\n inputs = activation(inputs)\n inputs = tf.layers.dropout(inputs, dropout_rate, training=training)\n\n return inputs\n\ndef build_graph(n_inputs, n_outputs):\n X = tf.placeholder(tf.float32, shape=(None, 2, n_inputs), name=\"X\")\n y = tf.placeholder(tf.int32, shape=(None), name=\"y\")\n\n X1, X2 = tf.unstack(X, axis=1)\n\n training = tf.placeholder_with_default(False, shape=(), name='training')\n\n dnn_outputs1 = build_dnn(X1, \"DNN_A\", training)\n dnn_outputs2 = build_dnn(X2, \"DNN_B\", training)\n\n dnn_outputs = tf.concat([dnn_outputs1, dnn_outputs2], axis =1)\n hidden_layer = tf.layers.dense(dnn_outputs, units=10, activation=leaky_relu(), kernel_initializer = he_init, name=\"hidden_summary\")\n logits = tf.layers.dense(hidden_layer, units=1, kernel_initializer=he_init, name=\"logits\")\n\n y_proba = tf.nn.sigmoid(logits)\n y_pred = tf.cast(tf.greater_equal(logits, 0), tf.int32)\n\n y_as_float = tf.cast(y, tf.float32)\n xentropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_as_float, logits=logits)\n loss = tf.reduce_mean(xentropy)\n\n optimiser = tf.train.AdamOptimizer(learning_rate=learning_rate)\n training_op = optimiser.minimize(loss)\n\n y_pred_correct = tf.equal(y_pred, y)\n accuracy = tf.reduce_mean(tf.cast(y_pred_correct, tf.float32))\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n\n return X, y, loss, training_op, accuracy ,init, saver\n\ndef generate_batch(images, labels, batch_size):\n size1 = batch_size // 2\n size2 = batch_size - size1\n if size1 != size2 and np.random.rand() > 0.5:\n size1, size2 = size2, size1\n X = []\n y = []\n while len(X) < size1:\n rnd_idx1, rnd_idx2 = np.random.randint(0, len(images), 2)\n if rnd_idx1 != rnd_idx2 and labels[rnd_idx1] == labels[rnd_idx2]:\n X.append(np.array([images[rnd_idx1], images[rnd_idx2]]))\n y.append([1])\n while len(X) < batch_size:\n rnd_idx1, rnd_idx2 = np.random.randint(0, len(images), 2)\n if labels[rnd_idx1] != labels[rnd_idx2]:\n X.append(np.array([images[rnd_idx1], images[rnd_idx2]]))\n y.append([0])\n rnd_indices = np.random.permutation(batch_size)\n return np.array(X)[rnd_indices], np.array(y)[rnd_indices]\n\n\ndef train():\n X_test1, y_test1 = generate_batch(X_test, y_test, batch_size=len(X_test))\n\n X, y, loss, training_op, accuracy, init, saver = build_graph(28*28, 1)\n\n n_epochs = 300\n batch_size = 500\n\n with tf.Session() as sess:\n init.run()\n for epoch in range(n_epochs):\n for iteration in range(mnist.train.num_examples // batch_size):\n X_batch, y_batch = generate_batch(X_train1, y_train1, batch_size)\n loss_val, _ = sess.run([loss, training_op], feed_dict={X: X_batch, y: y_batch})\n print(epoch, \"Train loss:\", loss_val)\n if epoch % 5 == 0:\n acc_test = accuracy.eval(feed_dict={X: X_test1, y: y_test1})\n print(epoch, \"Test accuracy:\", acc_test)\n\n save_path = saver.save(sess, \"./my_digit_comparison_model.ckpt\")\n\ntrain()\n\n","sub_path":"11_10_transfer_learning.py","file_name":"11_10_transfer_learning.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"42815532","text":"'''\nExercício Python 70: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o\nusuário vai continuar ou não. No final, mostre:\n\nA) qual é o total gasto na compra.\n\nB) quantos produtos custam mais de R$1000.\n\nC) qual é o nome do produto mais barato.\n'''\n\nqtdprodutos = count = total = produtocaro = countprodutocaro = menor =0\nnomeprodutocaro = ' '\nnomeprodutobarato = ' '\nop = 's'\nwhile True:\n produto = str(input(\"Digite o nome do produto: \"))\n preco = float(input(\"Digite o preço do produto: R$\"))\n total += preco\n count += 1\n\n if preco > 1000:\n countprodutocaro += 1\n if preco < produtocaro:\n nomeprodutocaro = produto\n produtocaro = preco\n if count == 1 or preco < menor:\n menor = preco\n nomeprodutobarato = produto\n\n op = ' '\n while op not in 'SN':\n op = str(input(\"Deseja continuar a comprar? [S/N]\")).upper().strip()[0]\n\n if op not in 'S':\n break\n\nprint('{:-^40}'.format('Fim da compra'))\nprint(f'O Valor gasto na compra foi: R$ {total :.2f}')\nprint(f'Quantidade de produto que custam mais que R$1000,00 é: {countprodutocaro}')\nprint(f'Produto mais caro foi {nomeprodutocaro} e o preço foi R${produtocaro :.2f}')\nprint(f'O produto mais barato foi {nomeprodutobarato} e o preço dele R${menor :.2f}')","sub_path":"Arquivos Exercicios/Exercicios/Ex070.py","file_name":"Ex070.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"621252898","text":"import math\nfrom geompreds import orient2d, incircle\nfrom opendrivepy.point import Point\n\na = 6378137\nb = 6356752.3142\nf = (a - b) / a\ne_sq = f * (2-f)\n\ndef point_distance(pointa, pointb):\n return math.sqrt((pointa.x - pointb.x) ** 2 + (pointa.y - pointb.y) ** 2)\n\ndef line(p1, p2):\n A = (p1.y - p2.y)\n B = (p2.x - p1.x)\n C = (p1.x*p2.y - p2.x*p1.y)\n return A, B, -C\n\ndef intersection(L1, L2):\n D = L1[0] * L2[1] - L1[1] * L2[0]\n Dx = L1[2] * L2[1] - L1[1] * L2[2]\n Dy = L1[0] * L2[2] - L1[2] * L2[0]\n if D != 0:\n x = Dx / D\n y = Dy / D\n return Point(x,y)\n else:\n return False\n\ndef line_cross(line1, line2):\n L1 = line(line1[0], line1[1])\n L2 = line(line2[0], line2[1])\n\n R = intersection(L1, L2)\n if R:\n return R\n else:\n x1 = line1[0].x\n x2 = line1[1].x\n x3 = line2[0].x\n x4 = line2[1].x\n\n y1 = line1[0].y\n y2 = line1[1].y\n y3 = line2[0].y\n y4 = line2[1].y\n return Point((x1+x2+x3+x4)/4,(y1+y2+y3+y4)/4)\n\ndef orient_node(nodea, nodeb, nodec):\n return orient2d((nodea.x, nodea.y), (nodeb.x, nodeb.y), (nodec.x, nodec.y))\n\n\ndef find_diagonal(nodes):\n # find the diagonal node of node[0]\n if orient_node(nodes[0], nodes[1], nodes[2]) * orient_node(nodes[3], nodes[1], nodes[2]) < 0:\n return 3\n elif orient_node(nodes[0], nodes[1], nodes[3]) * orient_node(nodes[2], nodes[1], nodes[3]) < 0:\n return 2\n else:\n return 1\n\n\n\n\ndef enu_to_ecef(xEast, yNorth, zUp, lat0, lon0, h0):\n lamb = math.radians(lat0)\n phi = math.radians(lon0)\n s = math.sin(lamb)\n N = a / math.sqrt(1 - e_sq * s * s)\n\n sin_lambda = math.sin(lamb)\n cos_lambda = math.cos(lamb)\n sin_phi = math.sin(phi)\n cos_phi = math.cos(phi)\n\n x0 = (h0 + N) * cos_lambda * cos_phi\n y0 = (h0 + N) * cos_lambda * sin_phi\n z0 = (h0 + (1 - e_sq) * N) * sin_lambda\n\n t = cos_lambda * zUp - sin_lambda * yNorth\n\n zd = sin_lambda * zUp + cos_lambda * yNorth\n xd = cos_phi * t - sin_phi * xEast \n yd = sin_phi * t + cos_phi * xEast\n\n x = xd + x0 \n y = yd + y0 \n z = zd + z0 \n\n return x, y, z\n\ndef ecef_to_geodetic(x, y, z):\n # Convert from ECEF cartesian coordinates to \n # latitude, longitude and height. WGS-84\n x2 = x ** 2 \n y2 = y ** 2 \n z2 = z ** 2 \n\n a = 6378137.0000 # earth radius in meters\n b = 6356752.3142 # earth semiminor in meters \n e = math.sqrt (1-(b/a)**2) \n b2 = b*b \n e2 = e ** 2 \n ep = e*(a/b) \n r = math.sqrt(x2+y2) \n r2 = r*r \n E2 = a ** 2 - b ** 2 \n F = 54*b2*z2 \n G = r2 + (1-e2)*z2 - e2*E2 \n c = (e2*e2*F*r2)/(G*G*G) \n s = ( 1 + c + math.sqrt(c*c + 2*c) )**(1/3) \n P = F / (3 * (s+1/s+1)**2 * G*G) \n Q = math.sqrt(1+2*e2*e2*P) \n ro = -(P*e2*r)/(1+Q) + math.sqrt((a*a/2)*(1+1/Q) - (P*(1-e2)*z2)/(Q*(1+Q)) - P*r2/2) \n tmp = (r - e2*ro) ** 2 \n U = math.sqrt( tmp + z2 ) \n V = math.sqrt( tmp + (1-e2)*z2 ) \n zo = (b2*z)/(a*V) \n\n height = U*( 1 - b2/(a*V) ) \n \n lat = math.atan( (z + ep*ep*zo)/r ) \n\n temp = math.atan(y/x) \n if x >=0 : \n long = temp \n elif (x < 0) & (y >= 0):\n long = math.pi + temp \n else :\n long = temp - math.pi \n\n lat0 = lat/(math.pi/180) \n lon0 = long/(math.pi/180) \n h0 = height \n\n return lat0, lon0, h0\n\ndef enu_to_geodetic(xEast, yNorth, zUp, lat_ref, lon_ref, h_ref):\n\n x,y,z = enu_to_ecef(xEast, yNorth, zUp, lat_ref, lon_ref, h_ref)\n\n return ecef_to_geodetic(x,y,z)","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"332486176","text":"# -*- coding: utf-8 -*-\nfrom datetime import date\nimport logging\n\nfrom odoo import api\n\n_logger = logging.getLogger(__name__)\n\n\ndef get_sequence(cr, uid, code):\n env = api.Environment(cr, uid, {})\n ir_sequence = env['ir.sequence']\n sequence_name = code\n sequence_value = ir_sequence.get(sequence_name)\n if not sequence_value:\n args = {\n 'name': sequence_name,\n 'code': sequence_name,\n 'implementation': 'no_gap',\n 'padding': 4,\n }\n ir_sequence.create(args)\n sequence_value = ir_sequence.get(sequence_name)\n return sequence_name + sequence_value\n","sub_path":"izi_pos_revenue_allocation/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"623199399","text":"import yaml\nimport os\n\n\nclass Config:\n\n _instance = None\n\n __slots__ = [\n '_path',\n \n 'DEBUG',\n 'PORT',\n 'HOST',\n\n 'DBHOST',\n 'DBPORT',\n 'DBNAME',\n 'DBUSER',\n 'DBPASSWORD',\n ]\n\n def __init__(self, yaml_file: str):\n self._path = yaml_file\n self._read()\n\n def __call__(cls, *args, **kwargs):\n if cls is not cls._instance:\n instance = super().__call__(*args, **kwargs)\n cls._instance = instance\n return cls._instance\n \n def to_dict(self):\n return {field.lower(): getattr(self, field) for field in self.__slots__}\n\n def _read(self):\n if not os.path.exists(self._path):\n raise AttributeError(f\"Config yaml doesnot exist: {self._path}\")\n\n with open(self._path) as config_file:\n config_content = config_file.read()\n config_yaml = yaml.safe_load(config_content)\n\n for k, v in config_yaml.items():\n k = k.upper()\n if k in self.__slots__:\n setattr(self, k, v)","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"631945665","text":"# -*- coding: utf-8 -*-\n\"\"\"Module providing faculty member assignment functionality\"\"\"\nfrom Acquisition import aq_inner\nfrom plone import api\nfrom plone.protect.utils import addTokenToUrl\nfrom Products.Five.browser import BrowserView\nfrom zope.lifecycleevent import modified\nfrom zope.publisher.interfaces.browser import IPublishTraverse\nfrom zope.interface import implementer\n\nfrom hph.faculty.facultymember import IFacultyMember\n\nfrom hph.publications import MessageFactory as _\n\n\nclass FacultyMemberAssignment(BrowserView):\n \"\"\" Manage publication faculty member assignments \"\"\"\n\n def __call__(self):\n return self.render()\n\n @property\n def traverse_subpath(self):\n return self.subpath\n\n def publishTraverse(self, request, name):\n if not hasattr(self, 'subpath'):\n self.subpath = []\n self.subpath.append(name)\n return self\n\n def render(self):\n return self.index()\n\n def generate_protected_url(self, url):\n return addTokenToUrl(url)\n\n def selectable_faculty_members(self):\n faculty_members = api.content.find(\n context=api.portal.get(),\n object_provides=IFacultyMember,\n review_state='published',\n sort_on='lastname'\n )\n return faculty_members\n\n def has_active_assignment(self, uuid):\n context = aq_inner(self.context)\n context_uid = api.content.get_uuid(obj=context)\n faculty_member = api.content.get(UID=uuid)\n assignments = getattr(faculty_member, 'associatedPublications', None)\n if assignments and context_uid in assignments:\n return True\n return False\n\n\n@implementer(IPublishTraverse)\nclass FacultyMemberAssignmentFactory(BrowserView):\n \"\"\" Factory view to set and delete assignments \"\"\"\n\n def __call__(self):\n return self.render()\n\n @property\n def traverse_subpath(self):\n return self.subpath\n\n def publishTraverse(self, request, name):\n if not hasattr(self, 'subpath'):\n self.subpath = []\n self.subpath.append(name)\n return self\n\n def render(self):\n context = aq_inner(self.context)\n faculty_member_uid = self.traverse_subpath[0]\n action = self.traverse_subpath[1]\n faculty_member = api.content.get(UID=faculty_member_uid)\n assignments = getattr(faculty_member, 'associatedPublications', None)\n if assignments is None:\n assignments = list()\n uuid = api.content.get_uuid(obj=context)\n if action == 'remove':\n if uuid in assignments:\n assignments.remove(uuid)\n else:\n assignments.append(uuid)\n # Store updated assignment list\n setattr(faculty_member, 'associatedPublications', assignments)\n modified(faculty_member)\n faculty_member.reindexObject(idxs='modified')\n next_url = '{0}/@@faculty-member-assignment?updated=true'.format(\n context.absolute_url())\n api.portal.show_message(\n message=_(u\"Faculty member successfully assigned\"),\n request=self.request)\n return self.request.response.redirect(next_url)\n","sub_path":"src/hph.publications/hph/publications/browser/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"86321070","text":"import asyncio\nfrom typing import Optional\n\nfrom loguru import logger\nfrom nonebot import CommandGroup, CommandSession\nfrom nonebot import permission as perm\nfrom nonebot.command import call_command\nfrom nonebot.command.argfilter import controllers, extractors, validators\n\n\nfrom app.services.subscribe.school_notice import get_rss_list\nfrom app.services.subscribe.score import get_score_subscribes\nfrom app.services.subscribe.wrapper import handle_message, get_subs, handle_rm\n\n__plugin_name__ = \"订阅\"\n__plugin_short_description__ = \"订阅 通知/成绩/考试 等,命令: subscribe\"\n__plugin_usage__ = r\"\"\"添加订阅:\n - 订阅\n - 添加订阅\n - 新建订阅\n - subscribe\n 然后会提示输入序号,你也可以直接在后面加上序号,如:\n - 订阅 1\n查看订阅:\n - 查看订阅\n - 订阅列表\n - subscribe show\n\n移除订阅:\n - 移除订阅\n - 取消订阅\n - 停止订阅\n - 删除订阅\n - subscribe rm\n 然后会提示输入序号,你也可以直接在后面加上序号,如:\n - 移除订阅 1\n - 移除订阅 all\n\"\"\".strip()\n\ncg = CommandGroup(\n \"subscribe\", permission=perm.PRIVATE | perm.GROUP_ADMIN | perm.DISCUSS\n)\n\n\ndef get_subscribe_lst() -> str:\n msg = \"\"\n msg += get_rss_list().strip() + \"\\n\"\n msg += get_score_subscribes().strip() + \"\\n\"\n\n return msg\n\n\n@cg.command(\n \"subscribe\", aliases=[\"subscribe\", \"订阅\", \"添加订阅\", \"新增订阅\", \"新建订阅\"], only_to_me=False\n)\nasync def subscribe(session: CommandSession):\n message = session.get(\n \"message\",\n prompt=f\"你想订阅什么内容呢?(请输入序号,也可输入 `取消、不` 等语句取消):\\n{get_subscribe_lst()}\",\n arg_filters=[\n controllers.handle_cancellation(session),\n str.lstrip,\n validators.not_empty(\"请输入有效内容哦~\"),\n ],\n )\n await handle_message(session.event, message)\n\n\n@subscribe.args_parser\nasync def _(session: CommandSession):\n if session.is_first_run:\n if session.current_arg:\n session.state[\"message\"] = session.current_arg\n return\n\n\n@cg.command(\"show\", aliases=[\"查看订阅\", \"我的订阅\", \"订阅列表\"], only_to_me=False)\nasync def _(session: CommandSession):\n subs = session.state.get(\"subs\") or await get_subs(session.event)\n\n if not subs:\n session.finish(\"你还没有订阅任何内容哦\")\n\n for k, v in subs.items():\n await session.send(format_subscription(k, v))\n await asyncio.sleep(0.05)\n session.finish(f\"以上是所有的 {len(subs)} 个订阅\")\n\n\n@cg.command(\"rm\", aliases=[\"取消订阅\", \"停止订阅\", \"关闭订阅\", \"删除订阅\", \"移除订阅\"], only_to_me=False)\nasync def unsubscribe(session: CommandSession):\n subs = await get_subs(session.event)\n logger.info(f\"subs: {subs}\",)\n index: Optional[str] = session.state.get(\"index\")\n logger.info(f\"session.state: {session.state}\",)\n if index is None:\n session.state[\"subs\"] = subs\n await call_command(\n session.bot,\n session.ctx,\n (\"subscribe\", \"show\"),\n args={\"subs\": subs},\n disable_interaction=True,\n )\n\n if not subs:\n session.finish()\n\n index = session.get(\n \"index\",\n prompt=\"你想取消哪一个订阅呢?(请发送序号,或者 `取消`)\",\n arg_filters=[\n extractors.extract_text,\n controllers.handle_cancellation(session),\n ],\n )\n\n if index:\n await handle_rm(session.event, index)\n\n\n@unsubscribe.args_parser\nasync def _(session: CommandSession):\n if session.is_first_run:\n if session.current_arg:\n session.state[\"index\"] = session.current_arg\n\n\ndef format_subscription(k, v) -> str:\n return f\"序号:{k}\\n\" f\"订阅名称:\" f\"{v}\\n\"\n","sub_path":"app/bot/subscribe/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"487394129","text":"'''\nCreated on Jan 15, 2014\n\n@author: tariktosun\n'''\nfrom Embedding.SmoresModule import SmoresModule\nfrom Embedding.SmoresDesign import SmoresDesign\nimport copy\n\n\ndef setUpGrasperWalker(test_object):\n '''\n Sets up fixtures for the grasper and walker designs in the test class given n \n as arg.\n '''\n ''' Grasper design: '''\n g_modules = [SmoresModule('1', 0, []),\n SmoresModule('2', 1, [3,2]),\n SmoresModule('3', 1, [3,2]),\n SmoresModule('4', 1, [3,0,2]),\n SmoresModule('5', 1, [3,2]),\n SmoresModule('6', 1, [3,2]),\n SmoresModule('7', 1, [3,0,2]),\n ]\n g_small = copy.deepcopy( g_modules )\n g_smaller = copy.deepcopy( g_modules )\n # The -1's here are to make the code more readable when compared with the\n # original drawings of the designs I made (where modules numbers start at 1\n # rather than 0)\n g_modules[1-1].add_child_module( 2, g_modules[5-1] )\n g_modules[1-1].add_child_module( 3, g_modules[2-1] )\n g_modules[2-1].add_child_module( 0, g_modules[3-1] )\n g_modules[3-1].add_child_module( 0, g_modules[4-1] )\n g_modules[5-1].add_child_module( 0, g_modules[6-1] )\n g_modules[6-1].add_child_module( 0, g_modules[7-1] )\n grasper = SmoresDesign( g_modules[1-1], g_modules )\n test_object.grasper = grasper\n \n # now make a smaller version:\n g_small[1-1].add_child_module( 2, g_small[5-1] )\n #g_small[1-1].add_child_module( 3, g_small[2-1] )\n g_small[5-1].nodes[0].active = False #need to hack this for it to work.\n #grasper_small = SmoresDesign( g_small[1-1], [g_small[1-1], g_small[2-1], g_small[5-1]])\n grasper_small = SmoresDesign( g_small[1-1], [g_small[1-1], g_small[5-1]])\n test_object.grasper_small = grasper_small\n \n # ...and an even smaller version:\n grasper_smaller = SmoresDesign( g_smaller[1-1], [g_smaller[1-1]] )\n test_object.grasper_smaller = grasper_smaller\n \n ''' Walker design: '''\n w_modules = [SmoresModule('1', 1, [2,3,0] ),\n SmoresModule('2', 1, [2,3] ),\n SmoresModule('3', 1, [2,3] ),\n \n SmoresModule('4', 3, [2] ),\n \n SmoresModule('5', 0, [2,3] ),\n SmoresModule('6', 0, [2,3] ),\n SmoresModule('7', 0, [2,3] ),\n \n SmoresModule('8', 0, [2,3] ),\n SmoresModule('9', 0, [2,3] ),\n SmoresModule('10', 0, [2,3] ),\n \n SmoresModule('11', 2, [3] ),\n \n SmoresModule('12', 1, [2,3] ),\n SmoresModule('13', 1, [2,3] ),\n SmoresModule('14', 1, [2,3,0] ),\n ]\n \n w_small = copy.deepcopy( w_modules )\n w_smaller = copy.deepcopy( w_modules )\n \n # First I am connecting the bottom legs (which will be the grasper)\n # right leg:\n w_modules[11-1].add_child_module( 0, w_modules[12-1] )\n w_modules[12-1].add_child_module( 0, w_modules[13-1] )\n w_modules[13-1].add_child_module( 0, w_modules[14-1] )\n # left leg:\n w_modules[11-1].add_child_module( 1, w_modules[10-1] )\n w_modules[10-1].add_child_module( 1, w_modules[9-1] )\n w_modules[9-1].add_child_module( 1, w_modules[8-1] )\n # now for the top two legs:\n #right leg:\n w_modules[11-1].add_child_module( 2, w_modules[4-1] )\n # Note that above is allowed because 11 is the root module.\n w_modules[4-1].add_child_module( 0, w_modules[3-1] )\n w_modules[3-1].add_child_module( 0, w_modules[2-1] )\n w_modules[2-1].add_child_module( 0, w_modules[1-1] )\n # left leg:\n w_modules[4-1].add_child_module( 1, w_modules[5-1] )\n w_modules[5-1].add_child_module( 1, w_modules[6-1] )\n w_modules[6-1].add_child_module( 1, w_modules[7-1] )\n # Node 11 is the root.\n walker = SmoresDesign( w_modules[11-1], w_modules ) \n test_object.walker= walker\n \n # now make a small version:\n w_small[11-1].add_child_module( 0, w_small[12-1] )\n w_small[11-1].add_child_module( 1, w_small[10-1] )\n walker_small = SmoresDesign( w_small[11-1], [w_small[11-1], w_small[12-1], w_small[10-1]])\n test_object.walker_small = walker_small\n \n # ... and an even smaller version:\n w_smaller[11-1].add_child_module( 1, w_smaller[10-1] )\n walker_smaller = SmoresDesign( w_smaller[11-1], [ w_smaller[11-1], w_smaller[10-1] ])\n test_object.walker_smaller = walker_smaller\n \n \n \n \n \n ","sub_path":"Design_Merging/test/fixtures_grasper_walker.py","file_name":"fixtures_grasper_walker.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"123137840","text":"# Name: Hieu Le - htl5683@truman.edu\n# Name: Anh Nguyen - adn6627@truman.edu\n\n# File eightPuzzle.py\n# Implements the Eight Puzzle problem for state space search\n\n# Node Expansions\n# Problem | BFS | A*(tiles) | A*(dist) | Steps\n# A 7 3 3 2\n# B 69 8 7 6\n# C 183 18 9 8\n# D 807 40 24 10\n# E 831 40 24 10\n# F 1557 95 18 12\n# G 6005 269 46 15\n# H 46690 3616 183 20\n\n\nfrom informedSearch import *\n\n\nclass EightPuzzleState(InformedProblemState):\n \"\"\"\n Each state in the Eight Puzzle problem is characterized by a 2-dimensional\n array representing the puzzle grid. The grid is filled with numbers from 0\n to 9 with the blank square denoted with a 0 value.\n \"\"\"\n\n def __init__(self, grid):\n self.grid = grid\n if grid is not None:\n # Extract the position of the blank square from the current grid.\n self.blank_row, self.blank_col = self.find_position(0)\n\n def __str__(self):\n \"\"\"Returns a string representation of this state\"\"\"\n rep = \"\"\n for row in range(len(self.grid)):\n for col in range(len(self.grid[row])):\n rep += '%s ' % self.grid[row][col]\n rep += '\\n'\n return rep\n\n def illegal(self):\n \"\"\"Tests whether this state is illegal\"\"\"\n return self.grid is None\n\n def equals(self, state):\n \"\"\"\n Determines whether the state instance and the given state are equal\n \"\"\"\n return self.grid == state.grid\n\n # Each operator corresponds to shifting the blank square in each of the four\n # possible directions. This induces changes in the row and column number of\n # the blank square.\n OPERATORS = [[-1, 0], [0, 1], [1, 0], [0, -1]]\n\n def operatorNames(self):\n \"\"\"\n Returns a list of operator names in the same order as the applyOperators\n method. The returned name corresponds to the action applied on the\n numbered square that is moved into the blank square.\n \"\"\"\n return ['Slide Down', 'Slide Left', 'Slide Up', 'Slide Right']\n\n def applyOperators(self):\n \"\"\"\n Returns a list of possible successors to the current state, some of\n which maybe illegal.\n \"\"\"\n next_states = []\n\n for operator in self.OPERATORS:\n next_board = [row[:] for row in self.grid]\n # Compute the new position of the blank square.\n next_blank_row = self.blank_row + operator[0]\n next_blank_col = self.blank_col + operator[1]\n\n if (0 <= next_blank_row < len(next_board)\n and 0 <= next_blank_col < len(next_board[next_blank_row])):\n # Exchange two adjacent squares.\n next_board[self.blank_row][self.blank_col], \\\n next_board[next_blank_row][next_blank_col] = \\\n next_board[next_blank_row][next_blank_col], \\\n next_board[self.blank_row][self.blank_col]\n next_states.append(EightPuzzleState(next_board))\n else:\n next_states.append(EightPuzzleState(None))\n\n return next_states\n\n def heuristic(self, goal):\n \"\"\"Returns the estimated cost of reaching the goal from this state.\"\"\"\n # return 0\n # return self.get_hamming_distance(goal)\n return self.get_manhattan_distance(goal)\n\n def get_hamming_distance(self, other):\n \"\"\"\n Computes the Hamming distance from this state to other, i.e. the number\n of out-of-place squares\n \"\"\"\n hamming_distance = 0\n for value in range(1, 9):\n actual_row, actual_col = self.find_position(value)\n expected_row, expected_col = other.find_position(value)\n if not (actual_row == expected_row and actual_col == expected_col):\n hamming_distance += 1\n return hamming_distance\n\n def get_manhattan_distance(self, other):\n \"\"\"Computes the Manhattan distance from this state to other\"\"\"\n manhattan_distance = 0\n\n for value in range(1, 9):\n actual_row, actual_col = self.find_position(value)\n expected_row, expected_col = other.find_position(value)\n manhattan_distance += abs(expected_row - actual_row)\n manhattan_distance += abs(expected_col - actual_col)\n\n return manhattan_distance\n\n def find_position(self, value):\n \"\"\"Returns row and column number of the cell containing value\"\"\"\n for row in range(len(self.grid)):\n for col in range(len(self.grid[row])):\n if self.grid[row][col] == value:\n return row, col\n return -1, -1\n\n\ngoalState = EightPuzzleState(\n [[1, 2, 3],\n [8, 0, 4],\n [7, 6, 5]])\n\ninitialStateBoards = [\n [[1, 3, 0],\n [8, 2, 4],\n [7, 6, 5]],\n\n [[1, 3, 4],\n [8, 6, 2],\n [0, 7, 5]],\n\n [[0, 1, 3],\n [4, 2, 5],\n [8, 7, 6]],\n\n [[7, 1, 2],\n [8, 0, 3],\n [6, 5, 4]],\n\n [[8, 1, 2],\n [7, 0, 4],\n [6, 5, 3]],\n\n [[2, 6, 3],\n [4, 0, 5],\n [1, 8, 7]],\n\n [[7, 3, 4],\n [6, 1, 5],\n [8, 0, 2]],\n\n [[7, 4, 5],\n [6, 0, 3],\n [8, 1, 2]]\n]\n\nInformedSearch(EightPuzzleState(initialStateBoards[0]), goalState)\n","sub_path":"heuristic-search/eightPuzzle.py","file_name":"eightPuzzle.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"21221688","text":"import copy\nimport re\nfrom bitcoinx import TxInputContext, InterpreterLimits, MinerPolicy, Script, pack_byte\n\nimport scryptlib.utils as utils\nfrom scryptlib.compiler_wrapper import ABIEntityType\nfrom scryptlib.types import Struct, Int, Bool\n\n\nclass ABICoder:\n\n def __init__(self, abi, aliases):\n self.abi = abi\n self.aliases = aliases\n\n def encode_constructor_call(self, contract, hex_script, *args):\n abi_constructor = self.abi_constructor()\n c_params = self.__get_abi_params(abi_constructor)\n\n if len(args) != len(c_params):\n raise Exception('Wrong number of arguments passed to constructor. ' \\\n 'Expected {}, but got {}.'.format(len(c_params), len(args)))\n\n _c_params = []\n _args = []\n for idx, param in enumerate(c_params):\n arg = args[idx]\n arg = utils.primitives_to_scrypt_types(arg)\n resolved_type = utils.resolve_type(param['type'], self.aliases)\n if utils.is_array_type(resolved_type):\n elem_type, array_sizes = utils.factorize_array_type_str(resolved_type)\n\n if not utils.check_array(arg, elem_type, array_sizes):\n raise Exception('Constructors parameter with index {} should be of type \"{}\".'.format(idx, resolved_type))\n\n flattened_arr = utils.flatten_array(arg, param['name'], resolved_type)\n for obj in flattened_arr:\n _c_params.append({ 'name': obj['name'], 'type': obj['type'] })\n _args.append(obj['value'])\n elif utils.is_struct_type(resolved_type):\n if arg.final_type != resolved_type:\n raise Exception('Constructors parameter with index {} should be Struct object of type \"{}\". ' \\\n 'Got struct of type \"{}\" instead.'.format(idx, param['type'], arg.type_str))\n\n flattened_struct = utils.flatten_struct(arg, param['name'])\n for obj in flattened_struct:\n _c_params.append({ 'name': obj['name'], 'type': obj['type'] })\n _args.append(obj['value'])\n else:\n _c_params.append(param)\n _args.append(arg)\n\n finalized_hex_script = hex_script\n for idx, param in enumerate(_c_params):\n if not '<{}>'.format(param['name']) in hex_script:\n raise Exception('Missing \"{}\" contract constructor parameter in passed args.'.format(param['name']))\n param_regex = re.compile(escape_str_for_regex('<{}>'.format(param['name'])))\n finalized_hex_script = re.sub(param_regex, self.encode_param(_args[idx], param), finalized_hex_script)\n\n # Replace inline assembly variable placeholders in locking script with the actual arguments.\n # TODO: Check if each value if instance of ScryptType\n if contract.inline_asm_vars:\n for key, val in contract.inline_asm_vars.items():\n param_regex = re.compile(escape_str_for_regex('<{}>'.format(key)))\n finalized_hex_script = re.sub(param_regex, val.hex, finalized_hex_script)\n\n locking_script = Script.from_hex(finalized_hex_script)\n return FunctionCall('constructor', args, contract, locking_script=locking_script)\n\n def encode_pub_function_call(self, contract, name, *args):\n for entity in self.abi:\n if entity['name'] == name:\n if len(entity['params']) != len(args):\n raise Exception('Wrong number of arguments passed to function call \"{}\", ' \\\n 'expected {}, but got {}.'.format(name, len(entity['params']), len(args)))\n hex_script = self.encode_params(args, entity['params'])\n if len(self.abi) > 2 and 'index' in entity:\n pub_func_index = entity['index']\n hex_script += '{}'.format(Int(pub_func_index).hex) # TODO\n unlocking_script = Script.from_hex(hex_script) \n return FunctionCall(name, args, contract, unlocking_script=unlocking_script)\n\n def encode_params(self, args, param_entities):\n res = []\n for idx, arg in enumerate(args):\n res.append(self.encode_param(arg, param_entities[idx]))\n return ''.join(res)\n\n def encode_param(self, arg, param_entity):\n resolved_type = utils.resolve_type(param_entity['type'], self.aliases)\n if utils.is_array_type(resolved_type):\n if isinstance(arg, list):\n return self.encode_param_array(arg, param_entity)\n else:\n scrypt_type = arg.type_str\n raise Exception('Expected parameter \"{}\" as \"{}\", but got \"{}\".'.format(param_entity['name'],\n resolved_type, scrypt_type))\n if utils.is_struct_type(resolved_type):\n if isinstance(arg, Struct):\n if resolved_type != arg.final_type:\n raise Exception('Expected struct of type \"{}\", but got struct of type \"{}\".'.format(\n param_entity['name'], resolved_type, arg.final_type))\n else:\n scrypt_type = arg.type_str\n raise Exception('Expected parameter \"{}\" as struct of type \"{}\", but got \"{}\".'.format(\n param_entity['name'], resolved_type, scrypt_type))\n\n scrypt_type = utils.type_of_arg(arg)\n if resolved_type != scrypt_type:\n raise Exception('Wrong argument type. Expected \"{}\", but got \"{}\".'.format(param_entity['type'], \n scrypt_type))\n\n if isinstance(arg, bool):\n arg = Bool(arg)\n elif isinstance(arg, int):\n arg = Int(arg)\n\n return arg.hex\n\n def encode_param_array(self, args, param_entity):\n if len(args) == 0:\n raise Exception('Empty arrays not allowed.')\n \n first_arg_type = type(args[0])\n for arg in args:\n if type(arg) != first_arg_type:\n raise Exception('Array arguments are not of same type.')\n\n resolved_type = utils.resolve_type(param_entity['type'], self.aliases)\n elem_type, array_sizes = utils.factorize_array_type_str(resolved_type)\n\n if not utils.check_array(args, elem_type, array_sizes):\n raise Exception('Array check failed for \"{}\".'.format(param_entity['type']))\n\n res_buff = []\n for arg in utils.flatten_array(args, param_entity['name'], resolved_type):\n res_buff.append(self.encode_param(arg['value'], { 'name': arg['name'], 'type': arg['type'] }))\n return ''.join(res_buff)\n\n def abi_constructor(self):\n constructor_abi = None\n for entity in self.abi:\n if entity['type'] == ABIEntityType.CONSTRUCTOR.value:\n constructor_abi = entity\n break\n return constructor_abi\n\n @staticmethod\n def __get_abi_params(abi_entity):\n return abi_entity.get('params', [])\n\n\nclass FunctionCall:\n\n def __init__(self, method_name, params, contract, locking_script=None, unlocking_script=None):\n if not (locking_script or unlocking_script):\n raise Exception('Binding locking_script and unlocking_script can\\'t both be empty.')\n\n self.contract = contract\n self.locking_script = locking_script\n self.unlocking_script = unlocking_script\n self.method_name = method_name\n\n self.args = []\n for entity in self.contract.abi:\n if (method_name == 'constructor' and entity['type'] == 'constructor') or \\\n ('name' in entity and entity['name'] == method_name):\n for idx, param in enumerate(entity['params']):\n self.args.append({\n 'name': param['name'],\n 'type': param['type'],\n 'value': params[idx]\n })\n\n def verify(self, tx_input_context=utils.create_dummy_input_context(), interpreter_limits=None,\n use_contract_script_pair=True):\n '''\n Evaluate lock and unlock script pair using the passed TxInputContext object.\n Additionally an InterpreterLimits object can be passed to limit the scope of verification.\n\n If not TxInputContext object is passed, a dummy context object gets created and used in the verification \n process.\n\n If use_contract_script_pair is set to True (defaults to True), then evaluate the scriptPubKey and scriptSig\n pair of the contract object, instead of the ones passed via the TxInputContext object.\n '''\n assert isinstance(tx_input_context, TxInputContext)\n\n if not self.unlocking_script:\n raise Exception('Cannot verify function \"{}\". \\\n FunctionCall object is missing unlocking_script property.'.format(self.method_name))\n\n if not interpreter_limits:\n policies = [\n # A fairly restrictive policy\n MinerPolicy(100_000, 64, 20_000, 1_000, 16),\n # A loose policy\n MinerPolicy(10_000_000, 256, 10_000_000, 32_000, 256)\n ]\n interpreter_limits = InterpreterLimits(policies[1], is_genesis_enabled=True, is_consensus=True, base_flags='consensus')\n\n # Make a deep copy of the passed TxInputContext object, because it may be modified from here on.\n tx_input_context = copy.deepcopy(tx_input_context)\n\n if use_contract_script_pair:\n self.update_input_context_scripts(tx_input_context)\n\n return tx_input_context.verify_input(interpreter_limits)\n\n def update_input_context_scripts(self, tx_input_context):\n '''\n Updates the unlocking input script (scriptSig) and the matching UTXOs locking script (scriptPubKey)\n to the unlocking script of this FunctionCall object and the locking script of the contract object it belongs to.\n\n Notice, that the function doesn't create a copy of the context object, but rather just modifies it.\n '''\n # Set unlock script for passed input context.\n input_index = tx_input_context.input_index\n tx_input_context.tx.inputs[input_index].script_sig = self.unlocking_script\n\n # Set utxo script to verify sciptSig against.\n tx_input_context.utxo.script_pubkey = self.contract.locking_script\n\n return tx_input_context\n\n @property\n def script(self):\n '''\n The function calls scriptSig.\n '''\n return self.unlocking_script\n\n\ndef escape_str_for_regex(string):\n special_chars = {'-', '\\\\', '^', '$', '*', '+', '?', '.', '(', ')', '|', '[', ']', '{', '}'}\n res_buff = []\n for c in string:\n if c in special_chars:\n res_buff.append('\\\\')\n res_buff.append(c)\n return ''.join(res_buff)\n","sub_path":"scryptlib/abi.py","file_name":"abi.py","file_ext":"py","file_size_in_byte":10923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"394425421","text":"\"\"\"\n==============\nDisease States\n==============\n\nThis module contains tools to manage standard disease states.\n\n\"\"\"\nfrom typing import Callable, Dict, List\n\nimport numpy as np\nimport pandas as pd\nfrom vivarium.framework.population import PopulationView, SimulantData\nfrom vivarium.framework.state_machine import State, Transient, Transition\nfrom vivarium.framework.values import list_combiner, union_post_processor\n\nfrom vivarium_public_health.disease.transition import (\n ProportionTransition,\n RateTransition,\n TransitionString,\n)\nfrom vivarium_public_health.utilities import is_non_zero\n\n\nclass BaseDiseaseState(State):\n def __init__(\n self, cause, name_prefix=\"\", side_effect_function=None, cause_type=\"cause\", **kwargs\n ):\n super().__init__(name_prefix + cause, **kwargs) # becomes state_id\n self.cause_type = cause_type\n self.cause = cause\n\n self.side_effect_function = side_effect_function\n if self.side_effect_function is not None:\n self._sub_components.append(side_effect_function)\n\n self.event_time_column = self.state_id + \"_event_time\"\n self.event_count_column = self.state_id + \"_event_count\"\n\n @property\n def columns_created(self):\n return [self.event_time_column, self.event_count_column]\n\n # noinspection PyAttributeOutsideInit\n def setup(self, builder):\n \"\"\"Performs this component's simulation setup.\n\n Parameters\n ----------\n builder : `engine.Builder`\n Interface to several simulation tools.\n \"\"\"\n super().setup(builder)\n\n self.clock = builder.time.clock()\n\n view_columns = self.columns_created + [self._model, \"alive\"]\n self.population_view = builder.population.get_view(view_columns)\n builder.population.initializes_simulants(\n self.on_initialize_simulants,\n creates_columns=self.columns_created,\n requires_columns=[self._model],\n )\n\n def on_initialize_simulants(self, pop_data: SimulantData) -> None:\n \"\"\"Adds this state's columns to the simulation state table.\"\"\"\n for transition in self.transition_set:\n if transition.start_active:\n transition.set_active(pop_data.index)\n\n pop_update = self.get_initial_event_times(pop_data)\n self.population_view.update(pop_update)\n\n def get_initial_event_times(self, pop_data: SimulantData) -> pd.DataFrame:\n return pd.DataFrame(\n {self.event_time_column: pd.NaT, self.event_count_column: 0}, index=pop_data.index\n )\n\n def _transition_side_effect(self, index, event_time):\n \"\"\"Updates the simulation state and triggers any side effects associated with this state.\n\n Parameters\n ----------\n index\n An iterable of integer labels for the simulants.\n event_time : pandas.Timestamp\n The time at which this transition occurs.\n\n \"\"\"\n pop = self.population_view.get(index)\n pop[self.event_time_column] = event_time\n pop[self.event_count_column] += 1\n self.population_view.update(pop)\n\n if self.side_effect_function is not None:\n self.side_effect_function(index, event_time)\n\n ##################\n # Public methods #\n ##################\n\n def get_transition_names(self) -> List[str]:\n transitions = []\n for trans in self.transition_set.transitions:\n _, _, init_state, _, end_state = trans.name.split(\".\")\n transitions.append(TransitionString(f\"{init_state}_TO_{end_state}\"))\n return transitions\n\n def add_transition(\n self,\n output: State,\n source_data_type: str = None,\n get_data_functions: Dict[str, Callable] = None,\n **kwargs,\n ) -> Transition:\n \"\"\"Builds a transition from this state to the given state.\n\n Parameters\n ----------\n output\n The end state after the transition.\n\n source_data_type\n the type of transition: either 'rate' or 'proportion'\n\n get_data_functions\n map from transition type to the function to pull that transition's data\n\n Returns\n -------\n vivarium.framework.state_machine.Transition\n The created transition object.\n\n \"\"\"\n transition_map = {\"rate\": RateTransition, \"proportion\": ProportionTransition}\n\n if not source_data_type:\n return super().add_transition(output, **kwargs)\n elif source_data_type in transition_map:\n t = transition_map[source_data_type](self, output, get_data_functions, **kwargs)\n self.transition_set.append(t)\n return t\n else:\n raise ValueError(f\"Unrecognized data type {source_data_type}\")\n\n\nclass SusceptibleState(BaseDiseaseState):\n def __init__(self, cause, *args, **kwargs):\n super().__init__(cause, *args, name_prefix=\"susceptible_to_\", **kwargs)\n\n def add_transition(\n self,\n output: State,\n source_data_type: str = None,\n get_data_functions: Dict[str, Callable] = None,\n **kwargs,\n ) -> Transition:\n if source_data_type == \"rate\":\n if get_data_functions is None:\n get_data_functions = {\n \"incidence_rate\": lambda builder, cause: builder.data.load(\n f\"{self.cause_type}.{cause}.incidence_rate\"\n )\n }\n elif \"incidence_rate\" not in get_data_functions:\n raise ValueError(\"You must supply an incidence rate function.\")\n elif source_data_type == \"proportion\":\n if \"proportion\" not in get_data_functions:\n raise ValueError(\"You must supply a proportion function.\")\n\n return super().add_transition(output, source_data_type, get_data_functions, **kwargs)\n\n\nclass RecoveredState(BaseDiseaseState):\n def __init__(self, cause, *args, **kwargs):\n super().__init__(cause, *args, name_prefix=\"recovered_from_\", **kwargs)\n\n def add_transition(\n self,\n output: State,\n source_data_type: str = None,\n get_data_functions: Dict[str, Callable] = None,\n **kwargs,\n ) -> Transition:\n if source_data_type == \"rate\":\n if get_data_functions is None:\n get_data_functions = {\n \"incidence_rate\": lambda builder, cause: builder.data.load(\n f\"{self.cause_type}.{cause}.incidence_rate\"\n )\n }\n elif \"incidence_rate\" not in get_data_functions:\n raise ValueError(\"You must supply an incidence rate function.\")\n elif source_data_type == \"proportion\":\n if \"proportion\" not in get_data_functions:\n raise ValueError(\"You must supply a proportion function.\")\n\n return super().add_transition(output, source_data_type, get_data_functions, **kwargs)\n\n\nclass DiseaseState(BaseDiseaseState):\n \"\"\"State representing a disease in a state machine model.\"\"\"\n\n def __init__(self, cause, get_data_functions=None, cleanup_function=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n cause : str\n The name of this state.\n disability_weight : pandas.DataFrame or float, optional\n The amount of disability associated with this state.\n prevalence_data : pandas.DataFrame, optional\n The baseline occurrence of this state in a population.\n dwell_time : pandas.DataFrame or pandas.Timedelta, optional\n The minimum time a simulant exists in this state.\n event_time_column : str, optional\n The name of a column to track the last time this state was entered.\n event_count_column : str, optional\n The name of a column to track the number of times this state was entered.\n side_effect_function : callable, optional\n A function to be called when this state is entered.\n \"\"\"\n super().__init__(cause, **kwargs)\n\n self.excess_mortality_rate_pipeline_name = f\"{self.state_id}.excess_mortality_rate\"\n self.excess_mortality_rate_paf_pipeline_name = (\n f\"{self.excess_mortality_rate_pipeline_name}.paf\"\n )\n\n self._get_data_functions = (\n get_data_functions if get_data_functions is not None else {}\n )\n self.cleanup_function = cleanup_function\n\n if self.cause is None and not set(self._get_data_functions.keys()).issuperset(\n [\"disability_weight\", \"dwell_time\", \"prevalence\"]\n ):\n raise ValueError(\n \"If you do not provide a cause, you must supply\"\n \"custom data gathering functions for disability_weight, prevalence, and dwell_time.\"\n )\n\n # noinspection PyAttributeOutsideInit\n def setup(self, builder):\n \"\"\"Performs this component's simulation setup.\n\n Parameters\n ----------\n builder : `engine.Builder`\n Interface to several simulation tools.\n \"\"\"\n super().setup(builder)\n\n prevalence_data = self.load_prevalence_data(builder)\n self.prevalence = builder.lookup.build_table(\n prevalence_data, key_columns=[\"sex\"], parameter_columns=[\"age\", \"year\"]\n )\n\n birth_prevalence_data = self.load_birth_prevalence_data(builder)\n self.birth_prevalence = builder.lookup.build_table(\n birth_prevalence_data, key_columns=[\"sex\"], parameter_columns=[\"year\"]\n )\n\n dwell_time_data = self.load_dwell_time_data(builder)\n self.dwell_time = builder.value.register_value_producer(\n f\"{self.state_id}.dwell_time\",\n source=builder.lookup.build_table(\n dwell_time_data, key_columns=[\"sex\"], parameter_columns=[\"age\", \"year\"]\n ),\n requires_columns=[\"age\", \"sex\"],\n )\n\n disability_weight_data = self.load_disability_weight_data(builder)\n self.has_disability = is_non_zero(disability_weight_data)\n self.base_disability_weight = builder.lookup.build_table(\n disability_weight_data, key_columns=[\"sex\"], parameter_columns=[\"age\", \"year\"]\n )\n self.disability_weight = builder.value.register_value_producer(\n f\"{self.state_id}.disability_weight\",\n source=self.compute_disability_weight,\n requires_columns=[\"age\", \"sex\", \"alive\", self._model],\n )\n builder.value.register_value_modifier(\n \"disability_weight\", modifier=self.disability_weight\n )\n\n excess_mortality_data = self.load_excess_mortality_rate_data(builder)\n self.has_excess_mortality = is_non_zero(excess_mortality_data)\n self.base_excess_mortality_rate = builder.lookup.build_table(\n excess_mortality_data, key_columns=[\"sex\"], parameter_columns=[\"age\", \"year\"]\n )\n self.excess_mortality_rate = builder.value.register_rate_producer(\n self.excess_mortality_rate_pipeline_name,\n source=self.compute_excess_mortality_rate,\n requires_columns=[\"age\", \"sex\", \"alive\", self._model],\n requires_values=[self.excess_mortality_rate_paf_pipeline_name],\n )\n paf = builder.lookup.build_table(0)\n self.joint_paf = builder.value.register_value_producer(\n self.excess_mortality_rate_paf_pipeline_name,\n source=lambda idx: [paf(idx)],\n preferred_combiner=list_combiner,\n preferred_post_processor=union_post_processor,\n )\n builder.value.register_value_modifier(\n \"mortality_rate\",\n modifier=self.adjust_mortality_rate,\n requires_values=[self.excess_mortality_rate_pipeline_name],\n )\n\n self.randomness_prevalence = builder.randomness.get_stream(\n f\"{self.state_id}_prevalent_cases\"\n )\n\n def get_initial_event_times(self, pop_data: SimulantData) -> pd.DataFrame:\n pop_update = super().get_initial_event_times(pop_data)\n\n simulants_with_condition = self.population_view.subview([self._model]).get(\n pop_data.index, query=f'{self._model}==\"{self.state_id}\"'\n )\n if not simulants_with_condition.empty:\n infected_at = self._assign_event_time_for_prevalent_cases(\n simulants_with_condition,\n self.clock(),\n self.randomness_prevalence.get_draw,\n self.dwell_time,\n )\n pop_update.loc[infected_at.index, self.event_time_column] = infected_at\n\n return pop_update\n\n def compute_disability_weight(self, index):\n \"\"\"Gets the disability weight associated with this state.\n\n Parameters\n ----------\n index\n An iterable of integer labels for the simulants.\n\n Returns\n -------\n `pandas.Series`\n An iterable of disability weights indexed by the provided `index`.\n \"\"\"\n disability_weight = pd.Series(0, index=index)\n with_condition = self.with_condition(index)\n disability_weight.loc[with_condition] = self.base_disability_weight(with_condition)\n return disability_weight\n\n def compute_excess_mortality_rate(self, index):\n excess_mortality_rate = pd.Series(0, index=index)\n with_condition = self.with_condition(index)\n base_excess_mort = self.base_excess_mortality_rate(with_condition)\n joint_mediated_paf = self.joint_paf(with_condition)\n excess_mortality_rate.loc[with_condition] = base_excess_mort * (\n 1 - joint_mediated_paf.values\n )\n return excess_mortality_rate\n\n def adjust_mortality_rate(self, index, rates_df):\n \"\"\"Modifies the baseline mortality rate for a simulant if they are in this state.\n\n Parameters\n ----------\n index\n An iterable of integer labels for the simulants.\n rates_df : `pandas.DataFrame`\n\n \"\"\"\n rate = self.excess_mortality_rate(index, skip_post_processor=True)\n rates_df[self.state_id] = rate\n return rates_df\n\n def with_condition(self, index):\n pop = self.population_view.subview([\"alive\", self._model]).get(index)\n with_condition = pop.loc[\n (pop[self._model] == self.state_id) & (pop[\"alive\"] == \"alive\")\n ].index\n return with_condition\n\n @staticmethod\n def _assign_event_time_for_prevalent_cases(\n infected, current_time, randomness_func, dwell_time_func\n ):\n dwell_time = dwell_time_func(infected.index)\n infected_at = dwell_time * randomness_func(infected.index)\n infected_at = current_time - pd.to_timedelta(infected_at, unit=\"D\")\n return infected_at\n\n def add_transition(\n self,\n output: State,\n source_data_type: str = None,\n get_data_functions: Dict[str, Callable] = None,\n **kwargs,\n ) -> Transition:\n if source_data_type == \"rate\":\n if get_data_functions is None:\n get_data_functions = {\n \"remission_rate\": lambda builder, cause: builder.data.load(\n f\"{self.cause_type}.{cause}.remission_rate\"\n )\n }\n elif (\n \"remission_rate\" not in get_data_functions\n and \"transition_rate\" not in get_data_functions\n ):\n raise ValueError(\n \"You must supply a transition rate or remission rate function.\"\n )\n elif source_data_type == \"proportion\":\n if \"proportion\" not in get_data_functions:\n raise ValueError(\"You must supply a proportion function.\")\n return super().add_transition(output, source_data_type, get_data_functions, **kwargs)\n\n def next_state(\n self, index: pd.Index, event_time: pd.Timestamp, population_view: PopulationView\n ):\n \"\"\"Moves a population among different disease states.\n\n Parameters\n ----------\n index\n An iterable of integer labels for the simulants.\n event_time:\n The time at which this transition occurs.\n population_view:\n A view of the internal state of the simulation.\n \"\"\"\n eligible_index = self._filter_for_transition_eligibility(index, event_time)\n return super().next_state(eligible_index, event_time, population_view)\n\n def _filter_for_transition_eligibility(self, index, event_time):\n \"\"\"Filter out all simulants who haven't been in the state for the prescribed dwell time.\n\n Parameters\n ----------\n index\n An iterable of integer labels for the simulants.\n\n Returns\n -------\n pd.Index\n A filtered index of the simulants.\n \"\"\"\n population = self.population_view.get(index, query='alive == \"alive\"')\n if np.any(self.dwell_time(index)) > 0:\n state_exit_time = population[self.event_time_column] + pd.to_timedelta(\n self.dwell_time(index), unit=\"D\"\n )\n return population.loc[state_exit_time <= event_time].index\n else:\n return index\n\n def _cleanup_effect(self, index, event_time):\n if self.cleanup_function is not None:\n self.cleanup_function(index, event_time)\n\n def load_prevalence_data(self, builder):\n if \"prevalence\" in self._get_data_functions:\n return self._get_data_functions[\"prevalence\"](builder, self.cause)\n else:\n return builder.data.load(f\"{self.cause_type}.{self.cause}.prevalence\")\n\n def load_birth_prevalence_data(self, builder):\n if \"birth_prevalence\" in self._get_data_functions:\n return self._get_data_functions[\"birth_prevalence\"](builder, self.cause)\n else:\n return 0\n\n def load_dwell_time_data(self, builder):\n if \"dwell_time\" in self._get_data_functions:\n dwell_time = self._get_data_functions[\"dwell_time\"](builder, self.cause)\n else:\n dwell_time = 0\n\n if isinstance(dwell_time, pd.Timedelta):\n dwell_time = dwell_time.total_seconds() / (60 * 60 * 24)\n if (\n isinstance(dwell_time, pd.DataFrame) and np.any(dwell_time.value != 0)\n ) or dwell_time > 0:\n self.transition_set.allow_null_transition = True\n\n return dwell_time\n\n def load_disability_weight_data(self, builder):\n if \"disability_weight\" in self._get_data_functions:\n disability_weight = self._get_data_functions[\"disability_weight\"](\n builder, self.cause\n )\n else:\n disability_weight = builder.data.load(\n f\"{self.cause_type}.{self.cause}.disability_weight\"\n )\n\n if isinstance(disability_weight, pd.DataFrame) and len(disability_weight) == 1:\n disability_weight = disability_weight.value[0] # sequela only have single value\n\n return disability_weight\n\n def load_excess_mortality_rate_data(self, builder):\n if \"excess_mortality_rate\" in self._get_data_functions:\n return self._get_data_functions[\"excess_mortality_rate\"](builder, self.cause)\n elif builder.data.load(f\"cause.{self._model}.restrictions\")[\"yld_only\"]:\n return 0\n else:\n return builder.data.load(f\"{self.cause_type}.{self.cause}.excess_mortality_rate\")\n\n def __repr__(self):\n return \"DiseaseState({})\".format(self.state_id)\n\n\nclass TransientDiseaseState(BaseDiseaseState, Transient):\n def __repr__(self):\n return \"TransientDiseaseState(name={})\".format(self.state_id)\n","sub_path":"src/vivarium_public_health/disease/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":19748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"48397415","text":"from django.contrib.auth.models import User\r\nfrom django.core.exceptions import (PermissionDenied)\r\nfrom rest_framework import serializers\r\nfrom rest_framework_jwt.settings import api_settings\r\n\r\nfrom stores.models import Merchant, Store\r\nfrom vfrlight.config import Config as cfg\r\nfrom vfrlight.tasks import (initilize_webhooks, intitalize_scripttag,\r\n sync_collections, sync_products, getlocaletaskandemail)\r\n\r\n\r\ndef verify_store_access_token(request, store):\r\n jwt_token = request.META.get('HTTP_AUTHORIZATION')\r\n jwt_decode_handler = api_settings.JWT_DECODE_HANDLER\r\n username = jwt_decode_handler(jwt_token.split(' ')[1])['username']\r\n if not store.owner.user.username == username:\r\n raise PermissionDenied()\r\n\r\n\r\ndef get_or_raise(classmodel, **kwargs):\r\n try:\r\n return classmodel.objects.get(**kwargs)\r\n except Exception as e:\r\n raise serializers.ValidationError(e)\r\n\r\n\r\ndef generate_token(user):\r\n jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER\r\n jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER\r\n\r\n payload = jwt_payload_handler(user)\r\n token = jwt_encode_handler(payload)\r\n return token\r\n\r\nfrom django.core.mail import send_mail\r\nfrom vfrlight.settings import EMAIL_HOST_USER\r\nimport sys\r\ndef initialize(token, shop, ignore_webhooks=False, ignore_scripttag=False, source=\"connect\"):\r\n try:\r\n user = User.objects.get(\r\n username=(shop + \"_User\"))\r\n merchant = Merchant.objects.get(user=user)\r\n store = Store.objects.get(owner=merchant)\r\n store.token = token\r\n store.save()\r\n except User.DoesNotExist:\r\n user = User.objects.create_user(\r\n username=shop + \"_User\", password='user12345')\r\n merchant = Merchant.objects.create(user=user)\r\n store = Store.objects.create(\r\n url=shop, token=token, owner=merchant)\r\n\r\n if ignore_webhooks:\r\n store.webhooks_added = True\r\n store.save()\r\n if ignore_scripttag:\r\n store.scripttag_added = True\r\n store.save()\r\n\r\n if cfg.getLocale:\r\n getLocale(store.slug)\r\n\r\n if cfg.Async:\r\n asynchronous_initialization(store.slug, source)\r\n else:\r\n non_asynchronous_initialization(store.slug, source)\r\n\r\n jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER\r\n jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER\r\n\r\n payload = jwt_payload_handler(store.owner.user)\r\n token = jwt_encode_handler(payload)\r\n\r\n return store, token\r\n\r\n\r\ndef asynchronous_initialization(store_slug, source):\r\n # if source == \"connect\" and Store.objects.get(slug=store_slug).did_fetch_data_during_connect is True:\r\n # return\r\n send_mail(\r\n \"Welcome to asynchronous_initialization function\",\r\n \"Hello \",\r\n EMAIL_HOST_USER,\r\n [\"surinder.indybytes@gmail.com\"],\r\n fail_silently=True,\r\n )\r\n initilize_webhooks.delay(store_slug)\r\n intitalize_scripttag.delay(store_slug)\r\n # changed here not condition\r\n if cfg.IGNORE_SYNC_DURING_CONNECT:\r\n sync_products.delay(store_slug)\r\n sync_collections.delay(store_slug)\r\n if source == \"connect\":\r\n Store.objects.filter(slug=store_slug).update(did_fetch_data_during_connect=True)\r\n\r\n\r\ndef getLocale(store_slug):\r\n if cfg.IGNORE_SYNC_DURING_CONNECT:\r\n getlocaletaskandemail(store_slug)\r\n else:\r\n getlocaletaskandemail.delay(store_slug)\r\n\r\n\r\ndef non_asynchronous_initialization(store_slug, source):\r\n # if(not cfg.DEBUG):\r\n # initilize_webhooks(store_slug)\r\n # intitalize_scripttag(store_slug)\r\n if source == \"connect\" and Store.objects.get(slug=store_slug).did_fetch_data_during_connect is True:\r\n return\r\n initilize_webhooks(store_slug)\r\n intitalize_scripttag(store_slug)\r\n # for performance issues, do not sync when you are connecting\r\n if not cfg.IGNORE_SYNC_DURING_CONNECT:\r\n sync_products(store_slug)\r\n sync_collections(store_slug)\r\n if source == \"connect\":\r\n Store.objects.filter(slug=store_slug).update(did_fetch_data_during_connect=True)\r\n\r\n\r\ndef fake_initialize():\r\n initialize('1f145682dd384b589a7f1a2fa1bfc28f',\r\n 'meet10.myshopify.com', ignore_webhooks=True,\r\n ignore_scripttag=True)\r\n","sub_path":"vfrlight/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"498742032","text":"#!/usr/bin/env python3\n\nfrom typing import Optional, List\n\nimport unittest\n\nclass InvalidMarkers(Exception):\n pass\n\nclass Grid:\n textual_positions = ['top_left', 'top_middle', 'top_right',\n 'middle_left', 'center', 'middle_right',\n 'bottom_left', 'bottom_middle', 'bottom_right']\n def __init__(self, markers: str = \"XO\") -> None:\n if len(markers) != 2:\n raise InvalidMarkers()\n if markers[0] == markers[1]:\n raise InvalidMarkers()\n self.played_positions = dict()\n self.markers = markers\n def is_empty(self) -> bool:\n return len(self.played_positions) == 0\n def is_full(self) -> bool:\n return len(self.played_positions) == 9\n def get_grid(self) -> str:\n if self.is_empty():\n return \" \"*9\n return \"\".join(self.played_positions[posn]\n if posn in self.played_positions else \" \"\n for posn in self.textual_positions)\n def __str__(self) -> str:\n return self.get_grid()\n def play(self, position: str) -> Optional[str]:\n if position in self.played_positions:\n return None\n if position not in self.textual_positions:\n return None\n marker = self.markers[len(self.played_positions)%2]\n self.played_positions[position] = marker\n return marker\n def get_winning_player(self) -> Optional[str]:\n if self.is_empty() or len(self.played_positions) < 5:\n return None\n winning_lines = [{'top_left', 'middle_left', 'bottom_left'}, # Down\n {'top_middle', 'center', 'bottom_middle'},\n {'top_right', 'middle_right', 'bottom_right'},\n {'top_left', 'top_middle', 'top_right'}, # Across\n {'middle_left', 'center', 'middle_right'},\n {'bottom_left', 'bottom_middle', 'bottom_right'},\n {'top_left', 'center', 'bottom_right'}, # Diagonal\n {'top_right', 'center', 'bottom_left'},\n ]\n for marker in self.markers:\n positions = {k for k, v in self.played_positions.items() if v is marker}\n if len([line for line in winning_lines if positions.issuperset(line)]):\n return marker\n return None\n\nclass TicTacToeTest(unittest.TestCase):\n player_1 = \"X\"\n player_2 = \"O\"\n def make_grid(self):\n return Grid()\n\n def setUp(self):\n self.grid = self.make_grid()\n def test_too_few_markers(self):\n with self.assertRaises(InvalidMarkers):\n grid = Grid(\"O\")\n def test_too_many_markers(self):\n with self.assertRaises(InvalidMarkers):\n grid = Grid(\"OXY\")\n def test_duplicate_markers(self):\n with self.assertRaises(InvalidMarkers):\n grid = Grid(\"OO\")\n def test_havegrid(self):\n assert(self.grid is not None)\n def test_startgrid_is_empty_and_not_full(self):\n assert(self.grid.is_empty())\n self.assertFalse(self.grid.is_full())\n def test_not_empty_and_not_full_after_play_center(self):\n assert(self.grid.play('center'))\n assert(not self.grid.is_empty())\n self.assertFalse(self.grid.is_full())\n def test_play_center_twice_fails(self):\n assert(self.grid.play('center'))\n assert(not self.grid.play('center'))\n def test_play_top_left_twice(self):\n assert(self.grid.play('top_left'))\n assert(not self.grid.play('top_left'))\n def test_play_center_then_top_left(self):\n assert(self.grid.play('center'))\n assert(self.grid.play('top_left'))\n def test_bad_play_position(self):\n self.assertEqual(self.grid.play('cheese'), None)\n def test_all_textual_moves(self):\n for move in Grid.textual_positions:\n self.assertIsNotNone(self.grid.play(move), move)\n def test_is_full_after_all_moves_made(self):\n for move in Grid.textual_positions:\n self.grid.play(move)\n self.assertEqual(self.grid.is_full(), True)\n def test_no_player_won_with_empty_grid(self):\n self.assertEqual(self.grid.get_winning_player(), None)\n def test_no_player_won_after_one_play(self):\n self.grid.play('center')\n self.assertEqual(self.grid.get_winning_player(), None)\n def test_alternating_play_marks(self):\n self.assertEqual(self.grid.play('center'), self.player_1)\n self.assertEqual(self.grid.play('top_left'), self.player_2)\n self.assertEqual(self.grid.play('bottom_middle'), self.player_1)\n self.assertEqual(self.grid.play('bottom_left'), self.player_2)\n def test_many_plays_but_no_player_won_yet(self):\n moves = ['top_left', 'top_right', 'middle_left', 'middle_right', 'center']\n for move in moves:\n self.grid.play(move)\n self.assertEqual(self.grid.get_winning_player(), None)\n\n def _make_plays(self, first_moves, second_moves, grid=None):\n if grid is None:\n grid = self.grid\n moves = first_moves + second_moves\n moves[::2] = first_moves\n moves[1::2] = second_moves\n for move in moves:\n grid.play(move)\n def _get_grids_for_multiple_encoded_plays(self, first_moves, second_moves):\n grids = []\n for game_first, game_second in zip(first_moves, second_moves):\n grid = self.make_grid()\n game_first = [Grid.textual_positions[i] for i in game_first]\n game_second = [Grid.textual_positions[j] for j in game_second]\n self._make_plays(game_first, game_second, grid)\n grids.append((grid, game_first, game_second))\n return grids\n\n def test_first_player_should_win_on_left(self):\n moves = ['top_left', 'top_right', 'middle_left', 'middle_right', 'bottom_left']\n for move in moves:\n self.grid.play(move)\n self.assertEqual(self.grid.get_winning_player(), self.player_1)\n def test_first_player_should_win_on_right(self):\n moves = ['top_right', 'top_left', 'middle_right', 'middle_left', 'bottom_right']\n for move in moves:\n self.grid.play(move)\n self.assertEqual(self.grid.get_winning_player(), self.player_1)\n def test_second_player_should_win_on_left(self):\n moves = ['top_left', 'top_right', 'middle_left', 'middle_right', 'center', 'bottom_right']\n for move in moves:\n self.grid.play(move)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_second_player_should_win_on_right(self):\n moves = ['top_right', 'top_left', 'middle_right', 'middle_left', 'center', 'bottom_left']\n for move in moves:\n self.grid.play(move)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_second_player_should_win_on_top(self):\n player_1_moves = ['bottom_left', 'bottom_middle', 'center']\n player_2_moves = ['top_left', 'top_middle', 'top_right']\n self._make_plays(player_1_moves, player_2_moves)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_second_player_should_win_on_bottom(self):\n player_1_moves = ['top_left', 'top_middle', 'center']\n player_2_moves = ['bottom_left', 'bottom_middle', 'bottom_right']\n self._make_plays(player_1_moves, player_2_moves)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_second_player_should_win_middle_horizontally(self):\n player_1_moves = ['top_left', 'top_middle', 'bottom_left']\n player_2_moves = ['middle_left', 'center', 'middle_right']\n self._make_plays(player_1_moves, player_2_moves)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_second_player_should_win_middle_vertically(self):\n player_1_moves = ['top_left', 'bottom_right', 'bottom_left']\n player_2_moves = ['top_middle', 'center', 'bottom_middle']\n self._make_plays(player_1_moves, player_2_moves)\n self.assertEqual(self.grid.get_winning_player(), self.player_2)\n def test_first_player_should_win_horizontally_x3(self):\n player_1_moves = [[0,1,2], [3,4,5], [6,7,8]]\n player_2_moves = [[3,4], [6,7], [0,1]] # Abitrary valid other moves\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_1, (first, second))\n def test_first_player_should_win_vertically_x3(self):\n player_1_moves = [[0,3,6], [1,4,7], [2,5,8]]\n player_2_moves = [[1,2], [2,3], [3,4]] # Abitrary valid other moves\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_1, (first, second))\n def test_first_player_should_win_diagonally_x2(self):\n player_1_moves = [[0,4,8], [2,4,6]]\n player_2_moves = [[1,2], [3,5]] # Abitrary valid other moves\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_1, (first, second))\n def test_second_player_should_win_horizontally_x3(self):\n player_1_moves = [[0,1,6], [3,4,1], [6,7,3]] # Abitrary valid other moves\n player_2_moves = [[3,4,5], [6,7,8], [0,1,2]]\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_2, (first, second))\n def test_second_player_should_win_vertically_x3(self):\n player_1_moves = [[0,3,5], [1,4,5], [1,4,6]] # Abitrary valid other moves\n player_2_moves = [[1,4,7], [0,3,6], [2,5,8]]\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_2, (first, second))\n def test_second_player_should_win_diagonally_x2(self):\n player_1_moves = [[1,3,7], [1,0,3]] # Abitrary valid other moves\n player_2_moves = [[0,4,8], [2,4,6]]\n for grid, first, second in self._get_grids_for_multiple_encoded_plays(player_1_moves, player_2_moves):\n self.assertEqual(grid.get_winning_player(), self.player_2, (first, second))\n def test_get_grid_at_start(self):\n self.assertEqual(self.grid.get_grid(), \" \"*9)\n def test_get_grid_after_all_textual_moves(self):\n for move in Grid.textual_positions:\n self.grid.play(move)\n self.assertEqual(self.grid.get_grid(),\n (self.player_1 + self.player_2)*4 + self.player_1)\n def test_get_grid_after_all_moves_offset_by_3(self):\n moves = list(range(3,9))\n moves.extend(list(range(0,3)))\n for move in moves:\n self.grid.play(Grid.textual_positions[move])\n target = (self.player_1 + self.player_2 + self.player_1 +\n (self.player_1 + self.player_2)*3)\n self.assertEqual(self.grid.get_grid(), target)\n def test_get_grid_after_center_play(self):\n self.grid.play('center')\n self.assertEqual(self.grid.get_grid(), \" \"*4 + self.player_1 + \" \"*4)\n def test_get_grid_same_as_str(self):\n self.grid.play('center')\n self.grid.play('top_left')\n self.grid.play('bottom_right')\n self.assertEqual(self.grid.get_grid(), \"%s\" % self.grid)\n\nclass TicTacToeTest_XO(TicTacToeTest):\n player_1 = \"X\"\n player_2 = \"O\"\n def make_grid(self):\n return Grid(\"XO\")\n\nclass TicTacToeTest_OX(TicTacToeTest):\n player_1 = \"O\"\n player_2 = \"X\"\n def make_grid(self):\n return Grid(\"OX\")\n\nclass TicTacToeTest_star_plus(TicTacToeTest): # Demonstration of arbitrary marker pairs\n player_1 = \"*\"\n player_2 = \"+\"\n def make_grid(self):\n return Grid(\"*+\")\n\nclass TTTComputer:\n def __init__(self):\n self.triples = [ {0, 4, 8}, {2, 4, 6} ] # Diagonals\n for i in range(0,3):\n self.triples.append({0+(3*i), 1+(3*i), 2+(3*i)}) # Horizontals\n self.triples.append({0+i, 3+i, 6+i}) # Verticals\n def play_on_grid(self, grid: Grid, with_mark: str, vs_mark: str) -> None:\n grid_s = grid.get_grid()\n number_of_plays = len([entry for entry in grid_s if entry is not \" \"])\n # Try to win\n winning_move = self._try_to_win(grid_s, with_mark)\n if winning_move is not None:\n grid.play(Grid.textual_positions[winning_move])\n return\n # Block any potential losing move\n avoid_loss_move = self._try_to_avoid_loss(grid_s, vs_mark)\n if avoid_loss_move: # Non-empty list\n grid.play(Grid.textual_positions[avoid_loss_move[0]]) # Might be forked, play anyhow\n return\n # Try to detect a fork for computer and play there\n fork_move_for_me = self._detect_fork_move_for_mark(grid_s, with_mark, vs_mark)\n if fork_move_for_me: # Non-empty list\n grid.play(Grid.textual_positions[fork_move_for_me[0]])\n return\n # Try to detect a fork for opponent and play (block) there\n fork_move_for_opponent = self._detect_fork_move_for_mark(grid_s, vs_mark, with_mark)\n if fork_move_for_opponent: # Non-empty list\n grid.play(Grid.textual_positions[fork_move_for_opponent[0]])\n return\n # If center is not taken, take it, except on first move\n if number_of_plays > 0 and grid_s[4] == \" \":\n grid.play('center')\n return\n # Play in next available space\n for sequential_move in range(0, 9):\n if grid_s[sequential_move] == \" \":\n grid.play(Grid.textual_positions[sequential_move])\n return\n return\n def _try_to_win(self, grid_str: str, with_mark: str) -> Optional[int]:\n '''Tries to find a move to win; if so, returns index, otherwise None.'''\n my_marks = {idx for idx, what in enumerate(grid_str) if what is with_mark}\n # We know we have one entry, so using pop is safe (triple less length=2 item)\n winning_moves = [(triple - (triple & my_marks)).pop() for triple in self.triples\n if len(triple & my_marks) == 2]\n if winning_moves:\n empty_winning_moves = [move for move in winning_moves if grid_str[move] == \" \"]\n if empty_winning_moves:\n assert(len(empty_winning_moves)==1) # FIXME? Previous code assumed this\n return empty_winning_moves[0]\n return None\n def _try_to_avoid_loss(self, grid_str: str, vs_mark: str) -> List[int]:\n '''Tries to find if a position must be played to block an opponent's win.\n If so, returns that index, otherwise None.'''\n vs_marks = {idx for idx, what in enumerate(grid_str) if what is vs_mark}\n # We know we have one entry, so using pop is safe (triple less length=2 item)\n avoid_loss_moves = [(triple - (triple & vs_marks)).pop() for triple in self.triples\n if len(triple & vs_marks) == 2]\n if avoid_loss_moves:\n empty_avoid_loss_moves = [move for move in avoid_loss_moves if grid_str[move] == \" \"]\n if empty_avoid_loss_moves:\n return empty_avoid_loss_moves\n return []\n def _detect_fork_move_for_mark(self, grid_str: str, mark: str, other_mark: str) -> List[int]:\n '''Tries to find if a position exists where 'mark' can fork.\n If so, returns that index, otherwise None.'''\n marks = {idx for idx, what in enumerate(grid_str) if what is mark}\n other_marks = {idx for idx, what in enumerate(grid_str) if what is other_mark}\n intersecting_triples = [(triple, triple & marks, triple - marks) for triple in self.triples\n if (triple & marks) != set() and triple & other_marks == set()]\n forks = {(a & available).pop() # Can pop since not an empty set\n for triple, overlap, available in intersecting_triples\n for t, o, a in intersecting_triples\n if triple != t and (a & available) != set()}\n if forks:\n return list(forks)\n return []\n\nclass TTT_computer_test(unittest.TestCase):\n def setUp(self):\n self.computer = TTTComputer()\n self.grid = Grid(\"XO\")\n def assertNumberOfPlaysOnGrid(self, grid_str: str, number_of_plays: int, msg=\"\"):\n expected_number_of_plays = len([entry for entry in grid_str if entry is not \" \"])\n self.assertEqual(expected_number_of_plays, number_of_plays, msg=msg)\n def print_grid_2d(self, grid_str: str):\n grid_str_ = \"\".join([\"_\" if chr == \" \" else chr for chr in grid_str])\n print()\n print(grid_str_[0:3])\n print(grid_str_[3:6])\n print(grid_str_[6:9])\n print()\n\n def test_TTTComputer_exists(self):\n self.assertIsNotNone(self.computer)\n def test_computer_play_leaves_grid_not_empty(self):\n self.assertTrue(self.grid.is_empty())\n self.computer.play_on_grid(self.grid, \"X\", \"O\")\n self.assertFalse(self.grid.is_empty())\n def test_computer_tries_to_win_from_2_in_row_down_left_side(self):\n self.grid.play('top_left') # X\n self.grid.play('top_right') # O\n self.grid.play('bottom_left') # X\n self.grid.play('bottom_right') # O\n self.computer.play_on_grid(self.grid, \"X\", \"O\") # X\n self.assertEqual(self.grid.get_grid(), \"X OX X O\")\n self.assertEqual(self.grid.get_winning_player(), 'X')\n def test_computer_tries_to_win_from_2_in_row_down_right_side(self):\n self.grid.play('top_right') # X\n self.grid.play('top_left') # O\n self.grid.play('bottom_right') # X\n self.grid.play('bottom_left') # O\n self.computer.play_on_grid(self.grid, \"X\", \"O\") # X\n self.assertEqual(self.grid.get_grid(), \"O X XO X\")\n self.assertEqual(self.grid.get_winning_player(), 'X')\n def test_computer_doesnt_try_to_win_where_opponent_has_marker(self):\n self.grid.play('top_right') # X\n self.grid.play('top_left') # O\n self.grid.play('bottom_right') # X\n self.grid.play('middle_right') # O [blocks X win]\n self.computer.play_on_grid(self.grid, \"X\", \"O\") # X\n self.assertNumberOfPlaysOnGrid(self.grid.get_grid(), 5)\n def test_computer_plays_in_blank_if_cant_win(self):\n for move_2 in range(1, 9):\n grid = Grid(\"XO\") # Use new grid each time\n grid.play('top_left')\n grid.play(Grid.textual_positions[move_2])\n self.computer.play_on_grid(grid, \"X\", \"O\")\n self.assertNumberOfPlaysOnGrid(grid.get_grid(), 3, Grid.textual_positions[move_2])\n def test_computer_can_block(self):\n self.grid.play('top_right') # X\n self.grid.play('top_left') # O\n self.grid.play('bottom_middle') # X\n self.grid.play('middle_left') # O\n self.computer.play_on_grid(self.grid, \"X\", \"O\") # X\n grid_s = self.grid.get_grid()\n self.assertNumberOfPlaysOnGrid(grid_s, 5)\n self.assertEqual(grid_s, \"O XO XX \")\n def test_computer_plays_in_center_if_unoccupied_and_not_first_move(self):\n for move_1 in range(0, 9):\n grid = Grid(\"XO\") # Use new grid each time\n grid.play(Grid.textual_positions[move_1])\n self.computer.play_on_grid(grid, \"O\", \"X\")\n self.assertNumberOfPlaysOnGrid(grid.get_grid(), 2, Grid.textual_positions[move_1])\n expected_grid = [\"X\" if i==move_1 else \" \" for i in range(0, 9)]\n if move_1 != 4:\n expected_grid[4] = \"O\"\n else:\n expected_grid[0] = \"O\"\n self.assertEqual(grid.get_grid(), \"\".join(expected_grid))\n def test_computer_starts_in_the_corner(self): # best probabilistic strategy\n self.computer.play_on_grid(self.grid, \"X\", \"O\")\n grid_s = self.grid.get_grid()\n self.assertNumberOfPlaysOnGrid(grid_s, 1)\n X_index = grid_s.find(\"X\")\n self.assertTrue(X_index in (0, 2, 6, 8))\n def test_computer_detects_and_plays_a_fork(self):\n self.grid.play('top_left')\n self.grid.play('top_middle')\n self.grid.play('center')\n self.grid.play('bottom_right')\n self.computer.play_on_grid(self.grid, \"X\", \"O\")\n grid_str = self.grid.get_grid()\n self.assertNumberOfPlaysOnGrid(grid_str, 5)\n self.assertIn(grid_str, (\"XO XX O\", \"XO X X O\"))\n def test_computer_detects_and_blocks_fork(self):\n self.grid.play('center')\n self.computer.play_on_grid(self.grid, \"O\", \"X\")\n self.grid.play('bottom_right')\n self.computer.play_on_grid(self.grid, \"O\", \"X\")\n grid_str = self.grid.get_grid()\n self.assertNumberOfPlaysOnGrid(grid_str, 4)\n self.assertEqual(grid_str, \"O O X X\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":21076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"458646057","text":"from django.conf.urls import patterns, url\n\nfrom publications import views\n\nurlpatterns = patterns('',\n # Publications List\n url(r'^$', views.publications, name='publications'),\n\n # General publication actions\n # url(r'^create/$', views.createPublication, name='createPublication'),\n url(r'^vote/$', views.votePublication, name='votePublication'),\n url(r'^delete/$', views.deletePublication, name='deletePublication'),\n\n # Announcements actions\n # url(r'^announcements/$', views.announcements, name='announcements'),\n # url(r'^announcements/create/$', views.createAnnouncement, name='createAnnouncement'),\n # url(r'^announcements/(?P\\d+)$', views.announcementDetails, name='announcementDetails'),\n # url(r'^announcements/edit/(?P\\d+)$', views.editAnnouncement, name='editAnnouncement'),\n\n # Class material actions\n # url(r'^classmaterial/$', views.classMaterial, name='classMaterial'),\n # url(r'^classmaterial/create/$', views.createClassMaterial, name='createClassMaterial'),\n # url(r'^classmaterial/(?P\\d+)$', views.classMaterialDetails, name='classMaterialDetails'),\n # url(r'^classmaterial/edit/(?P\\d+)$', views.editClassMaterial, name='editClassMaterial'),\n\n # Event actions\n url(r'^events/$', views.events, name='events'),\n url(r'^events/create/$', views.createEvent, name='createEvent'),\n url(r'^events/(?P\\d+)$', views.eventDetails, name='eventDetails'),\n url(r'^events/edit/(?P\\d+)$', views.editEvent, name='editEvent'),\n\n # Job Offer actions\n # url(r'^joboffers/$', views.joboffers, name='joboffers'),\n # url(r'^joboffers/create/$', views.createJobOffer, name='createJobOffer'),\n # url(r'^joboffers/(?P\\d+)$', views.jobOfferDetails, name='jobOfferDetails'),\n # url(r'^joboffers/edit/(?P\\d+)$', views.editJobOffer, name='editJobOffer'),\n\n # Lost and Found Actions\n # url(r'^lostandfound/$', views.lostAndFound, name='lostAndFound'),\n # url(r'^lostandfound/create/$', views.createLostAndFound, name='createLostAndFound'),\n # url(r'^lostandfound/(?P\\d+)$', views.lostAndFoundDetails, name='lostAndFoundDetails'),\n # url(r'^lostandfound/edit/(?P\\d+)$', views.editLostAndFound, name='editLostAndFound'),\n \n # Buy and Sell Actions\n # url(r'^buyandsell/$', views.buyandsell, name='buyandsell'),\n # url(r'^buyandsell/create/$', views.createBuyAndSell, name='createBuyAndSell'),\n # url(r'^buyandsell/(?P\\d+)$', views.buyAndSellDetails, name='buyAndSellDetails'),\n # url(r'^buyandsell/edit/(?P\\d+)$', views.editBuyAndSell, name='editBuyAndSell'),\n)\n","sub_path":"publications/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206432730","text":"from sklearn import svm, metrics\r\nfrom sklearn.model_selection import train_test_split\r\nimport pandas as pd\r\n\r\ndef changeValue(lst):\r\n return [float(v)/255 for v in lst]\r\n\r\n## 0. Training Data, Test Data\r\n\r\ncsv = pd.read_csv('C:/PySource/Project1/mnist/train_10k.csv')\r\ntrain_data = csv.iloc[:, 1:].values\r\ntrain_data = list(map(changeValue, train_data))\r\ntrain_label = csv.iloc[:, 0].values\r\n\r\ncsv = pd.read_csv('C:/PySource/Project1/mnist/t10k_0.5k.csv')\r\ntest_data = csv.iloc[:, 1:].values\r\ntest_data = list(map(changeValue, test_data))\r\ntest_label = csv.iloc[:, 0].values\r\n## 학습용, 훈련용 분리\r\n\r\n# train_data, test_data, train_label, test_label = \\\r\n# train_test_split(train_data, train)label, train_size=0.3)\r\n## 1. Create Classfire - Select ML Algorithm\r\n\r\nclf = svm.NuSVC(gamma='auto')\r\n\r\n## 2. Learning Data\r\n#clf.fit([훈련 데이터], [정답])\r\n\r\nclf.fit(train_data, train_label)\r\n\r\nimport joblib\r\n\r\njoblib.dump(clf,'mnist_model_10k.dmp')\r\n\r\nclf=joblib.load('mnist_model_10k.dmp')\r\n\r\n\r\n## 3. Predict\r\n# clf.predict([예측할 데이터])\r\n\r\n## 4. Check Accuracy Rate\r\n\r\nresult = clf.predict(test_data)\r\n\r\nscore = metrics.accuracy_score(result, test_label)\r\nprint(result)\r\nprint(\"정답률: \",\"{0:.2f}%\".format(score*100))\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimg= np.array(test_data[0]).reshape([28,28])\r\nplt.imshow(img, cmap='gray')\r\nplt.show()\r\n\r\n","sub_path":"Code14-07 ML scikit-Learn 06 MNIST 모델 저장.py","file_name":"Code14-07 ML scikit-Learn 06 MNIST 모델 저장.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"373909588","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport tempfile\nfrom shutil import rmtree\n\nimport pytest\n\n__author__ = \"Florian Wilhelm\"\n__copyright__ = \"Blue Yonder\"\n__license__ = \"new BSD\"\n\n\n@pytest.yield_fixture()\ndef tmpdir():\n old_path = os.getcwd()\n newpath = tempfile.mkdtemp()\n os.chdir(newpath)\n yield\n rmtree(newpath)\n os.chdir(old_path)","sub_path":"tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"172794678","text":"import pika\nfrom time import sleep\n\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\n\nchannel.queue_declare(queue='cle_queue')\n\n\ndef publish(message):\n channel.basic_publish(exchange='',\n routing_key='cle_queue',\n body=message)\n print(\"Published to rabbit\")\n print(message)\n\n\nif __name__ == '__main__':\n while True:\n publish(\"test\")\n sleep(1)\n","sub_path":"CLE/ds/rabbit.py","file_name":"rabbit.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"609257713","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport json, os, os.path as path\nfrom bes.web.web_server import web_server\nfrom bes.system.log import log\nfrom bes.fs.file_find import file_find\nfrom bes.fs.file_util import file_util\nfrom bes.compat import url_compat\n\nfrom .artifactory_requests import artifactory_requests\n\nclass mock_artifactory_server(web_server):\n 'A mock artifactory web server. Tries to impersonate artifactory enough to do unit tests.'\n\n def __init__(self, port = None, root_dir = None, artifactory_id = '', users = None):\n super(mock_artifactory_server, self).__init__(port = port, users = users, log_tag = 'artifactory')\n self._root_dir = root_dir or os.getcwd()\n self._artifactory_id = artifactory_id\n\n _ERROR_404_HTML = '''\n\n \n 404 - Not found \n \n \n 404 - Not found \n \n\n'''\n\n _ERROR_405_HTML = '''\n\n \n 405 - Method not supported \n \n \n 405 - Method not supported \n \n\n'''\n \n def handle_request(self, environ, start_response):\n print_environ = False\n #print_environ = True\n \n print_headers = False\n #print_headers = True\n\n if print_headers:\n for key, value in sorted(self.headers.items()):\n log.output('HEADER: %s=%s\\n' % (key, value), console = True)\n\n if print_environ:\n for key, value in sorted(environ.items()):\n log.output('%s=%s\\n' % (key, value), console = True)\n method = environ['REQUEST_METHOD']\n path_info = self.path_info(environ)\n if path_info.path_info.startswith('/api'):\n return self._api(environ, path_info, start_response)\n if method == 'GET':\n return self._get(environ, path_info, start_response)\n elif method == 'PUT':\n return self._put(environ, path_info, start_response)\n if method == 'HEAD':\n return self._head(environ, path_info, start_response)\n else:\n return self.response_error(start_response, 405)\n\n def _get(self, environ, path_info, start_response):\n if not path.isfile(path_info.rooted_filename):\n return self.response_error(start_response, 404)\n mime_type = self.mime_type(path_info.rooted_filename)\n content = file_util.read(path_info.rooted_filename)\n headers = [\n ( 'Content-Type', str(mime_type) ),\n ( 'Content-Length', str(len(content)) ),\n ( 'X-Artifactory-Filename', path.basename(path_info.path_info) ),\n ( 'X-Artifactory-Id', self._artifactory_id ),\n ]\n headers += artifactory_requests.checksum_headers_for_file(path_info.rooted_filename).items()\n return self.response_success(start_response, 200, [ content ], headers)\n\n def _head(self, environ, path_info, start_response):\n if not path.isfile(path_info.rooted_filename):\n return self.response_error(start_response, 404)\n mime_type = self.mime_type(path_info.rooted_filename)\n headers = [\n ( 'Content-Type', str(mime_type) ),\n ( 'Content-Length', str(file_util.size(path_info.rooted_filename)) ),\n ( 'X-Artifactory-Filename', path.basename(path_info.path_info) ),\n ( 'X-Artifactory-Id', self._artifactory_id ),\n ]\n headers += artifactory_requests.checksum_headers_for_file(path_info.rooted_filename).items()\n return self.response_success(start_response, 200, [], headers)\n \n def _put(self, environ, path_info, start_response):\n 'https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-DeployArtifact'\n content_length = int(environ['CONTENT_LENGTH'])\n# filename = environ['PATH_INFO']\n# filename = file_util.lstrip_sep(filename)\n# file_path = path.join(self._root_dir, filename)\n fin = environ['wsgi.input']\n chunk_size = 1024\n n = int(content_length / chunk_size)\n r = int(content_length % chunk_size)\n file_util.ensure_file_dir(path_info.rooted_filename)\n with open(path_info.rooted_filename, 'wb') as fout:\n for i in range(0, n):\n chunk = fin.read(chunk_size)\n fout.write(chunk)\n if r:\n chunk = fin.read(r)\n fout.write(chunk)\n fout.flush()\n fout.close()\n base = '%s://%s' % (environ['wsgi.url_scheme'], environ['HTTP_HOST'])\n uri = url_compat.urljoin(base, path_info.path_info)\n data = {\n 'downloadUri': uri,\n }\n content = json.dumps(data, indent = 2) + '\\n'\n content = content.encode('utf8')\n headers = [\n ( 'Content-Type', 'application/json' ),\n ( 'Content-Length', str(len(content)) ),\n ]\n return self.response_success(start_response, 201, [ content ], headers)\n\n def _api(self, environ, path_info, start_response):\n parts = path_info.path_info.split('/')\n what = parts[2]\n if what == 'storage':\n return self._api_storage(environ, path_info, start_response)\n assert False\n\n def _api_storage(self, environ, path_info, start_response):\n xpath = file_util.remove_head(path_info.path_info, '/api/storage')\n fpath = path.join(self._root_dir, xpath)\n files = file_find.find(fpath, relative = True)\n for f in files:\n print('FILE: %s' % (f))\n# print(xpath)\n import sys\n sys.stdout.flush()\n assert False\n","sub_path":"lib/rebuild/artifactory/mock_artifactory_server.py","file_name":"mock_artifactory_server.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"146840927","text":"from comp61542 import app\nfrom database import database\nfrom flask import (render_template, request)\nfrom comp61542.statistics import utils\nimport json\nfrom flask.json import jsonify\ndef format_data(data):\n fmt = \"%.2f\"\n result = []\n for item in data:\n if type(item) is list:\n result.append(\", \".join([ (fmt % i).rstrip('0').rstrip('.') for i in item ]))\n else:\n result.append((fmt % item).rstrip('0').rstrip('.'))\n return result\n\n@app.route(\"/averages\")\ndef showAverages():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"Averages\", link= \"/averages\")\n \n args = {\"dataset\":dataset, \"id\":\"averages\"}\n args['title'] = \"Averaged Data\"\n db.title_cache = args['title']\n tables = []\n headers = [\"Average\", \"Conference Paper\", \"Journal\", \"Book\", \"Book Chapter\", \"All Publications\"]\n averages = [ database.Stat.MEAN, database.Stat.MEDIAN, database.Stat.MODE ]\n tables.append({\n \"id\":1,\n \"title\":\"Average Authors per Publication\",\n \"header\":headers,\n \"rows\":[\n [ database.Stat.STR[i] ]\n + format_data(db.get_average_authors_per_publication(i)[1])\n for i in averages ] })\n tables.append({\n \"id\":2,\n \"title\":\"Average Publications per Author\",\n \"header\":headers,\n \"rows\":[\n [ database.Stat.STR[i] ]\n + format_data(db.get_average_publications_per_author(i)[1])\n for i in averages ] })\n tables.append({\n \"id\":3,\n \"title\":\"Average Publications in a Year\",\n \"header\":headers,\n \"rows\":[\n [ database.Stat.STR[i] ]\n + format_data(db.get_average_publications_in_a_year(i)[1])\n for i in averages ] })\n tables.append({\n \"id\":4,\n \"title\":\"Average Authors in a Year\",\n \"header\":headers,\n \"rows\":[\n [ database.Stat.STR[i] ]\n + format_data(db.get_average_authors_in_a_year(i)[1])\n for i in averages ] })\n\n args['tables'] = tables\n args[\"breadcrump\"] = db.breadcrump\n return render_template(\"averages.html\", args=args)\n\n\n\n@app.route(\"/coauthors\")\ndef showCoAuthors():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"coauthors\", link= \"/coauthors\")\n \n PUB_TYPES = [\"Conference Papers\", \"Journals\", \"Books\", \"Book Chapters\", \"All Publications\"]\n args = {\"dataset\":dataset, \"id\":\"coauthors\"}\n args[\"title\"] = \"Co-Authors\"\n \n db.title_cache = args['title']\n start_year = db.min_year\n if \"start_year\" in request.args:\n start_year = int(request.args.get(\"start_year\"))\n\n end_year = db.max_year\n if \"end_year\" in request.args:\n end_year = int(request.args.get(\"end_year\"))\n\n pub_type = 4\n if \"pub_type\" in request.args:\n pub_type = int(request.args.get(\"pub_type\"))\n\n args[\"data\"] = db.get_coauthor_data(start_year, end_year, pub_type)\n args[\"start_year\"] = start_year\n args[\"end_year\"] = end_year\n args[\"pub_type\"] = pub_type\n args[\"min_year\"] = db.min_year\n args[\"max_year\"] = db.max_year\n args[\"start_year\"] = start_year\n args[\"end_year\"] = end_year\n args[\"pub_str\"] = PUB_TYPES[pub_type]\n db.args_cache = args\n db.title_cache = args['title']\n args[\"breadcrump\"] = db.breadcrump\n return render_template(\"coauthors.html\", args=args)\n\n@app.route(\"/firstLastSoleType\")\ndef showAuthorFirstLastSolePerType():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"Author order\", link=\"/firstLastSoleType\")\n PUB_TYPES = [\"Conference Papers\", \"Journals\", \"Books\", \"Book Chapters\", \"All Publications\"]\n args = {\"dataset\":dataset, \"id\":\"firstLastSoleType\"}\n args[\"title\"] = \"Author First/Last/Sole per publication type\"\n \n db.title_cache = args['title']\n \n pub_type = 4\n if \"pub_type\" in request.args:\n pub_type = int(request.args.get(\"pub_type\"))\n\n args[\"data\"] = db.get_all_authors_stats(pub_type)\n args[\"pub_type\"] = pub_type\n args[\"pub_str\"] = PUB_TYPES[pub_type]\n db.args_cache = args\n db.title_cache = args['title']\n return render_template('authorFirstLastSolePerType.html', args=args)\n\n@app.route(\"/\")\ndef showStatisticsMenu():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"Home\", link= \"/\", level=0)\n \n args = {\"dataset\":dataset}\n return render_template('statistics.html', args=args)\n\n@app.route(\"/statisticsdetails/\")\ndef showPublicationSummary(status):\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n args = {\"dataset\":dataset, \"id\":status}\n if (status == \"publication_summary\"):\n args[\"title\"] = \"Publication Summary\"\n args[\"data\"] = db.get_publication_summary()\n \n if (status == \"publication_author\"):\n args[\"title\"] = \"Author Publication\"\n args[\"data\"] = db.get_publications_by_author()\n\n if (status == \"publication_year\"):\n args[\"title\"] = \"Publication by Year\"\n args[\"data\"] = db.get_publications_by_year()\n\n if (status == \"author_year\"):\n args[\"title\"] = \"Author by Year\"\n args[\"data\"] = db.get_author_totals_by_year()\n \n if (status == \"author_first_last_sole\"):\n args[\"title\"] = \"Author statistics\"\n args[\"data\"] = db.get_all_authors_stats()\n \n if (status == \"author_first_last_sole_per_type\"):\n args[\"title\"] = \"Author statistics per type\"\n args[\"data\"] = db.get_all_authors_stats(3)\n \n db.title_cache = args['title']\n db.set_breadcrump(name=args[\"title\"], link=\"/statisticsdetails/\" + status )\n args[\"breadcrump\"] = db.breadcrump\n return render_template('statistics_details.html', args=args)\n\n@app.route(\"/authorsDegreeOfSeparation\")\ndef displayDegreeOfSeparation():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"Degree of separation\", link=\"/authorsDegreeOfSeparation\")\n args = {\"dataset\":dataset}\n args[\"title\"] = \"Degree Of Separation\"\n# author_names = [ author.name for author in db.authors ]\n# authors = [ author.name for author in db.authors ]\n author_A = \" - \"\n author_B = \" - \"\n degree_of_separation = \" - \"\n args[\"graph_js\"] = None\n db.cache_graph = None\n if \"authorA\" in request.args and \"authorB\" in request.args:\n author_A = request.args.get(\"authorA\")\n author_B = request.args.get(\"authorB\")\n db.generate_degrees_of_separation_graph()\n degree_of_separation=db.bfs(db.author_idx[author_A], db.author_idx[author_B])\n url = \"/authorsDegreeOfSeparation?authorA=\" + author_A + \"&authorB=\" + author_B\n db.set_breadcrump(name=author_A + \" | \" + author_B, link=url, level=2)\n graph = db.dfs(db.author_idx[author_A], db.author_idx[author_B], degree_of_separation+1)\n db.cache_graph = graph\n if degree_of_separation==-1:\n degree_of_separation=\"X\"\n args[\"columns\"] = (\"Author A\", \"Author B\", \"Degree of Separation\")\n author_names = db.author_idx.keys()\n author_names.sort()\n args[\"author_names\"] = author_names\n args[\"authorA\"] = author_A\n args[\"authorB\"] = author_B\n args[\"degree_of_separation\"] = degree_of_separation\n args[\"breadcrump\"] = db.breadcrump\n \n \n return render_template(\"authorsDegreeOfSeparation.html\", args=args)\n\n@app.route(\"/graph//\")\ndef getGraph(authora, authorb):\n db = app.config['DATABASE']\n db.generate_degrees_of_separation_graph()\n degree_of_separation=db.bfs(db.author_idx[authora], db.author_idx[authorb])\n graph = db.dfs(db.author_idx[authora], db.author_idx[authorb], degree_of_separation+1)\n return jsonify(db.convertIDGraphToNames(graph))\n\n@app.route(\"/publications/\")\ndef displayPublications(sortby):\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n args = {\"dataset\":dataset, \"id\":sortby}\n sortby = sortby.lower()\n args[\"title\"] = \"Publications\" \n \n if (sortby == \"year\"):\n db.publications = db.sortPublicationsByYear()\n elif (sortby == \"authors\"):\n db.publications = db.sortPublicationsByFirstAuthors()\n elif (sortby == \"title\"):\n db.publications = db.sortPublicationsByTitle()\n elif sortby == \"type\":\n db.publications = db.sortPublicationsByType()\n else:\n db.publications = db.sortPublicationsByTitle()\n \n args[\"data\"] = db.get_publication_list()\n db.title_cache = args['title']\n \n return render_template('publications.html', args=args)\n\n@app.route(\"/author/firstlast\")\ndef displayAuthorFirstLastSoleStats():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n try:\n authorname = request.args.get('fname')\n args = {\"dataset\":dataset, \"id\":authorname}\n first = db.get_times_as_first(authorname)\n last = db.get_times_as_last(authorname)\n author = {'name':authorname, 'first':first, 'last':last}\n args['title'] = \"Author First/Last/Sole stats\"\n db.title_cache = args['title']\n \n args['data'] = utils.author_stats_fist_last_table(author)\n db.cache = args['data'][1]\n db.header_cache = args['data'][0]\n db.sorted_cache = [ False for i in range(0, len(db.header_cache))]\n return render_template('author_first_last.html', args=args)\n except:\n return firstlast()\n \n@app.route(\"/stats/\")\ndef sortByField(field):\n db = app.config['DATABASE']\n dataset = app.config['DATASET']\n field = int(field)\n args = {\"dataset\":dataset, \"id\":field}\n db.sort_cache_generic(field)\n db.set_breadcrump(name=\"Order by field: \" + db.header_cache[field], link=\"/stats/\"+str(field), level=2)\n args['data'] = (db.header_cache, db.cache)\n try:\n args['title'] = db.title_cache\n except:\n pass #no title cached\n args[\"breadcrump\"] = db.breadcrump\n return render_template('statistics_details.html', args = args)\n\n@app.route(\"/stats/coauthors/\")\ndef sortByCoauthorField(field):\n db = app.config['DATABASE']\n field = int(field)\n db.sort_cache_generic(field)\n \n args = db.args_cache \n args['data'] = (db.header_cache, db.cache)\n try:\n args['title'] = db.title_cache\n except:\n pass #no title cached\n \n \n db.title_cache = args['title']\n\n \n return render_template('coauthors.html', args = args)\n\n@app.route(\"/stats/authors/\")\ndef sortStatsField(field):\n db = app.config['DATABASE']\n field = int(field)\n db.sort_cache_generic(field)\n \n args = db.args_cache \n args['data'] = (db.header_cache, db.cache)\n try:\n args['title'] = db.title_cache\n except:\n pass #no title cached\n \n \n db.title_cache = args['title']\n\n args[\"breadcrump\"] = db.breadcrump \n return render_template('authorFirstLastSolePerType.html', args = args)\n\n\n \ndef displayAuthorStats(authorname, args):\n db = app.config['DATABASE']\n \n try:\n author_stats = db.get_author_stats(authorname)\n author = {'name':authorname, \"Conference\": author_stats[0], \"Journal\": author_stats[1], \"Book\": author_stats[2],\n \"Book Chapter\": author_stats[3], \"first\": author_stats[4], \"last\": author_stats[5], \"sole\": author_stats[6],\n \"Total\": author_stats[7], \"coauthors\": author_stats[8]}\n args['data'] = utils.author_all_stats_table(author)\n args['title'] = str(authorname)\n db.title_cache = args['title']\n return render_template('search_for_author.html', args=args)\n except:\n return searchPage()\n\n\ndef displayAuthorListWithHyperlinks(authors, args):\n db = app.config['DATABASE']\n \n args['title'] = \"Search result\"\n db.title_cache = args['title']\n header = [\"Author Name\"]\n data = [[author.name] for author in authors]\n args['data'] = (header, data)\n db.cache = data\n db.header_cache = header\n db.sorted_cache = [False for i in range(0, len(header))]\n return render_template('author_list.html', args=args)\n\n@app.route(\"/authors/search/author\")\ndef searchAuthorByKeyword():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n authorname = request.args.get('fname')\n \n args = {\"dataset\":dataset, \"id\":authorname}\n try:\n authors = db.search_author(authorname)\n except:\n return searchPage()\n if (len(authors) == 1):\n author_name = authors[0].name\n return getAuthorProfile(author_name)\n else:\n return displayAuthorListWithHyperlinks(authors, args)\n \n \n \n@app.route('/authors/search')\ndef searchPage():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=\"Author search\", link=\"/authors/search\")\n args = {\"dataset\":dataset, \"id\":'search'}\n args['title'] = 'Search'\n db.title_cache = args['title']\n args['data'] = '/authors/search/author'\n \n args['author_search_type'] = 'Search author'\n args['author_search_type_link'] = '/authors/search'\n args[\"breadcrump\"] = db.breadcrump\n return render_template('search.html', args=args)\n\n@app.route(\"/author\")\ndef firstlast():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n args = {\"dataset\":dataset, \"id\":'search'}\n args['title'] = 'Search'\n db.title_cache = args['title']\n args['data'] = '/author/firstlast'\n \n args['author_search_type'] = 'Number of times author appeared first or last'\n args['author_search_type_link'] = '/author'\n return render_template('search.html', args=args)\n\ndef showAllAuthorsFirstLastSole():\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n PUB_TYPES = [\"Author\", \"Journals\", \"Books\", \"Book Chapters\", \"All Publications\"]\n args = {\"dataset\":dataset, \"id\":\"coauthors\"}\n args[\"title\"] = \"Co-Authors\"\n \n db.title_cache = args['title']\n start_year = db.min_year\n if \"start_year\" in request.args:\n start_year = int(request.args.get(\"start_year\"))\n\n end_year = db.max_year\n if \"end_year\" in request.args:\n end_year = int(request.args.get(\"end_year\"))\n\n pub_type = 4\n if \"pub_type\" in request.args:\n pub_type = int(request.args.get(\"pub_type\"))\n\n args[\"data\"] = db.get_coauthor_data(start_year, end_year, pub_type)\n args[\"start_year\"] = start_year\n args[\"end_year\"] = end_year\n args[\"pub_type\"] = pub_type\n args[\"min_year\"] = db.min_year\n args[\"max_year\"] = db.max_year\n args[\"start_year\"] = start_year\n args[\"end_year\"] = end_year\n args[\"pub_str\"] = PUB_TYPES[pub_type]\n db.args_cache = args\n db.title_cache = args['title']\n return render_template(\"coauthors.html\", args=args)\n\n\n@app.route(\"/profile/\")\ndef getAuthorProfile(author):\n dataset = app.config['DATASET']\n db = app.config['DATABASE']\n db.set_breadcrump(name=author, link=\"/profile/\"+author, level=2)\n args = {\"dataset\":dataset, \"id\":\"coauthors\"}\n args['title'] = author + \" profile\"\n args['real_author_name'] = author\n \n tables = db.get_author_profile(author)\n args[\"tables\"] = tables\n args[\"breadcrump\"] = db.breadcrump \n args[\"coauthor_names_dictionary\"] = db.get_coauthor_names(author)\n \n return render_template('author_profile.html',args=args )\n","sub_path":"src/comp61542/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"460504816","text":"#!/usr/bin/env python3\nimport ctypes\nimport mmap\n\ndef load_func(filename):\n src = open(filename, \"r+b\")\n buf = mmap.mmap(src.fileno(), 0, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)\n return buf\n\ndef asm_func(buf, argtypes, restype):\n ftype = ctypes.CFUNCTYPE(*argtypes)\n fpointer = ctypes.c_void_p.from_buffer(buf)\n f = ftype(ctypes.addressof(fpointer))\n f.argtypes = argtypes\n f.restype = restype\n return f\n\nargtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_long)\nrestype = ctypes.c_long\nbuf = load_func(\"add2.bin\")\nf = asm_func(buf, argtypes, restype)\nr = f(422342, 212343, 123456789090)\nprint(r, 422342 * 212343 + 123456789090)\nbuf.close()\n","sub_path":"pyasm2.py","file_name":"pyasm2.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"553384953","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n##\n# thorlabsapt.py: Driver for the Thorlabs APT Controller.\n##\n# © 2013 Steven Casagrande (scasagrande@galvant.ca).\n#\n# This file is a part of the InstrumentKit project.\n# Licensed under the AGPL version 3.\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 published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU 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## FEATURES ####################################################################\n\nfrom __future__ import division\n\n## IMPORTS #####################################################################\n\nfrom rotational_stage import _abstract\nfrom rotational_stage import _packets\nfrom rotational_stage import _cmds\n\nfrom flufl.enum import IntEnum\n\nimport quantities as pq\n\nimport re\nimport struct\n\n## LOGGING #####################################################################\n\nimport logging\nfrom rotational_stage.util_fns import NullHandler\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(NullHandler())\n\n## CLASSES #####################################################################\n\nclass ThorLabsAPT(_abstract.ThorLabsInstrument):\n '''\n Generic ThorLabs APT hardware device controller. Communicates using the \n ThorLabs APT communications protocol, whose documentation is found in the\n thorlabs source folder.\n '''\n \n class APTChannel(object):\n '''\n Represents a channel within the hardware device. One device can have \n many channels, each labeled by an index.\n '''\n def __init__(self, apt, idx_chan):\n self._apt = apt\n # APT is 1-based, but we want the Python representation to be\n # 0-based.\n self._idx_chan = idx_chan + 1\n \n @property\n def enabled(self):\n pkt = _packets.ThorLabsPacket(message_id=_cmds.ThorLabsCommands.MOD_REQ_CHANENABLESTATE,\n param1=self._idx_chan,\n param2=0x00,\n dest=self._apt._dest,\n source=0x01,\n data=None)\n resp = self._apt.querypacket(pkt, expect=_cmds.ThorLabsCommands.MOD_GET_CHANENABLESTATE)\n return not bool(resp._param2 - 1)\n @enabled.setter\n def enabled(self, newval):\n pkt = _packets.ThorLabsPacket(message_id=_cmds.ThorLabsCommands.MOD_SET_CHANENABLESTATE,\n param1=self._idx_chan,\n param2=0x01 if newval else 0x02,\n dest=self._apt._dest,\n source=0x01,\n data=None)\n self._apt.sendpacket(pkt)\n \n _channel_type = APTChannel\n \n def __init__(self, filelike):\n super(ThorLabsAPT, self).__init__(filelike)\n self._dest = 0x50 # Generic USB device; make this configurable later.\n \n # Provide defaults in case an exception occurs below.\n self._serial_number = None\n self._model_number = None\n self._hw_type = None\n self._fw_version = None\n self._notes = \"\"\n self._hw_version = None\n self._mod_state = None\n self._n_channels = 0\n self._channel = ()\n \n # Perform a HW_REQ_INFO to figure out the model number, serial number,\n # etc.\n try:\n req_packet = _packets.ThorLabsPacket(\n message_id=_cmds.ThorLabsCommands.HW_REQ_INFO,\n param1=0x00,\n param2=0x00,\n dest=self._dest,\n source=0x01,\n data=None\n )\n hw_info = self.querypacket(req_packet, expect=_cmds.ThorLabsCommands.HW_GET_INFO)\n \n self._serial_number = str(hw_info._data[0:4]).encode('hex')\n self._model_number = str(hw_info._data[4:12]).replace('\\x00', '').strip()\n \n hw_type_int = struct.unpack(' 0:\n self._channel = list(self._channel_type(self, chan_idx) for chan_idx in xrange(self._n_channels) )\n \n @property\n def serial_number(self):\n return self._serial_number\n \n @property\n def model_number(self):\n return self._model_number\n \n @property\n def name(self):\n return \"ThorLabs APT Instrument model {model}, serial {serial} (HW version {hw_ver}, FW version {fw_ver})\".format(\n hw_ver=self._hw_version, serial=self.serial_number, \n fw_ver=self._fw_version, model=self.model_number\n )\n \n @property\n def channel(self):\n return self._channel\n \n @property\n def n_channels(self):\n return self._n_channels\n \n @n_channels.setter\n def n_channels(self, nch):\n # Change the number of channels so as not to modify those instances already existing:\n # If we add more channels, append them to the list,\n # If we remove channels, remove them from the end of the list.\n if nch > self._n_channels:\n self._channel = self._channel + \\\n list( self._channel_type(self, chan_idx) for chan_idx in xrange(self._n_channels, nch) )\n elif nch < self._n_channels:\n self._channel = self._channel[:nch]\n self._n_channels = nch\n \n def identify(self):\n '''\n Causes a light on the APT instrument to blink, so that it can be\n identified.\n '''\n pkt = _packets.ThorLabsPacket(message_id=_cmds.ThorLabsCommands.MOD_IDENTIFY,\n param1=0x00,\n param2=0x00,\n dest=self._dest,\n source=0x01,\n data=None)\n self.sendpacket(pkt)\n\nclass APTPiezoDevice(ThorLabsAPT):\n '''\n Generic ThorLabs APT piezo device, superclass of more specific piezo devices.\n '''\n \n class PiezoDeviceChannel(ThorLabsAPT.APTChannel):\n ## PIEZO COMMANDS ##\n \n @property\n def max_travel(self):\n pkt = _packets.ThorLabsPacket(message_id=_cmds.ThorLabsCommands.PZ_REQ_MAXTRAVEL,\n param1=self._idx_chan,\n param2=0x00,\n dest=self._apt._dest,\n source=0x01,\n data=None)\n resp = self._apt.querypacket(pkt)\n \n # Not all APT piezo devices support querying the maximum travel\n # distance. Those that do not simply ignore the PZ_REQ_MAXTRAVEL\n # packet, so that the response is empty.\n if resp is None:\n return NotImplemented\n \n chan, int_maxtrav = struct.unpack(' 0))\n for key, bit_mask in self.__STATUS_BIT_MASK.iteritems()\n )\n \n return status_dict\n \n @property\n def position(self):\n pkt = _packets.ThorLabsPacket(message_id=_cmds.ThorLabsCommands.MOT_REQ_POSCOUNTER,\n param1=self._idx_chan,\n param2=0x00,\n dest=self._apt._dest,\n source=0x01,\n data=None)\n response = self._apt.querypacket(pkt, expect=_cmds.ThorLabsCommands.MOT_GET_POSCOUNTER)\n chan, pos = struct.unpack('