diff --git "a/2525.jsonl" "b/2525.jsonl"
new file mode 100644--- /dev/null
+++ "b/2525.jsonl"
@@ -0,0 +1,696 @@
+{"seq_id":"91856187","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Kerem Vatandas'\nSITENAME = u'\\u03bb Kerem Vatandas \\u2192 Personal Web Site'\nSITEURL = 'http://www.keremvatandas.net'\n\nSLOGAN = u'Open source software...'\nALT_SLOGAN = u'''\nMalesef Turkiye'de yeteri kadar eleman yetistiren insan ve sirket yok...'''\n\nTHEME = 'responsive'\n\nTIMEZONE = 'Europe/Istanbul'\n\nDEFAULT_LANG = u'en'\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\n\n# Blogroll\nLINKS = (\n ('Pelican', 'http://getpelican.com/'),\n ('Python.org', 'http://python.org/'),\n ('Jinja2', 'http://jinja.pocoo.org/'),\n)\n\n# Social widget\nSOCIAL = (\n ('Twitter', 'https://twitter.com/keremvatandas', ''),\n ('Github', 'https://github.com/keremvatandas', ''),\n)\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = True\n\nSTATIC_PATHS = [\n 'images',\n 'theme/img/logo.jpg',\n]\n\nGOOGLE_ANALYTICS = 'UA-48632912-1'\nDISQUS_SITENAME = 'keremvatandas'\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"348014739","text":"'''\nFuzzy CRFのデータ作成\n'''\n\n\nclass FuzzyLabeler():\n\n def __init__(self):\n pass\n\n def read(self, read_file):\n with open(read_file, 'r') as r:\n token_list = [token for token in r]\n return token_list\n\n def split_sent(self, token_list):\n sent_list = []\n word_list = []\n for token in token_list:\n if token == '\\n':\n # sentences bounder\n sent_list.append(word_list)\n word_list = []\n else:\n # inside sentence\n word_list.append(token)\n return sent_list\n\n def fuzzy_labeling(self, sent_list):\n fuzzy_sent_list = []\n for sent in sent_list:\n fuzzy_sent = self.relabeling(sent)\n fuzzy_sent_list.append(fuzzy_sent)\n return fuzzy_sent_list\n\n def relabeling(self, sent):\n fuzzy_sent = []\n # sent is word_list\n for word in sent:\n name, gold, pred = self.extract(word)\n if gold != pred:\n # FP or FN\n label = ''\n elif gold == pred:\n label = gold\n fuzzy_word = name + ' ' + label + '\\n'\n fuzzy_sent.append(fuzzy_word)\n return fuzzy_sent\n\n def extract(self, word):\n info_list = word.split()\n name = info_list[0]\n gold = info_list[1]\n pred = info_list[2]\n return name, gold, pred\n\n def write(self, write_file, fuzzy_sent_list):\n with open(write_file, 'w') as w:\n for sent in fuzzy_sent_list:\n for fuzzy_word in sent:\n w.write(fuzzy_word)\n w.write('\\n')\n\n\ndef creating(read_file, write_file):\n labeler = FuzzyLabeler()\n token_list = labeler.read(read_file)\n sent_list = labeler.split_sent(token_list)\n fuzzy_sent_list = labeler.fuzzy_labeling(sent_list)\n labeler.write(write_file, fuzzy_sent_list)\n\n\ndef main():\n # data\n read_file = '/cl/work/shusuke-t/flair/resources/taggers/fuzzy_crf_data/test.tsv'\n write_file = '/cl/work/shusuke-t/ds_ner/fuzzy_crf/fuzzy_conllform/train_conllform.txt'\n\n # creating fuzzy data\n creating(read_file, write_file)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fuzzy_crf/src/creat_fuzzy_data.py","file_name":"creat_fuzzy_data.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"249759493","text":"# -*- encoding: utf-8 -*-\n#################################################################################\n# #\n# Copyright (C) 2009 Renato Lima - Akretion #\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\nfrom osv import osv, fields\n\n\nclass l10n_br_account_cfop(osv.osv):\n _name = 'l10n_br_account.cfop'\n _description = 'CFOP - Código Fiscal de Operações e Prestações'\n \n def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):\n if not args:\n args = []\n if context is None:\n context = {}\n ids = self.search(cr, user, ['|', ('name', operator, name), ('code', operator, name)] + args, limit=limit, context=context)\n return self.name_get(cr, user, ids, context)\n \n def name_get(self, cr, uid, ids, context=None):\n if not len(ids):\n return []\n if isinstance(ids, (int, long)):\n ids = [ids]\n reads = self.read(cr, uid, ids, ['name','code'], context, load='_classic_write')\n return [(x['id'], (x['code'] and x['code'] or '') + (x['name'] and ' - ' + x['name'] or '')) \\\n for x in reads]\n\n _columns = {\n 'code': fields.char('Código', size=4, requeried=True),\n 'name': fields.char('Nome', size=256, requeried=True),\n 'small_name': fields.char('Nome Reduzido', size=32, requeried=True),\n 'description': fields.text('Descrição'),\n 'type': fields.selection([('input', 'Entrada'), ('output', 'Saida')], 'Tipo', requeried=True),\n 'parent_id': fields.many2one('l10n_br_account.cfop', 'CFOP Pai'),\n 'child_ids': fields.one2many('l10n_br_account.cfop', 'parent_id', 'CFOP Filhos'),\n 'internal_type': fields.selection([('view', 'Visualização'), ('normal', 'Normal')], 'Tipo Interno', required=True),\n }\n\n _defaults = {\n 'internal_type': 'normal',\n }\n\nl10n_br_account_cfop()\n\n\nclass l10n_br_account_service_type(osv.osv):\n _name = 'l10n_br_account.service.type'\n _description = 'Cadastro de Operações Fiscais de Serviço'\n\n _columns = {\n 'code': fields.char('Código', size=16, required=True),\n 'name': fields.char('Descrição', size=256, required=True),\n 'parent_id': fields.many2one('l10n_br_account.service.type', 'Tipo de Serviço Pai'),\n 'child_ids': fields.one2many('l10n_br_account.service.type', 'parent_id', 'Tipo de Serviço Filhos'),\n 'country_id': fields.many2one('res.country', 'País'),\n 'state_id': fields.many2one('res.country.state', 'Estado'),\n 'l10n_br_city_id': fields.many2one('l10n_br_base.city', 'Município'),\n 'internal_type': fields.selection([('view', 'Visualização'), ('normal', 'Normal')], 'Tipo Interno', required=True),\n }\n\n _defaults = {\n 'internal_type': 'normal',\n }\n \n def name_get(self, cr, uid, ids, context=None):\n if not ids:\n return []\n reads = self.read(cr, uid, ids, ['name', 'code'], context=context)\n res = []\n for record in reads:\n name = record['name']\n if record['code']:\n name = record['code'] + ' - '+name\n res.append((record['id'], name))\n return res\n\nl10n_br_account_service_type()\n\n\nclass l10n_br_account_fiscal_document(osv.osv):\n _name = 'l10n_br_account.fiscal.document'\n _description = 'Tipo de Documento Fiscal'\n\n _columns = {\n 'code': fields.char('Codigo', size=8,required=True),\n 'name': fields.char('Descrição', size=64),\n 'nfe': fields.boolean('NFe'),\n }\n\nl10n_br_account_fiscal_document()\n\n\nclass l10n_br_account_fiscal_operation_category(osv.osv):\n _name = 'l10n_br_account.fiscal.operation.category'\n _description = 'Categoria de Operações Fiscais'\n\n _columns = {\n 'code': fields.char('Código', size=24, required=True),\n 'name': fields.char('Descrição', size=64),\n 'type': fields.selection([('input', 'Entrada'), ('output', 'Saida')], 'Tipo'),\n 'journal_ids': fields.many2many('account.journal', 'l10n_br_account_fiscal_operation_category_rel',\n 'fiscal_operation_category_id', 'journal_id', 'Consolidated Children'),\n 'use_sale' : fields.boolean('Usado em Vendas'),\n 'use_invoice' : fields.boolean('Usado nas Notas Fiscais'),\n 'use_purchase' : fields.boolean('Usado nas Compras'),\n 'use_picking' : fields.boolean('Usado nas Listas de Separações'),\n 'fiscal_type': fields.selection([('product', 'Produto'), ('service', 'Serviço')], 'Tipo Fiscal', requeried=True),\n }\n\n _defaults = {\n 'type': 'output',\n 'fiscal_type': 'product',\n }\n\nl10n_br_account_fiscal_operation_category()\n\n\nclass l10n_br_account_fiscal_operation(osv.osv):\n _name = 'l10n_br_account.fiscal.operation'\n _description = 'Operações fiscais'\n\n _columns = {\n 'code': fields.char('Código', size=16, required=True),\n 'name': fields.char('Descrição', size=64),\n 'type': fields.selection([('input', 'Entrada'), ('output', 'Saida')], 'Tipo', requeried=True),\n 'fiscal_operation_category_id': fields.many2one('l10n_br_account.fiscal.operation.category', 'Categoria',\n domain=\"[('type','=',type)]\", requeried=True),\n 'fiscal_document_id': fields.many2one('l10n_br_account.fiscal.document', 'Documento Fiscal', requeried=True),\n 'fiscal_operation_line': fields.one2many('l10n_br_account.fiscal.operation.line', 'fiscal_operation_id', \n 'Fiscal Operation Lines'),\n 'cfop_id': fields.many2one('l10n_br_account.cfop', 'CFOP'),\n 'service_type_id': fields.many2one('l10n_br_account.service.type', 'Tipo de Serviço'),\n 'use_sale' : fields.boolean('Usado em Vendas'),\n 'use_invoice' : fields.boolean('Usado nas Notas Fiscais'),\n 'use_purchase' : fields.boolean('Usado nas Compras'),\n 'use_picking' : fields.boolean('Usado nas Listas de Separações'),\n 'refund_fiscal_operation_id': fields.many2one('l10n_br_account.fiscal.operation', 'Op. Fiscal Devolução',\n domain=\"[('type','!=',type)]\" ),\n 'note': fields.text('Observação'),\n 'inv_copy_note': fields.boolean('Copiar Observação na Nota Fiscal'),\n 'fiscal_type': fields.selection([('product', 'Produto'), ('service', 'Serviço')], 'Tipo Fiscal',\n domain=\"[('fiscal_type','=',fiscal_type)]\", requeried=True),\n 'asset_operation': fields.boolean('Operação de Aquisição de Ativo', \n help=\"Caso seja marcada essa opção, será incluido o IPI na base de calculo do ICMS.\")\n }\n\n _defaults = {\n 'type': 'output',\n 'fiscal_type': 'product',\n 'fiscal_type': False,\n }\n\nl10n_br_account_fiscal_operation()\n\n\nclass l10n_br_account_fiscal_operation_line(osv.osv):\n _name = 'l10n_br_account.fiscal.operation.line'\n _description = 'Linhas das operações ficais'\n\n _columns = {\n 'company_id': fields.many2one('res.company', 'Empresa', requeried=True),\n 'fiscal_classification_id': fields.many2one('account.product.fiscal.classification', 'NCM'),\n 'tax_code_id': fields.many2one('account.tax.code', 'Código do Imposto', requeried=True, \n domain=\"['|',('company_id','=',False),('company_id','=',company_id)]\"),\n 'cst_id': fields.many2one('l10n_br_account.cst', 'Código de Situação Tributária', requeried=True),\n 'fiscal_operation_id': fields.many2one('l10n_br_account.fiscal.operation', 'Fiscal Operation Ref', \n ondelete='cascade', select=True),\n 'cfop_id': fields.many2one('l10n_br_account.cfop', 'CFOP') \n }\n\nl10n_br_account_fiscal_operation_line()\n\n\nclass l10n_br_account_document_serie(osv.osv):\n _name = 'l10n_br_account.document.serie'\n _description = 'Serie de documentos fiscais'\n \n _columns = {\n 'code': fields.char('Código', size=3, required=True),\n 'name': fields.char('Descrição', size=64, required=True),\n 'fiscal_document_id': fields.many2one('l10n_br_account.fiscal.document', 'Documento Fiscal', required=True),\n 'company_id': fields.many2one('res.company', 'Company', required=True),\n 'active':fields.boolean('Active'),\n 'fiscal_type': fields.selection([('product', 'Product'), ('service', 'Service')], 'Tipo Fiscal', required=True),\n 'internal_sequence_id': fields.many2one('ir.sequence', 'Sequência Interna'),\n }\n\n _defaults = {\n \t 'active': True,\n\t\t 'fiscal_type': 'product',\n }\n \n def create_sequence(self, cr, uid, vals, context=None):\n \"\"\" Create new no_gap entry sequence for every new document serie\n \"\"\"\n seq = {\n 'name': vals['name'],\n 'implementation':'no_gap',\n 'padding': 1,\n 'number_increment': 1\n }\n if 'company_id' in vals:\n seq['company_id'] = vals['company_id']\n return self.pool.get('ir.sequence').create(cr, uid, seq)\n\n def create(self, cr, uid, vals, context=None):\n \"\"\" Overwrite method to create a new ir.sequence if this field is null\n \"\"\"\n if not 'internal_sequence_id' in vals or not vals['internal_sequence_id']:\n vals.update({'internal_sequence_id': self.create_sequence(cr, uid, vals, context)})\n return super(l10n_br_account_document_serie, self).create(cr, uid, vals, context)\n\nl10n_br_account_document_serie()\n\n\nclass l10n_br_account_partner_fiscal_type(osv.osv):\n _name = 'l10n_br_account.partner.fiscal.type'\n _description = 'Tipo Fiscal de Parceiros'\n\n _columns = {\n 'code': fields.char('Código', size=16, required=True),\n 'name': fields.char('Descrição', size=64),\n 'tipo_pessoa': fields.selection([('F', 'Física'), ('J', 'Jurídica')], 'Tipo de pessoa', required=True),\n 'icms': fields.boolean('Recupera ICMS'),\n 'ipi':fields.boolean('Recupera IPI'), \n }\n\nl10n_br_account_partner_fiscal_type()\n\n\nclass l10n_br_account_cnae(osv.osv):\n _name = 'l10n_br_account.cnae'\n _description = 'Cadastro de CNAE'\n \n def name_get(self, cr, uid, ids, context=None):\n if not ids:\n return []\n reads = self.read(cr, uid, ids, ['name', 'code'], context=context)\n res = []\n for record in reads:\n name = record['name']\n if record['code']:\n name = record['code'] + ' - '+name\n res.append((record['id'], name))\n return res\n\n _columns = {\n 'code': fields.char('Código', size=16, required=True),\n 'name': fields.char('Descrição', size=64, required=True),\n 'version': fields.char('Versão', size=16, required=True),\n 'parent_id': fields.many2one('l10n_br_account.cnae', 'CNAE Pai'),\n 'child_ids': fields.one2many('l10n_br_account.cnae', 'parent_id', 'CNAEs Filhos'),\n 'internal_type': fields.selection([('view', 'Visualização'), ('normal', 'Normal')], 'Tipo Interno', required=True),\n }\n _defaults = {\n 'internal_type': 'normal',\n }\n\nl10n_br_account_cnae()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","sub_path":"l10n_br_account/l10n_br_account.py","file_name":"l10n_br_account.py","file_ext":"py","file_size_in_byte":12896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"612228550","text":"\"\"\"\nAuthor: Eleven\nDate: 2020/10/09\nDescription: What’s New In Python 3.9\nRef. https://docs.python.org/3.9/whatsnew/3.9.html\n\"\"\"\n\nfrom collections import ChainMap\n\n\ndef PEP584():\n \"\"\"Add Union Operators To dict\n https://www.python.org/dev/peps/pep-0584/\n\n \"\"\"\n d1 = {\"str_key\": 1}\n d2 = {\"str_key\": 11, 123: 2}\n # dict(d1, **d2) # error\n merged = ChainMap(d2, d1)\n print(merged)\n\n # merge two dicts with str keys\n d3 = {\"str_key_2\": 2}\n print(dict(d1, **d3)) # ac\n\n # merge two dicts with \"or\" operator\n print(d1|d2)\n print(d2|d1)\n\n\ndef PEP448():\n \"\"\"Additional Unpacking Generalizations\n https://www.python.org/dev/peps/pep-0448/\n\n \"\"\"\n return\n\n\nPEP584()\n","sub_path":"example_code/item_02.py","file_name":"item_02.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"582405144","text":"\ndef containsCommonItem(arr1, arr2):\n for i in range(len(arr1)):\n for j in range(len(arr2)):\n if arr1[i] == arr2[j]:\n return True\n return False\n # O(a*b) Time Complexity\n # O(1) Space Complexity\n\narr1 = ['a', 'b', 'c', 'x']\narr2 = ['z', 'y', 'x']\n\nres = containsCommonItem(arr1, arr2)\n# print(res)\n\n# BETTER APPROACH\n\n\ndef containsCommonItem2(arr1, arr2):\n map = {}\n for i in range(len(arr1)):\n if not map.get(i, False):\n item = arr1[i]\n map[item] = True\n print(map)\n for j in range(len(arr2)):\n if map.get(arr2[j], False):\n return True\n return False\n # O(a+b) Time Complexity\n # O(a) Space Complexity Since a new map (DICTIONARY) of size a (length of arr1) is created.\n\nres = containsCommonItem2(arr1, arr2)\nprint(res)","sub_path":"src/Random/interview.py","file_name":"interview.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"26789461","text":"from General_functions import *\n\ndef PC_equations():\n eqs_PC = \"\"\"\n dv/dt = (gL*(EL - v) + gL*DeltaT*exp((v - VT)/DeltaT) + I_Noise + I_intrinsic -w)/C : volt\n dw/dt = (a*(v - EL) - w)/(tauw) : amp\n\n I_intrinsic : amp\n I_Noise : amp \n I_Noise_empty : amp\n \n C : farad\n gL : siemens \n EL : volt\n VT : volt\n DeltaT : volt\n Vcut : volt\n tauw : second\n a : siemens\n b : ampere\n Vr : volt\n \n New_recent_rate = recent_rate+try_new_bcm : Hz\n recent_rate : Hz\n dtry_new_bcm/dt = -try_new_bcm/(50*ms) : Hz\n \"\"\"\n return eqs_PC\n\n\ndef PC_neurons(N_Cells_PC,PC_Values,dt,dt_rec):\n eqs_PC = PC_equations()\n PC = NeuronGroup(N_Cells_PC, model = eqs_PC, threshold='v>Vcut', reset=\"v=Vr; w+=b\", method='euler', dt=dt)\n \n for jj in range(0,N_Cells_PC,1):\n PC.C[jj] = PC_Values[\"PC_C\"].item()[jj]*pF\n PC.gL[jj] = PC_Values[\"PC_gL\"].item()[jj]*nS\n PC.EL[jj] = PC_Values[\"PC_EL\"].item()[jj]*mV\n PC.VT[jj] = PC_Values[\"PC_VT\"].item()[jj]*mV\n PC.DeltaT[jj] = PC_Values[\"PC_DeltaT\"].item()[jj]*mV\n PC.Vcut[jj] = PC.VT[jj] + 5*PC.DeltaT[jj]\n PC.tauw[jj] = PC_Values[\"PC_tauw\"].item()[jj]*ms\n PC.a[jj] = PC_Values[\"PC_a\"].item()[jj]*nS\n PC.b[jj] = PC_Values[\"PC_b\"].item()[jj]*nA\n PC.Vr[jj] = PC_Values[\"PC_Vr\"].item()[jj]*mV\n PC.I_Noise[jj] = 0.5*nA\n PC.v[jj] = PC_Values[\"PC_v\"].item()[jj]*mV\n PC.I_intrinsic[jj] = PC_Values[\"PC_I_intrinsic\"].item()[jj]*nA\n\n PC_Statemon = StateMonitor(PC, variables = ['v', 'w', 'I_Noise','I_Noise_empty','I_intrinsic','tauw','recent_rate','New_recent_rate'], record=True, dt=dt_rec)\n PC_Spikemon = SpikeMonitor(PC)\n PC_rate = PopulationRateMonitor(PC)\n\n return PC, PC_Statemon, PC_Spikemon, PC_rate\n\n\ndef PC_plot_neurons(N_Cells_PC, PC_Statemon, PC_Spikemon, dt_rec):\n plt.figure(figsize=(14, 5), dpi= 80, facecolor='w', edgecolor='k')\n for ii in range(0,N_Cells_PC):\n vm = PC_Statemon[ii].v[:]\n for t in PC_Spikemon.t:\n i = int(t / dt_rec)\n vm[i] = 20*mV\n plot(PC_Statemon.t/ms,vm/mV, label='PC_'+str(ii+1))\n title('Membrane Potential for '+str(N_Cells_PC)+\" cells\")\n ylabel('V [mV]')\n xlabel('Time [ms]')\n legend()\n show()\n\ndef PC_plot_current(N_Cells_PC, N_Noise, PC_Statemon, PC_Spikemon, dt_rec):\n plt.figure(figsize=(14, 5), dpi= 80, facecolor='w', edgecolor='k')\n for ii in range(0,N_Cells_PC):\n plot(PC_Statemon.t/ms,PC_Statemon.I_Noise[ii]/nA, label='PSC_Cell'+str(ii+1))\n title('Post synaptic current for '+str(N_Cells_PC)+\" cells and \"+str(N_Noise)+\" sources\")\n ylabel('V [mV]')\n xlabel('Time [ms]')\n legend()\n show()","sub_path":"Code/2021/LabTalk/Functions/PC_functions.py","file_name":"PC_functions.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"521136993","text":"import pygame as pg\nfrom settings import *\nfrom game import *\n\nclass GameLoop:\n def __init__(self):\n self.clock = pg.time.Clock()\n pg.key.set_repeat(500, 100)\n\n def run(self, game, player):\n # game loop - set self.playing = False to end the game\n self.playing = True\n while self.playing:\n self.dt = self.clock.tick(FPS) / 1000\n self.events(player)\n game.update()\n game.draw()\n\n def events(self, player):\n # catch all events here\n for event in pg.event.get():\n if event.type == pg.QUIT:\n self.quit()\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n self.quit()\n if event.key == pg.K_LEFT:\n player.move(dx=-1)\n if event.key == pg.K_RIGHT:\n player.move(dx=1)\n if event.key == pg.K_UP:\n player.move(dy=-1)\n if event.key == pg.K_DOWN:\n player.move(dy=1)\n\n def quit(self):\n pg.quit()\n sys.exit()\n\n","sub_path":"gameLoop.py","file_name":"gameLoop.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"201810290","text":"# encoding=utf8\n# !/usr/bin/python\nimport requests\nfrom bs4 import BeautifulSoup\nfrom requests.adapters import HTTPAdapter\nimport time\nimport js2py\nimport re\n\n# execute this commands before run this script\n\n# pip install beautifulsoup4\n# pip install js2py\n# pip install request\n\n# update your userids\npushurl = 'https://api.telegram.org/bot969014158:AAErfGwxgELxhWhSRDUl3SjqghJOtics_Z9/sendMessage?parse_mode=HTML&disable_web_page_preview=1&chat_id=-1001379644046&text='\n\n\ndef getcookies():\n url = 'https://www.hostloc.com/forum.php?mod=forumdisplay&fid=45&filter=author&orderby=dateline'\n js = js2py.EvalJs()\n headers = {\n 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'}\n\n try:\n aesjs = requests.get(\"https://www.hostloc.com/aes.min.js\", headers=headers, timeout=5).text\n except Exception as e:\n print ('ReturnNothing')\n return 'ReturnNothing'\n # print aesjs\n if('www.hostloc.com' in aesjs):\n print ('ReturnNothing')\n return 'ReturnNothing'\n js.execute(aesjs)\n getcookie = requests.get(url).text\n # print getcookie\n getcookie_script = re.findall(\"\", getcookie)\n js.execute(getcookie_script[0].split(\"document\")[0])\n data = js.toHex(js.slowAES.decrypt(js.c, 2, js.a, js.b))\n cookie = \"L7DFW=\" + data\n print (cookie)\n return cookie\n\n\ndef getnewesttitle():\n url = 'https://www.hostloc.com/forum.php?mod=forumdisplay&fid=45&filter=author&orderby=dateline'\n headers = {\n 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'}\n\n requests.adapters.DEFAULT_RETRIES = 5\n s = requests.session()\n s.keep_alive = False\n\n result = 'L7DFW' in cookiestr\n print (result)\n if (result):\n print ('hostloc start AES Decrypt ... ')\n headers = {'Cookie': cookiestr,\n 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'}\n r = s.get(url, headers=headers)\n else:\n r = s.get(url, headers=headers)\n\n soup = BeautifulSoup(r.text, 'html.parser')\n newest = soup.find('span', class_='by')\n # print newest.text\n author = newest.text\n title = newest.parent.text.replace(author,'')\n\n pid = r.text[r.text.find('tid') + 4:r.text.find('tid') + 10]\n post_url = \"https://www.hostloc.com/thread-{}-1-1.html\".format(pid)\n\n # print post_url\n print ('monitor is runing ,please wait for a monent')\n\n resultArr = [title, post_url, author]\n return resultArr\n\n\ndef sendmessage(newesttitle, postUrl, author):\n nowtime = time.strftime(\"%m-%d %H:%M:%S\", time.localtime())\n # finalUrl = pushurl+ newesttitle + '&url=' + postUrl\n finalUrl = pushurl + 'hostloc新帖提醒' + '\\n' + nowtime + ' ' + author + '' + newesttitle + ''\n\n requests.adapters.DEFAULT_RETRIES = 5\n s = requests.session()\n s.keep_alive = False\n s.get(finalUrl)\n\n print('send a new message to wechat')\n\n\ncookiestr = getcookies()\nfirstArr = getnewesttitle()\nnewesttitle = firstArr[0]\nsendmessage(firstArr[0], firstArr[1], firstArr[2])\nwhile True:\n try:\n time.sleep(30)\n try:\n newArr = getnewesttitle()\n finally:\n time.sleep(5)\n pass\n thenexttitle = newArr[0]\n postUrl = newArr[1]\n author = newArr[2]\n print('monitoring...')\n print('old message is ' + newesttitle.encode('utf-8').decode())\n print('new message is ' + thenexttitle.encode('utf-8').decode())\n print(postUrl.encode('utf-8').decode())\n if thenexttitle != newesttitle:\n newesttitle = thenexttitle\n print('find new message ,reading....')\n sendmessage(thenexttitle, postUrl,author)\n\n pass\n else:\n pass\n except RuntimeError:\n print(RuntimeError)\n pass\n","sub_path":"hostloc2tg.py","file_name":"hostloc2tg.py","file_ext":"py","file_size_in_byte":4105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"593705910","text":"#!/usr/bin/env python3\n# -*- coding:UTF-8 -*-\n\n################################################################################\n#\n# Copyright 2010-2015 Carlos Ramisch, Vitor De Araujo, Silvio Ricardo Cordeiro,\n# Sandra Castellanos\n#\n# ft_xml.py is part of mwetoolkit\n#\n# mwetoolkit is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# mwetoolkit is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with mwetoolkit. If not, see .\n#\n################################################################################\n\"\"\"\nThis module provides classes to manipulate files that are\nencoded in mwetoolkit's \"XML\" filetype.\n\nYou should use the methods in package `filetype` instead.\n\"\"\"\n\n\nimport collections\nimport itertools\nfrom xml.etree import ElementTree\nimport pyexpat as expat\n\nfrom . import _common as common\nfrom ..base.word import Word\nfrom ..base.sentence import SentenceFactory\nfrom ..base.candidate import Candidate, CandidateFactory\nfrom ..base.entry import Entry\nfrom ..base.mweoccur import MWEOccurrence\nfrom ..base.ngram import Ngram\nfrom ..base.frequency import Frequency\nfrom ..base.feature import Feature\nfrom ..base.tpclass import TPClass\nfrom ..base.meta import Meta\nfrom ..base.corpus_size import CorpusSize\nfrom ..base.meta_feat import MetaFeat\nfrom ..base.meta_tpclass import MetaTPClass\nfrom ..base import patternlib\nfrom .. import util\n\n\n\n################################################################################\n\n\nclass XMLInfo(common.FiletypeInfo):\n r\"\"\"FiletypeInfo subclass for mwetoolkit's XML.\"\"\"\n description = \"An XML in mwetoolkit format (dtd/mwetoolkit-*.dtd)\"\n filetype_ext = \"XML\"\n\n # Used to escape (but not to unescape!) XML files\n escaper = common.Escaper(\"&\", \";\", [\n # We don't escape \"'\", as it's useless and e.g. \"walk's\" is ugly :p\n (\"&\", \"&\"), (\"\\\"\", \""\"), (\"<\", \"<\"), (\">\", \">\"),\n (\"\\n\", \"
\"), (\"\\t\", \" \")\n ])\n\n def operations(self):\n return common.FiletypeOperations(XMLChecker, XMLParser, XMLPrinter)\n\n\nINFO = XMLInfo()\n\n################################################################################\n\nclass XMLChecker(common.AbstractChecker):\n r\"\"\"Checks whether input is in XML format.\"\"\"\n def matches_header(self, strict):\n header = self.fileobj.peek(300)\n if header.startswith(b\"\\xef\\xbb\\xbf\"):\n header = header[3:] # remove utf8's BOM\n return (header.startswith(b\"' in header\n\n\n\n################################################################################\n\nXML_HEADER = \"\"\"\n\n\n<{category} {ns}>\"\"\"\n\nXML_FOOTER = \"\"\"{category}>\"\"\"\n\n\nclass XMLPrinter(common.AbstractPrinter):\n \"\"\"Instances can be used to print XML objects.\"\"\"\n valid_categories = [\"dict\", \"corpus\", \"candidates\", \"patterns\"]\n\n def __init__(self, ctxinfo, *args, **kwargs):\n super(XMLPrinter, self).__init__(ctxinfo, *args, **kwargs)\n self.serializer = XMLSerializer(\n self.add_string, self.filetype_info.escaper)\n self.add_string(ctxinfo, XML_HEADER.format(\n category=self._category, ns=\"\"), \"\\n\")\n self._printed_filetype_directive = True\n\n def finish(self, ctxinfo):\n self.add_string(ctxinfo, XML_FOOTER.format(\n category=self._category), \"\\n\")\n super(XMLPrinter, self).finish(ctxinfo)\n\n def handle_comment(self, comment, ctxinfo):\n self.serializer.serialize(ctxinfo, comment)\n\n def handle_pattern(self, pattern, ctxinfo):\n self.serializer.serialize(ctxinfo, pattern)\n\n def _fallback(self, obj, ctxinfo):\n self.serializer.serialize(ctxinfo, obj)\n\n\n\nXML_INDENT_LEVEL = 4\n\nclass XMLSerializer(common.ObjSerializer):\n r\"\"\"Instances can serialize objects into XML.\"\"\"\n\n def serialize_Comment(self, ctxinfo, comment, indent=0):\n # XML does not demand escaping inside comments\n # (instead, they forbid the substring \"--\"... Pfff)\n comment_s = str(comment).replace(\"--\", \"–\")\n self.add_string(ctxinfo, \" \"*indent,\n \"\\n\")\n\n\n def serialize_Word(self, ctxinfo, word, indent=0):\n self.add_string(ctxinfo, \"\")\n else:\n self.add_string(ctxinfo, \" >\")\n self.serialize(ctxinfo, word.freqs, indent=0)\n self.add_string(ctxinfo, \"\")\n ctxinfo.check_all_popped(props)\n\n\n def serialize_Candidate(self, ctxinfo, candidate, indent=0):\n subindent = indent + XML_INDENT_LEVEL\n subsubindent = indent + 2*XML_INDENT_LEVEL\n\n self.add_string(ctxinfo, \"\\n\")\n self.serialize_Ngram(ctxinfo, candidate, indent=subindent)\n\n if candidate.bigrams:\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n for bigram in self.bigrams :\n self.serialize(ctxinfo, bigram, indent=subsubindent)\n self.add_string(ctxinfo, \"\\n\")\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n\n if candidate.occurs:\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n for mweoccur in candidate.occurs:\n # TODO adapt to use subsubindent (need to fix tests)\n self.serialize(ctxinfo, mweoccur, indent=subindent)\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n\n if candidate.vars:\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n for var in self.vars:\n self.serialize(ctxinfo, var, indent=subsubindent)\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n\n if candidate.features:\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n self.serialize(ctxinfo, candidate.features,\n indent=subsubindent, after_each=\"\\n\")\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n\n if candidate.tpclasses:\n self.serialize(ctxinfo, candidate.tpclasses,\n indent=subindent, after_each=\"\\n\")\n\n self.add_string(ctxinfo, \"\\n\")\n\n\n def serialize_Sentence(self, ctxinfo, sentence, indent=0):\n subindent = indent + XML_INDENT_LEVEL\n self.add_string(ctxinfo, \"\")\n\n for word in sentence.word_list:\n self.serialize(ctxinfo, word)\n self.add_string(ctxinfo, \" \")\n\n if sentence.mweoccurs:\n self.add_string(ctxinfo, \"\\n\\n\")\n for mweoccur in sentence.mweoccurs:\n self.add_string(ctxinfo, \" \") # TODO replace by subindent\n self.serialize(ctxinfo, mweoccur)\n self.add_string(ctxinfo, \"\\n\")\n self.add_string(ctxinfo, \"\\n\")\n self.add_string(ctxinfo, \"\\n\")\n\n\n def serialize_Entry(self, ctxinfo, entry, indent=0):\n subindent = indent + XML_INDENT_LEVEL\n subsubindent = indent + XML_INDENT_LEVEL\n self.add_string(ctxinfo, \" \"*indent, \"\")\n self.helper_serialize_Ngram(ctxinfo, ngram, indent=indent)\n\n if entry.features:\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n self.serialize(ctxinfo, entry.features, indent=subsubindent)\n self.add_string(ctxinfo, \" \"*subindent, \"\\n\")\n self.add_string(ctxinfo, \"\\n\")\n\n\n def serialize_Ngram(self, ctxinfo, ngram, indent=0):\n self.add_string(ctxinfo, \" \"*indent, \"\")\n self.helper_serialize_Ngram(ctxinfo, ngram, indent=indent)\n self.add_string(ctxinfo, \"\\n\")\n\n\n def helper_serialize_Ngram(self, ctxinfo, ngram, indent=0):\n subindent = indent + XML_INDENT_LEVEL\n for word in ngram:\n self.serialize(ctxinfo, word, indent=subindent)\n self.add_string(ctxinfo, \" \")\n\n self.serialize(ctxinfo, ngram.freqs, indent=0)\n\n if len(ngram.sources) > 0:\n sources_string = ';'.join(str(s) for s in ngram.sources)\n self.add_string(ctxinfo, '' % sources_string)\n\n\n def serialize_Meta(self, ctxinfo, meta, indent=0):\n subindent = indent + XML_INDENT_LEVEL\n self.add_string(ctxinfo, \"\\n\")\n self.serialize(ctxinfo, meta.corpus_sizes,\n indent=subindent, after_each=\"\\n\")\n for meta_feat in meta.meta_feats:\n self.serialize(ctxinfo, meta_feat, indent=subindent)\n for meta_tpclass in meta.meta_tpclasses:\n self.serialize(ctxinfo, meta_tpclass, indent=subindent)\n self.add_string(ctxinfo, \"\\n\")\n\n\n def serialize_MetaFeat(self, ctxinfo, metafeat, indent=0):\n self.add_string(ctxinfo, \" \"*indent,\n \"<\", metafeat.xml_class, \" name=\\\"\",\n self.escape(metafeat.name), \"\\\" type=\\\"\",\n self.escape(metafeat.feat_type), \"\\\" />\\n\")\n\n # XXX remove MetaTPClass? It's a glorified subclass of MetaFeat...\n serialize_MetaTPClass = serialize_MetaFeat\n\n\n def serialize_FeatureSet(self, ctxinfo, featset,\n indent=0, after_each=\"\"):\n # Handle , , , \n for featname, value in sorted(featset._dict.items()):\n value = util.portable_float2str(value)\n self.add_string(ctxinfo, \" \"*indent, \"<\", featset._xml_class,\n \" name=\\\"\", self.escape(featname), \"\\\" value=\\\"\",\n self.escape(str(value)), \"\\\" />\", after_each)\n\n\n def serialize_MWEOccurrence(self, ctxinfo, mweoccur, indent=0):\n self.add_string(ctxinfo, \"\")\n\n # For each (candidate index, sentence index)...\n for c_i, s_i in enumerate(mweoccur.indexes):\n self.add_string(ctxinfo, \"\")\n self.add_string(ctxinfo, \"\")\n\n\n def serialize_EitherPattern(self, ctxinfo, pattern, indent=0):\n \"\"\"Format the either pattern into XML.\"\"\"\n self.add_string(ctxinfo, \" \"*indent, '\\n')\n for subpattern in pattern.subpatterns:\n self.serialize(ctxinfo, subpattern,\n indent=indent+XML_INDENT_LEVEL)\n self.add_string(ctxinfo, \" \"*indent, '\\n')\n\n\n def serialize_SequencePattern(self, ctxinfo, pattern, indent=0):\n \"\"\"Format the sequence pattern into XML.\"\"\"\n self.add_string(ctxinfo, \" \"*indent, \"\\n\")\n for subpattern in pattern.subpatterns:\n self.serialize(ctxinfo, subpattern,\n indent=indent+XML_INDENT_LEVEL)\n self.add_string(ctxinfo, \" \"*indent, '\\n')\n\n\n def serialize_WordPattern(self, ctxinfo, pattern, indent=0):\n \"\"\"Format the word pattern into XML.\"\"\"\n self.add_string(ctxinfo, \" \"*indent, \"\")\n\n for k, values in sorted(pattern.negative_props.items()):\n if self.check_xml_pat_prop(ctxinfo, k):\n for v in values:\n self.add_string(ctxinfo, \"\")\n self.add_string(ctxinfo, \"\\n\")\n\n\n def check_xml_pat_prop(self, ctxinfo, propname):\n if propname.startswith(\"\u001B[\"): # Behave nicely with for view.py\n propname = propname.split(\"m\", 1)[1]\n if propname.endswith(\"m\"): # Behave nicely with for view.py\n propname = propname.rsplit(\"\u001B\", 1)[0]\n\n if propname in patternlib.CLASSICAL_PAT_PROPS:\n return True\n ctxinfo.warn(\"Skipping unsupported propname \" \\\n \"`{propname}`\", propname=propname)\n\n\n def serialize_RegexProp(self, ctxinfo, wordprop, indent=0):\n self.add_string(ctxinfo, \"\\\"\", self.escape(wordprop.value),\n \"\\\" style=\\\"regex\\\"\")\n if wordprop.flags:\n self.add_string(ctxinfo, \" flags=\\\"{}\\\"\".format(wordprop.flags))\n\n def serialize_StarredWildcardProp(self, ctxinfo, wordprop, indent=0):\n self.add_string(ctxinfo, \"\\\"\", self.escape(wordprop.value), \"\\\"\")\n if \"*\" in wordprop.value:\n self.add_string(ctxinfo, \" style=\\\"starred-wildcard\\\"\")\n\n def serialize_LiteralProp(self, ctxinfo, wordprop, indent=0):\n self.add_string(ctxinfo, \"\\\"\", self.escape(wordprop.value), \"\\\"\")\n if \"*\" in wordprop.value:\n self.add_string(ctxinfo, \" style=\\\"literal\\\"\")\n\n def serialize_BackrefProp(self, ctxinfo, wordprop, indent=0):\n self.add_string(ctxinfo, \"\\\"back:\", self.escape(wordprop.w_strid),\n \".\", self.escape(wordprop.prop), \"\\\"\")\n\n\n\n\n\n################################################################################\n\nclass XMLParser(common.AbstractParser):\n r\"\"\"Instances of this class parse the mwetoolkit XML format,\n calling the `handler` for each object that is parsed.\n \"\"\"\n valid_categories = [\"dict\", \"corpus\", \"candidates\", \"patterns\"]\n\n\n def _parse_file(self):\n xmlparser = iter(IterativeXMLParser(self.inputobj, self))\n if not self.inputobj.peek_bytes(10).startswith(b\" cannot appear after first line!\")\n self.latest_ctxinfo.warn(\"XML file should start with tag!\")\n\n already_seen = []\n\n for xmlevent in xmlparser:\n if xmlevent.event_str == \"start\":\n already_seen.append(xmlevent) # XXX MOVE ABOVE TEST FOR \"start\"\n if xmlevent.elem.tag != ElementTree.Comment:\n if xmlevent.elem.tag == \"dict\":\n delegate = self.parse_dict\n elif xmlevent.elem.tag == \"corpus\":\n delegate = self.parse_corpus\n elif xmlevent.elem.tag == \"candidates\":\n delegate = self.parse_candidates\n elif xmlevent.elem.tag == \"patterns\":\n delegate = self.parse_patterns\n else:\n self.ctxinfo.error(\"Bad top-level XML elem: {tag!r}\" \\\n .format(tag=xmlevent.elem.tag))\n\n self.inputobj.category = xmlevent.elem.tag\n with common.ParsingContext(self):\n it = itertools.chain(already_seen, xmlparser)\n delegate(it)\n\n\n\n def unknown_end_elem(self, xmlevent):\n r\"\"\"Complain about unknown XML element.\"\"\"\n if xmlevent.elem.tag == ElementTree.Comment:\n comment = common.Comment(xmlevent.elem.text.strip())\n self.handler.handle_comment(comment, xmlevent.ctxinfo)\n else:\n xmlevent.ctxinfo.warn(\"Ignoring unexpected XML elem: <{tag}>\",\n tag=xmlevent.elem.tag)\n\n\n #######################################################\n def _parse_wordelem2props(self, ctxinfo, elem):\n props = {}\n for key in (\"surface\", \"lemma\", \"pos\", \"syn\"):\n try:\n value = elem.attrib.pop(key)\n except KeyError:\n pass # Input does not assign to this key\n else:\n if not value:\n ctxinfo.warn('Ignoring empty attribute: {attr}=\"\"', attr=key)\n else:\n props[key] = value\n\n for key in elem.attrib:\n ctxinfo.warn(\"Invalid word attribute: {attr!r}\", attr=key)\n return props\n\n\n\n #######################################################\n def parse_corpus(self, inner_iterator):\n sentence_factory = SentenceFactory()\n sentence = None\n\n for xmlevent in inner_iterator:\n if xmlevent.event_str == \"start\":\n if xmlevent.elem.tag == \"s\" :\n s_id = None\n if \"s_id\" in xmlevent.elem.attrib:\n s_id = int(xmlevent.elem.get(\"s_id\"))\n sentence = sentence_factory.make(id_number=s_id)\n\n elif xmlevent.elem.tag == \"mweoccur\":\n occur_cand = Candidate(int(xmlevent.elem.get(\"candid\")))\n new_occur = MWEOccurrence(sentence, occur_cand, [])\n sentence.mweoccurs.append(new_occur)\n\n elif xmlevent.event_str == \"end\":\n if xmlevent.elem.tag == \"s\":\n # A complete sentence was read, call the callback function\n self.handler.handle_sentence(sentence, xmlevent.ctxinfo)\n\n elif xmlevent.elem.tag == \"w\":\n props = self._parse_wordelem2props(xmlevent.ctxinfo, xmlevent.elem)\n # Add word to the sentence that is currently being read\n sentence.append(Word(xmlevent.ctxinfo, props))\n\n elif xmlevent.elem.tag == \"mweoccurs\":\n pass # This tag is just a wrapper around `mweoccur` tags\n elif xmlevent.elem.tag == \"mweoccur\":\n pass # Already created MWEOccurrence on `start` event\n\n elif xmlevent.elem.tag == \"mwepart\":\n sentence.mweoccurs[-1].indexes.append(int(xmlevent.elem.get(\"index\"))-1)\n\n elif xmlevent.elem.tag == \"corpus\":\n return # Finished processing\n else:\n self.unknown_end_elem(xmlevent)\n xmlevent.elem.clear()\n\n\n\n #######################################################\n\n def parse_patterns(self, inner_iterator):\n for top_xmlevent in inner_iterator:\n assert top_xmlevent.event_str == \"start\"\n if top_xmlevent.elem.tag == \"patterns\":\n self.parse_until_closed(top_xmlevent, inner_iterator)\n else:\n self.unknown_end_elem(top_xmlevent)\n\n\n def parse_until_closed(self, outer_xmlevent, inner_iterator):\n def iter_until_closed(closing_tag):\n for sub_xmlevent in inner_iterator:\n if sub_xmlevent.event_str == \"end\":\n if closing_tag == sub_xmlevent.elem.tag:\n return # Finished processing\n else:\n self.unknown_end_elem(sub_xmlevent)\n else:\n assert sub_xmlevent.event_str == \"start\"\n yield sub_xmlevent\n\n\n outer_elem = outer_xmlevent.elem\n if outer_elem.tag == \"patterns\":\n for sub_xmlevent in iter_until_closed(outer_elem.tag):\n if sub_xmlevent.elem.tag == \"pat\":\n if self.check_subelem(inner_iterator,\n sub_xmlevent, \"patterns\", (\"pat\",)):\n p = self.parse_until_closed(sub_xmlevent, inner_iterator)\n self.handler.handle_pattern(p, sub_xmlevent.ctxinfo)\n return\n\n\n elif outer_elem.tag == \"pat\": # XXX Future `seq`?\n seq_strid = outer_elem.attrib.pop(\"id\", None)\n seq_repeat = outer_elem.attrib.pop(\"repeat\", None)\n seq_ignore = bool(outer_elem.attrib.pop(\"ignore\", False))\n outer_xmlevent.check_empty()\n ret = patternlib.SequencePattern(outer_xmlevent.ctxinfo, seq_strid, seq_repeat, seq_ignore)\n for sub_xmlevent in iter_until_closed(outer_elem.tag):\n if self.check_subelem(inner_iterator, sub_xmlevent, \"pat\", (\"pat\", \"either\", \"w\")):\n p = self.parse_until_closed(sub_xmlevent, inner_iterator)\n ret.append_pattern(sub_xmlevent.ctxinfo, p)\n return ret.freeze()\n\n\n elif outer_elem.tag == \"either\":\n outer_xmlevent.check_empty()\n ret = patternlib.EitherPattern(outer_xmlevent.ctxinfo)\n for sub_xmlevent in iter_until_closed(outer_elem.tag):\n p = self.parse_until_closed(sub_xmlevent, inner_iterator)\n ret.append_pattern(sub_xmlevent.ctxinfo, p)\n return ret.freeze()\n\n\n elif outer_elem.tag == \"w\":\n w_strid = outer_elem.attrib.pop(\"id\", None)\n ret = patternlib.WordPattern(outer_xmlevent.ctxinfo, w_strid)\n\n match_style = outer_elem.attrib.pop(\"style\", \"\")\n match_flags = outer_elem.attrib.pop(\"flags\", \"\")\n for propname in patternlib.CLASSICAL_PAT_PROPS:\n if propname in outer_elem.attrib:\n propval = outer_elem.attrib.pop(propname)\n propval = self.propval2propobj(outer_xmlevent.ctxinfo,\n propval, match_style, match_flags)\n ret.add_prop(propname, propval, negated=False)\n outer_xmlevent.check_empty()\n\n for sub_xmlevent in iter_until_closed(outer_elem.tag):\n if self.check_subelem(inner_iterator, sub_xmlevent, \"w\", (\"neg\",)):\n if sub_xmlevent.elem.tag == \"neg\":\n match_style = outer_elem.attrib.pop(\"style\", \"\")\n match_flags = outer_elem.attrib.pop(\"flags\", \"\")\n for propname in patternlib.CLASSICAL_PAT_PROPS:\n if propname in sub_xmlevent.elem.attrib:\n propval = sub_xmlevent.elem.attrib.pop(propname)\n propval = self.propval2propobj(sub_xmlevent.ctxinfo,\n propval, match_style, match_flags)\n ret.add_prop(propname, propval, negated=True)\n sub_xmlevent.check_empty()\n self.parse_until_closed(sub_xmlevent, inner_iterator)\n return ret.freeze()\n\n\n else:\n for sub_xmlevent in inner_iterator:\n if (sub_xmlevent.event_str, sub_xmlevent.elem) == (\"end\", outer_elem):\n break # Finished skipping this elem\n\n\n\n def check_subelem(self, inner_iterator, sub_xmlevent, outer_elem_tag, valid_subelem_tags):\n r\"\"\"Check whether `sub_xmlevent.elem.tag` is a valid child under `elem_tag`.\"\"\"\n if sub_xmlevent.elem.tag == ElementTree.Comment:\n self.parse_until_closed(sub_xmlevent, inner_iterator)\n self.unknown_end_elem(sub_xmlevent)\n return False\n\n if sub_xmlevent.elem.tag not in valid_subelem_tags:\n sub_xmlevent.ctxinfo.warn(\"Element <{tag}> does not allow sub-element \" \\\n \"<{subtag}>\", tag=outer_elem_tag, subtag=sub_xmlevent.elem.tag)\n self.parse_until_closed(sub_xmlevent, inner_iterator)\n return False\n return True\n\n\n def propval2propobj(self, ctxinfo, propval, match_style, match_flags):\n r\"\"\"Return a regex version of `propval`.\"\"\"\n if match_style not in (\"regex\", \"literal\", \"\", \"starred-wildcard\"):\n ctxinfo.warn(\"Unknown match-style `{style}`\", style=match_style)\n\n if match_style == \"regex\":\n return patternlib.RegexProp(ctxinfo, propval, match_flags)\n if match_flags:\n ctxinfo.warn(\"Flags being ignored for match-style \" \\\n \"`{style}`\", style=match_style or \"starred-wildcard\")\n if match_style == \"literal\":\n return patternlib.LiteralProp(ctxinfo, propval)\n\n if match_style == \"\":\n if propval.startswith(\"back:\"):\n w_strid, prop = propval.split(\":\", 1)[1].split(\".\", 1)\n return patternlib.BackrefProp(ctxinfo, w_strid, prop)\n\n if not \"*\" in propval:\n return patternlib.LiteralProp(ctxinfo, propval)\n return patternlib.StarredWildcardProp(ctxinfo, propval)\n\n\n\n #######################################################\n def parse_candidates(self, inner_iterator):\n candidate_factory = CandidateFactory()\n candidate = None\n ngram = None\n in_bigram = False\n in_occurs = False\n in_vars = False\n word = None\n meta = None\n\n for xmlevent in inner_iterator:\n event_str, elem, ctxinfo = xmlevent\n\n if event_str == \"start\":\n if elem.tag == \"cand\":\n # Get the candidate ID or else create a new ID for it \n id_number = None\n if \"candid\" in elem.attrib:\n id_number = elem.get(\"candid\")\n candidate = candidate_factory.make([], id_number=id_number)\n\n elif elem.tag == \"ngram\":\n ngram = Ngram()\n\n elif elem.tag == \"bigrams\":\n in_bigram = True\n elif elem.tag == \"occurs\" :\n in_occurs = True\n elif elem.tag == \"vars\" :\n in_vars = True\n\n elif elem.tag == \"w\":\n props = self._parse_wordelem2props(ctxinfo, elem)\n word = Word(ctxinfo, props)\n # Add the word to the ngram that is on the stack\n ngram.append(word)\n\n # Meta section and elements, correspond to meta-info about the\n # candidates lists. Meta-info are important for generating\n # features and converting to arff files, and must correspond\n # to the info in the candidates (e.g. meta-feature has the \n # same elem.tag as actual feature) \n elif elem.tag == \"meta\":\n meta = Meta(None, None, None)\n\n\n elif event_str == \"end\":\n\n if elem.tag == \"cand\" :\n # Finished reading the candidate, call callback\n self.handler.handle_candidate(candidate, ctxinfo) \n\n elif elem.tag == \"ngram\":\n if in_occurs:\n candidate.add_occur(ngram)\n elif in_bigram:\n candidate.add_bigram(ngram)\n elif in_vars:\n candidate.add_var(ngram)\n else:\n candidate.word_list = ngram.word_list\n candidate.freqs = ngram.freqs\n\n elif elem.tag == \"w\":\n # Set word to none, otherwise I cannot make the difference between\n # the frequency of a word and the frequency of a whole ngram\n word = None \n\n elif elem.tag == \"meta\":\n # Finished reading the meta header, call callback \n self.handler.handle_meta(meta, ctxinfo)\n\n elif elem.tag == \"bigrams\":\n in_bigram = False\n elif elem.tag == \"occurs\":\n in_occurs = False\n elif elem.tag == \"vars\":\n in_vars = False\n\n\n elif elem.tag == \"freq\":\n freq = Frequency(elem.get(\"name\"),\n int(elem.get(\"value\")))\n # If is inside a word element, then it's the word's\n # frequency, otherwise it corresponds to the frequency of\n # the ngram that is being read\n if word is not None:\n word.add_frequency(freq) \n else:\n ngram.add_frequency(freq)\n\n elif elem.tag == \"sources\":\n ngram.add_sources(elem.get(\"ids\").split(';'))\n\n elif elem.tag == \"feat\":\n feat_name = elem.get(\"name\")\n feat_value = elem.get(\"value\")\n feat_type = meta.get_feat_type(feat_name)\n if feat_type == \"integer\":\n feat_value = int(feat_value)\n elif feat_type == \"real\":\n feat_value = float(feat_value) \n f = Feature(feat_name, feat_value)\n candidate.add_feat(f) \n\n elif elem.tag == \"tpclass\" :\n tp = TPClass(elem.get(\"name\"), \n elem.get(\"value\"))\n candidate.add_tpclass(tp)\n \n elif elem.tag == \"corpussize\":\n cs = CorpusSize(elem.get(\"name\"), elem.get(\"value\"))\n meta.add_corpus_size(cs)\n elif elem.tag == \"metafeat\" : \n mf = MetaFeat(elem.get(\"name\"), elem.get(\"type\"))\n meta.add_meta_feat(mf) \n elif elem.tag == \"metatpclass\" : \n mtp = MetaTPClass(elem.get(\"name\"), elem.get(\"type\"))\n meta.add_meta_tpclass(mtp)\n elif elem.tag == \"features\":\n pass # nothing to do, but don't WARNING user\n elif elem.tag == \"candidates\":\n return # Finished processing\n else:\n self.unknown_end_elem(xmlevent)\n elem.clear()\n\n\n #######################################################\n def parse_dict(self, inner_iterator):\n id_number_counter = 1\n entry = None\n word = None\n meta = None\n\n for event_str, elem, ctxinfo in inner_iterator:\n if event_str == \"start\":\n\n if elem.tag == \"entry\":\n # Get the candidate ID or else create a new ID for it\n if \"entryid\" in elem.attrib:\n id_number_counter = elem.get(\"entryid\")\n # Instantiates an empty dict entry that will be treated\n # when the tag is closed\n entry = Entry(id_number_counter)\n id_number_counter += 1\n\n elif elem.tag == \"w\":\n props = self._parse_wordelem2props(ctxinfo, elem)\n word = Word(ctxinfo, props)\n entry.append(word)\n\n # Meta section and elements, correspond to meta-info about the\n # reference lists. Meta-info are important for generating\n # features and converting to arff files, and must correspond\n # to the info in the dictionary (e.g. meta-feature has the\n # same name as actual feature)\n elif elem.tag == \"meta\":\n meta = Meta(None,None,None)\n\n if event_str == \"end\":\n\n if elem.tag == \"entry\":\n self.handler.handle_candidate(entry, ctxinfo)\n entry = None\n elif elem.tag == \"w\":\n word = None\n elif elem.tag == \"meta\":\n # Finished reading the meta header, call callback \n self.handler.handle_meta(meta, ctxinfo)\n\n elif elem.tag == \"freq\":\n freq = Frequency(elem.get(\"name\"),\n int(elem.get(\"value\")))\n # If is inside a word element, then it's the word's\n # frequency, otherwise it corresponds to the frequency of\n # the ngram that is being read\n if word is not None:\n word.add_frequency(freq)\n else:\n entry.add_frequency(freq)\n\n elif elem.tag == \"feat\":\n feat_name = elem.get(\"name\")\n feat_value = elem.get(\"value\")\n feat_type = meta.get_feat_type(feat_name)\n if feat_type == \"integer\":\n feat_value = int(feat_value)\n elif feat_type == \"real\":\n feat_value = float(feat_value)\n f = Feature(feat_name, feat_value)\n entry.add_feat(f)\n\n elif elem.tag == \"corpussize\":\n cs = CorpusSize(elem.get(\"name\"), elem.get(\"value\"))\n meta.add_corpus_size(cs)\n elif elem.tag == \"metafeat\" : \n mf = MetaFeat(elem.get(\"name\"), elem.get(\"type\"))\n meta.add_meta_feat(mf) \n\n elif elem.tag == \"dict\":\n return # Finished processing\n else:\n self.unknown_end_elem(elem, ctxinfo)\n\n\n\n\n\n\n######################################################################\n\nclass XMLEvent(collections.namedtuple('XMLEvent', 'event_str elem ctxinfo')):\n def check_empty(self):\n r\"\"\"Check whether `xmlevent.elem.attrib` values have been popped.\"\"\"\n for k in self.elem.attrib:\n self.ctxinfo.warn(\"Ignoring unexpected XML attribute `{attr}` \" \\\n \"for elem `{elem}`\", attr=k, elem=self.elem.tag)\n\n\n\nclass IterativeXMLParser:\n r\"\"\"This class allows us to iterate through the XML.\n Normally, `XMLPullParser` or `iterparse` would do the job,\n but we actually want to iterate through *everything*, including\n comments, and the devs decided that comments are not worthy\n of being iterated over... So we implement our own.\n\n We also generate source_{line,col}.\n \"\"\"\n def __init__(self, inputobj, mwetkparser):\n self._subparser = expat.ParserCreate()\n self._subparser.CommentHandler = self.CommentHandler\n self._subparser.StartElementHandler = self.StartElementHandler\n self._subparser.EndElementHandler = self.EndElementHandler\n self._inputobj = inputobj\n self._mwetkparser = mwetkparser\n self._queue = collections.deque() # deque[XMLEvent]\n self._elemstack = [] # list[XMLEvent] (event_str==\"start\")\n\n def __iter__(self):\n r\"\"\"This object is an iterator.\"\"\"\n return self\n\n def __next__(self):\n r\"\"\"Return next pair in buffer (parse more if needed)\"\"\"\n while True:\n if self._queue:\n return self._queue.popleft()\n\n data = self._inputobj.read_str(16*1024)\n if not data:\n # XXX check if self._subparser is in the\n # middle of processing something (HOW?), and\n # if so, raise an EOF error\n raise StopIteration\n self._subparser.Parse(data)\n\n\n def CommentHandler(self, text):\n elem = ElementTree.Element(ElementTree.Comment, {})\n elem.text = text\n ctxinfo = self._ctxinfo()\n self._queue.append(XMLEvent(\"start\", elem, ctxinfo))\n self._queue.append(XMLEvent(\"end\", elem, ctxinfo))\n\n def StartElementHandler(self, tag, attrs):\n elem = ElementTree.Element(tag, attrs)\n xmlevent = XMLEvent(\"start\", elem, self._ctxinfo())\n self._elemstack.append(xmlevent)\n self._queue.append(xmlevent)\n\n def EndElementHandler(self, tag):\n xmlevent_start = self._elemstack.pop()\n xmlevent_end = XMLEvent(\"end\", xmlevent_start.elem,\n self._ctxinfo(start_ctxinfo=xmlevent_start.ctxinfo))\n assert xmlevent_start.elem.tag == xmlevent_end.elem.tag\n self._queue.append(xmlevent_end)\n\n def _ctxinfo(self, start_ctxinfo=None):\n x_line = self._subparser.CurrentLineNumber-1\n x_col = self._subparser.CurrentColumnNumber\n if start_ctxinfo is not None:\n return start_ctxinfo.with_endpoint(x_line, x_col)\n\n return util.InputObjContextInfo(self._inputobj,\n mwetkparser=self._mwetkparser,\n linenum=util.NumberRange(x_line, None),\n colnum=util.NumberRange(x_col, None))\n","sub_path":"TP01-corpus/bin/libs/filetype/ft_xml.py","file_name":"ft_xml.py","file_ext":"py","file_size_in_byte":37817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"338716637","text":"from Maya_UtilLib.Controls import build_world_pos_loc\nfrom Util import *\nfrom ...Utils import List\nfrom ...Utils import DummyUtil as dU\n\n\ndef build(name, side, module_name, num_con, axis, dis, color_index):\n print('building Spine Dummy Skeleton Module')\n lock = ''\n\n # create spineModule\n spine_placer = linear_dis_dummy_bone_creator(name, side, module_name, num_con, axis, dis, color_index)\n create_module_annotation((name + side + module_name), spine_placer)\n chest = create_module_annotation((name + side + 'chest'), (name + side + module_name + str(num_con) + '_loc'))\n pc.setAttr((chest + '.t'), (0, 0, 0))\n\n # negate pos value in order to get hips position opposite to the spine joint\n pos = (dis / dis) * -1\n\n hips_dummy_jnt = create_dummy_joint(color_index)\n hips_dummy_jnt[0] = pc.rename(hips_dummy_jnt[0], (name + side + module_name + 'Hips_loc'))\n pc.addAttr(hips_dummy_jnt[0], ln='jointPosList', dt='string')\n pc.setAttr((hips_dummy_jnt[0] + '.jointPosList'), hips_dummy_jnt[0], type='string')\n hips = create_module_annotation((name + side + 'hips'), hips_dummy_jnt[0])\n pc.setAttr((hips + '.t'), (0, -1, 0))\n\n pc.parent(hips_dummy_jnt[0], spine_placer)\n\n joint_pos_list = pc.getAttr(spine_placer + '.jointPosList')\n joint_pos_lists = List.seperate(joint_pos_list)\n dummy_bone_grp = create_dummy_bone(side, module_name, joint_pos_lists[0], hips_dummy_jnt[0])\n\n pc.addAttr(hips_dummy_jnt[0], ln='parent', dt='string')\n pc.setAttr((hips_dummy_jnt[0] + '.parent'), joint_pos_lists[0], type='string')\n\n pc.addAttr(spine_placer, ln='child', dt='string')\n pc.setAttr((spine_placer + '.child'), hips_dummy_jnt[0], type='string')\n\n if axis == 'x' or axis == 'X':\n pc.move(pos, 0, 0, hips_dummy_jnt[0])\n lock = 'z'\n elif axis == 'y' or axis == 'Y':\n pc.move(0, pos, 0, hips_dummy_jnt[0])\n lock = 'x'\n elif axis == 'z' or axis == 'Z':\n pc.move(0, 0, pos, hips_dummy_jnt[0])\n lock = 'x'\n\n pc.setAttr((hips_dummy_jnt[0] + '.t' + lock), lock=True)\n\n pc.setAttr((dummy_bone_grp + '.inheritsTransform'), 0)\n try:\n pc.parent(dummy_bone_grp, spine_placer, r=True)\n except:\n pass\n pc.select(cl=True)\n\n # create world pos loc and parent main arm placer ctrl...\n world_pos_loc = build_world_pos_loc(name)\n if not pc.attributeQuery('spine', n=world_pos_loc, ex=True):\n pc.addAttr(world_pos_loc, ln='spine', dt='string')\n\n module_parts = pc.getAttr(world_pos_loc + '.' + 'spine')\n pc.setAttr((world_pos_loc + '.' + 'spine'), (str(module_parts or '') + ' ' + spine_placer), type='string')\n\n pc.parent(spine_placer, world_pos_loc)\n\n # module tags\n pc.addAttr(spine_placer, ln='moduleTag', dt='string')\n pc.addAttr(spine_placer, ln='buildTag', dt='string')\n\n pc.setAttr((spine_placer + '.moduleTag'), 'spine', type='string')\n pc.setAttr((spine_placer + '.buildTag'), world_pos_loc, type='string')\n\n # rig info Attr\n spine_list = pc.getAttr(spine_placer + '.jointPosList')\n spine_joints_list = List.seperate(spine_list)\n size = len(spine_joints_list)\n\n pc.addAttr(spine_placer, ln='name', dt='string')\n pc.setAttr((spine_placer + '.name'), name, type='string')\n pc.addAttr(spine_placer, ln='side', dt='string')\n pc.setAttr((spine_placer + '.side'), side, type='string')\n pc.addAttr(spine_placer, ln=(side + 'rootJoint'), dt='string')\n pc.setAttr((spine_placer + '.' + (side + 'rootJoint')), spine_joints_list[0], type='string')\n pc.addAttr(spine_placer, ln=(side + 'chestJoint'), dt='string')\n pc.setAttr((spine_placer + '.' + (side + 'chestJoint')), spine_joints_list[size - 1], type='string')\n pc.addAttr(spine_placer, ln=(side + 'hipJoint'), dt='string')\n pc.setAttr((spine_placer + '.' + (side + 'hipJoint')), hips_dummy_jnt[0], type='string')\n pc.select(cl=True)\n\n dU.add_dummy_twist_joints_attr(spine_placer, joint_pos_lists[0], spine_joints_list[size - 1], 7)\n","sub_path":"Core/Dummy/Spine.py","file_name":"Spine.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"641941660","text":"#!/usr/bin/env python\n\nimport os, sys, commands, string, subprocess, shutil\n\ngalaxyhome=os.environ.get('GALAXY_HOME')\n\noutput = sys.argv[1]\n\n##uncomment when running on VM\nos.chdir(galaxyhome + \"/tools/groovy/\") #uncomment when running on cluster\n#os.chdir(\"/media/Work/galaxy-proteonics/tools/groovy/\") #for local running\n\ncommand=\"groovy -cp GLSGeneusRestApiUtils.groovy UpdateProcessUDF_from_Galaxy.groovy\"\n\nfile = open(output, 'w')\n\nproc = subprocess.Popen( args=command, shell=True, stdout=file, stderr=subprocess.PIPE )\n\n","sub_path":"tools/groovy/groovy.py","file_name":"groovy.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"347962508","text":"import sys\nimport subprocess\nimport multiprocessing as mp\n\ndef runR(r):\n subprocess.call('python 20newsgroup.py -r B -l A.pkl -d B_{0}.pkl -e 10000 -R {0} > B_{0}.txt'.format(r), shell=True)\ndef runRevR(r):\n subprocess.call('python 20newsgroup.py -r A -l B.pkl -d A_{0}.pkl -e 10000 -R {0} > A_{0}.txt'.format(r), shell=True)\n\nruns = []\ntn = 0\n# all layers\nR = [1,5,10,50,100,200]\n\ntn = 0\nfor r in R:\n AB = mp.Process(target=runR, args=(r,))\n AB.start()\n AB.join()\n # BA = mp.Process(target=runRevR, args=(r,))\n # BA.start()\n # BA.join()","sub_path":"old/TensorNet/once/part_layer/12/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"550435633","text":"import cv2\nimport albumentations as albu\nimport random\nfrom albumentations import (\n HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,\n Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,\n IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine,\n IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose\n)\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_mask():\n which = random.randint(0, 6)\n item_name = 'src/imgs/mask' + str(which) + '.png'\n # print(item_name)\n item_img_ = cv2.imread(item_name, cv2.IMREAD_UNCHANGED)\n return item_img_\n\n\naug = albu.Compose([\n albu.HorizontalFlip(),\n OneOf([\n IAAAdditiveGaussianNoise(),\n GaussNoise(),\n ], p=0.2),\n OneOf([\n MotionBlur(p=0.2),\n MedianBlur(blur_limit=3, p=0.1),\n Blur(blur_limit=3, p=0.1),\n ], p=0.2),\n # ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=45, p=0.2),\n HueSaturationValue(p=0.3),\n])\n\n\ndef get_aug_mask(img=None):\n if img is None:\n img = get_mask()\n mask = img[:, :, 3:]\n img_ = img[:, :, :3]\n\n augmented = aug(image=img_, mask=mask)\n img_, mask = augmented['image'], augmented['mask']\n ret, mask = cv2.threshold(mask, 175, 255, cv2.THRESH_BINARY)\n mask = mask[:, :, np.newaxis]\n # mask pass by threhold can good\n img_1 = cv2.bitwise_and(img_, img_, mask)\n\n img_1 = np.concatenate([img_1, mask], axis=2)\n # img[:, :, ]\n return img_1\n\n\ndef get_glasses():\n return cv2.imread('src/imgs/glasses.png', cv2.IMREAD_UNCHANGED)\n\n\nif __name__ == '__main__':\n for i in range(100):\n # img_ = get_mask()\n img = get_aug_mask()\n print(img.shape)\n cv2.imshow('img', img)\n # cv2.waitKey()\n # img = get_mask()\n #\n # cv2.imshow('mask', mask)\n # cv2.imshow('aaa', img)\n cv2.imwrite('tmp.png', img)\n cv2.waitKey()\n # plt.imshow(img)\n # plt.show()\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"350294994","text":"import codecs\nimport os\n\nfrom fonduer.parser.models import Document\nfrom fonduer.parser.preprocessors.doc_preprocessor import DocPreprocessor\n\n\nclass TextDocPreprocessor(DocPreprocessor):\n \"\"\"A generator which processes a text file or directory of text files into\n a set of Document objects.\n\n Assumes one document per file.\n\n :param encoding: file encoding to use (e.g. \"utf-8\").\n :type encoding: str\n :param path: filesystem path to file or directory to parse.\n :type path: str\n :param max_docs: the maximum number of ``Documents`` to produce.\n :type max_docs: int\n :rtype: A generator of ``Documents``.\n \"\"\"\n\n def _parse_file(self, fp, file_name):\n with codecs.open(fp, encoding=self.encoding) as f:\n name = os.path.basename(fp).rsplit(\".\", 1)[0]\n stable_id = self._get_stable_id(name)\n doc = Document(\n name=name,\n stable_id=stable_id,\n meta={\"file_name\": file_name},\n text=f.read(),\n )\n yield doc\n","sub_path":"src/fonduer/parser/preprocessors/text_doc_preprocessor.py","file_name":"text_doc_preprocessor.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"353651550","text":"import itertools\nimport copy\ntry:\n from general_functions import *\n from change_abbreviations import change_abbrev\n from use_lemmas import use_basic_lemmas\n from analyze_definition import process_sentences, get_lesser_skeleton\n from put_words_in_slots import categorize_words, determine_constants\n from prepare_for_print import rearrange\n from classes import ErrorWithCode\nexcept:\n from .general_functions import *\n from .change_abbreviations import change_abbrev\n from .use_lemmas import use_basic_lemmas\n from .analyze_definition import process_sentences, get_lesser_skeleton\n from .put_words_in_slots import categorize_words, determine_constants\n from .prepare_for_print import rearrange\n from .classes import ErrorWithCode\n\n\n\n############### THE FOLLOWING FUNCTIONS ARE RELATED TO THE USE OF IDENTITY\n\n\ndef identity():\n global identities\n names = {}\n props = {}\n tvalues = {}\n indexes = {}\n\n for sent in output.all_sent:\n if sent[13] == '=' and output.abbreviations.get(sent[10]) != sent[14]:\n names.update({sent[10]: sent[14]})\n props.update({sent[10]: set()})\n tvalues.update({sent[10]: {}})\n indexes.update({sent[10]: {}})\n props.update({sent[14]: set()})\n tvalues.update({sent[14]: {}})\n indexes.update({sent[14]: {}})\n\n identities = [names, props, tvalues, indexes]\n\n\ndef update_identity(begin, end):\n global identities\n names = identities[0]\n props = identities[1]\n tvalues = identities[2]\n indexes = identities[3]\n\n for k, v in names.items():\n properties1 = props.get(k)\n properties2 = props.get(v)\n tvalues1 = tvalues.get(k)\n tvalues2 = tvalues.get(v)\n idx1 = indexes.get(k)\n idx2 = indexes.get(v)\n for i in range(begin, end):\n sent = output.all_sent[i]\n if sent[13] != \"=\":\n build_identity(sent, k, tvalues1, properties1, idx1, i)\n\n if sent[13] != \"=\":\n build_identity(sent, v, tvalues2, properties2, idx2, i)\n\n props.update({k: properties1})\n props.update({v: properties2})\n tvalues.update({k: tvalues1})\n tvalues.update({v: tvalues2})\n indexes.update({k: idx1})\n indexes.update({v: idx2})\n\n identities = [names, props, tvalues, indexes]\n\n use_identity()\n\n\ndef build_identity(sent, obj, tv, properties, _index, asent_idx):\n list1 = []\n match = False\n for n in sent[54]:\n if sent[n] == obj:\n match = True\n list1.append(alpha)\n elif sent[n] != \"~\":\n list1.append(sent[n])\n if not match:\n return\n\n new_sent = \"\".join(list1)\n properties.add(new_sent)\n tv.update({new_sent: sent[3]})\n _index.update({new_sent: asent_idx})\n\n\ndef use_identity():\n for k, v in identities[0].items():\n properties1 = identities[1].get(k)\n properties2 = identities[1].get(v)\n tvalues1 = identities[2].get(k)\n tvalues2 = identities[2].get(v)\n idx1 = identities[3].get(k)\n idx2 = identities[3].get(v)\n\n properties3 = properties1 & properties2\n if properties3 != set():\n for sent in properties3:\n tv1 = tvalues1.get(sent)\n tv2 = tvalues2.get(sent)\n if tv1 != tv2:\n num = idx1.get(sent)\n num2 = idx2.get(sent)\n construct_contr_identity(num, num2, k, v)\n return\n\n\ndef construct_contr_identity(num, num2, k, v):\n global consistent\n sent1 = output.all_sent[num]\n sent2 = output.all_sent[num2]\n for pos in sent2[42]:\n if sent2[pos] == v:\n sent2[pos] = k\n break\n\n name_and_build(output, sent2)\n anc1 = find_counterpart_inlist(\"(\" + k + \" = \" + v + \")\", output.total_sent, 1, 0)\n add_to_tsent(output, sent2[1], sent2[2], sent2[3], \"SUB\", sent2[44], anc1)\n build_contradiction(output, sent1[44])\n consistent = False\n\n\n##########group: prepare for instantiation #############\n\n\ndef get_range(sentences):\n x = 10\n list1 = []\n while sentences[x] != None:\n list1.append(x)\n x += 1\n return list1\n\n\ndef reduce_hypotheticals_in_premises():\n j = -1\n quant_counter = \"\"\n while j < len(output.all_sent) - 1:\n j += 1\n sent = output.all_sent[j]\n len_asent = len(output.all_sent)\n quantifier = False\n if len(sent) == 46:\n quant_counter += \"a\"\n sent = sent[0]\n quantifier = True\n\n if isinstance(sent, str):\n if not one_sentence(sent):\n output.all_sent[j] = None\n j -= 1\n osent = sent\n sent_class, old_prop = process_sentences(sent, quant_counter, dictionary, output)\n sent_class = sent_class[0]\n anc1 = \"\"\n sentences = sent_class.sentences\n definiendum, done = universal_negations(sent_class, output)\n\n if quantifier:\n definiendum = \"qu\" + quant_counter\n anc1 = find_counterpart_inlist(osent, output.total_sent, 1, 0)\n assert anc1 != None\n\n asent_idx = name_connected_sent(osent, old_prop, sent_class, quantifier, anc1)\n lst = [x for x in range(len(sentences))]\n skeleton = get_lesser_skeleton(lst, sentences)\n output.lsent_list.append(skeleton)\n output.lsent_dict.setdefault(skeleton, []).append(asent_idx)\n if quantifier or definiendum == 'thing':\n sent_class.def_stats.def_word = definiendum\n sent_class.def_stats.def_word_num = definiendum + \"0\"\n if quantifier: add_to_gsent([sent_class], output)\n output.trans_def.update({definiendum + \"0\": sent_class})\n do_not_instantiate.append([j + 1, definiendum])\n for x in range(len_asent, len(output.all_sent)):\n do_not_instantiate.append([x, definiendum])\n\n return\n\n\ndef name_connected_sent(osent, old_prop, sent_class, quantifier, anc1=\"\"):\n # because we cannot delete sentences from the all sent otherwise we\n # mess up the order of the subvalues, we turn connected sentences into\n # nones in the all sent and then gradually replace the all sent with\n # the parts of the connected sent\n sentences = sent_class.sentences\n none_pos = [i for i, sent in enumerate(output.all_sent) if sent == None]\n asent_idx = []\n greek_english = {}\n greek_english_abb = {}\n for sentence in sentences:\n if osent != sent_class.def_stats.translated_sent:\n sentence[44] = output.tindex + 2\n else:\n sentence[44] = output.tindex + 1\n sent_abb = name_sent(sentence[1], output.prop_name)\n sentence[2] = sent_abb\n output.oprop_name[sent_abb] = sentence[1]\n if none_pos != []:\n output.all_sent[none_pos[0]] = sentence\n asent_idx.append(none_pos[0])\n del none_pos[0]\n else:\n output.all_sent.append(sentence)\n asent_idx.append(len(output.all_sent) - 1)\n greek_english.update({sentence[5]: sentence[0]})\n greek_english_abb.update({sentence[5]: sentence[3] + sent_abb})\n if proof_kind:\n for o in sentence[42]:\n try:\n output.variables.remove(sentence[o])\n except:\n pass\n\n new_greek = sent_class.def_stats.tot_greek_sent\n new_greek_abb = sent_class.def_stats.tot_greek_sent\n for k, v in greek_english.items():\n new_greek = new_greek.replace(k, v)\n for k, v in greek_english_abb.items():\n new_greek_abb = new_greek_abb.replace(k, v)\n\n add_to_tsent(output, osent, old_prop)\n\n if osent != sent_class.def_stats.translated_sent:\n if quantifier:\n add_to_tsent(output, new_greek, new_greek_abb, \"\", \"ASC\", output.tindex)\n else:\n add_to_tsent(output, new_greek, new_greek_abb, \"\", \"ASC\", output.tindex)\n\n sent_class.def_stats.tot_sent_idx = output.tindex\n\n return asent_idx\n\n\ndef prepare_stan():\n if proof_kind == 'artificial':\n for i in range(len(output.all_sent)):\n if isinstance(output.all_sent[i], str):\n if one_sentence(output.all_sent[i][0]):\n output.all_sent[i] = quick_reduction(output.all_sent[i])\n output.all_sent[i][6] = str(output.tindex)\n add_to_tsent(output, output.all_sent[i][1], output.all_sent[i][2], output.all_sent[i][3], \"\")\n output.all_sent[i][44] = output.tindex\n output.all_sent[i][7] = \"c\"\n output.lsent_dict.setdefault(output.all_sent[i][58], []).append(i)\n output.lsent_list.append(output.all_sent[i][58])\n\n for j in output.all_sent[i][42]:\n try:\n output.variables.remove(output.all_sent[i][j])\n except:\n pass\n else:\n for e, sent in enumerate(output.all_sent):\n if one_sentence(sent[0]) and sent[7] == 'c':\n sent[58] = determine_constants(output.abbreviations, sent)\n output.lsent_dict.setdefault(sent[58], []).append(e)\n output.lsent_list.append(sent[58])\n if proof_kind == 'lemmas':\n add_to_tsent(output, sent[1], sent[2], sent[3])\n output.all_sent[e][44] = output.tindex\n\n return\n\n\ndef quick_reduction(sent):\n sent = sent.strip()\n sent = sent.replace(\"(\", \"\")\n sent = sent.replace(\")\", \"\")\n sent = sent.split(\" \")\n sent = categorize_words(output.abbreviations, sent, dictionary)\n sent[2] = name_sent(sent[1], output.prop_name)\n output.oprop_name[sent[1]] = sent[2]\n return sent\n\n\ndef get_propositional_variables():\n for sent in output.all_sent:\n if sent[9] == mini_e:\n list1 = json.loads(json.dumps(sent))\n prop = list1[8]\n for x in [8, 9]: list1[54].remove(x)\n list1[8] = None\n list1[9] = None\n name_and_build(output, list1)\n output.abbreviations.update({prop: list1[1]})\n\n\ndef get_constants():\n for lst in output.all_sent:\n if lst[7] == 'c':\n for num in lst[42]:\n if lst[num] not in output.constants: output.constants.add(lst[num])\n\n for var in output.abbreviations.keys():\n if var not in output.constants: output.constants.add(var)\n\n\ndef get_abbreviations_standard():\n if proof_kind in [\"\", \"lemmas\"]: return\n i = 0\n list2 = []\n while \"=\" in output.all_sent[i]:\n sent = output.all_sent[i]\n if sent == None:\n break\n if \"=\" in sent:\n list2.append(sent)\n sent = sent.replace(\"(\", \"\")\n sent = sent.replace(\")\", \"\")\n list1 = sent.split(\"=\")\n list1[0] = list1[0].strip()\n list1[1] = list1[1].strip()\n\n output.abbreviations.update({list1[0]: list1[1]})\n try:\n output.variables.remove(list1[0])\n except:\n pass\n\n del output.all_sent[i]\n\n\ndef add_disjuncts(cls, definiendum):\n for disjunct in cls.def_stats.natural_disjuncts:\n if disjunct != 0:\n add_to_tsent(output, disjunct[0], \"\", \"\", xorr + \" \" + definiendum)\n output.substitutions.setdefault(xorr + \" \" + definiendum, []).append(output.total_sent[-1])\n\n\ndef add_disjuncts2(tran_disjuncts, qn, definiendum, rn_list):\n for disjunct in tran_disjuncts:\n if disjunct != 0:\n output.substitutions.setdefault(xorr + \" \" + definiendum, []).append(rn_list)\n add_to_tsent(output, disjunct[1], \"\", \"\", \"SUBI\", qn - 1, qn)\n output.substitutions.setdefault(xorr + \" \" + definiendum, []).append(output.total_sent[-1])\n\n\ndef translate_abbreviations(lst, definiendum):\n # in the map var the old output.variables are on the left and the new ones are ont he right\n if definiendum == 'GN':\n bb = 8\n conjunctive_definition = False\n map_var = {}\n already_used_map = {}\n temp_constants = dictionary.def_constants.get(definiendum, {})\n change_constants(already_used_map, output, temp_constants)\n\n if len(lst) > 1:\n conjunctive_definition = True\n add_to_tsent(output, dictionary.definitions.get(definiendum), \"\", \"\", \"DF \" + definiendum)\n anc1 = output.tindex\n\n for m, cls in enumerate(lst):\n def_stats = cls.def_stats\n sentences = cls.sentences\n tran_disjuncts = json.loads(json.dumps(cls.def_stats.natural_disjuncts))\n greek_definition = def_stats.tot_greek_sent\n\n if conjunctive_definition:\n add_to_tsent(output, def_stats.natural_sent, \"\", \"\", \"CE\", anc1)\n else:\n add_to_tsent(output, def_stats.natural_sent, \"\", \"\", \"DF \" + definiendum)\n output.substitutions.setdefault(definiendum + str(m), []).append(output.total_sent[-1])\n def_stats.tot_sent_idx = output.tindex\n pn = output.tindex\n add_disjuncts(cls, definiendum)\n\n for e, sent in enumerate(sentences):\n if e == 6:\n bb = 8\n ogreek = sent[5]\n for j in sent[42]:\n ovar = sent[j]\n if ovar != None and ovar not in temp_constants.values():\n nvar = already_used_map.get(ovar)\n if nvar == None:\n nvar = map_var.get(ovar)\n else:\n map_var.update({ovar: nvar})\n if nvar != None:\n sent[j] = nvar\n elif ovar in output.variables:\n output.variables.remove(ovar)\n map_var.update({ovar: ovar})\n else:\n sent[j] = output.variables[0]\n map_var.update({ovar: output.variables[0]})\n del output.variables[0]\n\n name_and_build(output, sent)\n greek_definition = greek_definition.replace(ogreek, sent[0])\n tran_disjuncts = translate_greek_disjuncts(ogreek, sent, tran_disjuncts)\n sent[44] = output.tindex + 2\n\n if translations_made(map_var):\n rn_sent = build_trans_sent(map_var)\n already_used_map = {**map_var, **already_used_map}\n map_var = {}\n qn = output.tindex + 1\n add_to_tsent(output, rn_sent, \"\", \"\", \"TR\", \"id\")\n rn_list = output.total_sent[-1]\n output.substitutions.setdefault(definiendum + str(m), []).append(output.total_sent[-1])\n add_to_tsent(output, greek_definition, \"\", \"\", \"SUBI\", pn, 0)\n output.substitutions.setdefault(definiendum + str(m), []).append(output.total_sent[-1])\n def_stats.tot_sent_idx = output.tindex\n add_disjuncts2(tran_disjuncts, qn, definiendum, rn_list)\n def_stats.translated_sent = greek_definition\n else:\n def_stats.translated_sent = def_stats.natural_sent\n\n\n return\n\n\ndef translations_made(map_var):\n for k, v in map_var.items():\n if k != v:\n return True\n return False\n\n\ndef translate_greek_disjuncts(ogreek, sent, tran_disjuncts):\n for tran_disjunct in tran_disjuncts:\n if tran_disjunct != 0:\n tran_disjunct[1] = tran_disjunct[1].replace(ogreek, sent[0])\n\n return tran_disjuncts\n\n\ndef build_trans_sent(map_var):\n list1 = []\n for k, v in map_var.items():\n if k != v:\n str1 = \"(\" + k + idd + v + \")\"\n list1.append(str1)\n\n return \" \".join(list1)\n\n\ndef definition_constant(sent):\n if sent[13] in [\"I\", \"J\", \"V\"]:\n word = output.abbreviations.get(sent[14])\n if word != None:\n return word\n else:\n return sent[13]\n\n elif sent[13] == '=' and sent[14] in output.abbreviations.values():\n return sent[14]\n else:\n return sent[13]\n\n\ndef is_exceptional2(output, word, m):\n if proof_kind == 'lemmas' and word in dictionary.entailments.keys():\n return True\n elif proof_kind == 'lemmas' and word == 'point':\n if output.all_sent[m][10] in output.main_var:\n return False\n else:\n return True\n return False\n\n\ndef get_hypotheticals(start):\n if proof_kind == 'lemmas2': return\n done = []\n for m in range(start, len(output.all_sent)):\n if output.all_sent[m][43] != 'do not define' and \\\n output.all_sent[m][0] != 'irrelevant':\n word = definition_constant(output.all_sent[m])\n assert word != None\n if findposinmd(\"DF \" + word, output.total_sent, 4) == -1 and word not in done:\n if word in dictionary.categorized_sent.keys() and \\\n not is_exceptional2(output, word, m):\n item1 = get_word_info(dictionary, word, output.user)\n\n add_to_gsent(item1, output)\n for j, itm in enumerate(item1):\n output.trans_def.update({word + str(j): itm})\n translate_abbreviations(item1, word)\n done.append(word)\n\n return\n\n\ndef try_instantiation(output2, dictionary2, proof_kind2=\"\"):\n global consistent, identities, proof_kind, output, reduced\n global do_not_instantiate, rel_abbrev, atomic_dict1, atomic_dict2\n global dictionary, lemmata\n\n pkl_file = open('lemmata.pkl', 'rb')\n lemmata = pickle.load(pkl_file)\n pkl_file.close()\n\n consistent = True\n reduced = False\n identities = []\n do_not_instantiate = []\n rel_abbrev = set()\n atomic_dict1 = {}\n atomic_dict2 = {}\n output = output2\n proof_kind = proof_kind2\n dictionary = dictionary2\n\n step_one()\n\n return output, consistent, reduced\n\n\ndef step_one():\n global output\n\n get_abbreviations_standard()\n\n reduce_hypotheticals_in_premises()\n\n prepare_stan()\n\n get_propositional_variables()\n\n get_constants()\n\n get_relevant_abbreviations(0)\n\n get_hypotheticals(0)\n\n identity()\n\n employ_lemmas()\n\n loop_through_gsent()\n\n output = rearrange(\"last\", output, consistent, proof_kind, rel_abbrev)\n\n\ndef use_basic_lemmas2(begin, end):\n global consistent\n if proof_kind == 'lemmas2': return\n if not consistent: return\n\n update_identity(begin, end)\n if not consistent: return\n\n for i in range(begin, end):\n sent = output.all_sent[i]\n if sent[7] == 'c':\n for pos in sent[42]:\n\n consistent = use_basic_lemmas(output, pos, sent, atomic_dict1, atomic_dict2)\n\n if not consistent: return\n\n\n######## group: loop until instantiation is done ##############\n\n\ndef prepare_from_lemmas(output2, proof_kind2, dictionary2):\n global consistent, identities, proof_kind, output, reduced\n global do_not_instantiate, rel_abbrev, atomic_dict1, atomic_dict2\n global dictionary\n\n proof_kind = proof_kind2\n output = output2\n dictionary = dictionary2\n identities = []\n consistent = True\n reduced = False\n rel_abbrev = output.main_var\n atomic_dict1 = {}\n atomic_dict2 = {}\n do_not_instantiate = output.disj_elim\n output.disj_elim = []\n\n\ndef get_relevant_abbreviations(begin):\n universal = lambda x, y: x[13] in [\"I\", \"J\", \"V\", \"OFW\"] and y == 14\n if begin == 0:\n for k in output.abbreviations.keys():\n if isvariable(k):\n rel_abbrev.add(k) # todo this rule might contradict the one below\n\n for sent in output.all_sent[begin:]:\n for noun in sent[42]:\n if sent[noun] == 'x':\n bb = 8\n\n if not universal(sent, noun):\n rel_abbrev.add(sent[noun])\n\n return\n\n\ndef delete_irrelevant_lsent(begin):\n if proof_kind in [\"lemmas2\"]: return\n list1 = []\n for e in range(begin, len(output.all_sent)):\n sent = output.all_sent[e]\n if sent[13] == 'I':\n if any(sent2[10] in rel_abbrev and sent2[13] == 'H'\n and sent2[14] == sent[10] for sent2 in output.all_sent):\n pass\n elif all(sent[x] not in rel_abbrev for x in sent[42]):\n sent[0] = 'irrelevant'\n list1.append(e)\n\n elif all(sent[x] not in rel_abbrev for x in sent[42]):\n sent[0] = 'irrelevant'\n list1.append(e)\n\n if list1 != []:\n delete_this = []\n for k, v in output.lsent_dict.items():\n j = 0\n while j < len(v):\n if v[j] in list1:\n del v[j]\n if v == []:\n delete_this.append(k)\n break\n else:\n j += 1\n for k in delete_this: del output.lsent_dict[k]\n for k in delete_this: output.lsent_list.remove(k)\n\n return\n\n\ndef is_exceptional(matrix, j):\n if j == 25:\n bb = 8\n\n lesser_word = matrix[j][0]\n lesser_word = lesser_word.replace(\"~\", \"\")\n if matrix[j][1] == \"I\":\n if dictionary.kind.get(lesser_word) == 'c':\n return True\n elif matrix[j][1] == 'J':\n pos = dictionary.pos.get(lesser_word)\n if pos[0] == 'a':\n return True\n elif matrix[j][3] in output.near_matches.keys():\n return True\n\n return False\n\n\ndef instantiable(lconstant, gconstant):\n lst = output.lsent_dict.get(lconstant)\n\n for num in lst:\n if [num, gconstant[0]] not in do_not_instantiate or \\\n gconstant[3] != lst[0]:\n return True\n\n return False\n\n\ndef build_matrix(matrix, gstart, gstop, lstart, lend):\n for lconstant in output.lsent_list[lstart:lend]:\n for gconstant in output.gsent[gstart: gstop]:\n if instantiable(lconstant, gconstant):\n matrix.append([lconstant, gconstant[0], gconstant[1], gconstant[2]])\n\n return\n\n\ndef loop_through_gsent(output2=\"\", proof_kind2=\"\", dictionary2=\"\"):\n global reduced\n if proof_kind2 == 'lemmas2':\n prepare_from_lemmas(output2, proof_kind2, dictionary2)\n\n if not consistent: return\n for x in output.abbreviations.values(): assert not x.islower() or len(x) > 1\n matrix = []\n prev_instant = []\n output.lsent_list = sorted(list(set(output.lsent_list)))\n delete_irrelevant_lsent(0)\n build_matrix(matrix, 0, len(output.gsent), 0, len(output.lsent_list))\n # in the matrix, the 2nd member is the index in the output.gsent, the 3rd member\n # is 0 for antecedent and 1 for consequent and the 4th member is the index\n # in the output.lsent_dict\n j = 0\n z = 0\n while j < len(matrix):\n z += 1\n if z > 600: raise ErrorWithCode(\"caught in infinite loop\")\n\n word = matrix[j][3]\n len_gsent = len(output.gsent)\n len_lsent = len(output.lsent_list)\n len_asent = len(output.all_sent)\n possibilities = []\n if j == 10:\n\n bb = 8\n\n if matrix[j][0] == matrix[j][1] or is_exceptional(matrix, j):\n # print(j)\n\n if matrix[j][3] == \"INE00\" or j == 61 or word == 'natural' + ur:\n bb = 8\n\n used_possibilities = loop_through_gsent2(possibilities, matrix, prev_instant, j)\n if used_possibilities != []:\n reduced = True\n reconfigure_matrix(j, len_asent, len_gsent, len_lsent, matrix, used_possibilities)\n if not consistent: return\n\n elif j == len(matrix) - 1:\n last_resort_axioms(j, matrix)\n if not consistent: return\n j += 1\n\n if consistent:\n add_to_tsent(output, consist, consist, \"\", consist + \"I\")\n\n return reduced\n\n\ndef reconfigure_matrix(j, len_asent, len_gsent, len_lsent, matrix, used_possibilities, definiendum=\"\"):\n global output\n if not consistent: return\n output.lsent_list = output.lsent_list[:len_lsent] + sorted(list(set(output.lsent_list[len_lsent:])))\n # the point of the following is that if (b > c) & (b I d) = (b I e) in (b I d)\n # then it would be useless to (b > c) in (b I e)\n if used_possibilities != []:\n # if the used possibilities are blank then the ax id tense was used as last resort\n for snum in range(len_asent, len(output.all_sent)):\n do_not_instantiate.append([snum, matrix[j][3]])\n for possibility in used_possibilities:\n do_not_instantiate.append([possibility[0], matrix[j][3]])\n else:\n for snum in range(len_asent, len(output.all_sent)):\n do_not_instantiate.append([snum, definiendum + \"0\"])\n delete_irrelevant_lsent(len_asent)\n get_hypotheticals(len_asent)\n build_matrix(matrix, 0, len(output.gsent), len_lsent, len(output.lsent_list))\n build_matrix(matrix, len_gsent, len(output.gsent), 0, len_lsent)\n return\n\n\ndef eliminate_impossibilities(possibilities, ndefiniendum):\n i = 0\n while i < len(possibilities):\n k = 0\n while k < len(possibilities[i]):\n if isinstance(possibilities[i][k], int):\n if [possibilities[i][k], ndefiniendum] in do_not_instantiate:\n del possibilities[i][k]\n k -= 1\n k += 1\n i += 1\n\n return\n\n\ndef loop_through_gsent2(possibilities, matrix, prev_instant, j):\n ndefiniendum = matrix[j][3]\n detacher = matrix[j][2]\n fake_lsent = copy.deepcopy(output.lsent_dict)\n cls = output.trans_def.get(ndefiniendum)\n disj_cls = \"\"\n if detacher == 0:\n cls.def_stats.detacher = 0\n remaining_conditions = cls.def_stats.ant_index\n elif detacher == 1:\n cls.def_stats.detacher = 1\n remaining_conditions = cls.def_stats.con_index\n elif cls.def_stats.def_word == 'thing':\n cls.def_stats.now_disjunctive = cls.disjuncts[detacher - 2]\n remaining_conditions = cls.disjuncts[detacher - 2]\n cls.def_stats.detacher = 0\n detacher = 0\n else:\n disj_cls = cls.disjuncts[detacher - 2]\n remaining_conditions = disj_cls.index1\n\n possibilities.append(fake_lsent.get(matrix[j][0]))\n gsent_pos = copy.deepcopy(remaining_conditions)\n gconstants = []\n eliminate_impossibilities(possibilities, ndefiniendum)\n\n if possibilities == [[]]:\n return []\n elif len(remaining_conditions) > 1:\n comp_num = 0\n sentences = cls.sentences\n for gindex in remaining_conditions[1:]:\n if isinstance(gindex, list):\n gconstant, comp_num = get_complex_constant(cls, comp_num, detacher, disj_cls)\n else:\n gconstant = sentences[gindex][58]\n if gconstant == matrix[j][0] or gconstant == 'thing':\n gsent_pos.remove(gindex)\n else:\n lindexes = output.lsent_dict.get(gconstant)\n if lindexes != None:\n for lst in lindexes:\n if [lst, ndefiniendum] not in do_not_instantiate:\n possibilities.append(lindexes)\n gconstants.append(gconstant)\n break\n else:\n return []\n else:\n rearrange_matrix(matrix, j, detacher, remaining_conditions, gconstant, gindex)\n return []\n\n if len(remaining_conditions) == 1:\n i = 0\n while i < len(possibilities):\n if [possibilities[0][i], ndefiniendum] in do_not_instantiate:\n del possibilities[0]\n else:\n i += 1\n\n cls.def_stats.detacher = detacher\n _ = loop_through_gsent3(possibilities, cls, prev_instant, flatten_list(gsent_pos))\n used_possibilities, failed = _\n\n if failed != [] and len(failed[0]) > 1:\n add_to_failures(failed, ndefiniendum, cls)\n\n return used_possibilities\n\n\ndef add_to_failures(failed, ndefiniendum, cls):\n if ndefiniendum not in output.near_matches.keys():\n output.near_matches.update({cls.def_stats.def_word_num: failed})\n else:\n failures = output.near_matches.get(ndefiniendum)\n for fail in failed:\n failures.append(fail)\n\n\ndef get_complex_constant(cls, comp_num, detacher, disj_cls):\n if detacher == 0:\n gconstant = list(cls.def_stats.ant_comp_const)[comp_num]\n elif detacher == 1:\n gconstant = list(cls.def_stats.con_comp_const)[comp_num]\n else:\n gconstant = disj_cls.comp_const[comp_num]\n comp_num += 1\n\n return gconstant, comp_num\n\n\ndef rearrange_matrix(matrix, j, detacher, remaining_conditions, gconstant, gindex):\n if matrix[j][3] in output.near_matches.keys():\n return\n remaining_conditions.remove(gindex)\n gsent = matrix[j][3]\n remaining_conditions.insert(0, gindex)\n for k in range(j + 1, len(matrix)):\n if matrix[k][3] == gsent and matrix[k][2] == detacher:\n matrix[k][1] = gconstant\n\n for e, lst in enumerate(output.gsent):\n if lst[2] == gsent:\n lst[0] = gconstant\n break\n\n return\n\n\ndef loop_through_gsent3(possibilities, cls, prev_instant, gsent_pos):\n global output, consistent\n\n dead_combinations = []\n conj_intro_pos = []\n possibilities = [i for i in itertools.product(*possibilities)]\n combine_lists(possibilities, conj_intro_pos)\n used_possibilities = []\n failed_possibilities = []\n failures = output.near_matches.get(cls.def_stats.def_word_num, [])\n if failures != []:\n bb = 8\n\n for e, possibility in enumerate(possibilities):\n\n if possibility not in failures:\n abbrev_dict, match_found = variables_match(gsent_pos, possibility, cls, dead_combinations)\n if match_found:\n if cls.def_stats.def_word == 'thing':\n pos = universal_instantiation(abbrev_dict, possibility, cls)\n conj_intro_pos[e] = pos\n if [possibility, cls.def_stats.def_word_num] not in prev_instant:\n consistent = change_abbrev(abbrev_dict, cls, conj_intro_pos[e], output, dictionary)\n prev_instant.append([possibility, cls.def_stats.def_word_num])\n\n if not consistent:\n return used_possibilities.append(possibility), []\n else:\n used_possibilities.append(possibility)\n else:\n failed_possibilities.append(possibility)\n\n return used_possibilities, failed_possibilities\n\n\ndef combine_lists(possibilities, conj_intro_pos):\n e = 0\n while e < len(possibilities):\n possibility = possibilities[e]\n list1 = []\n temp_conj = []\n for lst in possibility:\n\n if isinstance(lst, list):\n temp_conj.append(output.all_sent[lst[0]][44])\n list1 += lst\n else:\n temp_conj.append(output.all_sent[lst][44])\n list1.append(lst)\n if len(list1) == len(set(list1)):\n possibilities[e] = list1\n conj_intro_pos.append(temp_conj)\n e += 1\n else:\n del possibilities[e]\n\n return\n\n\ndef are_identical_unique_obj(i, j, sentences):\n if output.all_sent[i][13] == '=' and sentences[j][13] == '=' and \\\n all(output.all_sent[i][x] == sentences[j][y] for x, y in zip(output.all_sent[i][42], sentences[j][42])):\n return True\n return False\n\n\ndef variables_match(gsent_pos, possibility, cls, dead_combinations):\n if is_dead_combination(dead_combinations, possibility):\n return {}, False\n abbrev_dict = {}\n used_lesser = []\n sentences = cls.sentences\n detacher = cls.def_stats.detacher\n if cls.def_stats.def_word_num == 'qua0':\n bb = 8\n\n for e, i in enumerate(possibility):\n j = gsent_pos[e]\n if j == 61:\n bb = 8\n used_lesser.append(i)\n if are_identical_unique_obj(i, j, sentences):\n return {}, True\n\n else:\n\n for pos in output.all_sent[i][42]:\n gvar = sentences[j][pos]\n lvar = output.all_sent[i][pos]\n if lvar == 'f' + l1:\n bb = 8\n\n # for those sentences of the form y = time, 'time' cannot be replaced\n if lvar != gvar and gvar not in output.constants \\\n and gvar not in output.abbreviations.values():\n var = abbrev_dict.get(output.all_sent[i][pos])\n if pos == 8 and lvar == None or sentences[j][pos] == None:\n # this is because 8 is the place of the propositional variable and\n # sometimes some sentences will have it and others won't\n pass\n elif (var == None and gvar in abbrev_dict.values()):\n dead_combinations.append(copy.deepcopy(used_lesser))\n return {}, False\n elif var == None:\n abbrev_dict.update({lvar: gvar})\n elif var != sentences[j][pos]:\n dead_combinations.append(copy.deepcopy(used_lesser))\n return {}, False\n elif lvar in output.constants and gvar in output.constants \\\n and gvar != lvar:\n return {}, False\n else:\n if detacher == 0:\n idx = cls.def_stats.ant_index[0]\n del cls.def_stats.ant_index[0]\n cls.def_stats.ant_index.append(idx)\n elif detacher == 1:\n idx = cls.def_stats.con_index[0]\n del cls.def_stats.con_index[0]\n cls.def_stats.con_index.append(idx)\n\n if abbrev_dict == {}: return {}, False\n return abbrev_dict, True\n\n\ndef is_dead_combination(dead_detach, possibility):\n # if we know that detach sentences 6 and 4, for example, are impossible then any instantiation\n # which uses sentences 6 and 4 will also be impossible\n for dead_list in dead_detach:\n if len(set(dead_list).intersection(set(possibility))) == len(dead_list):\n return True\n return False\n\n\ndef get_detach_idx(possibility, k):\n for num in possibility:\n sent = output.all_sent[num]\n for noun in sent[42]:\n if sent[noun] == k:\n return num\n raise Exception('you failed to find the thing sentence')\n\n\ndef universal_instantiation(abbrev_map, possibility, cls):\n # the thing conditional's remaining conditions always has the consq\n # first, so for conj intro, we must use all of the nums in the possibility\n # except the first one\n ant_set = []\n ant_setp = []\n ancestors = []\n sentences = cls.sentences\n thing_concept = get_key(output.abbreviations, 'thing')\n\n for k, v in abbrev_map.items():\n for sent in sentences:\n if sent[10] == v and sent[13] == 'I' and sent[14] == thing_concept:\n str1 = \"(\" + k + \" I \" + thing_concept + \")\"\n str1p = name_sent(str1, output.prop_name)\n output.oprop_name[str1p] = str1\n ant_set.append(str1)\n ant_setp.append(str1p)\n if len(possibility) > 1:\n idx = get_detach_idx(possibility, k)\n else:\n idx = possibility[0]\n\n sent1 = output.all_sent[idx][0] + \" \" + implies + \" \" + str1\n sent1p = output.all_sent[idx][3] + output.all_sent[idx][2] + \" \" + implies + \" \" + str1p\n add_to_tsent(output, sent1, sent1p, \"\", \"LE ENT\")\n add_to_tsent(output, str1, str1p, \"\", \"MP\", 0, output.all_sent[possibility[0]][44])\n ancestors.append(output.tindex)\n\n for num in possibility[1:]:\n ancestors.append(output.all_sent[num][44])\n\n return ancestors\n\n\ndef last_resort_axioms(j, matrix, first_resort=False):\n if proof_kind == 'lemmas': return\n global output, consistent, rel_abbrev\n len_gsent = len(output.gsent)\n len_lsent = len(output.lsent_list)\n len_asent = len(output.all_sent)\n total_constants = set(output.abbreviations.keys()) | output.constants\n for con in total_constants:\n if isvariable(con): rel_abbrev.add(con)\n\n n = len(output.trans_def) if not first_resort else 1\n for itm in range(n):\n item1 = list(output.trans_def)[itm]\n cls = output.trans_def.get(item1)\n if cls.def_stats.already_instantiated == False:\n sentences = cls.sentences\n definiendum = cls.def_stats.def_word\n abbrev_dict = {}\n relevant = False\n for num in cls.def_stats.ant_index:\n if isinstance(num, int):\n for idx in sentences[num][42]:\n if sentences[num][idx] not in total_constants and \\\n sentences[num][idx] not in abbrev_dict.values():\n abbrev_dict.update({output.variables[0]: sentences[num][idx]})\n del output.variables[0]\n if sentences[num][idx] in rel_abbrev:\n relevant = True\n elif sentences[num][58] not in output.lsent_list:\n relevant = True\n\n if relevant:\n tot_idx = cls.def_stats.tot_sent_idx\n cls.def_stats.detacher = 0\n consistent = change_abbrev(abbrev_dict, cls, [tot_idx], output, dictionary, \"ax ind tense\")\n get_relevant_abbreviations(len_asent)\n if not first_resort:\n reconfigure_matrix(j, len_asent, len_gsent, len_lsent, matrix, [], definiendum)\n len_gsent = len(output.gsent)\n len_lsent = len(output.lsent_list)\n len_asent = len(output.all_sent)\n\n return\n\n\ndef add_to_prop(dict1, props, var):\n for prop in list(props):\n\n dict1.setdefault(var, set()).add(prop)\n\n\ndef employ_lemmas():\n global consistent\n neg_found = []\n prop_by_var = {}\n prop_by_neg_var = {}\n pos_mol = {}\n\n\n for e, sent in enumerate(output.all_sent):\n assert \"~\" not in sent[0] or sent[3] == \"~\"\n for num in sent[42]:\n if sent[13] in [\"I\", \"J\", \"V\"] and \\\n sent[14] in output.abbreviations.keys() and num == 14:\n pass\n else:\n var = sent[num]\n constant = sent[58]\n oconstant = constant\n if sent[3] == \"~\":\n neg_found.append(sent[num])\n constant = sent[58].replace(\"~\", \"\")\n constant = constant.strip()\n\n pos = dictionary.pos.get(constant)\n if pos[0] == 'r':\n constant = str(num) + sent[58]\n oconstant = constant\n\n props = dictionary.entailments.get(constant)\n if props != None:\n props = props | {constant}\n else:\n props = {constant}\n\n if sent[3] == \"~\":\n add_to_prop(prop_by_neg_var,props, var)\n else:\n add_to_prop(prop_by_var, props, var)\n pos_mol.setdefault(var, set()).add(oconstant)\n\n\n for var, prop in pos_mol.items():\n if len(prop) > 1:\n power_sets = powerset(prop)\n for st in power_sets:\n if len(st) == 2:\n\n list1 = [st[0], st[1]]\n list1.sort()\n tvalue = lemmata.get(\".\".join(list1))\n assert tvalue != None\n if not tvalue:\n consistent = False\n return\n\n\n if neg_found:\n for var in neg_found:\n neg_prop = prop_by_neg_var.get(var)\n prop = prop_by_var.get(var)\n if len(neg_prop & prop) > 0:\n consistent = False\n\n return\n\n\n","sub_path":"inference2/Proofs/search_for_instantiation.py","file_name":"search_for_instantiation.py","file_ext":"py","file_size_in_byte":40251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"395720772","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nfrom sys import platform\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QHBoxLayout,\nQAction, qApp, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QMainWindow)\nfrom PyQt5.QtGui import QIcon, QFont, QPalette, QColor\nfrom PyQt5.QtCore import pyqtSlot, Qt\nfrom sys import platform\n\nclass Menu(QMainWindow):\n def __init__(self, parent=None, DB=None):\n super(Menu, self).__init__(parent)\n self.DB = DB\n self.form_widget = FormWidget(self, DB) \n self.setCentralWidget(self.form_widget) \n self.menuTop()\n self.showFullScreen()\n \n def menuTop(self):\n exitAct = QAction(QIcon('salir.png'), '&SALIR', self) \n exitAct.setShortcut('Ctrl+Q')\n exitAct.setStatusTip('Salir de la aplicación')\n exitAct.triggered.connect(qApp.quit)\n self.statusBar()\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('&Archivo')\n fileMenu.addAction(exitAct)\n\n \nclass FormWidget(QWidget):\n\n def __init__(self, parent, DB=None): \n super(FormWidget, self).__init__(parent)\n self.title = 'MENÚ'\n self.left = 500\n self.top = 350\n self.width = 800\n self.height = 400\n self.DB = DB\n self.initUI()\n \n\n def initUI(self):\n print('Menu paginas')\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n self.createGridLayout()\n \n windowLayout = QVBoxLayout()\n windowLayout.addWidget(self.horizontalGroupBox)\n self.setLayout(windowLayout)\n \n self.showFullScreen()\n\n def createGridLayout(self):\n self.horizontalGroupBox = QGroupBox(\"MENÚ PRINCIPAL\")\n \n layout = QGridLayout()\n layout.setColumnStretch(1, 3)\n \n btnNuevo = QPushButton(\"NUEVO ACTIVO\", self)\n btnNuevo.setFixedWidth(135)\n btnNuevo.setFixedHeight(80)\n \n btnNuevo.clicked.connect(self.gotToNuevoActivo)\n\n btnLectura = QPushButton(\" LECTURA DE ACTIVO \", self)\n #btnLectura.setMinimumWidth(50)\n btnLectura.setFixedWidth(180)\n btnLectura.setFixedHeight(80)\n\n btnLectura.clicked.connect(self.gotToBuscarActivo)\n\n btnReporte = QPushButton(\"REPORTE\", self)\n btnReporte.setFixedWidth(135)\n btnReporte.setFixedHeight(80)\n btnReporte.clicked.connect(self.gotToReportes)\n \n layout.addWidget(btnNuevo,0,0) \n layout.addWidget(btnLectura,0,1) \n layout.addWidget(btnReporte,0,2) \n \n self.horizontalGroupBox.setLayout(layout)\n\n def gotToNuevoActivo(self):\n self.close()\n from paginas.NuevoActivo import NuevoActivo \n self.SW = NuevoActivo(None, self.DB)\n\n def gotToBuscarActivo(self):\n self.close()\n from paginas.BuscarActivo import BuscarActivo \n self.SW = BuscarActivo(None, self.DB)\n\n def gotToReportes(self):\n self.close()\n from paginas.Reportes import Reportes \n self.SW = Reportes(None, self.DB)\n\n\nif __name__ == '__main__':\n import sys\n app = QApplication([])\n foo = Menu()\n foo.showFullScreen()\n sys.exit(app.exec_())","sub_path":"paginas/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"163596278","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/6/30 8:43 下午\n# @Author : Li\n# @Email : m15574933885@163.com\n# @File : run_all_cases.py\n# @Software: PyCharm\n\nfrom file.HTMLTestRunner import HTMLTestRunner\nimport unittest\nimport time\nfrom P9.weixin_apitest.common.config import Configs\n\ncof = Configs()\n\n\n# 使用discover方法遍历用例\ndef createSuite():\n testdir = cof.casedir\n suite = unittest.TestSuite()\n discover = unittest.defaultTestLoader.discover(\n start_dir=testdir,\n pattern='weixin_*.py',\n top_level_dir=None\n )\n\n for d in discover: # 找用例文件\n # print('d的值', d)\n for j in d: # 把用例文件里面的用例\n # print('j的值:', j)\n suite.addTests(j)\n\n return suite\n\n\nnow = time.strftime('%Y_%m_%d_%H_%M_%S')\nfp = open(cof.reportpath + now + '_weixin.html',\n 'w+', encoding='utf-8')\nrunner = HTMLTestRunner(stream=fp, title='微信公众号接口报告', description='微信公众号接口报告')\nrunner.run(createSuite())\n","sub_path":"task/weixin_apitest/run_all_cases.py","file_name":"run_all_cases.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"455026787","text":"#!/usr/bin/env python\n\n# python 3 compatibility\nfrom __future__ import print_function\n\n# stdlib imports\nfrom xml.dom import minidom\nfrom datetime import datetime\nfrom collections import OrderedDict\nimport re\nimport sys\n\nfrom xml.sax import saxutils\n\n# third party\nfrom .gridbase import Grid\nfrom .multiple import MultiGrid\nfrom .dataset import DataSetException\nfrom .grid2d import Grid2D\nfrom .geodict import GeoDict\nimport numpy as np\nimport pandas as pd\n\n\nGRIDKEYS = {\n \"event_id\": \"string\",\n \"shakemap_id\": \"string\",\n \"shakemap_version\": \"int\",\n \"code_version\": \"string\",\n \"process_timestamp\": \"datetime\",\n \"shakemap_originator\": \"string\",\n \"map_status\": \"string\",\n \"shakemap_event_type\": \"string\",\n}\n\nEVENTKEYS = {\n \"event_id\": \"string\",\n \"magnitude\": \"float\",\n \"depth\": \"float\",\n \"lat\": \"float\",\n \"lon\": \"float\",\n \"event_timestamp\": \"datetime\",\n \"event_network\": \"string\",\n \"event_description\": \"string\",\n}\n\nSPECKEYS = {\n \"lon_min\": \"float\",\n \"lon_max\": \"float\",\n \"lat_min\": \"float\",\n \"lat_max\": \"float\",\n \"nominal_lon_spacing\": \"float\",\n \"nominal_lat_spacing\": \"float\",\n \"nlon\": \"int\",\n \"nlat\": \"int\",\n}\n\nFIELDKEYS = OrderedDict()\nFIELDKEYS[\"lat\"] = (\"dd\", \"%.4f\")\nFIELDKEYS[\"lon\"] = (\"dd\", \"%.4f\")\n\n\nTIMEFMT = \"%Y-%m-%dT%H:%M:%S\"\n\n\ndef _readElement(element, keys):\n \"\"\"Convenience function for reading all attributes of a ShakeMap gridfile element,\n doing data conversion.\n\n Args:\n element (XML DOM):\n XML DOM element with attributes\n keys (dict):\n Dictionary of keys for different elements with types.\n Returns:\n Dictionary of named attributes with values from DOM element, converted to int,\n float or datetime where needed.\n \"\"\"\n eldict = OrderedDict()\n for (key, dtype) in keys.items():\n if dtype == \"datetime\":\n eldict[key] = datetime.strptime(element.getAttribute(key)[0:19], TIMEFMT)\n elif dtype == \"int\":\n try:\n eldict[key] = int(element.getAttribute(key))\n except ValueError:\n eldict[key] = int(float(element.getAttribute(key)))\n elif dtype == \"float\":\n eldict[key] = float(element.getAttribute(key))\n else:\n eldict[key] = element.getAttribute(key)\n return eldict\n\n\ndef _getXMLText(fileobj):\n \"\"\"Convenience function for reading the XML header data in a ShakeMap grid file.\n\n Args:\n fileobj (IO):\n File-like object representing an open ShakeMap grid file.\n Returns:\n All XML header text.\n \"\"\"\n tline = fileobj.readline()\n datamatch = re.compile(\"grid_data\")\n xmltext = \"\"\n tlineold = \"\"\n while not datamatch.search(tline) and tline != tlineold:\n tlineold = tline\n xmltext = xmltext + tline\n tline = fileobj.readline()\n\n xmltext = xmltext + \"\"\n return xmltext\n\n\ndef getHeaderData(shakefile):\n \"\"\"Return all relevant header data from ShakeMap grid.xml file.\n\n Args\n shakefile (str):\n File-like object representing an open ShakeMap grid file.\n Returns:\n Tuple of dictionaries:\n - Dictionary representing the grid element in the ShakeMap header.\n - Dictionary representing the event element in the ShakeMap header.\n - Dictionary representing the grid_specification element in the ShakeMap\n header.\n - Dictionary representing the list of grid_field elements in the ShakeMap\n header.\n - Dictionary representing the list of event_specific_uncertainty elements in\n the ShakeMap header.\n \"\"\"\n f = open(shakefile, \"rt\")\n griddict, eventdict, specdict, fields, uncertainties = _getHeaderData(f)\n f.close()\n return (griddict, eventdict, specdict, fields, uncertainties)\n\n\ndef _getHeaderData(fileobj):\n \"\"\"Return all relevant header data from ShakeMap grid.xml file.\n\n Args:\n fileobj (IO):\n File-like object representing an open ShakeMap grid file.\n Returns:\n Tuple of dictionaries:\n - Dictionary representing the grid element in the ShakeMap header.\n - Dictionary representing the event element in the ShakeMap header.\n - Dictionary representing the grid_specification element in the ShakeMap\n header.\n - Dictionary representing the list of grid_field elements in the ShakeMap\n header.\n - Dictionary representing the list of event_specific_uncertainty elements in\n the ShakeMap header.\n \"\"\"\n xmltext = _getXMLText(fileobj)\n root = minidom.parseString(xmltext)\n griddict = OrderedDict()\n gridel = root.getElementsByTagName(\"shakemap_grid\")[0]\n griddict = _readElement(gridel, GRIDKEYS)\n eventel = root.getElementsByTagName(\"event\")[0]\n eventdict = _readElement(eventel, EVENTKEYS)\n # un-xmlify the location string (convert & to &)\n eventdict[\"event_description\"] = saxutils.unescape(eventdict[\"event_description\"])\n specel = root.getElementsByTagName(\"grid_specification\")[0]\n specdict = _readElement(specel, SPECKEYS)\n field_elements = root.getElementsByTagName(\"grid_field\")\n fields = []\n for fieldel in field_elements:\n att = fieldel.getAttribute(\"name\").lower()\n if att in [\"lon\", \"lat\"]:\n continue\n fields.append(att)\n\n uncertainties = OrderedDict()\n unc_elements = root.getElementsByTagName(\"event_specific_uncertainty\")\n for uncel in unc_elements:\n key = uncel.getAttribute(\"name\")\n value = float(uncel.getAttribute(\"value\"))\n try:\n numsta = int(uncel.getAttribute(\"numsta\"))\n except:\n numsta = 0\n uncertainties[key] = (value, numsta)\n\n return (griddict, eventdict, specdict, fields, uncertainties)\n\n\ndef readShakeFile(fileobj, adjust=\"bounds\"):\n \"\"\"Reads in the data and metadata for a ShakeMap object (can be passed to ShakeGrid\n constructor).\n\n Args:\n fileobj (IO):\n File-like object representing an open ShakeMap grid file.\n adjust (str):\n String (one of 'bounds','res') - adjust some of the ShakeMap parameters as\n necessary (usually \"bounds\").\n None:\n All input parameters are assumed to be self-consistent, an\n exception will be raised if they are not.\n 'bounds':\n dx/dy, nx/ny, xmin/ymax are assumed to be correct, xmax/ymin\n will be recalculated.\n 'res':\n nx/ny, xmin/ymax, xmax/ymin and assumed to be correct, dx/dy\n will be recalculated.\n Returns:\n Tuple containing:\n - Ordered Dictionary with the data layers in ShakeMap (MMI, PGA, PGV, etc.)\n - Geo dictionary describing the spatial extent and resolution of all the\n layers.\n - Dictionary representing the event element in the ShakeMap header.\n - Dictionary representing the grid element in the ShakeMap header.\n - Dictionary representing the list of event_specific_uncertainty elements in\n the ShakeMap header.\n \"\"\"\n griddict, eventdict, specdict, fields, uncertainties = _getHeaderData(fileobj)\n nx = specdict[\"nlon\"]\n ny = specdict[\"nlat\"]\n layers = OrderedDict()\n\n # use pandas read_csv to read in the actual data - this should be faster than\n # numpy's loadtxt\n columns = fields[:]\n columns.insert(0, \"lat\")\n columns.insert(0, \"lon\")\n dframe = pd.read_csv(\n fileobj, sep=r\"\\s+\", names=columns, header=None, comment=\"<\", dtype=np.float32\n )\n for field in fields:\n layers[field] = dframe[field].values.reshape(ny, nx)\n\n # use the numpy loadtxt function to read in the actual data\n # we're cheating by telling numpy.loadtxt that the last two lines of the XML\n # file are comments\n # data = np.loadtxt(fileobj,comments='<').astype('float32')\n # data = data[:,2:] #throw away lat/lon columns\n # for i in range(0,len(fields)):\n # field = fields[i]\n # layers[field] = data[:,i].reshape(ny,nx)\n\n # create the geodict from the grid_spec element\n geodict = GeoDict(\n {\n \"xmin\": specdict[\"lon_min\"],\n \"xmax\": specdict[\"lon_max\"],\n \"ymin\": specdict[\"lat_min\"],\n \"ymax\": specdict[\"lat_max\"],\n \"dx\": specdict[\"nominal_lon_spacing\"],\n \"dy\": specdict[\"nominal_lat_spacing\"],\n \"ny\": specdict[\"nlat\"],\n \"nx\": specdict[\"nlon\"],\n },\n adjust=adjust,\n )\n\n return (layers, geodict, eventdict, griddict, uncertainties)\n\n\nclass ShakeGrid(MultiGrid):\n \"\"\"\n A class that implements a MultiGrid object around ShakeMap grid.xml data sets.\n \"\"\"\n\n def __init__(\n self, layers, geodict, eventDict, shakeDict, uncertaintyDict, field_keys={}\n ):\n \"\"\"Construct a ShakeGrid object.\n\n Args:\n layers (OrderedDict):\n OrderedDict containing ShakeMap data layers (keys are 'pga', etc.,\n values are 2D arrays of data).\n geodict (dict):\n Dictionary specifying the spatial extent,resolution and shape of the\n data.\n eventDict (dict):\n Dictionary with elements:\n - event_id String of event ID (i.e., 'us2015abcd')\n - magnitude Float event magnitude\n - depth Float event depth\n - lat Float event latitude\n - lon Float event longitude\n - event_timestamp Datetime object representing event origin time.\n - event_network Event originating network (i.e., 'us')\n shakeDict (dict):\n Dictionary with elements:\n - event_id String of event ID (i.e., 'us2015abcd')\n - shakemap_id String of ShakeMap ID (not necessarily the same as\n the event ID)\n - shakemap_version Integer ShakeMap version number (i.e., 1)\n - code_version String version of ShakeMap code that created this\n file (i.e.,'4.0')\n - process_timestamp Datetime of when ShakeMap data was created.\n - shakemap_originator String representing network that created the\n ShakeMap\n - map_status String, one of RELEASED, ??\n - shakemap_event_type String, one of ['ACTUAL','SCENARIO']\n uncertaintyDict (dict):\n Dictionary with elements that have keys matching the layers keys, and\n values that are a tuple of that layer's uncertainty (float) and the\n number of stations used to determine that uncertainty (int).\n field_keys (dict):\n Dictionary containing keys matching at least some of input layers. For\n each key, a tuple of (UNITS,DIGITS) where UNITS is a string indicating\n the units of the layer quantity (e.g, cm/s) and DIGITS is the number of\n significant digits that the layer column should be printed with.\n Returns:\n A ShakeGrid object.\n \"\"\"\n self._descriptions = OrderedDict()\n self._layers = OrderedDict()\n self._geodict = geodict\n for (layerkey, layerdata) in layers.items():\n self._layers[layerkey] = Grid2D(data=layerdata, geodict=geodict)\n self._descriptions[layerkey] = \"\"\n self._setEventDict(eventDict)\n self._setShakeDict(shakeDict)\n self._setUncertaintyDict(uncertaintyDict)\n self._field_keys = FIELDKEYS.copy()\n\n # assign the units and digits the user wants\n for layer, layertuple in field_keys.items():\n units, digits = layertuple\n fmtstr = \"%%.%ig\" % digits\n self._field_keys[layer] = (units, fmtstr)\n\n # if the user missed any, fill in with default values\n for layer in self._layers.keys():\n if layer in self._field_keys:\n continue\n self._field_keys[layer] = (\"\", \"%.4g\")\n\n @classmethod\n def getFileGeoDict(cls, shakefilename, adjust=\"bounds\"):\n \"\"\"Get the spatial extent, resolution, and shape of grids inside ShakeMap grid\n file.\n\n Args:\n shakefilename (str):\n File name of ShakeMap grid file.\n adjust (str):\n String (one of 'bounds','res') - adjust some of the ShakeMap parameters\n as necessary (usually \"bounds\").\n None:\n All input parameters are assumed to be self-consistent, an exception\n will be raised if they are not.\n 'bounds':\n dx/dy, nx/ny, xmin/ymax are assumed to be correct, xmax/ymin will\n be recalculated.\n 'res':\n nx/ny, xmin/ymax, xmax/ymin and assumed to be correct, dx/dy will be\n recalculated.\n Returns:\n GeoDict specifying spatial extent, resolution, and shape of grids inside\n ShakeMap grid file.\n \"\"\"\n isFileObj = False\n if not hasattr(shakefilename, \"read\"):\n shakefile = open(shakefilename, \"r\")\n else:\n isFileObj = True\n shakefile = shakefilename\n griddict, eventdict, specdict, fields, uncertainties = _getHeaderData(shakefile)\n if isFileObj:\n shakefile.close()\n geodict = GeoDict(\n {\n \"xmin\": specdict[\"lon_min\"],\n \"xmax\": specdict[\"lon_max\"],\n \"ymin\": specdict[\"lat_min\"],\n \"ymax\": specdict[\"lat_max\"],\n \"dx\": specdict[\"nominal_lon_spacing\"],\n \"dy\": specdict[\"nominal_lat_spacing\"],\n \"ny\": specdict[\"nlat\"],\n \"nx\": specdict[\"nlon\"],\n },\n adjust=adjust,\n )\n return geodict\n\n @classmethod\n def load(\n cls,\n shakefilename,\n samplegeodict=None,\n resample=False,\n method=\"linear\",\n doPadding=False,\n padValue=np.nan,\n adjust=\"bounds\",\n ):\n\n # readShakeFile takes a file object. Figure out if shakefilename is a file\n # name or file object.\n if not hasattr(shakefilename, \"read\"):\n shakefile = open(shakefilename, \"r\")\n else:\n shakefile = shakefilename\n\n # read everything from the file\n (layers, fgeodict, eventDict, shakeDict, uncertaintyDict) = readShakeFile(\n shakefile, adjust=adjust\n )\n\n # If the sample grid is aligned with the host grid, then resampling won't\n # accomplish anything\n # if samplegeodict is not None and fgeodict.isAligned(samplegeodict):\n # resample = False\n\n # get area of shakemap that intersects with the desired input sampling grid\n if samplegeodict is not None:\n sampledict = fgeodict.getIntersection(samplegeodict)\n else:\n sampledict = fgeodict\n\n # Ensure that the two grids at least 1) intersect and 2) are aligned if\n # resampling is True.\n # parent static method, may raise an exception\n Grid2D.verifyBounds(fgeodict, sampledict, resample=resample)\n\n pad_dict = Grid2D.getPadding(\n fgeodict, samplegeodict, doPadding=doPadding\n ) # parent static method\n newlayers = OrderedDict()\n newgeodict = None\n for layername, layerdata in layers.items():\n data, geodict = Grid2D.padGrid(layerdata, fgeodict, pad_dict)\n grid = Grid2D(data, geodict)\n if resample:\n grid = grid.interpolateToGrid(samplegeodict, method=method)\n\n if np.any(np.isinf(grid._data)):\n grid._data[np.isinf(grid._data)] = padValue\n\n newlayers[layername] = grid.getData()\n if newgeodict is None:\n newgeodict = grid.getGeoDict().copy()\n\n return cls(newlayers, newgeodict, eventDict, shakeDict, uncertaintyDict)\n\n def interpolateToGrid(self, geodict, method=\"linear\"):\n \"\"\"\n Given a geodict specifying another grid extent and resolution, resample all\n layers in ShakeGrid to match.\n\n Args:\n geodict (dict):\n geodict dictionary from another grid whose extents are inside the\n extent of this ShakeGrid.\n method (str):\n Optional interpolation method - ['linear', 'cubic','nearest']\n Raises:\n DataSetException:\n If the GeoDict object upon which this function is being called is not\n completely contained by the grid to which this ShakeGrid is being\n resampled.\n DataSetException:\n If the method is not one of ['nearest','linear','cubic'] If the\n resulting interpolated grid shape does not match input geodict.\n This function modifies the internal griddata and geodict object variables.\n \"\"\"\n multi = super(ShakeGrid, self).interpolateToGrid(geodict, method=method)\n layers = OrderedDict()\n geodict = multi.getGeoDict()\n # I need to get the layer data here...\n for layername in multi.getLayerNames():\n layers[layername] = multi.getLayer(layername).getData()\n eventdict = self.getEventDict()\n shakedict = self.getShakeDict()\n uncdict = self._uncertaintyDict\n shakemap = ShakeGrid(layers, geodict, eventdict, shakedict, uncdict)\n return shakemap\n\n def subdivide(self, finerdict, cellFill=\"max\"):\n \"\"\"Subdivide the cells of the host grid into finer-resolution cells.\n\n Args:\n finerdict (geodict):\n GeoDict object defining a grid with a finer resolution than the host\n grid.\n cellFill (str):\n String defining how to fill cells that span more than one host grid\n cell.\n Choices are:\n 'max': Choose maximum value of host grid cells.\n 'min': Choose minimum value of host grid cells.\n 'mean': Choose mean value of host grid cells.\n Returns:\n ShakeGrid instance with host grid values subdivided onto finer grid.\n Raises:\n DataSetException:\n When finerdict is not a) finer resolution or b) does not intersect.x or\n cellFill is not valid.\n \"\"\"\n shakemap = super.subdivide(finerdict, cellFill=cellFill)\n shakemap._setEventDict(self.getEventDict())\n shakemap._setShakeDict(self.getShakeDict())\n shakemap._setUncertaintyDict(self.self._uncertaintyDict)\n return shakemap\n\n def save(self, filename, version=1):\n \"\"\"Save a ShakeGrid object to the grid.xml format.\n\n Args:\n filename (str):\n File name or file-like object.\n version (int):\n Integer Shakemap version number.\n \"\"\"\n\n # handle differences btw python2 and python3\n isThree = True\n if sys.version_info.major == 2:\n isThree = False\n\n isFile = False\n if not hasattr(filename, \"read\"):\n isFile = True\n f = open(filename, \"wb\")\n else:\n f = filename\n SCHEMA1 = \"http://www.w3.org/2001/XMLSchema-instance\"\n SCHEMA2 = \"http://earthquake.usgs.gov/eqcenter/shakemap\"\n SCHEMA3 = \"http://earthquake.usgs.gov http://earthquake.usgs.gov/eqcenter/shakemap/xml/schemas/shakemap.xsd\"\n\n f.write(b'')\n fmt = '\\n'\n tpl = (\n SCHEMA1,\n SCHEMA2,\n SCHEMA3,\n self._shakeDict[\"event_id\"],\n self._shakeDict[\"shakemap_id\"],\n self._shakeDict[\"shakemap_version\"],\n self._shakeDict[\"code_version\"],\n datetime.utcnow().strftime(TIMEFMT),\n self._shakeDict[\"shakemap_originator\"],\n self._shakeDict[\"map_status\"],\n self._shakeDict[\"shakemap_event_type\"],\n )\n if isThree:\n f.write(bytes(fmt % tpl, \"utf-8\"))\n else:\n f.write(fmt % tpl)\n\n # location string could have non-valid XML characters in it (like &). Make that\n # string safe for XML before we write it out\n locstr = saxutils.escape(self._eventDict[\"event_description\"])\n\n fmt = '\\n'\n event_extras = \"\"\n if \"intensity_observations\" in self._eventDict:\n event_extras += (\n ' intensity_observations=\"%s\"'\n % self._eventDict[\"intensity_observations\"]\n )\n if \"seismic_stations\" in self._eventDict:\n event_extras += (\n ' seismic_stations=\"%s\"' % self._eventDict[\"seismic_stations\"]\n )\n if \"point_source\" in self._eventDict:\n event_extras += ' point_source=\"%s\"' % self._eventDict[\"point_source\"]\n tpl = (\n self._eventDict[\"event_id\"],\n self._eventDict[\"magnitude\"],\n self._eventDict[\"depth\"],\n self._eventDict[\"lat\"],\n self._eventDict[\"lon\"],\n self._eventDict[\"event_timestamp\"].strftime(TIMEFMT),\n self._eventDict[\"event_network\"],\n locstr,\n event_extras,\n )\n if isThree:\n f.write(bytes(fmt % tpl, \"utf-8\"))\n else:\n f.write(fmt % tpl)\n fmt = ''\n tpl = (\n self._geodict.xmin,\n self._geodict.ymin,\n self._geodict.xmax,\n self._geodict.ymax,\n self._geodict.dx,\n self._geodict.dy,\n self._geodict.nx,\n self._geodict.ny,\n )\n if isThree:\n f.write(bytes(fmt % tpl, \"utf-8\"))\n else:\n f.write(fmt % tpl)\n fmt = '\\n'\n for (key, unctuple) in self._uncertaintyDict.items():\n value, numsta = unctuple\n tpl = (key, value, numsta)\n if isThree:\n f.write(bytes(fmt % tpl, \"utf-8\"))\n else:\n f.write(fmt % tpl)\n f.write(b'\\n')\n f.write(b'\\n')\n idx = 3\n fmt = '\\n'\n data_formats = [\"%.4f\", \"%.4f\"]\n for field in self._layers.keys():\n tpl = (idx, field.upper(), self._field_keys[field][0])\n data_formats.append(self._field_keys[field][1])\n if isThree:\n db = bytes(fmt % tpl, \"utf-8\")\n else:\n db = fmt % tpl\n f.write(db)\n idx += 1\n f.write(b\"\\n\")\n lat, lon = Grid().getLatLonMesh(self._geodict)\n\n # let's see if we can use pandas to write data out as well\n # this was really slow, mostly because we had to make strings out\n # of each column in order to get column-specific formatting.\n # return to this someday and re-investigate.\n\n # ldict = OrderedDict()\n # for lname,lgrid in self._layers.items():\n # ldict[lname] = lgrid.getData().flatten()\n\n # df = pd.DataFrame.from_dict(ldict)\n # df['lat'] = lat.flatten()\n # df['lon'] = lon.flatten()\n # cols = df.columns.tolist()\n # cols.remove('lat')\n # cols.remove('lon')\n # cols.insert(0,'lat')\n # cols.insert(0,'lon')\n # df = df[cols]\n # for field,fieldtpl in FIELDKEYS.items():\n # fieldfmt = fieldtpl[1]\n # df[field].map(lambda x: fieldfmt % x)\n # df.to_csv(f,sep=' ')\n\n nfields = 2 + len(self._layers)\n data = np.zeros((self._geodict.ny * self._geodict.nx, nfields))\n # the data are ordered from the top left, so we need to invert the latitudes to\n # start from the top left\n lat = lat[::-1]\n data[:, 0] = lon.flatten()\n data[:, 1] = lat.flatten()\n fidx = 2\n for grid in self._layers.values():\n data[:, fidx] = grid.getData().flatten()\n fidx += 1\n np.savetxt(f, data, delimiter=\" \", fmt=data_formats)\n f.write(b\"\\n\\n\")\n if isFile:\n f.close()\n\n def _checkType(self, key, dtype):\n \"\"\"Internal method used to validate the types of the input dictionaries used in\n constructor.\n\n Args:\n key (str):\n String key value\n dtype (str):\n Expected data type of key.\n Returns:\n True if key matches expected dtype, False if not.\n \"\"\"\n # In Python 3 str type is now unicode by default, no such thing as unicode any\n # more.\n if sys.version_info.major == 2:\n strtypes = str\n else:\n strtypes = (str,)\n if dtype == \"string\" and (not isinstance(key, strtypes)):\n return False\n if dtype == \"int\" and not isinstance(key, int):\n return False\n if dtype == \"float\" and not isinstance(key, float):\n return False\n if dtype == \"datetime\" and not isinstance(key, datetime):\n return False\n return True\n\n def _setEventDict(self, eventdict):\n \"\"\"Set the event dictionary, validating all values in the dictionary.\n\n Args:\n eventdict (dict):\n Event dictionary (see constructor).\n Raises:\n DataSetException:\n When one of the values in the dictionary does not match its expected type.\n \"\"\"\n for (key, dtype) in EVENTKEYS.items():\n if key not in eventdict:\n raise DataSetException('eventdict is missing key \"%s\"' % key)\n if not self._checkType(eventdict[key], dtype):\n raise DataSetException(\n 'eventdict key value \"%s\" is the wrong datatype'\n % str(eventdict[key])\n )\n self._eventDict = eventdict.copy()\n\n def getEventDict(self):\n \"\"\"Get the event dictionary (the attributes of the \"event\" element in the\n ShakeMap header).\n\n Returns:\n Dictionary containing the following fields:\n - event_id: String like \"us2016abcd\".\n - magnitude: Earthquake magnitude.\n - lat: Earthquake latitude.\n - lon: Earthquake longitude.\n - depth: Earthquake depth.\n - event_timestamp: Earthquake origin time.\n - event_network: Network of earthquake origin.\n - event_description: Description of earthquake location.\n \"\"\"\n return self._eventDict\n\n def _setShakeDict(self, shakedict):\n \"\"\"Set the shake dictionary, validating all values in the dictionary.\n\n Args:\n shakedict (dict):\n Shake dictionary (see constructor).\n Raises:\n DataSetException:\n When one of the values in the dictionary does not match its expected\n type.\n \"\"\"\n for (key, dtype) in GRIDKEYS.items():\n if key not in shakedict:\n raise DataSetException('shakedict is missing key \"%s\"' % key)\n if not self._checkType(shakedict[key], dtype):\n raise DataSetException(\n 'shakedict key value \"%s\" is the wrong datatype'\n % str(shakedict[key])\n )\n self._shakeDict = shakedict.copy()\n\n def getShakeDict(self):\n \"\"\"Get the shake dictionary (the attributes of the \"shakemap_grid\" element in\n the ShakeMap header).\n\n Returns:\n Dictionary containing the following fields:\n - event_id: String like \"us2016abcd\".\n - shakemap_id: String like \"us2016abcd\".\n - shakemap_version: Version of the map that has been created.\n - code_version: Version of the ShakeMap software that was used to\n create the map.\n - shakemap_originator: Network that created the ShakeMap.\n - map_status: One of 'RELEASED' or 'REVIEWED'.\n - shakemap_event_type: One of 'ACTUAL' or 'SCENARIO'.\n \"\"\"\n return self._shakeDict\n\n def _setUncertaintyDict(self, uncertaintyDict):\n \"\"\"Set the uncertainty dictionary.\n\n Args:\n uncertaintyDict (dict):\n Uncertainty dictionary (see constructor).\n \"\"\"\n self._uncertaintyDict = uncertaintyDict.copy()\n","sub_path":"mapio/shake.py","file_name":"shake.py","file_ext":"py","file_size_in_byte":29523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"266854322","text":"# import os\n# working_directory = r'F:\\CityU\\Hong Kong Twitter 2016\\emoji2vec'\n# os.chdir(working_directory)\n# print('The current working directory has changed to: ',os.getcwd())\n\n#===================================================================================================================\n# Impore Relevant Packages\n# Commonly used\nimport os\nimport gensim.models as gs\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\nimport time\nimport read_data\nimport utils\nimport csv\n\n# Classifiers\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn.utils import shuffle, compute_class_weight\n\n# Model Evaluations\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix, precision_score, recall_score, \\\n classification_report\nfrom sklearn.model_selection import GridSearchCV, train_test_split, StratifiedKFold\n\n# This paper requires\nimport phrase2vec as p2v\nfrom twitter_sentiment_dataset import TweetTrainingExample\nfrom model import ModelParams\n\n# Build my classifier\nfrom keras.utils.np_utils import to_categorical\nfrom keras.preprocessing.text import Tokenizer\nfrom keras import backend as K\nfrom keras import models\nfrom keras import layers\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom tensorflow.keras import backend\nfrom tensorflow import set_random_seed\n\n# tokenization\nimport nltk.tokenize as tk\n\n# Cope with the imbalanced issue\nfrom imblearn.pipeline import make_pipeline\nfrom imblearn.over_sampling import ADASYN, SMOTE, RandomOverSampler\nfrom imblearn.metrics import geometric_mean_score\n\n# Visualization\nfrom matplotlib import pyplot as plt\n\n# Ignore the tedious warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings('ignore', category=FutureWarning)\n\n# Specify the random seed\nrandom_seed = 777\n\n# Some important paths\nw2v_path = './data/word2vec/'\n\n\ndef list_of_array_to_array(list_array):\n shape = list(list_array[0].shape)\n shape[:0] = [len(list_array)]\n arr = np.concatenate(list_array).reshape(shape)\n return arr\n\n\ndef precision(y_true, y_pred):\n \"\"\"Precision metric.\n\n Only computes a batch-wise average of precision.\n\n Computes the precision, a metric for multi-label classification of\n how many selected items are relevant.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n\ndef recall(y_true, y_pred):\n \"\"\"Recall metric.\n\n Only computes a batch-wise average of recall.\n\n Computes the recall, a metric for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n\ndef f1(y_true, y_pred):\n def recall(y_true, y_pred):\n \"\"\"Recall metric.\n\n Only computes a batch-wise average of recall.\n\n Computes the recall, a metric for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n def precision(y_true, y_pred):\n \"\"\"Precision metric.\n\n Only computes a batch-wise average of precision.\n\n Computes the precision, a metric for multi-label classification of\n how many selected items are relevant.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n precision = precision(y_true, y_pred)\n recall = recall(y_true, y_pred)\n return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\ndef weighted_categorical_crossentropy(weights):\n \"\"\"\n A weighted version of keras.objectives.categorical_crossentropy\n\n Variables:\n weights: numpy array of shape (C,) where C is the number of classes\n\n Usage:\n weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.\n loss = weighted_categorical_crossentropy(weights)\n model.compile(loss=loss,optimizer='adam')\n \"\"\"\n\n weights = K.variable(weights)\n\n def loss(y_true, y_pred):\n # scale predictions so that the class probas of each sample sum to 1\n y_pred /= K.sum(y_pred, axis=-1, keepdims=True)\n # clip to prevent NaN's and Inf's\n y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())\n # calc\n loss = y_true * K.log(y_pred) * weights\n loss = -K.sum(loss, -1)\n return loss\n\n return loss\n\n\ndef get_ffnn_model(dropout_rate=0.2):\n model = models.Sequential()\n # Dense(1000) is a fully-connected layer with 1000 hidden units.\n # in the first layer, you must specify the expected input data shape:\n # here, 100-dimensional vectors.\n model.add(layers.Dense(1000, activation='relu', input_dim=100, name='dense_1'))\n model.add(layers.Dropout(dropout_rate, name='dropout_1'))\n model.add(layers.Dense(1000, activation='relu',name='dense_2'))\n model.add(layers.Dropout(dropout_rate, name='dropout_2'))\n model.add(layers.Dense(1000, activation='relu',name='dense_3'))\n model.add(layers.Dropout(dropout_rate, name='dropout_3'))\n model.add(layers.Dense(3, activation='softmax', name='output_layer'))\n # loss = weighted_categorical_crossentropy(label_weights)\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=[precision, recall, f1])\n return model\n\n\n# Need to change\ndef kfold_with_smote(clf, train_valid_data_X, train_valid_label_y, tuned_parameters, X_test, y_test,\n whole_tweets_array, save_path, clf_name=None):\n \"\"\"\n clf: the classifier\n train_valid_data_X: the data used for cross validation with grid search\n train_valid_label_y: the labels used for cross validation with grid search\n tuned_parameters: the hyperparameters we want to tune\n X_test: the test data\n y_test: the test labels\n whole_tweets_array: a numpy array which records the representations of tweets\n save_path: the path used to save predictions\n clf_name: the name of the classifier\n Return: two dictionaries: 1. the best hyperparameters in cross validation; 2. the mean test score in\n 4 fold cross validation\n \"\"\"\n scores = ['f1']\n # The dict which records the performance based on the evaluation metric\n performance_dict = {}\n # The dict which records the best hyparameter setting for the evaluation metric\n params_dict = {}\n for score in scores:\n print()\n print(\"# Use %s to check the model's performance...\" % score)\n # cv = 4 here implements stratified 4 fold cross validation\n # It means that in each fold, the distribution of each label is consistent with the whole training_valid_data\n skf = StratifiedKFold(n_splits=4)\n cross_validation = skf.get_n_splits(train_valid_data_X, train_valid_label_y)\n if score != 'accuracy':\n Grid_clf = GridSearchCV(clf, tuned_parameters, cv=cross_validation, scoring='%s_macro' % score)\n else:\n Grid_clf = GridSearchCV(clf, tuned_parameters, cv=cross_validation, scoring='%s' % score)\n Grid_clf.fit(train_valid_data_X, train_valid_label_y)\n print(\"Best parameters set found on development set:\")\n print()\n params_dict[score] = Grid_clf.best_params_\n print(Grid_clf.best_params_)\n print()\n print(\"Grid scores on the validation set:\")\n print()\n # The means show the mean f1 score across 4 fold cross validation\n # stds records the standard deviations\n means = Grid_clf.cv_results_['mean_test_score']\n stds = Grid_clf.cv_results_['std_test_score']\n for mean, std, params in zip(means, stds, Grid_clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"\n % (mean, std * 2, params))\n performance_dict[score] = means\n # Call predict on the estimator with the best found parameters.\n y_true, y_pred = y_test, Grid_clf.predict(X_test)\n print('The distribution of the test set is: ')\n print(Counter(y_test))\n print('The distribution of the predictions computed by ', clf_name, ' is: ')\n print(Counter(y_pred))\n print()\n # ffnn_dataframe = pd.DataFrame({'y_true': y_true, 'y_pred':y_pred})\n # ffnn_dataframe.to_csv(os.path.join(read_data.desktop, 'ffnn_on_test.csv'))\n\n accuracy = accuracy_score(y_true, y_pred)\n precision = precision_score(y_true, y_pred, average=None)\n precision_macro = precision_score(y_true, y_pred, average='macro')\n recall = recall_score(y_true, y_pred, average=None)\n recall_macro = recall_score(y_true, y_pred, average='macro')\n f1 = f1_score(y_true, y_pred, average=None)\n f1_macro = f1_score(y_true, y_pred, average='macro')\n print('How '+clf_name+' performs on the test set.....')\n print(\"Accuracy: \", accuracy, \"Precision: \", precision, \"Recall: \", recall, 'f1_score: ', f1)\n print('The Macro scores are...')\n print(\"Accuracy: \", accuracy, \"Precision: \", precision_macro, \"Recall: \", recall_macro,\n 'f1_score: ', f1_macro)\n print()\n\n # Make predictions on the review data\n whole_predictions_review = Grid_clf.predict(tweets_representations_whole_sample_array)\n print('The distribution of the review prediction is:')\n print(Counter(whole_predictions_review))\n np.save(os.path.join(save_path, 'whole_predictions_by_' + clf_name +'_review'), whole_predictions_review)\n\n # Make predictions on the whole 2017 data\n whole_predictions_combined = Grid_clf.predict(whole_tweets_array)\n print('The sentiment distribution of the combined tweet dataframe is:')\n print(Counter(whole_predictions_combined))\n np.save(os.path.join(save_path, 'whole_predictions_tweet_combined_by_' + clf_name), whole_predictions_combined)\n\n return params_dict, performance_dict\n\n\nif __name__ == '__main__':\n\n # Use kfold with GridSearch to compare the performance of different classification methods\n print(\"========================================================================\")\n print('The sentiment would be set to neutral only if two reviewer label it neutral...')\n # Load the tweet_representation_array\n tweets_representations_whole_sample_array = np.load(os.path.join(read_data.tweet_representation_path,\n 'whole_sample_array.npy'))\n whole_review_result_scheme2 = np.load(os.path.join(read_data.tweet_representation_path,\n 'whole_samply_label.npy'))\n # Load the data and label for train and validation\n X_train_valid = np.load(os.path.join(read_data.tweet_representation_path,\n 'train_valid_cross_validation_data.npy'))\n y_train_valid = np.load(os.path.join(read_data.tweet_representation_path,\n 'train_valid_cross_validation_label.npy'))\n # Load the data and label for test\n X_test = np.load(os.path.join(read_data.tweet_representation_path, 'test_data_for_model_compare.npy'))\n y_test = np.load(os.path.join(read_data.tweet_representation_path, 'test_label_for_model_compare.npy'))\n # Load the data for the whole tweet combined array\n whole_combined_array = np.load(os.path.join(read_data.tweet_combined_path, 'tweet_representations',\n 'tweet_combined_repre.npy'))\n\n # Use SMOTE to do the oversampling\n smt = SMOTE(random_state=random_seed, k_neighbors=1)\n oversampled_train_validate_data, oversampled_train_validate_y = smt.fit_sample(X_train_valid,\n y_train_valid)\n print('====================================================')\n print('The distribution of the train_valid_data is: ')\n print(Counter(y_train_valid))\n print('The distribution of the oversampled data is: ')\n print(Counter(oversampled_train_validate_y))\n print('====================================================')\n\n # Build the Classifiers\n ffnn_model = get_ffnn_model()\n ffnn_model.summary()\n # The KerasClassifier Wrapper helps us GridSearch the hyperparameters of our neural net\n ffnn_model_wrapper = KerasClassifier(build_fn=get_ffnn_model, verbose=0,\n epochs=5, batch_size=128)\n\n classifiers_svm = {'SVM': svm.SVC(random_state=random_seed)}\n\n classifiers_decision_tree = {'Decision Tree': tree.DecisionTreeClassifier(random_state=random_seed)}\n\n ensembled_classifiers = {'Random Forest': RandomForestClassifier(random_state=random_seed)}\n\n starting_time = time.time()\n\n print('Decision Tree...')\n\n tuned_parameters_tree = {'max_depth': np.arange(3, 11)}\n\n params_dict_tree, performance_dict_tree = kfold_with_smote(clf=classifiers_decision_tree['Decision Tree'],\n train_valid_data_X=oversampled_train_validate_data,\n train_valid_label_y=oversampled_train_validate_y,\n tuned_parameters=tuned_parameters_tree, X_test=X_test,\n y_test=y_test,\n whole_tweets_array=whole_combined_array,\n save_path=read_data.model_selection_path_oversampling,\n clf_name='DT')\n print('The best hyperparameter setting is....')\n print(params_dict_tree)\n print()\n\n print('Random Forest...')\n\n tuned_parameters_rf = {'n_estimators': np.arange(10, 60)}\n params_dict_rf, performance_dict_rf = kfold_with_smote(clf=ensembled_classifiers['Random Forest'],\n train_valid_data_X=oversampled_train_validate_data,\n train_valid_label_y=oversampled_train_validate_y,\n tuned_parameters=tuned_parameters_rf, X_test=X_test,\n y_test=y_test,\n whole_tweets_array=whole_combined_array,\n save_path=read_data.model_selection_path_oversampling,\n clf_name='RF')\n print('The best hyperparameter setting is....')\n print(params_dict_rf)\n print()\n\n print('SVM......')\n tuned_parameters_svm = {'kernel': ['rbf', 'poly', 'sigmoid'], 'C': [1, 10, 100, 1000]}\n params_dict_svm, performance_dict_svm = kfold_with_smote(clf=classifiers_svm['SVM'],\n train_valid_data_X=oversampled_train_validate_data,\n train_valid_label_y=oversampled_train_validate_y,\n tuned_parameters=tuned_parameters_svm, X_test=X_test,\n y_test=y_test,\n whole_tweets_array=whole_combined_array,\n save_path=read_data.model_selection_path_oversampling,\n clf_name='SVM')\n print('The best hyperparameter setting is....')\n print(params_dict_svm)\n print()\n\n print('Neural Net...')\n\n dropout_rate = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]\n tuned_parameters_ffnn = dict(dropout_rate=dropout_rate)\n\n params_dict_ffnn, performance_dict_ffnn = kfold_with_smote(clf=ffnn_model_wrapper,\n tuned_parameters=tuned_parameters_ffnn,\n train_valid_data_X=oversampled_train_validate_data,\n train_valid_label_y=oversampled_train_validate_y,\n X_test = X_test, y_test = y_test,\n whole_tweets_array = whole_combined_array,\n save_path = read_data.model_selection_path_oversampling,\n clf_name='ffnn')\n print('The best hyperparameter setting is....')\n print(params_dict_ffnn)\n print()\n\n end_time = time.time()\n print('Total time for training is: ', end_time-starting_time)\n\n\n\n\n\n","sub_path":"model_selection.py","file_name":"model_selection.py","file_ext":"py","file_size_in_byte":17563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"304853251","text":"import json, hmac, hashlib, time, requests\nfrom requests.auth import AuthBase\nimport os\nAPI_KEY = os.environ[\"COINBASE_KEY\"]\nAPI_SECRET = os.environ[\"COINBASE_SECRET\"]\n\n\nclass CoinbaseWalletAuth(AuthBase):\n def __init__(self, api_key, secret_key):\n self.api_key = api_key\n self.secret_key = secret_key\n\n def __call__(self, request):\n timestamp = str(int(time.time()))\n message = timestamp + request.method + request.path_url + (request.body or '')\n signature = hmac.new(str.encode(self.secret_key), str.encode(message), hashlib.sha256).hexdigest()\n request.headers.update({\n 'CB-ACCESS-SIGN': signature,\n 'CB-ACCESS-TIMESTAMP': timestamp,\n 'CB-ACCESS-KEY': self.api_key,\n })\n return request\n\n","sub_path":"pysrc/api_auth.py","file_name":"api_auth.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"487189491","text":"#!python3.6\nimport difflib\n\na='abc\\n \\n\t\\n#日本語'\nb='abc\\n \\n\t\\n#日本人'\na=a.splitlines()\nb=b.splitlines()\nprint('========== ndiff format ==========')\nfor buf in difflib.ndiff(a,b):\n print(buf, 'IS_CHARACTER_JUNK(buf[0]):', difflib.IS_CHARACTER_JUNK(buf[0]))\n","sub_path":"16/00/difflib.IS_CHARACTER_JUNK.py","file_name":"difflib.IS_CHARACTER_JUNK.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"150538828","text":"from datetime import datetime\nfrom django.template import Context\nfrom django.template.loader import render_to_string\nfrom celery.utils.log import get_task_logger\nfrom gtgs.users.models import user_ordered_by_month_day\nfrom gtgs.users.models import get_sysadmin_users\nfrom .emails import send_reminder_email\nfrom .emails import normalize_email_to\nfrom .emails import send_reminder_email_with_embedded_images\n\n\ntemplate_text = 'users/msg_card.txt'\ntemplate_html = 'users/msg_card.html'\n\nlogger = get_task_logger(__name__)\n\n\ndef birthdate_greetings(user):\n subject = 'Feliz aniversário, {}!'.format(user.fullname())\n greetings = 'Feliz aniversário!'\n return subject, greetings\n\n\ndef anniversary_greetings(user):\n years = user.display_years()\n subject = '{}, parabéns por {}!'.format(user.fullname(), years)\n greetings = 'Parabéns por {}!'.format(years)\n return subject, greetings\n\n\ndef no_greetings(user):\n subject = 'No greetings'\n greetings = 'No GREETINGS'\n return subject, greetings\n\n\nGREETINGS = {\n 'birthdate': birthdate_greetings,\n 'anniversary': anniversary_greetings,\n 'none': no_greetings,\n}\n\n\ndef send_absence_of_message(date, reminder):\n logger.info(\"send_absence_of_message(): inicio: name={}\".format(reminder.name))\n email_to = reminder.email_to_alt\n logger.info(\"send_absence_of_message(): email_to={}\".format(email_to))\n sysadmin_users = get_sysadmin_users()\n for user in sysadmin_users:\n logger.info(\"send_absence_of_message(): user={}\".format(user.email))\n if '@' not in reminder.email_to_alt:\n email_to = user.email\n logger.info(\"send_absence_of_message(): email_to={}\".format(email_to))\n logger.info(\"send_absence_of_message(): email_to={}\".format(date))\n logger.info('send_absence_of_message(): emails={}'.format(normalize_email_to(email_to)))\n logger.info('send_absence_of_message(): subj={}'.format(reminder.name))\n logger.info('send_absence_of_message(): subj={}'.format(date))\n send_reminder_email(\n email_to,\n date + ' ' + reminder.name,\n date + ' ' + reminder.name)\n logger.info(\"send_absence_of_message(): send_reminder_email {}\".format(email_to))\n send_greetings(email_to, no_greetings, user)\n logger.info(\"send_absence_of_message(): send_greetings {}\".format(email_to))\n\n\ndef send_greetings(email_to, greetings_function, user):\n subject, greetings = ('', '') if greetings_function is None else greetings_function(user)\n context = Context(\n {\n 'fullname': user.fullname,\n 'greetings': greetings,\n 'photo': user.photo\n }\n )\n images = [user.photo]\n\n html_message = render_to_string(template_html, context)\n text_message = render_to_string(template_text, context)\n\n send_reminder_email_with_embedded_images(\n email_to,\n subject,\n text_message,\n html_message,\n images)\n\n\ndef remind_date(reminder):\n logger.info(\"remind_date(): inicio: name={}\".format(reminder.name))\n\n month_day = datetime.now().isoformat()[5:10]\n logger.info(\"remind_date(): today={}\".format(month_day))\n\n if '-' in reminder.default_date:\n month_day = reminder.default_date\n logger.info(\"remind_date(): month_day={}\".format(month_day))\n users = user_ordered_by_month_day(reminder.name, month_day)\n if len(users) == 0:\n logger.info(\"remind_date(): mensagem ninguem nesta data {}\".format(month_day))\n send_absence_of_message(month_day, reminder)\n else:\n for user in users:\n logger.info(\"remind_date(): mensagem para {} sobre {}\".format(reminder.email_to, user.fullname))\n send_greetings(reminder.email_to, GREETINGS.get(reminder.name), user)\n","sub_path":"reminder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"434506385","text":"import pygame\nfrom sprites import SpritesContainer\nfrom math import degrees\nwidth = 1440\nheight = 900\nmap_width = 1500\nmap_height = 1500\n\n\nclass GraphicsHandler:\n\tdef __init__(self):\n\t\tself.x_offset = 0\n\t\tself.y_offset = 0\n\t\tself.screen = pygame.display.set_mode((width, height))\n\t\tpygame.display.set_caption(\"Tankagons\")\n\t\tself.sprites_container = SpritesContainer(self.screen)\n\t\tself.map_screen = pygame.Surface((200, 200))\n\n\tdef update_display(self, data, x_offset, y_offset, trees):\n\t\tself.screen.fill((60, 112, 45))\n\t\tself.map_screen.fill((0, 0, 0))\n\t\tself.x_offset = x_offset\n\t\tself.y_offset = y_offset\n\t\tself.draw_tanks(data[\"tanks\"])\n\t\tself.draw_bullets(data[\"bullets\"])\n\t\tself.draw_trees(trees)\n\t\tself.screen.blit(self.map_screen, (width-200, 0))\n\t\tpygame.display.update()\n\n\tdef draw_background(self):\n\t\tself.screen.fill((0, 0, 0)) #blit(self.sprites_container.background_sprite, (0, 0))\n\n\tdef draw_tanks(self, tank_data):\n\t\tfor tank in tank_data.values():\n\t\t\tself.draw_tank_body(tank.x - self.x_offset + width//2, tank.y - self.y_offset + height//2, tank.body_rotation, tank.tank_body_model)\n\t\t\tself.draw_tank_turret(tank.x - self.x_offset + width//2, tank.y - self.y_offset + height//2, tank.turret_rotation, tank.tank_turret_model)\n\t\t\tpygame.draw.rect(self.map_screen, (255, 0, 0), (int(tank.x/map_width*200), int(tank.y/map_width*200), 5, 5))\n\n\tdef draw_bullets(self, bullet_data):\n\t\tfor bullet in bullet_data:\n\t\t\tself.draw_bullet(bullet.x - self.x_offset + width//2, bullet.y - self.y_offset + height//2, bullet.bullet_angle)\n\n\tdef draw_trees(self, trees):\n\t\tx_offset = int(self.x_offset)\n\t\ty_offset = int(self.y_offset)\n\t\tleftmost = x_offset - width // 2\n\t\trightmost = x_offset + width // 2\n\t\ttopmost = y_offset - height // 2\n\t\tbottommost = y_offset + height // 2\n\n\t\tfor tree in trees.values():\n\t\t\tif (leftmost <= tree.x <= rightmost) and (topmost <= tree.y <= bottommost):\n\t\t\t\tpygame.draw.circle(self.screen, (145, 103, 70), (tree.x-leftmost, tree.y-topmost), tree.radius)\n\t\t\tpygame.draw.circle(self.map_screen, (255, 0, 0), (int(tree.x / map_width * 200), int(tree.y / map_width * 200)), 2)\n\n\tdef draw_bullet(self, x: int, y: int, bullet_angle: int):\n\t\tbullet_image = self.sprites_container.bullet_sprites['bullet']\n\t\tbullet_image = pygame.transform.rotate(bullet_image, degrees(bullet_angle))\n\t\timage_size = bullet_image.get_size()\n\t\tself.screen.blit(bullet_image, (x - image_size[0] // 2, y - image_size[1] // 2))\n\n\tdef draw_tank_turret(self, x: int, y: int, turret_rotation: float, turret_model: str):\n\t\tturret_image = self.sprites_container.tank_turret_sprites[turret_model]\n\t\tturret_image = pygame.transform.rotate(turret_image, degrees(turret_rotation))\n\t\timage_size = turret_image.get_size()\n\t\tself.screen.blit(turret_image, (x - image_size[0] // 2, y - image_size[1] // 2))\n\n\tdef draw_tank_body(self, x: int, y: int, body_rotation: float, body_model: str):\n\t\tbody_image = self.sprites_container.tank_body_sprites[body_model]\n\t\tbody_image = pygame.transform.rotate(body_image, degrees(body_rotation))\n\t\timage_size = body_image.get_size()\n\t\tself.screen.blit(body_image, (x - image_size[0] // 2, y - image_size[1] // 2))\n","sub_path":"graphicshandler.py","file_name":"graphicshandler.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"447656101","text":"from collections import deque\n\n\n# Define what a card is; each card has a name, a point value, and a suit\nclass Card:\n def __init__(self, this_card_name, this_card_points, this_card_suit):\n self.card_name = this_card_name\n self.card_points = this_card_points\n self.card_suit = this_card_suit\n\n # Return the card's name and suit for printing\n def get_card(self):\n return unicode(self.card_name) + self.card_suit\n\n # Return the card's name\n def get_name(self):\n return unicode(self.card_name)\n\n # Return the card's point value\n def get_points(self):\n return self.card_points\n\n\n# Create a deck of cards\ndef create_deck():\n suit_list = [unichr(0x2665), unichr(0x2666), unichr(0x2663), unichr(0x2660)]\n name_points_dict = {\"A\":1, \"2\":2, \"3\":3, \"4\":4, \"5\":5, \"6\":6, \"7\":7, \"8\":8, \"9\":9, \"10\":10, \"J\":10, \"Q\":10, \"K\":10}\n\n # Use a double ended queue structured list for the deck\n deck_list = deque([])\n\n # For each suit, create a card with each of the name and point entries\n for each_suit in suit_list:\n for each_entry in name_points_dict.keys():\n new_card = Card(each_entry, name_points_dict[each_entry], each_suit)\n deck_list.append(new_card)\n\n return deck_list\n\n\n# Select the top card from the deck\ndef deal(this_deck):\n dealt_card = this_deck.popleft()\n\n return dealt_card\n\n\n# Calculate the points for a hand\ndef calculate_points(this_hand):\n # Check to see if hand got dealt an Ace and whether 11 points or 1 point\n total_points = 0\n int_ace_count = 0\n\n # For each card, add together all the points\n for each_card in this_hand:\n total_points += each_card.get_points()\n\n # Check for Aces, get the name of the card\n this_card_name = each_card.get_name()\n\n if (this_card_name == \"A\"):\n int_ace_count += 1\n\n # How to determine if Aces are worth 1 or 11\n # A - 1 or 11\n # AA - 2 or 12\n # AAA - 3 or 13\n # AAAA - 4 or 14\n\n if (int_ace_count > 0):\n # Add 10 points to the total if it doesn't bust the hand\n if ((total_points + 10) <= 21):\n total_points += 10\n\n return total_points\n","sub_path":"game_library/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"551456760","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport re,datetime\nimport sys,codecs\n\nfrom iiData import Link, DayData, GetDataStore\nfrom iiDebugging import *\n\nclass opsyriaLogParser :\n\n def __init__(self,bizmgr,fname=\"opsyria.irclog\"):\n self.fname=fname\n \n #Business layer\n self.bizmgr=bizmgr\n\n #Date translation dict\n self.monthnb={\"janv\":1,\"févr\":2,\"mar\":3,\"avr\":4,\"mai\":5,\"jun\":6,\"jui\":7,'ao\\xc3\\xbb':8,\"sep\":9,\"oct\":10,\"nov\":11,\"d\\xc3\\xa9c\":12}\n\n def parseLog(self, maxlink=0):\n #Preparing regular expressions for data extraction\n linepat=re.compile(\"(?P
\",contents) # getting all the useful contents between p tags\n contents = ' '.join(contents) # joining the resulting string list\n contents = remove_tags(contents) # removing the remaining tags\n\n date = response.xpath(\"//span[@class='date date-published']/text()\").get() # getting the publication date\n label = response.xpath(\"//h5[contains(@class,'rating-label')]/text()\").get() # getting the label\n author = response.xpath(\"//a[@class='author']/text()\").get() # getting the author\n claim = response.xpath(\"//div[@class='claim']/p/text()\").get() # getting the claim\n\n yield {\n 'title': title,\n 'url': url,\n 'contents': contents,\n 'date': date,\n 'label': label,\n 'author': author,\n 'claim': claim\n }\n\n def parse(self, response):\n posts = response.xpath(\"//a[contains(@class,'media post')]/@href\").getall()\n for post in posts:\n if post not in self.visited_urls:\n self.visited_urls.append(post)\n yield scrapy.Request(post,callback=self.parse_post,dont_filter=True)\n next_page = response.xpath(\"//a[@class='btn-next btn']/@href\").get()\n if next_page is not None:\n yield scrapy.Request(next_page,callback=self.parse,dont_filter=True)\n\n\n","sub_path":"news/news/spiders/news_spider.py","file_name":"news_spider.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"51846635","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom exp.models import Session, Report, ReportForm, Experiment, Security\n\nfrom datetime import date, datetime\nfrom django.conf import settings\nfrom django.utils import timezone\n\nimport time\n\n# These are the functions that work with apps\n# exp/group/\n# exp/consent/ (?sessionToken)\n# exp/start/\n# exp/report/\n\n# New structure\n# exp/start/ -- return sessionToken, config, consent, created workerId\n# exp/start// -- return sessionToken, config, consent for workerId\n# In this mode, workerId checked on participant list\n# If workerId is on the list, return the associated session token (last?)\n# exp/new// -- force new session token for this participant (if not disallowed by Exp)\n#\n# exp/report/ -- modified to include the config file\n\n# XML format\n# \n# \n# \n# \n# -- marks info that needs to be removed to deidentify data records\n# -- data that can eventually be shared\n\n\n# special data event types:\n# 'start' created when config file handed out, contains workerid verbatim\n# 'status' written/read by apps, no xml formatting\n# 'private' for non-shared data from the app, wrapped in xnl private tags\n# 'complete' type used to facilitate download (by restriction to just these events)\n# Conventionally, 'partial' types are used to reflect progress, 'complete' at finish but these aren't required\n\n\ndef empirical_error(msg):\n r=\"Error: %s\\n\" % msg\n r=r+settings.VERSION+'\\n'\n r=r+(\"At: %s\\n\" % datetime.now())\n return r\n\ndef xml_string(xmldict):\n r=\"\\n\"\n for i in xmldict.keys():\n r=r+\"<%s>%s%s>\\r\\n\" % (i,xmldict[i],i)\n r=r+\"\\n\\n\"\n return r\n\ndef session_order(e, session_list): # e is the experiment, session_list is a list of strings of sessionTokens\n configs=Session.objects.filter(exp=e)\n order=[]\n for i in configs:\n if i.sessionToken in session_list:\n if i.lastStarted is None:\n d = timezone.make_aware(datetime(2, 1, 1, tzinfo=None), timezone.get_default_timezone())\n #d = timezone.make_aware(datetime.min, timezone.get_default_timezone())\n else:\n d = i.lastStarted\n order.append((d,i))\n order.sort()\n (date_list, session_list)=zip(*order)\n return session_list\n\ndef start_session(request, groupToken, workerId=''):\n try:\n e=Experiment.objects.get(groupToken=groupToken)\n except:\n return HttpResponse(empirical_error('Invalid group token %s' % groupToken))\n\n s=e.study\n try:\n consent=s.consentJSON\n except:\n try:\n return HttpResponse(empirical_error('Unable to get consent info from %s' % s.name))\n except:\n return HttpResponse(empirical_error('Bad study linked to %s' % e.name))\n\n session_list=e.groupSessions.split()[:e.numTokens] # sessionlist of tokens to be used\n c=None\n has_prior = False\n demo_mode = False\n prior_session=''\n if workerId.lower()=='demo':\n # demo session\n session=session_list[0]\n config = ''\n demo_mode=True\n elif workerId!='':\n # check for existing workerId\n prior=s.participants.split()\n for i in prior:\n if ':' in i:\n t = i.split(':')\n if len(t)==2:\n worker=t[0]\n token=t[1]\n else:\n worker=t[0]\n token=t[-1]\n #(worker,token)=i.split(':')\n else:\n worker=i\n token=''\n if worker==workerId:\n has_prior=True\n prior_session=token\n break\n else: # create a synthetic workerId if not provided\n workerId='NoId_%s' % datetime.now().strftime(\"%m%d%Y_%H%M%S\")\n if has_prior: # either returning to finish or restarting\n # if there is no token, will have to search the db to find the session -- to do\n if prior_session=='':\n # search\n r=Report.objects.filter(eventType='start').order_by('-uploadDate')\n for i in r:\n if i.dataLog==workerId:\n prior_session=i.sessionToken\n break\n # if prior_session doesn't get set, the participant might be 'blacklisted'\n if prior_session=='':\n return HttpResponse(empirical_error('Participant %s on exclusion list' % workerId))\n else:\n session=prior_session\n elif not demo_mode:\n # get new session token\n # sort on lastUpdated\n config_list=session_order(e,session_list) # sorting needs to be done manually in the function above\n\n # if no recycle, only return if lastUpdated is None\n if e.recycle==False:\n if config_list[0].lastStarted==None:\n c = config_list[0]\n session=c.sessionToken\n else:\n return HttpResponse(empirical_error('No tokens are available for %s' % e.name))\n else:\n c = config_list[0]\n session = c.sessionToken\n # for new workers, create started datalog event\n r = Report(sessionToken=session,sessionKey=c,eventType='start',dataLog=workerId) # workerId stored in this event to catch re-use later\n r.save()\n # and update study particpant list\n s.addParticipant(workerId,session)\n\n if c==None:\n try:\n c=Session.objects.get(sessionToken=session)\n except:\n return HttpResponse(empirical_error('Invalid session token %s' % session))\n config=c.configFile\n\n # update last started\n if not demo_mode:\n c.lastStarted=datetime.now()\n c.save()\n\n start_xml={}\n start_xml['Empirical:workerid']=workerId\n start_xml['Empirical:consent']=\"\" % consent\n start_xml['Empirical:config']=\"\" % config\n start_xml['Empirical:session']=session\n #debug_string=''\n #for i in config_list:\n # debug_string=debug_string+('%s %s;\\n' % (i.sessionToken, i.lastStarted))\n #start_xml['Empirical:debug']=debug_string\n\n return HttpResponse(xml_string(start_xml))\n\n# Used to force restarting with a new session token -- assumes no restart from status\n\ndef newstart_session(request, groupToken, workerId=''):\n try:\n e=Experiment.objects.get(groupToken=groupToken)\n except:\n return HttpResponse(empirical_error('Invalid group token %s' % groupToken))\n\n s=e.study\n try:\n consent=s.consentJSON\n except:\n try:\n return HttpResponse(empirical_error('Unable to get consent info from %s' % s.name))\n except:\n return HttpResponse(empirical_error('Bad study linked to %s' % e.name))\n\n session_list=e.groupSessions.split()[:e.numTokens] # sessionlist of tokens to be used\n c=None\n has_prior = False\n if workerId.lower()=='demo':\n # demo session\n session=session_list[0]\n elif workerId=='': # create a synthetic workerId if not provided\n workerId='NoId_%s' % datetime.now().strftime(\"%m%d%Y_%H%M%S\")\n\n config_list=session_order(e,session_list) # sorting needs to be done manually in the function above\n if e.recycle==False:\n if config_list[0].lastStarted==None:\n c=config_list[0]\n session=c.sessionToken\n else:\n return HttpResponse(empirical_error('No tokens are available for %s' % e.name))\n else:\n c = config_list[0]\n session = c.sessionToken\n\n if c==None:\n try:\n c=Session.objects.get(sessionToken=session)\n except:\n return HttpResponse(empirical_error('Invalid session token %s' % session))\n config=c.configFile\n\n # update last started\n c.lastStarted=datetime.now()\n c.save()\n\n # update study particpant list\n s.addParticipant(workerId,session)\n\n # create started datalog event\n r = Report(sessionToken=session,sessionKey=c,eventType='start',dataLog=workerId) # workerId stored in this event to catch re-use later\n r.save()\n\n start_xml={}\n start_xml['Empirical:workerid']=workerId\n start_xml['Empirical:consent']=\"\" % consent\n start_xml['Empirical:config']=\"\" % config\n start_xml['Empirical:session']=session\n\n return HttpResponse(xml_string(start_xml))\n\n\n\n# return_status() reports back on the latest status report for that sessionToken, used for continuing/restarting\ndef return_status(request, sessionToken, workerId=''):\n try:\n reports = Report.objects.filter(sessionToken=sessionToken,eventType='status').order_by('-uploadDate') # returns last status\n except:\n return HttpResponse('None') # no status is available, no data for this session yet\n if not reports.exists():\n return HttpResponse('None') # no status reports\n\n # check to make sure workerId matches, necessary if recycle is set\n if workerId!='':\n starts = Report.objects.filter(sessionToken=sessionToken,eventType='start').order_by('-uploadDate')\n for s in starts:\n if s.dataLog==workerId:\n if s.uploadDatesettings.MAX_SECURITY_COUNT:\n s.locked=True\n s.securityLog=s.securityLog+'%d seconds since last update; ' % elap.total_seconds()\n s.save()\n else:\n s=Security(sessionToken=sessionToken,hit_count=0)\n s.securityLog='%d seconds since last update; ' % elap.total_seconds()\n s.save()\n return False\n return True\n\n# to do -- wrap upload in xml structure adding worker id, configfile\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\ndef report(request, sessionToken, workerid=''):\n if request.method==\"POST\":\n report_form = ReportForm(request.POST)\n if report_form.is_valid():\n r=report_form.save(commit=False)\n try:\n r.sessionKey=Session.objects.get(sessionToken=sessionToken)\n except:\n # not a valid session, maybe don't save?\n return HttpResponse(empirical_error('Invalid session token %s' % sessionToken))\n # here should check how long ago the token was given out or started and disallow data too long after start\n security_ok=security_check(sessionToken,report_form.cleaned_data['eventType'])\n if security_ok:\n if r.eventType=='private': # wrap content in private tags\n report_xml={}\n ip_addr=get_client_ip(request)\n wrapped_report = xml_string(report_xml)\n report_xml['Empirical:privatedata'] = \"IP address: %s\\n%s\" % (ip_addr,r.dataLog)\n r.dataLog = wrapped_report\n r.save()\n elif r.eventType=='status': # no xml wrapping on status events\n r.save()\n else:\n report_xml={}\n ip_addr=get_client_ip(request)\n if workerid=='':\n # find workerid from recent start event\n start_event=Report.objects.filter(sessionToken=sessionToken, eventType='start').order_by('-uploadDate')\n if len(start_event)==0:\n workerid='None, no start event found'\n else:\n workerid=start_event[0].dataLog\n report_xml['Empirical:config']=r.sessionKey.configFile\n if r.eventType == 'private': # wrap the data into the private section\n report_xml['Empirical:privatedata'] = \"WorkerId: %s\\nIP address: %s\\n%s\" % (workerid, ip_addr, r.dataLog)\n else: # typical format\n report_xml['Empirical:privatedata']=\"WorkerId: %s\\nIP address: %s\" % (workerid,ip_addr)\n report_xml['Empirical:datalog']=r.dataLog\n wrapped_report=xml_string(report_xml)\n r.dataLog=wrapped_report\n r.save()\n return render(request, 'report_accepted.html',{'log':r.dataLog, 'security':security_ok})\n\n upload_form=ReportForm()\n return render(request, 'test_report.html',{'form':upload_form})\n\n########################\n#\n#\n# # get_session should be first function called to get a sessionToken associated with a group\n# # to do: select from restricted token set if appropriate\n# def get_session(request, groupToken, workerId=''):\n# start=time.time()\n# try:\n# t=TokenGeneration.objects.get(groupToken=groupToken)\n# except:\n# return HttpResponse('Error: Invalid group %s' % groupToken)\n#\n# done=time.time()\n# debug_string=\"Found group token, %.2f; \" % (done-start)\n#\n# sessions=t.groupSessions.split()\n# # check if this workerId has already been assigned a token and re-assign\n# if workerId!='': # one was provided with the URL\n# if workerId=='demo': # this is a call to produce a demo cfg, use first\n# return HttpResponse(sessions[0])\n#\n# # check the study to see if this workerId has already done a related experiment and return error if so\n# study=t.studyName\n# if study!=None:\n# if study.participants and study.unique_id: # if unique_id is set, then check to make sure worker id is not in participants\n# prev_ids=study.participants.split(' ')\n# if workerId in prev_ids:\n# return HttpResponse(\"Error: duplicate participant %s\" % workerId)\n#\n# if not study.recycle:\n# done = time.time()\n# debug_string += \"Checking %d sessions, %.2f; \" % (len(sessions),done - start)\n# for s in sessions:\n# r=Report.objects.filter(sessionToken=s,eventType='given')\n# if r.exists():\n# for i in r: # if the token is being recycled there could be several of these events\n# if i.dataLog == workerId:\n# return HttpResponse(\"%s match to %s\" % (s,workerId))\n# done = time.time()\n# debug_string += \"Going to check study list, %.2f; \" % (done - start)\n#\n# else:\n# workerId='NoId_%s' % datetime.now() # unique workerId string that embeds the date\n#\n# done=time.time()\n# debug_string+=\"worker id: %s, %.2f; \" % (workerId,done-start)\n#\n# # restrict sessions to consider to the numTokens list\n# if t.numTokens 0 :\n number = numbers.pop()\n if(number % 2 == 0):\n even.append(number) # 偶数\n else:\n odd.append(number) # 奇数\nprint(numbers)\nprint(even)\nprint(odd)\nprint()\n\nprint(\"# Normal While\")\ncount = 0\nwhile (count < 5):\n print(\"The count is:\", count)\n count += 1\nprint()\n\n# Continue 和 break 用法\nprint(\"# Continue 和 break 用法\")\ni = 1\nwhile i< 10:\n i+=1\n if i%2 >0: # 非双数时跳过输出\n continue\n print(i, end=\"|\") # 输出双数 2|4|6|8|10|\nprint()\n\ni = 1\nwhile 1:\n print(i, end=\"|\") # 输出 1|2|3|4|5|\n i += 1;\n if i > 5:\n break\nprint()\n\n# 无限循环\n# print(\"# 无限循环\")\n# var = 1\n# while var == 1:\n# num = input(\"Enter a number:\")\n# print(\"You entered: \", num)\n# print(\"Good Bye!\")\n\n# 循环使用else语句\nprint(\"# 循环使用else语句\")\ncount = 0\nwhile count < 5:\n print(count, \"is less than 5\")\n count += 1\nelse:\n print(count, \"is not less than 5\")\nprint()\n\n# 简单语句组\n# print(\"# 简单语句组\")\n# flag = 1\n# while(flag) : print(\"Givin flag is really true!\")\n# print(\"Good Bye!\")\n# print()\n","sub_path":"Python3_Basic/B07_While_Loop.py","file_name":"B07_While_Loop.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"53143769","text":"import arcade\nimport random\n\nSCREEN_WIDTH = 400\nSCREEN_HEIGHT = 600\nSCREEN_TITLE = \"Flappy Zombie\"\n\nMIN_HEIGHT = 50\nGAP_SIZE = 120\n\n# sounds and images from kenney.nl\nSOUNDS = {'point': arcade.load_sound(\"impactMetal_light_003.ogg\"),\n 'die': arcade.load_sound(\"impactPlate_heavy_001.ogg\")}\npipe = [arcade.Sprite(\"lollipopBase.png\")]\n\n\nclass Pipe(arcade.Sprite):\n\n def __init__(self, image, scale=1):\n super().__init__(image, scale)\n self.horizontal_speed = -1.5\n\n def random_pipe(self, sprites, height):\n\n bottom_pipe = self(pipe)\n bottom_pipe.top = random.randrange(sprites['base'].height + MIN_HEIGHT, height - GAP_SIZE - MIN_HEIGHT)\n bottom_pipe.left = sprites['background'].width\n\n top_pipe = self(pipe)\n top_pipe.bottom = bottom_pipe.top + GAP_SIZE\n # top_pipe.bottom = random.randrange(bottom_pipe.top + MIN_GAP, height - MIN_HEIGHT)\n\n return bottom_pipe, top_pipe\n\n def update(self):\n self.center_x += self.horizontal_speed\n\n\nclass MyGame(arcade.Window):\n def __init__(self):\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n\n # Sprite lists\n self.sprites = None\n self.zombie_list = None\n self.zombie_sprite = None\n self.pipe_sprites = None\n self.pipe_list = None\n self.score = 0\n\n # Don't show the mouse cursor\n self.set_mouse_visible(False)\n\n arcade.set_background_color(arcade.color.SKY_BLUE)\n\n def setup(self):\n\n # Sprite Lists\n self.zombie_list = arcade.SpriteList()\n self.pipe_sprites = arcade.SpriteList()\n self.pipe_list = arcade.SpriteList()\n\n # Score\n self.score = 0\n\n self.zombie_sprite = arcade.Sprite(\"character_zombie_idle.png\", 20)\n self.zombie_sprite.center_x = 50\n self.zombie_sprite.center_y = 50\n self.zombie_list.append(self.zombie_sprite)\n\n # Create the pipe\n start_pipe1 = Pipe(self.sprites, self.height)\n self.pipe_sprites.append(start_pipe1)\n\n def on_draw(self):\n\n arcade.start_render()\n self.zombie_list.draw()\n self.pipe_sprites.draw()\n\n # Draw the score\n output = f\"Score: {self.score}\"\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_mouse_motion(self, x, y, dx, dy):\n self.zombie_sprite.center_x = x\n self.zombie_sprite.center_y = y\n\n def on_update(self, delta_time):\n\n new_pipe = None\n\n # Remove pipe that is no longer on the screen\n for pipe in self.pipe_sprites:\n if pipe.right <= 0:\n pipe.kill()\n elif len(self.pipe_sprites) == 2 and pipe.right <= random.randrange(self.width // 2, self.width // 2 + 15):\n new_pipe = True\n\n if new_pipe:\n self.pipe_sprites.append(new_pipe)\n\n self.zombie_list.update()\n self.pipe_sprites.update()\n\n if self.zombie.center_x >= self.pipe_sprites[0].center_x and not self.pipe_sprites[0].scored:\n arcade.play_sound(SOUNDS['point'])\n self.score += 1\n self.pipe_sprites[0].scored = True\n self.pipe_sprites[1].scored = True\n print(self.score)\n\n hit = arcade.check_for_collision_with_list(self.zombie, self.pipe_sprites)\n\n if any(hit):\n output = f\"Game Over\"\n arcade.draw_text(output, 500, 400, arcade.color.WHITE, 60)\n\n\ndef main():\n window = MyGame()\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Testing/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"638435614","text":"import zipfile\r\nimport os\r\nimport shutil\r\n\r\nfrom pptx import Presentation\r\nfrom pptx.util import Pt\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom animation import animation, before, after\r\n\r\ndef produce_pptx():\r\n filename = \"notes.txt\"\r\n rows_in_page = 10\r\n\r\n with open(filename, \"r\", encoding=\"utf-8\") as f:\r\n data = f.read()\r\n\r\n data = data.split(\"\\n\\n\")\r\n\r\n ppt = Presentation()\r\n width = ppt.slide_width\r\n height = ppt.slide_height\r\n pages_rows = []\r\n\r\n for word in data:\r\n rows = word.split(\"\\n\")\r\n page = len(rows) // rows_in_page\r\n for i in range(page+1):\r\n slide = ppt.slides.add_slide(ppt.slide_layouts[6])\r\n\r\n textbox = slide.shapes.add_textbox(500000, 500000, width-1000000, height-1000000).text_frame\r\n for index in range(rows_in_page):\r\n if index == 0:\r\n textbox_para = textbox.paragraphs[0]\r\n else:\r\n textbox_para = textbox.add_paragraph()\r\n try:\r\n textbox_para.text = rows[rows_in_page*i + index]\r\n except IndexError:\r\n pages_rows.append(index)\r\n break\r\n else:\r\n textbox_para.font.name = \"monospace\"\r\n textbox_para.font.size = Pt(36)\r\n else:\r\n pages_rows.append(index + 1)\r\n\r\n ppt.save(\"test.pptx\")\r\n\r\n f = zipfile.ZipFile(\"test.pptx\",'r')\r\n for file in f.namelist():\r\n f.extract(file,\"./temp/\")\r\n\r\n index = 0\r\n for i in os.listdir(\"./temp/ppt/slides\"):\r\n if i == '_rels':\r\n break\r\n with open('./temp/ppt/slides/' + i, \"r\", encoding=\"utf-8\") as f:\r\n soup = f.read()\r\n res = before\r\n res += \"\".join(animation[:pages_rows[index]])\r\n res += after\r\n soup = soup.replace(\"\", \"\" + res + \"\")\r\n with open(\"./temp/ppt/slides/\" + i, \"w\", encoding=\"utf-8\") as f:\r\n f.write(soup)\r\n index += 1\r\n\r\n os.chdir(\"./temp\")\r\n with zipfile.ZipFile('../res.pptx', 'w') as f:\r\n for root, dirs, files in os.walk(\".\"):\r\n for file in files:\r\n f.write(root + \"/\" + file) \r\n\r\n os.chdir(\"../\")\r\n shutil.rmtree(\"temp\")\r\n os.remove(\"test.pptx\")\r\n\r\nif __name__ == \"__main__\":\r\n produce_pptx()\r\n print(\"ppt已生成至res.pptx!\")\r\n","sub_path":"ppt.py","file_name":"ppt.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"361367486","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('merchant', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='PayzatTransaction',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('type', models.PositiveSmallIntegerField(default=4, max_length=10, verbose_name='Type', choices=[(0, 'Sticker'), (1, 'Wrist Band'), (2, 'Terminal'), (3, 'Web'), (4, 'Other')])),\n ('amount', models.DecimalField(verbose_name='Amount', max_digits=10, decimal_places=3)),\n ('is_rollback', models.BooleanField(default=False)),\n ('transaction_time', models.DateTimeField()),\n ('description', models.TextField(null=True, blank=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('from_person', models.ForeignKey(related_name='from_user', blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ('from_terminal', models.ForeignKey(related_name='from_terminal', blank=True, to='merchant.TerminalUser', null=True)),\n ('location', models.ForeignKey(related_name='terminal_location', blank=True, to='merchant.SubLocation', null=True)),\n ('to_person', models.ForeignKey(related_name='to_user', blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ('to_terminal', models.ForeignKey(related_name='to_terminal', blank=True, to='merchant.TerminalUser', null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='PendingSyncData',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('data', models.TextField()),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"payzat/transactions/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"214147431","text":"import sys\nsys.stdin = open(\"input_4874.txt\", \"r\")\nsys.stdout= open(\"output_4874.txt\", \"w\")\nT = int(input())\nfor t in range(1, T + 1):\n lst = list(map(str, input().split()))\n stack = []\n\n for a in range(len(lst)):\n if lst[a] == '+':\n if len(stack) < 2:\n print(f'#{t} error')\n break\n num = stack[-2] + stack[-1]\n stack.pop(-1)\n stack.pop(-1)\n stack += [int(num)]\n\n elif lst[a] == '-':\n if len(stack) < 2:\n print(f'#{t} error')\n break\n num = stack[-2] - stack[-1]\n stack.pop(-1)\n stack.pop(-1)\n stack += [int(num)]\n\n elif lst[a] == '*':\n if len(stack) < 2:\n print(f'#{t} error')\n break\n num = stack[-2] * stack[-1]\n stack.pop(-1)\n stack.pop(-1)\n stack += [int(num)]\n\n elif lst[a] == '/':\n if len(stack) < 2:\n print(f'#{t} error')\n break\n\n elif stack[-1] == 0:\n print(f'#{t} error')\n break\n\n elif stack[-1] != 0:\n num = stack[-2] / stack[-1]\n stack.pop(-1)\n stack.pop(-1)\n stack += [int(num)]\n\n elif lst[a] == '.':\n if len(stack) > 1:\n print(f'#{t} error')\n\n else:\n print(f'#{t} {\"\".join(list(map(str, stack)))}')\n\n elif type(int(lst[a])) is int:\n stack += [int(lst[a])]\n\n\n\n\n","sub_path":"SWEA/4874_Forth.py","file_name":"4874_Forth.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"461512897","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, re_path\nfrom django.views.generic.base import RedirectView\n\nfrom .datasets import views as dataset_views\nfrom .points import views as points_views\n\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n re_path(r\"admin$\", RedirectView.as_view(url=\"admin/\", permanent=True)),\n path(\"api/v1/datasets/\", dataset_views.DatasetList.as_view()),\n path(\"api/v1/datasets//indicators/\", dataset_views.DatasetIndicatorsList.as_view()),\n path(\"api/v1/indicators/\", dataset_views.IndicatorsList.as_view()),\n path(\"api/v1/indicators//\", dataset_views.IndicatorDataView.as_view()),\n path(\"api/v1/indicators//geographies//\", dataset_views.IndicatorDataView.as_view()),\n path(\"api/v1/profiles/\", dataset_views.ProfileList.as_view()),\n path(\"api/v1/profiles//\", dataset_views.ProfileDetail.as_view()),\n path(\"api/v1/profiles//geographies//\", dataset_views.profile_geography_data),\n path(\"api/v1/geography/search/\", dataset_views.search_geography),\n path(\"api/v1/points/\", points_views.LocationList.as_view()),\n path(\"api/v1/points/themes/\", points_views.ThemeList.as_view()),\n path(\"api/v1/points/themes//\", points_views.LocationList.as_view()),\n path(\"api/v1/points/categories/\", points_views.CategoryList.as_view()),\n path(\"api/v1/points/categories//\", points_views.LocationList.as_view()),\n re_path(r\"^$\", RedirectView.as_view(url=\"/api/v1/datasets/\", permanent=False)),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"wazimap_ng/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"357345775","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom .bash import bash\nfrom .config import read_config\n\nimport os\n\ndef build_docs(source='ortho/docs_source',build='docs',single=False\t):\n\t\"\"\"Make documentation.\"\"\"\n\tif build=='build_docs': \n\t\traise Exception('name collision. you cannot build docs in the name of this function: %s'%build)\n\tdocs_default = {'local':{'source':source,'build':build}}\n\tconf = read_config()\n\tif conf.get('docs',{}).get('list',None): \n\t\tprint('warning','overriding source, build arguments to write the docs according to the config')\n\tdocs = conf.get('docs',{}).get('list',docs_default)\n\t# command-line options\n\topts = []\n\tif single: opts.append('-b singlehtml')\n\t# iterate over docs to make\n\turls = {}\n\tfor name,detail in docs.items():\n\t\tsource,build = detail['source'],detail['build']\n\t\tbash('sphinx-build -b html %s %s%s'%(source,build,' '+' '.join(opts) if opts else ''),cwd='.')\n\t\tindex = os.path.abspath(os.path.join(build,'index.html'))\n\t\tif not os.path.isfile(index): raise Exception('building docs \"%s\" failed'%name)\n\t\turls[name] = index\n\tfor name,index in urls.items(): print('status','docs are available at file:///%s'%index)\n","sub_path":"ortho/documentation.py","file_name":"documentation.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"188555454","text":"\"\"\"Functions for handling the file-based marketdata-repository. Used by prices and forex\n\nPROFIT - Python-Based Return on Investment and Financial Investigation Tool\nMIT License\nCopyright (c) 2018 Mario Mauerer\n\"\"\"\n\nimport stringoperations\nimport dateoperations\nimport files\nimport helper\n\n\ndef update_check_marketdata_in_file(filepath, dateformat_marketdata, dateformat, marketdata_delimiter,\n newdates, newvals):\n \"\"\"Imports data into a potentially available marketdata-file and if possible, cross-checks it with the dates in\n newdates, newvals.\n If the marketdata-file does not exist, it is created and populated with newdates, newvals. These values are\n then also returned.\n NEVER provide extrapolated data here, the market-files should only contain real data.\n If newdates, newvals contains new dates and values that do not yet exist in the existing marketdata-file,\n an updated version of the file is written. The values of the updated file are returned as tuple.\n The last second entries of the marketdata (the two most recent dates) are ignored when checking for matching data,\n since the daily data is end-of-day and might be extrapolated one day forward, which changes it...\n It is assumed that the data in the marketdata-file is always correct and hence, this data is used. A warning is\n issued if mismatches are detected.\n :param filepath: String of the path of the marketdata-file\n :param dateformat_marketdata: String of the dateformat used in the marketdata-file\n :param dateformat: String of the dateformat as used by the rest of the functions\n :param marketdata_delimiter: String of the delimiter used to separate dates, values in the marketdata-file\n :param newdates: New dates (strings) (with format dateformat) that are used to compare/update the file\n :param newvals: New values (floats) that are used to compare/update the file\n :return: The contents of the updated / newly created marketdata-file, as tuple: (dates, values); dates are\n Strings with the datetime-format.\n \"\"\"\n # Sanity checks:\n if len(newdates) != len(newvals):\n raise RuntimeError(\"Length of date- and value-lists must be identical. Cannot update market-data. Path: \"\n + filepath)\n\n # Convert the newdates to datetime-objects and back, to be sure they are of the correct format:\n newdates_dt = [stringoperations.str2datetime(x, dateformat) for x in newdates]\n newdates = [stringoperations.datetime2str(x, dateformat) for x in newdates_dt]\n\n # Files does not yet exist: Create it and add the available data to it:\n if files.file_exists(filepath) is False:\n lines = []\n for idx, date in enumerate(newdates):\n # Assemble the line, comprising the date, delimiter and value\n string = date + marketdata_delimiter + repr(newvals[idx])\n lines.append(string)\n # Write the lines to the file. It will be newly created.\n try:\n files.write_file_lines(filepath, lines, overwrite=True)\n except:\n raise RuntimeError(\"Could not create/write new marketdata-file. Path: \" + filepath)\n return newdates, newvals\n\n # There is already an existing marketdata-file:\n else:\n # Import the currently stored data from the marketdata-file:\n # The dates are already formatted in dateformat.\n mketdates_cur, mketprices_cur = import_marketdata_from_file(filepath, dateformat_marketdata, dateformat,\n marketdata_delimiter)\n\n # Crop the last entry out of the list; it might change after a day, due to end-of-day data and/or\n # potential extrapolation. It will be re-added anyways further below by the data-source. But: Only do this if\n # there is sufficient data in the file (the dataprovider sometimes only provides data of a single day).\n if len(mketdates_cur) > 1:\n mketdates_cur = mketdates_cur[0:-1]\n mketprices_cur = mketprices_cur[0:-1]\n\n # Iterate over all lines of the marketdata-file and\n # check if stored values match with newdates,newvals (if possible)\n # If not, a list of non-matching strings is output afterwards.\n discrepancy_entries = []\n for idx, date_cur in enumerate(mketdates_cur):\n # Check, if the currently selected date is available in the newdates, too:\n indexes = [i for i, x in enumerate(newdates) if x == date_cur]\n # If it is available, check if it matches reasonably well with the stored value:\n if len(indexes) > 1:\n raise RuntimeError(\"The supplied list of new dates contains multiple identical dates. \"\n \"This is not allowed.\")\n # The currently selected date is available in the new list (once, which is good): Check, if it matches:\n elif len(indexes) == 1:\n price_cur = mketprices_cur[idx]\n price_new = newvals[indexes[0]]\n # The values should match within 0.5% at least.\n if helper.within_tol(price_cur, price_new, 0.5 / 100.0) is False:\n # It is assumed that the marketdata-file is always correct:\n newvals[indexes[0]] = price_cur\n # Record a string for later output:\n discrepancy_str = repr(date_cur) + \";\\t\" + repr(price_cur) + \";\\t\" + repr(\n price_new)\n discrepancy_entries.append(discrepancy_str)\n \"\"\"\n Don't create an output yet\n print(\"WARNING: The obtained market-price does not match with the recorded value. Path: \" +\n filepath + \". Recorded Value=\" + repr(price_cur) +\n \". New Value=\" + repr(price_new) + \". Date: \" + date_cur + \". Using recorded data from file. \"\n \"Double-check data/source.\")\n \"\"\"\n # Output the mismatching entries of the market data file:\n if len(discrepancy_entries) > 0:\n print(\"WARNING: Some obtained market data does not match the recorded values. Potentially double-check.\")\n print(\"File: \" + filepath + \". Entries:\")\n print(\"Date;\\tRecorded Price;\\tObtained Price\")\n for _, lineout in enumerate(discrepancy_entries):\n print(lineout)\n\n # The obtained new values now match the existing values (if there are double entries), which is good.\n # In the following: the new values are sorted into the existing market-data, and the file is updated\n # These copies will be updated:\n mketdates_update_dt = [stringoperations.str2datetime(x, dateformat) for x in mketdates_cur]\n mketprices_update = list(mketprices_cur)\n for idx, newdate in enumerate(newdates):\n # Check, if the current new date exists somewhere in the market-data:\n indexes = [i for i, x in enumerate(mketdates_cur) if x == newdate]\n if len(indexes) > 1:\n raise RuntimeError(\"The supplied list of new dates contains multiple identical dates. \"\n \"This is not allowed.\")\n # The current new date is not in the market-data-list: it can be inserted there!\n elif len(indexes) == 0:\n newdate_dt = stringoperations.str2datetime(newdate, dateformat)\n # Find the index, where it has to go:\n inserted = False\n for idxup, date_update in enumerate(mketdates_update_dt):\n # Insert it according to the date:\n if newdate_dt < date_update:\n mketdates_update_dt.insert(idxup, newdate_dt)\n mketprices_update.insert(idxup, newvals[idx])\n inserted = True\n break\n # At end of for-loop, it must be inserted, it then has the newest date:\n if inserted is False:\n lastidx = len(mketdates_update_dt) # It's relly the length, no -1 needed...\n mketdates_update_dt.insert(lastidx, newdate_dt)\n mketprices_update.insert(lastidx, newvals[idx])\n\n # Convert back to string-representation and check the consistency, to be sure nothing went wrong:\n mketdates_update = [stringoperations.datetime2str(x, dateformat) for x in mketdates_update_dt]\n if dateoperations.check_date_order(mketdates_update, dateformat, allow_ident_days=False) is False:\n raise RuntimeError(\"Something went wrong when updating the market-data. Path: \" + filepath)\n\n # Write the updated data back into the file:\n lines = []\n for idx, date in enumerate(mketdates_update):\n # Assemble the line, comprising the date, delimiter and value\n string = date + marketdata_delimiter + repr(mketprices_update[idx])\n lines.append(string)\n # Write the lines to the file. It will be newly created.\n try:\n files.write_file_lines(filepath, lines, overwrite=True)\n except:\n raise RuntimeError(\"Could not overwrite existing marketdata-file. Path: \" + filepath +\n \". Maybe data has now been lost...?\")\n # Return the updated full lists of all stored market data:\n return mketdates_update, mketprices_update\n\n\ndef import_marketdata_from_file(filepath, dateformat_marketdata, dateformat, marketdata_delimiter):\n \"\"\"Imports recorded market-data from the specified file\n The dates are converted from dateformat_marketdata to dateformat, and returned as strings in the latter format\n :param filepath: String of the path of the file, where data is potentially available\n :param dateformat_marketdata: String of the dateformat of the marketdata\n :param dateformat: String of the dateformat as used by the rest of the scripts\n :param marketdata_delimiter: Delimiter used in the marketdata-files\n :return: Tuple of two lists: (dates, values) as imported from the specified files. Dates are strings in the\n dateformat. Values are floats.\n \"\"\"\n if files.file_exists(filepath) is False:\n raise RuntimeError(\"Cannot import data, file not existing. Path: \" + filepath)\n\n # Get all lines (as list) from the file:\n try:\n lines = files.get_file_lines(filepath)\n except:\n raise RuntimeError(\"Could not obtain lines from marketdata-file. Path: \" + filepath)\n # Accumulate the dates and the values:\n datelist = []\n vallist = []\n for line in lines:\n # Get rid of all whitespaces in a line:\n stripline = stringoperations.strip_whitespaces(line)\n # Read the identifier, and also retain the value encoded after the delimiter:\n date, val = stringoperations.read_crop_string_delimited(stripline, marketdata_delimiter)\n # Convert the format of the dates:\n date_dt = stringoperations.str2datetime(date, dateformat_marketdata)\n date = stringoperations.datetime2str(date_dt, dateformat)\n val = float(val)\n datelist.append(date)\n vallist.append(val)\n\n # Sanity checks:\n if dateoperations.check_date_order(datelist, dateformat, allow_ident_days=False) is False:\n raise RuntimeError(\"The imported dates from the marketdata-file are not in order. They must be consecutive \"\n \"and may not contain duplicates. Paht: \" + filepath)\n\n return datelist, vallist\n\n\n\"\"\"\n Stand-alone execution for testing:\n\"\"\"\nif __name__ == '__main__':\n test = list(reversed(list(range(3))))\n print(test)\n\n # lis = [1, 2, 3, 4]\n # lis.insert(4, 8)\n # print(lis)\n","sub_path":"marketdata.py","file_name":"marketdata.py","file_ext":"py","file_size_in_byte":11901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"137840395","text":"import os\nimport sys\n\nfrom setuptools import setup\nfrom setuptools.command.install import install\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nVERSION = '0.2.0'\nabout = {'version': VERSION}\n\nwith open(\n os.path.join(here, 'typed_json_dataclass', '__init__.py'), 'r',\n encoding='utf-8'\n) as f:\n for line in f:\n if line.startswith('__version__'):\n about['version'] = line.strip().split('=')[1].strip(' \\'\"')\n\nwith open(os.path.join(here, 'README.md'), 'r', encoding='utf-8') as f:\n README = f.read()\n\n\nclass VerifyVersionCommand(install):\n \"\"\"Custom command to verify that the git tag matches our version\"\"\"\n description = 'verify that the git tag matches our version'\n\n def run(self):\n tag = os.getenv('CIRCLE_TAG')\n\n if tag != VERSION:\n info = ('Git tag: {0} does not match '\n 'the version of this app: {1}').format(\n tag, VERSION\n )\n sys.exit(info)\n\n\nsetup(\n name='typed_json_dataclass',\n version=about['version'],\n url='http://github.com/abatilo/typed_json_dataclass/',\n license='MIT',\n author='Aaron Batilo',\n author_email='aaronbatilo@gmail.com',\n maintainer='Aaron Batilo',\n maintainer_email='aaronbatilo@gmail.com',\n description='Make your dataclasses automatically validate their types',\n long_description=README,\n long_description_content_type='text/markdown',\n packages=['typed_json_dataclass'],\n package_data={'typed_json_dataclass': ['typed_json_dataclass/*']},\n platforms='any',\n install_requires=[],\n classifiers=[\n 'Intended Audience :: Developers',\n 'Development Status :: 4 - Beta',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Environment :: Web Environment',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.7',\n ],\n keywords='dataclasses dataclass json mypy pyre marshmallow attrs cattrs',\n python_requires='==3.7.*',\n cmdclass={\n 'verify': VerifyVersionCommand,\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"196043690","text":"# -*- coding: utf-8 -*-\n\"\"\"\nEphemeris calculations using SunPy coordinate frames\n\n\"\"\"\nfrom __future__ import absolute_import, division\nimport datetime\nimport warnings\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.time import Time\nfrom astropy.coordinates import (SkyCoord, Angle, Longitude,\n ICRS, PrecessedGeocentric, AltAz,\n get_body_barycentric)\nfrom astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation\nfrom astropy._erfa.core import ErfaWarning\n\nfrom sunpy.time import parse_time\nfrom sunpy.time.time import _astropy_time\n\nfrom .frames import HeliographicStonyhurst as HGS\nfrom .transformations import _SUN_DETILT_MATRIX\n\n__all__ = ['get_body_heliographic_stonyhurst', 'get_earth',\n 'get_sun_B0', 'get_sun_L0', 'get_sun_P', 'get_sunearth_distance',\n 'get_sun_orientation']\n\n\ndef get_body_heliographic_stonyhurst(body, time='now'):\n \"\"\"\n Return a `~sunpy.coordinates.frames.HeliographicStonyhurst` frame for the location of a\n solar-system body at a specified time.\n\n Parameters\n ----------\n body : `str`\n The solar-system body for which to calculate positions\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~sunpy.coordinates.frames.HeliographicStonyhurst`\n Location of the solar-system body in the `~sunpy.coordinates.HeliographicStonyhurst` frame\n \"\"\"\n obstime = _astropy_time(time)\n\n body_icrs = ICRS(get_body_barycentric(body, obstime))\n body_hgs = body_icrs.transform_to(HGS(obstime=obstime))\n\n return body_hgs\n\n\ndef get_earth(time='now'):\n \"\"\"\n Return a `~astropy.coordinates.SkyCoord` for the location of the Earth at a specified time in\n the `~sunpy.coordinates.frames.HeliographicStonyhurst` frame. The longitude will be 0 by definition.\n\n Parameters\n ----------\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.SkyCoord`\n Location of the Earth in the `~sunpy.coordinates.frames.HeliographicStonyhurst` frame\n \"\"\"\n earth = get_body_heliographic_stonyhurst('earth', time=time)\n\n # Explicitly set the longitude to 0\n earth = SkyCoord(0*u.deg, earth.lat, earth.radius, frame=earth)\n\n return earth\n\n\ndef get_sun_B0(time='now'):\n \"\"\"\n Return the B0 angle for the Sun at a specified time, which is the heliographic latitude of the\n Sun-disk center as seen from Earth. The range of B0 is +/-7.23 degrees.\n\n Parameters\n ----------\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.Angle`\n The position angle\n \"\"\"\n return Angle(get_earth(time).lat)\n\n\n# Ignore warnings that result from going back in time to the first Carrington rotation\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", ErfaWarning)\n\n # Carrington rotation 1 starts late in the day on 1853 Nov 9\n # according to Astronomical Algorithms (Meeus 1998, p.191)\n _time_first_rotation = Time('1853-11-09 21:36')\n\n # Longitude of Earth at Carrington rotation 1 in de-tilted HCRS (so that solar north pole is Z)\n _lon_first_rotation = \\\n get_earth(_time_first_rotation).hcrs.cartesian.transform(_SUN_DETILT_MATRIX) \\\n .represent_as(SphericalRepresentation).lon.to('deg')\n\n\ndef get_sun_L0(time='now'):\n \"\"\"\n Return the L0 angle for the Sun at a specified time, which is the Carrington longitude of the\n Sun-disk center as seen from Earth.\n\n .. warning::\n Due to apparent disagreement between published references, the returned L0 may be inaccurate\n by up to ~2 arcmin, which translates in the worst case to a shift of ~0.5 arcsec in\n helioprojective coordinates for an observer at 1 AU. Until this is resolved, be cautious\n with analysis that depends critically on absolute (as opposed to relative) values of\n Carrington longitude.\n\n Parameters\n ----------\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.Longitude`\n The Carrington longitude\n \"\"\"\n obstime = _astropy_time(time)\n\n # Calculate the longitude due to the Sun's rotation relative to the stars\n # A sidereal rotation is defined to be exactly 25.38 days\n sidereal_lon = Longitude((obstime.jd - _time_first_rotation.jd) / 25.38 * 360*u.deg)\n\n # Calculate the longitude of the Earth in de-tilted HCRS\n lon_obstime = get_earth(obstime).hcrs.cartesian.transform(_SUN_DETILT_MATRIX) \\\n .represent_as(SphericalRepresentation).lon.to('deg')\n\n return Longitude(lon_obstime - _lon_first_rotation - sidereal_lon)\n\n\ndef get_sun_P(time='now'):\n \"\"\"\n Return the position (P) angle for the Sun at a specified time, which is the angle between\n geocentric north and solar north as seen from Earth, measured eastward from geocentric north.\n The range of P is +/-26.3 degrees.\n\n Parameters\n ----------\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.Angle`\n The position angle\n \"\"\"\n obstime = _astropy_time(time)\n\n # Define the frame where its Z axis is aligned with geocentric north\n geocentric = PrecessedGeocentric(equinox=obstime, obstime=obstime)\n\n return _sun_north_angle_to_z(geocentric)\n\n\ndef get_sunearth_distance(time='now'):\n \"\"\"\n Return the distance between the Sun and the Earth at a specified time.\n\n Parameters\n ----------\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.Distance`\n The Sun-Earth distance\n \"\"\"\n return get_earth(time).radius\n\n\ndef get_sun_orientation(location, time='now'):\n \"\"\"\n Return the orientation angle for the Sun from a specified Earth location and time. The\n orientation angle is the angle between local zenith and solar north, measured eastward from\n local zenith.\n\n Parameters\n ----------\n location : `~astropy.coordinates.EarthLocation`\n Observer location on Earth\n time : various\n Time to use as `~astropy.time.Time` or in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.Angle`\n The orientation of the Sun\n \"\"\"\n obstime = _astropy_time(time)\n\n # Define the frame where its Z axis is aligned with local zenith\n local_frame = AltAz(obstime=obstime, location=location)\n\n return _sun_north_angle_to_z(local_frame)\n\n\ndef _sun_north_angle_to_z(frame):\n \"\"\"\n Return the angle between solar north and the Z axis of the provided frame's coordinate system\n and observation time.\n \"\"\"\n # Find the Sun center in HGS at the frame's observation time\n sun_center = SkyCoord(0*u.deg, 0*u.deg, 0*u.km, frame=HGS, obstime=frame.obstime)\n\n # Find the Sun north in HGS at the frame's observation time\n # Only a rough value of the solar radius is needed here because, after the cross product,\n # only the direction from the Sun center to the Sun north pole matters\n sun_north = SkyCoord(0*u.deg, 90*u.deg, 690000*u.km, frame=HGS, obstime=frame.obstime)\n\n # Find the Sun center and Sun north in the frame's coordinate system\n sky_normal = sun_center.transform_to(frame).data.to_cartesian()\n sun_north = sun_north.transform_to(frame).data.to_cartesian()\n\n # Use cross products to obtain the sky projections of the two vectors (rotated by 90 deg)\n sun_north_in_sky = sun_north.cross(sky_normal)\n z_in_sky = CartesianRepresentation(0, 0, 1).cross(sky_normal)\n\n # Normalize directional vectors\n sky_normal /= sky_normal.norm()\n sun_north_in_sky /= sun_north_in_sky.norm()\n z_in_sky /= z_in_sky.norm()\n\n # Calculate the signed angle between the two projected vectors\n cos_theta = sun_north_in_sky.dot(z_in_sky)\n sin_theta = sun_north_in_sky.cross(z_in_sky).dot(sky_normal)\n angle = np.arctan2(sin_theta, cos_theta).to('deg')\n\n return Angle(angle)\n","sub_path":"sunpy/coordinates/ephemeris.py","file_name":"ephemeris.py","file_ext":"py","file_size_in_byte":8335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"441630094","text":"import re\n\n\nclass FieldValidator:\n \"\"\"wash and validate a single field\"\"\"\n def __init__(self, name, rule):\n self.__name = name\n self.__rule = rule\n\n def wash(self, field_str):\n return field_str.strip().capitalize()\n\n def validate(self, field_str):\n return re.fullmatch(self.__rule, field_str)\n\n def __str__(self):\n return self.__name + \" validator\\nRule: \" + self.__rule\n\n\nclass Validator:\n \"\"\"\n wash and validate data for a single record\n \"\"\"\n def __init__(self):\n self.__fields = []\n\n def add_all_fields(self, rules_array):\n for rule in rules_array:\n rule_name, rule_value = rule[0], rule[1]\n self.__fields.append(FieldValidator(rule_name, rule_value))\n\n def wash(self, input_list):\n \"\"\"return washed data\"\"\"\n washed = []\n try:\n for field, data in zip(self.__fields, input_list):\n washed.append(field.wash(data))\n except TypeError:\n raise\n except IndexError:\n raise\n finally:\n return washed\n\n def validated(self, washed_list):\n \"\"\"\n wash and validate data using re patterns\n :return: is_valid , validated\n \"\"\"\n result = False, None\n try:\n for field, data in zip(self.__fields, washed_list):\n if not field.validate(data):\n break\n else:\n result = True, washed_list\n except TypeError:\n pass\n except IndexError:\n pass\n finally:\n return result\n","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"150420971","text":"# https://stackoverflow.com/questions/50757497/simplest-async-await-example-possible-in-python\n\nimport asyncio\n\nasync def async_foo():\n print(\"async_foo started\")\n await asyncio.sleep(5)\n print(\"async_foo done\")\n\nasync def main():\n asyncio.ensure_future(async_foo()) # fire and forget async_foo()\n print('Do some actions 1')\n await asyncio.sleep(5)\n print('Do some actions 2')\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())","sub_path":"project/async/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"654062285","text":"import sys\nsys.path.append('../..')\n\nimport unittest\nimport mock\n\nfrom model_service.mxnet_vision_service import MXNetVisionService\nfrom model_service.mxnet_model_service import MXNetBaseService\nfrom serving_frontend import ServingFrontend\n\nclass TestServingFrontend(unittest.TestCase):\n\n def setUp(self):\n self.test_frontend = ServingFrontend('test')\n\n def test_register_module(self):\n # Mock \n ret = [MXNetVisionService]\n self.test_frontend.service_manager.parse_modelservices_from_module = mock.Mock(return_value=ret)\n self.test_frontend.service_manager.add_modelservice_to_registry = mock.Mock()\n\n self.assertEqual(self.test_frontend.register_module('mx_vision_service'), ret)\n\n def test_get_registered_modelservices(self):\n # Mock\n all_model_services = {\n MXNetBaseService.__name__: MXNetBaseService, \n MXNetVisionService.__name__: MXNetVisionService\n }\n\n self.test_frontend.service_manager.get_modelservices_registry = mock.Mock(return_value=all_model_services)\n self.assertEqual(self.test_frontend.get_registered_modelservices(), all_model_services)\n\n def runTest(self):\n self.test_register_module()\n self.test_get_registered_modelservices()","sub_path":"mms/tests/unit_tests/test_serving_frontend.py","file_name":"test_serving_frontend.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"412512057","text":"import django_tables2 as tables\nfrom django.conf import settings\nfrom django.utils.translation import gettext as _\n\nfrom extras.models import *\nfrom netbox.tables import NetBoxTable, columns\nfrom .template_code import *\n\n__all__ = (\n 'ConfigContextTable',\n 'CustomFieldTable',\n 'CustomLinkTable',\n 'ExportTemplateTable',\n 'JobResultTable',\n 'JournalEntryTable',\n 'ObjectChangeTable',\n 'SavedFilterTable',\n 'TaggedItemTable',\n 'TagTable',\n 'WebhookTable',\n)\n\n\nclass CustomFieldTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n content_types = columns.ContentTypesColumn()\n required = columns.BooleanColumn()\n ui_visibility = columns.ChoiceFieldColumn(verbose_name=\"UI visibility\")\n\n class Meta(NetBoxTable.Meta):\n model = CustomField\n fields = (\n 'pk', 'id', 'name', 'content_types', 'label', 'type', 'group_name', 'required', 'default', 'description',\n 'search_weight', 'filter_logic', 'ui_visibility', 'weight', 'choices', 'created', 'last_updated',\n )\n default_columns = ('pk', 'name', 'content_types', 'label', 'group_name', 'type', 'required', 'description')\n\n\nclass JobResultTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n obj_type = columns.ContentTypeColumn(\n verbose_name=_('Type')\n )\n status = columns.ChoiceFieldColumn()\n created = columns.DateTimeColumn()\n scheduled = columns.DateTimeColumn()\n interval = columns.DurationColumn()\n started = columns.DateTimeColumn()\n completed = columns.DateTimeColumn()\n actions = columns.ActionsColumn(\n actions=('delete',)\n )\n\n class Meta(NetBoxTable.Meta):\n model = JobResult\n fields = (\n 'pk', 'id', 'obj_type', 'name', 'status', 'created', 'scheduled', 'interval', 'started', 'completed',\n 'user', 'job_id',\n )\n default_columns = (\n 'pk', 'id', 'obj_type', 'name', 'status', 'created', 'scheduled', 'interval', 'started', 'completed',\n 'user',\n )\n\n\nclass CustomLinkTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n content_types = columns.ContentTypesColumn()\n enabled = columns.BooleanColumn()\n new_window = columns.BooleanColumn()\n\n class Meta(NetBoxTable.Meta):\n model = CustomLink\n fields = (\n 'pk', 'id', 'name', 'content_types', 'enabled', 'link_text', 'link_url', 'weight', 'group_name',\n 'button_class', 'new_window', 'created', 'last_updated',\n )\n default_columns = ('pk', 'name', 'content_types', 'enabled', 'group_name', 'button_class', 'new_window')\n\n\nclass ExportTemplateTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n content_types = columns.ContentTypesColumn()\n as_attachment = columns.BooleanColumn()\n\n class Meta(NetBoxTable.Meta):\n model = ExportTemplate\n fields = (\n 'pk', 'id', 'name', 'content_types', 'description', 'mime_type', 'file_extension', 'as_attachment',\n 'created', 'last_updated',\n )\n default_columns = (\n 'pk', 'name', 'content_types', 'description', 'mime_type', 'file_extension', 'as_attachment',\n )\n\n\nclass SavedFilterTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n content_types = columns.ContentTypesColumn()\n enabled = columns.BooleanColumn()\n shared = columns.BooleanColumn()\n\n class Meta(NetBoxTable.Meta):\n model = SavedFilter\n fields = (\n 'pk', 'id', 'name', 'slug', 'content_types', 'description', 'user', 'weight', 'enabled', 'shared',\n 'created', 'last_updated',\n )\n default_columns = (\n 'pk', 'name', 'content_types', 'user', 'description', 'enabled', 'shared',\n )\n\n\nclass WebhookTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n content_types = columns.ContentTypesColumn()\n enabled = columns.BooleanColumn()\n type_create = columns.BooleanColumn(\n verbose_name='Create'\n )\n type_update = columns.BooleanColumn(\n verbose_name='Update'\n )\n type_delete = columns.BooleanColumn(\n verbose_name='Delete'\n )\n ssl_validation = columns.BooleanColumn(\n verbose_name='SSL Validation'\n )\n\n class Meta(NetBoxTable.Meta):\n model = Webhook\n fields = (\n 'pk', 'id', 'name', 'content_types', 'enabled', 'type_create', 'type_update', 'type_delete', 'http_method',\n 'payload_url', 'secret', 'ssl_validation', 'ca_file_path', 'created', 'last_updated',\n )\n default_columns = (\n 'pk', 'name', 'content_types', 'enabled', 'type_create', 'type_update', 'type_delete', 'http_method',\n 'payload_url',\n )\n\n\nclass TagTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n color = columns.ColorColumn()\n\n class Meta(NetBoxTable.Meta):\n model = Tag\n fields = ('pk', 'id', 'name', 'items', 'slug', 'color', 'description', 'created', 'last_updated', 'actions')\n default_columns = ('pk', 'name', 'items', 'slug', 'color', 'description')\n\n\nclass TaggedItemTable(NetBoxTable):\n id = tables.Column(\n verbose_name='ID',\n linkify=lambda record: record.content_object.get_absolute_url(),\n accessor='content_object__id'\n )\n content_type = columns.ContentTypeColumn(\n verbose_name='Type'\n )\n content_object = tables.Column(\n linkify=True,\n orderable=False,\n verbose_name='Object'\n )\n actions = columns.ActionsColumn(\n actions=()\n )\n\n class Meta(NetBoxTable.Meta):\n model = TaggedItem\n fields = ('id', 'content_type', 'content_object')\n\n\nclass ConfigContextTable(NetBoxTable):\n name = tables.Column(\n linkify=True\n )\n is_active = columns.BooleanColumn(\n verbose_name='Active'\n )\n\n class Meta(NetBoxTable.Meta):\n model = ConfigContext\n fields = (\n 'pk', 'id', 'name', 'weight', 'is_active', 'description', 'regions', 'sites', 'locations', 'roles',\n 'platforms', 'cluster_types', 'cluster_groups', 'clusters', 'tenant_groups', 'tenants', 'created',\n 'last_updated',\n )\n default_columns = ('pk', 'name', 'weight', 'is_active', 'description')\n\n\nclass ObjectChangeTable(NetBoxTable):\n time = tables.DateTimeColumn(\n linkify=True,\n format=settings.SHORT_DATETIME_FORMAT\n )\n user_name = tables.Column(\n verbose_name='Username'\n )\n full_name = tables.TemplateColumn(\n accessor=tables.A('user'),\n template_code=OBJECTCHANGE_FULL_NAME,\n verbose_name='Full Name',\n orderable=False\n )\n action = columns.ChoiceFieldColumn()\n changed_object_type = columns.ContentTypeColumn(\n verbose_name='Type'\n )\n object_repr = tables.TemplateColumn(\n accessor=tables.A('changed_object'),\n template_code=OBJECTCHANGE_OBJECT,\n verbose_name='Object',\n orderable=False\n )\n request_id = tables.TemplateColumn(\n template_code=OBJECTCHANGE_REQUEST_ID,\n verbose_name='Request ID'\n )\n actions = columns.ActionsColumn(\n actions=()\n )\n\n class Meta(NetBoxTable.Meta):\n model = ObjectChange\n fields = (\n 'pk', 'id', 'time', 'user_name', 'full_name', 'action', 'changed_object_type', 'object_repr', 'request_id',\n 'actions',\n )\n\n\nclass JournalEntryTable(NetBoxTable):\n created = tables.DateTimeColumn(\n linkify=True,\n format=settings.SHORT_DATETIME_FORMAT\n )\n assigned_object_type = columns.ContentTypeColumn(\n verbose_name='Object type'\n )\n assigned_object = tables.Column(\n linkify=True,\n orderable=False,\n verbose_name='Object'\n )\n kind = columns.ChoiceFieldColumn()\n comments = columns.MarkdownColumn()\n comments_short = tables.TemplateColumn(\n accessor=tables.A('comments'),\n template_code='{{ value|markdown|truncatewords_html:50 }}',\n verbose_name='Comments (Short)'\n )\n tags = columns.TagColumn(\n url_name='extras:journalentry_list'\n )\n\n class Meta(NetBoxTable.Meta):\n model = JournalEntry\n fields = (\n 'pk', 'id', 'created', 'created_by', 'assigned_object_type', 'assigned_object', 'kind', 'comments',\n 'comments_short', 'tags', 'actions',\n )\n default_columns = (\n 'pk', 'created', 'created_by', 'assigned_object_type', 'assigned_object', 'kind', 'comments'\n )\n","sub_path":"netbox/extras/tables/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"603302886","text":"\nimport pygame\nimport os\n\n\n\n\nclass Goban():\n def __init__(self, boardlist=None):\n \"\"\"Create, initialize and draw a stone.\"\"\" \n# def board_gui():\n if boardlist:\n self.boardlist = boardlist\n else:\n # https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python/3459131\n self.boardlist = [0]*361\n # for y in range(0, 361):\n # boardlist.append(0) \n\n def getFilePath(filename):\n my_path = os.path.abspath(os.path.dirname(__file__))\n path = os.path.join(my_path, filename)\n return path\n\n BACKGROUND = 'images/set41Board.png'\n self.BlackStone = pygame.image.load(getFilePath(\"images/set41Black.png\"))\n self.WhiteStone = pygame.image.load(getFilePath(\"images/set41White.png\"))\n # self.Empty = pygame.image.load(\"images/set41Empty.png\")\n\n \n\n\n # WhiteStone = pygame.image.load(\"images/set41WhiteV2.png\")\n\n \n # image size\n BOARD_SIZE = (840, 840)\n\n self.BOARDSIZE = 19\n\n # set: 41\n self.STONE_SIZE =41.0\n self.STONE_SIZE_INT =41\n self.STONE_HALF_INT =20\n # X0=166\n # Y0=1600\n self.SX0=-11\n self.SY0=-11\n\n\n pygame.init()\n pygame.display.set_caption('Board GUI')\n self.screen = pygame.display.set_mode(BOARD_SIZE, 0, 32)\n self.background = pygame.image.load(getFilePath(BACKGROUND)).convert()\n self.screen.blit(self.background, (0, 0))\n self.player = 1\n # screen.blit(background, (0, 0))\n pygame.display.flip()\n\n def switchPlayer(self):\n if self.player == 1:\n self.player = 2\n else:\n self.player = 1\n # print(\"player is \",self.player)\n def get18XY(self,pos):\n rawX, rawY = pos \n \n x = int(round(((rawX - 5) / self.STONE_SIZE), 0))\n y = int(round(((rawY - 5) / self.STONE_SIZE), 0))\n return x-1,y-1\n def renderBackground(self):\n self.screen.blit(self.background, (0, 0))\n def renderStones(self):\n def p(x,y):\n return x+19*y\n\n def xy( i):\n y = i // self.BOARDSIZE\n x = i - self.BOARDSIZE*y\n return x, y\n for k in range(361):\n x, y = xy(k)\n val = self.boardlist[k]\n x = self.SX0+(1+x)* self.STONE_SIZE_INT\n y = self.SY0+ (1+y) * self.STONE_SIZE_INT\n if val == 1:\n\n self.screen.blit(self.BlackStone, (x,y))\n\n if val == 2:\n self.screen.blit(self.WhiteStone, (x,y))\n def playXY(self,x,y):\n def p(x,y):\n return x+19*y\n if x >=0 and y >= 0 and x <=18 and y <=18:\n # if x >=1 and y >= 1 and x <=19 and y <=19:\n self.boardlist[p(x,y)]=self.player\n return True\n return False\n\n\n def show(self):\n # def p(x,y):\n # return x+19*y\n\n # def xy( i):\n # y = i // self.BOARDSIZE\n # x = i - self.BOARDSIZE*y\n # return x, y\n \n \n while True:\n self.renderBackground()\n self.renderStones()\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n print(\"user click on close window\")\n exit()\n # if event.type == pygame.key.get_pressed()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n return\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n # NOTE: Convert mouse position to go board 18*18\n x,y = self.get18XY(event.pos)\n\n # NOTE: When play is valid, change turn\n if self.playXY(x,y):\n self.switchPlayer()\n \n \nif __name__ == '__main__':\n \n # gui = BoardGUI([0]*361)\n BoardGUI([1]*361).show()\n BoardGUI([2]*361).show()\n boardlist =[]\n for k in range(361):\n boardlist.append(1+ k % 2)\n # print(boardlist)\n BoardGUI(boardlist).show()\n BoardGUI([0]*361).show()\n ","sub_path":"python-sockets-tutorial/goban/goban.py","file_name":"goban.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"50943543","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport datetime\nimport unittest\nimport os\nimport os.path\nimport shutil\nimport tempfile\n\nimport dbp_testing\nfrom dbprocessing import DBfile\nfrom dbprocessing import DButils\nfrom dbprocessing import Diskfile\nfrom dbprocessing import Version\n\nclass DBfileTests(unittest.TestCase, dbp_testing.AddtoDBMixin):\n \"\"\"Tests for DBfile class\"\"\"\n \n def setUp(self):\n super(DBfileTests, self).setUp()\n self.makeTestDB()\n sourcedir = os.path.join(dbp_testing.testsdir, '..',\n 'functional_test', 'L0')\n shutil.copytree(sourcedir, os.path.join(self.td, 'L0'))\n sourcepath = os.path.join(dbp_testing.testsdir, 'tars')\n for f in os.listdir(sourcepath):\n shutil.copy2(os.path.join(sourcepath, f), os.path.join(self.td, f))\n self.loadData(os.path.join(dbp_testing.testsdir, 'data', 'db_dumps',\n 'testDB_dump.json'))\n #Update the mission path to the tmp dir\n self.dbu.getEntry('Mission', 1).rootdir = self.td\n self.dbu.commitDB()\n self.dbu.MissionDirectory = self.dbu.getMissionDirectory()\n\n def tearDown(self):\n super(DBfileTests, self).tearDown()\n self.removeTestDB()\n\n def createDummyDBF(self, fname):\n fullpath = os.path.join(self.td, fname)\n dbf = DBfile.DBfile(fullpath, self.dbu, makeDiskFile=True)\n dbf.diskfile.params['utc_file_date'] = datetime.date.today()\n dbf.diskfile.params['utc_start_time'] = datetime.date.today()\n dbf.diskfile.params['utc_stop_time'] = datetime.date.today() + datetime.timedelta(days=1)\n dbf.diskfile.params['data_level'] = 0\n dbf.diskfile.params['file_create_date'] = datetime.date.today()\n dbf.diskfile.params['exists_on_disk'] = True\n dbf.diskfile.params['product_id'] = 1\n dbf.diskfile.params['shasum'] = Diskfile.calcDigest(fullpath)\n dbf.diskfile.params['version'] = Version.Version(1, 2, 3)\n\n return dbf\n\n def test_invalidInput(self):\n self.assertRaises(DBfile.DBfileError, DBfile.DBfile, self.td + '/L0/testDB_000_000.raw', self.dbu)\n\n def test_repr(self):\n dbf = DBfile.DBfile(self.td + '/L0/testDB_000_000.raw', self.dbu, makeDiskFile=True)\n self.assertTrue(dbf.__repr__().startswith(\" 0:\n\tvc = mergestack.pop()\n\tcommit = vc.commitobj\n\t#print commit.hex, commit.message.split(\"\\n\")[0]\n\tx = float(vc.x)\n\ty = float(vc.y)\n\tz = float(vc.z)\n\tcolors.extend(vc.mergecolor)\n\tcolors.extend(vc.mergecolor)\n\tcolors.extend(vc.mergecolor)\n\tcolors.extend(vc.mergecolor)\n\tvertices.extend([x, y - clen/2, z])\n\tvertices.extend([x, vc.parenty - clen/2, vc.parentz])\n\tvertices.extend([x, vc.parenty - clen/2, vc.parentz])\n\tvertices.extend([vc.parentx, vc.parenty - clen/2, vc.parentz])\n\tcolor_commitlines[2] = (float(125) + random.uniform(126, 205)) / 255\n\n\t# if we've seen this before, draw the commit text and continue on to the next merge\n\tif commit.hex in visitedcommits and commit.hex not in orighead.hex:\n\t\tdrawText(font, commit.parents[0].hex[0:8], x + 0.02, y - clen - nextlen - randy, z, textcolor)\n\t\tcontinue\n\tif firstline == True:\n\t\tcommitlinescolor = centrallinecolor\n\telse:\n\t\tcommitlinescolor = color_commitlines\n\tcolors, vertices, randy = add_commit(colors, vertices, x, y, z, commit, clen, True, commitlinescolor)\n\tif impcommit.hex in commit.hex:\n\t\tvisitedcommits[commit.hex] = (x, y, z, commit, vc.childcommit, firstline)\n\telse:\n\t\tvisitedcommits[commit.hex] = (x, y, z, commit, vc.childcommit, firstline)\n\tprintprogress(commitscount)\n\tcommitscount = commitscount + 1\n\twhile len(commit.parents) > 0:\n\t\tr = random.uniform(5, 10)\n\t\tif firstline:\n\t\t\tsw = switch\n\t\t\tswitch = 1 - switch\n\t\telse:\n\t\t\tsw = vc.switch\n\t\tif sw == 1:\n\t\t\tpxs = x + xlim * r\n\t\telse:\n\t\t\tpxs = x - (xlim * r)\n\t\tismerge = False\n\t\tif len(commit.parents) > 1:\n\t\t\tismerge = True\n\t\t\tvcmergecolor = copy.copy(color_mergelines)\n\t\t\tvcmergecolor[2] = (float(40) + random.uniform(41, 205)) / 255\n\t\t\tfor i, parent in enumerate(commit.parents):\n\t\t\t\tr = random.uniform(5, 10)\n\t\t\t\tq = random.uniform(25, 50)\n\t\t\t\tif i == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tif sw == 1:\n\t\t\t\t\tpxs = pxs + xlimextend * r\n\t\t\t\telse:\n\t\t\t\t\tpxs = pxs - (xlimextend * r)\n\t\t\t\tpxy = y - q\n\t\t\t\tvc = viscommit(parent, commit, pxs, pxy, z, x, y, z, vcmergecolor, sw)\n\t\t\t\tmergestack.append(vc)\n\t\t\txlim = xlim + xlimextend\n\t\t\tif xlim >= 5.0:\n\t\t\t\txlim = xlimextend\n\t\ty = y - (nextlen) - randy\n\n\t\tchildcommit = commit\n\t\tcommit = commit.parents[0]\n\t\t#print commit.hex,commit.message.split(\"\\n\")[0]\n\t\tif commit.hex in visitedcommits:\n\t\t\tbreak\n\t\t(colors, vertices, randy) = add_commit(colors, vertices, x, y, z, commit, clen,\n\t\t\t\t\t\t\tismerge or (len(commit.parents) > 1),\n\t\t\t\t\t\t\tcommitlinescolor)\n\t\tif impcommit.hex in commit.hex:\n\t\t\tvisitedcommits[commit.hex] = (x, y, z, commit, childcommit, firstline)\n\t\telse:\n\t\t\tvisitedcommits[commit.hex] = (x, y, z, commit, childcommit, firstline)\n\t\tprintprogress(commitscount)\n\t\tcommitscount = commitscount + 1\n\n\tif firstline == True:\n\t\t(colors, vertices, randy) = add_commit(colors, vertices, x, y, z, commit, clen,\n\t\t\t\t\t\t\tTrue,\n\t\t\t\t\t\t\tcommitlinescolor)\n\tfirstline = False\n\nimplinescolor = [1, 1, 1]\nprint(\"Starting highlight procedure...\")\ntraverse = visitedcommits[impcommit.hex]\nwhile traverse[5] is not True:\n\tx = traverse[0]\n\ty = traverse[1]\n\tz = traverse[2]\n\tchild = visitedcommits[traverse[4].hex]\n\tif child is None:\n\t\tbreak\n\n\tcx = child[0]\n\tcy = child[1]\n\tcz = child[2]\n\n\tif x == cx:\n\t\tcolors.extend(implinescolor)\n\t\tcolors.extend(implinescolor)\n\t\tvertices.extend([x, y, z])\n\t\tvertices.extend([cx, cy, cz])\n\telse:\n\t\t# reached a merge point!\n\t\tcolors.extend(implinescolor)\n\t\tcolors.extend(implinescolor)\n\t\tcolors.extend(implinescolor)\n\t\tcolors.extend(implinescolor)\n\t\tvertices.extend([x, y, z])\n\t\tvertices.extend([x, cy - clen/2, z])\n\t\tvertices.extend([x, cy - clen/2, z])\n\t\tvertices.extend([cx, cy - clen/2, z])\n\ttraverse = visitedcommits[traverse[4].hex]\nprint(\"Finished highlight procedure...\")\n\nglEndList ()\nglShadeModel (GL_FLAT)\nprint(\"Finished constructing text lists\")\n\n\ndef highlight_commit(hcommit):\n\thvertices = []\n\thcolors = []\n\ttraverse = visitedcommits[hcommit.hex]\n\thx = traverse[0]\n\thy = traverse[1]\n\thz = traverse[2]\n\thtextlist = glGenLists(1)\n\tglNewList (htextlist, GL_COMPILE)\n\tdrawText(font, hcommit.message.split(\"\\n\")[0], hx + 0.02, hy + 0.03, hz, imptextcolor)\n\n\twhile traverse[5] is not True:\n\t\tx = traverse[0]\n\t\ty = traverse[1]\n\t\tz = traverse[2]\n\t\tchild = visitedcommits[traverse[4].hex]\n\t\tif child is None:\n\t\t\tbreak\n\n\t\tcx = child[0]\n\t\tcy = child[1]\n\t\tcz = child[2]\n\n\t\tif x != cx:\n\t\t\tmsg = child[3].hex[0:8] + \" \" + child[3].message.split(\"\\n\")[0][0:51]\n\t\t\tdrawText(font, msg, cx + clen/2 + 0.05, cy + clen/2 + 0.05, cz, imptextcolor)\n\n\t\tif x == cx:\n\t\t\thcolors.extend(implinescolor)\n\t\t\thcolors.extend(implinescolor)\n\t\t\thvertices.extend([x, y, z])\n\t\t\thvertices.extend([cx, cy, cz])\n\t\telse:\n\t\t\t# reached a merge point!\n\t\t\thcolors.extend(implinescolor)\n\t\t\thcolors.extend(implinescolor)\n\t\t\thcolors.extend(implinescolor)\n\t\t\thcolors.extend(implinescolor)\n\t\t\thvertices.extend([x, y, z])\n\t\t\thvertices.extend([x, cy - clen/2, z])\n\t\t\thvertices.extend([x, cy - clen/2, z])\n\t\t\thvertices.extend([cx, cy - clen/2, z])\n\t\ttraverse = visitedcommits[traverse[4].hex]\n\tglEndList ()\n\tglShadeModel (GL_FLAT)\n\n\thbo = glGenBuffers (1)\n\tglBindBuffer (GL_ARRAY_BUFFER, hbo)\n\tglBufferData (GL_ARRAY_BUFFER, len(hvertices)*4, (c_float*len(hvertices))(*hvertices), GL_STATIC_DRAW)\n\tglVertexPointer (3, GL_FLOAT, 0, None)\n\n\thcbo = glGenBuffers(1)\n\tglBindBuffer(GL_ARRAY_BUFFER, hcbo)\n\tglBufferData(GL_ARRAY_BUFFER, len(hcolors)*4, (c_float*len(hcolors))(*hcolors), GL_STATIC_DRAW)\n\tglColorPointer(3, GL_FLOAT, 0, None)\n\n\treturn hvertices, hbo, hcbo, htextlist, hx, hy, hz\n\t\t\n\nprint(\"Binding buffers...\")\n# create vertex buffer object\nvbo = glGenBuffers (1)\nglBindBuffer (GL_ARRAY_BUFFER, vbo)\nglBufferData (GL_ARRAY_BUFFER, len(vertices)*4, (c_float*len(vertices))(*vertices), GL_STATIC_DRAW)\nglVertexPointer (3, GL_FLOAT, 0, None)\n\n# create color buffer object\ncbo = glGenBuffers(1)\nglBindBuffer(GL_ARRAY_BUFFER, cbo)\nglBufferData(GL_ARRAY_BUFFER, len(colors)*4, (c_float*len(colors))(*colors), GL_STATIC_DRAW)\nglColorPointer(3, GL_FLOAT, 0, None)\nprint(\"....done. Number of vertices:\", len(vertices))\n\nspeed = 32.0\nrunning = True\ndrawall = True\ntextrendering = False\n\nglShadeModel (GL_FLAT)\npygame.key.set_repeat(2,10)\n\nimpx = visitedcommits[impcommit.hex][0]\nimpy = visitedcommits[impcommit.hex][1]\nimpz = visitedcommits[impcommit.hex][2]\nimportantcommit = visitedcommits[impcommit.hex][3]\n\nlookdistance = 250\ngluLookAt(impx, impy, lookdistance, impx, impy, 0, 0, 1, 0)\n\nhbo = 0\nhcbo = 0\nhtextlist = 0\nhvertices = []\noverx = -40\novery = 40\noverz = 200\n\nstartcommitsearch = False\n\nwhile running:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\trunning = False\n\t\t\tbreak\n\t\telif event.type == pygame.KEYDOWN:\n\t\t\tdrawall = True\n\t\telif event.type == pygame.KEYUP:\n\t\t\tdrawall = True\n\t\t\tif event.key == pygame.K_t:\n\t\t\t\ttextrendering = not textrendering\n\t\t\telif event.key == pygame.K_q:\n\t\t\t\tspeed *= 2\n\t\t\t\tif speed > 1024:\n\t\t\t\t\tspeed = 1024\n\t\t\t\tprint(speed)\n\t\t\telif event.key == pygame.K_r:\n\t\t\t\tspeed /= 2\n\t\t\t\tif speed <= 1:\n\t\t\t\t\tspeed = 1\n\t\t\t\tprint(speed)\n\t\t\telif event.key == pygame.K_SLASH:\n\t\t\t\tstartcommitsearch = True\n\t\t\t\tsearchhex = \"\"\n\t\t\telif event.key == pygame.K_ESCAPE:\n\t\t\t\tstartcommitsearch = False\n\t\t\t\tsearchhex = \"\"\n\t\t\telif startcommitsearch and event.key >= pygame.K_a and event.key <= pygame.K_z:\n\t\t\t\tn = ord('a') + (event.key - pygame.K_a)\n\t\t\t\tif pygame.key.get_mods() & (KMOD_SHIFT | KMOD_CAPS):\n\t\t\t\t\tn = ord('A') + (event.key - pygame.K_a)\n\t\t\t\tsearchhex += chr(n)\n\t\t\t\tprint(searchhex)\n\t\t\telif startcommitsearch and event.key >= pygame.K_a and event.key <= pygame.K_f:\n\t\t\t\tn = 10 + event.key - pygame.K_a\n\t\t\t\tsearchhex += str(hex(n)).replace(\"0x\", \"\")\n\t\t\t\tprint(searchhex)\n\t\t\telif startcommitsearch and event.key >= pygame.K_0 and event.key <= pygame.K_9:\n\t\t\t\tn = event.key - pygame.K_0\n\t\t\t\tsearchhex += str(n)\n\t\t\t\tprint(searchhex)\n\t\t\telif startcommitsearch and event.key == K_BACKSPACE:\n\t\t\t\tif len(searchhex) > 0:\n\t\t\t\t\tsearchhex = searchhex[0:len(searchhex)-1]\n\n\t\tif startcommitsearch and len(searchhex) > 7:\n\t\t\ttry:\n\t\t\t\thcommit = repo.revparse_single(searchhex)\n\t\t\texcept:\n\t\t\t\tprint(\"Couldn't find \" + searchhex)\n\t\t\t\tstartcommitsearch = False\n\t\t\t\tcontinue\n\t\t\tstartcommitsearch = False\n\t\t\thvertices, hbo, hcbo, htextlist, hx, hy, hz = highlight_commit(hcommit)\n\t\t\tdrawall = True\n\t\t\tglLoadIdentity()\n\t\t\tgluPerspective(45, (display[0]/display[1]), 0.01, 9250.0)\n\t\t\tgluLookAt(hx, hy, lookdistance, hx, hy, 0, 0, 1, 0)\n\t\t\toverx = hx - 10\n\t\t\tovery = hy + 10\n\t\t\toverz = 200\n\n\t\tkp = pygame.key.get_pressed()\n\t\tif kp[K_RIGHT]:\n\t\t\tglTranslatef(-1 * speed, 0, 0)\n\t\t\toverx += speed\n\t\tif kp[K_LEFT]:\n\t\t\tglTranslatef(speed, 0, 0)\n\t\t\toverx -= speed\n\t\tif kp[K_w]:\n\t\t\tglTranslatef(0, 0, speed)\n\t\t\toverz -= speed\n\t\tif kp[K_s]:\n\t\t\tglTranslatef(0, 0, -1 * speed)\n\t\t\toverz += speed\n\t\tif kp[K_DOWN]:\n\t\t\tglTranslatef(0, speed, 0)\n\t\t\tovery -= speed\n\t\tif kp[K_UP]:\n\t\t\tglTranslatef(0, -1 * speed, 0)\n\t\t\tovery += speed\n\t\tif kp[K_z]:\n\t\t\trunning = False\n\t\t\tbreak\n\n\tif drawall == True:\n\t\t# clear and draw everything!\n\t\tglClear (GL_COLOR_BUFFER_BIT)\n\t\tif textrendering == True:\n\t\t\tglCallList (textlist)\n\t\tmsg = importantcommit.hex[0:8] + \" \" + importantcommit.message.split(\"\\n\")[0][0:10]\n\t\tdrawText(font, msg, impx + clen/2 + 0.05, impy + clen/2 + 0.05, impz, imptextcolor)\n\t\tglBindBuffer (GL_ARRAY_BUFFER, vbo)\n\t\tglVertexPointer (3, GL_FLOAT, 0, None)\n\t\tglBindBuffer (GL_ARRAY_BUFFER, cbo)\n\t\tglColorPointer (3, GL_FLOAT, 0, None)\n\t\t# create vertex buffer object\n\t\tglDrawArrays (GL_LINES, 0, int(len(vertices)/3))\n\t\tdrawText(font, \"gitGL\", overx, overy, overz, imptextcolor)\n\t\tif startcommitsearch:\n\t\t\tdrawText(font, \"search: \" + searchhex, overx, overy - 2, overz, imptextcolor)\n\t\tdrawText(font, \"speed: \" + str(speed), overx, overy - 3.5, overz, imptextcolor)\n\n\t\tif hbo > 0:\n\t\t\tpxpe = 1\n\t\t\tglBindBuffer (GL_ARRAY_BUFFER, hbo)\n\t\t\tglVertexPointer (3, GL_FLOAT, 0, None)\n\t\t\tglBindBuffer(GL_ARRAY_BUFFER, hcbo)\n\t\t\tglColorPointer(3, GL_FLOAT, 0, None)\n\t\t\tglLineWidth(2)\t\n\t\t\tglDrawArrays (GL_LINES, 0, len(hvertices)/3)\n\t\t\tglLineWidth(1)\t\n\t\t\tglCallList (htextlist)\n\t\tpygame.display.flip ()\n\t\tdrawall = False\n\tpygame.time.wait(10)\n","sub_path":"gitgl.py","file_name":"gitgl.py","file_ext":"py","file_size_in_byte":13565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"467262579","text":"from algotrader.utils.time_series import DataSeries\n\n\nclass Indicator(DataSeries):\n VALUE = 'value'\n\n __slots__ = (\n 'input_name',\n 'input_keys',\n 'calculate',\n )\n\n\n __transient__ = (\n 'app_context',\n 'input'\n )\n\n @staticmethod\n def get_name(indicator_name, input, input_key, *args):\n if not input:\n return '%s' % indicator_name\n parts = [Indicator.get_input_name(input)]\n if input_key:\n parts.extend(DataSeries.convert_to_list(input_key))\n if args:\n parts.extend(args)\n content = \",\".join(str(part) for part in parts)\n return '%s(%s)' % (indicator_name, content)\n\n @staticmethod\n def get_input_name(input):\n if isinstance(input, Indicator):\n return input.name\n if isinstance(input, DataSeries):\n return \"'%s'\" % input.name\n return \"'%s'\" % input\n\n def __init__(self, name, input, input_keys, desc=None, **kwargs):\n super(Indicator, self).__init__(name=name, desc=desc, **kwargs)\n\n self.input_keys = self._get_key(input_keys, None)\n self.calculate = True\n\n if input:\n if isinstance(input, DataSeries):\n self.input_name = input.name\n self.input = input\n else:\n self.input_name = input\n self.input = None\n\n def _start(self, app_context, **kwargs):\n super(Indicator, self)._start(self.app_context, **kwargs)\n\n if not hasattr(self, 'input') or not self.input:\n self.input = self.app_context.inst_data_mgr.get_series(self.input_name)\n\n self.app_context.inst_data_mgr.add_series(self)\n\n self.update_all()\n self.input.subject.subscribe(self.on_update)\n\n def _stop(self):\n pass\n\n def update_all(self):\n data_list = self.input.get_data()\n for data in data_list:\n # if timestamp has been processed, we should skipped the update.....\n if data['timestamp'] not in self.time_list:\n if self.input_keys:\n filtered_data = {key: data[key] for key in self.input_keys}\n filtered_data['timestamp'] = data['timestamp']\n self.on_update(filtered_data)\n else:\n self.on_update(data)\n\n def on_update(self, data):\n raise NotImplementedError()\n","sub_path":"algotrader/technical/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"136328512","text":"import json\n\nfrom pulsar import ImproperlyConfigured\nfrom pulsar.apps.wsgi import (route, wsgi_request, cached_property,\n html_factory)\nfrom pulsar.apps import wsgi\nfrom pulsar.apps.wsgi import RouterParam, Router, render_error_debug\nfrom pulsar.apps.wsgi.utils import error_messages\nfrom pulsar.utils.httpurl import (JSON_CONTENT_TYPES, is_absolute_uri,\n iri_to_uri)\nfrom pulsar.utils.structures import mapping_iterator\n\nfrom lux.utils import unique_tuple\nfrom pulsar.utils.exceptions import MethodNotAllowed\n\n__all__ = ['Html', 'WsgiRequest', 'Router', 'HtmlRouter',\n 'JsonRouter', 'route', 'wsgi_request',\n 'cached_property', 'html_factory', 'RedirectRouter',\n 'RouterParam', 'JSON_CONTENT_TYPES',\n 'DEFAULT_CONTENT_TYPES']\n\nHtml = wsgi.Html\n\n\nTEXT_CONTENT_TYPES = unique_tuple(('text/html', 'text/plain'))\n\nDEFAULT_CONTENT_TYPES = unique_tuple(('text/html', 'text/plain', 'text/csv'),\n JSON_CONTENT_TYPES)\n\n\nclass WsgiRequest(wsgi.WsgiRequest):\n '''Extend pulsar :class:`~pulsar.apps.wsgi.wrappers.WsgiRequest` with\n additional methods and attributes.\n '''\n @property\n def app(self):\n '''The :class:`.Application` running the website.'''\n return self.cache.app\n\n @property\n def config(self):\n '''The :attr:`.Application.config` dictionary'''\n return self.cache.app.config\n\n @property\n def logger(self):\n '''Shortcut to app logger'''\n return self.cache.app.logger\n\n @property\n def cache_server(self):\n return self.cache.app.cache_server\n\n @cached_property\n def html_document(self):\n '''The HTML document for this request.'''\n return self.app.html_document(self)\n\n @property\n def scheme(self):\n '''Protocol scheme, one of ``http`` and ``https``\n '''\n HEADER = self.config['SECURE_PROXY_SSL_HEADER']\n if HEADER:\n try:\n header, value = HEADER\n except ValueError:\n raise ImproperlyConfigured(\n 'The SECURE_PROXY_SSL_HEADER setting must be a tuple '\n 'containing two values.')\n return 'https' if self.environ.get(header) == value else 'http'\n return self.environ.get('HTTPS') == 'on'\n\n @property\n def is_secure(self):\n '''``True`` if this request is via a TLS connection\n '''\n return self.scheme == 'https'\n\n\nwsgi.set_wsgi_request_class(WsgiRequest)\n\n\nclass RedirectRouter(Router):\n\n def __init__(self, routefrom, routeto):\n super(RedirectRouter, self).__init__(routefrom, routeto=routeto)\n\n def get(self, request):\n return request.redirect(self.routeto)\n\n\nclass JsonRouter(Router):\n response_content_types = ['application/json']\n\n\nclass HtmlRouter(Router):\n '''Extend pulsar :class:`~pulsar.apps.wsgi.routers.Router`\n with content management.\n '''\n in_nav = False\n html_body_template = None\n form = None\n uirouter = None\n uimodules = None\n model = None\n response_content_types = TEXT_CONTENT_TYPES\n\n def get(self, request, html=None):\n # render the inner html\n if html is None:\n html = self.get_html(request)\n\n if isinstance(html, Html):\n html = html.render(request)\n\n # This request is for the inner template only\n if request.url_data.get('template') == 'ui':\n request.response.content = html\n return request.response\n\n context = {'html_main': html}\n self.context(request, context)\n app = request.app\n template = self.get_html_body_template(app)\n return app.html_response(request, template, context=context)\n\n def get_html(self, request):\n '''Must be implemented by subclasses.\n\n This method should return the main part of the html body.\n It is rendered where the $html_main key is placed.\n '''\n return ''\n\n def context(self, request, context):\n pass\n\n def get_html_body_template(self, app):\n '''Fetch the HTML template for the body part of this request\n '''\n cms = app.cms\n template = (cms.template(self.full_route.path) or\n self.html_body_template)\n if not template:\n if self.parent:\n template = self.parent.get_html_body_template(app)\n else:\n template = 'home.html'\n return template\n\n def childname(self, prefix):\n '''key for a child router\n '''\n return '%s%s' % (self.name, prefix) if self.name else prefix\n\n def make_router(self, rule, **params):\n '''Create a new :class:`.Router` form rule and parameters\n '''\n params.setdefault('cls', HtmlRouter)\n return super().make_router(rule, **params)\n\n def add_api_urls(self, request, api):\n for r in self.routes:\n if isinstance(r, Router):\n r.add_api_urls(request, api)\n\n def angular_page(self, app, router, page):\n '''Add angular router information (lux.extensions.angular)\n '''\n page['templateUrl'] = '%s?template=ui' % page['url']\n\n\nclass HeadMeta(object):\n '''Wrapper for HTML5 head metatags.\n '''\n def __init__(self, head):\n self.head = head\n\n def __repr__(self):\n return repr(self.head.meta.children)\n\n def __str__(self):\n return str(self.head.meta.children)\n\n def update(self, iterable):\n for name, value in mapping_iterator(iterable):\n self.set(name, value)\n\n def __setitem__(self, entry, content):\n self.set(entry, content)\n\n def __getitem__(self, entry):\n return self.get(entry)\n\n def __len__(self):\n return len(self.head.meta.children)\n\n def __iter__(self):\n return iter(self.head.meta.children)\n\n def set(self, entry, content, meta_key=None):\n '''Set the a meta tag with ``content`` and ``entry`` in the HTML5 head.\n The ``key`` for ``entry`` is either ``name`` or ``property`` depending\n on the value of ``entry``.\n '''\n if content:\n if entry == 'title':\n self.head.title = content\n else:\n self.head.replace_meta(entry, content, meta_key)\n\n def get(self, entry, meta_key=None):\n if entry == 'title':\n return self.head.title\n else:\n return self.head.get_meta(entry, meta_key=meta_key)\n\n\ndef error_handler(request, exc):\n '''Default renderer for errors.'''\n app = request.app\n response = request.response\n if not response.content_type:\n content_type = request.get('default.content_type')\n if content_type:\n response.content_type = request.content_types.best_match(\n content_type)\n content_type = None\n if response.content_type:\n content_type = response.content_type.split(';')[0]\n is_html = content_type == 'text/html'\n\n if app.debug:\n msg = render_error_debug(request, exc, is_html)\n else:\n msg = error_messages.get(response.status_code) or str(exc)\n if is_html:\n msg = app.render_template(['%s.html' % response.status_code,\n 'error.html'],\n {'status_code': response.status_code,\n 'status_message': msg})\n #\n if is_html:\n doc = request.html_document\n doc.head.title = response.status\n doc.body.append(msg)\n return doc.render(request)\n elif content_type in JSON_CONTENT_TYPES:\n return json.dumps({'status': response.status_code,\n 'message': msg})\n else:\n return '\\n'.join(msg) if isinstance(msg, (list, tuple)) else msg\n","sub_path":"lux/core/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":7862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"265271291","text":"\"\"\"\nDefines the possible infections within the game and their associated symptoms,\ntreatment, and prevention.\n\"\"\"\n\nINFECTIONS = [\n\n {\n\n 'name': 'Flu',\n 'type': 'viral',\n 'treatment': None,\n 'prevention': 'vaccination',\n 'unique_symptom': 'difficulty breathing',\n\n 'symptoms': [\n 'a cough',\n 'a fever',\n 'a sore throat',\n 'difficulty breathing'\n ]\n\n },\n\n {\n\n 'name': 'Ebola',\n 'type': 'viral',\n 'treatment': None,\n 'prevention': None,\n 'unique_symptom': 'red eyes',\n\n 'symptoms': [\n 'diarrhea',\n 'vomiting',\n 'a fever',\n 'red eyes'\n ]\n\n },\n\n {\n\n 'name': 'Smallpox',\n 'type': 'viral',\n 'treatment': None,\n 'prevention': 'vaccination',\n 'unique_symptom': 'a rash',\n\n 'symptoms': [\n 'vomiting',\n 'diarrhea',\n 'a rash'\n ]\n\n },\n\n {\n\n 'name': 'Anthrax',\n 'type': 'bacterial',\n 'treatment': 'antibiotic',\n 'prevention': None,\n 'unique_symptom': 'swelling',\n\n 'symptoms': [\n 'bleeding',\n 'swelling',\n 'vomiting',\n 'diarrhea'\n ]\n\n },\n\n {\n\n 'name': 'Botulism',\n 'type': 'bacterial',\n 'treatment': 'antitoxin',\n 'prevention': None,\n 'unique_symptom': 'paralysis',\n\n 'symptoms': [\n 'paralysis',\n 'vomiting',\n 'nausea'\n ]\n\n },\n\n {\n\n 'name': 'Salmonella',\n 'type': 'bacterial',\n 'treatment': 'antibiotic',\n 'prevention': None,\n 'unique_symptom': 'stomach cramps',\n\n 'symptoms': [\n 'vomiting',\n 'a fever',\n 'diarrhea',\n 'stomach cramps'\n ]\n\n }\n]\n","sub_path":"crystalcortex/game/infections.py","file_name":"infections.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"488810044","text":"#P30\n\"\"\"\nSurprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:\n\n1634 = 1**4 + 6**4 + 3**4 + 4**4\n8208 = 8**4 + 2**4 + 0**4 + 8**4\n9474 = 9**4 + 4**4 + 7**4 + 4**4\nAs 1 = 1**4 is not a sum it is not included.\n\nThe sum of these numbers is 1634 + 8208 + 9474 = 19316.\n\nFind the sum of all the numbers that can be written as the sum of fifth powers of their digits.\n\"\"\"\np=int(input('input the power:'))\nresult=0\nfor num in range(2,1000000):\n sumTerm=0\n numStr=str(num)\n for term in numStr:\n sumTerm = sumTerm + (int(term) ** p)\n if sumTerm == num:\n print(num)\n result=result+num\nprint('The result is',result)\n\nprint('the result is {result}')\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"P30.py","file_name":"P30.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"129870858","text":"#!/usr/bin/env python3\n\nimport cv2\nimport numpy as np\nimport scipy.cluster.vq\nimport math\n\n\n\n\ndef dist_between(rho1, theta1, rho2, theta2):\n return (rho1 - rho2) ** 2 + (theta1 - theta2) ** 2\n\ndef find_border(lines):\n #### Split into vert and horizontal\n avg_rho, avg_theta = np.mean(lines, axis=0)\n low_thresh = np.pi / 4\n high_thresh = 3 * np.pi / 4\n print(avg_theta)\n\n linesV = []\n linesH = []\n for i in range(len(lines)):\n line = lines[i]\n rho, theta = line[0], line[1]\n if theta > high_thresh or theta < low_thresh:\n linesV.append(line)\n print(line)\n else:\n linesH.append(line)\n\n \n linesV = np.asarray(linesV)\n linesH = np.asarray(linesH)\n \n\n #find extremeties\n lineV1 = linesV[np.argmin(abs(linesV), axis=0)][0]\n lineV2 = linesV[np.argmax(abs(linesV), axis=0)][0]\n lineH1 = linesH[np.argmin(abs(linesH), axis=0)][0]\n lineH2 = linesH[np.argmax(abs(linesH), axis=0)][0]\n\n\n #print lines given extremities\n edge_lines = [lineV1, lineV2, lineH1, lineH2]\n \n return edge_lines\n\ndef draw_border(img, name, edge_lines):\n for i in range(len(edge_lines)):\n line = edge_lines[i]\n print(\"line\",line)\n rho, theta = line[0], line[1]\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 10000 * (-b))\n y1 = int(y0 + 10000 * a)\n x2 = int(x0 - 10000 * (-b))\n y2 = int(y0 - 10000 * a)\n\n cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 3)\n\n\n\ndef draw_intersection(img, line1, line2): \n rho1, theta1, rho2, theta2 = line1[0], line1[1], line2[0], line2[1]\n \n x = (rho2 * np.sin(theta1) - rho1 * np.sin(theta2)) / (np.sin(theta1 - theta2))\n \n y = (rho1 * np.cos(theta2) - rho2 * np.cos(theta1)) / (np.sin(theta1 - theta2))\n \n cv2.circle(img, (x, y), 2, (255, 255, 255), 2)\n return (x, y)\n\ndef draw_corners(img, name, edge_lines):\n\n lineV1 = edge_lines[0]\n lineV2 = edge_lines[1]\n lineH1 = edge_lines[2]\n lineH2 = edge_lines[3]\n\n corner1 = draw_intersection(img, lineV1, lineH1)\n corner2 = draw_intersection(img, lineV1, lineH2)\n corner3 = draw_intersection(img, lineV2, lineH1)\n corner4 = draw_intersection(img, lineV2, lineH2)\n \n corners = []\n corners.append(corner1)\n corners.append(corner2)\n corners.append(corner3)\n corners.append(corner4)\n\n cv2.imwrite('board_output/houghlines_' + name + '.jpg', img)\n\n return corners\n\ndef compute_proj_transform(corners):\n A = np.ones((3,3)) \n A[0, 0] = corners[0][0]\n A[0, 1] = corners[1][0] \n A[0, 2] = corners[2][0] \n A[1, 0] = corners[0][1] \n A[1, 1] = corners[1][1] \n A[1, 2] = corners[2][1] \n\n b = np.ones((3, 1)) \n b[0, 0] = corners[3][0]\n b[1, 0] = corners[3][1]\n \n vec = np.linalg.solve(A, b)\n print(vec)\n\n A[:, 0] *= vec[0, 0]\n A[:, 1] *= vec[1, 0]\n A[:, 2] *= vec[2, 0]\n\n B = np.ones((3,3)) \n B[0, 0] = 1\n B[0, 1] = 1\n B[0, 2] = 1023\n B[1, 0] = 1\n B[1, 1] = 1023\n B[1, 2] = 1\n\n b2 = np.ones((3, 1)) \n b2[0, 0] = 1023\n b2[1, 0] = 1023\n \n vec2 = np.linalg.solve(B, b2)\n B[:, 0] *= vec2[0, 0]\n B[:, 1] *= vec2[1, 0]\n B[:, 2] *= vec2[2, 0]\n\n C = B @ np.linalg.inv(A)\n return C\n\ndef draw_transformed_img(img, proj_transform):\n new_img = np.zeros(img.shape)\n print(img.shape)\n \n for i, j in np.ndindex(img.shape[0], img.shape[1]):\n vec = np.ones((3, 1))\n vec[0, 0] = j\n vec[1, 0] = i\n\n new_vec = proj_transform @ vec\n #print(new_vec)\n zP = new_vec[2, 0]\n new_x = int(new_vec[0, 0] / zP)\n new_y = int(new_vec[1, 0] / zP)\n\n if(new_x >= 0 and new_x < img.shape[1] and new_y >= 0 and new_y < img.shape[0]):\n new_img[new_y, new_x] = img[i, j]\n \n cv2.imwrite('board_output/test.jpg', new_img)\n\ndef main():\n name = \"8253_labeled\"\n img_path = 'board_images/' + name + '.jpg'\n\n img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n\n lines = cv2.HoughLines(edges, 1, np.pi / 360, 200)\n lines = np.ndarray.flatten(lines)\n lines = np.reshape(lines, (len(lines) // 2, 2))\n\n edge_lines = find_border(lines)\n draw_border(img, name, edge_lines) \n \n corners = draw_corners(img, name, edge_lines)\n\n proj_transform = compute_proj_transform(corners)\n draw_transformed_img(img, proj_transform)\n \nif __name__ == '__main__':\n main()\n","sub_path":"board_transform.py","file_name":"board_transform.py","file_ext":"py","file_size_in_byte":4586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"567498137","text":"spam = ['apples', 'bananas', 'tofu', 'cats']\r\n\r\ndef addVirgularEmLista(lista):\r\n str = ''\r\n count = 0\r\n for i in lista:\r\n if count == len(lista) - 1:\r\n str += ' and ' + i\r\n elif count == len(lista) - 2:\r\n str += i\r\n else:\r\n str += i + ', '\r\n count += 1\r\n return str\r\n\r\nprint(addVirgularEmLista(spam))\r\n\r\n\r\n\r\n","sub_path":"projetos/cap4-codigo-virgulas.py","file_name":"cap4-codigo-virgulas.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"234340152","text":"\"\"\"Templatetags for the ``online_docs`` app.\"\"\"\nfrom django import template\n\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef render_docs_link(request):\n t = template.loader.get_template('online_docs/online_docs_link.html')\n ctx = template.RequestContext(request)\n return t.render(ctx)\n","sub_path":"online_docs/templatetags/online_docs_tags.py","file_name":"online_docs_tags.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"19895420","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 16:38:10 2018\n\n@author: kzile\n\"\"\"\nimport os\nimport sys\nsys.path.insert(0, './src')\nfrom revised_inference import run_inference\nfrom revised_classifier import train\nimport revised_train_softmax\nimport facenet\nimport imageio\nimport numpy as np\nimport shutil\nimport string\n\ndef reframe():\n \n path_to_new_aligned_data = './collected_dataset'\n new_data_tmp = facenet.get_dataset(path_to_new_aligned_data)\n \n # Directory to access processed images\n put_into_classifier_data = './reframed_dataset'\n \n print('Number of new persons adding to classifier: ' + str(len(new_data_tmp)))\n \n for person in new_data_tmp:\n \n # Decalring name of person\n name = person.name\n \n # Declaring number of images for this person\n nrof_image = len(person.image_paths)\n \n print('Number of images for {a}: {b}'.format(a=name, b=nrof_image))\n \n # Change directory to see if there is an existing folder for this person\n os.chdir(put_into_classifier_data)\n if not os.path.exists(name):\n os.mkdir(name)\n \n # Return to base directory\n os.chdir('../')\n \n # preprocess image\n for n in range(nrof_image):\n # Get image file name\n filename = person.image_paths[n].replace(path_to_new_aligned_data, '')\n ## \\\\ in replace represents only a single \\\n filename = filename.replace('\\\\' + name + '\\\\', '')\n shutil.copyfile(person.image_paths[n], put_into_classifier_data + '/' + name + '/' + filename)\n \ndef collected():\n \n # Load dataset\n path_to_new_data = './recorder'\n \n # Arrange dataset\n list_of_pictures = os.listdir(path_to_new_data)\n list_of_pictures = sorted(list_of_pictures) \n \n for pic in list_of_pictures:\n print(type(pic[-3:]))\n if pic[-3:] == 'jpg':\n name = ''\n for letter in pic:\n if letter in string.digits:\n break\n else:\n name += letter\n os.chdir(path_to_new_data)\n if not os.path.exists(name):\n os.mkdir(name)\n os.chdir('../')\n shutil.copyfile(path_to_new_data + '/' + pic, path_to_new_data + '/' + name + '/' + pic)\n else:\n pass\n\n \n \n # Creating a temporary folder for mtcnn_aligned images\n os.system('python ' + './src/align/align_dataset_mtcnn.py ' + path_to_new_data + ' ' + path_to_new_data + '_rev' + ' ' + '--image_size 182 --margin 44')\n aligned_data = './recorder_rev'\n new_data_tmp = facenet.get_dataset(aligned_data)\n \n # Directory to access processed images\n ready_to_use = './collected_dataset'\n \n print('Number of new persons adding to dataset: ' + str(len(new_data_tmp)))\n \n for person in new_data_tmp:\n \n # Decalring name of person\n name = person.name\n \n # Declaring number of images for this person\n nrof_image = len(person.image_paths)\n \n print('Number of images for {a}: {b}'.format(a=name, b=nrof_image))\n \n # Change directory to see if there is an existing folder for this person\n os.chdir(ready_to_use)\n if not os.path.exists(name):\n os.mkdir(name)\n os.chdir('../')\n \n # preprocess image\n for n in range(nrof_image):\n # Load image\n img = facenet.load_data([person.image_paths[n]], False, False, 160)\n \n # Reformat to remove 1st dimension (which is no. of image in this case always 1)\n img = np.squeeze(img, axis=0)\n \n # Get image file name\n filename = person.image_paths[n].replace(aligned_data, '')\n ## \\\\ in replace represents only a single \\\n filename = filename.replace('\\\\' + name + '\\\\', '')\n \n # Change directory ready_dataset then save\n # Note! This will overwrite any image files with the same name\n os.chdir(ready_to_use + '/' + name)\n imageio.imsave(filename, img)\n os.chdir('../..')\n \n # Deletes temporary folder with mtcnn_aligned images \n shutil.rmtree(aligned_data, ignore_errors=None, onerror=None)\n \n ","sub_path":"Facial based Identity recognition/fr.py","file_name":"fr.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"113836343","text":"#!/usr/bin/python\n# encoding=utf-8\n\nfrom operator import itemgetter, attrgetter\n\nimport pymysql\nimport sqlparse\nfrom pymysql.converters import escape_item\nfrom pymysql.err import ProgrammingError\nfrom python_cgtools.utils import *\nfrom sqlalchemy import create_engine\nfrom sshtunnel import SSHTunnelForwarder\n\n\n# 获得数据连接\ndef get_connection(host, user, password, port, db=None, charset=\"UTF8\"):\n # charset=\"utf8\"必须加,否则中文出现乱码\n return pymysql.connect(host=host, user=user, passwd=password, port=port, db=db, charset=charset)\n\n\n# 获得curses(_cursor=pymysql.cursors.DictCursor)\ndef get_cursors(conn, n=1, _cursor=None):\n if n == 1:\n # 注意n=1一定要单独拿出来讨论,不然会被包装为tuple,使得后面的initializeCursors出问题\n return conn.cursor(cursor=_cursor)\n cursors = []\n while n >= 1:\n cursors.append(conn.cursor(cursor=_cursor))\n n -= 1\n return tuple(cursors)\n\n\n# 初始化cursers\ndef initialize_cursors(*cursors):\n for cur in cursors:\n cur.execute(\"SET NAMES 'utf8mb4'\")\n cur.execute(\"SET CHARACTER SET utf8mb4\")\n cur.execute(\"SET CHARACTER_SET_RESULTS=utf8mb4\")\n cur.execute(\"SET CHARACTER_SET_CONNECTION=utf8mb4\")\n\n\n# 关闭cursers\ndef close_cursors(*cursors):\n for cursor in cursors:\n cursor.close()\n\n\n# 关闭数据连接\ndef close_connections(*connections):\n for connection in connections:\n try:\n connection.close()\n # 避免Already closed的异常\n except pymysql.err.Error:\n pass\n\n\n# 同时关闭游标和数据库连接\ndef close_all(_cursors=None, _connections=None):\n if _cursors is not None:\n if is_sequence(_cursors):\n close_cursors(*_cursors)\n else:\n close_cursors(_cursors)\n if _connections is not None:\n if is_sequence(_connections):\n close_connections(*_connections)\n else:\n close_connections(_connections)\n\n\n# 根据最大尝试次数获取数据库连接\ndef get_conn_cur_by_class(_class, _n=1, _cursor=None, _try_times=5, _time_sleep=3):\n while _try_times > 0:\n try:\n conn = pymysql.connect(host=_class.host, port=_class.port, user=_class.user,\n password=_class.password, db=_class.db, charset=_class.charset)\n curs = get_cursors(conn, _n, _cursor)\n initialize_cursors(curs)\n return conn, curs\n except Exception as e:\n print(type(e))\n print(e)\n time.sleep(_time_sleep)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\n# ���据最大尝试次数获取数据\ndef fetch_all(_conn, _cur, _sql, _try_times=5):\n while _try_times > 0:\n try:\n return (_conn, _cur), _cur.execute(_sql), _cur.fetchall()\n except ProgrammingError as e:\n print(_sql)\n raise e\n except Exception as e:\n print(_sql)\n print(type(e))\n print(e)\n close_all(_cur, _conn)\n time.sleep(3)\n # 注意,当程序运行时间较长的时候,会报(0, '')\n # 这说明长时间idle导致的conn失效与 conn.close()之后的状态是不一样的\n # http://www.cnblogs.com/bugmaker/articles/2444905.html\n _conn, _cur = get_conn_cur_by_class(_conn)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\n# 根据最大尝试次数获取单列\ndef fetch_all_with_one_column(_conn, _cur, _sql, _try_times=5):\n (_conn, _cur), _count, _result = fetch_all(_conn, _cur, _sql, _try_times=_try_times)\n return (_conn, _cur), _count, get_sub_list_from_2d_list(_result, _index=0)\n\n\n# 根据最大尝试次数获取单列\ndef fetch_all_with_one_column_with_class(_class, _sql, _try_times=5):\n _conn, _cur = get_conn_cur_by_class(_class)\n (_conn, _cur), _, _result = fetch_all_with_one_column(_conn, _cur, _sql, _try_times=_try_times)\n close_all(_cur, _conn)\n return _result\n\n\n# 根据最大尝试次数获取数据\ndef fetch_one(_conn, _cur, _sql, _try_times=5):\n while _try_times > 0:\n try:\n return (_conn, _cur), _cur.execute(_sql), _cur.fetchone()\n except ProgrammingError as e:\n print(_sql)\n raise e\n except Exception as e:\n print(type(e))\n print(e)\n close_all(_cur, _conn)\n time.sleep(3)\n _conn, _cur = get_conn_cur_by_class(_conn)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\n# 根据最大尝试次数获取单列\ndef fetch_one_with_one_column(_conn, _cur, _sql, _try_times=5):\n (_conn, _cur), _count, _result = fetch_one(_conn, _cur, _sql, _try_times=_try_times)\n return (_conn, _cur), _count, _result[0]\n\n\n# 根据最大尝试次数执行语句execute(包含commit)\ndef execute(_conn, _cur, _sql, _try_times=5, _with_commit=True, _with_insert_id=False):\n while _try_times > 0:\n try:\n result = _cur.execute(_sql)\n if _with_commit:\n _conn.commit()\n if _with_insert_id:\n return (_conn, _cur), _cur.lastrowid, result\n else:\n return (_conn, _cur), result\n except ProgrammingError as e:\n print(_sql)\n raise e\n except Exception as e:\n print(type(e))\n print(e)\n close_all(_cur, _conn)\n time.sleep(3)\n _conn, _cur = get_conn_cur_by_class(_conn)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\n# 根据最大尝试次数执行语句executemany(包含commit)\ndef executemany(_conn, _cur, _sql, _values, _try_times=5, _with_commit=True):\n while _try_times > 0:\n try:\n result = _cur.executemany(_sql, _values)\n if _with_commit:\n _conn.commit()\n return (_conn, _cur), result\n except ProgrammingError as e:\n print(_sql)\n raise e\n except Exception as e:\n print(type(e))\n print(e)\n close_all(_cur, _conn)\n time.sleep(3)\n _conn, _cur = get_conn_cur_by_class(_conn)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\n# 根据最大尝试次数获取数据库连接\ndef get_engine_by_class(_class, _db=None, _try_times=5):\n assert _db is not None and len(_db) > 0, \"数据库名不能为空\"\n engine_url = \"mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset={charset}\" \\\n .format(user=_class.user, password=_class.password, host=_class.host, port=_class.port, db=_db,\n charset=_class.charset)\n while _try_times > 0:\n try:\n engine = create_engine(engine_url)\n return engine\n except Exception as e:\n print(type(e))\n print(e)\n time.sleep(3)\n _try_times -= 1\n if _try_times > 0:\n print(\"最后第{try_times}次尝试\".format(try_times=_try_times))\n else:\n raise e\n\n\nclass SendMessageUser3306(object):\n name = \"send_message_user_3306\"\n host = \"172.16.0.103\"\n port = 3306\n user = \"send_message_user\"\n password = \"S6*Zft%IFdE64jT2b&XfykMFRlnUyNHF\"\n charset = \"UTF8\"\n db = None\n\n\nclass WorkOrderUser3306(object):\n name = \"workOrder_user_3306\"\n host = \"172.16.0.105\"\n port = 3306\n user = \"workOrder_user\"\n password = \"3JLUBjELrd7bHGpbiEORcKt6%6!D!rn0\"\n charset = \"UTF8\"\n db = None\n\n\nclass AnalysisUser3406(object):\n name = \"analysis_user_3406\"\n host = \"118.178.139.112\"\n port = 3406\n user = \"analysis_user\"\n password = \"driv!p8AOZaDn^Xhhh%Z$wY8p$!!*9O#\"\n charset = \"UTF8\"\n db = None\n\n\nclass AnalysisUser3407(object):\n name = \"analysis_user_3407\"\n host = \"118.178.139.112\"\n port = 3407\n user = \"analysis_user\"\n password = \"L7#05*YoT5Z$yyOT8S2DX&qv&NWBT9i^\"\n charset = \"UTF8\"\n db = None\n\n\n# # 主库,不再使用,从相应的从库中查\n# class AnalysisUser3411(object):\n# name = \"analysis_user_3411\"\n# host = \"118.178.139.112\"\n# port = 3411\n# user = \"analysis_user\"\n# password = \"WO0k7c0O2y77BdTL47VDdfCuW2iPw701\"\n# charset = \"UTF8\"\n\n\nclass AnalysisUser6066(object):\n name = \"analysis_user_6066\"\n host = \"10.24.239.2\"\n port = 6066\n user = \"analysis_user\"\n password = \"WO0k7c0O2y77BdTL47VDdfCuW2iPw701\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3401(object):\n name = \"ugc_user_on_3401\"\n host = \"118.178.139.112\"\n port = 3401\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3402(object):\n name = \"ugc_user_on_3402\"\n host = \"118.178.139.112\"\n port = 3402\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3406(object):\n name = \"ugc_user_on_3406\"\n host = \"118.178.139.112\"\n port = 3406\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3407(object):\n name = \"ugc_user_on_3407\"\n host = \"118.178.139.112\"\n port = 3407\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3408(object):\n name = \"ugc_user_on_3408\"\n host = \"118.178.139.112\"\n port = 3408\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3409(object):\n name = \"ugc_user_on_3409\"\n host = \"118.178.139.112\"\n port = 3409\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3501(object):\n name = \"ugc_user_on_3501\"\n host = \"118.178.139.112\"\n port = 3501\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\n# class UgcUserOn3502(object):\n# name = \"ugc_user_on_3502\"\n# host = \"118.178.139.112\"\n# port = 3502\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n\nclass UgcUserOn3503(object):\n name = \"ugc_user_on_3503\"\n host = \"118.178.139.112\"\n port = 3503\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3504(object):\n name = \"ugc_user_on_3504\"\n host = \"118.178.139.112\"\n port = 3504\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3505(object):\n name = \"ugc_user_on_3505\"\n host = \"118.178.139.112\"\n port = 3505\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\n# class UgcUserOn3506(object):\n# name = \"ugc_user_on_3506\"\n# host = \"118.178.139.112\"\n# port = 3506\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\nclass UgcUserOn3508(object):\n name = \"ugc_user_on_3508\"\n host = \"118.178.139.112\"\n port = 3508\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3510(object):\n name = \"ugc_user_on_3510\"\n host = \"118.178.139.112\"\n port = 3510\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3513(object):\n name = \"ugc_user_on_3513\"\n host = \"118.178.139.112\"\n port = 3513\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass UgcUserOn3515(object):\n name = \"ugc_user_on_3515\"\n host = \"118.178.139.112\"\n port = 3515\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\n# class UgcUser3403(object):\n# name = \"ugc_user_3403\"\n# host = \"118.178.139.112\"\n# port = 3403\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n\n# class UgcUser3404(object):\n# name = \"ugc_user_3404\"\n# host = \"118.178.139.112\"\n# port = 3404\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n\n# class UgcUser3405(object):\n# name = \"ugc_user_3405\"\n# host = \"118.178.139.112\"\n# port = 3405\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n# class UgcUser3410(object):\n# name = \"ugc_user_3410\"\n# host = \"118.178.139.112\"\n# port = 3410\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n\n# class UgcUser3411(object):\n# name = \"ugc_user_3411\"\n# host = \"118.178.139.112\"\n# port = 3411\n# user = \"ugc_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\nclass UgcUser6000(object):\n name = \"ugc_user_6000\"\n host = \"116.62.24.58\"\n port = 6000\n user = \"ugc_user\"\n password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n charset = \"UTF8\"\n db = None\n\n\nclass BiUserOffline(object):\n name = \"bi_user_offline\"\n host = \"118.178.139.112\"\n port = 3330\n user = \"bi_user\"\n password = \"gocepfFaXvTq3kTTloWHLE2b\"\n charset = \"UTF8\"\n db = None\n\n\n# class BiUser3306(object):\n# name = \"bi_user_3306\"\n# host = \"rdsmeauv2zfmqjy.mysql.rds.aliyuncs.com\"\n# port = 3306\n# user = \"bi_user\"\n# password = \"0921WBg2F2qnYjO892EyE28ZcLDHdW28\"\n# charset = \"UTF8\"\n# db = None\n\n\nclass BiUserOnline(object):\n name = \"bi_user_online\"\n host = \"172.16.12.7\"\n port = 15066\n user = \"bi_user\"\n password = \"eOgDUJaNcBpLHZeFYKtrKRxhTdhFznXZ\"\n charset = \"UTF8\"\n db = None\n\n\nclass BiUser10813(object):\n name = \"bi_user_10813\"\n host = \"585a7b55718f0.bj.cdb.myqcloud.com\"\n port = 10813\n user = \"bi_user\"\n password = \"wqbZ4PWxR7ttpkMW\"\n charset = \"UTF8\"\n db = None\n\n\n# 获取SSH限制的数据库的连接\ndef get_production_server(_class):\n production_connection = _class()\n return SSHTunnelForwarder(\n (production_connection.sshHost, production_connection.sshPort),\n ssh_username=production_connection.sshUsername,\n ssh_password=production_connection.sshPassword,\n remote_bind_address=(production_connection.host, production_connection.port))\n\n\n# 获取一个select语句的查询列,必须明确有as指定,不支持select 123这样的语句\ndef get_simple_sql_column_list(_sql):\n stmt = sqlparse.parse(_sql)[0]\n column_list = []\n for token in stmt.tokens:\n if isinstance(token, sqlparse.sql.Identifier):\n column_list.append(token.get_name())\n break\n if isinstance(token, sqlparse.sql.IdentifierList):\n for sub_token in token:\n if isinstance(sub_token, sqlparse.sql.Identifier):\n column_list.append(sub_token.get_name())\n break\n return column_list\n\n\n# 用单引号包装字符串,如果字符串本身带有单引号,为了方便mysql插入,将一个单引号变成两个连写的单引号\n# 弃用,而直接使用from pymysql.converters import escape_item\ndef __escape_string_for_mysql(_value, _charset=\"UTF-8\", _replace_quote=True):\n # None特殊处理\n if _value is None:\n return \"null\"\n # bool类型是int类型的一种\n assert isinstance(_value, (str, int, float, bool, datetime.datetime, datetime.date)), \\\n \"目前只支持str, int, float, bool, datetime.datetime, datetime.date数据类型\"\n if isinstance(_value, str):\n if _replace_quote:\n return \"'\" + _value.replace(\"'\", \"''\") + \"'\"\n else:\n return \"'\" + _value + \"'\"\n if isinstance(_value, (datetime.datetime, datetime.date)):\n return \"'\" + str(_value) + \"'\"\n return str(_value)\n\n\n# 将一个值列表转化为mysql的insert语句中多个values值,提高mysql执行效率\n# 注意传入变量必须形如[[], []],注意fetch_one的结果不能直接传入,而应该采用[fetch_one]\ndef join_big_sql_from_list(_values, _charset=\"UTF-8\", _max_length=1000000):\n assert isinstance(_values, (tuple, list, zip, np.ndarray)), \"参数必须传入可迭代的列表或者元祖\"\n final_string_list = []\n final_string = \"\"\n for values in _values:\n if not isinstance(values, (tuple, list, np.ndarray)):\n values = (values,)\n escape_string = \",\".join([escape_item(value, _charset) for value in values])\n escape_string_length = len(escape_string)\n assert escape_string_length < _max_length, \"'\" + escape_string + \"',字段长度太大,一个sql语句无法执行!\"\n if len(final_string) + escape_string_length + 1 > _max_length:\n final_string_list.append(final_string[:-1])\n final_string = \"\"\n final_string += \"(\" + escape_string + \"),\"\n if final_string:\n final_string_list.append(final_string[:-1])\n return tuple(final_string_list)\n\n\n# 将一个dataframe转化为mysql的insert语句中多个values值,提高mysql执行效率\ndef join_big_sql_from_dataframe(_df, _charset=\"UTF-8\", _max_length=1000000):\n # 需要将_df的数据类型强转,因为escape_item只支持原生类型,不支持形如numpy.int64这样的类型\n # astype不会影响元数据\n return _df.columns.tolist(), join_big_sql_from_list(_df.values.astype(object), _charset=_charset,\n _max_length=_max_length)\n\n\n# 利用limit、offset多次执行mysql语句获得较大的结果集\n# 注意必须显示的写明ORDER BY,否则limit offset会失效\ndef get_many_results_by_limit_and_offset(_conn, _cur, _sql, _limit=10000, _offset=0):\n if \"order by\" not in _sql.lower():\n raise ValueError(\"必须显式的指明ORDER BY的顺序,否则limit offset将会失效\")\n result_tuple = tuple()\n while True:\n sql = _sql + \" LIMIT \" + str(_offset) + \", \" + str(_limit)\n (_conn, _cur), result_number, results = fetch_all(_conn, _cur, sql)\n result_tuple += results\n if result_number < _limit:\n break\n _offset += _limit\n return (_conn, _cur), result_tuple\n\n\n# 通过cur获得sql语句的列名\ndef get_columns_from_cur(_cur):\n return list(map(itemgetter(0), _cur.description))\n\n\ndef sort_object_list(_object_list, _attr, _reverse=False):\n return sorted(_object_list, key=attrgetter(_attr), reverse=_reverse)\n\n\n# 将fetch_all结果转为dataframe\ndef fetch_all_dataframe_with_conn_cur(_conn, _cur, _sql, _columns=None, _print=False, _index=None, _drop=True):\n if _print:\n print(_sql)\n (_conn, _cur), _, results = fetch_all(_conn, _cur, _sql)\n if _columns is None:\n results = pd.DataFrame(list(results), columns=get_columns_from_cur(_cur))\n if _index is not None:\n return _conn, _cur, results.set_index(keys=_index, drop=_drop)\n else:\n return _conn, _cur, results\n else:\n results = pd.DataFrame(list(results), columns=_columns)\n if _index is not None:\n return _conn, _cur, results.set_index(keys=_index, drop=_drop)\n else:\n return _conn, _cur, results\n\n\n# 将fetch_all结果转为dataframe\ndef fetch_all_dataframe_with_class(_class, _sql, _columns=None, _print=False, _index=None, _drop=True):\n if _print:\n print(_sql)\n _conn, _cur = get_conn_cur_by_class(_class)\n _conn, _cur, results = fetch_all_dataframe_with_conn_cur(_conn, _cur, _sql, _columns, _print, _index, _drop)\n close_all(_cur, _conn)\n return results\n\n\n# 描述一个表的详情\n@func_timer(True)\ndef describe_table(_class, _db, _table, _only_description=False, _with_row_count=True, _with_index=True,\n _with_min_max=False):\n # 执行一些形如\"SHOW INDEX FROM\"的sql底层语句的时候,需要db与其对应\n initial_db = _class.db\n _class.db = _db\n if _only_description:\n _with_row_count = False\n _with_index = False\n _with_min_max = False\n print(\"描述[{conn_name}]{db}.{table}\".format(conn_name=_class.name, db=_db, table=_table))\n\n conn, cur = get_conn_cur_by_class(_class)\n cur_dict = get_cursors(conn, _cursor=pymysql.cursors.DictCursor)\n\n print(\"\\t基本信息\")\n (conn, cur_dict), _, res = fetch_one(conn, cur_dict,\n \"SHOW TABLE STATUS FROM {db} LIKE '{table}'\".format(db=_db, table=_table))\n print(\"\\t\\t引擎 \\t: {Engine}\".format(Engine=res[\"Engine\"]))\n print(\"\\t\\t版本号 \\t: {Version}\".format(Version=res[\"Version\"]))\n print(\"\\t\\t字符集 \\t: {Collation}\".format(Collation=res[\"Collation\"]))\n print(\"\\t\\t创建时间\\t: {Create_time}\".format(Create_time=res[\"Create_time\"]))\n print(\"\\t\\t更新时间\\t: {Update_time}\".format(Update_time=res[\"Update_time\"]))\n print(\"\\t\\t解释说明\\t: {Comment}\".format(Comment=res[\"Comment\"]))\n\n if _with_row_count:\n print(\"\\t\\t【查询总行数的时候sql会运行较慢,请稍等...】\")\n (conn, cur), _, res = fetch_one(conn, cur, \"SELECT COUNT(*) FROM {db}.{table}\".format(db=_db, table=_table))\n print(\"\\t\\t共计{count}行\".format(count=res[0]))\n print()\n\n if _with_index:\n (conn, cur_dict), _, res = fetch_all(conn, cur_dict,\n \"SHOW INDEX FROM {db}.{table}\".format(db=_db, table=_table))\n index_data = pd.DataFrame(list(res), columns=[\"Non_unique\", \"Key_name\", \"Seq_in_index\", \"Column_name\"]) \\\n .sort_values([\"Non_unique\", \"Key_name\", \"Seq_in_index\"], ascending=True) \\\n .groupby([\"Key_name\", \"Non_unique\"]) \\\n .apply(lambda df: \", \".join(df[\"Column_name\"])) \\\n .sort_index(level=\"Non_unique\")\n print(\"\\t索引信息\")\n for (key_name, not_unique), field in index_data.iteritems():\n if key_name.lower() == \"primary\":\n print(\"\\t\\t主键: {field}\".format(field=field))\n else:\n if not_unique == 0:\n print(\"\\t\\t唯一索引: {field}\".format(field=field))\n else:\n print(\"\\t\\t普通索引: {field}\".format(field=field))\n print()\n\n print(\"\\t字段信息\")\n sql = \"\"\"\n SELECT\n column_name, column_type, column_default, is_nullable, column_comment\n FROM\n information_schema. COLUMNS\n WHERE\n table_schema = '{db}'\n AND table_name = '{table}'\n ORDER BY ordinal_position ASC\n \"\"\"\n (conn, cur), _, res = fetch_all(conn, cur, sql.format(db=_db, table=_table))\n field_data = pd.DataFrame(list(res), columns=[\"字段名\", \"类型\", \"默认值\", \"可否为空\", \"描述\"])\n if _with_min_max:\n print(\"\\t\\t【查询最大值、最小值的时候sql会运行较慢,请稍等...】\")\n field_data.set_index(['字段名'], inplace=True)\n min_max_list = []\n for column_name in field_data.index:\n min_max_list.append(\"MIN({column_name}), MAX({column_name})\".format(column_name=column_name))\n sql = \"SELECT {min_max_str} FROM {db}.{table}\".format(min_max_str=\", \".join(min_max_list), db=_db, table=_table)\n (conn, cur), _, res = fetch_one(conn, cur, sql)\n for index, column_name in enumerate(field_data.index):\n field_data.loc[column_name, \"最小值\"] = res[2 * index]\n field_data.loc[column_name, \"最大值\"] = res[2 * index + 1]\n field_data.reset_index(inplace=True)\n\n # 数据格式整理\n for index, row in field_data.iterrows():\n row[\"描述\"] = simplify_blank(row[\"描述\"])\n if row[\"可否为空\"].lower() == \"yes\":\n row[\"可否为空\"] = \"Y\"\n else:\n row[\"可否为空\"] = \"N\"\n if \"int\" in row[\"类型\"].lower():\n if \"最小值\" in row:\n row[\"最小值\"] = int(row[\"最小值\"])\n if \"最大值\" in row:\n row[\"最大值\"] = int(row[\"最大值\"])\n if \"varchar\" in row[\"类型\"] or \"date\" in row[\"类型\"]:\n if \"最小值\" in row:\n row[\"最小值\"] = \"'\" + str(row[\"最小值\"]) + \"'\"\n if \"最大值\" in row:\n row[\"最大值\"] = \"'\" + str(row[\"最大值\"]) + \"'\"\n if \"默认值\" in row:\n if row[\"默认值\"] is not None:\n row[\"默认值\"] = \"'\" + str(row[\"默认值\"]) + \"'\"\n if row[\"默认值\"] is None:\n row[\"默认值\"] = \"null\"\n\n # 打印输出,将每一列用该列的最大字符串的长度填充\n max_length_dict = dict()\n for column, series in field_data.items():\n max_length_dict[column] = get_max_str_length_from_list(series)\n print_str_list = [\"字段名\", \"类型\", \"默认值\", \"可否为空\", \"描述\"]\n if _with_min_max:\n print_str_list = [\"字段名\", \"类型\", \"默认值\", \"可否为空\", \"最小值\", \"最大值\", \"描述\"]\n if _only_description:\n print_str_list = [\"字段名\", \"描述\"]\n for index in field_data.index:\n string_list = []\n for print_str in print_str_list:\n assert print_str in max_length_dict, \"指定的输出字段不在查询结果中...\"\n value = str(field_data.loc[index][print_str])\n if print_str == \"描述\":\n string_list.append(print_str + \": \" + value)\n else:\n string_list.append(print_str + \": \" + (\"%+\" + str(max_length_dict[print_str]) + \"s\") % value)\n print(\"\\t\\t\" + \",\\t\".join(string_list))\n print()\n # field_data.reset_index(inplace=True)\n # field_data = field_data[[\"字段名\", \"类型\", \"默认值\", \"可否为空\", \"最小值\", \"最大值\", \"描述\"]]\n # set_pd_option(pd)\n # print(field_data)\n # reset_pd_option(pd)\n close_all((cur, cur_dict), conn)\n _class.db = initial_db\n\n\n# 查询数据库实例、库、表的大小\ndef get_mysql_instance_gb_size(_class, _db=None, _table=None):\n if _table is not None:\n assert _db is not None, \"如果指定表名的话必须指定相应的库名\"\n sql = \"SELECT ROUND(SUM((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 4) FROM information_schema.TABLES\"\n if _db is not None:\n sql += \" WHERE TABLE_SCHEMA = '{db}'\".format(db=_db)\n if _table is not None:\n if is_sequence(_table):\n sql += \" AND TABLE_NAME IN ('\" + \"', '\".join(_table) + \"')\"\n else:\n sql += \" AND TABLE_NAME = '\" + _table + \"'\"\n conn, cur = get_conn_cur_by_class(_class)\n (conn, cur), _, res = fetch_one(conn, cur, sql)\n close_all(cur, conn)\n return res[0] if res else None\n\n\n# 获取当前所有的数据连接类,按照类名排序\ndef get_all_mysql_class():\n globals_copy = globals().copy()\n # pattern = re.compile(r'.*[0-9]{1,6}$')\n connection_info_list = []\n for value in globals_copy.values():\n # 判断是否是类,且类名满足多位数字port结尾\n if isinstance(value, type) and getattr(value, \"__module__\") == __name__ \\\n and hasattrs(value, [\"name\", \"port\", \"user\", \"password\"]):\n connection_info_list.append(value)\n connection_info_list.sort(key=lambda x: x.__name__)\n return connection_info_list\n\n\n# # 获得所有游戏gindex对应的游戏名称,慎用!!!\n# def get_gindex_gname():\n# conn3406, cur3406 = get_conn_cur_by_class(UgcUserOn3406)\n# initial_gname_sql = \"\"\"\n# SELECT gindex, gname\n# FROM dbbh_website.org_game_summary\n# \"\"\"\n# (conn3406, cur3406), _, res = fetch_all(conn3406, cur3406, initial_gname_sql)\n# close_all(cur3406, conn3406)\n# return {gindex: gname for gindex, gname in res}\n\n\ndef __test_get_mysql_collection(_with_fields=False):\n connection_info_list = get_all_mysql_class()\n\n # 遍历数据连接\n if _with_fields:\n fp = open(\"./Fields.txt\", 'w', encoding=\"UTF-8\")\n else:\n fp = open(\"./Tables.txt\", 'w', encoding=\"UTF-8\")\n for connection_info in connection_info_list:\n # 初始化数据连接\n connection_info = connection_info()\n print(connection_info.name)\n conn, cur = get_conn_cur_by_class(connection_info)\n\n # 写文件\n fp.write(connection_info.name + \"\\n\")\n # 获取所有数据库\n (conn, cur), _, res = fetch_all(conn, cur, \"SHOW DATABASES\")\n database_list = [x[0] for x in res]\n database_list = list(set(database_list) - {\"information_schema\", \"mysql\", \"performance_schema\"})\n for datebase in database_list:\n fp.write(\"\\t[\" + connection_info.name + \"]\" + datebase + \"\\n\")\n if _with_fields:\n sql = \"SELECT table_name, column_name, data_type, column_comment FROM information_schema.columns WHERE \" \\\n \"table_schema = '\" + datebase + \"' ORDER BY table_name, ordinal_position\"\n (conn, cur), _, res = fetch_all(conn, cur, sql)\n table_name_set = set()\n for table_name, column_name, data_type, column_comment in res:\n if table_name not in table_name_set:\n table_name_set.add(table_name)\n fp.write(\"\\t\\t[\" + datebase + \"]\" + table_name + \"\\n\")\n fp.write(\"\\t\\t\\t\" + column_name + \"(\" + data_type + \"): \" + column_comment + \"\\n\")\n else:\n sql = \"SELECT DISTINCT table_name FROM information_schema.columns WHERE \" \\\n \"table_schema = '\" + datebase + \"' ORDER BY table_name\"\n (conn, cur), _, res = fetch_all(conn, cur, sql)\n for table_name in res:\n table_name = table_name[0]\n fp.write(\"\\t\\t[\" + connection_info.name + \"][\" + datebase + \"]\" + table_name + \"\\n\")\n\n # 关闭数据连接\n close_all(cur, conn)\n fp.write(\"\\n\")\n\n fp.close()\n\n\ndef __test_pymysql_executemany():\n conn, cur = get_conn_cur_by_class(WorkOrderUser3306)\n values = range(20, 30)\n # executemany只有命中下面的正则表达式才会触发真正的executemany,否则就是单纯的for循环execute\n # 而executemany可以将多个insert语句组装成一个大的、有多个values的insert语句\n # RE_INSERT_VALUES = re.compile(\n # r\"\\s*((?:INSERT|REPLACE)\\s.+\\sVALUES?\\s+)\" +\n # r\"(\\(\\s*(?:%s|%\\(.+\\)s)\\s*(?:,\\s*(?:%s|%\\(.+\\)s)\\s*)*\\))\" +\n # r\"(\\s*(?:ON DUPLICATE.*)?);?\\s*\\Z\",\n # re.IGNORECASE | re.DOTALL)\n cur.executemany(\"INSERT INTO workOrder.test (gindex) values(%s)\", values)\n conn.commit()\n close_all(cur, conn)\n\n\ndef __test_join_big_sql_from_list():\n int_list = range(10)\n str_list = [str(x) for x in int_list]\n str1_list = [\"'\" + str(x) for x in int_list]\n bool_list = [True] * 10\n values = zip(int_list, str_list, bool_list, str1_list)\n for value in join_big_sql_from_list(values, _max_length=80):\n print(value)\n\n\ndef __test_describe_table():\n # describe_table(UgcUser6000, \"analysis_db\", \"user_pay_info\", _with_min_max=True)\n describe_table(UgcUser6000, \"analysis_db\", \"sync_third_pay_order\", _with_min_max=True)\n # describe_table(UgcUser6000, \"analysis_db\", \"user_pay_info\", _only_description=True)\n\n\ndef __test_double_close_conn():\n conn, cur = get_conn_cur_by_class(UgcUser6000)\n close_connections(conn)\n close_connections(conn)\n close_cursors(cur)\n close_cursors(cur)\n\n\ndef __test_get_mysql_instance_gb_size():\n connection_info_list = get_all_mysql_class()\n for connection_info in connection_info_list:\n print(connection_info.name)\n print(get_mysql_instance_gb_size(connection_info))\n print(get_mysql_instance_gb_size(BiUserOffline))\n print(get_mysql_instance_gb_size(BiUserOffline, \"bi_offline\"))\n print(get_mysql_instance_gb_size(BiUserOffline, _db=\"bi_offline\", _table=\"yidun_text_check_new_00\"))\n print(get_mysql_instance_gb_size(BiUserOffline, _db=\"bi_offline\",\n _table=[\"yidun_text_check_new_00\", \"yidun_text_check_new_01\"]))\n\n\n# 根据sql查询结果组装为dict,dict的key必须指定\ndef get_dict_from_fetch_all(_conn, _cur, _sql, _main_key, _with_main_key=False, _try_times=5):\n (_conn, _cur), _, results = fetch_all(_conn, _cur, _sql, _try_times)\n item_list = get_sub_list_from_2d_list(_cur.description, 0)\n if _main_key not in item_list:\n raise ValueError(\n \"预设键'{key}'不在查询字段[{item_list}]中,请核对后重试...\".format(key=_main_key, item_list=\", \".join(item_list)))\n main_index = item_list.index(_main_key)\n result_dict = OrderedDict()\n for result in results:\n main_value = result[main_index]\n if main_value not in result_dict:\n result_dict[main_value] = OrderedDict()\n temp_dict = result_dict[main_value]\n for index, value in enumerate(result):\n if not _with_main_key:\n if index == main_index:\n continue\n temp_dict[item_list[index]] = value\n return (_conn, _cur), result_dict\n\n\n# 去掉一个字符串开头指定的字符,或者说,一个字符串不能以指定的字符开头\ndef delete_str_head(_str, _delete_value=\" \", _case_sensitive=False):\n if is_empty(_str):\n return _str\n if _case_sensitive:\n while _str.startswith(_delete_value):\n _str = _str[len(_delete_value):]\n return _str\n else:\n _delete_value = _delete_value.lower()\n while _str.lower().startswith(_delete_value):\n _str = _str[len(_delete_value):]\n return _str\n\n\n# 删除一个where条件开头的and或者or\ndef delete_where_condition_head(_str):\n if _str is None:\n return _str\n _str = delete_str_head(delete_str_head(delete_str_head(_str, \" \"), \"and \"), \" \")\n _str = delete_str_head(delete_str_head(delete_str_head(_str, \" \"), \"or \"), \" \")\n return _str\n\n\n# mysql添加where条件\ndef add_where_condition(_where, _str):\n if is_empty(_str):\n return _where\n if is_empty(_where):\n return \"WHERE \" + delete_where_condition_head(_str)\n else:\n return _where + \" \" + _str\n\n\nif __name__ == '__main__':\n __test_get_mysql_collection()\n # __test_pymysql_executemany()\n # __test_join_big_sql_from_list()\n # __test_describe_table()\n # __test_double_close_conn()\n # __test_get_mysql_instance_gb_size()\n pass\n","sub_path":"utils_sql.py","file_name":"utils_sql.py","file_ext":"py","file_size_in_byte":35219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"565511748","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom nav_msgs.msg import Odometry\nimport spidev\nimport tf\nimport time\nimport math\nfrom math import sin, cos, pi\nfrom geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3, TransformStamped\n#import geometry_msgs.msg\n\n\nWHEEL_RADIUS = 0.115#meters prev = 0.1016\nROBOT_RADIUS = 0.3#meters prev = 0.2794\n\nDISTANCE_PER_TICK = (2 * 3.14159265 * WHEEL_RADIUS) / (16383 * 30); \n\n\ndef linear_transform(DOMAIN,RANGE,debug=0):\n scale = (RANGE[1]-RANGE[0])/(DOMAIN[1]-DOMAIN[0])\n DOMAIN_SHIFT = DOMAIN[0]+(DOMAIN[1]-DOMAIN[0])/2\n RANGE_SHIFT = RANGE[0]+(RANGE[1]-RANGE[0])/2\n\n function = lambda x:scale*(x - DOMAIN_SHIFT) + RANGE_SHIFT\n if debug != 0:\n print(\"scale: \" + str(scale))\n print(\"RANGE_SHIFT: \" + str(RANGE_SHIFT))\n print(\"DOMAIN_SHIFT: \" + str(DOMAIN_SHIFT))\n return function\n\nclass Encoder:\n def __init__(self):\n self.encoder_pub = rospy.Publisher('odom_frame',Odometry, queue_size=50)\n self.r = rospy.Rate(100)\n \n # Initial SPI\n self.lw_spi = spidev.SpiDev()\n self.lw_spi.open(0,0) \n self.lw_spi.max_speed_hz = 5000\n self.lw_spi.mode = 0b01\n\n self.rw_spi = spidev.SpiDev()\n self.rw_spi.open(0,1) \n self.rw_spi.max_speed_hz = 5000\n self.rw_spi.mode = 0b01\n\n # Convert 14bit values from encoders to degrees for testing\n self.data2degree = linear_transform((0,16383),(0,360))\n\n\n\n self.prev_tick_L = 0\n self.prev_tick_R = 0\n \n self.current_time = rospy.Time.now()\n self.last_time = rospy.Time.now()\n\n\n self.list_of_bytes = [0xFF,0xFF]\n\n # Need to write description of this\n # CHANGE THIS TO TICK VALUES - 14BITS/2 ETC\n # 14 bits = 16383 = 360 degrees\n # 16383/2 = 8920 (rounded up = 180 degrees\n # 0 = 0 degrees\n def angle2tick(self, end, start):\n diff = end - start\n if diff > 8920 and start < end:\n return diff - 16383\n elif diff < -8920 and start > end:\n return diff + 16383\n else:\n return diff\n\n \n # SPI Decoding - Error bit\n def get_error_bit(self, byte):\n error_bit = (~(0b10111111) & byte) >> 6\n # Check if there was an error\n if error_bit == 1: \n return False # Error was present\n else:\n return True # Error not present\n\n # SPI Decoding - Calculate paridty bit for command message\n def get_pard_bit(self, byte):\n pard_bit = (~(0b10111111) & byte) >> 7\n\n SUM = 0\n for i in range(7):\n bit_check = (byte >> i) & 0x00000001\n if bit_check == 1:\n SUM += 1\n\n pard_bit = (~(0b01111111) & byte) >> 7\n if pard_bit == 0 and SUM % 2 == 0:\n return True\n elif pard_bit == 1 and SUM % 2 != 0:\n return True\n else:\n return False\n\n # Gets data from encoders \n def get_data(self, list_of_2bytes):\n if not (self.get_pard_bit(list_of_2bytes[0]) or self.get_error_bit(list_of_2bytes[0])):\n return 0x80\n else:\n data = ~(0b11000000) & list_of_2bytes[0]\n data = (data << 8) + list_of_2bytes[1]\n return data\n\nclass RobotPosition():\n def __init__(self):\n\n # Initial values for odom frame\n self.x = 0.0\n self.y = 0.0\n self.th = 0.0\n self.vx = 0.1\n self.vy = -0.1\n self.vth = 0.1\n\ndef main(encoder, robot):\n # Set up odometry broadcaster \n odom_broadcaster = tf.TransformBroadcaster()\n\n while not rospy.is_shutdown():\n current_time = rospy.Time.now()\n\n encoder.rw_spi.xfer3(encoder.list_of_bytes,2) # try removing \"something_r\"\n raw_data_r = encoder.rw_spi.readbytes(2)\n curr_tick_r = encoder.get_data(raw_data_r) # angle from encoder\n\n encoder.lw_spi.xfer3(encoder.list_of_bytes,2)\n raw_data_l = encoder.lw_spi.readbytes(2)\n curr_tick_l = encoder.get_data(raw_data_l) #angle from encoder\n\n # <<<< I think we need to convert the 14bit values to angles >>>>\n # Calculating the change in encoder tick values\n deltaLeftTicks = -encoder.angle2tick(encoder.prev_tick_L, curr_tick_l)\n deltaRightTicks = encoder.angle2tick(encoder.prev_tick_R, curr_tick_r)\n \n # print(\"deltaLeftTicks: \" + str(deltaLeftTicks))\n # print(\"deltaRightTicks: \" + str(deltaRightTicks))\n\n\n # Calculating the velocity of the wheels based on encoder ticks\n dt = (current_time - encoder.last_time).to_sec()\n vel_wheel_L = (deltaLeftTicks * DISTANCE_PER_TICK) / dt \n vel_wheel_R = (deltaRightTicks * DISTANCE_PER_TICK) / dt\n\n # Calculating the robot's linear and angular velocities from wheel velocities\n robot.vx = ((vel_wheel_R + vel_wheel_L) / 2)\n robot.vy = 0;\n robot.vth = ((vel_wheel_R - vel_wheel_L)/ROBOT_RADIUS)\n \n # compute odometry in a typical way given the velocities of the robot\n # Computing the robot's change in position and angle \n delta_x = (robot.vx * cos(robot.th) - robot.vy * sin(robot.th)) * dt\n delta_y = (robot.vx * sin(robot.th) + robot.vy * cos(robot.th)) * dt\n delta_th = robot.vth * dt\n\n\n # In relation to the global coordinate frame\n robot.x += delta_x\n robot.y += delta_y\n robot.th += delta_th\n# print(\"robot.x: \" + str(robot.x))\n# print(\"robot.y: \" + str(robot.y))\n# print(\"robot.th: \" + str(robot.th))\n\n\n # Since all odometry is 6DOF we'll need a quaternion created from yaw\n # this is different the C++ code (they use createQuaternionMsgfromYaw\n odom_quat = tf.transformations.quaternion_from_euler(0, 0, robot.th)\n\n\n\n # First, we'll publish the transform over tf\n odom_trans = TransformStamped()\n odom_trans.header.stamp = current_time\n odom_trans.header.frame_id = \"odom\"\n odom_trans.child_frame_id = \"base_link\"\n\n\n odom_trans.transform.translation.x = robot.x\n odom_trans.transform.translation.y = robot.y\n odom_trans.transform.translation.z = 0.0\n odom_trans.transform.rotation = odom_quat\n\n # Send the transform\n #odom_broadcaster.sendTransform(odom_trans)\n \n odom_broadcaster.sendTransform(\n (robot.x, robot.y, 0.0),\n odom_quat, #\n current_time, # stamp\n \"base_link\", # child_frame_id\n \"odom\" # frame_id\n )\n\n\n # Next, we'll publish the odometry message over ROS\n odom = Odometry()\n odom.header.stamp = current_time\n odom.header.frame_id = \"odom\"\n\n\n # set the position\n odom.pose.pose.position.x = robot.x\n odom.pose.pose.position.y = robot.y\n odom.pose.pose.position.z = 0.0\n odom.pose.pose.orientation = Quaternion(*odom_quat)\n #odom.pose.pose = Pose(Point(robot.x, robot.y, 0.0), Quaternion(*odom_quat))\n\n\n # set the velocity\n odom.child_frame_id = \"base_link\"\n odom.twist.twist.linear.x = robot.vx\n odom.twist.twist.linear.y = robot.vy\n odom.twist.twist.angular.z = robot.vth\n #odom.twist.twist = Twist(Vector3(robot.vx, robot.vy, 0), Vector3(0, 0, robot.vth))\n\n\n # publish the message\n encoder.encoder_pub.publish(odom)\n \n encoder.prev_tick_L = curr_tick_l\n encoder.prev_tick_R = curr_tick_r\n encoder.last_time = current_time\n encoder.r.sleep()\n\nif __name__ == \"__main__\":\n \n try:\n rospy.init_node('encoders')\n encoder = Encoder()\n robot = RobotPosition()\n main(encoder, robot)\n\n except:\n print(\"Failed to run encoder script\")\n \n\n","sub_path":"mpdr/src/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":7840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"425607357","text":"\"\"\"\nTests for the loans application, we want to tests the models and the rest api responses\n\"\"\"\nfrom django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom loans.models import Business, Loan\nfrom rest_framework.test import APITestCase, APIClient\nfrom django.urls import reverse\nfrom rest_framework import status\n\n#Tests for the DB models\nclass ModelsTests(TestCase):\n def test_creating_user(self):\n user_object = User()\n user_object.name = \"test\"\n user_object.phone_number = \"12345678\"\n user_object.email = \"test@testing.com\"\n user_object.save()\n\n def test_creating_business(self):\n #We need a user object first in order to be able to add the business\n user_object = User()\n user_object.name = \"test\"\n user_object.phone_number = \"12345678\"\n user_object.email = \"test@testing.com\"\n user_object.save()\n\n business_object = Business()\n business_object.business_name = \"Test business\"\n business_object.registered_company_number = \"12345678\"\n business_object.business_sector = \"Food & Drink\"\n business_object.user = user_object\n business_object.address1 = \"Test Address 1\"\n business_object.address2 = \"Test Address 2\"\n business_object.post_code = \"ES1 34GH\"\n business_object.city_name = \"London\"\n business_object.save()\n\n def test_creating_loans(self):\n #We need a user object first in order to be able to add the business\n user_object = User()\n user_object.name = \"test\"\n user_object.phone_number = \"12345678\"\n user_object.email = \"test@testing.com\"\n user_object.save()\n\n #We need a business object in order to to be able to add the loan\n business_object = Business()\n business_object.business_name = \"Test business\"\n business_object.registered_company_number = \"12345678\"\n business_object.business_sector = \"Food & Drink\"\n business_object.user = user_object\n business_object.address1 = \"Test Address 1\"\n business_object.address2 = \"Test Address 2\"\n business_object.post_code = \"ES1 34GH\"\n business_object.city_name = \"London\"\n business_object.save()\n\n #We need a user object first in order to be able to add the business\n loan_object = Loan()\n loan_object.number_of_days = 25\n loan_object.amount = 50000\n loan_object.reason = \"Test Loan\"\n loan_object.user = user_object\n loan_object.business_name = business_object\n loan_object.save()\n\n#Tests for REST API\nclass CreateLoanFlow(APITestCase):\n def setUp(self):\n User.objects.create_user('temp_user', 'temporary@gmail.com', 'temp_user_password')\n\n #Create loan flow, first create business, then a loan\n def test_create_loan_flow(self):\n \"\"\"\n Ensure we can create a new Business object.\n \"\"\"\n self.client.login(username='temp_user', password='temp_user_password')\n url = reverse('business')\n #Defining the business name here to make sure we use the same text in the two places we need it, in the data and in the assertEqual test. \n business_name = 'Test business'\n data = {'business_name': business_name,'registered_company_number': '12345678','business_sector': 'RE','address1': 'Address test line 1','address2': 'Address test line 2','post_code': 'XXX XXX','city_name': 'London'}\n response = self.client.post(url, data, format='json')\n #We are going to make sure that we get an http 201 for a created object, that the Business table has one object and that the name of the object is the same as the one used for the test\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Business.objects.count(), 1)\n self.assertEqual(Business.objects.get().business_name, business_name)\n #We need the id of the insterted object in order to use it to create the loan\n business_id = response.data.get(\"id\")\n \"\"\"\n After creating the business we use it to create a loan\n \"\"\"\n url = reverse('loan')\n #Defining the loan's reason here to make sure we use the same in the two places we need it, in the data and in the assertEqual test. \n loan_reason = 'We are testing the loan creation, we do not really need any money'\n data = {'business_name': 'Test business','amount': '20000','number_of_days': '12','reason': loan_reason,'business_name': business_id}\n response = self.client.post(url, data, format='json')\n #We are going to make sure that we get an http 201 for a created object, that the Loan table has one object and that the reason of the object is the same as the one used for the test\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Loan.objects.count(), 1)\n self.assertEqual(Loan.objects.get().reason, loan_reason)\n\n\n\n","sub_path":"loans/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"28029735","text":"\"\"\"\nIntersection: Given two (singly) linked lists, determine if the two lists intersect. Return the\nintersecting node. Note that the intersection is defned based on reference, not value. That is, if the\nkth node of the frst linked list is the exact same node (by reference) as the jth node of the second\nlinked list, then they are intersecting.\n\n\"\"\"\nfrom tools.LinkedList import LinkedList\ndef intersection(ll_a,ll_b):\n if ll_a.tail is not ll_b.tail:\n return False\n longer=ll_a if len(ll_b) value\n self.move_values = {}\n\n # Random Rate: How often the agent will explore\n self.epsilon = .5\n\n self.moves_taken = 0\n\n # Discount Factor\n self.gamma = .9\n\n # Define what token this agent plays as\n self.token = user_token\n\n self.winning_value = 3\n self.available_value = .1\n self.draw_value = -1\n self.losing_value = -2\n\n # Keep track of last state the agent saw\n self.last_state = None\n self.last_value = 0\n\n\n\n def set_learn_rate(self, rate):\n '''\n Public setter for learn rate\n '''\n self.epsilon = rate\n\n def choose_random(self, board):\n '''\n random choice n board\n '''\n spaces = board.available_spaces()\n return random.choice(spaces)\n\n def set_user(self, user):\n '''\n sets the user token\n '''\n self.token = user\n\n def get_value_of_board(self, board):\n '''\n Get the vale of the move\n '''\n tokenized = board.tokenize()\n if not tokenized in self.move_values:\n self.add_key(board, tokenized)\n return self.move_values[tokenized]\n\n def add_key(self, board, key):\n '''\n check the move status\n '''\n game_status = board.game_status()\n\n if game_status == self.token:\n self.move_values[key] = self.winning_value\n elif game_status == user.available:\n self.move_values[key] = self.available_value\n elif game_status == user.draw:\n self.move_values[key] = self.draw_value\n else:\n self.move_values[key] = self.losing_value\n\n def next_move(self, board):\n '''\n Decide the net move base on reinforcement learning\n '''\n # if self.moves_taken % 200 == 0:\n # self.epsilon *= .9\n\n # Keep track of state before\n self.last_state = board.tokenize()\n self.last_value = self.get_value_of_board(board)\n\n # Uses epsilon to choose if it will explore or not\n if random.random() <= self.epsilon:\n return self.choose_random(board)\n\n # Learning move\n else:\n highest_move = -1\n highest_value_of_move = -100000\n\n available_spaces = board.available_spaces()\n\n original_board = board.tokenize()\n\n\n # Goes through each available space and checks the value\n for i in range(len(available_spaces)):\n board.take_space(self.token, available_spaces[i])\n value = self.get_value_of_board(board)\n\n # If the value is higher than the current highest,\n # set new highest\n if value > highest_value_of_move:\n highest_move = available_spaces[i]\n highest_value_of_move = value\n\n # Return the board to the original\n board.set_board_from_string(original_board)\n\n # Based on the next move, and value, adjust the current value\n if self.last_state is not None:\n self.move_values[self.last_state] += self.gamma * (highest_value_of_move - self.last_value)\n\n self.moves_taken += 1\n return highest_move\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"499308100","text":"import keras \nimport Loader_mnist as ld\nfrom keras.layers import Input , Conv2D , Dropout , BatchNormalization , Dense , MaxPool2D , Flatten\nfrom keras import losses , optimizers , models\nfrom functools import *\nimport numpy as np\nimport yaml\n\npath = r\"data\\mnist\\train.csv\"\nx , y = ld.Loadmnist(path)\ny = np.eye(10)[y] \n\n# model \n\ninput = Input( (28,28,1) )\nconv1 = Conv2D( 64 , (3,3) , padding = \"same\" , activation = \"relu\")\nmaxpool1 = MaxPool2D( (2,2) )\nflat = Flatten() \nh0 = Dense( 128 , activation = \"relu\")\nh1 = Dense(64 , activation = \"relu\" )\noutput = Dense(10 , activation = \"softmax\" )\n\nlayer_squence = [ input , conv1 , maxpool1 , flat , h0 , h1 , output]\nmodel_test = reduce( lambda f,s : s(f) , layer_squence )\n\nmodel_test = models.Model( input , model_test )\nmodel_test.compile( loss = losses.categorical_crossentropy , optimizer = optimizers.Adam() , metrics = ['acc'] )\n\nhist = model_test.fit(x,y, batch_size = 64 , epochs = 1 , validation_split = 0.2 )\n\n\n# model to yaml - this method is for only save model structure\nmodel_yaml = model_test.to_yaml()\nwith open(\"model1.yaml\" , 'w') as f:\n yaml.dump(model_yaml, f, default_flow_style=False)\n\n\n# model to h5 - this method is for save both model structure and weight\nmodel_test.save(\"weight.h5\")\n\nmodel1 = keras.models.model_from_yaml(model_yaml)\n\nmodel1.compile( loss = losses.categorical_crossentropy , optimizer = optimizers.Adam() , metrics = ['acc'])\n\nprint(\"model1 from yaml\")\nhist = model1.fit(x,y, batch_size = 64 , epochs = 1 , validation_split = 0.2 )\n \nprint(\"done\")\n\n\n\n\n\n\n\n\n","sub_path":"Base_Code_TF_Keras/Base_Code_TF_Keras/Keras/Keras_model_save.py","file_name":"Keras_model_save.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"83289767","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/\n\nhttps://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/discuss/104904/Python-Heap-based-solution\n\n\"\"\"\nclass Solution(object):\n def smallestRange(self, nums):\n \"\"\"\n :type nums: List[List[int]]\n :rtype: List[int]\n \"\"\"\n from heapq import heapify, heappop, heappush\n hp = [(row[0], i, 0) for i, row in enumerate(nums)]\n # print(hp)\n heapify(hp)\n left = min(row[0] for row in nums)\n right = max(row[0] for row in nums)\n res = [left, right]\n while hp:\n left, i, j = heappop(hp)\n if right - left < res[1] - res[0]:\n res = [left, right] # check range\n if j + 1 == len(nums[i]):\n return res \n v = nums[i][j+1]\n right = max(right, v)\n heappush(hp, (v, i, j+1)) # As we pop element A[i][j], we'll replace it with A[i][j+1]","sub_path":"Hard/LC632.py","file_name":"LC632.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"408815628","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\ntf.keras.backend.clear_session()\ntf.random.set_seed(100)\nimport time\nfrom tqdm import tqdm\nfrom create_dataset import train_dataset, val_dataset\nfrom configuration import config, source_tokenizer, target_tokenizer\nfrom utilities import log\nfrom model_training_helper import (check_ckpt, eval_step, train_step, batch_run_check, \n save_evaluate_monitor)\n\n# if a checkpoint exists, restore the latest checkpoint.\nck_pt_mgr = check_ckpt(config.checkpoint_path)\ntotal_steps = int(config.epochs * (config.gradient_accumulation_steps))\ntrain_dataset = train_dataset.repeat(total_steps)\n\ntry:\n for (step, (input_ids, target_ids)) in tqdm(enumerate(train_dataset, 1), initial=1):\n if step > 1899567:\n start_time = time.time()\n grad_accum_flag = (True if (step%config.gradient_accumulation_steps) == 0 else False) if config.accumulate_gradients else None\n predictions, bert_f1_score = train_step(\n input_ids, \n target_ids,\n grad_accum_flag\n )\n if (step % config.steps_to_print_training_info) == 0:\n batch_run_check(\n step, \n start_time,\n bert_f1_score\n )\n if (step % config.eval_after_steps) == 0:\n (early_stop,\n draft_attention_weights,\n refine_attention_weights) = save_evaluate_monitor(ck_pt_mgr, val_dataset, \n target_tokenizer, predictions, \n target_ids, step, start_time,\n bert_f1_score\n )\n if early_stop:\n break\n else:\n early_stop = True\n else:\n continue\n if not early_stop:\n _ = save_evaluate_monitor(ck_pt_mgr, val_dataset, \n target_tokenizer, predictions, target_ids, step, start_time)\n log.info(f'Training completed at step {step}')\nexcept KeyboardInterrupt:\n log.info(f' Checkpoint saved due to KeyboardInterrupt at step {step} in {ck_pt_mgr.save()}')\n","sub_path":"scripts/train_temp.py","file_name":"train_temp.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"446857017","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py:light\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.11.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# # k-최근접 이웃 회귀 (knn regression)\n#\n\n# + [markdown] colab_type=\"text\" id=\"i5J2cFzCrDWT\"\n# ## 데이터 준비\n\n# + colab={} colab_type=\"code\" id=\"fL3wuWxD0cH6\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# %matplotlib inline\n\n# + colab={} colab_type=\"code\" id=\"np5j0UTtJNI_\"\n## 농어\n\nperch_length = np.array(\n [8.4, 13.7, 15.0, 16.2, 17.4, 18.0, 18.7, 19.0, 19.6, 20.0, \n 21.0, 21.0, 21.0, 21.3, 22.0, 22.0, 22.0, 22.0, 22.0, 22.5, \n 22.5, 22.7, 23.0, 23.5, 24.0, 24.0, 24.6, 25.0, 25.6, 26.5, \n 27.3, 27.5, 27.5, 27.5, 28.0, 28.7, 30.0, 32.8, 34.5, 35.0, \n 36.5, 36.0, 37.0, 37.0, 39.0, 39.0, 39.0, 40.0, 40.0, 40.0, \n 40.0, 42.0, 43.0, 43.0, 43.5, 44.0]\n )\nperch_weight = np.array(\n [5.9, 32.0, 40.0, 51.5, 70.0, 100.0, 78.0, 80.0, 85.0, 85.0, \n 110.0, 115.0, 125.0, 130.0, 120.0, 120.0, 130.0, 135.0, 110.0, \n 130.0, 150.0, 145.0, 150.0, 170.0, 225.0, 145.0, 188.0, 180.0, \n 197.0, 218.0, 300.0, 260.0, 265.0, 250.0, 250.0, 300.0, 320.0, \n 514.0, 556.0, 840.0, 685.0, 700.0, 700.0, 690.0, 900.0, 650.0, \n 820.0, 850.0, 900.0, 1015.0, 820.0, 1100.0, 1000.0, 1100.0, \n 1000.0, 1000.0]\n )\n\ntype(perch_length)\nperch_length.shape\n# -\n\n# ## 산점도 그리기 (Scatter plot )\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} colab_type=\"code\" executionInfo={\"elapsed\": 1097, \"status\": \"ok\", \"timestamp\": 1587904061347, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"gE78Nuog4Eg4\" outputId=\"e2862f05-14c9-4445-b711-1326aca5c020\"\n# scatter plot\n\nplt.scatter(perch_length, perch_weight)\nplt.xlabel('length')\nplt.ylabel('weight')\nplt.show()\n# -\n\n# ## 훈련 자료와 테스트 자료로 분할\n\n# + colab={} colab_type=\"code\" id=\"dqSDbM-K4pkB\"\nfrom sklearn.model_selection import train_test_split\n\ntrain_input_0, test_input_0, train_target_0, test_target_0 = train_test_split(\n perch_length, perch_weight, random_state=42)\n\nprint('훈련 feature 자료의 배열 = {0},테스트 feature 자료의 배열 = {1},'.format(train_input_0.shape, test_input_0.shape))\n# print(train_input.shape, test_input.sha\n\n\n# -\n\n# ### sklearn 형식에 맞게 2차원 배열로 변환\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} colab_type=\"code\" executionInfo={\"elapsed\": 1666, \"status\": \"ok\", \"timestamp\": 1587904061928, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"Og1eucsRwzIs\" outputId=\"fbfbad2f-99ed-43f7-aedb-d0cf67410c96\"\ntrain_input = train_input_0.reshape(-1, 1)\ntest_input = test_input_0.reshape(-1, 1)\n\nprint(train_input.shape)\nprint(test_input.shape)\n\n# + colab={} colab_type=\"code\" id=\"2z-LC4zrxzWL\"\n# 아래 코드의 주석을 제거하고 실행하면 에러가 발생합니다\n\n\n# + [markdown] colab_type=\"text\" id=\"NtmNJ7OqrKy_\"\n# ### knn regression 클래스 import \n\n# + colab={} colab_type=\"code\" id=\"BcPh-Da44lhx\"\nfrom sklearn.neighbors import KNeighborsRegressor\n\n# knn regression class 만들기\nknr = KNeighborsRegressor()\n\n# k-최근접 이웃 회귀 모델을 훈련합니다\nknr.fit(train_input, train_target_0)\n\n\n# -\n\n# ### 결정 계수 ($ R^2$)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} colab_type=\"code\" executionInfo={\"elapsed\": 1644, \"status\": \"ok\", \"timestamp\": 1587904061931, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"yEv88u6LIokr\" outputId=\"1ff7d16b-0231-45ee-e9c8-86c739f2b38c\"\n# Return the coefficient of determination :math:`R^2` of the prediction.\n\nknr.score(test_input, test_target_0)\n# -\n\n# ### 평가모델 함수 import\n\n# + colab={} colab_type=\"code\" id=\"R8Uju0xGLX3s\"\nfrom sklearn.metrics import mean_absolute_error\n\n# 테스트 세트에 대한 예측을 만듭니다\ntest_prediction = knr.predict(test_input)\n\n# 테스트 세트에 대한 평균 절댓값 오차를 계산합니다\n# mean_absolute_error(y_true, y_pred)\n\nmae = mean_absolute_error(test_target_0, test_prediction)\nprint(mae)\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} colab_type=\"code\" executionInfo={\"elapsed\": 1637, \"status\": \"ok\", \"timestamp\": 1587904061931, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"QKEf3y-5KVQx\" outputId=\"c083b9d6-6836-4980-fcb7-0723e0cbcf86\"\n## scikit learn\n## https://scikit-learn.org/stable/modules/model_evaluation.html\n\nfrom sklearn.metrics import mean_squared_error\n\n# 테스트 세트에 대한 예측을 만듭니다\ntest_prediction = knr.predict(test_input)\n\n# 테스트 세트에 대한 평균 절댓값 오차를 계산합니다\n# mean_absolute_error(y_true, y_pred)\n\nmse = mean_squared_error(test_target_0, test_prediction)\nprint(mse)\n\n# + [markdown] colab_type=\"text\" id=\"pLW8kdDv5asl\"\n# ## 과대적합 vs 과소적합\n# * Overfitting: 훈련 date에서는 성적이 좋은데 테스트 data에서 성적이 나쁜 경우 \n# * Underfitting: 훈련 date 보다 테스트 data의 성적이 높은 경우 또는 둘 다 낮은 경우\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} colab_type=\"code\" executionInfo={\"elapsed\": 1634, \"status\": \"ok\", \"timestamp\": 1587904061932, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"ZoXIfmiAJaNw\" outputId=\"99289bfd-0735-4f96-874b-e52dda1725c4\"\nprint('훈련자료의 `R^2` = ', knr.score(train_input, train_target_0))\nprint('테스트자료의 `R^2` = ', knr.score(test_input, test_target_0))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} colab_type=\"code\" executionInfo={\"elapsed\": 1628, \"status\": \"ok\", \"timestamp\": 1587904061932, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"Jhu9abILLHjq\" outputId=\"7fa6a8cf-1137-4ec6-e3df-14acfcb6be4d\"\n# 이웃의 갯수를 3으로 설정합니다\nknr.n_neighbors = 3\n\n# 모델을 다시 훈련합니다\n\nknr.fit(train_input, train_target_0)\n\nprint('훈련자료의 `R^2` = ', knr.score(train_input, train_target_0))\nprint('테스트자료의 `R^2` = ', knr.score(test_input, test_target_0))\n\n# +\nr2_train = np.zeros(20)\nr2_test = np.zeros(20)\nneighbors_n = np.zeros(20)\nfor n in range(1, 21):\n knr.n_neighbors = n\n knr.fit(train_input, train_target_0)\n r2_train[n - 1] = knr.score(train_input, train_target_0)\n r2_test[n - 1] = knr.score(test_input, test_target_0)\n neighbors_n[n - 1] = n\n \nprint(r2_train)\nprint(r2_test)\nprint(neighbors_n)\n\n# -\n\nplt.scatter(neighbors_n, r2_train, label = 'train')\nplt.scatter(neighbors_n, r2_test, c=\"r\", label = 'test')\nplt.xlabel('neighbors number')\nplt.ylabel('R^2')\nplt.legend()\nplt.show()\n\n# + [markdown] colab_type=\"text\" id=\"z-oQeMvC2NnY\"\n# ## 확인문제\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 851} colab_type=\"code\" executionInfo={\"elapsed\": 2364, \"status\": \"ok\", \"timestamp\": 1587904062678, \"user\": {\"displayName\": \"Haesun Park\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhsWlS7sKQL-9fIkg3FmxpTMz_u-KDSs8y__P1ngQ=s64\", \"userId\": \"14935388527648823821\"}, \"user_tz\": -540} id=\"ICPoeo9c2RLG\" outputId=\"2f7e7afc-3d3b-46fd-d8ee-83b3f16fbc55\"\n# k-최근접 이웃 회귀 객체를 만듭니다\nknr = KNeighborsRegressor()\n# 5에서 45까지 x 좌표를 만듭니다\nx = np.arange(5, 45).reshape(-1, 1)\n\n# n = 1, 5, 10일 때 예측 결과를 그래프로 그립니다.\nfor n in [1, 5, 10]:\n # 모델 훈련\n knr.n_neighbors = n\n knr.fit(train_input, train_target)\n # 지정한 범위 x에 대한 예측 구하기 \n prediction = knr.predict(x)\n # 훈련 세트와 예측 결과 그래프 그리기\n plt.scatter(train_input, train_target)\n plt.plot(x, prediction)\n plt.title('n_neighbors = {}'.format(n)) \n plt.xlabel('length')\n plt.ylabel('weight')\n plt.show()\n","sub_path":"ML_DL/nbk_knn_regression.py","file_name":"nbk_knn_regression.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"513993712","text":"from division_data import *\nfrom climdiv_data import *\nfrom atmos_ocean_data import *\nfrom simpleNIPA import *\nfrom hindcast import *\nfrom smapFuncts import valueMap, sstMap\nimport os\nfrom matplotlib import pyplot as plt\nbase_fp = '/Users/bz/code/nipa/working/results/'\ndef seasonal_setup(season = 'DJF', phase = 'allyears', n = 30):\n n_yrs = 118\n startyr = 1895\n endyr = startyr + n_yrs - 1\n n_mon_sst = 4\n n_mon_mei = 4\n mei_lag = 4\n sst_lag = 4\n slp_lag = 2\n n_mon_slp = 2\n kwgroups = create_kwgroups( climdiv_months = [3, 4, 5, 6], \\\n sst_lag = sst_lag, n_mon_sst = n_mon_sst, \\\n mei_lag = mei_lag, n_mon_mei = n_mon_mei, \\\n slp_lag = slp_lag, n_mon_slp = n_mon_slp, \\\n climdiv_startyr = startyr, n_yrs = n_yrs, \\\n )\n\n\n alldivDF, sst, mei, phaseind, regionalDF, stateDF = get_data(kwgroups)\n phaseind = gen_phase_index(mei, n_yrs = n, phase = phase)\n slp = load_slp(newFormat = True, **kwgroups['slp'])\n return alldivDF, sst, mei, phaseind, slp\n\ndef lcrb_djf(phase = 'elnino'):\n from pandas import Series\n alldivDF, sst, mei, phaseind, slp = seasonal_setup('DJF', phase, n = 30)\n index = alldivDF['Texas-06'].index\n fp = '/Users/bz/Desktop/LCRB_DJF.tsv'\n clim_data = Series(data = np.loadtxt(fp), index = index)\n nipa = NIPAphase(clim_data, sst, mei, phaseind)\n nipa.bootcorr(ntim = 1000, corrconf = 0.90, bootconf = 0.80)\n sstMap(nipa); plt.show()\n return\n\ndef lcrb_mam(phase = 'elnino'):\n from pandas import Series\n alldivDF, sst, mei, phaseind, slp = seasonal_setup('MAM', phase, n = 20)\n index = alldivDF['Texas-06'].index\n fp = '/Users/bz/Desktop/LCRB_MAMJ.tsv'\n clim_data = Series(data = np.loadtxt(fp), index = index)\n nipa = NIPAphase(clim_data, sst, mei, phaseind)\n nipa.bootcorr(ntim = 1000, corrconf = 0.95, bootconf = 0.90)\n sstMap(nipa); plt.show()\n return nipa\n\nif __name__ == '__main__':\n #lcrb_djf(phase = 'allyears')\n nipa = lcrb_mam(phase = 'lanina')\n","sub_path":"working/new_lcrb.py","file_name":"new_lcrb.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"585248015","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\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/mediagoblin/app.py\n# Compiled at: 2016-03-29 15:18:42\n# Size of source mod 2**32: 13232 bytes\nimport os, logging\nfrom contextlib import contextmanager\nfrom mediagoblin.routing import get_url_map\nfrom mediagoblin.tools.routing import endpoint_to_controller\nfrom werkzeug.wrappers import Request\nfrom werkzeug.exceptions import HTTPException\nfrom werkzeug.routing import RequestRedirect\nfrom werkzeug.wsgi import SharedDataMiddleware\nfrom mediagoblin import meddleware, __version__\nfrom mediagoblin.db.util import check_db_up_to_date\nfrom mediagoblin.tools import common, session, translate, template\nfrom mediagoblin.tools.response import render_http_exception\nfrom mediagoblin.tools.theme import register_themes\nfrom mediagoblin.tools import request as mg_request\nfrom mediagoblin.media_types.tools import media_type_warning\nfrom mediagoblin.mg_globals import setup_globals\nfrom mediagoblin.init.celery import setup_celery_from_config\nfrom mediagoblin.init.plugins import setup_plugins\nfrom mediagoblin.init import get_jinja_loader, get_staticdirector, setup_global_and_app_config, setup_locales, setup_workbench, setup_database, setup_storage\nfrom mediagoblin.tools.pluginapi import PluginManager, hook_transform\nfrom mediagoblin.tools.crypto import setup_crypto\nfrom mediagoblin.auth.tools import check_auth_enabled, no_auth_logout\nfrom mediagoblin.tools.transition import DISABLE_GLOBALS\n_log = logging.getLogger(__name__)\n\nclass Context(object):\n __doc__ = '\\n MediaGoblin context object.\\n\\n If a web request is being used, a Flask Request object is used\\n instead, otherwise (celery tasks, etc), attach things to this\\n object.\\n\\n Usually appears as \"ctx\" in utilities as first argument.\\n '\n\n\nclass MediaGoblinApp(object):\n __doc__ = '\\n WSGI application of MediaGoblin\\n\\n ... this is the heart of the program!\\n '\n\n def __init__(self, config_path, setup_celery=True):\n \"\"\"\n Initialize the application based on a configuration file.\n\n Arguments:\n - config_path: path to the configuration file we're opening.\n - setup_celery: whether or not to setup celery during init.\n (Note: setting 'celery_setup_elsewhere' also disables\n setting up celery.)\n \"\"\"\n _log.info('GNU MediaGoblin %s main server starting', __version__)\n _log.debug('Using config file %s', config_path)\n self.global_config, self.app_config = setup_global_and_app_config(config_path)\n media_type_warning()\n setup_crypto(self.app_config)\n self.session_manager = session.SessionManager()\n setup_locales()\n _log.info('Setting up plugins.')\n setup_plugins()\n if DISABLE_GLOBALS:\n self.db_manager = setup_database(self)\n else:\n self.db = setup_database(self)\n self.theme_registry, self.current_theme = register_themes(self.app_config)\n self.template_loader = get_jinja_loader(self.app_config.get('local_templates'), self.current_theme, PluginManager().get_template_paths())\n self.auth = check_auth_enabled()\n if not self.auth:\n self.app_config['allow_comments'] = False\n self.public_store, self.queue_store = setup_storage()\n self.url_map = get_url_map()\n self.staticdirector = get_staticdirector(self.app_config)\n if setup_celery:\n if not self.app_config.get('celery_setup_elsewhere'):\n if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':\n setup_celery_from_config(self.app_config, self.global_config, force_celery_always_eager=True)\n else:\n setup_celery_from_config(self.app_config, self.global_config)\n if not DISABLE_GLOBALS:\n setup_globals(app=self)\n self.workbench_manager = setup_workbench()\n self.meddleware = [common.import_component(m)(self) for m in meddleware.ENABLED_MEDDLEWARE]\n\n @contextmanager\n def gen_context(self, ctx=None, **kwargs):\n \"\"\"\n Attach contextual information to request, or generate a context object\n\n This avoids global variables; various utilities and contextual\n information (current translation, etc) are attached to this\n object.\n \"\"\"\n if DISABLE_GLOBALS:\n with self.db_manager.session_scope() as (db):\n yield self._gen_context(db, ctx)\n else:\n yield self._gen_context(self.db, ctx)\n\n def _gen_context(self, db, ctx, **kwargs):\n if ctx is None:\n ctx = Context()\n ctx.app = self\n ctx.db = db\n ctx.staticdirect = self.staticdirector\n if isinstance(ctx, Request):\n ctx = self._request_only_gen_context(ctx)\n return ctx\n\n def _request_only_gen_context(self, request):\n \"\"\"\n Requests get some extra stuff attached to them that's not relevant\n otherwise.\n \"\"\"\n request.session = self.session_manager.load_session_from_cookie(request)\n request.locale = translate.get_locale_from_request(request)\n request.template_env = template.get_jinja_env(self, self.template_loader, request.locale)\n mg_request.setup_user_in_request(request)\n request.map_adapter = self.url_map.bind_to_environ(request.environ)\n\n def build_proxy(endpoint, **kw):\n try:\n qualified = kw.pop('qualified')\n except KeyError:\n qualified = False\n\n return request.map_adapter.build(endpoint, values=dict(**kw), force_external=qualified)\n\n request.urlgen = build_proxy\n return request\n\n def call_backend(self, environ, start_response):\n request = Request(environ)\n request.GET = request.args\n request.full_path = environ['SCRIPT_NAME'] + request.path\n if environ.get('HTTPS', '').lower() == 'off':\n environ.pop('HTTPS')\n with self.gen_context(request) as (request):\n return self._finish_call_backend(request, environ, start_response)\n\n def _finish_call_backend(self, request, environ, start_response):\n no_auth_logout(request)\n request.controller_name = None\n try:\n found_rule, url_values = request.map_adapter.match(return_rule=True)\n request.matchdict = url_values\n except RequestRedirect as response:\n return response(environ, start_response)\n except HTTPException as exc:\n return render_http_exception(request, exc, exc.get_description(environ))(environ, start_response)\n\n controller = endpoint_to_controller(found_rule)\n request.controller_name = found_rule.endpoint\n try:\n for m in self.meddleware:\n response = m.process_request(request, controller)\n if response is not None:\n return response(environ, start_response)\n\n except HTTPException as e:\n return render_http_exception(request, e, e.get_description(environ))(environ, start_response)\n\n request = hook_transform('modify_request', request)\n request.start_response = start_response\n try:\n response = controller(request)\n except HTTPException as e:\n response = render_http_exception(request, e, e.get_description(environ))\n\n try:\n for m in self.meddleware[::-1]:\n m.process_response(request, response)\n\n except HTTPException as e:\n response = render_http_exception(request, e, e.get_description(environ))\n\n self.session_manager.save_session_to_cookie(request.session, request, response)\n return response(environ, start_response)\n\n def __call__(self, environ, start_response):\n try:\n return self.call_backend(environ, start_response)\n finally:\n if not DISABLE_GLOBALS:\n self.db.reset_after_request()\n\n\ndef paste_app_factory(global_config, **app_config):\n configs = app_config['config'].split()\n mediagoblin_config = None\n for config in configs:\n if os.path.exists(config) and os.access(config, os.R_OK):\n mediagoblin_config = config\n break\n\n if not mediagoblin_config:\n raise IOError('Usable mediagoblin config not found.')\n del app_config['config']\n mgoblin_app = MediaGoblinApp(mediagoblin_config)\n mgoblin_app.call_backend = SharedDataMiddleware(mgoblin_app.call_backend, exports=app_config)\n mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app)\n return mgoblin_app","sub_path":"pycfiles/mediagoblin-0.9.0-py3.4/app.cpython-34.py","file_name":"app.cpython-34.py","file_ext":"py","file_size_in_byte":8756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"150974805","text":"##########################################################################\n#\n# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n# Copyright (c) 2014, John Haddon. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n#\n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n##########################################################################\n\nimport functools\n\nimport IECore\n\nimport Gaffer\nimport GafferUI\nimport GafferScene\nimport GafferSceneUI\n\n##########################################################################\n# Shading Mode\n##########################################################################\n\nclass _ShadingModePlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\t\tdef __init__( self, plug, **kw ) :\n\n\t\t\tmenuButton = GafferUI.MenuButton(\n\t\t\t\timage = \"shading.png\",\n\t\t\t\tmenu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ) ),\n\t\t\t\thasFrame = False,\n\t\t\t)\n\n\t\t\tGafferUI.PlugValueWidget.__init__( self, menuButton, plug, **kw )\n\n\t\tdef hasLabel( self ) :\n\n\t\t\treturn True\n\n\t\tdef _updateFromPlug( self ) :\n\n\t\t\tpass\n\n\t\tdef __menuDefinition( self ) :\n\n\t\t\tm = IECore.MenuDefinition()\n\n\t\t\tcurrentName = self.getPlug().getValue()\n\t\t\tfor name in [ \"\" ] + GafferSceneUI.SceneView.registeredShadingModes() :\n\t\t\t\tm.append(\n\t\t\t\t\t\"/\" + name if name else \"Default\",\n\t\t\t\t\t{\n\t\t\t\t\t\t\"checkBox\" : name == currentName,\n\t\t\t\t\t\t\"command\" : functools.partial( Gaffer.WeakMethod( self.__setValue ), name if name != currentName else \"\" ),\n\t\t\t\t\t}\n\t\t\t\t)\n\n\t\t\t\tif not name :\n\t\t\t\t\tm.append( \"/DefaultDivider\", { \"divider\" : True } )\n\n\t\t\treturn m\n\n\t\tdef __setValue( self, value, *unused ) :\n\n\t\t\tself.getPlug().setValue( value )\n\nGaffer.Metadata.registerPlugValue( GafferSceneUI.SceneView, \"shadingMode\", \"layout:index\", 2 )\nGaffer.Metadata.registerPlugValue( GafferSceneUI.SceneView, \"shadingMode\", \"divider\", True )\nGafferUI.PlugValueWidget.registerCreator( GafferSceneUI.SceneView, \"shadingMode\", _ShadingModePlugValueWidget )\n\n##########################################################################\n# Expansion\n##########################################################################\n\nclass _ExpansionPlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\tdef __init__( self, plug, **kw ) :\n\n\t\tmenu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ) )\n\t\tmenuButton = GafferUI.MenuButton( menu=menu, image = \"expansion.png\", hasFrame=False )\n\n\t\tGafferUI.PlugValueWidget.__init__( self, menuButton, plug, **kw )\n\n\tdef hasLabel( self ) :\n\n\t\treturn True\n\n\tdef _updateFromPlug( self ) :\n\n\t\tpass\n\n\tdef __menuDefinition( self ) :\n\n\t\texpandAll = bool( self.getPlug().getValue() )\n\n\t\tm = IECore.MenuDefinition()\n\t\tm.append( \"/Expand Selection\", { \"command\" : self.getPlug().node().expandSelection, \"active\" : not expandAll, \"shortCut\" : \"Down\" } )\n\t\tm.append( \"/Expand Selection Fully\", { \"command\" : IECore.curry( self.getPlug().node().expandSelection, depth = 999 ), \"active\" : not expandAll, \"shortCut\" : \"Shift+Down\" } )\n\t\tm.append( \"/Collapse Selection\", { \"command\" : self.getPlug().node().collapseSelection, \"active\" : not expandAll, \"shortCut\" : \"Up\" } )\n\t\tm.append( \"/Expand All Divider\", { \"divider\" : True } )\n\t\tm.append( \"/Expand All\", { \"checkBox\" : expandAll, \"command\" : Gaffer.WeakMethod( self.__toggleMinimumExpansionDepth ) } )\n\n\t\treturn m\n\n\tdef __toggleMinimumExpansionDepth( self, *unused ) :\n\n\t\tself.getPlug().setValue( 0 if self.getPlug().getValue() else 999 )\n\nGafferUI.PlugValueWidget.registerCreator( GafferSceneUI.SceneView, \"minimumExpansionDepth\", _ExpansionPlugValueWidget )\n\nGaffer.Metadata.registerPlugValue( GafferSceneUI.SceneView, \"minimumExpansionDepth\", \"divider\", True )\n\n##########################################################################\n# Lookthrough\n##########################################################################\n\nclass _LookThroughPlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\tdef __init__( self, plug, **kw ) :\n\n\t\trow = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal )\n\n\t\tGafferUI.PlugValueWidget.__init__( self, row, plug, **kw )\n\n\t\twith row :\n\t\t\tself.__enabledWidget = GafferUI.BoolPlugValueWidget( plug[\"enabled\"], displayMode=GafferUI.BoolWidget.DisplayMode.Switch )\n\t\t\tself.__cameraWidget = GafferSceneUI.ScenePathPlugValueWidget(\n\t\t\t\tplug[\"camera\"],\n\t\t\t\tpath = GafferScene.ScenePath(\n\t\t\t\t\tplug.node()[\"in\"],\n\t\t\t\t\tplug.node().getContext(),\n\t\t\t\t\t\"/\",\n\t\t\t\t\tfilter = GafferScene.ScenePath.createStandardFilter( [ \"__cameras\" ], \"Show only cameras\" )\n\t\t\t\t),\n\t\t\t)\n\t\t\tself.__cameraWidget.pathWidget().setFixedCharacterWidth( 13 )\n\t\t\tif hasattr( self.__cameraWidget.pathWidget()._qtWidget(), \"setPlaceholderText\" ) :\n\t\t\t\tself.__cameraWidget.pathWidget()._qtWidget().setPlaceholderText( \"Render Camera\" )\n\n\t\tself._updateFromPlug()\n\n\tdef _updateFromPlug( self ) :\n\n\t\twith self.getContext() :\n\t\t\tself.__cameraWidget.setEnabled( self.getPlug()[\"enabled\"].getValue() )\n\nGafferUI.PlugValueWidget.registerCreator(\n\tGafferSceneUI.SceneView,\n\t\"lookThrough\",\n\t_LookThroughPlugValueWidget,\n)\n\nGaffer.Metadata.registerPlugValue( GafferSceneUI.SceneView, \"lookThrough\", \"label\", \"\" )\n\nGaffer.Metadata.registerPlugDescription( GafferSceneUI.SceneView, \"lookThrough.enabled\",\n\t\"When enabled, locks the view to look through a specific camera in the scene. \"\n\t\"By default, the current render camera is used, but this can be changed using the lookThrough.camera \"\n\t\"setting.\"\n)\n\nGaffer.Metadata.registerPlugDescription( GafferSceneUI.SceneView, \"lookThrough.camera\",\n\t\"Specifies the camera to look through when lookThrough.enabled is on. The default value \"\n\t\"means that the current render camera will be used - the paths to other cameras may be specified \"\n\t\"to choose another camera.\"\n)\n\n##########################################################################\n# Grid\n##########################################################################\n\nclass _GridPlugValueWidget( GafferUI.PlugValueWidget ) :\n\n\tdef __init__( self, plug, **kw ) :\n\n\t\tmenu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ) )\n\t\tmenuButton = GafferUI.MenuButton( menu=menu, image = \"grid.png\", hasFrame=False )\n\n\t\tGafferUI.PlugValueWidget.__init__( self, menuButton, plug, **kw )\n\n\tdef hasLabel( self ) :\n\n\t\treturn True\n\n\tdef _updateFromPlug( self ) :\n\n\t\tpass\n\n\tdef __menuDefinition( self ) :\n\n\t\tm = IECore.MenuDefinition()\n\t\tm.append(\n\t\t\t\"/Show Grid\",\n\t\t\t{\n\t\t\t\t\"checkBox\" : self.getPlug()[\"visible\"].getValue(),\n\t\t\t\t\"command\" : self.getPlug()[\"visible\"].setValue,\n\t\t\t}\n\t\t)\n\n\t\tm.append(\n\t\t\t\"/Show Gnomon\",\n\t\t\t{\n\t\t\t\t\"checkBox\" : self.getPlug().node()[\"gnomon\"][\"visible\"].getValue(),\n\t\t\t\t\"command\" : self.getPlug().node()[\"gnomon\"][\"visible\"].setValue,\n\t\t\t}\n\t\t)\n\n\t\treturn m\n\nGafferUI.PlugValueWidget.registerCreator( GafferSceneUI.SceneView.staticTypeId(), \"grid\", _GridPlugValueWidget )\nGafferUI.PlugValueWidget.registerCreator( GafferSceneUI.SceneView.staticTypeId(), \"gnomon\", None )\n","sub_path":"python/GafferSceneUI/SceneViewToolbar.py","file_name":"SceneViewToolbar.py","file_ext":"py","file_size_in_byte":8344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"312764314","text":"import logging\nimport logging.handlers\nfrom server.core import chat_server\n\n# init logs\nlogger = logging.getLogger('')\nlogger.setLevel(logging.DEBUG)\nfh = logging.handlers.RotatingFileHandler('server.log', maxBytes=1024, backupCount=5)\nfh.setLevel(logging.ERROR)\nsh = logging.StreamHandler()\nsh.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\nsh.setFormatter(formatter)\nlogger.addHandler(fh)\nlogger.addHandler(sh)\n\n# start server\ntry:\n server = chat_server.ChatServer()\n server.start()\nexcept Exception as ex:\n logging.getLogger(__name__).error(ex)\n\n","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"64348382","text":"N, K = map(int, input().split())\nH = 0\n\nC = 0\nwhile True:\n cnt = 0\n temp = N\n while temp > 0:\n if temp % 2 != 0:\n cnt += 1\n temp //= 2 \n\n if cnt <= K:\n break\n N += 1\n C += 1\nprint(C)\n","sub_path":"backjoon/1052 물병.py","file_name":"1052 물병.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"307549031","text":"# import threading, functions\nimport threading\n# from functions import functions \nimport functions\nfrom threading import Thread\ndef solve():\n f1 = Thread(name= 1, target=functions.f[0])\n f2 = Thread(name= 2, target=functions.f[1])\n f3 = Thread(name= 3, target=functions.f[2])\n f4 = Thread(name= 4, target=functions.f[3])\n\n f1.start()\n f2.start()\n f3.start()\n f4.start()\n f1.join()\n f2.join()\n f3.join()\n f4.join()\n\n g1 = Thread(name= 1, target=functions.g[0])\n g2 = Thread(name= 2, target=functions.g[1])\n\n g1.start()\n g2.start()\n g1.join()\n g2.join()\n\n h1 = Thread(name= 1, target=functions.h[0])\n\n h1.start()\n h1.join()","sub_path":"10-Threading/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"507055061","text":"\nfrom django.contrib.auth.models import User\n\nfrom rest_framework import viewsets, status\nfrom rest_framework.response import Response\n\nfrom .serializers import ClienteSerializer\nfrom .models import Cliente\nfrom .forms import ClienteForm\n\n\nclass ClienteViewSet(viewsets.ModelViewSet):\n\n queryset = Cliente.objects.all()\n serializer_class = ClienteSerializer\n\n def get_queryset(self):\n queryset = Cliente.objects.all()\n if 'buscador' in self.request.GET:\n if self.request.GET.get('buscador') != '':\n queryset = Cliente.objects.filter(nombre__icontains=\n self.request.GET.get('buscador'))\n if len(queryset) == 0:\n queryset = Cliente.objects.filter(apellido__icontains=\n self.request.GET.get('buscador'))\n if len(queryset) == 0:\n queryset = Cliente.objects.filter(numero_documento__icontains=\n self.request.GET.get('buscador'))\n return queryset\n \n def create(self, request):\n '''\n {'nombre': 'asd', \n 'apellido': 'asd', \n 'fecha_nacimiento': '2020-08-03', \n 'numero_documento': '1231231', \n 'email': '', \n 'telefono': '123123', \n 'user': 'admin', \n 'password1': 'se242403germanb', \n 'password2': 'se242403germanb'}\n '''\n\n user = User.objects.create_user(\n request.data.get('user'),\n request.data.get('email'),\n request.data.get('password1')\n )\n user.save()\n\n cliente = Cliente.objects.create(\n nombre=request.data.get('nombre'),\n apellido=request.data.get('apellido'),\n fecha_nacimiento=request.data.get('fecha_nacimiento'),\n email=request.data.get('email'),\n numero_documento=request.data.get('numero_documento'),\n telefono=request.data.get('telefono'),\n user=user,\n confirmacion_correo=False\n )\n\n return Response({'response': '200'}, status=status.HTTP_201_CREATED)\n","sub_path":"apps/clientes/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"67773527","text":"\nimport torch\nimport numpy as np\nimport pickle\nimport cv2\nimport os.path as osp\n\nfrom reward_poisoned_drl.contrastive_encoder.contrast import Contrastor\nfrom reward_poisoned_drl.utils import (semantic_crop_pong, show_frame_stacks_with_scores,\n show_frame_feed_with_scores)\n\nFRAME_STACK = 4\nMODEL_PREFIX = \"/home/lowell/reward-poisoned-drl/runs/contrast_enc_4_20\"\nMODEL_FILE = \"contrast_enc_50.pt\"\nDATA_PREFIX = \"/home/lowell/reward-poisoned-drl/data\"\nTARG_OB_FILE = \"targets/targ_mid.pkl\"\nCONT_OB_FILE = \"ep_stack.pkl\"\n\n\ndef viz_contrastive_encoder(args):\n # load contrastive model\n device = torch.device(args.cuda_idx if args.cuda_idx is not None else \"cpu\")\n state_dict = torch.load(osp.join(MODEL_PREFIX, MODEL_FILE))\n contrastor = Contrastor(state_dict, device)\n\n # load target and contrast obs\n with open(osp.join(DATA_PREFIX, TARG_OB_FILE), \"rb\") as f:\n targ = pickle.load(f).transpose(2, 0, 1)\n assert targ.shape == (4, 104, 80)\n\n with open(osp.join(DATA_PREFIX, CONT_OB_FILE), \"rb\") as f:\n contrasts = pickle.load(f)\n assert contrasts.shape[1:] == (104, 80)\n\n # generate query (targeted observation) and keys (frame stacks in episode)\n keys = np.stack([contrasts[t:t+FRAME_STACK, :, :] \n for t in np.arange(len(contrasts)-FRAME_STACK+1)])\n query = np.expand_dims(targ, axis=0)\n\n # perform semantic then center crop to get correct shape\n keys = semantic_crop_pong(keys)\n query = semantic_crop_pong(query)\n\n keys = keys[:, :, 4:80, 4:66]\n query = query[:, :, 4:80, 4:66]\n\n # get contrastive scores between each ob in sequence and target ob\n keys = torch.as_tensor(keys, dtype=torch.float32, device=device)\n query = torch.as_tensor(query, dtype=torch.float32, device=device)\n\n scores = contrastor(query, keys)\n assert scores.shape == (1, len(keys))\n\n # show top K matches\n if args.top_matches is not None:\n num_matches = args.top_matches\n top_matches = torch.flip(torch.argsort(scores.squeeze())[-num_matches:], dims=(0,)).cpu().numpy()\n targ_stack = np.stack([targ] * num_matches, axis=0)\n match_stack = np.stack([contrasts[t:t+FRAME_STACK, :, :] for t in top_matches], axis=0)\n side_by_side = np.concatenate((targ_stack, match_stack), axis=-1) # cat on width\n top_scores = scores.squeeze().cpu().detach().numpy()[top_matches]\n show_frame_stacks_with_scores(side_by_side, top_scores, \"Target vs Match\")\n\n # show feed with scores side by side (targ is rolling for viz purposes only)\n if args.feed_idx is not None:\n fidx = args.feed_idx\n targ_stack = np.stack([targ[i] for i in np.arange(len(contrasts)) % FRAME_STACK], axis=0)\n feed = np.concatenate((targ_stack, contrasts), axis=-1)\n\n feed = feed[:-FRAME_STACK+1] # remove trailing ob frames on tail ob\n show_frame_feed_with_scores(feed[fidx:], scores.squeeze()[fidx:], \"Contrastive Scores\", idx_offset=fidx)\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-g', '--cuda_idx', help='gpu to use', type=int, default=None)\n parser.add_argument('-t', '--top_matches', help='display this number of top matches', type=int, default=None)\n parser.add_argument('-f', '--feed_idx', help='display rolling score feed starting at this idx', type=int, default=None)\n args = parser.parse_args()\n viz_contrastive_encoder(args)\n","sub_path":"tools/viz_contrastive_encoder.py","file_name":"viz_contrastive_encoder.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"70852898","text":"# RUN THIS TO GET THE STATISTICS YOU WANT\n# Testing: run the file. when asked which data you would like to analyze, enter 'test_theses'. \n#\t\t\tThen enter 'English' (the part you tested before)\n\nfrom stats import stats\nfrom filepaths import create_list, create_dir\nimport os\n\n\ndef ask_for_data_directory():\n\n\t\"\"\"\n\tInput:\n\t--\n\t\n\tAsks the user for the name of the directory containing the data\n\tto be analyzed,\n\tprints the absolute path to this directory\n\t\n\tOutput:\n\tabsolute path to the directory containing the data (str)\n\t\n\t\"\"\"\n\n\tdata_name = input('Please enter the name of the folder containing your data ')\n\n\n\tcwd = os.getcwd()\n\tdata_path = os.path.join(cwd, data_name)\n\tprint(data_path)\n\t\n\treturn data_path\n\n\n# Create a list of all MA programs:\ndef list_ma_programs(data_directory):\n\n\t\"\"\"\n\tInput:\n\tabsolut path to the data directory (str)\n\t\n\tMakes a list of all directories in the data directory\n\t(first makes a list of all items in the data directory, \n\tthen only keeps those that are direcotories)\n\t\n\tOutput:\n\tall directories in the data directory (str)\n\t\"\"\"\n\t\n\tcwd = os.getcwd()\n\t\n\tlist_of_programs = os.listdir(data_directory)\n\n\tlist_of_programs_clean = []\n\t# Change cwd to the data directory in order to check if \n\t# items on the list are directories\n\tos.chdir(data_directory)\n\t\n\tfor item in list_of_programs:\n\t\tif os.path.isdir(item)== True:\n\t\t\n\t\t\tlist_of_programs_clean.append(item)\n\t# Change cwd back \t\t\n\tos.chdir(cwd) \n # Turn list of directories into a string so it can be \n\t# used in the following function (containing an input function)\n\tprograms_str = ','.join(list_of_programs_clean)\n\t\n\treturn programs_str\n\n\ndef which_stats(data_directory):\n\n\t\"\"\"\n\tInput:\n\t--\n\t\n\tAsks the user which statistics (of all MA theses, only English theses, \n\tonly Dutch thesis or per MA program) should be performed and assigns the \n\tchoice to the variable 'stats_name'\n\tIf the user chooses 'per program', a list of MA programs is compiled\n\t(using list_ma_programs()) and they are asked again which one they would\n\tlike to analyze. The variable 'stats_name' is assigned to their choice.\n\tIf 'all programs' is chosen, the a list of all ma program directories is created\n\tand assigned to the variable 'stats_name'\n\t\n\tOutput:\n\tthe name of the statistics (str), or list of ma program directories (list)\n\t\"\"\"\n\n\tstats_name = input('''Which theses would you like to analyze? You can select either \"all\", \n\t\"English\", \"Dutch\" or \"per program\" (you can then select the MA program you want to analyze). \n\tIf you choose 'all programs', statsitics will be performed for each of the programs automtically. ''')\n\n\tif stats_name == 'per program':\n\t\tchoice_of_ma_directories = list_ma_programs(data_directory)\n\t\tstats_name = input('Please choose the program you would like to analyze from the programs: '+choice_of_ma_directories+' ')\n\telif stats_name == 'all programs':\n\t\tchoice_of_ma_directories = list_ma_programs(data_directory)\n\t\tstats_name = choice_of_ma_directories.split(',')\t\n\tprint(stats_name)\n\treturn stats_name\n\n\n\n# Generate different lists according to which statsitics should be done:\n\n\n\t\t\ndef get_statistics():\n\n\t\"\"\"\n\tInput:\n\t--\n\t\n\tCombines all functions in order to perform statistics\n\tOnce the statistics for a particular part of the data have\n\tbeen performed, the user is asked if they would like to \n\tcontinue (yes: statistics can be run again, otherwise \n\tthe program stops)\n\tAll results are written to files in the results folder\n\tcalled name of the statsitics_results to be found in the cwd\n\t(the absolut path is printed each time the statistics of a particular\n\tpart of the data are run).\n\tAn overview of the results (average number of tokens, average number of types,\n\taverage number of sentences, type-token ratio and the number of analyzed files\n\tis printed)\n\t\n\tOutput:\n\t---\n\t\n\t\"\"\"\n\n\tdata = ask_for_data_directory()\n\n\t\n\tcontinue_statistics = 'yes'\n\t\n\twhile continue_statistics == 'yes':\n\t\n\t\t\n\t\tname = which_stats(data)\n\t\t\n\t\t# In case the user chose 'all programs', the variable 'name'\n\t\t# is assigned to a list of all MA programs. In this case, the\n\t\t# program loops through the list of programs and calculates the\n\t\t# statistics for each one.\n\t\t\n\t\t\n\t\t# Else, it calculates the statistics for the chosen part of the data\n\t\t# ('name' is assigned to a string).\n\t\tif type(name)== list:\n\t\t\n\t\t\tfor program_name in name:\n\t\n\t\t\t\tresults_folder = create_dir(program_name)\n\t\t\t\tprint(results_folder)\n\t\t\t\tfile_list = create_list(data, program_name, results_folder)\n\t\t\t\tprint(stats(file_list, results_folder))\n\t\telse:\n\t\t\tresults_folder = create_dir(name)\n\t\t\tprint(results_folder)\n\t\t\tfile_list = create_list(data, name, results_folder)\n\t\t\tprint(stats(file_list, results_folder))\n\t\t\n\t\tcontinue_statistics = input('Would you like to continue? ')\n\n\t\t\nget_statistics()\t\t\n\n\n","sub_path":"combined_stats.py","file_name":"combined_stats.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"39713443","text":"# Taken from github.com/sirk390/wxasync/ under the MIT license.\n# Copyright 2018-2020 Christian Bodt \n\nfrom asyncio.events import get_event_loop\nimport asyncio\nimport wx\nimport warnings\nfrom asyncio import CancelledError\nfrom collections import defaultdict\nimport platform\nfrom asyncio.locks import Event\nfrom asyncio.coroutines import iscoroutinefunction\nfrom wx._html import HtmlHelpDialog\nfrom wx._adv import PropertySheetDialog\n\n\nIS_MAC = platform.system() == \"Darwin\"\n\n\nclass WxAsyncApp(wx.App):\n def __init__(self, warn_on_cancel_callback=False, loop=None):\n self.loop = loop or get_event_loop()\n self.BoundObjects = {}\n self.RunningTasks = defaultdict(set)\n self.exiting = False\n self.warn_on_cancel_callback = warn_on_cancel_callback\n super(WxAsyncApp, self).__init__()\n self.SetExitOnFrameDelete(True)\n\n if IS_MAC:\n\n async def MainLoop(self):\n evtloop = wx.GUIEventLoop()\n with wx.EventLoopActivator(evtloop):\n while not self.exiting:\n evtloop.DispatchTimeout(0)\n await asyncio.sleep(0.005)\n self.ProcessPendingEvents()\n evtloop.ProcessIdle()\n\n else:\n\n async def MainLoop(self):\n evtloop = wx.GUIEventLoop()\n with wx.EventLoopActivator(evtloop):\n while not self.exiting:\n while evtloop.Pending():\n evtloop.Dispatch()\n await asyncio.sleep(0)\n await asyncio.sleep(0.005)\n self.ProcessPendingEvents()\n evtloop.ProcessIdle()\n\n def ExitMainLoop(self):\n self.exiting = True\n\n def AsyncBind(\n self,\n event_binder,\n async_callback,\n object,\n source=None,\n id=wx.ID_ANY,\n id2=wx.ID_ANY,\n ):\n \"\"\"Bind a coroutine to a wx Event. Note that when wx object is destroyed, any\n coroutine still running will be cancelled automatically.\"\"\"\n if not iscoroutinefunction(async_callback):\n raise Exception(\"async_callback is not a coroutine function\")\n # We restrict the object to wx.Windows to be able to cancel the coroutines on\n # EVT_WINDOW_DESTROY, even if wx.Bind works with any wx.EvtHandler\n if not isinstance(object, wx.Window):\n raise Exception(\"object must be a wx.Window\")\n if object not in self.BoundObjects:\n self.BoundObjects[object] = defaultdict(list)\n object.Bind(\n wx.EVT_WINDOW_DESTROY,\n lambda event: self.OnDestroy(event, object),\n object,\n )\n self.BoundObjects[object][event_binder.typeId].append(async_callback)\n object.Bind(\n event_binder,\n lambda event: self.OnEvent(event, object, event_binder.typeId),\n source=source,\n id=id,\n id2=id2,\n )\n\n def StartCoroutine(self, coroutine, obj):\n \"\"\"Start and attach a coroutine to a wx object. When object is destroyed, the\n coroutine will be cancelled automatically.\"\"\"\n if asyncio.iscoroutinefunction(coroutine):\n coroutine = coroutine()\n if obj not in self.BoundObjects:\n self.BoundObjects[obj] = defaultdict(list)\n obj.Bind(\n wx.EVT_WINDOW_DESTROY, lambda event: self.OnDestroy(event, obj), obj\n )\n task = self.loop.create_task(coroutine)\n task.add_done_callback(self.OnTaskCompleted)\n task.obj = obj\n self.RunningTasks[obj].add(task)\n\n def OnEvent(self, event, obj, type):\n for asyncallback in self.BoundObjects[obj][type]:\n self.StartCoroutine(asyncallback(event.Clone()), obj)\n\n def OnTaskCompleted(self, task):\n try:\n # This gathers completed callbacks (otherwise asyncio will show a warning)\n # Note: exceptions from callbacks raise here\n # we just let them bubble as there is nothing we can do at this point\n _res = task.result()\n except CancelledError:\n # Cancelled because the window was destroyed, this is normal so ignore it\n pass\n self.RunningTasks[task.obj].remove(task)\n\n def OnDestroy(self, event, obj):\n # Cancel async callbacks\n for task in self.RunningTasks[obj]:\n if not task.done():\n task.cancel()\n if self.warn_on_cancel_callback:\n warnings.warn(\"cancelling callback\" + str(obj) + str(task))\n del self.BoundObjects[obj]\n\n\ndef AsyncBind(event, async_callback, object, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):\n app = wx.App.Get()\n if not isinstance(app, WxAsyncApp):\n raise Exception(\"Create a 'WxAsyncApp' first\")\n app.AsyncBind(event, async_callback, object, source=source, id=id, id2=id2)\n\n\ndef StartCoroutine(coroutine, obj):\n app = wx.App.Get()\n if not isinstance(app, WxAsyncApp):\n raise Exception(\"Create a 'WxAsyncApp' first\")\n app.StartCoroutine(coroutine, obj)\n\n\nasync def AsyncShowModal(dlg):\n loop = asyncio.get_running_loop()\n return await loop.run_in_executor(None, dlg.ShowModal)\n\n\nasync def AsyncShow(dlg):\n closed = Event()\n\n def end_dialog(return_code):\n dlg.SetReturnCode(return_code)\n dlg.Hide()\n closed.set()\n\n async def on_button(event):\n # Same code as in wxwidgets:/src/common/dlgcmn.cpp:OnButton\n # to automatically handle OK, CANCEL, APPLY,... buttons\n id = event.GetId()\n if id == dlg.GetAffirmativeId():\n if dlg.Validate() and dlg.TransferDataFromWindow():\n end_dialog(id)\n elif id == wx.ID_APPLY:\n if dlg.Validate():\n dlg.TransferDataFromWindow()\n elif id == dlg.GetEscapeId() or (\n id == wx.ID_CANCEL and dlg.GetEscapeId() == wx.ID_ANY\n ):\n end_dialog(wx.ID_CANCEL)\n else:\n event.Skip()\n\n async def on_close(event):\n closed.set()\n dlg.Hide()\n\n AsyncBind(wx.EVT_CLOSE, on_close, dlg)\n AsyncBind(wx.EVT_BUTTON, on_button, dlg)\n dlg.Show()\n await closed.wait()\n return dlg.GetReturnCode()\n\n\nasync def AsyncShowDialog(dlg):\n if type(dlg) in [\n HtmlHelpDialog,\n wx.TextEntryDialog,\n wx.MultiChoiceDialog,\n wx.NumberEntryDialog,\n wx.PrintAbortDialog,\n PropertySheetDialog,\n wx.RearrangeDialog,\n wx.SingleChoiceDialog,\n ]:\n return await AsyncShow(dlg)\n return await AsyncShowModal(dlg)\n","sub_path":"aiotone/wxasync.py","file_name":"wxasync.py","file_ext":"py","file_size_in_byte":6665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"475435888","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*- \n\n\n'''\ntracker utils\n'''\n\n\n\nimport json, time, copy, math\nfrom collections import defaultdict\nfrom collections import namedtuple\n\nimport GlobalVar # for GLOBAL_BLOCKED_SLOTS\n\n\n\nSLU_Hypo = namedtuple(\"SLU_Hypo\", [\"act\", \"slot\", \"value\"])\n\ndef what_slot(mact) :\n\t# get context for \"this\" in inform(=donot_care)\n\tthis_slot = None\n\t\n\tfor act in mact :\n\t\tif act[\"act\"] == \"request\" :\n\t\t\tthis_slot = act[\"slots\"][0][1]\n\t\telif act[\"act\"] == \"select\" :\n\t\t\tthis_slot = act[\"slots\"][0][0]\n\t\telif act[\"act\"] == \"expl-conf\" :\n\t\t\tthis_slot = act[\"slots\"][0][0]\n\t\t\t\n\treturn this_slot\n\ndef pause() :\n\traw_input('press enter to continue ...')\n\ndef rule_canthelp(act,blocked_single,blocked_joint) :\n\tsv = act[\"slots\"]\n\tif len(sv) == 1 :\n\t\ts = sv[0][0]\n\t\tv = sv[0][1]\n\t\tif not (s,v) in blocked_single :\n\t\t\tblocked_single.append((s,v))\n\telse :\n\t\tc = {}\n\t\tfor t in sv :\n\t\t\ts = t[0]\n\t\t\tv = t[1]\n\t\t\tc[s] = v\n\t\tif not c in blocked_joint :\n\t\t\tblocked_joint.append(c)\n\ndef rule_canthelp_missing_slot_value(act,goals,requested_slots) :\n\tsv = act[\"slots\"]\n\tif len(sv) != 2 : return\n\tname = ''\n\tslot = ''\n\tfor t in sv :\n\t\tif t[0] == 'name' :\n\t\t\tname = t[1]\n\t\telif t[0] == 'slot' :\n\t\t\tslot = t[1]\n\tif 'name' in goals.keys() and name in goals[\"name\"].keys() :\n\t\tif slot in requested_slots.keys() :\n\t\t\trequested_slots[slot] *= clip(1.0-goals[\"name\"][name])\n\ndef remove_informed_slots(mact,requested_slots) :\n\t# clear requested-slots that have been informed\n\tfor act in mact :\n\t\tif act[\"act\"] == \"inform\" :\n\t\t\tfor slot,value in act[\"slots\"]:\n\t\t\t\tif slot in requested_slots.keys() :\n\t\t\t\t\trequested_slots[slot] = 0.0\n\ndef Uacts(user_acts_hyps,mact) :\n\t# return merged slu-hyps, replacing \"this\" with the correct slot\n\tthis_slot = None\n\tfor act in mact :\n\t\tif act[\"act\"] == \"request\" :\n\t\t\tthis_slot = act[\"slots\"][0][1]\n\tthis_output = []\n\tfor slu_hyp in user_acts_hyps :\n\t\tscore = slu_hyp['score']\n\t\tthis_slu_hyp = slu_hyp['slu-hyp']\n\t\tthese_hyps = []\n\t\tfor hyp in this_slu_hyp :\n\t\t\tfor i in range(len(hyp[\"slots\"])) :\n\t\t\t\tslot,value = hyp[\"slots\"][i]\n\t\t\t\tif slot == \"this\" :\n\t\t\t\t\thyp[\"slots\"][i][0] = this_slot\n\t\t\t\telif slot == None and value == \"donot_care\" :\n\t\t\t\t\thyp[\"slots\"][i][0] = what_slot(mact)\n\t\t\tthese_hyps.append(hyp)\n\t\tthis_output.append((score, these_hyps))\n\tthis_output.sort(key=lambda x:x[0], reverse=True)\n\treturn this_output\n\ndef correct_score(slu_hyps,mact,gamma = 0.1):\n\t'''\n\tslu_hyps 中 如果没有响应 mact request 的 slot ,则概率 * gamma\n\t'''\n\tif slu_hyps == []:\n\t\treturn []\n\n\trequested_slots = []\n\tfor act in mact:\n\t\tif act['act'] == 'request':\n\t\t\tfor slot,value in act['slots']:\n\t\t\t\tif value not in requested_slots:\n\t\t\t\t\trequested_slots.append(value)\n\n\told_sum_prob = sum([score for (score,_) in slu_hyps])\n\tif old_sum_prob > 1:\n\t\told_sum_prob = 1\n\tscore_vec = []\n\thyps_vec = []\n\tfor (score, these_hyps) in slu_hyps:\n\t\tmentioned_flag = False\n\t\tfor hyp in these_hyps:\n\t\t\tfor i in range(len(hyp[\"slots\"])) :\n\t\t\t\tslot,value = hyp[\"slots\"][i]\n\t\t\t\tif slot in requested_slots:\n\t\t\t\t\tmentioned_flag = True\n\t\t\t\t\tbreak\n\t\thyps_vec.append(these_hyps)\n\t\tif not mentioned_flag:\n\t\t\tscore_vec.append(score * gamma)\n\t\telse:\n\t\t\tscore_vec.append(score)\n\t\n\tnew_sum_prob = sum(score_vec)\n\tfactor = old_sum_prob*1.0/new_sum_prob\n\tscore_vec = [score * factor for score in score_vec]\n\tnew_slu_hyps = zip(score_vec,hyps_vec)\n\tnew_slu_hyps.sort(key=lambda x:x[0], reverse=True)\n\treturn new_slu_hyps\n\ndef is_informable(slot) :\n\t# global GLOBAL_BLOCKED_SLOTS\n\tif slot in GlobalVar._GLOBAL_BLOCKED_SLOTS:\n\t\treturn False\n\telse:\n\t\treturn True\n\ndef get_slot_value(dact) :\n\ta = dact[\"act\"]\n\ts = None;\n\tv = None;\n\tif dact[\"slots\"] :\n\t\tif len(dact[\"slots\"][0]) >= 1 :\n\t\t\ts = dact[\"slots\"][0][0]\n\t\tif len(dact[\"slots\"][0]) == 2 :\n\t\t\tv = dact[\"slots\"][0][1]\n\treturn a,s,v\n\ndef remove_dup(mylist) :\n\tnewlist = []\n\tfor elm in mylist :\n\t\tif not elm in newlist :\n\t\t\tnewlist.append(elm)\n\treturn newlist\n\ndef rule_requested_slot(marg_hyps, requested_slots) :\n\t# rule for 'request' user act, similar to 'inform'\n\tfor hyp, score in marg_hyps.items() :\n\t\tif hyp.act != 'request' : continue\n\t\tif hyp.value not in requested_slots.keys() :\n\t\t\trequested_slots[hyp.value] = score\n\t\telse :\n\t\t\trequested_slots[hyp.value] = clip(1.0-(1.0-requested_slots[hyp.value])*(1.0-score))\n\ndef betafit(stats) :\n\t# naive maximum likelihood approximation of beta distribution parameters\n\t# though very rough and inaccurate\n\tGx = 1.0\n\tG1_x = 1.0\n\tN = len(stats)\n\tfor x in stats :\n\t\tif x >= 1.0 : x = 0.999999\n\t\tGx *= x**(1.0/N)\n\t\tG1_x = (1-x)**(1.0/N)\n\t\t\n\tif is_zero(1.0-Gx-G1_x) : #division by zero\n\t\treturn 1.0, 1.0\n\t\n\ta = 0.5 + Gx/(2.0*(1.0-Gx-G1_x))\n\tb = 0.5 + G1_x/(2.0*(1.0-Gx-G1_x))\n\t\n\treturn a,b\n\ndef adjust_noise(slu_hyps, stats) :\n\tfor i in range(0,len(slu_hyps)) :\n\t\tif i >= len(slu_hyps) : break\n\t\tscore,uact = slu_hyps[i]\n\t\tif not uact :\n\t\t\tdel slu_hyps[i]\n\t\t\n\tf = sum([score for score,_ in slu_hyps])\n\t\n\tm = 1.0\n\t\n\tif slu_hyps or stats :\n\t\tstats.append(f)\n\tif stats : \n\t\ta,b = betafit(stats)\n\t\tm = a/(a+b)\n\t\n\tslu_hyps = [(score/m,hyp) for score,hyp in slu_hyps]\n\t\n\tf = sum([score for score,_ in slu_hyps])\n\tif f > 1.0 :\n\t\tslu_hyps = [(score/f,hyp) for score,hyp in slu_hyps]\n\t\n\treturn slu_hyps\n\ndef clip(x) :\n\tif x > 1:\n\t\treturn 1\n\tif x < 0:\n\t\treturn 0\n\treturn x\n\ndef get_nonzero(x) :\n\tm = []\n\tfor k, p in x.items() :\n\t\tif not is_zero(p) :\n\t\t\tm.append(k)\n\treturn m\n\ndef normalise_joint_hyps(x) :\n\ttotal_p = sum([h[\"score\"] for h in x])\n\tif total_p > 1.0 :\n\t\tx = [{\"slots\":h[\"slots\"], \"score\":h[\"score\"]/total_p} for h in x]\n\treturn x\n\ndef normalise_dict(x) :\n\tx_items = x.items()\n\ttotal_p = sum([p for k,p in x_items])\n\tif total_p > 1.0 :\n\t\tx_items = [(k,p/total_p) for k,p in x_items]\n\treturn dict(x_items)\n\ndef is_zero(x) :\n\tepsilon = 1e-9\n\treturn math.fabs(x) < epsilon\n\n","sub_path":"src/Tracker_Utils.py","file_name":"Tracker_Utils.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"484087303","text":"from django.db import models\nfrom django.utils import timezone\nfrom geoposition import Geoposition\nfrom django.conf import settings\nfrom geoposition.fields import GeopositionField\nfrom checkout.models import Order\n\n# Create your models here.\n\n\nclass SampleStatus(models.Model):\n \"\"\"Sample Status model is automatically generated when an sample is\n ordered, it is updated automatically as the sample gets processesed\"\"\"\n STATUS_CHOICES = ((('Ordered'), ('Ordered')),\n (('Dispatched'), ('Dispatched')),\n (('Submitted'), ('Submitted')),\n (('Received'), ('Received')),\n (('Complete'), ('Complete')))\n\n TEST_CHOICES = ((('SS1'), ('Soil 1 - Basic')),\n (('SS2'), ('Soil 2 - Beef, Sheep & Horses')),)\n\n order = models.ForeignKey(Order,\n null=False)\n sample_ref = models.CharField(max_length=50,\n blank=False)\n status = models.CharField(max_length=50,\n choices=STATUS_CHOICES,\n default='Ordered',)\n testing_required = models.CharField(max_length=50,\n choices=TEST_CHOICES)\n ordered_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='orderedby',\n blank=True,\n null=True)\n ordered_date = models.DateTimeField(blank=True,\n null=True)\n dispatched_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='dispatchedby',\n blank=True,\n null=True)\n dispatched_date = models.DateTimeField(blank=True,\n null=True)\n submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n related_name='submittedby',\n blank=True,\n null=True)\n submit_date = models.DateTimeField(blank=True,\n null=True)\n received_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n limit_choices_to={'is_staff': True},\n on_delete=models.CASCADE,\n related_name='recievedby',\n blank=True,\n null=True)\n received_date = models.DateTimeField(blank=True,\n null=True)\n tested_by = models.ForeignKey(settings.AUTH_USER_MODEL,\n limit_choices_to={'is_staff': True},\n on_delete=models.CASCADE,\n related_name='testedby',\n blank=True,\n null=True)\n tested_date = models.DateTimeField(blank=True,\n null=True)\n\n def __str__(self):\n return \"{0}-{1}-{2}\".format(self.testing_required,\n self.id,\n self.status)\n\n\nclass SampleDetails(models.Model):\n \"\"\"Sample Details model stores the data entered\n by the customer about each sample\"\"\"\n\n SOIL_TYPES = ((('Clay - low plasticity, lean clay'),\n ('Clay - low plasticity, lean clay')),\n (('Clay - high plasticity, fat clay'),\n ('Clay - high plasticity, fat clay')),\n (('Clay - organic'),\n ('Clay - organic')),\n (('Gravel - well-graded, fine to coarse gravel'),\n ('Gravel - well-graded, fine to coarse gravel')),\n (('Gravel - poorly graded'),\n ('Gravel - poorly graded')),\n (('Gravel - silty'),\n ('Gravel - silty')),\n (('Gravel - clayey'),\n ('Gravel - clayey')),\n (('Sand - well-graded, fine to coarse Sand'),\n ('Sand - well-graded, fine to coarse Sand')),\n (('Sand - poorly graded'),\n ('Sand - poorly graded')),\n (('Sand - silty'),\n ('Sand - silty')),\n (('Sand - clayey'),\n ('Sand - clayey')),\n (('Peat'),\n ('Peat')),\n (('Silt - low plasticity, lean silt'),\n ('Silt - low plasticity, lean silt')),\n (('Silt - high plasticity, fat silt'),\n ('Silt - high plasticity, fat silt')),\n (('Silt - organic'),\n ('Silt - organic')))\n\n LAND_USES = ((('Beef'), ('Beef')),\n (('Dairy'), ('Dairy')),\n (('Grassland'), ('Grassland')),\n (('Horticulture'), ('Horticulture')),\n (('Sheep'), ('Sheep')),\n (('Tillage'), ('Tillage')))\n\n sample = models.ForeignKey(SampleStatus,\n null=True)\n\n customer_name = models.CharField(max_length=50,\n blank=False)\n customer_ref_1 = models.CharField(max_length=50,\n blank=True,\n null=True)\n customer_ref_2 = models.CharField(max_length=50,\n blank=True,\n null=True)\n sample_location = GeopositionField()\n sample_address = models.CharField(max_length=250,\n blank=True,\n null=True)\n sample_date = models.DateField(blank=False,\n default=timezone.now)\n soil_type = models.CharField(max_length=50,\n choices=SOIL_TYPES)\n land_use = models.CharField(max_length=50,\n choices=LAND_USES)\n other_comments = models.TextField(max_length=500,\n blank=True)\n\n def __str__(self):\n return \"{0}-{1}-Details\".format(self.sample.testing_required,\n self.sample.id)\n\n\nclass SampleResults(models.Model):\n \"\"\"Sample Results stores the sample test results for each sample\"\"\"\n sample = models.ForeignKey(SampleStatus,\n null=False,\n limit_choices_to={'status': 'Received'},)\n p = models.DecimalField(max_digits=4,\n decimal_places=2,\n null=False)\n k = models.DecimalField(max_digits=4,\n decimal_places=2,\n null=False)\n lr_ph = models.DecimalField(max_digits=4,\n decimal_places=2,\n null=False)\n ph = models.DecimalField(max_digits=4,\n decimal_places=2,\n null=False)\n other_comments = models.TextField(max_length=254,\n blank=True)\n\n def __str__(self):\n return \"{0}-{1}-Results\".format(self.sample.testing_required,\n self.sample.id)\n","sub_path":"samples/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"495938132","text":"import shutil\nimport sys\nimport os\nimport threading\nimport time\n\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nfrom PyQt5.QtCore import pyqtSignal, QThread\nfrom PyQt5.QtWidgets import QMessageBox, QTableWidgetItem, QMainWindow, QDialog, QTableWidget, QHeaderView, \\\n QAbstractItemView, QMenu, QFileDialog\nfrom ui1 import Ui_MainWindow\nfrom ui2 import Ui_Dialog as Tag_Dialog\nfrom ui3 import Ui_Dialog as Batch_Dialog\nimport utils\nfrom xlsx import Export2XLSX\nfrom ocr import OcrProcess\nfrom utils import split_cell_coordinate, make_cell_coordinate\nfrom string import ascii_uppercase\nimport numpy as np\n\nTAG_FILES_PATH = './tags/'\nTAG_FILE_NAME = 'tag_list.txt'\nTAG_FILE = TAG_FILES_PATH + TAG_FILE_NAME\nCONFIG_FILE_PATH = './config.yaml'\nOUTPUT_FILE_PATH = './output/'\n\ncells: list\ncols_count: int\nrows_count: int\n\nfilename_now = ''\n\nverbose = 'v'\n\n\nclass MyWindow(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MyWindow, self).__init__()\n self.work: Export2XLSX\n self.names = []\n self.xlsx_name = ''\n self.image_path = ''\n\n self.setupUi(self)\n self.imageList.setVisible(False)\n\n self.status = 0\n\n if not os.path.exists(OUTPUT_FILE_PATH):\n os.mkdir(OUTPUT_FILE_PATH)\n\n # 自定义函数\n def loadImage(self):\n self.image1.loadImageFromFile()\n img_path = self.image1.img_path\n if img_path != '':\n self.image_path = img_path\n (filename, extension) = os.path.splitext(os.path.basename(img_path))\n global filename_now\n filename_now = filename\n self.xlsx_name = filename + '.xlsx'\n self.work = Export2XLSX(img_path, verbose=verbose, workbook=OUTPUT_FILE_PATH + self.xlsx_name)\n self.startProcess1()\n self.status = 1\n\n def reloadImage(self):\n if self.image_path != '':\n self.work = Export2XLSX(self.image_path, verbose=verbose, workbook=OUTPUT_FILE_PATH + self.xlsx_name)\n self.startProcess1()\n\n def changeImage(self):\n index = self.imageList.currentIndex()\n path = './temp/' + self.names[index]\n self.image2.loadImageFromFile(path)\n\n def startProcess1(self):\n self.work.process()\n\n self.names = utils.get_temp_image_names()\n self.imageList.clear()\n self.imageList.addItems(self.names)\n self.imageList.setVisible(True)\n self.imageList.setCurrentIndex(7)\n\n def editConfig(self):\n os.startfile(os.path.abspath(CONFIG_FILE_PATH))\n self.reloadImage()\n\n def startProcess2(self):\n if self.status == 0:\n QtWidgets.QMessageBox.information(self, '警告', '请先点击“打开图片”按钮!',\n QMessageBox.Close, QMessageBox.Close)\n return\n # self.startProcess1()\n\n start = time.time()\n self.reloadImage()\n self.work.ocr_process()\n self.work.export_to_xlsx()\n end = time.time()\n print(\"time: \" + str(end - start))\n\n global cells\n global cols_count\n global rows_count\n cells = self.work.cells\n cols_count = len(self.work.final_x) - 1\n rows_count = len(self.work.final_y) - 1\n\n msgBox = QtWidgets.QMessageBox.information(self, '完成',\n '耗时' + str(round((end - start), 2)) + 's\\nExcel文件转换完成,是否打开?',\n QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)\n if msgBox == QMessageBox.Ok:\n os.startfile(os.path.abspath(OUTPUT_FILE_PATH + self.xlsx_name))\n\n else:\n pass\n\n self.status = 2\n\n def openTagDialog(self):\n if self.status == 0:\n QtWidgets.QMessageBox.information(self, '警告', '请先点击“打开图片”按钮!',\n QMessageBox.Close, QMessageBox.Close)\n return\n elif self.status == 1:\n QtWidgets.QMessageBox.information(self, '警告', '请先点击“生成Excel”按钮!',\n QMessageBox.Close, QMessageBox.Close)\n return\n else:\n self.tag_dialog = MyTagDialog()\n self.tag_dialog.show()\n\n def openBatchDialog(self):\n self.batch_dialog = MyBatchDialog()\n self.batch_dialog.show()\n\n\nclass MyTagDialog(QDialog, Tag_Dialog):\n def __init__(self, is_batch=False):\n super(MyTagDialog, self).__init__()\n\n self.tag_status = 0\n self.tags_list = []\n\n if not os.path.exists(TAG_FILES_PATH):\n os.mkdir(TAG_FILES_PATH)\n\n self.setupUi(self)\n\n if not is_batch:\n # 允许右键产生菜单\n self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n # 将右键菜单绑定到槽函数generateMenu\n self.tableWidget.customContextMenuRequested.connect(self.generateMenu)\n\n self.make_base()\n self.fill_table()\n\n def batch_init(self):\n # 允许右键产生菜单\n self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n # 将右键菜单绑定到槽函数generateMenu\n self.tableWidget.customContextMenuRequested.connect(self.generateMenu)\n\n self.make_base()\n self.fill_table()\n\n def make_base(self):\n # tableWidget\n self.tableWidget.setColumnCount(cols_count)\n self.tableWidget.setRowCount(rows_count)\n self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n self.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)\n header_list = []\n for i in range(cols_count):\n header_list.append(ascii_uppercase[i])\n self.tableWidget.setHorizontalHeaderLabels(header_list)\n\n # tableWidget_tags\n self.tableWidget_tags.setColumnCount(2)\n self.tableWidget_tags.setRowCount(0)\n self.tableWidget_tags.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.tableWidget_tags.setHorizontalHeaderLabels(['Tag', 'Data'])\n self.tableWidget_tags.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.tableWidget_tags.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n # 读取文件\n self.load_tags()\n\n def fill_table(self):\n for y in range(len(cells)):\n for x in range(len(cells[y])):\n present = cells[y][x]\n coor_x, coor_y = split_cell_coordinate(present.cell_name)\n text = present.text\n if text is not None:\n pass\n # text = text.replace('\\n', ' ')\n self.tableWidget.setItem(coor_y, coor_x, QTableWidgetItem(text))\n if present.cell_name != present.merged_info:\n coor_x2, coor_y2 = split_cell_coordinate(present.merged_info)\n self.tableWidget.setSpan(coor_y, coor_x, coor_y2 - coor_y + 1, coor_x2 - coor_x + 1)\n\n def generateMenu(self, pos):\n qtcell = self.tableWidget.selectionModel().selection().indexes()[0]\n row_num = qtcell.row()\n col_num = qtcell.column()\n menu = QMenu()\n item1 = menu.addAction(u'选择标签')\n item2 = menu.addAction(u'选择数据')\n action = menu.exec_(self.tableWidget.mapToGlobal(pos))\n # 显示选中行的数据文本\n if action == item1:\n self.tag_status = 1\n self.tags_list.clear()\n text = self.tableWidget.item(row_num, col_num).text()\n coor = make_cell_coordinate(col_num, row_num)\n self.tags_list.append(coor)\n # print('你选了选项一,当前行文字内容是:', text)\n if action == item2 and self.tag_status == 1:\n self.tag_status = 2\n text = self.tableWidget.item(row_num, col_num).text()\n coor = make_cell_coordinate(col_num, row_num)\n self.tags_list.append(coor)\n # print('你选了选项二,当前行文字内容是:', text)\n # 填表\n current_row = self.tableWidget_tags.rowCount()\n self.tableWidget_tags.setRowCount(self.tableWidget_tags.rowCount() + 1)\n self.tableWidget_tags.setItem(current_row, 0, QTableWidgetItem(self.tags_list[0]))\n self.tableWidget_tags.setItem(current_row, 1, QTableWidgetItem(self.tags_list[1]))\n self.save_tags() # 随时保存\n\n def save_tags(self):\n tags_list_save = []\n for y in range(self.tableWidget_tags.rowCount()):\n temp_list = [self.tableWidget_tags.item(y, 0).text(), self.tableWidget_tags.item(y, 1).text()]\n tags_list_save.append(temp_list)\n numpy_list = np.asarray(tags_list_save)\n np.savetxt(TAG_FILE, numpy_list, fmt='%s', delimiter=' ') # 这样就以文本的形式把刚才的数组保存下来了\n\n def load_tags(self):\n\n if not os.path.exists(TAG_FILE) or os.path.getsize(TAG_FILE) == 0:\n return\n\n # tags_list_save = np.loadtxt(TAGS_FILE_PATH)\n tags_list_save = np.loadtxt(TAG_FILE, dtype=bytes).astype(str)\n # print(tags_list_save.shape)\n if tags_list_save.ndim == 1:\n tags_list_save = [tags_list_save]\n # print(tags_list_save)\n\n self.tableWidget_tags.setRowCount(0)\n self.tableWidget_tags.clearContents()\n\n for i in range(len(tags_list_save)):\n item = tags_list_save[i]\n row = self.tableWidget_tags.rowCount()\n self.tableWidget_tags.insertRow(row)\n for j in range(len(item)):\n item = QTableWidgetItem(str(tags_list_save[i][j]))\n self.tableWidget_tags.setItem(row, j, item)\n\n # 按钮相关函数\n def deleteRow(self):\n current_row = self.tableWidget_tags.currentRow()\n self.tableWidget_tags.removeRow(current_row)\n self.save_tags()\n\n def clearTable(self):\n self.tableWidget_tags.setRowCount(0)\n self.tableWidget_tags.clearContents()\n self.save_tags()\n\n def output(self):\n data_list = []\n for y in range(self.tableWidget_tags.rowCount()):\n coor_x, coor_y = split_cell_coordinate(self.tableWidget_tags.item(y, 0).text())\n text1 = self.tableWidget.item(coor_y, coor_x).text()\n text1 = text1.strip().replace(' ', '').replace('\\n', '')\n coor_x, coor_y = split_cell_coordinate(self.tableWidget_tags.item(y, 1).text())\n text2 = self.tableWidget.item(coor_y, coor_x).text()\n # text2 = text2.strip().replace(' ', '').replace('\\n', '')\n text2 = text2.strip().replace('\\n', '')\n # print('<' + text1 + '>' + text2 + '<' + text1 + '/>')\n data_list.append([text1, text2])\n utils.write_xml(OUTPUT_FILE_PATH, filename_now, data_list)\n\n def load(self):\n fileName, dummy = QFileDialog.getOpenFileName(self, \"打开保存的标签\", TAG_FILES_PATH, \"Text Files (*.txt)\")\n if fileName == '':\n QtWidgets.QMessageBox.information(self, '警告', '无效文件!',\n QMessageBox.Close, QMessageBox.Close)\n else:\n try:\n shutil.copyfile(fileName, TAG_FILE)\n except shutil.SameFileError:\n pass\n self.load_tags()\n\n def save(self):\n fileName, dummy = QFileDialog.getSaveFileName(self, \"保存标签\", TAG_FILES_PATH, \"Text Files (*.txt)\")\n if fileName == '':\n QtWidgets.QMessageBox.information(self, '警告', '无效文件!',\n QMessageBox.Close, QMessageBox.Close)\n else:\n try:\n shutil.copyfile(TAG_FILE, fileName)\n except shutil.SameFileError:\n pass\n\n\nclass MyBatchDialog(QDialog, Batch_Dialog):\n signal_run = pyqtSignal()\n signal_ui = pyqtSignal(int, int)\n def __init__(self):\n super(MyBatchDialog, self).__init__()\n self.setupUi(self)\n\n self.path = None\n self.mode = None\n self.is_path_ok = False\n self.is_tag_ok = False\n\n self.is_stop = False\n\n self.MyTagDialog = MyTagDialog(is_batch=True)\n\n def get_radio_select(self):\n name = self.buttonGroup.checkedButton().objectName()\n if name == 'radioButton1':\n self.mode = 1\n elif name == 'radioButton2':\n self.mode = 2\n elif name == 'radioButton3':\n self.mode = 3\n else:\n self.mode = 1\n return self.mode\n\n def set_progress(self, now_value, max_value):\n self.progressBar.setMaximum(max_value)\n self.progressBar.setValue(now_value)\n self.label.setText(str(now_value) + '/' + str(max_value))\n\n def ui_update(self):\n self.startButton.setEnabled(True)\n self.label.setText('完成!')\n\n def selectFolder(self):\n directory = QtWidgets.QFileDialog.getExistingDirectory(self, \"getExistingDirectory\", \"./\")\n if directory == '':\n return\n is_have_pics = False\n names = os.listdir(directory)\n for name in names:\n if name.endswith('.jpg') or name.endswith('.png'):\n is_have_pics = True\n if directory is not None and is_have_pics:\n self.path = directory\n self.is_path_ok = True\n else:\n self.is_path_ok = False\n\n def selectTag(self):\n self.MyTagDialog.load()\n self.is_tag_ok = True\n\n def startProcess(self):\n self.startButton.setEnabled(False)\n self.set_progress(0, 0)\n\n proc = self.startProcess1\n\n class Example(QThread):\n def __init__(self):\n super().__init__()\n\n def run(self):\n # 进行任务操作\n proc()\n\n self.thread = Example()\n self.signal_ui.connect(self.set_progress)\n self.signal_run.connect(self.ui_update)\n self.thread.start() # 启动线程\n\n def startProcess1(self):\n if not self.is_path_ok:\n return\n\n self.get_radio_select()\n self.is_stop = False\n\n pics = os.listdir(self.path)\n list_pics = []\n for pic in pics:\n if pic.endswith('.jpg') or pic.endswith('.png'):\n list_pics.append(self.path + os.sep + pic)\n\n global cells\n global cols_count\n global rows_count\n\n #self.set_progress(0, len(list_pics))\n\n for i, pic in enumerate(list_pics):\n if self.is_stop:\n self.is_stop = False\n return\n\n (filename, extension) = os.path.splitext(os.path.basename(pic))\n xlsx_name = filename + '.xlsx'\n global filename_now\n filename_now = filename\n\n if self.mode == 1:\n\n work = Export2XLSX(pic, verbose=verbose, workbook=OUTPUT_FILE_PATH + xlsx_name)\n work.ocr_process()\n work.export_to_xlsx()\n\n cells = work.cells\n cols_count = len(work.final_x) - 1\n rows_count = len(work.final_y) - 1\n\n self.MyTagDialog.batch_init()\n self.MyTagDialog.output()\n\n elif self.mode == 2:\n work = Export2XLSX(pic, verbose=verbose, workbook=OUTPUT_FILE_PATH + xlsx_name)\n work.ocr_process()\n work.export_to_xlsx()\n\n elif self.mode == 3:\n work = OcrProcess(pic, verbose=verbose)\n work.ocr_process()\n\n cells = work.cells\n cols_count = len(work.final_x) - 1\n rows_count = len(work.final_y) - 1\n\n self.MyTagDialog.batch_init()\n self.MyTagDialog.output()\n\n self.signal_ui.emit(i + 1, len(list_pics))\n\n self.signal_run.emit()\n\n def cancelProcess(self):\n self.is_stop = True\n self.startButton.setEnabled(True)\n pass\n\n\ndef start_ui():\n app = QtWidgets.QApplication(sys.argv)\n window = MyWindow()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"ui_main.py","file_name":"ui_main.py","file_ext":"py","file_size_in_byte":16326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"386560363","text":"import datetime as dt\n\nfrom django.contrib.auth.models import AbstractUser\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef now_year():\n return dt.datetime.now().year\n\n\nclass User(AbstractUser):\n class Roles(models.TextChoices):\n USER = 'user'\n MODERATOR = 'moderator'\n ADMIN = 'admin'\n\n email = models.EmailField(\n _('email адрес'),\n unique=True\n )\n confirmation_code = models.CharField(\n _('код доступа к токену'),\n max_length=40,\n blank=True,\n null=True\n )\n bio = models.CharField(\n _('о себе'),\n max_length=400,\n blank=True,\n null=True\n )\n role = models.CharField(\n _('Права'),\n max_length=9,\n choices=Roles.choices,\n default=Roles.USER\n )\n\n REQUIRED_FIELDS = ['email']\n\n class Meta:\n verbose_name = _('пользователь')\n verbose_name_plural = _('пользователи')\n\n @property\n def is_admin(self):\n return self.is_superuser or self.role == self.Roles.ADMIN\n\n @property\n def is_moderator(self):\n return self.is_admin or self.role == self.Roles.MODERATOR\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=30,\n verbose_name=_('Название категории'))\n slug = models.SlugField(unique=True,\n verbose_name=_('URL адрес категории'))\n\n class Meta:\n verbose_name = _('Категория')\n verbose_name_plural = _('Категории')\n\n def __str__(self):\n return self.slug[:20]\n\n\nclass Genre(models.Model):\n name = models.CharField(max_length=40,\n verbose_name=_('Название жанра'))\n slug = models.SlugField(unique=True,\n max_length=30,\n verbose_name=_('URL адрес жанра'))\n\n class Meta:\n verbose_name = _('Жанр')\n verbose_name_plural = _('Жанры')\n\n def __str__(self):\n return self.slug[:20]\n\n\nclass Title(models.Model):\n category = models.ForeignKey(Category,\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n related_name='titles',\n verbose_name=_('Категория произведения')\n )\n genre = models.ManyToManyField(Genre,\n blank=True,\n related_name='titles',\n related_query_name='genres',\n verbose_name=_('Жанр произведения')\n )\n name = models.CharField(max_length=50,\n verbose_name=_('Название произведения'))\n year = models.PositiveIntegerField(blank=True,\n null=True,\n db_index=True,\n verbose_name=_(\n 'Год выпуска произведения'),\n validators=[\n MaxValueValidator(\n now_year)\n ])\n description = models.TextField(blank=True,\n null=True,\n verbose_name=_('Описание произведения')\n )\n\n class Meta:\n verbose_name = _('Произведение')\n verbose_name_plural = _('Произведения')\n\n def __str__(self):\n return self.name[:20]\n\n\nclass Review(models.Model):\n title = models.ForeignKey(\n Title,\n on_delete=models.CASCADE,\n related_name='reviews',\n )\n text = models.TextField(\n verbose_name=_('Содержание отзыва')\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='reviews',\n verbose_name=_('Автор отзыва')\n )\n score = models.PositiveSmallIntegerField(\n verbose_name=_('Оценка от 1 до 10'),\n validators=[MinValueValidator(1, 'Не может быть меньше 1'),\n MaxValueValidator(10, 'Не может быть больше 10')\n ]\n )\n pub_date = models.DateTimeField(\n auto_now_add=True,\n verbose_name=_('Дата отзыва')\n )\n\n class Meta:\n ordering = ('-pub_date',)\n verbose_name = _('отзыв')\n verbose_name_plural = _('отзывы')\n constraints = [\n models.UniqueConstraint(\n fields=['title', 'author'],\n name='onereviewpertitle'\n )\n ]\n\n def __str__(self):\n return self.text[:20]\n\n\nclass Comment(models.Model):\n review = models.ForeignKey(\n Review,\n on_delete=models.CASCADE,\n related_name='comments',\n )\n text = models.TextField(\n verbose_name='Текст комментария'\n )\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Автор комментария'\n )\n pub_date = models.DateTimeField(\n auto_now_add=True,\n verbose_name='Дата комментария'\n )\n\n class Meta:\n ordering = ('-pub_date',)\n verbose_name = 'комментарий'\n verbose_name_plural = 'комментарии'\n\n def __str__(self):\n return self.text[:20]\n","sub_path":"apiv1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"283637348","text":"import os\nimport pandas as pd\nimport numpy as np\nimport time\nfrom torch.utils.data import DataLoader, TensorDataset, random_split\nfrom pytorch_lightning.callbacks import ModelCheckpoint\nfrom pytorch_lightning import Trainer, seed_everything\n\nfrom torch_explain.models.explainer import Explainer\nfrom torch_explain.logic.metrics import formula_consistency\nfrom experiments.data.load_datasets import load_mnist\n\n# %% md\n\n## Import MIMIC-II dataset\n\n# %%\nx, y, concept_names = load_mnist()\n\n\ndataset = TensorDataset(x, y)\ntrain_size = int(len(dataset) * 0.9)\nval_size = (len(dataset) - train_size) // 2\ntest_size = len(dataset) - train_size - val_size\ntrain_data, val_data, test_data = random_split(dataset, [train_size, val_size, test_size])\ntrain_loader = DataLoader(train_data, batch_size=len(train_data))\nval_loader = DataLoader(val_data, batch_size=len(val_data))\ntest_loader = DataLoader(test_data, batch_size=len(test_data))\nn_concepts = next(iter(train_loader))[0].shape[1]\nn_classes = 2\nprint(concept_names)\nprint(n_concepts)\nprint(n_classes)\n\n# %% md\n\n## 5-fold cross-validation with explainer network\n\nbase_dir = f'./results/MNIST/explainer'\nos.makedirs(base_dir, exist_ok=True)\n\nn_seeds = 5\nresults_list = []\nexplanations = {i: [] for i in range(n_classes)}\nfor seed in range(n_seeds):\n seed_everything(seed)\n print(f'Seed [{seed + 1}/{n_seeds}]')\n train_loader = DataLoader(train_data, batch_size=len(train_data))\n val_loader = DataLoader(val_data, batch_size=len(val_data))\n test_loader = DataLoader(test_data, batch_size=len(test_data))\n\n checkpoint_callback = ModelCheckpoint(dirpath=base_dir, monitor='val_loss', save_top_k=1)\n trainer = Trainer(max_epochs=10, gpus=1, auto_lr_find=True, deterministic=True,\n check_val_every_n_epoch=1, default_root_dir=base_dir,\n weights_save_path=base_dir, callbacks=[checkpoint_callback])\n model = Explainer(n_concepts=n_concepts, n_classes=n_classes, l1=0.0000001, temperature=5, lr=0.01,\n explainer_hidden=[10], conceptizator='identity_bool')\n\n start = time.time()\n trainer.fit(model, train_loader, val_loader)\n print(f\"Concept mask: {model.model[0].concept_mask}\")\n model.freeze()\n model_results = trainer.test(model, test_dataloaders=test_loader)\n for j in range(n_classes):\n n_used_concepts = sum(model.model[0].concept_mask[j] > 0.5)\n print(f\"Extracted concepts: {n_used_concepts}\")\n results, f = model.explain_class(val_loader, val_loader, test_loader, topk_explanations=5,\n x_to_bool=None, max_accuracy=True, concept_names=concept_names)\n end = time.time() - start\n results['model_accuracy'] = model_results[0]['test_acc']\n results['extraction_time'] = end\n\n results_list.append(results)\n extracted_concepts = []\n all_concepts = model.model[0].concept_mask[0] > 0.5\n common_concepts = model.model[0].concept_mask[0] > 0.5\n for j in range(n_classes):\n n_used_concepts = sum(model.model[0].concept_mask[j] > 0.5)\n print(f\"Extracted concepts: {n_used_concepts}\")\n print(f\"Explanation: {f[j]['explanation']}\")\n print(f\"Explanation accuracy: {f[j]['explanation_accuracy']}\")\n explanations[j].append(f[j]['explanation'])\n extracted_concepts.append(n_used_concepts)\n all_concepts += model.model[0].concept_mask[j] > 0.5\n common_concepts *= model.model[0].concept_mask[j] > 0.5\n\n results['extracted_concepts'] = np.mean(extracted_concepts)\n results['common_concepts_ratio'] = sum(common_concepts) / sum(all_concepts)\n\nconsistencies = []\nfor j in range(n_classes):\n consistencies.append(formula_consistency(explanations[j]))\nexplanation_consistency = np.mean(consistencies)\n\nresults_df = pd.DataFrame(results_list)\nresults_df['explanation_consistency'] = explanation_consistency\nresults_df.to_csv(os.path.join(base_dir, 'results_aware_mnist.csv'))\nresults_df\n\n# %%\n\nresults_df.mean()\n\n# %%\n\nresults_df.sem()\n","sub_path":"experiments/elens/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"583392013","text":"# coding: utf-8\n#\n# Project: BioSaxs\n# http://www.edna-site.org\n#\n# File: \"$Id$\"\n#\n# Copyright (C) ESRF, 2010\n#\n# Principal author: Jérôme Kieffer\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\nfrom XSDataBioSaxsv1_0 import XSDataResultBioSaxsAsciiExportv1_0\n\n__author__ = \"Jérôme Kieffer\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"ESRF\"\n\nimport os, sys\nfrom EDVerbose import EDVerbose\nfrom EDAssert import EDAssert\nfrom EDTestCasePluginExecute import EDTestCasePluginExecute\nfrom EDFactoryPluginStatic import EDFactoryPluginStatic\n\n\nEDFactoryPluginStatic.loadModule(\"EDInstallNumpyv1_3\")\nEDFactoryPluginStatic.loadModule(\"EDInstallSpecClient\")\nEDFactoryPluginStatic.loadModule(\"EDInstallEdfFile\")\n\n\n\nclass EDTestCasePluginExecuteBioSaxsAsciiExportv1_1(EDTestCasePluginExecute):\n\n\n def __init__(self, _strTestName=None):\n EDTestCasePluginExecute.__init__(self, \"EDPluginBioSaxsAsciiExportv1_1\")\n# self.setConfigurationFile(os.path.join(self.getPluginTestsDataHome(),\n# \"XSConfiguration_.xml\"))\n self.setDataInputFile(os.path.join(self.getPluginTestsDataHome(), \\\n \"XSDataInputBioSaxsAsciiExportv1_0_reference.xml\"))\n self.setReferenceDataOutputFile(os.path.join(self.getPluginTestsDataHome(), \\\n \"XSDataResultBioSaxsAsciiExportv1_0_reference.xml\"))\n\n def preProcess(self):\n \"\"\"\n PreProcess of the execution test: download a set of images from http://www.edna-site.org\n and remove any existing output file \n \"\"\"\n EDTestCasePluginExecute.preProcess(self)\n self.loadTestImage([ \"bioSaxsAsciiExportv1_1.dat\", \"bioSaxsIntegrated.edf\"])\n strExpectedOutput = self.readAndParseFile (self.getReferenceDataOutputFile())\n EDVerbose.DEBUG(\"strExpectedOutput:\" + strExpectedOutput)\n xsDataResultReference = XSDataResultBioSaxsAsciiExportv1_0.parseString(strExpectedOutput)\n self.integratedCurve = xsDataResultReference.getIntegratedCurve().getPath().value\n EDVerbose.DEBUG(\"Output file is %s\" % self.integratedCurve)\n if not os.path.isdir(os.path.dirname(self.integratedCurve)):\n os.makedirs(os.path.dirname(self.integratedCurve))\n if os.path.isfile(self.integratedCurve):\n EDVerbose.DEBUG(\" Output Integrated Curve file exists %s, I will remove it\" % self.integratedCurve)\n os.remove(self.integratedCurve)\n\n\n def testExecute(self):\n \"\"\"\n \"\"\"\n self.run()\n plugin = self.getPlugin()\n\n################################################################################\n# Compare XSDataResults\n################################################################################\n\n strExpectedOutput = self.readAndParseFile (self.getReferenceDataOutputFile())\n# strObtainedOutput = self.readAndParseFile (self.m_edObtainedOutputDataFile)\n EDVerbose.DEBUG(\"Checking obtained result...\")\n xsDataResultReference = XSDataResultBioSaxsAsciiExportv1_0.parseString(strExpectedOutput)\n xsDataResultObtained = plugin.getDataOutput()\n EDAssert.strAlmostEqual(xsDataResultReference.marshal(), xsDataResultObtained.marshal(), \"XSDataResult output are the same\", _strExcluded=\"bioSaxs\")\n\n################################################################################\n# Compare spectrum ascii Files\n################################################################################\n\n outputData = open(xsDataResultObtained.getIntegratedCurve().getPath().value, \"rb\").read()\n referenceData = open(os.path.join(self.getTestsDataImagesHome(), \"bioSaxsAsciiExportv1_1.dat\"), \"rb\").read()\n\n EDAssert.strAlmostEqual(referenceData, outputData, _strComment=\"3-column ascii spectra files are the same\", _fRelError=0.1, _fAbsError=0.1, _strExcluded=\"bioSaxs\")\n\n\n\n\n def process(self):\n \"\"\"\n \"\"\"\n self.addTestMethod(self.testExecute)\n\n\n\n\nif __name__ == '__main__':\n\n edTestCasePluginExecuteBioSaxsAsciiExportv1_0 = EDTestCasePluginExecuteBioSaxsAsciiExportv1_1(\"EDTestCasePluginExecuteBioSaxsAsciiExportv1_1\")\n edTestCasePluginExecuteBioSaxsAsciiExportv1_0.execute()\n","sub_path":"bioSaxsv1/tests/testsuite/EDTestCasePluginExecuteBioSaxsAsciiExportv1_1.py","file_name":"EDTestCasePluginExecuteBioSaxsAsciiExportv1_1.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"458833219","text":"# -*- coding: utf-8 -*-\nfrom typing import Dict\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\nfrom typing import Union\n\nimport ujson\n\n\nclass JussiJSONRPCRequest(NamedTuple):\n id: Optional[Union[str, int, float, type(None)]]\n jsonrpc: str\n method: str\n params: Optional[Union[Dict, List]]\n urn: NamedTuple\n upstream: NamedTuple\n amzn_trace_id: str\n jussi_request_id: str\n batch_index: int\n original_request: Optional[Dict]\n\n # pylint: disable=no-member\n @classmethod\n def from_request(cls, sanic_request, batch_index: int,\n request: Dict[str, any]) -> NamedTuple:\n from .urn import URN\n from .upstream import Upstream\n\n assert isinstance(request, dict), 'request must be dict'\n upstreams = sanic_request.app.config.upstreams\n urn = URN.from_request(request)\n upstream = Upstream.from_urn(urn, upstreams=upstreams)\n original_request = None\n\n if upstreams.translate_to_appbase(urn):\n original_request = request\n request = JussiJSONRPCRequest.translate_to_appbase(request, urn)\n urn = URN.from_request(request)\n upstream = Upstream.from_urn(urn, upstreams=upstreams)\n\n _id = request.get('id', False)\n jsonrpc = request['jsonrpc']\n method = request['method']\n params = request.get('params', False)\n\n return JussiJSONRPCRequest(_id,\n jsonrpc,\n method,\n params,\n urn,\n upstream,\n sanic_request.headers.get('x-amzn-trace-id'),\n sanic_request['jussi_request_id'],\n batch_index,\n original_request)\n\n # pylint: enable=no-member\n\n def to_dict(self):\n return {k: getattr(self, k, False) for k in\n ('id', 'jsonrpc', 'method', 'params') if getattr(self, k, False) is not False}\n\n def json(self):\n return ujson.dumps(self.to_dict(), ensure_ascii=False)\n\n def to_upstream_request(self, as_json=True):\n jrpc_dict = self.to_dict()\n jrpc_dict.update({'id': self.upstream_id})\n if as_json:\n return ujson.dumps(jrpc_dict, ensure_ascii=False)\n return jrpc_dict\n\n @property\n def upstream_headers(self):\n headers = {'x-jussi-request-id': self.jussi_request_id}\n if self.amzn_trace_id:\n headers['x-amzn-trace-id'] = self.amzn_trace_id\n return headers\n\n @property\n def upstream_id(self):\n return int(self.jussi_request_id) + self.batch_index\n\n @property\n def translated(self):\n return self.original_request is not None\n\n def log_extra(self, **kwargs):\n try:\n base_extra = {\n 'x-amzn-trace-id': self.amzn_trace_id,\n 'jussi_request_id': self.jussi_request_id,\n 'jsonrpc_id': self.id,\n 'batch_index': self.batch_index,\n 'urn': self.urn._asdict(),\n 'upstream': self.upstream._asdict(),\n 'upstream_request_id': self.upstream_id,\n 'translated': self.translated\n }\n base_extra.update(**kwargs)\n return base_extra\n\n except Exception:\n return None\n\n def __hash__(self):\n return hash(self.urn)\n\n @staticmethod\n def translate_to_appbase(request, urn):\n params = urn.params\n if params is False:\n params = []\n return {\n 'id': request.get('id', False),\n 'jsonrpc': request['jsonrpc'],\n 'method': 'call',\n 'params': ['condenser_api', urn.method, params]\n }\n","sub_path":"jussi/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"600128649","text":"#!/usr/bin/env python\n\nfrom os import system,getenv\nfrom sys import argv\nimport argparse\n\n### SET GLOBAL VARIABLES ###\nbaseDir = getenv('PANDA_FLATDIR')+'/' \nparser = argparse.ArgumentParser(description='plot stuff')\nparser.add_argument('--basedir',metavar='basedir',type=str,default=None)\nparser.add_argument('--outdir',metavar='outdir',type=str,default=None)\nparser.add_argument('--cut',metavar='cut',type=str,default='1==1')\nargs = parser.parse_args()\nlumi = 36560.\nsname = argv[0]\nif args.basedir:\n baseDir = args.basedir\n\nargv=[]\nimport ROOT as root\nroot.gROOT.SetBatch()\nfrom PandaCore.Tools.Misc import *\nfrom PandaCore.Drawers.plot_utility import *\n\n### DEFINE REGIONS ###\n\ncut = 'pfmet>250 && nFatjet==1 && fj1Pt>250'\ncut = tAND(cut,args.cut)\n\n\n### LOAD PLOTTING UTILITY ###\nplot = PlotUtility()\nplot.SetTDRStyle()\nplot.InitLegend()\nplot.AddCMSLabel()\nplot.cut = cut\nplot.SetEvtNum(\"eventNumber\")\nplot.SetLumi(lumi/1000)\nplot.AddLumiLabel(True)\nplot.do_overflow = True\nplot.do_underflow = True\nplot.SetNormFactor(True)\n\nweight = 'normalizedWeight' \nplot.mc_weight = weight\nplot.AddPlotLabel('m_{#chi}=1 GeV, g^{V}_{q}=0.25, g^{V}_{#chi}=1',.18,.77,False,42,.04)\n\n#mVs = [300,500,1000,1500,2500]\nmVs = [300,1000,2500]\n\n### DEFINE PROCESSES ###\nprocs = [] \ncounter=root.kExtra1\nfor m in mVs:\n matched = Process('m_{V}=%.1f TeV [top]'%(m/1000.),counter)\n matched.additional_cut = 'fj1IsMatched==1 && fj1GenSize<1.44'\n\n wmatched = Process('m_{V}=%.1f, [W]'%(m/1000.),counter)\n wmatched.additional_cut = '(fj1IsMatched==0 || fj1GenSize>1.44) && fj1IsWMatched==1 && fj1GenWSize<1.44'\n wmatched.dashed = True\n\n unmatched = Process('m_{V}=%.1f, [none]'%(m/1000.),counter)\n unmatched.additional_cut = '(fj1IsMatched==0 || fj1GenSize>1.44) && (fj1IsWMatched==0 || fj1GenWSize>1.44)'\n unmatched.dotted = True\n\n counter += 1\n for p in [unmatched,wmatched,matched]:\n #for p in [matched]:\n p.add_file(baseDir + '/Vector_MonoTop_NLO_Mphi-%i_Mchi-1_gSM-0p25_gDM-1p0_13TeV-madgraph.root'%m)\n procs.append(p)\n\nfor p in procs:\n plot.add_process(p)\n\nplot.add_distribution(FDistribution('max(genAntiTopPt,genTopPt)',0,1000,40,'gen t p_{T} [GeV]','a.u.',filename='genTopPt'))\nplot.add_distribution(FDistribution('fj1Pt',250,1000,40,'fatjet p_{T} [GeV]','a.u.'))\nplot.add_distribution(FDistribution('fj1MSD',0,400,40,'fatjet m_{SD} [GeV]','a.u.'))\nplot.add_distribution(FDistribution('top_ecf_bdt',-1,1,40,'Top BDT','a.u.'))\n\n### DRAW AND CATALOGUE ###\nplot.draw_all(args.outdir+'/')\n","sub_path":"Monotop/plotting/new_signals.py","file_name":"new_signals.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"382682627","text":"from logging import getLogger\n\nfrom .node import Node, NodeHeap\nfrom .utils import gather_dict, decode_nodes\n\n\nclass SpiderCrawl(object):\n \"\"\"\n Crawl the network and look for given 160-bit keys.\n \"\"\"\n\n def __init__(self, protocol, node, peers, k_size, alpha):\n \"\"\"\n Create a new C{SpiderCrawl}er.\n\n Args:\n protocol: A :class:`~kademlia.protocol.KademliaProtocol` instance.\n node: A :class:`~kademlia.node.Node` representing the key we're looking for\n peers: A list of :class:`~kademlia.node.Node` instances that provide the entry point for the network\n k_size: The value for k based on the paper\n alpha: The value for alpha based on the paper\n \"\"\"\n self.protocol = protocol\n self.k_size = k_size\n self.alpha = alpha\n self.node = node\n self.nearest = NodeHeap(self.node, self.k_size)\n self.last_ids_crawled = []\n self.log = getLogger(\"kademlia-spider\")\n self.log.info(\"creating spider with peers: %s\" % peers)\n self.nearest.push(peers)\n\n async def _find(self, rpcmethod):\n \"\"\"\n Get either a value or list of nodes.\n\n Args:\n rpcmethod: The protocol's callfindValue or callFindNode.\n\n The process:\n 1. calls find_* to current ALPHA nearest not already queried nodes,\n adding results to current nearest list of k nodes.\n 2. current nearest list needs to keep track of who has been queried already\n sort by nearest, keep k_size\n 3. if list is same as last time, next call should be to everyone not\n yet queried\n 4. repeat, unless nearest list has all been queried, then ur done\n \"\"\"\n self.log.info(\"crawling with nearest: %s\" % str(tuple(self.nearest)))\n count = self.alpha\n if self.nearest.get_nids() == self.last_ids_crawled:\n self.log.info(\"last iteration same as current - checking all in list now\")\n count = len(self.nearest)\n self.last_ids_crawled = self.nearest.get_nids()\n\n ds = {}\n for peer in self.nearest.get_uncontacted()[:count]:\n ds[peer.nid] = rpcmethod(peer, self.node)\n self.nearest.mark_contacted(peer)\n found = await gather_dict(ds)\n return await self._nodes_found(found)\n\n async def _nodes_found(self, found):\n raise NotImplementedError()\n\n\nclass ValueSpiderCrawl(SpiderCrawl):\n def __init__(self, protocol, node, peers, k_size, alpha):\n SpiderCrawl.__init__(self, protocol, node, peers, k_size, alpha)\n # keep track of the single nearest node without value - per\n # section 2.3 so we can set the key there if found\n self.nearest_without_value = NodeHeap(self.node, 1)\n\n async def find(self):\n \"\"\"\n Find either the closest nodes or the value requested.\n \"\"\"\n return await self._find(self.protocol.call_get_peers)\n\n async def _nodes_found(self, responses):\n \"\"\"\n Handle the result of an iteration in _find.\n \"\"\"\n to_remove = []\n found_values = []\n for peerid, response in responses.items():\n response = RPCFindResponse(response)\n if not response.happened():\n to_remove.append(peerid)\n elif response.has_value():\n found_values.append(response.get_value())\n else:\n peer = self.nearest.get_node_by_nid(peerid)\n self.nearest_without_value.push(peer)\n self.nearest.push(response.get_node_list())\n self.nearest.remove(to_remove)\n\n if len(found_values) > 0:\n return await self._handle_found_values(found_values)\n if self.nearest.all_been_contacted():\n # not found!\n return None\n return await self.find()\n\n async def _handle_found_values(self, values):\n \"\"\"\n We got some values! Exciting. But let's make sure\n they're all the same or freak out a little bit. Also,\n make sure we tell the nearest node that *didn't* have\n the value to store it.\n \"\"\"\n\n # value_counts = Counter(values)\n # if len(value_counts) != 1:\n # args = (self.node.long_id, str(values))\n # self.log.warning(\"Got multiple values for key %i: %s\" % args)\n # value = value_counts.most_common(1)[0][0]\n #\n # peer_to_save_to = self.nearest_without_value.popleft()\n # if peer_to_save_to is not None:\n # await self.protocol.call_store(peer_to_save_to, self.node.nid, value)\n #\n return values\n\n\nclass NodeSpiderCrawl(SpiderCrawl):\n async def find(self):\n \"\"\"\n Find the closest nodes.\n \"\"\"\n return await self._find(self.protocol.call_find_node)\n\n async def _nodes_found(self, responses):\n \"\"\"\n Handle the result of an iteration in _find.\n \"\"\"\n to_remove = []\n for peerid, response in responses.items():\n response = RPCFindResponse(response)\n if not response.happened():\n to_remove.append(peerid)\n else:\n self.nearest.push(response.get_node_list())\n self.nearest.remove(to_remove)\n\n if self.nearest.all_been_contacted():\n return list(self.nearest)\n return await self.find()\n\n\nclass RPCFindResponse(object):\n def __init__(self, response):\n \"\"\"\n A wrapper for the result of a RPC find.\n\n Args:\n response: This will be a tuple of (, )\n where will be a list of tuples if not found or\n a dictionary of {'value': v} where v is the value desired\n \"\"\"\n self.response = response\n\n def happened(self):\n \"\"\"\n Did the other host actually respond?\n \"\"\"\n return self.response[0]\n\n def has_value(self):\n return isinstance(self.response[1], dict) and ('values' in self.response[1]['r'])\n\n def get_value(self):\n return self.response[1]['r']['values']\n\n def get_node_list(self):\n \"\"\"\n Get the node list in the response. If there's no value, this should\n be set.\n \"\"\"\n if 'nodes' not in self.response[1]['r']:\n return []\n nodes = decode_nodes(self.response[1]['r']['nodes'])\n return [Node(*nodeple) for nodeple in nodes]\n","sub_path":"kademlia/crawling.py","file_name":"crawling.py","file_ext":"py","file_size_in_byte":6483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"481095156","text":"import os\nimport sys\n\nimport torch\nfrom setuptools import setup, find_packages\nimport subprocess\n\nimport warnings\n\nif not torch.cuda.is_available():\n # https://github.com/NVIDIA/apex/issues/486\n # Extension builds after https://github.com/pytorch/pytorch/pull/23408 attempt to query torch.cuda.get_device_capability(),\n # which will fail if you are compiling in an environment without visible GPUs (e.g. during an nvidia-docker build command).\n print('\\nWarning: Torch did not find available GPUs on this system.\\n',\n 'If your intention is to cross-compile, this is not an error.\\n'\n 'By default, Apex will cross-compile for Pascal (compute capabilities 6.0, 6.1, 6.2),\\n'\n 'Volta (compute capability 7.0), and Turing (compute capability 7.5).\\n'\n 'If you wish to cross-compile for a single specific architecture,\\n'\n 'export TORCH_CUDA_ARCH_LIST=\"compute capability\" before running setup.py.\\n')\n if os.environ.get(\"TORCH_CUDA_ARCH_LIST\", None) is None:\n os.environ[\"TORCH_CUDA_ARCH_LIST\"] = \"6.0;6.1;6.2;7.0;7.5\"\n\nprint(\"torch.__version__ = \", torch.__version__)\nTORCH_MAJOR = int(torch.__version__.split('.')[0])\nTORCH_MINOR = int(torch.__version__.split('.')[1])\n\nif TORCH_MAJOR == 0 and TORCH_MINOR < 4:\n raise RuntimeError(\"Apex requires Pytorch 0.4 or newer.\\n\" +\n \"The latest stable release can be obtained from https://pytorch.org/\")\n\ncmdclass = {}\next_modules = []\n\nextras = {}\n\nif \"--pyprof\" in sys.argv:\n with open('requirements.txt') as f:\n required_packages = f.read().splitlines()\n extras['pyprof'] = required_packages\n try:\n sys.argv.remove(\"--pyprof\")\n except:\n pass\nelse:\n warnings.warn(\"Option --pyprof not specified. Not installing PyProf dependencies!\")\n\nif \"--cpp_ext\" in sys.argv or \"--cuda_ext\" in sys.argv:\n if TORCH_MAJOR == 0:\n raise RuntimeError(\"--cpp_ext requires Pytorch 1.0 or later, \"\n \"found torch.__version__ = {}\".format(torch.__version__))\n from torch.utils.cpp_extension import BuildExtension\n cmdclass['build_ext'] = BuildExtension\n\nif \"--cpp_ext\" in sys.argv:\n from torch.utils.cpp_extension import CppExtension\n sys.argv.remove(\"--cpp_ext\")\n ext_modules.append(\n CppExtension('apex_C',\n ['csrc/flatten_unflatten.cpp',]))\n\ndef check_cuda_torch_binary_vs_bare_metal(cuda_dir):\n raw_output = subprocess.check_output([cuda_dir + \"/bin/nvcc\", \"-V\"], universal_newlines=True)\n output = raw_output.split()\n release_idx = output.index(\"release\") + 1\n release = output[release_idx].split(\".\")\n bare_metal_major = release[0]\n bare_metal_minor = release[1][0]\n torch_binary_major = torch.version.cuda.split(\".\")[0]\n torch_binary_minor = torch.version.cuda.split(\".\")[1]\n\n print(\"\\nCompiling cuda extensions with\")\n print(raw_output + \"from \" + cuda_dir + \"/bin\\n\")\n\n if (bare_metal_major != torch_binary_major) or (bare_metal_minor != torch_binary_minor):\n raise RuntimeError(\"Cuda extensions are being compiled with a version of Cuda that does \" +\n \"not match the version used to compile Pytorch binaries. \" +\n \"Pytorch binaries were compiled with Cuda {}.\\n\".format(torch.version.cuda) +\n \"In some cases, a minor-version mismatch will not cause later errors: \" +\n \"https://github.com/NVIDIA/apex/pull/323#discussion_r287021798. \"\n \"You can try commenting out this check (at your own risk).\")\n\n# Set up macros for forward/backward compatibility hack around\n# https://github.com/pytorch/pytorch/commit/4404762d7dd955383acee92e6f06b48144a0742e\n# and\n# https://github.com/NVIDIA/apex/issues/456\n# https://github.com/pytorch/pytorch/commit/eb7b39e02f7d75c26d8a795ea8c7fd911334da7e#diff-4632522f237f1e4e728cb824300403ac\nversion_ge_1_1 = []\nif (TORCH_MAJOR > 1) or (TORCH_MAJOR == 1 and TORCH_MINOR > 0):\n version_ge_1_1 = ['-DVERSION_GE_1_1']\nversion_ge_1_3 = []\nif (TORCH_MAJOR > 1) or (TORCH_MAJOR == 1 and TORCH_MINOR > 2):\n version_ge_1_3 = ['-DVERSION_GE_1_3']\nversion_dependent_macros = version_ge_1_1 + version_ge_1_3\n\nif \"--cuda_ext\" in sys.argv:\n from torch.utils.cpp_extension import CUDAExtension\n sys.argv.remove(\"--cuda_ext\")\n\n if torch.utils.cpp_extension.CUDA_HOME is None:\n raise RuntimeError(\"--cuda_ext was requested, but nvcc was not found. Are you sure your environment has nvcc available? If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.\")\n else:\n check_cuda_torch_binary_vs_bare_metal(torch.utils.cpp_extension.CUDA_HOME)\n\n ext_modules.append(\n CUDAExtension(name='amp_C',\n sources=['csrc/amp_C_frontend.cpp',\n 'csrc/multi_tensor_sgd_kernel.cu',\n 'csrc/multi_tensor_scale_kernel.cu',\n 'csrc/multi_tensor_axpby_kernel.cu',\n 'csrc/multi_tensor_l2norm_kernel.cu',\n 'csrc/multi_tensor_lamb_stage_1.cu',\n 'csrc/multi_tensor_lamb_stage_2.cu',\n 'csrc/multi_tensor_adam.cu',\n 'csrc/multi_tensor_novograd.cu',\n 'csrc/multi_tensor_lamb.cu'],\n extra_compile_args={'cxx': ['-O3'] + version_dependent_macros,\n 'nvcc':['-lineinfo',\n '-O3',\n # '--resource-usage',\n '--use_fast_math'] + version_dependent_macros}))\n ext_modules.append(\n CUDAExtension(name='syncbn',\n sources=['csrc/syncbn.cpp',\n 'csrc/welford.cu'],\n extra_compile_args={'cxx': ['-O3'] + version_dependent_macros,\n 'nvcc':['-O3'] + version_dependent_macros}))\n\n ext_modules.append(\n CUDAExtension(name='fused_layer_norm_cuda',\n sources=['csrc/layer_norm_cuda.cpp',\n 'csrc/layer_norm_cuda_kernel.cu'],\n extra_compile_args={'cxx': ['-O3'] + version_dependent_macros,\n 'nvcc':['-maxrregcount=50',\n '-O3',\n '--use_fast_math'] + version_dependent_macros}))\n\nif \"--bnp\" in sys.argv:\n from torch.utils.cpp_extension import CUDAExtension\n sys.argv.remove(\"--bnp\")\n\n from torch.utils.cpp_extension import BuildExtension\n cmdclass['build_ext'] = BuildExtension\n\n if torch.utils.cpp_extension.CUDA_HOME is None:\n raise RuntimeError(\"--bnp was requested, but nvcc was not found. Are you sure your environment has nvcc available? If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.\")\n else:\n ext_modules.append(\n CUDAExtension(name='bnp',\n sources=['apex/contrib/csrc/groupbn/batch_norm.cu',\n 'apex/contrib/csrc/groupbn/ipc.cu',\n 'apex/contrib/csrc/groupbn/interface.cpp',\n 'apex/contrib/csrc/groupbn/batch_norm_add_relu.cu'],\n include_dirs=['csrc'],\n extra_compile_args={'cxx': [] + version_dependent_macros,\n 'nvcc':['-DCUDA_HAS_FP16=1',\n '-D__CUDA_NO_HALF_OPERATORS__',\n '-D__CUDA_NO_HALF_CONVERSIONS__',\n '-D__CUDA_NO_HALF2_OPERATORS__'] + version_dependent_macros}))\n\nif \"--xentropy\" in sys.argv:\n from torch.utils.cpp_extension import CUDAExtension\n sys.argv.remove(\"--xentropy\")\n\n from torch.utils.cpp_extension import BuildExtension\n cmdclass['build_ext'] = BuildExtension\n\n if torch.utils.cpp_extension.CUDA_HOME is None:\n raise RuntimeError(\"--xentropy was requested, but nvcc was not found. Are you sure your environment has nvcc available? If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.\")\n else:\n ext_modules.append(\n CUDAExtension(name='xentropy_cuda',\n sources=['apex/contrib/csrc/xentropy/interface.cpp',\n 'apex/contrib/csrc/xentropy/xentropy_kernel.cu'],\n include_dirs=['csrc'],\n extra_compile_args={'cxx': ['-O3'] + version_dependent_macros,\n 'nvcc':['-O3'] + version_dependent_macros}))\n\nif \"--deprecated_fused_adam\" in sys.argv:\n from torch.utils.cpp_extension import CUDAExtension\n sys.argv.remove(\"--deprecated_fused_adam\")\n\n from torch.utils.cpp_extension import BuildExtension\n cmdclass['build_ext'] = BuildExtension\n\n if torch.utils.cpp_extension.CUDA_HOME is None:\n raise RuntimeError(\"--deprecated_fused_adam was requested, but nvcc was not found. Are you sure your environment has nvcc available? If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.\")\n else:\n ext_modules.append(\n CUDAExtension(name='fused_adam_cuda',\n sources=['apex/contrib/csrc/optimizers/fused_adam_cuda.cpp',\n 'apex/contrib/csrc/optimizers/fused_adam_cuda_kernel.cu'],\n include_dirs=['csrc'],\n extra_compile_args={'cxx': ['-O3',] + version_dependent_macros,\n 'nvcc':['-O3',\n '--use_fast_math'] + version_dependent_macros}))\n\nif \"--fast_multihead_attn\" in sys.argv:\n from torch.utils.cpp_extension import CUDAExtension\n sys.argv.remove(\"--fast_multihead_attn\")\n\n from torch.utils.cpp_extension import BuildExtension\n cmdclass['build_ext'] = BuildExtension\n\n if torch.utils.cpp_extension.CUDA_HOME is None:\n raise RuntimeError(\"--fast_multihead_attn was requested, but nvcc was not found. Are you sure your environment has nvcc available? If you're installing within a container from https://hub.docker.com/r/pytorch/pytorch, only images whose names contain 'devel' will provide nvcc.\")\n else:\n import subprocess\n subprocess.run([\"git\", \"submodule\", \"update\", \"--init\", \"apex/contrib/csrc/multihead_attn/cutlass\"])\n ext_modules.append(\n CUDAExtension(name='fast_self_multihead_attn',\n sources=['apex/contrib/csrc/multihead_attn/self_multihead_attn.cpp', \n 'apex/contrib/csrc/multihead_attn/self_multihead_attn_cuda.cu'],\n extra_compile_args={'cxx': ['-O3',] + version_dependent_macros,\n 'nvcc':['-O3',\n '-gencode', 'arch=compute_70,code=sm_70',\n '-I./apex/contrib/csrc/multihead_attn/cutlass/',\n '-U__CUDA_NO_HALF_OPERATORS__',\n '-U__CUDA_NO_HALF_CONVERSIONS__',\n '--expt-relaxed-constexpr',\n '--expt-extended-lambda',\n '--use_fast_math'] + version_dependent_macros}))\n ext_modules.append(\n CUDAExtension(name='fast_self_multihead_attn_norm_add',\n sources=['apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add.cpp', \n 'apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add_cuda.cu'],\n extra_compile_args={'cxx': ['-O3',] + version_dependent_macros,\n 'nvcc':['-O3',\n '-gencode', 'arch=compute_70,code=sm_70',\n '-I./apex/contrib/csrc/multihead_attn/cutlass/',\n '-U__CUDA_NO_HALF_OPERATORS__',\n '-U__CUDA_NO_HALF_CONVERSIONS__',\n '--expt-relaxed-constexpr',\n '--expt-extended-lambda',\n '--use_fast_math'] + version_dependent_macros}))\n ext_modules.append(\n CUDAExtension(name='fast_encdec_multihead_attn',\n sources=['apex/contrib/csrc/multihead_attn/encdec_multihead_attn.cpp', \n 'apex/contrib/csrc/multihead_attn/encdec_multihead_attn_cuda.cu'],\n extra_compile_args={'cxx': ['-O3',] + version_dependent_macros,\n 'nvcc':['-O3',\n '-gencode', 'arch=compute_70,code=sm_70',\n '-I./apex/contrib/csrc/multihead_attn/cutlass/',\n '-U__CUDA_NO_HALF_OPERATORS__',\n '-U__CUDA_NO_HALF_CONVERSIONS__',\n '--expt-relaxed-constexpr',\n '--expt-extended-lambda',\n '--use_fast_math'] + version_dependent_macros}))\n ext_modules.append(\n CUDAExtension(name='fast_encdec_multihead_attn_norm_add',\n sources=['apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add.cpp', \n 'apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add_cuda.cu'],\n extra_compile_args={'cxx': ['-O3',] + version_dependent_macros,\n 'nvcc':['-O3',\n '-gencode', 'arch=compute_70,code=sm_70',\n '-I./apex/contrib/csrc/multihead_attn/cutlass/',\n '-U__CUDA_NO_HALF_OPERATORS__',\n '-U__CUDA_NO_HALF_CONVERSIONS__',\n '--expt-relaxed-constexpr',\n '--expt-extended-lambda',\n '--use_fast_math'] + version_dependent_macros}))\n \nif \"--parallel\" in sys.argv:\n sys.argv.remove(\"--parallel\")\n import multiprocessing.dummy as multiprocessing\n import itertools\n import distutils.ccompiler\n import copy\n # monkey-patch for parallel compilation\n def parallel_compile(self, sources, output_dir=None, macros=None,\n include_dirs=None, debug=0, extra_preargs=None,\n extra_postargs=None, depends=None):\n macros, objects, extra_postargs, pp_opts, build = \\\n self._setup_compile(output_dir, macros, include_dirs, sources,\n depends, extra_postargs)\n cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)\n\n cuda_compile_jobs = []\n compile_jobs = []\n for obj in objects:\n try:\n src, ext = build[obj]\n except KeyError:\n continue\n if \".cu\" in src:\n cuda_compile_jobs.append(copy.deepcopy((obj, src, ext, cc_args, extra_postargs, pp_opts)))\n else:\n compile_jobs.append(copy.deepcopy((obj, src, ext, cc_args, extra_postargs, pp_opts)))\n with multiprocessing.Pool() as pool:\n list(pool.map(lambda x: self._compile(*x), compile_jobs))\n og_compiler = self.compiler_so\n list(pool.map(lambda x: self._compile(*x), cuda_compile_jobs))\n self.set_executable('compiler_so', og_compiler)\n\n # Return *all* object filenames, not just the ones we just built.\n return objects\n\n distutils.ccompiler.CCompiler.compile = parallel_compile\n\nsetup(\n name='apex',\n version='0.1',\n packages=find_packages(exclude=('build',\n 'csrc',\n 'include',\n 'tests',\n 'dist',\n 'docs',\n 'tests',\n 'examples',\n 'apex.egg-info',)),\n description='PyTorch Extensions written by NVIDIA',\n ext_modules=ext_modules,\n cmdclass=cmdclass,\n extras_require=extras,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":17744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"241165948","text":"\nimport string\nimport datetime\nnow = datetime.datetime.now()\n\n# hellopapa <=> welaopppa\n# minute = 2\n\n\ndef fun1(user_in):\n out = list(user_in)\n for count in range(0, len(user_in), 3):\n x = user_in[count]\n if x >= 'a' and x <= 'z':\n\n var = ord(x) - ord('a')\n var = var - minute + 0x54\n if chr(var) not in string.ascii_lowercase:\n var = ord(x) - ord('a') + 0x1a\n var = var - minute + 0x54\n\n out[count] = chr(var)\n\n if x >= 'A' and x <= 'Z':\n var = ord(x) - ord('A')\n var = var - minute + 0x34\n if chr(var) not in string.ascii_uppercase:\n var = ord(x) - ord('A') + 0x1a\n var = var - minute + 0x34\n\n out[count] = chr(var)\n return ''.join(out)\n\n\ndef fun2(user_in):\n out = list(user_in)\n for count in range(len(user_in)-1, -1, -1):\n out[count] = user_in[(-minute+count % len(user_in))]\n return ''.join(out)\n # 0 -> 7\n # 1 -> 8\n # 2 -> 0\n # 3 -> 1\n # 4 -> 2\n # 5 -> 3\n # 6 -> 4\n # 7 -> 5\n # 8 -> 6\n # 9 -> 7\n\n\ndef fun3(user_in):\n out = list(user_in)\n for count in range(0, len(user_in)):\n x = user_in[count]\n if x >= '0' and x <= '9':\n out[count] = chr(ord(out[count]) - minute)\n return ''.join(out)\n\n\nminute_mod = now.minute % 6\nminute_mod_plus = minute_mod + 2\nminute = minute_mod_plus\n\nfuns = [fun1, fun2, fun3]\n\nuser_in = raw_input()\nuser_in = funs[(minute_mod+4) % 3](user_in)\nuser_in = funs[(minute_mod+3) % 3](user_in)\nuser_in = funs[minute_mod_plus % 3](user_in)\n\nprint(user_in)\n","sub_path":"2020-TAMUCTF/REVERSING/ABOUT_TIME/about_time_decrpyt.py","file_name":"about_time_decrpyt.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"58193158","text":"# Copyright (C) 2017 Binh Nguyen binh@cs.utah.edu.\n# Copyright (C) 2018 Simon Redman sredman@cs.utah.edu\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nfrom webob import Response\nfrom northbound_match import Match as Match\nfrom northbound_actions import Actions as Actions\nfrom sr_flows_mgmt import SR_flows_mgmt as SR_flows_mgmt\nfrom ospf_monitor import *\n\nfrom ryu.app.wsgi import ControllerBase\n\n\nLOG = logging.getLogger('ryu.app.North_api')\nLOG.setLevel(logging.INFO)\nHEADERS = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST',\n 'Access-Control-Allow-Headers': 'Origin, Content-Type',\n 'Content-Type':'application/json'}\n\nclass North_api(ControllerBase):\n def __init__(self, req, link, data, **config):\n super(North_api, self).__init__(req, link, data, **config)\n\n #NORTH BOUND API - REST\n def delete_single_flow(self, req, **_kwargs):\n post = req.POST\n M = Match()\n SR = SR_flows_mgmt()\n if len(post) < 2 or \"dpid\" not in post:\n LOG.info(\"INVALID POST values: %s\" % post)\n return Response(status=404, headers=HEADERS)\n\n match = M.parse_match_fields(post['match'])\n dpid = post['dpid']\n priority = 0\n if 'priority' in post:\n priority = int(post['priority'])\n\n\n LOG.debug(\"RECEIVED NB API: delete_single_flow: (dpid, match) = (%s, %s)\" % (dpid, match) )\n if SR.delete_single_flow(dpid, priority, match):\n LOG.info(\"Deleted a flow.\")\n return Response(status=200, headers=HEADERS)\n return Response(status=500, headers=HEADERS)\n\n #NORTH BOUND API - REST\n def delete_all_flows(self, req, **_kwargs):\n post = req.POST\n SR = SR_flows_mgmt()\n if len(post) != 1 or \"dpid\" not in post:\n LOG.info(\"INVALID POST values: %s\" % post)\n return Response(status=404, headers=HEADERS)\n\n dpid = post['dpid']\n\n LOG.debug(\"RECEIVED NB API: delete_all_flows: (dpid) = (%s)\" % (dpid) )\n if SR.delete_all_flows(dpid):\n LOG.info(\"Deleted all flows in switch %s.\" % dpid)\n return Response(status=200, headers=HEADERS)\n return Response(status=500, headers=HEADERS)\n\n #Usage: curl --data \"dpid=12345&match=123,456&actions=src_ip=1,dst_ip=2\" http://0.0.0.0:8080/flow_mgmt/insert\n def insert_single_flow(self, req, **_kwargs):\n post = req.POST\n A = Actions()\n M = Match()\n SR = SR_flows_mgmt()\n if len(post) < 3 or \"actions\" not in post or \"dpid\" not in post:\n LOG.info(\"INVALID POST values: %s\" % post)\n return Response(status=404, headers=HEADERS)\n actions = A.parse_actions_fields(post['actions'])\n match = M.parse_match_fields(post['match'])\n dpid = post['dpid']\n priority = 0\n if 'priority' in post:\n priority = int(post['priority'])\n\n LOG.debug(\"RECEIVED NB_API: insert_single_flow: (dpid, match, actions) = (%s,%s,%s)\" % (dpid, match, actions))\n if not actions or not match:\n LOG.error(\"Actions or match fields are empty: actions = %s, match = %s\" % (actions, match))\n return Response(status = 500, headers=HEADERS)\n if not SR.insert_single_flow(dpid, priority, match, actions):\n LOG.info(\"Inserted a flow.\")\n return Response(status=200, headers=HEADERS)\n else:\n LOG.error(\"Can't insert a flow!\")\n return Response(status=500, headers=HEADERS)\n\n def handle_http_options(self, req, **_kwargs):\n return Response(content_type='application/json', headers=HEADERS)\n","sub_path":"northbound_api.py","file_name":"northbound_api.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"246061282","text":"from __future__ import print_function\n\nimport math\nimport subprocess\nimport sys\nimport unittest\n\n# N.B. Do not import modules here, as we want to test the order in which\n# they're imported (if they're imported at all).\n\n# Change this to inspect output.\nverbose = False\n\n\ndef debug_print(*args):\n # Prints only if `verbose` is true.\n if verbose:\n print(*args)\n\n\ndef qualname(obj):\n return \"{}.{}\".format(obj.__module__, obj.__name__)\n\n\nclass Overloads(object):\n # Provides interface for testing function overloads for a given type, `T`.\n def supports(self, func):\n # Determines if `func` is supported by this overload.\n raise NotImplemented\n\n def to_float(self, y_T):\n # Converts `y_T` (a value of type `T`) to a float.\n raise NotImplemented\n\n def to_type(self, y_float):\n # Converts `y_float` (a float value) to a value of type `T`.\n raise NotImplemented\n\n\nclass FloatOverloads(Overloads):\n # Imports `math` and provides support for testing `float` overloads.\n def __init__(self):\n from pydrake import math as drake_math\n self.m = drake_math\n self.T = float\n\n def supports(self, func):\n return True\n\n def to_float(self, y_T):\n return y_T\n\n def to_type(self, y_float):\n return y_float\n\n\nclass AutoDiffOverloads(Overloads):\n # Imports `pydrake.autodiffutils` and provides support for testing its\n # overloads.\n def __init__(self):\n from pydrake import autodiffutils\n self.m = autodiffutils\n self.T = self.m.AutoDiffXd\n\n def supports(self, func):\n backwards_compat = [\n \"cos\", \"sin\",\n ]\n supported = backwards_compat + [\n \"log\",\n \"tan\", \"asin\", \"acos\", \"atan2\",\n \"sinh\", \"cosh\", \"tanh\",\n ]\n if func.__name__ in backwards_compat:\n # Check backwards compatibility.\n assert hasattr(self.T, func.__name__)\n return func.__name__ in supported\n\n def to_float(self, y_T):\n return y_T.value()\n\n def to_type(self, y_float):\n return self.T(y_float, [])\n\n\nclass SymbolicOverloads(Overloads):\n # Imports `pydrake.symbolic` and provides support for testing its\n # overloads.\n def __init__(self):\n from pydrake import symbolic\n self.m = symbolic\n self.T = self.m.Expression\n\n def supports(self, func):\n backwards_compat = [\n \"log\", \"abs\", \"exp\", \"sqrt\",\n \"sin\", \"cos\", \"tan\", \"asin\", \"acos\", \"atan\",\n \"sinh\", \"cosh\", \"tanh\", \"ceil\", \"floor\",\n \"min\", \"max\", \"pow\", \"atan2\",\n ]\n supported = backwards_compat\n if func.__name__ in backwards_compat:\n # Check backwards compatibility.\n assert hasattr(self.m, func.__name__)\n return func.__name__ in supported\n\n def to_float(self, y_T):\n return y_T.Evaluate()\n\n def to_type(self, y_float):\n return self.T(y_float)\n\n\nclass TestMathOverloads(unittest.TestCase):\n \"\"\"Tests overloads of math functions, specifically ensuring that we will be\n robust against import order.\"\"\"\n\n def _check_overload(self, overload):\n # TODO(eric.cousineau): Consider comparing against `numpy` ufunc\n # methods.\n import pydrake.math as drake_math\n unary = [\n (drake_math.log, math.log),\n (drake_math.abs, math.fabs),\n (drake_math.exp, math.exp),\n (drake_math.sqrt, math.sqrt),\n (drake_math.sin, math.sin),\n (drake_math.cos, math.cos),\n (drake_math.tan, math.tan),\n (drake_math.asin, math.asin),\n (drake_math.acos, math.acos),\n (drake_math.atan, math.atan),\n (drake_math.sinh, math.sinh),\n (drake_math.cosh, math.cosh),\n (drake_math.tanh, math.tanh),\n (drake_math.ceil, math.ceil),\n (drake_math.floor, math.floor),\n ]\n binary = [\n (drake_math.min, min),\n (drake_math.max, max),\n (drake_math.pow, pow),\n (drake_math.atan2, math.atan2),\n ]\n\n # Arbitrary values to test overloads with.\n args_float_all = [0.1, 0.2]\n\n def check_eval(functions, nargs):\n # Generate arguments.\n args_float = args_float_all[:nargs]\n args_T = map(overload.to_type, args_float)\n # Check each supported function.\n for f_drake, f_builtin in functions:\n if not overload.supports(f_drake):\n continue\n debug_print(\n \"- Functions: \", qualname(f_drake), qualname(f_builtin))\n y_builtin = f_builtin(*args_float)\n y_float = f_drake(*args_float)\n debug_print(\" - - Float Eval:\", repr(y_builtin), repr(y_float))\n self.assertEquals(y_float, y_builtin)\n self.assertIsInstance(y_float, float)\n # Test method current overload, and ensure value is accurate.\n y_T = f_drake(*args_T)\n y_T_float = overload.to_float(y_T)\n debug_print(\" - - Overload Eval:\", repr(y_T), repr(y_T_float))\n self.assertIsInstance(y_T, overload.T)\n # - Ensure the translated value is accurate.\n self.assertEquals(y_T_float, y_float)\n\n debug_print(\"\\n\\nOverload: \", qualname(type(overload)))\n float_overload = FloatOverloads()\n # Check each number of arguments.\n debug_print(\"Unary:\")\n check_eval(unary, 1)\n debug_print(\"Binary:\")\n check_eval(binary, 2)\n\n def _check_overloads(self, order):\n for overload_cls in order:\n self._check_overload(overload_cls())\n\n def test_overloads(self):\n # Each of these orders implies the relevant module is imported in this\n # test, in the order specified. This is done to guarantee that the\n # cross-module overloading does not affect functionality.\n orders = [\n (FloatOverloads,),\n (SymbolicOverloads,),\n (AutoDiffOverloads,),\n (AutoDiffOverloads, SymbolicOverloads),\n (SymbolicOverloads, AutoDiffOverloads),\n ]\n # At present, the `pybind11` modules appear not to be destroyed, even\n # when we try to completely dergister them and garbage collect.\n # To keep this test self-contained, we will just reinvoke this test\n # with the desired order so we can control which modules get imported.\n if len(sys.argv) == 1:\n # We have arrived here from a direct call. Call the specified\n # ordering.\n for i in range(len(orders)):\n args = [sys.executable, sys.argv[0], str(i)]\n subprocess.check_call(args)\n else:\n self.assertEquals(len(sys.argv), 2)\n i = int(sys.argv[1])\n self._check_overloads(orders[i])\n","sub_path":"bindings/pydrake/test/math_overloads_test.py","file_name":"math_overloads_test.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"593485984","text":"import pytest\nimport sys, os\nimport torchvision\nsys.path.insert(0,\"../torchxrayvision/\")\nimport torchxrayvision as xrv\nimport shutil\n\nfile_path = os.path.abspath(os.path.dirname(__file__))\n \ndataset_classes = [xrv.datasets.NIH_Dataset,\n xrv.datasets.PC_Dataset,\n xrv.datasets.NIH_Google_Dataset,\n xrv.datasets.Openi_Dataset,\n xrv.datasets.CheX_Dataset,\n xrv.datasets.SIIM_Pneumothorax_Dataset,\n xrv.datasets.VinBrain_Dataset]\n\ntest_data_path = \"/tmp/testdata\"\ntest_png_img_file = os.path.join(file_path,\"00000001_000.png\")\ntest_jpg_img_file = os.path.join(file_path,\"16747_3_1.jpg\")\ntest_dcm_img_file = os.path.join(file_path,\"1.2.276.0.7230010.3.1.4.8323329.6904.1517875201.850819.dcm\")\n\ndef get_clazz_imgpath(clazz):\n return os.path.join(test_data_path, clazz.__name__)\n\ndef create_test_img(test_img_file, clazz, filename):\n imgpath = get_clazz_imgpath(clazz)\n os.makedirs(os.path.join(imgpath, os.path.dirname(filename)))\n shutil.copyfile(test_img_file, os.path.join(imgpath, filename))\n \n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef create_test_images(request):\n \n if os.path.exists(test_data_path):\n shutil.rmtree(test_data_path)\n \n # for nih dataset\n create_test_img(test_png_img_file, xrv.datasets.NIH_Dataset, \"00000001_000.png\")\n create_test_img(test_png_img_file, xrv.datasets.PC_Dataset, \"125374151943505747025890313053997514922_j5rk5q.png\")\n create_test_img(test_png_img_file, xrv.datasets.NIH_Google_Dataset, \"00000211_006.png\")\n create_test_img(test_png_img_file, xrv.datasets.Openi_Dataset, \"CXR10_IM-0002-1001.png\")\n create_test_img(test_jpg_img_file, xrv.datasets.CheX_Dataset, \"train/patient00004/study1/view1_frontal.jpg\")\n create_test_img(test_dcm_img_file, xrv.datasets.SIIM_Pneumothorax_Dataset, \"1.2.276.0.7230010.3.1.2.8323329.6904.1517875201.850818/1.2.276.0.7230010.3.1.3.8323329.6904.1517875201.850817/1.2.276.0.7230010.3.1.4.8323329.6904.1517875201.850819.dcm\")\n create_test_img(test_dcm_img_file, xrv.datasets.VinBrain_Dataset, \"000434271f63a053c4128a0ba6352c7f.dicom\")\n \n \n\n\ndef test_dataloader_basic(create_test_images):\n \n transform = torchvision.transforms.Compose([xrv.datasets.XRayCenterCrop(),\n xrv.datasets.XRayResizer(224)])\n \n for dataset_class in dataset_classes:\n dataset = dataset_class(imgpath=get_clazz_imgpath(dataset_class), transform=transform)\n \n sample = dataset[0]\n \n assert(\"img\" in sample)\n assert(\"lab\" in sample)\n assert(\"idx\" in sample)\n \n\ndef test_dataloader_merging():\n \n datasets = []\n for dataset_class in dataset_classes:\n dataset = dataset_class(imgpath=\".\")\n datasets.append(dataset)\n \n for dataset in datasets:\n xrv.datasets.relabel_dataset(xrv.datasets.default_pathologies, dataset)\n \n dd = xrv.datasets.MergeDataset(datasets)\n \n # also test alias\n dd = xrv.datasets.Merge_Dataset(datasets)\n \ndef test_dataloader_merging_dups():\n \n datasets = []\n for dataset_class in dataset_classes:\n dataset = dataset_class(imgpath=\".\")\n datasets.append(dataset)\n \n for dataset in datasets:\n xrv.datasets.relabel_dataset(xrv.datasets.default_pathologies, dataset)\n \n for dataset in datasets:\n dd = xrv.datasets.Merge_Dataset([dataset,dataset])\n \n #now merge merge datasets\n for dataset in datasets:\n dd = xrv.datasets.Merge_Dataset([dataset,dataset])\n dd = xrv.datasets.Merge_Dataset([dd,dd])\n\n# test that we catch incorrect pathology alignment\ndef test_dataloader_merging_incorrect_alignment():\n with pytest.raises(Exception) as excinfo:\n \n d_nih = xrv.datasets.NIH_Dataset(imgpath=\".\")\n d_pc = xrv.datasets.PC_Dataset(imgpath=\".\")\n\n dd = xrv.datasets.Merge_Dataset([d_nih, d_pc])\n \n assert \"incorrect pathology alignment\" in str(excinfo.value)\n \n \n with pytest.raises(Exception) as excinfo:\n \n d_nih = xrv.datasets.NIH_Dataset(imgpath=\".\")\n d_pc = xrv.datasets.PC_Dataset(imgpath=\".\")\n xrv.datasets.relabel_dataset(xrv.datasets.default_pathologies, d_nih)\n xrv.datasets.relabel_dataset(xrv.datasets.default_pathologies[:-1], d_pc)\n\n dd = xrv.datasets.Merge_Dataset([d_nih, d_pc])\n \n assert \"incorrect pathology alignment\" in str(excinfo.value)\n \n","sub_path":"tests/test_dataloaders.py","file_name":"test_dataloaders.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"201543757","text":"import logging\nimport numpy as np\nfrom functools import reduce\nfrom random_search import RandomSearch\nfrom solutions.solution import Solution\n\n\nclass PSO(RandomSearch):\n def __init__(self, problem_instance, random_state, swarm_size, social, cognitive, inertia):\n RandomSearch.__init__(self, problem_instance, random_state)\n self.swarm_size = swarm_size\n self.social = social\n self.cognitive = cognitive\n self.inertia = inertia\n\n def initialize(self):\n self.swarm = self._generate_random_valid_particles()\n self.best_solution = self._get_current_best_particle(self.swarm)\n\n def search(self, n_iterations, report=False, log=False, dplot=None):\n if dplot is not None:\n dplot.background_plot(self.problem_instance.search_space, self.problem_instance.fitness_function)\n\n def _iterative_plot():\n points = np.array([particle.representation for particle in self.swarm])\n points = np.insert(points, points.shape[0], values=self.best_solution.representation, axis=0)\n points = np.vstack((points[:, 0], points[:, 1]))\n z = np.array([particle.fitness for particle in self.swarm])\n z = np.insert(z, z.shape[0], values=self.best_solution.fitness)\n dplot.iterative_plot(points, z, self.best_solution.fitness)\n\n for iteration in range(n_iterations):\n self._update_position()\n [self.problem_instance.evaluate(particle) for particle in self.swarm]\n self._update_lBest()\n self._update_gBest()\n\n if report:\n self._verbose_reporter_inner(self.best_solution, iteration)\n\n if dplot is not None:\n _iterative_plot()\n\n def _update_gBest(self):\n self.best_solution = self._get_best(self.best_solution, self._get_current_best_particle(self.swarm))\n\n def _update_position(self):\n for particle in self.swarm:\n r1 = self._random_state.uniform(size=self.problem_instance.dimensionality)\n social_factor = np.multiply(np.multiply(self.social, r1),\n (np.subtract(self.best_solution.representation, particle.representation)))\n r2 = self._random_state.uniform(size=self.problem_instance.dimensionality)\n cognitive_factor = np.multiply(np.multiply(self.cognitive, r2),\n (np.subtract(particle.lBest_representation, particle.representation)))\n particle.velocity = np.add(np.multiply(self.inertia, particle.velocity),\n np.add(cognitive_factor, social_factor))\n particle.representation = np.add(particle.representation, particle.velocity)\n\n def _update_lBest(self):\n for particle in self.swarm:\n if self.problem_instance.minimization:\n if particle.fitness <= particle.lBest_fitness:\n particle.lBest_fitness = particle.fitness\n particle.lBest_representation = particle.representation.copy()\n else:\n if particle.fitness >= particle.lBest_fitness:\n particle.lBest_fitness = particle.fitness\n particle.lBest_representation = particle.representation.copy()\n\n def _generate_random_valid_particles(self):\n particles = np.array([self._generate_random_valid_solution()\n for _ in range(self.swarm_size)])\n # set lBest and initial velocity\n for particle_i in particles:\n particle_i.lBest_representation = particle_i.representation.copy()\n particle_i.lBest_fitness = particle_i.fitness\n particle_i.velocity = np.zeros(self.problem_instance.dimensionality)\n return particles\n\n def _get_current_best_particle(self, swarm):\n cBest_pointer = reduce(self._get_best, swarm)\n cBest = Solution(cBest_pointer .representation.copy())\n cBest.fitness = cBest_pointer .fitness\n cBest.valid = cBest_pointer .valid\n cBest.dimensionality = cBest_pointer .dimensionality\n\n return cBest","sub_path":"algorithms/pso.py","file_name":"pso.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"205623014","text":"import math\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\"\"\"\n1. Открыть страницу http://suninjuly.github.io/alert_accept.html\n2. Нажать на кнопку\n3. Принять confirm\n4. На новой странице решить капчу для роботов, чтобы получить число с ответом\nЕсли все сделано правильно и достаточно быстро \n(в этой задаче тоже есть ограничение по времени), вы увидите окно с числом. \n5. Отправьте полученное число в качестве ответа на это задание.\n\"\"\"\n\n\n\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\n\n\n# browser_default = webdriver.Firefox()\n# link_default = \"http://suninjuly.github.io/alert_accept.html\"\n# def main(browser=browser_default, link=link_default):\ndef main(browser, link):\n try:\n browser.get(link)\n\n # жмём кнопку\n browser.find_element(By.CSS_SELECTOR, \"[type='submit']\").click()\n time.sleep(1)\n # получаем alert\n alert = browser.switch_to.alert\n alert.accept()\n time.sleep(1)\n\n # считаем функцию и вводим в поле\n x = browser.find_element(By.ID, \"input_value\").text\n browser.find_element(By.ID, \"answer\").send_keys(calc(x))\n\n # жмём кнопку\n browser.find_element(By.CSS_SELECTOR, \"[type='submit']\").click()\n\n # получаем ответ из alert\n alert = browser.switch_to.alert\n text_alert = alert.text\n answer_value = text_alert[(text_alert.index(': ')) + 2:]\n time.sleep(1)\n alert.accept()\n\n finally:\n time.sleep(1)\n # browser.quit()\n\n return answer_value\n\n\n# print(main())\n","sub_path":"Chapter2/les3_4_accept_alert.py","file_name":"les3_4_accept_alert.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"610614892","text":"\"\"\"This illustrates multi-taper spectral density function estimation.\n\nReferences:\n\n[1] D. Thomson, \"Spectrum estimation and harmonic analysis,\" Proceedings of the\nIEEE, vol. 70, 1982.\n\n[2] D.J. Thomson, \"Jackknifing Multitaper Spectrum Estimates [Identifying\nvariances of complicated estimation procedures],\" IEEE Signal Processing\nMagazine, 2007, pp. 20-30.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as pp\nimport scipy.stats.distributions as dist\n\nimport nitime.algorithms as alg\nimport nitime.utils as utils\n\ndef dB(x, out=None):\n if out is None:\n return 10 * np.log10(x)\n else:\n np.log10(x, out)\n np.multiply(out, 10, out)\n\n### Log-to-dB conversion factor ###\nln2db = dB(np.e)\n\nN = 512\nimport os\nif os.path.exists('example_arrs.npz'):\n foo = np.load('example_arrs.npz')\n ar_seq = foo['arr_0']\n nz = foo['arr_1']\n alpha = foo['arr_2']\nelse:\n ar_seq, nz, alpha = utils.ar_generator(N=N, drop_transients=10)\n ar_seq -= ar_seq.mean()\n np.savez('example_arrs', ar_seq, nz, alpha)\n# --- True SDF\nfgrid, hz = alg.my_freqz(1.0, a=np.r_[1, -alpha], Nfreqs=N)\nsdf = (hz*hz.conj()).real\n# onesided spectrum, so double the power\nsdf[1:-1] *= 2\ndB(sdf, sdf)\n\n# --- Direct Spectral Estimator\nfreqs, d_sdf = alg.periodogram(ar_seq)\ndB(d_sdf, d_sdf)\n\n# --- Welch's Overlapping Periodogram Method via mlab\nmlab_sdf, mlab_freqs = pp.mlab.psd(ar_seq, NFFT=N)\nmlab_freqs *= (np.pi/mlab_freqs.max())\nmlab_sdf = mlab_sdf.squeeze()\ndB(mlab_sdf, mlab_sdf)\n\n\n### Taper Bandwidth Adjustments\nNW = 4\n\n# --- Regular Multitaper Estimate\nf, sdf_mt, nu = alg.multi_taper_psd(\n ar_seq, width=NW, adaptive=False, jackknife=False\n )\ndB(sdf_mt, sdf_mt)\n# OK.. grab the number of tapers used from here\nKmax = nu[0]/2\n\n# --- Adaptively Weighted Multitapter Estimate\n# -- Adaptive weighting from Thompson 1982, or Percival and Walden 1993\nf, adaptive_sdf_mt, nu = alg.multi_taper_psd(\n ar_seq, width=NW, adaptive=True, jackknife=False\n )\ndB(adaptive_sdf_mt, adaptive_sdf_mt)\n\n# --- Jack-knifed intervals for regular weighting-----------------------------\n# currently returns log-variance\n_, _, jk_var = alg.multi_taper_psd(\n ar_seq, width=NW, adaptive=False, jackknife=True\n )\n\n# the Jackknife mean is approximately distributed about the true log-sdf\n# as a Student's t distribution with variance jk_var ... but in\n# fact the jackknifed variance better describes the normal\n# multitaper estimator < have ref for this >\n\n# find 95% confidence limits from inverse of t-dist CDF\njk_p = (dist.t.ppf(.975, Kmax-1) * np.sqrt(jk_var)) * ln2db\n\njk_limits = ( sdf_mt - jk_p, sdf_mt + jk_p )\n\n# --- Jack-knifed intervals for adaptive weighting----------------------------\n_, _, adaptive_jk_var = alg.multi_taper_psd(\n ar_seq, width=NW, adaptive=True, jackknife=True\n )\n\n# find 95% confidence limits from inverse of t-dist CDF\njk_p = (dist.t.ppf(.975, Kmax-1)*np.sqrt(adaptive_jk_var)) * ln2db\n\nadaptive_jk_limits = ( adaptive_sdf_mt - jk_p, adaptive_sdf_mt + jk_p )\n\n# --- Hypothetical intervals with chi2(2Kmax) --------------------------------\n# from Percival and Walden eq 258\np975 = dist.chi2.ppf(.975, 2*Kmax)\np025 = dist.chi2.ppf(.025, 2*Kmax)\n\nl1 = ln2db * np.log(2*Kmax/p975)\nl2 = ln2db * np.log(2*Kmax/p025)\n\nhyp_limits = ( sdf_mt + l1, sdf_mt + l2 )\n\n# --- Hypothetical intervals with chi2(nu(f)) --------------------------------\n\n## p975 = dist.chi2.ppf(.975, nu_f)\n## p025 = dist.chi2.ppf(.025, nu_f)\n\n## l1 = ln2db * np.log(nu_f/p975)\n## l2 = ln2db * np.log(nu_f/p025)\n\n## adaptive_hyp_limits = ( adaptive_sdf_mt + l1, adaptive_sdf_mt + l2 )\n\n# --- Plotting ---------------------------------------------------------------\nax_limits = 2*sdf.min(), 1.25*sdf.max()\n\ndef plot_estimate(ax, f, sdf_ests, limits=None, elabels=()):\n ax.plot(f, sdf, 'c', label='True S(f)')\n if not elabels:\n elabels = ('',) * len(sdf_ests)\n colors = 'bgkmy'\n for e, l, c in zip(sdf_ests, elabels, colors):\n ax.plot(f, e, color=c, linewidth=2, label=l)\n\n if limits is not None:\n ax.fill_between(f, limits[0], y2=limits[1], color=(1,0,0,.3))\n ax.set_ylim(ax_limits)\n ax.legend()\n\nf = pp.figure()\nax = f.add_subplot(611)\nplot_estimate(ax, freqs, (d_sdf,), elabels=(\"Periodogram\",))\nax = f.add_subplot(612)\nplot_estimate(ax, mlab_freqs, (mlab_sdf,), elabels=(\"Welch's method\",))\nax = f.add_subplot(613)\nplot_estimate(ax, freqs, (sdf_mt,), hyp_limits,\n elabels=('MT with hypothetical 5% interval',))\nax = f.add_subplot(614)\nplot_estimate(ax, freqs, (sdf_mt,),\n jk_limits,\n elabels=('MT with JK 5% interval',))\nax = f.add_subplot(615)\n## plot_estimate(ax, freqs, (adaptive_sdf_mt,),\n## adaptive_hyp_limits,\n## elabels=('(a)MT with hypothetical 5% interval',))\n## ax = f.add_subplot(616)\nplot_estimate(ax, freqs, (adaptive_sdf_mt, ),\n adaptive_jk_limits,\n elabels=('(a)MT with JK 5% interval',))\nf.text(.5, .9, '%d Tapers'%Kmax)\npp.show()\n","sub_path":"doc/examples/multi_taper_sdf.py","file_name":"multi_taper_sdf.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"515082166","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport math\nimport collections\nfrom scipy.sparse import *\n\n\nclass Cube(object):\n\n def __init__(self, ranges, az, el, data, index):\n\n self.rmin = min(ranges)\n self.rmax = max(ranges)\n\n self.x, self.y, self.z = self.convert_into_cartesian(ranges, az, el)\n self.dimension = 1\n self.aggr_data = {}\n self.index = index\n self.data = data\n\n def convert_into_cartesian(self, ranges, az, el):\n tmp = []\n _x = []\n _y = []\n _z = []\n for i in xrange(len(ranges)):\n _x.append(ranges[i] * math.cos(math.radians(el[i])) * math.sin(math.radians(az[i])))\n _y.append(ranges[i] * math.cos(math.radians(el[i])) * math.cos(math.radians(az[i])))\n _z.append(ranges[i] * math.sin(math.radians(el[i])))\n return _x, _y, _z\n\n def set_dimension(self, dim):\n self.dimension = int(dim)\n\n def get_dimension(self):\n return self.dimension\n\n def get_x(self):\n return self.x\n\n def get_y(self):\n return self.y\n\n def get_z(self):\n return self.z\n\n def get_data(self):\n return self.aggr_data\n\n def get_rmin(self):\n return self.rmin\n\n def get_rmax(self):\n return self.rmax\n\n def get_data_range(self):\n output = {}\n #print self.aggr_data, len(self.aggr_data['1'])\n for k, v in self.aggr_data.iteritems():\n #print v\n tmp = {}\n for item, value in v.iteritems():\n xlst = []\n ylst = []\n zlst = []\n #print len(value)\n for unit in value:\n xlst.append(unit[0])\n ylst.append(unit[1])\n zlst.append(unit[2])\n x = float(sum(xlst)) / float(len(xlst))\n y = float(sum(ylst)) / float(len(ylst))\n z = float(sum(zlst)) / float(len(zlst))\n r = (math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(z, 2)))\n tmp[r] = value\n tmp = collections.OrderedDict(sorted(tmp.items())) \n output[k] = [tmp]\n output = collections.OrderedDict(sorted(output.items()))\n return output\n\n def aggregate(self, zfix=None):\n tmp = {}\n time = {}\n dim = self.dimension\n for i in xrange(len(self.data)):\n xindex = str(int(self.x[i] / dim))\n yindex = str(int(self.y[i] / dim))\n if zfix:\n zindex = str(int(self.z[i] / zfix))\n else:\n zindex = str(int(self.z[i] / dim))\n index = xindex + \".\" + yindex + \".\" + zindex\n #print index, dim, self.x[i], self.data[i]\n\n t_index = str(self.index[i])\n if t_index not in time:\n time[t_index] = {}\n\n #tmp_buffer = []\n if index in time[t_index]:\n time[t_index][index].append([self.x[i], self.y[i], self.z[i], self.data[i]])\n else:\n time[t_index][index] = {}\n time[t_index][index] = []\n time[t_index][index] = [[self.x[i], self.y[i], self.z[i], self.data[i]]]\n\n self.aggr_data = time\n\n def total_cubes(self):\n total = 0\n for key in self.aggr_data:\n total = total + len(self.aggr_data[key])\n return total\n\n","sub_path":"cubify/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"201885363","text":"import os\r\nfrom json import load\r\n\r\nfrom flask import render_template, request, url_for, jsonify\r\n\r\nfrom app import app\r\nfrom app.client.control import CtrlWrapper, Settings\r\n\r\nwith open('./app/client/settings.json', 'r') as json:\r\n default_settings = load(json)\r\nctrl = CtrlWrapper(default_settings)\r\n\r\n\r\n@app.after_request\r\ndef add_header(response):\r\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\r\n response.headers['Cache-Control'] = 'public, max-age=12'\r\n return response\r\n\r\n\r\n@app.route('/')\r\n@app.route('/control')\r\ndef control():\r\n if ctrl.running_bot:\r\n bot_state = 'online'\r\n else:\r\n bot_state = 'offline'\r\n return render_template('control.html', state=bot_state)\r\n\r\n\r\n@app.route('/settings', methods=['POST', 'GET'])\r\ndef settings():\r\n global ctrl\r\n if request.method == 'POST':\r\n action = request.get_json()['action']\r\n bot_settings = request.get_json()['config']\r\n if action == 'start':\r\n if ctrl.running_bot:\r\n configuration = Settings(\r\n bot_settings.get('START_MODE') or default_settings.get('START_MODE'),\r\n bot_settings.get('LOG_TO_FILE') or default_settings.get('LOG_TO_FILE'),\r\n bot_settings.get('LOG_TO_CONSOLE') or default_settings.get('LOG_TO_CONSOLE'),\r\n bot_settings.get('LOG_LEVEL_DEBUG') or default_settings.get('LOG_LEVEL_DEBUG'),\r\n bot_settings.get('LOG_REQUESTS_TO_SERVER') or default_settings.get('LOG_REQUESTS_TO_SERVER'),\r\n bot_settings.get('MULTIPLE_MODE') or default_settings.get('MULTIPLE_MODE'),\r\n bot_settings.get('INFINITY_MODE') or default_settings.get('INFINITY_MODE'),\r\n False,\r\n bot_settings.get('SIMPLIFIED_ALGORITHMS_MODE') or\r\n default_settings.get('SIMPLIFIED_ALGORITHMS_MODE'),\r\n )\r\n ctrl = CtrlWrapper(configuration)\r\n ctrl.start()\r\n elif action == 'stop':\r\n ctrl.stop_bot()\r\n return render_template('settings.html')\r\n\r\n\r\n@app.route('/state', methods=['POST'])\r\ndef state():\r\n global ctrl\r\n if ctrl.running_bot:\r\n bot_state = {'state': 'online'}\r\n else:\r\n bot_state = {'state': 'offline'}\r\n return jsonify(bot_state), 200\r\n\r\n\r\n@app.errorhandler(404)\r\ndef page_not_found(error):\r\n return '404'\r\n\r\n\r\n@app.context_processor\r\ndef override_url_for():\r\n return dict(url_for=dated_url_for)\r\n\r\n\r\ndef dated_url_for(endpoint, **values):\r\n if endpoint == 'static':\r\n filename = values.get('filename', None)\r\n if filename:\r\n file_path = os.path.join(app.root_path, endpoint, filename)\r\n values['q'] = int(os.stat(file_path).st_mtime)\r\n return url_for(endpoint, **values)\r\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"563217409","text":"from sklearn import metrics\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport scikitplot as skplt\nimport numpy as np\nfrom random import randint\nimport os\ndef podstawowe_statystyki(true_labels, pred_labels, klasy, nazwa_modelu):\n accuracy_dict={}\n accuracy_dict['nazwa modelu'] = (nazwa_modelu)\n accuracy_dict['Dokładność całkowita (Overall Accuracy)'] = metrics.accuracy_score(true_labels, pred_labels)\n accuracy_dict['Współczynnik Kappa']=metrics.cohen_kappa_score(true_labels, pred_labels)\n accuracy_dict['Precision']= metrics.precision_score(true_labels,pred_labels, average='macro')\n accuracy_dict['Recall'] = metrics.recall_score(true_labels, pred_labels, average='macro')\n statystki=pd.DataFrame.from_dict(accuracy_dict, 'index')\n print(statystki)\n path='statystyki_{0}.csv'.format(nazwa_modelu)\n if os.path.isfile(path):\n path='statystyki_{0}_{1}.csv'.format(nazwa_modelu, randint(1,1000))\n out_stat=statystki.to_csv(path, encoding='utf-8')\n return out_stat\n\ndef raport(true_labels, pred_labels, names, nazwa_modelu):\n '''\n names - nazwy klas w postaci listy\n '''\n print(nazwa_modelu)\n metryki=(metrics.classification_report(true_labels, pred_labels, target_names=names))\n path='statystyki_{0}.csv'.format(nazwa_modelu)\n if os.path.isfile(path):\n path='statystyki_%s_%d.csv' % (nazwa_modelu, (randint(1,1000)))\n with open(path, 'w') as plk:\n plk.writelines(metryki)\n return plk\n\n\ndef macierz_bledow(true_labels, pred_labels, naglowki, nazwa_modelu):\n\n macierz=metrics.confusion_matrix(true_labels, pred_labels)\n\n path='macierz_{0}.csv'.format(nazwa_modelu)\n df=pd.DataFrame(macierz, columns=naglowki)\n if os.path.isfile(path):\n path='statystyki_%s_%d.csv' %(nazwa_modelu, randint(1,1000))\n #np.savetxt(path.format(nazwa_modelu), macierz)\n out=df.to_csv(path)\n return out\n\n\ndef macierz_bledow_wykres(true_labels, pred_labels, liczba_klas, names, nazwa_modelu):\n '''\n names - nazwy klas w postaci listy\n '''\n confusion_mat = metrics.confusion_matrix(true_labels, pred_labels)\n fig, ax = plt.subplots(figsize=(liczba_klas, liczba_klas))\n hm=sns.heatmap(confusion_mat, annot=True, annot_kws={\"size\": 10}, fmt='d',\n cmap='YlOrRd',\n xticklabels=names, yticklabels=names)\n hm.tick_params(labelsize=6)\n plt.xticks(rotation=45.)\n plt.ylabel('Actual')\n plt.xlabel('Predicted')\n\n path='macierz_wykres_{0}.png'.format(nazwa_modelu)\n if os.path.isfile(path):\n path='macierz_wykres_%s_%d.png'%(nazwa_modelu, randint(1,1000))\n fig=hm.get_figure()\n wykres = fig.savefig(path.format(nazwa_modelu))\n return wykres\n\n\ndef learning_curve(clf, X_trening, y_trening, nazwa_modelu):\n y_trening_en=y_trening\n from scikitplot import estimators\n estimators.plot_learning_curve(clf, X_trening, y_trening_en)\n path='learning_curve_{0}.png'.format(nazwa_modelu)\n if os.path.isfile(path):\n path='learning_curve_%s_%d.png'%(nazwa_modelu, randint(1,1000))\n plot = plt.savefig(path.format(nazwa_modelu))\n return plot\n\ndef rozrzut_danych(X_trening, y_trening_en, nazwa_modelu, kanal_1, kanal_2):\n '''\n Rysuje wykres rozrzutu z pogrupowanymi danymi na klasy. Za kanal_1 i kanal_2 należy podstawić wybrane dwa kanały\n '''\n z = []\n path='rozrzut_danych.png'.format(nazwa_modelu)\n if os.path.isfile(path):\n path='rozrzut_danych_%s_%d.png'%(nazwa_modelu, randint(1,1000))\n\n for element in X_trening:\n z.append([element[kanal_1], element[kanal_2]])\n print(y_trening_en.dtype)\n z = np.array(z).astype('float')\n df = pd.DataFrame(dict(x=z[:, 0], y=z[:, 1], label=y_trening_en))\n fig, ax = plt.subplots()\n grouped = df.groupby('label')\n kolory = ['gold', 'blue', 'green', 'red', 'm', 'k', 'aqua', 'brown', 'coral', 'grey', 'pink','sienna', 'plum', 'tomato', 'wheat', 'khaki', 'cyan']\n klasy=np.unique(y_trening_en)\n ilosc_klas=(klasy.shape[0])\n col=kolory[:ilosc_klas]\n\n for key, group in grouped:\n group.plot(ax=ax, kind='scatter', x='x', y='y',color=col, legend=True)\n\n ax.legend()\n plt.xlabel('kanal 1')\n plt.ylabel('kanal 2')\n plt.savefig(path)\n ","sub_path":"statystyki.py","file_name":"statystyki.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"555528696","text":"'''\nURL: https://leetcode.com/problems/di-string-match/\n\nDifficulty: Easy\n\nDescription: DI String Match\n\nGiven a string S that only contains \"I\" (increase) or \"D\" (decrease), let N = S.length.\n\nReturn any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:\n\nIf S[i] == \"I\", then A[i] < A[i+1]\nIf S[i] == \"D\", then A[i] > A[i+1]\n \n\nExample 1:\n\nInput: \"IDID\"\nOutput: [0,4,1,3,2]\nExample 2:\n\nInput: \"III\"\nOutput: [0,1,2,3]\nExample 3:\n\nInput: \"DDI\"\nOutput: [3,2,0,1]\n \n\nNote:\n\n1 <= S.length <= 10000\nS only contains characters \"I\" or \"D\".\n\n'''\n\n\nclass Solution:\n def diStringMatch(self, S):\n output = []\n lower_limit = 0\n upper_limit = len(S)\n\n for ch in S:\n if ch == \"I\":\n output.append(lower_limit)\n lower_limit += 1\n elif ch == \"D\":\n output.append(upper_limit)\n upper_limit -= 1\n\n output.append(upper_limit)\n\n return output\n","sub_path":"0942 DI String Match.py","file_name":"0942 DI String Match.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"475906772","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"\", views.greet, name=\"greet\"),\n path(\"voight\", views.voight, name=\"voight\"),\n path(\"pals\", views.pals, name=\"pals\")\n\n]","sub_path":"CS50/Django/lecture3/hello/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"532592403","text":"import argparse\nimport sys\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nimport uuid\nfrom pathlib import Path\nfrom typing import Optional\n\nimport numpy as np\nimport trimesh\n\nSIMILARITY_TAG = b\"SIMILARITY:\"\nCURRENT_DIR = Path(__file__).parent\n\nGENERATED_FILES_NAMES = [\n \"all_q4_v1.8.art\",\n \"all_q8_v1.8.art\",\n \"all_q8_v1.8.cir\",\n \"all_q8_v1.8.ecc\",\n \"all_q8_v1.8.fd\",\n]\n\nOUTPUT_NAME_TEMPLATES = [\n \"{}_q4_v1.8.art\",\n \"{}_q8_v1.8.art\",\n \"{}_q8_v1.8.cir\",\n \"{}_q8_v1.8.ecc\",\n \"{}_q8_v1.8.fd\",\n]\n\n\ndef find_similarity_in_logs(logs: bytes) -> float:\n \"\"\"Get line from the logs where similarity is mentioned.\n\n Args:\n logs: Unprocessed logs from the docker container after a command was\n run.\n\n Returns:\n Similarity measure from the log.\n \"\"\"\n logs = logs.split()\n similarity_line: Optional[bytes] = None\n for index, line in enumerate(logs):\n if line.startswith(SIMILARITY_TAG):\n similarity_line = logs[index + 1]\n break\n return float(similarity_line)\n\n\nclass MeshEncoder:\n \"\"\"Class holding an object and preprocessing it using an external cmd.\"\"\"\n\n def __init__(self, vertices: np.ndarray, triangles: np.ndarray):\n \"\"\"Instantiate the class.\n\n It instantiates an empty, temporary folder that will hold any\n intermediate data necessary to calculate Light Field Distance.\n\n Args:\n vertices: np.ndarray of vertices consisting of 3 coordinates each.\n triangles: np.ndarray where each entry is a vector with 3 elements.\n Each element correspond to vertices that create a triangle.\n \"\"\"\n self.mesh = trimesh.Trimesh(vertices=vertices, faces=triangles)\n self.temp_dir_path = Path(tempfile.mkdtemp())\n self.file_name = uuid.uuid4()\n self.temp_path = self.temp_dir_path / \"{}.obj\".format(self.file_name)\n\n self.mesh.export(self.temp_path.as_posix())\n\n def get_path(self) -> str:\n \"\"\"Get path of the object.\n\n Commands require that an object is represented without any extension.\n\n Returns:\n Path to the temporary object created in the file system that\n holds the Wavefront OBJ data of the object.\n \"\"\"\n return self.temp_path.with_suffix(\"\").as_posix()\n\n def align_mesh(self):\n \"\"\"Create data of a 3D mesh to calculate Light Field Distance.\n\n It runs an external command that create intermediate files and moves\n these files to created temporary folder.\n\n Returns:\n None\n \"\"\"\n process = subprocess.Popen(\n [\"./3DAlignment\", self.temp_path.with_suffix(\"\").as_posix()],\n cwd=(CURRENT_DIR / \"Executable\").as_posix(),\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n\n output, err = process.communicate()\n if len(err) > 0:\n print(err)\n sys.exit(1)\n\n for file, out_file in zip(\n GENERATED_FILES_NAMES, OUTPUT_NAME_TEMPLATES\n ):\n shutil.move(\n os.path.join((CURRENT_DIR / \"Executable\").as_posix(), file),\n (\n self.temp_dir_path / out_file.format(self.file_name)\n ).as_posix(),\n )\n\n def __del__(self):\n shutil.rmtree(self.temp_dir_path.as_posix())\n\n\nclass LightFieldDistance:\n \"\"\"Class that allows to calculate light field distance.\n\n It supports representing objects in the Wavefront OBJ format.\n \"\"\"\n\n def __init__(self, verbose: bool = 0):\n \"\"\"Instantiate the class.\n\n Args:\n verbose: Whether to display processing information performed step\n by step.\n \"\"\"\n self.verbose = verbose\n\n def get_distance(\n self,\n vertices_1: np.ndarray,\n triangles_1: np.ndarray,\n vertices_2: np.ndarray,\n triangles_2: np.ndarray,\n ) -> float:\n \"\"\"Calculate LFD between two meshes.\n\n These objects are taken as meshes from the Wavefront OBJ format. Hence\n vertices represent coordinates as a matrix Nx3, while `triangles`\n connects these vertices. Each entry in the `triangles` is a 3 element\n vector consisting of indices to appropriate vertices.\n\n Args:\n vertices_1: np.ndarray of vertices of the first object.\n triangles_1: np.ndarray of indices to vertices corresponding\n to particular indices connecting and forming a triangle.\n vertices_2: np.ndarray of vertices of the second object.\n triangles_2: np.ndarray of indices to vertices corresponding\n to particular indices connecting and forming a triangle. This\n parameter is for the second object.\n\n Returns:\n Light Field Distance between `object_1` and `object_2`.\n \"\"\"\n mesh_1 = MeshEncoder(vertices_1, triangles_1)\n mesh_2 = MeshEncoder(vertices_2, triangles_2)\n\n if self.verbose:\n print(\"Aligning mesh 1 at {} ...\".format(mesh_1.get_path()))\n mesh_1.align_mesh()\n\n if self.verbose:\n print(\"Aligning mesh 2 at {} ...\".format(mesh_2.get_path()))\n mesh_2.align_mesh()\n\n if self.verbose:\n print(\"Calculating distances ...\")\n\n process = subprocess.Popen(\n [\"./Distance\", mesh_1.get_path(), mesh_2.get_path()],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n cwd=(CURRENT_DIR / \"Executable\").as_posix(),\n )\n\n output, err = process.communicate()\n lfd = find_similarity_in_logs(output)\n\n return lfd\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=(\n \"Script that generates score for two shapes saved in Wavefront \"\n \"OBJ format\"\n )\n )\n parser.add_argument(\n \"file1\",\n type=str,\n help=\"Path to the first *.obj file in Wavefront OBJ format\",\n )\n\n parser.add_argument(\n \"file2\",\n type=str,\n help=\"Path to the second *obj file in Wavefront OBJ format\",\n )\n\n args = parser.parse_args()\n\n lfd_calc = LightFieldDistance(verbose=True)\n\n mesh_1: trimesh.Trimesh = trimesh.load(args.file1)\n mesh_2: trimesh.Trimesh = trimesh.load(args.file2)\n\n lfd = lfd_calc.get_distance(\n mesh_1.vertices, mesh_1.faces, mesh_2.vertices, mesh_2.faces\n )\n print(\"LFD: {:.4f}\".format(lfd))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lfd/lfd.py","file_name":"lfd.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"106806770","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: /Users/robertbanagale/code/opensource/django-address/django-address/example_site/address/models.py\n# Compiled at: 2020-05-10 01:31:38\nimport logging, sys\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models.fields.related import ForeignObject\ntry:\n from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor\nexcept ImportError:\n from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor as ForwardManyToOneDescriptor\n\nlogger = logging.getLogger(__name__)\nif sys.version > '3':\n long = int\n basestring = (str, bytes)\n unicode = str\n__all__ = ['Country', 'State', 'Locality', 'Address', 'AddressField']\n\nclass InconsistentDictError(Exception):\n pass\n\n\ndef _to_python(value):\n raw = value.get('raw', '')\n country = value.get('country', '')\n country_code = value.get('country_code', '')\n state = value.get('state', '')\n state_code = value.get('state_code', '')\n locality = value.get('locality', '')\n sublocality = value.get('sublocality', '')\n postal_code = value.get('postal_code', '')\n street_number = value.get('street_number', '')\n route = value.get('route', '')\n formatted = value.get('formatted', '')\n latitude = value.get('latitude', None)\n longitude = value.get('longitude', None)\n if not raw:\n return\n else:\n if not locality and sublocality:\n locality = sublocality\n if (country or state or locality) and not (country and state and locality):\n raise InconsistentDictError\n try:\n country_obj = Country.objects.get(name=country)\n except Country.DoesNotExist:\n if country:\n if len(country_code) > Country._meta.get_field('code').max_length:\n if country_code != country:\n raise ValueError('Invalid country code (too long): %s' % country_code)\n country_code = ''\n country_obj = Country.objects.create(name=country, code=country_code)\n else:\n country_obj = None\n\n try:\n state_obj = State.objects.get(name=state, country=country_obj)\n except State.DoesNotExist:\n if state:\n if len(state_code) > State._meta.get_field('code').max_length:\n if state_code != state:\n raise ValueError('Invalid state code (too long): %s' % state_code)\n state_code = ''\n state_obj = State.objects.create(name=state, code=state_code, country=country_obj)\n else:\n state_obj = None\n\n try:\n locality_obj = Locality.objects.get(name=locality, postal_code=postal_code, state=state_obj)\n except Locality.DoesNotExist:\n if locality:\n locality_obj = Locality.objects.create(name=locality, postal_code=postal_code, state=state_obj)\n else:\n locality_obj = None\n\n try:\n if not (street_number or route or locality):\n address_obj = Address.objects.get(raw=raw)\n else:\n address_obj = Address.objects.get(street_number=street_number, route=route, locality=locality_obj)\n except Address.DoesNotExist:\n address_obj = Address(street_number=street_number, route=route, raw=raw, locality=locality_obj, formatted=formatted, latitude=latitude, longitude=longitude)\n if not address_obj.formatted:\n address_obj.formatted = unicode(address_obj)\n address_obj.save()\n\n return address_obj\n\n\ndef to_python(value):\n if value is None:\n return\n else:\n if isinstance(value, Address):\n return value\n if isinstance(value, (int, long)):\n return value\n if isinstance(value, basestring):\n obj = Address(raw=value)\n obj.save()\n return obj\n if isinstance(value, dict):\n try:\n return _to_python(value)\n except InconsistentDictError:\n return Address.objects.create(raw=value['raw'])\n\n raise ValidationError('Invalid address value.')\n return\n\n\nclass Country(models.Model):\n name = models.CharField(max_length=40, unique=True, blank=True)\n code = models.CharField(max_length=2, blank=True)\n\n class Meta:\n verbose_name_plural = 'Countries'\n ordering = ('name', )\n\n def __str__(self):\n return '%s' % (self.name or self.code)\n\n\nclass State(models.Model):\n name = models.CharField(max_length=165, blank=True)\n code = models.CharField(max_length=3, blank=True)\n country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='states')\n\n class Meta:\n unique_together = ('name', 'country')\n ordering = ('country', 'name')\n\n def __str__(self):\n txt = self.to_str()\n country = '%s' % self.country\n if country and txt:\n txt += ', '\n txt += country\n return txt\n\n def to_str(self):\n return '%s' % (self.name or self.code)\n\n\nclass Locality(models.Model):\n name = models.CharField(max_length=165, blank=True)\n postal_code = models.CharField(max_length=10, blank=True)\n state = models.ForeignKey(State, on_delete=models.CASCADE, related_name='localities')\n\n class Meta:\n verbose_name_plural = 'Localities'\n unique_together = ('name', 'postal_code', 'state')\n ordering = ('state', 'name')\n\n def __str__(self):\n txt = '%s' % self.name\n state = self.state.to_str() if self.state else ''\n if txt and state:\n txt += ', '\n txt += state\n if self.postal_code:\n txt += ' %s' % self.postal_code\n cntry = '%s' % (self.state.country if self.state and self.state.country else '')\n if cntry:\n txt += ', %s' % cntry\n return txt\n\n\nclass Address(models.Model):\n street_number = models.CharField(max_length=20, blank=True)\n route = models.CharField(max_length=100, blank=True)\n locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses', blank=True, null=True)\n raw = models.CharField(max_length=200)\n formatted = models.CharField(max_length=200, blank=True)\n latitude = models.FloatField(blank=True, null=True)\n longitude = models.FloatField(blank=True, null=True)\n\n class Meta:\n verbose_name_plural = 'Addresses'\n ordering = ('locality', 'route', 'street_number')\n\n def __str__(self):\n if self.formatted != '':\n txt = '%s' % self.formatted\n elif self.locality:\n txt = ''\n if self.street_number:\n txt = '%s' % self.street_number\n if self.route:\n if txt:\n txt += ' %s' % self.route\n locality = '%s' % self.locality\n if txt and locality:\n txt += ', '\n txt += locality\n else:\n txt = '%s' % self.raw\n return txt\n\n def clean(self):\n if not self.raw:\n raise ValidationError('Addresses may not have a blank `raw` field.')\n\n def as_dict(self):\n ad = dict(street_number=self.street_number, route=self.route, raw=self.raw, formatted=self.formatted, latitude=self.latitude if self.latitude else '', longitude=self.longitude if self.longitude else '')\n if self.locality:\n ad['locality'] = self.locality.name\n ad['postal_code'] = self.locality.postal_code\n if self.locality.state:\n ad['state'] = self.locality.state.name\n ad['state_code'] = self.locality.state.code\n if self.locality.state.country:\n ad['country'] = self.locality.state.country.name\n ad['country_code'] = self.locality.state.country.code\n return ad\n\n\nclass AddressDescriptor(ForwardManyToOneDescriptor):\n\n def __set__(self, inst, value):\n super(AddressDescriptor, self).__set__(inst, to_python(value))\n\n\nclass AddressField(models.ForeignKey):\n description = 'An address'\n\n def __init__(self, *args, **kwargs):\n kwargs['to'] = 'address.Address'\n kwargs['on_delete'] = models.CASCADE\n super(AddressField, self).__init__(*args, **kwargs)\n\n def contribute_to_class(self, cls, name, virtual_only=False):\n from address.compat import compat_contribute_to_class\n compat_contribute_to_class(self, cls, name, virtual_only)\n setattr(cls, self.name, AddressDescriptor(self))\n\n def formfield(self, **kwargs):\n from .forms import AddressField as AddressFormField\n defaults = dict(form_class=AddressFormField)\n defaults.update(kwargs)\n return super(AddressField, self).formfield(**defaults)","sub_path":"pycfiles/django_address-0.2.2-py3-none-any/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"124166310","text":"from django.conf.urls import url\nfrom django.urls import include\nfrom rest_framework.routers import DefaultRouter\nfrom network.rest import api\n\nrouter = DefaultRouter()\n\nrouter.register('car_outlet', api.CarOutletApiSet, base_name='caroutlet')\nrouter.register('car_outlet_place', api.CarOutletPlaceApiSet, base_name='caroutletplace')\n\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^service_city/$', api.ServiceCityList.as_view(), name='servicecity-list'),\n url(r'^service_city/(?P[0-9]+)/$',\n api.ServiceCityDetail.as_view(),\n name='servicecity-detail'),\n url(r'^service_area/$', api.ServiceAreaList.as_view(), name='servicearea-list'),\n url(r'^service_area/(?P[0-9]+)/$',\n api.ServiceAreaDetail.as_view(),\n name='servicearea-detail'),\n]\n","sub_path":"simplegit/zerocar-master/network/rest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"84151974","text":"# Configuration settings for controller\n\nSTART_LOCALLY = False # set to True to start all processes on localhost\n # set to False to start all processes across CSIL machines\nTYPE = \"release\" # can be replaced with debug\nNUM_GRIDS = 25\nNUM_ROBOT_CLIENTS = 10\n\n# Server settings\nGRID_RUN_COMMAND = \"GridServer/build/\" + TYPE + \"/grid.bin\"\nGRID_PORT = \"13337\" # for simplicity, every subsequent grid will use port +1\n\n# the controller will cd to antix Path + this directory and call \"make\":\nGRID_BUILD_DIR = \"GridServer/\"\nGRID_BUILD_COMMAND = \"make grid\"\n\n# Clock settings\nCLOCK_RUN_COMMAND = \"ClockServer/build/\" + TYPE + \"/clock.bin\"\nCLOCK_PORT = \"13437\" # for simplicity, every subseqent clock will use port +1\n\n# the controller will cd to antix Path + this directory and call \"make\":\nCLOCK_BUILD_DIR = \"ClockServer/\"\nCLOCK_BUILD_COMMAND = \"make clock\"\n\n# Controller Client settings\nCTRL_CLIENT_RUN_COMMAND = \"ControllerClient/build/\" + TYPE + \"/controller.bin\"\n\n# the controller will cd to antix Path + this directory and call \"make\":\nCTRL_CLIENT_BUILD_DIR = \"ControllerClient/\"\nCTRL_CLIENT_BUILD_COMMAND = \"make controller\"\n\n# Client settings\nROBOT_CLIENT_RUN_COMMAND = \"RobotClient/build/\" + TYPE + \"/robot.bin\"\n\n# the controller will cd to antix Path + this directory and call \"make\":\nROBOT_CLIENT_BUILD_DIR = \"RobotClient/\"\nROBOT_CLIENT_BUILD_COMMAND = \"make robot\"\n\n# Drawer settings\nDRAWER_RUN_COMMAND = \"Drawer/build/\" + TYPE + \"/drawer.bin\"\n\n# the controller will cd to antix Path + this directory and call \"make\":\nDRAWER_BUILD_DIR = \"Drawer/\"\nDRAWER_BUILD_COMMAND = \"make drawer\"\n\n# Computers\nCSIL_COMPUTERS = (\n 'amber',\n 'aqua',\n 'auburn',\n 'azure',\n 'beige',\n 'black',\n 'blue',\n 'brown',\n 'buff',\n 'carmine',\n 'cerise',\n 'cerulean',\n 'chartreuse',\n 'cinnabar',\n 'crimson',\n 'ecru',\n 'emerald',\n 'gray',\n 'green',\n #'khaki',\n 'magenta',\n 'maize',\n 'mauve',\n 'ochre',\n 'pink',\n 'puce',\n 'red',\n 'russet',\n 'scarlet',\n 'sienna',\n 'tan',\n 'taupe',\n 'teal',\n 'turquoise',\n 'vermillion',\n 'violet',\n 'white',\n 'yellow',\n 'apple',\n 'apricot',\n 'avocado',\n 'banana',\n 'blackberry',\n 'blueberry',\n 'breadfruit',\n 'cantelope',\n 'cherry',\n 'citron',\n 'coconut',\n 'cranberry',\n 'currant',\n 'durian',\n 'fig',\n 'granadilla',\n 'grape',\n 'guava',\n 'honeydew',\n 'jujube',\n 'kiwi',\n 'kumquat',\n 'mandarin',\n 'mango',\n 'maypop',\n 'medlar',\n 'melon',\n 'mulberry',\n 'nectarine',\n 'orange',\n 'papaya',\n 'peach',\n 'pear',\n 'pineapple',\n 'plum',\n 'pomelo',\n 'rambutan',\n 'salak',\n 'tamarind',\n 'tangerine',\n)\n","sub_path":"Controller/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"648441901","text":"#!/usr/bin/env python\n\n# from __future__ import print_function, division, absolute_import, unicode_literals\nfrom __future__ import print_function, division, absolute_import\nimport argparse\nimport json\nimport os.path\nimport sys\n\nHISTORY = \"./pairwise_history.json\"\n# pairwise_history.json is a dictionary with keys of ISO8601 timestamps\n# and value of a list of pair_lists\nCOWORKERS = \"./pairwise_coworkers.json\"\n# list of lists of mutual coworkers. If more than 2 people work together,\n# put them in the same list. All pairwise combinations will be created.\nNAMES = \"./pairwise_names.json\"\n# pairwise_names.json is a list of all the names in the rota\nRELEVANT_HISTORY = 8\n# RELEVANT_HISTORY controls how much recent history is used for ensuring\n# matches are not repeated. Set to zero (0) to ignore\n\n\ndef parse_cli(test_args=None):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--names\", default=NAMES,\n help=\"File for the list participant names\")\n parser.add_argument(\"member\", help=\"Member to add to names list\")\n if test_args is None:\n args = parser.parse_args()\n else:\n args = parser.parse_args(test_args)\n return args\n\n\ndef load_names(args):\n \"\"\"Loads the names from JSON\"\"\"\n # NAMES is a json document which is just a list of names\n if os.path.isfile(args.names):\n with open(args.names, 'r') as n:\n try:\n names = json.load(n)\n except:\n sys.exit(\"ERROR: {0} is invalid JSON\".format(args.names))\n else:\n names = []\n return names\n\n\ndef save_names(args, names):\n \"\"\"Saves the names to JSON\"\"\"\n # NAMES is a json document which is just a list of names\n with open(args.names, 'w') as n:\n try:\n json.dump(names, n, sort_keys=True, indent=4)\n except:\n sys.exit(\"ERROR! Failed to overwrite args.names\")\n\n\ndef main():\n args = parse_cli()\n names = load_names(args)\n if args.member in names:\n names.remove(args.member)\n else:\n sys.exit(\"ERROR: Could not find {0} in list of names\".format(args.member))\n save_names(args, names)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pairwise-remove-member.py","file_name":"pairwise-remove-member.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"476220649","text":"import csv\nimport sqlite3\n \nfrom flask import Flask, request, g\nfrom flask import render_template\n \nDATABASE = '/var/www/html/flaskapp/Wikipedia.db'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\ndef connect_to_database():\n return sqlite3.connect(app.config['DATABASE'])\n\ndef get_db():\n db = getattr(g, 'db', None)\n if db is None:\n db = g.db = connect_to_database()\n return db\n\n@app.teardown_appcontext\ndef close_connection(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\ndef execute_query(query, args=()):\n cur = get_db().execute(query, args)\n rows = cur.fetchall()\n cur.close()\n return rows\n\n@app.route(\"/viewdb\")\ndef viewdb():\n rows = execute_query(\"\"\"SELECT id, website FROM Wikipedia\"\"\")\n return '
'.join(str(row) for row in rows)\n\n@app.route('/')\ndef my_form():\n return render_template(\"my-form.html\")\n\n@app.route('/', methods=['POST'])\ndef my_form_post():\n id_in = request.form['text']\n rows = execute_query(\"\"\"SELECT * FROM Wikipedia WHERE id = ?\"\"\",\n [id_in.title()])\n return '
'.join(str(row) for row in rows)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"flaskapp-natl-park/flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"442745020","text":"__author__ = 'Benco'\nimport numpy as np\nimport operator\n\ndef createDataSet():\n group=np.array([[1.0,1.1],\n [1.0,1.0],\n [0,0],\n [0,0.1]])\n labels=['A','A','B','B']\n return group,labels\n","sub_path":"约会网站数据/SimpleExample.py","file_name":"SimpleExample.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"372300777","text":"import argparse\nfrom glob import glob\n\nimport tensorflow as tf\n\nfrom model import denoiser\nfrom utils import *\nimport os\nimport numpy as np\n\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--epoch', dest='epoch', type=int, default=50, help='# of epoch')\nparser.add_argument('--batch_size', dest='batch_size', type=int, default=16, help='# images in batch')\nparser.add_argument('--lr', dest='lr', type=float, default=0.0001, help='initial learning rate for adam')\nparser.add_argument('--use_gpu', dest='use_gpu', type=int, default=1, help='gpu flag, 1 for GPU and 0 for CPU')\nparser.add_argument('--is_color', dest='is_color', type=int, default=1, help='color flag, 1 for color image and 0 for grayscale image')\nparser.add_argument('--sigma', dest='sigma', type=int, default=20, help='noise level')\nparser.add_argument('--phase', dest='phase', default='train', help='train or test')\nparser.add_argument('--checkpoint_dir', dest='ckpt_dir', default='./checkpoint', help='models are saved here')\nparser.add_argument('--paras', dest='paras', default='model/color_20', help='load parameters from here')\nparser.add_argument('--train_path', dest='train_path', default='./data/color_img_clean_pats.npy', help='training file')\nparser.add_argument('--test_dir', dest='test_dir', default='./test', help='test sample are saved here')\nparser.add_argument('--test_path', dest='test_path', default='data/test_PHD/tennis/', help='dataset for testing')\nargs = parser.parse_args()\n\n\ndef denoiser_train(denoiser, lr):\n with load_data(filepath=args.train_path) as data:\n denoiser.train(data, batch_size=args.batch_size, ckpt_dir=args.ckpt_dir, epoch=args.epoch, lr=lr)\n\n\ndef denoiser_test(denoiser):\n denoiser.test(args.test_path, paras=args.paras, save_dir=args.test_dir)\n\n\ndef main(_):\n if args.phase == 'test':\n if not os.path.exists(args.test_dir):\n os.makedirs(args.test_dir)\n\n lr = args.lr * np.ones([args.epoch])\n lr[40:] = lr[0] / 10.0\n if args.use_gpu:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n print(\"GPU\\n\")\n config = tf.ConfigProto() \n config.gpu_options.allow_growth = True #\n with tf.Session(config=config) as sess:\n model = denoiser(sess, is_color=args.is_color,sigma=args.sigma,batch_size=args.batch_size)\n if args.phase == 'train':\n denoiser_train(model, lr=lr)\n elif args.phase == 'test':\n denoiser_test(model)\n else:\n print('[!]Unknown phase')\n exit(0)\n else:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n print(\"CPU\\n\")\n with tf.Session() as sess:\n model = denoiser(sess,is_color=args.is_color, sigma=args.sigma,batch_size=args.batch_size)\n if args.phase == 'train':\n denoiser_train(model, lr=lr)\n elif args.phase == 'test':\n denoiser_test(model)\n else:\n print('[!]Unknown phase')\n exit(0)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"307536922","text":"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# (system_id, gpu_name_from_driver, gpu_count)\nsystem_list = ([\n (\"R740_vT4x4\", \"GRID T4-16Q\", 4),\n (\"XE2420_T4x4\", \"Tesla T4\", 4),\n (\"DSS8440_T4x12\", \"Tesla T4\", 12),\n (\"R740_T4x4\", \"Tesla T4\", 4),\n (\"R7515_T4x4\", \"Tesla T4\", 4),\n (\"DSS8440_T4x16\", \"Tesla T4\", 16),\n (\"DSS8440_QuadroRTX8000x8\", \"Quadro RTX 8000\", 8),\n (\"DSS8440_QuadroRTX6000x10\", \"Quadro RTX 6000\", 10),\n (\"DSS8440_QuadroRTX8000x10\", \"Quadro RTX 8000\", 10),\n (\"R7525_A100x2\", \"A100-PCIE-40GB\", 2),\n (\"R7525_A100x3\", \"A100-PCIE-40GB\", 3),\n (\"R7525_QuadroRTX8000x3\", \"Quadro RTX 8000\", 3),\n])\n\n","sub_path":"closed/DellEMC/code/common/system_list.py","file_name":"system_list.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"422883002","text":"import unittest\nimport logging\nfrom parser.parser import Parser\nfrom graph.graph import graph_factory\nfrom graph.path import CandidatePathsFetcher\n\n\nclass TestPath(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n logging.basicConfig(level=logging.INFO)\n parser = Parser('../test_data', 'euro16_k2.txt')\n parser = parser.get_scenario(2)\n networkTopology = parser.networkTopology\n cls.graph = graph_factory(networkTopology)\n cls.candidate_path_fetcher = CandidatePathsFetcher(parser.candidatePaths,\n networkTopology.n_nodes,\n parser.pathsLengths)\n\n def test_correct_nr_of_candidates(self):\n self.assertEqual(2, TestPath.candidate_path_fetcher.candidate_paths.nr_of_candidates_for_each_node)\n\n def test_paths(self):\n expected = {(0, 1): [[0],\n [1, 6, 10]\n ]}\n fetch_candidates = TestPath.candidate_path_fetcher.fetch_candidates\n for key, value in expected.items():\n paths = TestPath.candidate_path_fetcher.fetch_candidates(key[0], key[1])\n for val, path in zip(value, paths):\n self.assertListEqual(val, path.edges)\n pass\n\n def test_indices(self):\n expected = {(0, 1): 0,\n (0, 2): 2,\n (0, 15): 28,\n (1, 0): 30,\n (1, 15): 58,\n (2, 3): 64}\n get_index = TestPath.candidate_path_fetcher._get_index\n for key, value in expected.items():\n self.assertEqual(value, get_index(key[0], key[1]))\n\n def test_lengths(self):\n expected = {(0, 1): [343, 791],\n (0, 15): [1255, 1633],\n (2, 3): [173, 961]}\n fetch_candidates = TestPath.candidate_path_fetcher.fetch_candidates\n for key, value in expected.items():\n paths = TestPath.candidate_path_fetcher.fetch_candidates(key[0], key[1])\n for val, path in zip(value, paths):\n self.assertEqual(val, path.length)\n\n def test_modulation(self):\n expected = {(0, 1): [4, 2],\n (0, 15): [2, 1],\n (2, 3): [4, 2]}\n fetch_candidates = TestPath.candidate_path_fetcher.fetch_candidates\n for key, value in expected.items():\n paths = TestPath.candidate_path_fetcher.fetch_candidates(key[0], key[1])\n for val, path in zip(value, paths):\n self.assertEqual(val, path.modulation_level)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"test/test_graph/test_path.py","file_name":"test_path.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"485097339","text":"def perfect_num(a,b):\n p=0\n for i in range(a,b+1):\n j=1\n while (j*j<=i):\n if(j*j==i):\n p=p+1\n j=j+1\n i=i+1\n return p\nm=int(input())\nn=int(input())\nprint(perfect_num(m,n))\n","sub_path":"Perfect sqre bw 2 numbers.py","file_name":"Perfect sqre bw 2 numbers.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"54912351","text":"from collections import defaultdict\nfrom sys import argv\n\nfrom inputoutput import inputoutput as io\n\nfrom knowledgerepr import fieldnetwork\nfrom modelstore.elasticstore import StoreHandler\nfrom ontomatch import glove_api\nfrom ontomatch import matcher_lib as matcherlib\nfrom ontomatch.matcher_lib import MatchingType\nfrom ontomatch.sem_prop_benchmarking import write_matchings_to, compute_pr_matchings, read\nfrom ontomatch.ss_api import SSAPI\n\n\ndef generate_matchings(network, store_client, om, path_to_results):\n\n l7_matchings = matcherlib.find_hierarchy_content_fuzzy(om.kr_handlers, store_client)\n write_matchings_to(path_to_results + 'l7', l7_matchings)\n\n l4_matchings_01 = matcherlib.find_relation_class_name_matchings(network, om.kr_handlers,\n minhash_sim_threshold=0.1)\n write_matchings_to(path_to_results + 'l4', l4_matchings_01)\n\n l5_matchings_01 = matcherlib.find_relation_class_attr_name_matching(network, om.kr_handlers,\n minhash_sim_threshold=0.1)\n write_matchings_to(path_to_results + 'l5', l5_matchings_01)\n\n l42_matchings_05, neg_l42_matchings_02 = matcherlib.find_relation_class_name_sem_matchings(network, om.kr_handlers,\n sem_sim_threshold=0.5,\n negative_signal_threshold=0.1,\n add_exact_matches=False,\n penalize_unknown_word=True)\n write_matchings_to(path_to_results + 'l42', l42_matchings_05)\n write_matchings_to(path_to_results + 'neg_l42', neg_l42_matchings_02)\n\n l52_matchings_05, neg_l52_matchings_02 = matcherlib.find_relation_class_attr_name_sem_matchings(network, om.kr_handlers,\n semantic_sim_threshold=0.5,\n negative_signal_threshold=0.1,\n add_exact_matches=False,\n penalize_unknown_word=True)\n write_matchings_to(path_to_results + 'l52', l52_matchings_05)\n write_matchings_to(path_to_results + 'neg_l52', neg_l52_matchings_02)\n\n l6_matchings_02_1, table_groups = matcherlib.find_sem_coh_matchings(network, om.kr_handlers,\n sem_sim_threshold=0.2,\n group_size_cutoff=1)\n write_matchings_to(path_to_results + 'l6', l6_matchings_02_1)\n\n\ndef list_from_dict(combined):\n l = []\n for k, v in combined.items():\n matchings = v.get_matchings()\n for el in matchings:\n l.append(el)\n return l\n\n\ndef combine_matchings(l4, l5, l6, l42, l52, nl42, nl52, l7, ground_truth_matchings, om, cutting_ratio=0.8,\n summary_threshold=1):\n print(\"Started computation ... \")\n l4_dict = dict()\n for matching in l4:\n l4_dict[matching] = 1\n total_cancelled = 0\n for m in nl42:\n if m in l4_dict:\n total_cancelled += 1\n l4.remove(m)\n\n l5_dict = dict()\n for matching in l5:\n l5_dict[matching] = 1\n total_cancelled = 0\n for m in nl52:\n if m in l5_dict:\n total_cancelled += 1\n l5.remove(m)\n\n l6_dict = dict()\n for matching in l6:\n l6_dict[matching] = 1\n\n # curate l42 with l6\n removed_l42 = 0\n for m in l42:\n if m not in l6_dict:\n removed_l42 += 1\n l42.remove(m)\n print(\"rem-l42: \" + str(removed_l42))\n\n # curate l52 with l6\n # (('chemical', 'activity_stds_lookup', 'std_act_id'), ('efo', 'Metabolomic Profiling'))\n # (('chemical', 'activity_stds_lookup', '_'), ('efo', 'Experimental Factor'))\n removed_l52 = 0\n for m in l52:\n db, relation, attr = m[0]\n el = ((db, relation, '_'), m[1])\n if el not in l6_dict:\n removed_l52 += 1\n l52.remove(m)\n print(\"rem-l52: \" + str(removed_l52))\n\n all_matchings = defaultdict(list)\n all_matchings[MatchingType.L4_CLASSNAME_RELATIONNAME_SYN] = l4\n all_matchings[MatchingType.L5_CLASSNAME_ATTRNAME_SYN] = l5\n all_matchings[MatchingType.L42_CLASSNAME_RELATIONNAME_SEM] = l42\n all_matchings[MatchingType.L52_CLASSNAME_ATTRNAME_SEM] = l52\n all_matchings[MatchingType.L7_CLASSNAME_ATTRNAME_FUZZY] = l7\n\n combined = matcherlib.combine_matchings(all_matchings)\n combined_list = list_from_dict(combined)\n\n print(\"StructS ... \")\n combined_sum = matcherlib.summarize_matchings_to_ancestor(om, combined_list,\n threshold_to_summarize=summary_threshold,\n summary_ratio=cutting_ratio)\n precision_sum, recall_sum = compute_pr_matchings(ground_truth_matchings, combined_sum)\n print(\"Precision: {}\\nRecall: {}\".format(precision_sum, recall_sum))\n\n return precision_sum, recall_sum\n\n\ndef combine_and_report_results(om, path_to_raw_data, path_to_ground_truth_file):\n\n # Getting ground truth\n with open(path_to_ground_truth_file, 'r') as gt:\n ground_truth_matchings_strings = gt.readlines()\n\n def parse_strings(list_of_strings):\n # format is: db %%% table %%% attr ==>> onto %%% class_name %%% list_of_matchers\n matchings = []\n for l in list_of_strings:\n tokens = l.split(\"==>>\")\n sch = tokens[0]\n cla = tokens[1]\n sch_tokens = sch.split(\"%%%\")\n sch_tokens = [t.strip() for t in sch_tokens]\n cla_tokens = cla.split(\"%%%\")\n cla_tokens = [t.strip() for t in cla_tokens]\n matching_format = (((sch_tokens[0], sch_tokens[1], sch_tokens[2]), (cla_tokens[0], cla_tokens[1])))\n matchings.append(matching_format)\n return matchings\n\n ground_truth_matchings = parse_strings(ground_truth_matchings_strings)\n\n neg_l42 = read(path_to_raw_data + \"neg_l42\")\n neg_l52 = read(path_to_raw_data + \"neg_l52\")\n l6 = read(path_to_raw_data + \"l6\")\n l42 = read(path_to_raw_data + \"l42\")\n l52 = read(path_to_raw_data + \"l52\")\n l4 = read(path_to_raw_data + \"l4\")\n l5 = read(path_to_raw_data + \"l5\")\n l7 = read(path_to_raw_data + \"l7\")\n\n precision, recall = combine_matchings(l4, l5, l6, l42, l52, neg_l42, neg_l52, l7, ground_truth_matchings, om)\n return precision, recall\n\n\nif __name__ == \"__main__\":\n \"\"\"\n argv[1] - path to serialized model\n argv[2] - ontology name\n argv[3] - path to ontology\n argv[4] - path to semantic model\n argv[5] - path to output folder for generating the matchings\n argv[6] - path to gold standard\n \n Example: python run_semprop models/chembl22/ efo cache_onto/efo.pkl glove/glove.6B.100d.txt raw/ gold_standard\n \"\"\"\n\n if len(argv) < 6:\n raise RuntimeError(\"Not enough arguments\\nUsage: \" +\n \"python run_semprop path_to_serialized_model onto_name path_to_ontology path_to_sem_model\" +\n \"path_to_results path_to_gold_standard\")\n\n path_to_serialized_model = argv[1]\n onto_name = argv[2]\n path_to_ontology = argv[3]\n path_to_sem_model = argv[4]\n path_to_results = argv[5]\n path_to_gold_standard = argv[6]\n\n # Deserialize model\n network = fieldnetwork.deserialize_network(path_to_serialized_model)\n # Create client\n store_client = StoreHandler()\n\n # Load glove model\n print(\"Loading language model...\")\n glove_api.load_model(path_to_sem_model)\n print(\"Loading language model...OK\")\n\n # Retrieve indexes\n schema_sim_index = io.deserialize_object(path_to_serialized_model + 'schema_sim_index.pkl')\n content_sim_index = io.deserialize_object(path_to_serialized_model + 'content_sim_index.pkl')\n\n # Create ontomatch api\n om = SSAPI(network, store_client, schema_sim_index, content_sim_index)\n # Load parsed ontology\n om.add_krs([(onto_name, path_to_ontology)], parsed=True)\n\n # # Build content sim\n om.priv_build_content_sim(0.6)\n\n print(\"Benchmarking matchers and linkers\")\n generate_matchings(network, store_client, om, path_to_results)\n precision, recall = combine_and_report_results(om, path_to_results, path_to_gold_standard)\n print(\"F1-score: {}\".format(2 * precision * recall / (precision + recall)))\n","sub_path":"run_semprop.py","file_name":"run_semprop.py","file_ext":"py","file_size_in_byte":9019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"622959569","text":"#!/usr/bin/env python\n\n## Copyright 2018-2020 Intel Corporation\n## SPDX-License-Identifier: Apache-2.0\n\nimport os\n\nfrom config import *\nfrom util import *\nfrom dataset import *\nfrom image import *\nfrom color import *\n\n# Transforms a feature image to another feature type\ndef transform_image(image, input_feature, output_feature, exposure=1.):\n if input_feature == 'hdr':\n image *= exposure\n if output_feature in {'ldr', None}:\n image = tonemap(image)\n if not output_feature:\n # Transform to sRGB\n if input_feature in {'hdr', 'ldr', 'alb'}:\n image = srgb_forward(image)\n elif input_feature == 'nrm':\n # Transform [-1, 1] -> [0, 1]\n image = image * 0.5 + 0.5\n return image\n\ndef main():\n # Parse the command line arguments\n cfg = parse_args(description='Converts a feature image to a different image format.')\n\n # Load the input image\n image = load_image(cfg.input, num_channels=3)\n\n # Load metadata for the image if it exists\n tonemap_exposure = cfg.exposure\n metadata = load_image_metadata(cfg.input)\n if metadata:\n tonemap_exposure = metadata['exposure']\n\n # Convert the image to tensor\n image = to_tensor(image).unsqueeze(0)\n\n # Transform the image\n input_feature = get_image_feature(cfg.input)\n output_feature = get_image_feature(cfg.output)\n image = transform_image(image, input_feature, output_feature, tonemap_exposure)\n\n # Save the image\n save_image(cfg.output, to_numpy(image))\n\nif __name__ == '__main__':\n main()","sub_path":"training/convert_image.py","file_name":"convert_image.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"443709770","text":"#!/usr/bin/env python3\nimport argparse\nimport sys\nimport codecs\nif sys.version_info[0] == 2:\n from itertools import izip\nelse:\n izip = zip\nfrom collections import defaultdict as dd\nimport re\nimport os.path\nimport gzip\nimport unicodedata as ud\nscriptdir = os.path.dirname(os.path.abspath(__file__))\n\n\nreader = codecs.getreader('utf8')\nwriter = codecs.getwriter('utf8')\n\n\ndef prepfile(fh, code):\n ret = gzip.open(fh.name, code if code.endswith(\"t\") else code+\"t\") if fh.name.endswith(\".gz\") else fh\n if sys.version_info[0] == 2:\n if code.startswith('r'):\n ret = reader(fh)\n elif code.startswith('w'):\n ret = writer(fh)\n else:\n sys.stderr.write(\"I didn't understand code \"+code+\"\\n\")\n sys.exit(1)\n return ret\n\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"nfc normalization of data\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--infile\", \"-i\", nargs='?', type=argparse.FileType('rb'), default=sys.stdin, help=\"input file\")\n parser.add_argument(\"--outfile\", \"-o\", nargs='?', type=argparse.FileType('w'), default=sys.stdout, help=\"output file\")\n\n\n\n try:\n args = parser.parse_args()\n except IOError as msg:\n parser.error(str(msg))\n\n infile = prepfile(args.infile, 'r')\n outfile = prepfile(args.outfile, 'w')\n\n errcount=0\n for line in infile:\n try:\n outfile.write(ud.normalize('NFKC', line.decode('utf-8')))\n except UnicodeDecodeError:\n errcount+=1\n continue\n if errcount>0:\n sys.stderr.write(\"{} lines skipped for unicode errors\\n\".format(errcount))\nif __name__ == '__main__':\n main()\n\n","sub_path":"nfkc.py","file_name":"nfkc.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"338259544","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 11 16:26:29 2014\n\n@author: Jordan\n\"\"\"\n\nimport csv\nfrom numpy.linalg import norm\nfrom scipy import *\nfrom pylab import plot, show, legend,xlim,ylim,savefig,title,xlabel,ylabel,clf, loglog\nfrom Hamil import *\nfrom os import listdir\n\ndef copyarraytoC(a):\n n = len(a)\n b = mallocPy(n)\n for i in range(n):\n writetomem(b,i,a[i])\n return b\n \ndef copyarrayfromC(a,n):\n b = [0]*n\n for i in range(n):\n b[i] = readfrommem(a,i)\n \n return b\n \ndef dambreaksmooth(x,x0,base,eta0,diffuse,dx):\n from numpy import tanh\n n = len(x)\n h = zeros(n)\n u = zeros(n)\n \n for i in range(n):\n h[i] = base + 0.5*eta0*(1 + tanh(diffuse*(x0 - abs(x[i]))))\n return h,u \n \ndef makevar(sx,ex,dx,st,et,dt): \n x = arange(sx, ex, dx)\n t = arange(st, et, dt)\n \n return x,t \n\ndxw = \"3\"\nwdirord = \"o1\"\nwdatadir = \"../../../../data/raw/bigsmoothtargetted/\" +wdirord +\"/\"\n\n\ndxws = listdir(wdatadir)\ndxws.sort(key=int)\nEvals = []\n\nsdir1 = \"../../../../data/postprocessing/dbEnergy/\"\nif not os.path.exists(sdir1):\n os.makedirs(sdir1)\n\ns = sdir1 + \"Evalsinitial.txt\"\nwith open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n writefile2.writerow(['dx' ,'beta','Eval']) \n\nfor dxw in dxws:\n wdatadirn = wdatadir + dxw + \"/\" \n nums = listdir(wdatadirn)\n nums.sort(key=int)\n for k in nums:\n wdir = wdatadirn + str(k) + \"/\" \n sdir = \"../../../../data/postprocessing/dbEnergy/\" + wdirord+ \"/\" + dxw + \"/\" + str(k) + \"/\"\n #if not os.path.exists(sdir):\n # os.makedirs(sdir) \n \n s = wdir + \"outlast.txt\"\n with open(s,'r') as file1:\n lines = file1.readlines()\n rl = lines[1].split(\",\")\n dx = float(rl[0])\n dt = float(rl[1])\n beta = float(rl[7])\n \n l = 0.01\n dt = l*dx\n startx = 0.0\n endx = 1000.0 + dx\n startt = 0.0\n endt = 30.0+(dt*0.9) \n g = 9.81\n \n x,t = makevar(startx,endx,dx,startt,endt,dt)\n n = len(x)\n \n bot = 0.0\n hf = 1.8\n hl = 1.0\n base = hl\n eta0 = hf - hl\n x0 = 500\n diffuse = beta\n \n niBC = 3 \n h,u= dambreaksmooth(x,x0,base,eta0,diffuse,dx) \n xbeg = arange(startx - niBC*dx,startx,dx)\n xend = arange(endx + dx,endx + (niBC+1)*dx) \n hbeg = h[0]*ones(niBC)\n hend = h[-1]*ones(niBC)\n ubeg = u[0]*ones(niBC)\n uend = u[-1]*ones(niBC)\n xbc = concatenate([xbeg,array(x),xend])\n hbc = concatenate([hbeg,array(h),hend])\n ubc = concatenate([ubeg,array(u),uend])\n \n xbc_c = copyarraytoC(xbc)\n hbc_c = copyarraytoC(hbc)\n ubc_c = copyarraytoC(ubc)\n \n Eval = HankEnergyall(xbc_c,hbc_c,ubc_c,g,n + 2*niBC,niBC,dx)\n Evals.append((Eval,wdirord,dxw,beta))\n \n s = sdir1 + \"Evalsinitial.txt\"\n with open(s,'a') as file2:\n writefile2 = csv.writer(file2, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n writefile2.writerow([str(dx) ,str(beta),str(Eval)]) \n \n ","sub_path":"CODE/postprocessing/makeup/dbsmoothenerg/dbinitalenergy.py","file_name":"dbinitalenergy.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"169531177","text":"class Solution(object):\n def readBinaryWatch(self, num):\n \"\"\"\n :type num: int\n :rtype: List[str]\n \"\"\"\n\n light_num = 10\n self.res = []\n\n def dfs(start, light_left, h, m):\n if light_left == 0:\n if h <= 11 and m <= 59:\n self.res.append(str(h) + \":\" + \"%02d\" % m)\n return\n\n for i in range(start, light_num - light_left + 2):\n if i <= 4:\n dfs(i + 1, light_left - 1, h + (1 << (i - 1)), m)\n else:\n dfs(i + 1, light_left - 1, h, m + (1 << (i - 5)))\n\n dfs(1, num, 0, 0)\n\n return self.res\n\n\ns = Solution()\nprint(s.readBinaryWatch(1))\n","sub_path":"leetcode/401. Binary Watch.py","file_name":"401. Binary Watch.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"493328809","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef L(w1, w2):\r\n return w1**2 + w2**2\r\n\r\ndef dL(w):\r\n return np.array([2*w[0], 2*w[1]])\r\n\r\ndef gradient_descent(w_start, df, lr, epochs):\r\n w1_gd = []\r\n w2_gd = []\r\n w1_gd.append(w_start[0])\r\n w2_gd.append(w_start[1]) \r\n pre_w = w_start\r\n\r\n for i in range(epochs):\r\n w = pre_w - lr*df(pre_w)\r\n w1_gd.append(w[0])\r\n w2_gd.append(w[1])\r\n pre_w = w\r\n\r\n return np.array(w1_gd), np.array(w2_gd)\r\n\r\nw0 = np.array([2, 4])\r\nlr = 0.1\r\nepochs = 40\r\n\r\nx1 = np.arange(-5, 5, 0.05)\r\nx2 = np.arange(-5, 5, 0.05)\r\n\r\nw1, w2 = np.meshgrid(x1, x2)\r\n\r\nfig1, ax1 = plt.subplots()\r\nax1.contour(w1, w2, L(w1, w2), levels=np.logspace(-3, 3, 30), cmap='jet')\r\nmin_point = np.array([0., 0.])\r\nmin_point_ = min_point[:, np.newaxis]\r\nax1.plot(*min_point_, L(*min_point_), 'r*', markersize=10)\r\nax1.set_xlabel('w1')\r\nax1.set_ylabel('w2')\r\n\r\nw1_gd, w2_gd = gradient_descent(w0, dL, lr, epochs)\r\nw_gd = np.column_stack([w1_gd, w2_gd])\r\nprint(w_gd)\r\n\r\nax1.plot(w1_gd, w2_gd, 'bo')\r\nfor i in range(1, epochs+1):\r\n ax1.annotate('', xy=(w1_gd[i], w2_gd[i]), \r\n xytext=(w1_gd[i-1], w2_gd[i-1]),\r\n arrowprops={'arrowstyle': '->', 'color': 'r', 'lw': 1},\r\n va='center', ha='center')\r\nplt.show()\r\n\r\n\r\n","sub_path":"F9744/tf.keras/Ch04/Ch4_5_1a.py","file_name":"Ch4_5_1a.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"643540218","text":"from typing import Optional\n\nfrom django.db import connection\n\n\ndef execute_database_statement(sql: str, values: Optional[list] = None) -> int:\n \"\"\"Execute the SQL and return the UPDATE count\"\"\"\n with connection.cursor() as cursor:\n if values:\n cursor.execute(sql, values)\n else:\n cursor.execute(sql)\n rowcount = cursor.rowcount\n\n return rowcount\n\n\ndef update_awards(award_tuple: Optional[tuple] = None) -> int:\n \"\"\"\n Update Award records in `awards` using transaction data\n\n Awards can have one or more transactions. We maintain some information on\n the award model that needs to be updated as its transactions change.\n For example, an award's total obligated amount represents the summary of its\n transaction's obligated amounts. Another example is a series of fields\n (award type, awarding agency, etc.) that will always be set to the value of\n the Award's most recent transaction.\n \"\"\"\n\n _earliest_transaction_cte = str(\n \"txn_earliest AS ( \"\n \" SELECT DISTINCT ON (tn.award_id) \"\n \" tn.award_id, \"\n \" tn.id, \"\n \" tn.action_date, \"\n \" tn.description, \"\n \" tn.period_of_performance_start_date \"\n \" FROM transaction_normalized tn \"\n \" {} \"\n \" ORDER BY tn.award_id, tn.action_date ASC, tn.modification_number ASC, tn.transaction_unique_id ASC \"\n \")\"\n )\n _latest_transaction_cte = str(\n \"txn_latest AS ( \"\n \" SELECT DISTINCT ON (tn.award_id) \"\n \" tn.award_id, \"\n \" tn.id, \"\n \" tn.awarding_agency_id, \"\n \" tn.action_date, \"\n \" tn.funding_agency_id, \"\n \" tn.last_modified_date, \"\n \" tn.period_of_performance_current_end_date, \"\n \" tn.place_of_performance_id, \"\n \" tn.recipient_id, \"\n \" tn.type, \"\n \" tn.type_description, \"\n \" CASE WHEN tn.type IN ('A', 'B', 'C', 'D') THEN 'contract' \"\n \" WHEN tn.type IN ('02', '03', '04', '05') THEN 'grant' \"\n \" WHEN tn.type in ('06', '10') THEN 'direct payment' \"\n \" WHEN tn.type in ('07', '08') THEN 'loans' \"\n \" WHEN tn.type = '09' THEN 'insurance' \"\n \" WHEN tn.type = '11' THEN 'other' \"\n \" WHEN tn.type LIKE 'IDV%%' THEN 'idv' \"\n \" ELSE NULL END AS category \"\n \" FROM transaction_normalized tn \"\n \" {} \"\n \" ORDER BY tn.award_id, tn.action_date DESC, tn.modification_number DESC, tn.transaction_unique_id DESC \"\n \")\"\n )\n _aggregate_transaction_cte = str(\n \"txn_totals AS ( \"\n \" SELECT \"\n \" tn.award_id, \"\n \" SUM(tn.federal_action_obligation) AS total_obligation, \"\n \" SUM(tn.original_loan_subsidy_cost) AS total_subsidy_cost, \"\n \" SUM(tn.funding_amount) AS total_funding_amount, \"\n \" SUM(tn.face_value_loan_guarantee) AS total_loan_value, \"\n \" SUM(tn.non_federal_funding_amount) AS non_federal_funding_amount \"\n \" FROM transaction_normalized tn\"\n \" {} \"\n \" GROUP BY tn.award_id \"\n \")\"\n )\n\n if award_tuple:\n values = [award_tuple, award_tuple, award_tuple]\n earliest_transaction_cte = _earliest_transaction_cte.format(\" WHERE tn.award_id IN %s \")\n latest_transaction_cte = _latest_transaction_cte.format(\" WHERE tn.award_id IN %s \")\n aggregate_transaction_cte = _aggregate_transaction_cte.format(\" WHERE tn.award_id IN %s \")\n else:\n values = None\n earliest_transaction_cte = _earliest_transaction_cte.format(\"\")\n latest_transaction_cte = _latest_transaction_cte.format(\"\")\n aggregate_transaction_cte = _aggregate_transaction_cte.format(\"\")\n\n # construct a sql query that uses the common table expressions defined above\n # and joins each of them to their corresopnding award.\n # The joined data from the CTEs are used to update awards fields as appropriate\n _sql_update = str(\n \"WITH {}, {}, {} \"\n \"UPDATE awards a \"\n \" SET \"\n \" earliest_transaction_id = e.id, \"\n \" date_signed = e.action_date, \"\n \" description = e.description, \"\n \" period_of_performance_start_date = e.period_of_performance_start_date, \"\n \"\"\n \" latest_transaction_id = l.id, \"\n \" awarding_agency_id = l.awarding_agency_id, \"\n \" category = l.category, \"\n \" certified_date = l.action_date, \"\n \" funding_agency_id = l.funding_agency_id, \"\n \" last_modified_date = l.last_modified_date, \"\n \" period_of_performance_current_end_date = l.period_of_performance_current_end_date, \"\n \" place_of_performance_id = l.place_of_performance_id, \"\n \" recipient_id = l.recipient_id, \"\n \" type = l.type, \"\n \" type_description = l.type_description, \"\n \"\"\n \" non_federal_funding_amount = t.non_federal_funding_amount, \"\n \" total_funding_amount = t.total_funding_amount, \"\n \" total_loan_value = t.total_loan_value, \"\n \" total_obligation = t.total_obligation, \"\n \" total_subsidy_cost = t.total_subsidy_cost \"\n \"\"\n \" FROM txn_earliest e \"\n \" JOIN txn_latest l ON e.award_id = l.award_id \"\n \" JOIN txn_totals t ON e.award_id = t.award_id \"\n \" WHERE e.award_id = a.id \"\n )\n\n sql_update = _sql_update.format(earliest_transaction_cte, latest_transaction_cte, aggregate_transaction_cte)\n # We don't need to worry about this double counting awards, because if it's deleted in the first step it can't be updated!\n return prune_empty_awards(award_tuple) + execute_database_statement(sql_update, values)\n\n\ndef prune_empty_awards(award_tuple: Optional[tuple] = None) -> int:\n _find_empty_awards_sql = str(\n \"SELECT a.id \"\n \"FROM awards a \"\n \"LEFT JOIN transaction_normalized tn \"\n \"ON tn.award_id = a.id \"\n \"WHERE tn IS NULL {}\"\n ).format(\" AND a.id IN %s \" if award_tuple else \"\")\n\n _modify_subawards_sql = \"UPDATE subaward SET award_id = null WHERE award_id IN ({});\".format(_find_empty_awards_sql)\n\n _modify_financial_accounts_sql = (\n \"UPDATE financial_accounts_by_awards \"\n \"SET award_id = null \"\n \"WHERE award_id IN ({});\".format(_find_empty_awards_sql)\n )\n\n _delete_parent_award_sql = \"DELETE FROM parent_award WHERE award_id in ({});\".format(_find_empty_awards_sql)\n\n _prune_empty_awards_sql = \"DELETE FROM awards WHERE id IN ({}) \".format(_find_empty_awards_sql)\n\n return execute_database_statement(\n _modify_subawards_sql + _modify_financial_accounts_sql + _delete_parent_award_sql + _prune_empty_awards_sql,\n [award_tuple, award_tuple, award_tuple, award_tuple],\n )\n\n\ndef update_assistance_awards(award_tuple: Optional[tuple] = None) -> int:\n _sql_update = str(\n \"WITH executive_comp AS ( \"\n \" SELECT DISTINCT ON (tn.award_id) \"\n \" tn.award_id, \"\n \" fabs.officer_1_amount, \"\n \" fabs.officer_1_name, \"\n \" fabs.officer_2_amount, \"\n \" fabs.officer_2_name, \"\n \" fabs.officer_3_amount, \"\n \" fabs.officer_3_name, \"\n \" fabs.officer_4_amount, \"\n \" fabs.officer_4_name, \"\n \" fabs.officer_5_amount, \"\n \" fabs.officer_5_name \"\n \" FROM transaction_normalized tn \"\n \" INNER JOIN transaction_fabs AS fabs ON tn.id = fabs.transaction_id \"\n \" WHERE fabs.officer_1_name IS NOT NULL {} \"\n \" ORDER BY tn.award_id, tn.action_date DESC, tn.modification_number DESC, tn.transaction_unique_id DESC \"\n \") \"\n \"UPDATE awards a \"\n \" SET \"\n \" officer_1_amount = ec.officer_1_amount, \"\n \" officer_1_name = ec.officer_1_name, \"\n \" officer_2_amount = ec.officer_2_amount, \"\n \" officer_2_name = ec.officer_2_name, \"\n \" officer_3_amount = ec.officer_3_amount, \"\n \" officer_3_name = ec.officer_3_name, \"\n \" officer_4_amount = ec.officer_4_amount, \"\n \" officer_4_name = ec.officer_4_name, \"\n \" officer_5_amount = ec.officer_5_amount, \"\n \" officer_5_name = ec.officer_5_name \"\n \" FROM executive_comp AS ec \"\n \" WHERE ec.award_id = a.id \"\n )\n\n if award_tuple:\n values = [award_tuple]\n sql_update = _sql_update.format(\"AND tn.award_id IN %s \")\n else:\n values = None\n sql_update = _sql_update.format(\"\")\n\n return execute_database_statement(sql_update, values)\n\n\ndef update_contract_awards(award_tuple: Optional[tuple] = None) -> int:\n \"\"\"Update contract-specific award data based on the info in child transactions.\"\"\"\n\n _aggregate_transaction_cte = str(\n \"txn_totals AS ( \"\n \" SELECT \"\n \" tn.award_id, \"\n \" SUM(CAST(tf.base_and_all_options_value AS double precision)) AS total_base_and_options_value, \"\n \" SUM(CAST(tf.base_exercised_options_val AS double precision)) AS base_exercised_options_val \"\n \" FROM transaction_normalized AS tn \"\n \" INNER JOIN transaction_fpds AS tf ON tn.id = tf.transaction_id \"\n \" {} \"\n \" GROUP BY tn.award_id \"\n \") \"\n )\n\n # Gather additional fpds fields such as agency_ids and types\n _extra_fpds_fields = str(\n \"extra_fpds_fields AS ( \"\n \" SELECT \"\n \" tn.award_id, \"\n \" CASE \"\n \" WHEN tf.pulled_from IS DISTINCT FROM 'IDV' THEN tf.contract_award_type \"\n \" WHEN tf.idv_type = 'B' AND tf.type_of_idc IS NOT NULL THEN CONCAT('IDV_B_', tf.type_of_idc::text) \"\n \" WHEN tf.idv_type = 'B' AND tf.type_of_idc IS NULL and \"\n \" tf.type_of_idc_description = 'INDEFINITE DELIVERY / REQUIREMENTS' THEN 'IDV_B_A' \"\n \" WHEN tf.idv_type = 'B' AND tf.type_of_idc IS NULL and \"\n \" tf.type_of_idc_description = 'INDEFINITE DELIVERY / INDEFINITE QUANTITY' THEN 'IDV_B_B' \"\n \" WHEN tf.idv_type = 'B' AND tf.type_of_idc IS NULL and \"\n \" tf.type_of_idc_description = 'INDEFINITE DELIVERY / DEFINITE QUANTITY' THEN 'IDV_B_C' \"\n \" ELSE CONCAT('IDV_', tf.idv_type::text) END AS type, \"\n \" CASE WHEN tf.pulled_from IS DISTINCT FROM 'IDV' THEN tf.contract_award_type_desc \"\n \" WHEN tf.idv_type = 'B' AND \"\n \" (tf.type_of_idc_description IS DISTINCT FROM NULL AND tf.type_of_idc_description <> 'NAN') \"\n \" THEN tf.type_of_idc_description \"\n \" WHEN tf.idv_type = 'B' THEN 'INDEFINITE DELIVERY CONTRACT' \"\n \" ELSE tf.idv_type_description END AS type_description, \"\n \" tf.agency_id, \"\n \" tf.referenced_idv_agency_iden \"\n \" FROM transaction_normalized AS tn \"\n \" INNER JOIN transaction_fpds AS tf ON tn.id = tf.transaction_id \"\n \" {}\"\n \")\"\n )\n\n _executive_comp_cte = str(\n \"executive_comp AS ( \"\n \" SELECT DISTINCT ON (tn.award_id) \"\n \" tn.award_id, \"\n \" fpds.officer_1_amount, \"\n \" fpds.officer_1_name, \"\n \" fpds.officer_2_amount, \"\n \" fpds.officer_2_name, \"\n \" fpds.officer_3_amount, \"\n \" fpds.officer_3_name, \"\n \" fpds.officer_4_amount, \"\n \" fpds.officer_4_name, \"\n \" fpds.officer_5_amount, \"\n \" fpds.officer_5_name \"\n \" FROM transaction_normalized tn \"\n \" INNER JOIN transaction_fpds AS fpds ON tn.id = fpds.transaction_id \"\n \" WHERE fpds.officer_1_name IS NOT NULL {} \"\n \" ORDER BY tn.award_id, tn.action_date DESC, tn.modification_number DESC, tn.transaction_unique_id DESC \"\n \") \"\n )\n\n if award_tuple:\n values = [award_tuple, award_tuple, award_tuple]\n aggregate_transaction_cte = _aggregate_transaction_cte.format(\" WHERE tn.award_id IN %s \")\n extra_fpds_fields = _extra_fpds_fields.format(\" WHERE tn.award_id IN %s \")\n executive_comp_cte = _executive_comp_cte.format(\" AND tn.award_id IN %s \")\n else:\n values = None\n aggregate_transaction_cte = _aggregate_transaction_cte.format(\"\")\n extra_fpds_fields = _extra_fpds_fields.format(\"\")\n executive_comp_cte = _executive_comp_cte.format(\"\")\n # construct a sql query that uses the latest txn contract common table expression above and joins it to the\n # corresponding award. that joined data is used to update awards fields as appropriate (currently, there's only one\n # trasnaction_contract field that trickles up and updates an award record: base_and_all_options_value)\n _sql_update = str(\n \"WITH {}, {}, {} \"\n \"UPDATE awards a \"\n \" SET \"\n \" base_and_all_options_value = t.total_base_and_options_value, \"\n \" base_exercised_options_val = t.base_exercised_options_val, \"\n \"\"\n \" type = eff.type, \"\n \" type_description = eff.type_description, \"\n \" fpds_agency_id = eff.agency_id, \"\n \" fpds_parent_agency_id = eff.referenced_idv_agency_iden, \"\n \"\"\n \" officer_1_amount = ec.officer_1_amount, \"\n \" officer_1_name = ec.officer_1_name, \"\n \" officer_2_amount = ec.officer_2_amount, \"\n \" officer_2_name = ec.officer_2_name, \"\n \" officer_3_amount = ec.officer_3_amount, \"\n \" officer_3_name = ec.officer_3_name, \"\n \" officer_4_amount = ec.officer_4_amount, \"\n \" officer_4_name = ec.officer_4_name, \"\n \" officer_5_amount = ec.officer_5_amount, \"\n \" officer_5_name = ec.officer_5_name \"\n \" FROM txn_totals AS t \"\n \" INNER JOIN extra_fpds_fields AS eff ON t.award_id = eff.award_id \"\n \" LEFT JOIN executive_comp AS ec ON t.award_id = ec.award_id \"\n \" WHERE t.award_id = a.id \"\n )\n\n sql_update = _sql_update.format(aggregate_transaction_cte, extra_fpds_fields, executive_comp_cte)\n return execute_database_statement(sql_update, values)\n\n\ndef update_award_subawards(award_tuple: Optional[tuple] = None) -> int:\n \"\"\"Updates awards' subaward counts and totals\"\"\"\n\n _sql_sub_totals = str(\n \"subaward_totals AS ( \"\n \" SELECT \"\n \" award_id, \"\n \" SUM(amount) AS total_subaward_amount, \"\n \" COUNT(*) AS subaward_count \"\n \" FROM subaward \"\n \" {} \"\n \" GROUP BY award_id\"\n \") \"\n )\n if award_tuple:\n values = [award_tuple]\n sql_sub_totals = _sql_sub_totals.format(\"WHERE award_id IN %s \")\n else:\n values = None\n sql_sub_totals = _sql_sub_totals.format(\"\")\n\n _sql_update = str(\n \"WITH {} \"\n \"UPDATE awards \"\n \" SET \"\n \" total_subaward_amount = subaward_totals.total_subaward_amount, \"\n \" subaward_count = subaward_totals.subaward_count \"\n \" FROM subaward_totals \"\n \" WHERE subaward_totals.award_id = id \"\n )\n\n sql_update = _sql_update.format(sql_sub_totals)\n return execute_database_statement(sql_update, values)\n","sub_path":"usaspending_api/etl/award_helpers.py","file_name":"award_helpers.py","file_ext":"py","file_size_in_byte":15168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}
+{"seq_id":"66191316","text":"#!/usr/bin/env python\n\nfrom optparse import OptionParser\nfrom os.path import expandvars\n\nparser = OptionParser()\nparser.add_option(\"--i3-file\")\nparser.add_option(\"--outfile\", default = \"tmp/read_out_hits.txt\")\n\n(options, args) = parser.parse_args()\n\ninput_file = options.i3_file\n\nfrom I3Tray import *\nfrom icecube import icetray, dataclasses, dataio, phys_services, clsim, sim_services\n\n# \n#