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 = \"\"\"\"\"\"\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