seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28552898211 | #-*-coding:utf-8-*-
import argparse
import pyspark
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import *
from generic_utils import execute_compute_stats
def extract_tbau_documento(spark):
columns = [
col("DOCU_DK").alias("DOAT_DOCU_DK"),
col("DOCU_NR_EXTERNO").alias("DOAT_DOCU_NR_EXTERNO"),
col("DOCU_NR_MP").alias("DOAT_DOCU_NR_MP"),
col("DOCU_DT_CADASTRO").alias("DOAT_DOCU_DT_CADASTRO"),
col("DOCU_DT_FATO").alias("DOAT_DOCU_DT_FATO"),
col("DOCU_ORGI_ORGA_DK_RESPONSAVEL").alias("DOAT_ORGI_DK_RESPONSAVEL"),
col("DOCU_ORGI_ORGA_DK_CARGA").alias("DOAT_ORGI_DK_CARGA"),
col("DOCU_ORGA_DK_ORIGEM").alias("DOAT_ORGA_DK_ORIGEM"),
col("DOCU_ORGE_ORGA_DK_DELEG_FATO").alias("DOAT_ORGE_DK_DELEG_FATO"),
col("DOCU_ORGE_ORGA_DK_DELEG_ORIGEM").alias("DOAT_ORGE_DK_ORIGEM"),
col("DOCU_ORGE_ORGA_DK_VARA").alias("DOAT_ORGE_DK_VARA"),
col("DOCU_NR_DISTRIBUICAO").alias("DOAT_DOCU_NR_DISTRIBUICAO"),
col("DOCU_DT_DISTRIBUICAO").alias("DOAT_DOCU_DT_DISTRIBUICAO"),
col("DOCU_IN_DOCUMENTO_ELETRONICO").alias("DOAT_DOCU_IN_DOC_ELETRONICO"),
col("DOCU_CLDC_DK").alias("DOAT_CLDC_DK"),
col("NISI_DS_NIVEL_SIGILO").alias("DOAT_NISI_DS_NIVEL_SIGILO"),
col("MATE_DESCRICAO").alias("DOAT_MATE_ATRIBUICAO_DOC"),
col("TPDC_SIGLA").alias("DOAT_TPDC_SIGLA_DOC"),
col("TPDC_DESCRICAO").alias("DOAT_TPDC_DS_DOCUMENTO"),
col("DOAT_ORGAO_RESPONSAVEL"),
col("DOAT_CRAAI_OR"),
col("DOAT_COMARCA_OR"),
col("DOAT_FORO_OR"),
col("DOAT_ORGAO_TP_OR"),
col("DOAT_ORGAO_A_E_OR"),
col("DOAT_JUIZO_UNICO_OR"),
col("DOAT_DT_INICIO_OR"),
col("DOAT_DT_FIM_OR"),
col("DOAT_DET_CRIACAO_OR"),
col("DOAT_ORGAO_CARGA"),
col("DOAT_CRAAI_CG"),
col("DOAT_COMARCA_CG"),
col("DOAT_ORGAO_TP_CG"),
col("DOAT_ORGAO_A_E_CG"),
col("DOAT_JUIZO_UNICO_CG"),
col("DOAT_DT_FIM_CG"),
col("DOAT_NM_ORGAO_EXTERNO"),
col("TPOE_DESCRICAO").alias("DOAT_TP_ORGAO_EXTERNO"),
col("DOAT_NM_DELEF_FATO"),
col("DOAT_NM_DELEG_ORIGEM"),
col("DOAT_NM_VARA"),
col("TPST_DS_TP_SITUACAO").alias("DOAT_TPST_DS_TP_SITUACAO"),
col("FSDC_DS_FASE").alias("DOAT_FSDC_DS_FASE"),
col("cod_mgp").alias("DOAT_CD_CLASSE"),
col("descricao").alias("DOAT_CLASSE"),
col("hierarquia").alias("DOAT_CLASSE_HIERARQUIA"),
col("DOAA_DT_ALTERACAO").alias("DOAT_DT_ALTERACAO"),
]
documento = spark.table("%s.mcpr_documento" % options["schema_exadata"]).\
filter("DOCU_DT_CANCELAMENTO IS NULL")
sigilo = spark.table("%s.mcpr_nivel_sigilo" % options["schema_exadata"])
materia = spark.table("%s.mprj_materia_mgp" % options["schema_exadata"])
tipo_doc = spark.table("%s.mcpr_tp_documento" % options["schema_exadata"])
alteracao = spark.table("%s.mcpr_documento_alteracao" % options["schema_exadata"])
sit_doc = spark.table("%s.mcpr_tp_situacao_documento" % options["schema_exadata"])
fase_doc = spark.table("%s.mcpr_fases_documento" % options["schema_exadata"])
orgao_origem = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([
col("ORGE_ORGA_DK").alias("ORG_EXT_ORIGEM_DK"),
col("ORGE_TPOE_DK").alias("ORG_EXT_TPOE_DK"),
col("ORGE_NM_ORGAO").alias("DOAT_NM_ORGAO_EXTERNO"),
])
orgao_dp_fato = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([
col("ORGE_ORGA_DK").alias("ORG_EXT_DP_FATO_DK"),
col("ORGE_NM_ORGAO").alias("DOAT_NM_DELEF_FATO"),
])
orgao_dp_origem = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([
col("ORGE_ORGA_DK").alias("ORG_EXT_DP_ORIGEM_DK"),
col("ORGE_NM_ORGAO").alias("DOAT_NM_DELEG_ORIGEM"),
])
orgao_vara = spark.table("%s.mprj_orgao_ext" % options["schema_exadata"]).select([
col("ORGE_ORGA_DK").alias("ORG_EXT_VARA_DK"),
col("ORGE_NM_ORGAO").alias("DOAT_NM_VARA"),
])
tp_orgao_ext = spark.table("%s.mprj_tp_orgao_ext" % options["schema_exadata"])
classe_doc = spark.table("%s.mmps_classe_docto" % options["schema_exadata_aux"])
local_resp = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]).select([
col("ORLW_DK").alias("LOC_RESP_DK"),
col("ORLW_ORGI_TPOR_DK").alias("LOC_RESP_TPOR_DK"),
col("ORLW_ORGI_NM_ORGAO").alias("DOAT_ORGAO_RESPONSAVEL"),
col("ORLW_REGI_NM_REGIAO").alias("DOAT_CRAAI_OR"),
col("ORLW_CMRC_NM_COMARCA").alias("DOAT_COMARCA_OR"),
col("ORLW_COFO_NM_FORO").alias("DOAT_FORO_OR"),
col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAT_JUIZO_UNICO_OR"),
col("ORLW_ORGI_DT_INICIO").alias("DOAT_DT_INICIO_OR"),
col("ORLW_ORGI_DT_FIM").alias("DOAT_DT_FIM_OR"),
col("ORLW_ORGI_DET_CRIACAO").alias("DOAT_DET_CRIACAO_OR"),
])
local_carga = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"]).select([
col("ORLW_DK").alias("LOC_CARGA_DK"),
col("ORLW_ORGI_TPOR_DK").alias("LOC_CARGA_TPOR_DK"),
col("ORLW_ORGI_NM_ORGAO").alias("DOAT_ORGAO_CARGA"),
col("ORLW_REGI_NM_REGIAO").alias("DOAT_CRAAI_CG"),
col("ORLW_CMRC_NM_COMARCA").alias("DOAT_COMARCA_CG"),
col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAT_JUIZO_UNICO_CG"),
col("ORLW_ORGI_DT_FIM").alias("DOAT_DT_FIM_CG"),
])
tp_local_resp = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"]).select([
col("TPOR_DK").alias("TP_LOC_RESP_DK"),
col("TPOR_DS_TP_ORGAO").alias("DOAT_ORGAO_TP_OR"),
col("TPOR_CLASSIFICACAO").alias("DOAT_ORGAO_A_E_OR"),
])
tp_local_carga = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"]).select([
col("TPOR_DK").alias("TP_LOC_CARGA_DK"),
col("TPOR_DS_TP_ORGAO").alias("DOAT_ORGAO_TP_CG"),
col("TPOR_CLASSIFICACAO").alias("DOAT_ORGAO_A_E_CG"),
])
doc_sigilo = documento.join(sigilo, documento.DOCU_NISI_DK == sigilo.NISI_DK, "left")
doc_materia = doc_sigilo.join(materia, doc_sigilo.DOCU_MATE_DK == materia.MATE_DK, "left")
doc_tipo = doc_materia.join(tipo_doc, doc_materia.DOCU_TPDC_DK == tipo_doc.TPDC_DK, "inner")
# doc_tipo = doc_sigilo.join(tipo_doc, doc_sigilo.DOCU_TPDC_DK == tipo_doc.TPDC_DK, "inner")
doc_alteracao = doc_tipo.join(alteracao, alteracao.DOAA_DOCU_DK == doc_tipo.DOCU_DK, "inner")
doc_sit = doc_alteracao.join(sit_doc, doc_alteracao.DOCU_TPST_DK == sit_doc.TPST_DK, "left")
# doc_sit = doc_tipo.join(sit_doc, doc_tipo.DOCU_TPST_DK == sit_doc.TPST_DK, "left")
doc_fase = doc_sit.join(fase_doc, doc_sit.DOCU_FSDC_DK == fase_doc.FSDC_DK, "left")
doc_origem = doc_fase.join(orgao_origem, doc_fase.DOCU_ORGA_DK_ORIGEM == orgao_origem.ORG_EXT_ORIGEM_DK, "left")
doc_tp_ext = doc_origem.join(tp_orgao_ext, doc_origem.ORG_EXT_TPOE_DK == tp_orgao_ext.TPOE_DK , "left")
doc_classe = doc_tp_ext.join(classe_doc, doc_tp_ext.DOCU_CLDC_DK == classe_doc.ID , "left")
# doc_classe = doc_origem.join(classe_doc, doc_origem.DOCU_CLDC_DK == classe_doc.cldc_dk , "left")
doc_loc_resp = doc_classe.join(local_resp, doc_classe.DOCU_ORGI_ORGA_DK_RESPONSAVEL == local_resp.LOC_RESP_DK , "left")
doc_tp_loc_resp = doc_loc_resp.join(tp_local_resp, doc_loc_resp.LOC_RESP_TPOR_DK == tp_local_resp.TP_LOC_RESP_DK , "left")
doc_loc_carga = doc_tp_loc_resp.join(local_carga, doc_tp_loc_resp.DOCU_ORGI_ORGA_DK_CARGA == local_carga.LOC_CARGA_DK , "left")
doc_tp_carga_resp = doc_loc_carga.join(tp_local_carga, doc_loc_carga.LOC_CARGA_TPOR_DK == tp_local_carga.TP_LOC_CARGA_DK , "left")
doc_dp_fato = doc_tp_carga_resp.join(orgao_dp_fato, doc_tp_carga_resp.DOCU_ORGE_ORGA_DK_DELEG_FATO == orgao_dp_fato.ORG_EXT_DP_FATO_DK, "left")
doc_dp_origem = doc_dp_fato.join(orgao_dp_origem, doc_dp_fato.DOCU_ORGE_ORGA_DK_DELEG_ORIGEM == orgao_dp_origem.ORG_EXT_DP_ORIGEM_DK, "left")
doc_dp_vara = doc_dp_origem.join(orgao_vara, doc_dp_origem.DOCU_ORGE_ORGA_DK_VARA == orgao_vara.ORG_EXT_VARA_DK, "left")
return doc_dp_vara.select(columns)
def extract_tbau_andamento(spark):
columns = [
col("VIST_DOCU_DK").alias("DOAN_DOCU_DK"),
col("VIST_DK").alias("DOAN_VIST_DK"),
col("VIST_DT_ABERTURA_VISTA").alias("DOAN_VIST_DT_ABERTURA_VISTA"),
col("VIST_ORGI_ORGA_DK").alias("DOAN_VIST_ORGI_DK"),
col("ORLW_ORGI_NM_ORGAO").alias("DOAN_ORGAO_VISTA"),
col("ORLW_REGI_NM_REGIAO").alias("DOAN_CRAAI_OV"),
col("ORLW_CMRC_NM_COMARCA").alias("DOAN_COMARCA_OV"),
col("ORLW_COFO_NM_FORO").alias("DOAN_FORO_OV"),
col("TPOR_DS_TP_ORGAO").alias("DOAN_ORGAO_TP_OV"),
col("TPOR_CLASSIFICACAO").alias("DOAN_ORGAO_A_E_OV"),
col("ORLW_ORGI_IN_JUIZO_UNICO").alias("DOAN_JUIZO_UNICO_OV"),
col("ORLW_ORGI_DT_INICIO").alias("DOAN_DT_INICIO_OV"),
col("ORLW_ORGI_DT_FIM").alias("DOAN_DT_FIM_OV"),
col("ORLW_ORGI_DET_CRIACAO").alias("DOAN_DET_CRIACAO_OV"),
col("PESS_NM_PESSOA").alias("DOAN_PESS_NM_RESPONSAVEL_ANDAM"),
col("PCAO_DK").alias("DOAN_PCAO_DK"),
col("PCAO_DT_ANDAMENTO").alias("DOAN_PCAO_DT_ANDAMENTO"),
col("STAO_DK").alias("DOAN_STAO_DK_SUB_ANDAMENTO"),
col("STAO_TPPR_DK").alias("DOAN_TPPR_DK_ANDAMENTO"),
col("TPPR_TPPR_DK").alias("DOAN_TPPR_TPPR_DK_PAI"),
col("STAO_IN_RELATADO").alias("DOAN_STAO_IN_RELATADO"),
col("TPPR_CD_TP_ANDAMENTO").alias("DOAN_TPPR_CD_TP_ANDAMENTO"),
col("TPPR_DESCRICAO").alias("DOAN_TPPR_DS_ANDAMENTO"),
col("HIERARQUIA").alias("DOAN_ANDAMENTO_HIERARQUIA"),
col("TEMPO_ANDAMENTO").alias("DOAN_TEMPO")
]
vista = spark.table("%s.mcpr_vista" % options["schema_exadata"])
pessoa = spark.table("%s.mcpr_pessoa" % options["schema_exadata"])
vista_resp = vista.join(pessoa, vista.VIST_PESF_PESS_DK_RESP_ANDAM == pessoa.PESS_DK, "left")
andamento = spark.table("%s.mcpr_andamento" % options["schema_exadata"])
vista_andam = vista_resp.join(
andamento,
[
vista_resp.VIST_DK == andamento.PCAO_VIST_DK,
andamento.PCAO_TPSA_DK == 2
],
"left"
).withColumn(
'TEMPO_ANDAMENTO',
lit(datediff('PCAO_DT_ANDAMENTO', 'VIST_DT_ABERTURA_VISTA')).cast(IntegerType())
)
sub_andamento = spark.table("%s.mcpr_sub_andamento" % options["schema_exadata"])
vista_suba = vista_andam.join(sub_andamento, vista_andam.PCAO_DK == sub_andamento.STAO_PCAO_DK, "left")
tipo_andamento = spark.table("%s.mcpr_tp_andamento" % options["schema_exadata"])
vista_tpand = vista_suba.join(tipo_andamento, vista_suba.STAO_TPPR_DK == tipo_andamento.TPPR_DK, "left")
hier_andamento = spark.table("%s.mmps_tp_andamento" % options["schema_exadata_aux"])
vista_hrand = vista_tpand.join(hier_andamento, vista_tpand.TPPR_DK == hier_andamento.ID, "left")
orgao_local = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"])
vista_orgao = vista_hrand.join(orgao_local, vista_hrand.VIST_ORGI_ORGA_DK == orgao_local.ORLW_DK, "left")
tp_orgao = spark.table("%s.orgi_tp_orgao" % options["schema_exadata"])
vista_tp_orgao = vista_orgao.join(tp_orgao, vista_orgao.ORLW_ORGI_TPOR_DK == tp_orgao.TPOR_DK, "left")
return vista_tp_orgao.select(columns)
def extract_tbau_assunto(spark):
columns = [
col("ASDO_DOCU_DK").alias("DASN_DOCU_DK"),
col("ASDO_DK").alias("DASN_DK"),
col("ASSU_TX_DISPOSITIVO_LEGAL").alias("DASN_TP_LEGAL"),
col("ASSU_NM_ASSUNTO").alias("DASN_NM_ASSUNTO"),
col("ASSU_CD_CNJ").alias("DASN_CD_CNJ"),
col("ASSU_CD_ASSUNTO").alias("DASN_CD_ASSUNTO"),
col("ASSU_DK").alias("DASN_ASSU_DK"),
col("ASSU_ASSU_DK").alias("DASN_ASSU_ASSU_DK_PAI"),
]
assunto_documento = spark.table("%s.mcpr_assunto_documento" % options["schema_exadata"])
assunto = spark.table("%s.mcpr_assunto" % options["schema_exadata"])
doc_assunto_join = assunto_documento.join(assunto, assunto_documento.ASDO_ASSU_DK == assunto.ASSU_DK, "inner")
return doc_assunto_join.select(columns).distinct()
def extract_tbau_movimentacao(spark):
columns = [
col("ITEM_DOCU_DK").alias("DOMO_DOCU_DK"),
col("ITEM_DK").alias("DOMO_ITEM_DK"),
col("MOVI_DK").alias("DOMO_MOVIDK"),
col("MOVI_ORGA_DK_ORIGEM").alias("DOMO_ORGA_ORIGEM_GUIA"),
col("ORIG_NM_PESSOA").alias("DOMO_ORGI_ORIGEM_GUIA"),
col("ORIG_IN_TP_PESSOA").alias("DOMO_TP_ORGI_ORIGEM"),
col("MOVI_ORGA_DK_DESTINO").alias("DOMO_ORGA_DESTINO_GUIA"),
col("DEST_NM_PESSOA").alias("DOMO_ORGI_DESTINO_GUIA"),
col("DEST_IN_TP_PESSOA").alias("DOMO_TP_ORGI_DESTINO"),
col("MOVI_DT_ENVIO_GUIA").alias("DOMO_MOVI_DT_ENVIO_GUIA"),
col("MOVI_DT_RECEBIMENTO_GUIA").alias("DOMO_MOVI_DT_RECEBIMENTO_GUIA"),
col("PCED_DS_PROCEDENCIA").alias("DOMO_DS_PROCEDENCIA_GUIA"),
]
movimentacao = spark.table("%s.mcpr_movimentacao" % options["schema_exadata"])
item = spark.table("%s.mcpr_item_movimentacao" % options["schema_exadata"])
movi_item = movimentacao.join(item, item.ITEM_MOVI_DK == movimentacao.MOVI_DK, "inner")
procedencia = spark.table("%s.mcpr_procedencia_documento" % options["schema_exadata"])
movi_proc = movi_item.join(procedencia, movi_item.MOVI_PCED_DK_PROCEDENCIA == procedencia.PCED_DK, "inner")
destino = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]).select([
col("PESS_DK").alias("DEST_DK"),
col("PESS_NM_PESSOA").alias("DEST_NM_PESSOA"),
col("PESS_IN_TP_PESSOA").alias("DEST_IN_TP_PESSOA"),
])
movi_destino = movi_proc.join(destino, movi_proc.MOVI_ORGA_DK_DESTINO == destino.DEST_DK, "inner")
origem = spark.table("%s.mcpr_pessoa" % options["schema_exadata"]).select([
col("PESS_DK").alias("ORIG_DK"),
col("PESS_NM_PESSOA").alias("ORIG_NM_PESSOA"),
col("PESS_IN_TP_PESSOA").alias("ORIG_IN_TP_PESSOA"),
])
movi_origem = movi_destino.join(origem, movi_destino.MOVI_ORGA_DK_ORIGEM == origem.ORIG_DK, "inner")
return movi_origem.filter("MOVI_DT_CANCELAMENTO IS NULL").select(columns).distinct()
def extract_tbau_personagem(spark):
sf1_columns = [
col("PESF_PESS_DK").alias("PESFDK"),
col("PESF_SEXO").alias("SEX"),
col("ESCO_DESCRICAO").alias("ESCOL"),
col("ECIV_DESCRICAO").alias("ECIVIL"),
col("CORP_DESCRICAO").alias("CPELE"),
col("PESF_DT_NASC").alias("DT_NASC"),
]
sf2_columns = [
col("ENPE_PESS_DK").alias("ENPEDK"),
col("ENDC_CEP").alias("ECEP"),
col("ECIDA"),
col("EUFED"),
col("EBAIR"),
]
columns = [
col("PERS_PESS_DK").alias("DPSG_PERS_PESS_DK"),
col("PERS_DOCU_DK").alias("DPSG_DOCU_DK"),
col("PESS_NM_PESSOA").alias("DPSG_PESS_NM_PESSOA"),
col("TPPE_DESCRICAO").alias("DPSG_TPPE_DESCRICAO"),
col("TPAT_DS_AUTORIDADE").alias("DPSG_TPAT_DS_AUTORIDADE"),
col("REND_DESCRICAO").alias("DPSG_REND_DESCRICAO"),
col("PESS_IN_TP_PESSOA").alias("DPSG_PESS_IN_TP_PESSOA"),
col("SEX").alias("DPSG_SEXO"),
col("ESCOL").alias("DPSG_ESCOLARIDADE"),
col("ECIVIL").alias("DPSG_ESTADO_CIVIL"),
col("CPELE").alias("DPSG_COR_PELE"),
col("DT_NASC").alias("DPSG_DT_NASCIMENTO"),
col("ECEP").alias("DPSG_CEP_PERSONAGEM"),
col("EBAIR").alias("DPSG_BAIRRO_PERSONAGEM"),
col("ECIDA").alias("DPSG_CIDADE_PERSONAGEM"),
col("EUFED").alias("DPSG_UF_PERSONAGEM"),
]
pessoa_fisica = spark.table("%s.mcpr_pessoa_fisica" % options["schema_exadata"])
escolaridade = spark.table("%s.mcpr_escolaridade" % options["schema_exadata"])
pessoa_escolaridade = pessoa_fisica.join(escolaridade, pessoa_fisica.PESF_ESCO_DK == escolaridade.ESCO_DK, "left")
estado_civil = spark.table("%s.mcpr_estado_civil" % options["schema_exadata"])
pessoa_estado_civil = pessoa_escolaridade.join(estado_civil, pessoa_escolaridade.PESF_ECIV_DK == estado_civil.ECIV_DK, "left")
cor_pele = spark.table("%s.mcpr_cor_pele" % options["schema_exadata"])
pessoa_cor_pele = pessoa_estado_civil.join(cor_pele, pessoa_estado_civil.PESF_CORP_DK == cor_pele.CORP_DK, "left")
sf1 = pessoa_cor_pele.select(sf1_columns).distinct()
end_pes = spark.table("%s.mcpr_endereco_pessoa" % options["schema_exadata"])
endereco = spark.table("%s.mcpr_enderecos" % options["schema_exadata"]).select(
["ENDC_DK", "ENDC_BAIR_DK", "ENDC_NM_BAIRRO", "ENDC_CEP", "ENDC_CIDA_DK", "ENDC_NM_CIDADE", "ENDC_NM_ESTADO", "ENDC_UFED_DK"]
)
endereco_pessoa = end_pes.join(endereco, end_pes.ENPE_ENDC_DK == endereco.ENDC_DK, "left")
cidade = spark.table("%s.mprj_cidade" % options["schema_exadata"])
endereco_cidade = endereco_pessoa.join(cidade, endereco_pessoa.ENDC_CIDA_DK == cidade.CIDA_DK, "left")
uf = spark.table("%s.mprj_uf" % options["schema_exadata"])
endereco_uf = endereco_cidade.join(uf, endereco_cidade.CIDA_UFED_DK == uf.UFED_DK, "left")
bairro = spark.table("%s.mprj_bairro" % options["schema_exadata"])
endereco_bairro = endereco_uf.join(
bairro,
[
endereco_uf.ENDC_CIDA_DK == bairro.BAIR_CIDA_DK,
endereco_uf.ENDC_BAIR_DK == bairro.BAIR_DK,
],
"left"
).withColumn(
'ECIDA',
coalesce(
col('CIDA_NM_CIDADE'),
col('ENDC_NM_CIDADE')
)
).withColumn(
'EUFED',
coalesce(
col('UFED_SIGLA'),
col('ENDC_NM_ESTADO')
)
).withColumn(
'EBAIR',
coalesce(
col('BAIR_NM_BAIRRO'),
col('ENDC_NM_BAIRRO')
)
)
sf2 = endereco_bairro.select(sf2_columns).distinct()
personagem = spark.table("%s.mcpr_personagem" % options["schema_exadata"])
tipo_personagem = spark.table("%s.mcpr_tp_personagem" % options["schema_exadata"])
personagem_tipo = personagem.join(tipo_personagem, personagem.PERS_TPPE_DK == tipo_personagem.TPPE_DK, "inner")
pessoa = spark.table("%s.mcpr_pessoa" % options["schema_exadata"])
personagem_pessoa = personagem_tipo.join(pessoa, personagem_tipo.PERS_PESS_DK == pessoa.PESS_DK, "inner")
tipo_autoridade = spark.table("%s.mcpr_tp_autoridade" % options["schema_exadata"])
personagem_autoridade = personagem_pessoa.join(tipo_autoridade, personagem_pessoa.PERS_TPAT_DK == tipo_autoridade.TPAT_DK, "left")
perfil = spark.table("%s.mcpr_perfil" % options["schema_exadata"])
personagem_perfil = personagem_autoridade.join(perfil, personagem_autoridade.PERS_PESF_DK == perfil.PERF_PESF_PESS_DK, "left")
renda = spark.table("%s.mcpr_faixa_renda" % options["schema_exadata"])
personagem_renda = personagem_perfil.join(renda, personagem_perfil.PERF_REND_DK == renda.REND_DK, "left")
personagem_sf1 = personagem_renda.join(
sf1,
[
sf1.PESFDK == personagem_renda.PERS_PESS_DK,
personagem_renda.PESS_IN_TP_PESSOA.isin(['I', 'J']) == False,
],
"left"
)
personagem_sf2 = personagem_sf1.join(
sf2,
[
sf2.ENPEDK == personagem_sf1.PERS_PESS_DK,
personagem_sf1.PESS_IN_TP_PESSOA != 'I',
],
"left"
)
return personagem_sf2.filter("PERS_DT_FIM IS NULL").select(columns).distinct()
def extract_tbau_consumo(spark):
columns = [
col("cd_bem_servico").alias("tmat_cd_bem_servico"),
col("ds_bem_generico").alias("tmat_ds_bem_generico"),
col("nm_bem_servico").alias("tmat_nm_bem_servico"),
col("ds_completa").alias("tmat_ds_completa"),
col("mes_ano_consumo").alias("tmat_mes_ano_consumo"),
col("orlw_dk").alias("tmat_orgi_dk"),
col("orlw_orgi_nm_orgao").alias("tmat_orgi_nm_orgao"),
col("orlw_cofo_nm_foro").alias("tmat_cofo_nm_foro"),
col("orlw_cmrc_nm_comarca").alias("tmat_cmrc_nm_comarca"),
col("orlw_regi_nm_regiao").alias("tmat_regi_nm_regiao"),
col("sum_atendido").alias("tmat_qt_consumida"),
col("sg_um").alias("tmat_sg_unidade_medida"),
col("ds_um").alias("tmat_ds_unidade_medida"),
col("sum_consumido").alias("tmat_vl_consumido"),
]
pre_columns = [
col("cd_bem_servico"),
col("ds_bem_generico"),
col("nm_bem_servico"),
col("ds_completa"),
col("qt_atendido"),
col("sg_um"),
col("ds_um"),
col("vl_consumido"),
col("mes_ano_consumo"),
col("orlw_dk"),
col("orlw_orgi_nm_orgao"),
col("orlw_cofo_nm_foro"),
col("orlw_cmrc_nm_comarca"),
col("orlw_regi_nm_regiao"),
]
requisicao = spark.table("%s.asin_ax_v_requisicao_consulta" % options["schema_exadata_views"]).\
filter("CD_SITUACAO_REQ_ATUAL = '003'").\
filter("QT_ATENDIDO IS NOT NULL").\
withColumn("vl_consumido", col("vl_atendido")/100).\
withColumn("mes_ano_consumo", trunc("dt_situacao_req_atual", "month"))
situacao = spark.table("%s.asin_ax_situacao_req" % options["schema_exadata_views"])
ua = spark.table("%s.asin_cr_ua" % options["schema_exadata_views"]).select(col("CD_UA").alias("ua_id"))
servico = spark.table("%s.asin_cr_bem_servico" % options["schema_exadata_views"]).select([
col("CD_BEM_SERVICO").alias("servico_id"),
col("CD_BEM_GENERICO"),
col("nm_bem_servico"),
col("ds_completa"),
col("cd_um_elementar"),
])
generico = spark.table("%s.asin_cr_bem_generico" % options["schema_exadata_views"]).select([
col("CD_BEM_GENERICO").alias("generico_id"),
col("ds_bem_generico"),
])
umed = spark.table("%s.asin_cr_um" % options["schema_exadata_views"])
orgao = spark.table("%s.orgi_vw_orgao_local_atual" % options["schema_exadata"])
sit_req = requisicao.join(situacao, requisicao.CD_SITUACAO_REQ_ATUAL == situacao.CD_SITUACAO_REQ, "inner")
sit_ua = sit_req.join(ua, sit_req.CD_UA == ua.ua_id, "inner")
sit_servico = sit_ua.join(servico, sit_ua.CD_BEM_SERVICO == servico.servico_id, "inner")
sit_generico = sit_servico.join(generico, sit_servico.CD_BEM_GENERICO == generico.generico_id, "inner")
sit_umed = sit_generico.join(umed, sit_generico.cd_um_elementar == umed.CD_UM, "inner")
sit_orgao = sit_umed.join(orgao, sit_umed.CD_UA == orgao.ORLW_ORGI_CDORGAO, "inner").select(pre_columns)
result = sit_orgao.groupBy(
"cd_bem_servico", "ds_bem_generico", "nm_bem_servico", "ds_completa", "sg_um", "ds_um", "mes_ano_consumo",
"orlw_dk", "orlw_orgi_nm_orgao", "orlw_cofo_nm_foro", "orlw_cmrc_nm_comarca", "orlw_regi_nm_regiao"
).sum("qt_atendido", "vl_consumido").\
withColumn("sum_atendido", col("sum(qt_atendido)")).\
withColumn("sum_consumido", col("sum(vl_consumido)"))
return result.select(columns)
def extract_tbau_endereco(spark):
columns = [
col("EDOC_DOCU_DK").alias("DODR_DOCU_DK"),
concat(
col("TPLO_DS_LOGRADOURO"),
lit(" "),
col("ENDC_LOGRADOURO"),
lit(" "),
col("ENDC_NUMERO")
).alias("DODR_ENDERECO"),
col("DODR_NM_BAIRRO"),
col("ENDC_CEP").alias("DODR_CEP"),
col("DODR_NM_CIDADE"),
col("DODR_UFED"),
]
doc_endereco = spark.table("%s.mcpr_endereco_documento" % options["schema_exadata"])
endereco = spark.table("%s.mcpr_enderecos" % options["schema_exadata"]).filter("ENDC_CIDA_DK IS NOT NULL")
cidade = spark.table("%s.mprj_cidade" % options["schema_exadata"])
estado = spark.table("%s.mprj_uf" % options["schema_exadata"])
bairro = spark.table("%s.mprj_bairro" % options["schema_exadata"])
tipo_logradouro = spark.table("%s.mprj_tp_logradouro" % options["schema_exadata"])
end_documento = doc_endereco.join(endereco, doc_endereco.EDOC_ENDC_DK == endereco.ENDC_DK, "inner")
end_cidade = end_documento.join(cidade, end_documento.ENDC_CIDA_DK == cidade.CIDA_DK, "left")
end_estado = end_cidade.join(estado, end_cidade.CIDA_UFED_DK == estado.UFED_DK, "left")
end_bairro = end_estado.join(bairro, [
end_estado.ENDC_CIDA_DK == bairro.BAIR_CIDA_DK,
end_estado.ENDC_BAIR_DK == bairro.BAIR_DK,
], "left")
end_tp_logradouro = end_bairro.join(tipo_logradouro, end_bairro.ENDC_TPLO_DK == tipo_logradouro.TPLO_DK, "left").\
withColumn(
'DODR_NM_BAIRRO',
coalesce(
col('BAIR_NM_BAIRRO'),
col('ENDC_NM_BAIRRO')
)
).\
withColumn(
'DODR_NM_CIDADE',
coalesce(
col('CIDA_NM_CIDADE'),
col('ENDC_NM_CIDADE')
)
).\
withColumn(
'DODR_UFED',
coalesce(
col('UFED_SIGLA'),
col('ENDC_NM_ESTADO')
)
)
return end_tp_logradouro.select(columns).distinct()
def generate_tbau(spark, generator, schema, table_name):
dataframe = generator(spark)
full_table_name = "{}.{}".format(schema, table_name)
dataframe.coalesce(20).write.format('parquet').saveAsTable(full_table_name, mode='overwrite')
execute_compute_stats(full_table_name)
print("{} gravada".format(table_name))
def execute_process(options):
spark = pyspark.sql.session.SparkSession\
.builder\
.appName("tabelas_tbau")\
.enableHiveSupport()\
.getOrCreate()
sc = spark.sparkContext
schema_exadata_aux = options['schema_exadata_aux']
generate_tbau(spark, extract_tbau_documento, schema_exadata_aux, "tbau_documento")
generate_tbau(spark, extract_tbau_andamento, schema_exadata_aux, "tbau_documento_andamento")
generate_tbau(spark, extract_tbau_assunto, schema_exadata_aux, "tbau_documento_assunto")
generate_tbau(spark, extract_tbau_movimentacao, schema_exadata_aux, "tbau_documento_movimentacao")
generate_tbau(spark, extract_tbau_personagem, schema_exadata_aux, "tbau_documento_personagem")
generate_tbau(spark, extract_tbau_consumo, schema_exadata_aux, "tbau_material_consumo")
generate_tbau(spark, extract_tbau_endereco, schema_exadata_aux, "tbau_documento_endereco")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create tables tbau")
parser.add_argument('-e','--schemaExadata', metavar='schemaExadata', type=str, help='')
parser.add_argument('-a','--schemaExadataAux', metavar='schemaExadataAux', type=str, help='')
parser.add_argument('-v','--schemaExadataViews', metavar='schemaExadataViews', type=str, help='')
parser.add_argument('-i','--impalaHost', metavar='impalaHost', type=str, help='')
parser.add_argument('-o','--impalaPort', metavar='impalaPort', type=str, help='')
args = parser.parse_args()
options = {
'schema_exadata': args.schemaExadata,
'schema_exadata_aux': args.schemaExadataAux,
'schema_exadata_views': args.schemaExadataViews,
'impala_host' : args.impalaHost,
'impala_port' : args.impalaPort
}
execute_process(options)
| rhenanbartels/scripts-bda | extract_tbau/src/extractor.py | extractor.py | py | 25,402 | python | pt | code | 0 | github-code | 36 | [
{
"api_name": "pyspark.sql.types.IntegerType",
"line_number": 184,
"usage_type": "call"
},
{
"api_name": "generic_utils.execute_compute_stats",
"line_number": 503,
"usage_type": "call"
},
{
"api_name": "pyspark.sql.session.SparkSession.builder.appName",
"line_number": 509,
... |
8161754177 | import multiprocessing
import time
def pro1(q):
# q에 데이터를 넣는다
for i in range(100):
q.put(str(i))
time.sleep(0.1)
def pro2(q):
# q에 데이터를 빼낸다
for i in range(100):
item = q.get()
print(item)
# JoinableQueue
q.task_done()
if __name__ == '__main__':
queue = multiprocessing.JoinableQueue()
p1 = multiprocessing.Process(target=pro1, args=(queue,))
p2 = multiprocessing.Process(target=pro2, args=(queue,))
p1.start()
p2.start() | weatherbetter/levelup-python | multi_process/multiprocess_JoinableQueue.py | multiprocess_JoinableQueue.py | py | 540 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "time.sleep",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "multiprocessing.JoinableQueue",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "multiprocessing.Process",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "multi... |
15640198972 | from django.conf.urls import url,include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r"^$", views.HomePage.as_view(), name="home"),
url(r"^index/$", views.TestPage.as_view(), name="test"),
url(r"^thanks/$", views.ThanksPage.as_view(), name="thanks"),
url(r'^admin/', admin.site.urls, name='admin'),
url(r"^accounts/", include("accounts.urls", namespace="accounts")),
url(r"^accounts/", include("django.contrib.auth.urls")),
url(r"^groups/",include("groups.urls", namespace="groups")),
url(r'^company/', include('company.urls',namespace='company')),
url(r'^project/', include('project.urls',namespace='project')),
url(r'^sprint/', include('sprint.urls',namespace='sprint')),
url(r'^task/', include('task.urls',namespace='task')),
url(r'^log/', include('log.urls',namespace='log')),
url(r'^todo/', include('todo.urls',namespace='todo')),
url(r'^meeting/', include('meeting.urls',namespace='meeting')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | itzikorfa/SE-Lite-Scrum | SE_Project_VerX/urls.py | urls.py | py | 1,153 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.conf.urls.url",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "django.conf.urls.url",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "django.conf.urls.url",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "django.c... |
38264973809 | import importlib
from copy import deepcopy
from os import path as osp
from collections import OrderedDict
from pyiqa.utils import get_root_logger, scandir
from pyiqa.utils.registry import ARCH_REGISTRY
from pyiqa.default_model_configs import DEFAULT_CONFIGS
__all__ = ['build_network', 'create_metric']
# automatically scan and import arch modules for registry
# scan all the files under the 'archs' folder and collect files ending with
# '_arch.py'
arch_folder = osp.dirname(osp.abspath(__file__))
arch_filenames = [osp.splitext(osp.basename(v))[0] for v in scandir(arch_folder) if v.endswith('_arch.py')]
# import all the arch modules
_arch_modules = [importlib.import_module(f'pyiqa.archs.{file_name}') for file_name in arch_filenames]
def create_metric(metric_name, eval=True, **opt):
net_opts = OrderedDict()
if metric_name in DEFAULT_CONFIGS.keys():
# load default setting first
default_opt = DEFAULT_CONFIGS[metric_name]['metric_opts']
net_opts.update(default_opt)
# then update with custom setting
net_opts.update(opt)
network_type = net_opts.pop('type')
net = ARCH_REGISTRY.get(network_type)(**net_opts)
net.lower_better = DEFAULT_CONFIGS[metric_name].get('lower_better', False)
if eval:
net.eval()
logger = get_root_logger()
logger.info(f'Metric [{net.__class__.__name__}] is created.')
return net
def build_network(opt):
opt = deepcopy(opt)
network_type = opt.pop('type')
net = ARCH_REGISTRY.get(network_type)(**opt)
logger = get_root_logger()
logger.info(f'Network [{net.__class__.__name__}] is created.')
return net
| Sskun04085/IQA_PyTorch | pyiqa/archs/__init__.py | __init__.py | py | 1,637 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.dirname",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "os.path.abspath",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "os.path.splitext",
"line_... |
43587658067 | import json as _json
import re as _re
from typing import List as _List
from mitmproxy.http import HTTPFlow as _HTTPFlow
from mitmproxy.io import FlowReader as _FlowReader
from mitmproxy.io import FlowWriter as _FlowWriter
from mitmproxy.io import tnetstring as _tnetstring
from . import utils as _utils
# ---------- Constants ----------
__ENTITY_PROPERTY_NAMES = [
'accesstoken',
'advertisingkey',
'attackingshipxml',
'authenticationtype',
'battleid',
'defendingshipxml',
'devicekey',
'email',
'emailverificationstatus',
'facebooktoken',
'facebooktokenexpirydate',
'gamecentername',
'gamecenterfriendcount',
'googleplayaccesstokenexpirydate',
'refreshtoken',
'steamid',
]
__QUERY_PARAM_NAMES = [
'accesstoken',
'advertisingkey',
'battleid',
'checksum',
'devicekey',
'email',
'facebooktoken',
'gamecentername',
'password',
'refreshtoken',
'steamid',
'ticket',
]
__RX_PROPERTIES: _re.Pattern = _re.compile('( (' + '|'.join(__ENTITY_PROPERTY_NAMES) + ')="(.*?)")', _re.IGNORECASE | _re.MULTILINE)
# ---------- Functions ----------
def anonymize_flow(flow: _HTTPFlow) -> _HTTPFlow:
flow.server_conn.sockname = (None, None)
for query_param_name, query_param_value in flow.request.query.items():
if query_param_name.lower() in __QUERY_PARAM_NAMES and query_param_value:
try:
int(query_param_value)
query_param_value = '0' * len(query_param_value)
except:
query_param_value = 'x' * len(query_param_value)
flow.request.query[query_param_name] = query_param_value
request_content = ''
if flow.request.content:
request_content = flow.request.content.decode('utf-8')
try:
request_content_dict: dict = _json.loads(request_content)
except:
request_content_dict: dict = None
if request_content_dict:
# Request Content is a json dictionary
for query_param_name, query_param_value in request_content_dict.items():
if query_param_name.lower() in __QUERY_PARAM_NAMES and query_param_value:
try:
int(query_param_value)
query_param_value = '0' * len(query_param_value)
except:
query_param_value = 'x' * len(query_param_value)
request_content_dict[query_param_name] = query_param_value
request_content = _json.dumps(request_content_dict)
else:
# Request Content is most likely a query parameter string
if '=' in request_content:
query_params = request_content.split('&')
request_content_dict = {}
for query_param in query_params:
split_query_param = query_param.split('=')
if len(split_query_param) == 2: # Ignore malformed query parameters or strings that aren't query parameters
query_param_name, query_param_value = split_query_param
if query_param_name.lower() in __QUERY_PARAM_NAMES and query_param_value:
try:
int(query_param_value)
query_param_value = '0' * len(query_param_value)
except:
query_param_value = 'x' * len(query_param_value)
request_content_dict[query_param_name] = query_param_value
request_content = '&'.join('='.join((key, value)) for key, value in request_content_dict.items())
flow.request.content = request_content.encode('utf-8')
response_content = ''
if flow.response.content:
response_content = flow.response.content.decode('utf-8')
matches = __RX_PROPERTIES.finditer(response_content)
for match in matches:
matched_string, property_name, property_value = match.groups()
try:
int(property_value)
property_value = '0' * len(property_value)
except:
try:
_utils.parse_pss_datetime(property_value)
property_value = '2016-01-06T00:00:00'
except:
property_value = 'x' * len(property_value)
response_content = response_content.replace(matched_string, f' {property_name}="{property_value}"')
flow.response.content = response_content.encode('utf-8')
return flow
def anynomize_flows(file_path: str) -> _List[_HTTPFlow]:
with open(file_path, 'rb') as fp:
flow_reader: _FlowReader = _FlowReader(fp)
flows = [anonymize_flow(flow) for flow in flow_reader.stream()]
return flows
def store_flows(file_path: str, flows: _List[_HTTPFlow]) -> None:
with open(file_path, 'wb') as fp:
flow_writer: _FlowWriter = _FlowWriter(fp)
for flow in flows:
flow_writer.add(flow)
| PSS-Tools-Development/pss-api-parser | src/anonymize.py | anonymize.py | py | 5,070 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "re.Pattern",
"line_number": 46,
"usage_type": "attribute"
},
{
"api_name": "re.compile",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "re.IGNORECASE",
"line_number": 46,
"usage_type": "attribute"
},
{
"api_name": "re.MULTILINE",
"lin... |
19279680101 | import datetime
import os
import tensorflow as tf
import numpy as np
class Runner(object):
def __init__(self, agent, env, train, load_path):
self.agent = agent
self.env = env
self.train = train # True: entrenar agente, False: se carga agente entrenado
self.episode = 1
self.last_10_ep_rewards = []
self.path = './graphs/' + datetime.datetime.now().strftime("%y%m%d_%H%M") \
+ ('_train_' if self.train else 'run_') \
+ type(agent).__name__
self.writer = tf.summary.create_file_writer(self.path)
# Se carga modelo entrenado
if not self.train and load_path is not None and os.path.isdir(load_path):
self.agent.load_model(load_path)
def summarize(self):
"""Guarda los valores obtenidos por episodio."""
'''self.writer.add_summary(tf.Summary(
value=[tf.Summary.Value(tag='Score per Episode', simple_value=self.score)]),
self.episode
)
if self.train and self.episode % 10 == 0:
self.agent.save_model(self.path)
try:
self.agent.update_target_model() # No se que hace
except AttributeError:
...
'''
self.episode += 1
def run(self, episodes):
"""Entrenamiento del agente en la cantidad de episodios dados."""
while self.episode <= episodes:
obs = self.env.reset()
dist = 0
new_dist = 0
self.score = 0
done = False
act = 0
while act < 150:
if obs.last():
break
state, pos_marine, dist = self.agent.state_marine(obs)
if obs.first():
action = self.agent._SELECT_ARMY
act_value = 0
else:
act_value, action = self.agent.step(state, pos_marine)
obs = self.env.step(action)
next_state, pos_marine, new_dist = self.agent.state_marine(obs)
reward = obs.reward
done = reward > 0
reward += dist - new_dist
self.score += reward
# Guarda las experiencias del agente en cada paso de tiempo.
self.agent.buffer.add(state, act_value, reward, next_state, done)
state = next_state
self.agent.cur_frame += 1
# Copia los pesos de la red principal hacia la red target.
if self.agent.cur_frame % self.agent.update_target == 0:
self.agent.copy_weights(self.agent.main_nn, self.agent.target_nn)
# Entrenamiento de la red neuronal.
if len(self.agent.buffer) > self.agent.batch_size:
states, actions, rewards, next_states, dones = self.agent.buffer.sample(self.agent.batch_size)
loss = self.agent.train_step(states, actions, rewards, next_states, dones)
act += 1
# Decrecimiento del epsilon.
if self.episode < self.agent.num_episodes:
self.agent.decrease_epsilon()
# Guarda recompensas de los ultimos 10 episodios.
if len(self.last_10_ep_rewards) == 10:
self.last_10_ep_rewards = self.last_10_ep_rewards[1:]
self.last_10_ep_rewards.append(self.score)
# Guarda recompensa y explota el conocimiento del agente cada 10 episodios.
if self.episode % 10 == 0:
#aux_reward = agent.explotation(iteraciones)
mean_rewards = np.mean(self.last_10_ep_rewards)
print(f'Episode {self.episode}/{self.agent.num_episodes}, Epsilon: {self.agent.epsilon:.3f}, '\
f'Reward in last 100 episodes: {mean_rewards:.2f}')
#episodes.append(episode)
#eps_history.append(agent.epsilon)
#prom_rewards_greedy.append(aux_reward)
#last_100_mean_rewards.append(mean_rewards)
self.summarize()
| ericPrimelles/RLProject | runner.py | runner.py | py | 4,209 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "datetime.datetime.now",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "tensorflow.summary.create_file_writer",
"line_number": 20,
"usage_type": "call"
},
{
... |
15444060214 | #!/usr/bin/env python
from __future__ import print_function
import sys
import argparse
def parse_stdin(in_file):
d = {}
for line in in_file:
if ':' in line:
split = line.split(':')
stripped = [s.strip() for s in split]
#if len(stripped) > 2:
# print 'Warning: ignoring remaining column in line \'', line, '\''
# the split(' ')[0] is mainly to get rid of the ms info in runtime
d[stripped[0]] = stripped[1].split(' ')[0]
# Something whent wrong
if 'reason' in d:
if 'time' in d['reason']:
d['runtime'] = 'Timeout'
else:
d['runtime'] = 'N/A'
return d
def print_data(d, keys):
values = [d[key] for key in keys]
s = '&'.join(values)
s += '\\\\'
print(s)
if __name__ == '__main__':
argument_parser = argparse.ArgumentParser(
description=("A program to parse output form the COCP exercises."
" Pipe the input from your experiment file into it, "
" like so: ./queens | gather_stats.py."))
# Normally, we would save the results but we're not using them now.
argument_parser.parse_args()
d = parse_stdin(sys.stdin)
print_data(d, keys=['runtime', 'failures'])
| amandasystems/cocp-automation-2017 | conductor/gather_stats.py | gather_stats.py | py | 1,288 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "sys.stdin",
"line_number": 45,
"usage_type": "attribute"
}
] |
21664219940 | """
Receive an image
- Global binarize image
- Find word (connected component RETR_BOUNDARY)
- Find Rectilinear Polygon
Return an list of points in order
"""
import cv2
import numpy as np
import sys
import matplotlib.pyplot as plt
PADDING = 2
def binarize(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, bin_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
return bin_img
def bbox_words(bin_img):
contours = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
list_bboxes = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
list_bboxes.append((x-PADDING, y-PADDING, w+2*PADDING, h+2*PADDING))
return list_bboxes
def draw_region(img, x1, y1, x2, y2):
h, w = img.shape[:2]
x1 = max(0, x1)
y1 = max(0, y1)
x2 = min(x2, w)
y2 = min(y2, h)
cv2.rectangle(img, (x1, y1), (x2, y2), 255, -1)
def merge_words_2_line(bin_img, list_bboxes):
list_bboxes.sort(key = lambda bbox: bbox[1])
cnt = len(list_bboxes)
for i in range(len(list_bboxes)):
for j in range(len(list_bboxes)):
x1, y1, w1, h1 = list_bboxes[i]
x2, y2, w2, h2 = list_bboxes[j]
if y1 <= y2 and 2 * (y1 + h1 - y2) >= 0.5 * (h1 + h2):
x_left, x_right = min(x1, x2), max(x1 + w1, x2 + w2)
y_left, y_right = min(y1, y2), max(y1 + h1, y2 + h2)
list_bboxes[i] = x_left, y_left, x_right - x_left, y_right - y_left
list_bboxes[j] = x_left, y_left, x_right - x_left, y_right - y_left
highlight_img = bin_img.copy()
for i in range(cnt):
x, y, w, h = list_bboxes[i]
draw_region(highlight_img, x, y, x + w, y + h)
cv2.imwrite('line.png', highlight_img)
contours = cv2.findContours(highlight_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
return contours
def merge_lines_2_paragraph(bin_img, contours):
cnt = len(contours)
highlight_img = bin_img.copy()
cv2.drawContours(highlight_img, contours, -1, 255, -1)
# for contour in contours:
# x, y, w, h = cv2.boundingRect(contour)
# draw_region(highlight_img, x, y, x + w, y + h)
for contour_1 in contours:
for contour_2 in contours:
x1, y1, w1, h1 = cv2.boundingRect(contour_1)
x2, y2, w2, h2 = cv2.boundingRect(contour_2)
if (x1 != x2 or y1 != y2) and (y1 < y2 and y1 + h1 + h1//4 >= y2 - h2//4):
x_left = max(x1, x2)
x_right = min(x1 + w1, x2 + w2)
if x_left < x_right:
draw_region(highlight_img, x_left, y1 + h1, x_right, y2)
contours = cv2.findContours(highlight_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
if (len(contours) == 0):
return []
idx = -1
for i in range(len(contours)):
if idx == -1 or cv2.contourArea(contours[idx]) < cv2.contourArea(contours[i]):
idx = i
epsilon = 0.001*cv2.arcLength(contours[idx], True)
approx = cv2.approxPolyDP(contours[idx], epsilon, True)
highlight_img = bin_img.copy()
for i in range(len(approx)):
j = (i + 1) % len(approx)
cv2.line(highlight_img, (approx[i][0][0], approx[i][0][1]), (approx[j][0][0], approx[j][0][1]), 255)
cv2.imwrite('highlight.png', highlight_img)
return [(approx[i][0][0], approx[i][0][1]) for i in range(len(approx))]
def main(img):
cv2.imwrite('crop.png', img)
bin_img = binarize(img)
list_bboxes = bbox_words(bin_img)
line_contours = merge_words_2_line(bin_img, list_bboxes)
return merge_lines_2_paragraph(bin_img, line_contours)
if __name__ == '__main__':
img_path = sys.argv[1]
img = cv2.imread(img_path)
print(main(img)) | qcuong98/clabel | rectilinear_polygon.py | rectilinear_polygon.py | py | 3,815 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "cv2.cvtColor",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "cv2.COLOR_BGR2GRAY",
"line_number": 19,
"usage_type": "attribute"
},
{
"api_name": "cv2.threshold",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "cv2.THRESH_BINARY_... |
41573028205 | import logging
def get_logger():
"""Get logging."""
logging.getLogger('matplotlib.font_manager').setLevel(logging.WARNING)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s: - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger | TitusWjt/class3 | utils/log.py | log.py | py | 474 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "logging.WARNING",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "logging.getLogger",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "logging.DEBUG",... |
38799425699 | import discord
import bdg
import enum
import requests
import bs4
import datetime
class BrawlModes(enum.Enum):
BRAWLBALL = "brawlBall"
SOLOSHOWDOWN = "soloShowdown"
DUOSHOWDOWN = "duoShowdown"
GEMGRAB = "gemGrab"
BOUNTY = "bounty"
HOTZONE = "hotZone"
KNOCKOUT = "knockout"
HEIST = "heist"
SIEGE = "siege"
names = {
BrawlModes.BRAWLBALL: "FUTE-BRAWL",
BrawlModes.SOLOSHOWDOWN: "COMBATE SOLO",
BrawlModes.DUOSHOWDOWN: "COMBATE DUPLO",
BrawlModes.GEMGRAB: "PIQUE-GEMA",
BrawlModes.BOUNTY: "CAÇA ESTRELAS",
BrawlModes.HOTZONE: "ZONA ESTRATÉGICA",
BrawlModes.KNOCKOUT: "NOCAUTE",
BrawlModes.HEIST: "ROUBO",
BrawlModes.SIEGE: "ENCURRALADO"
}
colors = {
BrawlModes.BRAWLBALL: 0x8CA0DF,
BrawlModes.SOLOSHOWDOWN: 0x81D621,
BrawlModes.DUOSHOWDOWN: 0x81D621,
BrawlModes.GEMGRAB: 0x9B3DF3,
BrawlModes.BOUNTY: 0x01CFFF,
BrawlModes.HOTZONE: 0xE33C50,
BrawlModes.KNOCKOUT: 0xF7831C,
BrawlModes.HEIST: 0xD65CD3,
BrawlModes.SIEGE: 0xF04F32
}
class BrawlMetasCommand(discord.app_commands.Command):
def __init__(self, bot: bdg.BotDusGuri):
self.bot = bot
super().__init__(
name="brawl_meta",
description="Mostra uma lista dos brawlers meta de cada modo de jogo",
callback=self.on_command
)
async def on_command(self, i: discord.Interaction, modo: BrawlModes, top: int = 10):
await i.response.defer(thinking=True)
data = self.get_metas(modo, top)
desc = str()
for brawler in data['brawlers']:
desc += "{rank}. **{name}** - `{star}%`\n".format(**brawler)
embed = discord.Embed(
title=f"Top {top} - {names[modo]}",
color=colors[modo],
description=desc
)
# Definindo o autor como o Brawl Ace
embed.set_author(
name="Brawl Ace",
url="https://brawlace.com/meta",
icon_url="https://brawlace.com/assets/images/icon.png?v=22.87"
)
# Pegando o ícone do modo de jogo e definindo-o como a thumbnail
embed.set_thumbnail(url=data['icon'])
# Definindo legenda
embed.set_footer(text="(%) Porcentagem de Craque")
# definindo como timestamp como tempo da ultima atualização
embed.timestamp = data['last_update']
await i.followup.send(embed=embed)
def get_metas(self, mode: BrawlModes, count: int = 10) -> dict[str, any]:
html = bs4.BeautifulSoup(requests.get("https://brawlace.com/meta", cookies={"lang": "pt"}).content, "html.parser")
div = html.select_one(f"#gameModeData{mode.value}")
data = {}
# Pegando icone do modo de jogo
data['icon'] = div.select_one("h3 img")['src']
# Pegando o tempo da ultima atualização
last_update = html.select_one("div.input-group option", selected=True).text
last_update = datetime.datetime.strptime(last_update, "%Y-%m-%d %H:%M:%S")
last_update -= datetime.timedelta(hours=7) # Convertendo de UTC+7 para UTC+0
data['last_update'] = last_update
# Definindo brawlers
data['brawlers'] = []
brawlers = div.select_one(f"table tbody").find_all("tr")
count = sorted((3, count, len(brawlers)))[1] # Mesma coisa que .clamp()
for i in range(count):
info = {}
brawler = brawlers[i].find_all('td')
info['rank'] = i + 1
info['name'] = brawler[1].text
info['star'] = float(brawler[3].text[0:-2]) # Formatando de '3.33 %' para 3.33
data['brawlers'].append(info)
return data
| DanielKMach/BotDusGuri | src/commands/utilities/brawlmeta.py | brawlmeta.py | py | 3,277 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "enum.Enum",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "discord.app_commands",
"line_number": 43,
"usage_type": "attribute"
},
{
"api_name": "bdg.BotDusGuri",
"line_number": 45,
"usage_type": "attribute"
},
{
"api_name": "discord.I... |
20420839973 | # -*- coding: utf-8 -*-
from threading import Thread
import queue
import json
import os , sys
#导入requests库(请求和页面抓取)
import requests
#导入time库(设置抓取Sleep时间)
import time
#导入random库(生成乱序随机数)
import random
#导入正则库(从页面代码中提取信息)
import re
#导入数值计算库(常规计算)
import numpy as np
from PIL import Image
from wordcloud import WordCloud
#导入科学计算库(拼表及各种分析汇总)
import pandas as pd
#导入绘制图表库(数据可视化)
import matplotlib.pyplot as plt
#导入结巴分词库(分词)
import jieba as jb
#导入结巴分词(关键词提取)
import jieba.analyse
f=open("rest_idx.txt", 'r')
#设置请求中头文件的信息
headers = {'User-Agent':'Mozilla/5.0 '
'(Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML,'
' like Gecko) Chrome/76.0.3809.132 '
'Safari/537.36',
#'Accept':'text/html;q=0.9,*/*;q=0.8',
#'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
#"Accept-Language": "zh-CN,zh;q=0.9",
#'Connection':'close',
'Referer':'https://www.jd.com/'
}
q = queue.Queue()
NUM = 5
JOBS = 10
#cookies=***
def crawl_jd_cmt_tag(prdtId):# change for url
url=r"https://sclub.jd.com/comment/" \
r"productPageComments.action?callback=fetchJSON_comment98vv106813&" \
r"productId={}&" \
r"score=0&sortType=5&page=0&pageSize=10&isShadowSku=0&fold=1".format(prdtId)
comment_tag_path = r'C:\TC-prog\JetBrain_pycharm_TC' \
r'\PycharmProjects\Crawler_EEFinal' \
r'\jd_cmt_tags\httpsitem.jd.com{}.html.txt'.format(prdtId)
try:
r=requests.get(url,headers=headers,timeout=5)
r.raise_for_status()
except:
print ('爬取失败')
raw = r.text[:]
pos = 0
for i in range(len(raw)):
if raw[i] == '(':
pos = i
try:
# data0 = re.sub(u'^fetchJSON_comment98vv106813\(', '', html)
r_json_str = r.text[pos + 1:-2]
# print (r_json_str)
r_json_obj=json.loads(r_json_str,strict=False)
print (r_json_obj)
r_json_tags=r_json_obj['hotCommentTagStatistics']
print ('狗东评论标签:')
# 追加模式,逐行写入
for r_json_tag in r_json_tags:
with open(comment_tag_path,'a+') as file:
file.write(r_json_tag['name']+
'\t'+str(r_json_tag['count'])+'\n')
print(r_json_tag['name']+
'\t'+str(r_json_tag['count']))
except:
print('failed')
def run():
global f
for line in f.readlines():
try:
pp = line.split('\t')
webpage = pp[1].strip('\n')
print(webpage)
temp = webpage[14:-5]
pos = 0
for i in range(len(temp)):
if temp[i] == 'm':
pos = i
itemID = temp[pos + 1:]
if (len(webpage) > 35):
continue
crawl_jd_cmt_tag(itemID)
time.sleep(random.random() * 3)
except:
print("Invalid Input!")
def working():
while True:
#arguments = q.get()
run()
q.task_done()
#fork NUM个线程等待队列
for i in range(NUM):
t = Thread(target=working)
t.setDaemon(True)
t.start()
#把JOBS排入队列
for i in range(JOBS):
q.put(i)
#阻塞,等待所有JOBS完成
q.join()
f.close() | ltzone/EE208Lab | jd_cmt_tags/_jd_cmt_TAGS.py | _jd_cmt_TAGS.py | py | 3,546 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "queue.Queue",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 59,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 73,
"usage_type": "call"
},
{
"api_name": "time.sleep",
"line_number": 1... |
74329032423 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Station',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),
('created', django_extensions.db.fields.CreationDateTimeField(blank=True, verbose_name='created', editable=False, default=django.utils.timezone.now)),
('modified', django_extensions.db.fields.ModificationDateTimeField(blank=True, verbose_name='modified', editable=False, default=django.utils.timezone.now)),
('name', models.TextField()),
],
options={
'ordering': ('-modified', '-created'),
'get_latest_by': 'modified',
'abstract': False,
},
),
]
| opendata-stuttgart/metaEFA | meta_efa/main/migrations/0001_initial.py | 0001_initial.py | py | 1,045 | python | en | code | 33 | github-code | 36 | [
{
"api_name": "django.db.migrations.Migration",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "django.db.migrations",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "django.db.migrations.CreateModel",
"line_number": 15,
"usage_type": "call"
},
... |
37314300998 | # -*- coding:utf-8 -*-
from openpyxl import Workbook
from datetime import datetime
def write_excel(filename):
wb = Workbook() # load_work(filename)
ws = wb.create_sheet('sheet', 0)
wb.remove('sheet')
ws = wb.active # default Sheet
ws.title = 'Pi'
ws['A1'] = 3.1415926
ws['A2'] = datetime.now().strftime('%Y-%m-%d')
ws['A3'] = '=sum(A1:A5)'
row = [1, 2, 3, 4]
ws.append(row)
rows = [
['id', 'name', 'department'],
['001', 'lee', 'cs'],
['002', 'lee', 'ma']
]
ws.append(rows)
wb.save(filename)
| huazhicai/Demo | openpyxl/demo2.py | demo2.py | py | 580 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "openpyxl.Workbook",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.now",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 14,
"usage_type": "name"
}
] |
43194848130 | import pickle as pkl
import numpy as np
from utils import clean_str
import scipy.sparse as sp
from tqdm import tqdm
from utils import clean_str
import torch
word_embeddings = dict()
with open('glove.840B.300d.txt', 'r') as f:
for line in f.readlines():
data = line.split(' ')
word_embeddings[str(data[0])] = list(map(float, data[1:]))
word_embedding_dim = 300
docs = open("data/mr/mr.clean.txt", 'r')
doc_list = docs.readlines()
docs.close()
# build vocab
word_set = set()
for doc_words in doc_list:
words = doc_words.split()
for word in words:
word_set.add(word)
word_set.add("<pad>")
vocab = list(word_set)
vocab_size = len(vocab)
oov = np.random.uniform(-0.01, 0.01, (vocab_size, word_embedding_dim))
labels = open("data/mr/mr.txt", 'r')
label_list = labels.readlines()
labels.close()
labels = []
for i in range(len(doc_list)):
labels.append(clean_str(label_list[i]).split()[-1])
label_set = set(labels)
label_set = list(label_set)
"""
def dependency_adj_matrix(text, window_size=11, weighted_graph=False):
# https://spacy.io/docs/usage/processing-text
doc_len = len(text)
# sliding windows
windows = []
if doc_len <= window_size:
windows.append(text)
for i in range(doc_len - window_size + 1):
window = text[i: i + window_size]
windows.append(window)
word_pair_count = {}
for window in windows:
for p in range(1, len(window)):
for q in range(0, p):
word_p = window[p]
word_p_id = word_id_map[word_p]
word_q = window[q]
word_q_id = word_id_map[word_q]
if word_p_id == word_q_id:
continue
word_pair_key = (word_p_id, word_q_id)
# word co-occurrences as weights
if word_pair_key in word_pair_count:
word_pair_count[word_pair_key] += 1.
else:
word_pair_count[word_pair_key] = 1.
# bi-direction
word_pair_key = (word_q_id, word_p_id)
if word_pair_key in word_pair_count:
word_pair_count[word_pair_key] += 1.
else:
word_pair_count[word_pair_key] = 1.
row = []
col = []
weight = []
for key in word_pair_count:
p = key[0]
q = key[1]
row.append(word_id_map[vocab[p]])
col.append(word_id_map[vocab[q]])
weight.append(word_pair_count[key] if weighted_graph else 1.)
for key in range(vocab_size):
row.append(key)
col.append(key)
weight.append(1.)
adj = sp.csr_matrix((weight, (row, col)), shape=(vocab_size, vocab_size))
adj = adj.tocoo()
adj = torch.sparse.FloatTensor(torch.LongTensor([adj.row.tolist(), adj.col.tolist()]),
torch.FloatTensor(adj.data.astype(np.float)))
# adj = normalize_adj(adj)
#matrix = np.zeros((vocab_size, vocab_size)).astype('float32')
#for row in range(doc_len):
# for tk in range(doc_len):
# matrix[row, tk] += adj[word_id_map[orig_doc[row]], word_id_map[orig_doc[tk]]]
return adj
"""
def dependency_adj_matrix(text, max_len, window_size=3, weighted_graph=False):
# https://spacy.io/docs/usage/processing-text
doc_len = len(text)
doc_vocab = list(set(text))
vocab_size = len(doc_vocab)
word_ids_map = {}
ids_word_map = {}
for j in range(vocab_size):
word_ids_map[doc_vocab[j]] = j
ids_word_map[j] = doc_vocab[j]
# sliding windows
windows = []
if doc_len <= window_size:
windows.append(text)
else:
for i in range(doc_len - window_size + 1):
window = text[i: i + window_size]
windows.append(window)
word_pair_count = {}
for window in windows:
for p in range(1, len(window)):
for q in range(0, p):
word_p = window[p]
word_p_id = word_ids_map[word_p]
word_q = window[q]
word_q_id = word_ids_map[word_q]
if word_p_id == word_q_id:
continue
word_pair_key = (word_p_id, word_q_id)
# word co-occurrences as weights
if word_pair_key in word_pair_count:
word_pair_count[word_pair_key] += 1.
else:
word_pair_count[word_pair_key] = 1.
# bi-direction
word_pair_key = (word_q_id, word_p_id)
if word_pair_key in word_pair_count:
word_pair_count[word_pair_key] += 1.
else:
word_pair_count[word_pair_key] = 1.
row = []
col = []
weight = []
for key in word_pair_count:
p = key[0]
q = key[1]
row.append(word_ids_map[doc_vocab[p]])
col.append(word_ids_map[doc_vocab[q]])
weight.append(word_pair_count[key] if weighted_graph else 1.)
for key in range(vocab_size):
row.append(key)
col.append(key)
weight.append(1.)
adj = sp.csr_matrix((weight, (row, col)), shape=(vocab_size, vocab_size))
matrix = np.zeros((max_len, max_len)).astype('float32')
for row in range(doc_len):
for tk in range(doc_len):
matrix[row, tk] += adj[word_ids_map[text[row]], word_ids_map[text[tk]]]
matrix = normalize_adj(matrix)
return matrix
def normalize_adj(adj):
"""Symmetrically normalize adjacency matrix."""
rowsum = np.array(adj.sum(1))
with np.errstate(divide='ignore'):
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = np.diag(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)
all_graphs = []
all_labels = []
all_features = []
all_sentences = []
max_seq_len = 35
for i in tqdm(range(len(doc_list))):
doc = doc_list[i].lower().strip()
# doc = clean_str(doc[0]) + " " + clean_str(doc[1])
doc = doc.split()[:max_seq_len]
doc_words = ["<pad>" for _ in range(max_seq_len)]
doc_words[:len(doc)] = doc[:]
features = []
for key in range(len(doc_words)):
if doc_words[key] in word_embeddings:
features.append(word_embeddings[doc_words[key]])
else:
features.append(oov[vocab.index(doc_words[key]), :])
features = np.array(features)
adj_matrix = dependency_adj_matrix(doc, max_len=max_seq_len)
one_hot = [0 for l in range(len(label_set))]
label_index = label_set.index(labels[i])
one_hot[label_index] = 1
all_features.append(features)
all_graphs.append(adj_matrix)
all_labels.append(np.array(one_hot))
sentence = []
for k in range(max_seq_len):
sentence.append(vocab.index(doc_words[k]))
all_sentences.append(sentence)
with open("data/mr/mr.all.features", 'wb') as f:
pkl.dump(all_features, f)
with open("data/mr/mr.all.adj", 'wb') as f:
pkl.dump(all_graphs, f)
with open("data/mr/mr.all.label", 'wb') as f:
pkl.dump(all_labels, f)
with open("data/mr/mr.all.sentence", 'wb') as f:
pkl.dump(all_sentences, f)
with open("data/mr/mr.all.vocab", 'wb') as f:
pkl.dump(vocab, f)
| MathIsAll/HDGCN-pytorch | build_fixed_graph.py | build_fixed_graph.py | py | 7,500 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "numpy.random.uniform",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "numpy.random",
"line_number": 30,
"usage_type": "attribute"
},
{
"api_name": "utils.clean_str",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "scipy.sparse.c... |
13442778323 | import os
import argparse
import tensorflow as tf
import numpy as np
from load import load_graph
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
"""
Adapted from https://gist.github.com/morgangiraud/4a062f31e8a7b71a030c2ced3277cc20#file-medium-tffreeze-3-py
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-m", dest='model_filename', type=str, help="frozen model .pb file to import")
args = parser.parse_args()
graph = load_graph(args.model_filename)
for op in graph.get_operations():
print(op.name)
X = graph.get_tensor_by_name('prefix/X:0')
keep_prob = graph.get_tensor_by_name('prefix/keep_prob:0')
output = graph.get_tensor_by_name('prefix/output:0')
with tf.Session(graph=graph) as sess:
prediction = sess.run(output, feed_dict={
X: np.random.randn(40, 66, 200, 3) * 100,
keep_prob: 1.0
})
print(prediction)
| Yunski/nvidia-cnn | test_load.py | test_load.py | py | 961 | python | en | code | 9 | github-code | 36 | [
{
"api_name": "os.environ",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "argparse.ArgumentParser",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "load.load_graph",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "tensorflow.Ses... |
1812506827 | import os
import re
import torch
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms as T
import utils
class MyDataset(Dataset):
def __init__(self, file_list: list, name2label, transform_flag=True):
self.file_list = file_list
self.name2label = name2label
self.transform_flag = transform_flag
self.aug_transforms = T.Compose([
# T.Resize((256, 256)),
T.ColorJitter(),
T.RandomRotation(30),
T.RandomHorizontalFlip(p=0.5),
T.RandomVerticalFlip(p=0.5),
])
def __getitem__(self, item):
image, label = self.transform(self.file_list[item], transform_flag=self.transform_flag)
return image, label
# @classmethod
def transform(self, filename, transform_flag):
# preprocess (default Identity)
image = Image.open(filename)
if transform_flag:
image = self.aug_transforms(image)
image = T.ToTensor()(image)
class_name = re.findall('\w+_[0-9]', os.path.split(filename)[-1])[0][:-2]
label = self.name2label[class_name]
return image, label
def __len__(self):
return len(self.file_list)
| newchexinyi/mobilefacenet | dataset.py | dataset.py | py | 1,225 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "torch.utils.data.Dataset",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "torchvision.transforms.Compose",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "torchvision.transforms",
"line_number": 16,
"usage_type": "name"
},
{
"ap... |
44265086055 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
df = pd.read_csv("File.txt", sep=" ")
#print(df)
moviewriter = animation.FFMpegWriter( fps=60)
fig = plt.figure(figsize=(12, 6))
with moviewriter.saving(fig, 'myfile.mp4', dpi=100):
integration_time = 100
i = integration_time
end = len(df.get("x"))
while( i < end):
ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax.set_xlabel('X')
ax.set_xlim([-0.02, 0.02])
ax.set_ylim([-0.02, 0.02])
ax.set_ylabel('Y')
ax2.set_xlim([-0.02, 0.02])
ax2.set_xlabel('Z')
ax2.set_ylim([-0.02, 0.02])
ax2.set_ylabel('Y')
for j in range(i - integration_time, i):
ax.plot(df.get("x")[j],df.get("y")[j], 'ko')
ax2.plot(df.get("z")[j],df.get("y")[j], 'ko')
print(j)
moviewriter.grab_frame()
i += 50
fig.clear()
moviewriter.finish()
| josephmckenna/2021_April_IOP_IntroductionToCpp_Part1 | extras/AnimateFigure.py | AnimateFigure.py | py | 1,004 | python | en | code | 6 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "matplotlib.animation.FFMpegWriter",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "matplotlib.animation",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "m... |
38110745441 | import os
import shutil
from pathlib import Path
def checkPathExists(filePath):
if not (os.path.exists(filePath)):
errorMessage = f'File Path not found: {filePath}'
print(errorMessage)
raise FileNotFoundError(errorMessage)
def recreateFolderPath(filepath):
if not (os.path.exists(filepath)):
print(f'Creating filepath: {filepath}')
os.mkdir(filepath)
else:
print(f'Recreating filepath: {filepath}')
shutil.rmtree(filepath)
os.mkdir(filepath)
def sortFilesByExtension(filePath):
#moves files to subfolders based on their extension type
#to make loading a bit easier
print('Sorting files by extension type')
fileExtensions = set()
files = []
for file in os.listdir(filePath):
if os.path.isfile(os.path.join(filePath, file)):
files.append(file)
fileExtensions.add(Path(file).suffix)
#create/recreate empty subfolders
for fileExtension in fileExtensions:
fileExtensionFolderName = fileExtension.replace('.','')
print(fileExtensionFolderName)
recreateFolderPath(os.path.join(filePath, fileExtensionFolderName))
for file in files:
fileExtensionFolderName = Path(file).suffix.replace('.','')
oldFilePath = os.path.join(filePath, file)
newFilePath = os.path.join(filePath, fileExtensionFolderName, file)
print(f'Moving {oldFilePath} to {newFilePath}')
shutil.move(oldFilePath, newFilePath)
| ibaadaleem/filmDatabase | fileManagement.py | fileManagement.py | py | 1,354 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.exists",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "os.path.exists",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number":... |
40165431906 | # -*- encoding: utf-8 -*-
from django import template
from django.contrib import admin
from django.conf import settings
register = template.Library()
'''
templatetag, obtiene la configuración del menú
'''
def get_config_menu():
return Menu.get_menu(self)
register.filter('get_config_menu')
class Menu(object):
menu_key = 'SOMBRA_MENU'
def __init__(self):
return None
def get_default_menu(self):
'''
Devuelve las opciones por defecto del menú
'''
return {
'MENU': (
'sites',
{'label': 'Custom', 'icon':None, 'models': (
'auth.group',
{'model': 'auth.user', 'label': 'Staff'}
)},
),
'LIST_PER_PAGE': 20,
}
def get_menu(self, param=None):
'''
Obtiene la configuración de settings.py
Ex: get_menu()
Ex: get_menu('MENU')
return dicc
'''
if hasattr(settings, menu_key):
menu = getattr(settings, menu_key, {})
else:
menu = get_default_menu()
if param:
menu_value = menu.get(param)
return menu_value
return menu | elmanos/vari | vari/localesapp/templatetags/menu.py | menu.py | py | 1,276 | python | es | code | 0 | github-code | 36 | [
{
"api_name": "django.template.Library",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "django.template",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "django.conf.settings",
"line_number": 45,
"usage_type": "argument"
},
{
"api_name": "django... |
24951711823 | from flask import render_template, request, redirect
from app import app
from models.book import *
from models.book_list import book_list, add_new_book, delete_book
@app.route('/')
def index():
return render_template('index.html', book_list = book_list)
@app.route('/stock')
def display_stock():
return render_template('display_books.html', book_list = book_list)
@app.route('/stock/<display_stock>')
def book_detail(display_stock):
chosen_book = book_list [int(display_stock)]
return render_template ('single_book.html', book = chosen_book, book_list = book_list)
@app.route('/stock/add')
def new_book():
return render_template('add_book.html')
@app.route('/stock', methods=['POST'])
def add_book():
title = request.form['title']
author = request.form['author']
genre = request.form['genre']
description = request.form['description']
if request.form.get('available'):
availability = True
else:
availability = False
new_book = Book (title, author, genre, description, availability)
add_new_book(new_book)
return redirect("/stock")
@app.route('/stock/delete/', methods =['POST'])
def delete():
index_to_delete = int(request.form["delete"])
delete_book(index_to_delete)
return redirect("/stock")
| sshingler/Flask-library_homework | controllers/controller.py | controller.py | py | 1,287 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.render_template",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "models.book_list.book_list",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "app.app.route",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "app.app",... |
19475555146 | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, HttpResponse, redirect, get_object_or_404
from django.core.paginator import Paginator
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.http import JsonResponse, HttpResponseRedirect
from .models import *
import json
import math
from django.db.models import Q, Max, Min
# Create your views here.
def myAbout(me):
try:
about = About.objects.get(user=me)
except :
about = About.objects.create(user=me)
return about
@login_required(login_url='/accounts/login/')
def home(request):
allposts = Post.objects.all().order_by('-id')
paginator = Paginator(allposts, 2)
page_number = request.GET.get('page')
post = paginator.get_page(page_number)
aboutMe = myAbout(request.user)
followingUserId = []
followingUser = aboutMe.following.all()
for i in followingUser:
followingUserId.append(i.id)
randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5]
#randomUser = list(randomUser.values())
randomUserList = []
for i in randomUser:
l = {}
l['id'] = i.id
l['username'] = i.username
aboutUser = myAbout(i)
l['profilePicture'] = aboutUser.profilePicture.url
randomFollower = aboutUser.followed_by.all().order_by('?').first()
if request.user in aboutUser.following.all():
l['randomFollower'] = 'Follows you'
elif randomFollower == None:
l['randomFollower'] = 'New to Instagram'
else:
l['randomFollower'] = randomFollower.username
randomUserList.append(l)
storiesIdList = []
stories = Post.objects.all().order_by('?')[:7]
for i in stories:
aboutUser = About.objects.get(user=i.user).profilePicture
i.userProfilePicture = aboutUser
storiesIdList.append(i.id)
return render(request, 'home.html', {
'home': True,
'post': post,
'aboutMe': aboutMe,
'randomUser': randomUserList,
'stories': stories,
'storiesIdList': storiesIdList,
})
@login_required(login_url='/accounts/login/')
def getMorePost(request):
data = json.loads(request.body.decode("utf-8"))
if request.method == 'POST':
postId = data['postId']
post2 = Post.objects.exclude(id__in=postId).order_by('?')[:3]#[(page_number-1)*2:page_number*2]
# for i in post2:
# print(i.image.url)
post = list(post2.values())
for i in post:
user = User.objects.get(id=i['user_id'])
i['userId'] = user.id
i['userfullname'] = user.first_name+' '+user.last_name
aboutUser = myAbout(user)
i['userProfilePricture'] = aboutUser.profilePicture.url
postt = Post.objects.get(id=i['id'])
i['image'] = postt.image.url
i['totallikes'] = postt.liked_by.count()
if request.user in postt.liked_by.all():
i['isLiked'] = True
else:
i['isLiked'] = False
comments = Comment.objects.filter(post=postt)[:2]
comments2 = list(comments.values())
for ii in comments2:
userfullname2 = User.objects.get(id=ii['user_id']).first_name
ii['userfullname'] = userfullname2
i['comments'] = comments2
i['totalComments'] = Comment.objects.filter(post=postt).count()
return JsonResponse({'response': post})
@login_required(login_url='/accounts/login/')
def getMoreComments(request, pk):
post = get_object_or_404(Post, pk=pk)
page = json.loads(request.body.decode("utf-8"))['page']
page = int(page) - 1
comments = Comment.objects.filter(post=post)[5*page+2:5*(page+1)+2]
comments2 = list(comments.values())
for ii in comments2:
userfullname2 = User.objects.get(id=ii['user_id']).first_name
ii['userfullname'] = userfullname2
return JsonResponse({'response': comments2})
@login_required(login_url='/accounts/login/')
def likePost(request, pk):
user = request.user
try:
post = get_object_or_404(Post, pk=pk)
post.liked_by.add(user)
if not Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).exists():
Notification.objects.create(user1=post.user, user2=user, topic='like', post=post)
return JsonResponse({'response': 'liked'})
except:
return JsonResponse({'response': '404'})
@login_required(login_url='/accounts/login/')
def cancelLikePost(request, pk):
user = request.user
try:
post = get_object_or_404(Post, pk=pk)
post.liked_by.remove(user)
if Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).exists():
Notification.objects.filter(user1=post.user, user2=user, topic='like', post=post).delete()
return JsonResponse({'response': 'likeCanceled'})
except:
return JsonResponse({'response': '404'})
@login_required(login_url='/accounts/login/')
def addComment(request, pk):
user = request.user
post = get_object_or_404(Post, pk=pk)
data = json.loads(request.body.decode("utf-8"))
Comment.objects.create(user=user, post=post, body=data['body'])
#create notification
if not Notification.objects.filter(user1=post.user, user2=user, topic='comment', post=post).exists():
Notification.objects.create(user1=post.user, user2=user, topic='comment', post=post)
return JsonResponse({'response': 'ok'})
@login_required(login_url='/accounts/login/')
def message(request):
me = request.user
myAllMsg = Message.objects.filter(Q(sender = me)|Q(receiver = me)).order_by('-date')
conversationList = []
for lastMsg in myAllMsg:
if lastMsg.sender == me:
if lastMsg.receiver not in conversationList:
conversationList.append(lastMsg.receiver)
else:
if lastMsg.sender not in conversationList:
conversationList.append(lastMsg.sender)
conversationList2 = []
for i in conversationList:
l = {}
l['id'] = i.id
l['username'] = i.username
lm = Message.objects.filter(Q(sender = me, receiver = i)|Q(receiver = me, sender = i)).last()
try:
lmb = lm.body
if len(lmb) > 50:
lmb = lmb[:50] + '...'
except:
lmb = 'Sent an Image'
l['lm'] = lmb
user = User.objects.get(id = i.id)
aboutUser = myAbout(user)
l['profilePicture'] = aboutUser.profilePicture.url
conversationList2.append(l)
try:
myChatList = About.objects.get(user=me)
except:
myChatList = About.objects.create(user=me)
for i in myChatList.chatList.all():
if i not in conversationList:
l = {}
l['id'] = i.id
l['username'] = i.username
l['lm'] = 'Active 1 hour ago'
user = User.objects.get(id = i.id)
aboutUser = myAbout(user)
l['profilePicture'] = aboutUser.profilePicture.url
conversationList2.append(l)
aboutMe = myAbout(request.user)
return render(request, 'message.html', {
'message': True,
'conversationList': conversationList2,
'aboutMe': aboutMe,
})
@login_required(login_url='/accounts/login/')
def conversation(request, pk):
page = json.loads(request.body.decode("utf-8"))['pageNo']
user1 = request.user.id
user2 = User.objects.get(id=pk).id
msg = Message.objects.filter(Q(receiver = user1, sender = user2)|Q(sender = user1, receiver = user2)).order_by('-date')[(page-1)*10:page*10]#.reverse()
moreMessage = True
if msg.count() == 0:
moreMessage = False
messages = list(msg.values())
return JsonResponse({'messages': messages, 'moreMessage': moreMessage})
@login_required(login_url='/accounts/login/')
def sendMessage(request):
sender = request.user
try:
data = json.loads(request.body.decode("utf-8"))
receiverId = data['receiver']
receiver = User.objects.get(id=receiverId)
body = data['body']
Message.objects.create(sender=sender, receiver=receiver, body=body)
return JsonResponse({'response': 'sent'})
except:
image = request.FILES.get('image')
receiverId = request.POST.get('receiver')
receiver = User.objects.get(id=receiverId)
Message.objects.create(sender=sender, receiver=receiver, image=image)
return JsonResponse({'response': 'sent'})
@login_required(login_url='/accounts/login/')
def sendMessageFromStories(request):
data = json.loads(request.body.decode("utf-8"))
post = data['postId']
receiver = Post.objects.get(id=post).user
#receiver = User.objects.get(id=receiverId)
body = data['body']
sender = request.user
Message.objects.create(sender=sender, receiver=receiver, body=body)
return JsonResponse({'response': 'sent'})
@login_required(login_url='/accounts/login/')
def explore(request):
posts = Post.objects.all().order_by('?')[:12]
for i in posts:
i.totalLikes = i.liked_by.all().count()
i.totalComments = Comment.objects.filter(post=i.id).count()
try:
data = json.loads(request.body.decode("utf-8"))['exploreItemId']
posts2 = Post.objects.all().exclude(id__in = data).order_by('?')[:12]
noMoreExplorePost = False
posts3 = list(posts2.values())
countPost = posts2.count()
if countPost < 12:
needMore = 12-countPost
morePosts = Post.objects.all().order_by('?')[:needMore]
posts3.append(list(morePosts.values())[0])
noMoreExplorePost = True
for i in posts3:
p = Post.objects.get(id=i['id'])
i['totalLikes'] = p.liked_by.all().count()
i['totalComments'] = Comment.objects.filter(post=p.id).count()
i['image'] = p.image.url
return JsonResponse({'posts': posts3, 'noMoreExplorePost': noMoreExplorePost})
except:
pass
# allPosts = list(posts.values())
# for i in allPosts:
# comments = Comment.objects.filter(post = i['id']).count()
# totalLikes = Post.objects.get(id=i['id']).liked_by.all().count()
# i['totalLikes'] = totalLikes
# i['totalComments'] = comments
aboutMe = myAbout(request.user)
return render(request, 'explore.html', {
'explore': True,
'posts': posts,
'aboutMe': aboutMe,
})
@login_required(login_url='/accounts/login/')
def exploreMore(request, pk):
post = Post.objects.get(id=pk)
post.totalLikes = post.liked_by.all().count()
post.totalComments = Comment.objects.filter(post=pk).count()
userAbout = myAbout(post.user)
post.userProfilePicture = userAbout.profilePicture.url
post.userId = post.user.id
try:
post.firstComment = Comment.objects.filter(post=pk)[:1][0]
except :
post.firstComment = False
try:
post.secondComment = Comment.objects.filter(post=pk)[1:2][0]
except :
post.secondComment = False
#print(post.secondComment.values())
aboutMe = myAbout(request.user)
followingUserId = []
followingUser = aboutMe.following.all()
for i in followingUser:
followingUserId.append(i.id)
randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5]
#randomUser = list(randomUser.values())
randomUserList = []
for i in randomUser:
l = {}
l['id'] = i.id
l['username'] = i.username
aboutUser = myAbout(i)
l['profilePicture'] = aboutUser.profilePicture.url
randomFollower = aboutUser.followed_by.all().order_by('?').first()
if request.user in aboutUser.following.all():
l['randomFollower'] = 'Follows you'
elif randomFollower == None:
l['randomFollower'] = 'New to Instagram'
else:
l['randomFollower'] = randomFollower.username
randomUserList.append(l)
return render(request, 'exploremore.html', {
'p': post,
'aboutMe': aboutMe,
'randomUser': randomUserList,
'exploreMore': True,
})
@login_required(login_url='/accounts/login/')
def profile(request, pk):
#myUsername = request.user.username
user = User.objects.get(id=pk)
aboutUser = myAbout(user)
userPosts = Post.objects.filter(user=user).order_by('-date')
# for i in userPosts:
# i.image = i.image.url
# i.totalLikes = i.liked_by.all().count()
# print(i.liked_by.all().count())
# i.totalComments = Comment.objects.filter(post=i.id).count()
# print(i.totalLikes)
# print(userPosts.values())
posts = []
zero = 0
zero2 = 0
lenOfPosts = len(userPosts)
userPosts = userPosts.values()
isFollowing = False
if request.user in aboutUser.followed_by.all():
isFollowing = True
subListLen = math.ceil(lenOfPosts/3)
while zero < subListLen:
subList = []
while len(subList) < 3:
try:
subList.append(userPosts[zero2])
zero2 += 1
except :
break
posts.append(subList)
zero += 1
for i in posts:
for j in i:
post = Post.objects.get(id=j['id'])
j['image'] = post.image.url
j['totalLikes'] = post.liked_by.all().count()
j['totalComments'] = Comment.objects.filter(post=post).count()
aboutMe = myAbout(request.user)
totalPosts = Post.objects.filter(user=user).count()
return render(request, 'profile.html',{
'aboutMe': aboutMe,
'user': user,
'aboutUser': aboutUser,
'userPosts': posts,
'totalPosts': totalPosts,
'isFollowing': isFollowing,
})
@login_required(login_url='/accounts/login/')
def userPosts(request, pk):
post = Post.objects.get(id=pk)
post.totalLikes = post.liked_by.all().count()
post.totalComments = Comment.objects.filter(post=pk).count()
userAbout = myAbout(post.user)
post.userProfilePicture = userAbout.profilePicture.url
try:
post.firstComment = Comment.objects.filter(post=pk)[:1][0]
except :
post.firstComment = False
try:
post.secondComment = Comment.objects.filter(post=pk)[1:2][0]
except :
post.secondComment = False
#print(post.secondComment.values())
aboutMe = myAbout(request.user)
followingUserId = []
followingUser = aboutMe.following.all()
for i in followingUser:
followingUserId.append(i.id)
randomUser = User.objects.all().exclude(id__in = followingUserId).exclude(id=request.user.id).order_by('?')[:5]
#randomUser = list(randomUser.values())
randomUserList = []
for i in randomUser:
l = {}
l['id'] = i.id
l['username'] = i.username
aboutUser = myAbout(i)
l['profilePicture'] = aboutUser.profilePicture.url
randomFollower = aboutUser.followed_by.all().order_by('?').first()
if request.user in aboutUser.following.all():
l['randomFollower'] = 'Follows you'
elif randomFollower == None:
l['randomFollower'] = 'New to Instagram'
else:
l['randomFollower'] = randomFollower.username
randomUserList.append(l)
return render(request, 'userposts.html', {
'p': post,
'aboutMe': aboutMe,
'randomUser': randomUserList,
'exploreMore': True,
})
@login_required(login_url='/accounts/login/')
def getMoreUserPost(request):
data = json.loads(request.body.decode("utf-8"))
if request.method == 'POST':
postId = data['postId']
post2 = Post.objects.filter(id__lt = postId[0], user = Post.objects.get(id=postId[0]).user).exclude(id__in=postId).order_by('-date')[:2]#[(page_number-1)*2:page_number*2]
# for i in post2:
# print(i.image.url)
post = list(post2.values())
for i in post:
user = User.objects.get(id=i['user_id'])
i['userfullname'] = user.first_name+' '+user.last_name
i['userId'] = user.id
aboutUser = myAbout(user)
i['userProfilePricture'] = aboutUser.profilePicture.url
postt = Post.objects.get(id=i['id'])
i['image'] = postt.image.url
i['totallikes'] = postt.liked_by.count()
if request.user in postt.liked_by.all():
i['isLiked'] = True
else:
i['isLiked'] = False
comments = Comment.objects.filter(post=postt)[:2]
comments2 = list(comments.values())
for ii in comments2:
userfullname2 = User.objects.get(id=ii['user_id']).first_name
ii['userfullname'] = userfullname2
i['comments'] = comments2
i['totalComments'] = Comment.objects.filter(post=postt).count()
return JsonResponse({'response': post})
@login_required(login_url='/accounts/login/')
def editProfile(request):
aboutMe = myAbout(request.user)
if request.method == 'POST':
try:
profilePicture = request.FILES['pp']
if request.user.about:
currentPP = request.user.about.profilePicture
if not currentPP.url == '/media/images/useravater.png':
currentPP.delete(save=True)
request.user.about.profilePicture=profilePicture
request.user.about.save()
except :
pass
username = request.POST['username']
if User.objects.filter(username=username).exists() and username != request.user.username:
messages.error(request, 'This Username is already taken')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
if ' ' in username or len(username) < 1:
messages.error(request, 'Invalid username')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
fullname = request.POST['fullName']
website = request.POST['website']
bio = request.POST['bio']
email = request.POST['email']
try:
User.objects.filter(id=request.user.id).update(username=username, first_name = fullname, email=email)
About.objects.filter(user=request.user).update(website=website, bio=bio)
messages.success(request, 'Profile updated successfully.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
except :
messages.error(request, 'Can\'t update your profile')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
return render(request, 'editprofile.html',{
'aboutMe': aboutMe,
})
@login_required(login_url='/accounts/login/')
def uploadPhoto(request):
#myUsername = request.user.username
aboutMe = myAbout(request.user)
return render(request, 'uploadphoto.html',{'aboutMe': aboutMe})
@login_required(login_url='/accounts/login/')
def photoUploadHandler(request):
user = request.user
if request.method == 'POST':
img = request.FILES['photo']
caption = request.POST['caption']
Post.objects.create(user=user, image=img, caption = caption)
return redirect('/profile/'+str(request.user.id))
@login_required(login_url='/accounts/login/')
def follow(request, pk):
me = request.user
user = User.objects.get(id=pk)
aboutMe = myAbout(me)
aboutUser = myAbout(user)
aboutMe.following.add(user)
aboutMe.chatList.add(user)
aboutUser.followed_by.add(me)
aboutUser.chatList.add(me)
# Creating Notification
if not Notification.objects.filter(user1 = user, user2=me, topic = 'follow').exists():
Notification.objects.create(user1 = user, user2=me, topic = 'follow')
return JsonResponse({'response': 'ok'})
@login_required(login_url='/accounts/login/')
def unfollow(request, pk):
me = request.user
user = User.objects.get(id=pk)
aboutMe = myAbout(me)
aboutUser = myAbout(user)
aboutMe.following.remove(user)
aboutMe.chatList.remove(user)
aboutUser.followed_by.remove(me)
aboutUser.chatList.remove(me)
# deleting notification
if Notification.objects.filter(user1 = user, user2=me, topic = 'follow').exists():
Notification.objects.filter(user1 = user, user2=me, topic = 'follow').delete()
return JsonResponse({'response': 'ok'})
@login_required(login_url='/accounts/login/')
def getNotifications(request):
user1 = request.user
n = Notification.objects.filter(user1=user1).order_by('-date')[:10]
n = list(n.values())
for i in n:
i['profilePicture'] = myAbout(User.objects.get(id=i['user2_id'])).profilePicture.url
i['who'] = User.objects.get(id=i['user2_id']).username
return JsonResponse({'response': n})
@login_required(login_url='/accounts/login/')
def searchUser(request):
name = json.loads(request.body.decode("utf-8"))['name']
users = User.objects.filter(Q(username__icontains = name) | Q(first_name__icontains = name))#.filter(first_name__icontains = name)
users = list(users.values())
for i in users:
del i['password']
del i['email']
del i['last_login']
del i['date_joined']
i['profilePicture'] = myAbout(User.objects.get(id=i['id'])).profilePicture.url
return JsonResponse({'response': users})
def handleSignup(request):
data = json.loads(request.body.decode("utf-8"))
if request.method == 'POST':
username = data['username']
email = data['email']
pass1 = data['pass1']
pass2 = data['pass2']
if len(username) < 1:
return JsonResponse({'response':'Username can\'t be empty.'})
if ' ' in username:
return JsonResponse({'response':'Username must contain letters, digits and @/./+/-/_ only.'})
if pass1!=pass2:
return JsonResponse({'response':'The two password field didn\'t match.'})
if User.objects.filter(username=username).exists():
return JsonResponse({'response':'This username is already taken. Please try another one.'})
if len(pass1) < 4:
return JsonResponse({'response':'Your password must contain at least 4 characters.'})
try:
myuser = User.objects.create_user(username, email, pass1)
myuser.first_name = data['fullname']
myuser.save()
#messages.success(request, 'Your account created successfully.')
except:
return JsonResponse({'response':'Username must contain letters, digits and @/./+/-/_ only.'})
user = authenticate(username=username, password=pass1)
if user is not None:
login(request, user)
#messages.success(request, 'You are Logged in.')
return JsonResponse({'response':'ok'})
else:
return HttpResponse('404 - Page Not Found')
def handleLogin(request):
data = json.loads(request.body.decode("utf-8"))
if request.method == 'POST':
username = data['username']
password = data['pass']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
#messages.success(request, 'You are now Logged in.')
return JsonResponse({'response': 'ok'})
else:
return JsonResponse({'response': 'Invalid username or password, please try again'})
else:
return HttpResponse('404 - Page Not Found')
def handleLogout(request):
logout(request)
#messages.warning(request, 'You are Logged out.')
#return JsonResponse({'response': 'ok'})
return redirect(request.META['HTTP_REFERER'])
| Asif-Biswas/instagram-clone | instagram2/views.py | views.py | py | 24,038 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "django.core.paginator.Paginator",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "django.shortcuts.render",
"line_number": 63,
"usage_type": "call"
},
{
"api_name": "django.contrib.auth.decorators.login_required",
"line_number": 22,
"usage_type": ... |
16821571488 | # Author: Bill Pengyuan Zhai. Harvard University. Yelin Group. Oct 2022
from Utils_torch_version import Network, get_nn_pairs, binary_basis, unpacknbits
import numpy as np
import matplotlib.pyplot as plt
from scipy import sparse
import scipy
import scipy.linalg
import qiskit
import time
import torch
import math
# try another way of evolving
# The sparse H_OP is a sparse.csr matrix. Useful for calculating via scipy diagonalization. Does not involve qiskit classes
def initialize_sparse(conn_i, conn_j, a, b, c, d): #
print('debug a, b, c, d)',(a, b, c, d))
sx = sparse.csr_matrix(np.array([[0., 1.], [1., 0.]]))
sy = sparse.csr_matrix(np.array([[0 , -1j], [1j , 0]]))
sz = sparse.csr_matrix(np.array([[1., 0.], [0., -1.]]))
id = sparse.csr_matrix(np.eye(2))
# A list of single x, y, z operator applied on the site i_site
sx_list = []
sy_list = []
sz_list = []
for i_site in range(N):
x_ops = [id] * N
y_ops = [id] * N
z_ops = [id] * N
x_ops[i_site] = sx
y_ops[i_site] = sy
z_ops[i_site] = sz
X = x_ops[0]
Y = y_ops[0]
Z = z_ops[0]
for j in range(1, N):
X = sparse.kron(X, x_ops[j], 'csr')
Y = sparse.kron(Y, y_ops[j], 'csr')
Z = sparse.kron(Z, z_ops[j], 'csr')
sx_list.append(X)
sy_list.append(Y)
sz_list.append(Z)
# H_zz = sparse.csr_matrix((2**N, 2**N))
# H_xx = sparse.csr_matrix(np.zeros((2**N, 2**N)), dtype=np.complex128)
# H_yy = sparse.csr_matrix(np.zeros((2**N, 2**N)), dtype=np.complex128)
# H_xy = sparse.csr_matrix(np.zeros((2**N, 2**N)), dtype=np.complex128)
# H_yx = sparse.csr_matrix(np.zeros((2**N, 2**N)), dtype=np.complex128)
# H_z = sparse.csr_matrix(np.zeros((2**N, 2**N)),dtype=np.complex128)
#H_zzzi = sparse.csr_matrix((2**N, 2**N),dtype=np.complex128)
# H_zz = H_zz + sz_list[i] * sz_list[j]
H_xx = sx_list[conn_i] @ sx_list[conn_j]
H_yy = sy_list[conn_i] @ sy_list[conn_j]
H_xy = sx_list[conn_i] @ sy_list[conn_j]
H_yx = sy_list[conn_i] @ sx_list[conn_j]
H_zzz_id = sparse.csr_matrix(np.eye(2**N), dtype=np.complex128) # This is a diagonal of real numbers
for i in range(conn_i, conn_j):
H_zzz_id = sz_list[i] @ H_zzz_id
H_z = - (a/2) * sz_list[conn_i] - (b/2) * sz_list[conn_j]
H = H_z + ( (1.0j*c/2) * H_xy - (1.0j*c/2) * H_yx + (d*(1.0j)/2) * H_xx + (d*(1.0j)/2) * H_yy ) @ H_zzz_id
# print('H_z', H_z)
# print('H_xy',H_xy)
# print('H_yx',H_yx)
# print('H_xx',H_xx)
# print('H_yy',H_yy)
# print('debug H', H) # Somehow this doesn't come out to be Hermitian lol
# print('debug iH', 1j* H)
return H.todense()
Ns = [2,4,6,8]
reps = 1
avg_time_at_N_fermion, avg_time_at_N_exact = [], []
q_fidelities_all_runs, TVs_all_runs = [], []
for N in Ns:
print('start N: ', N)
conn_list = [ [np.min(p), np.max(p)] for p in get_nn_pairs(geometry=(N,))]*3 # zero indexed and should not be periodic (not a closed circle)
#conn_list = [[i, N-1] for i in range(N-1)]*2
#conn_list = [[0,1]]
# conn_list = []
times_fermion = []
times_exact = []
for rep in range(reps):
L = len(conn_list) # Number of layers
# initiliaze the circuit
circuit = Network(conn_list, N)
x = torch.tensor([[1,0]*int(N/2)]) if N%2==0 else torch.tensor([[1,0]*int(N/2)+[1]]) # The 1010101... single basis state
x_string = '10'*int(N/2)+'1' if N%2==1 else '10'*int(N/2)
init_state_numpy = qiskit.quantum_info.Statevector.from_label(x_string).data
# Fix this, the parameters are defined differently now for the pytorch implementation
params_m = torch.tensor(math.pi) * torch.rand((L, 4))
print('params_m',params_m)
circuit.manual_set_params(params_m)
basis_m_n_half = torch.tensor(binary_basis(geometry=(N//2,)))
basis_m_n = torch.tensor(binary_basis(geometry=(N,)))
probs = torch.zeros(2**(N//2), dtype=torch.cfloat)
# amps = torch.zeros(2**(N), dtype=torch.cfloat)
ts = time.time()
# sums = torch.sum(basis_m_n, axis=1)
# print('sums', sums)
# diff = sums-torch.sum(x) # a list of differences in the number of Fermions
# print('diff', diff)
# indices = (diff == 0).nonzero().flatten() # these are the indices where probability can be nonzero
# print('indices', indices)
# # Prepare the batches
n_batches = len(basis_m_n_half)//10 if len(basis_m_n_half)%10 == 0 else len(basis_m_n_half)//10+1
# n_batches = len(basis_m_n)//10 if len(basis_m_n)%10 == 0 else len(basis_m_n)//10+1
for i in range(n_batches):
y_batch = basis_m_n_half[10*i : 10*(i+1)]
# y_batch = basis_m_n[10*i : 10*(i+1)]
x_batch = x.repeat(y_batch.shape[0], 1) # a batch of 10
sub_mask_batch = (torch.tensor([ [1]*(N//2)+[0]*(N//2) ])).repeat(y_batch.shape[0], 1) # Measure the first half
# sub_mask_batch = (torch.tensor([ [1]*N ])).repeat(y_batch.shape[0], 1)
print('y_batch, x_batch, sub_mask_batch', (y_batch, x_batch, sub_mask_batch))
probs_batch = circuit.forward_partial_observation(y_batch, x_batch, sub_mask_batch)
print('debug probs_batch', probs_batch)
# Now put these amp_batch values into correct positions
probs[10*i : 10*(i+1)] = probs_batch
print('probs', probs)
probs = probs.detach().numpy()
tf = time.time()
times_fermion.append(tf - ts)
ts = time.time()
exp_iH_exact = np.eye(2**N)
for l in range(L):
conn = conn_list[l]
a, b, c, d = params_m.detach().numpy()[l]
H_exact = initialize_sparse(conn[0], conn[1], a, b, c, d)
exp_iH_exact = (scipy.linalg.expm(-1.0j*H_exact))@exp_iH_exact # 1.0j or -1.0j?
state_exact = np.matmul(exp_iH_exact, init_state_numpy[:,None])
tf = time.time()
times_exact.append(tf - ts)
rho_A = qiskit.quantum_info.partial_trace(state_exact, [i for i in np.arange(N//2)])
# rho_A = qiskit.quantum_info.partial_trace(state_exact, [i for i in np.arange(N//2, N)])
rho_test = qiskit.quantum_info.partial_trace(state_exact, [i for i in np.arange(N-1)])
print('rho_test', rho_test)
# rho_A = qiskit.quantum_info.partial_trace(state_exact, [])
probs_exact = (np.abs(np.diag(rho_A.data))).squeeze()
# probs_exact = (np.abs(state_exact)**2).squeeze()
print('rho_A', rho_A)
# print('exact evolved state', state_exact)
# print('exact evolved prob', probs_exact)
probs_fermion = probs
# print('fermion state', amps)
# print('Fermion probs', probs_fermion)
# print('sum Fermion probs', sum(probs_fermion))
plt.plot(probs_exact, '^-')
plt.plot(probs_fermion, 'x')
plt.legend(['exact probs', 'Fermion_probs'])
plt.title('(N, rep)='+str((N, rep)))
plt.savefig('img_torch/(N, rep)='+str((N, rep))+'.png')
plt.close()
# calculate the quantum fidelity
#q_fidelity1 = np.abs((np.conjugate(amps).dot(state_exact[:,0])))**2
#print('debug amps', amps)
#q_fidelity1 = qiskit.quantum_info.state_fidelity(qiskit.quantum_info.Statevector(amps), rho_A)
#fidelity2 = np.abs((np.conjugate(state_exact[:,0]).dot(amps)))**2
#print('q_fidelity', q_fidelity1)
print('debug probs_fermion shape', probs_fermion.shape)
print('debug probs_exact shape', probs_exact.shape)
print('diff', probs_fermion-probs_exact)
tv = np.sum(np.abs(probs_fermion-probs_exact))
print('tv', tv)
#q_fidelities_all_runs.append(q_fidelity1)
TVs_all_runs.append(tv)
avg_time_fermion = sum(times_fermion)/reps
std_time_fermion = np.std(times_fermion)
avg_time_exact = sum(times_exact)/reps
std_time_exact = np.std(times_exact)
avg_time_at_N_fermion.append(avg_time_fermion)
avg_time_at_N_exact.append(avg_time_exact)
print('avg_time_at_N_fermion', avg_time_at_N_fermion)
print('avg_time_at_N_exact', avg_time_at_N_exact)
plt.plot(Ns, avg_time_at_N_fermion)
plt.plot(Ns, avg_time_at_N_exact)
plt.plot(Ns, avg_time_at_N_fermion+std_time_fermion, '+')
plt.plot(Ns, avg_time_at_N_fermion-std_time_fermion, '-')
plt.plot(Ns, avg_time_at_N_exact+std_time_exact, '^')
plt.plot(Ns, avg_time_at_N_exact-std_time_exact, 'v')
plt.legend(['avg_time_at_N_fermion', 'avg_time_at_N_exact'])
plt.title('Runtime vs N-qubit sizes')
plt.savefig('img/Runtime.png')
plt.close()
# print('q fidelities_all_runs', q_fidelities_all_runs)
# plt.plot(q_fidelities_all_runs)
# plt.title('q fidelities at all runs')
# plt.savefig('img_torch/q_fidelities.png')
print('TVs_all_runs', TVs_all_runs)
plt.plot(TVs_all_runs)
plt.title('TVs at all runs')
plt.savefig('img_torch/TVs.png')
| BILLYZZ/NFNet | Benchmark_torch_version_partial.py | Benchmark_torch_version_partial.py | py | 9,049 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "scipy.sparse.csr_matrix",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "scipy.sparse",
"line_number": 18,
"usage_type": "name"
},
{
"api_name": "numpy.array",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "scipy.sparse.csr_mat... |
13123666146 | #!/usr/bin/env python
# coding: utf-8
# # Finding appropriate parametric models
# - Code from: https://lifelines.readthedocs.io/en/latest/Examples.html
# In[1]:
# Imports
from lifelines import *
from lifelines.plotting import qq_plot
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# ## OxyTarget
# In[2]:
response = pd.read_csv('/Users/mikkorekstad/Skole/master_data/prepared_data/oxytarget/oxytarget_RO_response.csv', index_col='ID')
# Target columns
time = 'Time until OS event'
event = 'OS event'
T = response[time]
E = response[event]
# In[3]:
from lifelines.utils import find_best_parametric_model
best_model, best_aic_ = find_best_parametric_model(event_times=T,
event_observed=E,
scoring_method="AIC")
# In[4]:
best_model
# In[5]:
best_aic_
# In[6]:
response.describe()
# In[7]:
plt.clf()
sns.set_style('white')
sns.set_context("paper", font_scale = 2)
sns.displot(data=response, x=time, kind="hist", bins = 25, aspect = 1.5, hue=event, multiple="stack")
plt.show()
# In[8]:
plt.clf()
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed=E)
kmf.survival_function_.plot()
plt.grid()
plt.title('Kaplan Meier Estimate OxyTarget')
plt.show()
# In[9]:
plt.clf()
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes = axes.reshape(4,)
models = [WeibullFitter(), LogNormalFitter(), LogLogisticFitter(), ExponentialFitter()]
model_names = ['Weibull', 'LogNormal', 'LogLogistic', 'Exponential']
oxy_dict = {}
for i, model in enumerate(models):
model.fit(T, E)
qq_plot(model, ax=axes[i], grid=True)
axes[i].grid()
print(f'{model_names[i]}: Log Likelihood [{model.log_likelihood_:.1f}], AIC [{model.AIC_:.1f}]')
oxy_dict[model_names[i]] = f'{model.AIC_:.1f}'
fig.suptitle('OxyTarget QQ-Plots', fontsize=16)
plt.tight_layout()
plt.show()
# ### Discussion
# - QQ-plot suggests that lognormal is the best fitting parametric distribution.
# - This is supported by LogNormal: Log Likelihood [-313.676], AIC [631.352]
# - AIC lower is better
# - Log Likelihood higher is better
# ## Head Neck
# In[10]:
response = pd.read_csv('/Users/mikkorekstad/Skole/master_data/prepared_data/headneck/response.csv', index_col='ID')
# Target columns
time = 'OS'
event = 'event_OS'
T = response[time]
E = response[event]
# In[11]:
response.describe()
# In[12]:
plt.clf()
sns.set_style('white')
sns.set_context("paper", font_scale = 2)
sns.displot(data=response, x=time, kind="hist", bins = 25, aspect = 1.5, hue=event, multiple="stack")
plt.show()
# In[13]:
plt.clf()
kmf = KaplanMeierFitter()
kmf.fit(T, event_observed=E)
kmf.survival_function_.plot()
plt.grid()
plt.title('Kaplan Meier Estimate Head Neck')
plt.show()
# kmf.cumulative_density_.plot()
# In[14]:
type(models[i])
# In[15]:
plt.clf()
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
#plt.title()
axes = axes.reshape(4,)
models = [WeibullFitter(), LogNormalFitter(), LogLogisticFitter(), ExponentialFitter()]
model_names = ['Weibull', 'LogNormal', 'LogLogistic', 'Exponential']
hnc_dict = {}
for i, model in enumerate(models):
model.fit(T, E)
qq_plot(model, ax=axes[i], grid=True)
axes[i].grid()
print(f'{model_names[i]}: Log Likelihood [{model.log_likelihood_:.3f}], AIC [{model.AIC_:.3f}]')
hnc_dict[model_names[i]] = f'{model.AIC_:.1f}'
fig.suptitle('Head Neck QQ-Plots', fontsize=16)
plt.tight_layout()
plt.show()
# ### Discussion
# - QQ-plot suggests that lognormal is the best fitting parametric distribution.
# - This is supported by LogNormal: LogNormal: Log Likelihood [-443.258], AIC [890.516]
# - AIC lower is better
# - Log Likelihood higher is better
# In[16]:
pd.DataFrame.from_records([oxy_dict, hnc_dict], index=['OxyTarget', 'HeadNeck'])
# In[ ]:
| mikkorekstad/M30-DV | Module C (Model Appropriateness)/Response Distributions.py | Response Distributions.py | py | 3,895 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "lifelines.utils.find_best_parametric_model",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.clf",
"line_number": 64,
"usage_type": "call"
},
{
"... |
16895923091 | from tkinter import Tk,Button,Label,Frame,Canvas,Entry,Text,StringVar, ttk, filedialog, messagebox
import pandas as pd
from pandas import datetime, read_csv
import numpy as np
import matplotlib as mp
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import seaborn as sb
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error
from PIL import ImageTk, Image
root = Tk
class TimeSeriesAnalysis(Tk):
"""
Class to manage frames and methods
"""
def __init__(self, *main):
Tk.__init__(self, *main)
container = Frame(self)
container.pack(side="top", expand=True)
container.grid_rowconfigure(0, weight=1) ### allows for frames to expand
container.grid_columnconfigure(0, weight=1)
self.fileAddress = "" ## creates the variable which will be used fo the main functions to plot/forecast
self.frames = {} #### creates dictionary to store alll frames which willl be used
pages = (MainMenu, Op1, Op2, Op3, Op4, FileSelection) ### list with all frames
for i in (pages): ##for loop to allow all pages to inherit methods from main class
frame = i(container, self)
self.frames[i] = frame #### allows frames to inherit characteristics of the main class and hence use its methods
frame.grid(row=0, column=0, sticky="nsew") #
frame.grid_rowconfigure(0,minsize=8,weight=1)
frame.grid_columnconfigure(0,minsize=8,weight=1)
frame.grid_propagate(False)
def show_frame(self, y):
frame = self.frames[y]
frame.tkraise()
def ignore(event):
pass
###def savefig(SaveFileAddress):
#self.SaveFileAddress = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
class MainMenu(Frame):
"""
Frame which operated as main menu which allows user to pick options and change file selection
"""
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text="Time Series Analysis")
label.pack()
im = Image.open("C:/Users/Fernando/Documents/NEA/logo.jpg") ## imports logo
canvas = Canvas(self,width=50,height=50)
canvas.pack()
canvas.image = ImageTk.PhotoImage(im) ## uses tkinte library in order to display image on canvas
canvas.create_image(25,25,image=canvas.image,anchor="center") ## creates a canvas for which the image wiill be displayed on
self.option1button = Button(self,text="Plot time series",command=lambda: ## Button to direct user to frame OP1
controller.show_frame(Op1))
self.option1button.pack()
self.option2button =Button(self,text="Plot time series using rolling mean",command=lambda: ## Button t direct user to frame OP2
controller.show_frame(Op2))
self.option2button.pack()
self.option3button = Button(self,text="Plot time series using first order differencing",command=lambda: ## Button t direct user to frame OP3
controller.show_frame(Op3))
self.option3button.pack()
self.option4button = Button(self,text="Analyse time series using arima model",command=lambda: ## Button t direct user to frame OP4
controller.show_frame(Op4))
self.option4button.pack()
self.ChangeFile = Button(self,text="Select/Change input file",command=lambda: ## Button t direct user to frame FileSelection
controller.show_frame(FileSelection))
self.ChangeFile.pack()
self.exitbutton = Button(self,text="exit",command=lambda:
exit())
self.exitbutton.pack()
class FileSelection(Frame):
"""
Frame which allows user to pick and change file selected
"""
def __init__(self, parent, controller):
Frame.__init__(self,parent)
label = Label(self, text="File Entry")
label.pack(pady=10,padx=10)
TempFileA = StringVar()
def OpenBrowser(event):
self.EnterButton.tk_focusNext().focus() ## changes focus of tkinter in order to prevent from going into a recursive loop with no end casae
TempFileA.set(filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV Files","*.csv"),("all files","*.*")))) ####Opens File browser at computer home directory in order to allow user to select file
return("break") ##Returns break in order to ensure that focus is changed
def GetVarChangeF():
controller.fileAddress = TempFileA.get() ##Gets the value stored in the entry widget which is labeled # TempFileA
if len(controller.fileAddress)>1 and controller.fileAddress.endswith("csv"): ##### Allows users to move on when they have entered a valid file address for a file with a .csv extension
controller.show_frame(MainMenu)
else:
controller.fileAddress = ""
messagebox.showinfo("Time Series Analysis", "Please enter a valid file address")
self.FileEntry = Entry(self,textvariable=TempFileA) ## Create a entry which is used as a storage for the fileAddress so it can be passed to controller later on and used to plot/forecast
self.FileEntry.pack(anchor="center")
self.FileEntry.bind("<FocusIn>",OpenBrowser) ### Binds when focus is put onnto the fille entry widget to OpenBrowser function
self.FileEntry.bind("<FocusOut>",controller.ignore()) ### Ignores focus out event
self.EnterButton = Button(self,text="Enter",command = lambda:
GetVarChangeF()) ## runs GetVarChangeF functionn
self.EnterButton.pack(anchor="center")
class Op1(Frame):
"""
Frame which allows user to plot the standard graph
"""
def __init__(self, parent, controller):
Frame.__init__(self,parent)
label = Label(self, text="Plotting a time series")
label.pack(anchor = "n", padx=10,pady=10)
self.GraphDrawn = False
def plot_graph(fileAddress):
lf = ttk.Labelframe(self, text='Plot Area') ### Adds plot area label
lf.pack()
headers = ['date','values'] ### Created a list of the name of the headers which will serve as the axis labels
dt=pd.read_csv(fileAddress,header = 0, names=headers,skiprows=1)
dt.date = pd.to_datetime(dt.date) ### Turns the date header into actual datetime data type values
dt.set_index('date',inplace=True)
f = Figure(figsize=(5,5),dpi = 100) ### defines a figure in which to embed the graph
ax1 = f.add_subplot(111) ### adds a subplot
dt.plot(legend = True,ax=ax1) ### plots graph
PlotCanvas = FigureCanvasTkAgg(f, self)
toolbar = NavigationToolbar2Tk(PlotCanvas,self)
PlotCanvas.get_tk_widget().pack(anchor="n",expand = True)
PlotCanvas.draw()
PlotCanvas._tkcanvas.pack(anchor="n")
if self.GraphDrawn == False:
self.GraphDrawn = True ###Only allows user to plot graph if it has not yet been plotted for this frame
elif self.GraphDrawn == True:
PlotCanvas.get_tk_widget().destroy()
toolbar.destroy()
self.previewButton=Button(self,text=("Preview"),command = lambda:
plot_graph(controller.fileAddress))
self.previewButton.pack(anchor = "s" ,pady=1)
self.ChangeFile = Button(self,text="Select/Change input file",command=lambda:
controller.show_frame(FileSelection))
self.ChangeFile.pack(anchor = "s" ,pady=1)
self.HomeButton = Button(self, text="Back to menu",command=lambda:
controller.show_frame(MainMenu))
self.HomeButton.pack(anchor = "s" ,pady=1)
self.exitbutton = Button(self,text="exit",command=lambda:
exit())
self.exitbutton.pack(anchor = "s" ,pady=1)
class Op2(Frame):
"""
Frame which allows user to plot the graph using rolling mean
"""
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text="Plotting time series with rolling mean")
label.pack(anchor = "n", padx=10,pady=10)
self.GraphDrawn = False
def plot_graph(fileAddress):
lf = ttk.Labelframe(self, text='Plot Area') ### Adds plot area label
lf.pack()
headers = ['date','values'] ### Created a list of the name of the headers which will serve as the axis labels
dt=pd.read_csv(fileAddress,header = 0, names=headers,skiprows=1)
dt.date = pd.to_datetime(dt.date) ### Turns the date header into actual datetime data type values
dt.set_index('date',inplace=True)
f = Figure(figsize=(5,5),dpi = 100) ### defines a figure in which to embed the graph
ax1 = f.add_subplot(111) ### adds a subplot
dt.rolling(12).mean().plot(legend = True,ax=ax1) ## Plot the data using rolling mean method
canvas = FigureCanvasTkAgg(f, self) ## Defines a canvas which can have a matploblib plot on it
canvas.draw() ##Makes the canvas
canvas.get_tk_widget().pack(anchor="center",expand = True) ### Adds the canvas to the frame
toolbar = NavigationToolbar2Tk(canvas,self) ## Defines toolbar to be used
canvas._tkcanvas.pack(anchor="center",expand = True)
self.GraphDrawn == True
if self.GraphDrawn == False:
self.GraphDrawn = True ###Only allows user to plot graph if it has not yet been plotted for this frame
elif self.GraphDrawn == True:
canvas.get_tk_widget().destroy()
toolbar.destroy()
self.previewButton=Button(self,text=("Preview"),command = lambda:
plot_graph(controller.fileAddress))
self.previewButton.pack(anchor = "s" ,pady=1)
self.ChangeFile = Button(self,text="Select/Change input file",command=lambda:
controller.show_frame(FileSelection))
self.ChangeFile.pack(anchor = "s" ,pady=1)
self.HomeButton = Button(self, text="Back to menu",command=lambda:
controller.show_frame(MainMenu))
self.HomeButton.pack(anchor = "s" ,pady=1)
self.exitbutton = Button(self,text="exit",command=lambda:
exit())
self.exitbutton.pack(anchor = "s" ,pady=1)
class Op3(Frame):
"""
Frame which allows user to plot the graph of their data using first orderr differencinng
"""
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text="Plot time series using first order differencing")
label.pack(anchor = "n", padx=10,pady=10)
self.GraphDrawn = False
def plot_graph(fileAddress):
lf = ttk.Labelframe(self, text='Plot Area')
lf.pack()
headers = ['date','values']
dt=pd.read_csv(fileAddress,header = 0, names=headers,skiprows=1)
dt.date = pd.to_datetime(dt.date)
dt.set_index('date',inplace=True)
f = Figure(figsize=(5,4),dpi = 100)
ax1 = f.add_subplot(111)
dt.diff().plot(legend = True,ax=ax1)
canvas = FigureCanvasTkAgg(f, self)
canvas.draw()
canvas.get_tk_widget().pack(anchor="center",expand = True)
toolbar = NavigationToolbar2Tk(canvas,self)
canvas._tkcanvas.pack(anchor="center",expand = True)
self.GraphDrawn == True
if self.GraphDrawn == False:
self.GraphDrawn = True ###Only allows user to plot graph if it has not yet been plotted for this frame
elif self.GraphDrawn == True:
canvas.get_tk_widget().destroy()
toolbar.destroy()
self.previewButton=Button(self,text=("Preview"),command = lambda:
plot_graph(controller.fileAddress))
self.previewButton.pack(anchor = "s" ,pady=1)
self.ChangeFile = Button(self,text="Select/Change input file",command=lambda:
controller.show_frame(FileSelection))
self.ChangeFile.pack(anchor = "s" ,pady=1)
self.HomeButton = Button(self, text="Back to menu",command=lambda:
controller.show_frame(MainMenu))
self.HomeButton.pack(anchor = "s" ,pady=1)
self.exitbutton = Button(self,text="exit",command=lambda:
exit())
self.exitbutton.pack(anchor = "s" ,pady=1)
class Op4(Frame):
"""
Fame which handles TimeSeries forecasting which shows an image of the forecasted data against the given data and saves it onto a csv called predictions
"""
def __init__(self, parent, controller):
Frame.__init__(self,parent)
label = Label(self, text="Analyse time series using arima model")
label.pack(anchor = "n", padx=10,pady=10)
self.GraphDrawn = False
"""
fuction which plots graph and makes a figure then packing it
"""
def plot_graph(dt):
lf = ttk.Labelframe(self, text='Plot Area')
lf.pack()
headers = ['date','values']
f = Figure(figsize=(5,4),dpi = 100)
ax1 = f.add_subplot(111)
dt.plot(legend = True,ax=ax1)
canvas = FigureCanvasTkAgg(f, self)
self.GraphDrawn = True
canvas.draw()
canvas.get_tk_widget().pack(anchor="center",expand = True)
toolbar = NavigationToolbar2Tk(canvas,self)
canvas._tkcanvas.pack(anchor="center")
self.GraphDrawn = True
def parser(x):
try:
return datetime.strptime(x, '%Y-%m-%d') ## Attempts to read the data given by using the format yyyy/mm/dd
except:
return datetime.strptime(x,'%Y-%m') ## Attempts to read the data given by using the format yyyy/mm
def forecast(fileAddress):
if self.GraphDrawn == False:
messagebox.showinfo("Time Series Analysis", "This will take a minute please wait. A file will be output with the prediction on the same location as the program.")
series = pd.read_csv(fileAddress, header=0, parse_dates=[0],
index_col=0, squeeze=True, date_parser=parser,skiprows = 1)
X = series.values
size = int(len(X) * 0.6) ## sets the amount of data that is going to be tested (max would be 0.1 min would be 0.9)
train, test = X[0:size], X[size:len(X)] ## defines the test data and the data which it will be compared to
history = [x for x in train]
predictions = list() ### defines a list for which the forecast will be input to
for t in range(len(test)):
model = ARIMA(history, order=(5,1,0)) ## Runs arima algorithm in order make the model
model_fit = model.fit(disp=0) ## Fits the model
output = model_fit.forecast() ## Forecasts based on previous data within the window defined by arima
yhat = output[0]
predictions.append(yhat)
obs = test[t]
history.append(obs)
"""
Part of the function which makes a new data fram with the predictions and plots said data frame
"""
error = mean_squared_error(test, predictions)
PredicVals = []
for i in range (int(len(predictions))):
PredicVals.append(predictions[i].item()) ##Due to the output of the forecast function being a numpy array in oder for me to plot the graph i have to add them to a list and get the modulous of them
headers = ['date','values']
RowsNeedSkip =1+int(len(train)) ##This is to remove the data which is unused for testing
dt = read_csv(fileAddress,header = 0, names=headers,skiprows=RowsNeedSkip) #### Imports csv file again but having removed unneeded data
dt.insert(2, "Predictions", PredicVals, True) ## inserts data which is needed
dt.date = pd.to_datetime(dt.date) ### Turns the date header into actual datetime data type values
dt.set_index('date',inplace=True)
dt.to_csv('prediction.csv') ### This will save a csv file with the actual and predicted values for the dates
plot_graph(dt)
elif self.GraphDrawn == True:
pass
self.opButton = Button(self,text="Time series forecasting using a csv file",command = lambda: forecast(controller.fileAddress))
self.opButton.pack(anchor="n")
self.HomeButton = Button(self, text="Back to menu",command=lambda:
controller.show_frame(MainMenu))
self.HomeButton.pack(anchor="s")
self.ChangeFile = Button(self,text="Select/Change input file",command=lambda:
controller.Unpack_ShowFrame(FileSelection))
self.ChangeFile.pack(anchor="s")
self.exitbutton = Button(self,text="exit",command=lambda: exit())
self.exitbutton.pack(anchor="s")
app = TimeSeriesAnalysis()
app.mainloop()
| FernandoLopezC/TSA | base.py | base.py | py | 19,718 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tkinter.Tk",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "tkinter.Tk",
"line_number": 14,
"usage_type": "name"
},
{
"api_name": "tkinter.Tk.__init__",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "tkinter.Tk",
"line_numb... |
30071209692 | # -*- coding: utf-8 -*-
""" This code is open-sourced software licensed under the MIT license"""
""" Copyright 2019 Marta Cortes, UbiComp - University of Oulu"""
""" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
"""
DISCLAIMER
This code is used to crawl/parse data from several files from Antalya. By downloading this code, you agree to contact the corresponding data provider and verify you are allowed to use (including, but not limited, crawl/parse/download/store/process) all data obtained from the data source.
"""
""" Parse excel files into correct format in csv files. """
""" """
""" Data are stored in an excel file named antalya_cutler_all_data_ (version 1).xlsx in different sheets """
""" Sheets names:
- TRANSPORT_VML55A, TRANSPORT_VC56, TRANSPORT_KC35, TRANSPORT_KC35A, TRANSPORT_CV17A, TRANSPORT_MZ78, TRANSPORT_MK80, TRANSPORT_MK80A, TRANSPORT_VF66
"""
""" Original files must be previously saved in folder temp"""
""" """
""" code: ant_env_cityofant_gwl """
import os
import pandas as pd
import shutil
import uuid
from kafka import KafkaProducer
from kafka.errors import KafkaError
import logging
__author__ = "Marta Cortes"
__mail__ = "marta.cortes@oulu.fi"
__origin__ = "UbiComp - University of Oulu"
logging.basicConfig(level=logging.INFO)
code= 'anta_eco_citiofantalya_cityzonepuplictransportationpasengernumber_monthly'
l_temp_path = './temp/'
l_final_path = './data/'
data_sheets = ['TRANSPORT_VML55A', 'TRANSPORT_VC56', 'TRANSPORT_KC35', 'TRANSPORT_KC35A', 'TRANSPORT_CV17A', 'TRANSPORT_MZ78','TRANSPORT_MK80', 'TRANSPORT_MK80A', 'TRANSPORT_VF66']
xlfname = 'antalya_cutler_all_data_ (version 1).xlsx'
class anta_eco_cityzonepuplictransportationpasengernumber_monthly(object):
def _init_(self):
self.local = True
def parse_file(self):
fileName = l_temp_path+xlfname#
xl = pd.ExcelFile(fileName)
print ('opening file '+fileName)
df_final = pd.DataFrame()
for data_sheetn in data_sheets:
#data into dataframe
df_data = xl.parse (data_sheetn, header =1)
print(len(df_data.columns))
print(len(df_data))
#remove index columns
df_data.reset_index(inplace = True)
#remove the last row
df_data.drop(df_data.tail(2).index,inplace=True)
#add reference to sheet name
df_data['CODE'] = data_sheetn
#First cleaning of sensor data column names
#df_data.columns = df_data.columns.str.replace(r"\(.*\)","")#remove all braces and data inside
#print (df_data.columns.tolist)
df_data_clean = df_data[['DATE', 'CODE','ZONE NAME', 'NUMBER OF TOUR ', 'FREE1', 'FREE2', 'FREE3', 'TICKET', 'STUDENT', 'PERSON', 'KREDI KART PERSON ', 'TEACHER','RETRIED', 'S.KART INDIRIMLI', 'AIRPORT EMPLOYER', 'TAX AUDIT CARD','TOTAL SUM']].copy()
#print (df_data_clean.count)
print(len(df_data_clean.columns))
print(len(df_data_clean))
#print (df_data_clean.columns.tolist)
df_final = df_final.append(df_data_clean)
print(len(df_final.columns))
print(len(df_final))
#print (df_final.count)
#Any date to reformat?
df_final['DATE'] = pd.to_datetime(df_final['DATE'], format='%d/%m/%Y').dt.strftime('%Y-%m-%d')
#RENAME COLUMNS
df_final.rename(columns={'DATE':'Date', 'CODE':'Code','ZONE NAME':'Zone Name', 'NUMBER OF TOUR ':'number_or_tour', 'FREE1':'free1', 'FREE2':'free2', 'FREE3':'free3', 'TICKET':'ticket', 'STUDENT':'student', 'PERSON':'person', 'KREDI KART PERSON ':'credit_card_person', 'TEACHER':'teacher','RETRIED':'retired', 'S.KART INDIRIMLI':'s_discount_card', 'AIRPORT EMPLOYER':'airport_employee', 'TAX AUDIT CARD':'tax_audir_card','TOTAL SUM':'total_sum'},inplace=True)
#save
outerdir = l_final_path
if not os.path.exists(outerdir):
os.mkdir(outerdir)
outdir = outerdir+'/'+code
if not os.path.exists(outdir):
os.mkdir(outdir)
csvfile = str(uuid.uuid4()) + ".csv"#sheet+'.csv'
print ('writing to folder '+code)
fullname = os.path.join(outdir, csvfile)
df_final.to_csv(fullname, mode='w', encoding='utf-8-sig', index=False)
def producer(self):
""" This function sends data to kafka bus"""
producer = KafkaProducer(bootstrap_servers=['HOST_IP'], api_version=(2, 2, 1))
topic = "ANTALYA_ECON_CITYOFANTALYA_CITYZONEPUPLICTRANSPORTATIONPASENGERNUMBER_MONTHLY_DATA_INGESTION"
producer.send(topic, b'City zone data for antalya ingested to HDFS').get(timeout=30)
if __name__ == '__main__':
a = anta_eco_cityzonepuplictransportationpasengernumber_monthly()
a.parse_file()
a.producer()
| CUTLER-H2020/DataCrawlers | Economic/antalya_econ_cityofantalya_cityzonepuplictransportationpasengernumber_monthly.py | antalya_econ_cityofantalya_cityzonepuplictransportationpasengernumber_monthly.py | py | 5,426 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "logging.basicConfig",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 38,
"usage_type": "attribute"
},
{
"api_name": "pandas.ExcelFile",
"line_number": 54,
"usage_type": "call"
},
{
"api_name": "pandas.DataFra... |
16127772066 | import cv2
import imageio
import pathlib
def fadeInGif(pathimg1, pathimg2, filegif, len=10, frames_per_second=2):
img1 = cv2.imread(pathimg1)
img2 = cv2.imread(pathimg2)
listimg = []
for seq in range(0,len):
fadein = seq/float(len)
dst = cv2.addWeighted(img1, 1-fadein, img2, fadein, 0)
listimg.append(dst)
cv2.waitKey(1)
print(fadein)
imageio.mimsave(filegif.as_posix(), listimg, fps=frames_per_second)
img1 = r"E:\Download\python\album\download.png"
img2 = r"E:\Download\python\album\downloadt.png"
fadeInGif(img1, img2, pathlib.Path('E:/Download/python/final.gif')) | doubsman/LedPanel64 | python_dev/TransitionGif.py | TransitionGif.py | py | 634 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "cv2.imread",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "cv2.imread",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "cv2.addWeighted",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "cv2.waitKey",
"line_number": ... |
23297154753 | """
Series Meta Analysis.
Some day this will be either the parent class of TAM and Adoption, or at least used by them.
For now, needed to have the general class for use in integrations where it is sometimes used in unique ways.
Note, at this time, this class does *not* handle the interpolation, fitting, etc;
we will need that eventually.
"""
from __future__ import annotations
from pathlib import Path
import pandas as pd
import json
from model import dd
from dataclasses import dataclass
from typing import Dict
# I started from solution_xls_extract.extract_source_data, but kept finding that there
# were inappropriate assumptions or requirements built in.... so I've ended up basically rewriting it.
class SMA:
@dataclass
class Source:
title: str
shortname: str
filename: str = None
description: str = None
data: pd.DataFrame = None
# TODO: add some optional metadata:
# The date this Source object was originally created
# The parameters used to interpolate/extrapolate it at that time.
# Original units and the conversion operation performed
def short_form(self):
# create a json-able struct that skips the dataframe
struct = { 'title': self.title, 'shortname': self.shortname, 'filename': self.filename }
if self.description:
struct['description'] = self.description
return struct
# The main state of the SMA: region_cases and sources:
region_cases : Dict[str,Dict[str,str]] = None
"""Structure mapping regions to cases to source-shortnames"""
sources: Dict[str, Source] = None
"""Map of shortnames to source data"""
# TODO: Add optional metadata:
# Title
# Units
# Description
# Version, date or something?
def __init__(self, region_cases=None, sources=None):
self.region_cases = region_cases or {}
self.sources = sources or {}
def rename_region(self,oldname,newname):
"""Rename one of the regions across both the region_cases and source data columns.
Typically used to give standardized names to the top-level block(s)"""
self.region_cases[newname] = self.region_cases[oldname]
del self.region_cases[oldname]
for source in self.sources.values():
source.data.rename(columns={oldname: newname}, inplace=True)
def summary(self, region=None, case=None, summary=None) -> pd.DataFrame:
"""Return a df summarizing the data in this SMA.
If region is specified, the DataFrame only includes that region, otherwise it includes all regions.
If case is specified, only sources in that case are used (and values may be nan if there are no corresponding sources).
Alternatively, case may be a shortname of a single source, which is returned instead.
...Currently, only lookup of a single source name is supported."""
# Eventually we want this to support the mean/hi/lo features and various interpolation and fit options.
# Eventually we will allow for the optional configuration of a default summary type, that accomplishes what the tamconfig, etc. does
if case in self.sources.keys():
if region:
return self.sources[case].data[[region]]
else:
return self.sources[case].data
else:
raise NotImplemented
@staticmethod
def read(directory, base_name, read_data=True) -> SMA:
directory = Path(directory)
jsonfile = directory / f"{base_name}.json"
jsondat = json.loads(jsonfile.read_text(encoding='utf-8'))
sources = {}
for source_info in jsondat['sources']:
smax = SMA.Source(**source_info)
if read_data:
smax.data = pd.read_csv( directory / source_info['filename'], index_col="Year",
skipinitialspace=True, skip_blank_lines=True, comment='#', encoding='utf-8')
sources[source_info['shortname']] = smax
return SMA(jsondat['region_cases'], sources)
def write(self, directory, base_name):
"""
Write to directory. Written as a set of csv files, one per data source,
and a json file for the top_level hierarchy.
"""
directory = Path(directory)
directory.mkdir(exist_ok=True)
for source in self.sources.values():
# even if we had a filename before, we update it with the current base
source.filename = f"{base_name}_{source.shortname}.csv"
outputfile = directory / source.filename
source.data.to_csv(outputfile, encoding='utf-8')
# for the top-level structure, create a json-dumpable dict
jdd = { 'region_cases' : self.region_cases,
'sources': [ v.short_form() for v in self.sources.values() ] }
toplevelfile = directory / f"{base_name}.json"
toplevelfile.write_text(json.dumps(jdd, indent=2), encoding='utf-8')
def as_tamsources(self, directory):
"""Translate the region_cases structure into the format expected by model.tam.TAM and model.adoptiondata.AdoptionData.
There are three changes:
1) The region names get prefixed with 'Region: '. We only do this for regions in dd.REGIONS
2) The first top-level region has the outer level of the hierarchy removed, so you get this weird mixed-level
thing that looks like this:
{ 'Baseline Cases': { ... },
'Conservative Cases': { ... },
'Ambitious Cases': { ... },
'Region: OECD90': {
'Baseline Cases': { ... },
'Conservative Cases': { ... },
'Ambitious Cases': { ... }
},
...
3) Instead of having a shortname, embed the title and full file reference directly in the sources data structure
"""
directory = Path(directory)
# Do the 2nd and 3rd substitions first
sources = {}
for region in self.region_cases.keys():
cases = {}
for case in self.region_cases[region].keys():
cases[case] = { self.sources[sn].title : directory/self.sources[sn].filename for sn in self.region_cases[region][case] }
if region in dd.REGIONS[1:]:
region = "Region: " + region
sources[region] = cases
# Do the 1st substitution: disinter the first region.
# To keep the dictionary ordering correct, we actually copy stuff over again.
firstregion = list(self.region_cases.keys())[0]
sources2 = sources[firstregion]
del(sources[firstregion])
sources2.update(sources)
return sources2
| ProjectDrawdown/solutions | limbo/sma.py | sma.py | py | 6,839 | python | en | code | 203 | github-code | 36 | [
{
"api_name": "pandas.DataFrame",
"line_number": 28,
"usage_type": "attribute"
},
{
"api_name": "dataclasses.dataclass",
"line_number": 22,
"usage_type": "name"
},
{
"api_name": "typing.Dict",
"line_number": 43,
"usage_type": "name"
},
{
"api_name": "typing.Dict",... |
8158020365 | import requests
import urllib
import json
import time
import pymysql
def get_latitude_longtitude(address):
address = urllib.parse.quote(address)
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address+"&key=AIzaSyAzA3f6KHEpViCBcLFSWS3a2ywVr3fCIvY"
while True:
res = requests.get(url)
js = json.loads(res.text)
if js["status"] != "OVER_QUERY_LIMIT":
time.sleep(1)
break
result = js["results"][0]["geometry"]["location"]
lat = result["lat"]
lng = result["lng"]
return lat, lng
# db = pymysql.connect("us-cdbr-east-02.cleardb.com","b5647ade0475c5","40d209f8","heroku_56d2d16ef2b2e35", charset='utf8')
db = pymysql.connect("localhost","root","xu.61i6u;6","heroku_56d2d16ef2b2e35")
Qcursor = db.cursor()
Icursor=db.cursor()
Ccursor=db.cursor()
print('開始定位!\n')
try:
select_sql = """SELECT id,adress FROM `page_data`"""
Qcursor.execute(select_sql)
i=0
while i<=816:
arr=Qcursor.fetchone()
print(f'編號:{arr[0]},地址:{arr[1]}')
check_sql=f"""SELECT COUNT( `houseid` )AS A FROM `localtion` WHERE `houseid` = {arr[0]} """
Ccursor.execute(check_sql)
count=Ccursor.fetchone()
if count[0]==0:
address=arr[1]
lat, lng = get_latitude_longtitude(address)
print(f'新增經緯度:{lat},{lng}\n====================================\n')
try:
sqlinsert = ("INSERT INTO localtion(houseid,lat,lng)" "VALUES(%s,%s,%s)")
val = [arr[0],lat,lng]
Icursor.execute(sqlinsert,val)
db.commit()
except:
print('新增經位度失敗\n====================================\n')
else:
print('已定位\n====================================\n')
time.sleep(1)
i+=1
if not arr:
break
except:
print("Select is failed")
db.close()
| NTUBimd1092/project-1 | python/GeoAPI.py | GeoAPI.py | py | 1,979 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "urllib.parse.quote",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "urllib.parse",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "requests.get",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "json.loads",
"lin... |
28932021496 | from django.shortcuts import render, redirect
from models import Book
# Create your views here.
def index(request):
books = Book.objects.all;
context = {
'books': books
}
return render(request, 'app/index.html', context)
def process(request):
if request.method == "POST":
Book.objects.create(title = request.POST['title'], category = request.POST['category'], author = request.POST['author'])
return redirect('/')
| melissaehong/AllProjects | Python/django/fullstackbooks/apps/app/views.py | views.py | py | 460 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "models.Book.objects",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "models.Book",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "django.shortcuts.render",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "models.Boo... |
3721701885 | import environ
from io import BytesIO
from PIL import Image, ImageFilter
env = environ.Env()
FILTERED_FILES = env('FILTERED_FILES', default='process_service/tmp/filtered')
def filter(file, filename, ext, method='blur', is_file=False):
filt = filt_obj.get(method, None)
Filter = getattr(ImageFilter, filt)
try:
img = Image.open(file) if is_file else Image.open(BytesIO(file))
img = img.filter(Filter)
filename = f'{filename}_filtered.{ext}'
img.save(f'{FILTERED_FILES}/{filename}')
return filename
except OSError as e:
print("Cannot filter this file", filename)
print(e)
filt_obj = {
"blur": "BLUR",
"contour": "CONTOUR",
"detail": "DETAIL",
"edge_enhance": "EDGE_ENHANCE",
"emboss": "EMBOSS",
"find_edges": "FIND_EDGES",
"sharpen": "SHARPEN",
"smooth": "SMOOTH",
}
| olacodes/prog-image | process_service/filtering/filter.py | filter.py | py | 875 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "environ.Env",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "PIL.ImageFilter",
"line_number": 10,
"usage_type": "argument"
},
{
"api_name": "PIL.Image.open",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_n... |
29719252617 | """
Day 9 part 2
"""
from utils import read_input
def find_window(opts, total):
window = []
for o in opts:
window.append(o)
while sum(window) > total:
window.pop(0)
if sum(window) == total:
return window
def find_missing(vals, pre):
idx = pre
while idx < len(vals):
preamble = set(vals[idx - pre : idx])
found = False
for p in preamble:
if vals[idx] - p in preamble:
found = True
break
if not found:
window = find_window(vals, vals[idx])
return min(window) + max(window)
idx += 1
test_input = [
35,
20,
15,
25,
47,
40,
62,
55,
65,
95,
102,
117,
150,
182,
127,
219,
299,
277,
309,
576,
]
assert find_missing(test_input, 5) == 62
inpt = read_input(9, line_parser=int)
assert find_missing(inpt, 25) == 4794981
| yknot/adventOfCode | 2020/09_02.py | 09_02.py | py | 975 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "utils.read_input",
"line_number": 64,
"usage_type": "call"
}
] |
20832740847 | import awkward as ak
from pocket_coffea.lib.cut_definition import Cut
def dilepton(events, params, year, sample, **kwargs):
MET = events[params["METbranch"][year]]
# Masks for same-flavor (SF) and opposite-sign (OS)
SF = ((events.nMuonGood == 2) & (events.nElectronGood == 0)) | (
(events.nMuonGood == 0) & (events.nElectronGood == 2)
)
OS = events.ll.charge == 0
# SFOS = SF & OS
not_SF = (events.nMuonGood == 1) & (events.nElectronGood == 1)
mask = (
(events.nLeptonGood == 2)
& (ak.firsts(events.LeptonGood.pt) > params["pt_leading_lepton"])
& (events.nJetGood >= params["njet"])
& (events.nBJetGood >= params["nbjet"])
& (MET.pt > params["met"])
& OS
)
# Pad None values with False
return ak.where(ak.is_none(mask), False, mask)
dilepton_presel = Cut(
name="dilepton",
params={
"METbranch": {
'2016_PreVFP': "MET",
'2016_PostVFP': "MET",
'2017': "MET",
'2018': "MET",
},
"njet": 2,
"nbjet": 0,
"pt_leading_lepton": 15,
"met": 10,
},
function=dilepton,
)
| ryanm124/AnalysisConfigs | configs/ttHbb/custom_cut_functions.py | custom_cut_functions.py | py | 1,172 | python | en | code | null | github-code | 36 | [
{
"api_name": "awkward.firsts",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "awkward.where",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "awkward.is_none",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "pocket_coffea.lib.cut_de... |
70846797543 | from pymongo import MongoClient
from datetime import datetime
import os, sys
sys.path.append(os.path.join(os.path.dirname(sys.path[0]), 'backend'))
import Model
import Repository as repo
def make_seats(secL, secH, rowL, rowH, seatL, seatH, secI=1, rowI=1, seatI=1):
seats = []
for sec in range(secL, secH, secI):
for row in range(rowL, rowH, rowI):
for seat in range(seatL, seatH, seatI):
seats.append(f"sec{sec}row{row}seat{seat}")
return seats
sb_seats = make_seats(100, 401, 1, 5, 1, 8, secI=100)
pres_seats = make_seats(1, 2, 1, 30, 1, 6)
yesterday_seats = make_seats(1, 2, 1, 2, 1, 2)
suberbowl = Model.Event({'start_time': datetime(2020, 2, 2, 19, 0, 0), 'team1': "Jets", 'team2': "Bengals", 'location': "Miami, FL", 'event_type': "NFL", 'period_count': 4, 'seats': sb_seats, 'event_name': "Suberb Owl"})
my_393_presentation = Model.Event({'start_time': datetime(2019, 12, 6, 11, 40, 0), 'team1': "us", 'team2': "Rohan & Anthony", 'location': "Bingham", 'event_type': "Presentation", 'period_count': 4, 'seats': pres_seats, 'event_name': "My 393 Presentation"})
yesterday = Model.Event({'start_time': datetime(2019, 12, 3, 0, 0, 0), 'team1': "today", 'team2': "tomorrow", 'location': "Yes", 'event_type': "Life", 'period_count': 1, 'seats': yesterday_seats, 'event_name': "Yesterday"})
repo.add_event(suberbowl)
repo.add_event(my_393_presentation)
repo.add_event(yesterday)
#print current events and ID's for convenince
print('Events currently in database:')
for event in repo.get_all_events():
print(f'Event name: {event.event_name}, ID: {event._id}') | DannyBarbaro/SeatSwap | db_code/EventCreator.py | EventCreator.py | py | 1,618 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.path.append",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "os.path.join",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": ... |
4712176028 | import numpy as np
import os
import trimesh.points
from abc import ABC
from typing import List, Union
from dataclasses import dataclass
from OpenGL import GL as gl
from .renderable import Renderable
from .shaders.shader_loader import Shader
from ..camera.models import BaseCameraModel, StandardProjectionCameraModel
from .shadowmap import ShadowMap
from .lights import Light
class Pointcloud(Renderable, ABC):
"""
Abstract class for all pointcloud objects
"""
@dataclass
class PointcloudContainer:
vertices: np.ndarray
colors: np.ndarray
def __init__(self, camera: BaseCameraModel = None, draw_shadows: bool = True, generate_shadows: bool = True):
super().__init__(camera, draw_shadows, generate_shadows)
self.render_back = True
class SimplePointcloud(Pointcloud):
"""
Pointcloud with simple rendering algorithm: one point - one color (only ambient lightning)
"""
def __init__(self, *args, **kwargs):
"""
Args:
camera (BaseCameraModel): main camera
shadowmaps (List[ShadowMap]): list of shadowmaps (no more than Renderable.SHADOWMAPS_MAX)
additional_lights: list of lights
"""
super().__init__(*args, **kwargs)
def _init_shaders(self, camera_model, shader_mode):
self.shader = shader = Shader()
dirname = os.path.dirname(os.path.abspath(__file__))
if self.draw_shadows:
shader.initShaderFromGLSL([os.path.join(dirname, f"shaders/simple_pointcloud/shadowdraw/vertex_{camera_model}.glsl")],
[os.path.join(dirname, "shaders/simple_pointcloud/shadowdraw/fragment.glsl")],
[os.path.join(dirname, "shaders/simple_pointcloud/shadowdraw/geometry.glsl")])
self.context.shader_ids.update(self.locate_uniforms(self.shader, ['shadowmap_MVP', 'shadowmap_enabled',
'shadowmaps', 'shadow_color']))
else:
shader.initShaderFromGLSL([os.path.join(dirname, f"shaders/simple_pointcloud/vertex_{camera_model}.glsl")],
[os.path.join(dirname, "shaders/simple_pointcloud/fragment.glsl")],
[os.path.join(dirname, "shaders/simple_pointcloud/geometry.glsl")])
self.context.shader_ids.update(self.locate_uniforms(self.shader, ['splat_size']))
if self.generate_shadows:
shadowgen_shader = self.shadowgen_shader = Shader()
shadowgen_shader.initShaderFromGLSL([os.path.join(dirname, f"shaders/simple_pointcloud/shadowgen/vertex_{camera_model}.glsl")],
[os.path.join(dirname,
"shaders/simple_pointcloud/shadowgen/fragment.glsl")],
[os.path.join(dirname,
"shaders/simple_pointcloud/shadowgen/geometry.glsl")])
self.shadowgen_context.shader_ids.update(self.locate_uniforms(self.shadowgen_shader, ['splat_size']))
def _finalize_init(self):
self.set_splat_size(0.5)
def _delete_buffers(self):
gl.glDeleteBuffers(2, [self.context.vertexbuffer, self.context.colorbuffer])
gl.glDeleteVertexArrays(1, [self.context.vao])
def _set_buffers(self, pointcloud: Union[Pointcloud.PointcloudContainer, trimesh.points.PointCloud]):
glverts = np.copy(pointcloud.vertices.astype(np.float32), order='C')
glcolors = np.copy(pointcloud.colors.astype(np.float32) / 255., order='C')
assert len(glverts)==len(glcolors), "PC vertices and colors length should match"
self.nglverts = len(glverts)
self.context.vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(self.context.vao)
self.context.vertexbuffer = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.vertexbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, glverts.nbytes, glverts, gl.GL_STATIC_DRAW)
self.context.colorbuffer = gl.glGenBuffers(1)
gl.glBindBuffer( gl.GL_ARRAY_BUFFER, self.context.colorbuffer)
gl.glBufferData( gl.GL_ARRAY_BUFFER, glcolors.nbytes, glcolors, gl.GL_STATIC_DRAW)
def _update_buffers(self, pointcloud: Union[Pointcloud.PointcloudContainer, trimesh.points.PointCloud]):
glverts = np.copy(pointcloud.vertices.astype(np.float32), order='C')
glcolors = np.copy(pointcloud.colors.astype(np.float32) / 255., order='C')
gl.glBindVertexArray(self.context.vao)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.vertexbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, glverts.nbytes, glverts, gl.GL_DYNAMIC_DRAW)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.colorbuffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, glcolors.nbytes, glcolors, gl.GL_DYNAMIC_DRAW)
def set_splat_size(self, splat_size):
self.context.splat_size = splat_size
def get_splat_size(self):
return self.context.splat_size
def _upload_uniforms(self, shader_ids, lights=(), shadowmaps=()):
gl.glUniform1f(shader_ids['splat_size'], self.context.splat_size)
shadowmaps_enabled = np.zeros(self.SHADOWMAPS_MAX, dtype=np.int32)
shadowmaps_enabled[:len(shadowmaps)] = 1
M = self.context.Model
shadowmaps_lightMVP = [np.array(s.light_VP*M) for s in shadowmaps]
shadowmaps_lightMVP = np.array(shadowmaps_lightMVP, dtype='f4')
if self.draw_shadows:
gl.glUniform1iv(self.context.shader_ids['shadowmap_enabled'], self.SHADOWMAPS_MAX, shadowmaps_enabled)
gl.glUniformMatrix4fv(self.context.shader_ids['shadowmap_MVP'], len(shadowmaps), gl.GL_TRUE, shadowmaps_lightMVP)
gl.glUniform4f(self.context.shader_ids['shadow_color'], *self.shadowcolor)
for shadow_ind, shadowmap in enumerate(shadowmaps):
gl.glActiveTexture(gl.GL_TEXTURE0+shadow_ind)
gl.glBindTexture(gl.GL_TEXTURE_2D, shadowmap.texture)
def _upload_shadowngen_uniforms(self, shader_ids):
gl.glUniform1f(shader_ids['splat_size'], self.context.splat_size)
def _draw(self, reset: bool, lights: List[Light], shadowmaps: List[ShadowMap]) -> bool:
"""
Internal draw pass
Args:
reset (bool): Reset drawing progress (for progressive drawing)
lights (List[Light]): All light objects that influence the current object
shadowmaps (List[ShadowMap]): List of shadowmaps to draw shadows from
Returns:
bool: if drawing buffer was changed (if something was actually drawn)
"""
if not reset:
return False
if not self.render_back:
if np.array(self.context.MV).dot(np.array([0, 0, 1, 0]))[2] <= 0:
return False
self.shader.begin()
self.upload_uniforms(self.context.shader_ids, lights, shadowmaps)
gl.glBindVertexArray(self.context.vao)
gl.glEnableVertexAttribArray(0)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.vertexbuffer)
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.colorbuffer)
gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glDrawArrays(gl.GL_POINTS, 0, self.nglverts)
gl.glDisableVertexAttribArray(0)
gl.glDisableVertexAttribArray(1)
self.shader.end()
return True
def _draw_shadowmap(self, shadowmap_camera: StandardProjectionCameraModel) -> bool:
"""
Shadow map draw pass - just to get depthmap values
Args:
shadowmap_camera (StandardProjectionCameraModel): perspective/ortho camera for shadow calculation
Returns:
bool: if drawing buffer was changed (if something was actually drawn)
"""
self.shadowgen_shader.begin()
self.upload_shadowgen_uniforms(shadowmap_camera, self.shadowgen_context.shader_ids)
gl.glBindVertexArray(self.context.vao)
gl.glEnableVertexAttribArray(0)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.vertexbuffer)
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.colorbuffer)
gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glDrawArrays(gl.GL_POINTS, 0, self.nglverts)
gl.glDisableVertexAttribArray(0)
gl.glDisableVertexAttribArray(1)
self.shadowgen_shader.end()
return True
class SimplePointcloudProgressive(SimplePointcloud):
"""
SimplePointcloud with progressive drawing support
"""
def __init__(self, *args, progressive_draw_size: int = None, progressive_draw_shuffle: bool = False, **kwargs):
"""
Args:
camera (BaseCameraModel): main camera
shadowmaps (List[ShadowMap]): list of shadowmaps (no more than Renderable.SHADOWMAPS_MAX)
additional_lights: list of lights
progressive_draw_size (int): number of points draw in one pass, None for all
progressive_draw_shuffle (bool): whether to shuffle drawing order during pointcloud load
"""
super().__init__(*args, **kwargs)
self.progressive_draw_size = progressive_draw_size
self.progressive_draw_shuffle = progressive_draw_shuffle
self.is_progressive = True
self.current_offset = 0
def _generate_indices(self, verts_count):
inds = np.arange(verts_count, dtype=np.uint32)
if self.progressive_draw_shuffle:
np.random.shuffle(inds)
return inds
def _set_buffers(self, pointcloud: Pointcloud.PointcloudContainer):
if self.progressive_draw_shuffle:
inds = self._generate_indices(len(pointcloud.vertices))
pointcloud = self.PointcloudContainer(pointcloud.vertices[inds], pointcloud.colors[inds])
super()._set_buffers(pointcloud)
self.current_offset = 0
def _update_buffers(self, pointcloud: Pointcloud.PointcloudContainer):
if self.progressive_draw_shuffle:
inds = self._generate_indices(len(pointcloud.vertices))
pointcloud = self.PointcloudContainer(pointcloud.vertices[inds], pointcloud.colors[inds])
super()._update_buffers(pointcloud)
self.current_offset = 0
def _draw(self, reset: bool, lights: List[Light], shadowmaps: List[ShadowMap]) -> bool:
if not self.render_back:
if np.array(self.context.MV).dot(np.array([0, 0, 1, 0]))[2] <= 0:
return False
if reset:
self.current_offset = 0
if self.current_offset >= self.nglverts:
return False
self.shader.begin()
self.upload_uniforms(self.context.shader_ids, lights, shadowmaps)
gl.glBindVertexArray(self.context.vao)
gl.glEnableVertexAttribArray(0)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.vertexbuffer)
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.context.colorbuffer)
gl.glVertexAttribPointer(1, 4, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
if self.progressive_draw_size is None:
gl.glDrawArrays(gl.GL_POINTS, 0, self.nglverts)
self.current_offset += self.nglverts
else:
curr_len = min(self.progressive_draw_size, self.nglverts - self.current_offset)
gl.glDrawArrays(gl.GL_POINTS, self.current_offset, curr_len)
self.current_offset += self.progressive_draw_size
gl.glDisableVertexAttribArray(0)
gl.glDisableVertexAttribArray(1)
self.shader.end()
return True
| vguzov/cloudrender | cloudrender/render/pointcloud.py | pointcloud.py | py | 12,029 | python | en | code | 16 | github-code | 36 | [
{
"api_name": "renderable.Renderable",
"line_number": 15,
"usage_type": "name"
},
{
"api_name": "abc.ABC",
"line_number": 15,
"usage_type": "name"
},
{
"api_name": "numpy.ndarray",
"line_number": 21,
"usage_type": "attribute"
},
{
"api_name": "numpy.ndarray",
... |
72219406185 | import math
import os.path
from os.path import join
import random
import torch
from torch.utils.data import DataLoader, Dataset
from typing import Dict, AnyStr, Any
from torchvision.transforms import transforms
from .image_folder import is_image_file, make_dataset
from PIL import Image
import numpy as np
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
to_tensor = transforms.Compose([
transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5),
transforms.ToTensor()])
class GTA5Dataset(Dataset):
def __init__(self, root, size=None, is_round=True, downsample=1, ext="png", resize=None):
super(GTA5Dataset, self).__init__()
self.root = root
self.origin_path = sorted(make_dataset(self.root + "/images/"))
self.origin_size = len(self.origin_path)
self.round = is_round
self.patch_size = 256
self.resize = resize
if size is None:
self.size = len(self.origin_path)
else:
self.size = min(size, len(self.origin_path))
def __len__(self) -> int:
return self.size
def __getitem__(
self,
index: int
) -> Dict[AnyStr, Any]:
if index > self.size:
raise IndexError("out of the range, indexed %d-th image, but have %d images in total." % (index, self.size))
paths = self.origin_path[index]
org_input = Image.open(paths).convert("RGB").resize((640, 480))
edge_input = Image.open(paths.replace("images", "labels")).convert("RGB").resize((640, 480)) #.resize((256, 256))
if self.resize is not None : org_input, edge_input = org_input.resize(self.resize), edge_input.resize(self.resize)
return to_tensor(org_input), \
to_tensor(edge_input), \
"".join(self.origin_path[index % self.origin_size].split('/')[-1].split(".")[:-1]) | leelxh/Adaptive-Texture-Filtering-for-Single-Domain-Generalized-Segmentation | texture_filter/datasets/smoothing_dataset.py | smoothing_dataset.py | py | 1,899 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "PIL.ImageFile.LOAD_TRUNCATED_IMAGES",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "PIL.ImageFile",
"line_number": 15,
"usage_type": "name"
},
{
"api_name": "torchvision.transforms.transforms.Compose",
"line_number": 16,
"usage_type": "call... |
14487480169 | import urllib.request, urllib.parse
from difflib import SequenceMatcher
import json
from msvcrt import getch
serviceurl = 'http://www.omdbapi.com/?'
apikey = '&apikey='+'da05069b'
abv90=[]
def match(s1, s2):
s2p=s2[0:len(s1)]
s1p=''.join(d for d in s1 if d.isalnum())
s2p=''.join(d for d in s2p if d.isalnum())
print("\n"+s1p+"--->"+s2p+"\n")
return SequenceMatcher(None, s1p, s2p ).ratio()*100
def search_movie(search):
if len(search) < 1:
return None
try:
url = serviceurl + urllib.parse.urlencode({'s': search})+apikey
print(f'Retrieving the data of "{search}" now... \n')
uh = urllib.request.urlopen(url)
print(url+"\n")
data = uh.read()
json_data=json.loads(data)
# list_keys=['Title', 'Year', 'Rated', 'Released', 'Runtime', 'Genre', 'Director', 'Writer',
# 'Actors', 'Plot', 'Language', 'Country', 'Awards', 'Ratings',
# 'Metascore', 'imdbRating', 'imdbVotes', 'imdbID']
if json_data['Response']=='True':
for k in json_data["Search"]:
print(k['Title'])
for k in json_data["Search"]:
print("Similarity "+str(match(str(k['Title']),fn)))
if match(str(k['Title']),fn)>=90.0:
abv90.append(str(k['Title']))
except Exception as e:
print(f"ERROR: {e}")
search = input('\nEnter: ')
fn=input("\nEnter filename\n")
search_movie(search)
print("Most similar..\n")
for i in abv90:
print(i)
getch()
| souvikchakraborty98/QuickScripts | z_test_1.py | z_test_1.py | py | 1,554 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "difflib.SequenceMatcher",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "urllib.request.parse.urlencode",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "urllib.request.parse",
"line_number": 22,
"usage_type": "attribute"
},
{
"... |
12227662181 | #!/home/mcollier/miniconda3/bin/python
# -*- coding: utf-8 -*-
__author__ = "Matthew Collier"
__version__ = "0.5"
# Typical use cases:
#hf> /media/mcollier/ONYX/ONYX/W/portfolio/scripts/scan.py -v
#hf> /media/mcollier/ONYX/ONYX/W/portfolio/scripts/scan_db.py -s WMT
#hf> /media/mcollier/ONYX/ONYX/W/portfolio/scripts/scan_db.py -d 2017-11-03
##############################################################################
# TBD:
#
# * Add total volume and range for S&P500 broad metrics
# * relativize the entire project's paths
# * improve documentation
#
##############################################################################
# standard python library imports
import argparse
import collections
import datetime as dt
from math import pi
import os
# third party python imports
from bs4 import BeautifulSoup # conda install beautifulsoup4
from bokeh.embed import file_html # conda install bokeh
from bokeh.io import output_file, save
from bokeh.layouts import column
from bokeh.models import Legend
from bokeh.plotting import figure, show
from bokeh.resources import CDN, INLINE
from pymysql import connect # conda install pymysql
from pymysql.cursors import DictCursor
from pandas import read_sql_query as rsql # conda install pandas
# overriding with local imports
home = "/home/mcollier/ONYX/wealth/portfolio"
os.chdir(os.path.join(home, "scripts"))
import common
##############################################################################
# Local User Function Definitions
##############################################################################
def get_broads(d_con, span, price_date, tids=[]):
"""
INPUTS:
d_con (mysql) - A pymysql database connection with dict() return
span (str) - 'daily' or 'weekly'
price_date (str) - Data in ISO 8601 standard as YYYY-MM-DD
tids [list] - id's of tickers to include with default of all
OUTPUT:
Dictionary with metrics as keys, and sums as values
"""
#span = "daily",
#price_date = "2017-10-31",
#tids = [1, 2, 5, 10, 20, 50, 100]
tids = [str(tid) for tid in tids]
cols = ["gt12", "gt26", "gt50", "ad"] # which metrics to sum()
sql = ["SELECT " + ("SUM({}) AS ##,"*len(cols)).format(*cols)[:-1],
"FROM {}_metrics".format(span),
"WHERE price_date='{}'".format(price_date),
"" if not tids else "AND symbol_id in {}".format(tuple(tids)),
';']
sql = " ".join(sql)
sql = sql.replace("##", "{}").format(*cols)
with d_con.cursor() as cur:
cur.execute(sql)
broads = cur.fetchone()
return broads
def get_sectors(n_con):
"""
INPUTS:
n_con (mysql) - A "normal" pymysql database connection
OUTPUT:
Dictionary with sectors as keys, and lists of ticker_id's as values
"""
sectors = collections.defaultdict(list)
with n_con.cursor() as n_cur:
n_cur.execute("SELECT sector,id FROM symbols where flag='a';")
results = n_cur.fetchall()
for result in results:
sectors[result[0]].append(result[1])
return sectors
def get_longs(n_con, span, price_date):
"""
INPUTS:
n_con (mysql) - A "normal" pymysql database connection
span (str) - 'daily' or 'weekly'
price_date (str) - Data in ISO 8601 standard as YYYY-MM-DD
OUTPUT:
Returns a list of potential long candidates.
"""
sql = ["SELECT symbol_id FROM {}_metrics".format(span),
"WHERE price_date='{}'".format(price_date),
"AND impulse>0", # positive impulse
"AND gt26<0"] # below value zone
with n_con.cursor() as n_cur:
n_cur.execute(" ".join(sql))
results = n_cur.fetchall()
return [result[0] for result in results]
def get_shorts(n_con, span, price_date):
"""
INPUTS:
n_con (mysql) - A "normal" pymysql database connection
span (str) - 'daily' or 'weekly'
price_date (str) - Data in ISO 8601 standard as YYYY-MM-DD
OUTPUT:
Returns a list of potential short candidates.
"""
sql = ["SELECT symbol_id FROM {}_metrics".format(span),
"WHERE price_date='{}'".format(price_date),
"AND impulse<0", # negative impulse
"AND gt26>0"] # above value zone
with n_con.cursor() as n_cur:
n_cur.execute(" ".join(sql))
results = n_cur.fetchall()
return [result[0] for result in results]
def get_ticker_info(d_con, tid):
"""
INPUTS:
d_con (mysql) - A pymysql database connection with dict() return
tid (int) - id of ticker
OUTPUT:
Dictionary with information about a ticker.
"""
sql = ["SELECT id,ticker,name,sector FROM symbols",
"WHERE id={}".format(tid),
";"]
with d_con.cursor() as d_cur:
d_cur.execute(" ".join(sql))
info = d_cur.fetchone()
return info
def report_individuals(n_con, price_date, tickers=[]): # tickers=singles
"""
INPUTS:
n_con (mysql) - A "normal" pymysql database connection
price_date (str) - Data in ISO 8601 standard as YYYY-MM-DD
tickers () - A list of dictionaries, one per ticker.
OUTPUT:
HTML as a string.
"""
msg = "{:>3s}, {:>8s}, {:>7s}, {:>6s}, {:5d}, {:5.3f}, {:8.3f}, {:<s}\n"
url = "<a href='./{}/{}{}.html'> {:s} </a>"
n_cur = n_con.cursor()
html = ""
for t in tickers:
#t={'id': 7,'name':'Abbott Laboratories','sector':'Health Care','ticker': 'ABT'}
n_cur.execute( ("SELECT count(*) FROM daily_data "
"WHERE symbol_id={}").format(t['id']) )
count = n_cur.fetchone()[0]
n_cur.execute( ("SELECT atr13 FROM daily_metrics WHERE symbol_id={} "
"AND price_date='{}';").format(t['id'], price_date) )
atr13 = n_cur.fetchone()[0]
n_cur.execute( ("SELECT close FROM daily_data WHERE symbol_id={} "
"AND price_date='{}'").format(t['id'], price_date) )
close = n_cur.fetchone()[0]
ticker_id = str(t['id']).zfill(3)
weekly_url = url.format(price_date, 'w', t["ticker"], "weekly")
daily_url = url.format(price_date, 'd', t["ticker"], "daily")
html += msg.format(ticker_id, weekly_url, daily_url, t["ticker"],
count, atr13/close, close, t["sector"])
return html
def bokeh_pages(d_con, span, price_date, att, tickers=[]):
"""
INPUTS:
d_con (pymysql) - MySQL connection returning a dictionary
span (str) -
price_date (str) -
att (str) -
tickers (list) - List containing ticker IDs
OUTPUT:
HTML files on disk.
"""
# set up variables
w = 12*60*60*1000 # half day in ms
if span == "weekly": w *= 7
TOOLS = "crosshair,hover,pan,wheel_zoom,box_zoom,reset,save"
data_sql = """SELECT d.price_date AS price_date, d.open AS open,
d.high AS high, d.low AS low,
d.close AS close, d.volume AS volume
FROM {}_data d
INNER JOIN symbols sym ON d.symbol_id = sym.id
WHERE sym.ticker='{}' AND d.price_date>"{}"
ORDER BY d.price_date ASC;"""
metrics_sql = """SELECT price_date, ema12, ema26, atr13,
macdf, macds, macdh, force2
FROM {}_metrics m
INNER JOIN symbols sym ON m.symbol_id = sym.id
WHERE sym.ticker='{}' AND m.price_date>"{}"
ORDER BY m.price_date ASC;"""
if span == "weekly":
price_date = common.get_dotw("next", "Friday", from_date=price_date)
offset = 52*7 + 1
else:
offset = 60
time_obj = dt.datetime.strptime(price_date, "%Y-%m-%d")
start_date = (time_obj - dt.timedelta(days=offset)).date().isoformat()
for ticker in tickers: # tickers = longs # tickers = shorts
# set up in-loop variables
info = get_ticker_info(d_con, ticker) # ticker = 69
t = info["ticker"]
D = rsql(data_sql.format(span, t, start_date),
con=n_con, index_col="price_date")
D["date"] = D.index.to_series()
inc = D.close > D.open
dec = D.open > D.close
M = rsql(metrics_sql.format(span, t, start_date),
con=n_con, index_col="price_date")
M["date"] = M.index.to_series()
# candlestick plot
title = "{}, {} {}".format(price_date, span, t)
p1 = figure(x_axis_type="datetime", tools=TOOLS, plot_height=618,
plot_width=1000, title = title+" Candlestick")
p1.xaxis.major_label_orientation = pi/4
p1.grid.grid_line_alpha = 0.3
p1.segment(D.date, D.high, D.date,
D.low, line_width=2, color="black")
p1.vbar(D.date[inc], w, D.open[inc], D.close[inc],
fill_color="#D5E1DD", line_color="black")
p1.vbar(D.date[dec], w, D.open[dec], D.close[dec],
fill_color="#F2583E", line_color="black")
# bokeh.pydata.org/en/latest/docs/user_guide/tools.html#hovertool
# ema26, ema12, 1atr, 2atr, 3atr linear overlays
p1.line(M.date, M.ema26 + 3*M.atr13, legend="3 ATR", color="gray")
p1.line(M.date, M.ema26 + 2*M.atr13, legend="2 ATR", color="dimgray")
p1.line(M.date, M.ema26 + M.atr13, legend="1 ATR", color="black")
p1.line(M.date, M.ema26, legend="ema26", color="green", line_width=4)
p1.line(M.date, M.ema12, legend="ema12", color="green", line_width=2)
p1.line(M.date, M.ema26 - M.atr13, legend="-1 ATR", color="black")
p1.line(M.date, M.ema26 - 2*M.atr13, legend="-2 ATR", color="dimgray")
p1.line(M.date, M.ema26 - 3*M.atr13, legend="-3 ATR",color="gray")
p1.legend.location = "top_left"
p1.legend.border_line_width = 2
p1.legend.background_fill_color = "aliceblue"
# second plot for macX family
p2 = figure(x_axis_type="datetime", tools=TOOLS, plot_height=250,
plot_width=1000, title = title+" MACDx")
p2.vbar(x=M.date, width=w, top=M.macdh, color="#CAB2D6")
p2.line(M.date, M.macds, legend="macds", color="black", line_width=2)
p2.line(M.date, M.macdf, legend="macdf", color="black", line_width=1)
p2.legend.location = "top_left"
p2.legend.border_line_width = 2
p2.legend.background_fill_color = "aliceblue"
# work with html
report = file_html(column(p1,p2), resources=CDN, title=title)
t_slash = t.replace('.', '/')
url1 = "https://www.bloomberg.com/quote/{}:US".format(t_slash)
url2 = "https://finance.google.com/finance?q={}".format(t)
url3 = "https://www.reuters.com/finance/stocks/overview/{}".format(t)
url4 = "http://shortsqueeze.com/?symbol={}".format(t.replace('.', ''))
new = ("<h2> Research Links </h2>"
"<ul><li><a href='{}'> Bloomberg </a>"
"<li><a href='{}'> Google </a>"
"<li><a href='{}'> Reuters </a>"
"<li><a href='{}'> ShortSqueeze </a>"
"</ul>").format(url1, url2, url3, url4)
miso = BeautifulSoup(report, "html.parser")
miso.body.insert(0, BeautifulSoup(new, "html.parser"))
with open("{}{}.html".format(span[0], ticker), "w") as f:
f.write(str(miso))
##############################################################################
# Treat this file as a script if invoked as __main__
##############################################################################
if __name__ == "__main__":
# load configuration from commented JSON into dictionary
conf = common.get_config("/etc/local/hf.conf")
# assign parsed commandline values to working objects
p = argparse.ArgumentParser()
p.add_argument("-d", "--date", default="today",
help="work with a particular date")
p.add_argument("-s", "--select", default="",
help="pull select ticker(s)... i.e. -s 69,488")
p.add_argument("-v", "--verbose", action="store_true",
help="print extra information on stdout")
# p.add_argument("-N", "--no_insert", action="store_true",
# help="suppress db insertion if true")
# p.add_argument("-R", "--no_report", action="store_true",
# help="option to suppress reporting at end")
args = p.parse_args()
vprint = print if args.verbose else lambda *a, **k: None
d_con = connect(host=conf["db_host"], db=conf["db_name"],
user=conf["db_user"], passwd=conf["db_pass"],
cursorclass=DictCursor)
n_con = connect(host=conf["db_host"], db=conf["db_name"],
user=conf["db_user"], passwd=conf["db_pass"])
if args.date == "today": price_date=dt.datetime.today().date().isoformat()
else: price_date = args.date # price_date = "2017-11-10"
##########################################################################
# S&P500 and Sector indicators, World Research
##########################################################################
html = """<html><head></head><body>
<center><em><b><h1><hr><hr>
"Every true idealist is after money ---because money means freedom,
and freedom, in the final analysis, means life." - Oscar Wilde
<hr><hr></h1></b></em></center>
<h2> Verify Processing </h2>
<a href="../logs> Log Directory </a>
<h2> Global Sweep </h2>
<ul>
<li> CNN <a href="http://money.cnn.com/data/world_markets/europe/"> World Markets </a> Map & News
<li> <a href="https://www.marketwatch.com/topics/columns/need-to-know"> Headlines </a> (a brief glance only)
</ul>\n"""
head = "{:>6s}, {:>4s}, {:>4s}, {:>4s}, {:>4s}"
head = head.format("span", "gt50", "gt26", "gt12", "ad")
# report S&P500-wide indicators
html += ("<h2> S&P500 </h2><pre>")
html += head + "<br>"
row = "{:>6s}: {:4d}, {:4d}, {:4d}, {:4d}<br>"
for span in ["daily", "weekly"]:
pop = get_broads(d_con, span, price_date)
html += row.format(span, int(pop['gt50']), int(pop['gt26']),
int(pop['gt12']), int(pop['ad']))
# report sector indicators
html += ("</pre><h2> GISC Sectors </h2>\n<pre>")
html += (head + ", {:>3s}, sector<br>".format("n"))
row = "{:>6s}: {:4d}, {:4d}, {:4d}, {:4d}, {:3d}, {}<br>"
for span in ["daily", "weekly"]:
sectors = get_sectors(n_con)
for sector, values in sectors.items():
m = get_broads(d_con, span, price_date, values)
html += row.format(span, int(m['gt50']), int(m['gt26']),
int(m['gt12']), int(m['ad']),
len(values), sector)
html += "<br>"
##########################################################################
# Individual short/long candidates
##########################################################################
head = "{:>3s}, {:>8s}, {:>7s}, {:>6s}, {:>5s}, {:>5s}, {:>8s}, {:<s}\n"
head = head.format("ID", "WEEKLIES", "DAILIES", "TICKER",
"COUNT", "CoV", "CLOSE($)", "SECTOR")
if not args.select:
# work with shorts
shorts = get_shorts(n_con, "daily", price_date)
esses = [get_ticker_info(d_con, short) for short in shorts]
html += ("<h2> Daily Shorts </h2><pre>")
html += head
html += report_individuals(n_con, price_date, esses)
# work with longs
longs = get_longs(n_con, "daily", price_date)
elles = [get_ticker_info(d_con, long) for long in longs]
html += ("</pre><h2> Daily Longs </h2><pre>")
html += head
html += report_individuals(n_con, price_date, elles)
else:
# work with singles
select = args.select.split(',')
select = [int(s) for s in select]
singles = [get_ticker_info(d_con, s) for s in select]
html += ("</pre><h2> Daily Single(s) </h2><pre>")
html += head
html += report_individuals(n_con, price_date, singles)
with open("inspection/{}.html".format(price_date), "w") as f:
f.write(html + "<br><br></pre></body></html>")
##########################################################################
# Generate Inpspection/Research Webpages
##########################################################################
# set up data
date_dir = os.path.join(home, "inspection/{}".format(price_date))
if not os.path.exists(date_dir): os.makedirs(date_dir)
os.chdir(date_dir)
# create inspection/research web pages
for span in ["weekly", "daily"]:
if not args.select: attitudes = {"longs": longs, "shorts": shorts}
else: attitudes = {"select": select}
for att in attitudes.keys():
bokeh_pages(d_con, span, price_date, att, tickers=attitudes[att])
# finally...
d_con.close()
n_con.close()
| mcStargazer/hf | scan_db.py | scan_db.py | py | 17,177 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.chdir",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line_number": 42,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 42,
"usage_type": "attribute"
},
{
"api_name": "collections.defaultdict",
"lin... |
42335398411 | import warnings
import torch
from mmdet.core import bbox2result
from ..builder import DETECTORS, build_backbone, build_head, build_neck
from .base import BaseDetector
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class TestGtDetector(SingleStageDetector):
"""Base class for single-stage detectors.
Single-stage detectors directly and densely predict bounding boxes on the
output features of the backbone+neck.
"""
def __init__(self,
backbone,
neck=None,
bbox_head=None,
train_cfg=None,
test_cfg=None,
pretrained=None,
init_cfg=None):
super(TestGtDetector, self).__init__(init_cfg)
def simple_test(self, img, img_metas, rescale=False, gt_labels=None, gt_bboxes=None):
"""Test function without test-time augmentation.
Args:
img (torch.Tensor): Images with shape (N, C, H, W).
img_metas (list[dict]): List of image information.
rescale (bool, optional): Whether to rescale the results.
Defaults to False.
Returns:
list[list[np.ndarray]]: BBox results of each image and classes.
The outer list corresponds to each image. The inner list
corresponds to each class.
"""
import ipdb
ipdb.set_trace()
feat = self.extract_feat(img)
results_list = self.bbox_head.simple_test(
feat, img_metas, rescale=rescale)
bbox_results = [
bbox2result(det_bboxes, det_labels, self.bbox_head.num_classes)
for det_bboxes, det_labels in results_list
]
return bbox_results
| mengqiDyangge/HierKD | mmdet/models/detectors/single_stage_test.py | single_stage_test.py | py | 1,754 | python | en | code | 32 | github-code | 36 | [
{
"api_name": "single_stage.SingleStageDetector",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "ipdb.set_trace",
"line_number": 43,
"usage_type": "call"
},
{
"api_name": "mmdet.core.bbox2result",
"line_number": 48,
"usage_type": "call"
},
{
"api_name":... |
35438464473 | from torch.utils.data import random_split
import torch
import argparse
import json
from pathlib import Path
from dataloader import SquadLocalContextContrastiveDataset, QuacLocalContextContrastiveDataset, get_quac_sets, get_squad_sets
from model import QClip
from trainer import Trainer
from tracker import WandBTracker
from config import Config, Dataset
import open_clip
def generate_model(config: Config, device: torch.device = torch.device("cpu")):
"""
Generates the qclip and clip models
"""
clip_model, _, _ = open_clip.create_model_and_transforms(config.data.clip_arch, pretrained=config.data.clip_checkpoint)
clip_model.to(device)
tokenizer = open_clip.get_tokenizer(config.data.clip_arch)
embedding_width = clip_model.encode_text(tokenizer(["hello", "world"]).to(device)).shape[1]
print(f"Embedding width: {embedding_width}")
qclip = QClip(
embedding_width,
config.model.output_dim,
config.model.hidden_dim,
projection_layers = config.model.num_layers,
use_question_projection = config.model.question_projection,
use_answer_projection = config.model.context_projection,
temperature = config.train.temperature,
simple_loss = config.train.simple_loss,
return_loss = True,
)
qclip.to(device)
return qclip, clip_model
def load_checkpoint(checkpoint: Path, config: Config = None, device: torch.device = torch.device("cpu")):
"""
Loads a checkpoint from the given path and returns the model, config, and start epoch
"""
if config is not None:
print("Overriding checkpoint config with provided config")
checkpoint = torch.load(checkpoint, map_location=device)
model_state_dict = checkpoint["model"]
optimizer_state_dict = checkpoint["optimizer"]
start_epoch = checkpoint["epoch"]
step = checkpoint["step"]
if config is None:
config = Config(**checkpoint["config"])
qclip, clip_model = generate_model(config, device)
qclip.load_state_dict(model_state_dict)
return qclip, clip_model, config, start_epoch, step, optimizer_state_dict
def get_datasets(config: Config, clip_model):
"""
"""
train_datasets = []
val_datasets = []
test_datasets = []
for dataset in config.data.datasets:
if dataset == Dataset.SQUAD:
train_set, test_set = get_squad_sets()
clip_device = next(clip_model.parameters()).device
tokenizer = open_clip.get_tokenizer(config.data.clip_arch)
train_val_dataset = SquadLocalContextContrastiveDataset(train_set, config.data.context_radius, clip_model, tokenizer, normalize_clip=True, clip_device=clip_device)
train_dataset, val_dataset = random_split(train_val_dataset, [0.9, 0.1])
test_dataset = SquadLocalContextContrastiveDataset(test_set, config.data.context_radius, clip_model, tokenizer, normalize_clip=True, clip_device=clip_device)
train_datasets.append(train_dataset)
val_datasets.append(val_dataset)
test_datasets.append(test_dataset)
elif dataset == Dataset.QUAC:
train_set, test_set = get_quac_sets()
clip_device = next(clip_model.parameters()).device
tokenizer = open_clip.get_tokenizer(config.data.clip_arch)
train_val_dataset = QuacLocalContextContrastiveDataset(train_set, config.data.context_radius, clip_model, tokenizer, normalize_clip=True, clip_device=clip_device)
train_dataset, val_dataset = random_split(train_val_dataset, [0.9, 0.1])
test_dataset = QuacLocalContextContrastiveDataset(test_set, config.data.context_radius, clip_model, tokenizer, normalize_clip=True, clip_device=clip_device)
train_datasets.append(train_dataset)
val_datasets.append(val_dataset)
test_datasets.append(test_dataset)
else:
raise ValueError(f"Unknown dataset {dataset}")
train_dataset = torch.utils.data.ConcatDataset(train_datasets)
val_dataset = torch.utils.data.ConcatDataset(val_datasets)
test_dataset = torch.utils.data.ConcatDataset(test_datasets)
return train_dataset, val_dataset, test_dataset
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint", type=str, default=None)
parser.add_argument("--config", type=str, default=None)
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
config = None
if args.config is not None:
config = Config(**json.load(open(args.config)))
qclip = None
start_epoch = 0
if args.checkpoint is not None:
qclip, clip_model, config, start_epoch, step, optimizer_state_dict = load_checkpoint(args.checkpoint, config, device)
else:
qclip, clip_model = generate_model(config, device)
train, val, test = get_datasets(config, clip_model)
tracker = WandBTracker(
"QuestionContext",
config.run.run_name,
report_train_loss_every=1,
run_id=config.run.resume_id,
config=config,
)
trainer = Trainer(
train,
val,
test,
qclip,
config,
tracker = tracker,
shuffle = True
)
if args.checkpoint is not None:
trainer.load_optimizer_state_dict(optimizer_state_dict)
tracker.step = step
print("Training with config:")
print(config.json(indent=4))
trainer.train(
epochs = config.run.epochs,
start_epoch = start_epoch,
train_sample_limit = config.run.train_sample_limit,
val_sample_limit = config.run.val_sample_limit,
test_out_of = config.run.test_out_of,
test_sample_limit = config.run.test_sample_limit,
)
if __name__ == "__main__":
main()
# parser = argparse.ArgumentParser()
# parser.add_argument("--run-name", type=str, default=None)
# parser.add_argument("--save-dir", type=str, default=None)
# parser.add_argument("--epochs", type=int, default=10)
# parser.add_argument("--batch-size", type=int, default=64)
# parser.add_argument("--train-sample-limit", type=int, default=None)
# parser.add_argument("--val-sample-limit", type=int, default=None)
# parser.add_argument("--test-sample-limit", type=int, default=None)
# parser.add_argument("--test-out-of", type=int, default=100)
# parser.add_argument("--context-radius", type=int, default=1)
# parser.add_argument("--clip-arch", type=str, default="ViT-B-32-quickgelu")
# parser.add_argument("--clip-checkpoint", type=str, default="laion400m_e32")
# parser.add_argument("--output-dim", type=int, default=512)
# parser.add_argument("--projection-layers", type=int, default=1)
# parser.add_argument("--answer-projection", action='store_true')
# parser.add_argument('--no-answer-projection', dest='answer-projection', action='store_false')
# parser.add_argument("--question-projection", action='store_true')
# parser.add_argument('--no-question-projection', dest='question-projection', action='store_false')
# parser.add_argument("--simple-loss", action='store_true')
# parser.add_argument('--no-simple-loss', dest='simple-loss', action='store_false')
# parser.add_argument("--temperature", type=float, default=1.0)
# parser.add_argument("--lr", type=float, default=1e-3)
# parser.add_argument("--checkpoint", type=str, default=None)
# parser.add_argument("--resume-run-id", type=str, default=None)
# args = parser.parse_args()
# # Load the datasets and CLIP model for preprocessing
# train_set, test_set = get_sets()
# model, _, preprocess = open_clip.create_model_and_transforms(args.clip_arch, pretrained=args.clip_checkpoint)
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# model.to(device)
# tokenizer = open_clip.get_tokenizer(args.clip_arch)
# embedding_width = model.encode_text(tokenizer(["hello", "world"]).to(device)).shape[1]
# print(f"Embedding width: {embedding_width}")
# train_val_dataset = SquadLocalContextContrastiveDataset(train_set, args.context_radius, model, tokenizer, normalize_clip=True, clip_device=device)
# train_dataset, val_dataset = random_split(train_val_dataset, [0.9, 0.1])
# test_dataset = SquadLocalContextContrastiveDataset(test_set, args.context_radius, model, tokenizer, normalize_clip=True, clip_device=device)
# # Configure and create the question-answer clip model
# model_config = {
# "embedding_dim": embedding_width,
# "output_dim": args.output_dim,
# "projection_layers": args.projection_layers,
# "use_answer_projection": args.answer_projection,
# "use_question_projection": args.question_projection,
# "simple_loss": args.simple_loss,
# "temperature": args.temperature
# }
# qclip = QClip(**model_config)
# qclip.to(device)
# # Configure the wandb tracker and pass context about this run
# if args.run_name:
# run_name = args.run_name
# else:
# print(f"Enter run name for wandb:")
# run_name = input()
# tracker = WandBTracker("QuestionContext", run_name, {
# **model_config,
# "dataset": "SQuAD",
# "clip_arch": args.clip_arch,
# "clip_checkpoint": args.clip_checkpoint,
# "batch_size": args.batch_size,
# "test_out_of": args.test_out_of,
# "lr": args.lr,
# "context_radius": args.context_radius,
# }, report_train_loss_every=1, run_id=args.resume_run_id)
# trainer = Trainer(
# train_dataset,
# val_dataset,
# test_dataset,
# qclip,
# tracker = tracker,
# batch_size = args.batch_size,
# shuffle = True,
# save_dir = args.save_dir,
# lr = args.lr
# )
# start_epoch = 0
# if args.checkpoint:
# start_epoch = tracker.load(args.checkpoint, qclip, trainer.optimizer)
# print(f"Loaded checkpoint from {args.checkpoint} at epoch {start_epoch} and step {tracker.step}.")
# trainer.train(
# epochs = 50,
# start_epoch = start_epoch,
# train_sample_limit = args.train_sample_limit,
# val_sample_limit = args.val_sample_limit,
# test_out_of=args.test_out_of,
# test_sample_limit = args.test_sample_limit
# )
| Veldrovive/QuestionContext | main.py | main.py | py | 10,429 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "config.Config",
"line_number": 15,
"usage_type": "name"
},
{
"api_name": "torch.device",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "open_clip.create_model_and_transforms",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": ... |
12040540403 | import os, sys, logging, glob2, csv
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
def create_directory(name):
"""
Create directory if not exists
Parameters
----------
name : string
name of the folder to be created
"""
try:
if not os.path.exists(name):
os.makedirs(name)
logging.info('Created directory: {}'.format(name))
except Exception(e):
logging.error("[{}] : {}".format(sys._getframe().f_code.co_name,e))
def read_directory(directory):
"""
Read file names from directory recursively
Parameters
----------
directory : string
directory/folder name where to read the file names from
Returns
---------
files : list of strings
list of file names
"""
try:
return glob2.glob(os.path.join(directory, '**' , '*.*'))
except Exception(e):
logging.error("[{}] : {}".format(sys._getframe().f_code.co_name,e))
def save_csv(data, name, folder):
"""
Save list of list as CSV (comma separated values)
Parameters
----------
data : list of list
A list of lists that contain data to be stored into a CSV file format
name : string
The name of the file you want to give it
folder: string
The folder location
"""
try:
# create folder name as directory if not exists
create_directory(folder)
# create the path name (allows for .csv and no .csv extension to be handled correctly)
suffix = '.csv'
if name[-4:] != suffix:
name += suffix
# create the file name
path = os.path.join(folder, name)
# save data to folder with name
with open(path, "w") as f:
writer = csv.writer(f, lineterminator='\n')
writer.writerows(data)
except Exception(e):
logging.error('[{}] : {}'.format(sys._getframe().f_code.co_name,e))
def calculate_hellinger_distance(p, q):
"""
Calculate the hellinger distance between two probability distributions
note that the hellinger distance is symmetrical, so distance p and q = q and p
other measures, such as KL-divergence, are not symmetric but can be used instead
Parameters
-----------
p : list or array
first probability distribution
q : list or array
second probability distribution
Returns
--------
hellinger_dinstance : float
hellinger distance of p and q
"""
return np.sqrt(np.sum((np.sqrt(p) - np.sqrt(q)) ** 2)) / np.sqrt(2)
def calc_cosine(vec_a, vec_b):
return cosine_similarity([vec_a], [vec_b])[0][0]
def read_vectors(file):
attract_repel_skills = pd.read_csv(file, sep=" ", header=None)
attract_repel_skills['vector'] = attract_repel_skills[attract_repel_skills.columns[1:]].values.tolist()
attract_repel_skills.rename(columns={0:'id'}, inplace=True)
attract_repel_skills = attract_repel_skills[['id', 'vector']].set_index('id')
return attract_repel_skills | stannida/skill-embeddings | utils/helper_functions.py | helper_functions.py | py | 3,147 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "os.path.exists",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "os.makedirs",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "logging.info",
"line_numb... |
37244411947 | # -*- coding: utf-8 -*-
"""
CAD120 data reader that is compatible with QSRlib.
:Author: Yiannis Gatsoulis <y.gatsoulis@leeds.ac.uk>
:Organization: University of Leeds
"""
from __future__ import print_function, division
import sys
import argparse
import timeit
import ConfigParser
import os
try:
import cPickle as pickle
except ImportError:
import pickle
from cad120_data_reader import CAD120_Data_Reader
from qsrlib.qsrlib import QSRlib, QSRlib_Request_Message
class CAD120_QSR_Keeper(object):
def __init__(self, description="", reader=None, qsrlib=None, which_qsr="", load_from_file=""):
start = timeit.default_timer()
print("\n--", self.__class__.__name__)
print("Generating QSRs...")
cloud_path = os.environ.get("CLOUD")
self.description = description
self.reader = reader
self.qsrlib = qsrlib
self.which_qsr = which_qsr
self.world_qsr_traces = {}
if load_from_file is not None and load_from_file != "":
if cloud_path is not None:
load_from_file = os.path.join(cloud_path, load_from_file)
self.load(load_from_file)
else:
if type(self.reader) is not CAD120_Data_Reader:
raise TypeError("Provide a CAD120_Data_Reader object")
if type(self.qsrlib) is not QSRlib:
raise TypeError("Provide a QSRlib object")
if self.which_qsr == "":
raise ValueError("Provide an appropriate QSR")
self.make()
stop = timeit.default_timer()
print("QSRs generated in: %.2f secs" % (stop - start))
def make(self, qsrlib=None):
if qsrlib:
self.qsrlib = qsrlib
if self.qsrlib is None:
raise TypeError("Pass a QSRlib object")
for k, world_trace in zip(self.reader.world_traces.keys(), self.reader.world_traces.values()):
request_message = QSRlib_Request_Message(which_qsr=self.which_qsr, input_data=world_trace, include_missing_data=True)
# out = self.qsrlib.request_qsrs(request_message=request_message)
self.world_qsr_traces[k] = self.qsrlib.request_qsrs(request_message=request_message)
def save(self, filename):
print("Saving...")
foo = {"description": self.description, "which_qsr": self.which_qsr, "world_qsr_traces": self.world_qsr_traces}
with open(filename, "wb") as f:
pickle.dump(foo, f)
print("\t\tdone")
def load(self, filename):
print("Loading QSRs from", filename, end="")
with open(filename, "rb") as f:
foo = pickle.load(f)
self.description = foo["description"]
self.which_qsr = foo["which_qsr"]
self.world_qsr_traces = foo["world_qsr_traces"]
print("\t\tdone")
if __name__ == '__main__':
start = timeit.default_timer()
options = {"sg1": "sg1",
"rcc3": "rcc3_rectangle_bounding_boxes_2d"}
parser = argparse.ArgumentParser(description="CAD120 QSR keeper in QSRlib format")
parser.add_argument("-i", "--ini", help="ini file", required=True)
parser_group = parser.add_mutually_exclusive_group(required=True)
parser.add_argument("-s", "--save", help="filename to save qsrs", type=str)
# parser_group.add_argument("-l", "--load", help="ini file that holds the qsrs filename, qsrs loaded from that file instead of being created from data", type=str)
parser_group.add_argument("-l", "--load", dest="load", action="store_true", help="load the data qsrs the file in 'config.ini'")
parser_group.add_argument("--qsr", help="choose qsr: %s" % options.keys(), type=str)
args = parser.parse_args()
inis_path = os.environ.get("INIS")
ini = os.path.join(inis_path, "strands_data_to_qsrlib", str(args.ini)) if inis_path else args.ini
cfg = ConfigParser.SafeConfigParser()
if len(cfg.read(ini)) == 0:
raise IOError(str(ini) + " not found")
if not args.load:
try:
reader_load = cfg.getboolean("cad120_data_keeper", "reader_load")
except ConfigParser.NoOptionError:
raise
try:
which_qsr = options[args.qsr]
except (IndexError, KeyError) as e:
parser.print_help()
sys.exit(1)
qsrlib = QSRlib()
reader = CAD120_Data_Reader(config_filename=ini, load_from_files=reader_load)
print()
keeper = CAD120_QSR_Keeper(description="description", reader=reader, qsrlib=qsrlib, which_qsr=which_qsr)
# optional saving
if args.save:
keeper.save(filename=args.save)
else:
try:
qsrs_filename = cfg.get("cad120_data_keeper", "qsrs_filename")
except ConfigParser.NoOptionError:
raise
keeper = CAD120_QSR_Keeper(load_from_file=qsrs_filename)
stop = timeit.default_timer()
print("Total execution time: %.2f secs" % (stop - start))
| gatsoulis/strands_data_to_qsrlib | src/cad120/cad120_qsr_keeper.py | cad120_qsr_keeper.py | py | 4,946 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "timeit.default_timer",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "os.environ.get",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 29,
"usage_type": "attribute"
},
{
"api_name": "qsrlib.qsrlib",
... |
36289747092 | from kafka.producer import KafkaProducer
TOPIC_NAME = "kafka.client.tutorial" # producer는 생성한 레코드를 전송하기 위해 전송하고자 하는 토픽을 알고 있어야 한다.
BOOTSTRAP_SERVER_HOST = "kafka_tutorial:9092" # 전송하고자 하는 카프카 클러스터 서버의 host와 IP를 지정
KEY_SERIALIZER = str.encode
VALUE_SERIALIZER = str.encode
producer = KafkaProducer(
bootstrap_servers=[BOOTSTRAP_SERVER_HOST],
key_serializer=KEY_SERIALIZER,
value_serializer=VALUE_SERIALIZER
)
# test message with key
test_message_key = "test"
test_message_value = "testMessage for python with Kafka"
# key_serializer 함수의 경우 None처리가 필요해보임(Spark udf와 같이)
producer.send(topic=TOPIC_NAME, value=test_message_value, key=test_message_key)
producer.flush()
producer.close() | 2h-kim/kafka-personal-study | simple-kafka-producer/kafka-producer-key-value.py | kafka-producer-key-value.py | py | 833 | python | ko | code | 0 | github-code | 36 | [
{
"api_name": "kafka.producer.KafkaProducer",
"line_number": 9,
"usage_type": "call"
}
] |
12553211459 | import datetime
current_weight = 220
goal_weight = 180
average_lbs_week = 1.5
start_date = datetime.date.today()
print('Today\'s Date is: {:%B %d, %Y}'.format(start_date))
end_date = start_date
# print(end_date)
while current_weight > goal_weight:
end_date += datetime.timedelta(days=7)
current_weight -= average_lbs_week
print()
print('Date to reach the goal is: {:%B %d, %Y}'.format(end_date))
print()
print(f'Reached the goal in {(end_date - start_date).days // 7} weeks')
| iampaavan/Pure_Python | Weekly_Goal.py | Weekly_Goal.py | py | 506 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "datetime.date.today",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "datetime.date",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "datetime.timedelta",
"line_number": 14,
"usage_type": "call"
}
] |
72549427943 | import traceback
from fastapi import HTTPException, Request
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import JSONResponse
from tortoise.exceptions import IntegrityError
from config import config
from utils.patch import MyFastAPI
app = MyFastAPI.get_app()
class BadRequest(HTTPException):
def __init__(self, message: str = 'Bad Request'):
super().__init__(400, message)
class ValidationError(BadRequest):
def __init__(self, message: str = 'Validation Error'):
super().__init__(message)
class Forbidden(HTTPException):
def __init__(self, message: str = 'Forbidden'):
super().__init__(403, message)
class NotFound(HTTPException):
def __init__(self, message: str = 'Not Found'):
super().__init__(404, message)
@app.exception_handler(IntegrityError)
async def integrity_error_handler(request, exception: IntegrityError):
raise BadRequest(str(exception))
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exception: RequestValidationError):
message = ''
errors = exception.errors()
for error in errors:
message += f'{".".join(error["loc"])} {error["msg"]}\n'
return JSONResponse(
content={'message': message.rstrip(), 'detail': errors},
status_code=400
)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exception: StarletteHTTPException):
return JSONResponse(
status_code=exception.status_code,
content={'message': exception.detail},
)
@app.exception_handler(Exception)
async def internal_server_error_handler(request, exception: Exception):
return JSONResponse(
status_code=500,
content={
'message': str(exception),
'detail': traceback.format_exc().split('\n') if config.debug else ''
},
)
| OpenTreeHole/treehole_backend | utils/exceptions.py | exceptions.py | py | 1,981 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "utils.patch.MyFastAPI.get_app",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "utils.patch.MyFastAPI",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "fastapi.HTTPException",
"line_number": 15,
"usage_type": "name"
},
{
"api_nam... |
6703674654 | import os, shutil
from datetime import datetime, timedelta
from tkinter import *
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import sqlite3
def load_gui(self):
# GUI set up using tkinter.
self.lbl_origin = tk.Label(self.master, bg = "silver", text = "Origin directory: ")
self.lbl_origin.grid( row = 0, column = 0, padx = (20, 0), pady = (10,0), sticky = N+W)
self.lst_origin = Listbox(self.master, width = 40, height = 8)
self.lst_origin.grid(row = 1, column = 0, columnspan = 3, padx = (20, 0), pady = (10,0), sticky = N+W)
self.lbl_dest = tk.Label(self.master, bg = "silver", text = "Destination directory: ")
self.lbl_dest.grid(row = 2, column = 0, padx = (20, 0), pady = (10,0), sticky = N+W )
self.lst_dest = Listbox(self.master, width = 40, height = 8)
self.lst_dest.grid(row = 3, column = 0, padx = (20, 0), pady = (10,0), sticky = N+W)
self.btn_open = tk.Button(self.master, width = 25, height = 2, text = "Open Origin",
command = lambda: open_file(self))
self.btn_open.grid( row = 1, column = 1, padx = (20,20), pady = (10,0), sticky = N+W)
self.btn_dest = tk.Button(self.master, width = 25, height = 2, text = "Open Destination",
command = lambda: dest_file(self))
self.btn_dest.grid( row = 1, column = 1, padx = (20,20), pady = (60,0), sticky = N+W)
self.btn_copy = tk.Button(self.master, width = 25, height = 2, text = "Copy",
command = lambda: copy_file(self))
self.btn_copy.configure(state = DISABLED)
self.btn_copy.grid( row = 1, column = 1, padx = (20,20), pady = (110,0), sticky = N+E)
self.btn_open = tk.Button(self.master, width = 25, height = 2, text = "Clear",
command = lambda: clear_box(self))
self.btn_open.grid( row = 3, column = 1, padx = (20,20), pady = (50,0), sticky = N+W)
self.btn_close = tk.Button(self.master, width = 25, height = 2, text = "Close",
command = lambda: close_window(self))
self.btn_close.grid( row = 3, column = 1, padx = (20,20), pady = (100,0), sticky = N+E)
create_db()
get_db(self)
def open_file(self):
# This function runs when user clicks the Open Origin button.
# Sets up global variable so the filedialog doesn't need to be called
# multiple times.
global src_folder
# Clearing the list box.
clear_box(self)
create_db()
src_folder = filedialog.askdirectory()
if src_folder == '':
messagebox.showwarning("Invalid Selection", "Please pick a valid directory.")
src_folder = filedialog.askdirectory()
else:
folder_name = get_folder(src_folder)
or_text = "Origin directory: " + folder_name
self.lbl_origin.configure(text = or_text)
get_data = get_db(self)
files = get_files(src_folder, get_data)
if(len(files) == 0):
self.lst_origin.insert(END, "No new or modified files")
else:
# Iterating through the files and lists ones that modified recently.
[self.lst_origin.insert(END, file) for file in files]
def dest_file(self):
# This function runs when user clicks the Open Destination button.
global dest_folder
dest_folder = filedialog.askdirectory()
if dest_folder == '':
messagebox.showwarning("Invalid Selection", "Please pick a valid directory.")
dest_folder = filedialog.askdirectory()
folder_name = get_folder(dest_folder)
dest_text = "Destination directory: " + folder_name
self.lbl_dest.configure(text = dest_text)
self.btn_copy.configure(state = ACTIVE)
def get_folder(folder):
# A helper function to get the selected folder name.
listA = folder.split('/')
return str(listA[0])+"/.../"+str(listA[len(listA)-1])
def get_files(folder, time):
# Getting the files from selected folder.
files = os.listdir(src_folder)
c_files = []
for file in files:
path = src_folder+'/'+file
# getting the modified time of the file.
m_time = os.path.getmtime(path)
# checking if file is recently created or edited.
if time == 0:
c_files.append(file)
elif datetime.fromtimestamp(m_time) > time:
# copying the file.
c_files.append(file)
return c_files
def copy_file(self):
# finding out the time 24 hours ago.
data = []
time_id = round(datetime.today().timestamp())
get_data = get_db(self)
files = get_files(src_folder, get_data)
# Clearing the list box.
clear_box(self)
for file in files:
path = os.path.join(src_folder, file)
dst = os.path.join(dest_folder, file)
if path == dst:
messagebox.showwarning("Invalid Selection", "Origin and Destination folders are the same! \nPlease pick a valid directory.")
else:
shutil.copy(path, dst)
data.append([time_id, file])
self.btn_copy.configure(state = DISABLED)
insert_db(data)
get_db(self)
def clear_box(self):
# Attached to Clear button to clear items from the list boxes.
self.btn_copy.configure(state = DISABLED)
self.lst_origin.delete(0, END)
self.lst_dest.delete(0, END)
self.lbl_origin.configure(text = "Origin directory: ")
self.lbl_dest.configure(text = "Destination directory: ")
def close_window(self):
if messagebox.askokcancel("Exit program", "Okay to exit application"):
# closing the app
self.master.destroy
os._exit(0)
def create_db():
# Creting the database if it is not already exists.
conn = sqlite3.connect('copyfiles.db')
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE if not exists tbl_savetime(\
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
col_timeid INTEGER, \
col_filename TEXT);")
conn.commit()
conn.close()
def insert_db(data):
# Inserting the copied filenames and the timestamp in the database.
conn = sqlite3.connect('copyfiles.db')
with conn:
cur = conn.cursor()
for item in data:
cur.execute("""INSERT INTO tbl_savetime (col_timeid, col_filename)
VALUES (?,?)""", (item[0], item[1]))
conn.commit()
conn.close()
def get_db(self):
# Getting the last updated time and the files updated from the database.
conn = sqlite3.connect('copyfiles.db')
cur = conn.cursor()
cur.execute("""SELECT MAX(ID) AS ID, col_timeid, col_filename FROM tbl_savetime""")
r_data = cur.fetchall()
updated_time = r_data[0][1]
if updated_time == None:
self.lst_dest.insert(END, "No files copied yet!")
#r_time = round(datetime.today().timestamp())
r_time = 0
else:
r_time = datetime.fromtimestamp(updated_time)
date = r_time.strftime('%B %d, %Y')
time = r_time.strftime('%I:%M%p')
self.lst_dest.insert(1, "Last file check: ")
self.lst_dest.insert(2, "Date: {}".format(date))
self.lst_dest.insert(3, "Time: {}".format(time))
self.lst_dest.insert(4, "Files updated: ")
cur.execute("""SELECT col_filename FROM tbl_savetime WHERE col_timeid ={id}""".format(
id = updated_time))
c_data = cur.fetchall()
[self.lst_dest.insert(5, item[0]) for item in c_data]
conn.close()
# returning the timestamp of the last check.
return r_time
| sajibhaskaran/Python_drills | PyDrill_db/modified_files_gui.py | modified_files_gui.py | py | 7,843 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "tkinter.Label",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "tkinter.Label",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "tkinter.Button",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "tkinter.Button",
"line... |
5462088920 | import cv2
import numpy as np
import logging
from skimage import io
import time
from multiprocessing import Lock
mutex = Lock()
class AClassify:
def __init__(self,uuid,net,image,s_client):
logging.debug("intialisation is requested")
self.url = s_client.generate_presigned_url(ClientMethod='get_object',Params={'Bucket':'data.ibeyonde','Key':image})
self.image = io.imread(self.url)
self.preds = None
self.blob = cv2.dnn.blobFromImage(self.image, 1, (224, 224), (104, 117, 123))
self.net = net
self.idxs = None
self.new_label = []
self.uuid = uuid
def compute(self,classes):
logging.debug("Aclassify computation is requested")
global mutex
mutex.acquire()
logging.info("lock acquired by thread")
self.net.setInput(self.blob)
start = time.time()
self.preds = self.net.forward()
end = time.time()
logging.info("[INFO] analytics took {:.5} seconds".format(end - start))
self.idxs = np.argsort(self.preds[0])[::-1][:5]
logging.info(self.idxs)
for idx in self.idxs:
label = classes[idx]
if label.endswith('\r'):
label = label[:-1]
self.new_label.append({label:self.preds[0][idx]})
mutex.release()
logging.info("lock relased by thread")
return self.uuid,self.new_label
| gitibeyonde/pyms | lib/AnalyticsClassify.py | AnalyticsClassify.py | py | 1,480 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "multiprocessing.Lock",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "logging.debug",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "skimage.io.imread",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "skimage.io",
... |
6999547749 | # Functions to calculate optical flow
import opyf
import utils
def analyze_frames(element):
dir = "/media/madziegielewska/Seagate Expansion Drive/Diploma-Project/"
analyzer = opyf.frameSequenceAnalyzer(f"{dir}Demo-App/static/segmentation_results/{element}")
num = analyzer.number_of_frames
utils.delete_files_in_directory(f"{dir}Demo-App/static/opyflow_results/{element}")
analyzer.writeGoodFeaturesPositionsAndDisplacements(fileFormat='csv', outFolder=f"{dir}Demo-App/static/opyflow_results/{element}")
analyzer.extractGoodFeaturesPositionsDisplacementsAndInterpolate()
analyzer.writeVelocityField(fileFormat='csv', outFolder=f"{dir}Demo-App/static/opyflow_results/{element}")
analyzer.set_vecTime(Ntot=num-1,shift=1,step=1)
analyzer.extractGoodFeaturesAndDisplacements(display='quiver', displayColor=True, saveImgPath=f"{dir}/Demo-App/static/opyflow_results/{element}", width=0.005)
utils.convert_frames_to_video(f'{element}.mp4', element, 10) | mdziegielewska/Diploma-Project | Demo-App/opticalflow.py | opticalflow.py | py | 994 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "opyf.frameSequenceAnalyzer",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "utils.delete_files_in_directory",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "utils.convert_frames_to_video",
"line_number": 23,
"usage_type": "call"
}
] |
16912146541 | """
Setup Module for Blob Creator
Author: Michael Kohlegger
Date: 2021-09
"""
import setuptools
with open("README.md", "r", encoding="utf8") as readme_file:
readme = readme_file.read()
with open('requirements.txt', "r", encoding="utf8") as requirement_file:
requirements = requirement_file.read().splitlines()
setuptools.setup(
name='blob_creator',
version='3.2.5',
author="Michael Kohlegger",
author_email="michael@datenberge.org",
description="Package to create dummy datasets for analysis tasks",
long_description=readme,
long_description_content_type="text/markdown",
url = "https://github.com/mckoh/blob_creator",
project_urls={
"Bug Tracker": "https://github.com/mckoh/blob_creator/issues",
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
package_dir={"": "src"},
packages=setuptools.find_packages(where="src"),
python_requires=">=3.6",
install_requires=requirements
)
| mckoh/blob_creator | setup.py | setup.py | py | 1,076 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "setuptools.setup",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "setuptools.find_packages",
"line_number": 34,
"usage_type": "call"
}
] |
28630475186 | from densefog import web
import flask # noqa
from icebox.model.iaas import image as image_model
def describe_images():
params = web.validate_request({
'type': 'object',
'properties': {
'limit': {
'type': 'integer',
'minimum': 1,
'maximum': 100,
},
'offset': {'type': 'integer', 'minimum': 0},
'reverse': {'type': 'boolean'},
'searchWord': {'type': ['string', 'null']},
'isPublic': {'type': 'boolean'},
'status': {
'type': 'array',
'items': {
'type': 'string',
'enum': [
image_model.IMAGE_STATUS_PENDING,
image_model.IMAGE_STATUS_ACTIVE,
image_model.IMAGE_STATUS_DELETED,
image_model.IMAGE_STATUS_CEASED,
image_model.IMAGE_STATUS_ERROR,
],
},
'minItems': 0,
'maxItems': 20,
'uniqueItems': True
},
'imageIds': {
'type': 'array',
'items': {
'type': 'string'
},
'minItems': 0,
'maxItems': 20,
'uniqueItems': True
}
}
})
project_id = flask.request.project['id']
image_ids = params.get('imageIds', None)
search_word = params.get('searchWord', None)
status = params.get('status', None)
is_public = params.get('isPublic', False)
offset = params.get('offset', 0)
limit = params.get('limit', 20)
reverse = params.get('reverse', True)
page = image_model.limitation(
project_ids=[project_id],
image_ids=image_ids,
is_public=is_public,
offset=offset,
status=status,
limit=limit,
search_word=search_word,
reverse=reverse)
formated = {
'limit': page['limit'],
'offset': page['offset'],
'total': page['total'],
'imageSet': []
}
for image in page['items']:
formated['imageSet'].append(image.format())
return formated
@web.mark_user_operation('image', 'imageIds')
def delete_images():
params = web.validate_request({
'type': 'object',
'properties': {
'imageIds': {
'type': 'array',
'items': {
'type': 'string'
},
'minItems': 0,
'maxItems': 20,
'uniqueItems': True
}
},
'required': ['imageIds']
})
project_id = flask.request.project['id']
image_ids = params['imageIds']
image_model.delete(project_id, image_ids)
return {
'imageIds': image_ids
}
@web.mark_user_operation('image', 'imageId')
def modify_image_attributes():
params = web.validate_request({
'type': 'object',
'properties': {
'imageId': {'type': 'string'},
'name': {'type': 'string', 'maxLength': 50},
'description': {'type': 'string', 'maxLength': 250}
},
'required': ['imageId']
})
project_id = flask.request.project['id']
image_id = params.get('imageId')
name = params.get('name', None)
description = params.get('description', None)
image_model.modify(project_id,
image_id,
name=name,
description=description)
return {
'imageId': image_id
}
| hashipod/icebox | core/icebox/api/public/image.py | image.py | py | 3,641 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "densefog.web.validate_request",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "densefog.web",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "icebox.model.iaas.image.IMAGE_STATUS_PENDING",
"line_number": 24,
"usage_type": "attribute"
},... |
43228825355 | # %%
from datasets import load_dataset
from transformers import AutoTokenizer, BertForSequenceClassification, TrainingArguments, Trainer
from transformers import pipeline
# %%
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
model = BertForSequenceClassification.from_pretrained("distilbert-base-uncased").cuda()
# %%
dataset = load_dataset("NgThVinh/dsc_model")
dataset.with_format("torch")
dataset
# %%
# dataset.push_to_hub('NgThVinh/dsc_model')
# %%
dataset['train'][:5]
# %%
dataset['train'].features
# %%
dataset['train'][0]
# %%
# max_length = 0
# for sen in dataset['train']['document']:
# length = len(tokenizer.tokenize(sen))
# max_length = max(length, max_length)
# max_length
# %%
def create_input_sentence(document, claim):
return f"Given claim-document pair where claim: \"{claim}\", document: \"{document}\". Classify the claim to which class it belongs. If the claim contains information about the document, its label will be SUPPORTED, otherwise, its label will be REFUTED. In case the information of the claim cannot be verified based on the given document, its label will be NEI"
# %%
print(create_input_sentence(dataset['train'][100]['document'], dataset['train'][100]['claim']))
# %%
def preprocess_function(examples):
inputs = tokenizer.encode_plus(
create_input_sentence(examples["claim"], examples["document"]),
truncation=True,
padding="max_length",
return_tensors='pt'
)
label = tokenizer.encode_plus(
examples["label"],
truncation=True,
padding="max_length",
return_tensors='pt'
)
examples["input_ids"] = inputs['input_ids'][0]
examples["attention_mask"] = inputs['attention_mask'][0]
examples['labels'] = label['input_ids'][0]
return examples
# %%
print(preprocess_function(dataset['train'][100]))
# %%
train_dataset = dataset["train"].map(preprocess_function, remove_columns=dataset["train"].column_names)
test_dataset = dataset["test"].map(preprocess_function, remove_columns=dataset["test"].column_names)
# %%
# from transformers import DefaultDataCollator
# data_collator = DefaultDataCollator()
# %%
training_args = TrainingArguments(
output_dir="dsc_model",
evaluation_strategy="epoch",
learning_rate=2e-5,
# per_device_train_batch_size=16,
# per_device_eval_batch_size=16,
num_train_epochs=3,
weight_decay=0.01,
push_to_hub=True,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset,
tokenizer=tokenizer,
# data_collator=data_collator,
)
trainer.train()
| NgThVinh/dsc_uit | main.py | main.py | py | 2,653 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "transformers.AutoTokenizer.from_pretrained",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "transformers.AutoTokenizer",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "transformers.BertForSequenceClassification.from_pretrained",
"line_number... |
19544626210 | # pip install pipwin
# pip install pyaudio
import pyaudio
import wave
from datetime import datetime, timedelta
import numpy as np
from multiprocessing import shared_memory
def runCapture(recDevice, rec_controls_sm, saveFilesPath, SECONDS = 1):
rec_controls = rec_controls_sm.buf
p = pyaudio.PyAudio()
micName = p.get_device_info_by_host_api_device_index(0, recDevice).get('name')
RATE = 44100 # 14700/second 44100/ 3secs
#SECONDS = 1 # ? multiple of RATE
CHUNK = int(RATE * SECONDS) # 44100 # 14700/second 44100/ 3secs ? 44100/30 = 1470
FORMAT = pyaudio.paInt16
FORMATstr = "pyaudio.paInt16"
# pyaudio.paInt16 format, the samples are 16-bit integers, so their range is from -32,768 to 32,767.
CHANNELS = 1
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=recDevice)
data_chunks = []
# shared script for recording
data_stamps = []
waitLoop = True
stopStamp = 0.0
while waitLoop:
stamp = datetime.timestamp(datetime.now())
# frame reading is embedded in stream.read(CHUNK..... no for loop
data_stamps.append(datetime.timestamp(datetime.now()))
#data_chunks.append(stream.read(CHUNK, exception_on_overflow=False))
data_chunks.append(stream.read(CHUNK))
# shared script for recording
if rec_controls[0] == 0:
if stopStamp == -1 and rec_controls[1] != 99:
nowTime = datetime.now()
stopStamp = datetime.timestamp(nowTime)
newSecond = rec_controls[1] - nowTime.second
if newSecond < 0: # adjust for wrap around the clock 1 - 58 = -57
newSecond += 60
stopStamp = stopStamp + timedelta(seconds = (newSecond))
elif stamp > stopStamp:
waitLoop = False
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(saveFilesPath + "\\audio_" + str(recDevice) + ".wav", 'wb')
wf.setnchannels(1) # CHANNELS
wf.setsampwidth(p.get_sample_size(FORMAT))#data_chunks[-1].get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(data_chunks))
wf.close()
audFrames = []
for data in data_chunks:
#print(len(data))
numpyData = np.frombuffer(data, dtype=np.int16)
audFrames.append(numpyData)
audFrames = np.array(audFrames, dtype=np.int16)
audFrames.tofile(saveFilesPath + "\\audioNpInt16_" + str(recDevice) + ".bin")
#audFrames = []
#for data in data_chunks:
# print(len(data))
# numpyData = np.frombuffer(data, dtype=np.float)
# audFrames.append(numpyData)
#audFrames = np.array(audFrames)
#audFrames.tofile(saveFilesPath + "\\audioNpFloat_" + str(recDevice) + ".bin")
data_raw = np.array(data_chunks)
data_raw.tofile(saveFilesPath + "\\audioFramesRaw_" + str(recDevice) + ".bin")
#data_chunks = data_chunks.astype(np.int16)
#print('audio raw', data_raw.dtype, np.shape(data_raw))
data_stamps = np.array(data_stamps, dtype=float)#, dtype=np.longdouble)
#print("audio stampss:", len(data_stamps), data_stamps[0], data_stamps[-1], recDevice, " micName: ", micName)
data_stamps.tofile(saveFilesPath+"\\audioStamps_" + str(recDevice) + ".csv", sep = ',')
lines = ['RATE:' + str(RATE), 'SECONDS:' + str(SECONDS), 'CHUNK:' + str(CHUNK), "FORMAT:" + FORMATstr]#str(FORMAT)]
lines.append('rawType:' + str(data_raw.dtype))
lines.append('rawShape:' + str(np.shape(data_raw)))
print('audio', len(data_stamps), lines, micName)
with open(saveFilesPath + "\\audioStats_" + str(recDevice) + ".txt", "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
return
| Richard-Kershner/Audio-Video-Screen-TimeStamp-Recorder | rec_audio.py | rec_audio.py | py | 4,034 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pyaudio.PyAudio",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "pyaudio.paInt16",
"line_number": 18,
"usage_type": "attribute"
},
{
"api_name": "datetime.datetime.timestamp",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "date... |
28037620802 | from setuptools import find_packages, setup
# read the contents of README file
from os import path
from io import open # for Python 2 and 3 compatibility
# get __version__ from _version.py
ver_file = path.join('tensorpi', 'version.py')
with open(ver_file) as f:
exec(f.read())
this_directory = path.abspath(path.dirname(__file__))
# read the contents of README.rst
def readme():
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
return f.read()
# read the contents of requirements.txt
with open(path.join(this_directory, 'requirements.txt'),
encoding='utf-8') as f:
requirements = f.read().splitlines()
setup(
name='tensorpi',
version=__version__,
description='Python library for low-rank tensor learning',
long_description=readme(),
long_description_content_type='text/x-rst',
author='Xinyu Chen',
author_email='chenxy346@gmail.com',
url='https://github.com/xinychen/tensorpi',
download_url='https://github.com/xinychen/tensorpi/archive/master.zip',
keywords=['tensor learning', 'tensor computation', 'matrix completion',
'tensor completion'],
packages=find_packages(exclude=['test']),
include_package_data=True,
install_requires=requirements,
setup_requires=['setuptools>=38.6.0'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Education',
'Intended Audience :: Financial and Insurance Industry',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
) | xinychen/TensorPi | setup.py | setup.py | py | 1,800 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "io.open",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"line_number": 12,
... |
74792104104 | # this is not CURE, just heirarchical clustering
# this is used to practice making a clustering algorithm
import numpy as np
import matplotlib.pyplot as plt
import math
# a vertex is just an x position and a y position
# this makes is easier for grouping vertices together
# rather than having 2 arrays for the x and y positions I can have 1 array with the x and y positions together
# I could have just used tuples or something but I prefer to have my own class
class Vertex:
def __init__(self, _x=0, _y=0):
self.x = _x
self.y = _y
def __repr__(self):
return f"({self.x}, {self.y})"
# A Cluster is an array of vertices, a centroid, and a radius
# this makes it easier than having a multi-dimensional array of vertices
# each cluster can easily calculate its own centroid
class Cluster:
def __init__(self, _vertices=[]):
self.vertices = _vertices
self.centroid = Vertex()
self.calc_centroid()
self.radius = self.calc_radius()
def __repr__(self):
return str(self.vertices)
def calc_centroid(self):
x_sum = 0
y_sum = 0
for c in self.vertices:
x_sum += c.x
y_sum += c.y
self.centroid = Vertex(x_sum/len(self.vertices), y_sum/len(self.vertices))
def calc_radius(self):
radius = 0
for v in self.vertices:
distance = euclidean_distance(v, self.centroid)
if distance > radius:
radius = distance
return radius
class Entry:
def __init__(self, key, val):
self.key = key
self.value = val
# i had to make my own map structure
# because the map given by python wasn't what I was looking for
class ClusterMap:
def __init__(self):
self.entries = []
def getValue(self, key): # get the value at the key
for e in self.entries:
if e.key == key:
return e.value
def add(self, key, value): # adds a new key value pair
if not self.contains(key):
self.entries.append(Entry(key, value))
def contains(self, key):
for e in self.entries:
if e.key == key:
return True
return False
def set(self, key, value): # updates the value for a given key
if not self.contains(key):
self.add(key, value)
return
for e in self.entries:
if e.key == key:
e.value = value
break
# calculates the number of vertices in a list of clusters
def num_vertices(clusters):
count = 0
for c in clusters:
count += len(c.vertices)
return count
# concatenates 2 clusters and returns the new cluster
def concat_clusters(c1, c2):
vertices = c1.vertices + c2.vertices
return Cluster(vertices)
# calculates the euclidean distance between 2 vertices
def euclidean_distance(v1, v2):
dx = abs(v2.x-v1.x)
dy = abs(v2.y-v1.y)
return math.sqrt(dx**2 + dy**2)
# draws a graph with x and y values
def draw_graph(clusters):
x, y = get_raw_xy(clusters)
# print(x)
# print(y)
fig, ax = plt.subplots()
for cluster in clusters:
_x = cluster.centroid.x
_y = cluster.centroid.y
circle = plt.Circle((_x, _y), cluster.radius+1, color='blue', fill=False)
ax.add_patch(circle)
ax.set_ylim(1,100)
ax.set_xlim(1,100)
ax.plot(x, y, 'o', color='black')
plt.show()
# gets the raw x and y data as their own lists from a list of clusters
def get_raw_xy(clusters):
x = []
y = []
for c in clusters:
for v in c.vertices:
x.append(v.x)
y.append(v.y)
return x, y
# not currently used by the algorithm
def f(avg, density):
a = 0.2
return a - ((-avg/density)+1)*a
# not currently used by the algorithm
def calc_density(cluster):
max_x, max_y = 0
min_x, min_y = math.inf
for vertex in cluster:
if vertex.x > max_x:
max_x = vertex.x
if vertex.y > max_y:
max_y = vertex.y
if vertex.x < min_x:
min_x = vertex.x
if vertex.y < min_y:
min_y = vertex.y
x = max_x - min_x
y = max_y - min_y
area = x * y
density = len(cluster.vertices) / area
return density
# print information about the clusters
def print_clusters(clusters):
print(f'Cluster Count: {len(clusters)}')
print(f'Vertex Count: {num_vertices(clusters)}')
for c in clusters:
for v in c.vertices:
print(v, end='')
print('\n')
# returns a random set of vertices as an x array and a y array
def random_vertices(count):
x = np.random.randint(low=1, high=100, size=count)
y = np.random.randint(low=1, high=100, size=count)
return x, y
# this will return vertices that are very obviously have their own clusters
# only used for debugging purposes
def cluster_test_vertices(count):
vertices = int(count/4)
lowest_low = 5
highest_low = 25
lowest_high = 75
highest_high = 95
x0 = np.random.randint(low=lowest_low, high=highest_low, size=vertices)
y0 = np.random.randint(low=lowest_low, high=highest_low, size=vertices)
x1 = np.random.randint(low=lowest_low, high=highest_low, size=vertices)
y1 = np.random.randint(low=lowest_high, high=highest_high, size=vertices)
x2 = np.random.randint(low=lowest_high, high=highest_high, size=vertices)
y2 = np.random.randint(low=lowest_high, high=highest_high, size=vertices)
x3 = np.random.randint(low=lowest_high, high=highest_high, size=vertices)
y3 = np.random.randint(low=lowest_low, high=highest_low, size=vertices)
x = np.concatenate((x0, x1, x2, x3), axis=0)
y = np.concatenate((y0, y1, y2, y3), axis=0)
return x, y
# this is the main heirarchical clustering algorithm
def hierarchical_clustering(vertex_count, goal_cluster_count):
# generates random x and y values for the vertices
x, y = random_vertices(vertex_count)
# x, y = cluster_test_vertices(vertex_count)
# static data for debugging purposes
# x = [12, 9, 18, 70, 75, 85, 30, 60, 70, 20]
# y = [60, 70, 66, 80, 77, 85, 50, 20, 22, 20]
clusters = [] # the list of the clusters
# make clusters out of the randomly generated x and y values
for i in range(vertex_count):
v = Vertex(x[i], y[i])
cluster = Cluster([v])
clusters.append(cluster)
# num_clusters is the number of clusters that has been created by the algorithm
# it is first equal to the size of the array becasue each vertex is originally its own cluster
num_clusters = len(clusters)
# this is the main algorithm and it will loop until the goal number of clusters has been reached
# basically it works by finding the closest cluster for every cluster
# then the algorithm puts all the closest pairs into map data structure
# then it loops over the map and finds the pair of clusters that are closest to each other
# it combines those clusters into a new cluster, deletes the old clusters and appends the new cluster
# this is about the slowest way to do this but it actually works really well
while num_clusters > goal_cluster_count:
c_map = ClusterMap() # a cluster map will map a cluster to its closest neighbor
# find all the closest points and add them to the map
for i in range(len(clusters)):
nearest_neighbor_distance = math.inf
for j in range(len(clusters)):
if i != j: # so a cluster doesn't consider itself as its closest neighbor
distance = euclidean_distance(clusters[i].centroid, clusters[j].centroid)
if distance < nearest_neighbor_distance:
nearest_neighbor_distance = distance
c_map.set(clusters[i], clusters[j])
closest_pair = 0 # index of closest pair
closest_pair_distance = math.inf
# loops over all the entries and finds the closest pair of clusters
for i in range(len(c_map.entries)):
e = c_map.entries[i]
distance = euclidean_distance(e.key.centroid, e.value.centroid)
if distance < closest_pair_distance:
closest_pair = i
closest_pair_distance = distance
# make a new cluster, delete the old ones, and add the new one
closest_clusters = c_map.entries[closest_pair]
new_cluster = concat_clusters(closest_clusters.key, closest_clusters.value)
clusters.remove(closest_clusters.key)
clusters.remove(closest_clusters.value)
clusters.append(new_cluster)
num_clusters = len(clusters)
# print(f'len clusters: {len(clusters)}')
# print_clusters(clusters)
draw_graph(clusters)
def main():
count_vertices = 100
desired_cluster_count = 30
hierarchical_clustering(count_vertices, desired_cluster_count)
if __name__ == "__main__":
main() | AdamPoper/CPSC-480-CURE-Clustering | heirarchical_clustering.py | heirarchical_clustering.py | py | 9,062 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "math.sqrt",
"line_number": 94,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.subplots",
"line_number": 102,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 102,
"usage_type": "name"
},
{
"api_name": "matplotlib.p... |
70987576744 | #!/usr/bin/python2.7
import rospy
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge
bridge = CvBridge()
def show_webcam():
cam = cv2.VideoCapture(0)
if not cam.isOpened():
raise IOError("Cannot open webcam")
while True:
ret_val, img = cam.read()
cv2.imshow("webcam", img)
img_message = bridge.cv2_to_imgmsg(img, encoding="passthrough")
pub.publish(img_message)
key = cv2.waitKey(1)
if key == 27:
break
cam.release()
cv2.destroyAllWindows()
pub = rospy.Publisher("/usb_cam/image_raw", Image, queue_size=1)
rospy.init_node("img_publisher", anonymous=True)
show_webcam()
'''rate = rospy.Rate(1)
while not rospy.is_shutdown():
img = cv2.imread("/home/wout/Pictures/arucotest.jpg")
img_message = bridge.cv2_to_imgmsg(img, encoding="passthrough")
pub.publish(img_message)
rate.sleep()
'''
| E-pep/HaldisBot | catkin_ws/src/Line_Follower_pkg/imgPub.py | imgPub.py | py | 924 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "cv_bridge.CvBridge",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "cv2.VideoCapture",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "cv2.imshow",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "cv2.waitKey",
"line... |
28068881292 | from itertools import combinations
import sys
input = sys.stdin.readline
def solution(orders, course):
answer = {}
for n in course:
food = {}
for i in orders:
combi = list(combinations(sorted(i), n))
for i2 in combi:
try:
food[''.join(i2)] += 1
except:
food[''.join(i2)] = 1
food = dict(filter(lambda x:x[1] == max(food.values()), food.items()))
for idx in food.keys():
answer[idx] = max(food.values())
answer = dict(filter(lambda x:x[1] >= 2, answer.items()))
answer = [ i[0] for i in sorted(answer.items(), key=lambda x : (x[0],x[1]),reverse=False)]
return answer | hwanginbeom/algorithm_study | 2.algorithm_test/21.08.22/21.08.22_gyeonghyeon.py | 21.08.22_gyeonghyeon.py | py | 726 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "sys.stdin",
"line_number": 3,
"usage_type": "attribute"
},
{
"api_name": "itertools.combinations",
"line_number": 10,
"usage_type": "call"
}
] |
74457197862 | import json
import os
import sys
import time
from apscheduler.schedulers.blocking import BlockingScheduler
from public import redis_con,get_conn
from data_change import get_setting
# 将数据查询到redis中
def get_data():
con = get_conn()
cur = con.cursor()
sql = f"SELECT id,title,Ncontent from {get_setting()} where is_change=0 LIMIT 50000"
num = cur.execute(sql)
results = cur.fetchall()
if num != 0:
for res in results:
res = json.dumps(list(res))
redis_con().lpush('data_all',res)
return True
return False
def chat():
if redis_con().exists('data_all') == 1:
if redis_con().llen('data_all') < 5000:
result = get_data()
if result is True:
print('更新数据成功')
print(f"总数据{redis_con().llen('data_all')}")
return True
print(f"总数据{redis_con().llen('data_all')}")
result = get_data()
if result is True:
print('更新数据成功')
print(f"总数据{redis_con().llen('data_all')}")
return True
return False
if __name__ == '__main__':
# scheduler = BlockingScheduler()
# scheduler.add_job(chat, 'cron', minute =1,timezone='Asia/Shanghai')
# scheduler.start()
# # chat()
while True:
res = chat()
if res is False:
sys.exit(0) # 终止运行
time.sleep(3600)
| AYongmengnan/zimeiti | zimeiti/get_data_redis.py | get_data_redis.py | py | 1,434 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "public.get_conn",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "data_change.get_setting",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "json.dumps",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "public.redis_con",... |
5808173653 | from datetime import datetime
class DateBuilder:
def __init__(self, raw_date: str):
self.raw_date = raw_date
def get_month(self):
months = {}
for i, m in enumerate(["january", "febuary", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]):
months[m] = i + 1
return months[self.raw_date.split(" ")[0].strip().lower()]
def get_day(self):
return int(self.raw_date.split(",", 1)[0].split(" ", 1)[1].split(" - ")[0].strip())
def get_year(self):
try:
return int(self.raw_date.split(",")[1].strip())
except:
return datetime.now().year
def get_time(self):
# 0 - 23
def convert(time):
if "pm" in time:
hr, min = time.split("pm")[0].split(":")
min = float(min)/100.0
time = float(hr)
if time < 12.0:
time += 12.0
time += min
else:
hr, min = time.split("am")[0].split(":")
min = float(min)/100.0
time = float(hr)
if time == 12.0:
time -= time
time += min
return time
temp = self.raw_date.split(",")[-1].split(" to ")
if len(temp) == 1:
return convert(temp[0].strip()), convert(temp[0].strip())
start, end = temp
return convert(start.strip()), convert(end.strip())
def less_than_equal(self, date):
return self.get_year() <= date.get_year() and (self.get_month() < date.get_month() or (self.get_month() == date.get_month() and (self.get_day() < date.get_day() or (self.get_day() == date.get_day() and self.get_time()[-1] <= date.get_time()[-1]))))
def makeDate(self):
start, end = self.get_time()
return (self.get_year(), self.get_month(), self.get_day(), start, end)
def displayDate(self):
o = ""
for value in self.makeDate():
o += str(value) + " "
return o.strip() | Vel4ta/Event_Manager | events/lib/DateBuilder.py | DateBuilder.py | py | 2,102 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "datetime.datetime.now",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 18,
"usage_type": "name"
}
] |
12248576934 | ######################################################################
# Script for processing Diss.
#
# (C) Christoph Schaller, BFH
######################################################################
import os
import sys
import math
import glob
import numpy as np
import fiona
from shapely.geometry import Point, box
from osgeo import ogr
PYFINT_HOME = os.environ.get("PYFINT_HOME")
sys.path.append(PYFINT_HOME)
from pyfintcontroller import *
FINTCH_HOME = os.environ.get("FINTCH_HOME")
sys.path.append(os.path.join(FINTCH_HOME,"Common"))
from fintch_utilities import *
import numpy as np
import pandas as pd
import geopandas as gpd
from osgeo import ogr, osr, gdal
import psycopg2
from shapely.wkt import dumps, loads
import configparser
from datetime import datetime, date, time, timedelta
import time
from multiprocessing import Process, Pool, Queue, JoinableQueue, current_process, freeze_support
from queue import Empty
import logging
import traceback
import fintch_processing_core_pub
def worker(q, work_function, cfg):
db_connection = psycopg2.connect(host=cfg.get("AP07__db","host"), dbname=cfg.get("AP07__db","dbname"), user=cfg.get("AP07__db","user"), password=cfg.get("AP07__db","password"))
configure_log(cfg)
current_forest_mask_path = None
current_trasse_mask_path = None
forest_mask_df = None
while True:
#Consume work as long as there are items in the queue
try:
flaeche_record = q.get()
if flaeche_record == None:
q.task_done()
print("Queue End")
break
if "waldmaske" in flaeche_record and flaeche_record["waldmaske"] != None and flaeche_record["waldmaske"] != "" :
if flaeche_record["waldmaske"] != current_forest_mask_path:
current_forest_mask_path = flaeche_record["waldmaske"]
forest_mask_df = gpd.read_file(current_forest_mask_path)
flaeche_record["waldmaske_df"] = forest_mask_df
if "trasse_maske" in flaeche_record and flaeche_record["trasse_maske"] != None and flaeche_record["trasse_maske"] != "":
if flaeche_record["trasse_maske"] != current_trasse_mask_path:
current_trasse_mask_path = flaeche_record["trasse_maske"]
trasse_mask_df = gpd.read_file(current_trasse_mask_path)
flaeche_record["trasse_mask_df"] = trasse_mask_df
work_function(flaeche_record,db_connection)
q.task_done()
except Empty:
print("Queue empty")
break
#No more work available
print("Exit:",current_process())
db_connection.close()
return
def process_record_setup(parameter_sets, reference_plot_df, flaeche_id_column, flaeche_info_df, veg_zone_df, dhm, plot_radius, process_function, table_schema, table_base_name, cfg, result_base_path, log_path, num_processes = 1):
# Create queues
records = []
for i,plot in reference_plot_df.iterrows():
flaeche = flaeche_info_df[flaeche_info_df["Flaeche_ID"]==plot[flaeche_id_column]].iloc[0]
if flaeche["VHM"]!=flaeche["VHM"]: # False if values is nan
# Info needed for processing not present -> skip plot
continue
vhm_path = flaeche["VHM"]
plot_center_geom = plot.geometry
x = plot_center_geom.x
y = plot_center_geom.y
plot_area_geom = plot_center_geom.buffer(plot_radius, resolution=16)
perimeter_record = {
"parameter_sets": parameter_sets,
"perimeter_id": plot["OBJECTID"],
"geom_center":plot_center_geom,
"geom_flaeche":plot_area_geom,
"vhm_input_file": vhm_path,
"geometry": plot_center_geom,
"flaeche_id": int(plot["plot_id"] if plot["plot_id"]>0 else int(plot["OBJECTID"])),
"quelle_id": plot["source_id"],
"result_base_path": result_base_path,
"log_path": log_path,
"plot_radius" : 12.62,
"perimeter_buffer" : 37.5,
"grid_step": 25,
"perimeter_buffer2" : 75,
"grid_step2" : 50,
"r_max" : cfg.getfloat("AP07__pyfint","r_max"),
"epsg" : cfg.get("AP07__pyfint","epsg"),
"crs" : {'init': "epsg:"+cfg.get("AP07__pyfint","epsg")},
"table_schema": table_schema,
"table_base_name": table_base_name,
"mischungsgrad": flaeche["Mischungsgrad"],
"vhm_input_file_150": flaeche["VHM_150"],
"waldmaske": flaeche["Waldmaske"],
"veg_zones": veg_zone_df,
"dhm": dhm
}
records.append(perimeter_record)
return records
def process_records(process_records, process_function, num_processes = 1):
# Create queues
perimeter_queue = JoinableQueue()
#Insert records into queue
for r in process_records:
perimeter_queue.put(r)
#Create and start worker processes
processes = []
for i in range(num_processes):
perimeter_queue.put(None)
proc = Process(target=worker, args=(perimeter_queue,process_function,cfg,))
processes.append(proc)
print("Start: ",proc)
proc.start()
perimeter_queue.join()
# for p in processes:
# if p.exitcode == None:
# p.terminate()
print("Processing finished")
def process_records_linear(process_records, process_function, num_processes = 1):
# Create queues
perimeter_queue = JoinableQueue()
#Insert records into queue
for r in process_records:
perimeter_queue.put(r)
# break
print("Start:")
worker(perimeter_queue,process_function,cfg)
print("Processing finished")
def configure_log(cfg):
log_path = cfg.get("AP07__fintch_processing_paths","log_path")
logfile_info_path = os.path.join(log_path, current_process().name+"_info.log")
logfile_error_path = os.path.join(log_path, current_process().name+"_error.log")
log_format = "%(asctime)s; %(processName)s; %(levelname)s; %(name)s; %(message)s"
# comment this to suppress console output
stream_handler = logging.StreamHandler()
file_handler_info = logging.FileHandler(logfile_info_path, mode='w')
file_handler_info.setLevel(logging.INFO)
file_handler_error = logging.FileHandler(logfile_error_path, mode='w')
file_handler_error.setLevel(logging.ERROR)
logging.basicConfig(
level=logging.INFO,
format=log_format,
handlers=[
stream_handler, file_handler_info, file_handler_error
])
sys.stdout = LogFile('stdout')
sys.stderr = LogFile('stderr')
# Default entry point
if __name__ == "__main__":
start_time = time.time()
#Setup detection
path_to_config_file = os.environ['FINTCH_CONFIG_HOME']
ini_config_file = os.path.join(path_to_config_file, "FINTCH_config.ini")
cfg = configparser.ConfigParser()
cfg._interpolation = configparser.ExtendedInterpolation()
cfg.read(ini_config_file)
result_base_path = r"F:\fint-ch\Geodaten\diss\Results"
log_path = os.path.join(result_base_path, "procesing_log")
flaechen_info_path = r"F:\fint-ch\Geodaten\diss\kantone_info.csv"
reference_plot_path = r"F:\fint-ch\Geodaten\diss\reference_plots.shp"
flaeche_id_column = "KANTONSNUM"
dhm_path = r"E:\GIS_Projekte\Geodaten\DHM25\TIFF\dhm25_grid_raster.tif"
veg_zone_gdb_path = r"F:\fint-ch\Geodaten\diss\Vegetationshöhenstufen_BAFU\veg_zones.gdb"
veg_zone_table = "Vegetationshoehenstufen_1995"
plot_radius = 25
reference_plot_df = gpd.read_file(reference_plot_path)
flaeche_info_df = pd.read_csv(flaechen_info_path, delimiter=";")
veg_zone_df = gpd.read_file(veg_zone_gdb_path, layer=veg_zone_table)
ensure_dir(result_base_path)
ensure_dir(log_path)
truncate = True
configure_log(cfg)
table_schema = "fintch"
table_base_name = "diss"
table_owner = "geoserver"
db_connection = psycopg2.connect(host=cfg.get("AP07__db","host"), dbname=cfg.get("AP07__db","dbname"), user=cfg.get("AP07__db","user"), password=cfg.get("AP07__db","password"))
srid = cfg.get("AP07__pyfint","epsg")
fintch_processing_core_pub.create_db_tables(table_schema,table_base_name,table_owner,srid,db_connection)
parameter_sets = {
1 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":"", "gauss_size":"", "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
2 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":"", "gauss_size":"", "resize_method":"bilinear", "resize_resolution":1.5, "output_suffix":"", "preprocessing":"", "postprocessing":""},
3 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":"", "gauss_size":"", "resize_method":"bilinear", "resize_resolution":2, "output_suffix":"", "preprocessing":"", "postprocessing":""},
4 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":1, "gauss_size":3, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
5 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":1, "gauss_size":5, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
6 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":1, "gauss_size":7, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
7 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":3, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
8 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":5, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
9 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":7, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
10 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":3, "gauss_size":3, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
11 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":3, "gauss_size":5, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
12 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":3, "gauss_size":7, "resize_method":"bilinear", "resize_resolution":1, "output_suffix":"", "preprocessing":"", "postprocessing":""},
13 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":3, "resize_method":"bilinear", "resize_resolution":1.5, "output_suffix":"", "preprocessing":"", "postprocessing":""},
14 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":5, "resize_method":"bilinear", "resize_resolution":1.5, "output_suffix":"", "preprocessing":"", "postprocessing":""},
15 : {"dbh_function":"2.52*H^0.84", "randomized":False, "random_variance":0, "altitutde_allowed":False, "minimum_detection_tree_height":1, "minimum_tree_height":3, "gauss_sigma":2, "gauss_size":7, "resize_method":"bilinear", "resize_resolution":1.5, "output_suffix":"", "preprocessing":"", "postprocessing":""},
}
#prepare jobs/job records
records = process_record_setup(parameter_sets, reference_plot_df, flaeche_id_column, flaeche_info_df, veg_zone_df, dhm_path, plot_radius, fintch_processing_core_pub.process_perimeter_dem, table_schema, table_base_name, cfg, result_base_path, log_path, num_processes = 1)
#process perimeter (FST, Vegetation Zones, Terrain)
process_records(records,fintch_processing_core_pub.process_perimeter, num_processes = 20)
#process detection
process_records(records,fintch_processing_core_pub.process_detection, num_processes = 40)
#process detection with Eysn LM + Filter preprocessing/parameterset_id:30
process_records(records,fintch_processing_core_pub.process_detection_eysn_lm_filter, num_processes = 40)
#process detection with Kaartinen FGI_LOCM without Watershed/parameterset_id:31
process_records(records,fintch_processing_core_pub.process_detection_kaartinen_fgi_locm, num_processes = 40)
db_connection.close()
print("TOTAL PROCESSING TIME: %s (h:min:sec)" % str(timedelta(seconds=(time.time() - start_time))))
| HAFL-WWI/FINTCH-publication-code | 2022-improving-local-maxima-idt/python/detection/Processing/fintch_processing_process_pub.py | fintch_processing_process_pub.py | py | 14,644 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.environ.get",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 19,
"usage_type": "attribute"
},
{
"api_name": "sys.path.append",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_n... |
35681548851 | import os
import sys
import cv2
import time
import pickle
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix,accuracy_score,f1_score
def generate_pca_dataset(datapath):
time1 = time.clock()
folders = [
'00000001', '00000002', '00000003', '00000004', '00000005', '00000006', '00000007', '00000008', '00000009', '00000010',
'00000011', '00000012', '00000013', '00000014', '00000015', '00000016', '00000017', '00000018', '00000019', '00000020',
'00000021', '00000022', '00000023', '00000024', '00000025', '00000026', '00000027', '00000028', '00000029', '00000030',
'00000031', '00000032', '00000033', '00000034', '00000035', '00000036', '00000037', '00000038', '00000039', '00000040',
'00000041', '00000042', '00000043', '00000044', '00000045', '00000046', '00000047', '00000048', '00000049', '00000050']
gray_list = []
for folder in folders:
all_files = os.listdir(datapath+"/"+folder+"/")
png_files = []
for file in all_files:
png_files.append(file) if ('.png' in file) else None
for file in png_files:
gray_list.append(np.float32(np.ravel(cv2.cvtColor(cv2.imread(datapath+"/"+folder+"/"+file)[32:196,11:153,:], cv2.COLOR_BGR2GRAY))/255.0))
del(all_files)
del(png_files)
a = np.array(gray_list)
del(gray_list)
del(folders)
time2 = time.clock()
print("Time taken to generate dataset for PCA -> " + str(time2-time1))
return a
def pca_transform_folder_wise(datapath,my_pca):
time1 = time.clock()
folder_list = os.listdir(datapath+"/")
counter = 0
for folder in folder_list:
time2 = time.clock()
print(folder)
all_files = os.listdir(datapath+"/"+folder+"/")
png_files = []
for file in all_files:
png_files.append(file) if ('.png' in file) else None
curr_data = []
for file in png_files:
curr_data.append(my_pca.transform(np.float32(np.ravel(cv2.cvtColor(cv2.imread(datapath+"/"+folder+"/"+file)[32:196,11:153,:], cv2.COLOR_BGR2GRAY)).reshape(1,-1)/255.0)).tolist())
del(all_files)
del(png_files)
svm_train_x = open(datapath+"/"+folder+"/pca_normalized_transform_list",'ab')
pickle.dump(curr_data,svm_train_x)
svm_train_x.close()
time3 = time.clock()
print("Time taken to generate and store pickle = " + str(time3-time2))
time3 = time.clock()
print("Time taken to generate all pickle files folder wise = " + str(time3-time1))
def synthesize_svm_data(datapath,my_pca,name,reward_avail):
time1 = time.clock()
folder_list = os.listdir(datapath+"/")
if reward_avail==1:
folder_list.remove("rewards.csv")
reward_list = np.array(pd.read_csv(datapath + "/rewards.csv",header=None,dtype=int))[:,1].tolist()
list_for_array = []
for folder in folder_list:
all_files = os.listdir(datapath+"/"+folder+"/")
png_files = []
curr_data = []
for file in all_files:
png_files.append(file) if ('.png' in file) else None
for file in png_files:
curr_data.extend(my_pca.transform(np.float32(np.ravel(cv2.cvtColor(cv2.imread(datapath+"/"+folder+"/"+file)[32:196,11:153,:], cv2.COLOR_BGR2GRAY)).reshape(1,-1)/255.0).tolist()))
list_for_array.append(curr_data)
del(curr_data)
del(all_files)
del(png_files)
time2 = time.clock()
print("Time taken to generate list = " + str(time2-time1))
svm_val_x = open(name+"x",'ab')
pickle.dump(list_for_array,svm_val_x)
svm_val_x.close()
time3 = time.clock()
print("Time taken to generate pickle file for x = " + str(time3-time2))
if reward_avail==1:
svm_val_y = open(name+"y",'ab')
pickle.dump(reward_list,svm_val_y)
svm_val_y.close()
time4 = time.clock()
print("Time taken to generate pickle file for y = " + str(time4-time3))
def get_train_data(datapath,num_folders):
time1 = time.clock()
train_x = []
train_y = []
folder_list = os.listdir(datapath+"/")
for folder_idx in range(num_folders):
folder = folder_list[folder_idx]
time2 = time.clock()
reward_array = np.array(pd.read_csv(datapath+"/"+folder+"/rew.csv",dtype=int)).tolist()
pickle_file = open(datapath+"/"+folder+"/pca_normalized_transform_list",'rb')
curr_data = pickle.load(pickle_file)
pickle_file.close()
del(pickle_file)
for last_frame in range(6,len(curr_data)-3,1):
frame_num_list = [x for x in range(last_frame-6,last_frame+1)]
data = []
for frame_num in frame_num_list:
data.append(curr_data[frame_num][0])
if reward_array[last_frame+1]==1:
for drop1 in range(5):
for drop2 in range(drop1+1,6):
new_list = [y for y in [0,1,2,3,4,5,6] if y not in [drop1,drop2]]
new_data = []
for idx in new_list:
new_data.extend(data[idx])
train_x.append(new_data)
train_y.append(reward_array[last_frame+1][0])
if last_frame%3==0:
train_x.append(new_data)
train_y.append(reward_array[last_frame+1][0])
del(new_list)
del(new_data)
else:
count_max = folder_idx%2
for count in range(count_max):
drop1 = 0
drop2 = 0
while drop1==drop2:
drop1 = np.random.randint(6)
drop2 = np.random.randint(6)
new_list = [y for y in [0,1,2,3,4,5,6] if y not in [drop1,drop2]]
new_data = []
for idx in new_list:
new_data.extend(data[idx])
train_x.append(new_data)
train_y.append(reward_array[last_frame+1][0])
del(new_list)
del(new_data)
del(data)
del(frame_num)
del(frame_num_list)
time3 = time.clock()
print("Time taken to generate data from "+folder+" -> "+str(time3-time2))
time2 = time.clock()
print("Total time taken to generate train data -> " + str(time2-time1))
return train_x,train_y
def get_test_data(val_or_test,reward_avail):
path = ""
val_x = []
if val_or_test==0:
path = "./pca_val_normalized"
else:
path = "pca_test_normalized"
# Loading the x file
pickle_file = open(path+"x",'rb')
data_dash = pickle.load(pickle_file)
pickle_file.close()
for i in range(len(data_dash)):
curr_data = []
for j in range(5):
curr_data.extend(data_dash[i][j])
val_x.append(curr_data)
if val_or_test==1:
return val_x
else:
pickle_file = open(path+"y",'rb')
data_dash = pickle.load(pickle_file)
pickle_file.close()
return val_x,data_dash
def main():
dataset = generate_pca_dataset("../train_dataset")
pca_dataset_pickle_file = open("pca_dataset_pickle",'rb')
dataset = pickle.load(pca_dataset_pickle_file)
my_pca = PCA(n_components=50)
my_pca.fit(dataset)
del(dataset)
pca_transform_folder_wise("../train_dataset",my_pca)
synthesize_svm_data("../validation_dataset",my_pca,"pca_val_normalized",1)
synthesize_svm_data("../test_dataset",my_pca,"pca_test_normalized",0)
del(my_pca)
time1 = time.clock()
num_folders = 500
train_x,train_y = get_train_data("../train_dataset",num_folders)
time2 = time.clock()
print("Training data read in " + str(time2-time1))
val_x,val_y = get_test_data(0,1)
test_x = get_test_data(1,0)
penalty = 5
gamma = "auto"
print("Val and test data read")
time3 = time.clock()
linear_svm = SVC(C=penalty,kernel='linear',max_iter=4000)
linear_svm.fit(train_x,train_y)
time4 = time.clock()
print("Linear trained in " + str(time4-time3))
time5 = time.clock()
gaussian_svm = SVC(C=penalty,kernel='rbf',gamma=gamma,max_iter=4000)
gaussian_svm.fit(train_x,train_y)
time6 = time.clock()
print("Gaussian trained in " + str(time6-time5))
linear_svm_pickle = open("svm_linear_trained",'ab')
pickle.dump(linear_svm,linear_svm_pickle)
linear_svm_pickle.close()
gaussian_svm_pickle = open("gaussian_svm_trained",'ab')
pickle.dump(gaussian_svm,gaussian_svm_pickle)
gaussian_svm_pickle.close()
linear_svm_pickle = open("svm_linear_trained",'rb')
linear_svm = pickle.load(linear_svm_pickle)
linear_svm_pickle.close()
gaussian_svm_pickle = open("gaussian_svm_trained",'rb')
gaussian_svm = pickle.load(gaussian_svm_pickle)
gaussian_svm_pickle.close()
linear_pred_lbl = linear_svm.predict(train_x)
print("Linear Model with penalty = " + str(penalty) + ": ")
print("Train Accuracy -> " + str(accuracy_score(np.array(train_y),linear_pred_lbl)))
print("Train F1_score -> " + str(f1_score(np.array(train_y),linear_pred_lbl,average="micro")))
print(confusion_matrix(np.array(train_y),linear_pred_lbl))
print(f1_score(np.array(train_y),linear_pred_lbl))
linear_pred_lbl = linear_svm.predict(val_x)
print("Test Accuracy -> " + str(accuracy_score(np.array(val_y),linear_pred_lbl)))
print("Test F1_score -> " + str(f1_score(np.array(val_y),linear_pred_lbl,average="micro")))
print(confusion_matrix(np.array(val_y),linear_pred_lbl))
print(f1_score(np.array(val_y),linear_pred_lbl))
# time5 = time.clock()
gaussian_pred_lbl = gaussian_svm.predict(train_x)
print("Gaussian Model with penalty = " + str(penalty) + " and gamma = " + str(gamma))
print("Train Accuracy -> " + str(accuracy_score(np.array(train_y),gaussian_pred_lbl)))
print("Train F1_score -> " + str(f1_score(np.array(train_y),gaussian_pred_lbl,average="micro")))
print(confusion_matrix(np.array(train_y),gaussian_pred_lbl))
print(f1_score(np.array(train_y),gaussian_pred_lbl))
gaussian_pred_lbl = gaussian_svm.predict(val_x)
print("Test Accuracy -> " + str(accuracy_score(np.array(val_y),gaussian_pred_lbl)))
print("Test F1_score -> " + str(f1_score(np.array(val_y),gaussian_pred_lbl,average="micro")))
print(confusion_matrix(np.array(val_y),gaussian_pred_lbl))
print(f1_score(np.array(val_y),gaussian_pred_lbl))
columns = ["Prediction"]
linear_test_pred = np.ravel(linear_svm.predict(test_x)).tolist()
gaussian_test_pred = np.ravel(gaussian_svm.predict(test_x)).tolist()
pd.DataFrame(np.array(linear_test_pred)).to_csv("linear_svm_prediction.csv",header=columns,index=True)
pd.DataFrame(np.array(gaussian_test_pred)).to_csv("gaussian_svm_prediction.csv",header=columns,index=True)
if __name__ == '__main__':
main()
| pradyumnameena/COL774-Machine-Learning | Assignment-4/pca.py | pca.py | py | 9,783 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "time.clock",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "os.listdir",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "numpy.float32",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "numpy.ravel",
"line_number": ... |
35376239294 | # time-dependent solutions for P_00(t), P_01(t), and P_10(t) and P_01(t)
# taken from Anderson 2017 Lecture Notes on Stochastic Processes with Applications in Biology
# P_00(t) is the chance of being in the inactive state at t=t, given being in the inactive state at t=0
# or P_00(t) = P(x_t = 0 | x_0 = 0) with x=0 is being inactive and x=1 is being inactive
# restrictions P_00(t) + P_01(t) = 1
# and P_10(t) + P_11(t) = 1
import numpy as np
import matplotlib.pyplot as plt
def p_00(k_on, k_off, t):
la = k_on
mu = k_off
ret_val = mu/(mu + la) + la/(mu + la) * np.exp(-(mu + la)*t)
return ret_val
def p_10(k_on, k_off, t):
la = k_on
mu = k_off
ret_val = mu/(mu + la) - mu/(mu + la) * np.exp(-(mu + la)*t)
return ret_val
def create_transition_chances(k_on, k_off):
wins = [j*15 for j in range(0, 9)]
p_00s = []
p_10s = []
for t in wins:
p_00s.append(p_00(k_on, k_off, t))
p_10s.append(p_10(k_on, k_off, t))
p_01s = [1 - p for p in p_00s]
p_11s = [1 - p for p in p_10s]
return wins, (p_00s, p_10s, p_01s, p_11s)
def plot_transition_chances(k_on, k_off, wins, p_00s, p_10s, p_01s, p_11s):
plt.plot(wins, p_00s, 'o-', label="P_00")
plt.plot(wins, p_10s, 'o-', label="P_10")
plt.plot(wins, p_01s, 'o-', label="P_01")
plt.plot(wins, p_11s, 'o-', label="P_11")
title = "k_on={k_on};k_off={k_off}. Chances of being in state x_t given state x_0," \
" with e.g. P_00 = P(x_t=0 | x_0=0)".\
format(k_on=k_on, k_off=k_off)
plt.title(title)
plt.ylim(0, 1)
plt.legend()
plt.xlabel("time in minutes")
plt.ylabel("chance")
plt.show()
plt.close(1)
k_on = 0.01
k_off = 0.04
wins, (p_00s, p_10s, p_01s, p_11s) = create_transition_chances(k_on=k_on, k_off=k_off)
plot_transition_chances(k_on, k_off, wins, p_00s, p_10s, p_01s, p_11s)
| resharp/scBurstSim | solution/nonstat_markov.py | nonstat_markov.py | py | 1,894 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "numpy.exp",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "numpy.exp",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.plot",
"line_number": 48,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"l... |
15975975433 | # *-* coding: utf-8 *-*
"""
Created on sam 22 mai 2021 19:11:56 CEST
@author : vekemans
"""
import numpy as np
from numpy.fft import \
rfft,irfft,fftfreq,\
rfft2,irfft2,rfftfreq
from scipy import sparse
from scipy.interpolate import interp2d
import matplotlib
import matplotlib.pyplot as plt
nfig = 1
import cahn_hilliard as ch
import cahn_hilliard_sd as chs
range_n = 2**np.arange(2,11)
error_fd = np.zeros(range_n.shape)
error_rk4 = np.zeros(range_n.shape)
error_bdf_ab = np.zeros(range_n.shape)
n_ref = 2*range_n[-1]
time = 1e-4
# c0 = np.random.random(n_ref*n_ref)*2 -1
# c0 = c0.reshape((n_ref,n_ref))
c0 = np.ones((n_ref,n_ref))
c0[:n_ref//4,:] = -1
c0[3*n_ref//4:,:] = -1
c0[:,:n_ref//4] = -1
c0[:,3*n_ref//4:] = -1
sim = iter(chs.simulate(c0,n_ref,time))
next(sim); sol = next(sim)
x = np.arange(0,1,step=1/n_ref)
# c0_interpolation = interp2d(x,x,c0, kind='cubic')
sol_interpolation = interp2d(x,x,sol, kind='linear')
for i,n in enumerate(range_n):
x = np.arange(0,1,step=1/n)[:n]
# c0 = c0_interpolation(x,x)
c0 = np.ones((n,n))
c0[:n//4,:] = -1
c0[3*n//4:,:] = -1
c0[:,:n//4] = -1
c0[:,3*n//4:] = -1
sim = iter(ch.simulate(c0.flatten(),n,time))
next(sim); guess = next(sim)
error_fd[i] = ((guess-sol_interpolation(x,x))**2).mean()**0.5
sim = iter(chs.simulate(c0,n,time,temp_scheme='rk4'))
next(sim); guess = next(sim)
error_rk4[i] = ((guess-sol_interpolation(x,x))**2).mean()**0.5
sim = iter(chs.simulate(c0,n,time))
next(sim); guess = next(sim)
error_bdf_ab[i] = ((guess-sol_interpolation(x,x))**2).mean()**0.5
fig = plt.figure(nfig)
plt.plot(range_n,error_fd,ls='-',marker='o',markersize=8, label='FD EE')
plt.plot(range_n,error_rk4,ls=':',marker='v',markersize=8, label='Spectral RK4')
plt.plot(range_n,error_bdf_ab,ls='--',marker='^',markersize=8, label='Spectral BDF/AB')
# plt.xticks([2,4,6,8,10],labels=[r'$2^{%d}$' %i for i in [2,4,6,8,10]])
plt.legend(loc='best'); plt.xscale('log', base=2); plt.yscale('log')
plt.xlabel('n'); plt.ylabel(r'L2 norm error at $t=10^{%d}$ [s]' %(round(np.log(time)/np.log(10))))
plt.grid(which='major',axis='both',color='xkcd:grey',linestyle='--',linewidth=0.8)
plt.grid(which='minor',axis='y',color='xkcd:grey',linestyle='--',linewidth=0.8)
fig.tight_layout()
print(np.log(error_bdf_ab[-2]/error_bdf_ab[-1])/np.log(2))
fig.savefig('../figs/convergence.pdf')
plt.show()
| abbarn/lmeca2300 | project/pylib/convergence.py | convergence.py | py | 2,416 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.arange",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number":... |
38688339389 | import torch
from utils.metrics import AURC
import numpy as np
from utils.measures import MSP
def centralize(y:torch.tensor):
return y-(y.mean(-1).view(-1,1))
def p_norm(y:torch.tensor,p, eps:float = 1e-12):
if p is None or p == 0: return torch.ones(y.size(0),1,device=y.device)
else: return y.norm(p=p,dim=-1).clamp_min(eps).view(-1,1)
def beta_heuristic(y:torch.tensor,p):
if p==0 or p is None: return 1
return (p_norm(y,p).mean())
def beta_generalized_mean(n,p):
if p==0 or p is None: return 1
else: return (n*np.math.factorial(p))**(1/p)
def pNormSoftmax(y:torch.tensor,p,beta= None, out = 'MSP'):
'''Implement pNormSoftmax (centralize the logits, p-normalize, scale by beta and
apply MSP).
If beta is None, defines beta as the heuristic beta (mean of the p-norms).
If out is passes as 'logits', return the normalized logits (skip MSP)'''
y = centralize(y)
norm = p_norm(y,p)
if beta is None: beta = norm.mean()
if out == 'logits':
return y.mul(beta).div(norm)
else: return MSP(y.mul(beta).div(norm))
class optimize:
'''Gradient methods could be used, but a grid search
on a small set of p's show to be strongly efficient for pNormSoftmax optimization.
Also, AURC and AUROC are not differentiable'''
p_range = torch.arange(8)
T_range = torch.arange(0.01,2,0.01)
@staticmethod
def p_and_beta(logits,risk,metric = AURC,p_range = p_range,T_range =T_range):
vals = optimize.p_T_grid(logits,risk,metric,p_range,T_range)
p,T = np.unravel_index(np.argmin(vals),np.shape(vals))
p = p_range[p]
T = T_range[T]
return p,beta_heuristic(logits,p)/T
@staticmethod
def p(logits, risk,metric = AURC,p_range = p_range, heuristic = True):
if heuristic: beta = None
else: beta = 1.0
vals = optimize.p_grid(logits,risk,metric,p_range, beta)
p = p_range[np.argmin(vals)]
return p
@staticmethod
def T(logits, risk,metric = AURC,T_range = T_range):
vals = optimize.T_grid(logits,risk,metric,T_range)
return T_range[np.argmin(vals)]
@staticmethod
def T_grid(logits,risk,metric = AURC,T_range = T_range):
vals = []
for T in T_range:
vals.append(metric(risk,MSP(logits.div(T))).item())
return vals
@staticmethod
def p_grid(logits,risk,metric = AURC,p_range = p_range, beta = None):
vals = []
for p in p_range:
vals.append(metric(risk,pNormSoftmax(logits,p,beta)).item())
return vals
@staticmethod
def p_T_grid(logits,risk,metric = AURC,p_range = p_range,T_range = T_range):
vals = []
for p in p_range:
vals_T = optimize.T_grid(pNormSoftmax(logits,p,None,'logits'),risk,metric,T_range)
vals.append(vals_T)
return vals
@staticmethod
def T_fromloss(logits,labels,loss = torch.nn.CrossEntropyLoss(),T_range = T_range):
vals = optimize.T_grid_fromloss(logits,labels,loss,T_range)
return T_range[np.argmin(vals)]
@staticmethod
def T_grid_fromloss(logits,labels,loss = torch.nn.CrossEntropyLoss(),T_range = T_range):
vals = []
for T in T_range:
vals.append(loss(logits.div(T),labels).item())
return vals
def optimal_pNormSoftmax(z:torch.tensor,risk:torch.tensor,metric = AURC,optimize_beta = False,**kwargs):
if optimize_beta: p,beta = optimize.p_and_beta(z,risk,metric,**kwargs)
else:
p = optimize.p(z, risk,metric, **kwargs)
beta = beta_heuristic(z,p)
return pNormSoftmax(z,p,beta) | lfpc/pNormSoftmax | pNormSoftmax.py | pNormSoftmax.py | py | 3,632 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "torch.tensor",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "torch.tensor",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "torch.ones",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "torch.tensor",
"line_... |
2356478535 | from __future__ import print_function
import argparse
import cgi
import locale
import os
import re
import sys
from .. import cli
from .. import hocr
from .. import ipc
from .. import logger
from .. import temporary
from .. import text_zones
from .. import unicode_support
from .. import utils
from .. import version
from ..hocr import etree
from ..text_zones import const
from ..text_zones import sexpr
__version__ = version.__version__
system_encoding = locale.getpreferredencoding()
logger = logger.setup()
class ArgumentParser(cli.ArgumentParser):
def __init__(self):
usage = '%(prog)s [options] FILE'
cli.ArgumentParser.__init__(self, usage=usage)
self.add_argument('--version', action=version.VersionAction)
group = self.add_argument_group(title='input selection options')
group.add_argument('path', metavar='FILE', help='DjVu file to covert')
def pages(x):
return utils.parse_page_numbers(x)
group.add_argument('-p', '--pages', dest='pages', action='store', default=None, type=pages, help='pages to convert')
group = self.add_argument_group(title='word segmentation options')
group.add_argument('--word-segmentation', dest='word_segmentation', choices=('simple', 'uax29'), default='simple', help='word segmentation algorithm')
# -l/--language is currently not very useful, as ICU don't have any specialisations for languages ocrodjvu supports:
group.add_argument('-l', '--language', dest='language', help=argparse.SUPPRESS or 'language for word segmentation', default='eng')
group = self.add_argument_group(title='HTML output options')
group.add_argument('--title', dest='title', help='document title', default='DjVu hidden text layer')
group.add_argument('--css', metavar='STYLE', dest='css', help='CSS style', default='')
def parse_args(self, args=None, namespace=None):
options = cli.ArgumentParser.parse_args(self, args, namespace)
if options.word_segmentation == 'uax29':
options.icu = icu = unicode_support.get_icu()
options.locale = icu.Locale(options.language)
else:
options.icu = None
options.locale = None
return options
class CharacterLevelDetails(Exception):
pass
class Zone(object):
def __init__(self, sexpr, page_height):
self._sexpr = sexpr
self._page_height = page_height
@property
def type(self):
return const.get_text_zone_type(self._sexpr[0].value)
@property
def bbox(self):
return text_zones.BBox(
self._sexpr[1].value,
self._page_height - self._sexpr[4].value,
self._sexpr[3].value,
self._page_height - self._sexpr[2].value,
)
@property
def text(self):
if len(self._sexpr) != 6:
raise TypeError('list of {0} (!= 6) elements'.format(len(self._sexpr))) # no coverage
if not isinstance(self._sexpr[5], sexpr.StringExpression):
raise TypeError('last element is not a string') # no coverage
return unicode(self._sexpr[5].value, 'UTF-8', 'replace')
@property
def children(self):
for child in self._sexpr[5:]:
if isinstance(child, sexpr.ListExpression):
yield Zone(child, self._page_height)
else:
yield self.text
return
@property
def n_children(self):
n = len(self._sexpr) - 5
if n <= 0:
raise TypeError('list of {0} (< 6) elements'.format(len(self._sexpr))) # no coverage
return n
def __repr__(self):
return '{tp}({sexpr!r})'.format(tp=type(self).__name__, sexpr=self._sexpr)
_xml_string_re = re.compile(
u'''
([^\x00-\x08\x0B\x0C\x0E-\x1F]*)
( [\x00-\x08\x0B\x0C\x0E-\x1F]?)
''',
re.VERBOSE
)
def set_text(element, text):
last = None
for match in _xml_string_re.finditer(text):
if match.group(1):
if last is None:
element.text = match.group(1)
else:
last.tail = match.group(1)
if match.group(2):
last = etree.Element('span')
last.set('class', 'djvu_char')
last.set('title', '#x{0:02x}'.format(ord(match.group(2))))
last.text = ' '
element.append(last)
def break_chars(char_zone_list, options):
bbox_list = []
text = []
for char_zone in char_zone_list:
bbox = char_zone.bbox
char_text = char_zone.text
if not char_text:
continue
for i, char in enumerate(char_text):
subbox = text_zones.BBox(
int(bbox.x0 + (bbox.x1 - bbox.x0) * 1.0 * i / len(char_text) + 0.5),
bbox.y0,
int(bbox.x0 + (bbox.x1 - bbox.x0) * 1.0 * (i + 1) / len(char_text) + 0.5),
bbox.y1,
)
bbox_list += [subbox]
text += [char_text]
text = str.join('', text)
break_iterator = unicode_support.word_break_iterator(text, options.locale)
element = None
i = 0
for j in break_iterator:
subtext = text[i:j]
if subtext.isspace():
if element is not None:
element.tail = ' '
i = j
continue
bbox = text_zones.BBox()
for k in xrange(i, j):
bbox.update(bbox_list[k])
element = etree.Element('span')
element.set('class', 'ocrx_word')
element.set('title', 'bbox {bbox}; bboxes {bboxes}'.format(
bbox=str.join(' ', map(str, bbox)),
bboxes=str.join(', ', (str.join(' ', map(str, bbox)) for bbox in bbox_list[i:j]))
))
set_text(element, subtext)
yield element
i = j
def break_plain_text(text, bbox, options):
break_iterator = unicode_support.word_break_iterator(text, options.locale)
i = 0
element = None
for j in break_iterator:
subtext = text[i:j]
if subtext.isspace():
if element is not None:
element.tail = ' '
i = j
continue
subbox = text_zones.BBox(
int(bbox.x0 + (bbox.x1 - bbox.x0) * 1.0 * i / len(text) + 0.5),
bbox.y0,
int(bbox.x0 + (bbox.x1 - bbox.x0) * 1.0 * j / len(text) + 0.5),
bbox.y1,
)
element = etree.Element('span')
element.set('class', 'ocrx_word')
element.set('title', 'bbox ' + str.join(' ', map(str, subbox)))
set_text(element, subtext)
yield element
i = j
def process_zone(parent, zone, last, options):
zone_type = zone.type
if zone_type <= const.TEXT_ZONE_LINE and parent is not None:
parent.tail = '\n'
try:
hocr_tag, hocr_class = hocr.djvu_zone_to_hocr(zone_type)
except LookupError as ex:
if ex[0] == const.TEXT_ZONE_CHARACTER:
raise CharacterLevelDetails
raise
self = etree.Element(hocr_tag)
self.set('class', hocr_class)
if zone_type == const.TEXT_ZONE_PAGE:
bbox = options.page_bbox
else:
bbox = zone.bbox
self.set('title', 'bbox ' + str.join(' ', map(str, bbox)))
n_children = zone.n_children
character_level_details = False
for n, child_zone in enumerate(zone.children):
last_child = n == n_children - 1
if isinstance(child_zone, Zone):
try:
process_zone(self, child_zone, last=last_child, options=options)
except CharacterLevelDetails:
# Do word segmentation by hand.
character_level_details = True
break
if character_level_details:
# Do word segmentation by hand.
child = None
for child in break_chars(zone.children, options):
parent.append(child)
if child is not None and zone_type == const.TEXT_ZONE_WORD and not last:
child.tail = ' '
self = None
elif isinstance(child_zone, unicode):
text = child_zone
if zone_type >= const.TEXT_ZONE_WORD and options.icu is not None and parent is not None:
# Do word segmentation by hand.
child = None
for child in break_plain_text(text, bbox, options):
parent.append(child)
if child is not None and zone_type == const.TEXT_ZONE_WORD and not last:
child.tail = ' '
self = None
else:
# Word segmentation as provided by DjVu.
# There's no point in doing word segmentation if only line coordinates are provided.
set_text(self, text)
if zone_type == const.TEXT_ZONE_WORD and not last:
self.tail = ' '
if parent is not None and self is not None:
parent.append(self)
return self
def process_page(page_text, options):
result = process_zone(None, page_text, last=True, options=options)
tree = etree.ElementTree(result)
tree.write(sys.stdout, encoding='UTF-8')
hocr_header_template = '''\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="ocr-system" content="{ocr_system}" />
<meta name="ocr-capabilities" content="{ocr_capabilities}" />
<style type="text/css">{css}</style>
<title>{title}</title>
</head>
<body>
'''
hocr_header_style_re = re.compile(r'^\s+<style\s.*?\n', re.MULTILINE)
hocr_footer = '''
</body>
</html>
'''
def main(argv=sys.argv):
options = ArgumentParser().parse_args(argv[1:])
logger.info('Converting {path}:'.format(path=utils.smart_repr(options.path, system_encoding)))
if options.pages is None:
djvused = ipc.Subprocess(
['djvused', '-e', 'n', os.path.abspath(options.path)],
stdout=ipc.PIPE,
)
try:
n_pages = int(djvused.stdout.readline())
finally:
djvused.wait()
options.pages = xrange(1, n_pages + 1)
page_iterator = iter(options.pages)
sed_script = temporary.file(suffix='.djvused')
for n in options.pages:
print('select {0}; size; print-txt'.format(n), file=sed_script)
sed_script.flush()
djvused = ipc.Subprocess(
['djvused', '-f', sed_script.name, os.path.abspath(options.path)],
stdout=ipc.PIPE,
)
ocr_system = 'djvu2hocr {ver}'.format(ver=__version__)
hocr_header = hocr_header_template.format(
ocr_system=ocr_system,
ocr_capabilities=str.join(' ', hocr.djvu2hocr_capabilities),
title=cgi.escape(options.title),
css=cgi.escape(options.css),
)
if not options.css:
hocr_header = re.sub(hocr_header_style_re, '', hocr_header, count=1)
sys.stdout.write(hocr_header)
for n in page_iterator:
try:
page_size = [
int(str(sexpr.Expression.from_stream(djvused.stdout).value).split('=')[1])
for i in xrange(2)
]
options.page_bbox = text_zones.BBox(0, 0, page_size[0], page_size[1])
page_text = sexpr.Expression.from_stream(djvused.stdout)
except sexpr.ExpressionSyntaxError:
break
logger.info('- Page #{n}'.format(n=n))
page_zone = Zone(page_text, page_size[1])
process_page(page_zone, options)
sys.stdout.write(hocr_footer)
djvused.wait()
# vim:ts=4 sts=4 sw=4 et
| jwilk-archive/ocrodjvu | lib/cli/djvu2hocr.py | djvu2hocr.py | py | 11,591 | python | en | code | 41 | github-code | 36 | [
{
"api_name": "locale.getpreferredencoding",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "argparse.SUPPRESS",
"line_number": 44,
"usage_type": "attribute"
},
{
"api_name": "text_zones.sexpr",
"line_number": 65,
"usage_type": "name"
},
{
"api_name": "t... |
15441316510 | """
Entity class for iDiamant.
"""
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, NAME, VERSION, MANUFACTURER
class IdiamantEntity(CoordinatorEntity):
"""
The main iDiamant entity class.
"""
def __init__(self, coordinator, config_entry):
super().__init__(coordinator)
self.config_entry = config_entry
@property
def unique_id(self):
"""
Return a unique ID to use for this entity.
"""
return self.config_entry.entry_id
@property
def device_info(self):
"""
Return the device information.
"""
return {
"identifiers": {(DOMAIN, self.unique_id)},
"manufacturer": MANUFACTURER,
"model": VERSION,
"name": NAME,
}
@property
def device_state_attributes(self):
"""
Return the state attributes.
"""
return {
"id": str(self.coordinator.data.get("id")),
"integration": DOMAIN,
}
| clementprevot/home-assistant-idiamant | custom_components/idiamant/entity.py | entity.py | py | 1,067 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "homeassistant.helpers.update_coordinator.CoordinatorEntity",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "const.DOMAIN",
"line_number": 34,
"usage_type": "name"
},
{
"api_name": "const.MANUFACTURER",
"line_number": 35,
"usage_type": "name"
},... |
22354363555 | import datetime
import traceback
import typing
import humanfriendly
import mergedeep
import pytz
import sqlalchemy.orm
import mlrun.common.schemas
import mlrun.config
import mlrun.errors
import mlrun.utils
import mlrun.utils.helpers
import mlrun.utils.regex
import mlrun.utils.singleton
import server.api.crud
import server.api.db.session
import server.api.utils.auth.verifier
import server.api.utils.clients.iguazio
import server.api.utils.periodic
import server.api.utils.projects.member as project_member
import server.api.utils.projects.remotes.leader
import server.api.utils.projects.remotes.nop_leader
from mlrun.errors import err_to_str
from mlrun.utils import logger
class Member(
project_member.Member,
metaclass=mlrun.utils.singleton.AbstractSingleton,
):
def initialize(self):
logger.info("Initializing projects follower")
self._leader_name = mlrun.mlconf.httpdb.projects.leader
self._sync_session = None
self._leader_client: server.api.utils.projects.remotes.leader.Member
if self._leader_name == "iguazio":
self._leader_client = server.api.utils.clients.iguazio.Client()
if not mlrun.mlconf.httpdb.projects.iguazio_access_key:
raise mlrun.errors.MLRunInvalidArgumentError(
"Iguazio access key must be configured when the leader is Iguazio"
)
self._sync_session = mlrun.mlconf.httpdb.projects.iguazio_access_key
elif self._leader_name == "nop":
self._leader_client = server.api.utils.projects.remotes.nop_leader.Member()
else:
raise NotImplementedError("Unsupported project leader")
self._periodic_sync_interval_seconds = humanfriendly.parse_timespan(
mlrun.mlconf.httpdb.projects.periodic_sync_interval
)
self._synced_until_datetime = None
# run one sync to start off on the right foot and fill out the cache but don't fail initialization on it
try:
# Basically the delete operation in our projects mechanism is fully consistent, meaning the leader won't
# remove the project from its persistency (the source of truth) until it was successfully removed from all
# followers. Therefore, when syncing projects from the leader, we don't need to search for the deletions
# that may happen without us knowing about it (therefore full_sync by default is false). When we
# introduced the chief/worker mechanism, we needed to change the follower to keep its projects in the DB
# instead of in cache. On the switch, since we were using cache and the projects table in the DB was not
# maintained, we know we may have projects that shouldn't be there anymore, ideally we would have trigger
# the full sync only once on the switch, but since we don't have a good heuristic to identify the switch
# we're doing a full_sync on every initialization
full_sync = (
mlrun.mlconf.httpdb.clusterization.role
== mlrun.common.schemas.ClusterizationRole.chief
)
self._sync_projects(full_sync=full_sync)
except Exception as exc:
logger.warning(
"Initial projects sync failed",
exc=err_to_str(exc),
traceback=traceback.format_exc(),
)
self._start_periodic_sync()
def shutdown(self):
logger.info("Shutting down projects leader")
self._stop_periodic_sync()
def create_project(
self,
db_session: sqlalchemy.orm.Session,
project: mlrun.common.schemas.Project,
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
leader_session: typing.Optional[str] = None,
wait_for_completion: bool = True,
commit_before_get: bool = False,
) -> typing.Tuple[typing.Optional[mlrun.common.schemas.Project], bool]:
if self._is_request_from_leader(projects_role):
server.api.crud.Projects().create_project(db_session, project)
return project, False
else:
is_running_in_background = self._leader_client.create_project(
leader_session, project, wait_for_completion
)
created_project = None
if not is_running_in_background:
# as part of the store_project flow we encountered an error related to the isolation level we use.
# We use the default isolation level, I wasn't able to find exactly what is the default that sql alchemy
# sets but its serializable(once you SELECT a series of rows in a transaction, you will get the
# identical data back each time you re-emit that SELECT) or repeatable read isolation (you’ll see newly
# added rows (and no longer see deleted rows), but for rows that you’ve already loaded, you won’t see
# any change). Eventually, in the store_project flow, we already queried get_project and at the second
# time(below), after the project created, we failed because we got the same result from first query.
# Using session.commit ends the current transaction and start a new one which will result in a
# new query to the DB.
# for further read: https://docs-sqlalchemy.readthedocs.io/ko/latest/faq/sessions.html
# https://docs-sqlalchemy.readthedocs.io/ko/latest/dialects/mysql.html#transaction-isolation-level
# https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html
# TODO: there are multiple isolation level we can choose, READ COMMITTED seems to solve our issue
# but will require deeper investigation and more test coverage
if commit_before_get:
db_session.commit()
created_project = self.get_project(
db_session, project.metadata.name, leader_session
)
return created_project, is_running_in_background
def store_project(
self,
db_session: sqlalchemy.orm.Session,
name: str,
project: mlrun.common.schemas.Project,
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
leader_session: typing.Optional[str] = None,
wait_for_completion: bool = True,
) -> typing.Tuple[typing.Optional[mlrun.common.schemas.Project], bool]:
if self._is_request_from_leader(projects_role):
server.api.crud.Projects().store_project(db_session, name, project)
return project, False
else:
try:
self.get_project(db_session, name, leader_session)
except mlrun.errors.MLRunNotFoundError:
return self.create_project(
db_session,
project,
projects_role,
leader_session,
wait_for_completion,
commit_before_get=True,
)
else:
self._leader_client.update_project(leader_session, name, project)
return self.get_project(db_session, name, leader_session), False
def patch_project(
self,
db_session: sqlalchemy.orm.Session,
name: str,
project: dict,
patch_mode: mlrun.common.schemas.PatchMode = mlrun.common.schemas.PatchMode.replace,
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
leader_session: typing.Optional[str] = None,
wait_for_completion: bool = True,
) -> typing.Tuple[typing.Optional[mlrun.common.schemas.Project], bool]:
if self._is_request_from_leader(projects_role):
# No real scenario for this to be useful currently - in iguazio patch is transformed to store request
raise NotImplementedError("Patch operation not supported from leader")
else:
current_project = self.get_project(db_session, name, leader_session)
strategy = patch_mode.to_mergedeep_strategy()
current_project_dict = current_project.dict(exclude_unset=True)
mergedeep.merge(current_project_dict, project, strategy=strategy)
patched_project = mlrun.common.schemas.Project(**current_project_dict)
return self.store_project(
db_session,
name,
patched_project,
projects_role,
leader_session,
wait_for_completion,
)
def delete_project(
self,
db_session: sqlalchemy.orm.Session,
name: str,
deletion_strategy: mlrun.common.schemas.DeletionStrategy = mlrun.common.schemas.DeletionStrategy.default(),
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
auth_info: mlrun.common.schemas.AuthInfo = mlrun.common.schemas.AuthInfo(),
wait_for_completion: bool = True,
) -> bool:
if self._is_request_from_leader(projects_role):
server.api.crud.Projects().delete_project(
db_session, name, deletion_strategy
)
else:
return self._leader_client.delete_project(
auth_info.session,
name,
deletion_strategy,
wait_for_completion,
)
return False
def get_project(
self,
db_session: sqlalchemy.orm.Session,
name: str,
leader_session: typing.Optional[str] = None,
) -> mlrun.common.schemas.Project:
return server.api.crud.Projects().get_project(db_session, name)
def get_project_owner(
self,
db_session: sqlalchemy.orm.Session,
name: str,
) -> mlrun.common.schemas.ProjectOwner:
return self._leader_client.get_project_owner(self._sync_session, name)
def list_projects(
self,
db_session: sqlalchemy.orm.Session,
owner: str = None,
format_: mlrun.common.schemas.ProjectsFormat = mlrun.common.schemas.ProjectsFormat.full,
labels: typing.List[str] = None,
state: mlrun.common.schemas.ProjectState = None,
# needed only for external usage when requesting leader format
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
leader_session: typing.Optional[str] = None,
names: typing.Optional[typing.List[str]] = None,
) -> mlrun.common.schemas.ProjectsOutput:
if (
format_ == mlrun.common.schemas.ProjectsFormat.leader
and not self._is_request_from_leader(projects_role)
):
raise mlrun.errors.MLRunAccessDeniedError(
"Leader format is allowed only to the leader"
)
projects_output = server.api.crud.Projects().list_projects(
db_session, owner, format_, labels, state, names
)
if format_ == mlrun.common.schemas.ProjectsFormat.leader:
leader_projects = [
self._leader_client.format_as_leader_project(project)
for project in projects_output.projects
]
projects_output.projects = leader_projects
return projects_output
async def list_project_summaries(
self,
db_session: sqlalchemy.orm.Session,
owner: str = None,
labels: typing.List[str] = None,
state: mlrun.common.schemas.ProjectState = None,
projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole] = None,
leader_session: typing.Optional[str] = None,
names: typing.Optional[typing.List[str]] = None,
) -> mlrun.common.schemas.ProjectSummariesOutput:
return await server.api.crud.Projects().list_project_summaries(
db_session, owner, labels, state, names
)
async def get_project_summary(
self,
db_session: sqlalchemy.orm.Session,
name: str,
leader_session: typing.Optional[str] = None,
) -> mlrun.common.schemas.ProjectSummary:
return await server.api.crud.Projects().get_project_summary(db_session, name)
def _start_periodic_sync(self):
# the > 0 condition is to allow ourselves to disable the sync from configuration
if self._periodic_sync_interval_seconds > 0:
logger.info(
"Starting periodic projects sync",
interval=self._periodic_sync_interval_seconds,
)
server.api.utils.periodic.run_function_periodically(
self._periodic_sync_interval_seconds,
self._sync_projects.__name__,
False,
self._sync_projects,
)
def _stop_periodic_sync(self):
server.api.utils.periodic.cancel_periodic_function(self._sync_projects.__name__)
def _sync_projects(self, full_sync=False):
"""
:param full_sync: when set to true, in addition to syncing project creation/updates from the leader, we will
also sync deletions that may occur without updating us the follower
"""
db_session = server.api.db.session.create_session()
try:
leader_projects, latest_updated_at = self._list_projects_from_leader()
db_projects = server.api.crud.Projects().list_projects(db_session)
self._store_projects_from_leader(db_session, db_projects, leader_projects)
if full_sync:
self._archive_projects_missing_from_leader(
db_session, db_projects, leader_projects
)
self._update_latest_synced_datetime(latest_updated_at)
finally:
server.api.db.session.close_session(db_session)
def _list_projects_from_leader(self):
try:
leader_projects, latest_updated_at = self._leader_client.list_projects(
self._sync_session, self._synced_until_datetime
)
except Exception:
# if we failed to get projects from the leader, we'll try get all the
# projects without the updated_at filter
leader_projects, latest_updated_at = self._leader_client.list_projects(
self._sync_session
)
return leader_projects, latest_updated_at
def _store_projects_from_leader(self, db_session, db_projects, leader_projects):
db_projects_names = [project.metadata.name for project in db_projects.projects]
# Don't add projects in non-terminal state if they didn't exist before to prevent race conditions
filtered_projects = []
for leader_project in leader_projects:
if (
leader_project.status.state
not in mlrun.common.schemas.ProjectState.terminal_states()
and leader_project.metadata.name not in db_projects_names
):
continue
filtered_projects.append(leader_project)
for project in filtered_projects:
# if a project was previously archived, it's state will be overriden by the leader
# and returned to normal here.
server.api.crud.Projects().store_project(
db_session, project.metadata.name, project
)
def _archive_projects_missing_from_leader(
self, db_session, db_projects, leader_projects
):
logger.info("Performing full sync")
leader_project_names = [project.metadata.name for project in leader_projects]
projects_to_archive = {
project.metadata.name: project for project in db_projects.projects
}
for project_name in leader_project_names:
if project_name in projects_to_archive:
del projects_to_archive[project_name]
for project_to_archive in projects_to_archive:
logger.info(
"Found project in the DB that is not in leader. Archiving...",
name=project_to_archive,
)
try:
projects_to_archive[
project_to_archive
].status.state = mlrun.common.schemas.ProjectState.archived
server.api.crud.Projects().patch_project(
db_session,
project_to_archive,
projects_to_archive[project_to_archive].dict(),
)
except Exception as exc:
logger.warning(
"Failed to archive project from DB, continuing...",
name=project_to_archive,
exc=err_to_str(exc),
)
def _update_latest_synced_datetime(self, latest_updated_at):
if latest_updated_at:
# sanity and defensive programming - if the leader returned a latest_updated_at that is older
# than the epoch, we'll set it to the epoch
epoch = pytz.UTC.localize(datetime.datetime.utcfromtimestamp(0))
if latest_updated_at < epoch:
latest_updated_at = epoch
self._synced_until_datetime = latest_updated_at
def _is_request_from_leader(
self, projects_role: typing.Optional[mlrun.common.schemas.ProjectsRole]
) -> bool:
if projects_role and projects_role.value == self._leader_name:
return True
return False
@staticmethod
def _is_project_matching_labels(
labels: typing.List[str], project: mlrun.common.schemas.Project
):
if not project.metadata.labels:
return False
for label in labels:
if "=" in label:
name, value = [v.strip() for v in label.split("=", 1)]
if name not in project.metadata.labels:
return False
return value == project.metadata.labels[name]
else:
return label in project.metadata.labels
| mlrun/mlrun | server/api/utils/projects/follower.py | follower.py | py | 18,072 | python | en | code | 1,129 | github-code | 36 | [
{
"api_name": "server.api.utils.projects.member.Member",
"line_number": 30,
"usage_type": "attribute"
},
{
"api_name": "server.api.utils.projects.member",
"line_number": 30,
"usage_type": "name"
},
{
"api_name": "mlrun.common.schemas.utils",
"line_number": 31,
"usage_type... |
17895276920 | from typing import Dict, Mapping, Sequence, Text, Union
import seqio
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE
NALUE_INPUT_NAME = 'sentence'
NALUE_OUTPUT_NAMES = ('vertical', 'domain', 'intent')
T5Text = Union[tf.Tensor, Text]
def toxic_comments_preprocessor_binary_classification(
dataset: tf.data.Dataset,
label_tokens: Sequence[str] = ('<extra_id_0>', '<extra_id_1>'),
threshold: float = 0.5) -> tf.data.Dataset:
"""Converts a toxicity detection dataset to classification format.
Toxicity detection task maps a sentence to a binary class of '<extra_id_0>'
(non-toxic) and '<extra_id_1>' (toxic). A floating toxicity score (e.g., 0.3)
will be converted to binary using a threshold.
For example, a typical example might look like
{
'text': 'Some text.',
'toxicity': 0.3,
}
This example would be transformed to
{
'inputs': 'Some text.',
'targets': '<extra_id_0>',
}
Args:
dataset: a tf.data.Dataset containing examples to process.
label_tokens: Strings indicating the two classes of the binary labels. They
should correspond to one of the extra tokens in SentencePiece tokenizer.
threshold: the binary threshold for converting a continuous score (e.g.,
0.3) to toxicity label.
Returns:
A mapped toxicity detection dataset in text2text format.
"""
label_tokens = tf.constant(label_tokens)
def _map_fn(ex: Mapping[str, tf.Tensor]) -> Mapping[str, tf.Tensor]:
label_index = tf.cast(ex['toxicity'] > threshold, tf.int32)
label_string = tf.gather(label_tokens, label_index)
return {'inputs': ex['text'], 'targets': label_string}
return dataset.map(_map_fn, num_parallel_calls=AUTOTUNE)
def toxic_comments_preprocessor_rank_classification(
dataset: tf.data.Dataset,
all_labels: Sequence[str] = ('0', '1'),
input_feature: str = 'text',
target_feature: str = 'toxicity',
threshold: float = 0.5) -> tf.data.Dataset:
"""Reformats toxicity dataset to use rank classification preprocessor.
Adapted from privacy.research.hark.t5.preprocessors.binary_classification.
In this method, we convert examples having a `text` and a `toxicity` feature
to a format that is subsequently consumed by a rank classification formatter.
The `rank_classification_formatter` in T5 preprocessors then consumes
the output features and creates two examples with `inputs` as input and each
of `choice1` and `choice2` as targets. Each combination is then scored given
the ground-truth `label`.
Input data format:
{
'text': 'Some text.',
'toxicity': 0.3,
}
This function will return example of the format:
{
'inputs': 'Some text.',
'choice1': '0',
'choice2': '1',
’label‘: 0
}
Args:
dataset: A dataset to process.
all_labels: Strings indicating the two classes of the binary labels.
input_feature: Input feature name.
target_feature: Target feature name.
threshold: the binary threshold for converting a continuous score
(e.g., 0.7) to toxicity label.
Returns:
A dataset preprocessed with the format listed above.
"""
def _map_fn(ex: Mapping[str, tf.Tensor]) -> Mapping[str, tf.Tensor]:
return {
'inputs': ex[input_feature],
'choice1': tf.constant(all_labels[0], dtype=tf.string),
'choice2': tf.constant(all_labels[1], dtype=tf.string),
'label': tf.cast(ex[target_feature] > threshold, dtype=tf.int32)
}
return dataset.map(_map_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def make_intent_to_token_map(intent_names: Sequence[str],
intent_tokens: Sequence[str],
unk_token: str) -> tf.lookup.StaticHashTable:
"""Creates a StaticHashTable that maps intent names to special tokens.
Different from Dict, the StaticHashTable supports value-based key lookup based
on a tf.Tensor string, which is important from working with tf.data-based
input processors.
Args:
intent_names: A sequence of possible intent names.
intent_tokens: A sequence of SentencePiece tokens corresponding to the
intent names.
unk_token: The token for unknown vocabulary values.
Returns:
A StaticHashTable that maps intent_names to special tokens in the format of
'<extra_id_X>' where X is an integer.
"""
mapping_initializer = tf.lookup.KeyValueTensorInitializer(
keys=tf.constant(intent_names), values=tf.constant(intent_tokens))
intent_to_token_mapping = tf.lookup.StaticHashTable(
mapping_initializer, default_value=tf.constant(unk_token))
return intent_to_token_mapping
def tokenize_compositional_intents(
example: Mapping[str, tf.Tensor],
intent_to_token_map: tf.lookup.StaticHashTable,
separator: str = ' ') -> tf.string:
"""Converts an intent tuple into a string of special tokens.
This function extracts intent names from an example with fields listed in
NALUE_OUTPUT_NAMES (e.g., "vertical", "domain", "intent"), convert them into
special tokens and then concatenantes them into a string. For example:
Input data format:
{
'vertical': 'Answers',
'domain': 'Dictionary',
'intent': 'Translate'
}
We will then extract the intent names 'Answers', 'Dictionary', 'Translate'
and convert them into special tokens using intent_to_token_map.
Output data format:
'<token_1> <token_2> <token_3>'. where `<token_X>` are the tokens
corresponding to the names 'Answers', 'Dictionary', 'Translate' as defined
in intent_to_token_map.
Args:
example: An input example with fields ('vertical', 'domain', 'intent').
intent_to_token_map: A StaticHashTable that maps intent name to the
corresponding special token.
separator: The string separater that is used to join special tokens into a
string.
Returns:
A string with format '<token_1> <token_2> <token_3>'.
"""
intent_tokens = []
# Extracts intent_name, and convert them into intent_tokens.
for output_field in NALUE_OUTPUT_NAMES:
intent_name = example[output_field]
intent_token = intent_to_token_map[intent_name]
intent_tokens.append(intent_token)
return tf.strings.reduce_join(intent_tokens, separator=separator)
@seqio.map_over_dataset
def nalue_preprocessors_classification(
example: Mapping[str, tf.Tensor],
intent_to_token_map: tf.lookup.StaticHashTable) -> Dict[str, tf.Tensor]:
"""Preprocess NALUE examples into text2text format.
Input data format:
{
'sentence': 'some sentence'.
'vertical': 'Answers',
'domain': 'Dictionary',
'intent': 'Translate'
}
This function will convert the intent names in ('vertical', 'domain',
'intent') into corresponding singular tokens for
seqio.SentencePieceVocabulary() (e.g., a sentence piece that will be encoded
into a single by seqio.SentencePieceVocabulary().encode()), and then
concatenate them together as the output string.
Output data format:
{
'inputs': 'some sentence'.
'targets': '<token_1> <token_2> <token_3>',
}
In this way, after tokenization, the target sequence that the model should
predict will be a sequence of three tokens (vertical_name_token,
domain_name_token, intent_name_token).
Args:
example: A NALUE example with fields ('sentence', 'vertical', 'domain',
'intent').
intent_to_token_map: A mapping that maps intent names in the ('vertical',
'domain', 'intent') fields to special tokens.
Returns:
A processed example.
"""
inputs = example[NALUE_INPUT_NAME]
targets = tokenize_compositional_intents(example, intent_to_token_map)
return {'inputs': inputs, 'targets': targets}
def process_nli_inputs(example: Mapping[str, T5Text],
data_type: str = 'mnli') -> tf.Tensor:
"""Processes the sentence-pair inputs from MNLI and HANS examples.
This function converts the sentence-pair inputs from NLI examples from MNLI or
HANS datasets into a unified format. Specifically,
Input data format from MNLI:
{
'premise': 'some sentence 1.',
'hypothesis': 'some sentence 2.',
}
Input data format from HANS (notice the extra blank before period):
{
'sentence1': 'some sentence 1 .',
'sentence2': 'some sentence 2 .',
}
Output:
'premise: some sentence 1. hypothesis: some sentence 2.'
Args:
example: An input example with fields ('premise', 'hypothesis') if
`data_type = 'mnli'`) or ('sentence1', 'sentence2') if `data_type='hans'`.
data_type: The source dataset, can only be 'mnli' or 'hans'.
Returns:
A string in the format 'premise: {1ST_SENTECE}. hypothesis: {2ND_SENTECE}.'
Raises:
ValueError: If data_type is not one of ('mnli', 'hans').
"""
supported_data_type = ('mnli', 'hans')
if data_type not in supported_data_type:
raise ValueError(
f'data_type must be one of {supported_data_type}. Got "{data_type}".')
# Extracts sentence from example.
if data_type == 'mnli':
premise = example['premise']
hypothesis = example['hypothesis']
else:
# Remove the space before period.
process_hans_str = lambda s: tf.strings.regex_replace(s, ' .$', '.')
premise = process_hans_str(example['sentence1'])
hypothesis = process_hans_str(example['sentence2'])
# Concatenant sentences following t5.data.preprocessors.glue().
strs_to_join = ['premise:', premise, 'hypothesis:', hypothesis]
return tf.strings.join(strs_to_join, separator=' ')
@seqio.map_over_dataset
def nli_preprocessors_classification(
example: Mapping[str, tf.Tensor],
intent_to_token_map: tf.lookup.StaticHashTable,
data_type: str = 'mnli',
mnli_label_names: Sequence[str] = ('entailment', 'neutral', 'contradiction')
) -> Dict[str, tf.Tensor]:
"""Preprocess NLI examples from MNLI or HANS into classification format.
Input data format (MNLI):
{
'premise': 'some sentence 1.'.
'hypothesis': 'some sentence 2.'.
"label": 1,
}
Input data format (HANS):
{
'sentence1': 'some sentence 1 .'.
'sentence2': 'some sentence 2 .'.
"gold_label": 'entailment',
}
Output data format:
{
'inputs': 'premise: {1ST_SENTENCE} hypothesis: {2ND_SENTENCE}',
'targets': '<token_1>',
}
Args:
example: An NLI example from MNLI or HANS.
intent_to_token_map: A mapping that maps intent names ('entailment',
'non-entailment', 'neutral', 'contradiction') into binary tokens. (i.e.,
'entailment' into class 1, otherwise to class 0).
data_type: The source dataset, can only be 'mnli' or 'hans'.
mnli_label_names: a ordered list of MNLI label names corresponding to class
index.
Returns:
A processed example.
Raises:
ValueError: If data_type is not one of ('mnli', 'hans').
"""
sentence = process_nli_inputs(example, data_type=data_type)
if data_type == 'mnli':
label_name = tf.gather(mnli_label_names, example['label'])
else:
label_name = example['gold_label']
label_token = intent_to_token_map[label_name]
return {'inputs': sentence, 'targets': label_token}
| google/uncertainty-baselines | baselines/t5/data/preprocessors.py | preprocessors.py | py | 11,183 | python | en | code | 1,305 | github-code | 36 | [
{
"api_name": "tensorflow.data",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "typing.Union",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "tensorflow.Tensor",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "typing.Text",... |
17256388628 | execfile('simple_map.py')
def viterbi(states, piarr, trans_p, emit_p, obs):
# Initialize T1, which keep track of everything done so far
# T1 - probability of most likely path so far
T1 = [{}]
T2 = [{}]
# length of sequence
T = len(obs)
# init T1 for each state
for s in range(0, len(states)):
st = states[s]
if obs[0] in emit_p[st].keys():
T1[0][s] = piarr[s]*emit_p[st][obs[0]]
else:
T1[0][s] = 0.0
for t in range(1, T):
T1.append({})
T2.append({})
for s in range(0, len(states)):
st = states[s]
# evaluate the probabilitiy of each possible state transition
# on the basis of the transition probability and the current observation
prob_each_step = [T1[(t-1)][y0]*trans_p[states[y0]][st]*emit_p[st][obs[t]] for y0 in range(0,len(states))]
maxprob = max(prob_each_step)
T1[t][s] = maxprob
T2[t][s] = prob_each_step
opt = []
for j in T1:
for x, y in j.items():
if j[x] == max(j.values()):
opt.append(x)
# The highest probability
h = max(T1[-1].values())
return([opt,T1, T2])
# Prior probability of state space
piarr = [0.0]*len(states)
piarr[0:2] = [0.05]*3
piarr[3] = 0.9
# observations: down, right, down, right, right, etc.
#obs = (2,3,2,3,3,0,0,1,3)
obs = (2,2,3,3,3,0,0,1,3)
vit = viterbi(states, piarr, trans_p, emit_p, obs)
path = vit[0]
path_states = [states[step] for step in path]
pp.pprint(path_states)
import json
with open('site/public/js/path.json', 'w') as outfile:
json.dump(path_states, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
| abarciauskas-bgse/stochastic | project/viterbi.py | viterbi.py | py | 1,593 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "json.dump",
"line_number": 51,
"usage_type": "call"
}
] |
29788651993 | from os.path import join, isdir
from os import listdir, mkdir
from importlib import import_module
NOTCODE_DIR = 'notcode'
if not isdir(NOTCODE_DIR):
mkdir(NOTCODE_DIR)
# read profile:
profiles = [x.rstrip('.py') for x in listdir('profiles') if x.endswith('.py')]
profile = None
if not profiles:
raise Exception('No profile found.')
elif len(profiles) == 1:
profile = profiles[0]
while profile not in profiles:
profile = input('Profile: ')
# import constants:
profmodule = import_module('profiles.' + profile)
ANKI_USER = profmodule.ANKI_USER
DECK_NAME = profmodule.DECK_NAME
NOT_FOUND_PATH = profmodule.NOT_FOUND_PATH
PONS_KEYS = profmodule.PONS_KEYS
getmarkings = profmodule.getmarkings
DONE_PATH = join(NOTCODE_DIR, 'donemarkings_' + profile + '.txt')
| ofek-b/vomBuch-insAnki | constants.py | constants.py | py | 774 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "os.path.isdir",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "os.mkdir",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "os.listdir",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "importlib.import_module",
"line_n... |
20693896588 | #!/usr/bin/python
# -- coding: utf8 --
"""
Django settings for Russian Learner Corpus project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
import os
import json
from django.utils.translation import ugettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Use a separate file for storing usernames and passwords
with open(os.path.join(BASE_DIR, '.secure.settings.json')) as secret:
SECRET = json.loads(secret.read())
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = SECRET["SECRET_KEY"]
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = SECRET["DEBUG"]
TEMPLATE_DEBUG = DEBUG
# Identifies whether the code is running in prod
PROD = '/home/elmira' in BASE_DIR
if PROD:
ALLOWED_HOSTS = ['.web-corpora.net']
else:
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Corpus',
'annotator',
'news'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.admindocs.middleware.XViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'heritage_corpus.urls'
WSGI_APPLICATION = 'heritage_corpus.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'TEST_CHARSET': 'UTF8',
'HOST': '',
'PORT': '3306',
}
}
if PROD:
DATABASES['default']['NAME'] = SECRET['PROD_DATABASES_NAME']
DATABASES['default']['USER'] = SECRET['PROD_DATABASES_USER']
DATABASES['default']['PASSWORD'] = SECRET['PROD_DATABASES_PASSWORD']
else:
DATABASES['default']['NAME'] = SECRET['DEV_DATABASES_NAME']
DATABASES['default']['USER'] = SECRET['DEV_DATABASES_USER']
DATABASES['default']['PASSWORD'] = SECRET['DEV_DATABASES_PASSWORD']
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
LANGUAGES = (
('ru', _('Russian')),
('en', _('English')),
)
TIME_ZONE = 'UTC'
# todo set timezone
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
if PROD:
STATIC_URL = '/RLC/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
else:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static/'),
)
MEDIA_ROOT = os.path.dirname(BASE_DIR) + '/public/media/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages'
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
# Corpus related settings
if PROD:
PATH_TO_MYSTEM = os.path.join(BASE_DIR, 'mystem')
else:
PATH_TO_MYSTEM = SECRET["DEV_PATH_TO_MYSTEM"]
TEMPORARY_FILE_LOCATION = os.path.join(BASE_DIR, 'tempfiles') | elmiram/russian_learner_corpus | heritage_corpus/settings.py | settings.py | py | 4,402 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "os.path.dirname",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "os.path.join",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number"... |
2114104151 | import aiohttp
import uvicorn
from fastapi import FastAPI
from fastapi import Request
from starlette.responses import Response
app = FastAPI(title="Yhop Proxy",
version="0.0.1",
openapi_url="/openapi.json", )
@app.route("/", methods=['HEAD', 'OPTION', 'GET', 'POST'])
async def proxy(request: Request):
url = request.url
method = request.method
headers = request.headers
data = await request.body()
# 发送转发请求到目标服务器
async with aiohttp.ClientSession(timeout=5) as session:
async with session.request(method=method, url=str(url), headers=headers, data=data) as response:
# 构造响应对象,并将目标服务器的响应返回给客户端
resp = Response(status_code=response.status,
content=response.content,
headers=response.headers)
return resp
def start_server(ip: str = '0.0.0.0', port: int = 1080, timeout: int = 60):
uvicorn.run(app, host=ip, port=port)
| sdliang1013/caul-proxy | src/caul_proxy/server_uvicorn.py | server_uvicorn.py | py | 1,038 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "fastapi.FastAPI",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "fastapi.Request",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "aiohttp.ClientSession",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "starlette.respon... |
17895997999 | import argparse
import time
from modulos.AOJApp import AOJ
from modulos.Acciones import Acciones
from modulos.BarraMenu import irA
from modulos.Cartas import EmitirCarta, BlanquearCarta
from modulos.ConsultaRespuesta import CR
from modulos.Reporte import Reporte
newInstance = AOJ()
app = newInstance.retornarAOJApp()
reporte = Reporte("Smoke de Cartas", "CPMB09.37 Editar Carta")
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--oficio")
parser.add_argument("-a", "--anio")
args = parser.parse_args()
if args.oficio and args.anio:
numOficio = args.oficio
anioOficio = args.anio
else:
numOficio = 25
anioOficio = 20201
# Ingreso a consulta respuesta
newConsultaRespuesta = CR(app, reporte)
irA(app, "Oficios->Consulta respuestas", reporte)
# Selecciona un oficio
newConsultaRespuesta.seleccionarOficio(anioOficio, numOficio)
# Clickea sobre el boton Bloq/DbloqRta
newConsultaRespuesta.presionarBloqDbloq()
time.sleep(1)
# Clickea sobre el boton Actualizar
newConsultaRespuesta.presionarActualizar()
time.sleep(1)
# Validamos el estado bloqueado del oficio
emitirCarta = EmitirCarta(app, reporte)
time.sleep(1)
emitirCarta.obtenerEstadoBloqueado("NO")
time.sleep(1)
# Presionamos en editar carta
emitirCarta.clickearEmitirCarta()
# Editamos la carta
editarCartaBlanqueada = BlanquearCarta(app,reporte)
editarCartaBlanqueada.editarCartaBlanqueada()
# Terminamos el reporte
reporte.terminarReporte()
# Cerramos la ventana de consulta de respuesta
newConsultaRespuesta.presionarSalir()
# Cerramos la app
newInstance.closeAOJApp() | gameztoy/AOJ | scripts/Cartas/CPMB09_37_EditarCarta.py | CPMB09_37_EditarCarta.py | py | 1,569 | python | es | code | 0 | github-code | 36 | [
{
"api_name": "modulos.AOJApp.AOJ",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "modulos.Reporte.Reporte",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "argparse.ArgumentParser",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "mo... |
9955744674 | #!/usr/bin/env python3
from PIL import ImageEnhance
from PIL import Image
def get_average_color(img):
img = Image.open('/home/pi/Desktop/img5.jpg')
img = img.resize((50,50))
#print(img.size)
img = img.crop((15, 15, 35, 35))
converter = ImageEnhance.Color(img)
img = converter.enhance(2.5)
#img.show()
#print(img.size)
w,h = img.size
r_tot = 0
g_tot = 0
b_tot = 0
count = 0
for i in range(0, w):
for j in range(0, h):
r, g, b = img.getpixel((i,j))
r_tot += r
g_tot += g
b_tot += b
count += 1
return (r_tot/count, g_tot/count, b_tot/count)
my_img = Image.open('/home/pi/Desktop/button.jpg')
average_color = get_average_color(my_img)
#print(average_color)
| aparajitaghimire/Clueless-Recreated | Python Scripts/color_detect.py | color_detect.py | py | 787 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "PIL.Image.open",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "PIL.ImageEnhance.Color",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "PIL.ImageEnhance",
... |
43143608911 | from rest_framework import serializers
from apps.categories.serializers import CategorySerializer
from apps.media.models import Image
from apps.media.serializers import ImageSerializer
from apps.products.models import Product, Variant
from apps.reviews.serializers import ReviewSerializer
class ProductSerializer(serializers.ModelSerializer):
product_category = serializers.SerializerMethodField()
product_images = serializers.SerializerMethodField()
class Meta:
model = Product
fields = "__all__"
extra_kwargs = {
"category": {
"required": True,
},
}
expandable_fields = {
'reviews': (ReviewSerializer, {'many': True}),
# 'image': (ImageSerializer, {'many': True}),
}
def get_product_category(self, obj):
data = {
'id': obj.category.id,
'name': obj.category.name
}
return data
def get_product_images(self, obj):
request = self.context.get('request')
product_id = obj.id
images = Image.objects.filter(product_id=product_id)
# serializer = ImageSerializer(product_images, many=True, context={"request": request})
serializer = ImageSerializer(images, many=True)
# images = [{'id': data['id'], 'name': data['name']} for data in serializer.data]
return serializer.data
# images = [{'id': data['id'], 'name': data['name']} for data in serializer.data]
# return images if images else ['https://www.electrosolutions.in/wp-content/uploads/2018/08/product-image-dummy'
# '-600x353.jpg']
# def get_brand(self, obj):
# data = {
# 'id': obj.brand.id,
# 'name': obj.brand.brand
# }
# return data
#
# def get_type(self, obj):
# data = {
# 'id': obj.type.id,
# 'name': obj.type.type
# }
# return data
class VariantSerializer(serializers.ModelSerializer):
class Meta:
model = Variant
fields = '__all__'
| mushfiq1998/bkpe-multivendor-ecommerce | apps/products/serializers.py | serializers.py | py | 2,117 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "rest_framework.serializers.ModelSerializer",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "rest_framework.serializers",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "rest_framework.serializers.SerializerMethodField",
"line_number": 10... |
2954449489 | import argparse
import logging
def main(pretrained_graph_path, dataset_path):
from model import FacialRecognition
from dataloader import load_inception_graph
load_inception_graph(pretrained_graph_path)
model = FacialRecognition(dataset_path, 'test_set.csv')
model.train()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('graph_path', nargs=1)
parser.add_argument('dataset_path', nargs=1)
parser.add_argument('--v', action='store_true')
parser.add_argument('--vv', action='store_true')
args = parser.parse_args()
if args.vv:
print('Super Verbose Mode enabled')
logging.getLogger().setLevel(logging.DEBUG)
elif args.v:
print('Verbose Mode enabled')
logging.getLogger().setLevel(logging.INFO)
main(args.graph_path[0], args.dataset_path[0]) | josepdecid/IU-AdvancedMachineLearning | Labs/Lab3/main.py | main.py | py | 886 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "dataloader.load_inception_graph",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "model.FacialRecognition",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "model.train",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "ar... |
30064471237 | from aljoadmin.models import Comment
from django import forms
class CommentForm(forms.ModelForm):
content = forms.CharField(
widget=forms.Textarea(attrs={'style':'width:100%; height:80px;'}),
label=''
)
class Meta:
model = Comment
fields = ('content',) | 97kim/aljo | aljoadmin/forms.py | forms.py | py | 264 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "django.forms.ModelForm",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "django.forms",
"line_number": 4,
"usage_type": "name"
},
{
"api_name": "django.forms.CharField",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "django.f... |
1544319051 | import json
import pandas as pd
# import file
print("reading actors.tsv")
actors_df = pd.read_csv('actors.tsv', sep='\t')
# drop unused columns
print("processing data")
actors_df = actors_df.drop(columns=['nconst', 'birthYear', 'primaryProfession', 'knownForTitles'])
actors_df['primaryName'] = actors_df['primaryName'].str.lower()
actors_df = actors_df.drop_duplicates()
# serializing json
print("serializing to json")
result = actors_df.to_json(orient="records")
parsed = json.loads(result)
json_object = json.dumps(parsed, indent=4)
# writing to json file
print("writing to json file")
with open("actors.json", "w") as outfile:
outfile.write(json_object)
print("Done converting actors.tsv to actors.json. Upload this to MongoDB")
| stephanieyaur/gg-project | actors_modifier.py | actors_modifier.py | py | 742 | python | en | code | null | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "json.dumps",
"line_number": 18,
"usage_type": "call"
}
] |
37639995341 | from block import Block
from hashlib import sha256
from collections import deque
class Blockchain():
# Set the parameters for the blockchain
def __init__(self, block_size, genesis_block_secret):
self.block_size = block_size
self.genesis_block_hash = sha256(genesis_block_secret.encode('utf-8')).hexdigest()
# Create the blockchain and the first block on it
self.blockchain = deque()
self.blockchain.append(Block(0, self.block_size, self.genesis_block_hash))
# Function to return the starting hash for the blockchain
def get_genesis_block_hash(self):
return self.genesis_block_hash
# Function to create a vote transaction on the blockchain
# We first try to perform the transaction on the current block,
# if it fails being full, we create a new block on the blockchain append
# add the new transaction to the newly created block.
def new_vote(self, vote_for):
# We will try to add the new transaction on the last block on the blockchain
# If the current_block is already full, then we create a new block and add a transaction to it
current_block = self.blockchain[-1]
if len(current_block.block) >= self.block_size:
self.blockchain.append(Block(len(self.blockchain), self.block_size, current_block.get_ending_hash()))
current_block = self.blockchain[-1]
# We are now sure that the current_block does have space for a new transaction
transaction_status = current_block.new_vote(vote_for)
# Function to summarise the blockchain
def summary(self, only_hashes = True):
for block in self.blockchain:
print("\nBlock: " + str(block.block_id))
t = 0
for transaction in block.block:
print(" " + str(t) + ": " + transaction['hash'])
if not only_hashes:
print(" vote_for: " + str(transaction['vote_for']) + " timestamp: " + str(transaction['timestamp']))
t += 1
| ketanv3/blockchain-evm | blockchain.py | blockchain.py | py | 2,050 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "hashlib.sha256",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "collections.deque",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "block.Block",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "block.Block",
"line_n... |
41928732216 | from __future__ import absolute_import
import xadmin
from .models import UserSettings, Log
from xadmin import views
from xadmin.layout import *
from django.utils.translation import ugettext_lazy as _, ugettext
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
xadmin.site.register(views.BaseAdminView, BaseSetting) # 注册到xadmin中
class GlobalSetting(object):
# 设置base_site.html的Title
site_title = '后台管理'
# 设置base_site.html的Footer
site_footer = '我的脚丫'
menu_style = 'accordion'
def get_site_menu(self):
return [
{
'title': '赋分表',
'menus': (
{
'title': '分配赋分表',
'url': '/xadmin/assignTables'
},
)
},
{
'title': "会议管理",
# # 'icon': 'fa fa-bar-chart-o',
'menus': (
{
'title': '会议设置',
'url': '/xadmin/meetingManage'
},
)
},
]
from rewardSystem.adminViews import MeetingManage, ImportStudent, Download_student_xls, AssignTables, \
MeetingSetting, AllotJury, JuryList, ImportStudentGrade, StatisticsQuestion, StatisticsResult
# 注册自定义分配赋分表页面
xadmin.site.register_view('meetingManage', MeetingManage, name='meetingManage')
# 分配赋分表
xadmin.site.register_view("assignTables", AssignTables, name='assignTables')
# 会议设置页面
xadmin.site.register_view('meetingSetting', MeetingSetting, name="meetingSetting")
# 导入学生成绩
xadmin.site.register_view('importStudentGrade', ImportStudentGrade, name="importStudentGrade")
# 评委列表
xadmin.site.register_view('juryList', JuryList, name="juryList")
# 分配评委
xadmin.site.register_view('allotJury', AllotJury, name="allotJury")
xadmin.site.register_view('importStudent', ImportStudent, name="importStudent")
xadmin.site.register_view('downloadStudent', Download_student_xls, name="downloadStudent")
# 会议统计 问题
xadmin.site.register_view('statisticsQuestion', StatisticsQuestion, name="statisticsQuestion")
# 会议统计 结果
xadmin.site.register_view('statisticsResult', StatisticsResult, name="statisticsResult")
# 注册F
xadmin.site.register(xadmin.views.CommAdminView, GlobalSetting)
class UserSettingsAdmin(object):
model_icon = 'fa fa-cog'
hidden_menu = True
xadmin.site.register(UserSettings, UserSettingsAdmin)
class LogAdmin(object):
def link(self, instance):
if instance.content_type and instance.object_id and instance.action_flag != 'delete':
admin_url = self.get_admin_url(
'%s_%s_change' % (instance.content_type.app_label, instance.content_type.model),
instance.object_id)
return "<a href='%s'>%s</a>" % (admin_url, _('Admin Object'))
else:
return ''
link.short_description = ""
link.allow_tags = True
link.is_column = False
list_display = ('action_time', 'user', 'ip_addr', '__str__', 'link')
list_filter = ['user', 'action_time']
search_fields = ['ip_addr', 'message']
model_icon = 'fa fa-cog'
xadmin.site.register(Log, LogAdmin)
| SweetShance/rewardSystem | rewardSystem/extra_apps/xadmin/adminx.py | adminx.py | py | 3,368 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "xadmin.site.register",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "xadmin.site",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "xadmin.views.BaseAdminView",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": ... |
42491423724 | import pytest
from demo_app import create_app
from demo_app import db as _db
from demo_app.blog.models import Author, Category, Entry
@pytest.fixture(scope='session')
def app():
app = create_app('testing')
app_context = app.app_context()
app_context.push()
yield app
app_context.pop()
@pytest.fixture(scope='session')
def app_client(app):
client = app.test_client()
return client
@pytest.fixture(scope='module')
def db():
_db.create_all()
yield _db
_db.drop_all()
@pytest.fixture(scope='function')
def session(db):
session = db.create_scoped_session()
db.session = session
yield session
session.remove()
@pytest.fixture()
def create_authors(session):
mike = Author(name='Mike', description="Hi, I'm Mike Doe", email='mike@example.com')
jane = Author(name='Jane', description="Hi, I'm Jane Doe", email='jane@example.com')
session.add_all([mike, jane])
session.commit()
@pytest.fixture()
def create_categories(session):
python = Category(name='Python')
javascript = Category(name='Javascript')
session.add_all([python, javascript])
session.commit()
@pytest.fixture()
def create_entries(session, create_authors, create_categories):
mike = Author.query.filter_by(name='Mike').first()
javascript = Category.query.filter_by(name='Javascript').first()
python = Category.query.filter_by(name='Python').first()
entry1 = Entry(title='Hello World', body='This is my first entry', \
author=mike)
entry1.en_ca.append(javascript)
entry1.en_ca.append(python)
session.add(entry1)
session.commit()
| AlexPG/flask-demo-app | tests/conftest.py | conftest.py | py | 1,640 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "demo_app.create_app",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "pytest.fixture",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "pytest.fixture",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "demo_app.db.create_a... |
72240231143 | from datetime import datetime
from typing import Any, Dict, List
import jsonlines
from tinydb import TinyDB, where
from higgins import const
class DateTimeSerializer():
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
def decode(self, s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
def load_database(db_path: str = const.TINY_DB_PATH) -> TinyDB:
return TinyDB(db_path)
def truncate(table_name: str, db: TinyDB) -> None:
table = db.table(table_name)
table.truncate()
def insert(table_name: str, records: List[Dict], db: TinyDB) -> None:
table = db.table(table_name)
table.insert_multiple(records)
def query(table_name: str, field_name: str, field_value: Any, db: TinyDB) -> List[Dict]:
table = db.table(table_name)
records = table.search(where(field_name) == field_value)
return records
def export_openai_jsonl(table_name: str, field_name: str, db: TinyDB, export_path: str):
# Export in the openai format needed for search: https://beta.openai.com/docs/guides/search
table = db.table(table_name)
with jsonlines.open(export_path, 'w') as writer:
for record in table:
writer.write({"text": record[field_name], "metadata": ""})
def load_jsonl(jsonl_path: str, table_name: str, db: TinyDB):
table = db.table(table_name)
with jsonlines.open(jsonl_path) as reader:
for record in reader:
table.insert(record)
if __name__ == "__main__":
db = load_database()
print(db)
table = db.table("episodes")
print(table)
chat_text = 'Brendan: Hello. Higgins: How can I help you?'
insert(
table_name="episodes",
records=[
{'context': {'active_window': 'Google Chrome', 'running_applications': []}, 'chat_text': chat_text, 'start_time': '2021-09-03T11:54:54'},
{'context': {'active_window': 'App Store', 'running_applications': []}, 'chat_text': chat_text, 'start_time': '2021-09-03T11:54:54'}
],
db=db
)
print(table.all())
rows = query(table_name="episodes", field_name="chat_text", field_value=chat_text, db=db)
print(rows)
export_path = "data/episode_openai.jsonl"
export_openai_jsonl(
table_name="episodes",
field_name="chat_text",
db=db,
export_path=export_path
)
from higgins.utils import jsonl_utils
records = jsonl_utils.open_jsonl(export_path)
print(records)
truncate("episodes", db)
| bfortuner/higgins | higgins/database/tiny.py | tiny.py | py | 2,550 | python | en | code | 7 | github-code | 36 | [
{
"api_name": "datetime.datetime",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "datetime.datetime.strptime",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "higgin... |
7748613059 | from tensorflow.keras.preprocessing import image as imageprep
import os
import numpy as np
from PIL import Image
import json
import requests
from io import BytesIO
def image_to_np_array(img_path, image_size):
img = imageprep.load_img(img_path, target_size=(image_size, image_size))
img = imageprep.img_to_array(img)
return img
def to_np_array(img, image_size):
img = img.resize((image_size, image_size))
img = imageprep.img_to_array(img)
if (img.shape[2] == 4):
img = img[..., :3]
return img
def file_to_np_array(file, image_size):
img = Image.open(file)
img = img.resize((image_size, image_size))
img = imageprep.img_to_array(img)
if (img.shape[2] == 4):
img = img[..., :3]
return img
def url_to_np_array(url, image_size):
if url.endswith(('.png', '.jpg', '.jpeg')):
response = requests.get(url)
img = file_to_np_array(BytesIO(response.content), image_size)
return img
else:
return None
def mkdir(dir_path):
os.makedirs(dir_path, exist_ok=True)
def image_array_from_dir(dir_path, image_size, valid_file_types):
image_paths = os.listdir(dir_path)
image_paths = [os.path.join(dir_path, file_) for file_ in image_paths if file_.split(
".")[1] in valid_file_types]
image_links = [file_.split("build/")[1] for file_ in image_paths]
image_holder = []
for img_path in image_paths:
img_path = os.path.join(dir_path, img_path)
image_holder.append(image_to_np_array(img_path, image_size))
return np.asarray(image_holder), image_links
def load_json_file(file_path):
with open(file_path, 'r') as f:
data = json.load(f)
return data
def save_json_file(file_path, data):
with open(file_path, 'w') as f:
json.dump(data, f)
| cloudera/CML_AMP_Image_Analysis | lib/utils.py | utils.py | py | 1,813 | python | en | code | 10 | github-code | 36 | [
{
"api_name": "tensorflow.keras.preprocessing.image.load_img",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "tensorflow.keras.preprocessing.image",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "tensorflow.keras.preprocessing.image.img_to_array",
"line_... |
13860968318 | import pygame
import assets
clock = pygame.time.Clock()
win = pygame.display.set_mode((1365, 768))
#=================ROW 1====================
button1 = assets.Button(0, 0, 452, 253, (12, 12, 12), "", (255, 255, 255))
button2 = assets.Button(455, 0, 452, 253, (12, 12, 12), "", (255, 255, 255))
button3 = assets.Button(910, 0, 452, 253, (12, 12, 12), "", (255, 255, 255))
#=================ROW 2======================
button4 = assets.Button(0, 256, 452, 253, (12, 12, 12), "", (255, 255, 255))
button5 = assets.Button(455, 256, 452, 253, (12, 12, 12), "", (255, 255, 255))
button6 = assets.Button(910, 256, 452, 253, (12, 12, 12), "", (255, 255, 255))
#=================ROW 3=======================
button7 = assets.Button(0, 512, 452, 253, (12, 12, 12), "", (255, 255, 255))
button8 = assets.Button(455, 512, 452, 253, (12, 12, 12), "", (255, 255, 255))
button9 = assets.Button(910, 512, 452, 253, (12, 12, 12), "", (255, 255, 255))
buttons = [button1, button2, button3, button4, button5, button6, button7, button8, button9]
click = True
def messagebox(text):
button_font = pygame.font.SysFont("Impact", 22)
text_surface = button_font.render(text, 1, (45, 167, 235))
win.blit(text_surface, (1365 /
2 - text_surface.get_width()/2, 768/2 - text_surface.get_height()/2))
def anyone_won():
'''WIN CHECK FOR TIC TACK TOE'''
if(button1.text == "X" and button2.text == "X" and button3.text == "X" or
button4.text == "X" and button5.text == "X" and button6.text == "X" or
button7.text == "X" and button8.text == "X" and button9.text == "X" or
button3.text == "X" and button6.text == "X" and button9.text == "X" or
button5.text == "X" and button2.text == "X" and button8.text == "X" or
button1.text == "X" and button4.text == "X" and button7.text == "X" or
button1.text == "X" and button5.text == "X" and button9.text == "X" or
button3.text == "X" and button5.text == "X" and button7.text == "X" ):
win.fill((0, 0, 0))
messagebox("X has won a game")
return
if(button1.text == "O" and button2.text == "O" and button3.text == "O" or
button4.text == "O" and button5.text == "O" and button6.text == "O" or
button7.text == "O" and button8.text == "O" and button9.text == "O" or
button3.text == "O" and button6.text == "O" and button9.text == "O" or
button5.text == "O" and button2.text == "O" and button8.text == "O" or
button1.text == "O" and button4.text == "O" and button7.text == "O" or
button1.text == "O" and button5.text == "O" and button9.text == "O" or
button3.text == "O" and button5.text == "O" and button7.text == "O" ):
win.fill((0, 0, 0))
messagebox("O has won a game")
return
i = 0
for x in buttons:
if x == "":
continue
i += 1
if i == 9:
return"Tie"
def whoose_turn():
'''
TURN DECIDER
'''
global click
if click == True:
click = False
elif click == False:
click = True
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
win.fill((45, 167, 235))
left, middle, right = pygame.mouse.get_pressed()
if left:
pos = pygame.mouse.get_pos()
for i in buttons:
x = i.clicked(pos)
if x:
if click and i.text == "":
i.text = "O"
elif i.text == "" and click == False:
i.text = "X"
click = not click
for i in buttons:
i.draw(win)
messagebox(anyone_won())
pygame.display.flip()
| tanmay440/Game-Hub-Mega | Tic Tack Toe/main.pyw | main.pyw | pyw | 3,872 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.time.Clock",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "pygame.time",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "pygame.displa... |
21548587442 | import pytest
from mixer.backend.django import mixer
from apps.edemocracia.models import EdemocraciaGA
from apps.edemocracia.tasks import (get_ga_edemocracia_daily,
get_ga_edemocracia_monthly,
get_ga_edemocracia_yearly,)
from django.db import IntegrityError
class TestGAEdemocracia:
@pytest.mark.django_db
def test_edemocracia_ga_create(self):
mixer.blend(EdemocraciaGA)
assert EdemocraciaGA.objects.count() == 1
@pytest.mark.django_db
def test_edemocracia_ga_integrity_error(self):
content = mixer.blend(EdemocraciaGA)
with pytest.raises(IntegrityError) as excinfo:
mixer.blend(EdemocraciaGA,
period=content.period,
start_date=content.start_date)
assert 'duplicate key value violates unique constraint' in str(
excinfo.value)
@pytest.mark.django_db
def test_monthly_get_ga_data(self):
json_data = {"date": "00000000", "users": 10, "newUsers": 10,
"sessions": 10, "pageViews": 10}
mixer.cycle(5).blend(EdemocraciaGA, period='daily', data=json_data,
start_date=mixer.sequence('2020-10-1{0}'),
end_date=mixer.sequence('2020-10-1{0}'))
get_ga_edemocracia_monthly.apply(args=(['2020-10-01']))
monthly_data = EdemocraciaGA.objects.filter(period='monthly').first()
assert monthly_data.data['users'] == 50
assert monthly_data.data['newUsers'] == 50
assert monthly_data.data['sessions'] == 50
assert monthly_data.data['pageViews'] == 50
@pytest.mark.django_db
def test_yearly_get_ga_data(self):
json_data = {"users": 10, "newUsers": 10,
"sessions": 10, "pageViews": 10}
start_dates = ['2019-01-01', '2019-02-01', '2019-03-01']
end_dates = ['2019-01-31', '2019-02-28', '2019-03-31']
for i in range(3):
mixer.blend(EdemocraciaGA, period='monthly', data=json_data,
start_date=start_dates[i], end_date=end_dates[i])
get_ga_edemocracia_yearly.apply(args=(['2019-01-01']))
monthly_data = EdemocraciaGA.objects.filter(period='yearly').first()
assert monthly_data.data['users'] == 30
assert monthly_data.data['newUsers'] == 30
assert monthly_data.data['sessions'] == 30
assert monthly_data.data['pageViews'] == 30
@pytest.mark.django_db
def test_get_ga_edemocracia_daily(self, mocker):
ga_data = ['20201208', '647', '446', '830', '1692']
mocker.patch(
'apps.edemocracia.tasks.get_analytics_data',
return_value=[ga_data])
get_ga_edemocracia_daily.apply()
data = {
"date": ga_data[0],
"users": ga_data[1],
"newUsers": ga_data[2],
"sessions": ga_data[3],
"pageViews": ga_data[4],
}
adiencias_ga = EdemocraciaGA.objects.first()
assert EdemocraciaGA.objects.count() > 0
assert adiencias_ga.data == data
| labhackercd/cpp-participacao-backend | src/apps/edemocracia/tests/test_analytics_edemocracia.py | test_analytics_edemocracia.py | py | 3,150 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "mixer.backend.django.mixer.blend",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "apps.edemocracia.models.EdemocraciaGA",
"line_number": 14,
"usage_type": "argument"
},
{
"api_name": "mixer.backend.django.mixer",
"line_number": 14,
"usage_type": ... |
35909639327 | import pygame
import pytest
from scoreboard import Scoreboard
from settings import Settings
from game_stats import GameStats
@pytest.fixture
def scoreboard():
""" 创建一个新的 Scoreboard 实例 """
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
stats = GameStats(ai_settings)
return Scoreboard(ai_settings, screen, stats)
def test_prep_score(scoreboard):
""" 测试 prep_score 方法 """
scoreboard.prep_score()
assert isinstance(scoreboard.score_iamge, pygame.Surface)
#assert scoreboard.score_iamge.get_rect().top == 12
def test_prep_high_score(scoreboard):
""" 测试 prep_high_score 方法 """
scoreboard.prep_high_score()
assert isinstance(scoreboard.high_score_iamge, pygame.Surface)
#assert scoreboard.high_score_iamge.get_rect().centerx == scoreboard.screen_rect.centerx
def test_prep_level(scoreboard):
""" 测试 prep_level 方法 """
scoreboard.prep_level()
assert isinstance(scoreboard.level_image, pygame.Surface)
def test_prep_ships(scoreboard):
""" 测试 prep_ships 方法 """
scoreboard.prep_ships()
assert len(scoreboard.ships.sprites()) == scoreboard.stats.ships_left
def test_show_score(scoreboard):
""" 测试 show_score 方法 """
scoreboard.show_score()
assert isinstance(scoreboard.score_iamge, pygame.Surface)
assert isinstance(scoreboard.high_score_iamge, pygame.Surface)
assert isinstance(scoreboard.level_image, pygame.Surface)
assert isinstance(scoreboard.ships, pygame.sprite.Group)
#assert scoreboard.score_iamge.get_rect().top == 12
#assert scoreboard.high_score_iamge.get_rect().centerx == scoreboard.screen_rect.centerx
#assert scoreboard.level_image.get_rect().top == scoreboard.score_rect.bottom + 10
| shixiaoxiya/py_course_zly_ | Projects/project_code/third2_left _test/test_scoreboard.py | test_scoreboard.py | py | 1,852 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.init",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "settings.Settings",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "pygame.display"... |
310628557 | import logging
import collections
import html
import gw2buildutil
from . import util as gw2util
logger = logging.getLogger(__name__)
PAGE_ID = 'build'
PAGE_ID_PREFIX = 'builds/'
PAGE_TITLE_PREFIX = 'Guild Wars 2 build: '
def build (gw2site):
textbody_renderer = gw2buildutil.textbody.Renderer(
gw2buildutil.textbody.RenderFormat.RST_HTML, {'heading level': 3})
with gw2buildutil.api.storage.FileStorage() as api_storage:
for build in gw2site.builds.values():
logger.info(f'render {build.metadata}')
dest_page_id = PAGE_ID_PREFIX + gw2util.get_build_id(build)
page_title = PAGE_TITLE_PREFIX + str(build.metadata)
texts = {}
if build.intro.description is not None:
texts['desc'] = textbody_renderer.render(
build.intro.description, build.metadata, api_storage)
if build.notes is not None:
texts['notes'] = textbody_renderer.render(
build.notes, build.metadata, api_storage)
if build.usage is not None:
texts['usage'] = textbody_renderer.render(
build.usage, build.metadata, api_storage)
gw2site.render_page_template(PAGE_ID, page_title, {
'build': build,
'texts': texts,
}, dest_page_id=dest_page_id)
| ikn/ikn.org.uk | lib/iknsite/gw2/build.py | build.py | py | 1,379 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "gw2buildutil.textbody.Renderer",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "gw2buildutil.textbody",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_na... |
34398257612 | import qrcode
data = "Winson is the goat no cappa"
img = qrcode.make(data)
qr = qrcode.QRCode(version = 1, box_size = 10, border = 5)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color = 'red', back_color = 'white')
img.save('C:/Users/wilko/Desktop/python12projects/qrcode/qrcode.png') | Riamuwilko/python_beginner_projects | qrcode/main.py | main.py | py | 303 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "qrcode.make",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "qrcode.QRCode",
"line_number": 6,
"usage_type": "call"
}
] |
937990517 | import logging
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import gettext as _
from custody.models import MultiSigAddress
from coldstoragetransfers.helpers.btc import BTCHelper
class MultiSigAddressForm(forms.ModelForm):
class Meta:
model = MultiSigAddress
exclude = ['address', 'redeem_script']
def clean(self):
#{'currency': <Currency: ETH>, 'user_addresses': <QuerySet [<UserAddress: BTC_tipu>, <UserAddress: ETH_tipu>]>, 'minimum_signatures': 2}
this_currency = self.cleaned_data['currency'].symbol
errors = {}
for a in self.cleaned_data['user_addresses']:
if a.currency.symbol != this_currency:
errors['user_addresses'] = _("Child addresses' currency must match selected currency.")
if self.cleaned_data['minimum_signatures'] > len(self.cleaned_data['user_addresses']):
errors['minimum_signatures'] = _("This amount can't be less than the number of child addresses.")
if errors:
raise ValidationError(errors)
super().clean()
"""
doesn't work on save_model in the MultisigAddressAdmin due to:
<MultiSigAddress: BTC_None>" needs to have a value for field "id" before this many-to-many relationship can be used.
because new models don't exist in the db, relationship can't be accessed. must happen here.
"""
raw_public_keys = [ua.address for ua in self.cleaned_data['user_addresses']]
# predictable ordering is required for multisig creation
raw_public_keys.sort()
#should only happen once !
if not self.instance.pk:
create_payload = BTCHelper().add_multisig_address(self.cleaned_data['minimum_signatures'], raw_public_keys)
self.instance.address = create_payload['address']
self.instance.redeem_script = create_payload['redeemScript']
| chriscslaughter/nodestack | custody/forms.py | forms.py | py | 1,960 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.forms.ModelForm",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "django.forms",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "custody.models.MultiSigAddress",
"line_number": 12,
"usage_type": "name"
},
{
"api_name"... |
35493639057 | from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from main.models import *
from main.forms import *
from cart.forms import CartAddProductForm
def base_context(request):
context = dict()
context['user'] = request.user
context["site_name"] = "Sushiman" # Строка перед | в title страницы
context["page_name"] = "Главная" # Строка после |
context["page_header"] = "" # Название страницы в display-3 стиле
return context
# Начальная страница
def index(request):
c = base_context(request)
c["page_header"] = "Меню"
c["categories"] = Category.objects.all()
return render(request, 'pages/index.html', c)
# Вьюха для просмотра товаров по категориям меню с фильтрацией
def view_category(request, category_slug):
c = base_context(request)
category = get_object_or_404(Category, slug=category_slug)
c["page_name"] = category.name
c["page_header"] = category.name
c['products'] = Product.objects.filter(category=category)
c['form'] = CartAddProductForm()
return render(request, 'pages/category.html', c)
def adresses(request):
c = base_context(request)
c["page_header"] = "Адреса"
c["page_name"] = "Адреса"
return render(request, 'pages/adresses.html', c)
| SwAsKk/Online_Shop_Django | main/views.py | views.py | py | 1,497 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.shortcuts.render",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "django.shortcuts.get_object_or_404",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "cart.forms.CartAddProductForm",
"line_number": 35,
"usage_type": "call"
},
... |
31826733278 | import argparse
import pprint
import sys
from designspaceProblems import DesignSpaceChecker
def main(args=None):
parser = argparse.ArgumentParser(
description='Check designspace data.')
parser.add_argument(
'input_ds',
metavar='PATH',
help='path to designspace file',
type=argparse.FileType())
options = parser.parse_args(args)
dc = DesignSpaceChecker(options.input_ds.name)
dc.checkEverything()
pprint.pprint(dc.problems)
if __name__ == '__main__':
sys.exit(main())
| LettError/DesignspaceProblems | Lib/designspaceProblems/__main__.py | __main__.py | py | 542 | python | en | code | 18 | github-code | 36 | [
{
"api_name": "argparse.ArgumentParser",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "argparse.FileType",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "designspaceProblems.DesignSpaceChecker",
"line_number": 18,
"usage_type": "call"
},
{
"a... |
37936099877 | import apache_beam as beam
with beam.Pipeline() as pipeline:
batches_with_keys = (
pipeline
| 'Create produce' >> beam.Create([
('spring', '🍓'),
('spring', '🥕'),
('spring', '🍆'),
('spring', '🍅'),
('summer', '🥕'),
('summer', '🍅'),
('summer', '🌽'),
('fall', '🥕'),
('fall', '🍅'),
('winter', '🍆'),
])
| 'Group into batches' >> beam.GroupIntoBatches(3)
| beam.Map(print)) | ezeparziale/apache-beam-start | examples/groupby_batches.py | groupby_batches.py | py | 529 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "apache_beam.Pipeline",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "apache_beam.Create",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "apache_beam.GroupIntoBatches",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "ap... |
19450895845 | # -*- coding: utf-8 -*-
import os
import sys
import datetime
import struct
import wave
def argumentsparser():
usage = "Usage: python {} inputfile.kamata_programs".format(__file__)
arguments = sys.argv
if len(arguments) == 1 or len(arguments) > 2:
return usage
arguments.pop(0)
if not arguments[0].endswith('.kamata_programs') or arguments[0].startswith('-'):
return usage
if __name__ == '__main__' :
if argumentsparser() is None :
filesize = os.path.getsize(sys.argv[0])
readpoint = 96
filenumber = 1
now = datetime.datetime.now()
dirname = "{0:%y%m%d%H%M%S}".format(now)
fin = open(sys.argv[0], mode="rb")
if readpoint < filesize :
os.makedirs(dirname, exist_ok=True)
print("inputfile size =", filesize)
while readpoint < filesize :
fin.seek(readpoint)
filename = "{0:03d}".format(filenumber)
data = struct.unpack("B", fin.read(1))
i = 0
while not data[0] == 0 and i < 12 :
filename += chr(data[0])
data = struct.unpack("B", fin.read(1))
i += 1
filename += ".wav"
readpoint += 616
fout = wave.Wave_write(dirname + "/" + filename)
fout.setparams((
1, # mono
1, # 8 bits = 1 byte
48000, # sampling bitrate
32, # samples
"NONE", # not compressed
"not compressed" # not compressed
))
for i in range(32):
fin.seek(readpoint)
valuekey = fin.read(4)
bitvalue = round(struct.unpack('<f', valuekey)[0] * 255)
fout.writeframesraw(struct.pack("B", bitvalue))
print("readpoint =", readpoint, " , ", bitvalue)
readpoint += 12
print("-----------------")
fout.close()
filenumber += 1
readpoint += 4
fin.close()
print(filenumber - 1, "wave files are created in the", dirname, "folder successfully.")
print("The format is monoral, 8-bit, 48kHz and 32 samples. Files are expected to be readable for an ELZ_1 synthesizer.")
else:
print(argumentsparser())
| amariichi/kamata2wav | kamata2wav.py | kamata2wav.py | py | 2,462 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.argv",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "os.path.getsize",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 19,
"usage_type": "attribute"
},
{
"api_name": "sys.argv",
"line_numbe... |
10353313162 | import streamlit as st
import pickle
model_random = pickle.load(open("model/forest.pkl", "rb"))
from utils import head, body
hasil = head()
if st.button("Submit"):
name, MDVP_FO,MDVP_FHI, MDVP_FloHz,MDVP_JitterPercent,MDVP_JitterAbs, MDVP_RAP, MDVP_PPQ,Jitter_DDP,MDVP_Shimmer,MDVP_ShimmerDb,Shimmer_APQ3, Shimmer_APQ5, MDVP_APQ,Shimmer_DDA,NHR, HNR, RPDE, DFA, spread1,spread2, D2, PPE = hasil
input_model = [[MDVP_FO,MDVP_FHI, MDVP_FloHz,MDVP_JitterPercent,MDVP_JitterAbs, MDVP_RAP, MDVP_PPQ,Jitter_DDP,MDVP_Shimmer,MDVP_ShimmerDb,Shimmer_APQ3, Shimmer_APQ5, MDVP_APQ,Shimmer_DDA,NHR, HNR, RPDE, DFA, spread1,spread2, D2, PPE]]
hasil_prediksi = model_random.predict(input_model)[0]
status = {0:"Healthy", 1:"Parkinsson"}
body("Result : "+ " " + name + " current status is " + status[hasil_prediksi])
| FathanKhansaArby/FinalProject083 | app/main.py | main.py | py | 833 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pickle.load",
"line_number": 3,
"usage_type": "call"
},
{
"api_name": "utils.head",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "streamlit.button",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "utils.body",
"line_number": ... |
30898137207 | """
Graph implementation
class GraphMatrix - adjacency matrix
"""
from collections import deque
class GraphMatrix:
"""
Graph implementation using an adjacency matrix
[
[ ]
[ ]
[ ]
]
"""
def __init__(self, size: int):
""" Inits Graph class with optional graph_matrix """
self.graph_matrix = []
for _ in range(size):
self.graph_matrix.append([0 for _ in range(size)])
self.size = size
def add_edge(self, edge: list):
""" add an edge between two vertices """
if not self.has_edge(edge):
v1, v2 = edge
self.graph_matrix[v1][v2] = 1
self.graph_matrix[v2][v1] = 1
return True
return False
def delete_edge(self, edge: list):
""" removes the edge between two given vertices - if it exists """
if self.has_edge(edge):
v1, v2 = edge
self.graph_matrix[v1][v2] = 0
self.graph_matrix[v2][v1] = 0
return True
return False
def has_edge(self, vertices: list):
""" checks if there's an edge between two given vertices """
if len(vertices) == 2:
v1, v2 = vertices
if self.graph_matrix[v1][v2] and self.graph_matrix[v2][v1]:
return True
return False
def bfs_traversal(self, node):
""" traverses graph level-order - O(v^2) """
self._bfs(node)
def _bfs(self, node):
""" helper method to BFS graph """
visited = [node]
queue = deque()
queue.append(node)
while queue:
node = queue.popleft()
print(node)
for i in range(len(self.graph_matrix)):
temp = self.graph_matrix[node][i]
if temp != 0 and i not in visited:
queue.append(i)
visited.append(i)
def dfs_traversal(self, node):
""" traverses graph in a dfs style - O(v^2) """
visited = set()
self._dfs(visited, node)
def _dfs(self, visited, node):
""" helper method to recursively DFS graph """
if node not in visited:
print(node)
visited.add(node)
for i in range(len(self.graph_matrix[node])):
if self.graph_matrix[node][i] != 0:
self._dfs(visited,i)
if __name__ == '__main__':
# 0 -- 1
# |
# |
# 2 -- 3 -- 4
# | /
# | /
# 5
g = GraphMatrix(6)
# add
print('Adding edges...')
g.add_edge([0,1])
g.add_edge([0,2])
g.add_edge([2,3])
g.add_edge([2,5])
g.add_edge([3,4])
g.add_edge([3,5])
# show
print('***Has edge?***')
print( g.has_edge([5,3]) )
#delete edge
print('***Delete edge: 5,3:***')
print( g.delete_edge([5,3]) )
# # show
print('***Has edge?***')
print( g.has_edge([5,3]) )
# # traversal
print('*** DFS ***')
g.dfs_traversal(0)
print('*** BFS ***')
g.bfs_traversal(0)
| g-areth/algos | src/algorithms/datastructures/graphs/graph_adj_matrix.py | graph_adj_matrix.py | py | 3,053 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.deque",
"line_number": 57,
"usage_type": "call"
}
] |
5913567690 | import torch
from torch import optim, nn
import os
from tqdm.auto import tqdm
from model import *
from data import *
from torch.cuda.amp import autocast, GradScaler
from validate_and_test import *
def load_checkpointed_model_params(model, optimizer, resume_checkpoint):
checkpoint = torch.load(resume_checkpoint)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
start_epoch = checkpoint['epoch']
# Things we are keeping track of
epoch_numbers = checkpoint['epoch_numbers']
training_losses = checkpoint['training_losses']
validation_losses = checkpoint['validation_losses']
training_accuracy = checkpoint['training_accuracy']
validation_accuracy = checkpoint['validation_accuracy']
print(f"Model checkpoint {resume_checkpoint} loaded! Will resume the epochs from number #{start_epoch}")
return model, optimizer, start_epoch, epoch_numbers, training_losses, training_accuracy, validation_losses, validation_accuracy
def save_model_checkpoint(experiment, model, optimizer, params, epoch, epoch_numbers, training_losses,
validation_losses, training_accuracy, validation_accuracy):
# set the model to train mode so that in case there was a validation before it doesnt impact the saved weights (as we have dropouts!)
model.train()
# create the directory if it doesn't exist
model_save_directory = os.path.join(params["save_dir"], experiment)
os.makedirs(model_save_directory, exist_ok=True)
# Checkpoint the model at the end of each epoch
checkpoint_path = os.path.join(params["save_dir"], experiment, f'model_epoch_{epoch + 1}.pt')
torch.save({
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'epoch': epoch + 1,
'epoch_numbers': epoch_numbers,
'training_losses': training_losses,
'validation_losses': validation_losses,
'training_accuracy': training_accuracy,
'validation_accuracy': validation_accuracy,
}, checkpoint_path)
print(f"Save checkpointed the model at the path {checkpoint_path}")
def train_model(model, train_loader, val_loader, num_epochs, params, experiment, epoch_saver_count=5,
resume_checkpoint=None):
# Device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.cuda.empty_cache()
# Things we are keeping track of
start_epoch = 0
epoch_numbers = []
training_losses = []
validation_losses = []
training_accuracy = []
validation_accuracy = []
# Adam optimizer
optimizer = optim.Adam(model.parameters(), lr=params['learning_rate'], weight_decay=params['weight_decay'])
# loss
criterion = nn.CrossEntropyLoss()
# load checkpoint
if resume_checkpoint:
model, optimizer, start_epoch, epoch_numbers, training_losses, training_accuracy, validation_losses, validation_accuracy = load_checkpointed_model_params(
model,
optimizer,
resume_checkpoint
)
# Set up one-cycle learning rate scheduler
sched = torch.optim.lr_scheduler.OneCycleLR(
optimizer, params['learning_rate'],
epochs=num_epochs,
steps_per_epoch=len(train_loader)
)
# Custom progress bar for total epochs with color and displaying average epoch loss
total_progress_bar = tqdm(total=num_epochs, desc=f"Total Epochs", position=0,
bar_format="{desc}: {percentage}% |{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
dynamic_ncols=True, ncols=100, colour='red')
# training loop
for epoch in range(start_epoch, start_epoch + num_epochs):
#set to train mode
model.train()
epoch_training_loss = 0.0
train_correct_predictions = 0
total_samples = 0
# Custom progress bar for each epoch with color
epoch_progress_bar = tqdm(total=len(train_loader), desc=f"Epoch {epoch + 1}/{start_epoch + num_epochs}",
position=1, leave=False, dynamic_ncols=True, ncols=100, colour='green')
for batch_idx, data in enumerate(train_loader):
# get the data and outputs
images, labels = data
images = images.to(device)
labels = labels.to(device)
output_logits = model(images)
loss = criterion(output_logits, labels)
loss.backward()
# Gradient clipping
nn.utils.clip_grad_value_(model.parameters(), params['grad_clip'])
optimizer.step()
optimizer.zero_grad()
# print(f"Curr LR -> {optimizer.param_groups[0]['lr']}")
# scheduler update
sched.step()
epoch_training_loss += loss.item()
# batch stats
# Compute training accuracy for this batch
output_probs = nn.Softmax(dim=1)(output_logits)
predicted = torch.argmax(output_probs, 1)
batch_correct_predictions = (predicted == labels).sum().item()
batch_size = labels.size(0)
train_correct_predictions += batch_correct_predictions
total_samples += batch_size # batch size basically
# Update the epoch progress bar (overwrite in place)
epoch_progress_bar.set_postfix({
"loss": loss.item(),
"batch_acc": batch_correct_predictions / batch_size
})
epoch_progress_bar.update(1)
# Close the epoch progress bar
epoch_progress_bar.close()
# Calculate average loss for the epoch
avg_training_loss_for_epoch = epoch_training_loss / len(train_loader)
# Calculate training accuracy for the epoch
avg_training_accuracy = train_correct_predictions / total_samples
# Validation loop
avg_val_accuracy, avg_val_loss_for_epoch = perform_validation(criterion, device, model, val_loader)
# Store values
training_accuracy.append(avg_training_accuracy)
training_losses.append(avg_training_loss_for_epoch)
validation_accuracy.append(avg_val_accuracy)
validation_losses.append(avg_val_loss_for_epoch)
epoch_numbers.append(epoch + 1)
# Update the total progress bar
total_progress_bar.set_postfix(
{
"loss": avg_training_loss_for_epoch,
"train_acc": avg_training_accuracy,
"val_loss": avg_val_loss_for_epoch,
"val_acc": avg_val_accuracy,
}
)
# Close the tqdm bat
total_progress_bar.update(1)
# Print state
print(
f'Epoch {epoch + 1}: train_loss: {avg_training_loss_for_epoch} | train_accuracy: {avg_training_accuracy} | val_loss: {avg_val_loss_for_epoch} | val_accuracy: {avg_val_accuracy} '
)
# Save model checkpoint periodically
need_to_save_model_checkpoint = (epoch + 1) % epoch_saver_count == 0
if need_to_save_model_checkpoint:
print(f"Going to save model @ Epoch:{epoch + 1}")
save_model_checkpoint(
experiment,
model,
optimizer,
params,
epoch,
epoch_numbers,
training_losses,
validation_losses,
training_accuracy,
validation_accuracy
)
# Close the total progress bar
total_progress_bar.close()
# Return things needed for plotting
return epoch_numbers, training_losses, training_accuracy, validation_losses, validation_accuracy
# %%
# if __name__ == '__main__':
# params = {
# 'batch_size': 32,
# 'learning_rate': 0.0045,
# 'save_dir': 'model_ckpts'
# }
# train_data_loader = create_train_data_loader(32)
# test_data_loader, validation_data_loader = create_test_and_validation_data_loader(32)
#
# full_experiment = "Full Data"
# # Check if GPU is available, otherwise use CPU
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# full_cifar_model = CIFARClassifier()
# full_cifar_model.to(device)
#
# train_model(
# full_cifar_model,
# train_data_loader,
# validation_data_loader,
# 2,
# params,
# full_experiment,
# epoch_saver_count=1,
# resume_checkpoint=None
# )
| ParasharaRamesh/NUS-CS5242-Neural-Networks-and-Deep-Learning | Assignment 2 (Autoencoders & CNNs)/Question-5_CIFAR10/train.py | train.py | py | 8,557 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "torch.load",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "model.load_state_dict",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "model.train",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "os.path.join",
"line... |
29498462869 | from main import validate_amount_payment, define_amount_hour, get_amount_hour, read_data_file
from constant.days_info import list_days
import pytest
def test_validate_valid_line():
assert validate_amount_payment(
"THOMAS=MO08:00-12:00,TU10:00-13:00,TH01:00-04:00,SA14:00-18:00,SU20:00-23:00",
define_amount_hour(list_days), 1) == "The amount to pay : THOMAS is 345"
def test_validate_invalide_line():
assert validate_amount_payment(
"INVALID LINE",
define_amount_hour(list_days), 1) == "The line number 1 is not valid for process"
@pytest.mark.parametrize(
"info_payment, hour_amount, line, expected",
[
(
"THOMAS=MO08:00-12:00,TU10:00-13:00,TH01:00-04:00,SA14:00-18:00,SU20:00-23:00",
define_amount_hour(list_days),
1,
"The amount to pay : THOMAS is 345"
),
(
"INVALID LINE",
define_amount_hour(list_days),
1,
"The line number 1 is not valid for process"
),
(
"JHON=MO10:00-12:00,TH12:00-14:00,FR07:00-11:00,SU20:00-21:00",
define_amount_hour(list_days),
1,
"The amount to pay : JHON is 165"
),
(
"RENE=MO10:00-12:00,TU10:00-12:00,TH01:00-03:00,SA14:00-18:00,SU20:00-21:00",
define_amount_hour(list_days),
1,
"The amount to pay : RENE is 215"
),
(
"ASTRID=MO10:00-12:00,TH12:00-14:00,SU20:00-21:00",
define_amount_hour(list_days),
1,
"The amount to pay : ASTRID is 85"
)
]
)
def test_validate_valid_multiple_line(info_payment, hour_amount, line, expected):
assert validate_amount_payment(info_payment, hour_amount, line) == expected
def test_get_amount_hour_fail_attribute_error():
assert get_amount_hour(None, None, None) == "Invalid values for defined amounts"
def test_open_file_success():
result, _ = read_data_file('files/data.txt')
assert result is True
def test_open_file_file_not_exists():
result, _ = read_data_file('../files/data.txt')
assert result is False | jefvasquezg/acme | test/test_main.py | test_main.py | py | 2,193 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "main.validate_amount_payment",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "main.define_amount_hour",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "constant.days_info.list_days",
"line_number": 9,
"usage_type": "argument"
},
{
... |
932629353 | import datetime
from neutron.common import rpc as proxy
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class HeloAgentNotifyAPI(proxy.RpcProxy):
"""API for plugin to ping agent."""
BASE_RPC_API_VERSION = '1.0'
def __init__(self, topic=None, version=None):
if version:
super(HeloAgentNotifyAPI, self).__init__(
topic=topic, default_version=version)
else:
super(HeloAgentNotifyAPI, self).__init__(
topic=topic, default_version=self.BASE_RPC_API_VERSION)
def helo_agent_host(self, context, host, topic):
"""Notify the agent on host."""
data = 0
try:
data = self.call(
context, self.make_msg('helo',
time=datetime.datetime.utcnow()),
timeout = 3,
topic='%s.%s' % (topic, host))
except Exception:
LOG.exception(_("Failed to helo %(topic)s on %(host)s"),
{"topic": topic, "host": host})
return data
class HeloRpcCallbackMixin(object):
def helo(self, context, time):
LOG.debug(time)
return 1
| CingHu/neutron-ustack | neutron/api/rpc/agentnotifiers/helo_rpc_agent_api.py | helo_rpc_agent_api.py | py | 1,219 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "neutron.openstack.common.log.getLogger",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "neutron.openstack.common.log",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "neutron.common.rpc.RpcProxy",
"line_number": 10,
"usage_type": "attribu... |
451073459 | #!/usr/bin/python3
from .config_utils import get_base_config
from .log_utils import get_module_logger
import DNS
import os
import sys
import time
import validators
CDIR = os.path.dirname(os.path.realpath(__file__))
ROOTDIR = os.path.abspath(os.path.join(CDIR, os.pardir))
BASECONFIG = get_base_config(ROOTDIR)
LOGGING = get_module_logger(__name__)
DNS.defaults['server'] = ['8.8.8.8', '8.8.4.4']
DNS.defaults['timeout'] = 5
def forward_dns_lookup(host_name):
"""Perform a DNS lookup of a FQDN.
Params:
- host_name: (type: string) FQDN to perform lookup of.
Returns:
- result: (type: string) resulting IP address.
"""
try:
ip_list = DNS.dnslookup(host_name, 'A')
if len(ip_list) > 0:
for ip_addr in ip_list:
if validators.ipv4(ip_addr):
return ip_addr
except BaseException:
LOGGING.warning('DNS lookup of {0} failed.'.format(host_name))
return None
return None
def resolve_dns(host_name):
"""Perform a DNS lookup of a FQDN.
Params:
- host_name: (type: string) FQDN to perform lookup of.
Returns:
- result: (type: string) resulting IP address.
"""
if validators.ipv4(host_name):
return host_name
ip_addr = forward_dns_lookup(host_name)
if ip_addr is not None:
return ip_addr
return False
| phage-nz/ph0neutria | core/dns_utils.py | dns_utils.py | py | 1,379 | python | en | code | 299 | github-code | 36 | [
{
"api_name": "os.path.dirname",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "os.path.realpath",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "os.path.abspath",
"... |
40164893998 | from django.shortcuts import render
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from djangoapi.models import Department,Employee
from djangoapi.serializers import DepartmentSerializer,EmployeeSerializer
@csrf_exempt
def departmentApi(request,id=0):
if request.method=='GET':
departments=Department.objects.all()
departments_serializer=DepartmentSerializer(departments,many=True)
return JsonResponse(departments_serializer.data,safe=False)
elif request.method=='POST':
department_data=JSONParser().parse(request)
departments_serializers=DepartmentSerializer(data=department_data)
if departments_serializers.is_valid():
departments_serializer.save()
return JsonResponse("Added Sucessfully",safe=False)
return JsonResponse("Failed to Add",safe=False)
elif request.method=='PUT':
department_data=JSONParser().parse(request)
department=Department.objects.get(DepartmentId=department_data['DepartmentId'])
departments_serializers=DepartmentSerializer(department,data=department_data)
if departments_serializers.is_valid():
departments_serializer.save()
return JsonResponse("Added Sucessfully",safe=False)
return JsonResponse("Failed to Add",safe=False)
elif request.method=='DELETE':
departments=Department.objects.GET(DepartmentId=id)
department.delete()
return JsonResponse("Deleted Sucessfully",safe=False)
| 00karina/FullStackApp | djangoapi/views.py | views.py | py | 1,633 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "djangoapi.models.Department.objects.all",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "djangoapi.models.Department.objects",
"line_number": 14,
"usage_type": "attribute"
},
{
"api_name": "djangoapi.models.Department",
"line_number": 14,
"usage_... |
15478699282 | import os
import copy
import sys
import glog
import tifffile
try: from .tools import uity
except: from tools import uity
import numpy as np
from absl import flags, app
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import controller.processing
class TissueCut(object):
def __init__(self, gpu="-1", num_threads=0):
"""
:param img_type:ssdna,rna
:param model_path:path of weights
"""
self._WIN_SIZE = None
self._model_path = None
self.net_cfg()
self._gpu = gpu
self._model = None
self._num_threads = num_threads
self._init_model()
def net_cfg(self, cfg='weights.json'):
cfg = os.path.join(os.path.dirname(os.path.abspath(__file__)), cfg)
import json
with open(cfg, 'r') as fd:
dct = json.load(fd)
self._WIN_SIZE = dct['tissue']['input']
self._model_path = dct['tissue']['weights_path']
if not os.path.exists(self._model_path):
glog.error('Not found weights file in {}.'.format(self._model_path))
else: glog.info(f"Start load weights from {self._model_path}")
def _init_model(self):
from net.onnx_net import cl_onnx_net
self._model = cl_onnx_net(self._model_path, self._gpu, self._num_threads)
def f_predict(self, img):
"""
:param img:CHANGE
:return: Model input image, mask
"""
img = np.squeeze(img)
src_shape = img.shape[:2]
img = controller.processing.f_tissue_preprocess(img, self._WIN_SIZE)
pred = self._model.f_predict(copy.deepcopy(img))
pred = controller.processing.f_post_process(pred)
pred = uity.f_resize(pred, src_shape)
return img, pred
def tissue_cut(input: str, output: str, gpu: str=-1, num_threads: int=0):
if input is None or output is None:
print("please check your parameters")
return
img = tifffile.imread(input)
sg = TissueCut(gpu=gpu, num_threads=int(num_threads))
img, pred = sg.f_predict(img)
glog.info(f"Predict finish, start write.")
tifffile.imwrite(output, pred, compression="zlib", compressionargs={"level": 8})
glog.info(f"Work Finished.")
def main(argv):
tissue_cut(input=FLAGS.input,
output=FLAGS.output,
gpu=FLAGS.gpu,
num_threads=FLAGS.num_threads)
if __name__ == '__main__':
FLAGS = flags.FLAGS
flags.DEFINE_string('input', '', 'the input img path')
flags.DEFINE_string('output', '', 'the output file')
flags.DEFINE_string('gpu', '-1', 'output path')
flags.DEFINE_integer('num_threads', 0, 'num threads.', lower_bound=0)
app.run(main)
| BGIResearch/StereoCell | stereocell/segmentation/tissue.py | tissue.py | py | 2,701 | python | en | code | 18 | github-code | 36 | [
{
"api_name": "sys.path.append",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_num... |
3703533790 | from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from myapp.forms import MyModelForm
from myapp.models import MyModel
def form_request(request, url, template):
if request.method == 'POST':
form = MyModelForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
request.session['name'] = name
mm = MyModel.objects.create(name=name)
mm.save()
return HttpResponseRedirect(url) # Redirect after POST
else:
form = MyModelForm()
args = {}
objs = MyModel.objects.all()
if objs:
args['last_item'] = MyModel.objects.all().order_by('pk').reverse()[0]
args['form'] = form
return render(request, template, args)
def main(request):
return form_request(request, '/add/', 'main.html')
def form_1(request):
return form_request(request, '/1/', 'form_1.html')
def form_2(request):
return form_request(request, '/2/', 'form_2.html')
def form_add(request):
args = {}
name = request.session['name']
args['name'] = name
return render(request, 'add.html', args)
| msampaio/estudo_django | myapp/views.py | views.py | py | 1,153 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "myapp.forms.MyModelForm",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "myapp.models.MyModel.objects.create",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "myapp.models.MyModel.objects",
"line_number": 12,
"usage_type": "attribute"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.