hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2f089c81f0500fcadc824a7c0d1b517a63bcccd2 | 1,119 | py | Python | asyncapi_schema_pydantic/v2_3_0/sqs_bindings.py | albertnadal/asyncapi-schema-pydantic | 83966bdc11f2d465a10b52cec5ff79d18fa6f5fe | [
"MIT"
] | null | null | null | asyncapi_schema_pydantic/v2_3_0/sqs_bindings.py | albertnadal/asyncapi-schema-pydantic | 83966bdc11f2d465a10b52cec5ff79d18fa6f5fe | [
"MIT"
] | null | null | null | asyncapi_schema_pydantic/v2_3_0/sqs_bindings.py | albertnadal/asyncapi-schema-pydantic | 83966bdc11f2d465a10b52cec5ff79d18fa6f5fe | [
"MIT"
] | null | null | null | from pydantic import BaseModel, Extra
class SqsChannelBinding(BaseModel):
"""
This document defines how to describe SQS-specific information on AsyncAPI.
This object MUST NOT contain any properties. Its name is reserved for future use.
"""
class Config:
extra = Extra.forbid
class SqsMessageBinding(BaseModel):
"""
This document defines how to describe SQS-specific information on AsyncAPI.
This object MUST NOT contain any properties. Its name is reserved for future use.
"""
class Config:
extra = Extra.forbid
class SqsOperationBinding(BaseModel):
"""
This document defines how to describe SQS-specific information on AsyncAPI.
This object MUST NOT contain any properties. Its name is reserved for future use.
"""
class Config:
extra = Extra.forbid
class SqsServerBinding(BaseModel):
"""
This document defines how to describe SQS-specific information on AsyncAPI.
This object MUST NOT contain any properties. Its name is reserved for future use.
"""
class Config:
extra = Extra.forbid
| 22.38 | 85 | 0.701519 | 137 | 1,119 | 5.729927 | 0.262774 | 0.066242 | 0.107006 | 0.142675 | 0.864968 | 0.864968 | 0.864968 | 0.864968 | 0.864968 | 0.864968 | 0 | 0 | 0.240393 | 1,119 | 49 | 86 | 22.836735 | 0.923529 | 0.567471 | 0 | 0.615385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.076923 | 0 | 0.692308 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 7 |
2f9b6e6262b2ba4457e56224423604ff8c91b6a3 | 101 | py | Python | example/Tobe.py | fileSound/PythonGuide | 7e8f37b5dfc00c0993863d80ab18984e10da0ef4 | [
"MIT"
] | 1 | 2019-06-15T02:28:52.000Z | 2019-06-15T02:28:52.000Z | example/Tobe.py | fileSound/PythonGuide | 7e8f37b5dfc00c0993863d80ab18984e10da0ef4 | [
"MIT"
] | null | null | null | example/Tobe.py | fileSound/PythonGuide | 7e8f37b5dfc00c0993863d80ab18984e10da0ef4 | [
"MIT"
] | null | null | null | print r'''"To be ,or not to be",this is a question./n Whether it's nobler in the mind to suffer.'''
| 50.5 | 100 | 0.673267 | 22 | 101 | 3.090909 | 0.863636 | 0.117647 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.188119 | 101 | 1 | 101 | 101 | 0.829268 | 0 | 0 | 0 | 0 | 1 | 0.86 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 1 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 7 |
c0cff8c0ea1f7f2a73c20647c2f8853bdee3e304 | 45,683 | py | Python | src/pyredemet.py | josuehfa/pyredemet | 5ed39f3ef2c05175e9e0d0e0bd3d516278072c9a | [
"MIT"
] | null | null | null | src/pyredemet.py | josuehfa/pyredemet | 5ed39f3ef2c05175e9e0d0e0bd3d516278072c9a | [
"MIT"
] | null | null | null | src/pyredemet.py | josuehfa/pyredemet | 5ed39f3ef2c05175e9e0d0e0bd3d516278072c9a | [
"MIT"
] | null | null | null | #!/usr/bin/ebv python
# coding=utf-8
"""
Author = Josue H. F. Andrade
License = MIT
Version = 1.0.1
Email = josuehfa@gmail.com
Status = Development
"""
import json
import requests
class pyredemet:
"""[summary] A API da REDEMET é um produto de interfaces de programação de aplicativos(APIs), que proporciona acesso a vários produtos meteorológicos.
"""
def __init__(self, api_key, server_url="https://api-redemet.decea.gov.br", log_level=None,):
"""[summary]
Args:
api_key ([type]): [description]
"""
self.api_key = api_key
self.log_level = log_level
self.server_url = server_url
if len(self.api_key) < 40:
raise TypeError("Tamanho da chave API_KEY menor que 40")
if not isinstance(self.server_url, str):
raise TypeError("O servidor não é uma string")
def get_aerodromos(self, pais=None):
#API destina à retornar informações de Aeródromos de países disponíveis no banco de dados da REDEMET.
#https://api-redemet.decea.gov.br/aerodromos
#Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# pais Não Nome do país. Brasil Argentina
#Exemplo de Solicitação
# https://api-redemet.decea.gov.br/aerodromos/?api_key=SUA_CHAVE_AQUI&pais=Argentina
params = { 'api_key': self.api_key }
if pais is not None:
if (isinstance(pais, str)):
params.update({'pais': pais})
else:
raise TypeError("Error: O pais não é uma string")
try:
url = self.server_url + "/aerodromos/"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_aerodromos [!] HTTP status == False')
if response['message'] != '':
print('get_aerodromos [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_aerodromos [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_aerodromos_status(self, pais):
# GET aerodromos/status
# API destina à retornar status das localidades em cores.
# As cores são obtidas através de avaliação de parâmetros baseados em visibilidade e teto da localidade, conforme tabela abaixo.
# Valor Visibilidade(m) Condição Teto(ft)
# g >= 5000 e >= 1500
# y < 5000 e >= 1500 e/ou < 1500 e > 500
# r < 1500 e/ou < 600
# Endereço de Acesso
# https://api-redemet.decea.gov.br/aerodromos/status
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# pais Sim País que se deseja as informações de status.
# Para obter informações de mais de um país, basta informar separados por vígula. BRASIL BRASIL,ARGENTINA
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/aerodromos/status?api_key=SUA_CHAVE_AQUI
params = { 'api_key': self.api_key }
if isinstance(pais, str):
params.update({'pais': pais})
else:
raise TypeError("Error: O pais não é uma string")
try:
url = self.server_url + "/aerodromos/status"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_aerodromos_status [!] HTTP status == False')
if response['message'] != '':
print('get_aerodromos_status [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_aerodromos_status [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_aerodromos_info(self, localidade, metar=None, taf=None, datahora=None):
# API destina à retornar informações das condições meteorológicas de uma localidade disponível no banco de dados da REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/aerodromos/info
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# localidade Sim Indicativo de localidade ICAO. Não há SBBR
# metar Não METAR codificado da localidade. sim sim
# taf Não TAF codificado da localidade nao sim
# datahora Não Data no formato (YYYYMMDDHH) Data e hora atual 2019010100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/aerodromos/info?api_key=SUA_CHAVE_AQUI&localidade=SBBR&datahora=2019010100
params = { 'api_key': self.api_key }
if isinstance(localidade, str):
if len(localidade) == 4:
params.update({'localidade': localidade})
else:
raise TypeError("Error: A localidade não esta no formato certo (4 chars)")
else:
raise TypeError("Error: A localidade não é uma string")
if metar is not None:
if (isinstance(metar, str)):
params.update({'metar': metar})
else:
raise TypeError("Error: A metar não é uma str")
if taf is not None:
if (isinstance(taf, str)):
params.update({'taf': taf})
else:
raise TypeError("Error: A taf não é uma string")
if datahora is not None:
if (isinstance(datahora, str)):
if len(datahora) == 10:
params.update({'datahora': datahora})
else:
raise TypeError("Error: A datahora não esta no formato correto (YYYYMMDDHH)")
else:
raise TypeError("Error: A datahora não é uma string")
try:
url = self.server_url + "/aerodromos/info"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_aerodromos_info [!] HTTP status == False')
if response['message'] != '':
print('get_aerodromos_info [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_aerodromos_info [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_produtos_amdar(self, data):
# GET produtos/amdar
# API destina à retornar informações do AMDAR
# Endereço de Acesso
# https://api-redemet.decea.gov.br/produtos/amdar
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# data Não Data no formato YYYYMMDDHH Data atual 2020051200
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/produtos/amdar?api_key=SUA_CHAVE_AQUI&data=2020032415
params = { 'api_key': self.api_key }
if isinstance(data, str):
if len(data) == 10:
params.update({'data': data})
else:
raise TypeError("Error: A data não esta no formato correto (YYYYMMDDHH)")
else:
raise TypeError("Error: A data não é uma string")
try:
url = self.server_url + "/produtos/amdar"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_produtos_amdar [!] HTTP status == False')
if response['message'] != '':
print('get_produtos_amdar [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_produtos_amdar [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_produtos_modelo(self, modelo, area, produto, nivel, anima=None, timeout=180):
# GET produtos/modelo
# API destina à retornar informações de imagens geradas pela modelagem numérica disponíveis na REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/produtos/modelo
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# modelo Sim wifs Não há wifs
# area Sim x Não há b1
# produto Sim x Não há cb_top
# nivel Sim x Não há 600
# anima Não x Não há 5
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/produtos/modelo?api_key=SUA_CHAVE_AQUI&modelo=wifs&area=b1&produto=vento-altitude-barb&nivel=600&anima=2
params = { 'api_key': self.api_key }
if isinstance(modelo, str):
params.update({'modelo': modelo})
else:
raise TypeError("Error: O modelo não é uma string")
if isinstance(area, str):
if area in ('b1','as','az','ao','bs','cw','re'):
params.update({'area': area})
else:
raise TypeError("Error: A area informada não está disponivel")
else:
raise TypeError("Error: A area não é uma string")
if isinstance(produto, str):
if produto in ('vento-altitude-barb','vento-altitude-corrente',
'vento-altitude-magnitude','vento-temperatura-altitude',
'temperatura-altitude-shaded','temperatura-altitude-grid',
'temperatura-altitude-contour','umidade-relativa-shaded',
'umidade-relativa-contour','cb_cobertura','cb_base',
'cb_topo','pot_max_fga_shaded','pot_max_fga_contour',
'cat_max_pot','incldturb'):
params.update({'produto': produto})
else:
raise TypeError("Error: O produto informado não está disponivel")
else:
raise TypeError("Error: O produto não é uma string")
if isinstance(nivel, str):
if nivel in ('850','700','600','500','400','350','300',
'275','250','225','200','150','100'):
params.update({'nivel': nivel})
else:
raise TypeError("Error: O nivel informado não está disponivel")
else:
raise TypeError("Error: O nivel não é uma string")
if anima is not None:
if anima <= 11:
params.update({'anima': anima})
else:
raise TypeError("Error: O anima informado é maior que 11")
try:
url = self.server_url + "/produtos/modelo"
response = requests.get(url, params=params, timeout=timeout)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_produtos_modelo [!] HTTP status == False')
if response['message'] != '':
print('get_produtos_modelo [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_produtos_modelo [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_produto_radar(self, tipo, area, data=None, anima=None, timeout=180):
# GET produtos/radar
# API destina à retornar imagens de eco de Radar Meteorológico.
# Há disponibilidade de METAR desde 01/01/2006 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/produtos/radar/{tipo}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# tipo Sim Tipo de eco disponíveis
# maxccapi 07km
# data Não Data no formato YYYYMMDDHH Data atual 2020031211
# area Sim Radares disponíveis
# Não há pv
# anima Não Informe a quantidade de ecos de radar que deseja animar.
# A animação tem como referência a opção data como última imagem.
# O valor máximo permitido para a animação é 15. 1 10
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/produtos/radar/maxcappi?api_key=SUA_CHAVE_AQUI&data=2020032410
params = { 'api_key': self.api_key }
if isinstance(tipo, str):
if tipo in ('maxcappi','10km','07km','05km','03km'):
tipo_url = tipo
else:
raise TypeError("Error: O tipo informado não está disponivel")
else:
raise TypeError("Error: O tipo não é uma string")
if data is not None:
if isinstance(data, str):
if len(data) == 10 :
params.update({'data': data})
else:
raise TypeError("Error: A data informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data não é uma string")
if isinstance(area, str):
if area in ('al','be','bv','cn','cz','ga','jr',
'mq','mo','mn','mi','nt','pl','pc',
'pv','sv','sn','st','sg','sf','ua',
'sl','sr','tt','tf','tm'):
params.update({'area': area})
else:
raise TypeError("Error: A area informada não está disponivel")
else:
raise TypeError("Error: A area não é uma string")
if anima is not None:
if anima <= 15:
params.update({'anima': anima})
else:
raise TypeError("Error: O anima informado é maior que 11")
try:
url = self.server_url + "/produtos/radar/" + tipo_url
response = requests.get(url, params=params, timeout=timeout)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_produto_radar [!] HTTP status == False')
if response['message'] != '':
print('get_produto_radar [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_produto_radar [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_produto_satelite(self, tipo, data=None, anima=None, timeout=180):
# GET produtos/satelite
# API destina à retornar informações de imagens de satélite disponíveis na REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/produtos/satelite/{tipo}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# tipo Sim Tipos disponíveis
# Não há realcada
# data Não Data no formato YYYYMMDDHH Data atual 2020051200
# anima Não Informe a quantidade de imagens que deseja animar.
# A animação tem como referência a opção data como última imagem.
# O valor máximo permitido para a animação é 15. 1 10
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/produtos/satelite/realcada?api_key=SUA_CHAVE_AQUI&data=2020032114
params = { 'api_key': self.api_key }
if isinstance(tipo, str):
if tipo in ('ir','realcada','vis'):
tipo_url = tipo
else:
raise TypeError("Error: O tipo informado não está disponivel")
else:
raise TypeError("Error: O tipo não é uma string")
if data is not None:
if isinstance(data, str):
if len(data) == 10 :
params.update({'data': data})
else:
raise TypeError("Error: A data informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data não é uma string")
if anima is not None:
if anima <= 15:
params.update({'anima': anima})
else:
raise TypeError("Error: O anima informado é maior que 11")
try:
url = self.server_url + "/produtos/satelite/" + tipo_url
response = requests.get(url, params=params, timeout=timeout)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_produto_satelite [!] HTTP status == False')
if response['message'] != '':
print('get_produto_satelite [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_produto_satelite [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_produto_stsc(self, data=None, anima=None, timeout=180):
# GET produtos/stsc
# API destina à retornar mensagens as informação de ocorrência de trovoada.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/produtos/stsc
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# data Não Data no formato YYYYMMDDHH Data atual 2020051200
# anima Não Informe a quantidade de ocorrências que deseja animar.
# A animação tem como referência a opção data como última imagem.
# O valor máximo permitido para a animação é 60. 1 10
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/produtos/satelite/stsc?api_key=SUA_CHAVE_AQUI&data=2020032114
params = { 'api_key': self.api_key }
if data is not None:
if isinstance(data, str):
if len(data) == 10 :
params.update({'data': data})
else:
raise TypeError("Error: A data informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data não é uma string")
if anima is not None:
if anima <= 60:
params.update({'anima': anima})
else:
raise TypeError("Error: O anima informado é maior que 11")
try:
url = self.server_url + "/produtos/stsc"
response = requests.get(url, params=params, timeout=timeout)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_produto_stsc [!] HTTP status == False')
if response['message'] != '':
print('get_produto_stsc [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_produto_stsc [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_aviso(self, localidades, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/aviso
# API destina à retornar mensagens Aviso de Aeródromo das localidades disponíveis no banco de dados da REDEMET.
# Há disponibilidade de mensagens desde 01/01/2003 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/aviso/{localidades}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# localidades Sim Indicativo de localidade ICAO.
# Quando precisar informar mais de uma localidade, basta informar separado por vírgula sem intervalo. Não há SBBR
# data_ini Não Data no formato YYYYMMDDHH Data atual 2020051200
# data_fim Não Data no formato YYYYMMDDHH Data atual 2020051206
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/aviso/SBBG?api_key=SUA_CHAVE_AQUI&data_ini=2020030313&data_fim=2020030313
params = { 'api_key': self.api_key }
if isinstance(localidades, str):
check = len(localidades) - 4 # SBBR,SBCF ... [4],[4] -> 9 elementos: Possibilidades 4,9,14,18,24 (4)+(5)*(Numero adicional de localidades)
if check % 5 == 0:
localidades_url = localidades
else:
raise TypeError("Error: As localidades não estão no padrao correto [SBBR,SBCF,..]")
else:
raise TypeError("Error: A localidades não são uma string")
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 10 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if data_fim is not None:
if isinstance(data_fim, str):
if len(data_fim) == 10 :
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_fim não é uma string")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/aviso/" + localidades_url
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_aviso [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_aviso [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_aviso [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_gamet(self, pais, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/gamet
# API destina à retornar mensagens GAMET dos países disponíveis no banco de dados da REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/gamet
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# pais Sim Nome do País Brasil Argentina
# data_ini Não Data no formato YYYYMMDDHHII Data atual 202005120000
# data_fim Não Data no formato YYYYMMDDHHII Data atual 202005120600
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/gamet/?api_key=SUA_CHAVE_AQUI&data_ini=202006120300&data_fim=202006120300
params = { 'api_key': self.api_key }
if isinstance(pais, str):
params.update({'pais': pais})
else:
raise TypeError("Error: O pais não é uma string")
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 12 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHHII) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if data_fim is not None:
if isinstance(data_fim, str):
if len(data_fim) == 12 :
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim informada não está no formato correto (YYYYMMDDHHII) ")
else:
raise TypeError("Error: A data_fim não é uma string")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/gamet"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_gamet [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_gamet [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_gamet [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_metar(self, localidades, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/metar
# API destina à retornar mensagens METAR das localidades disponíveis no banco de dados da REDEMET.
# Há disponibilidade de mensagens desde 01/01/2003 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/metar/{localidades}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# localidades Sim Indicativo de localidade ICAO.
# Quando precisar informar mais de uma localidade, basta informar separado por vírgula sem intervalo. Não há SBBR
# data_ini Não Data no formato YYYYMMDDHH Data atual 2020051200
# data_fim Não Data no formato YYYYMMDDHH Data atual 2020051206
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/metar/SBGL,SBBR?api_key=SUA_CHAVE_AQUI&data_ini=2019010100&data_fim=2019010101
params = { 'api_key': self.api_key }
if isinstance(localidades, str):
check = len(localidades) - 4 # SBBR,SBCF ... [4],[4] -> 9 elementos: Possibilidades 4,9,14,18,24 (4)+(5)*(Numero adicional de localidades)
if check % 5 == 0:
localidades_url = localidades
else:
raise TypeError("Error: As localidades não estão no padrao correto [SBBR,SBCF,..]")
else:
raise TypeError("Error: A localidades não são uma string")
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 10 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if (data_fim is not None) and (data_ini is not None):
if isinstance(data_fim, str) and isinstance(data_ini, str):
if len(data_fim) == 10 and len(data_ini) == 10:
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim ou data ini informadas não estão no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_fim ou data ini não são strings")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/metar/" + localidades_url
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_metar [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_metar [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_metar [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_meteograma(self, localidade, data_hora=None, horas=None):
# GET mensagens/meteograma
# API destina à retornar informações de mensagens de METAR, TAF e Aviso de Aeródromo das localidades disponíveis no banco de dados da REDEMET.
# Além de retornar as mensagens acima mencionadas, algumas informações também são disponibilizadas, tais como:
# Decodificação de METAR e TAF da data e hora solicitada
# Informações de até 96 horas passadas com base na data e hora solicitada
# Separação de grupos do METAR
# Há disponibilidade de mensagens desde 01/01/2003 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/meteograma/{localidades}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# localidade Sim Indicativo de localidade ICAO.
# Somente será permitido uma localidade por solicitação. Não há SBBR
# data_hora Não Data no formato YYYYMMDDHH Data atual 2020051200
# horas Não Determina quantas horas passadas a partir de data_hora 96 72
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/meteograma/SBBR?api_key=SUA_CHAVE_AQUI&data_hora=2020042114
params = { 'api_key': self.api_key }
if isinstance(localidade, str):
if len(localidade) == 4:
localidade_url = localidade
else:
raise TypeError("Error: A localidade não esta no padrao correto [SBBR,SBCF,..]")
else:
raise TypeError("Error: A localidade não é uma string")
if data_hora is not None:
if isinstance(data_hora, str):
if len(data_hora) == 10 :
params.update({'data_hora': data_hora})
else:
raise TypeError("Error: A data_hora informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_hora não é uma string")
if horas is not None:
params.update({'horas': horas})
try:
url = self.server_url + "/mensagens/meteograma/" + localidade_url
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_meteograma [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_meteograma [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_meteograma [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_pilot(self, estacao, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/pilot
# API destina à retornar mensagens PILOT das estações disponíveis no banco de dados da REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/pilot
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# estacao Sim Número sinótico da Estação. Não há 83378
# data_ini Não Data no formato YYYYMMDDHH Data atual 2020051200
# data_fim Não Data no formato YYYYMMDDHH Data atual 2020051206
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/pilot?api_key=SUA_CHAVE_AQUI&estacao=83378&data_ini=2020032912&data_fim=2020032912
params = { 'api_key': self.api_key }
params.update({'estacao': estacao})
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 10 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if (data_fim is not None) and (data_ini is not None):
if isinstance(data_fim, str) and isinstance(data_ini, str):
if len(data_fim) == 10 and len(data_ini) == 10:
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim ou data ini informadas não estão no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_fim ou data ini não são strings")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/pilot"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_pilot [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_pilot [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_pilot [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_sigmet(self, pais, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/sigmet
# API destina à retornar mensagens SIGMET dos países disponíveis no banco de dados da REDEMET.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/sigmet
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# pais Sim Nome do País Brasil Argentina
# data_ini Não Data no formato YYYYMMDDHHII Data atual 202005120000
# data_fim Não Data no formato YYYYMMDDHHII Data atual 202005120600
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/sigmet/?api_key=SUA_CHAVE_AQUI&data_ini=202003291200&data_fim=202003291200
params = { 'api_key': self.api_key }
if isinstance(pais, str):
params.update({'pais': pais})
else:
raise TypeError("Error: O pais não é uma string")
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 12 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHHII) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if (data_fim is not None) and (data_ini is not None):
if isinstance(data_fim, str) and isinstance(data_ini, str):
if len(data_fim) == 12 and len(data_ini) == 12:
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim ou data ini informadas não estão no formato correto (YYYYMMDDHHII) ")
else:
raise TypeError("Error: A data_fim ou data ini não são strings")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/sigmet"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_sigmet [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_sigmet [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_sigmet [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_taf(self, localidades, data_ini=None, data_fim=None, page_tam=None, fim_linha=None):
# GET mensagens/taf
# API destina à retornar mensagens TAF das localidades disponíveis no banco de dados da REDEMET.
# Há disponibilidade de mensagens desde 01/01/2003 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/taf/{localidades}
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# localidades Sim Indicativo de localidade ICAO.
# Quando precisar informar mais de uma localidade, basta informar separado por vírgula sem intervalo. Não há SBBR
# data_ini Não Data no formato YYYYMMDDHH Data atual 2020051200
# data_fim Não Data no formato YYYYMMDDHH Data atual 2020051206
# page_tam Não Número de registros por página 150 100
# fim_linha Não Utilizado para formatar o TAF
# Valores possíveis:
# texto: para a quebra de linha com “\n”
# html: para a quebra de linha com “<br \>”
# Não há texto
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/taf/SBBR,SBGL?api_key=SUA_CHAVE_AQUI&data_ini=2020031005&data_fim=2020031005&fim_linha=texto
params = { 'api_key': self.api_key }
if isinstance(localidades, str):
check = len(localidades) - 4 # SBBR,SBCF ... [4],[4] -> 9 elementos: Possibilidades 4,9,14,18,24 (4)+(5)*(Numero adicional de localidades)
if check % 5 == 0:
localidades_url = localidades
else:
raise TypeError("Error: As localidades não estão no padrao correto [SBBR,SBCF,..]")
else:
raise TypeError("Error: A localidades não são uma string")
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 10 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if (data_fim is not None) and (data_ini is not None):
if isinstance(data_fim, str) and isinstance(data_ini, str):
if len(data_fim) == 10 and len(data_ini) == 10:
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim ou data ini informadas não estão no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_fim ou data ini não são strings")
if page_tam is not None:
params.update({'page_tam': page_tam})
if fim_linha is not None:
if isinstance(fim_linha, str):
if fim_linha in ['texto','html']:
params.update({'fim_linha': fim_linha})
else:
raise TypeError("Error: O fim_linha informadas não está no formato correto (text ou html) ")
else:
raise TypeError("Error: O fim_linha não é strings")
try:
url = self.server_url + "/mensagens/taf/" + localidades_url
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_taf [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_taf [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_taf [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
def get_mensagens_temp(self, estacao, data_ini=None, data_fim=None, page_tam=None):
# GET mensagens/temp
# API destina à retornar mensagens TEMP das estações disponíveis no banco de dados da REDEMET.
# Há disponibilidade de mensagens desde 01/01/2003 até a presente data.
# Endereço de Acesso
# https://api-redemet.decea.gov.br/mensagens/temp
# Parâmetros
# Nome Requerido Descrição Valor Padrão Exemplo
# estacao Sim Número sinótico da Estação.
# Permitido somente uma estação por solicitação Não há 83378
# data_ini Não Data no formato YYYYMMDDHH Data atual 2020051200
# data_fim Não Data no formato YYYYMMDDHH Data atual 2020051206
# page_tam Não Número de registros por página 150 100
# Exemplo de Solicitação
# https://api-redemet.decea.gov.br/mensagens/temp?api_key=SUA_CHAVE_AQUI&estacao=83378&data_ini=2020030912&data_fim=2020030912
params = { 'api_key': self.api_key }
params.update({'estacao': estacao})
if data_ini is not None:
if isinstance(data_ini, str):
if len(data_ini) == 10 :
params.update({'data_ini': data_ini})
else:
raise TypeError("Error: A data_ini informada não está no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_ini não é uma string")
if (data_fim is not None) and (data_ini is not None):
if isinstance(data_fim, str) and isinstance(data_ini, str):
if len(data_fim) == 10 and len(data_ini) == 10:
params.update({'data_fim': data_fim})
else:
raise TypeError("Error: A data_fim ou data ini informadas não estão no formato correto (YYYYMMDDHH) ")
else:
raise TypeError("Error: A data_fim ou data ini não são strings")
if page_tam is not None:
params.update({'page_tam': page_tam})
try:
url = self.server_url + "/mensagens/temp"
response = requests.get(url, params=params)
except Exception as ex:
raise RuntimeError("Error: " + repr(ex))
if response.status_code == 200:
response = response.json()
if response['status'] == False:
print('get_mensagens_temp [!] HTTP status == False')
if response['message'] != '':
print('get_mensagens_temp [!] HTTP message == ' + str(response['message']))
return response['data']
else:
print('get_mensagens_temp [!] HTTP {0} calling [{1}]'.format(response.status_code, response.request.url))
return None
if __name__ == '__main__':
api_key = 'NniTZlc8mk00BhImNU0WH4173jo3j62YAh4CwAeW'
redemet = pyredemet(api_key)
#Aerodromos
result = redemet.get_aerodromos(pais='Brasil')
result = redemet.get_aerodromos_status(pais='Brasil')
result = redemet.get_aerodromos_info(localidade='SBBR', metar='sim', taf='sim')
#Produtos
result = redemet.get_produtos_amdar(data='2020032415')
result = redemet.get_produtos_modelo(modelo='wifs',area='b1',produto='vento-altitude-barb',nivel='600',anima=2)
result = redemet.get_produto_radar(tipo='maxcappi',area='tm',data='2020032410',anima=2)
result = redemet.get_produto_satelite(tipo='vis', data='2020032410', anima=2)
result = redemet.get_produto_stsc(data='2020032410', anima=2)
#Mensagens
result = redemet.get_mensagens_aviso(localidades='SBBR,SBPA', data_ini='2020030912', data_fim='2020030912')
result = redemet.get_mensagens_gamet(pais='Brasil', data_ini='202006120300',data_fim='202006120300')
result = redemet.get_mensagens_metar(localidades='SBBR,SBPA', data_ini='2020030912',data_fim='2020030912')
result = redemet.get_mensagens_meteograma(localidade='SBBR', data_hora='2020030912', horas=12)
result = redemet.get_mensagens_pilot(estacao=83378,data_ini='2020030912',data_fim='2020030912')
result = redemet.get_mensagens_sigmet(pais='Brasil', data_ini='202007071200',data_fim='202007071800')
result = redemet.get_mensagens_taf(localidades='SBBR,SBPA', data_ini='2020030912',data_fim='2020030912', page_tam=100, fim_linha='texto')
result = redemet.get_mensagens_temp(estacao=83378,data_ini='2020030912',data_fim='2020030912')
print ("Done!") | 45.052268 | 154 | 0.590395 | 5,427 | 45,683 | 4.866224 | 0.078128 | 0.027036 | 0.051119 | 0.065319 | 0.84138 | 0.810406 | 0.785149 | 0.766519 | 0.740922 | 0.699118 | 0 | 0.034517 | 0.310641 | 45,683 | 1,014 | 155 | 45.052268 | 0.804077 | 0.250859 | 0 | 0.712242 | 0 | 0 | 0.22698 | 0.011691 | 0 | 0 | 0 | 0 | 0 | 1 | 0.027027 | false | 0 | 0.00318 | 0 | 0.082671 | 0.077901 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
23ecb33836477420eb91c3e966f34c539a91e4ae | 222 | py | Python | extensible_classification_framework/src/utils/__init__.py | Innoplexus-Consulting-Services/extensible_classification_framework | a64865a2b39133a66bf9b7bfdbd8d46324ce643f | [
"MIT"
] | null | null | null | extensible_classification_framework/src/utils/__init__.py | Innoplexus-Consulting-Services/extensible_classification_framework | a64865a2b39133a66bf9b7bfdbd8d46324ce643f | [
"MIT"
] | null | null | null | extensible_classification_framework/src/utils/__init__.py | Innoplexus-Consulting-Services/extensible_classification_framework | a64865a2b39133a66bf9b7bfdbd8d46324ce643f | [
"MIT"
] | null | null | null | from extensible_classification_framework.src.utils import grid_search
from extensible_classification_framework.src.utils import saving_and_loading
from extensible_classification_framework.src.utils import custom_vectorizer | 74 | 76 | 0.923423 | 28 | 222 | 6.964286 | 0.5 | 0.215385 | 0.430769 | 0.569231 | 0.784615 | 0.784615 | 0.784615 | 0 | 0 | 0 | 0 | 0 | 0.04955 | 222 | 3 | 77 | 74 | 0.924171 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 10 |
9b162bc7ed6654001d0234425948e09db12ce669 | 365 | py | Python | librespot/audio/__init__.py | pawanpaudel93/librespot-python | e9c396b756db42ef9d2d0716fb314e24f3389324 | [
"Apache-2.0"
] | 1 | 2021-12-15T22:44:46.000Z | 2021-12-15T22:44:46.000Z | librespot/audio/__init__.py | zackmark29/librespot-python-1 | b4cb86f1e92b345983f0ba0161f93c36a06ce583 | [
"Apache-2.0"
] | 12 | 2021-10-06T02:18:44.000Z | 2022-02-07T02:16:47.000Z | librespot/audio/__init__.py | zackmark29/librespot-python-1 | b4cb86f1e92b345983f0ba0161f93c36a06ce583 | [
"Apache-2.0"
] | null | null | null | from librespot.audio import AbsChunkedInputStream
from librespot.audio import AudioKeyManager
from librespot.audio import GeneralAudioStream
from librespot.audio import GeneralWritableStream
from librespot.audio import HaltListener
from librespot.audio import NormalizationData
from librespot.audio import PlayableContentFeeder
from librespot.audio import StreamId
| 40.555556 | 49 | 0.890411 | 40 | 365 | 8.125 | 0.3 | 0.32 | 0.443077 | 0.590769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.087671 | 365 | 8 | 50 | 45.625 | 0.975976 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
f1d75bb5dcc780a8b13fc17d64cea28a7e94a501 | 28,557 | py | Python | tests/unittest/rbac_ut.py | OpenSwitchNOS/openswitch-ops-rbac | 0b4c64bd959fabcf4e9437e03d0074a5e1ed93a3 | [
"Apache-2.0"
] | null | null | null | tests/unittest/rbac_ut.py | OpenSwitchNOS/openswitch-ops-rbac | 0b4c64bd959fabcf4e9437e03d0074a5e1ed93a3 | [
"Apache-2.0"
] | null | null | null | tests/unittest/rbac_ut.py | OpenSwitchNOS/openswitch-ops-rbac | 0b4c64bd959fabcf4e9437e03d0074a5e1ed93a3 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright (C) 2016 Hewlett Packard Enterprise Development LP
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
# =======================================================
# Module: rbac_ut.py
# Description: Unit Test for RBAC interface
# =======================================================
import rbac
import time
import subprocess
import os
#
# Used to create user accounts
#
GROUP_OPS_ADMIN = "ops_admin"
GROUP_OPS_NETOP = "ops_netop"
GROUP_NONE = "users"
#
# Users
#
USER_ROOT = "root"
USER_ADMIN_BI = "admin"
USER_NETOP_BI = "netop"
USER_ADMIN = "rbactest_admin"
USER_NETOP = "rbactest_netop"
USER_GENERIC = "rbactest_generic"
USER_BOTH = "rbactest_both"
USER_BOGUS = "I_DONT_EXIST"
USER_BLANK = ""
USER_NETOP_SHORT = "neto"
USER_NETOP_LONG = "netopp"
USER_ADMIN_SHORT = "adm"
USER_ADMIN_LONG = "adminn"
#
# Global test variables
#
passed_tests = 0
failed_tests = 0
#
# These four function do a bulk of the work calling the rbac interfaces
# and making sure we receive the expected results. The expected results
# are passed in from the individual test cases.
#
# The print statements in these routines have been commented out and
# my be useful to un-comment when tracking down failing tests.
#
# Returning a 0 is a passing test case
# Returning a 1 is a failing test case
#
def rbac_ut_rbac_get_user_role(username, role):
# print "---Checking role ", username
rbacrole = rbac.get_user_role(username)
if role not in rbacrole:
# print "role is", role
# print "rbacrole is", rbacrole
# print "===Checking user role - failed"
return(1)
# print " Checking user role - passed"
return(0)
def rbac_ut_rbac_check_user_permission(username, permission, expected_result):
# print "---Checking user permission", permission, "for user",\
# username, "for result", expected_result
rbacresult = rbac.check_user_permission(username, permission)
if rbacresult != expected_result:
# print "===Checking user permission - failed"
return(1)
# print " Checking user permission - passed"
return(0)
def rbac_ut_rbac_get_user_permissions(username, permissionlist):
# print "---Getting user permissions for user", username
rbacpermissions = rbac.get_user_permissions(username)
permissionlist.sort()
rbacpermissions.sort()
result = cmp(permissionlist, rbacpermissions)
if result == 0:
# print " Getting user permission - passed"
return(0)
# print "permissionlist", permissionlist
# print "rbacpermissions", rbacpermissions
# print "===Getting user permission - failed (lists have different values)"
return(1)
#
# Creates the user accounts used in both python and C unit tests
#
def create_user_accounts():
print "---Creating user account ", USER_ADMIN
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/useradd")
cmd.insert(2, "-g")
cmd.insert(3, GROUP_OPS_ADMIN)
cmd.insert(4, "-s")
cmd.insert(5, "/sbin/bash")
cmd.insert(6, USER_ADMIN)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Creating user account ", USER_NETOP
cmd.remove(USER_ADMIN)
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/useradd")
cmd.insert(2, "-g")
cmd.insert(3, GROUP_OPS_NETOP)
cmd.insert(4, "-G")
cmd.insert(5, "ovsdb-client")
cmd.insert(6, "-s")
cmd.insert(7, "/usr/bin/vtysh")
cmd.insert(8, USER_NETOP)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Creating user account ", USER_GENERIC
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/useradd")
cmd.insert(2, "-g")
cmd.insert(3, GROUP_NONE)
cmd.insert(4, "-s")
cmd.insert(5, "/sbin/bash")
cmd.insert(6, USER_GENERIC)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Creating user account ", USER_BOTH
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/useradd")
cmd.insert(2, "-g")
cmd.insert(3, GROUP_OPS_NETOP)
cmd.insert(4, "-G")
cmd.insert(5, GROUP_OPS_ADMIN + ",ovsdb-client")
cmd.insert(6, "-s")
cmd.insert(7, "/sbin/bash")
cmd.insert(8, USER_BOTH)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
#
# Deletes the user accounts that were used in both python and C testing
#
def delete_user_accounts():
print "---Deleting user account ", USER_ADMIN
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/userdel")
cmd.insert(2, "-r")
cmd.insert(3, USER_ADMIN)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Deleting user account ", USER_NETOP
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/userdel")
cmd.insert(2, "-r")
cmd.insert(3, USER_NETOP)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Deleting user account ", USER_GENERIC
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/userdel")
cmd.insert(2, "-r")
cmd.insert(3, USER_GENERIC)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
print "---Deleting user account ", USER_BOTH
cmd = []
cmd.insert(0, "sudo")
cmd.insert(1, "/usr/sbin/userdel")
cmd.insert(2, "-r")
cmd.insert(3, USER_BOTH)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(5)
#
# These are the individual test cases. I have tried to structure then
# so they closely match the unittest test cases for the "C" shared library.
#
#
# Test the rbac.get_user_role() interface
#
def rbac_get_user_role_multiple_users():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_role_multiple_users"
tf = 0
tf += rbac_ut_rbac_get_user_role(USER_ROOT, rbac.ROLE_ROOT)
tf += rbac_ut_rbac_get_user_role(USER_ADMIN_BI, rbac.ROLE_ADMIN)
tf += rbac_ut_rbac_get_user_role(USER_NETOP_BI, rbac.ROLE_NETOP)
tf += rbac_ut_rbac_get_user_role(USER_ADMIN, rbac.ROLE_ADMIN)
tf += rbac_ut_rbac_get_user_role(USER_NETOP, rbac.ROLE_NETOP)
tf += rbac_ut_rbac_get_user_role(USER_GENERIC, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_BOGUS, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_BLANK, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_BOTH, rbac.ROLE_ADMIN)
tf += rbac_ut_rbac_get_user_role(USER_ADMIN_SHORT, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_ADMIN_LONG, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_NETOP_SHORT, rbac.ROLE_NONE)
tf += rbac_ut_rbac_get_user_role(USER_NETOP_LONG, rbac.ROLE_NONE)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_role_multiple_users"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_role_multiple_users"
#
# Tests the rbac.check_user_permission() interface
# with built-in root user
#
def rbac_check_user_permission_root():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_root"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_ROOT, rbac.READ_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_ROOT, rbac.WRITE_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_ROOT, rbac.SYS_MGMT, True)
tf += rbac_ut_rbac_check_user_permission(
USER_ROOT, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_ROOT, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_root"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_root"
#
# Tests the rbac.check_user_permission() interface
# with built-in admin user
#
def rbac_check_user_permission_builtin_admin():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_builtin_admin"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_BI, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_BI, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_BI, rbac.SYS_MGMT, True)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_BI, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_BI, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_builtin_admin"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_builtin_admin"
#
# Tests the rbac.check_user_permission() interface
# with built-in netop user
#
def rbac_check_user_permission_builtin_netop():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_builtin_netop"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_BI, rbac.READ_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_BI, rbac.WRITE_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_BI, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_BI, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_BI, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_builtin_netop"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_builtin_netop"
#
# Tests the rbac.check_user_permission() interface
# with created user with ops_admin
#
def rbac_check_user_permission_user_ops_admin():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_ops_admin"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN, rbac.SYS_MGMT, True)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_ops_admin"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_ops_admin"
#
# Tests the rbac.check_user_permission() interface
# with created user with ops_netop
#
def rbac_check_user_permission_user_ops_netop():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_ops_netop"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP, rbac.READ_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP, rbac.WRITE_SWITCH_CONFIG, True)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_ops_netop"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_ops_netop"
#
# Tests the rbac.check_user_permission() interface
# with created user with no ops role
#
def rbac_check_user_permission_user_generic():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_generic"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_GENERIC, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_GENERIC, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_GENERIC, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_GENERIC, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_GENERIC, "KJDSFKJDSK", False)
global failed_tests
global passed_tests
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_generic"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_generic"
#
# Tests the rbac.check_user_permission() interface
# with unknown user
#
def rbac_check_user_permission_user_bogus():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_bogus"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_BOGUS, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOGUS, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOGUS, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOGUS, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOGUS, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_bogus"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_bogus"
#
# Tests the rbac.check_user_permission() interface
# with blank user name
#
def rbac_check_user_permission_user_blank():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_blank"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_BLANK, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BLANK, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BLANK, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BLANK, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_BLANK, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_blank"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_blank"
#
# Tests the rbac.check_user_permission() interface
# with a user with both ops_admin and ops_netop role
#
def rbac_check_user_permission_user_multiple_roles():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_user_multiple_roles"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_BOTH, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOTH, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOTH, rbac.SYS_MGMT, True)
tf += rbac_ut_rbac_check_user_permission(
USER_BOTH, "", False)
tf += rbac_ut_rbac_check_user_permission(
USER_BOTH, "KJDSFKJDSK", False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_user_multiple_roles"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_user_multiple_roles"
#
# Tests the rbac.check_user_permission() interface
# with a partial valid user name
#
def rbac_check_user_permission_partial_user_names():
global failed_tests
global passed_tests
print "[ RUN ] rbac_check_user_permission_partial_user_name"
tf = 0
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_SHORT, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_SHORT, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_SHORT, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_LONG, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_LONG, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_ADMIN_LONG, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_SHORT, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_SHORT, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_SHORT, rbac.SYS_MGMT, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_LONG, rbac.READ_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_LONG, rbac.WRITE_SWITCH_CONFIG, False)
tf += rbac_ut_rbac_check_user_permission(
USER_NETOP_LONG, rbac.SYS_MGMT, False)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_check_user_permission_partial_user_names"
else:
passed_tests += 1
print "[ OK ] rbac_check_user_permission_partial_user_name"
#
# Tests the rbac.get_user_permissions() interface
# with built-in root user.
#
def rbac_get_user_permissions_user_root():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_root"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_ROOT, rbac.ROLE_ROOT_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_root"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_root"
#
# Tests the rbac.get_user_permissions() interface
# with built-in admin user.
#
def rbac_get_user_permissions_user_builtin_admin():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_builtin_admin"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_ADMIN_BI, rbac.ROLE_ADMIN_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_builtin_admin"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_builtin_admin"
#
# Tests the rbac.get_user_permissions() interface
# with built-in netop user.
#
def rbac_get_user_permissions_user_builtin_netop():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_builtin_netop"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_NETOP_BI, rbac.ROLE_NETOP_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_builtin_netop"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_builtin_netop"
#
# Tests the rbac.get_user_permissions() interface
# using a created user with ops_admin role
#
def rbac_get_user_permissions_user_ops_admin():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_ops_admin"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_ADMIN, rbac.ROLE_ADMIN_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_ops_admin"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_ops_admin"
#
# Tests the rbac.get_user_permissions() interface
# using a created user with ops_netop role
#
def rbac_get_user_permissions_user_ops_netop():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_ops_netop"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_NETOP, rbac.ROLE_NETOP_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_ops_netop"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_ops_netop"
#
# Tests the rbac.get_user_permissions() interface
# using a created user with no ops role
#
def rbac_get_user_permissions_user_generic():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_generic"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_GENERIC, rbac.ROLE_NONE_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_generic"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user generic"
#
# Tests the rbac.get_user_permissions() interface
# using a bogus user name
#
def rbac_get_user_permissions_user_bogus():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_bogus"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(USER_BOGUS,
rbac.ROLE_NONE_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_bogus"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user bogus"
#
# Tests the rbac.get_user_permissions() interface
# using a blank user name
#
def rbac_get_user_permissions_user_blank():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_blank"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(USER_BLANK,
rbac.ROLE_NONE_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_blank"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_blank"
#
# Tests the rbac.get_user_permissions() interface
# using a created user with both ops_admin and ops_netop role
#
def rbac_get_user_permissions_user_multiple_roles():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_user_multiple_roles"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_BOTH, rbac.ROLE_ADMIN_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_user_multiple_roles"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_user_mulitple_roles "
#
# Tests the rbac.get_user_permissions() interface
# using a partial built-in user name
#
def rbac_get_user_permissions_partial_user_names():
global failed_tests
global passed_tests
print "[ RUN ] rbac_get_user_permissions_partial_user_names"
tf = 0
tf += rbac_ut_rbac_get_user_permissions(
USER_ADMIN_SHORT, rbac.ROLE_NONE_PERMISSIONS)
tf += rbac_ut_rbac_get_user_permissions(
USER_ADMIN_LONG, rbac.ROLE_NONE_PERMISSIONS)
tf += rbac_ut_rbac_get_user_permissions(
USER_NETOP_SHORT, rbac.ROLE_NONE_PERMISSIONS)
tf += rbac_ut_rbac_get_user_permissions(
USER_NETOP_LONG, rbac.ROLE_NONE_PERMISSIONS)
if tf > 0:
failed_tests += 1
print "Value of: ", tf
print "Expected: 0"
print "[ FAILED ] rbac_get_user_permissions_parital_user_names"
else:
passed_tests += 1
print "[ OK ] rbac_get_user_permissions_partial_user_names"
#
# This is the main function that will run all the RBAC Python unit tests.
#
def rbac_ut():
#
# Setup
#
# print "Creating user accounts"
# create_user_accounts()
print ""
print ""
print "rbac_ut Test Harness for python libraries"
print "[==========]"
print "[----------]"
#
# Run the python unit tests
#
print "[----------]"
print "Running rbac.check_user_permissions() tests"
#
# get_user_role tests
#
rbac_get_user_role_multiple_users()
#
# check user permission tests
#
rbac_check_user_permission_root()
rbac_check_user_permission_builtin_admin()
rbac_check_user_permission_builtin_netop()
rbac_check_user_permission_user_ops_admin()
rbac_check_user_permission_user_ops_netop()
rbac_check_user_permission_user_generic()
rbac_check_user_permission_user_bogus()
rbac_check_user_permission_user_blank()
rbac_check_user_permission_user_multiple_roles()
rbac_check_user_permission_partial_user_names()
#
# get user permissions tests
#
rbac_get_user_permissions_user_root()
rbac_get_user_permissions_user_builtin_admin()
rbac_get_user_permissions_user_builtin_netop()
rbac_get_user_permissions_user_ops_admin()
rbac_get_user_permissions_user_ops_netop()
rbac_get_user_permissions_user_generic()
rbac_get_user_permissions_user_bogus()
rbac_get_user_permissions_user_blank()
rbac_get_user_permissions_user_multiple_roles()
rbac_get_user_permissions_partial_user_names()
#
# Results
#
print "[----------] ", passed_tests + failed_tests, "from rbac_ut"
print ""
print "[==========] ", passed_tests + failed_tests, "from rbac_ut"
if passed_tests > 0:
print "[ PASSED ] ", passed_tests
if failed_tests > 0:
print "[ FAILED ] ", failed_tests
print ""
print ""
#
# Teardown
#
# print "Deleting user accounts"
# delete_user_accounts()
return(0)
| 30.444563 | 79 | 0.651084 | 3,688 | 28,557 | 4.64859 | 0.069143 | 0.102077 | 0.090994 | 0.159648 | 0.849393 | 0.836619 | 0.795672 | 0.735651 | 0.705961 | 0.673122 | 0 | 0.0087 | 0.263403 | 28,557 | 937 | 80 | 30.477054 | 0.806323 | 0.142732 | 0 | 0.570234 | 0 | 0 | 0.194841 | 0.103221 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.080268 | 0.006689 | null | null | 0.212375 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 8 |
7b197bbe9f5578082dff8074864a6c5813b1a7a4 | 79,289 | py | Python | src/membership/models.py | Busaka/excellence | 1cd19770285584d61aeddd77d6c1dd83e2fd04ba | [
"MIT"
] | null | null | null | src/membership/models.py | Busaka/excellence | 1cd19770285584d61aeddd77d6c1dd83e2fd04ba | [
"MIT"
] | null | null | null | src/membership/models.py | Busaka/excellence | 1cd19770285584d61aeddd77d6c1dd83e2fd04ba | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
from django.db import models
class BasicStudyTip(models.Model):
tip1 = models.CharField("Study Tip One", max_length=200, blank=True, null=True)
tip1_file = models.FileField("Tip One File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip2 = models.CharField("Study Tip Two", max_length=200, blank=True, null=True)
tip2_file = models.FileField("Tip Two File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip3 = models.CharField("Study Tip Three", max_length=200, blank=True, null=True)
tip3_file = models.FileField("Tip Three File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip4 = models.CharField("Study Tip Four", max_length=200, blank=True, null=True)
tip4_file = models.FileField("Tip Four File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip5 = models.CharField("Study Tip Five", max_length=200, blank=True, null=True)
tip5_file = models.FileField("Tip Five File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip6 = models.CharField("Study Tip Six", max_length=200, blank=True, null=True)
tip6_file = models.FileField("Tip Six File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip7 = models.CharField("Study Tip Seven", max_length=200, blank=True, null=True)
tip7_file = models.FileField("Tip Seven File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip8 = models.CharField("Study Tip Eight", max_length=200, blank=True, null=True)
tip8_file = models.FileField("Tip Eight File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip9 = models.CharField("Study Tip Nine", max_length=200, blank=True, null=True)
tip9_file = models.FileField("Tip Nine File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip10 = models.CharField("Study Tip Ten", max_length=200, blank=True, null=True)
tip10_file = models.FileField("Tip Ten File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip11 = models.CharField("Study Tip Eleven", max_length=200, blank=True, null=True)
tip11_file = models.FileField("Tip Eleven File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip12 = models.CharField("Study Tip Twelve", max_length=200, blank=True, null=True)
tip12_file = models.FileField("Tip Twelve File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip13 = models.CharField("Study Tip Thirteen", max_length=200, blank=True, null=True)
tip13_file = models.FileField("Tip Thirteen File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip14 = models.CharField("Study Tip Fourteen", max_length=200, blank=True, null=True)
tip14_file = models.FileField("Tip Fourteen File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
tip15 = models.CharField("Study Tip Fifteen", max_length=200, blank=True, null=True)
tip15_file = models.FileField("Tip Fifteen File",upload_to='membership/study_tips/basic', max_length=200, blank=True, null=True)
def __str__(self):
return 'Basic Study Tips'
class PremiumStudyTip(models.Model):
tip1 = models.CharField("Study Tip One", max_length=200, blank=True, null=True)
tip1_file = models.FileField("Tip One File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip2 = models.CharField("Study Tip Two", max_length=200, blank=True, null=True)
tip2_file = models.FileField("Tip Two File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip3 = models.CharField("Study Tip Three", max_length=200, blank=True, null=True)
tip3_file = models.FileField("Tip Three File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip4 = models.CharField("Study Tip Four", max_length=200, blank=True, null=True)
tip4_file = models.FileField("Tip Four File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip5 = models.CharField("Study Tip Five", max_length=200, blank=True, null=True)
tip5_file = models.FileField("Tip Five File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip6 = models.CharField("Study Tip Six", max_length=200, blank=True, null=True)
tip6_file = models.FileField("Tip Six File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip7 = models.CharField("Study Tip Seven", max_length=200, blank=True, null=True)
tip7_file = models.FileField("Tip Seven File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip8 = models.CharField("Study Tip Eight", max_length=200, blank=True, null=True)
tip8_file = models.FileField("Tip Eight File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip9 = models.CharField("Study Tip Nine", max_length=200, blank=True, null=True)
tip9_file = models.FileField("Tip Nine File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip10 = models.CharField("Study Tip Ten", max_length=200, blank=True, null=True)
tip10_file = models.FileField("Tip Ten File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip11 = models.CharField("Study Tip Eleven", max_length=200, blank=True, null=True)
tip11_file = models.FileField("Tip Eleven File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip12 = models.CharField("Study Tip Twelve", max_length=200, blank=True, null=True)
tip12_file = models.FileField("Tip Twelve File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip13 = models.CharField("Study Tip Thirteen", max_length=200, blank=True, null=True)
tip13_file = models.FileField("Tip Thirteen File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip14 = models.CharField("Study Tip Fourteen", max_length=200, blank=True, null=True)
tip14_file = models.FileField("Tip Fourteen File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
tip15 = models.CharField("Study Tip Fifteen", max_length=200, blank=True, null=True)
tip15_file = models.FileField("Tip Fifteen File",upload_to='membership/study_tips/premium', max_length=200, blank=True, null=True)
def __str__(self):
return 'Premium Study Tips'
class BasicForm1Exam(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form_one/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Basic Form One Exams'
class BasicForm2Exam(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form_two/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Basic Form Two Exams'
class BasicForm3Exam(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form_three/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Basic Form Three Exams'
class BasicForm4Exam(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form_four/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Basic Form Four Exams'
##########################################################################################################################
# PREMIUM SERVICES
########################################################################################################################## # FORM ONE
# ########################################################################################################################
class Form1Cat1(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form1_cat1/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form One CAT1'
class Form1Cat2(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form1_cat2/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form One CAT2'
class Form1Cat3(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form1_cat3/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form One CAT3'
class Form1EndTerm(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form1_end_term/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form One End Term Exam'
##########################################################################################################################
# FORM TWO
# ########################################################################################################################
class Form2Cat1(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form2_cat1/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Two CAT1'
class Form2Cat2(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form2_cat2/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Two CAT2'
class Form2Cat3(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form2_cat3/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Two CAT3'
class Form2EndTerm(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form2_end_term/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Two End Term Exam'
##########################################################################################################################
# FORM THREE
# ########################################################################################################################
class Form3Cat1(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form3_cat1/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Three CAT1'
class Form3Cat2(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form3_cat2/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Three CAT2'
class Form3Cat3(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form3_cat3/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Three CAT3'
class Form3EndTerm(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form3_end_term/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Three End Term Exam'
##########################################################################################################################
# FORM FOUR
# ########################################################################################################################
class Form4Mock1(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form4_mock1/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Four Mock1'
class Form4Mock2(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form4_mock2/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Four Mock2'
class Form4Mock3(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form4_mock3/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Four Mock3'
##########################################################################################################################
# FORM REVISION
# ########################################################################################################################
class Form4Revision(models.Model):
subject1 = models.CharField("Subject One", max_length=200, blank=True, null=True)
subject1_code = models.FileField("Subject One Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject2 = models.CharField("Subject Two", max_length=200, blank=True, null=True)
subject2_code = models.FileField("Subject Two Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject3 = models.CharField("Subject Three", max_length=200, blank=True, null=True)
subject3_code = models.FileField("Subject Three Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject4 = models.CharField("Subject Four", max_length=200, blank=True, null=True)
subject4_code = models.FileField("Subject Four Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject5 = models.CharField("Subject Five", max_length=200, blank=True, null=True)
subject5_code = models.FileField("Subject Five Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject6 = models.CharField("Subject Six", max_length=200, blank=True, null=True)
subject6_code = models.FileField("Subject Six Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject7 = models.CharField("Subject Seven", max_length=200, blank=True, null=True)
subject7_code = models.FileField("Subject Seven Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject8 = models.CharField("Subject Eight", max_length=200, blank=True, null=True)
subject8_code = models.FileField("Subject Eight Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject9 = models.CharField("Subject Nine", max_length=200, blank=True, null=True)
subject9_code = models.FileField("Subject Nine Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject10 = models.CharField("Subject Ten", max_length=200, blank=True, null=True)
subject10_code = models.FileField("Subject Ten Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject11 = models.CharField("Subject Eleven", max_length=200, blank=True, null=True)
subject11_code = models.FileField("Subject Eleven Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject12 = models.CharField("Subject Twelve", max_length=200, blank=True, null=True)
subject12_code = models.FileField("Subject Twelve Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject13 = models.CharField("Subject Thirteen", max_length=200, blank=True, null=True)
subject13_code = models.FileField("Subject Thirteen Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject14 = models.CharField("Subject Fourteen", max_length=200, blank=True, null=True)
subject14_code = models.FileField("Subject Fourteen Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
subject15 = models.CharField("Subject Fifteen", max_length=200, blank=True, null=True)
subject15_code = models.FileField("Subject Fifteen Code",upload_to='membership/form4_revision/subjects', max_length=200, blank=True, null=True)
def __str__(self):
return 'Form Four Revision'
| 96.576127 | 148 | 0.751567 | 10,909 | 79,289 | 5.298652 | 0.010817 | 0.102763 | 0.137017 | 0.194108 | 0.989291 | 0.989291 | 0.989291 | 0.989291 | 0.989291 | 0.989291 | 0 | 0.047415 | 0.104125 | 79,289 | 820 | 149 | 96.693902 | 0.766334 | 0.000933 | 0 | 0.483516 | 0 | 0 | 0.264171 | 0.129061 | 0 | 0 | 0 | 0 | 0 | 1 | 0.03022 | false | 0 | 0.002747 | 0.03022 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
7b2687c9fd8e04c885fd2980fb43a7beefa46573 | 68 | py | Python | clients/python/haberdasher/__init__.py | neilmayhew/twirp-haskell | 4e23de13a60f317a1d1becc56f9ac3d44299c1c5 | [
"BSD-3-Clause"
] | 11 | 2019-02-09T18:30:37.000Z | 2019-12-11T04:42:15.000Z | clients/python/haberdasher/__init__.py | neilmayhew/twirp-haskell | 4e23de13a60f317a1d1becc56f9ac3d44299c1c5 | [
"BSD-3-Clause"
] | 18 | 2019-02-09T19:21:04.000Z | 2020-09-29T14:36:57.000Z | clients/python/haberdasher/__init__.py | neilmayhew/twirp-haskell | 4e23de13a60f317a1d1becc56f9ac3d44299c1c5 | [
"BSD-3-Clause"
] | 3 | 2019-05-02T00:04:23.000Z | 2020-08-13T21:46:49.000Z | from .haberdasher_pb2 import *
from .haberdasher_pb2_twirp import *
| 22.666667 | 36 | 0.823529 | 9 | 68 | 5.888889 | 0.555556 | 0.566038 | 0.679245 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.033333 | 0.117647 | 68 | 2 | 37 | 34 | 0.85 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
9e92ad0b125a746dd630161c39abe901d99600e9 | 54,248 | py | Python | tests/integrate_test/iiss/decentralized/test_preps_replace_in_term.py | bayeshack2016/icon-service | 36cab484d2e41548d7f2f74526f127ee3a4423fc | [
"Apache-2.0"
] | 52 | 2018-08-24T02:28:43.000Z | 2021-07-06T04:44:22.000Z | tests/integrate_test/iiss/decentralized/test_preps_replace_in_term.py | bayeshack2016/icon-service | 36cab484d2e41548d7f2f74526f127ee3a4423fc | [
"Apache-2.0"
] | 62 | 2018-09-17T06:59:16.000Z | 2021-12-15T06:02:51.000Z | tests/integrate_test/iiss/decentralized/test_preps_replace_in_term.py | bayeshack2016/icon-service | 36cab484d2e41548d7f2f74526f127ee3a4423fc | [
"Apache-2.0"
] | 35 | 2018-09-14T02:42:10.000Z | 2022-02-05T10:34:46.000Z | # -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""IconScoreEngine testcase
"""
from typing import TYPE_CHECKING, List
from iconservice.icon_constant import ICX_IN_LOOP, PREP_MAIN_PREPS, PREP_MAIN_AND_SUB_PREPS, PREP_PENALTY_SIGNATURE
from iconservice.iconscore.icon_score_context import IconScoreContext
from tests.integrate_test.iiss.test_iiss_base import TestIISSBase
from tests.integrate_test.test_integrate_base import EOAAccount
if TYPE_CHECKING:
from iconservice.iconscore.icon_score_result import TransactionResult
class TestPreps(TestIISSBase):
def _make_init_config(self) -> dict:
config: dict = super()._make_init_config()
return config
def setUp(self):
super().setUp()
self.init_decentralized()
# get main prep
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in self._accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": 0
}
self.assertEqual(expected_response, response)
def test_prep_replace_in_term1(self):
"""
scenario 1
when it starts new preps on new term, normal case, while 100 block.
expected :
all new preps have maintained until 100 block because it already passed GRACE_PERIOD
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
tx_list = []
for i in range(PREP_MAIN_PREPS):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + PREP_MAIN_PREPS],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + PREP_MAIN_PREPS],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check whether new PREPS become MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": expected_total_delegated
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
tx_results: ['TransactionResult'] = self.process_confirm_block_tx(
tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[account.address for account in self._accounts[1:PREP_MAIN_PREPS]]
)
# 0: base transaction index
for tx_result in tx_results[1:]:
self.assertEqual("PRepUnregistered(Address)", tx_result.event_logs[0].indexed[0])
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain
block_count = 40
self.make_blocks(to=self._block_height + block_count,
prev_block_generator=accounts[0].address,
prev_block_validators=[
account.address
for account in accounts[1:PREP_MAIN_PREPS]
])
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": expected_total_delegated
}
self.assertEqual(expected_response, response)
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count, response["totalBlocks"])
self.assertEqual(block_count, response["validatedBlocks"])
def test_prep_replace_in_term2(self):
PENALTY_GRACE_PERIOD = 35
BLOCK_VALIDATION_PENALTY_THRESHOLD = 35
IconScoreContext.engine.prep._penalty_imposer._penalty_grace_period = PENALTY_GRACE_PERIOD
IconScoreContext.engine.prep._penalty_imposer._block_validation_penalty_threshold = BLOCK_VALIDATION_PENALTY_THRESHOLD
"""
scenario 2
when it starts new preps on new term, half count (MAIN_PREPS // 2) preps have done to validate block until GRACE_PERIOD.
expected :
half preps are normal case. but another half preps don't validate block(static values are all zero).
so after GRACE_PERIOD will replace half preps.
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
half_prep_count: int = PREP_MAIN_PREPS // 2
test_prep_count: int = PREP_MAIN_PREPS + half_prep_count
tx_list = []
for i in range(test_prep_count):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + test_prep_count],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + test_prep_count],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
tx_results: List['TransactionResult'] = self.process_confirm_block_tx(
tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[account.address for account in self._accounts[1:half_prep_count]]
)
# 0: base transaction index
for tx_result in tx_results[1:]:
self.assertEqual("PRepUnregistered(Address)", tx_result.event_logs[0].indexed[0])
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain until GRACE_PERIOD
block_count1 = PENALTY_GRACE_PERIOD - 1
self.make_blocks(
to=self._block_height + block_count1,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": 1 * test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# change prep!
block_count2 = 1
tx_results: List[List['TransactionResult']] = self.make_blocks(
to=self._block_height + block_count2,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
)
for event_log in tx_results[0][0].event_logs[3:]:
self.assertEqual(PREP_PENALTY_SIGNATURE, event_log.indexed[0])
# new preps vote start!
block_count3 = 1
self.make_blocks(
to=self._block_height + block_count3,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# first new preps vote done!
block_count4 = 1
self.make_blocks(
to=self._block_height + block_count4,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
+
[
account.address for account in accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count]
]
)
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(1, response["totalBlocks"])
self.assertEqual(1, response["validatedBlocks"])
def test_prep_replace_in_term4(self):
PENALTY_GRACE_PERIOD = 35
LOW_PRODUCTIVITY_PENALTY_THRESHOLD = 50
IconScoreContext.engine.prep._penalty_imposer._penalty_grace_period = PENALTY_GRACE_PERIOD
IconScoreContext.engine.prep._penalty_imposer._low_productivity_penalty_threshold = LOW_PRODUCTIVITY_PENALTY_THRESHOLD
"""
scenario 4
when it starts new preps on new term, half count (MAIN_PREPS // 2) preps have done to validate block continuously.
expected :
half preps are normal case. but another half preps don't validate block(static values are all zero).
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
half_prep_count: int = PREP_MAIN_PREPS // 2
test_prep_count: int = PREP_MAIN_PREPS + half_prep_count
tx_list = []
for i in range(test_prep_count):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + test_prep_count],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + test_prep_count],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
self.process_confirm_block_tx(tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[
account.address
for account in self._accounts[1:half_prep_count]
])
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain until GRACE_PERIOD
block_count1 = PENALTY_GRACE_PERIOD - 1
self.make_blocks(
to=self._block_height + block_count1,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1:PREP_MAIN_PREPS]
]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
block_count2 = PENALTY_GRACE_PERIOD
self.make_blocks(
to=self._block_height + block_count2,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1:half_prep_count]
]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
block_count3 = 1
self.make_blocks(
to=self._block_height + block_count3,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1:half_prep_count]
]
)
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
block_count4 = 10
self.make_blocks(
to=self._block_height + block_count4,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
+
[
account.address for account in accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count]
]
)
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3 + block_count4, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3 + block_count4, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count4, response["totalBlocks"])
self.assertEqual(block_count4, response["validatedBlocks"])
def test_prep_replace_in_term5(self):
"""
scenario 1
when it starts new preps on new term, normal case, while 100 block.
expected :
all new preps have maintained until 100 block because it already passed GRACE_PERIOD
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
tx_list = []
for i in range(PREP_MAIN_PREPS):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + PREP_MAIN_PREPS],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + PREP_MAIN_PREPS],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check whether new PREPS become MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": expected_total_delegated
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
tx_results: ['TransactionResult'] = self.process_confirm_block_tx(
tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[account.address for account in self._accounts[1:PREP_MAIN_PREPS]],
prev_block_votes=[[account.address, i % 2 + 1] for i, account in enumerate(self._accounts[1:PREP_MAIN_PREPS])]
)
# 0: base transaction index
for tx_result in tx_results[1:]:
self.assertEqual("PRepUnregistered(Address)", tx_result.event_logs[0].indexed[0])
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain
block_count = 40
self.make_blocks(to=self._block_height + block_count,
prev_block_generator=accounts[0].address,
prev_block_validators=[
account.address
for account in accounts[1:PREP_MAIN_PREPS]
])
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": expected_total_delegated
}
self.assertEqual(expected_response, response)
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count, response["totalBlocks"])
self.assertEqual(block_count, response["validatedBlocks"])
def test_prep_replace_in_term6(self):
PENALTY_GRACE_PERIOD = 35
BLOCK_VALIDATION_PENALTY_THRESHOLD = 35
IconScoreContext.engine.prep._penalty_imposer._penalty_grace_period = PENALTY_GRACE_PERIOD
IconScoreContext.engine.prep._penalty_imposer._block_validation_penalty_threshold = BLOCK_VALIDATION_PENALTY_THRESHOLD
"""
scenario 2
when it starts new preps on new term, half count (MAIN_PREPS // 2) preps have done to validate block until GRACE_PERIOD.
expected :
half preps are normal case. but another half preps don't validate block(static values are all zero).
so after GRACE_PERIOD will replace half preps.
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
half_prep_count: int = PREP_MAIN_PREPS // 2
test_prep_count: int = PREP_MAIN_PREPS + half_prep_count
tx_list = []
for i in range(test_prep_count):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + test_prep_count],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + test_prep_count],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
tx_results: List['TransactionResult'] = self.process_confirm_block_tx(
tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[account.address for account in self._accounts[1:half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(self._accounts[1:half_prep_count])]
+
[[account.address, 0] for account in self._accounts[half_prep_count:PREP_MAIN_PREPS]]
)
# 0: base transaction index
for tx_result in tx_results[1:]:
self.assertEqual("PRepUnregistered(Address)", tx_result.event_logs[0].indexed[0])
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain until GRACE_PERIOD
block_count1 = PENALTY_GRACE_PERIOD - 1
self.make_blocks(
to=self._block_height + block_count1,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1: half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:half_prep_count])]
+
[[account.address, False] for account in accounts[half_prep_count:PREP_MAIN_PREPS]]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": 1 * test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# change prep!
block_count2 = 1
tx_results: List[List['TransactionResult']] = self.make_blocks(
to=self._block_height + block_count2,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1: half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:half_prep_count])]
+
[[account.address, 0] for account in accounts[half_prep_count:PREP_MAIN_PREPS]]
)
for event_log in tx_results[0][0].event_logs[3:]:
self.assertEqual(PREP_PENALTY_SIGNATURE, event_log.indexed[0])
# new preps vote start!
block_count3 = 1
self.make_blocks(
to=self._block_height + block_count3,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1: half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:half_prep_count])]
+
[[account.address, 0] for account in accounts[half_prep_count:PREP_MAIN_PREPS]]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
expected_total_delegated: int = 0
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_total_delegated += 1
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# first new preps vote done!
block_count4 = 1
self.make_blocks(
to=self._block_height + block_count4,
prev_block_generator=accounts[0].address,
prev_block_validators=
[account.address for account in accounts[1: half_prep_count]]
+
[account.address for account in accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1: half_prep_count])]
+
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count])],
)
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(1, response["totalBlocks"])
self.assertEqual(1, response["validatedBlocks"])
def test_prep_replace_in_term7(self):
"""
scenario 3
unregister prep half_prep_count on current preps
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
half_prep_count: int = PREP_MAIN_PREPS // 2
tx_list = []
for i in range(half_prep_count):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_register_prep_tx(from_=accounts[i + half_prep_count])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i],
value=1)
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + half_prep_count],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in self._accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": 0
}
self.assertEqual(expected_response, response)
self.make_blocks_to_end_calculation()
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in self._accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
response: dict = self.get_prep(self._accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain
block_count = 5
self.make_blocks(
to=self._block_height + block_count,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1: half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1: half_prep_count])]
+
[[account.address, 0] for account in self._accounts[0: half_prep_count]]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in self._accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(1, half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count, response["totalBlocks"])
self.assertEqual(block_count, response["validatedBlocks"])
response: dict = self.get_prep(self._accounts[i])
self.assertEqual(block_count, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# block 5 -> change term!
# so you should remove preps unitl 5 times.
# or you have to unregister preps on one time.
count = 2
for i in range(count):
self.unregister_prep(accounts[i])
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
# insert subpreps to unregister prep's position
for account in self._accounts[half_prep_count: half_prep_count + count]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
for account in accounts[count: half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in self._accounts[0: half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 0
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": half_prep_count
}
self.assertEqual(expected_response, response)
def test_prep_replace_in_term8(self):
PENALTY_GRACE_PERIOD = 35
LOW_PRODUCTIVITY_PENALTY_THRESHOLD = 50
IconScoreContext.engine.prep._penalty_imposer._penalty_grace_period = PENALTY_GRACE_PERIOD
IconScoreContext.engine.prep._penalty_imposer._low_productivity_penalty_threshold = LOW_PRODUCTIVITY_PENALTY_THRESHOLD
"""
scenario 4
when it starts new preps on new term, half count (MAIN_PREPS // 2) preps have done to validate block continuously.
expected :
half preps are normal case. but another half preps don't validate block(static values are all zero).
"""
self.distribute_icx(accounts=self._accounts[:PREP_MAIN_PREPS],
init_balance=1 * ICX_IN_LOOP)
accounts: List['EOAAccount'] = self.create_eoa_accounts(PREP_MAIN_AND_SUB_PREPS)
self.distribute_icx(accounts=accounts,
init_balance=3000 * ICX_IN_LOOP)
# replace new PREPS
half_prep_count: int = PREP_MAIN_PREPS // 2
test_prep_count: int = PREP_MAIN_PREPS + half_prep_count
tx_list = []
for i in range(test_prep_count):
tx = self.create_register_prep_tx(from_=accounts[i])
tx_list.append(tx)
tx = self.create_set_stake_tx(from_=accounts[i + test_prep_count],
value=1)
tx_list.append(tx)
tx = self.create_set_delegation_tx(from_=accounts[i + test_prep_count],
origin_delegations=[
(
accounts[i],
1
)
])
tx_list.append(tx)
self.process_confirm_block_tx(tx_list)
self.make_blocks_to_end_calculation()
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
tx_list: list = []
# unregister prev_main_preps
for account in self._accounts[:PREP_MAIN_PREPS]:
tx: dict = self.create_unregister_prep_tx(from_=account)
tx_list.append(tx)
self.process_confirm_block_tx(
tx_list=tx_list,
prev_block_generator=self._accounts[0].address,
prev_block_validators=[account.address for account in self._accounts[1: half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(self._accounts[1: half_prep_count])]
+
[[account.address, 0] for account in self._accounts[half_prep_count: PREP_MAIN_PREPS]]
)
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
# maintain until GRACE_PERIOD
block_count1 = PENALTY_GRACE_PERIOD - 1
self.make_blocks(
to=self._block_height + block_count1,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1:PREP_MAIN_PREPS]],
prev_block_votes=[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:PREP_MAIN_PREPS])]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:PREP_MAIN_PREPS]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count
}
self.assertEqual(expected_response, response)
for i in range(PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
block_count2 = PENALTY_GRACE_PERIOD
self.make_blocks(
to=self._block_height + block_count2,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1:half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:half_prep_count])]
+
[[account.address, 0] for account in accounts[half_prep_count:PREP_MAIN_PREPS]]
)
# check new PREPS to MAIN_PREPS
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
block_count3 = 1
self.make_blocks(
to=self._block_height + block_count3,
prev_block_generator=accounts[0].address,
prev_block_validators=[account.address for account in accounts[1:half_prep_count]],
prev_block_votes=
[[account.address, i % 2 + 1] for i, account in enumerate(accounts[1:half_prep_count])]
+
[[account.address, 0] for account in accounts[half_prep_count:PREP_MAIN_PREPS]]
)
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(0, response["totalBlocks"])
self.assertEqual(0, response["validatedBlocks"])
block_count4 = 10
self.make_blocks(
to=self._block_height + block_count4,
prev_block_generator=accounts[0].address,
prev_block_validators=
[
account.address for account in accounts[1: half_prep_count]
]
+
[
account.address for account in accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count]
],
prev_block_votes=
[
[account.address, i % 2 + 1] for i, account in enumerate(accounts[1: half_prep_count])
]
+
[
[account.address, i % 2 + 1] for i, account in enumerate(accounts[PREP_MAIN_PREPS: PREP_MAIN_PREPS + half_prep_count])
]
)
response: dict = self.get_main_prep_list()
expected_preps: list = []
for account in accounts[:half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
for account in accounts[PREP_MAIN_PREPS:PREP_MAIN_PREPS + half_prep_count]:
expected_preps.append({
'address': account.address,
'delegated': 1
})
expected_response: dict = {
"preps": expected_preps,
"totalDelegated": test_prep_count - half_prep_count
}
self.assertEqual(expected_response, response)
for i in range(half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3 + block_count4, response["totalBlocks"])
self.assertEqual(block_count1 + block_count2 + block_count3 + block_count4, response["validatedBlocks"])
for i in range(half_prep_count, PREP_MAIN_PREPS):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count1 + block_count2 + block_count3, response["totalBlocks"])
self.assertEqual(block_count1, response["validatedBlocks"])
for i in range(PREP_MAIN_PREPS, PREP_MAIN_PREPS + half_prep_count):
response: dict = self.get_prep(accounts[i])
self.assertEqual(block_count4, response["totalBlocks"])
self.assertEqual(block_count4, response["validatedBlocks"])
| 41.697156 | 134 | 0.587137 | 5,846 | 54,248 | 5.143859 | 0.041225 | 0.04669 | 0.054903 | 0.043597 | 0.961391 | 0.957035 | 0.956835 | 0.955106 | 0.952878 | 0.950085 | 0 | 0.01291 | 0.328897 | 54,248 | 1,300 | 135 | 41.729231 | 0.81308 | 0.045089 | 0 | 0.841951 | 0 | 0 | 0.049363 | 0.001988 | 0 | 0 | 0 | 0 | 0.116098 | 1 | 0.00878 | false | 0 | 0.005854 | 0 | 0.016585 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
7b368adbbf348efb19b4942330c61374f8d048c7 | 21,837 | py | Python | sdk/python/pulumi_gcp/folder/iam_binding.py | sisisin/pulumi-gcp | af6681d70ea457843409110c1324817fe55f68ad | [
"ECL-2.0",
"Apache-2.0"
] | 121 | 2018-06-18T19:16:42.000Z | 2022-03-31T06:06:48.000Z | sdk/python/pulumi_gcp/folder/iam_binding.py | sisisin/pulumi-gcp | af6681d70ea457843409110c1324817fe55f68ad | [
"ECL-2.0",
"Apache-2.0"
] | 492 | 2018-06-22T19:41:03.000Z | 2022-03-31T15:33:53.000Z | sdk/python/pulumi_gcp/folder/iam_binding.py | sisisin/pulumi-gcp | af6681d70ea457843409110c1324817fe55f68ad | [
"ECL-2.0",
"Apache-2.0"
] | 43 | 2018-06-19T01:43:13.000Z | 2022-03-23T22:43:37.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['IAMBindingArgs', 'IAMBinding']
@pulumi.input_type
class IAMBindingArgs:
def __init__(__self__, *,
folder: pulumi.Input[str],
members: pulumi.Input[Sequence[pulumi.Input[str]]],
role: pulumi.Input[str],
condition: Optional[pulumi.Input['IAMBindingConditionArgs']] = None):
"""
The set of arguments for constructing a IAMBinding resource.
:param pulumi.Input[str] folder: The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
:param pulumi.Input[Sequence[pulumi.Input[str]]] members: An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
:param pulumi.Input[str] role: The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
pulumi.set(__self__, "folder", folder)
pulumi.set(__self__, "members", members)
pulumi.set(__self__, "role", role)
if condition is not None:
pulumi.set(__self__, "condition", condition)
@property
@pulumi.getter
def folder(self) -> pulumi.Input[str]:
"""
The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
"""
return pulumi.get(self, "folder")
@folder.setter
def folder(self, value: pulumi.Input[str]):
pulumi.set(self, "folder", value)
@property
@pulumi.getter
def members(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:
"""
An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
"""
return pulumi.get(self, "members")
@members.setter
def members(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]):
pulumi.set(self, "members", value)
@property
@pulumi.getter
def role(self) -> pulumi.Input[str]:
"""
The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
return pulumi.get(self, "role")
@role.setter
def role(self, value: pulumi.Input[str]):
pulumi.set(self, "role", value)
@property
@pulumi.getter
def condition(self) -> Optional[pulumi.Input['IAMBindingConditionArgs']]:
return pulumi.get(self, "condition")
@condition.setter
def condition(self, value: Optional[pulumi.Input['IAMBindingConditionArgs']]):
pulumi.set(self, "condition", value)
@pulumi.input_type
class _IAMBindingState:
def __init__(__self__, *,
condition: Optional[pulumi.Input['IAMBindingConditionArgs']] = None,
etag: Optional[pulumi.Input[str]] = None,
folder: Optional[pulumi.Input[str]] = None,
members: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
role: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering IAMBinding resources.
:param pulumi.Input[str] etag: (Computed) The etag of the folder's IAM policy.
:param pulumi.Input[str] folder: The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
:param pulumi.Input[Sequence[pulumi.Input[str]]] members: An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
:param pulumi.Input[str] role: The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
if condition is not None:
pulumi.set(__self__, "condition", condition)
if etag is not None:
pulumi.set(__self__, "etag", etag)
if folder is not None:
pulumi.set(__self__, "folder", folder)
if members is not None:
pulumi.set(__self__, "members", members)
if role is not None:
pulumi.set(__self__, "role", role)
@property
@pulumi.getter
def condition(self) -> Optional[pulumi.Input['IAMBindingConditionArgs']]:
return pulumi.get(self, "condition")
@condition.setter
def condition(self, value: Optional[pulumi.Input['IAMBindingConditionArgs']]):
pulumi.set(self, "condition", value)
@property
@pulumi.getter
def etag(self) -> Optional[pulumi.Input[str]]:
"""
(Computed) The etag of the folder's IAM policy.
"""
return pulumi.get(self, "etag")
@etag.setter
def etag(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "etag", value)
@property
@pulumi.getter
def folder(self) -> Optional[pulumi.Input[str]]:
"""
The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
"""
return pulumi.get(self, "folder")
@folder.setter
def folder(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "folder", value)
@property
@pulumi.getter
def members(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
"""
return pulumi.get(self, "members")
@members.setter
def members(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "members", value)
@property
@pulumi.getter
def role(self) -> Optional[pulumi.Input[str]]:
"""
The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
return pulumi.get(self, "role")
@role.setter
def role(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "role", value)
class IAMBinding(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
condition: Optional[pulumi.Input[pulumi.InputType['IAMBindingConditionArgs']]] = None,
folder: Optional[pulumi.Input[str]] = None,
members: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
role: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Allows creation and management of a single binding within IAM policy for
an existing Google Cloud Platform folder.
> **Note:** This resource _must not_ be used in conjunction with
`folder.IAMPolicy` or they will fight over what your policy
should be.
> **Note:** On create, this resource will overwrite members of any existing roles.
Use `pulumi import` and inspect the output to ensure
your existing members are preserved.
## Example Usage
```python
import pulumi
import pulumi_gcp as gcp
department1 = gcp.organizations.Folder("department1",
display_name="Department 1",
parent="organizations/1234567")
admin = gcp.folder.IAMBinding("admin",
folder=department1.name,
role="roles/editor",
members=["user:alice@gmail.com"])
```
## Import
IAM binding imports use space-delimited identifiers; first the resource in question and then the role.
These bindings can be imported using the `folder` and role, e.g.
```sh
$ pulumi import gcp:folder/iAMBinding:IAMBinding viewer "folder-name roles/viewer"
```
-> **Custom Roles**If you're importing a IAM binding with a custom role, make sure to use the
full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] folder: The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
:param pulumi.Input[Sequence[pulumi.Input[str]]] members: An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
:param pulumi.Input[str] role: The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: IAMBindingArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Allows creation and management of a single binding within IAM policy for
an existing Google Cloud Platform folder.
> **Note:** This resource _must not_ be used in conjunction with
`folder.IAMPolicy` or they will fight over what your policy
should be.
> **Note:** On create, this resource will overwrite members of any existing roles.
Use `pulumi import` and inspect the output to ensure
your existing members are preserved.
## Example Usage
```python
import pulumi
import pulumi_gcp as gcp
department1 = gcp.organizations.Folder("department1",
display_name="Department 1",
parent="organizations/1234567")
admin = gcp.folder.IAMBinding("admin",
folder=department1.name,
role="roles/editor",
members=["user:alice@gmail.com"])
```
## Import
IAM binding imports use space-delimited identifiers; first the resource in question and then the role.
These bindings can be imported using the `folder` and role, e.g.
```sh
$ pulumi import gcp:folder/iAMBinding:IAMBinding viewer "folder-name roles/viewer"
```
-> **Custom Roles**If you're importing a IAM binding with a custom role, make sure to use the
full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`.
:param str resource_name: The name of the resource.
:param IAMBindingArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(IAMBindingArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
condition: Optional[pulumi.Input[pulumi.InputType['IAMBindingConditionArgs']]] = None,
folder: Optional[pulumi.Input[str]] = None,
members: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
role: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = IAMBindingArgs.__new__(IAMBindingArgs)
__props__.__dict__["condition"] = condition
if folder is None and not opts.urn:
raise TypeError("Missing required property 'folder'")
__props__.__dict__["folder"] = folder
if members is None and not opts.urn:
raise TypeError("Missing required property 'members'")
__props__.__dict__["members"] = members
if role is None and not opts.urn:
raise TypeError("Missing required property 'role'")
__props__.__dict__["role"] = role
__props__.__dict__["etag"] = None
super(IAMBinding, __self__).__init__(
'gcp:folder/iAMBinding:IAMBinding',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
condition: Optional[pulumi.Input[pulumi.InputType['IAMBindingConditionArgs']]] = None,
etag: Optional[pulumi.Input[str]] = None,
folder: Optional[pulumi.Input[str]] = None,
members: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
role: Optional[pulumi.Input[str]] = None) -> 'IAMBinding':
"""
Get an existing IAMBinding resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] etag: (Computed) The etag of the folder's IAM policy.
:param pulumi.Input[str] folder: The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
:param pulumi.Input[Sequence[pulumi.Input[str]]] members: An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
:param pulumi.Input[str] role: The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _IAMBindingState.__new__(_IAMBindingState)
__props__.__dict__["condition"] = condition
__props__.__dict__["etag"] = etag
__props__.__dict__["folder"] = folder
__props__.__dict__["members"] = members
__props__.__dict__["role"] = role
return IAMBinding(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def condition(self) -> pulumi.Output[Optional['outputs.IAMBindingCondition']]:
return pulumi.get(self, "condition")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[str]:
"""
(Computed) The etag of the folder's IAM policy.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def folder(self) -> pulumi.Output[str]:
"""
The resource name of the folder the policy is attached to. Its format is folders/{folder_id}.
"""
return pulumi.get(self, "folder")
@property
@pulumi.getter
def members(self) -> pulumi.Output[Sequence[str]]:
"""
An array of identities that will be granted the privilege in the `role`.
Each entry can have one of the following values:
* **user:{emailid}**: An email address that is associated with a specific Google account. For example, alice@gmail.com.
* **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
* **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
* **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
* For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
"""
return pulumi.get(self, "members")
@property
@pulumi.getter
def role(self) -> pulumi.Output[str]:
"""
The role that should be applied. Only one
`folder.IAMBinding` can be used per role. Note that custom roles must be of the format
`[projects|organizations]/{parent-name}/roles/{role-name}`.
"""
return pulumi.get(self, "role")
| 49.517007 | 173 | 0.646151 | 2,688 | 21,837 | 5.146205 | 0.09375 | 0.056459 | 0.047567 | 0.03188 | 0.859683 | 0.833225 | 0.807851 | 0.790212 | 0.783272 | 0.776983 | 0 | 0.001834 | 0.250904 | 21,837 | 440 | 174 | 49.629545 | 0.843807 | 0.537024 | 0 | 0.579487 | 1 | 0 | 0.094074 | 0.030666 | 0 | 0 | 0 | 0 | 0 | 1 | 0.153846 | false | 0.005128 | 0.035897 | 0.015385 | 0.282051 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
7b481d0acf3d5b7ecaf78448b675283b3704c9dc | 16,662 | py | Python | tests/dhcpv4/process/test_v4_decline.py | shawnmullaney/forge | aaaef0a0645f73d24666aab6a400f3604e753aac | [
"0BSD"
] | null | null | null | tests/dhcpv4/process/test_v4_decline.py | shawnmullaney/forge | aaaef0a0645f73d24666aab6a400f3604e753aac | [
"0BSD"
] | null | null | null | tests/dhcpv4/process/test_v4_decline.py | shawnmullaney/forge | aaaef0a0645f73d24666aab6a400f3604e753aac | [
"0BSD"
] | null | null | null | """DHCPv4 address decline process"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import srv_msg
import srv_control
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_success_long_decline_period():
# address in decline period
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.set_conf_parameter_global('decline-probation-period', '3600')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_copy_option('server_id')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_success_short_decline_period():
# address in decline period
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.set_conf_parameter_global('decline-probation-period', '2')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_copy_option('server_id')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
srv_msg.forge_sleep('3', 'seconds')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:44')
srv_msg.client_does_include_with_value('client_id', '00010203040144')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_fail_without_serverid():
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
# @v4 @dhcp4 @decline
# Scenario: v4.decline.fail-without-serverid
#
# Test Setup:
# Server is configured with 192.168.50.0/24 subnet with 192.168.50.1-192.168.50.1 pool.
# Send server configuration using SSH and config-file.
# DHCP server is started.
#
# Test Procedure:
# Client sends DISCOVER message.
#
# Pass Criteria:
# Server MUST respond with OFFER message.
# Response MUST contain yiaddr 192.168.50.1.
#
# Test Procedure:
# Client copies server_id option from received message.
# Client adds to the message requested_addr with value 192.168.50.1.
# Client sends REQUEST message.
#
# Pass Criteria:
# Server MUST respond with ACK message.
# Response MUST contain yiaddr 192.168.50.1.
#
# Test Procedure:
# Client sets ciaddr value to 0.0.0.0.
# Client adds to the message requested_addr with value 192.168.50.1.
# Client sends DECLINE message.
#
# Pass Criteria:
# Server MUST NOT respond.
#
# Test Procedure:
# Client sets chaddr value to 00:00:00:00:00:11.
# Client adds to the message client_id with value 00010203040111.
# Client sends DISCOVER message.
#
# Pass Criteria:
# Server MUST respond with NAK message.
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_fail_without_requested_ip_address():
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_copy_option('server_id')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
# client should get back this address because it's not in declined period
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_fail_client_id_not_included():
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
srv_msg.response_check_include_option('Response', None, '61')
srv_msg.response_check_option_content('Response', '61', None, 'value', '00010203040122')
misc.test_procedure()
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
srv_msg.response_check_include_option('Response', None, '61')
srv_msg.response_check_option_content('Response', '61', None, 'value', '00010203040122')
misc.test_procedure()
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040999')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:22')
srv_msg.client_does_include_with_value('client_id', '00010203040122')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
srv_msg.response_check_include_option('Response', None, '61')
srv_msg.response_check_option_content('Response', '61', None, 'value', '00010203040122')
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_fail_different_client_id():
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
srv_msg.response_check_include_option('Response', None, '61')
srv_msg.response_check_option_content('Response', '61', None, 'value', '00010203040111')
misc.test_procedure()
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
srv_msg.response_check_include_option('Response', None, '61')
srv_msg.response_check_option_content('Response', '61', None, 'value', '00010203040111')
misc.test_procedure()
srv_msg.client_does_include_with_value('client_id', '00010203040666')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_copy_option('server_id')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040999')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'NAK')
@pytest.mark.v4
@pytest.mark.dhcp4
@pytest.mark.decline
def test_v4_decline_fail_different_chaddr():
misc.test_setup()
srv_control.config_srv_subnet('192.168.50.0/24', '192.168.50.1-192.168.50.1')
srv_control.build_and_send_config_files('SSH', 'config-file')
srv_control.start_srv('DHCP', 'started')
misc.test_procedure()
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'OFFER')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_copy_option('server_id')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('REQUEST')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'ACK')
srv_msg.response_check_content('Response', None, 'yiaddr', '192.168.50.1')
misc.test_procedure()
srv_msg.client_copy_option('server_id')
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_sets_value('Client', 'ciaddr', '0.0.0.0')
srv_msg.client_does_include_with_value('requested_addr', '192.168.50.1')
srv_msg.client_send_msg('DECLINE')
misc.pass_criteria()
srv_msg.send_dont_wait_for_message()
misc.test_procedure()
srv_msg.client_sets_value('Client', 'chaddr', '00:00:00:00:00:11')
srv_msg.client_does_include_with_value('client_id', '00010203040111')
srv_msg.client_send_msg('DISCOVER')
misc.pass_criteria()
srv_msg.send_wait_for_message('MUST', None, 'NAK')
| 38.041096 | 92 | 0.728364 | 2,529 | 16,662 | 4.434955 | 0.050217 | 0.096291 | 0.126248 | 0.038516 | 0.947486 | 0.938213 | 0.937143 | 0.933577 | 0.931972 | 0.928406 | 0 | 0.097744 | 0.127476 | 16,662 | 437 | 93 | 38.128146 | 0.673752 | 0.074721 | 0 | 0.944262 | 0 | 0 | 0.230529 | 0.01451 | 0 | 0 | 0 | 0 | 0 | 1 | 0.022951 | true | 0.104918 | 0.013115 | 0 | 0.036066 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 9 |
7b533066d3199c8a59bdf2d9b14867d139a57e71 | 44,444 | py | Python | metric_visualizer/metric_visualizer.py | yangheng95/MetricVisualizer | 9522ce6b56ad554b1e19b0247054aec5077bd9c0 | [
"MIT"
] | 2 | 2022-02-12T16:08:22.000Z | 2022-02-21T09:39:09.000Z | metric_visualizer/metric_visualizer.py | yangheng95/metric_visualizer | 9522ce6b56ad554b1e19b0247054aec5077bd9c0 | [
"MIT"
] | null | null | null | metric_visualizer/metric_visualizer.py | yangheng95/metric_visualizer | 9522ce6b56ad554b1e19b0247054aec5077bd9c0 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# file: metric_visualizer.py
# time: 03/02/2022
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
import os.path
import pickle
import random
import shlex
import subprocess
from collections import OrderedDict
from functools import wraps
import time
import matplotlib.colors
import numpy as np
import tikzplotlib
from findfile import find_cwd_files
from matplotlib import pyplot as plt
from scipy.stats import iqr, wilcoxon
from tabulate import tabulate
from metric_visualizer import __version__
retry_count = 100
def legend_without_duplicate_labels(ax):
handles, labels = ax.get_legend_handles_labels()
unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
ax.legend(*zip(*unique))
def exception_handle(f, disable=False):
@wraps(f)
def decorated(*args, **kwargs):
if disable:
return f(*args, **kwargs)
else:
try:
return f(*args, **kwargs)
except Exception as e:
print('Exception <{}> found in function <{}>'.format(e, f))
return decorated
class MetricVisualizer:
COLORS_DICT = matplotlib.colors.XKCD_COLORS
COLORS_DICT.update(matplotlib.colors.CSS4_COLORS)
COLORS = list(COLORS_DICT.values())
MARKERS = [".", "o", "+", "P",
"x", "X", "D", "d",
]
HATCHES = ['/', '\\', '|', '-', '+', 'x',
'o', 'O', '.', '*']
box_plot_tex_template = r"""
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usepackage{caption}
\usetikzlibrary{intersections}
\usepackage{helvet}
\usepackage[eulergreek]{sansmath}
\usepackage{amsfonts,amssymb,amsmath,amsthm,amsopn} % math related
\begin{document}
\pagestyle{empty}
\pgfplotsset{ compat=1.3,every axis/.append style={
grid = major,
thick,
font=\normalsize,
xtick={$xtick$},
xticklabels={$xticklabel$},
ylabel = {$ylabel$},
xlabel = {$xlabel$},
x tick label style={rotate=0,anchor=north},
y tick label style={rotate=0,anchor=east},
xticklabel shift=$xtickshift$pt,
yticklabel shift=$ytickshift$pt,
xlabel shift=$xlabelshift$pt,
ylabel shift=$ylabelshift$pt,
line width = 1pt,
tick style = {line width = 0.8pt}}}
\pgfplotsset{every plot/.append style={thin}}
\begin{figure}
\centering
$tikz_code$
\end{figure}
\end{document}
"""
bar_plot_tex_template = r"""
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usepackage{caption}
\usetikzlibrary{intersections}
\usepackage{helvet}
\usepackage[eulergreek]{sansmath}
\usepackage{amsfonts,amssymb,amsmath,amsthm,amsopn} % math related
\begin{document}
\pagestyle{empty}
\pgfplotsset{ compat=1.3,every axis/.append style={
grid = major,
thick,
font=\normalsize,
xtick={$xtick$},
xticklabels={$xticklabel$},
ylabel = {$ylabel$},
xlabel = {$xlabel$},
x tick label style={rotate=0,anchor=north},
y tick label style={rotate=0,anchor=east},
xticklabel shift=$xtickshift$pt,
yticklabel shift=$ytickshift$pt,
xlabel shift=$xlabelshift$pt,
ylabel shift=$ylabelshift$pt,
line width = 1pt,
tick style = {line width = 0.8pt}}}
\pgfplotsset{every plot/.append style={thin}}
\begin{figure}
\centering
\usetikzlibrary{patterns}
$tikz_code$
\end{figure}
\end{document}
"""
violin_plot_tex_template = r"""
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usepackage{caption}
\usetikzlibrary{intersections}
\usepackage{helvet}
\usepackage[eulergreek]{sansmath}
\usepackage{amsfonts,amssymb,amsmath,amsthm,amsopn} % math related
\begin{document}
\pagestyle{empty}
\pgfplotsset{ compat=1.3,every axis/.append style={
grid = major,
thick,
font=\normalsize,
xticklabels={$xticklabel$},
xtick={$xtick$},
ylabel = {$ylabel$},
xlabel = {$xlabel$},
x tick label style={rotate=0,anchor=north},
y tick label style={rotate=0,anchor=east},
xticklabel shift=$xtickshift$pt,
yticklabel shift=$ytickshift$pt,
xlabel shift=$xlabelshift$pt,
ylabel shift=$ylabelshift$pt,
line width = 1pt,
tick style = {line width = 0.8pt}}}
\pgfplotsset{every plot/.append style={thin}}
\begin{figure}
\centering
$tikz_code$
\end{figure}
\end{document}
"""
traj_plot_tex_template = r"""
\documentclass{article}
\usepackage{pgfplots}
\usepackage{tikz}
\usetikzlibrary{intersections}
\usepackage{helvet}
\usepackage[eulergreek]{sansmath}
\begin{document}
\pagestyle{empty}
\pgfplotsset{every axis/.append style={
grid = major,
thick,
font=\normalsize,
xtick={$xtick$},
xticklabels={$xticklabel$},
xlabel = {$xlabel$},
ylabel = {$ylabel$},
x tick label style={rotate=0,anchor=north},
y tick label style={rotate=0,anchor=east},
xticklabel shift=$xtickshift$pt,
yticklabel shift=$ytickshift$pt,
xlabel shift=$xlabelshift$pt,
ylabel shift=$ylabelshift$pt,
line width = 1pt,
tick style = {line width = 0.8pt}}
}
\pgfplotsset{every plot/.append style={very thin}}
\begin{figure}
\centering
$tikz_code$
\end{figure}
\end{document}
"""
def set_box_plot_tex_template(self, box_plot_tex_template):
self.box_plot_tex_template = box_plot_tex_template
def set_bar_plot_tex_template(self, violin_plot_tex_template):
self.violin_plot_tex_template = violin_plot_tex_template
def set_violin_plot_tex_template(self, violin_plot_tex_template):
self.violin_plot_tex_template = violin_plot_tex_template
def set_traj_plot_tex_template(self, traj_plot_tex_template):
self.traj_plot_tex_template = traj_plot_tex_template
def __init__(self, name=None, trial_tag='', trial_tag_list=None, metric_dict=None):
"""
Used for plotting, e.g.,
'Metric1': {
'trial-0': [77.06, 2.52, 35.14, 3.04, 77.29, 3.8, 57.4, 38.52, 60.36, 22.45],
'train-1': [64.53, 58.33, 97.89, 68.12, 88.6, 60.33, 70.99, 75.91, 42.49, 15.03],
'train-2': [97.74, 86.05, 41.34, 81.66, 75.08, 1.76, 94.63, 27.26, 47.11, 42.06],
},
'Metric2': {
'trial-0': [111.5, 105.61, 179.08, 167.25, 181.85, 152.75, 194.82, 130.86, 108.51, 151.44] ,
'train-1': [187.58, 106.35, 134.22, 167.68, 188.24, 196.54, 154.21, 193.71, 183.34, 150.18],
'train-2': [159.24, 148.44, 119.49, 160.24, 169.6, 133.27, 129.36, 180.36, 165.24, 152.38],
}
:param metric_dict: If you want to plot figure, it is recommended to add multiple trial experiments. In these trial, the experimental results
are comparative, e.g., just minor different in these experiments.
"""
if not trial_tag:
self.trial_tag = 'Trial'
else:
self.trial_tag = trial_tag
if not trial_tag_list:
self.trial_tag_list = []
else:
self.trial_tag_list = [str(t) for t in trial_tag_list]
self.version = __version__
self.name = name
if metric_dict is None:
self.metrics = OrderedDict(
{
# 'Metric1': {
# 'trial-0': [80.41, 79.78, 81.03, 80.09, 79.62, 80.56, 80.88, 79.94, 79.47, 79.78, 80.72, 79.78, 81.35, 80.88, 81.03],
# 'train-1': [80.41, 79.78, 81.03, 80.09, 79.62, 80.56, 80.88, 79.94, 79.47, 79.78, 80.72, 79.78, 81.35, 80.88, 81.03],
# 'train-2': [80.41, 79.78, 81.03, 80.09, 79.62, 80.56, 80.88, 79.94, 79.47, 79.78, 80.72, 79.78, 81.35, 80.88, 81.03],
# },
# 'Metric2': {
# 'trial-0': [76.79, 75.49, 77.92, 77.21, 75.63, 76.96, 77.44, 76.26, 76.35, 76.12, 76.12, 76.78, 75.64, 77.31, 73.79],
# 'train-1': [76.79, 75.49, 77.92, 77.21, 75.63, 76.96, 77.44, 76.26, 76.35, 76.12, 76.12, 76.78, 75.64, 77.31, 73.79],
# 'train-2': [76.79, 75.49, 77.92, 77.21, 75.63, 76.96, 77.44, 76.26, 76.35, 76.12, 76.12, 76.78, 75.64, 77.31, 73.79],
# }
})
else:
self.metrics = metric_dict
self.trial_id = 0
self.dump_pointer = None
def next_trial(self):
self.trial_id += 1
self.dump()
def add_metric(self, metric_name='Accuracy', value=0):
if metric_name in self.metrics:
if 'trial-{}'.format(self.trial_id) not in self.metrics[metric_name]:
self.metrics[metric_name]['trial-{}'.format(self.trial_id)] = [value]
else:
self.metrics[metric_name]['trial-{}'.format(self.trial_id)].append(value)
else:
self.metrics[metric_name] = {'trial-{}'.format(self.trial_id): [value]}
def traj_plot_by_metric(self, save_name=None, **kwargs):
plot_metrics = self.transpose()
self.traj_plot(plot_metrics, save_name, **kwargs)
def box_plot_by_metric(self, save_name=None, **kwargs):
plot_metrics = self.transpose()
self.box_plot(plot_metrics, save_name, **kwargs)
def avg_bar_plot_by_metric(self, save_path=None, **kwargs):
plot_metrics = self.transpose()
self.avg_bar_plot(plot_metrics, save_path, **kwargs)
def sum_bar_plot_by_metric(self, save_name=None, **kwargs):
plot_metrics = self.transpose()
self.sum_bar_plot(plot_metrics, save_name, **kwargs)
def violin_plot_by_metric(self, save_name=None, **kwargs):
plot_metrics = self.transpose()
self.violin_plot(plot_metrics, save_name, **kwargs)
def traj_plot_by_trial(self, save_name=None, **kwargs):
plot_metrics = self.metrics
self.traj_plot(plot_metrics, save_name, **kwargs)
def box_plot_by_trial(self, save_name=None, **kwargs):
plot_metrics = self.metrics
self.box_plot(plot_metrics, save_name, **kwargs)
def avg_bar_plot_by_trial(self, save_name=None, **kwargs):
plot_metrics = self.metrics
self.avg_bar_plot(plot_metrics, save_name, **kwargs)
def sum_bar_plot_by_trial(self, save_name=None, **kwargs):
plot_metrics = self.metrics
self.sum_bar_plot(plot_metrics, save_name, **kwargs)
def violin_plot_by_trial(self, save_name=None, **kwargs):
plot_metrics = self.metrics
self.violin_plot(plot_metrics, save_name, **kwargs)
@exception_handle
def traj_plot(self, plot_metrics=None, save_name=None, **kwargs):
markers = self.MARKERS[:]
colors = self.COLORS[:]
hatches = self.HATCHES[:]
if isinstance(plot_metrics, str): # warning for early version (<0.4.0)
print('Please do not use this function directly for version (<0.4.0)')
if not plot_metrics:
plot_metrics = self.metrics
alpha = kwargs.pop('alpha', 0.1)
legend_loc = kwargs.pop('legend_loc', 2)
markersize = kwargs.pop('markersize', 3)
xlabel = kwargs.pop('xlabel', None)
xticks = kwargs.pop('xticks', None)
ylabel = kwargs.pop('ylabel', None)
yticks = kwargs.pop('yticks', None)
linewidth = kwargs.pop('linewidth', 0.5)
hatches = kwargs.pop('hatches', hatches)
xrotation = kwargs.pop('xrotation', 0)
yrotation = kwargs.pop('yrotation', 0)
xlabelshift = kwargs.pop('xlabelshift', 1)
ylabelshift = kwargs.pop('ylabelshift', 1)
xtickshift = kwargs.pop('xtickshift', 1)
ytickshift = kwargs.pop('ytickshift', 1)
minorticks_on = kwargs.pop('minorticks_on', False)
traj_parts = []
legend_labels = []
for metric_name in plot_metrics.keys():
metrics = plot_metrics[metric_name]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if self.trial_tag_list:
print('Unequal length of trial_tag_list and trial_num:', self.trial_tag_list, '<->', list(metrics.keys()))
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
ax = plt.subplot()
y = np.array([metrics[metric_name] for metric_name in metrics])
x = np.array([[i for i, label in enumerate(metrics)] for _ in range(y.shape[1])])
# y_avg = np.median(y, axis=1)
y_avg = np.average(y, axis=1)
y_std = np.std(y, axis=1)
marker = random.choice(markers)
markers.remove(marker)
color = random.choice(colors)
colors.remove(color)
if kwargs.pop('avg_point', True):
avg_point = ax.plot(x[0],
y_avg,
marker=marker,
color=color,
markersize=markersize,
linewidth=linewidth
)
if kwargs.pop('traj_fill', True):
traj_fill = plt.subplot().fill_between(x[0],
y_avg - y_std,
y_avg + y_std,
color=color,
alpha=alpha
)
if kwargs.pop('traj_point', True):
# color = random.choice(colors)
# colors.remove(color)
traj_point = plt.subplot().scatter(x,
y,
marker=marker,
color=color
)
tex_xtick = list(trial_tag_list) if xticks is None else xticks
traj_parts.append(avg_point[0])
legend_labels.append(metric_name)
plt.legend(traj_parts, legend_labels, loc=legend_loc)
plt.grid()
if minorticks_on:
plt.minorticks_on()
plt.xticks(rotation=xrotation)
plt.yticks(rotation=yrotation)
plt.xlabel('' if xlabel is None else xlabel)
plt.ylabel(', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
if save_name:
global retry_count
try:
tikz_code = tikzplotlib.get_tikz_code()
except ValueError as e:
if retry_count > 0:
retry_count -= 1
self.traj_plot(save_name, **kwargs)
else:
raise RuntimeError(e)
tex_src = self.traj_plot_tex_template.replace('$tikz_code$', tikz_code)
tex_src = tex_src.replace('$xticklabel$', ','.join(str(x) for x in tex_xtick))
tex_src = tex_src.replace('$xtick$', ','.join([str(x) for x in range(len(tex_xtick))]))
tex_src = tex_src.replace('$xlabel$', ', '.join(list(trial_tag_list)) if xlabel is None else xlabel)
tex_src = tex_src.replace('$ylabel$', ', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
tex_src = tex_src.replace('$xtickshift$', str(xtickshift))
tex_src = tex_src.replace('$ytickshift$', str(ytickshift))
tex_src = tex_src.replace('$xlabelshift$', str(xlabelshift))
tex_src = tex_src.replace('$ylabelshift$', str(ylabelshift))
# tex_src = fix_tex_traj_plot_legend(tex_src, self.metrics)
plt.savefig(save_name + '.pdf', dpi=1000)
plt.show()
fout = open((save_name + '_metric_traj_plot.tikz.tex').lstrip('_'), mode='w', encoding='utf8')
fout.write(tex_src)
fout.close()
texs = find_cwd_files(['.tex', save_name, '_metric_traj_plot'])
for pdf in texs:
cmd = 'pdflatex "{}" '.format(pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
pdfs = find_cwd_files(['.pdf', save_name, '_metric_traj_plot'], exclude_key='crop')
for pdf in pdfs:
cmd = 'pdfcrop "{}" "{}" '.format(pdf, pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
for f in find_cwd_files(['.aux', save_name]) + find_cwd_files(['.log', save_name]) + find_cwd_files(['crop', save_name]):
os.remove(f)
print('Tikz plot saved at ', find_cwd_files(['_metric_traj_plot', save_name], exclude_key='crop'))
else:
plt.show()
print('Traj plot finished')
plt.close()
@exception_handle
def box_plot(self, plot_metrics=None, save_name=None, **kwargs):
markers = self.MARKERS[:]
colors = self.COLORS[:]
hatches = self.HATCHES[:]
if isinstance(plot_metrics, str): # warning for early version (<0.4.0)
print('Please do not use this function directly for version (<0.4.0)')
if not plot_metrics:
plot_metrics = self.metrics
ax = plt.subplot()
alpha = kwargs.pop('alpha', 1)
markersize = kwargs.pop('markersize', 3)
xlabel = kwargs.pop('xlabel', None)
xticks = kwargs.pop('xticks', None)
ylabel = kwargs.pop('ylabel', None)
yticks = kwargs.pop('yticks', None)
legend_loc = kwargs.pop('legend_loc', 2)
hatches = kwargs.pop('hatches', hatches)
xrotation = kwargs.pop('xrotation', 0)
yrotation = kwargs.pop('yrotation', 0)
xlabelshift = kwargs.pop('xlabelshift', 1)
ylabelshift = kwargs.pop('ylabelshift', 1)
xtickshift = kwargs.pop('xtickshift', 1)
ytickshift = kwargs.pop('ytickshift', 1)
linewidth = kwargs.pop('linewidth', 3)
widths = kwargs.pop('widths', 0.9)
minorticks_on = kwargs.pop('minorticks_on', False)
box_parts = []
legend_labels = []
for metric_name in plot_metrics.keys():
metrics = plot_metrics[metric_name]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if self.trial_tag_list:
print('Unequal length of trial_tag_list and trial_num:', self.trial_tag_list, '<->', list(metrics.keys()))
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
color = random.choice(colors)
colors.remove(color)
tex_xtick = list(trial_tag_list) if xticks is None else xticks
data = [metrics[trial] for trial in metrics.keys()]
boxs_parts = ax.boxplot(data, positions=list(range(len(trial_tag_list))), widths=widths, meanline=True)
box_parts.append(boxs_parts['boxes'][0])
legend_labels.append(metric_name)
for item in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(boxs_parts[item], color=color)
plt.setp(boxs_parts["fliers"], markeredgecolor=color)
plt.grid()
if minorticks_on:
plt.minorticks_on()
plt.xticks(rotation=xrotation)
plt.yticks(rotation=yrotation)
plt.xlabel('' if xlabel is None else xlabel)
plt.ylabel(', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
plt.legend(box_parts, legend_labels, loc=legend_loc)
if save_name:
global retry_count
try:
tikz_code = tikzplotlib.get_tikz_code()
except ValueError as e:
if retry_count > 0:
retry_count -= 1
self.traj_plot(save_name, **kwargs)
else:
raise RuntimeError(e)
tex_src = self.box_plot_tex_template.replace('$tikz_code$', tikz_code)
tex_src = tex_src.replace('$xticklabel$', ','.join([str(x) for x in tex_xtick]))
tex_src = tex_src.replace('$xtick$', ','.join([str(x) for x in range(len(tex_xtick))]))
tex_src = tex_src.replace('$xlabel$', ', '.join(list(trial_tag_list)) if xlabel is None else xlabel)
tex_src = tex_src.replace('$ylabel$', ', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
tex_src = tex_src.replace('$xtickshift$', str(xtickshift))
tex_src = tex_src.replace('$ytickshift$', str(ytickshift))
tex_src = tex_src.replace('$xlabelshift$', str(xlabelshift))
tex_src = tex_src.replace('$ylabelshift$', str(ylabelshift))
plt.savefig(save_name + '.pdf', dpi=1000)
plt.show()
fout = open((save_name + '_metric_box_plot.tikz.tex').lstrip('_'), mode='w', encoding='utf8')
fout.write(tex_src)
fout.close()
plt.savefig(save_name + '_metric_box_plot.pdf')
texs = find_cwd_files(['.tex', save_name, '_metric_box_plot'])
for pdf in texs:
cmd = 'pdflatex "{}" '.format(pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
pdfs = find_cwd_files(['.pdf', save_name, '_metric_box_plot'], exclude_key='crop')
for pdf in pdfs:
cmd = 'pdfcrop "{}" "{}" '.format(pdf, pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
for f in find_cwd_files(['.aux', save_name]) + find_cwd_files(['.log', save_name]) + find_cwd_files(['crop', save_name]):
os.remove(f)
print('Tikz plot saved at ', find_cwd_files(['_metric_box_plot', save_name], exclude_key='crop'))
else:
plt.show()
print('Box plot finished')
plt.close()
@exception_handle
def avg_bar_plot(self, plot_metrics=None, save_name=None, **kwargs):
markers = self.MARKERS[:]
colors = self.COLORS[:]
hatches = self.HATCHES[:]
if isinstance(plot_metrics, str): # warning for early version (<0.4.0)
print('Please do not use this function directly for version (<0.4.0)')
if not plot_metrics:
plot_metrics = self.metrics
ax = plt.subplot()
alpha = kwargs.pop('alpha', 1)
markersize = kwargs.pop('markersize', 3)
xlabel = kwargs.pop('xlabel', None)
xticks = kwargs.pop('xticks', None)
ylabel = kwargs.pop('ylabel', None)
yticks = kwargs.pop('yticks', None)
legend_loc = kwargs.pop('legend_loc', 2)
hatches = kwargs.pop('hatches', hatches)
xrotation = kwargs.pop('xrotation', 0)
yrotation = kwargs.pop('yrotation', 0)
xlabelshift = kwargs.pop('xlabelshift', 1)
ylabelshift = kwargs.pop('ylabelshift', 1)
xtickshift = kwargs.pop('xtickshift', 1)
ytickshift = kwargs.pop('ytickshift', 1)
linewidth = kwargs.pop('linewidth', 3)
widths = kwargs.pop('widths', 0.9)
minorticks_on = kwargs.pop('minorticks_on', False)
sum_bar_parts = []
total_width = 0.9
for i, metric_name in enumerate(plot_metrics.keys()):
metrics = plot_metrics[metric_name]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if self.trial_tag_list:
print('Unequal length of trial_tag_list and trial_num:', self.trial_tag_list, '<->', list(metrics.keys()))
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
metric_num = len(plot_metrics.keys())
trial_num = len(plot_metrics[metric_name])
width = total_width / metric_num
x = np.arange(trial_num)
x = x - (total_width - width) / 2
x = x + i * width
Y = np.array([np.average(plot_metrics[m_name][trial]) for m_name in plot_metrics.keys() for trial in plot_metrics[m_name] if metric_name == m_name])
hatch = random.choice(hatches)
hatches.remove(hatch)
color = random.choice(colors)
colors.remove(color)
if save_name:
bar = plt.bar(x, Y, width=width, label=metric_name, hatch=hatch, color=color)
plt.legend()
else:
bar = plt.bar(x, Y, width=width, hatch=hatch, color=color)
sum_bar_parts.append(bar[0])
legend_labels = list(plot_metrics.keys())
plt.legend(sum_bar_parts, legend_labels, loc=legend_loc)
for i, j in zip(x, Y):
plt.text(i, j + max(Y) // 100, '%.1f' % j, ha='center', va='bottom')
tex_xtick = list(trial_tag_list) if xticks is None else xticks
plt.grid()
if minorticks_on:
plt.minorticks_on()
plt.xticks(rotation=xrotation)
plt.yticks(rotation=yrotation)
plt.xlabel('' if xlabel is None else xlabel)
plt.ylabel(', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
if save_name:
global retry_count
try:
tikz_code = tikzplotlib.get_tikz_code()
except ValueError as e:
if retry_count > 0:
retry_count -= 1
self.traj_plot(save_name, **kwargs)
else:
raise RuntimeError(e)
tex_src = self.bar_plot_tex_template.replace('$tikz_code$', tikz_code)
tex_src = tex_src.replace('$xticklabel$', ','.join([str(x) for x in tex_xtick]))
tex_src = tex_src.replace('$xtick$', ','.join([str(x) for x in range(len(tex_xtick))]))
tex_src = tex_src.replace('$xlabel$', ', '.join(list(trial_tag_list)) if xlabel is None else xlabel)
tex_src = tex_src.replace('$ylabel$', ', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
tex_src = tex_src.replace('$xtickshift$', str(xtickshift))
tex_src = tex_src.replace('$ytickshift$', str(ytickshift))
tex_src = tex_src.replace('$xlabelshift$', str(xlabelshift))
tex_src = tex_src.replace('$ylabelshift$', str(ylabelshift))
plt.savefig(save_name + '.pdf', dpi=1000)
plt.show()
fout = open((save_name + '_metric_avg_bar_plot.tikz.tex').lstrip('_'), mode='w', encoding='utf8')
fout.write(tex_src)
fout.close()
plt.savefig(save_name + '_metric_avg_bar_plot.pdf')
texs = find_cwd_files(['.tex', save_name, '_metric_avg_bar_plot'])
for pdf in texs:
cmd = 'pdflatex "{}" '.format(pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
pdfs = find_cwd_files(['.pdf', save_name, '_metric_avg_bar_plot'], exclude_key='crop')
for pdf in pdfs:
cmd = 'pdfcrop "{}" "{}" '.format(pdf, pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
for f in find_cwd_files(['.aux', save_name]) + find_cwd_files(['.log', save_name]) + find_cwd_files(['crop', save_name]):
os.remove(f)
print('Tikz plot saved at ', find_cwd_files(['_metric_avg_bar_plot', save_name], exclude_key='crop'))
else:
plt.show()
print('Avg Bar plot finished')
plt.close()
@exception_handle
def sum_bar_plot(self, plot_metrics=None, save_name=None, **kwargs):
markers = self.MARKERS[:]
colors = self.COLORS[:]
hatches = self.HATCHES[:]
if isinstance(plot_metrics, str): # warning for early version (<0.4.0)
print('Please do not use this function directly for version (<0.4.0)')
if not plot_metrics:
plot_metrics = self.metrics
ax = plt.subplot()
alpha = kwargs.pop('alpha', 1)
markersize = kwargs.pop('markersize', 3)
xlabel = kwargs.pop('xlabel', None)
xticks = kwargs.pop('xticks', None)
ylabel = kwargs.pop('ylabel', None)
yticks = kwargs.pop('yticks', None)
legend_loc = kwargs.pop('legend_loc', 2)
hatches = kwargs.pop('hatches', hatches)
xrotation = kwargs.pop('xrotation', 0)
yrotation = kwargs.pop('yrotation', 0)
xlabelshift = kwargs.pop('xlabelshift', 1)
ylabelshift = kwargs.pop('ylabelshift', 1)
xtickshift = kwargs.pop('xtickshift', 1)
ytickshift = kwargs.pop('ytickshift', 1)
linewidth = kwargs.pop('linewidth', 3)
widths = kwargs.pop('widths', 0.9)
minorticks_on = kwargs.pop('minorticks_on', False)
sum_bar_parts = []
total_width = 0.9
for i, metric_name in enumerate(plot_metrics.keys()):
metrics = plot_metrics[metric_name]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if self.trial_tag_list:
print('Unequal length of trial_tag_list and trial_num:', self.trial_tag_list, '<->', list(metrics.keys()))
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
metric_num = len(plot_metrics.keys())
trial_num = len(plot_metrics[metric_name])
width = total_width / metric_num
x = np.arange(trial_num)
x = x - (total_width - width) / 2
x = x + i * width
Y = np.array([np.sum(plot_metrics[m_name][trial]) for m_name in plot_metrics.keys() for trial in plot_metrics[m_name] if metric_name == m_name])
hatch = random.choice(hatches)
hatches.remove(hatch)
color = random.choice(colors)
colors.remove(color)
if save_name:
bar = plt.bar(x, Y, width=width, label=metric_name, hatch=hatch, color=color)
plt.legend()
else:
bar = plt.bar(x, Y, width=width, hatch=hatch, color=color)
sum_bar_parts.append(bar[0])
legend_labels = list(plot_metrics.keys())
plt.legend(sum_bar_parts, legend_labels, loc=legend_loc)
for i, j in zip(x, Y):
plt.text(i, j + max(Y) // 100, '%.1f' % j, ha='center', va='bottom')
tex_xtick = list(trial_tag_list) if xticks is None else xticks
plt.grid()
if minorticks_on:
plt.minorticks_on()
plt.xticks(rotation=xrotation)
plt.yticks(rotation=yrotation)
plt.xlabel('' if xlabel is None else xlabel)
plt.ylabel(', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
if save_name:
global retry_count
try:
tikz_code = tikzplotlib.get_tikz_code()
except ValueError as e:
if retry_count > 0:
retry_count -= 1
self.traj_plot(save_name, **kwargs)
else:
raise RuntimeError(e)
tex_src = self.bar_plot_tex_template.replace('$tikz_code$', tikz_code)
tex_src = tex_src.replace('$xticklabel$', ','.join([str(x) for x in tex_xtick]))
tex_src = tex_src.replace('$xtick$', ','.join([str(x) for x in range(len(tex_xtick))]))
tex_src = tex_src.replace('$xlabel$', ', '.join(list(trial_tag_list)) if xlabel is None else xlabel)
tex_src = tex_src.replace('$ylabel$', ', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
tex_src = tex_src.replace('$xtickshift$', str(xtickshift))
tex_src = tex_src.replace('$ytickshift$', str(ytickshift))
tex_src = tex_src.replace('$xlabelshift$', str(xlabelshift))
tex_src = tex_src.replace('$ylabelshift$', str(ylabelshift))
plt.savefig(save_name + '.pdf', dpi=1000)
plt.show()
fout = open((save_name + '_metric_sum_bar_plot.tikz.tex').lstrip('_'), mode='w', encoding='utf8')
fout.write(tex_src)
fout.close()
plt.savefig(save_name + '_metric_sum_bar_plot.pdf')
texs = find_cwd_files(['.tex', save_name, '_metric_sum_bar_plot'])
for pdf in texs:
cmd = 'pdflatex "{}" '.format(pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
pdfs = find_cwd_files(['.pdf', save_name, '_metric_sum_bar_plot'], exclude_key='crop')
for pdf in pdfs:
cmd = 'pdfcrop "{}" "{}" '.format(pdf, pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
for f in find_cwd_files(['.aux', save_name]) + find_cwd_files(['.log', save_name]) + find_cwd_files(['crop', save_name]):
os.remove(f)
print('Tikz plot saved at ', find_cwd_files(['_metric_sum_bar_plot', save_name], exclude_key='crop'))
else:
plt.show()
print('Sum Bar plot finished')
plt.close()
@exception_handle
def violin_plot(self, plot_metrics=None, save_name=None, **kwargs):
markers = self.MARKERS[:]
colors = self.COLORS[:]
hatches = self.HATCHES[:]
if isinstance(plot_metrics, str): # warning for early version (<0.4.0)
print('Please do not use this function directly for version (<0.4.0)')
if not plot_metrics:
plot_metrics = self.metrics
legend_labels = []
# def add_label(violin, label):
# color = violin["bodies"][0].get_facecolor().flatten()
# legend_labels.append((mpatches.Patch(color=color), label))
ax = plt.subplot()
alpha = kwargs.pop('alpha', 1)
markersize = kwargs.pop('markersize', 3)
xlabel = kwargs.pop('xlabel', None)
xticks = kwargs.pop('xticks', None)
ylabel = kwargs.pop('ylabel', None)
yticks = kwargs.pop('yticks', None)
legend_loc = kwargs.pop('legend_loc', 2)
hatches = kwargs.pop('hatches', hatches)
xrotation = kwargs.pop('xrotation', 0)
yrotation = kwargs.pop('yrotation', 0)
xlabelshift = kwargs.pop('xlabelshift', 1)
ylabelshift = kwargs.pop('ylabelshift', 1)
xtickshift = kwargs.pop('xtickshift', 1)
ytickshift = kwargs.pop('ytickshift', 1)
linewidth = kwargs.pop('linewidth', 3)
widths = kwargs.pop('widths', 0.9)
minorticks_on = kwargs.pop('minorticks_on', False)
violin_parts = []
legend_labels = []
for metric_name in plot_metrics.keys():
metrics = plot_metrics[metric_name]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if self.trial_tag_list:
print('Unequal length of trial_tag_list and trial_num:', self.trial_tag_list, '<->', list(metrics.keys()))
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
tex_xtick = list(trial_tag_list) if xticks is None else xticks
data = [metrics[trial] for trial in metrics.keys()]
if save_name:
violin = ax.violinplot(data, widths=widths, positions=list(range(len(trial_tag_list))), showmeans=True, showmedians=True, showextrema=True)
violin_parts.append(violin['bodies'][0])
legend_labels = list(plot_metrics.keys())
plt.legend(violin_parts, legend_labels, loc=0)
else:
violin = ax.violinplot(data, widths=widths, positions=list(range(len(trial_tag_list))), showmeans=True, showmedians=True, showextrema=True)
violin_parts.append(violin['bodies'][0])
legend_labels = list(plot_metrics.keys())
plt.legend(violin_parts, legend_labels, loc=legend_loc)
for pc in violin['bodies']:
pc.set_linewidth(linewidth)
plt.grid()
if minorticks_on:
plt.minorticks_on()
plt.xticks(rotation=xrotation)
plt.yticks(rotation=yrotation)
plt.xlabel('' if xlabel is None else xlabel)
plt.ylabel(', '.join(list(plot_metrics.keys())) if ylabel is None else ylabel)
if save_name:
global retry_count
try:
tikz_code = tikzplotlib.get_tikz_code()
except ValueError as e:
if retry_count > 0:
retry_count -= 1
self.traj_plot(save_name, **kwargs)
else:
raise RuntimeError(e)
tex_src = self.box_plot_tex_template.replace('$tikz_code$', tikz_code)
tex_src = tex_src.replace('$xticklabel$', ','.join([str(x) for x in tex_xtick]))
tex_src = tex_src.replace('$xtick$', ','.join([str(x) for x in range(len(tex_xtick))]))
tex_src = tex_src.replace('$xlabel$', ', '.join(list(trial_tag_list)) if xlabel is None else xlabel)
tex_src = tex_src.replace('$ylabel$', ', '.join(list(plot_metrics)) if ylabel is None else ylabel)
tex_src = tex_src.replace('$xtickshift$', str(xtickshift))
tex_src = tex_src.replace('$ytickshift$', str(ytickshift))
tex_src = tex_src.replace('$xlabelshift$', str(xlabelshift))
tex_src = tex_src.replace('$ylabelshift$', str(ylabelshift))
plt.savefig(save_name + '.pdf', dpi=1000)
plt.show()
fout = open((save_name + '_metric_violin_plot.tikz.tex').lstrip('_'), mode='w', encoding='utf8')
fout.write(tex_src)
fout.close()
plt.savefig(save_name + '_metric_violin_plot.pdf')
texs = find_cwd_files(['.tex', save_name, '_metric_violin_plot'])
for pdf in texs:
cmd = 'pdflatex "{}"'.format(pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
pdfs = find_cwd_files(['.pdf', save_name, '_metric_violin_plot'], exclude_key='crop')
for pdf in pdfs:
cmd = 'pdfcrop "{}" "{}"'.format(pdf, pdf).replace(os.path.sep, '/')
subprocess.check_call(shlex.split(cmd), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# os.system(cmd)
for f in find_cwd_files(['.aux', save_name]) + find_cwd_files(['.log', save_name]) + find_cwd_files(['crop', save_name]):
os.remove(f)
print('Tikz plot saved at ', find_cwd_files(['_metric_violin_plot', save_name], exclude_key='crop'))
else:
plt.show()
print('Violin plot finished')
plt.close()
@exception_handle
def transpose(self):
transposed_metrics = OrderedDict()
for metric_name in self.metrics.keys():
for trial_tag_list in self.metrics[metric_name].keys():
if trial_tag_list not in transposed_metrics:
transposed_metrics[trial_tag_list] = {}
transposed_metrics[trial_tag_list][metric_name] = self.metrics[metric_name][trial_tag_list]
return transposed_metrics
@exception_handle
def A12_plot(self):
raise NotImplementedError()
@exception_handle
def sk_rank_plot(self):
raise NotImplementedError()
@exception_handle
def wilconxon_rank_test_by_trial(self, target_trial):
raise NotImplementedError()
@exception_handle
def summary(self, save_path=None, no_print=False, **kwargs):
summary_str = ' ------------------------------------- Metric Visualizer ------------------------------------- \n'
header = ['Metric', self.trial_tag, 'Values (First 10 values)', 'Summary']
table_data = []
for mn in self.metrics.keys():
metrics = self.metrics[mn]
if not self.trial_tag_list or len(self.trial_tag_list) != len(metrics.keys()):
if len(self.trial_tag_list) > len(metrics.keys()):
trial_tag_list = self.trial_tag_list[:len(metrics.keys())]
else:
trial_tag_list = list(metrics.keys())
else:
trial_tag_list = self.trial_tag_list
for i, trial in enumerate(metrics.keys()):
_data = []
_data += [[mn, trial_tag_list[i], [round(x, 2) for x in metrics[trial][:10]]]]
_data[-1].append(
['Avg:{}, Median: {}, IQR: {}, STD:{}, Max: {}, Min: {}'.format(
round(np.average(metrics[trial]), 2),
round(np.median(metrics[trial]), 2),
round(np.std(metrics[trial]), 2),
round(iqr(metrics[trial], rng=(25, 75), interpolation='midpoint'), 2),
round(np.max(metrics[trial]), 2),
round(np.min(metrics[trial]), 2)
)]
)
table_data += _data
summary_str += tabulate(table_data,
headers=header,
numalign='center',
tablefmt='fancy_grid')
summary_str += '\n -------------------- https://github.com/yangheng95/metric_visualizer --------------------\n'
if not no_print:
print(summary_str)
if save_path:
fout = open(save_path + '_summary.txt', mode='w', encoding='utf8')
summary_str += '\n{}\n'.format(str(self.metrics))
fout.write(summary_str)
fout.close()
self.dump()
return summary_str
def dump(self, filename=None):
if not filename:
if self.dump_pointer:
os.remove(self.dump_pointer)
time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
trial_id = self.trial_id
postfix = 'mv'
self.dump_pointer = '{}_{}_id{}.{}'.format(self.name, time_tag, trial_id, postfix)
else:
self.dump_pointer = filename
pickle.dump(self, open(self.dump_pointer, mode='wb'))
@staticmethod
def load(filename='metric_visualizer.dat'):
if not os.path.exists(filename):
dats = find_cwd_files(filename)
if not dats:
raise ValueError('Can not find {}'.format(filename))
else:
filename = max(dats)
print('Load', filename)
mv = pickle.load(open(filename, mode='rb'))
return mv
| 38.714286 | 160 | 0.565971 | 5,376 | 44,444 | 4.488281 | 0.091332 | 0.022877 | 0.035808 | 0.019893 | 0.816196 | 0.800655 | 0.7922 | 0.765013 | 0.752787 | 0.747275 | 0 | 0.027711 | 0.302538 | 44,444 | 1,147 | 161 | 38.748038 | 0.750694 | 0.054293 | 0 | 0.726415 | 0 | 0 | 0.18773 | 0.038664 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037736 | false | 0 | 0.018868 | 0 | 0.074292 | 0.029481 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
7bb276c852115e80d09eeabe70fa19322f869548 | 14 | py | Python | .idea/VirtualEnvironment/Lib/site-packages/tests/outcomes/imports/user_module_not_exists_but_exists_other/random_module/main.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | null | null | null | .idea/VirtualEnvironment/Lib/site-packages/tests/outcomes/imports/user_module_not_exists_but_exists_other/random_module/main.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | 5 | 2021-04-08T22:02:15.000Z | 2022-02-10T14:53:45.000Z | .idea/VirtualEnvironment/Lib/site-packages/tests/outcomes/imports/user_module_not_exists_but_exists_other/random_module/main.py | Vladpetr/NewsPortal | cd4127fbc09d9c8f5e65c8ae699856c6d380a320 | [
"Apache-2.0"
] | null | null | null | print('2050')
| 7 | 13 | 0.642857 | 2 | 14 | 4.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | 0.071429 | 14 | 1 | 14 | 14 | 0.384615 | 0 | 0 | 0 | 0 | 0 | 0.285714 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 7 |
7bba9e409ba0a1a904570710f7161efb7bbcf288 | 48 | py | Python | python/testData/resolve/multiFile/importSubModuleDunderAll/ImportSubModuleDunderAll.py | jnthn/intellij-community | 8fa7c8a3ace62400c838e0d5926a7be106aa8557 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | python/testData/resolve/multiFile/importSubModuleDunderAll/ImportSubModuleDunderAll.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | python/testData/resolve/multiFile/importSubModuleDunderAll/ImportSubModuleDunderAll.py | Cyril-lamirand/intellij-community | 60ab6c61b82fc761dd68363eca7d9d69663cfa39 | [
"Apache-2.0"
] | 2 | 2020-03-15T08:57:37.000Z | 2020-04-07T04:48:14.000Z | import pkg1.m1
print(pkg1.m1)
# <ref>
| 9.6 | 16 | 0.541667 | 7 | 48 | 3.714286 | 0.714286 | 0.461538 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.121212 | 0.3125 | 48 | 4 | 17 | 12 | 0.666667 | 0.104167 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 7 |
7bc5b7320960c2fee833d0c2a00b4fa09d845066 | 8,479 | py | Python | tempest/tests/rbac/test_rbac_utils.py | DavidPurcellATT/TempestRbacDemo | 814626486508044a1403e746da5af83f82e24631 | [
"Apache-2.0"
] | null | null | null | tempest/tests/rbac/test_rbac_utils.py | DavidPurcellATT/TempestRbacDemo | 814626486508044a1403e746da5af83f82e24631 | [
"Apache-2.0"
] | null | null | null | tempest/tests/rbac/test_rbac_utils.py | DavidPurcellATT/TempestRbacDemo | 814626486508044a1403e746da5af83f82e24631 | [
"Apache-2.0"
] | null | null | null | # Copyright 2016 AT&T Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import mock
from tempest.common.rbac import rbac_utils as utils
from tempest.tests import base
class RBACUtilsTest(base.TestCase):
def setUp(self):
super(RBACUtilsTest, self).setUp()
self.rbac_utils = utils.RbacUtils
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_get_roles_none(self, requests, config):
self.rbac_utils.dictionary = {}
caller = mock.Mock()
caller.admin_client.token = "test_token"
response = mock.Mock()
response.status_code = 200
response.text = json.dumps({'roles': []})
requests.get.return_value = response
self.assertEqual({'admin_role_id': None, 'rbac_role_id': None},
self.rbac_utils.get_roles(caller))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_get_roles_member(self, requests, config):
self.rbac_utils.dictionary = {}
caller = mock.Mock()
caller.admin_client.token = "test_token"
response = mock.Mock()
response.status_code = 200
response.text = json.dumps({'roles': [{'name': '_member_',
'id': '_member_id'}]})
requests.get.return_value = response
config.identity.rbac_role = '_member_'
self.assertEqual({'admin_role_id': None,
'rbac_role_id': '_member_id'},
self.rbac_utils.get_roles(caller))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_get_roles_admin(self, requests, config):
self.rbac_utils.dictionary = {}
caller = mock.Mock()
caller.admin_client.token = "test_token"
response = mock.Mock()
response.status_code = 200
response.text = json.dumps({'roles': [{'name': 'admin',
'id': 'admin_id'}]})
requests.get.return_value = response
config.identity.rbac_role = 'admin'
self.assertEqual({'admin_role_id': 'admin_id',
'rbac_role_id': 'admin_id'},
self.rbac_utils.get_roles(caller))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_get_roles_admin_not_role(self, requests, config):
self.rbac_utils.dictionary = {}
caller = mock.Mock()
caller.admin_client.token = "test_token"
response = mock.Mock()
response.status_code = 200
response.text = json.dumps(
{'roles': [{'name': 'admin', 'id': 'admin_id'}]}
)
requests.get.return_value = response
self.assertEqual({'admin_role_id': 'admin_id', 'rbac_role_id': None},
self.rbac_utils.get_roles(caller))
def test_RBAC_utils_get_existing_roles(self):
self.rbac_utils.dictionary = {'admin_role_id': None,
'rbac_role_id': None}
self.assertEqual({'admin_role_id': None, 'rbac_role_id': None},
self.rbac_utils.get_roles(None))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_get_roles_response_404(self, requests, config):
self.rbac_utils.dictionary = {}
caller = mock.Mock()
caller.admin_client.token = "test_token"
response = mock.Mock()
response.status_code = 404
response.text = json.dumps({'roles': []})
requests.get.return_value = response
self.assertRaises(StandardError, self.rbac_utils.get_roles, caller)
def test_RBAC_utils_switch_roles_none(self):
self.assertIsNone(self.rbac_utils.switch_role(None))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.RbacUtils.get_roles')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_switch_roles_member(self, requests,
get_roles, config):
get_roles.return_value = {'admin_role_id': None,
'rbac_role_id': '_member_id'}
self.auth_provider = mock.Mock()
self.auth_provider.credentials.user_id = "user_id"
self.auth_provider.credentials.tenant_id = "tenant_id"
self.admin_client = mock.Mock()
self.admin_client.token = "admin_token"
response_204 = mock.Mock()
response_204.status_code = 204
response_200 = mock.Mock()
response_200.status_code = 200
response_200.text = json.dumps({'roles': [{'id': 'id'}]})
requests.put.side_effect = None
requests.put.return_value = response_204
requests.delete.return_value = response_204
requests.get.return_value = response_200
self.assertIsNone(self.rbac_utils.switch_role(self, "_member_"))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.RbacUtils.get_roles')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_switch_roles_false(self, requests,
get_roles, config):
get_roles.return_value = {'admin_role_id': None,
'rbac_role_id': '_member_id'}
self.auth_provider = mock.Mock()
self.auth_provider.credentials.user_id = "user_id"
self.auth_provider.credentials.tenant_id = "tenant_id"
self.admin_client = mock.Mock()
self.admin_client.token = "admin_token"
response_204 = mock.Mock()
response_204.status_code = 204
response_200 = mock.Mock()
response_200.status_code = 200
response_200.text = json.dumps({'roles': [{'id': 'id'}]})
requests.put.side_effect = None
requests.put.return_value = response_204
requests.delete.return_value = response_204
requests.get.return_value = response_200
self.assertIsNone(self.rbac_utils.switch_role(self, False))
@mock.patch('tempest.common.rbac.rbac_utils.CONF')
@mock.patch('tempest.common.rbac.rbac_utils.RbacUtils.get_roles')
@mock.patch('tempest.common.rbac.rbac_utils.requests')
def test_RBAC_utils_switch_roles_get_roles_fails(self, requests,
get_roles, config):
get_roles.return_value = {'admin_role_id': None,
'rbac_role_id': '_member_id'}
self.auth_provider = mock.Mock()
self.auth_provider.credentials.user_id = "user_id"
self.auth_provider.credentials.tenant_id = "tenant_id"
self.admin_client = mock.Mock()
self.admin_client.token = "admin_token"
response_204 = mock.Mock()
response_204.status_code = 204
response_200 = mock.Mock()
response_200.status_code = 404
response_200.text = json.dumps({'roles': [{'id': 'id'}]})
requests.put.side_effect = None
requests.put.return_value = response_204
requests.delete.return_value = response_204
requests.get.return_value = response_200
self.assertRaises(StandardError, self.rbac_utils.switch_role, self,
False)
@mock.patch('tempest.common.rbac.rbac_utils.RbacUtils.get_roles')
def test_RBAC_utils_switch_roles_exception(self, get_roles):
get_roles.return_value = {'admin_role_id': None,
'rbac_role_id': '_member_id'}
self.assertRaises(AttributeError, self.rbac_utils.switch_role,
self, "admin")
| 38.894495 | 78 | 0.636042 | 1,031 | 8,479 | 4.956353 | 0.124151 | 0.088063 | 0.069863 | 0.086106 | 0.841487 | 0.840117 | 0.817613 | 0.80998 | 0.80998 | 0.80137 | 0 | 0.018271 | 0.251209 | 8,479 | 217 | 79 | 39.073733 | 0.786581 | 0.067697 | 0 | 0.703226 | 0 | 0 | 0.175792 | 0.10038 | 0 | 0 | 0 | 0 | 0.070968 | 1 | 0.077419 | false | 0 | 0.025806 | 0 | 0.109677 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
cdffa7022a030b7546039ad9368d85165d23f0f0 | 20,252 | py | Python | tests/case_management/test_workflow_event_interface.py | kdeltared/tcex | 818c0d09256764f871e42d9ca5916f92d941d882 | [
"Apache-2.0"
] | 18 | 2017-01-09T22:17:49.000Z | 2022-01-24T20:46:42.000Z | tests/case_management/test_workflow_event_interface.py | kdeltared/tcex | 818c0d09256764f871e42d9ca5916f92d941d882 | [
"Apache-2.0"
] | 84 | 2017-04-11T13:47:49.000Z | 2022-03-21T20:12:57.000Z | tests/case_management/test_workflow_event_interface.py | kdeltared/tcex | 818c0d09256764f871e42d9ca5916f92d941d882 | [
"Apache-2.0"
] | 43 | 2017-01-05T20:40:26.000Z | 2022-03-31T19:18:02.000Z | """Test the TcEx Case Management Module."""
# standard library
import os
from datetime import datetime, timedelta
# first-party
from tcex.case_management.tql import TQL
from .cm_helpers import CMHelper, TestCaseManagement
class TestWorkflowEvent(TestCaseManagement):
"""Test TcEx CM Workflow Event Interface."""
def setup_method(self):
"""Configure setup before all tests."""
self.cm_helper = CMHelper('workflow_event')
self.cm = self.cm_helper.cm
self.tcex = self.cm_helper.tcex
def teardown_method(self):
"""Configure teardown before all tests."""
if os.getenv('TEARDOWN_METHOD') is None:
self.cm_helper.cleanup()
def test_workflow_event_api_options(self):
"""Test filter keywords."""
super().obj_api_options()
def test_workflow_event_code_gen(self):
"""Generate code and docstring from Options methods.
This is not truly a test case, but best place to store it for now.
"""
doc_string, filter_map, filter_class = super().obj_code_gen()
assert doc_string
assert filter_map
assert filter_class
def test_workflow_event_filter_keywords(self):
"""Test filter keywords."""
super().obj_filter_keywords()
def test_workflow_event_object_properties(self):
"""Test properties."""
super().obj_properties()
def test_workflow_event_object_properties_extra(self):
"""Test properties."""
super().obj_properties_extra()
def test_workflow_event_create_by_case_id(self, request):
"""Test Workflow Event Creation"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# get workflow event from API to use in asserts
workflow_event = self.cm.workflow_event(id=workflow_event.id)
workflow_event.get()
# run assertions on returned data
assert workflow_event.summary == workflow_event_data.get('summary')
# TODO: @mj - confirm this should work
# def test_workflow_event_delete_by_id(self, request):
# """Test Workflow Event Creation"""
# # create case
# case = self.cm_helper.create_case()
# # workflow event data
# workflow_event_data = {
# 'case_id': case.id,
# 'summary': request.node.name,
# }
# # create workflow_event
# workflow_event = self.cm.workflow_event(**workflow_event_data)
# workflow_event.submit()
# # get single workflow event
# workflow_event = self.cm.workflow_event(id=workflow_event.id)
# workflow_event.get()
# # delete the workflow event
# workflow_event.delete()
# # get single workflow event
# workflow_event = self.cm.workflow_event(id=workflow_event.id)
# workflow_event.get()
# # workflow action don't actually get deleted, the deleted flag gets set to True
# assert workflow_event.deleted is True
def test_workflow_event_get_many(self, request):
"""Test Workflow Event Creation"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# iterate over all workflow events looking for needle
for we in self.cm.workflow_events():
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False
def test_workflow_event_get_single_by_id(self, request):
"""Test Workflow Event Creation"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# get workflow event from API to use in asserts
workflow_event = self.cm.workflow_event(id=workflow_event.id)
workflow_event.get(all_available_fields=True)
# run assertions on returned data
assert workflow_event.summary == workflow_event_data.get('summary')
def test_workflow_event_get_single_by_id_properties(self, request):
"""Test Workflow Event Creation"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'case_xid': case.xid,
'event_date': datetime.now().isoformat(),
'note_text': f'a note for {request.node.name}',
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event()
workflow_event.case_id = workflow_event_data.get('case_id')
workflow_event.case_xid = workflow_event_data.get('case_xid')
workflow_event.event_date = workflow_event_data.get('event_date')
workflow_event.summary = workflow_event_data.get('summary')
# add note
workflow_event.add_note(text=workflow_event_data.get('note_text'))
# submit
workflow_event.submit()
# get workflow event from API to use in asserts
workflow_event = self.cm.workflow_event(id=workflow_event.id)
workflow_event.get(all_available_fields=True)
# run assertions on returned data
assert workflow_event.case_id == workflow_event_data.get('case_id')
assert workflow_event.case_xid == workflow_event_data.get('case_xid')
assert workflow_event.user.user_name == os.getenv('API_ACCESS_ID')
assert workflow_event.date_added
assert workflow_event_data.get('event_date')[:17] in workflow_event.event_date
assert workflow_event.id == workflow_event.id
# TODO: @mj - confirm this should work
# for note in workflow_event.notes:
# print('note', note)
# if note.text == workflow_event_data.get('note_text'):
# break
# else:
# assert False, 'Note not found'
assert workflow_event.parent_case.id == case.id
assert workflow_event.summary == workflow_event_data.get('summary')
assert workflow_event.user.user_name == os.getenv('API_ACCESS_ID')
assert workflow_event.as_entity.get('value') == workflow_event_data.get('summary')
# TODO: @mj - confirm the status of these fields
assert workflow_event.deleted is None
assert workflow_event.deleted_reason is None
def test_workflow_event_update_properties(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event initial data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# workflow event updated data
workflow_event_data = {
'case_id': case.id,
'summary': f'updated {request.node.name} summary',
'event_date': (datetime.now() + timedelta(days=1)).isoformat(),
}
workflow_event.summary = workflow_event_data.get('summary')
workflow_event.event_date = workflow_event_data.get('event_date')
workflow_event.submit()
workflow_event.get(all_available_fields=True)
assert workflow_event.summary == workflow_event_data.get('summary')
assert workflow_event_data.get('event_date')[:10] in workflow_event.event_date
def test_workflow_event_get_by_tql_filter_link(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case.id)
workflow_events.filter.link(TQL.Operator.CONTAINS, case.id)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == 'Case created':
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_case_id(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case.id)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_date_added(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case_id=case.id)
workflow_events.filter.date_added(
TQL.Operator.GT, (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_deleted(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.deleted(TQL.Operator.EQ, False)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
# TODO: @mj - confirm this should work
# def test_workflow_event_get_by_tql_filter_deleted_reason(self, request):
# """Test Workflow Event Get by TQL"""
# # create case
# case = self.cm_helper.create_case()
# # workflow event data
# workflow_event_data = {
# 'case_id': case.id,
# 'summary': request.node.name,
# }
# # create workflow_event
# workflow_event = self.cm.workflow_event(**workflow_event_data)
# workflow_event.submit()
# # delete event
# workflow_event.delete()
# # retrieve workflow event using TQL
# workflow_events = self.cm.workflow_events()
# workflow_events.filter.deleted(TQL.Operator.EQ, True)
# workflow_events.filter.deleted_reason(
# TQL.Operator.EQ, f"Deleted through API by User:{os.getenv('API_ACCESS_ID')}"
# )
# for we in workflow_events:
# # more than one workflow event will always be returned
# if we.summary == workflow_event_data.get('summary'):
# break
# else:
# assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_event_date(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'event_date': (datetime.now() + timedelta(days=1)).isoformat(),
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case.id)
workflow_events.filter.event_date(TQL.Operator.GT, datetime.now().strftime('%Y-%m-%d'))
for we in workflow_events: # pylint: disable=unused-variable
# more than one workflow event will always be returned
if workflow_event.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_id(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.id(TQL.Operator.EQ, workflow_event.id)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
# per @mj link_text is not added when the workflow event is created via the API
# def test_workflow_event_get_by_tql_filter_link(self, request):
# """Test Workflow Event Get by TQL"""
# # create case
# case = self.cm_helper.create_case()
# # workflow event data
# workflow_event_data = {
# 'case_id': case.id,
# 'summary': request.node.name,
# }
# # create workflow_event
# workflow_event = self.cm.workflow_event(**workflow_event_data)
# workflow_event.submit()
# # retrieve workflow event using TQL
# link = f"{os.getenv('TC_API_PATH')}/v3/cases/{case.id}"
# workflow_events = self.cm.workflow_events(params={'fields': ['user']})
# workflow_events.filter.id(TQL.Operator.EQ, workflow_event.id)
# # workflow_events.filter.link(TQL.Operator.EQ, link)
# for we in workflow_events:
# # more than one workflow event will always be returned
# if we.summary == workflow_event_data.get('summary'):
# break
# else:
# assert False, 'No workflow event returned for TQL'
# per @mj link is not added when the workflow event is created via the API
# def test_workflow_event_get_by_tql_filter_link_text(self, request):
# """Test Workflow Event Get by TQL"""
def test_workflow_event_get_by_tql_filter_summary(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.summary(TQL.Operator.EQ, workflow_event_data.get('summary'))
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_system_generated(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case.id)
workflow_events.filter.system_generated(TQL.Operator.EQ, False)
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_tql(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.tql(f'caseid EQ {case.id}')
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
def test_workflow_event_get_by_tql_filter_user_name(self, request):
"""Test Workflow Event Get by TQL"""
# create case
case = self.cm_helper.create_case()
# workflow event data
workflow_event_data = {
'case_id': case.id,
'summary': request.node.name,
}
# create workflow_event
workflow_event = self.cm.workflow_event(**workflow_event_data)
workflow_event.submit()
# retrieve workflow event using TQL
workflow_events = self.cm.workflow_events()
workflow_events.filter.case_id(TQL.Operator.EQ, case.id)
workflow_events.filter.user_name(TQL.Operator.EQ, os.getenv('API_ACCESS_ID'))
for we in workflow_events:
# more than one workflow event will always be returned
if we.summary == workflow_event_data.get('summary'):
break
else:
assert False, 'No workflow event returned for TQL'
| 36.035587 | 95 | 0.629962 | 2,446 | 20,252 | 4.969747 | 0.07359 | 0.31869 | 0.116074 | 0.081277 | 0.858177 | 0.83465 | 0.808736 | 0.796644 | 0.764808 | 0.752632 | 0 | 0.000548 | 0.279133 | 20,252 | 561 | 96 | 36.099822 | 0.832112 | 0.306143 | 0 | 0.659176 | 0 | 0 | 0.072885 | 0 | 0 | 0 | 0 | 0.001783 | 0.11236 | 1 | 0.082397 | false | 0 | 0.014981 | 0 | 0.101124 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
a81eec6abf48a4c8e2fa41b97a25e219c0ebd2c7 | 154 | py | Python | pygfa/graph_element/__init__.py | Francesco2304/pygfa | 9bf6fb5f0a959685300ab863a0e716a2268109f7 | [
"MIT"
] | 3 | 2020-06-25T22:47:02.000Z | 2022-02-27T15:16:02.000Z | pygfa/graph_element/__init__.py | Francesco2304/pygfa | 9bf6fb5f0a959685300ab863a0e716a2268109f7 | [
"MIT"
] | 3 | 2017-08-08T12:24:23.000Z | 2022-02-27T15:17:25.000Z | pygfa/graph_element/__init__.py | Francesco2304/pygfa | 9bf6fb5f0a959685300ab863a0e716a2268109f7 | [
"MIT"
] | 4 | 2019-02-04T20:54:53.000Z | 2020-05-14T19:52:24.000Z | from pygfa.graph_element import node
from pygfa.graph_element import edge
from pygfa.graph_element import subgraph
from pygfa.graph_element import parser
| 30.8 | 40 | 0.87013 | 24 | 154 | 5.416667 | 0.375 | 0.276923 | 0.430769 | 0.646154 | 0.830769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.103896 | 154 | 4 | 41 | 38.5 | 0.942029 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 9 |
a8290d47fb0e8904fc3bc631e3cd176b55ed4678 | 51,557 | py | Python | unittests/config_tests/base_tests.py | Mirevi/face-synthesizer-JVRB | 3c5774b1c5c981131df21b299389f568502b8ecf | [
"BSD-3-Clause"
] | null | null | null | unittests/config_tests/base_tests.py | Mirevi/face-synthesizer-JVRB | 3c5774b1c5c981131df21b299389f568502b8ecf | [
"BSD-3-Clause"
] | null | null | null | unittests/config_tests/base_tests.py | Mirevi/face-synthesizer-JVRB | 3c5774b1c5c981131df21b299389f568502b8ecf | [
"BSD-3-Clause"
] | null | null | null | import unittest
from unittest import TestCase
from unittest.mock import MagicMock, patch, call
from config import *
class TestEnum(Enum):
a = 'a'
b = 'b'
c = 'c'
def __str__(self):
return self.value
class ConfigOptionPackageRequiredImpl(ConfigOptionPackage):
@staticmethod
def get_options_metadata() -> list:
return [
ConfigOptionMetadata(str, 'coat_color', 'black', 'Color of the coat.', False),
]
class ConfigOptionPackageConditionalRequiredImpl1(ConfigOptionPackage):
@staticmethod
def get_options_metadata() -> list:
return [
ConfigOptionMetadata(str, 'dog_size', 'Small', 'Size of the dog.', False),
]
class ConfigOptionPackageConditionalRequiredImpl2(ConfigOptionPackage):
@staticmethod
def get_options_metadata() -> list:
return [
ConfigOptionMetadata(str, 'toy', 'Bone', 'Toy', False),
]
class ConfigOptionPackageImpl(COPWithModifiableDefaults):
options_metadata = [
ConfigOptionMetadata(str, 'name', 'Charly', 'Name.', False),
ConfigOptionMetadata(str, 'type', 'dog', 'The animal type.', False),
ConfigOptionMetadata(int, 'age', 10, 'Age', False),
ConfigOptionMetadata(bool, 'has_toy', True, 'If there is a toy', False),
]
@staticmethod
def get_options_metadata() -> list:
return ConfigOptionPackageImpl.options_metadata
conditional_options_metadata = [
ConfigOptionMetadata(str, 'dog_breed', 'jack russel', 'The breed of the dog', False)
]
@staticmethod
def get_conditional_options_metadata(options) -> list:
if options.type == 'dog':
return ConfigOptionPackageImpl.conditional_options_metadata
else:
return []
default_modifications = [
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'coat_color', 'gray')
]
@staticmethod
def get_default_modifications() -> list:
return ConfigOptionPackageImpl.default_modifications
conditional_default_modifications = [
ConfigDefaultModification(ConfigOptionPackageConditionalRequiredImpl1, 'dog_size', 'Medium')
]
@staticmethod
def get_conditional_default_modifications(options):
if options.type == 'dog':
return ConfigOptionPackageImpl.conditional_default_modifications
else:
return []
class WrongConfigOptionPackageImpl:
@staticmethod
def get_options_metadata() -> list:
return [
ConfigOptionMetadata(str, 'name', 'Charly', 'Name.', False),
ConfigOptionMetadata(str, 'type', 'dog', 'The animal type.', False),
ConfigOptionMetadata(int, 'age', 10, 'Age', False),
]
class ConfigPackageProviderImpl(ConfigPackageProvider):
@staticmethod
def get_required_option_packages() -> list:
return [ConfigOptionPackageImpl]
@staticmethod
def get_conditional_option_packages(options) -> list:
if options.has_toy:
return [ConfigOptionPackageConditionalRequiredImpl2]
else:
return []
class WrongConfigPackageProviderImpl:
@staticmethod
def get_required_option_packages() -> list:
return [ConfigOptionPackageImpl]
class ConfigOptionMetadataTests(TestCase):
def test_initDefaultDatatypeValidation_correctType_noError(self):
try:
ConfigOptionMetadata(str, '', 'string', 'help', False)
ConfigOptionMetadata(int, '', 5, 'help', True)
ConfigOptionMetadata(float, '', 3.0, 'help', False)
ConfigOptionMetadata(TestEnum, '', TestEnum.a, 'help', True, list(TestEnum))
except TypeError:
self.fail('Unexpected TypeError')
def test_initDefaultDatatypeValidation_wrongType_raiseTypeError(self):
with self.assertRaises(TypeError):
ConfigOptionMetadata(str, '', 5, 'help', False)
with self.assertRaises(TypeError):
ConfigOptionMetadata(int, '', 'test', 'help', True)
with self.assertRaises(TypeError):
ConfigOptionMetadata(float, '', TestEnum.a, 'help', False)
with self.assertRaises(TypeError):
ConfigOptionMetadata(TestEnum, '', 3.0, 'help', True)
def test_initChoicesValidation_correctTypes_noError(self):
try:
ConfigOptionMetadata(str, '', 'string', 'help', False, choices=['string', 'test'])
ConfigOptionMetadata(int, '', 5, 'help', True, choices=range(0, 10))
ConfigOptionMetadata(float, '', 3.0, 'help', False, choices=[1.0, 1.1, 3.0])
ConfigOptionMetadata(TestEnum, '', TestEnum.a, 'help', True, choices=list(TestEnum))
except TypeError:
self.fail('Unexpected TypeError')
def test_initChoicesValidation_wrongType_raiseTypeError(self):
with self.assertRaises(TypeError):
ConfigOptionMetadata(str, '', 'string', 'help', False, choices=['string', 0])
with self.assertRaises(TypeError):
ConfigOptionMetadata(int, '', 5, 'help', True, choices=[1, 2, 'test'])
with self.assertRaises(TypeError):
ConfigOptionMetadata(float, '', 3.0, 'help', False, choices=[1.0, 1.1, '3.0'])
with self.assertRaises(TypeError):
ConfigOptionMetadata(TestEnum, '', TestEnum.a, 'help', True, choices=['test'])
def test_initDefaultInChoiceValidation_isInChoice_noError(self):
try:
ConfigOptionMetadata(str, '', 'test', 'help', False, choices=['string', 'test'])
ConfigOptionMetadata(int, '', 5, 'help', True, choices=[1, 5, 4])
ConfigOptionMetadata(float, '', 3.0, 'help', False, choices=[1.0, 1.1, 3.0])
ConfigOptionMetadata(TestEnum, '', TestEnum.a, 'help', True, choices=[TestEnum.a, TestEnum.b])
except TypeError:
self.fail('Unexpected TypeError')
def test_initDefaultInChoiceValidation_isNotInChoice_raiseValueError(self):
with self.assertRaises(ValueError):
ConfigOptionMetadata(str, '', 'default', 'help', False, choices=['string', 'test'])
with self.assertRaises(ValueError):
ConfigOptionMetadata(int, '', 75, 'help', True, choices=[1, 5, 4])
with self.assertRaises(ValueError):
ConfigOptionMetadata(float, '', 4.0, 'help', False, choices=[1.0, 1.1, 3.0])
with self.assertRaises(ValueError):
ConfigOptionMetadata(TestEnum, '', TestEnum.c, 'help', True, choices=[TestEnum.a, TestEnum.b])
class ConfigDefaultModificationTests(TestCase):
def test_initPackageValidation_correctType_noError(self):
try:
ConfigDefaultModification(ConfigOptionPackageImpl, 'name', 'value')
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'name', 'value')
ConfigDefaultModification(ConfigOptionPackageConditionalRequiredImpl1, 'name', 'value')
except TypeError:
self.fail('Unexpected TypeError')
def test_initPackageValidation_wrongType_raiseTypeError(self):
with self.assertRaises(TypeError):
ConfigDefaultModification(WrongConfigOptionPackageImpl, 'name', 'value')
class BaseConfigProviderTests(TestCase):
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addPackageProviders_correctTypesInList_noError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
try:
config.add_package_providers([ConfigPackageProviderImpl, ConfigPackageProviderImpl])
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addPackageProviders_wrongTypeInList_raiseTypeError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
with self.assertRaises(TypeError):
config.add_package_providers([ConfigPackageProviderImpl, WrongConfigPackageProviderImpl])
with self.assertRaises(TypeError):
config.add_package_providers([ConfigPackageProviderImpl, ConfigOptionPackageImpl])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addPackageProvider_correctType_noError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
try:
config.add_package_provider(ConfigPackageProviderImpl)
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addPackageProvider_wrongType_raiseTypeError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
with self.assertRaises(TypeError):
config.add_package_provider(WrongConfigPackageProviderImpl)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addPackageProvider_doubleRegistration_onlyOnceInConfig(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_package_provider(ConfigPackageProviderImpl)
config.add_package_provider(ConfigPackageProviderImpl)
self.assertIs(config.package_provider.count(ConfigPackageProviderImpl), 1)
config.add_option_packages.assert_called_with(ConfigPackageProviderImpl.get_required_option_packages())
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_conditionalsMet_addedConditionals(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_package_provider(ConfigPackageProviderImpl)
config.options.has_toy = True
config.gather_options()
calls = [call([ConfigOptionPackageImpl]), call([ConfigOptionPackageConditionalRequiredImpl2])]
config.add_option_packages.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_conditionalsNotMet_conditionalsNotAdded(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_package_provider(ConfigPackageProviderImpl)
config.options.has_toy = False
config.gather_options()
calls = [call([ConfigOptionPackageImpl])]
config.add_option_packages.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_conditionalsNotAvailable_raiseAttributeError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_package_provider(ConfigPackageProviderImpl)
with self.assertRaises(AttributeError):
config.gather_options()
calls = [call([ConfigOptionPackageImpl])]
config.add_option_packages.assert_has_calls(calls)
class BaseConfigPackageTests(TestCase):
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackages_correctTypesInList_noError(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
try:
config.add_option_packages([ConfigOptionPackageImpl, ConfigOptionPackageConditionalRequiredImpl2])
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackages_wrongTypeInList_raiseTypeError(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
with self.assertRaises(TypeError):
config.add_option_packages([ConfigOptionPackageImpl, WrongConfigOptionPackageImpl])
with self.assertRaises(TypeError):
config.add_option_packages([ConfigOptionPackageImpl, ConfigPackageProviderImpl])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackage_correctTypesInList_noError(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
try:
config.add_option_package(ConfigOptionPackageImpl)
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackage_wrongType_raiseTypeError(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
with self.assertRaises(TypeError):
config.add_option_package(WrongConfigOptionPackageImpl)
with self.assertRaises(TypeError):
config.add_option_package(ConfigPackageProviderImpl)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackage_doubleRegistration_onlyOnceInConfig(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.add_option_package(ConfigOptionPackageImpl)
config.add_option_package(ConfigOptionPackageImpl)
self.assertIs(config.option_packages.count(ConfigOptionPackageImpl), 1)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackage_withModifications_necessaryPackagesAdded(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.add_option_package(ConfigOptionPackageImpl)
self.assertIs(len(config.option_packages), 2)
self.assertTrue(ConfigOptionPackageImpl in config.option_packages)
self.assertTrue(ConfigOptionPackageRequiredImpl in config.option_packages)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addOptionPackage_withModifications_defaultsModified(self):
config = BaseConfig()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.add_option_package(ConfigOptionPackageImpl)
config.apply_default_modifications.assert_called_with(ConfigOptionPackageImpl.default_modifications)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_optionConditionalsMet_addedConditionalOptions(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'dog'
config.gather_options()
calls = [call(ConfigOptionPackageImpl.conditional_options_metadata)]
config.add_multiple_option_metadata.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_optionConditionalsNotMet_conditionalOptionsNotAdded(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'cat'
config.gather_options()
calls = [call([])]
config.add_multiple_option_metadata.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_optionConditionalsNotAvailable_raiseAttributeError(self):
config = BaseConfig()
config.add_option_packages = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
with self.assertRaises(AttributeError):
config.gather_options()
config.add_multiple_option_metadata.assert_not_called()
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsMet_necessaryPackagesAdded(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'dog'
config.gather_options()
calls = [call(ConfigOptionPackageConditionalRequiredImpl1)]
config.add_option_package.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsMet_defaultsModified(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'dog'
config.gather_options()
calls = [call(ConfigOptionPackageImpl.conditional_default_modifications)]
config.apply_default_modifications.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsNotMet_noPackagesAdded(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'cat'
config.gather_options()
config.add_option_package.assert_not_called()
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsNotMet_noDefaultsModified(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
config.options.type = 'cat'
config.gather_options()
calls = [call([])]
config.apply_default_modifications.assert_has_calls(calls)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsNotAvailable_raiseAttributeError(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
with self.assertRaises(AttributeError):
config.gather_options()
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_modificationConditionalsNotAvailable_raiseAttributeError(self):
config = BaseConfig()
config.add_option_package = MagicMock()
config.add_multiple_option_metadata = MagicMock()
config.apply_default_modifications = MagicMock()
config.option_packages = [ConfigOptionPackageImpl]
with self.assertRaises(AttributeError):
config.gather_options()
class BaseConfigOptionTests(TestCase):
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMultipleMetadata_correctTypesInList_noError(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
try:
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name', 'default', 'help', False),
ConfigOptionMetadata(int, 'name1', 1, 'help', False),
ConfigOptionMetadata(str, 'name2', None, 'help', True),
])
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMultipleMetadata_wrongTypesInList_raiseTypeError(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
with self.assertRaises(TypeError):
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name', 'default', 'help', False),
ConfigOptionMetadata(int, 'name1', 1, 'help', False),
ConfigDefaultModification(None, 'name', 'value'),
])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_correctType_noError(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
try:
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', False))
config.add_option_metadata(ConfigOptionMetadata(int, 'name1', 1, 'help', False))
config.add_option_metadata(ConfigOptionMetadata(str, 'name2', 'default2', 'help', True))
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_correctType_metadataInConfig(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'default', 'help', False)
config.add_option_metadata(metadata)
self.assertTrue(metadata in config.options_metadata.values())
self.assertEqual(metadata, config.options_metadata[metadata.name])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_correctType_createAndAddOptionCalled(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'default', 'help', False)
config.add_option_metadata(metadata)
config.create_and_add_option.assert_called_with(metadata)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_choiceIsInvalidDtype_raiseTypeError(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'default1', 'help', False)
metadata.choices = ['default1', 0]
with self.assertRaises(TypeError):
config.add_option_metadata(metadata)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_defaultNotInChoices_raiseValueError(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'no choice', 'help', False)
metadata.choices = ['default1', 'default2']
with self.assertRaises(ValueError):
config.add_option_metadata(metadata)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_defaultInChoices_metadataInConfig(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'default1', 'help', False, choices=['default1', 'default2'])
config.add_option_metadata(metadata)
self.assertTrue(metadata in config.options_metadata.values())
self.assertEqual(metadata, config.options_metadata[metadata.name])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_addMetadata_defaultInChoices_createAndAddOptionCalled(self):
config = BaseConfig()
config.create_and_add_option = MagicMock()
metadata = ConfigOptionMetadata(str, 'name', 'default1', 'help', False, choices=['default1', 'default2'])
config.add_option_metadata(metadata)
config.create_and_add_option.assert_called_with(metadata)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_requiredIsGiven_noError(self):
config = BaseConfig()
config.options_metadata = {'name': ConfigOptionMetadata(str, 'name', None, 'help', True)}
config.options.name = 'test'
try:
config.gather_options()
except RuntimeError:
self.fail('Unexpected RuntimeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_gatherOptions_requiredIsNone_raiseRuntimeError(self):
config = BaseConfig()
config.options_metadata = {'name': ConfigOptionMetadata(str, 'name', None, 'help', True)}
config.options.name = None
with self.assertRaises(RuntimeError):
config.gather_options()
class BaseConfigModificationTests(TestCase):
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModifications_correctTypesInList_noError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
metadata = [
ConfigOptionMetadata(str, 'name1', 'default1', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', 'default3', 'help', True),
]
config.add_multiple_option_metadata(metadata)
config.add_option_package(ConfigOptionPackageRequiredImpl)
try:
config.apply_default_modifications([
ConfigDefaultModification(None, 'name1', 'new default 1'),
ConfigDefaultModification(None, 'name2', 0),
ConfigDefaultModification(None, 'name3', 'new default 3'),
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'coat_color', 'red'),
])
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModifications_wrongTypesInList_raiseTypeError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
metadata = [
ConfigOptionMetadata(str, 'name1', 'default1', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', 'default3', 'help', True),
]
config.add_multiple_option_metadata(metadata)
config.add_option_package(ConfigOptionPackageRequiredImpl)
with self.assertRaises(TypeError):
config.apply_default_modifications([
ConfigDefaultModification(None, 'name1', 'new default 1'),
ConfigDefaultModification(None, 'name2', 0),
ConfigDefaultModification(None, 'name3', 'new default 3'),
ConfigOptionMetadata(str, 'name4', 'default4', 'help', False),
])
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_correctType_noError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
metadata = [
ConfigOptionMetadata(str, 'name1', 'default1', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', 'default3', 'help', True),
]
config.add_multiple_option_metadata(metadata)
config.add_option_package(ConfigOptionPackageRequiredImpl)
try:
config.apply_default_modification(ConfigDefaultModification(None, 'name1', 'new default 1'))
config.apply_default_modification(ConfigDefaultModification(None, 'name2', 0))
config.apply_default_modification(ConfigDefaultModification(None, 'name3', 'new default 3'))
config.apply_default_modification(
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'coat_color', 'red'))
except TypeError:
self.fail('Unexpected TypeError')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_packageNotInConfig_raiseValueError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
with self.assertRaises(ValueError):
config.apply_default_modification(
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'coat_color', 'red'))
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_nameNotInPackage_raiseValueError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
config.add_option_package(ConfigOptionPackageRequiredImpl)
with self.assertRaises(ValueError):
config.apply_default_modification(
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'color', 'red'))
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_nameNotInConfig_raiseValueError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
with self.assertRaises(ValueError):
config.apply_default_modification(ConfigDefaultModification(None, 'name1', 'new default 1'))
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_wrongDtype_raiseTypeError(self):
config = BaseConfig()
config.set_option_value = MagicMock()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', False))
with self.assertRaises(TypeError):
config.apply_default_modification(ConfigDefaultModification(None, 'name', 0))
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_valid_defaultChanged(self):
config = BaseConfig()
config.set_option_value = MagicMock()
metadata = [
ConfigOptionMetadata(str, 'name1', 'default1', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
]
config.add_multiple_option_metadata(metadata)
config.add_option_package(ConfigOptionPackageRequiredImpl)
config.apply_default_modification(ConfigDefaultModification(None, 'name1', 'new default 1'))
config.apply_default_modification(ConfigDefaultModification(None, 'name2', 0))
config.apply_default_modification(ConfigDefaultModification(None, 'name3', 'new default 3'))
config.apply_default_modification(
ConfigDefaultModification(ConfigOptionPackageRequiredImpl, 'coat_color', 'red'))
self.assertEqual(config.options_metadata['name1'].default, 'new default 1')
self.assertEqual(config.options_metadata['name2'].default, 0)
self.assertEqual(config.options_metadata['name3'].default, 'new default 3')
self.assertEqual(config.options_metadata['coat_color'].default, 'red')
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_requiredNotExplicitlyChanged_valueChanged(self):
config = BaseConfig()
config.set_option_value = MagicMock()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', None, 'help', True))
config.apply_default_modification(ConfigDefaultModification(None, 'name', 'default'))
config.set_option_value.assert_called_with('name', 'default')
self.assertIs(config.options_metadata["name"].value_was_explicitly_changed, False)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_applyDefaultModification_requiredExplicitlyChanged_valueNotChanged(self):
config = BaseConfig()
config.set_option_value = MagicMock()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', None, 'help', True))
config.options_metadata["name"].value_was_explicitly_changed = True
config.apply_default_modification(ConfigDefaultModification(None, 'name', 'default'))
config.set_option_value.assert_not_called()
self.assertIs(config.options_metadata["name"].value_was_explicitly_changed, True)
class BaseConfigUtilityTest(TestCase):
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_str_emptyConfig_stringEmpty(self):
config = BaseConfig()
expected = ''
actual = str(config)
self.assertEqual(expected, actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_str_fullConfig_stringAsExpected(self):
config = BaseConfig()
config.options.string = 'str'
config.options.integer = 0
config.options.float = 1.0
config.options.enum = TestEnum.a
expected = '{:>25}: {:<30}\n'.format('enum', str(TestEnum.a)) \
+ '{:>25}: {:<30}\n'.format('float', str(1.0)) \
+ '{:>25}: {:<30}\n'.format('integer', str(0)) \
+ '{:>25}: {:<30}'.format('string', str('str'))
actual = str(config)
self.assertEqual(expected, actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withProviderClass_returnTrue(self):
config = BaseConfig()
config.package_provider.append(ConfigPackageProviderImpl)
try:
actual = ConfigPackageProviderImpl in config
except:
self.fail('Unexpected Error occured')
self.assertTrue(actual)
try:
actual = ConfigPackageProviderImpl() in config
except:
self.fail('Unexpected Error occured')
self.assertTrue(actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withoutProviderClass_returnFalse(self):
config = BaseConfig()
try:
actual = ConfigPackageProviderImpl in config
except:
self.fail('Unexpected Error occured')
self.assertFalse(actual)
try:
actual = ConfigPackageProviderImpl() in config
except:
self.fail('Unexpected Error occured')
self.assertFalse(actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withPackageClass_returnTrue(self):
config = BaseConfig()
config.option_packages.append(ConfigOptionPackageImpl)
try:
actual = ConfigOptionPackageImpl in config
except:
self.fail('Unexpected Error occured')
self.assertTrue(actual)
try:
actual = ConfigOptionPackageImpl() in config
except:
self.fail('Unexpected Error occured')
self.assertTrue(actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withoutPackageClass_returnFalse(self):
config = BaseConfig()
try:
actual = ConfigOptionPackageImpl in config
except:
self.fail('Unexpected Error occured')
self.assertFalse(actual)
try:
actual = ConfigOptionPackageImpl() in config
except:
self.fail('Unexpected Error occured')
self.assertFalse(actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withMetadataInstance_returnTrue(self):
config = BaseConfig()
config.options_metadata = {'name', ConfigOptionMetadata(str, 'name', 'default', 'help')}
try:
actual = 'name' in config
except:
self.fail('Unexpected Error occured')
self.assertTrue(actual)
@patch.object(BaseConfig, '__abstractmethods__', set())
def test_contains_withoutMetadataInstance_returnFalse(self):
config = BaseConfig()
try:
actual = 'name' in config
except:
self.fail('Unexpected Error occured')
self.assertFalse(actual)
class StandardConfigTests(TestCase):
def test_createAndAddOption_notRequired_addedToOptions(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', False))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'default')
def test_createAndAddOption_requiredWithExplicitNoDefault_addedToOptionsWithExplicitValue(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', None, 'help', True))
config['name'] = 'required'
self.assertEqual(len(vars(config.options)), 1)
self.assertTrue(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'required')
def test_createAndAddOption_requiredNoExplicitWithDefault_addedToOptionsWithDefaultValue(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', True))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'default')
def test_createAndAddOption_requiredWithExplicitWithDefault_addedToOptionsWithExplicitValue(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', True))
config['name'] = 'required'
self.assertEqual(len(vars(config.options)), 1)
self.assertTrue(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'required')
def test_createAndAddOption_enumAttribute_addedToOptions(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(TestEnum, 'name', TestEnum.a, 'help', False, list(TestEnum)))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, TestEnum.a)
def test_createAndAddOption_withArguments_valueFromArguments(self):
config = StandardConfig({'name': TestEnum.c})
config.add_option_metadata(ConfigOptionMetadata(TestEnum, 'name', TestEnum.a, 'help', False, list(TestEnum)))
self.assertEqual(len(vars(config.options)), 1)
self.assertTrue(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, TestEnum.c)
def test_setitem_wrongType_raiseTypeError(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help'))
with self.assertRaises(TypeError):
config['name'] = 0
def test_setitem_notInChoices_raiseValueError(self):
config = StandardConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default1', 'help', choices=['default1', 'default2']))
with self.assertRaises(ValueError):
config['name'] = 'test'
def test_setitem_correctType_valueSet(self):
config = StandardConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default', 'help'))
config['name'] = 'test'
self.assertEqual(config['name'], 'test')
def test_setitem_inChoices_valueSet(self):
config = StandardConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default1', 'help', choices=['default1', 'default2']))
config['name'] = 'default1'
self.assertEqual(config['name'], 'default1')
def test_setitem_isConstant_raiseAttributeError(self):
config = StandardConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default1', 'help', is_constant=True))
with self.assertRaises(AttributeError):
config['name'] = 'default1'
def test_valuesFromString_emptyString_raiseValueError(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = ''
with self.assertRaises(ValueError):
config.set_values_from_string(s)
def test_valuesFromString_emptyStringIgnoreUnexpected_noErrorAndNothingChanged(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = ''
try:
config.set_values_from_string(s, True)
except:
self.fail('Unexpected Error')
self.assertIs(len(vars(config.options)), 4)
self.assertFalse(config.options_metadata['name1'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name2'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name3'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name4'].value_was_explicitly_changed)
self.assertEqual(config.options.name1, 'default')
self.assertEqual(config.options.name2, 1)
self.assertEqual(config.options.name3, None)
self.assertEqual(config.options.name4, TestEnum.a)
def test_valuesFromString_unexpectedAttribute_raiseValueError(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = '{:>25}: {:<30}\n'.format('unexpected', 'test')
with self.assertRaises(ValueError):
config.set_values_from_string(s)
def test_valuesFromString_unexpectedAttributeIgnored_noErrorAndNothingChanged(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = '{:>25}: {:<30}\n'.format('unexpected', 'test')
try:
config.set_values_from_string(s, True)
except:
self.fail('Unexpected Error')
self.assertIs(len(vars(config.options)), 4)
self.assertFalse(config.options_metadata['name1'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name2'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name3'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name4'].value_was_explicitly_changed)
self.assertEqual(config.options.name1, 'default')
self.assertEqual(config.options.name2, 1)
self.assertEqual(config.options.name3, None)
self.assertEqual(config.options.name4, TestEnum.a)
def test_valuesFromString_oneAttribute_onlyOneValueChanged(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = '{:>25}: {:<30}'.format('name1', 'test')
try:
config.set_values_from_string(s)
except:
self.fail('Unexpected Error')
self.assertIs(len(vars(config.options)), 4)
self.assertTrue(config.options_metadata['name1'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name2'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name3'].value_was_explicitly_changed)
self.assertFalse(config.options_metadata['name4'].value_was_explicitly_changed)
self.assertEqual(config.options.name1, 'test')
self.assertEqual(config.options.name2, 1)
self.assertEqual(config.options.name3, None)
self.assertEqual(config.options.name4, TestEnum.a)
def test_valuesFromString_allAttributes_allValuesChanged(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = '' \
+ '{:>25}: {:<30}\n'.format('name1', 'test') \
+ '{:>25}: {:<30}\n'.format('name2', str(0)) \
+ '{:>25}: {:<30}\n'.format('name3', 'not None') \
+ '{:>25}: {:<30}'.format('name4', str(TestEnum.b))
try:
config.set_values_from_string(s)
except:
self.fail('Unexpected Error')
self.assertIs(len(vars(config.options)), 4)
self.assertTrue(config.options_metadata['name1'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name2'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name3'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name4'].value_was_explicitly_changed)
self.assertEqual(config.options.name1, 'test')
self.assertEqual(config.options.name2, 0)
self.assertEqual(config.options.name3, 'not None')
self.assertEqual(config.options.name4, TestEnum.b)
def test_valuesFromString_strippedStringAllAttributes_allValuesChanged(self):
config = StandardConfig()
config.add_multiple_option_metadata([
ConfigOptionMetadata(str, 'name1', 'default', 'help', False),
ConfigOptionMetadata(int, 'name2', 1, 'help', False),
ConfigOptionMetadata(str, 'name3', None, 'help', True),
ConfigOptionMetadata(TestEnum, 'name4', TestEnum.a, 'help', False, list(TestEnum)),
])
s = 'name1: test\nname2: 0\nname3: not None\nname4: {}'.format(str(TestEnum.b))
try:
config.set_values_from_string(s)
except:
self.fail('Unexpected Error')
self.assertIs(len(vars(config.options)), 4)
self.assertTrue(config.options_metadata['name1'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name2'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name3'].value_was_explicitly_changed)
self.assertTrue(config.options_metadata['name4'].value_was_explicitly_changed)
self.assertEqual(config.options.name1, 'test')
self.assertEqual(config.options.name2, 0)
self.assertEqual(config.options.name3, 'not None')
self.assertEqual(config.options.name4, TestEnum.b)
class ArgparseConfigTests(TestCase):
def test_createAndAddOption_notRequired_addedToOptions(self):
config = ArgparseConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', False))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'default')
def test_createAndAddOption_requiredWithExplicitNoDefault_addedToOptionsWithExplicitValue(self):
config = ArgparseConfig()
config.parser_args = ['--name', 'required']
config.add_option_metadata(ConfigOptionMetadata(str, 'name', None, 'help', True))
self.assertEqual(len(vars(config.options)), 1)
self.assertTrue(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'required')
def test_createAndAddOption_requiredNoExplicitWithDefault_addedToOptionsWithDefaultValue(self):
config = ArgparseConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', True))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'default')
def test_createAndAddOption_requiredWithExplicitWithDefault_addedToOptionsWithExplicitValue(self):
config = ArgparseConfig()
config.parser_args = ['--name', 'required']
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', True))
self.assertEqual(len(vars(config.options)), 1)
self.assertTrue(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'required')
def test_createAndAddOption_enumAttribute_addedToOptions(self):
config = ArgparseConfig()
config.add_option_metadata(ConfigOptionMetadata(TestEnum, 'name', TestEnum.a, 'help', False, list(TestEnum)))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, TestEnum.a)
def test_createAndAddOption_constantOption_seDefaultAlthoughExplicitIsGiven(self):
config = ArgparseConfig()
config.parser_args = ['--name', 'modification']
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default', 'help', is_constant=True))
self.assertEqual(len(vars(config.options)), 1)
self.assertFalse(config.options_metadata['name'].value_was_explicitly_changed)
self.assertEqual(config.options.name, 'default')
def test_setitem_wrongType_raiseTypeError(self):
config = ArgparseConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default', 'help'))
with self.assertRaises(TypeError):
config['name'] = 0
def test_setitem_notInChoices_raiseValueError(self):
config = ArgparseConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default1', 'help', choices=['default1', 'default2']))
with self.assertRaises(ValueError):
config['name'] = 'test'
def test_setitem_correctType_valueSet(self):
config = ArgparseConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default', 'help'))
config['name'] = 'test'
self.assertEqual(config['name'], 'test')
def test_setitem_inChoices_valueSet(self):
config = ArgparseConfig()
config.add_option_metadata(
ConfigOptionMetadata(str, 'name', 'default1', 'help', choices=['default1', 'default2']))
config['name'] = 'default1'
self.assertEqual(config['name'], 'default1')
def test_setitem_isConstant_raiseAttributeError(self):
config = ArgparseConfig()
config.add_option_metadata(ConfigOptionMetadata(str, 'name', 'default1', 'help', is_constant=True))
with self.assertRaises(AttributeError):
config['name'] = 'default1'
if __name__ == '__main__':
unittest.main()
| 42.294504 | 117 | 0.687996 | 4,699 | 51,557 | 7.297084 | 0.05831 | 0.029922 | 0.031497 | 0.055645 | 0.865992 | 0.839336 | 0.822217 | 0.790953 | 0.749628 | 0.700837 | 0 | 0.00798 | 0.202785 | 51,557 | 1,218 | 118 | 42.329228 | 0.826262 | 0 | 0 | 0.757895 | 0 | 0 | 0.085342 | 0 | 0 | 0 | 0 | 0 | 0.177895 | 1 | 0.107368 | false | 0 | 0.004211 | 0.009474 | 0.152632 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
b535ac9603f0960de718f40de0134ae852c17444 | 201 | py | Python | noughtpad_app/admin.py | codelixir/nought-pad | 79987a87070ca5c9f48303ca701d00cf0bb27eac | [
"MIT"
] | 4 | 2021-07-03T10:26:25.000Z | 2021-08-21T07:59:15.000Z | noughtpad_app/admin.py | codelixir/nought-pad | 79987a87070ca5c9f48303ca701d00cf0bb27eac | [
"MIT"
] | 2 | 2021-06-30T18:48:03.000Z | 2021-10-03T12:03:30.000Z | noughtpad_app/admin.py | codelixir/nought-pad | 79987a87070ca5c9f48303ca701d00cf0bb27eac | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Note, Category, Comment, Profile
admin.site.register(Note)
admin.site.register(Profile)
admin.site.register(Category)
admin.site.register(Comment)
| 25.125 | 52 | 0.81592 | 28 | 201 | 5.857143 | 0.428571 | 0.219512 | 0.414634 | 0.292683 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.079602 | 201 | 7 | 53 | 28.714286 | 0.886486 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.333333 | 0 | 0.333333 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 7 |
a958e9e7b4b0bb90f5d6be48dda6d5dbcd93560d | 5,004 | py | Python | spylind/tf_misc.py | morgatron/spylind | 27a201cebf111cc36765077028a3211ec386ddc2 | [
"BSD-3-Clause"
] | 1 | 2020-09-27T17:16:04.000Z | 2020-09-27T17:16:04.000Z | spylind/tf_misc.py | morgatron/spylind | 27a201cebf111cc36765077028a3211ec386ddc2 | [
"BSD-3-Clause"
] | null | null | null | spylind/tf_misc.py | morgatron/spylind | 27a201cebf111cc36765077028a3211ec386ddc2 | [
"BSD-3-Clause"
] | null | null | null | import tensorflow as tf
class InterpolatorMask(tf.keras.Model):
def __init__(self, xOrig, yOrig): #pars are parameters to the ode
super().__init__()
self.xOrig = tf.constant(tf.convert_to_tensor(xOrig, dtype=tf.float64))
self.yOrig = tf.Variable(tf.convert_to_tensor(yOrig, dtype=tf.float64), name='yOrig')
self.N = xOrig.shape[0]
self.dx = xOrig[1]-xOrig[0]
self.x0 = xOrig[0]
self.xMax = xOrig[-1]
self.zero = tf.constant(0, dtype=tf.float64)
self.mask = tf.concat([tf.constant([0.5,0.5], dtype='float64'), tf.zeros(xOrig.shape[0]-2, dtype='float64') ], axis=0)
def set_y(self, yNew):
self.yOrig.assign(yNew)
def call(self, x):
#pdb.set_trace()
#ind = tf.math.floormod((x-x0), dx)
if x>=self.xMax or x<self.x0:
retVal= self.zero#tf.constant(0., dtype=tf.float64);
else:
ind = tf.math.floordiv(x-self.x0, self.dx)
remainder = x- ind*self.dx
ind = tf.cast(ind, tf.int64)
res = tf.roll(self.mask, ind, axis=0)*self.yOrig
retVal = tf.reduce_sum(res)
#tf.print(retVal)
return retVal
class InterpolatorMask2(tf.keras.Model):
def __init__(self, xOrig, yOrig): #pars are parameters to the ode
super().__init__()
self.xOrig = tf.constant(tf.convert_to_tensor(xOrig, dtype=tf.float64))
self.yOrig = tf.Variable(tf.convert_to_tensor(yOrig, dtype=tf.float64), name='yOrig')
self.N = xOrig.shape[0]
self.dx = xOrig[1]-xOrig[0]
self.x0 = xOrig[0]
self.xMax = xOrig[-1]
self.zero = tf.constant(0, dtype=tf.float64)
self.mask = tf.concat([tf.constant([0.5,0.5], dtype='float64'), tf.zeros(xOrig.shape[0]-2, dtype='float64') ], axis=0)
def set_y(self, yNew):
self.yOrig.assign(yNew)
def call(self, x):
#pdb.set_trace()
#ind = tf.math.floormod((x-x0), dx)
ind_f = tf.math.floordiv(x-self.x0, self.dx)
ind=tf.cast(ind_f, tf.int64)
if ind < 0 or ind >= self.N-1:
retVal= tf.constant(0., dtype=tf.float64);
else:
remainder = (x/self.dx- ind_f)
#tf.print(remainder)
retVal = (1.-remainder)*self.yOrig[ind] + remainder*self.yOrig[ind+1]
#tf.print(retVal)
return retVal
class InterpolatorMaskArgs(tf.keras.Model):
def __init__(self, xOrig): #pars are parameters to the ode
super().__init__()
self.xOrig = tf.constant(tf.convert_to_tensor(xOrig, dtype=tf.float64))
self.N = xOrig.shape[0]
self.dx = xOrig[1]-xOrig[0]
self.x0 = xOrig[0]
self.xMax = xOrig[-1]
self.zero = tf.constant(0, dtype=tf.float64)
self.mask = tf.concat([tf.constant([0.5,0.5], dtype='float64'), tf.zeros(xOrig.shape[0]-2, dtype='float64') ], axis=0)
def call(self, x, yOrig):
#pdb.set_trace()
#ind = tf.math.floormod((x-x0), dx)
if x>=self.xMax or x<self.x0:
return self.zero#tf.constant(0., dtype=tf.float64);
else:
ind = tf.math.floordiv(x-self.x0, self.dx)
remainder = x- ind*self.dx
ind = tf.cast(ind, tf.int64)
res = tf.roll(self.mask, ind, axis=0)*yOrig
return tf.reduce_sum(res)
return f
def tf_interpolator(xOrig, yOrig):
xOrig = tf.constant(tf.convert_to_tensor(xOrig, dtype=tf.float64))
yOrig = tf.constant(tf.convert_to_tensor(yOrig, dtype=tf.float64))
N = xOrig.shape[0]
dx = xOrig[1]-xOrig[0]
x0 = xOrig[0]
xMax = xOrig[-1]
zero = tf.constant(0, dtype=tf.float64)
#@tf.function(experimental_compile=True)
def f(x):
#pdb.set_trace()
#ind = tf.math.floormod((x-x0), dx)
if x>=xMax or x<x0:
return zero#tf.constant(0., dtype=tf.float64);
else:
ind_f = tf.math.floordiv(x-x0, dx)
remainder = (x/dx- ind_f)
ind=tf.cast(ind_f, tf.int64)
#tf.print(remainder)
return (1.-remainder)*yOrig[ind] + remainder*yOrig[ind+1]
return f
def tf_interpolator2(xOrig, yOrig):
xOrig = tf.constant(tf.convert_to_tensor(xOrig, dtype=tf.float64))
#yOrig = tf.constant(tf.convert_to_tensor(yOrig, dtype=tf.float64))
N = xOrig.shape[0]
dx = xOrig[1]-xOrig[0]
x0 = xOrig[0]
xMax = xOrig[-1]
zero = tf.constant(0, dtype=tf.float64)
mask = tf.concat([tf.constant([0.5,0.5], dtype='float64'), tf.zeros(xOrig.shape[0]-2, dtype='float64') ], axis=0)
def f(x):
#pdb.set_trace()
#ind = tf.math.floormod((x-x0), dx)
if x>=xMax or x<x0:
return zero#tf.constant(0., dtype=tf.float64);
else:
ind = tf.math.floordiv(x-x0, dx)
remainder = x- ind*dx
ind=tf.cast(ind, tf.int64)
res = tf.roll(mask, ind, axis=0)*yOrig
return tf.reduce_sum(res)
return f
| 38.198473 | 126 | 0.578337 | 745 | 5,004 | 3.802685 | 0.100671 | 0.074126 | 0.093893 | 0.056477 | 0.864455 | 0.864455 | 0.841511 | 0.807271 | 0.782563 | 0.782563 | 0 | 0.04264 | 0.264189 | 5,004 | 130 | 127 | 38.492308 | 0.726779 | 0.129097 | 0 | 0.742574 | 0 | 0 | 0.015225 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.118812 | false | 0 | 0.009901 | 0 | 0.267327 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
a95e2de7a7d8c36a4ac26a52825eb84e1f4f2df3 | 286 | py | Python | hooks/post_gen_project.py | wrist/vst3_plugin_cookiecutter | aeff6f807561e61306da8eaecfd7eac2f70319f1 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | hooks/post_gen_project.py | wrist/vst3_plugin_cookiecutter | aeff6f807561e61306da8eaecfd7eac2f70319f1 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | hooks/post_gen_project.py | wrist/vst3_plugin_cookiecutter | aeff6f807561e61306da8eaecfd7eac2f70319f1 | [
"Unlicense",
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
print("")
print("New project {{ cookiecutter.PLUGIN_NAME_CLI }} is generated!")
print("Please generate two uuids manually (ex. `uuidgen`) and replace uids in {{ cookiecutter.PLUGIN_NAME_CLI }}/source/{{ cookiecutter.PREFIX_FOR_FILENAMES_CLI }}cids.h with that.")
| 47.666667 | 182 | 0.751748 | 40 | 286 | 5.2 | 0.8 | 0.173077 | 0.211538 | 0.240385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.101399 | 286 | 5 | 183 | 57.2 | 0.809339 | 0.06993 | 0 | 0 | 1 | 0.333333 | 0.879245 | 0.350943 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
a98974fa429a3552e73ce32b5318270707f3b05f | 20,315 | py | Python | CNN_models/models.py | woshialex/lasagne_CNN_framework | 856b56c9f076ce77aba0d6b00adf9c9e02ff80f0 | [
"MIT"
] | 3 | 2016-05-22T17:09:11.000Z | 2018-01-04T07:43:17.000Z | CNN_models/models.py | woshialex/lasagne_CNN_framework | 856b56c9f076ce77aba0d6b00adf9c9e02ff80f0 | [
"MIT"
] | null | null | null | CNN_models/models.py | woshialex/lasagne_CNN_framework | 856b56c9f076ce77aba0d6b00adf9c9e02ff80f0 | [
"MIT"
] | 2 | 2016-06-01T09:45:13.000Z | 2019-01-29T10:51:49.000Z | import theano
import theano.tensor as T
import lasagne as nn
from lasagne.layers import batch_norm as bn
import os
import numpy as np
import sys
sys.path.append('..')
from SETTINGS import params_dir
def build_cnn(input_var, shape, version=1, N_output=10):
ret = {}
if N_output == 1:
output_fn = nn.nonlinearities.sigmoid;
else:
output_fn = nn.nonlinearities.softmax;
nlf = nn.nonlinearities.LeakyRectify(leakiness = 0.1);
if version == 1:
ret['input'] = layer = nn.layers.InputLayer(shape, input_var)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=16, filter_size=(5,5), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(5,5), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=256, filter_size=(3,3), nonlinearity = nlf))
ret['flatten'] = layer = nn.layers.FlattenLayer(layer);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 128, nonlinearity = nlf);
ret['output'] = layer = nn.layers.DenseLayer(layer, num_units=N_output, nonlinearity=output_fn)
elif version == 2:
ret['input'] = layer = nn.layers.InputLayer(shape, input_var)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=48, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=48, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['flatten'] = layer = nn.layers.FlattenLayer(layer);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 64, nonlinearity = nlf);
ret['output'] = layer = nn.layers.DenseLayer(layer, num_units=N_output, nonlinearity=output_fn)
elif version == 3:#196, CV=0.66
ret['input'] = layer = nn.layers.InputLayer(shape, input_var)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=16, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=16, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=164, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=164, filter_size=(3,3), nonlinearity = nlf))
ret['flatten'] = layer = nn.layers.FlattenLayer(layer);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 64, nonlinearity = nlf);
ret['output'] = layer = nn.layers.DenseLayer(layer, num_units=N_output, nonlinearity=output_fn)
elif version == 4: #196
ret['input'] = layer = nn.layers.InputLayer(shape, input_var)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=256, filter_size=(3,3), nonlinearity = nlf))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=512, filter_size=(3,3), nonlinearity = nlf))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=512, filter_size=(3,3), nonlinearity = nlf))
ret['flatten'] = layer = nn.layers.FlattenLayer(layer);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 512, nonlinearity = nlf);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 128, nonlinearity = nlf);
ret['output'] = layer = nn.layers.DenseLayer(layer, num_units=N_output, nonlinearity=output_fn)
elif version == 5:#VGG 16, LB = 0.32
from lasagne.layers import Conv2DLayer as ConvLayer;
from lasagne.layers import MaxPool2DLayer as PoolLayer;
ret['input'] = nn.layers.InputLayer((None,3,224,224), input_var)
ret['conv1_1'] = ConvLayer(ret['input'], 64, 3, pad=1, flip_filters=False)
for k,x in ret['conv1_1'].params.iteritems():
x.remove('trainable')
ret['conv1_2'] = ConvLayer(ret['conv1_1'], 64, 3, pad=1, flip_filters=False)
for k,x in ret['conv1_2'].params.iteritems():
x.remove('trainable')
ret['pool1'] = PoolLayer(ret['conv1_2'], 2)
ret['conv2_1'] = ConvLayer( ret['pool1'], 128, 3, pad=1, flip_filters=False)
for k,x in ret['conv2_1'].params.iteritems():
x.remove('trainable')
ret['conv2_2'] = ConvLayer( ret['conv2_1'], 128, 3, pad=1, flip_filters=False)
ret['pool2'] = PoolLayer(ret['conv2_2'], 2)
ret['conv3_1'] = ConvLayer( ret['pool2'], 256, 3, pad=1, flip_filters=False)
ret['conv3_2'] = ConvLayer( ret['conv3_1'], 256, 3, pad=1, flip_filters=False)
ret['conv3_3'] = ConvLayer( ret['conv3_2'], 256, 3, pad=1, flip_filters=False)
ret['pool3'] = PoolLayer(ret['conv3_3'], 2)
ret['conv4_1'] = ConvLayer( ret['pool3'], 512, 3, pad=1, flip_filters=False)
ret['conv4_2'] = ConvLayer( ret['conv4_1'], 512, 3, pad=1, flip_filters=False)
ret['conv4_3'] = ConvLayer( ret['conv4_2'], 512, 3, pad=1, flip_filters=False)
ret['pool4'] = PoolLayer(ret['conv4_3'], 2)
ret['conv5_1'] = ConvLayer( ret['pool4'], 512, 3, pad=1, flip_filters=False)
ret['conv5_2'] = ConvLayer( ret['conv5_1'], 512, 3, pad=1, flip_filters=False)
ret['conv5_3'] = ConvLayer( ret['conv5_2'], 512, 3, pad=1, flip_filters=False)
ret['pool5'] = PoolLayer(ret['conv5_3'], 2)
ret['fc6'] = nn.layers.DenseLayer(ret['pool5'], num_units=4096)
ret['fc6_dropout'] = nn.layers.dropout(ret['fc6'], p=0.5)
ret['fc7'] = nn.layers.DenseLayer(ret['fc6_dropout'], num_units=4096)
ret['fc7_dropout'] = nn.layers.dropout(ret['fc7'], p=0.5)
ret['fc8'] = nn.layers.DenseLayer(ret['fc7_dropout'], num_units=1000, nonlinearity=None)
ret['output'] = nn.layers.NonlinearityLayer(ret['fc8'], nn.nonlinearities.softmax)
import pickle
model = pickle.load(open(params_dir+'/vgg16.pkl'));
nn.layers.set_all_param_values(ret['output'],model['param values']);
ret.pop("output",None);
ret.pop("fc8",None);
ret['output'] = nn.layers.DenseLayer(ret['fc7_dropout'], num_units=N_output, nonlinearity=output_fn)
elif version == 6:#VGG 16 # 0.31
nlf = nn.nonlinearities.LeakyRectify(leakiness = 0.1);
from lasagne.layers import Conv2DLayer as ConvLayer;
from lasagne.layers import MaxPool2DLayer as PoolLayer;
ret['input'] = nn.layers.InputLayer((None,3,224,224), input_var)
ret['conv1_1'] = ConvLayer(ret['input'], 64, 3, pad=1, flip_filters=False)
for k,x in ret['conv1_1'].params.iteritems():
x.remove('trainable')
ret['conv1_2'] = ConvLayer(ret['conv1_1'], 64, 3, pad=1, flip_filters=False)
for k,x in ret['conv1_2'].params.iteritems():
x.remove('trainable')
ret['pool1'] = PoolLayer(ret['conv1_2'], 2)
ret['conv2_1'] = ConvLayer( ret['pool1'], 128, 3, pad=1, flip_filters=False)
for k,x in ret['conv2_1'].params.iteritems():
x.remove('trainable')
ret['conv2_2'] = ConvLayer( ret['conv2_1'], 128, 3, pad=1, flip_filters=False)
for k,x in ret['conv2_2'].params.iteritems():
x.remove('trainable')
ret['pool2'] = PoolLayer(ret['conv2_2'], 2)
ret['conv3_1'] = ConvLayer( ret['pool2'], 256, 3, pad=1, flip_filters=False)
for k,x in ret['conv3_1'].params.iteritems():
x.remove('trainable')
ret['conv3_2'] = ConvLayer( ret['conv3_1'], 256, 3, pad=1, flip_filters=False)
for k,x in ret['conv3_2'].params.iteritems():
x.remove('trainable')
ret['conv3_3'] = ConvLayer( ret['conv3_2'], 256, 3, pad=1, flip_filters=False)
for k,x in ret['conv3_3'].params.iteritems():
x.remove('trainable')
ret['pool3'] = PoolLayer(ret['conv3_3'], 2)
ret['conv4_1'] = ConvLayer( ret['pool3'], 512, 3, pad=1, flip_filters=False)
ret['conv4_2'] = ConvLayer( ret['conv4_1'], 512, 3, pad=1, flip_filters=False)
ret['conv4_3'] = ConvLayer( ret['conv4_2'], 512, 3, pad=1, flip_filters=False)
ret['pool4'] = PoolLayer(ret['conv4_3'], 2)
ret['conv5_1'] = ConvLayer( ret['pool4'], 512, 3, pad=1, flip_filters=False)
ret['conv5_2'] = ConvLayer( ret['conv5_1'], 512, 3, pad=1, flip_filters=False)
ret['conv5_3'] = ConvLayer( ret['conv5_2'], 512, 3, pad=1, flip_filters=False)
ret['pool5'] = PoolLayer(ret['conv5_3'], 2)
ret['fc6'] = nn.layers.DenseLayer(ret['pool5'], num_units=4096)
ret['fc6_dropout'] = nn.layers.dropout(ret['fc6'], p=0.5)
ret['fc7'] = nn.layers.DenseLayer(ret['fc6_dropout'], num_units=4096)
ret['fc7_dropout'] = nn.layers.dropout(ret['fc7'], p=0.5)
ret['fc8'] = nn.layers.DenseLayer(ret['fc7_dropout'], num_units=1000, nonlinearity=None)
ret['output'] = nn.layers.NonlinearityLayer(ret['fc8'], nn.nonlinearities.softmax)
import pickle
model = pickle.load(open(params_dir+'/vgg16.pkl'));
nn.layers.set_all_param_values(ret['output'],model['param values']);
ret.pop("output",None);
ret.pop("fc8",None);
#ret.pop("fc7_dropout",None);
#ret.pop("fc7",None);
#ret['fc7'] = nn.layers.DenseLayer(ret['fc6_dropout'], num_units=256, nonlinearity=nlf);
#ret['fc7_dropout'] = nn.layers.dropout(ret['fc7'], p=0.5)
ret['output'] = nn.layers.DenseLayer(ret['fc7_dropout'], num_units=N_output, nonlinearity=output_fn)
elif version == 7: #inception_v3 # LB ~ 0.31
import inception_v3
ret = inception_v3.build_network(input_var);
import pickle
model = pickle.load(open(params_dir+'/inception_v3.pkl'));
nn.layers.set_all_param_values(ret['softmax'],model['param values']);
ret.pop("softmax",None);
ret['pool3_dropout'] = nn.layers.dropout(ret['pool3'], p=0.5)
ret['output'] = nn.layers.DenseLayer(ret['pool3_dropout'], num_units=N_output, nonlinearity=output_fn)
#non trainable
for ll in nn.layers.get_all_layers(ret['conv_4']):#4->3
if ll is not ret['input']:
for k,x in ll.params.iteritems():
if 'trainable' in x:
x.remove('trainable')
elif version == 8: #inception_v3
import inception_v3
ret = inception_v3.build_network(input_var);
import pickle
model = pickle.load(open(params_dir+'/inception_v3.pkl'));
nn.layers.set_all_param_values(ret['softmax'],model['param values']);
ret.pop("softmax",None);
ret['pool3_dropout'] = nn.layers.dropout(ret['pool3'], p=0.5) #0.5 is a little better than 0.7
ret['output'] = nn.layers.DenseLayer(ret['pool3_dropout'], num_units=N_output, nonlinearity=output_fn)
#non trainable
#for ll in nn.layers.get_all_layers(ret['conv_3']): #conv_3(0.278)>mix1 (0.285)>mix3 >> mix7
for ll in nn.layers.get_all_layers(ret['mixed_1/join']):
if ll is not ret['input']:
for k,x in ll.params.iteritems():
if 'trainable' in x:
x.remove('trainable')
elif version == 9: #res_net, no pretrain overfit. (LB ~ 0.7)
import Deep_Residual_Learning as resnet
ret['output'] = resnet.build_cnn(shape, input_var, n=2);
#import pickle
#model = pickle.load(open(params_dir+'/cifar_model_n5.pkl'));
#nn.layers.set_all_param_values(ret['output'],model['param values']);
elif version == 10:#192, add small img short cuts
nlf = nn.nonlinearities.LeakyRectify(leakiness = 0.1);
ret['input'] = layer = nn.layers.InputLayer(shape, input_var)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=16, filter_size=(5,5), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['h'] = nn.layers.Pool2DLayer(ret['input'],pool_size=(2,2),mode='average_inc_pad');
layer = nn.layers.ConcatLayer([layer,ret['h']]);
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=32, filter_size=(5,5), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['hh'] = nn.layers.Pool2DLayer(ret['h'],pool_size=(2,2),mode='average_inc_pad');
layer = nn.layers.ConcatLayer([layer,ret['hh']]);
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=64, filter_size=(3,3), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['hhh'] = nn.layers.Pool2DLayer(ret['hh'],pool_size=(2,2),mode='average_inc_pad');
layer = nn.layers.ConcatLayer([layer,ret['hhh']]);
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=128, filter_size=(3,3), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['hhhh'] = nn.layers.Pool2DLayer(ret['hhh'],pool_size=(2,2),mode='average_inc_pad');
layer = nn.layers.ConcatLayer([layer,ret['hhhh']]);
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=256, filter_size=(3,3), pad = 'same', nonlinearity = nlf, flip_filters=False))
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=256, filter_size=(3,4), nonlinearity = nlf, flip_filters=False))
ret['pool{}'.format(len(ret))] = layer = nn.layers.MaxPool2DLayer(layer, pool_size=2)
ret['conv{}'.format(len(ret))] = layer = bn(nn.layers.Conv2DLayer(layer, num_filters=512, filter_size=(3,2), nonlinearity = nlf, flip_filters=False))
ret['flatten'] = layer = nn.layers.FlattenLayer(layer);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['FC{}'.format(len(ret))] = layer = nn.layers.DenseLayer(layer, num_units = 256, nonlinearity = nlf);
ret['dropout'] = layer = nn.layers.dropout(layer,0.5);
ret['output'] = layer = nn.layers.DenseLayer(layer, num_units=N_output, nonlinearity=output_fn)
return ret, nn.layers.get_output(ret['output']), \
nn.layers.get_output(ret['output'], deterministic=True)
# loads params in npz
def load_params(model, fn):
with np.load(fn) as f:
param_values = [f['arr_%d' % i] for i in range(len(f.files))]
nn.layers.set_all_param_values(model, param_values)
def get_predict_function(m_param, weights, file_fmt, shape):
weights = np.asarray(weights, dtype=np.float32);
weights = weights/np.sum(weights);
input_var = T.tensor4('input')
expr = 0
for ii in range(len(m_param)):
model_file = file_fmt.format(*(m_param[ii]))
net, _, output_det = build_cnn(input_var, shape, m_param[ii][0])
load_params(net['output'], model_file)
expr = expr + output_det * weights[ii];
print 'loaded {}'.format(model_file.split('/')[-1])
return theano.function([input_var], expr)
| 73.33935 | 171 | 0.638543 | 2,902 | 20,315 | 4.345968 | 0.069607 | 0.082461 | 0.063749 | 0.090311 | 0.908896 | 0.905566 | 0.89288 | 0.875357 | 0.872185 | 0.869807 | 0 | 0.046001 | 0.177111 | 20,315 | 276 | 172 | 73.605072 | 0.708441 | 0.032095 | 0 | 0.735409 | 0 | 0 | 0.092011 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.07393 | null | null | 0.003891 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
8d1847f61d830924b2a6e46e70fa19f1f60aaccc | 21,777 | py | Python | yang_et_al/params.py | wagner-group/geoadex | 693856dc4537937fa09ec7a22e175f8243483b44 | [
"MIT"
] | 4 | 2021-11-01T18:18:28.000Z | 2022-02-14T05:58:57.000Z | yang_et_al/params.py | wagner-group/geoadex | 693856dc4537937fa09ec7a22e175f8243483b44 | [
"MIT"
] | null | null | null | yang_et_al/params.py | wagner-group/geoadex | 693856dc4537937fa09ec7a22e175f8243483b44 | [
"MIT"
] | null | null | null |
from nnattack.variables import auto_var
from utils import RobustExperiments
random_seed = list(range(1))
ATTACK_NORM = 'inf'
datasets = [
'australian',
'fourclass',
'diabetes',
'cancer',
'halfmoon_2200',
'covtypebin_2200',
'fashion_mnist35f_pca25',
'fashion_mnist06f_pca25',
'mnist17f_pca25',
#'fashion_mnist35_2200_pca25',
#'fashion_mnist06_2200_pca25',
#'mnist17_2200_pca25',
]
tree_datasets = [
'australian',
'fourclass',
'diabetes',
'cancer',
'halfmoon_2200',
'covtypebin_2200',
'fashion_mnist35f_pca25',
'fashion_mnist06f_pca25',
'mnist17f_pca25',
#'fashion_mnist35_10200_pca25',
#'fashion_mnist06_10200_pca25',
#'mnist17_10200_pca25',
]
class compare_attacks(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "compare_attacks"
grid_params = []
grid_params.append({
'model': ['knn1'],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['direct_k1', 'blackbox',
'kernelsub_c1000_pgd',
'RBA_Exact_KNN_k1',
'RBA_Approx_KNN_k1_50',
],
'random_seed': random_seed,
})
grid_params.append({
'model': ['knn3'],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['direct_k3', 'blackbox',
'kernelsub_c1000_pgd',
'RBA_Approx_KNN_k3_50'],
'random_seed': random_seed,
})
grid_params.append({
'model': ['decision_tree_d5'],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['dt_papernots', 'blackbox', 'RBA_Exact_DT'],
'random_seed': random_seed,
})
grid_params.append({
'model': ['random_forest_100_d5'],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['blackbox', 'RBA_Approx_RF_100'],
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
#class parametric_defense(RobustExperiments):
# def __new__(cls, *args, **kwargs):
# cls.name = "parametric_defense"
# grid_params = []
# grid_params.append({
# 'model': [
# 'logistic_regression',
# 'adv_logistic_regression_50',
# 'advPruning_logistic_regression_50',
# ],
# 'ord': [ATTACK_NORM],
# 'dataset': tree_datasets,
# 'attack': ['pgd'],
# 'random_seed': random_seed,
# })
# grid_params.append({
# 'model': [
# 'mlp',
# 'adv_mlp_50',
# 'advPruning_mlp_50',
# ],
# 'ord': [ATTACK_NORM],
# 'dataset': tree_datasets,
# 'attack': ['pgd'],
# 'random_seed': random_seed,
# })
# cls.grid_params = grid_params
# return RobustExperiments.__new__(cls, *args, **kwargs)
class compare_defense(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "compare_defense"
def_strength = 30
grid_params = []
grid_params.append({
'model': [
'knn1',
f'adv_nn_k1_{def_strength}',
f'robustv2_nn_k1_{def_strength}',
f'advPruning_nn_k1_{def_strength}'
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Exact_KNN_k1'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'knn1',
f'adv_nn_k1_{def_strength}',
f'robustv2_nn_k1_{def_strength}',
f'advPruning_nn_k1_{def_strength}'
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Approx_KNN_k1_50'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'knn3',
f'adv_nn_k3_{def_strength}',
f'advPruning_nn_k3_{def_strength}'
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Approx_KNN_k3_50'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'decision_tree_d5',
f'adv_decision_tree_d5_{def_strength}',
f'robust_decision_tree_d5_{def_strength}',
f'advPruning_decision_tree_d5_{def_strength}',
],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['RBA_Exact_DT'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'random_forest_100_d5',
f'adv_rf_100_{def_strength}_d5',
f'robust_rf_100_{def_strength}_d5',
f'advPruning_rf_100_{def_strength}_d5',
],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['RBA_Approx_RF_100'],
'random_seed': random_seed,
})
#grid_params.append({
# 'model': [
# 'logistic_regression',
# f'adv_logistic_regression_{def_strength}',
# f'advPruning_logistic_regression_{def_strength}',
# ],
# 'ord': [ATTACK_NORM],
# 'dataset': tree_datasets,
# 'attack': ['pgd'],
# 'random_seed': random_seed,
#})
#grid_params.append({
# 'model': [
# 'mlp',
# f'adv_mlp_{def_strength}',
# f'advPruning_mlp_{def_strength}',
# ],
# 'ord': [ATTACK_NORM],
# 'dataset': tree_datasets,
# 'attack': ['pgd'],
# 'random_seed': random_seed,
#})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class tst_scores(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "tst_scores"
grid_params = []
grid_params.append({
'model': [
'knn1', 'advPruning_nn_k1_10', 'advPruning_nn_k1_30', 'advPruning_nn_k1_50',
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Exact_KNN_k1'], #, 'blackbox'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'knn3', 'advPruning_nn_k3_10', 'advPruning_nn_k3_30', 'advPruning_nn_k3_50',
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Approx_KNN_k3_50'], #, 'blackbox'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'decision_tree_d5',
'advPruning_decision_tree_d5_10',
'advPruning_decision_tree_d5_30',
'advPruning_decision_tree_d5_50',
],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['RBA_Exact_DT'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'random_forest_100_d5',
'advPruning_rf_100_10_d5',
'advPruning_rf_100_30_d5',
'advPruning_rf_100_50_d5',
],
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': ['RBA_Approx_RF_100'],
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class fullds(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "fullds"
grid_params = []
grid_params.append({
'model': [
'random_forest_500_d10', 'approxAP_rf_500_20_d10',
'xgb_xgb_models/prune_fullmnist_pca100_20_rf_linf.0200.model',
"knn1", "approxAP_nn_k1_20",
"knn3", "approxAP_nn_k3_20",
'xgb_xgb_models/prune_fullmnist_pca100_20_linf.unrob.0200.model',
'xgb_xgb_models/fullmnist_pca100.unrob.0200.model',
'xgb_xgb_models/fullmnist_pca100.0200.model',
],
'ord': [ATTACK_NORM],
'dataset': ['fullmnist_pca100'],
'attack': ['blackbox'],
'random_seed': random_seed,
})
grid_params.append({
'model': [
'random_forest_500_d10', 'approxAP_rf_500_20_d10',
'xgb_xgb_models/prune_fullfashion_pca100_20_rf_linf.0200.model',
"knn1", "approxAP_nn_k1_20",
"knn3", "approxAP_nn_k3_20",
'xgb_xgb_models/prune_fullfashion_pca100_20_linf.unrob.0200.model',
'xgb_xgb_models/fullfashion_pca100.unrob.0200.model',
'xgb_xgb_models/fullfashion_pca100.0200.model',
],
'ord': [ATTACK_NORM],
'dataset': ['fullfashion_pca100'],
'attack': ['blackbox'],
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn_k1_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "1nn_robustness"
grid_params = []
grid_params.append({
'model': [
'knn1',
'advPruning_nn_k1_10',
'advPruning_nn_k1_30',
'advPruning_nn_k1_50',
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Exact_KNN_k1'],#, 'blackbox'],
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn_k3_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "3nn_robustness"
grid_params = []
grid_params.append({
'model': [
'knn3',
'advPruning_nn_k3_10',
'advPruning_nn_k3_30',
'advPruning_nn_k3_50',
],
'ord': [ATTACK_NORM],
'dataset': datasets,
'attack': ['RBA_Approx_KNN_k3_50'],#, 'blackbox'],
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class rf_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "rf-robustness"
models = [
'random_forest_100_d5',
#'adv_rf_100_10_d5', 'adv_rf_100_30_d5', 'adv_rf_100_50_d5',
#'robust_rf_100_10_d5', 'robust_rf_100_30_d5', 'robust_rf_100_50_d5',
'advPruning_rf_100_10_d5', 'advPruning_rf_100_30_d5', 'advPruning_rf_100_50_d5',
#'robustv2_rf_100_10_d5', 'robustv2_rf_100_30_d5', 'robustv2_rf_100_50_d5',
]
attacks = ['RBA_Approx_RF_100']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class dt_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "dt-robustness"
models = [
'decision_tree_d5',
'advPruning_decision_tree_d5_10',
'advPruning_decision_tree_d5_30',
'advPruning_decision_tree_d5_50',
]
attacks = ['RBA_Exact_DT']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class lr_ap_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "lr-ap-robustness"
models = [
'logistic_regression',
'advPruning_logistic_regression_10',
'advPruning_logistic_regression_30',
'advPruning_logistic_regression_50',
]
attacks = ['pgd']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class lr_at_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "lr-at-robustness"
models = [
'logistic_regression',
'adv_logistic_regression_10',
'adv_logistic_regression_30',
'adv_logistic_regression_50',
]
attacks = ['pgd']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class mlp_ap_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "mlp-ap-robustness"
models = [
'mlp', 'advPruning_mlp_10', 'advPruning_mlp_30', 'advPruning_mlp_50',
]
attacks = ['pgd']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class mlp_at_robustness(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "mlp-at-robustness"
models = ['mlp', 'adv_mlp_10', 'adv_mlp_30', 'adv_mlp_50',]
attacks = ['pgd']
grid_params = []
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': tree_datasets,
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class dt_robustness_figs(RobustExperiments):
def __new__(cls, *args, **kwargs):
dt_models = [
'decision_tree_d5',
'robust_decision_tree_d5_30',
'advPruning_decision_tree_d5_30',
]
cls.name = "dt_robustness_figs"
grid_params = {
'model': dt_models, 'attack': ['RBA_Exact_DT'],
'dataset': tree_datasets, 'ord': [ATTACK_NORM], 'random_seed': random_seed,
}
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn_k1_approx_robustness_figs(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "nn_k1_approx_robustness_figs"
nn_k1_models = ['knn1', 'advPruning_nn_k1_30',]
grid_params = {
'model': nn_k1_models, 'attack': ['RBA_Approx_KNN_k1_50'],
'dataset': datasets, 'ord': [ATTACK_NORM], 'random_seed': random_seed,
}
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn_k1_robustness_figs(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "nn_k1_robustness_figs"
nn_k1_models = ['knn1', 'advPruning_nn_k1_30',]
grid_params = {
'model': nn_k1_models, 'attack': ['RBA_Exact_KNN_k1'],
'dataset': datasets, 'ord': [ATTACK_NORM], 'random_seed': random_seed,
}
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn_k3_robustness_figs(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "nn_k3_robustness_figs"
nn_k3_models = ['knn3', 'advPruning_nn_k3_30',]
grid_params = {
'model': nn_k3_models, 'attack': ['RBA_Approx_KNN_k3_50'],
'dataset': datasets, 'ord': [ATTACK_NORM], 'random_seed': random_seed,
}
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class rf_robustness_figs(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "rf_robustness_figs"
rf_models = ['random_forest_100_d5', 'robust_rf_100_30_d5',
'advPruning_rf_100_30_d5',]
grid_params = {
'model': rf_models, 'attack': ['RBA_Approx_RF_100'],
'dataset': tree_datasets, 'ord': [ATTACK_NORM], 'random_seed': random_seed,
}
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn1_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "rf-robustness"
attacks = ['RBA_Exact_KNN_k1']
grid_params = []
for ds in datasets:
k = 30
models = [
'knn1',
f'adv_nn_k1_{k}',
f'robustv2_nn_k1_{k}',
f'advPruning_nn_k1_{k}',
]
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class nn3_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "rf-robustness"
attacks = ['RBA_Approx_KNN_k3_50']
grid_params = []
for ds in datasets:
k = 30
models = [
'knn3',
f'adv_nn_k3_{k}',
f'robustv2_nn_k3_{k}',
f'advPruning_nn_k3_{k}',
]
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class dt_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "dt-robustness"
attacks = ['RBA_Exact_DT']
grid_params = []
for ds in tree_datasets:
k = 30
models = [
'decision_tree_d5',
f'adv_decision_tree_d5_{k}',
f'robust_decision_tree_d5_{k}',
f'advPruning_decision_tree_d5_{k}',
]
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class rf_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "rf-robustness"
attacks = ['RBA_Approx_RF_100']
grid_params = []
for ds in tree_datasets:
k = 30
models = [
'random_forest_100_d5',
f'adv_rf_100_{k}_d5',
f'robust_rf_100_{k}_d5',
f'advPruning_rf_100_{k}_d5',
]
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class lr_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "dt-robustness"
attacks = ['pgd']
grid_params = []
for ds in tree_datasets:
k = 30
models = [
'logistic_regression',
f'adv_logistic_regression_{k}',
f'advPruning_logistic_regression_{k}',
]
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
class mlp_def(RobustExperiments):
def __new__(cls, *args, **kwargs):
cls.name = "dt-robustness"
attacks = ['pgd']
grid_params = []
for ds in tree_datasets:
k = 30
models = ['mlp', f'adv_mlp_{k}', f'advPruning_mlp_{k}']
grid_params.append({
'model': models,
'ord': [ATTACK_NORM],
'dataset': [ds],
'attack': attacks,
'random_seed': random_seed,
})
cls.grid_params = grid_params
return RobustExperiments.__new__(cls, *args, **kwargs)
| 33.400307 | 92 | 0.530192 | 2,142 | 21,777 | 4.901494 | 0.053221 | 0.10001 | 0.045719 | 0.07315 | 0.888085 | 0.846843 | 0.818554 | 0.787408 | 0.741309 | 0.702638 | 0 | 0.041608 | 0.345548 | 21,777 | 651 | 93 | 33.451613 | 0.69506 | 0.084217 | 0 | 0.742173 | 0 | 0 | 0.24956 | 0.092912 | 0 | 0 | 0 | 0 | 0 | 1 | 0.042357 | false | 0 | 0.003683 | 0 | 0.130755 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
8d3f800fb0fbb9e4c535a1249a11f05fcea9bc18 | 6,179 | py | Python | restricted_sharing.py | ameldocena/StratifiedAggregation | 0031fea120bff00c739eb6c3d654a5c6d3f094bb | [
"MIT"
] | null | null | null | restricted_sharing.py | ameldocena/StratifiedAggregation | 0031fea120bff00c739eb6c3d654a5c6d3f094bb | [
"MIT"
] | null | null | null | restricted_sharing.py | ameldocena/StratifiedAggregation | 0031fea120bff00c739eb6c3d654a5c6d3f094bb | [
"MIT"
] | null | null | null | import torch
import numpy as np
from collections import OrderedDict
def get_uploaded_params(args, idx, epoch, save=True):
"""
Creates the model file that will be shared with the aggregator when parameter sharing is restricted
Parameters with the smallest gradients will be replaced with numpy NaNs
This is a novel contribution beyond the Tolpegin et al framework
:param args: experiment arguments
:type args: Arguments
:param idx: worker ID
:type idx: int
:param epoch: epoch number
:type epoch: int
:param portion: portion of parameters that should be shared; e.g. 0.5 means 50% of parameters with highest gradients will be shared
:return: OrderedDict
"""
folder = args.get_save_model_folder_path()
#The way this works is that a start model and end model are stored for each client at every epoch
end_path = f"{folder}/model_{idx}_{epoch}_end.model"
end_model = torch.load(end_path)
#If all parameters are shared, we return the entire end model
portion = args.get_portion_uploaded()
if portion == 1:
if save:
torch.save(end_model, f"{folder}/model_{idx}_{epoch}_uploaded.model")
return end_model
#Else, we return only a portion of the end model
#We set some parameters for sharing by sorting them based on their gradient values.
#We replace those restricted parameters for sharing by NaNs
start_path = f"{folder}/model_{idx}_{epoch}_start.model" #Loads model of client idx at given epoch
start_model = torch.load(start_path)
grad_dict = OrderedDict()
for i in start_model.keys():
grad_dict[i] = end_model[i] - start_model[i]
end_model_portioned = OrderedDict()
for i in grad_dict.keys(): #Ordered keys
end_model_portioned[i] = torch.empty(grad_dict[i].shape)
if len(grad_dict[i].shape) > 1:
for j in range(len(grad_dict[i])):
topx = round(portion * grad_dict[i][j].numel())
if topx < 1:
grad_dict[i][j].fill_(np.NaN)
end_model_portioned[i][j] = torch.full_like(grad_dict[i][j], np.NaN)
else:
grad_dict[i][j][torch.abs(grad_dict[i][j]) <
torch.sort(torch.abs(grad_dict[i][j]).flatten(), descending=True)[0][topx - 1]] = np.NaN
end_model_portioned[i][j] = torch.full_like(grad_dict[i][j], np.NaN)
end_model_portioned[i][j][~torch.isnan(grad_dict[i][j])] = end_model[i][j][~torch.isnan(grad_dict[i][j])].cpu()
elif len(grad_dict[i].shape) == 1:
j = grad_dict[i]
topx = round(portion * j.numel())
if topx < 1:
j.fill_(np.NaN)
end_model_portioned[i] = torch.full_like(grad_dict[i], np.NaN)
else:
j[torch.sort(torch.abs(j).flatten(), descending=True)[1][topx:]] = np.NaN
end_model_portioned[i] = torch.full_like(grad_dict[i], np.NaN)
end_model_portioned[i][~torch.isnan(grad_dict[i])] = end_model[i][~torch.isnan(grad_dict[i])]
else:
end_model_portioned[i] = end_model[i]
if save:
torch.save(end_model_portioned, f"{folder}/model_{idx}_{epoch}_uploaded.model")
#We return the portioned (or restrictedly shared) end model
return end_model_portioned
def get_downloadable_params(args, epoch, save=True):
"""
Creates the model file that will be shared from aggregator to local models when download is restricted
Parameters with the smallest gradients will be replaced with numpy NaNs
This is a novel contribution beyond the Tolpegin et al framework
:param args: experiment arguments
:type args: Arguments
:param epoch: epoch number
:type epoch: int
:param portion: portion of parameters that should be shared; e.g. 0.5 means 50% of parameters with highest gradients will be shared
:return: OrderedDict
"""
folder = args.get_save_model_folder_path()
end_path = f"{folder}/model_GLOBAL_{epoch}_end.model"
end_model = torch.load(end_path)
portion = args.get_portion_downloaded()
if portion == 1:
if save:
torch.save(end_model, f"{folder}/model_GLOBAL_{epoch}_shared.model")
return end_model
start_path = f"{folder}/model_GLOBAL_{epoch}_start.model"
start_model = torch.load(start_path)
grad_dict = OrderedDict()
for i in start_model.keys():
grad_dict[i] = end_model[i] - start_model[i]
end_model_portioned = OrderedDict()
for i in grad_dict.keys():
end_model_portioned[i] = torch.empty(grad_dict[i].shape)
if len(grad_dict[i].shape) > 1:
for j in range(len(grad_dict[i])):
topx = round(portion * grad_dict[i][j].numel())
if topx < 1:
grad_dict[i][j].fill_(np.NaN)
end_model_portioned[i][j] = torch.full_like(grad_dict[i][j], np.NaN)
else:
grad_dict[i][j][torch.abs(grad_dict[i][j]) <
torch.sort(torch.abs(grad_dict[i][j]).flatten(), descending=True)[0][topx - 1]] = np.NaN
end_model_portioned[i][j] = torch.full_like(grad_dict[i][j], np.NaN)
end_model_portioned[i][j][~torch.isnan(grad_dict[i][j])] = end_model[i][j][~torch.isnan(grad_dict[i][j])].cpu()
elif len(grad_dict[i].shape) == 1:
j = grad_dict[i]
topx = round(portion * j.numel())
if topx < 1:
j.fill_(np.NaN)
end_model_portioned[i] = torch.full_like(grad_dict[i], np.NaN)
else:
j[torch.sort(torch.abs(j).flatten(), descending=True)[1][topx:]] = np.NaN
end_model_portioned[i] = torch.full_like(grad_dict[i], np.NaN)
end_model_portioned[i][~torch.isnan(grad_dict[i])] = end_model[i][~torch.isnan(grad_dict[i])]
else:
end_model_portioned[i] = end_model[i]
if save:
torch.save(end_model_portioned, f"{folder}/model_GLOBAL_{epoch}_shared.model")
return end_model_portioned
| 45.77037 | 135 | 0.626315 | 898 | 6,179 | 4.124722 | 0.152561 | 0.090713 | 0.092333 | 0.048596 | 0.819654 | 0.805346 | 0.780508 | 0.769168 | 0.769168 | 0.74919 | 0 | 0.005229 | 0.257161 | 6,179 | 134 | 136 | 46.11194 | 0.801743 | 0.238712 | 0 | 0.831461 | 0 | 0 | 0.071397 | 0.071397 | 0 | 0 | 0 | 0 | 0 | 1 | 0.022472 | false | 0 | 0.033708 | 0 | 0.101124 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
a5e6295e38fcf83c75e36f36d2ba01daf632b012 | 261 | py | Python | tests/general_test.py | nitzan-tz/ansible-subprocess | 5854ee8d631c31538a7274d75f7cfd952b46f695 | [
"MIT"
] | 3 | 2016-11-22T12:43:15.000Z | 2021-01-14T15:58:21.000Z | tests/general_test.py | nitzan-tz/ansible-subprocess | 5854ee8d631c31538a7274d75f7cfd952b46f695 | [
"MIT"
] | 2 | 2020-01-01T05:28:56.000Z | 2020-03-11T01:38:12.000Z | tests/general_test.py | nitzan-tz/ansible-subprocess | 5854ee8d631c31538a7274d75f7cfd952b46f695 | [
"MIT"
] | 3 | 2017-11-24T14:21:04.000Z | 2019-11-18T20:06:46.000Z | import unittest
class GenericTest(unittest.TestCase):
def test_import(self):
import ansible_subprocess
def test_accessible(self):
import ansible_subprocess
ansible_subprocess.run_playbook
ansible_subprocess.run_ping
| 18.642857 | 39 | 0.727969 | 28 | 261 | 6.5 | 0.5 | 0.373626 | 0.186813 | 0.296703 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.226054 | 261 | 13 | 40 | 20.076923 | 0.90099 | 0 | 0 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.5 | 0 | 0.875 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
a5e7a0be6dafcd13db0f7d26f334ee7283f41448 | 140 | py | Python | flask_chown/__init__.py | xvzf/flask-chmod | 1dcd6b4281a930ac889415c1913e9551c882da23 | [
"Apache-2.0"
] | null | null | null | flask_chown/__init__.py | xvzf/flask-chmod | 1dcd6b4281a930ac889415c1913e9551c882da23 | [
"Apache-2.0"
] | 1 | 2018-05-13T09:39:30.000Z | 2018-05-13T09:39:30.000Z | flask_chown/__init__.py | xvzf/flask-chmod | 1dcd6b4281a930ac889415c1913e9551c882da23 | [
"Apache-2.0"
] | 1 | 2018-05-13T09:06:09.000Z | 2018-05-13T09:06:09.000Z | from .permission_manager import PermissionManager, PermissionManagerException
from .permission_manager_redis import CachedPermissionManager
| 46.666667 | 77 | 0.914286 | 12 | 140 | 10.416667 | 0.666667 | 0.224 | 0.336 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.064286 | 140 | 2 | 78 | 70 | 0.954198 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
9398f5cfd834804efff320096ef2becfba2587bb | 6,107 | py | Python | test/test_security_profile.py | xmedius/sendsecure-python | c1fd75acf7eb1772025e92b1cc7777b205c5d734 | [
"MIT"
] | null | null | null | test/test_security_profile.py | xmedius/sendsecure-python | c1fd75acf7eb1772025e92b1cc7777b205c5d734 | [
"MIT"
] | null | null | null | test/test_security_profile.py | xmedius/sendsecure-python | c1fd75acf7eb1772025e92b1cc7777b205c5d734 | [
"MIT"
] | null | null | null | from sendsecure import *
import unittest
class TestSecurityProfile(unittest.TestCase):
security_profile_params = { 'id': 10,
'name': 'email-only',
'description': '',
'created_at': '2016-04-27T21:08:29.457Z',
'updated_at': '2016-07-27T19:03:05.883Z',
'allowed_login_attempts': {'value': 3, 'modifiable': False},
'allow_remember_me': {'value': False, 'modifiable': False},
'allow_sms': {'value': False, 'modifiable': False},
'allow_voice': {'value': False, 'modifiable': False},
'allow_email': {'value': True, 'modifiable': False},
'code_time_limit': {'value': 5, 'modifiable': False},
'code_length': {'value': 4, 'modifiable': False},
'auto_extend_value': {'value': 3, 'modifiable': False},
'auto_extend_unit': {'value': 'days', 'modifiable': False},
'two_factor_required': {'value': True, 'modifiable': False},
'encrypt_attachments': {'value': True, 'modifiable': False},
'encrypt_message': {'value': False, 'modifiable': False},
'expiration_value': {'value': 7, 'modifiable': False},
'expiration_unit': {'value': 'hours', 'modifiable': False},
'reply_enabled': {'value': True, 'modifiable': False},
'group_replies': {'value': False, 'modifiable': False},
'double_encryption': {'value': True, 'modifiable': False},
'retention_period_type': {'value': 'discard_at_expiration', 'modifiable': False},
'retention_period_value': {'value': None, 'modifiable': False},
'retention_period_unit': {'value': None, 'modifiable': False}
}
def setUp(self):
pass
def test_initialization_with_params(self):
security_profile = SecurityProfile(self.security_profile_params)
self.assertEqual(security_profile.id, 10)
self.assertEqual(security_profile.name, 'email-only')
self.assertEqual(security_profile.description, '')
self.assertEqual(security_profile.created_at, '2016-04-27T21:08:29.457Z')
self.assertEqual(security_profile.updated_at, '2016-07-27T19:03:05.883Z')
self.assertIsInstance(security_profile.allowed_login_attempts, Value)
self.assertIsInstance(security_profile.allow_remember_me, Value)
self.assertIsInstance(security_profile.allow_sms, Value)
self.assertIsInstance(security_profile.allow_voice, Value)
self.assertIsInstance(security_profile.allow_email, Value)
self.assertIsInstance(security_profile.code_time_limit, Value)
self.assertIsInstance(security_profile.code_length, Value)
self.assertIsInstance(security_profile.auto_extend_value, Value)
self.assertIsInstance(security_profile.auto_extend_unit, Value)
self.assertIsInstance(security_profile.two_factor_required, Value)
self.assertIsInstance(security_profile.encrypt_attachments, Value)
self.assertIsInstance(security_profile.encrypt_message, Value)
self.assertIsInstance(security_profile.expiration_value, Value)
self.assertIsInstance(security_profile.expiration_unit, Value)
self.assertIsInstance(security_profile.reply_enabled, Value)
self.assertIsInstance(security_profile.group_replies, Value)
self.assertIsInstance(security_profile.double_encryption, Value)
self.assertIsInstance(security_profile.retention_period_type, Value)
self.assertIsInstance(security_profile.retention_period_value, Value)
self.assertIsInstance(security_profile.retention_period_unit, Value)
def test_initialization_with_json_params(self):
security_profile = SecurityProfile(self.security_profile_params)
self.assertEqual(security_profile.id, 10)
self.assertEqual(security_profile.name, 'email-only')
self.assertEqual(security_profile.description, '')
self.assertEqual(security_profile.created_at, '2016-04-27T21:08:29.457Z')
self.assertEqual(security_profile.updated_at, '2016-07-27T19:03:05.883Z')
self.assertIsInstance(security_profile.allowed_login_attempts, Value)
self.assertIsInstance(security_profile.allow_remember_me, Value)
self.assertIsInstance(security_profile.allow_sms, Value)
self.assertIsInstance(security_profile.allow_voice, Value)
self.assertIsInstance(security_profile.allow_email, Value)
self.assertIsInstance(security_profile.code_time_limit, Value)
self.assertIsInstance(security_profile.code_length, Value)
self.assertIsInstance(security_profile.auto_extend_value, Value)
self.assertIsInstance(security_profile.auto_extend_unit, Value)
self.assertIsInstance(security_profile.two_factor_required, Value)
self.assertIsInstance(security_profile.encrypt_attachments, Value)
self.assertIsInstance(security_profile.encrypt_message, Value)
self.assertIsInstance(security_profile.expiration_value, Value)
self.assertIsInstance(security_profile.expiration_unit, Value)
self.assertIsInstance(security_profile.reply_enabled, Value)
self.assertIsInstance(security_profile.group_replies, Value)
self.assertIsInstance(security_profile.double_encryption, Value)
self.assertIsInstance(security_profile.retention_period_type, Value)
self.assertIsInstance(security_profile.retention_period_value, Value)
self.assertIsInstance(security_profile.retention_period_unit, Value)
if __name__ == '__main__':
unittest.main() | 66.380435 | 113 | 0.654331 | 583 | 6,107 | 6.566038 | 0.147513 | 0.215517 | 0.292581 | 0.365726 | 0.780564 | 0.740857 | 0.740857 | 0.740857 | 0.726228 | 0.726228 | 0 | 0.024454 | 0.243327 | 6,107 | 92 | 114 | 66.380435 | 0.803939 | 0 | 0 | 0.597701 | 0 | 0 | 0.142272 | 0.041094 | 0 | 0 | 0 | 0 | 0.574713 | 1 | 0.034483 | false | 0.011494 | 0.022989 | 0 | 0.08046 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
93b2dedad21a1643f4b4a7698928e3e33b154fc3 | 2,304 | py | Python | tests/property_based/conftest.py | KarenImmanuel/hangar-py | 2a5caff259ad699db56676f14a70cb94e75d8a5b | [
"Apache-2.0"
] | null | null | null | tests/property_based/conftest.py | KarenImmanuel/hangar-py | 2a5caff259ad699db56676f14a70cb94e75d8a5b | [
"Apache-2.0"
] | null | null | null | tests/property_based/conftest.py | KarenImmanuel/hangar-py | 2a5caff259ad699db56676f14a70cb94e75d8a5b | [
"Apache-2.0"
] | null | null | null | import pytest
import numpy as np
from hangar import Repository
backend_params = ['00', '10']
@pytest.fixture(params=backend_params)
def fixed_shape_repo_co_float32(managed_tmpdir, request) -> Repository:
repo_obj = Repository(path=managed_tmpdir, exists=False)
repo_obj.init(user_name='tester', user_email='foo@test.bar', remove_old=True)
co = repo_obj.checkout(write=True)
co.arraysets.init_arrayset(name='writtenaset',
shape=(10, 10, 10, 10),
dtype=np.float32,
variable_shape=True,
backend_opts=request.param)
yield co
co.close()
repo_obj._env._close_environments()
@pytest.fixture(params=backend_params)
def variable_shape_repo_co_float32(managed_tmpdir, request) -> Repository:
repo_obj = Repository(path=managed_tmpdir, exists=False)
repo_obj.init(user_name='tester', user_email='foo@test.bar', remove_old=True)
co = repo_obj.checkout(write=True)
co.arraysets.init_arrayset(name='writtenaset',
shape=(10, 10, 10, 10),
dtype=np.float32,
variable_shape=True,
backend_opts=request.param)
yield co
co.close()
repo_obj._env._close_environments()
@pytest.fixture(params=backend_params)
def variable_shape_repo_co_uint8(managed_tmpdir, request) -> Repository:
repo_obj = Repository(path=managed_tmpdir, exists=False)
repo_obj.init(user_name='tester', user_email='foo@test.bar', remove_old=True)
co = repo_obj.checkout(write=True)
co.arraysets.init_arrayset(name='writtenaset',
shape=(10, 10, 10, 10),
dtype=np.uint8,
variable_shape=True,
backend_opts=request.param)
yield co
co.close()
repo_obj._env._close_environments()
@pytest.fixture()
def w_metadata_co(managed_tmpdir) -> Repository:
repo_obj = Repository(path=managed_tmpdir, exists=False)
repo_obj.init(user_name='tester', user_email='foo@test.bar', remove_old=True)
co = repo_obj.checkout(write=True)
yield co
co.close()
repo_obj._env._close_environments() | 36.571429 | 81 | 0.630208 | 279 | 2,304 | 4.935484 | 0.189964 | 0.081336 | 0.026144 | 0.078431 | 0.918664 | 0.918664 | 0.893246 | 0.893246 | 0.893246 | 0.863471 | 0 | 0.022406 | 0.263889 | 2,304 | 63 | 82 | 36.571429 | 0.789505 | 0 | 0 | 0.803922 | 0 | 0 | 0.047289 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.078431 | false | 0 | 0.058824 | 0 | 0.137255 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
9e13c8f651669926510589a16ebf6b0d2be35179 | 1,498 | py | Python | venv/lib/python2.7/site-packages/pychart/afm/Bookman_DemiItalic.py | Christian-Castro/castro_odoo8 | 8247fdb20aa39e043b6fa0c4d0af509462ab3e00 | [
"Unlicense"
] | 1 | 2019-12-19T01:53:13.000Z | 2019-12-19T01:53:13.000Z | venv/lib/python2.7/site-packages/pychart/afm/Bookman_DemiItalic.py | Christian-Castro/castro_odoo8 | 8247fdb20aa39e043b6fa0c4d0af509462ab3e00 | [
"Unlicense"
] | null | null | null | venv/lib/python2.7/site-packages/pychart/afm/Bookman_DemiItalic.py | Christian-Castro/castro_odoo8 | 8247fdb20aa39e043b6fa0c4d0af509462ab3e00 | [
"Unlicense"
] | null | null | null | # AFM font Bookman-DemiItalic (path: /usr/share/fonts/afms/adobe/pbkdi8a.afm).
# Derived from Ghostscript distribution.
# Go to www.cs.wisc.edu/~ghost to get the Ghostcript source code.
import dir
dir.afm["Bookman-DemiItalic"] = (500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 340, 320, 380, 680, 680, 880, 980, 320, 260, 260, 460, 600, 340, 280, 340, 360, 680, 680, 680, 680, 680, 680, 680, 680, 680, 680, 340, 340, 620, 600, 620, 620, 780, 720, 720, 700, 760, 720, 660, 760, 800, 380, 620, 780, 640, 860, 740, 760, 640, 760, 740, 700, 700, 740, 660, 1000, 740, 660, 680, 260, 580, 260, 620, 500, 320, 680, 600, 560, 680, 560, 420, 620, 700, 380, 320, 700, 380, 960, 680, 600, 660, 620, 500, 540, 440, 680, 540, 860, 620, 600, 560, 300, 620, 300, 620, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 320, 680, 680, 120, 680, 680, 620, 680, 180, 520, 380, 220, 220, 820, 820, 500, 500, 420, 420, 340, 500, 680, 360, 300, 520, 520, 380, 1000, 1360, 500, 620, 500, 380, 340, 480, 480, 480, 460, 380, 520, 500, 360, 360, 500, 560, 320, 480, 1000, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 1140, 500, 440, 500, 500, 500, 500, 640, 760, 1180, 440, 500, 500, 500, 500, 500, 880, 500, 500, 500, 380, 500, 500, 380, 600, 920, 660, )
| 249.666667 | 1,300 | 0.625501 | 287 | 1,498 | 3.264808 | 0.240418 | 0.576307 | 0.78762 | 0.973319 | 0.329776 | 0.294557 | 0.294557 | 0.294557 | 0.294557 | 0.26254 | 0 | 0.62541 | 0.185581 | 1,498 | 5 | 1,301 | 299.6 | 0.142623 | 0.119493 | 0 | 0 | 0 | 0 | 0.013688 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 10 |
f570bb94f9be06e5dc0b5750409d60e755fe7ff2 | 7,600 | py | Python | datasets.py | gim4855744/GCCF | eaf17c38e7d78ae92672c07fb167600629f58eb3 | [
"MIT"
] | null | null | null | datasets.py | gim4855744/GCCF | eaf17c38e7d78ae92672c07fb167600629f58eb3 | [
"MIT"
] | null | null | null | datasets.py | gim4855744/GCCF | eaf17c38e7d78ae92672c07fb167600629f58eb3 | [
"MIT"
] | null | null | null | import pandas as pd
import torch
import os
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from utils import load_matlab_file, matrix2data
class ML1M:
def __init__(self, root_dir, device):
data_path = os.path.join(root_dir, 'ratings.dat')
user_info_path = os.path.join(root_dir, 'users.dat')
movie_info_path = os.path.join(root_dir, 'movies.dat')
self._data = pd.read_csv(
data_path,
sep='::',
names=['user', 'movie', 'rating', 'time'],
engine='python'
)
self._user_info = pd.read_csv(
user_info_path,
sep='::',
names=['id', 'gender', 'age', 'occupation', 'zip-code'],
engine='python'
)
self._movie_info = pd.read_csv(
movie_info_path,
sep='::',
names=['id', 'title', 'genres'],
engine='python'
)
user_label_encoder = LabelEncoder()
movie_label_encoder = LabelEncoder()
self._user_info['id'] = user_label_encoder.fit_transform(self._user_info['id'])
self._movie_info['id'] = movie_label_encoder.fit_transform(self._movie_info['id'])
self._data['user'] = user_label_encoder.transform(self._data['user'])
self._data['movie'] = movie_label_encoder.transform(self._data['movie'])
self._train_data, self._test_data = train_test_split(self._data, test_size=0.1)
self._device = device
def _split_user_movie_rating(self, data):
user = torch.tensor(data['user'].values, dtype=torch.int64, device=self._device)
movie = torch.tensor(data['movie'].values, dtype=torch.int64, device=self._device)
rating = torch.tensor(data['rating'].values, dtype=torch.float32, device=self._device) / 5.
return user, movie, rating
def get_train_data(self):
return self._split_user_movie_rating(self._train_data)
def get_test_data(self):
return self._split_user_movie_rating(self._test_data)
def get_num_users(self):
return max(self._user_info['id']) + 1
def get_num_movies(self):
return max(self._movie_info['id']) + 1
@staticmethod
def inverse_transform(values):
return values * 5
class ML100K:
def __init__(self, root_dir, device):
data_path = os.path.join(root_dir, 'split_1.mat')
rating = load_matlab_file(data_path, 'M') # rating matrix
training = load_matlab_file(data_path, 'Otraining') # train matrix
test = load_matlab_file(data_path, 'Otest') # test matrix
self._num_users = rating.shape[0]
self._num_movies = rating.shape[1]
self._train_data = matrix2data(training, rating)
self._test_data = matrix2data(test, rating)
self._device = device
def _split_user_movie_rating(self, data):
user = torch.tensor(data['user'].values, dtype=torch.int64, device=self._device)
movie = torch.tensor(data['movie'].values, dtype=torch.int64, device=self._device)
rating = torch.tensor(data['rating'].values, dtype=torch.float32, device=self._device) / 5.
return user, movie, rating
def get_train_data(self):
return self._split_user_movie_rating(self._train_data)
def get_test_data(self):
return self._split_user_movie_rating(self._test_data)
def get_num_users(self):
return self._num_users
def get_num_movies(self):
return self._num_movies
@staticmethod
def inverse_transform(values):
return values * 5
class Flixster:
def __init__(self, root_dir, device):
data_path = os.path.join(root_dir, 'training_test_dataset_10_NNs.mat')
rating = load_matlab_file(data_path, 'M') # rating matrix
training = load_matlab_file(data_path, 'Otraining') # train matrix
test = load_matlab_file(data_path, 'Otest') # test matrix
self._num_users = rating.shape[0]
self._num_movies = rating.shape[1]
self._train_data = matrix2data(training, rating)
self._test_data = matrix2data(test, rating)
self._device = device
def _split_user_movie_rating(self, data):
user = torch.tensor(data['user'].values, dtype=torch.int64, device=self._device)
movie = torch.tensor(data['movie'].values, dtype=torch.int64, device=self._device)
rating = torch.tensor(data['rating'].values, dtype=torch.float32, device=self._device) / 5.
return user, movie, rating
def get_train_data(self):
return self._split_user_movie_rating(self._train_data)
def get_test_data(self):
return self._split_user_movie_rating(self._test_data)
def get_num_users(self):
return self._num_users
def get_num_movies(self):
return self._num_movies
@staticmethod
def inverse_transform(values):
return values * 5
class Douban:
def __init__(self, root_dir, device):
data_path = os.path.join(root_dir, 'training_test_dataset.mat')
rating = load_matlab_file(data_path, 'M') # rating matrix
training = load_matlab_file(data_path, 'Otraining') # train matrix
test = load_matlab_file(data_path, 'Otest') # test matrix
self._num_users = rating.shape[0]
self._num_movies = rating.shape[1]
self._train_data = matrix2data(training, rating)
self._test_data = matrix2data(test, rating)
self._device = device
def _split_user_movie_rating(self, data):
user = torch.tensor(data['user'].values, dtype=torch.int64, device=self._device)
movie = torch.tensor(data['movie'].values, dtype=torch.int64, device=self._device)
rating = torch.tensor(data['rating'].values, dtype=torch.float32, device=self._device) / 5.
return user, movie, rating
def get_train_data(self):
return self._split_user_movie_rating(self._train_data)
def get_test_data(self):
return self._split_user_movie_rating(self._test_data)
def get_num_users(self):
return self._num_users
def get_num_movies(self):
return self._num_movies
@staticmethod
def inverse_transform(values):
return values * 5
class YahooMusic:
def __init__(self, root_dir, device):
data_path = os.path.join(root_dir, 'training_test_dataset_10_NNs.mat')
rating = load_matlab_file(data_path, 'M') # rating matrix
training = load_matlab_file(data_path, 'Otraining') # train matrix
test = load_matlab_file(data_path, 'Otest') # test matrix
self._num_users = rating.shape[0]
self._num_movies = rating.shape[1]
self._train_data = matrix2data(training, rating)
self._test_data = matrix2data(test, rating)
self._device = device
def _split_user_movie_rating(self, data):
user = torch.tensor(data['user'].values, dtype=torch.int64, device=self._device)
movie = torch.tensor(data['movie'].values, dtype=torch.int64, device=self._device)
rating = torch.tensor(data['rating'].values, dtype=torch.float32, device=self._device) / 100.
return user, movie, rating
def get_train_data(self):
return self._split_user_movie_rating(self._train_data)
def get_test_data(self):
return self._split_user_movie_rating(self._test_data)
def get_num_users(self):
return self._num_users
def get_num_movies(self):
return self._num_movies
@staticmethod
def inverse_transform(values):
return values * 100
| 33.043478 | 101 | 0.665263 | 998 | 7,600 | 4.728457 | 0.088176 | 0.048739 | 0.066751 | 0.063573 | 0.856114 | 0.824327 | 0.819029 | 0.808434 | 0.808434 | 0.796779 | 0 | 0.012536 | 0.223289 | 7,600 | 229 | 102 | 33.187773 | 0.786888 | 0.020395 | 0 | 0.757764 | 0 | 0 | 0.05113 | 0.011975 | 0 | 0 | 0 | 0 | 0 | 1 | 0.217391 | false | 0 | 0.037267 | 0.15528 | 0.47205 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 9 |
191eeb5ffa421f3409c74c2d105bec2786470649 | 2,055 | py | Python | shopid/serializers/douyinserializers.py | yuntechcloud/GreaterWMS | 4a1c54fb962a0a6a3790e30340424c81175fe07b | [
"Apache-2.0"
] | 3 | 2020-10-19T05:55:28.000Z | 2020-11-12T03:55:06.000Z | shopid/serializers/douyinserializers.py | yuntechcloud/GreaterWMS | 4a1c54fb962a0a6a3790e30340424c81175fe07b | [
"Apache-2.0"
] | 1 | 2020-07-24T07:34:36.000Z | 2020-07-24T07:34:36.000Z | shopid/serializers/douyinserializers.py | Singosgu/Elvis_WMS | e6911b7daae76be640ece8946104af24b6cf0fa6 | [
"MIT"
] | 4 | 2020-09-04T13:35:15.000Z | 2020-10-16T15:10:38.000Z | from rest_framework import serializers
from shopid.models.douyinmodels import ListModel
class DouYinGetSerializer(serializers.ModelSerializer):
shop_name = serializers.CharField(read_only=True, required=False)
shop_mode = serializers.CharField(read_only=True, required=False)
shop_appid = serializers.CharField(read_only=True, required=False)
shop_app_secret = serializers.CharField(read_only=True, required=False)
shop_id = serializers.CharField(read_only=True, required=False)
sandbox = serializers.IntegerField(read_only=True, required=False)
proxy = serializers.IntegerField(read_only=True, required=False)
proxy_ip = serializers.JSONField(read_only=True, required=False)
t_code = serializers.CharField(read_only=True, required=False)
create_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S')
update_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S')
class Meta:
model = ListModel
exclude = ['openid', 'appid', ]
read_only_fields = ['id']
class DouYinfileRenderSerializer(serializers.ModelSerializer):
shop_name = serializers.CharField(read_only=True, required=False)
shop_mode = serializers.CharField(read_only=True, required=False)
shop_appid = serializers.CharField(read_only=True, required=False)
shop_app_secret = serializers.CharField(read_only=True, required=False)
shop_id = serializers.CharField(read_only=True, required=False)
sandbox = serializers.IntegerField(read_only=True, required=False)
proxy = serializers.IntegerField(read_only=True, required=False)
proxy_ip = serializers.JSONField(read_only=True, required=False)
t_code = serializers.CharField(read_only=True, required=False)
create_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S')
update_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M:%S')
class Meta:
model = ListModel
exclude = ['openid', 'appid', ]
read_only_fields = ['id']
| 55.540541 | 87 | 0.746959 | 257 | 2,055 | 5.789883 | 0.18677 | 0.129032 | 0.177419 | 0.241935 | 0.91129 | 0.91129 | 0.91129 | 0.91129 | 0.91129 | 0.91129 | 0 | 0 | 0.134307 | 2,055 | 36 | 88 | 57.083333 | 0.836425 | 0 | 0 | 0.882353 | 0 | 0 | 0.045742 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.058824 | 0 | 0.823529 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 9 |
196d58e0f2b65db1b40160276404d5995eaec706 | 8,347 | py | Python | CODES/flood fill/with inner walls/01.py | YashwanthYarala/MICROMOUSE | 69ba518ee81e1e6b70a13f7480844459d240ed11 | [
"MIT"
] | null | null | null | CODES/flood fill/with inner walls/01.py | YashwanthYarala/MICROMOUSE | 69ba518ee81e1e6b70a13f7480844459d240ed11 | [
"MIT"
] | null | null | null | CODES/flood fill/with inner walls/01.py | YashwanthYarala/MICROMOUSE | 69ba518ee81e1e6b70a13f7480844459d240ed11 | [
"MIT"
] | null | null | null | from numpy import *
#creating maze with no walls.
m = array([[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,6,7,5,7,4,7,3,7,3,7,4,7,5,7,6,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,5,7,4,7,3,7,2,7,2,7,3,7,4,7,5,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,4,7,3,7,2,7,1,7,1,7,2,7,3,7,4,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,3,7,2,7,1,7,0,7,0,7,1,7,2,7,3,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,3,7,2,7,1,7,0,7,0,7,1,7,2,7,3,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,4,7,3,7,2,7,1,7,1,7,2,7,3,7,4,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,5,7,4,7,3,7,2,7,2,7,3,7,4,7,5,10,10],
[10,10,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,10,10],
[10,10,6,7,5,7,4,7,3,7,3,7,4,7,5,7,6,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]])
i = array([[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,6,7,5,10,4,7,3,7,3,10,4,10,5,7,6,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],#done till here
[10,10,5,10,4,7,3,10,2,10,2,7,3,7,4,10,5,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,4,10,3,10,2,10,1,7,1,7,2,10,3,7,4,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,3,10,2,10,1,7,0,7,0,10,1,7,2,7,3,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,3,7,2,7,1,10,0,7,0,10,1,7,2,10,3,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,4,7,3,10,2,7,1,10,1,7,2,7,3,7,4,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,5,7,4,10,3,10,2,10,2,7,3,7,4,10,5,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,6,10,5,7,4,7,3,7,3,7,4,7,5,7,6,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]])
w= array([[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,6,7,5,10,4,7,3,7,3,10,4,10,5,7,6,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],#done till here
[10,10,5,10,4,7,3,10,2,10,2,7,3,7,4,10,5,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,4,10,3,10,2,10,1,7,1,7,2,10,3,7,4,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,3,10,2,10,1,7,0,7,0,10,1,7,2,7,3,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,3,7,2,7,1,10,0,7,0,10,1,7,2,10,3,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,4,7,3,10,2,7,1,10,1,7,2,7,3,7,4,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,5,7,4,10,3,10,2,10,2,7,3,7,4,10,5,10,10],
[10,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,7,10,10],
[10,10,6,10,5,7,4,7,3,7,3,7,4,7,5,7,6,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10],
[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]])
#sarting position is 1,1 .....x,y are positions in y and x direction.
x = y = 2
while(i[x][y]!=0):
w[x][y] = 9
a = i[x][y]
d = i[x+1][y] #downward direction one unit
u = i[x-1][y] #upward direction one unit
l = i[x][y-1] #left direction one unit
r = i[x][y+1] #right direcion one unit
D = i[x+2][y] #downward 2 units
U = i[x-2][y] # upward 2 units
L = i[x][y-2] #left 2 units
R = i[x][y+2] #right 2 units
# sorting the cell values.
val = [D,R,L,U]
asc = array((sorted(set(val))))
print(asc)# arranging the values in ascending order.
print(asc[0],asc[1])
l1 = asc.size
print(l1)
p = 0
while(p<l1): # to get the number of elements in the sorted array excluding 10
#print("working")
if(asc[p]==10):
l1 = l1-1
p = p+1
# now walls are to be checked
t = min(d,l,u,r)
if(l1 == 4):
a = x
b = y
if(d == t):
if(D == asc[0]):
x +=2
elif(r == t):
if(R == asc[0]):
y+=2
elif( u == t):
if(U == asc[0]):
x = x-2
elif( l == t):
if(L == asc[0]):
y =y-2
if(a==x and b == y):
if (d == t):
if (D == asc[1]):
x += 2
elif (r == t):
if (R == asc[1]):
y += 2
elif (u == t):
if (U == asc[1]):
x = x - 2
elif (l == t):
if (L == asc[1]):
y = y - 2
if(a == x and b == y):
if (d == t):
if (D == asc[2]):
x += 2
elif (r == t):
if (R == asc[2]):
y += 2
elif (u == t):
if (U == asc[2]):
x = x - 2
elif (l == t):
if (L == asc[2]):
y = y - 2
if(a == x and b == y):
if (d == t):
if (D == asc[3]):
x += 2
elif (r == t):
if (R == asc[3]):
y += 2
elif (u == t):
if (U == asc[3]):
x = x - 2
elif (l == t):
if (L == asc[3]):
y = y - 2
elif (l1 == 3):
a = x
b = y
if(d == t):
if(D == asc[0]):
x +=2
elif(r == t):
if(R == asc[0]):
y+=2
elif( u == t):
if(U == asc[0]):
x = x-2
elif( l == t):
if(L == asc[0]):
y =y-2
if(a==x and b == y):
if (d == t):
if (D == asc[1]):
x += 2
elif (r == t):
if (R == asc[1]):
y += 2
elif (u == t):
if (U == asc[1]):
x = x - 2
elif (l == t):
if (L == asc[1]):
y = y - 2
if(a == x and b == y):
if (d == t):
if (D == asc[2]):
x += 2
elif (r == t):
if (R == asc[2]):
y += 2
elif (u == t):
if (U == asc[2]):
x = x - 2
elif (l == t):
if (L == asc[2]):
y = y - 2
elif(l1 == 2):
a = x
b = y
if (d == t):
if (D == asc[0]):
x += 2
elif (r == t):
if (R == asc[0]):
y += 2
elif (u == t):
if (U == asc[0]):
x = x - 2
elif (l == t):
if (L == asc[0]):
y = y - 2
print(a,b,x,y)
if (a == x and b == y):
if (d == t):
if (D == asc[1]):
x += 2
elif (r == t):
if (R == asc[1]):
y += 2
elif (u == t):
if (U == asc[1]):
x = x - 2
elif (l == t):
if (L == asc[1]):
y = y - 2
elif(l1 == 1):
a = x
b = y
if (d == t):
if (D == asc[0]):
x += 2
elif (r == t):
if (R == asc[0]):
y += 2
elif (u == t):
if (U == asc[0]):
x = x - 2
elif (l == t):
if (L == asc[0]):
y = y - 2
print("a , b" ,a,b)
print("x , y",x,y)
| 29.185315 | 86 | 0.350186 | 1,735 | 8,347 | 1.684726 | 0.045533 | 0.492645 | 0.636333 | 0.722545 | 0.813548 | 0.806363 | 0.806363 | 0.806363 | 0.796784 | 0.791652 | 0 | 0.356636 | 0.40877 | 8,347 | 285 | 87 | 29.287719 | 0.235664 | 0.05511 | 0 | 0.816144 | 0 | 0 | 0.001274 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.004484 | 0 | 0.004484 | 0.026906 | 0 | 0 | 1 | null | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 |
2705778a3699cb848dcaa1c5ff43bd502d1476b1 | 6,945 | py | Python | core/migrations/0002_auto_20211122_1315.py | marceloshigenaga/PCWEES | 2a9d05e844a76e2f63523d3a121c315f66fa867f | [
"MIT"
] | null | null | null | core/migrations/0002_auto_20211122_1315.py | marceloshigenaga/PCWEES | 2a9d05e844a76e2f63523d3a121c315f66fa867f | [
"MIT"
] | null | null | null | core/migrations/0002_auto_20211122_1315.py | marceloshigenaga/PCWEES | 2a9d05e844a76e2f63523d3a121c315f66fa867f | [
"MIT"
] | 1 | 2021-11-26T12:13:25.000Z | 2021-11-26T12:13:25.000Z | # Generated by Django 3.2.9 on 2021-11-22 16:15
from django.db import migrations, models
import django.db.models.deletion
import stdimage.models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Topico_swebook_1',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, verbose_name='Tópico 1')),
],
),
migrations.CreateModel(
name='Topico_swebook_2',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, verbose_name='Tópico 2')),
('associacao', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.topico_swebook_1')),
],
),
migrations.AddField(
model_name='exemplo',
name='conhecimento_previo_ou_restricoes',
field=models.TextField(verbose_name='Conhecimento Prévio e Restrições de Uso'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_descicao_conceitual_problema',
field=models.TextField(verbose_name='Descrição Conceitual do Problema'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_descricao_solucao',
field=models.TextField(verbose_name='Descrição da Solução e Etapas da Solução'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_imagem_problema',
field=stdimage.models.StdImageField(upload_to='IMG-exemplos', verbose_name='Imagem para demonstrar o contexto'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_imagem_resultado',
field=stdimage.models.StdImageField(upload_to='IMG-exemplos', verbose_name='Imagem para demonstrar um resultado'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_imagem_solucao',
field=stdimage.models.StdImageField(upload_to='IMG-exemplos', verbose_name='Imagem para demonstrar as etapas de solução'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_material_complementar',
field=models.TextField(verbose_name='Material Complementar'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_ocorrencia_problema',
field=models.TextField(verbose_name='Ocorrência do Problema no Projeto'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='exemplo_resultado',
field=models.TextField(verbose_name='Resultado'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='outros_topicos',
field=models.CharField(max_length=200, verbose_name='Outros Tópicos'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_data_extracao_exemplo',
field=models.DateField(),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_descricao',
field=models.TextField(verbose_name='Descrição do Projeto'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_linguagem_programacao',
field=models.CharField(max_length=200, verbose_name='Linguagem de Programação'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_link',
field=models.CharField(max_length=200, verbose_name='Link do Projeto'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_link_exemplo',
field=models.CharField(max_length=200, verbose_name='Link do Exemplo'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='projeto_nome',
field=models.CharField(max_length=200, verbose_name='Nome do projeto'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='sugestores_de_uso',
field=models.TextField(verbose_name='Sugestões de Uso'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='tag_1',
field=models.CharField(max_length=200, verbose_name='Tag 1'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='tag_2',
field=models.CharField(max_length=200, verbose_name='Tag 2'),
preserve_default=False,
),
migrations.AddField(
model_name='exemplo',
name='tag_3',
field=models.CharField(max_length=200, verbose_name='Tag 3'),
preserve_default=False,
),
migrations.CreateModel(
name='Topico_swebook_3',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, verbose_name='Tópico 3')),
('associacao', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.topico_swebook_2')),
],
),
migrations.AddField(
model_name='exemplo',
name='topico_swebook_1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.topico_swebook_1'),
),
migrations.AddField(
model_name='exemplo',
name='topico_swebook_2',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.topico_swebook_2'),
),
migrations.AddField(
model_name='exemplo',
name='topico_swebook_3',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='core.topico_swebook_3'),
),
]
| 39.913793 | 134 | 0.597696 | 685 | 6,945 | 5.835037 | 0.164964 | 0.085314 | 0.132349 | 0.155367 | 0.83963 | 0.780085 | 0.738304 | 0.738304 | 0.702777 | 0.668251 | 0 | 0.014649 | 0.292297 | 6,945 | 173 | 135 | 40.144509 | 0.798576 | 0.006479 | 0 | 0.622754 | 1 | 0 | 0.18875 | 0.055378 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.017964 | 0 | 0.035928 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
2733a84435afeb80fe9f02138e1824a000b74963 | 8,271 | py | Python | test/test_accounts_api.py | cvent/octopus-deploy-api-client | 0e03e842e1beb29b132776aee077df570b88366a | [
"Apache-2.0"
] | null | null | null | test/test_accounts_api.py | cvent/octopus-deploy-api-client | 0e03e842e1beb29b132776aee077df570b88366a | [
"Apache-2.0"
] | null | null | null | test/test_accounts_api.py | cvent/octopus-deploy-api-client | 0e03e842e1beb29b132776aee077df570b88366a | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Octopus Server API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import octopus_deploy_swagger_client
from octopus_deploy_client.accounts_api import AccountsApi # noqa: E501
from octopus_deploy_swagger_client.rest import ApiException
class TestAccountsApi(unittest.TestCase):
"""AccountsApi unit test stubs"""
def setUp(self):
self.api = octopus_deploy_client.accounts_api.AccountsApi() # noqa: E501
def tearDown(self):
pass
def test_create_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for create_response_descriptor_environments_accounts_account_accounts_account_resource
Create a AccountResource # noqa: E501
"""
pass
def test_create_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for create_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Create a AccountResource # noqa: E501
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_account_public_key_download_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_account_public_key_download_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_account_public_key_download_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_account_public_key_download_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_account_usage_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_account_usage_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_account_usage_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_account_usage_list_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_environments_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_environments_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_environments_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_environments_list_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_resource_groups_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_resource_groups_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_resource_groups_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_resource_groups_list_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_storage_accounts_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_storage_accounts_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_storage_accounts_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_storage_accounts_list_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_list_action_spaces
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_slot_list_action(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_slot_list_action
"""
pass
def test_custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_slot_list_action_spaces(self):
"""Test case for custom_action_response_descriptor_octopus_server_web_api_actions_azure_web_sites_slot_list_action_spaces
"""
pass
def test_delete_on_background_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for delete_on_background_response_descriptor_environments_accounts_account_accounts_account_resource
Delete a AccountResource by ID # noqa: E501
"""
pass
def test_delete_on_background_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for delete_on_background_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Delete a AccountResource by ID # noqa: E501
"""
pass
def test_index_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for index_response_descriptor_environments_accounts_account_accounts_account_resource
Get a list of AccountResources # noqa: E501
"""
pass
def test_index_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for index_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Get a list of AccountResources # noqa: E501
"""
pass
def test_list_all_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for list_all_response_descriptor_environments_accounts_account_accounts_account_resource
Get a list of AccountResources # noqa: E501
"""
pass
def test_list_all_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for list_all_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Get a list of AccountResources # noqa: E501
"""
pass
def test_load_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for load_response_descriptor_environments_accounts_account_accounts_account_resource
Get a AccountResource by ID # noqa: E501
"""
pass
def test_load_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for load_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Get a AccountResource by ID # noqa: E501
"""
pass
def test_modify_response_descriptor_environments_accounts_account_accounts_account_resource(self):
"""Test case for modify_response_descriptor_environments_accounts_account_accounts_account_resource
Modify a AccountResource by ID # noqa: E501
"""
pass
def test_modify_response_descriptor_environments_accounts_account_accounts_account_resource_spaces(self):
"""Test case for modify_response_descriptor_environments_accounts_account_accounts_account_resource_spaces
Modify a AccountResource by ID # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| 40.743842 | 131 | 0.79942 | 1,009 | 8,271 | 5.91774 | 0.089197 | 0.156758 | 0.093787 | 0.14068 | 0.921454 | 0.911405 | 0.911405 | 0.898677 | 0.881259 | 0.881259 | 0 | 0.012092 | 0.160077 | 8,271 | 202 | 132 | 40.945545 | 0.847416 | 0.467779 | 0 | 0.421875 | 1 | 0 | 0.001984 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4375 | false | 0.421875 | 0.078125 | 0 | 0.53125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 10 |
274fc7dba1c1981306d94f56c02a682ca23c93bc | 142 | py | Python | web-gui/flaskr/apps/pricing/add.py | kpk-pl/wallet | 68bcc2685d1932e4a5ec021c09854c1d6a7294a9 | [
"MIT"
] | null | null | null | web-gui/flaskr/apps/pricing/add.py | kpk-pl/wallet | 68bcc2685d1932e4a5ec021c09854c1d6a7294a9 | [
"MIT"
] | null | null | null | web-gui/flaskr/apps/pricing/add.py | kpk-pl/wallet | 68bcc2685d1932e4a5ec021c09854c1d6a7294a9 | [
"MIT"
] | null | null | null | from flask import render_template
from flaskr import header
def add():
return render_template("pricing/add.html", header=header.data())
| 20.285714 | 68 | 0.767606 | 20 | 142 | 5.35 | 0.65 | 0.261682 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.133803 | 142 | 6 | 69 | 23.666667 | 0.869919 | 0 | 0 | 0 | 0 | 0 | 0.112676 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | true | 0 | 0.5 | 0.25 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 8 |
27558b977daeb2f6402602484c4541c3ca39a678 | 33,890 | py | Python | tests/base/test_doing.py | ProSapien/hio | 7c7110611d424ab2e04c277d8d6605cc0e2c8e79 | [
"Apache-2.0"
] | null | null | null | tests/base/test_doing.py | ProSapien/hio | 7c7110611d424ab2e04c277d8d6605cc0e2c8e79 | [
"Apache-2.0"
] | null | null | null | tests/base/test_doing.py | ProSapien/hio | 7c7110611d424ab2e04c277d8d6605cc0e2c8e79 | [
"Apache-2.0"
] | null | null | null | # -*- encoding: utf-8 -*-
"""
tests.core.test_doing module
"""
import pytest
import os
import inspect
from hio.base import tyming
from hio.base import doing
from hio.base.doing import State
from hio.core.tcp import serving, clienting
from hio.core.serial import serialing
# for testing purposes
class TryDoer(doing.Doer):
"""
TryDoer supports testing with methods to record sends and yields
Inherited Attributes:
.done is Boolean completion state:
True means completed
Otherwise incomplete. Incompletion maybe due to close or abort.
Attributes:
.states is list of State namedtuples (tyme, context, feed, count)
.count is context count
Inherited Properties:
.tyme is float ._tymist.tyme, relative cycle or artificial time
.tock is float, desired time in seconds between runs or until next run,
non negative, zero means run asap
Properties:
Methods:
.wind injects ._tymist dependency
.__call__ makes instance callable
Appears as generator function that returns generator
.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.exit is exit context method
.close is close context method
.abort is abort context method
"""
def __init__(self, **kwa):
"""
Initialize instance.
Parameters:
tymist is Tymist instance
tock is float seconds initial value of .tock
"""
super(TryDoer, self).__init__(**kwa)
self.states = []
self.count = None
def enter(self):
"""
"""
feed = "Default"
self.count = 0
self.states.append(State(tyme=self.tyme, context="enter",
feed=feed, count=self.count))
def recur(self, tyme):
"""
"""
self.count += 1
self.states.append(State(tyme=self.tyme, context="recur",
feed=tyme, count=self.count))
if self.count > 3:
return True # complete
return False # incomplete
def exit(self):
"""
"""
self.count += 1
self.states.append(State(tyme=self.tyme, context='exit',
feed=None, count=self.count))
def close(self):
"""
"""
self.count += 1
self.states.append(State(tyme=self.tyme, context='close',
feed=None, count=self.count))
def abort(self, ex):
"""
"""
self.count += 1
self.states.append(State(tyme=self.tyme, context='abort',
feed=ex.args[0], count=self.count))
@doing.doize()
def tryDo(states, tymist, tock=0.0, **opts):
"""
Generator function test example non-class based generator.
Calling this function returns generator
"""
feed = "Default"
count = 0
try:
# enter context
states.append(State(tyme=tymist.tyme, context="enter", feed=feed, count=count))
while (True): # recur context
feed = (yield (count)) # yields tock then waits for next send
count += 1
states.append(State(tyme=tymist.tyme, context="recur", feed=feed, count = count))
if count > 3:
break # normal exit
except GeneratorExit: # close context, forced exit due to .close
count += 1
states.append(State(tyme=tymist.tyme, context='close', feed=feed, count=count))
except Exception: # abort context, forced exit due to uncaught exception
count += 1
states.append(State(tyme=tymist.tyme, context='abort', feed=feed, count=count))
raise
finally: # exit context, unforced exit due to normal exit of try
count += 1
states.append(State(tyme=tymist.tyme, context='exit', feed=feed, count=count))
return (True) # return value of yield from, or yield ex.value of StopIteration
def test_doify():
"""
Test wrapper function doify()
"""
def genfun(tymist=None, tock=0.0, **opts):
tyme = yield(tock)
assert inspect.isgeneratorfunction(genfun)
gf0 = doing.doify(genfun, name='gf0', tock=0.25)
gf1 = doing.doify(genfun, name='gf1', tock=0.125)
assert inspect.isgeneratorfunction(gf0)
assert inspect.isgeneratorfunction(gf1)
assert id(gf0) != id(gf1)
assert gf0.__name__ == 'gf0'
assert gf1.__name__ == 'gf1'
assert gf0.tock == 0.25
assert gf1.tock == 0.125
assert gf0.done == None
assert gf1.done == None
assert gf0.opts == dict()
assert gf1.opts == dict()
tymist = tyming.Tymist()
g0 = gf0(tymist=tymist, tock=gf0.tock, **gf0.opts)
assert inspect.isgenerator(g0)
g1 = gf0(tymist=tymist, tock=gf1.tock, **gf1.opts)
assert inspect.isgenerator(g1)
assert id(g0) != id(g1)
"""End Test"""
def test_doize():
"""
Test decorator @doize
"""
@doing.doize(tock=0.25)
def genfun(tymist=None, tock=0.0, **opts):
tyme = yield(tock)
assert inspect.isgeneratorfunction(genfun)
assert genfun.tock == 0.25
assert genfun.done == None
assert genfun.opts == dict()
tymist = tyming.Tymist()
gen = genfun(tymist=tymist, tock=genfun.tock, **genfun.opts)
assert inspect.isgenerator(gen)
"""End Test"""
def test_doer():
"""
Test Doer base class
"""
tock = 1.0
doer = doing.Doer()
assert isinstance(doer._tymist, tyming.Tymist)
assert doer.tock == 0.0
tymist = tyming.Tymist()
doer = doing.Doer(tymist=tymist, tock=tock)
assert doer._tymist == tymist
assert doer.tock == tock == 1.0
doer.tock = 0.0
assert doer.tock == 0.0
# create generator use send and explicit close
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, **args)
assert inspect.isgenerator(dog)
result = dog.send(None)
assert result == doer.tock == 0.0
result = dog.send("Hello")
assert result == doer.tock == 0.0
result = dog.send("Hi")
assert result == doer.tock == 0.0
result = dog.close()
assert result == None # no yielded value on close
with pytest.raises(StopIteration): # send after close
try:
result = dog.send("what?")
except StopIteration as ex:
assert ex.value == None
raise
# use next instead of send
dog = doer(tymist=doer._tymist, tock=doer.tock)
assert inspect.isgenerator(dog)
result = next(dog)
assert result == doer.tock == 0.0
result = next(dog)
assert result == doer.tock == 0.0
result = next(dog)
assert result == doer.tock == 0.0
result = dog.close()
assert result == None
with pytest.raises(StopIteration): # send after close
try:
result = dog.send("what?")
except StopIteration as ex:
assert ex.value == None
raise
# use different tock
dog = doer(tymist=doer._tymist, tock=tock)
assert inspect.isgenerator(dog)
result = next(dog)
assert result == tock == 1.0
result = next(dog)
assert result == tock == 1.0
result = next(dog)
assert result == tock == 1.0
result = dog.close()
assert result == None
with pytest.raises(StopIteration):
result = dog.send("what?")
doer.tock = 0.0
dog = doer(tymist=doer._tymist, tock=tock)
assert inspect.isgenerator(dog)
result = next(dog)
assert result == tock == 1.0
result = next(dog)
assert result == 1.0
result = next(dog)
assert result == 1.0
result = dog.close()
assert result == None
with pytest.raises(StopIteration): # send after close
try:
result = dog.send("what?")
except StopIteration as ex:
assert ex.value == None
raise
"""End Test """
def test_redoer():
"""
Test ReDoer base class
"""
tock = 1.0
doer = doing.ReDoer()
assert isinstance(doer._tymist, tyming.Tymist)
assert doer.tock == 0.0
tymist = tyming.Tymist()
doer = doing.ReDoer(tymist=tymist, tock=tock)
assert doer._tymist == tymist
assert doer.tock == tock == 1.0
doer.tock = 0.0
assert doer.tock == 0.0
# create generator use send and run until normal exit. emulates Doist.ready
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, **args)
assert inspect.isgenerator(dog)
result = dog.send(None)
assert result == doer.tock == 0.0
tymist.tick()
result = dog.send(tymist.tyme)
assert result == doer.tock == 0.0
tymist.tick()
result = dog.send(tymist.tyme)
assert result == doer.tock == 0.0
tymist.tick()
with pytest.raises(StopIteration):
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == True
raise
tymist.tick()
with pytest.raises(StopIteration): # send after break
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == None
raise
# create generator use send and then explicit close. emulates Doist.ready
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, **args)
assert inspect.isgenerator(dog)
result = dog.send(None)
assert result == doer.tock == 0.0
tymist.tick()
result = dog.send(tymist.tyme)
assert result == doer.tock == 0.0
result = dog.close()
assert result == None # no yielded value on close
tymist.tick()
with pytest.raises(StopIteration): # send after close
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == None
raise
# use next instead of send
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, **args)
assert inspect.isgenerator(dog)
result = next(dog)
assert result == doer.tock == 0.0
result = next(dog)
assert result == doer.tock == 0.0
result = dog.close()
assert result == None # no yielded value on close
tymist.tick()
with pytest.raises(StopIteration): # send after close
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == None
raise
"""End Test """
def test_dodoer():
"""
Test DoDoer class
"""
tock = 1.0
doer = doing.DoDoer()
assert isinstance(doer._tymist, tyming.Tymist)
assert doer.tock == 0.0
tymist = tyming.Tymist()
doer = doing.DoDoer(tymist=tymist, tock=tock)
assert doer._tymist == tymist
assert doer.tock == tock == 1.0
doer.tock = 0.0
assert doer.tock == 0.0
# create generator use send and run until normal exit. emulates Doist.ready
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, **args)
assert inspect.isgenerator(dog)
assert doer.doers == []
result = dog.send(None)
assert result == doer.tock == 0.0
assert doer.doers == []
tymist.tick() # empty doers does list so ends right away
with pytest.raises(StopIteration):
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == True
raise
tymist.tick()
with pytest.raises(StopIteration): # send after break
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == None
raise
# create some doers
doer0 = doing.Doer()
doer1 = doing.Doer()
doer2 = doing.Doer()
doers = [doer0, doer1, doer2]
# create generator use send and then explicit close. emulates Doist.ready
args = {}
dog = doer(tymist=doer._tymist, tock=doer.tock, doers=doers, **args)
assert inspect.isgenerator(dog)
assert doer.doers == []
result = dog.send(None)
assert result == doer.tock == 0.0
assert doer.doers == doers
tymist.tick()
result = dog.send(tymist.tyme)
assert result == doer.tock == 0.0
tymist.tick()
result = dog.send(tymist.tyme)
assert result == doer.tock == 0.0
result = dog.close()
assert result == None # no yielded value on close
tymist.tick()
with pytest.raises(StopIteration): # send after close
try:
result = dog.send(tymist.tyme)
except StopIteration as ex:
assert ex.value == None
raise
"""End Test """
def test_exampleDo():
"""
Test exampleDo generator function non-class based
"""
exDo = doing.exDo
assert inspect.isgeneratorfunction(exDo)
assert hasattr(exDo, "tock")
assert hasattr(exDo, "opts")
assert "states" in exDo.opts
assert exDo.opts["states"] == None
exDo.opts["states"] = []
tymist = tyming.Tymist()
dog = exDo(tymist=tymist, tock=exDo.tock, **exDo.opts)
assert inspect.isgenerator(dog)
tock = dog.send(None)
assert tock == 0.0
tock = dog.send("Hello")
assert tock == 0.0
tock = dog.send("Hi")
assert tock == 0.0
tock = dog.close()
assert tock == None
with pytest.raises(StopIteration):
tock = dog.send("what?")
assert exDo.opts["states"] == [State(tyme=0.0, context='enter', feed=0.0, count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.0, context='recur', feed='Hi', count=2),
State(tyme=0.0, context='close', feed=None, count=3),
State(tyme=0.0, context='exit', feed=None, count=4)]
exDo.opts["states"] = []
dog = exDo(tymist=tymist, tock=1.0, **exDo.opts)
assert inspect.isgenerator(dog)
tock = dog.send(None)
assert tock == 1.0
tock = dog.send("Hello")
assert tock == 1.0
tock = dog.send("Hi")
assert tock == 1.0
tock = dog.close()
assert tock == None
with pytest.raises(StopIteration):
tock = dog.send("what?")
assert exDo.opts["states"] == [State(tyme=0.0, context='enter', feed=0.0, count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.0, context='recur', feed='Hi', count=2),
State(tyme=0.0, context='close', feed=None, count=3),
State(tyme=0.0, context='exit', feed=None, count=4)]
exDo.opts["states"] = []
dog = exDo(tymist=tymist, tock=1.0, **exDo.opts)
assert inspect.isgenerator(dog)
tock = next(dog)
assert tock == 1.0
tock = next(dog)
assert tock == 1.0
tock = next(dog)
assert tock == 1.0
tock = dog.close()
assert tock == None
with pytest.raises(StopIteration):
tock = dog.send("what?")
assert exDo.opts["states"] == [State(tyme=0.0, context='enter', feed=0.0, count=0),
State(tyme=0.0, context='recur', feed=None, count=1),
State(tyme=0.0, context='recur', feed=None, count=2),
State(tyme=0.0, context='close', feed=None, count=3),
State(tyme=0.0, context='exit', feed=None, count=4)]
"""End Test """
def test_trydoer_break():
"""
Test WhoDoer testing class with break to normal exit
"""
tymist = tyming.Tymist(tock=0.125)
doer = TryDoer(tymist=tymist, tock=0.25)
assert doer._tymist == tymist
assert doer._tymist.tock == 0.125
assert doer.tock == 0.25
assert doer.states == []
assert tymist.tyme == 0.0
do = doer(tymist=doer._tymist, tock=doer.tock)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
result = do.send("Blue")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3)]
tymist.tick()
try:
result = do.send("Red")
except StopIteration as ex:
assert ex.value == True # clean return
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3),
State(tyme=0.375, context='recur', feed='Red', count=4),
State(tyme=0.375, context='exit', feed=None, count=5)]
# send after break
tymist.tick()
try:
result = do.send("Red")
except StopIteration as ex:
assert ex.value == None # after break no StopIteration value
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3),
State(tyme=0.375, context='recur', feed='Red', count=4),
State(tyme=0.375, context='exit', feed=None, count=5)]
"""End Test """
def test_trydoer_close():
"""
Test WhoDoer testing class with close to force exit
"""
tymist = tyming.Tymist(tock=0.125)
doer = TryDoer(tymist=tymist, tock=0.25)
assert doer._tymist == tymist
assert doer._tymist.tock == 0.125
assert doer.tock == 0.25
assert doer.states == []
assert tymist.tyme == 0.0
do = doer(tymist=doer._tymist, tock=doer.tock)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
result = do.close()
assert result == None # not clean return no return from close
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='close', feed=None, count=3),
State(tyme=0.25, context='exit', feed=None, count=4)]
# send after close
tymist.tick()
try:
result = do.send("what?")
except StopIteration as ex:
assert ex.value == None # after close no StopIteration value
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='close', feed=None, count=3),
State(tyme=0.25, context='exit', feed=None, count=4)]
"""End Test """
def test_trydoer_throw():
"""
Test WhoDoer testing class with throw to force exit
"""
tymist = tyming.Tymist(tock=0.125)
doer = TryDoer(tymist=tymist, tock=0.25)
assert doer._tymist == tymist
assert doer._tymist.tock == 0.125
assert doer.tock == 0.25
assert doer.states == []
assert tymist.tyme == 0.0
do = doer(tymist=doer._tymist, tock=doer.tock)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 0.25
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
try:
result = do.throw(ValueError, "Bad")
except ValueError as ex:
assert ex.args[0] == "Bad" # exception alue is thrown value
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='abort', feed='Bad', count=3),
State(tyme=0.25, context='exit', feed=None, count=4)]
# send after throw
tymist.tick()
try:
result = do.send("what?")
except StopIteration as ex:
assert ex.value == None # after throw no StopIteration value
assert doer.states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='abort', feed='Bad', count=3),
State(tyme=0.25, context='exit', feed=None, count=4)]
def test_trydo_break():
"""
Test trialdog testing function example with break to normal exit
"""
assert inspect.isgeneratorfunction(tryDo)
assert hasattr(tryDo, "tock")
assert hasattr(tryDo, "opts")
tymist = tyming.Tymist(tock=0.125)
assert tymist.tyme == 0.0
states = []
do = tryDo(states=states, tymist=tymist, tock=0.25)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 1
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 2
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
result = do.send("Blue")
assert result == 3
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3)]
tymist.tick()
try:
result = do.send("Red")
except StopIteration as ex:
assert ex.value == True # clean return
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3),
State(tyme=0.375, context='recur', feed='Red', count=4),
State(tyme=0.375, context='exit', feed='Red', count=5)]
# send after break
tymist.tick()
try:
result = do.send("Red")
except StopIteration as ex:
assert ex.value == None # no value after already finished
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='recur', feed='Blue', count=3),
State(tyme=0.375, context='recur', feed='Red', count=4),
State(tyme=0.375, context='exit', feed='Red', count=5)]
"""End Test """
def test_trydo_close():
"""
Test traildog testing function example with close to force exit
"""
tymist = tyming.Tymist(tock=0.125)
assert tymist.tyme == 0.0
states = []
do = tryDo(states=states, tymist=tymist, tock=0.25)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 1
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 2
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
result = do.close()
assert result == None
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='close', feed='Hi', count=3),
State(tyme=0.25, context='exit', feed='Hi', count=4)]
tymist.tick()
try:
result = do.send("what?")
except StopIteration as ex:
assert ex.value == None # not clean return
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='close', feed='Hi', count=3),
State(tyme=0.25, context='exit', feed='Hi', count=4)]
"""End Test """
def test_trydo_throw():
"""
Test trialdog testing function example with throw to force exit
"""
tymist = tyming.Tymist(tock=0.125)
assert tymist.tyme == 0.0
states = []
do = tryDo(states=states, tymist=tymist, tock=0.25)
assert inspect.isgenerator(do)
result = do.send(None)
assert result == 0
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0)]
result = do.send("Hello")
assert result == 1
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1)]
tymist.tick()
result = do.send("Hi")
assert result == 2
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2)]
tymist.tick()
try:
result = do.throw(ValueError, "Bad")
except ValueError as ex:
assert ex.args[0] == "Bad"
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='abort', feed='Hi', count=3),
State(tyme=0.25, context='exit', feed='Hi', count=4)]
tymist.tick()
try:
result = do.send("what?")
except StopIteration as ex:
assert ex.value == None # not clean return
assert states == [State(tyme=0.0, context='enter', feed='Default', count=0),
State(tyme=0.0, context='recur', feed='Hello', count=1),
State(tyme=0.125, context='recur', feed='Hi', count=2),
State(tyme=0.25, context='abort', feed='Hi', count=3),
State(tyme=0.25, context='exit', feed='Hi', count=4)]
def test_server_client():
"""
Test ServerDoer ClientDoer classes
"""
tock = 0.03125
ticks = 16
limit = ticks * tock
doist = doing.Doist(tock=tock, real=True, limit=limit)
assert doist.tyme == 0.0 # on next cycle
assert doist.tock == tock == 0.03125
assert doist.real == True
assert doist.limit == limit == 0.5
assert doist.doers == []
port = 6120
server = serving.Server(host="", port=port)
client = clienting.Client(host="localhost", port=port)
serdoer = doing.ServerDoer(tymist=doist, server=server)
assert serdoer.server.tymist == serdoer._tymist == doist
assert serdoer.server == server
clidoer = doing.ClientDoer(tymist=doist, client=client)
assert clidoer.client.tymist == clidoer._tymist == doist
assert clidoer.client == client
assert serdoer.tock == 0.0 # ASAP
assert clidoer.tock == 0.0 # ASAP
doers = [serdoer, clidoer]
for doer in doers:
assert doer._tymist == doist
msgTx = b"Hello me maties!"
clidoer.client.tx(msgTx)
doist.do(doers=doers)
assert doist.tyme == limit
assert server.opened == False
assert client.opened == False
assert not client.txes
ca, ix = list(server.ixes.items())[0]
msgRx = bytes(ix.rxbs)
assert msgRx == msgTx
"""End Test """
def test_echo_server_client():
"""
Test EchoServerDoer ClientDoer classes
"""
tock = 0.03125
ticks = 16
limit = ticks * tock
doist = doing.Doist(tock=tock, real=True, limit=limit)
assert doist.tyme == 0.0 # on next cycle
assert doist.tock == tock == 0.03125
assert doist.real == True
assert doist.limit == limit == 0.5
assert doist.doers == []
port = 6120
server = serving.Server(host="", port=port)
client = clienting.Client(host="localhost", port=port)
serdoer = doing.EchoServerDoer(tymist=doist, server=server)
assert serdoer.server.tymist == serdoer._tymist == doist
assert serdoer.server == server
clidoer = doing.ClientDoer(tymist=doist, client=client)
assert clidoer.client.tymist == clidoer._tymist == doist
assert serdoer.tock == 0.0 # ASAP
assert clidoer.tock == 0.0 # ASAP
doers = [serdoer, clidoer]
for doer in doers:
assert doer._tymist == doist
msgTx = b"Hello me maties!"
clidoer.client.tx(msgTx)
doist.do(doers=doers)
assert doist.tyme == limit
assert server.opened == False
assert client.opened == False
assert not client.txes
msgEx = bytes(client.rxbs) # echoed back message
assert msgEx == msgTx
ca, ix = list(server.ixes.items())[0]
assert bytes(ix.rxbs) == b"" # empty server rxbs becaue echoed
"""End Test """
def test_echo_console():
"""
Test EchoConsoleDoer class
Must run in WindIDE with Debug I/O configured as external console
"""
port = os.ctermid() # default to console
try: # check to see if running in external console
fd = os.open(port, os.O_NONBLOCK | os.O_RDWR | os.O_NOCTTY)
except OSError as ex:
# maybe complain here
return # not in external console
else:
os.close(fd) # cleanup
tock = 0.03125
ticks = 16
limit = 0.0
# limit = ticks * tock
doist = doing.Doist(tock=tock, real=True, limit=limit)
assert doist.tyme == 0.0 # on next cycle
assert doist.tock == tock == 0.03125
assert doist.real == True
assert doist.limit == 0.0
# assert doist.limit == limit == 0.5
assert doist.doers == []
console = serialing.Console()
echoer = doing.EchoConsoleDoer(console=console)
doers = [echoer]
doist.do(doers=doers)
# assert doist.tyme == limit
assert console.opened == False
"""End Test """
if __name__ == "__main__":
test_echo_console()
| 33.788634 | 93 | 0.568309 | 4,310 | 33,890 | 4.447564 | 0.064965 | 0.062445 | 0.064166 | 0.041891 | 0.800981 | 0.784391 | 0.771715 | 0.759716 | 0.757473 | 0.73911 | 0 | 0.034273 | 0.292299 | 33,890 | 1,002 | 94 | 33.822355 | 0.764968 | 0.107642 | 0 | 0.810127 | 0 | 0 | 0.047993 | 0 | 0 | 0 | 0 | 0 | 0.340366 | 1 | 0.033755 | false | 0 | 0.011252 | 0 | 0.052039 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
275f8feaf93f2f5470a1d5a33c5be5a624d63edf | 23,260 | py | Python | wf_psf/tf_mccd_psf_field.py | tobias-liaudat/wf-psf | 0ff1a12d06c46bd8599061d227785393fb528d76 | [
"MIT"
] | 7 | 2022-03-10T10:49:01.000Z | 2022-03-17T16:06:12.000Z | wf_psf/tf_mccd_psf_field.py | tobias-liaudat/wf-psf | 0ff1a12d06c46bd8599061d227785393fb528d76 | [
"MIT"
] | null | null | null | wf_psf/tf_mccd_psf_field.py | tobias-liaudat/wf-psf | 0ff1a12d06c46bd8599061d227785393fb528d76 | [
"MIT"
] | null | null | null | import numpy as np
import tensorflow as tf
from tensorflow.python.keras.engine import data_adapter
from wf_psf.tf_layers import TF_poly_Z_field, TF_zernike_OPD, TF_batch_poly_PSF
from wf_psf.tf_layers import TF_NP_MCCD_OPD_v2, TF_NP_GRAPH_OPD
from wf_psf.tf_layers import TF_batch_mono_PSF
from wf_psf.graph_utils import GraphBuilder
from wf_psf.utils import calc_poly_position_mat
class TF_SP_MCCD_field(tf.keras.Model):
r""" Semi-parametric MCCD PSF field model!
Semi parametric model based on the hybrid-MCCD matrix factorization scheme.
The forward model is different for the training procedure and for the
inference procedure. This makes things more complicated and requires several
custom functions.
The prediction step is the forward model for the inference while the
``call(inputs, trainable=True)`` is the forward model for the training
procedure. When calling ``call(inputs, trainable=False)`` we are falling
back to the predict function for the inference forward model. This is needed
in order to handle the calculation of validation metrics on the validation
dataset.
Parameters
----------
zernike_maps: Tensor(n_batch, opd_dim, opd_dim)
Zernike polynomial maps.
obscurations: Tensor(opd_dim, opd_dim)
Predefined obscurations of the phase.
batch_size: int
Batch size
obs_pos: Tensor(n_stars, 2)
The positions of all the stars
spatial_dic:
TODO ...
output_Q: int
Downsampling rate to match the specified telescope's sampling. The value
of `output_Q` should be equal to `oversampling_rate` in order to have
the right pixel sampling corresponding to the telescope characteristics
`pix_sampling`, `tel_diameter`, `tel_focal_length`. The final
oversampling obtained is `oversampling_rate/output_Q`.
Default is `1`, so the output psf will be super-resolved by a factor of
`oversampling_rate`.
l2_param: float
Parameter going with the l2 loss on the opd. If it is `0.` the loss
is not added. Default is `0.`.
d_max_nonparam: int
Maximum degree of the polynomial for the non-parametric variations.
output_dim: int
Output dimension of the PSF stamps.
n_zernikes: int
Order of the Zernike polynomial for the parametric model.
d_max: int
Maximum degree of the polynomial for the Zernike coefficient variations.
x_lims: [float, float]
Limits for the x coordinate of the PSF field.
y_lims: [float, float]
Limits for the x coordinate of the PSF field.
coeff_mat: Tensor or None
Initialization of the coefficient matrix defining the parametric psf
field model.
"""
def __init__(
self,
zernike_maps,
obscurations,
batch_size,
obs_pos,
spatial_dic,
output_Q,
l2_param=0.,
d_max_nonparam=3,
graph_features=6,
l1_rate=1e-3,
output_dim=64,
n_zernikes=45,
d_max=2,
x_lims=[0, 1e3],
y_lims=[0, 1e3],
coeff_mat=None,
name='TF_SP_MCCD_field'
):
super(TF_SP_MCCD_field, self).__init__()
# Inputs: oversampling used
self.output_Q = output_Q
# Inputs: TF_poly_Z_field
self.n_zernikes = n_zernikes
self.d_max = d_max
self.x_lims = x_lims
self.y_lims = y_lims
# Inputs: TF_NP_MCCD_OPD
self.d_max_nonparam = d_max_nonparam
self.opd_dim = tf.shape(zernike_maps)[1].numpy()
self.graph_features = graph_features
self.l1_rate = l1_rate
# Inputs: TF_zernike_OPD
# They are not stored as they are memory-heavy
# zernike_maps =[]
# Inputs: TF_batch_poly_PSF
self.batch_size = batch_size
self.obscurations = obscurations
self.output_dim = output_dim
# Inputs: Loss
self.l2_param = l2_param
# Initialize the first layer
self.tf_poly_Z_field = TF_poly_Z_field(
x_lims=self.x_lims, y_lims=self.y_lims, n_zernikes=self.n_zernikes, d_max=self.d_max
)
# Initialize the zernike to OPD layer
self.tf_zernike_OPD = TF_zernike_OPD(zernike_maps=zernike_maps)
# Initialize the non-parametric layer
self.tf_NP_mccd_OPD = TF_NP_MCCD_OPD_v2(
obs_pos=obs_pos,
spatial_dic=spatial_dic,
x_lims=self.x_lims,
y_lims=self.y_lims,
d_max=self.d_max_nonparam,
graph_features=self.graph_features,
l1_rate=self.l1_rate,
opd_dim=self.opd_dim
)
# Initialize the batch opd to batch polychromatic PSF layer
self.tf_batch_poly_PSF = TF_batch_poly_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
# Initialize the model parameters with non-default value
if coeff_mat is not None:
self.assign_coeff_matrix(coeff_mat)
def set_zero_nonparam(self):
r""" Set to zero the non-parametric part."""
self.tf_NP_mccd_OPD.set_alpha_zero()
def set_output_Q(self, output_Q, output_dim=None):
r""" Set the value of the output_Q parameter.
Useful for generating/predicting PSFs at a different sampling wrt the
observation sampling.
"""
self.output_Q = output_Q
if output_dim is not None:
self.output_dim = output_dim
# Reinitialize the PSF batch poly generator
self.tf_batch_poly_PSF = TF_batch_poly_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
def set_l1_rate(self, new_l1_rate):
r""" Set l1 rate the non-parametric part."""
self.l1_rate = new_l1_rate
self.tf_NP_mccd_OPD.l1_rate = new_l1_rate
def set_nonzero_nonparam(self):
r""" Set to non-zero the non-parametric part."""
self.tf_NP_mccd_OPD.set_alpha_identity()
def set_trainable_layers(self, param_bool=True, nonparam_bool=True):
r""" Set the layers to be trainable or not."""
self.tf_NP_mccd_OPD.trainable = nonparam_bool
self.tf_poly_Z_field.trainable = param_bool
def get_coeff_matrix(self):
""" Get coefficient matrix."""
return self.tf_poly_Z_field.get_coeff_matrix()
def assign_coeff_matrix(self, coeff_mat):
r""" Assign coefficient matrix."""
self.tf_poly_Z_field.assign_coeff_matrix(coeff_mat)
def predict_step(self, data, evaluate_step=False):
r""" Custom predict (inference) step.
It is needed as the non-parametric MCCD part requires a special
interpolation (different from training).
"""
if evaluate_step:
input_data = data
else:
# Format input data
data = data_adapter.expand_1d(data)
input_data, _, _ = data_adapter.unpack_x_y_sample_weight(data)
# Unpack inputs
input_positions = input_data[0]
packed_SEDs = input_data[1]
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_mccd_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the polychromatic PSFs
poly_psfs = self.tf_batch_poly_PSF([opd_maps, packed_SEDs])
return poly_psfs
def predict_mono_psfs(self, input_positions, lambda_obs, phase_N):
r""" Predict a set of monochromatic PSF at desired positions.
Parameters
----------
input_positions: Tensor(batch x 2)
Positions to predict the monochromatic PSFs.
lambda_obs: float
Observed wavelength in um.
phase_N: int
Required wavefront dimension. Should be calculated with as:
``simPSF_np = wf.SimPSFToolkit(...)``
``phase_N = simPSF_np.feasible_N(lambda_obs)``
Returns
-------
mono_psf_batch: Tensor [batch x output_dim x output_dim]
Batch of monochromatic PSFs at requested positions and
wavelength.
"""
# Initialise the monochromatic PSF batch calculator
tf_batch_mono_psf = TF_batch_mono_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
# Set the lambda_obs and the phase_N parameters
tf_batch_mono_psf.set_lambda_phaseN(phase_N, lambda_obs)
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_mccd_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the monochromatic PSFs
mono_psf_batch = tf_batch_mono_psf(opd_maps)
return mono_psf_batch
def predict_opd(self, input_positions):
r""" Predict the OPD at some positions.
Parameters
----------
input_positions: Tensor(batch_dim x 2)
Positions to predict the OPD.
Returns
-------
opd_maps : Tensor [batch x opd_dim x opd_dim]
OPD at requested positions.
"""
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_mccd_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
return opd_maps
def call(self, inputs, training=True):
r"""Define the PSF field forward model.
[1] From positions to Zernike coefficients
[2] From Zernike coefficients to OPD maps
[3] From OPD maps and SED info to polychromatic PSFs
OPD: Optical Path Differences
"""
# Unpack inputs
input_positions = inputs[0]
packed_SEDs = inputs[1]
# Forward model
# For the training
if training:
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_mccd_OPD(input_positions)
# Add l2 loss on the parmetric OPD
self.add_loss(self.l2_param * tf.math.reduce_sum(tf.math.square(nonparam_opd_maps)))
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the polychromatic PSFs
poly_psfs = self.tf_batch_poly_PSF([opd_maps, packed_SEDs])
# For the inference
# This is absolutely needed to compute the metrics on the
# validation data.
else:
# Compute predictions
poly_psfs = self.predict_step(inputs, evaluate_step=True)
return poly_psfs
def build_mccd_spatial_dic(
obs_stars, obs_pos, x_lims, y_lims, d_max=2, graph_features=6, verbose=0
):
"""Build the spatial-constraint dictionary.
Based on the hybrid approach from the MCCD model.
"""
# The obs_data needs to be in RCA format (with the batch dim at the end)
# Graph parameters
graph_kwargs = {
'obs_data': obs_stars.swapaxes(0, 1).swapaxes(1, 2),
'obs_pos': obs_pos,
'obs_weights': np.ones_like(obs_stars),
'n_comp': graph_features,
'n_eigenvects': 5,
'n_iter': 3,
'ea_gridsize': 10,
'distances': None,
'auto_run': True,
'verbose': verbose
}
# Compute graph-spatial constraint matrix
VT = GraphBuilder(**graph_kwargs).VT
# Compute polynomial-spatial constaint matrix
tf_Pi = calc_poly_position_mat(pos=obs_pos, x_lims=x_lims, y_lims=y_lims, d_max=d_max)
# Need to translate to have the batch dimension first
spatial_dic = np.concatenate((tf_Pi.numpy(), VT), axis=0).T
# Return the tf spatial dictionary
return tf.convert_to_tensor(spatial_dic, dtype=tf.float32)
def build_mccd_spatial_dic_v2(
obs_stars, obs_pos, x_lims, y_lims, d_max=2, graph_features=6, verbose=0
):
"""Build the spatial-constraint dictionaries.
Based on the hybrid approach from the MCCD model.
Returns the polynomial dict and the graph dict.
"""
# The obs_data needs to be in RCA format (with the batch dim at the end)
# Graph parameters
graph_kwargs = {
'obs_data': obs_stars.swapaxes(0, 1).swapaxes(1, 2),
'obs_pos': obs_pos,
'obs_weights': np.ones_like(obs_stars),
'n_comp': graph_features,
'n_eigenvects': 5,
'n_iter': 3,
'ea_gridsize': 10,
'distances': None,
'auto_run': True,
'verbose': verbose
}
# Compute graph-spatial constraint matrix
VT = GraphBuilder(**graph_kwargs).VT
# Compute polynomial-spatial constaint matrix
tf_Pi = calc_poly_position_mat(pos=obs_pos, x_lims=x_lims, y_lims=y_lims, d_max=d_max)
# Return the poly dictionary and the graph dictionary
return tf.transpose(tf_Pi, perm=[1, 0]), tf.convert_to_tensor(VT.T, dtype=tf.float32)
class TF_SP_graph_field(tf.keras.Model):
r""" Semi-parametric graph-constraint-only PSF field model!
Semi parametric model based on the graph-constraint-only matrix factorization scheme.
Parameters
----------
zernike_maps: Tensor(n_batch, opd_dim, opd_dim)
Zernike polynomial maps.
obscurations: Tensor(opd_dim, opd_dim)
Predefined obscurations of the phase.
batch_size: int
Batch size
d_max_nonparam: int
Maximum degree of the polynomial for the non-parametric variations.
output_dim: int
Output dimension of the PSF stamps.
n_zernikes: int
Order of the Zernike polynomial for the parametric model.
d_max: int
Maximum degree of the polynomial for the Zernike coefficient variations.
x_lims: [float, float]
Limits for the x coordinate of the PSF field.
y_lims: [float, float]
Limits for the x coordinate of the PSF field.
coeff_mat: Tensor or None
Initialization of the coefficient matrix defining the parametric psf
field model.
"""
def __init__(
self,
zernike_maps,
obscurations,
batch_size,
obs_pos,
spatial_dic,
output_Q,
l2_param=0.,
graph_features=6,
l1_rate=1e-3,
output_dim=64,
n_zernikes=45,
d_max=2,
x_lims=[0, 1e3],
y_lims=[0, 1e3],
coeff_mat=None,
name='TF_SP_graph_field'
):
super(TF_SP_graph_field, self).__init__()
# Inputs: oversampling used
self.output_Q = output_Q
# Inputs: TF_poly_Z_field
self.n_zernikes = n_zernikes
self.d_max = d_max
self.x_lims = x_lims
self.y_lims = y_lims
# Inputs: TF_NP_GRAPH_OPD
self.opd_dim = tf.shape(zernike_maps)[1].numpy()
self.graph_features = graph_features
self.l1_rate = l1_rate
# Inputs: TF_zernike_OPD
# They are not stored as they are memory-heavy
# zernike_maps =[]
# Inputs: TF_batch_poly_PSF
self.batch_size = batch_size
self.obscurations = obscurations
self.output_dim = output_dim
# Inputs: Loss
self.l2_param = l2_param
# Initialize the first layer
self.tf_poly_Z_field = TF_poly_Z_field(
x_lims=self.x_lims, y_lims=self.y_lims, n_zernikes=self.n_zernikes, d_max=self.d_max
)
# Initialize the zernike to OPD layer
self.tf_zernike_OPD = TF_zernike_OPD(zernike_maps=zernike_maps)
# Initialize the non-parametric layer
self.tf_NP_graph_OPD = TF_NP_GRAPH_OPD(
obs_pos=obs_pos,
spatial_dic=spatial_dic,
x_lims=self.x_lims,
y_lims=self.y_lims,
graph_features=self.graph_features,
l1_rate=self.l1_rate,
opd_dim=self.opd_dim
)
# Initialize the batch opd to batch polychromatic PSF layer
self.tf_batch_poly_PSF = TF_batch_poly_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
# Initialize the model parameters with non-default value
if coeff_mat is not None:
self.assign_coeff_matrix(coeff_mat)
def set_zero_nonparam(self):
""" Set to zero the non-parametric part."""
self.tf_NP_graph_OPD.set_alpha_zero()
def set_output_Q(self, output_Q, output_dim=None):
r""" Set the value of the output_Q parameter.
Useful for generating/predicting PSFs at a different sampling wrt the
observation sampling.
"""
self.output_Q = output_Q
if output_dim is not None:
self.output_dim = output_dim
# Reinitialize the PSF batch poly generator
self.tf_batch_poly_PSF = TF_batch_poly_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
def set_l1_rate(self, new_l1_rate):
""" Set l1 rate the non-parametric part."""
self.l1_rate = new_l1_rate
self.tf_NP_graph_OPD.l1_rate = new_l1_rate
def set_nonzero_nonparam(self):
""" Set to non-zero the non-parametric part."""
self.tf_NP_graph_OPD.set_alpha_identity()
def set_trainable_layers(self, param_bool=True, nonparam_bool=True):
""" Set the layers to be trainable or not."""
self.tf_NP_graph_OPD.trainable = nonparam_bool
self.tf_poly_Z_field.trainable = param_bool
def get_coeff_matrix(self):
""" Get coefficient matrix."""
return self.tf_poly_Z_field.get_coeff_matrix()
def assign_coeff_matrix(self, coeff_mat):
""" Assign coefficient matrix."""
self.tf_poly_Z_field.assign_coeff_matrix(coeff_mat)
def predict_step(self, data, evaluate_step=False):
""" Custom predict (inference) step.
It is needed as the non-parametric MCCD part requires a special
interpolation (different from training).
"""
if evaluate_step:
input_data = data
else:
# Format input data
data = data_adapter.expand_1d(data)
input_data, _, _ = data_adapter.unpack_x_y_sample_weight(data)
# Unpack inputs
input_positions = input_data[0]
packed_SEDs = input_data[1]
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_graph_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the polychromatic PSFs
poly_psfs = self.tf_batch_poly_PSF([opd_maps, packed_SEDs])
return poly_psfs
def predict_mono_psfs(self, input_positions, lambda_obs, phase_N):
r""" Predict a set of monochromatic PSF at desired positions.
Parameters
----------
input_positions: Tensor(batch x 2)
Positions to predict the monochromatic PSFs.
lambda_obs: float
Observed wavelength in um.
phase_N: int
Required wavefront dimension. Should be calculated with as:
``simPSF_np = wf.SimPSFToolkit(...)``
``phase_N = simPSF_np.feasible_N(lambda_obs)``
Returns
-------
mono_psf_batch: Tensor [batch x output_dim x output_dim]
Batch of monochromatic PSFs at requested positions and
wavelength.
"""
# Initialise the monochromatic PSF batch calculator
tf_batch_mono_psf = TF_batch_mono_PSF(
obscurations=self.obscurations, output_Q=self.output_Q, output_dim=self.output_dim
)
# Set the lambda_obs and the phase_N parameters
tf_batch_mono_psf.set_lambda_phaseN(phase_N, lambda_obs)
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_graph_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the monochromatic PSFs
mono_psf_batch = tf_batch_mono_psf(opd_maps)
return mono_psf_batch
def predict_opd(self, input_positions):
""" Predict the OPD at some positions.
Parameters
----------
input_positions: Tensor(batch_dim x 2)
Positions to predict the OPD.
Returns
-------
opd_maps : Tensor [batch x opd_dim x opd_dim]
OPD at requested positions.
"""
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_graph_OPD.predict(input_positions)
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
return opd_maps
def call(self, inputs, training=True):
r"""Define the PSF field forward model.
[1] From positions to Zernike coefficients
[2] From Zernike coefficients to OPD maps
[3] From OPD maps and SED info to polychromatic PSFs
OPD: Optical Path Differences
"""
# Unpack inputs
input_positions = inputs[0]
packed_SEDs = inputs[1]
# Forward model
# For the training
if training:
# Calculate parametric part
zernike_coeffs = self.tf_poly_Z_field(input_positions)
param_opd_maps = self.tf_zernike_OPD(zernike_coeffs)
# Calculate the non parametric part
nonparam_opd_maps = self.tf_NP_graph_OPD(input_positions)
# Add l2 loss on the parmetric OPD
self.add_loss(self.l2_param * tf.math.reduce_sum(tf.math.square(nonparam_opd_maps)))
# Add the estimations
opd_maps = tf.math.add(param_opd_maps, nonparam_opd_maps)
# Compute the polychromatic PSFs
poly_psfs = self.tf_batch_poly_PSF([opd_maps, packed_SEDs])
# For the inference
# This is absolutely needed to compute the metrics on the
# validation data.
else:
# Compute predictions
poly_psfs = self.predict_step(inputs, evaluate_step=True)
return poly_psfs
| 34.459259 | 96 | 0.653611 | 3,166 | 23,260 | 4.514529 | 0.096336 | 0.027426 | 0.010285 | 0.017631 | 0.883929 | 0.874484 | 0.871266 | 0.861541 | 0.861541 | 0.850066 | 0 | 0.007415 | 0.275279 | 23,260 | 674 | 97 | 34.510386 | 0.840482 | 0.387618 | 0 | 0.79322 | 0 | 0 | 0.015516 | 0 | 0 | 0 | 0 | 0.001484 | 0 | 1 | 0.088136 | false | 0 | 0.027119 | 0 | 0.162712 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
fd95620e07a234be305c7b8b7e53cb380fbbf702 | 7,294 | py | Python | src/models/monuseg/metrics.py | voreille/2d_bispectrum_cnn | ba8f26f6a557602bc3343c4562c83a3de914c67e | [
"MIT"
] | null | null | null | src/models/monuseg/metrics.py | voreille/2d_bispectrum_cnn | ba8f26f6a557602bc3343c4562c83a3de914c67e | [
"MIT"
] | null | null | null | src/models/monuseg/metrics.py | voreille/2d_bispectrum_cnn | ba8f26f6a557602bc3343c4562c83a3de914c67e | [
"MIT"
] | null | null | null | import numpy as np
def aggregated_jaccard_index(y_true, y_pred):
y_true_indices = np.unique(y_true)
y_pred_indices = np.unique(y_pred)
y_true_indices = np.delete(y_true_indices, y_true_indices == 0)
y_pred_indices = np.delete(y_pred_indices, y_pred_indices == 0)
overall_correct_count = 0
union_pixel_count = 0
matched_pred_count = {i: 0 for i in y_pred_indices}
for i in y_true_indices:
nuclei_mask = y_true == i
y_pred_match = nuclei_mask * y_pred
if np.sum(y_pred_match) == 0:
union_pixel_count += np.sum(nuclei_mask)
continue
else:
pred_nuclei_indices = np.unique(y_pred_match)
pred_nuclei_indices = np.delete(pred_nuclei_indices,
pred_nuclei_indices == 0)
jaccard_index = 0
for j in pred_nuclei_indices:
matched = y_pred == j
intersection_tmp = np.sum(matched & nuclei_mask)
union_tmp = np.sum(matched | nuclei_mask)
ji_tmp = intersection_tmp / union_tmp
if ji_tmp > jaccard_index:
jaccard_index = ji_tmp
best_match = j
correct_count = intersection_tmp
union = union_tmp
overall_correct_count += correct_count
union_pixel_count += union
matched_pred_count[best_match] += 1
unmatched_pred = [
k for k in matched_pred_count.keys() if matched_pred_count[k] == 0
]
for k in unmatched_pred:
union_pixel_count += np.sum(y_pred == k)
return overall_correct_count / union_pixel_count
def confusion_indices(y_true, y_pred):
y_true_indices = np.unique(y_true)
y_pred_indices = np.unique(y_pred)
y_true_indices = np.delete(y_true_indices, y_true_indices == 0)
y_pred_indices = np.delete(y_pred_indices, y_pred_indices == 0)
matched_pred_indices = list()
unmatched_true_indices = list()
for i in y_true_indices:
nuclei_mask = y_true == i
y_pred_match = nuclei_mask * y_pred
nuclei_area = np.sum(nuclei_mask)
if np.sum(y_pred_match) == 0:
unmatched_true_indices.append(i)
continue
else:
pred_nuclei_indices = np.unique(y_pred_match)
pred_nuclei_indices = np.delete(pred_nuclei_indices,
pred_nuclei_indices == 0)
matched = False
for j in pred_nuclei_indices:
if j not in matched_pred_indices:
if np.sum(y_pred_match == j) > 0.5 * nuclei_area:
matched_pred_indices.append(j)
matched = True
break
if not matched:
unmatched_true_indices.append(i)
unmatched_pred_indices = list(
set(matched_pred_indices) - set(y_pred_indices))
return matched_pred_indices, unmatched_pred_indices, unmatched_true_indices
def confusion_terms(y_true, y_pred):
y_true_indices = np.unique(y_true)
y_pred_indices = np.unique(y_pred)
y_true_indices = np.delete(y_true_indices, y_true_indices == 0)
y_pred_indices = np.delete(y_pred_indices, y_pred_indices == 0)
n_pred_nuclei = len(y_pred_indices)
n_true_nuclei = len(y_true_indices)
true_positive = 0
matched_pred_indices = list()
for i in y_true_indices:
nuclei_mask = y_true == i
y_pred_match = nuclei_mask * y_pred
nuclei_area = np.sum(nuclei_mask)
if np.sum(y_pred_match) == 0:
continue
else:
pred_nuclei_indices = np.unique(y_pred_match)
pred_nuclei_indices = np.delete(pred_nuclei_indices,
pred_nuclei_indices == 0)
for j in pred_nuclei_indices:
if (np.sum(y_pred_match == j) > 0.5 * nuclei_area
and j not in matched_pred_indices):
true_positive += 1
matched_pred_indices.append(j)
break
false_positive = n_pred_nuclei - true_positive
false_negative = n_true_nuclei - true_positive
return false_positive, false_negative, true_positive
def f_score(y_true, y_pred):
y_true_indices = np.unique(y_true)
y_pred_indices = np.unique(y_pred)
y_true_indices = np.delete(y_true_indices, y_true_indices == 0)
y_pred_indices = np.delete(y_pred_indices, y_pred_indices == 0)
n_pred_nuclei = len(y_pred_indices)
n_true_nuclei = len(y_true_indices)
true_positive = 0
matched_pred_indices = list()
for i in y_true_indices:
nuclei_mask = y_true == i
y_pred_match = nuclei_mask * y_pred
nuclei_area = np.sum(nuclei_mask)
if np.sum(y_pred_match) == 0:
continue
else:
pred_nuclei_indices = np.unique(y_pred_match)
pred_nuclei_indices = np.delete(pred_nuclei_indices,
pred_nuclei_indices == 0)
for j in pred_nuclei_indices:
if (np.sum(y_pred_match == j) > 0.5 * nuclei_area
and j not in matched_pred_indices):
true_positive += 1
matched_pred_indices.append(j)
continue
false_positive = n_pred_nuclei - true_positive
false_negative = n_true_nuclei - true_positive
fscore = true_positive / (true_positive + 0.5 *
(false_positive + false_negative))
return fscore
def monuseg_metrics(y_true, y_pred):
y_true_indices = np.unique(y_true)
y_pred_indices = np.unique(y_pred)
y_true_indices = np.delete(y_true_indices, y_true_indices == 0)
y_pred_indices = np.delete(y_pred_indices, y_pred_indices == 0)
overall_correct_count = 0
union_pixel_count = 0
matched_pred_count = {i: 0 for i in y_pred_indices}
for i in y_true_indices:
nuclei_mask = y_true == i
y_pred_match = nuclei_mask * y_pred
if np.sum(y_pred_match) == 0:
union_pixel_count += np.sum(nuclei_mask)
continue
else:
pred_nuclei_indices = np.unique(y_pred_match)
pred_nuclei_indices = np.delete(pred_nuclei_indices,
pred_nuclei_indices == 0)
jaccard_index = 0
for j in pred_nuclei_indices:
matched = y_pred == j
intersection_tmp = np.sum(matched & nuclei_mask)
union_tmp = np.sum(matched | nuclei_mask)
ji_tmp = intersection_tmp / union_tmp
if ji_tmp > jaccard_index:
jaccard_index = ji_tmp
best_match = j
correct_count = intersection_tmp
union = union_tmp
overall_correct_count += correct_count
union_pixel_count += union
matched_pred_count[best_match] += 1
unmatched_pred = [
k for k in matched_pred_count.keys() if matched_pred_count[k] == 0
]
for k in unmatched_pred:
union_pixel_count += np.sum(y_pred == k)
return overall_correct_count / union_pixel_count
| 36.288557 | 79 | 0.604881 | 974 | 7,294 | 4.110883 | 0.062628 | 0.077423 | 0.080919 | 0.05994 | 0.898601 | 0.873377 | 0.869131 | 0.862887 | 0.862887 | 0.862887 | 0 | 0.008963 | 0.326981 | 7,294 | 200 | 80 | 36.47 | 0.806682 | 0 | 0 | 0.872727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.030303 | false | 0 | 0.006061 | 0 | 0.066667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
fdb8907ebcffbf17678646e78649cedf922f9a4c | 20,114 | py | Python | negar/negar.py | sys113/negar | ae76bcac876376a97a5c58042716b1e65596666c | [
"MIT"
] | 23 | 2019-11-30T14:27:31.000Z | 2022-03-17T13:05:02.000Z | negar/negar.py | sys113/negar | ae76bcac876376a97a5c58042716b1e65596666c | [
"MIT"
] | 1 | 2020-05-05T10:23:23.000Z | 2020-11-27T18:09:18.000Z | negar/negar.py | sys113/negar | ae76bcac876376a97a5c58042716b1e65596666c | [
"MIT"
] | 5 | 2019-12-01T07:10:42.000Z | 2020-02-11T21:31:38.000Z | # Copyright SYS113 2019. MIT license , see README.md file.
# import libraries
from re import search
from traceback import format_exc
from tzlocal import get_localzone
from datetime import datetime
from platform import system, release, machine
from getpass import getuser
from os.path import isfile
from inspect import getframeinfo, stack
from negar.countriesWithTheirCapital import countries
# helper function for country capital
def get_country(_city):
data = countries
if _city in data:
return data[_city]
else:
return 'unknown'
# helper function for negar module errors printing
def err_temp_func(file_, line, problem):
error_template = 'negar module - error | python file : {} | line : {} | problem : {}'
return error_template.format(file_, line, problem)
# helper function for justify text center with fixed length
def justify_text(text_, length):
return '{}{}{}'.format(int((length - len(str(text_))) / 2) * ' ', text_, length * ' ')[:length]
# helper function for create header row
def header_row(header_specs):
sep = '—' * (len(header_specs) - 4)
out = '\n .{1}.\n {0}\n |{1}|\n'.format(header_specs, sep)
return out
# helper function for create each log row
def log_row(row_num, log_date, log_time, row_text, row_log_size, row_file_name, row_type, row_line_num):
row_num = justify_text(row_num, 7)
row_type = justify_text(row_type, 8)
out = ' |{num}| {date} | {time} | {text}{pad}|{file}|{type}|{line}|\n'.format(
num=row_num, date=log_date, time=log_time, text=row_text, file=row_file_name, type=row_type,
line=row_line_num, pad=' ' * (row_log_size - (len(row_text) + 1)))
out += ' |{}|\n'.format('—' * (len(out) - 5))
return out
# create text log function ...
def text(text_log=None, save=None, size=None , line=None , date=None , time=None , title=None):
# find (filename or line) python file ...
x = stack()[1]
x = x[0]
get_log_file_python_file_name_or_line = getframeinfo(x)
# ----------------------------------------------------------------------------------------------------------------
'''
'find line in python file' variable is 'line_python_file'
'find python file name' variable is 'python_file'
'save log in a file' variable is 'log_file'
'log text' variable is 'log_text'
'set log file size' variable is 'log_file_size'
'''
# ----------------------------------------------------------------------------------------------------------------
# set Flase and True value for show line python file in log file ...
if (line is None) or (line is False):
line_python_file = '-'
elif line is True:
line_python_file = str(get_log_file_python_file_name_or_line.lineno)
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"show" value is not boolean ...'))
return
# set value for find python file name ...
python_file_name = str(get_log_file_python_file_name_or_line.filename.split('/')[-1])
if python_file_name in ['<stdin>', '<input>']:
python_file = 'interpreter'
elif len(python_file_name) < 18:
python_file = python_file_name
else:
print(err_temp_func(python_file_name, line_python_file, 'maximum size of python file name is 15 character ...'))
return
# set value for save log in a file ...
if isinstance(save, str):
log_file = save
elif save is None:
log_file = 'log.txt'
else:
print(err_temp_func(python_file_name, line_python_file, '"save" type is not str ...'))
return
# set value for log text ...
if text_log is None:
print(err_temp_func(python_file_name, line_python_file, '"text" value is empty ...'))
return
elif not isinstance(text_log, str):
print(err_temp_func(python_file_name, line_python_file, '"text" type is not str ...'))
return
elif text_log == '':
print(err_temp_func(python_file_name, line_python_file, '"text" value is empty ...'))
return
else:
log_text = text_log
# set value for log file size ...
if size is None:
log_size = 3
elif not isinstance(size, int):
print(err_temp_func(python_file_name, line_python_file, '"size" type is not str ...'))
return
elif size > 5:
print(err_temp_func(python_file_name, line_python_file, '"size" value range is not (1 ... 5) ...'))
return
elif size == 0:
print(err_temp_func(python_file_name, line_python_file, '"size" value is not in range (1 ... 5) ...'))
return
else:
log_size = size
# ----------------------------------------------------------------------------------------------------------------
'''
'write python file name in log file' variable is 'justified_python_file'
'write line of python file in log file' variable is 'justified_line_python_file'
'write log text in log file' variable is 'log_file_text'
'log file name' variable is 'log_file_name'
'log file size' variable is 'log_file_size'
'''
# ----------------------------------------------------------------------------------------------------------------
# check character size ...
if (log_size == 1) and (len(log_text) > 69):
print(err_temp_func(python_file_name, line_python_file, '"size = 1" maximum 69 character support ...'))
return
elif (log_size == 2) and (len(log_text) > 93):
print(err_temp_func(python_file_name, line_python_file, '"size = 2" maximum 93 character support ...'))
return
elif (log_size == 3) and (len(log_text) > 131):
print(err_temp_func(python_file_name, line_python_file, '"size = 3" maximum 131 character support ...'))
return
elif (log_size == 4) and (len(log_text) > 199):
print(err_temp_func(python_file_name, line_python_file, '"size = 4" maximum 199 character support ...'))
return
elif (log_size == 5) and (len(log_text) > 397):
print(err_temp_func(python_file_name, line_python_file, '"size = 5" maximum 397 character support ...'))
return
# set value for write python file name in log file ...
justified_python_file = justify_text(python_file, 18)
# set value for write line of python file in log file ...
if len(line_python_file) <= 6:
justified_line_python_file = justify_text(line_python_file, 6)
else:
print(err_temp_func(python_file_name, line_python_file, 'maximum python line number support is 999999 ...'))
return
# set value for log file name ...
log_file_name = log_file
# set value for log file size ...
log_file_size = round(((6 - 0.3) / 100) * ((5 - [0.1, 2.9, 3.9, 4.4, 4.7][log_size - 1]) * 20), 1)
# ----------------------------------------------------------------------------------------------------------------
# get continent ...
continent = str(get_localzone()).lower().split('/')[0]
# get city ...
city = str(get_localzone()).lower().split('/')[1]
# get country ...
country = str(get_country(city))
# get username ...
username = str(getuser())
# get os ...
os = str(system().lower())
# get version ...
version = str(release().lower())
# get architecture
architecture = str(machine().lower())
# log type
log_type = 'text'
# ----------------------------------------------------------------------------------------------------------------
# set Flase and True value for time in log file ...
if (time is None) or (time is True):
time = str(datetime.now()).split(' ')[1].split('.')[0]
elif time is False:
time = ' - '
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"time" value is not boolean ...'))
return
# ----------------------------------------------------------------------------------------------------------------
# set Flase and True value for show date in log file ...
if (date is None) or (date is True):
date = str(datetime.now()).split(' ')[0]
elif date is False:
date = ' - '
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"date" value is not boolean ...'))
return
# ----------------------------------------------------------------------------------------------------------------
# show city , country , continent , username , os , version , architecture in log file ...
sp_center = '%s < %s < %s | %s | %s > %s > %s' % (
city, country, continent, username, os, version, architecture)
spec_center = justify_text(sp_center, 2 * int(len(sp_center) / log_file_size) + len(sp_center))
T = (len(spec_center)-len(sp_center))/2
if title is not None:
if len(title) > len(spec_center):
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), 'maximum \'title\' size is '+str(len(spec_center))+' ...'))
return
if (title is None) or (title is False):
specifications = ' | num | date | time |' + spec_center + '| file | type | line | '
else:
specifications = ' | num | date | time |' + title.center(len(spec_center)) + '| file | type | line | '
# if is not log file ...
if not isfile(log_file_name):
# create log file ...
with open(log_file_name, 'w') as log_file:
# write ' ___ ' to log file ...
log_file.write(header_row(specifications))
# write 'error & text' to log file ...
log_file.write(
log_row(1, date, time, text_log, len(spec_center), justified_python_file, log_type,
justified_line_python_file))
# if is log file ...
elif isfile(log_file_name):
with open(log_file_name, 'r') as f:
if f.read().splitlines()[-1] != ' |' + '—' * (len(specifications) - 4) + '|':
print(err_temp_func(python_file_name, line_python_file,
"previously defined log file size , can't be resized ..."))
return
# find line number ...
with open(log_file_name, 'r') as f:
line_number = f.read().splitlines()[-2].split('|')[1]
line_number = line_number.replace(' ', '')
line_number = int(line_number) + 1
# ckeck log file line number ...
if len(str(line_number)) > 7:
print(err_temp_func(python_file_name, line_python_file,
"'size = 5' maximum line number support is 9999999 ..."))
return
# set value for log file line number ...
if len(str(line_number)) <= 7:
log_file_number = justify_text(line_number, 7)
else:
print(err_temp_func(python_file_name, line_python_file,
'maximum number to numbering lines support is 9999999 ...'))
return
# open log file ...
with open(log_file_name, 'a') as log_file:
# add new 'error & text' to log file ...
log_file.write(log_row(log_file_number, date, time, text_log, len(spec_center), justified_python_file,
log_type, justified_line_python_file))
# create error log function ...
def error(save=None, size=None, line=None , time=None , date=None , title=None):
# find (filename or line) python file ...
x = stack()[1]
x = x[0]
get_log_file_python_file_name_or_line = getframeinfo(x)
# write exception to error_log variable ...
error_log = format_exc()
if len(error_log.splitlines()) < 2:
return
# error log ...
error_text = str(error_log.splitlines()[-1])
a = [*filter(lambda x: x.find('File') > -1, error_log.splitlines())]
# file name ...
python_file_name = search('File "(.*)", line (.*), in (.*)', a[-1]).groups()
for i in a[:-1][::-1]:
x = search('File "(.*)", line (.*), in (.*)', i).groups()
if x and python_file_name[2] == x[2]:
python_file_name = x
else:
break
# set Flase and True value for show line python file in log file ...
if (line is None) or (line is True):
line_python_file = str(get_log_file_python_file_name_or_line.lineno)
elif line is False:
line_python_file = '-'
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"line" value is not boolean ...'))
return
# name python file ...
python_file_name = str(python_file_name[0]).split('/')[-1]
# ----------------------------------------------------------------------------------------------------------------
'''
'find line in python file' variable is 'line_python_file'
'find python file name' variable is 'python_file'
'save log in a file' variable is 'log_file'
'log text' variable is 'log_text'
'set log file size' variable is 'log_file_size'
'''
# ----------------------------------------------------------------------------------------------------------------
if python_file_name in ['<stdin>', '<input>']:
python_file = 'interpreter'
elif len(python_file_name) < 18:
python_file = python_file_name
else:
print(err_temp_func(python_file_name, line_python_file, 'maximum size of python file name is 15 character ...'))
return
# set value for save log in a file ...
if isinstance(save, str):
log_file = save
elif save is None:
log_file = 'log.txt'
else:
print(err_temp_func(python_file_name, line_python_file, '"save" type is not str ...'))
return
# set value for log file size ...
if size is None:
log_size = 3
elif not isinstance(size, int):
print(err_temp_func(python_file_name, line_python_file, '"size" type is not str ...'))
return
elif size > 5:
print(err_temp_func(python_file_name, line_python_file, '"size" value range is not (1 ... 5) ...'))
return
elif size == 0:
print(err_temp_func(python_file_name, line_python_file, '"size" value is not in range (1 ... 5) ...'))
return
else:
log_size = size
# ----------------------------------------------------------------------------------------------------------------
'''
'write python file name in log file' variable is 'justified_python_file'
'write line of python file in log file' variable is 'justified_line_python_file'
'write log text in log file' variable is 'log_file_text'
'log file name' variable is 'log_file_name'
'log file size' variable is 'log_file_size'
'''
# ----------------------------------------------------------------------------------------------------------------
# check character size ...
if (log_size == 1) and (len(error_text) > 69):
print(err_temp_func(python_file_name, line_python_file, '"size = 1" maximum 69 character support ...'))
return
elif (log_size == 2) and (len(error_text) > 93):
print(err_temp_func(python_file_name, line_python_file, '"size = 2" maximum 93 character support ...'))
return
elif (log_size == 3) and (len(error_text) > 131):
print(err_temp_func(python_file_name, line_python_file, '"size = 3" maximum 131 character support ...'))
return
elif (log_size == 4) and (len(error_text) > 199):
print(err_temp_func(python_file_name, line_python_file, '"size = 4" maximum 199 character support ...'))
return
elif (log_size == 5) and (len(error_text) > 397):
print(err_temp_func(python_file_name, line_python_file, '"size = 5" maximum 397 character support ...'))
return
# set value for write python file name in log file ...
justified_python_file = justify_text(python_file, 18)
# set value for write line of python file in log file ...
if len(line_python_file) <= 6:
justified_line_python_file = justify_text(line_python_file, 6)
else:
print(err_temp_func(python_file_name, line_python_file, 'maximum python line number support is 999999 ...'))
return
# set value for log file name ...
log_file_name = log_file
# set value for log file size ...
log_file_size = round(((6 - 0.3) / 100) * ((5 - [0.1, 2.9, 3.9, 4.4, 4.7][log_size - 1]) * 20), 1)
# ----------------------------------------------------------------------------------------------------------------
# get continent ...
continent = str(get_localzone()).lower().split('/')[0]
# get city ...
city = str(get_localzone()).lower().split('/')[1]
# get country ...
country = str(get_country(city))
# get username ...
username = str(getuser())
# get os ...
os = str(system().lower())
# get version ...
version = str(release().lower())
# get architecture
architecture = str(machine().lower())
# log type
log_type = ' error'
# ----------------------------------------------------------------------------------------------------------------
# set Flase and True value for time in log file ...
if (time is None) or (time is True):
time = str(datetime.now()).split(' ')[1].split('.')[0]
elif time is False:
time = ' - '
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"time" value is not boolean ...'))
return
# ----------------------------------------------------------------------------------------------------------------
# set Flase and True value for show date in log file ...
if (date is None) or (date is True):
date = str(datetime.now()).split(' ')[0]
elif date is False:
date = ' - '
else:
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), '"date" value is not boolean ...'))
return
# ----------------------------------------------------------------------------------------------------------------
'''
# show city , country , continent , username , os , version , architecture in log file ...
spec_center = '%s < %s < %s | %s | %s > %s > %s' % (
city, country, continent, username, os, version, architecture)
spec_center = justify_text(spec_center, 2 * int(len(spec_center) / log_file_size) + len(spec_center))
specifications = ' | num | date | time |' + spec_center + '| file | type | line | '
'''
# show city , country , continent , username , os , version , architecture in log file ...
sp_center = '%s < %s < %s | %s | %s > %s > %s' % (
city, country, continent, username, os, version, architecture)
spec_center = justify_text(sp_center, 2 * int(len(sp_center) / log_file_size) + len(sp_center))
T = (len(spec_center)-len(sp_center))/2
if title is not None:
if len(title) > len(spec_center):
print(err_temp_func(str(get_log_file_python_file_name_or_line.filename.split('/')[-1]), str(get_log_file_python_file_name_or_line.lineno), 'maximum \'title\' size is '+str(len(spec_center))+' ...'))
return
if (title is None) or (title is False):
specifications = ' | num | date | time |' + spec_center + '| file | type | line | '
else:
specifications = ' | num | date | time |' + title.center(len(spec_center)) + '| file | type | line | '
# if is not log file ...
if not isfile(log_file_name):
# create log file ...
with open(log_file_name, 'w') as log_file:
# write ' ___ ' to log file ...
log_file.write(header_row(specifications))
# write 'error & text' to log file ...
log_file.write(
log_row(1, date, time, error_text, len(spec_center), justified_python_file, log_type,
justified_line_python_file))
# if is log file ...
elif isfile(log_file_name):
with open(log_file_name, 'r') as f:
if f.read().splitlines()[-1] != ' |' + '—' * (len(specifications) - 4) + '|':
print(err_temp_func(python_file_name, line_python_file,
"previously defined log file size , can't be resized ..."))
return
# find line number ...
with open(log_file_name, 'r') as f:
line_number = f.read().splitlines()[-2].split('|')[1]
line_number = line_number.replace(' ', '')
line_number = int(line_number) + 1
# ckeck log file line number ...
if len(str(line_number)) > 7:
print(err_temp_func(python_file_name, line_python_file,
"'size = 5' maximum line number support is 9999999 ..."))
return
# set value for log file line number ...
if len(str(line_number)) <= 7:
log_file_number = justify_text(line_number, 7)
else:
print(err_temp_func(python_file_name, line_python_file,
'maximum number to numbering lines support is 9999999 ...'))
return
# open log file ...
with open(log_file_name, 'a') as log_file:
# add new 'error & text' to log file ...
log_file.write(log_row(log_file_number, date, time, error_text, len(spec_center), justified_python_file,
log_type, justified_line_python_file))
| 38.905222 | 201 | 0.613752 | 2,831 | 20,114 | 4.11586 | 0.064288 | 0.128733 | 0.08771 | 0.053553 | 0.851528 | 0.842001 | 0.829986 | 0.829986 | 0.829986 | 0.825953 | 0 | 0.015413 | 0.167794 | 20,114 | 516 | 202 | 38.98062 | 0.680447 | 0.210997 | 0 | 0.770492 | 0 | 0.003279 | 0.161793 | 0.002478 | 0.006557 | 0 | 0 | 0 | 0 | 1 | 0.022951 | false | 0.003279 | 0.029508 | 0.003279 | 0.203279 | 0.127869 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
fdd91f4cedba5c93ce5db46d60bf415c327dd456 | 11,477 | py | Python | savecode/threeyears/idownclient/scan/plugin/logicalbanner/temporary.py | Octoberr/swm0920 | 8f05a6b91fc205960edd57f9076facec04f49a1a | [
"Apache-2.0"
] | 2 | 2019-05-19T11:54:26.000Z | 2019-05-19T12:03:49.000Z | savecode/threeyears/idownclient/scan/plugin/logicalbanner/temporary.py | Octoberr/swm0920 | 8f05a6b91fc205960edd57f9076facec04f49a1a | [
"Apache-2.0"
] | 1 | 2020-11-27T07:55:15.000Z | 2020-11-27T07:55:15.000Z | savecode/threeyears/idownclient/scan/plugin/logicalbanner/temporary.py | Octoberr/swm0920 | 8f05a6b91fc205960edd57f9076facec04f49a1a | [
"Apache-2.0"
] | 2 | 2021-09-06T18:06:12.000Z | 2021-12-31T07:44:43.000Z | """
huawei hg532 vuln
"""
from socket import timeout
import traceback
from urllib import parse
from requests.models import Response
from proxymanagement.proxymngr import ProxyItem, ProxyMngr
from idownclient.scan.plugin.component.webalyzer import WebAlyzer
from .logicalhttp import LogicalHttp
from ....clientdatafeedback.scoutdatafeedback import PortInfo, SiteInfo
class TempScan(LogicalHttp):
vuln = "Temp_KB"
def __init__(self):
LogicalHttp.__init__(self, TempScan.vuln)
def run_logic_grabber(self, host: str, portinfo: PortInfo, **kwargs):
try:
funclist = [
self.kb1, # KB demand 210119
self.kb2, # KB demand 210119
]
for f in funclist:
f(host, portinfo, **kwargs)
except Exception as ex:
self._logger.error(f"{TempScan.vuln} error: {ex.args}")
###################################
def kb1(self, host, portinfo: PortInfo, **kwargs):
try:
# kb20210121
url = f"http://{host}/Login.php"
outlog = kwargs.get("outlog")
log = f"Start special scan: {TempScan.vuln}"
outlog(log)
# self._logger.debug(log)
failnum = 0
resp: Response = None
html: str = None
got = False
redirect = False
redirectcnt = 0
while True:
log = f"Start {TempScan.vuln}: {url}"
try:
# p: ProxyItem = ProxyMngr.get_one_crosswall()
# proxydict = None
# if isinstance(p, ProxyItem):
# proxydict = p.proxy_dict
# log = log + f"proxy: {p.ip}:{p.port}"
# self._logger.debug(
# f"proxy ip: {p._ip}, port: {p._port}")
# self._logger.debug(log)
html = None
redirected_url = None
bs_html = bytes()
with self._ha.get_response(
url,
verify=False,
timeout=10,
allow_redirects=False,
stream=True,
headers="""
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36""",
) as resp:
if resp is None:
self._logger.debug(f"Access {url} failed, get nothing")
return
res_count = 0
for chunk in resp.iter_content(8196):
bs_html += chunk
res_count += len(chunk)
# 10M
if res_count > 10000000:
break
get_headers = resp.headers
html = self._ha._decode_data(get_headers, bs_html)
siteinfo: SiteInfo = SiteInfo(url)
respheard = ""
for k, v in get_headers.items():
respheard += f"{k}:{v}\n"
siteinfo.set_httpdata(None, None, respheard, html)
if portinfo.service == "unknown":
portinfo.service = "http"
portinfo.set_siteinfo(siteinfo)
# parse redirect
if (
resp.is_redirect
or resp.is_permanent_redirect
or 300 <= resp.status_code < 400
):
redirected_url = self._ha.get_redirect_target(resp)
host = parse.urlparse(resp.url)
redirected_url = parse.urljoin(
"{}://{}".format(host.scheme, host.netloc),
redirected_url,
)
elif resp.url and resp.url != url:
redirected_url = resp.url
# redirect
redirect = False
# <script>DD_belatedPNG.fix('*');</script>
if (
not html is None
and html.__contains__("<title>登录</title>")
and html.lower().__contains__(
"<script>dd_belatedpng.fix('*');</script>"
)
and html.lower().__contains__("h-ui.admin")
):
got = True
self._logger.debug(
f"Succeed get {TempScan.vuln}, url:{url}"
)
break
elif not redirected_url is None:
url = redirected_url
redirected_url = None
redirect = True
redirectcnt += 1
self._logger.info(f"Redirected: {url}")
continue
else:
failnum += 1
continue
except Exception as ex:
self._logger.debug(f"Request {url} error: {ex}")
failnum += 1
finally:
if not redirect or not got and failnum >= 1:
break
if redirectcnt > 5:
break
log = f"{TempScan.vuln} special scan complete"
outlog(log)
except Exception as ex:
self._logger.error(f"{TempScan.vuln} error: {ex.args}")
def kb2(self, host, portinfo: PortInfo, **kwargs):
try:
# kb20210121
url = f"http://{host}/admin/common/login.shtml"
outlog = kwargs.get("outlog")
log = f"Start special scan: {TempScan.vuln}"
outlog(log)
# self._logger.debug(log)
failnum = 0
resp: Response = None
html: str = None
got = False
redirect = False
redirectcnt = 0
while True:
log = f"Start {TempScan.vuln}: {url}"
try:
# p: ProxyItem = ProxyMngr.get_one_crosswall()
# proxydict = None
# if isinstance(p, ProxyItem):
# proxydict = p.proxy_dict
# log = log + f"proxy: {p.ip}:{p.port}"
# self._logger.debug(
# f"proxy ip: {p._ip}, port: {p._port}")
# self._logger.debug(log)
html = None
bs_html = bytes()
# parse redirect
redirected_url = None
with self._ha.get_response(
url,
verify=False,
timeout=10,
allow_redirects=False,
stream=True,
headers="""
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36""",
) as resp:
if resp is None:
self._logger.debug(f"Access {url} failed, get nothing")
return
res_count = 0
for chunk in resp.iter_content(8196):
bs_html += chunk
res_count += len(chunk)
# 10M
if res_count > 10000000:
break
get_heaers = resp.headers
html = self._ha._decode_data(get_heaers, bs_html)
# record
# html = bs_html.decode("utf-8")
siteinfo: SiteInfo = SiteInfo(url)
respheard = ""
for k, v in get_heaers.items():
respheard += f"{k}:{v}\n"
siteinfo.set_httpdata(None, None, respheard, html)
if portinfo.service == "unknown":
portinfo.service = "http"
portinfo.set_siteinfo(siteinfo)
if (
resp.is_redirect
or resp.is_permanent_redirect
or 300 <= resp.status_code < 400
):
redirected_url = self._ha.get_redirect_target(resp)
host = parse.urlparse(resp.url)
redirected_url = parse.urljoin(
"{}://{}".format(host.scheme, host.netloc),
redirected_url,
)
elif resp.url and resp.url != url:
redirected_url = resp.url
# redirect
redirect = False
if (
not html is None
and html.lower().__contains__("/admin/common/login.shtml")
and html.lower().__contains__("layui-form-item")
):
self._logger.debug(
f"Succeed get {TempScan.vuln}, url:{url}"
)
got = True
break
elif not redirected_url is None:
url = redirected_url
redirected_url = None
redirect = True
redirectcnt += 1
self._logger.info(f"Redirected: {url}")
continue
else:
failnum += 1
continue
except Exception as ex:
self._logger.debug(f"Request {url} error: {ex}")
failnum += 1
finally:
if not redirect or not got and failnum >= 1:
break
if redirectcnt > 5:
break
log = f"{TempScan.vuln} special scan complete"
outlog(log)
except Exception as ex:
self._logger.error(f"{TempScan.vuln} error: {ex.args}") | 40.270175 | 163 | 0.406029 | 976 | 11,477 | 4.644467 | 0.206967 | 0.051621 | 0.039709 | 0.028237 | 0.809177 | 0.797265 | 0.797265 | 0.787558 | 0.772557 | 0.772557 | 0 | 0.029787 | 0.508582 | 11,477 | 285 | 164 | 40.270175 | 0.773936 | 0.067178 | 0 | 0.812207 | 0 | 0.018779 | 0.13927 | 0.036393 | 0 | 0 | 0 | 0 | 0 | 1 | 0.018779 | false | 0 | 0.037559 | 0 | 0.075117 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
fdfbb2b4ff9a867e4da27c745fba51de7c4d1f11 | 190 | py | Python | app/gws/ext/search/provider/wms/__init__.py | ewie/gbd-websuite | 6f2814c7bb64d11cb5a0deec712df751718fb3e1 | [
"Apache-2.0"
] | null | null | null | app/gws/ext/search/provider/wms/__init__.py | ewie/gbd-websuite | 6f2814c7bb64d11cb5a0deec712df751718fb3e1 | [
"Apache-2.0"
] | null | null | null | app/gws/ext/search/provider/wms/__init__.py | ewie/gbd-websuite | 6f2814c7bb64d11cb5a0deec712df751718fb3e1 | [
"Apache-2.0"
] | null | null | null | import gws.ext.ows.provider.wms.search
class Config(gws.ext.ows.provider.wms.search.Config):
"""WMS search"""
pass
class Object(gws.ext.ows.provider.wms.search.Object):
pass
| 17.272727 | 53 | 0.710526 | 29 | 190 | 4.655172 | 0.37931 | 0.266667 | 0.2 | 0.377778 | 0.577778 | 0.577778 | 0 | 0 | 0 | 0 | 0 | 0 | 0.136842 | 190 | 10 | 54 | 19 | 0.823171 | 0.052632 | 0 | 0.4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.4 | 0.2 | 0 | 0.6 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 7 |
e31b725a121b79559b356270d0c9fc178cab017d | 97 | py | Python | celest/encounter/__init__.py | JaiWillems/celest | 5074b94feecc39127e5b0b0b1a683f636b725ca4 | [
"BSD-3-Clause"
] | 3 | 2021-12-31T08:17:19.000Z | 2022-03-27T00:36:31.000Z | celest/encounter/__init__.py | JaiWillems/celest | 5074b94feecc39127e5b0b0b1a683f636b725ca4 | [
"BSD-3-Clause"
] | 1 | 2022-02-05T04:05:41.000Z | 2022-02-05T04:05:41.000Z | celest/encounter/__init__.py | JaiWillems/celest | 5074b94feecc39127e5b0b0b1a683f636b725ca4 | [
"BSD-3-Clause"
] | null | null | null |
from celest.encounter.groundposition import GroundPosition
from celest.encounter import windows
| 24.25 | 58 | 0.876289 | 11 | 97 | 7.727273 | 0.545455 | 0.235294 | 0.447059 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.092784 | 97 | 3 | 59 | 32.333333 | 0.965909 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
e322a7f8367c8412618278c4d9a44cd7da09c591 | 22,836 | py | Python | temp/integwin.py | Pugavkomm/NS-analyst | 698af0e94f57b431fd77c17c49d4a23f11d21d3f | [
"MIT"
] | null | null | null | temp/integwin.py | Pugavkomm/NS-analyst | 698af0e94f57b431fd77c17c49d4a23f11d21d3f | [
"MIT"
] | null | null | null | temp/integwin.py | Pugavkomm/NS-analyst | 698af0e94f57b431fd77c17c49d4a23f11d21d3f | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'win_integrate.ui'
#
# Created by: PyQt5 UI code generator 5.12
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_integrWin(object):
def setupUi(self, integrWin):
integrWin.setObjectName("integrWin")
integrWin.setEnabled(True)
integrWin.resize(401, 111)
integrWin.setMinimumSize(QtCore.QSize(401, 111))
integrWin.setMaximumSize(QtCore.QSize(401, 111))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(246, 246, 245))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(119, 119, 118))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(159, 159, 157))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(246, 246, 245))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(246, 246, 245))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(119, 119, 118))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(159, 159, 157))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(246, 246, 245))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(246, 246, 245))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(119, 119, 118))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(159, 159, 157))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(238, 238, 236))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
integrWin.setPalette(palette)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icon_app.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
integrWin.setWindowIcon(icon)
integrWin.setStyleSheet("color: black;\n"
" font-family: ;\n"
"font: 11pt \"Noto Serif CJK JP\";\n"
"background-color: rgba(255, 255, 255, 85);")
integrWin.setLocale(QtCore.QLocale(QtCore.QLocale.Russian, QtCore.QLocale.Russia))
self.centralwidget = QtWidgets.QWidget(integrWin)
self.centralwidget.setObjectName("centralwidget")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(11, 9, 351, 102))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_2 = QtWidgets.QLabel(self.layoutWidget)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush)
brush = QtGui.QBrush(QtGui.QColor(170, 170, 170))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 85))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush)
self.label_2.setPalette(palette)
self.label_2.setObjectName("label_2")
self.horizontalLayout.addWidget(self.label_2)
self.doubleSpinBox = QtWidgets.QDoubleSpinBox(self.layoutWidget)
self.doubleSpinBox.setStyleSheet("float: flat;\n"
"margin-rigth: 3%;\n"
" margin-top: 5px;\n"
" \n"
" border: 1px rgba(114, 147, 182, 1);\n"
" padding: 5px 9px;\n"
" font-size: 1.2em;\n"
" background-color: rgba(114, 147, 182, 1);\n"
" text-shadow: #454545 0 0 2px;\n"
" border-bottom: 4px solid rgba(114, 147, 182, 1);\n"
" color: white;\n"
" font-family: ;\n"
"font: 11pt \"Noto Serif CJK JP\";\n"
"\n"
"")
self.doubleSpinBox.setLocale(QtCore.QLocale(QtCore.QLocale.C, QtCore.QLocale.AnyCountry))
self.doubleSpinBox.setDecimals(10)
self.doubleSpinBox.setObjectName("doubleSpinBox")
self.horizontalLayout.addWidget(self.doubleSpinBox)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label = QtWidgets.QLabel(self.layoutWidget)
self.label.setObjectName("label")
self.horizontalLayout_2.addWidget(self.label)
self.spinBox = QtWidgets.QSpinBox(self.layoutWidget)
self.spinBox.setStyleSheet("float: flat;\n"
"margin-rigth: 3%;\n"
" margin-top: 5px;\n"
" \n"
" border: 1px rgba(114, 147, 182, 1);\n"
" padding: 5px 9px;\n"
" font-size: 1.2em;\n"
" background-color: rgba(114, 147, 182, 1);\n"
" text-shadow: #454545 0 0 2px;\n"
" border-bottom: 4px solid rgba(114, 147, 182, 1);\n"
" color: white;\n"
" font-family: ;\n"
"font: 11pt \"Noto Serif CJK JP\";\n"
"\n"
"")
self.spinBox.setMaximum(99999999)
self.spinBox.setObjectName("spinBox")
self.horizontalLayout_2.addWidget(self.spinBox)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3.addLayout(self.verticalLayout)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.okstep = QtWidgets.QPushButton(self.layoutWidget)
self.okstep.setStyleSheet("QPushButton {\n"
"float: right;\n"
"margin-rigth: 3%;\n"
" margin-top: 5px;\n"
" background-shadow: 1px;\n"
" border: 1px rgba(114, 147, 182, 1);\n"
" padding: 5px 9px;\n"
" font-size: 1.2em;\n"
" background-color: rgba(114, 147, 182, 1);\n"
" text-shadow: #454545 0 0 3px;\n"
" border-bottom: 4px solid rgba(114, 147, 182, 1);\n"
" color: white;\n"
" font-family: ;\n"
"font: 11pt \"Noto Serif CJK JP\";\n"
"\n"
"\n"
" border: 1px solid rgba(114, 147, 182, 1);\n"
"\n"
"\n"
"}\n"
"QPushButton:hover\n"
"{\n"
" background-color:rgb(163, 175, 188);\n"
"}\n"
"")
self.okstep.setObjectName("okstep")
self.verticalLayout_2.addWidget(self.okstep)
self.okiter = QtWidgets.QPushButton(self.layoutWidget)
self.okiter.setStyleSheet("QPushButton {\n"
"float: right;\n"
"margin-rigth: 3%;\n"
" margin-top: 5px;\n"
" background-shadow: 1px;\n"
" border: 1px rgba(114, 147, 182, 1);\n"
" padding: 5px 9px;\n"
" font-size: 1.2em;\n"
" background-color: rgba(114, 147, 182, 1);\n"
" text-shadow: #454545 0 0 3px;\n"
" border-bottom: 4px solid rgba(114, 147, 182, 1);\n"
" color: white;\n"
" font-family: ;\n"
"font: 11pt \"Noto Serif CJK JP\";\n"
"\n"
"\n"
" border: 1px solid rgba(114, 147, 182, 1);\n"
"\n"
"\n"
"}\n"
"QPushButton:hover\n"
"{\n"
" background-color:rgb(163, 175, 188);\n"
"}\n"
"")
self.okiter.setObjectName("okiter")
self.verticalLayout_2.addWidget(self.okiter)
self.horizontalLayout_3.addLayout(self.verticalLayout_2)
integrWin.setCentralWidget(self.centralwidget)
self.retranslateUi(integrWin)
QtCore.QMetaObject.connectSlotsByName(integrWin)
def retranslateUi(self, integrWin):
_translate = QtCore.QCoreApplication.translate
integrWin.setWindowTitle(_translate("integrWin", "параметры интегрирования"))
self.label_2.setText(_translate("integrWin", "шаг"))
self.label.setText(_translate("integrWin", "количество итераций"))
self.okstep.setText(_translate("integrWin", "ok"))
self.okiter.setText(_translate("integrWin", "ok"))
| 52.376147 | 97 | 0.686372 | 2,753 | 22,836 | 5.681438 | 0.069379 | 0.151269 | 0.092066 | 0.120836 | 0.846877 | 0.822837 | 0.8167 | 0.8167 | 0.8167 | 0.8167 | 0 | 0.052786 | 0.180373 | 22,836 | 435 | 98 | 52.496552 | 0.782871 | 0.008101 | 0 | 0.828979 | 1 | 0 | 0.089436 | 0.002208 | 0 | 0 | 0 | 0 | 0 | 1 | 0.004751 | false | 0 | 0.002375 | 0 | 0.009501 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
e368a3b492b80ee5f1e502abece67b7d2aaf89bc | 36,338 | py | Python | tests/integration/test_transaction.py | andrew-chang-dewitt/hoops-api | 3530c5127c35742aad84df8d6a5286b9f5ad3608 | [
"MIT"
] | null | null | null | tests/integration/test_transaction.py | andrew-chang-dewitt/hoops-api | 3530c5127c35742aad84df8d6a5286b9f5ad3608 | [
"MIT"
] | 10 | 2021-11-02T23:31:56.000Z | 2021-12-07T03:41:12.000Z | tests/integration/test_transaction.py | andrew-chang-dewitt/hoops | 3530c5127c35742aad84df8d6a5286b9f5ad3608 | [
"MIT"
] | null | null | null | """Tests for /transaction routes."""
from datetime import datetime
from decimal import Decimal
from typing import Dict, List, Optional, Tuple
from uuid import UUID
from unittest import main, IsolatedAsyncioTestCase as TestCase
from db_wrapper.model import sql
# internal test dependencies
from tests.helpers.application import (
get_test_client,
get_token_header,
)
from tests.helpers.database import setup_user, setup_account, setup_envelope
from src.database import Client
BASE_URL = "/transaction"
class TestRoutePostRoot(TestCase):
"""Tests for `POST /transaction`."""
async def test_valid_request(self) -> None:
"""Testing a valid request's response."""
async with get_test_client() as clients:
client, database = clients
user_id = await setup_user(database)
account_id = await setup_account(database, user_id)
new_transaction = {
"amount": 1.23,
"description": "a description",
"payee": "payee",
"timestamp": "2019-12-10T08:12-05:00",
"account_id": str(account_id),
}
response = await client.post(
BASE_URL,
headers={
**get_token_header(user_id),
"accept": "application/json"},
json=new_transaction)
with self.subTest(
msg="Responds with a status code of 201."):
self.assertEqual(201, response.status_code)
with self.subTest(
msg="Responds with new Transaction's information."
):
body = response.json()
with self.subTest():
self.assertTrue(UUID(body["id"]))
with self.subTest():
self.assertEqual(body["amount"],
new_transaction["amount"])
with self.subTest():
self.assertEqual(body["description"],
new_transaction["description"])
with self.subTest():
self.assertEqual(body["payee"], new_transaction["payee"])
with self.subTest():
self.assertEqual(
datetime.fromisoformat(body["timestamp"]),
datetime.fromisoformat(new_transaction["timestamp"]))
with self.subTest():
self.assertEqual(body["account_id"],
new_transaction["account_id"])
with self.subTest(
msg="New Transaction is in the database."):
body = response.json()
new_id = UUID(body["id"])
await database.connect()
query_result = await database.execute_and_return(sql.SQL("""
SELECT * FROM transaction
WHERE id = {new_id};
""").format(new_id=sql.Literal(new_id)))
await database.disconnect()
result = query_result[0]
with self.subTest(
msg="Given transaction amount & database match."
):
self.assertEqual(result["amount"],
Decimal(str(new_transaction["amount"])))
with self.subTest(
msg="Given transaction payee & database match."
):
self.assertEqual(result["payee"], new_transaction["payee"])
with self.subTest(
msg="Given transaction description & database match."
):
self.assertEqual(
result["description"], new_transaction["description"])
with self.subTest(
msg="Given transaction timestamp & database match."
):
self.assertEqual(
result["timestamp"],
datetime.fromisoformat(new_transaction["timestamp"]))
with self.subTest(
msg="Given transaction account_id & database match."
):
self.assertEqual(
result["account_id"],
UUID(new_transaction["account_id"]))
async def test_cant_create_transactions_if_not_own_account(self) -> None:
"""Return 403 attempting to create transaction for other account."""
async with get_test_client() as clients:
client, database = clients
user_id = await setup_user(database, "user")
other_user = await setup_user(database, "other")
other_account = await setup_account(database, other_user)
new_transaction = {
"amount": 1.23,
"description": "a description",
"payee": "payee",
"timestamp": "2019-12-10T08:12-05:00",
"account_id": str(other_account),
}
response = await client.post(
BASE_URL,
headers={
**get_token_header(user_id),
"accept": "application/json"},
json=new_transaction)
self.assertEqual(403, response.status_code)
class TestRouteGetRoot(TestCase):
"""Tests for `GET /transaction`."""
async def test_valid_request(self) -> None:
"""Testing a valid request's response."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account_id = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account_id}),
(1.23, 'a payee', 'a description',
{timestamp2}, {account_id}),
(1.23, 'a payee', 'a description',
{timestamp3}, {account_id});
""").format(
account_id=sql.Literal(account_id),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
timestamp2=sql.Literal("2019-12-10T09:12-05:00"),
timestamp3=sql.Literal("2019-12-11T06:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
BASE_URL,
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(msg="All objects returned are Transactions."):
for item in response.json():
with self.subTest(msg="Amount is float"):
self.assertTrue(isinstance(item["amount"], float))
with self.subTest(msg="Payee is string"):
self.assertTrue(isinstance(item["payee"], str))
with self.subTest(msg="Description is string"):
self.assertTrue(isinstance(item["description"], str))
with self.subTest(msg="Timestamp is ISO Datetime"):
self.assertTrue(
datetime.fromisoformat(item["timestamp"]))
with self.subTest(msg="Account ID is UUID"):
self.assertTrue(UUID(item["account_id"]))
async def test_filter_by_account(self) -> None:
"""Requests can filter by account."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
account2 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(1.23, 'a payee', 'a description',
{timestamp1}, {account2});
""").format(
account1=sql.Literal(account1),
account2=sql.Literal(account2),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
f"{BASE_URL}?account_id={account1}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions belonging to requested Account."
):
for transaction in response.json():
self.assertEqual(transaction["account_id"], str(account1))
async def test_filter_payee(self) -> None:
"""Requests can filter by payee."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(1.23, 'someone else', 'a description',
{timestamp1}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
f"{BASE_URL}?payee=a%20payee",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions with matching payee."
):
for transaction in response.json():
self.assertEqual(transaction["payee"], str("a payee"))
async def test_filter_minimum_amount(self) -> None:
"""Requests can filter by minimum amount."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(0.23, 'a payee', 'a description',
{timestamp1}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
f"{BASE_URL}?minimum_amount=1.00",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions >= to given amount."):
for transaction in response.json():
self.assertGreaterEqual(transaction["amount"], 1)
async def test_filter_maximum_amount(self) -> None:
"""Requests can filter by maximum amount."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(0.23, 'a payee', 'a description',
{timestamp1}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
f"{BASE_URL}?maximum_amount=1.00",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions >= to given amount."):
for transaction in response.json():
self.assertLessEqual(transaction["amount"], 1)
async def test_filter_minumum_and_maximum_amount(self) -> None:
"""Requests can filter by both minimum and maximum amount."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(0.23, 'a payee', 'a description',
{timestamp1}, {account1}),
(-1.00, 'a payee', 'a description',
{timestamp1}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
response = await client.get(
f"{BASE_URL}?minimum_amount=0.00&maximum_amount=1.00",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions inclusive between amounts."
):
body = response.json()
for transaction in body:
with self.subTest(msg="Greater than/equal to minimum."):
self.assertGreaterEqual(transaction["amount"], 0)
with self.subTest(msg="Less than/equal to maximum."):
self.assertLessEqual(transaction["amount"], 1)
async def test_filter_minimum_timestamp(self) -> None:
"""Requests can filter by minimum timestamp."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1, 'a payee', 'a description',
{timestamp1}, {account1}),
(1, 'a payee', 'a description',
{timestamp2}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
timestamp2=sql.Literal("2020-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
after = "2020-01-01T00:00-00:00"
response = await client.get(
f"{BASE_URL}?after={after}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions >= to given timestamp."):
for transaction in response.json():
self.assertGreaterEqual(
datetime.fromisoformat(transaction["timestamp"]),
datetime.fromisoformat(after))
async def test_filter_maximum_timestamp(self) -> None:
"""Requests can filter by maximum timestamp."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1, 'a payee', 'a description',
{timestamp1}, {account1}),
(1, 'a payee', 'a description',
{timestamp2}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
timestamp2=sql.Literal("2020-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
before = "2020-01-01T00:00-00:00"
response = await client.get(
f"{BASE_URL}?before={before}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions >= to given timestamp."):
for transaction in response.json():
self.assertLessEqual(
datetime.fromisoformat(transaction["timestamp"]),
datetime.fromisoformat(before))
async def test_filter_minumum_and_maximum_timestamp(self) -> None:
"""Requests can filter by both minimum and maximum timestamp."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1, 'a payee', 'a description',
{timestamp1}, {account1}),
(1, 'a payee', 'a description',
{timestamp2}, {account1}),
(1, 'a payee', 'a description',
{timestamp3}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
timestamp2=sql.Literal("2020-12-10T08:12-05:00"),
timestamp3=sql.Literal("2021-12-10T08:12-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
after = "2020-01-01T00:00-00:00"
before = "2021-01-01T00:00-00:00"
response = await client.get(
f"{BASE_URL}?after={after}&before={before}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Only returns Transactions >= to given timestamp."):
for transaction in response.json():
self.assertLessEqual(
datetime.fromisoformat(transaction["timestamp"]),
datetime.fromisoformat(before))
with self.subTest(
msg="Only returns Transactions inclusive between timestamps."
):
body = response.json()
for transaction in body:
with self.subTest(msg="Greater than/equal to minimum."):
self.assertGreaterEqual(
datetime.fromisoformat(transaction["timestamp"]),
datetime.fromisoformat(after))
with self.subTest(msg="Less than/equal to maximum."):
self.assertLessEqual(
datetime.fromisoformat(transaction["timestamp"]),
datetime.fromisoformat(before))
async def test_pagination(self) -> None:
"""Requests can be paginated with number of results & page number."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account1 = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description,
timestamp, account_id)
VALUES
(1, 'a payee', 'a description',
{timestamp0}, {account1}),
(1, 'a payee', 'a description',
{timestamp1}, {account1}),
(1, 'a payee', 'a description',
{timestamp2}, {account1}),
(1, 'a payee', 'a description',
{timestamp3}, {account1}),
(1, 'a payee', 'a description',
{timestamp4}, {account1}),
(1, 'a payee', 'a description',
{timestamp5}, {account1}),
(1, 'a payee', 'a description',
{timestamp6}, {account1}),
(1, 'a payee', 'a description',
{timestamp7}, {account1}),
(1, 'a payee', 'a description',
{timestamp8}, {account1}),
(1, 'a payee', 'a description',
{timestamp9}, {account1});
""").format(
account1=sql.Literal(account1),
timestamp0=sql.Literal("2019-12-10T08:12-05:00"),
timestamp1=sql.Literal("2019-12-10T08:13-05:00"),
timestamp2=sql.Literal("2019-12-10T08:14-05:00"),
timestamp3=sql.Literal("2019-12-10T08:15-05:00"),
timestamp4=sql.Literal("2019-12-10T08:16-05:00"),
timestamp5=sql.Literal("2019-12-10T08:17-05:00"),
timestamp6=sql.Literal("2019-12-10T08:18-05:00"),
timestamp7=sql.Literal("2019-12-10T08:19-05:00"),
timestamp8=sql.Literal("2019-12-10T08:20-05:00"),
timestamp9=sql.Literal("2019-12-10T08:21-05:00"),
)
await database.connect()
await database.execute(query)
await database.disconnect()
limit = 5
page1 = 0
response1 = await client.get(
f"{BASE_URL}?limit={limit}&page={page1}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response1.status_code)
with self.subTest(
msg="Responds with number of Transactions specified by limit."
):
body1 = response1.json()
self.assertEqual(len(body1), limit)
with self.subTest(
msg=f"Can get next {limit} Transactions using page."):
page2 = 1
response2 = await client.get(
f"{BASE_URL}?limit={limit}&page={page2}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
body2 = response2.json()
first_page = [tran1["id"] for tran1 in body1]
for tran in body2:
with self.subTest():
self.assertNotIn(tran["id"], first_page)
class TestRoutePutId(TestCase):
"""Tests for `PUT /transaction/{id}`."""
async def test_valid_request(self) -> None:
"""Testing a valid request's response."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account_id = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp1}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(account_id),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
changes = {
"description": "something new",
}
response = await client.put(
f"{BASE_URL}/{tran_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"},
json=changes)
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Returns the updated transaction."):
body = response.json()
self.assertEqual(body["description"], changes["description"])
with self.subTest(msg="Updates the database."):
new_id = UUID(body["id"])
await database.connect()
query_result = await database.execute_and_return(sql.SQL("""
SELECT * FROM transaction
WHERE id = {new_id};
""").format(new_id=sql.Literal(new_id)))
await database.disconnect()
result = query_result[0]
self.assertEqual(result["description"], changes["description"])
async def test_cant_update_transactions_if_not_own_account(self) -> None:
"""Return 403 attempting to update transaction for other account."""
async with get_test_client() as clients:
client, database = clients
user_id = await setup_user(database, "user")
other_user = await setup_user(database, "other")
other_account = await setup_account(database, other_user)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp1}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(other_account),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
changes = {
"description": "new description",
}
response = await client.put(
f"{BASE_URL}/{tran_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"},
json=changes)
self.assertEqual(403, response.status_code)
class TestRouteDeleteId(TestCase):
"""Test DELETE /transaction/{id}."""
async def test_valid_request(self) -> None:
"""Testing a valid request's response."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account_id = await setup_account(database, user_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp1}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(account_id),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
response = await client.delete(
f"{BASE_URL}/{tran_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
async def test_cant_delete_transactions_if_not_own_account(self) -> None:
"""Return 403 attempting to delete transaction for other account."""
async with get_test_client() as clients:
client, database = clients
user_id = await setup_user(database, "user")
other_user = await setup_user(database, "other")
other_account = await setup_account(database, other_user)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp1}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(other_account),
timestamp1=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
response = await client.delete(
f"{BASE_URL}/{tran_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
self.assertEqual(403, response.status_code)
class TestRoutePutSpentFrom(TestCase):
"""Test PUT /transaction/{id}/spent_from/{spent_from_id}."""
async def test_valid_request(self) -> None:
"""Testing a valid request's response."""
async with get_test_client() as clients:
client, database = clients
# insert some test transactions
user_id = await setup_user(database)
account_id = await setup_account(database, user_id)
envelope_id = await setup_envelope(database, user_id, account_id)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(account_id),
timestamp=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
response = await client.put(
f"{BASE_URL}/{tran_id}/spent_from/{envelope_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
with self.subTest(
msg="Responds with a status code of 200."):
self.assertEqual(200, response.status_code)
with self.subTest(
msg="Responds with updated Transaction."
):
body = response.json()
self.assertEqual(UUID(body["spent_from"]), envelope_id)
async def test_cant_update_transactions_if_not_own_account(self) -> None:
"""Return 403 attempting to update transaction for other account."""
async with get_test_client() as clients:
client, database = clients
user_id = await setup_user(database, "user")
other_user = await setup_user(database, "other")
other_account = await setup_account(database, other_user)
envelope_id = await setup_envelope(database, user_id, other_account)
query = sql.SQL("""
INSERT INTO
transaction(amount, payee, description, timestamp, account_id)
VALUES
(1.23, 'a payee', 'a description', {timestamp}, {account_id})
RETURNING id;
""").format(
account_id=sql.Literal(other_account),
timestamp=sql.Literal("2019-12-10T08:12-05:00"),
)
await database.connect()
tran_id = (await database.execute_and_return(query))[0]["id"]
await database.disconnect()
response = await client.put(
f"{BASE_URL}/{tran_id}/spent_from/{envelope_id}",
headers={
**get_token_header(user_id),
"accept": "application/json"})
self.assertEqual(403, response.status_code)
if __name__ == "__main__":
main()
| 41.013544 | 82 | 0.512384 | 3,425 | 36,338 | 5.310073 | 0.06365 | 0.017815 | 0.042888 | 0.044537 | 0.877715 | 0.84324 | 0.80739 | 0.77154 | 0.748282 | 0.713752 | 0 | 0.042466 | 0.38307 | 36,338 | 885 | 83 | 41.059887 | 0.768802 | 0.017337 | 0 | 0.772414 | 0 | 0 | 0.308241 | 0.03558 | 0 | 0 | 0 | 0 | 0.068966 | 1 | 0 | false | 0 | 0.012414 | 0 | 0.01931 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
8b5019a56a0d4cbdf6162933b5fbbd1fe3508d51 | 55,429 | py | Python | forgetting/forget.py | zero-or-one/URP-Summer-Fall-2021 | 042fc18ba7db13754264e66de4330d6f7376b9c3 | [
"MIT"
] | null | null | null | forgetting/forget.py | zero-or-one/URP-Summer-Fall-2021 | 042fc18ba7db13754264e66de4330d6f7376b9c3 | [
"MIT"
] | null | null | null | forgetting/forget.py | zero-or-one/URP-Summer-Fall-2021 | 042fc18ba7db13754264e66de4330d6f7376b9c3 | [
"MIT"
] | null | null | null | import os
import sys
sys.path.append("../URP")
path = ".."
sys.path.append(path)
sys.path.append(path + "/learning")
sys.path.append(path + "/data")
sys.path.append(path + "/models")
from data_utils import *
#from learning.learn import *
#from data_utils import *
#from learn import *
from forget_utils import *
from copy import deepcopy
'''
Methods I need to implement
- Retraining
- Rapid retraining
- Fine-tuning
- Negative Gradiemnt
- Random Labels
- Hiding
- Fisher Forgetting
- Variational forgetting
'''
###########################
# Proposed methods #
###########################
class FD(object):
''' Feature Destruction '''
def __init__(self, mean=0, std=0.2, noise_type='gauss'):
self.name = "FD"
self.noise = AddNoise(mean=mean, std=std, noise_type=noise_type, s_vs_p=0.5, amount=0.5)
def forget_class(self, model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget whole class identity'''
set_seed()
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
noisy_forget = self.noise.encode_data(forget_train)
concat = combine_datasets(noisy_forget, retain_train)
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("FORGETTING PROCESS")
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=concat, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=self.name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def forget_subset(self, model, img_num, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget random subset of data, either from single class or not.
May be not working with this method'''
set_seed()
if class_id:
forget_train, retain_train = remove_class(train_loader, [class_id])
#forget_val, retain_val = remove_class(val_loader, [class_id])
subset, left = separate_random(forget_train, img_num)
forget = self.noise.encode_data(subset)
retain = combine_datasets(left, retain_train)
else:
subset, retain = separate_random(train_loader, img_num)
forget = self.noise.encode_data(subset)
train = combine_datasets(forget, retain)
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=subset, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
print('-' * 20)
print("FORGETTING PROCESS")
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=train, val_loader=forget,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=self.name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=subset, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
def forget_image(self, model, imglab, ds, ds_test, loss, optimizer, epochs, device, dataset, lossfn,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget single image'''
set_seed()
if imglab is None:
imglab = get_random_img(ds_test)
img, lab = imglab
img0 = torch.clone(img)
#img = img.to(device)
#lab = lab.to(device)
#model = model.to(device)
plab = predict(model, img, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
if plab != lab:
print('-' * 20)
print("PREDICTION IS WRONG, CHOOSE OTHER IMAGE")
return
#sys.exit()
print('-' * 20)
print("INITIAL D PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
noisy_img = self.noise.encodes(img)
data = ForgetDataset(noisy_img, [lab])
dataloader = DataLoader(data, batch_size=1)
print('-' * 20)
print("FORGETTING PROCESS")
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=dataloader, val_loader=ds,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=self.name)
print('-' * 20)
print("FINAL D PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
plab = predict(model, img0, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
class NIA(object):
''' Negative Information Allocation '''
def __init__(self, input_size=1024, num_layer=2, hidden_size=1024):
self.mean = 0
self.std = 0
self.encoder_model = Encoder(input_size=input_size, hidden_size=hidden_size, num_layer=num_layer)
def forget_class(self, model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="NIA_class_", squeeze=True):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("TRAINING ENCODER")
model = train_encoder(encoder_model=self.encoder_model, model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_forget=forget_train, val_forget=forget_val, train_retain=retain_train, val_retain=retain_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print("FORGETTING PROCESS")
#encoder_model = model_learning(encoder_model, True)
noisy_data = self.encoder_model.predict(forget_train, device, dataset, squeeze=squeeze)
#noisy_forget = ForgetDataset(noisy_data, target)
#noisy_forget = DataLoader(dataset, retain_train.batch_size)
concat = combine_datasets(noisy_data, retain_train, shuffle=True, device=device)
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=concat, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name, retain_graph=True)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
return model
def forget_subset(self, model, img_num, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget random subset of data, either from single class or not.
May be not working with this method'''
set_seed()
name="NIA_subset"
if class_id:
forget_train, retain_train = remove_class(train_loader, [class_id])
#forget_val, retain_val = remove_class(val_loader, [class_id])
subset, left = separate_random(forget_train, img_num)
forget = subset
retain = combine_datasets(left, retain_train)
else:
subset, retain = separate_random(train_loader, img_num)
forget = subset
#train = combine_datasets(forget, retain)
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=subset, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
print('-' * 20)
print("TRAINING ENCODER")
model = train_encoder(encoder_model=self.encoder_model, model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_forget=forget, val_forget=None, train_retain=retain, val_retain=None,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print("FORGETTING PROCESS")
#encoder_model = model_learning(encoder_model, True)
squeeze = False if 'mnist' in dataset else True
noisy_data = self.encoder_model.predict(forget, device, dataset, squeeze=squeeze)
#noisy_forget = ForgetDataset(noisy_data, target)
#noisy_forget = DataLoader(dataset, retain_train.batch_size)
concat = combine_datasets(noisy_data, retain, shuffle=True, device=device)
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=concat, val_loader=forget,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name, retain_graph=True)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
return model
def forget_image(self, model, imglab, ds, ds_test, loss, optimizer, epochs, device, dataset, lossfn,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget single image'''
set_seed()
if imglab is None:
imglab = get_random_img(ds_test)
img, lab = imglab
img0 = torch.clone(img)
#img = img.to(device)
#lab = lab.to(device)
#model = model.to(device)
plab = predict(model, img, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
if plab != lab:
print('-' * 20)
print("PREDICTION IS WRONG, CHOOSE OTHER IMAGE")
return
#sys.exit()
print('-' * 20)
print("INITIAL D PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
noisy_img = torch.clone(img)
data = ForgetDataset(noisy_img, [lab])
dataloader = DataLoader(data, batch_size=1)
print('-' * 20)
print("TRAINING ENCODER")
model = train_encoder(encoder_model=self.encoder_model, model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_forget=dataloader, val_forget=None, train_retain=ds, val_retain=None,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name='whatever')
print('-' * 20)
print("FORGETTING PROCESS")
#encoder_model = model_learning(encoder_model, True)
squeeze = False if 'mnist' in dataset else True
noisy_data = self.encoder_model.predict(dataloader, device, dataset, squeeze=squeeze)
#noisy_forget = ForgetDataset(noisy_data, target)
#noisy_forget = DataLoader(dataset, retain_train.batch_size)
concat = combine_datasets(noisy_data, ds, shuffle=True, device=device)
fine_tune_helper(model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=concat, val_loader=ds,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name="name", retain_graph=True)
print('-' * 20)
print("FINAL D PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
plab = predict(model, img0, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
class BL(object):
'''Backward learning'''
def __init__(self):
pass
def forget_class(self, model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader,
val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget whole class identity'''
set_seed()
name = 'backward_learning'
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("FORGETTING PROCESS")
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__) + '_training')
# logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index + '.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index + '_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs//2): # double epoch
# configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(forget_train):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
# this one is changed
ascent_loss = make_ascent(loss)
ascent_loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train', epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (forget_val is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=forget_val, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep, train=False,
logger=logger)
print(f'Epoch number: {2*ep} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
t = time.time()
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=retain_train, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep+1, train=True,
logger=logger, retain_graph=False)
if (val_loader is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=retain_val, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep+1, train=False,
logger=logger)
print(f'Epoch number: {2 * ep + 1} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}_{epochs + 1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss='ce', lossfn=lossfn, optimizer='adam', device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss='ce', lossfn=lossfn, optimizer='adam', device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def forget_subset(self, model, img_num, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, forget_val=None):
'''Forget random subset of data, either from single class or not.
May be not working with this method'''
set_seed()
name="NIA_subset"
if class_id:
forget_train, retain_train = remove_class(train_loader, [class_id])
#forget_val, retain_val = remove_class(val_loader, [class_id])
subset, left = separate_random(forget_train, img_num)
forget = subset
retain = combine_datasets(left, retain_train)
else:
subset, retain = separate_random(train_loader, img_num)
forget = subset
#train = combine_datasets(forget, retain)
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=subset, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
print('-' * 20)
print("FORGETTING PROCESS")
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__) + '_training')
# logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index + '.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index + '_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs//2): # double epoch
# configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(forget):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
# this one is changed
ascent_loss = make_ascent(loss)
ascent_loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train', epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (forget_val is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=forget_val, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep, train=False,
logger=logger)
print(f'Epoch number: {2*ep} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
t = time.time()
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=retain, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep+1, train=True,
logger=logger, retain_graph=False)
print(f'Epoch number: {2 * ep + 1} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}_{epochs + 1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss='ce', lossfn=lossfn, optimizer='adam', device=device, dataset=dataset,
test_loader=forget, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss='ce', lossfn=lossfn, optimizer='adam', device=device, dataset=dataset,
test_loader=retain, at_epoch=None)
def forget_image(self, model, imglab, ds, ds_test, loss, optimizer, epochs, device, dataset, lossfn,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9):
'''Forget single image'''
set_seed()
if imglab is None:
imglab = get_random_img(ds_test)
img, lab = imglab
img0 = torch.clone(img)
#img = img.to(device)
#lab = lab.to(device)
#model = model.to(device)
plab = predict(model, img, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
if plab != lab:
print('-' * 20)
print("PREDICTION IS WRONG, CHOOSE OTHER IMAGE")
return
#sys.exit()
print('-' * 20)
print("INITIAL D PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
noisy_img = torch.clone(img)#self.noise.encodes(img)
data = ForgetDataset(noisy_img, [lab])
forget = DataLoader(data, batch_size=1)
retain = ds
print('-' * 20)
print("FORGETTING PROCESS")
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__) + '_training')
# logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index + '.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index + '_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs//2): # double epoch
# configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(forget):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
# this one is changed
ascent_loss = make_ascent(loss)
ascent_loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train', epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
print(f'Epoch number: {2*ep} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
t = time.time()
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model,
lossfn=lossfn,
train_loader=retain, scheduler=scheduler, weight_decay=0.0, epoch_num=2*ep+1, train=True,
logger=logger, retain_graph=False)
print(f'Epoch number: {2 * ep + 1} :\n Epoch Time: {np.round(time.time() - t, 2)} sec')
name='img_forget'
filename = f"./checkpoints/{model.__class__.__name__}_{name}_{epochs + 1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print('-' * 20)
print("FINAL D PERFOMANCE")
test(model=model, loss='ce', lossfn=lossfn, optimizer='adam', device=device, dataset=dataset,
test_loader=ds, at_epoch=None)
plab = predict(model, img0, device)
print('-' * 20)
print("True label is: ", lab)
print("Predicted label is: ", plab)
#---------------------------------------------------
def train_encoder(encoder_model, model, loss, optimizer, epochs, device, dataset, lossfn, train_forget, val_forget, train_retain, val_retain,
scheduler=None, weight_decay=0.0, lr=0.001, momentum=0.9, curves=True, patience=7,
min_delta=-1, step_size=10, gamma=0.5, name=""):
encoder_model.to(device)
model.to(device)
model = model_learning(model, False)
optimizer = set_optimizer(optimizer, encoder_model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=step_size, gamma=gamma, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
early_stop_callback = EarlyStopping(patience=patience, min_delta=min_delta)
logger = Logger(index=str(model.__class__.__name__)+'_training')
#logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index+'.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index+'_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs):
t = time.time()
#configure_learning_rate(optimizer, epoch)
encoder_model, _ = encoder_epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model, encoder_model=encoder_model,
lossfn=lossfn, forget_loader=train_forget, retain_loader=train_retain, scheduler=scheduler,
weight_decay=0.0, epoch_num=ep, train=True, logger=logger)
if (val_forget is not None):
encoder_model, _ = encoder_epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset,
model=model, encoder_model=encoder_model,
lossfn=lossfn, forget_loader=val_forget, retain_loader=val_retain,
scheduler=scheduler,
weight_decay=0.0, epoch_num=ep, train=False, logger=logger)
loss_val = logger.get('test')[-1]["loss"]
#print(loss_val)
early_stop_callback(loss_val)
if scheduler:
scheduler.step()
print(f'Epoch number: {ep} \nEpoch Time: {np.round(time.time()-t,2)} sec')
if early_stop_callback.early_stop:
print("EARLY STOPPING")
break
filename = f"./checkpoints/{model.__class__.__name__}_{name}{ep+1}.pth.tar"
save_state(encoder_model, optimizer, filename)
print("FINISHED TRAINING")
if curves:
plot_curves(logger, bool(val_forget))
model = model_learning(model, True)
return model
def encoder_epoch(criterion, optimizer, device, dataset, model, encoder_model, lossfn, forget_loader, retain_loader, logger, scheduler=None, weight_decay=0.0, epoch_num=10, train=True, otype="other"):
if train:
encoder_model.train()
else:
encoder_model.eval()
mult=0.5 if lossfn=='mse' else 1
metrics = AverageMeter()
for batch_idx, (forg, ret) in enumerate(zip(forget_loader, retain_loader)):
(data_forget, target_forget) = forg
(data_retain, target_retain) = ret
data_forget, target_forget = data_forget.to(device), target_forget.to(device)
data_retain, target_retain = data_retain.to(device), target_retain.to(device)
target = torch.cat((target_forget, target_retain), 0)
if 'mnist' in dataset:
data_forget = data_forget.view(data_forget.shape[0],-1)
data_retain = data_retain.view(data_retain.shape[0], -1)
if train:
encoded = encoder_model(data_forget, dataset)
if dataset == 'mnist':
encoded = encoded.reshape(data_forget.size(0),data_forget.size(1))
else:
encoded = encoded.reshape(data_forget.size(0),data_forget.size(1), data_forget.size(2), data_forget.size(3))
#print(encoded.shape)
#print(data_forget.shape)
both = torch.cat((encoded, data_retain), 0)
output = model(both)
if otype == "float":
output = output.float()
target = target.float()
loss = mult * criterion(output, target) + regularization(encoder_model, weight_decay, l2=True)
optimizer.zero_grad()
loss.backward()
optimizer.step()
else:
encoded = encoder_model(data_forget, dataset)
#encoded = encoded.reshape(data_forget.size(0),data_forget.size(1), data_forget.size(2), data_forget.size(3))
both = torch.cat((encoded, data_retain), 0)
#print(model)
#print("in", both.shape)
output = model(both)
#print("out", output)
#print("outsize", output.shape)
#print("targ", target)
#print("targsize", target.shape)
if otype == "float":
loss = mult * criterion(output.float(), target.float()) + regularization(encoder_model, weight_decay, l2=True)
else:
loss = mult * criterion(output, target) + regularization(encoder_model, weight_decay, l2=True)
metrics.update(n=both.size(0), loss=loss.item(), error=get_error(output, target))
if epoch_num is not None:
log_metrics('train' if train else 'test', metrics, epoch_num)
logger.append('train' if train else 'test', epoch=epoch_num, loss=metrics.avg['loss'], error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
else:
print("Loss: ", loss.item())
print("Error: ", get_error(output, target))
#print('Learning Rate : {}'.format(optimizer.param_groups[0]['lr']))
return encoder_model, metrics
#########################
# Simple methods #
#########################
def retrain(model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="retrain"):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("RETRAINING")
# reset the model
model.apply(weight_reset)
fine_tune_helper(model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=retain_train, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name, patience=100)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def fine_tune(model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="finetune"):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("FINETUNING")
fine_tune_helper(model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=retain_train, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def random_labels(model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="random_labels"):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("RANDOMING")
random_labels_helper(model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=retain_train, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def hiding(model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="random_labels"):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("HIDING")
hiding_helper(model_base=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=retain_train, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
def neg_gradient(model, class_id, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="neg_grad", ver1=True):
forget_train, retain_train = remove_class(train_loader, [class_id])
forget_val, retain_val = remove_class(val_loader, [class_id])
print('-' * 20)
print("INITIAL Df PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print("INITIAL Dr PERFOMANCE")
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
print('-' * 20)
print("ASCENDING")
if ver1 == True:
neg_grad = neg_gradient_helper_ver1
else:
neg_grad = neg_gradient_helper_ver2
neg_grad(model=model, loss=loss, optimizer=optimizer, epochs=epochs, device=device, dataset=dataset, lossfn=None,
train_loader=forget_train, val_loader=forget_val,
scheduler=scheduler, weight_decay=weight_decay, lr=lr, momentum=momentum, name=name)
print('-' * 20)
print('FINAL Df PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=forget_val, at_epoch=None)
print('-' * 20)
print('FINAL Dr PERFOMANCE')
test(model=model, loss=loss, lossfn=lossfn, optimizer=optimizer, device=device, dataset=dataset,
test_loader=retain_val, at_epoch=None)
# HELPERS
def fine_tune_helper(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="", retain_graph=False, patience=10): # and retrain
start_time = time.time()
train(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler, weight_decay, lr, momentum, name, retain_graph=retain_graph, patience=patience, min_delta=-1.5)
print("Forget time is:", time.time() - start_time)
def random_labels_helper(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader, scheduler=None,
weight_decay=0.0, lr=0.01, momentum=0.9, name="random_lables"):
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__)+'_training')
#logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index+'.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index+'_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs):
#configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train',epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (val_loader is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model, lossfn=lossfn,
train_loader=val_loader, scheduler=scheduler, weight_decay=0.0, epoch_num=ep, train=False,
logger=logger)
print(f'Epoch number: {ep} :\n Epoch Time: {np.round(time.time()-t,2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}{ep+1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time)
def hiding_helper(model_base, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.01, momentum=0.9, name="hiding"):
set_seed()
start_time = time.time()
#for p in model_base.parameters():
# if p.requires_grad:
# print(p.name, p.data)
for img, label in train_loader:
img = img.cuda()
label = label.cuda()
model_base.cuda()
out = model_base(img)
#print(out.size())
out_size = out.size()
break
modules=list(model_base.children())[:-1]
removed = list(model_base.children())[-1]
last_layer = torch.nn.Sequential(*modules)
for img, label in train_loader:
img = img.cuda()
label = label.cuda()
last_layer.cuda()
out = last_layer(img)
in_size = out.size()
break
#print(in_size[1])
model = torch.nn.Sequential(*modules, torch.nn.Linear(int(in_size[1]), int(out_size[1]-1)))
train(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler, weight_decay, lr, momentum, name, patience=10, min_delta=-1.5)
print("Forget time is:", time.time() - start_time)
return model
# few versions for negative gradient as it may be done in different ways
def neg_gradient_helper_ver1(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.001, momentum=0.9, name="neg_gradient", curves=True):
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__)+'_training')
#logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index+'.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index+'_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs):
#configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
output = -1 * output
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train',epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (val_loader is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model, lossfn=lossfn,
train_loader=val_loader, scheduler=scheduler, weight_decay=0.0, epoch_num=ep, train=False,
logger=logger)
print(f'Epoch number: {ep} :\n Epoch Time: {np.round(time.time()-t,2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}{ep+1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time)
def neg_gradient_helper_ver1(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.001, momentum=0.9, name="neg_gradient", curves=True):
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__)+'_training')
#logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index+'.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index+'_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs):
#configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
# change output sign
output = -1 * output
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train',epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (val_loader is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model, lossfn=lossfn,
train_loader=val_loader, scheduler=scheduler, weight_decay=0.0, epoch_num=ep, train=False,
logger=logger)
print(f'Epoch number: {ep} :\n Epoch Time: {np.round(time.time()-t,2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}{ep+1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time)
def neg_gradient_helper_ver2(model, loss, optimizer, epochs, device, dataset, lossfn, train_loader, val_loader,
scheduler=None, weight_decay=0.0, lr=0.001, momentum=0.9, name="neg_gradient", curves=True):
set_seed()
start_time = time.time()
model.to(device)
optimizer = set_optimizer(optimizer, model.parameters(), lr, weight_decay, momentum)
criterion = set_loss(loss)
scheduler = set_scheduler(scheduler, optimizer, step_size=3, gamma=0.1, last_epoch=-1)
mkdir('logs')
mkdir('checkpoints')
logger = Logger(index=str(model.__class__.__name__)+'_training')
#logger['args'] = args
logger['checkpoint'] = os.path.join('models/', logger.index+'.pth')
logger['checkpoint_step'] = os.path.join('models/', logger.index+'_{}.pth')
print("[Logging in {}]".format(logger.index))
for ep in range(epochs):
#configure_learning_rate(optimizer, epoch)
t = time.time()
model.train()
mult = 0.5 if lossfn == 'mse' else 1
metrics = AverageMeter()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
if 'mnist' in dataset:
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
output = model(data)
loss = mult * criterion(output, target) + regularization(model, weight_decay, l2=True)
# this one is changed
ascent_loss = make_ascent(loss)
ascent_loss.backward()
optimizer.step()
metrics.update(n=data.size(0), loss=loss.item(), error=get_error(output, target))
log_metrics('train', metrics, ep)
logger.append('train',epoch=ep, loss=metrics.avg['loss'],
error=metrics.avg['error'],
lr=optimizer.param_groups[0]['lr'])
if (val_loader is not None):
epoch(criterion=criterion, optimizer=optimizer, device=device, dataset=dataset, model=model, lossfn=lossfn,
train_loader=val_loader, scheduler=scheduler, weight_decay=0.0, epoch_num=ep, train=False,
logger=logger)
print(f'Epoch number: {ep} :\n Epoch Time: {np.round(time.time()-t,2)} sec')
filename = f"./checkpoints/{model.__class__.__name__}_{name}{ep+1}.pth.tar"
save_state(model, optimizer, filename)
print("FINISHED TRAINING")
print("Forget time is:", time.time() - start_time) | 50.071364 | 201 | 0.608075 | 6,564 | 55,429 | 4.965265 | 0.04479 | 0.041084 | 0.027982 | 0.060628 | 0.900006 | 0.885309 | 0.879817 | 0.874908 | 0.870183 | 0.870091 | 0 | 0.013367 | 0.267153 | 55,429 | 1,107 | 202 | 50.071364 | 0.788976 | 0.051994 | 0 | 0.836323 | 0 | 0.015695 | 0.087144 | 0.014334 | 0 | 0 | 0 | 0 | 0 | 1 | 0.028027 | false | 0.001121 | 0.005605 | 0 | 0.045964 | 0.219731 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
8b92b954e9362eb797c0a146131a92419f4ab5f1 | 401,708 | py | Python | src/encryptation/encrypt.py | Wanghley/M82589933-Criptography | 2b253ad34cc65e3beae1ce558c6f76b487a1f986 | [
"MIT"
] | null | null | null | src/encryptation/encrypt.py | Wanghley/M82589933-Criptography | 2b253ad34cc65e3beae1ce558c6f76b487a1f986 | [
"MIT"
] | null | null | null | src/encryptation/encrypt.py | Wanghley/M82589933-Criptography | 2b253ad34cc65e3beae1ce558c6f76b487a1f986 | [
"MIT"
] | null | null | null | import uuid
import sha3
class Encryptor:
def __init__(self,msg):
self.msg = msg
self.inverted_msg = self._invert(self.msg)
self.uuid = self._getUUID()
self.node = int(self._getPrimer()//self.uuid)
def _invert(self,msg):
return msg[::-1]
def _getUUID(self):
return uuid.uuid4().int
def encrypt(self):
encrypted_msg = []
encrypted_msg.extend(ord(char) for char in self.inverted_msg)
final_msg = ''
for i in encrypted_msg:
final_msg+=str((self.node//i))
if len(encrypted_msg)>1:
final_msg += '@'
self.encrypted_msg = final_msg
def _encryptSHA3(self,data):
print(sha3.sha3_224(data.encode('utf-8')).hexdigest())
def _getPrimer(self):
return int(14889444574204132554780645847239791660302627399279532418527128942521323936106447531030997113218033717475283440142358756005197751832658564918429319597082295063433434510973136992053423106411405952647678767468193322117818493754771079862112265347927886299421244723581697946442467372269911156615468898349878577880899273633363565129754335286257452179055411135678548030295382592318290404619188080666720079222244571059309881538873940476999622792071943193965077120657269659128778891780444893214525405268925811066972135872605813039683144951084398145854211844200148437701610642903895817082977059418889948793270160812797274143481859080774599648655190062672294171521513754528281191030824461144012351159456852196747038826579037625519936415833523853151542818455868825953589547210298809847780883701686351419725240132772231534427225747181306147625815374655866269118381029260722922742741591677805540986193572204715936611931996160718058420541094365289984777531682622451908706025415912905755515034019195752086990922805950586823483423433390222157805175447893152068114144372052179721953250909235527812846017542915009972903387013545695298798195320350480795142078820863181303301447893410049938809455111231101759512706475179910893305478968476738845311528956294865410389965240118794320230435982271872731945392862234043546115519206647266152947365666491343980517913524133584754719822227043388948929318395674897931865702725164400479229622242295788968435733349412339814209907503634531584014992355905105152022144724440227062589567552831347259132359157427762069987246226694367770209990555277196120271441974172256327014788875746679124199366714820470229716090665964657712569235389178681061603854163358405200016225195673967146876492494867746446903248286792594583448144637816858382679167552340846715800589130776357209833960997051753835959845972392961630281757197948832984801393805798045615405758687738625458851970408170833341277613140279962436235669244277131822651023538185961839314606582745607505245516679921541267831030874556394034080539903165597271724466499101784698299639425307607480799713800784507146075897701462244102623923688549199040362239051115037239765884472754925261950233838768997072160454726690363728261075630868392922558992198427292657169642094901339854872309371396098196888310182277160960191570936096818063132464630015801550485471753977702445169961676559013908321043252243873235324406663353861983808879451650295622820476518935980373939666631169200343587494296098854279527552356855375126623245944395202991646005399999923801822624310208184982948769365533292206132647198294811169743683993355976987974930955023234966439599006564085423061103428244589439521075497160359822511128949129202231897327108555961069438781770131614441685157857081050023685868390795994569254904531673869187368552861718694771774854002784337628007956776070022608536807517839650666870241788002131942049083021544260824154115722969256967502675661014023424641192963009190878192222135720797145475983997905153529120046061849130603031714627864253371895963724428837034542006561505063169307024058325351104253896482023711792604852022840588383191569450190058072480472099517495817476348119593831324891126008419561832651441610635028897807138233517659811156775865637086084358306199333620666213815032051552336808926116049895781634416898446801019937039200207934709023422449930352930534830364461631359999857221835294250520825321722772250152983777337351921002779593650623241614825306367548525690851957815907221172064840134036138268814342151514895669614318677143428234865095446493955154526689526452138712750027300805586081866018185030876090938309172691629758112330222197228965695872683692175304838796727655081184177480383392476618156442677111164383752549472912149431485949469508215572646573477723467393711741523028941008072907168860689771658207438492691168271196315607744109599250062802538210321592471139254162947630098509353531863961985911999764259264797744453417356720836404273185010339425200153698376923714613517950176039183758908828901469234512472706473263461602717371720516997958644776017990064639190540594127826302581748122203498340446219211021995729755873000518693786221174961826397958078759667713862394146824055894008394118551909220322674739399031646217485653286542347615523569194940849916317599662436601959110847436232027348728328382280038207248907099205796712422114136102361165926818663931224763935168931919560950276700231527291957791690253043866820412828224012493218029240674073139264094285414395261600723676951457825480169682720258167777430204762630739364104286720561311501262031350517337293688263544418114530454977612408549340119828324868844306462641450952397273189851121464910358778782068461128368627428950567272786715899677207491635419043274241727515638015404907847912310553504253203188881204125597653983333463250186819800936176212528124945870243867867323544540471056474899535841839310034779576084380553148557601211071497019290198513589823800688172385432659832313135406784959937017000405736695450564525514309958648972817184053279627125061184618801730847481980464416650512001304348359281449001984369344282363026844069702795605005225234756431275052739237928318212866369463682882013196878851903709910321184124695565744997586698663296368212065482871109470239125925925146373974321413620497860179543363024884768405393381377149145771581104133023724229962864348826821065241721087817204436306041474182174010010044249352087799157896789965536880846023677266552455569059567512452274889115665993453258077488670072582993319098257140715480482827140913756802489683170496545062795113806647452666025473904337083534096200227355291305175753791746506222667300841061924867716526512592202038405216075351873935592658854724018658510858402731892968988031341161657135065109767315103480217340893850687280630217136662497274208015481008678374871767361496208666712274503355671965382619968106582246106672420286694652657119568892476969801498352489267441204700190623200652293394577474764963786111519692901004085678494931900580241105024145944688152015306060950058612462116773405676011712021772936717577290532159181414933047199128102077495097207363539607199976218030061442831392280960920333057023296056079602264802445478845637061562364349114154535998411323684636937040177657388146126116044116886112961748382974475285572742560479764774480923145833906624172132889671221876999519763410271578098532155273764551331171182449033186072162294229953835940179425273362720098535274234010940482972804242949130658354750407455994291106638842850696211314265785528693499744341786379207473578971172467379877559839188890918033511354425957544861324920765976838329521914202517596258401474960955596048740760917054523236248684721224051053757970312577497764909437407825038813339513787663100509584329447783754294417743231667945357128505819874969367468260051602043757236116303200816856893152441818462733659928814308742487658511511919016957147058125553563170241635684154540143542484506368161751230606271994406259945556978883414150243376474900452008945606276885887591325779829514622801885817805492606526533188588994997164961119429422203417691892489664989657245663648758909469700005471508084471512675043922035815621022293865375461254626603672491389115627008613161422326111105512814434799745727090322421856329877583366479719872564393631070235174769712021327334871424382567826346911751421319137461471390061149915469530594368116088899155902353413133905618968149217282362555492768366212821651671837638758922139289463480206358062389006482384607920574600580820044613574581526589912037607325097137357172766532583414196159260530915764646439903491113531202433405097091857554806707519723436355629132710409356491588232801568776039193751042999269379953713170009048874486490380061337498070313187135338133115394691389481099598596780657189064271577599670940317648287061494947654318310126720686001276738963717560687940092784492797762167775910224749480654337599534858573285795922445515611843375361657467002047934692482334576174656953922355079844871439629675916166640196701299039797200043829638150111684062580425956560162106224442288655758053753513646307475882126880628905710468441456489388792734274320929698383930242216749785624025208491687515166469595935705843541741667913756022234352358496388200404212690558073200019682246334888099567389456596699189820955728603745509618911177862601585075294289307292882326966926656564994955700883992632549703526161894580187390885868489215677350382160962811829938800864995326034207923480882570466736620157023212791591962632494283281275895166603328766724175316789352616150706251957267672723071161838553504278357458628737012926456179705922755586283512683865152326213854417788547771625378310466844634684879001978394526901451218426824961147400408921343364949705300702225672993490240255945890849156884018048461251372854941913704401744285054975227707711411981848279233293607782051403412534822822408676714867220887806863036947365954250395311129421215560000027530959810640544045862110591439519550652824553584280756461410380424409564156890418218293611424065833644017845963006477708884154342357331573678601148932502575296203328506389220779674410185092321265169599945428254375197182341784664701186412820247562869740778971549747791027431900771101404799397088463043020262059755401975003725366906826939609556020917577293531045278545434773975446694072352932072513435904684512039153067187952268637908484791667344711490992402667243573212052294355079556095644367455666810106084638255646432709938172673406089989848851005478826329818602400624412534932830136969003372256665498595846330230386454285944237348815900495187927301261943178084688610524512255121928002679226753524800611771106501412134875357087119791271463568784521526398323317913996764701921031465646053060367494330332248342351241451285400544745489051165646398630062564242573151055044216019775379684306297203103633741878893556792933505238716168040401633094785834383360734318689042610531723594213814712426570282853420235994395523279274386614451971808222747726977332223386063431314905711075864998846097222236917809238888245496206136078172933734198762448851380933251919820315835043320508510979763579385262103450748441136275066548410363586352894189960693966242891523970787820811660832434768930116546119628586401913023078398986467539355166878260017276699561065485057899681124288140153610233034607659759464422745240682939725822337883975954146990434318746918153190184745237404826889435019833686013984808686013686238586298713436799504413737492404541270307602170572880412461803442517838105676740458422369722351742822213339306756470546403285797275462429557362819009831904008567405699752918289020260206953109167182312206689476222791839783385430155523381214354908065672359552541891961155545666832439643786197074964154991338725560945463380160842368843337622371691345633160438275691502276296924262379573944621561721982551725550226590434572805183242017690706254473474434125735536949747213077709011618455697958736099253412193872987580716429011238121207553841463075628452546930897823491393511399927725337230005251684331122788060700979551674827805491226855426222848156864143294572685942179021637709842835316035036776145765937885899666948933466373988983140838722043478258455138740154957322251132033991051012963460350600122095731474559644627490395071282422941299367184580139528760894402599396810677646672379768772991286240623822717081061748078350811075713927623701333559553653049062315604134423855049918249843154920445100392665399260492131278831274471618532198327005935635664202087612176806373097549799556720054019626076753681185185191211358252106203855169566759062838999853085539805134028402172523720327940260257075235157098802863414882291952683020559088282113998881644338692317046216315940420509100649339780397560081270620691777540464975377453931146128096526382132306698600269358550649333539141676864238810881295878258030702068273919113481893421183982446315226728578229959616127037824846726691479391821902529695462612872720738792827765896804757732795420562448199274596302175986266444218299565690233317628622586547602750389601666800165647512998827046331411750462266076991301585485915079656567411065761178695166120656880183348005347780046956073440930340098591185631038503817591934642426890082072051615111966444059606015478769111488807998918393539267676562778984260391809650332440267955572884278009991823291936838839765373006849666246345203926728212192927726243427800551609062495967883093371629642151683947135773694013029532495453922824532449582863363240922882972333742555245118576472529339515250833569367762040668974227819784194861468893903918885037040040326778674175140037577872195793337843287347311703392039287069811403579554597029074183668986145772979642881334600889978679174915238076503845936562711853781134216951363133484003511107088800104232701120464464791533453831646006944102483456287806407799765274359905881142984538171780100097785645139260600548491855369259726300321553266337872426120252460155474134947126239183459481135629825520133023050231309830066572130366451109904136100105333887416496277554565312390362061556580915452667643119868785847716541089371736067656480113937210532734066531534056715714701362291205230842087482555080099338302548485395872667455048166239318222592638281700317889741174551039988045810441091842657546526530970708016541840794096945730281736012994941522993036346928078561923188766075612373865149283606312103506348273934220821473783114636679263231746695288634784418746773024524480889576297947901855244040556622856821628700602301635578914055173221401326471262281136607814984910697018487813015328880871297937754468881344990494205357885861230430741926162237643617094486943213370157303562126814326270763262515619993968161860061418309861378855373843218032670672280962629691573404202980401973356180254237370148904743898499462683272295819928821523267210489694205784450935747986394615359319023522058410289309429292344526141635317889927836080631677022902318265993746482868904470271378100355333592626968001541324565566921037533941647990593826962972778461912165376527949664551662070296855895937445802899589892300352280899634284967270371496321596797257584584484207636906282290779606907361791185492386272909617356481561825284172006043682410772200247430094275098185671784615914930238348577112878900312675690400468311863429159732294303279185748567652279371017190100777990573286364261871198989027726519350955275244884379725038985599022829104858254204472102582664918250965853534745075620551922643709843651521473043348450301466273225668621031080676670582083552038037514733469259246369458295973800012788187363617174807426856437507983418077101757966878194085000461883385917228759817896453402469869402723770085819284122142271428548463881068572171591324914291457581777814272046080598124708031530287265288222356268828787126272506947311570766356636574664979777696403661359123678483118542003489067693321337471886474516257205012545338050639927239958617189775369878015946542554391842761733931412172986337251296385428996727958767001398470304637862776969139248120080715005353384908663837376276866453724652751865006604509630447226478431832313095723677630042507895239713695015135594365388321378256360112763122427114367605378119425345557410215089755871139904339319074350365194149255553026290003010793612972226606695766992157650695253581027441132044574161590276885682638274380285775809227912843603740946039322111910514226836261864341237105247768434539966596598329262631893764097160212121612122486674148048884911561602170880695986176161227311983086569310483579487598801723939696005677407774431157400695512360619165168282858495500851208920918720898132487735535655022535687048760878867375168933173224667904616355453181952761211057287085072434538281187121499090617334383140957969222057887029369421129764644317155528282105635835744493138829196889817246094552525297440275942858734101155353870777435535975075731443884646628319826621184122926869451417485211968720211424209746380866623621991286069277078966190128275042602300292249873573049704685799135883687819785501102426125743923525118199507688796925178875687256104807870622309959554827315739564652773101374429160013990081784888841600902065263924942737093056303013673903543839893749720230264511546891376806309508470657375818507769642540721936560935742344826731400342318489718217399880318119227504815020859910187101450262955488747884718888788411794806089708745953305174445583437480736767026743735028708636873171603399963432985982853886377713909954692362301187619887545227739459305013088978698588521851953721337731583740509952276969891010491607301427915210926151135200263212303455177266863671394716947574380483166211418059594415316677775698703837796699837718855168491824940020336404301285850243006312356146165945135204712830604988689217753572056502383793967923604140002527942556853779067155320305973109373786295440102991403449104675244201721440645149451215613624505116502773894529183364913781643233683096788448511533397231148124789790160030329457753286712578111663460167053960298906454538056044432911893305577538564330500404509665832391589152447679243487398337140453696155605396928804335056991968282513561767074255023636256345094093068221430333532350500064153762779908608594782054919492102291998981976662027357739033838696464587995151722050629801080174603190123340055242962900700053363013502081523490796928318325091190917904709804124219003640161494407836065192838882034801083551273926546493651135304885714511048689226652784878485013335027081148162926627427061275959861665396674294430698689150425904203617913258547213973122275438508084187951778438261682928158669797995158809749035431867449539287519710049265633960686548597692654861386167641474259261151520485436728925197150658134635425204890520488423959528039316970749327972123353110548787740704178497893841398530528339769434271306594507255588648299622857219813526118621364101523456347102092025513202364077570990376851977841769259602674051448856984824717162006619768596800211947081503080408379549835415336482886644658349035583617411358485172159052954334049964213995829586774852698995520838271449240488879220670502867651864305026404547910907165192564324897810992324873644921866497503234424531853673433683431915667785772331692036032254582066476018068287543596698113995211834571027556545873245718901512347237065440499581913773789397780049048523627930111428308744862258263506994802715220059416431454771121628954652025364316831189124917143543178065159726124384347389346726054949052034848676199967208450631273009014627429120444754571497463718283791704997705003319553393847153019400846200727495313100709914662662277039419820162167680456746454985730886285088352819285022321851799621391356721002155030523504332860227686781559745595504663042455207377040410687335982733740586706183783747691200435552665962938034112502496191703261214443999107186023572566115410880780712462750843185597307648419385387804923357192034725760533418026876909307666047140120273807324306800991119980607503185425993439696018352486230410382299307703103252155700404199928735639914003582763396792749098499475470447875987353443351506132439732972927322643881077882924013525227575923803167605593186310064693459113634511648311272445273740578549401108388477733087710897824628940555080694533589491848776414697553953518232562268286480717323862066489198848698724404580734006250029843244483646772537784524278889268779501978545162248345004395014113715646952472968350155804496608759698854083225926812503945834663155054246188665721734553309277506232223025774669894286165962437575810415039712837069674389496223989810642631869531646296583103444622854319651831364110576665324497676567253581562136425744175232333499269308000102724163791756674977260451780817145856313522609391912767555554203374900697289155311063718312048983271122550114122010410398695649813959682008136268523477127365886473795666475175421449532574296182309025950179180141915904188800927578937528149568162528928644638390027116955928773883415719971142954090248715577222949229376544894046393104426054149142838225466107094452636370862059281469445449098212181485448353427761949411166880166961348903381067581359469174146410994630833607858362452323781164023197574974507878453915683282721871102486425805433198784634233510921533266569124333692675097783157413550639375214348645990126490351846859690560530081140697344134697905552032595980871920040897667792391282671441449584999771934771023242258818318633184417199026707045550890710950532447180399316082098826458166487656548789780980929362932328911050183938713136189655854984311479878010163273119035270705879228851113921632522194883580639260939584145754267034647679877897151301505931154015132127369773670425291569480539713029766710444393244051060316018646074894139299743188334970617012159594675938944891793891323485652481301262926229871540885736851601767089517750404998367269654048794869258948060685963287059641378764800153080578900825167425144628027372716423715307884124386295007701879967208051830332197365749179941270931970563793802947546361692247951844967899605540614951143095130613239441948506217688427009063284893293040259176642089292621802972765534782710237781595154190678512245893368840679838938535684051175605929841324106620724288913744183521493710529061609588773800001386596796279712050307155689970761394275437947234021886734307008528421175259433783301480272288733285990412066310447328079668008476155435071492084710912701171787840960703100962474469972425694917884853416698891747707403231283719349392339198424278432857678627645386538821910387255702982409670849896380343178110610485609879295781137437735967943703067649734706584087001860015698333924319640726483859199383486709821741102308968165678284493800270038834089239504103489762371831439342644332974730242795339727153950916318486728854138867982083406621526209296017111983747071635501406293497102080303007996916706383265261525968815617167504288578809516186020041758200488136564176306378476797570772482877092052392935581423710959434608109470388086941340582508198250932098605056962879205451784169479328406344816286421944645628694630912627119649003810561858880506642885374134888843227826014434070581008317495248034283388434970901219395317744439512473789419800254133826512361493643496289267270415519919010535395258612131079705352077689824861995451211564842631807921968301535256994391891235229253370976416974325562645554291393318297932301443377136600963716830409186383107330587481988039133586162800978196639539410914942843679246080865027059098036228057578495322874965276930073466552612767389392844349070331699541880414538924808143421782568738348439550019584206314582777781623042110232493392404711914117973909846572750493080125843212150703567414903002435011158817209838198494458365581360251688547025918036601697735354640727184386216381057901003296743855848154390921681885489625711440682898504218022043132147750321199652470455524904411486875946356435388646786831901858535434963076499094622442484025773875070349701777764263406111207524849039485180795002174677553550221881470582785716590854038771219398999991954928404333445180286944964796400423605583959768037037751120146987666629351448209549077774776893198061455211821408463715211830695814380356874942209484612883282386435540061586317398228672616561578778111983943683918739893904415977535147374897972946931827745176482369762419152366472719610345388366632789192613018981430547283570877490068178771240605685908614746700985437130314758557146215740295287176905519509736280118495843365022720548183989396992597357162567865815324026607915651698618329737357112907801710886694790396738944083224959908867118561338238974491207610283718487707789665103761164524421360970876412369652570918427218749285166426605984707410396221976425888885047047223315487713784362130114482975919766690666983722563980407224175069637687671203759580805063193816649036612723836340773466425276875232600490000646498447324034081256878827367914639328364844043969531654415667972857676175079394018027613744152728756974853219881061001704592929642852888186758334516987007571796094714579249720154018380988387516333992817824584480125803532009813776757750074797154902176515851364600376479127751434049525708240122740313599980510602468050099849495214589650146808807217503003506698793165043842899077372560787558433493829881054377762351749391548617276788426547445137551687677499238635829900762540467268733659967141340709469077213274692804878809729360499376368629191311387328506189008977759638139284129054821497092274266301009854160032445375529542130733261465112857451331486166304434936912508115426970649700452266800429619863153743104988400254885131700966322699454659719432813611390997479279488639321911780150070552113493707260295083843250239169556550514226975151612233476332125508041221849596024701227796397286161030828665156789609586348897876382680554027037728716099672632913617224417046060687937262634671765327000343526450841163164767302298412634364890288670298095056439978774381811986169422902953686344553927538314989331736574188318449403686964256112728623709586772155726217179344356588767571586898407748578681852514466000789932705302844822284071840582593859147577724966550206358031170988006151249024550253564384025887658959686856880927769453000942095892561559483872612628341331438091399548330589156361644674053619850483532950084470997631926488885928558208195437425981113527941632347662732043849597987806483834595784198766334355937239212835653202884330184177816686947666770846853534748725822397118347608536181258051161954992310492912567714381005168348531183848546006382217911097820133154499242689076700072439660342930989289021894534042000350875044376895294281969181599588903295297511821512225863108085810245615162026124276625968812583327125547357710704870740964137344819278444425909164305117481606266800495741421531505872501212327152519011582188943633618914212209496101883537247608839994117319448280806748606477300519447518420025053242675724175722659491896542652908108676989986275943981329506794136057329010480311124171768967234152817701627768464787455604798923937443795164482831828124767941415916637019102540525585407603417015768610289296477081010730727289721572679863900818920878864248156143789424464358341316442426036604798955059563565805270501592571413412632146569267122943646622822811582652675327524526333651111776266750357559714873185265725851496289846784730318423495227776519338794687425470384004588362246994382848920478929705175200557407036654635218082487200539391335096726930531284200817380267570213224632401331560189838983382960485783568982628078608457842190299306494356441974107111783437193054211672791247859039752334382114826046062441183996340266827715188678032469795432891317420320529198949434304782928688322673980389533011553016209382269356896217821848568682025832102087229903591021985342142949461637848459289150372505582176294351778897645199854319661499535404254581476595856063836638432093448264699124408499223739646640967038691452325545100982910224295368490901279409733393348406473942561988014319910344451183988919959107799887117680985854127921489432636945424257773315698420489246273664188206728515250143517715300631510410398029243364740043189414908588839951372660227949442392096680829373494454314861244387423532421062966759624367106123395813801309845268643641024396803377608002121110522449576457049580968645818756916271272323465509203937568310792952840669766374698125493865002899999181052685259828761784238238546319973212576140009328864048688760114366252583594871011190857514366911263355245535740621762898485609648992984590305493086006035425938719286098753293535188108989732696256688735968114521721954980439319778542986375670159270819670101447653293179839865277682062765442253650626042742181276912471776269353780857585293646255030336732156150775932260757894584556319771037649059672513752580609417622280583523945177392542571742854600546510516026756796047277427061050019773147796612775872175250279175421253342094079780985294317967542611020195569986044387040302537705935326015957825303189075886473874710477032178612652191660338012865510774655238436595573118171480141131457071955966001167738997349109413644579301239749767518529649978238110184155446502890390072779763763156349657046604603248074615278168679260736795117406658098164094273311195903617870038289366597592350936587981363582671000421186203881370764742364873833956662477684706356184681341238677724436361547826535131900181874083489583446114043650225208663227392491741753221631384781864966354097593978065823597093171210498945032052934591006275065931727460553006050327465507162980208048831034253139453164390987438944698053862794991439280410836053340254252128411545715304867852529733309214562520529633024954142544791301146932950573506833383839006178684787731435382971951118901184447292161825662192833137100574144773657150444082816746304745559942643989660219325192604901607820474106064933059081725343397564803322304832623735810664917513033527589982442636091016178963615166582890805544498923550875253794435710578288565655167286718088426602172366597997208481194605847748080858364393670048482855954631457319577763443673044875386037671239271408765185505340774478778260148222110753571180744356019751849227474509652330448370123469485793850523149433775637748717890832911295399645230234193029729204044823734508467949030621262972874885488919767170457580265755650561255609340100609883110144759070412333706617823915753749151234914197393965808050353680349626648269967305143684862366175730581490942222470383653262727778382389839699595312955933755588876583970722093276469061677365733783966294363402415075357703787031984500428832965789534033880971009695025962132584310935524140014301079404986708206983307634425464808602632751680689752484671587413809529776458161837333853611343203875919037044813725634853068872593665967735473735018532140417082301135972228099271705515182094653500746539198357174722919619410948873884109748340208515244993824811906524240420459236421653635000226753780322092859041223406442480571867329615606428406286666089538873244858022840328753047554461559293547542551567098401114702924714455970061353790604124676815657813219397776429635224185894616389709438064251885930951346580472183675958329480366123537485642460486824026041384490663609433718837709129438761310938209429252122093839392110179179454572832559788979069640173176426784406820888169611792180489544296768872303817825021172492382334636125893081491554176580991119291834199324582740032972740010069336948471131107925853938441264104824332390053782616059743887744417772376653528944458207958230866021667197076044907737370577781698086628837670418200249747763833044653003217732899802391710956135049063810480897197403834836367457358554918901642920334678715645153158066931952865025865878226225155992431236921496108183164060350401069738810220798140385108582352896408344250581741034247550430184509370079021349163090194864770765333574331136422415459953920531364151906624004403258820526281897388341534739607024924640065496694993658085648776084263346713561356524897859334830046251563193585441318768265970310958159679606778229268101357767608179120972163356744715755569771362017323084246014628712904883617420146300457042213446365600664427628025414624858334751195149969257244387714837333236397472729344219403533090484910222270079418789712046039694715452051923418174544053429068493627003442922829571245158394362025272908928870712407657488159353676394271954274658572803429281298620042435836612103203923604626945817054683807504470218692263222881333910389466718088110885525740846295264545463062934692854073214021135863208509424315499070810868979378610029437584773564372101370585891272694377790307491398879125914396675296530551653552443310390609695007046507562912719657892024350535093068086716138091475428163663054160030116000716850344829547148580407858903586930519515407506384090299154286234194926599174085145921211149546348634530458104178810439724627529745296231976822468216167195751498809238435468317420713219028259758176371041490915820661304606307036486312924553211377798490690656056537179170342671217239060272471433565405775304765122412312408750144956013426600603961172257771020441900314201540460884664923048364521440184255887009514314355897805176580864170491310527953997410165526955139123917130725545929027214286931208365711871392339811138947306562957691529189016177295158091855406159345206746883038489742075701234317502386304587968409392946960530053111634191127664036013937568701203162042675723667550571374968744106582490135241198787005507124641927011098581585970197031688020848877091114275354562505902335272971757624945583210780956235432673457769136047778042337214253781721312457032603066167324196551414070061493121940867703621346374896754401868617685202497025235978226605433532317928126224817119479396408529116034977391747184291612796078477470495321239427471698571554449755253297329489232907725210033043728030877021274590880055810512509650406134100840452391942082814834467117676043592626907029872271641373574455606914555671960678153847137195351907291185821393727517951658144982184763616037394726911483786082433111322422597705246095729096495648517905942465288725180739010144759253495211739008083638741545615898636087776154451848865050292763391112130337998263699758913438764521809289766251293484042690564581969525948032392142340159346624865937391170665604020056979855402129380555498653197759343045177747424430290219420889602814259283255874508157674616799406207892610797047607700609569739272627624355665776539852609085370481236699174857463258057580442803227704359803082154220062526894410950866552446243828693281783986808067326183957514610794212871725915188936405556949817413900255699057265642212501235276596988894110230562412737911787251833391040985319317171403233912657093796125877647879525329558883452155146606341660700998757254923754252413901494025121074803201820828603514507318444818726915467474486862828778846867200466506828142517450717733273188396558197477430320261615607789608234259239322556933044542208801443134939280020315657009927143306204789811861771109353677847752770571978292035710742110383429514385165991016229218527958460324632702077083986886901431581406057754709253933427913528658619736592370418869743905276522749886911734726738964712043797512450545778143403661918234340398889487658468055914020904532592989080382138275813261451721031270112244449976587354728334764601109818346995010523855405968482596706950007498992529561332291996325729579227542163577069459597760058367846520113074948555146936195552996657633248585148180031656517550167779195500544002947116917356392042008764868070423036200018029080164485301572316022075561920283822598828953019746583006651503031539067620612812674482345965491682094941493715972044965678314624540745103288908815143862214891782398858998211436068714973545586264641253161643059848041698995421188808818059366458350230511504175766410675865667207484205444972822166061039408416717339347075640429410233496240570083958158697767115403424638933180958738891064955199086042252442546408745562291466385912049337397922891550216790859974802961946818802746572270424596887118554787912531675731716550658475671448728409509041667715964661545907368249058833779023844365823663996406006572430652880574874913567992346314009718041572550697292732382842292874533559499640381855161465963224610045740112773948215596308040386123689934511803512075778897472706436266022638440123438110067074363335743902075531153761160637100965139031968680604129002486273822882193697217192167796225305261247030716405098180251538190906027189591874359815231141626185464313788396308821219071839522889690744220715825343376226456554929173930328399764370966113686019585827800605154560558163498888204724446668019381208612340316779334812762108685895441478566282059540223954019653411443886033512768817209120540306222289507492660857021562121548649928880357499478418009760783599597958956947191200006637481394082869397819555495733540681510647288391550660152072328152487749094550486997803137767223263900522231049688180947790228522651902016771492826073236347831306711331400903536656162284454133871684477432224253066152283402065398297375393781827505649627826923818183250446564410989677218924210096275071403618731626919877104743737050837734279534108083415072142580106248821076282564402006704387265077760536965647885234198970073222809456552796380795100493002739669993760405449676250222871195977059297963849873625632909958384067422136640406357877517306789292073897972010255762095105313952527891774431424167377952741061026810912628105868441843758650146971243189482475735448824167639825036081747912769761524216986688437624174774339864583529720953590167408579805770062041398435345038591743034965593247470960419445623079876798312698235903661971772957785289614772059442833358401295926569330830745419163531929330375280554984644242405975079934630141543296928696978782763384189068216734301754084083217570721152623794787232627659617251395039840183298240119354245103350732188276842151157131358520931753672424606580409601816435650212752652579568083399071237544203720509573288875502834312487873697957097661539723125444829621269665688234127309667146304553464175786751591604062839981990548474753588872361309533564861979696517830332863515920016877615744293766535812810371225499683174918931033030910767741199315124469047828422395807709651388435816466548233605704449155640974585791504764138197179257941747784971632092248981332095560092320823614474440660687160250572489960758002342610415792905802858683592710556832706323205334893450256961643868277542852390262559088738950089082785266085293479220024513001343156744371421792892502364105138188481586395465714993088539392103970911858196438067479322758059489862133632066953361265471789356773602893322699701288491273338129805314249496464425730512878289010547601127810348759423792864385570691391195221831525416039920330850209347117883819576793270764641293333194039976359646320778026429957455580573254114124384629173599367752654067350156111025269279084492175912296453970782168707160730850166292071978825778211307750140128111939495748776936988269314605026412824640071278841166476316885827688264152490113771663160697535710583438105885274231316053221085554695632710889604073007459297138634471629562439905526284579015876744614067895500303062937644452770474159483324732109875320820190781837720280476350177154232189435904140208637378259512732271841097450955182473555363583723418015901770513206788370790483521782009269848570618575235026083609178219649604307874938004112365501678128824780715692788838186873627266503318850294952677863182078491294082136096666354888868435064572533023399145684142010598913707115993438287534295765599428962303879795835510667519095361469897786955055694168462558962911063489324750047224157130511949288193820827666281900183292642262742046647859253949874290415146661639649175702689487824938773301899926118951332061517004594010800418892023947021175647288657023640252362933941089657804332827803048917791603509191040646249123046994430370453218023595186402304165930213242051358133692382742060040600201626837908932766451593083950954757220453273008708583783729704627194226104851955386159352120165485881749117171861472246172898523883828073709792822382497893629036524323224936266366151572529058780063607284688614884835192952694893544037479347294845985434125108800062836004652894945199454521095799786027526248958669990087466358485186481571644784734719367684952350159292697663665293722645762285771424127838733923387965642924043608649790497455124173651932850279256065311701266285089959805173812547158111897030553997443376417579718304219328028813098312812549230823090522541335452071787299642800397513361834772093032668473874436448627090033261961963211739013155067359181262930016090966936478461289275492456879786837915357307325928942663184010990056815330753185168698996099357121474097081712632615670315387817286272214334435698083695582512728682298810164362235155797038840302587976280396132368545191288339282660628216844445143774005604724128549815594544647914988028858138942496421930183502137340825263688259554492715720253120436429912725110909043018828044500989662627802598966616107941754514160795246842600246356533175154937048586318470055337196996162510816053679905465218554235942759166993534456988773604967636143759671789775382419101214705787191846103085548081500920582153014974513320145132157473246341169581964526950696818235382557743540161463203109040597823502961671847251988883886975592447291149136248479160801859287893399360368685271754342230716565589237980316762447760469990315246572265341480905640448327116245362096771180473014690385111125210571874828417957698784705680071660319863763080298588546457085354344792816775329393005611364718033916253308421164722351275271552313759332351643402147807665127522580461726270297309965996147880479730552448919246805434302265122761268955878026191966986672043034502866563948087180051749749627353854292098305590928949928963245457164437790484179079119495101481486727935879378078347940874992912796950527050419976862093512247008377658209321924999074037486362454298417863797053163158258341776295306580343777282378416408055008013325126711325281021610664576898086271506758716272000355799470935794107269547929368769160834114554170838233367423947065994061805642764832659817424504482165357720343972775269577410602584455758448791630827007009028574103109374617004112919923758820336689765797775008172732459855091718120629623070764836206209904957810180429068175160110703120597508597187501588042399873782478964262152316669918764756806475832352429168716152682722782005321597505305588701681970984208960925417057613971246320752047095201312970696990491229732377066624538739693094269350412729350058398035876433798722279929531590150213233034548655820148381989775721021180203995544598653913121430011806291244748453043253933928113908855083171238221822097115829391786200317122528211766326515456360569323787462036227401042449498420787120956885359040455646201426137198928857533129342923703487524817101408736063402108791415903721544318014774642538257916601321064511683813417389231889046452417142162441555936005878968431450049518827193907020386338092959999810860494542642972530652684470255117873334975369699511796895615935433669989062171432577344274609992494710278035053807280983659967359537014941341139868354567977707452888764419723881514653706834310534080291135648388732786076569250671704457697575305602859752903065120860544793236681033130966849925023432468548168076535349263928165647971352912505668384553953324472260367933847070013293228381129603000235666627027528846961267274268358991513021465942199866942130924584061749218390447837609791321337722900485635643280412482591984673942115501079555486989882709122718921802443306310947524058722877658546060756886237377331806108617804343847248530557005793090215715017457889734688943529486777050308370213197936200636444355837629282278227536025704096728479385875773157446592199042750707854930054672880538558367085189533703796890936316728777541745556613760091449714467672734213805725896015014720043370845136243677428898469641673293357571188836957690513904181300736517780707879764196694289906972373363846076221481615639289383657207732289004370903480118436976869955581426557428821367832537112488099457581632542193993940900389683992172465622866784541242854480297826278609490707822586721075952094033438309514787943285287735197262202750314612127156194372319576273898106881537562613305545545674708618295066120091091335299696442411021333712550220829444041108308838750075803795169022338521863308187504486686346737372070405017603886886988281397938548937389961822702551873167700062368398740808229284032634557522643191587560305657994056296574066155323628868654255956860856930982766373825527695577487100742600786028859030738988881738659375302926193494154274398377005144256489768013321007312173582472039161405919761912176249920110394279204343816388841611995961105295260250881112949855669346332298113574926561479116746575154108269631704160308725678688522648367246660206765001855252923463358920303508487435828100826772482203436581346860479504333419246968462680203781896650166373479794129193551350775517164042369220601183429463191499014486712597632572460991145605829118117039989597783505201391282148901633587890302539027869311836168542214530195870769594278414719190692098721489987181196046760566718432155854423343262805710702070069557341642728604914761350421962525343616422296166042590481126336030624319519294435211049276917691542939653598988987259717506185489405096903205583579472841304092651026823220520370547226646010984315285576823677677357211531525479152170059057732738148784072347040277621171593633802645056882717357200683354135692023771787084078582733906543972012857473211296283385139826027285170008173446038743823313774363462962493559386537948721021980374654998056010029087720202310139810536440551815985737979302060729658485904645600057689268716560438240841656689576137363343656010874234939464584843881448723342012166832026541158341978369637962309805853741245757416734067399389226748360074689587002944436924512493176909936807102901898158576719756124682505599405231086032296815351744586182747552487518308878461544515717365455307031478809640376142315082152276103981166797318371706148998944995439424822493089721041083601016651395053599282222958371459993382483993825828184018688079060939238137637754023488918926585661882544541327695737754089360910518987963765458708325147403117653031341042744907191979319786103194047344124854288438490991764543930235828011233515336331559415531919395020226035004954249251483741263629430839142462185631753827568086952183860279617301392032206718276921931222335310515828137480484587489169611444063090213140306027674166225280204473279579473886580865057887696938228959595211453014598578499091518469812468940778694115831501796364763538893214076428621313670159985365369379967393794155549752896756641551454699614309405440341351367534984469884682004675658243771611223577442450964883915703049888534978992148345937764003222882644805873472839791677612931213179658753182462229492400753256522506541789326262710929592343048431775701600929288841855443461075687009114075882545700279381676486935742607832144311750358069468553608763687543761537677228551609723146382107384958521538147341926045105727822129329128390147351292429275355471250240383638124523412934539441106472556457197752841972384627755452172228127028369709065532982355547521728784144066510676555522752886685948969459683883814598133365745709892273462417478143684587197717850654988715412142811363193198547199967625188884879829565061321494676231992698909938381301871247879143891055609668028330592564391494678412741160679086581758770326252945479195664311651368405415688121649608147325285135931532834365061942231130038416898863778033930477194251710608306009754053920587647850820047641353899802547976911790586951517724234615788330615582079363294379683983663573800520531452974136999814223495719651829526619175558695650441720675172583293703882324447371202110782950057137951871219187649428477787247443315078497941305077691714440898107767308309707837753571287366901590026083820487956094929777740611069475009422767056927425023613324188252542065714663519110856434143970979557471790076227611250179211053007628941827064835933427812267390394137442316973334527039333034402447757024048964198008222506437360142027306593006704477503019840177087548476126522325381652052577757243846233676911203143737346561762784375891601740794869812127941626969901183481230891961487360788883076804044034670820522583123580623950390650688747071822027914524873182203870980250135555299941095642133168708122566425942895684203884729148681775218945067140230036714197268838629584216414790752422004230927494406263018187652710126347362747748244222517735450163316702054844271605405417876909598200279448384237734349369673067370607950578327017154749585490661795632352226426871631748120505816282991153277650619849560028773614439701138016229100635735242023955988477201543651186596580581231907321934873859028968879237519800513687952685840747616823566835772317631419909220034224302880258387177348463123670932144116109479688738518983411513801589867419288621218115182358757567153240629863009575737127851056966296222157735598648303010319145410939475429666851399373246996824557264944736525479044203114062663037821692943975049876250877825888426189038138504042389868898861842597008272269571190708786583723442224195689520693674628609233425521859646697796238436572750957677205303858514860534158539898953823472226753234666974673242759954027132941455323925960586210690141608166608132706051433546951470284301062588138408275033107533245243312692708734652861064558182658268796408747973564500281033096384064389692458533897703159249685769250277822905465490057593893546107691871414102363241312900614856325571700056516480937541115232817123885746347395100699875071667682801367486455012755466965098069096105253028275496271789430068371422573916043342301409150587623923574502100877911117695438931131691386282134278898500307444855197680671053895414309444808310656515192367139081058100583245993852676039129739566657717961658121133993816515125984903684033222166209441902067907645648879185031454511829251516108293915880068039490512035257597203850272563411612634908819980764400589285459260527998283132974137216799186179358782363185766288484177872812866595585724640014680391015509204155184589675394098607380502172406041320566320621995325510689985014558276600991215755012864102228314975278729741809587202775664970212022273294256319201636253966718837996707844099094156838496599081743194583127136678875767439661766452320832816688237887600413398001747149220258985765181596265546090413425020722482375724237879412339432284145990920933804405877865260580750178516024532957701954474894414714911777324669190673190480862289944867310241987769908924552245620340284763647857398046568180828868754957444750841188365555838003155026536257872179893292054831125315005775707408871997646967210176793650659315260930913368036072484954041502504538702911058732889278140431066800575079273921800684206068013376741425836543827615808834975754158191583353204165098649865627630853220912374573456430560791899602564357312466915943047925395852751114333724676035327652062640223612751322346074919443454005310899918834933712330268559539109107719263848130373621694358970234883987703170452566647946824328422324848371129552469522266960806136235980318139033519683095408762787499890767130088717247219387465572910830866276590392423301449744211190648853740627227435717572141454385151688241920429698228506590217690918891494002552513285786382530175893394354230623155538488997069110333502584527527172131127925565281719995776432770337170763310067707453277185214843806970148975924223434133673204089389779608302391240048770349057794294041543503815868444727953671826944629646561253263610497629567697995765841911953512143016277311990968669831496674905609543751437084879406302213814307832326602498762850735192795331773254728490281965346455884912018275747698057326515175448297819767129093497675651405525805959520646912987520619901077374489947591657013083683236343732843970416922816087877260164249706103947984870421593732747362495448528241015206358065575716971992035331028052891664395830671281335867610234162008713899358167607351244448074896772955995304186349054896541212894179412718048834567216807842077300716033036154079325414992380981086935792415863953340679349484221646774525799533866165573095743663157675736762950759009434621397501034436337698062235868160132343449537829233702240752294107207935975156800773596998327188433560747489508910308952271910345977592912617196336143113413992009955872080338922050315378835675715766179269631505246230130395977689467951647926953562080671440063814902506163808608467121485207086338920565951304101425334878644615246212337640317215681263515535912285217433815527436444851936540465016856840615079704484544725354034440188630369614508098640201973248972559258125029673293997055990963598113578286672353377394271618323234796616292805285062935572792191997503340119306277876268403229297210251503125150834772003574684343316391320740392073580198931824268625962034044069217156975856527362557392137780792757270616011805102921619091829550173412639567618846688514101664228712006136617436890607007036974515221969033300435002483151213106708960663929624580552670796771250928605716092758926595258567350968755716156852641823904645021011874189028014939557333968201273201560271096768064223269316486957625662950885165046764578028859231594225301503380592166900035719604633449154362991121828560433968802693335752833419314833580528571943705075829380693993881556218827059171617998466876304500429728261681246615204329669581154744990433630340134935046030047288468751007536299859838094148253669042464437640273539804506994660164244739009804733170823759412856766489072533125950049254546449360923420973440276049068794275842582126919641336591155144803071373122364544932741488407146807388049455020586750340449980222031501785086120944993247590752859783548276047195945764504312315559526711595304598418190876282179696185661660746263239811362388022840441869091993841629677278662298746888328759389265051733741756827006302790526638442069160105750654604194210440687879384772865386672590861278741765861795686548523715010827738093441279271516460197437585711617440758812598562685989238455888625231745675491578320007890493439603971998384427421496197583274042925273560415847618020996421375851595381104298155510881131529258734817420582985261692781228366139722121930612840393160884953896980027444491900280527486619806198872852865941583694488960811436016899616605484319788726498775895753688267649702368023913998607944150481607429222014593293043819455161830953379954626068953463962255506853512097198043327223713832798435049123857237082744901221684696799220864202155631404022208338040852613399406554441237703390684842303419341406112131379855291623893888583297543463301693679560002624880973808539140803811285365213331909212800862429825142281275673285046190988552874838405131454539628562249047933912011332818485964989164301741762953919657763273819916628019868699528144051759823352819456710533238314980250726996282675012532723354501402028242364355794380099627331165180551007760980358022589735957836409629224077096739145463124105453706019930627692102166875319521294777075170691416358042202569291891994939177712909489698180014903911649628117210108318049581187926960851092785325544632190846665213189486565663238930288988768770015834251025738940717517151208065783496811022217690726648079581485466792866582978517058428561002088150907363575627547422784736531857798357126791846074953901359817638347025783172995702464819381428265209852967790977350706598578815204533525471385895325750677914376412079498125978613600967396342243683160460633264395806884526352148334672966576407569268929638160119510657242126945461348511912060199017825177073180145121584498622316325767608876261372562335555972313166631640329531231095596097936623902052758253061012561522839438335999194698975466639544179464200451964962834685382437063543985374791915362376606063605972946608510016925522240517422810235168265025976986013123832932960154084946216227113074996975665196080221929509332190163120329430383864099787609895860563704673257132285390506234569478276951011282511342131474351310195525662119264682765937375002062723682024537337443172690765611467316714783639970214722206165717636236704867657319519394530200809556653542494374770253018746983009154225261513679694053529284552614067250450509273229240174097945167767865395980032579662504738520072635199386531404058172463564342925340693072688969908914864012903245358941402222024700907615668846954553922803221063300821804630964295999458646978961610196165422397536582163089707546366029981167626204282444697416274906740970601243089780335316691273482106718292649766148260622463766083899576377204855595927742188526619069399772333024496952393366586386893817422368497028515736297525621736516038519654638008409705378338492684501167202372052368418407951140275232059204157434558544386787494350959284168649810460856141707603458502750683452204716342140267773000666153793900833896851906063603023103246268437131104594060678817229467982576230417554950226692620167887307468943999064152939635402455465760530902582048235444146350914898813861720655841158622461237978006683152048819675741847213312647345631321678216562286805188526247314591971197504933415145738673261081465840330673847514952090008426761634056468290932812455783615521854067421561791301131039407816332314638345606818162577433886930767951789012203242057995648815857431704053488038568858036094883435659861200354548757809323402960043474239924559670473083031950531611505956689856543911902978461067693578672224783531488630304789299465737510906740749052324742161615076151621763171805506099064423829638670533113474652246172821260949145601925028961811735686199764767019207396019920047720047342726764325849158632132915123472117416869524183220702106232033182063427512559433944777387566513781063091623369019307104504085299647403251627540454598007616144290889875038585573184300206536266357332994652128732931993628388984212974055583571292445745918345772430943074343716236431945019087746085927160477718490659001215774692695428955126458405655385458894672633584712654504838565786151857318604979728874044954567203100018479613362607072316087784064479299559646353410262304894896487901641906987731217903636257862047940466935218948302022836088112992146027464991549347297236867192527528819919894048815844227146807018419552864618599899004786317149665253961048663242776307639457703001290124191219193080053974761854072820705774733476551706805690240065854395492217919621238755488530104047885301580426372722214675363152043156952686378190746620888515465841012520981470786036895566233551502805762108200114692756091002092847810259701002863776765572523481428411606083099077593871534130885596165744706679101754285261449216184926115233404982587339695665704128735441497725440590252096892828498311361669199071849948024947553307276246490089274866018734313891691850833661555253091455194778949435821925576201680373254023266459140843150763412259726678692523668850960324468070472408643500060728705306645692576690574993641562460264632827259378964109371830023648947895808686952642192130996879993928985807661410382276026060719152308925835850246010776477845166358660653099360764626796573917881622236279998616589050081481560987057191095099999656257349254252936797802529658738040289584111608281229210185753728882279569174732180684775396832719821979607860560041213927175523364218963547093156085601516928542034710142326626718341966749156791828065831127006710901540054547259193894229307404156039535294420515814500979375109839052689475868049555011053858924314596344792387266004297891090393239970928127464721041406435218685739522287135532597142073448265404209998158213907532617271371525468142454413980085275313224225658501829812684932897969728305127975491191274670665678628310827622751410320419316691607388559948499454158654694706455881786381279793419882058358518884691715555749957071320557086341885470887435719735176110493642934030690517673514201573685555315051063239400790573559429336942511493388324971445635944668613998491429009524270821136314802818600682463877256793093622520235371275206389256854914787673726886368740707487871883758125120277558441918176998921603691111761823562163388567316843342760981668481052862792910890515102331343716648644252736916216300390412940211866064808836573452969104183706051690016605959091425808298144362269189984962240949704822470864898416882035573010841841638875384129401956920731947020626607830604828691921006064678611937025822877304227020808819619174309238815111803670577895744438222634513375453359263104181956680925204915314747839006436064994580108576988816432253112734455392398312746002058361944964152336670336553458075054343249070022145614096246226385306460993019109630791626751846176574630389780398780363700807987963118814520335016689292592021324284855885256740257731031713469292373853347192072084832458947378429133819395791926899789756441580217513475231678627223562064280317322810498066157227230293363058672433871347798625866204444074819905676063952022440852192674394152066450015740616271186730835691231702183968101492363881243227418740675188730187293401360659540841663211576660565690332122707232688293518479368091124022983630240070596878171892441061170783659514517148152390060386654094880338914721126488227316223995422482028823237555622908009789448047337641425175569651847144595793037841001122791983934520312320360061702434744956251521032511114199552346121092421744704837980066623743146375553599005459195925696297175587402701308398988417205571053999959807313995093145216251977583656569851053319024216837346174007852726453692574081270005073582572308193376618554936616798188066212262817013350489225769057295679188382738535420420544532240241624313541272701400154030407395802292716007783773367574101693230015158768393932956078853081461699923671559348887892987746492470636134443852077038441897592275628894913169908598582521028581989740919582371951471788046944702091601633758214840204414107711752632549864613459116412183384819042438770951181210549739081711651389767739192541419900862413458678507654832532734975977110004907283982702054616517360761899107912442838615512138458917999690728333064335278076928354999283715721108823592516194739775872303787862912741744184027359623975182808433504556230918307854416711798716507615869370796264364877006271115441988087173342748378245838556394819101782916435758528047022541916425426256599577594992729355380580208637202929390097811380680894071202244637832063316454857645123987960167342582753405082329780314037185917414553329446133253341142837143039099091859138229058214593561429223535384906531678867009073797912559675590528255913209400388422369036944429260107878333955868330415457367790684717613555178491118570209716986379187479079095932100987905818890068779348185536009333986313535615365032726574026128022114314261514309391496400436773330082376786409077334567676659976425913679972042643571122609661333152368884185044060362308310430118231402948898433153100052129083788129494704422118509441674107248659044129789786413391537771362465848383230814059137578051145833860256599033475327223552697379757964084540266780255155886375410849819278287808446352585114488567829852509676725025833275963197205897630446510019468726461640246398738829627206874461662761622994728189621766331280374771104808038211736286391595595865079907422089742271891943446390587644209026143396812551932967520827042454283289976530331180745754450019232471777486480411275729413595831346734790532397958739585343406168215309049723581996620515406352509223034160604742695552806983846847530232987611141718333888124185365617226176228395481318726221241464452154053776318871467114457889710242833547597372978669678977382944296884716637975246554216532753729118715159022548355711556630437010025597524927975230675304552399079666225973189335269059937263201600044632135372662553291185812467999358809278117655443210430923179215932523718581233265282151510281989087904079634144214152463022212423827056763081120004013531975513949086478052644112235816358865767814477727419335820322255371352612762358042942818357273662618962881287346660166996503261875323294895919044804429764979348855632554693032157292398257336871908115392918033415932935608777233407278197817122030790506107457238232468264237711456306505653867847336718179023979700736046961049264386939424613159210053782533754446797606272571034816476760843899572238807586906967643057024335349347257259312222767918119138513266318691843482038732784724534901619079866833890500083162852596947859626039319456719534557084231140803422887374009198676025802064875015435468232341301833254694748731756581161427093828463055675593628080052140680597447765980194166890294889194394351682654783939394621654878384621663442980642508590434735710159125012097875429650493801345360477300973849130789513258880020103236896096784181068441894687334547467317073056767523108752350323923858491320580417314842388590618668734009556357091185440371838520461030927020583181156012587416860091726271072006861727424923868841387611153077202733157484809491114634323968529068225262630031425899437103163189486222686204606011429099603129241558341999410868023409934802218067993905207063668627938773692005562556440898415959257377868211002764618676485771757014144801301655654272249994845091427409663228383527240984754021542649553617055048021394163745410537731031967333896690626203046460344442085871131770160521886464377840832642025923296559991123299465707721528364194850599212395599277482892335771767490790591515075872910160996426273451910944833029605950170976772002517448070845053954420332356168698627579294445314356752328566397535248811637107370524493714265096639546733784000275746997721161080740749164170170944490937848067773491544691530107873958381762335125662509320995027135433926575296158250310187339432101878180722593963966094271134928411443910870277553061496246913237753199108082798698510266160706488561451410379306800484779977119533081533472399855410021114691202118898476840942545492820751416614803559657156684532395910742279664467824285767931023602999750206791371053975970856915769668113655560679320939188280580590296502249425787091911036207693789435758675277647784796803584719993469318314616720247951461071206349238544670001080172559766379326751491258564269546852102242537844084698037615652525018213044547412080036594772419499907889351863644513181825806694127014184839409090549627425373506976640102941076594299005669832720747695967255888574921973643159933911248371464831617081651251707651317795104257337063821741691697514440803091965404483766719310895117235229974967498713051766197247538200277531149463839292154555323146842370341964145393263827347801014286690064450241442449548718958108731437448061999829747146888534271802759893713579341907645800128529717992213536857317964717543362674394203122009676948853772986361657039183608875354654503129100857707316957959027321462917740802928786869716431353739235284224314087728521516212318150058837409248509687661816158599844496576451608949651000918835014838825746109918244031609417336755660941385979205789882508267580199576445147993679381184382308768101692701202826567140605392194521848327473493227307376465859839716477203047422003912227432168798945476270802665559844124222553621271770138746903547174279712841404958843106326793010835945179056176184547926452859888835350286679372086715769645628998845874324685168439986553288053319016386013918078191344017330820322597657417220485165601160859482348465456807045465838935013445609978188213272521450743163537952374085742437379382416595810308307147528127562653301749891242359821762029974399299335065304766448518683358353031868290256412449657898514382434672411536165343081475160046508289546814293239908520443983396720729610606385030530231498211844455179243876419230741264832411995802323657345712759655116019324781077051532800676038509558431490577197477422704368668379149290988227377530675370136806637392937541676763128424889456705525501335713715504596102315398846268758458677238215721490056134762951035450200389001452862283949690174563782838450047554048100305173308958873315368223993488825391032235343003643859244597065925162226968993224441391845050044619722036234371176965660846534323871660313653454579383495788197680696578307582421621855352748480149717638053520148230729747252287606712299709013903110844480166118842662403365426521209848807375485198647861212542591548640272859464717236228684676903097229800506260747098890635728916036696747689685111891489067467008076293457385233890717797648913917858255349992669550862821712741058128707264977866081156987530195862697026494261996519801118670372822603419983419554555419212739191403977988424052709458810782348800279689704041092796316909677394580662002569684613617960442474864092655880631828106286867985152234527379847807152866318693734267719564564735874933864971583153848980501891549415565625008778114912156677984961089271109131680372821306058074005174822912410202285932081178299166347769700800109755053975739370598685518157788184918887714821868664348482234456890848343445313675761173870435148558756185015242518518184864669934463685073497899516663778040247056696240497521285851452781842498039415443338751614203818699873208883458844636715847791525424009894792412701612859392099276783027897315808695398014324149886295640218729370052574997786506625578353396527405392079626489456853612825656031743454383475265002169062470404803853788901443522354656047706014806468655785531620281638678920361491332304666369905007384624160357858214044229518387267085640260403863753609986268446202085114269327193841581459944743196518841009309662660701413834402881598345243236205254932876207384224128768985442997232372358266242439444913760026853211668685409810128989160507523931226960340953340825140265822100948798753900925308763496617837009742235294495399867905995020376664333095721818889700649349702999877903563248266599405355323057946138143283761048911294137365347534057001637850440085553033579304986695315434452281629363974786642175782011030619318294531457882373314062106910498675104021302054794190561735994223636864085338128964463040715155731984072725889145059598846535023842408875221146321066261835769213866913378305898833662195658757123623984682264999018342297930814073277523166806320227900561175544319693762004931880371703621561085377398837558212988003300318771596887427135818332378354743131741781785469253852835080835109137279727857034933450323338903833828644920745613331403447813020615361024365091727298312061660544374432701220456356907334109138236081272705094822581386481125180019491723442200095458435719416508249360666319489298264956716150249216955298951116946662352611693827513720196751868341806972306987494817613168923152212610979933825146918492391707313499000433900741232659028567248246874812806134679535350756024316406901745624427327373514542503058802610877420242337124952627296097702098975635551014433875442559840444800511276335077624513010539731682624981884157154802504040145369660246382974434680453559835832317714890994042355651800981284210324036044572285559430254552544796972683528281218628840403918635470397919690463485839006446128039570417258086832675634319491542808651521188159344712977988181663593537159132265123473534013562354869623128722793332668793897404507384551377847276315555371947156568238331838050033723041180296995756913982263735291545916339244280895188321754526437923336485744137122215515597480642824463751228028340657686989940831374992749483097740477461964506962110789725866888221494710141203068680185524330558376309988759464641996043642368799538629828797190186327326906984518766167119328699465154488080883878778009046899618929858996805927598689523344404200165272860297858759653859909306414295160815336818498794376811272453074466902645457689293953172964964967609093269972307192257700054041246783001965499618087015938270586727390912688881695924013122944928427550636746309608927859005744115422454172307869742117126238099035208847197170624979057997907174693487663918688221524423083920748420089722567585160428802586612027238525191448035749318336979946685177823208506268737629268142264973887409721103511489963691791591841240748265424654634719061784928163034919216634999131587862966631899058147844198482640415962674022681295030854773268274776951482064621856713648412547752836685831449107865183926358030564165376265598416443753861916649443324836112116352807589357760317066705780698425166876341979261911080832036643331776934389934061052284040248516300862448586510819088146814541889613405516363178384684980856670136809836527803956234408783346594446483552209467701541918261108766530734567215788046428642766436911500105814923057938662156899290814204048216534947727128229840083198324487874086706487050558521829048104682576063017856642553479936630366879342502758064400088916288546867386793028676471251458712739320149316841315873362532473432264860172447424161125500571047117929869692537251695702190036598509448090378500038047109961500160886515072149728699544826123893075051492209329940027621469936366655549878648868356440092548773334076469709520327411878633272943626397288104784495431347442525870399207511960375196192813125890917848421294925038753706905101680574504646429338317851977785812592759143203376693970591828672723587495760137484068116764186888452240553781387601936291893807278670045497405476366839901329186996999770911026156981779278808764407981614883087010398731720991249261668283840477123937613751303966984384939627368123875070328221341632062684221036862177586461387504246454212031692252160223880357359779557733836378100217078288938352066313068380685693246534522629656533675558975124614965522029674016706651064591158220053986358981972827135993669949580733065200720974380100822234718556743181489086649626985860025886450544976714813438950315833852353151985872127363457378696534517525225664964378338706632550699662899754082782608153431566292051183999660068940146390303399529093073240013483004473681911941404891555203079511160257496090504924634750389465003855765300903681168147182735913401344248299833713349363339482896551423907946930446086163195924059103294562646987729355012692825601587426595508373594173939100878954612934994851256344771687614389096588767598422066942406871695111734664199222263375062918084565732317380014210642048690130090484939459115996046925385923772849998194095132718821215767691420539561784121793749294055833283069255032069422755612385725664235362423303572722797826901668539668814540361677177680180957535475656143486257366310611233504853632324861242170779177395514737315978749707945691372768914880425889442447746882518299159309709863338249743593669193901001424046815688209462461998963727899759633359481495888211368488903600712824732649984814273128626628610526935323694226809571576035264445052384672058682344297061535481006950061290005539835621662926384298144082966075739390194575784345029478642046378039840870180816127766162357235539601033334540057023141694920823358386887357798596852194024001929672803799509548551245494580186016123029668761735064024699491757019985978142384479365504984394268183676905690397620944191128482214032772493924147254670766376576721094099176112177586033701112351665564843971894200172424517974372731115528575694547682872572923922704177158969252585439406431929074351795718857993629803357390354141838136087669757156870474095520349341894044153687844090131209394929833616156991357536303068955874864445585622309097465195023539645674812518464743797555379827621427469351776009525931897567748625062146440257006520716720019860682762217830984730659701325621677484717596024994053933484032373576822547904393802455434467308831943717770553895492871815520619511808080713006907083123071974623919927071324897914890057634184295795106401197022697338600252093366417267844239773672301519343099414211992922716018307374643994801209952202587276829022580571616419618688893593467435199113991405062673739777110578006328129446323403916311297355699876114876628529325468112417740538080690468412468644930270791057535631320504182779624878045433039935953535277278851765955846828160947188694584648101337027281781142268852884651790047039309831636678970767027713868438955232546309323521302691731966229424308407100809524815777674357968812495063057566422103872375061312102454448071572633922147188829849755647052097484909863612950790305937836882421260253081026051364333166242094526436649512798619880443919160563305042210644767261707083441854487983073462389495098103851739324117173613163811093791665916553344962251625158260976773386290651818230096275486114689931644761441952627329040490358481324268423852328683605739547435404968907644957487557062768115013832487800909466368549391719373997754633232387456363605979013028590154762250623990490557172426601418883783712757498790832874715286988735349655473141420330399216610091770644419329685858126931224721313153028761593394454536981971324748729654743020187197672871879473442997582238370543348629231491145132162027989834979644851572484173216375276695416261680466879132603063543541404826210835011652637224986157962089790347107224405557975537837559430166710761851217298864583106964917591477075684293177744011146199900745718497643817527165928401716626096461344227280669388711570110264633980313520590977448097348132161735986138822476438559231505051815878639481629716683608597531649976819277632824049325729300127433904124781388462060738465444159409186013003778482299817915101979861354100695721148030664353042215358869191466984073880436091689719592808817054124169961436873681901738815169512547438708236769636055379539487964616281460839768121091520710135087273979612302634303319226212028110044149945450329663743527171836342024836532753285701801625956721292223365959245846839396680179999969199767709845914658137847802234285831268684231071121599979689543987422180535242703186397904152036139904379771925313102758953051892358995823630876000678210071196493177474279682098125655691869158983015207185667938392882571235022560018932850677756377074058807888927226182520388401168250374370359889202526148281249197673893692083565966969229257326958941858400685780975331276480013783298584967999044589331580009856727908937877558317997017571892215680870614829607536899151225475210559411702860721965442214761832766251360631615564652666934020548884008341152255699127920378116263816004916383379446067992431424543378133621580522278049005173163198773595958630550468309357396329494058617934494408422570158500652928622634391293916896098577173090598741858138097940782124649462630777571164506320954541479673362707460104520619749037201509154326124169114623596149871299237279197930520204575010802981454905001497192065519439854584709911168811453338021735849812160099820546434971283730936874074270506124820663261875468577948980285283771818964722138737702863966216083780005702147604858535594449912593074627934755968315432741563063411614475990744977215679919433420409324779695763341542203124565248061287199030744796748268068893912235822393656899692485964210590020587082715292177307790302233924032619510817958799473474793614079864296464392509672828712904356299366921763399607429961349519051009253542095362671579700703266716011191599961996357392432523480161292603407572087953423502662098080759210060194273933443923355095832764104862593122708984812885231632222378757683939963065832001509984317358807394120609707003078567555023051039219601815252371041764941681660503971551824734002274513595005249176636750437782527983558187415946389371021429698227291984721955526022467301877321915182756827468162628900894564485114106712690269967548968693238832794250577317690770005763687388997941918944808880324872629299923969122903375554678593107270265383905057643057268225069071131543800707891127351727818916018180407609945692102700168686306854864515960649195453982328942378762566512914443000244437581349119984764294690287301276132806038196557496022301433228802024184760988447266803290125863658802767777620217237370434475966820261795747543422298857250440393062546993959111695164004412500092479173474467840787608409700697911059196446753843156778366727095129452266246462230907946232722158827418558647602717760792074627130951896196844392865521100170744905191686076491678004164201521084473264289452318131542302287533093757994172028820585415883003237279152704078873502692311373498060131058017296793020324276723981612961711401385523406681443937886595416424014394967309233892554323901455393396097501083497101409368712584097416002013557281817565341448244478832924166934843769825371253367001398549705459699392873581456475111278620855645752291390655423097368776674357350406149286967377177459929179872474020756076136457201577230147194154107228367074376852203567848450957883129766296210373104877810140106882943258770806121948652948971849258482499267530142183027640628671991552614803455782536180271696350231015119214113576856905146614986934637596354388307252133288688324546342825113346865849807141071340592553290775424548028521435021165005926809693809444099680586761959914252138739363435256336928052386437702219705283530737961273508988793109422750318368164503500910585047700960875481400989630583679604729080961921596957710077229798107831204706858272161589278766958679847482940239949148752025174436182973178032619164700986480387248303337386015493300804736260619060622314522495141656831026561189152449200390739562597931278862679601594310366933507057739759151772539651380466601070009280261240704742820146543938335356077017257990939134935931275863406422038337569464693239889004833778642146543888691745271278117316501386151570077882168135563350294957077938293306994711563381206412773569287759175582867891209152999090577354656919371660331154239675944257171796812191674245398198422402895925284312321826386730041917804511944536162827343874957343858253464137679920999396712290425475922019837156979402084068274560309915423595467188531067552489789761823985357015792634183207320848664483617939370146475628854637880319568368204489312079826883759388345301011941578081943347100590382529992498820828632860004138335449266418581280108188381297541191126947626644072489193621001984330943827607886124687482059146272699153869473764212946123726367071016937873484485783467741880706750114370997932258989912453608904608395957635603092867789968891118782783240676299339572810925551467522523046734253230212002743208047905946649395925538617326897305296578865464437737473374565094708931637117797882179693656063835402501702045286241061643047898604780105856540625830274353792966032788112081156638869895675526345259490153886932119169882761840698826378279951492547551091756112092937241584864593554105580886117070216089562582253587334811552437615326309043272579728161457851240785767688440382304182471663519342314296780942856867274804227455873576370975214771692344342461264977213187807214963139978723032384259031806576648797692274714900668960233302728530292848358898880903447074109768445622280306052499667018142322448204851310018045793035046424425496209355493719227664522475353611159757590060456035592602442554260658621545035028097329340514512281615077334033051576950890553847507695861871397761877100828937561274031226667752949216031002354290338431535078910108968413998059176620020007847854156608402784340599500670083548486502853742215012353497247368741685938413628838314141659507437627683590741173376060173596317909744854772113035540916158940866361609588919771142571811171082015394549383224455321191032232383739840434301718865910418308742627413817693275567920762961829884395138549212386252875686653340470721951873030930795234403159579933065238568493415261352688316548098289828171721722317795829215461649932124938001674462752231027051195147296429063187425884599948546277141361296968258837689210078108763277830519825437218050878869482064274292331829379196813849009660093099843249277000754492671817854990220724803310707495985179079829348661161017284015432742709695994851129570994602423489521453140529462301485298147836006374718420271470790269496133518973743088094290686548080128212325058751639487303386937915338863037628838581509812047285941675784425147784599609538852978666768926375326320402582069011083496353479178745735096030524378824012784394183864485959583418118138652126641488318497365866774597653703033073028919295745363728095048883514484658587495155144856340659847814522947163160608322814471544675603153363197551362048191117370308412053792944747928190528540860859144468174899490400473334744419173777245641768399472748520923333895551571792615796755551657310215205689111352303601040371057936191847658963252278584373385776928651998530803006919812956207862678050754940973195781767363395124646299925975879925217447728242890358892164833957224707677231446467569066926305102712896929923093167331320823691869753133514343181921893747416686685759923084121189534153848271152377384466334749251467414729767838103385798507584226225692899257886947162362669210023579457535612753515093626227101891775885069025969655789579740146116312092872730414308170108899247321026317275489765991704589526681933246144586457428756593542814988495930561122543484577454810592620117761283166946204463133806511315137934630588495198049811366542015558451691081158641378354433112679301166741776676893469378514143388224878702497475978116788929605283989143413994626898089591561397429079718977670547320745506416346739044520285240137269693732929318846915887881049519259946456239314599695124203123341259661897896062549833465266905368668575889244089798291877711973810700572720031746008324467719002444648882432411507444394440500520927859350046005478709715431704702747179891816380474237748146527800581530558694373639906274464869323466416807440767668186152702607286739419830837193591169594058151401845097310985705057851107322993628676474572806424563125256022498774605290932530029356756909373991052614744051081131836694398121419141424514564269703868266233254691404985378404217422467551852643651896828195110624815040383111182615069892597778147842699169022682658439787530986041123500245554526309339203430095483556286126598767585465526087631175193243998721126566213542848557017185482246674116666727205271908364971167182578070659508039873517344505611531508579390145480833991273363548838261474956125411646300624989164009554633089033397283455726545299986964779211113152528670770401049129189645901051868864809210152033104864784335717349980310344065211511042895618858439402477253355676832983922975518533132177015207394971643278099581009433290337325430660737850060351019817509943732598927850824262593450049245570946072984590120412623591873983567455427538616794565797527511247410482244416969387152493963352666344198655029323389607611438615669300704052928577539804898944369155546452393322863453439052671435633545699793606310638103479619189039228229792456791197515950823678159442365992591548036839787122403977911042424876321181906861513497140965947488942322935741752057174231918522871823773799977564800595705151151352967679723343706628102482543521244151977808568830995325708405085195680948811362618027739653564961994655381228451045684490642807200567438711317781539993418981347548753667698915490991150156100274154137385177836422779463352487938530367501516482472925770911770634296498403385156701780784264711345035307317262880341386007213889450693608187293919551327401867072086569106758459837889512206723794131219220871020843619109499145951330030495244048326603520673583744503131353559661417581320199963120424353245580751783104583607149690613451997777320463190760410253343983392929745433377532109023624438458355047785789829429594992935686565093467676872982793508495105828708675889864831304721367900252454735256607684739368879443920018844674519937047604377590668893972573425534930403888504342819604432752907787509322319437992651296796098819400484346463449778682168555523799707992182060948789752449787809210449784315228480550853105577156086899482685844958612668298850602670394571472114334926929054489202204812371944798542364252531812336131591944360341334127983013012745828875451036125008889243680849101436854385578693096873736408455750683695314235734712190762561422124748647586315472413881958767335984491979975557278373611587767215851154102065184398929192868542344933277124915526447009938247979076902567905884174681764156952939643896882236543813854123436489593975403243351551765792773683931848054946767186536145539763929155566103776103644999674839113693581348615243332492506294699277251552826968367075160037731774662270973356949301860335316218514994222514761568461649606568985266510199325361640151423800546150756044944758435826290726298223244775088491255485829106201517637356224757051425423569756635355511968544592374151407968050276531822906275013459050574435580759523118223266012272615871196432046956428669136173986162662648693309032602952237417253457032268244670615697013578884864711925053846431148628436423904608405919347540406280153023358429899194234564734900782737071242057155475414044594644012150091738522284707821225518456496519613588837013169144824739982212264182842145155047010308549025768438085570261742885773170405335599377138310274928063964724036640279022516298290417198860504500155578530899290811456030721995176631373399270325608810842850895279526943704629184164510675163593099979323289517449153991159251503400271978207993057140179002356291026106009747760085143835637997995650531358360987626912122207920038784301764368268866594860961334596292376698346680421911262432615004142767822770131865332544197966646706742588729687543181754444315968675713321152640825004990099985224658890045718147041366277985183438340294852805700044726544173088964489681980905765378088090497220636437483937029938954531723053928235406531804689702556769442983748101777754249836823430622493020282793848678863286182173597419246044936232381322605780786208765788867671669948925945271864477786275688290507727910465489928981706096359975273784304462398285415821751776372052619520053483391439584387893852313495117398259289769361252392421866538053454323535950307207115657236651493044713055017744286425860637055764901767717785416021629303477011450952429337713045831856766046042750694636574077824127232164435607061329954209436478681036394021857875470009137624557320154626955091381031938903535627700009888548433051185608278530773671311014319245066393244118398511598217456297130887586560138398688243651127486974430280988983122091676877929119698422041582890311734995652430427359641315233287582218207208765838843680422425074807751179847511535238754347150151630401641665744027883751056757950569611046023840759068079005908164464275907050841708697440015661416832536774355766528434099789766315687380246091238529734015491141474124417352217135758414951635190579724271561070948958292525387672681625262222669140882670462506920580910612682509935810226329109204728895252555945689570052541202922362715081505467453532311389053227453427689721590338852062643743620667835298048022419080831087043063753149288384865281354880766792445183484810630294052216570861221975072878888626549689563412319605333608518311743955146984597839517339166723661324615458681445523373455253698820567656955221384713546439073208134809800544603213872590707751535800143101163217352271844810275158882946155714722739078082405855032815489743033482229921098773451276062005365090782232913932294301421394099245674398032776523721275532317407492229112722295766413446480362460614258049239682352655813061328838088596304973169893474763778024695653486740213583019432655813154926652390822805653283898098669559490876620999725835370782825759761722086312144527420440079444310724582715584021892549394330112387784095387743122830829699403556833737556940823578030506573391841793898890217102527087992382045719467486095667404283121337664428747573104315747296120393732659239046050775372944057606792142078793308787219253307452364216267980495332313141328549571899542404256172077360888563364509496497509661258486180127493020008492933354832421456904524311413317752442948488819118966569962783924855923926077633166072532328314242732956145869978737364099322278295803195937651801423025537729509110468496494673488604521703139415970314298037057801600628318075000005946018471567094167745777630353742542443684197871580551110784077008094857064294977432506097014422832835816681216880120200910938030402640329004334674214062867353925384875634364605115332289188091605258260558103047916983151716252120735241954184132212892841268841357946027445972312892766997638488032610084483744011117988580065170197165319718737001235963274642103076284396460046593079795965444943920523421191141578692070564874047471982963227861292022990975911356835853175135715473318754006071321006519469998553084191973699235975229231153378110772116101503084701429528853258199931231754184004739961909773586666110379589059888605040123092857985706072969437917367865836222929835628989185225301566910346578712194570528317215874885551626436173489091630537691009393333113239910700372546960379206907450715509426399607715133488436623360639954882298990947666062443435909840645133287669451741697366338212542112683164013764995989085840794619456223572740335135287054993166018920397383970976057193916047317879118291046501588079970650012774646075324405176326715549664301127497332833493852641247172892872507491427275600164616315624997916977248709295126331876681655471875999561776478183135548982050291247647001335807707660221608349694239041638057279923071388770594055313648501614918164525491523153232188025699874977454408751838431078549378891354061077392430299285449271921614167660002300362212207209503858393210208103653646713634423792268035475429982765724730530133413424386356636160275249607243480107953142655239230243007525071839713544456448911843119893474939178194483471264049012706851875419316648199416400236848347874272605996770120407039540320701166613575833164411810315092716172390088507260255613989297341544812629424041233769662079277119252267119454062961678903276410539111620976517948117220486020449945169325397649088022395129315629458796183759782414550125289898403235394627285570278173485448807203855332012355538362132521682963439865032422297056734311406775491077832867713114276976133542404818801640950870649284965054070430120511667897962591518143538095027134119156621643142511608016070895496672379881936246775711890137841158248008137332511058889120648504798782741711135280398080105013528739177211767061277029031769414365823980075075241517235085454795406713409150404700918870169163648324932929529520953532267000355774257167278945495583925129531764827388925374261151037462482176718415945100360397422113043015674763870702233829170543009790425840172539726450834927377895552648234581974872872540144734764297812932184122353355493934567140691628040190929004197328658912366093940632554044062209677384228127094207003415978262872063579580490077819944344134156240708147923836430555448655534957623262981376372540725118244536815312240717531825234788667040595264379242380537842827740764184209802083276344338496111101603980135545320758715009713007470994896845705146167845320050244970903433007361083645406849319847270687101380497733176943543135837571158270291482403529501451485347624311701885411323252409955994346211771677103874453494572272776701587248701779381093133551881589274580639468746227801384224782416907248865979222018237213059481664709898916259849620822324393557489458138388630490774102847565602585261813843227295368443836551759038865807224535450036705575565761725425647630575827830636459029041045849817927484123487881783028728523613420930074545742961251750197219496214854313497085011954706970120313198752566249040859010711173472849812567244763656327306886290448016546770411454682946089378439960968849781007802563941460288699369033258011638723772046415010310424724874003027826404424306536132721571581376237612634128505730925527057829245025379643532716683964472831702434683248614688933692624024362120511117547264110593725550018285603454038359854153845934662634571177923185706670323661967434949849329963843788016375209448396414473368420112023886106007475059481929737248607671813113125773852315187048025720895603765801511863010516309444205955461299733016411514663981294352662731165704679078093475103034408163038419490603812741760807869782642646622907790663655931844417102379229377097609196466724096367241653828723531266856264387501026357440724502578566736055004804343690283356191557502500433295245374342412713658543565501443064318526553234999253806342687518148455261838217062338468833993503208402552318454471486840589798305694981311767364696070699006248559547252843549293249228438154677056921326684366025926141330176886656139631263048367732680507178331776010439883016910502707085248487196530716800397042444919277089300905794228734390919885179890520675635966273638188553815956403460252283946010042979849799041707695596604428338381659994455333727378788614915269211805460535000687449447742760575403968121765089522872601877022800712937830922114075005923787576272258331606560369053079687511373558663799655260357788509398865044770043790479339407710577500699614250382812885492211928812456487511014341860202625092269640518734095885381176568784491284131542357269503017763901286919104131076443017026653117813699306184884087699412732206697731558749689242058601031646965741217904411427122294244812903029023364496712640280848038661626542772516758494993520182339264611567533010384884055593035849251483528964138015079845748449146743123948238563284371132849731682901931253802087059287000307812920641183250496869725019868043198012374327981067174993528572597001718850732834177767806881799784707571598293520703694798112044947912815652199526827316188271361289832762879892868275945104677908576535602014779886138584203890770966310861986350276495953295286645891438997361779881885642384269511518409031252593329529948997651982874337415686354768662643154676512765029103794226107395439246474748748705457179463357986971256726258619769369516432962542396093068647845803313342334394797854396187160241918325059730672052721408747981510612051902987110985871518031366301220541745493949745701578940622571192210515136579022975190338211156914684420963771788841740535072240688955561427101305821425969421016224759834634047517356638244414933462024596204914489196595699368950038689261417812341529766313480762315275079093536615256846797049751435990329471249367835518335071125820684677515656500844662833066153553999914216108857002267016975683683309655982382519605255585321238500034080264740184031623178673999529629995330491173596869666010168794847445043543014659165098975489562690719607335278546371789403783166390089047101838172745930560059513347008374819141314761221323826190205055600371933573210189796665597783340436329579855870043465192790214770594381918332471973287205544397008321327266383481206712877784248771102683069868217272898281298004105698826318426275178157953017567604883369690256726178370324911179383269955626057435878822523840405987890311601862948799372323311782545813068292133330807400644956997940572013168384923962078836016280094023904535800612457218666411454049780485065361086177133345136118711292116978652198448122060799804966472776304823762197166721686527894660120774080092385837757284639704570035553270133875995002488111265565215172549468662751997898300493612677481238038826847397065321724538479552797891311961501671628452938765870082604693764802740385807479837800810462587852417052152244403811008511620281842761435853606491408892771098405553989349254700855887241829670138947886016910174020863547124895854879029104554152081085846031186664209059533021368591533286100298447457713444120894233228953110828074783924126518624061582649270915258374542066334020933323915093435997869498096271775942235921753774441778650291850437920937649087359220501598083566139773995020690947512567561525081420419912548151017621281652194399122331021400609479605570499490890585155162009615043988176134872703815435502665139857197727687924231125452509256960931738875783642912729182974529274415425478760285548834750899959920790908016375010043824436168933020257541361370335260459049153466255097603564061509333977282572896582249261449297406040991151130703457455190987984489821942003813947347826232757647197984383219411970613411280906930285674027245171940516110054642975696476657133116910497269872424777417888701256519657532210393438531975739733161462000161024720903164497816774502417160388068150772588277835778559851973903917084927680109911224523409978750794179561608298357249515612783553123384829866621916850594381386657917727548630484662665537607918820318364578529934317966201802762600047400189077921184039124017629880294645056994113494962135635024099537122262594114041243329980252219857087736753930715931251665191947818169940828733072914687937108672355225767125151527659997517072509458705324244932800578942702260741552849199100396918440802203015782806111083095985349281392991021305979121696766292394223445963058639198844215987560535104866219259675518096209607236910287844628265732428238680029643097040796348258485419560519350999816144277109230237720675725562730543513047689641142077758926690468633832967000319796210600789134829626761613046133005571179516530586500954351582732988420140280911662179550231293192378709644195444955538631813053051234402709356012042126334744506056870110519626403090360953891469972855287681086086574430365554576999289880257498361768416700594819102819317710834249616063549273217459644664947096530582552809355893185267399385355036187982474335016405769716543399407573169661531706866752873725060174550189111433008748344667631425960506771487423287034859259103117512456547095309278875780682811262305658227356647662556237535186686148331991359924892781308854690999789148168622075409274195745846200624955248635309126506749601222318723877393187946121050462023673011206835282729721777064968017658437270400861696113005833070660676044089898860552115647198436680407107638271123434611422709387447404964196651822489804305055616820620820702837128677573730127099648242953277375675972277993974835846321636030956640404558996772156612777167503309709537672261819649448724341590442465110091037822904279376620647024927446849837261609636792146455134785587440590900748531325552750529904995100939304680037298985786514429756617160433984345270907196305397527596636660330513661217750176163376385324870623497817746049274830656010560958325422677540303288329019406688923512784940780955457961758819649836908328369183858888004614691055164872100829484085109813048596934461977764507493358611959656228108829573331900424371592701496117727628234188142876262292136532747894667291394333593655162680547535107481342763938451438143755830512991519970699774287252990482526485882957244766594006383856263705227748093650705460208197097811060666678876409550014592610177691182415549595576344049111007195438036634846524892355742607310915359948290417117844471555335800382206932611591091122315150243962512223839184325389848417550039028877750177867557089341633320756963725844648292029960929061240428070423380402130683686825232163141432190280367451553471436743080396180944352359960296815223463057253080024664746840998347316943847368637019323084450977078722932066295007282271961776930506152166651143131724488990501507234157081005031640975246780831573659543250675073984721728970347723753121397288113874626234432978344419418359082700650120374113434299537207026421791804621308088389676946101893103388530382681256594770347356590851463490989448908997552322107750741186861765449683459842059571506065441090802224358801448032991753471388065358389115974812363497748653030113371040617246682121561586834248177313774526638417602675936036368805654935230551044449518595683551720871075243307439352826433659519242005826311104480862443431600058361489926813575358107794567539280257639611600878476659714797925329516503775456708001376454620355314058147039452010259630653175922951593441439799132310366078576790823316847747858468337611746976164535005977819375496655025541716950128911584892284852292612241494302072383425031751266052264028827789231075497999786534121400433030981686203100922772043065067082440710486795780924238746281412474192385495073080223351309793509206796858308663864199421845309147922552068041476444959147720818981447610684617527978445724664955915685779447049716425384028580053924180533409006457840336978102873780281388872523723529235748977685117843248139117133860794532635912667277946933859470818082633592439939809901654065714647885474787988015279762498368847879383261452323506694089538950130541980218548131421372527468420528249419686452043184934631809879008901584657998494668199343859192927130383216344975037245569237951445591638162630788958443051341627432997049074219190855126795026532580802462321516441821602276935195842943430175012468893282719822529058225672646756444108277628053057185444714237855150169908183046722496919261222976249881491783186844595819751516043285112899462608681251343052815128870099845779173527649487808665740137016608719869842669612277641765575507160135342655529974281950783479415745561356517779538754674762215877039569844180450445411515672282770215204681972922405000184183159652462460645210598160003279860323173183416871846835654399207230402116377132515754604521239139707019011637377543430114662807217326695022752596728349302170231269204690692290972753089942711897024992909817986205248400918217770445328516069805181822058666301747690627317751124069135889677283275752909954059944611481268206296273469215204839584247870068027395706102062850513285615072454696469404960896564303972302519113318677953383154635505358536627104116997066908367129408937132961418987389950221352276278304062342333882003954834024249593223727902411207142338678934312972102465027270754949823420285981680937063118437424071357474289587119290761686187533031524141224890775030283367049234023476751657139436262993979473778373593007331031974911309424181519076480935659131187633835262369790438663782727554429810398784605313751011016625768451102419305791671315118444604039360076483371675848817855165438042255539573766197030363059556857030693496465404575254164511831388749871142451412848882967110954183270987737523917424744700208970883688218086403918306813934825359984164907981337262207099520093737880667526906589664151284815357744429212937420426266212178544077281565911409234820913493238779403845637688416394991071829179717528929192313663514443900275644311266991523894042952707372829797680206068658126990969705506512042151764600550560079925474915880444270628445006854008862747972866540905978661396195281040471733342938281271020331895465719756010946509922915576863256450801880962122853605294901555003824780709844437649218356520994627610543501996461609964590647301806216165740419861620551679885336703197476431639250134569686501973058520184511034038863066701638489620095324365040178179382663810930717947410752399272675775331202707384369138150516028686867290411361229465691393750004543857443271292775933213390086081375581716118829334852183412224075927903057672209480358906252209504967631703255178657324117195071503979311980164315187343193275975196165953937465426871310198285889886008013205532383754411391545488489482605153863165336719323303821771027247444242104952409169811673557717759934190766174143956146431163262528114713293444230124293382033168660114403744572346142464485937416577813030259221013519338165486038123595042920929558538035192149097129924469796569798772822793168505310525933296804527510876639213727070106365547924204817829436021802262255727845103579685734041570999790352151520405352939536797393993720637649171786977446630430921733737651571496221155377258374122561072643784767809723428836901245126569781154298085624309918416718242339575864757798979254939780063547409141245045278568193105458554203419056946193693295602423740576060724360231897414053515439754413034819322068994810900064985954961954010106996375845442604456228416699984304500220571153317409684677101139313973493588981999204853900948513418905264150302510682340258408336489223672126839287542888632241557144251971360139701343559294409065075292316290611897681535078541824369974061646195382730387718724020339767594844497735529558835684746764002421591809319520731939214157124722450494202148220778166762833670351815090717589616935775439834088747535975871214942078529598223388348332935681987986504279083236166876488298707071329221854456191902284006703752336745457029676874092262450518488534188834488576850534622074497812668733038471785830303810189633745458040256681494761845045059928260712997038805676612127858473552673424159241771722448509936280594784234604999493713352714497252270730492484696985613012151075779101828466225740436396488954534995899042485500009392182548244737789638264638934886282178524848402387929810238174484560037273129005548529737575267416632577306092392470431245161920361807782767962641247767587643066335284588784143828205973912836998123365591921434479387336050499752605910342788738268779075745088480432981181090980351713665499038748820237598946934836945559237948543533676795116471918727498306916074425513279160421061201168558844127966081486995133593430168597420424375479596429538425558355841127626268004107759670793354956286430444111719772311545935758428965628030859898569819930572536546258996501854339154650341778402603931069620471980112450142400441851003764484970542912869937284315039234836680938875867109038908336401011594516838622695410440722903982986361497344591835494277816924400390546148696951612120586736810398328252472178132819826852692154280131365682159235196616348410692163086794830090919925985644694305133029778601729944260967840654448976645561345607234325069483867890078653516622130555717252499499192980222585573592298292070215991038330096518555751391728352426957006220021888968734309706264563178215182570888027471243732089884534402936138978545461412316256017686536477346762354901274986223338857243549735675369315009803216051058686779996491396808938884934632980974665798178478464496021208845283836338960565312923904373100033884730133252693992478055044636469484803339683071566413474294560330371874064623827648238317761901005459911387418380200562627650737706197821123417319666637449816761378641080907336790531450087888700953990209261595255567024835624980678663488960595981391173167834148744679772382717495257765956721238393502468644537729877062656600395335161589911864627250220383833561384691718876750642669719177481776763052465810761315363361977330492319581021336667614080902873734117508414391274484204637132233403454209042766540751007382403416306761874432246911123012786680113980277743164372074052824336434241560943831231748315337594636978013716406881205553317835680209523399309271151511651874227275705311799209880217410006282661618080255087835322218088671331750010719463232797151357435155882652114443086238555388105913256070584731637314091909048553872459880294161906223292345723148082505253213238161878904473363991320724100606625567087825484823685291510787652638596368150182065600801372928957702536590819366451120409058887300302469906351839477482935522187328654182809116621729541780808192792826590264635657233425013671512546723558652869820110808791447197695963781782151459815843474814159261478407173020473669429856054315612275038586289361591300107551246746529256750979090043722112882119118386881527722130875555480798119517834285763492161660980968852606715882389977651017787006676877815727831021684826965306911015207816354937080403310483926730030164046987724673717568963217342994199421050121239364836962758744409482278278112286483425832776592855858793358315239018861591451594327223964666655295677157616915681517267797632080029337547546626460002015304882711858725060133980386886391113021046716593294501564447430459759953082451572121464793824194918021228630341274236168321343978976927758297793531035853411510605206608823618852626876892309300846392970899357118869236883344811742656674426611639975107048884794756655372770806359380271503453826194813308775113393971939520309790523166948884378226121619339002069660568030092445654156808239256568707632329395977832013743849558296052469751580374625987634417609179374581654363079746259921441089546090929029348792615778942682081804201448443474707747317504882415487231540759319711661430122257205101105362625935497618221459595034940545386184408829879709539109139931155094943010915436784825526258571704546055176622180357796642203609197683108662539710804695844961739849711003955845155279520263382448810016584612350353440987333721982341057501406557205169847846397862599504381047827446744035372465951890418832396091099889317164991371082791759801473878154675501739646964757315494959477264700480607077618748546166939899013324667393891828150567143101554649708770913543228504891486149124140690941422973048768645807641252140178931852376260757771852999023918051872836716609492013766217367124561704763237128858267903279265373035886913470764744638237314431121399483196258050819365763797460985869162821215147619515286492313977169892821098898341449734972107624326150369960062226700309883546774480151355699188292732309447619152488784444193112389106346785007658157427957148738541321374686345563356830940076612088231486983777517327782889205611514356914917891637015265472352600441542131536524648176077236753220724066677874420277327567367689959382026133796116390876061864720793769022746801362566714279062976716647080381117740408336784538143858374385623716054778963169490518537117784809060412001106921958653363314084693440176197359457791373702020513364560329902096113752897881232265927935078474165627751810064317406810577495249147150211148790014218669852052194040952951484970428440875966763196250969698785925849884865670520719356693828422041260764624222287914514476659583076419027303578362617791620829355007686754801061591540790858330813771481852787650853707126538533276302164754686133043256626804420981310387364940017734871354226279961565620449948306938275885842570716547037138000907741416437095676228011129035088255075701408795712147919893872725988560568606585445294741785271185609926211717355718483613286147857606940188384471549452056950503990649328258277060236212462670794536427820500502460054096296695083774824845513302601502955345223713651039737851004936543884172856628926080578107638116679960850765260477794342580395042097384816700013931920820576700021098049853016623546769453183947316574240824625566319667401131947354299204797762336639259261555753681084001163555298254399914483097552650506614867585933021155573174106711388317035777050814466865726010135167811889318696344671184947628954785399382714767591575751610817855667151371694290276354853813558110888290121836976755603845542001394532009434229862862124102784674963237516934362625592538651013541407372140054702378506206780684766270478001664174700586742560062344614929611262012493516096544892632529881477458842749239517129538722324223207801509502636460306311981996556269898074818163154361028930386137491881499381224129440510871089137111539120326442409987567882873545828490672141998589317406641924208627980809569031457095799375964200876351353595699983607540838444994316062579948414308353064066033944264628078605363834881249847074654501036051317540448476635064247007353449021511488101213622825588402748849885267997224045712267800950877125567298876629318799102591216877720999248132166537309599306040363622196608198613082519762084373123247148704477173912401757038884735359650031033559245617769872600935706607819408011234380179711619491025231251088876823760210389068719829790888690770061720812485180243631787120554188011282600725520241919057121795478089324478366423169867774944001146434608091825952101986688255125834507621589106135958017703397497572722293839158658725023724065542442670206516462505411014044952700833691637823459390799343516756563576619395533838967340827116674198220467062756341051518602220558082962085515827468308995730179646582118394084232312107936693706994433245560941145245476006540753004165160965126383529646470245974812111496562993200809889199064577141338172240925155492697635305565624354996653383304077408024303728784851259339765433964213136642962051866750064269361790207059583089885676633557558104988769848380107637150250287457323905971790050671782959841669880746610134405738871442396185656360008170598377499928600668878971053692798866594196118910037800190506323308673939717594885954903750974416698805123235028784449665551724564504520496761708788280707577411681532142169940957794585285112792740755894810180252192094163872200250919868761312553986542879438918945113731517595121314089555295900737676010813005387988121999025979843610024420165479366948145416086790439907900868673766768269311563190181064862700994867950760702286305662148534258400099740050649515581285026344083167299475370550616720598085575138953296037963102442704296320628062351431761886167402168361653889169222262133927357056229800706753277204343792969251597071099313031184693992822788416326429819541604334959823142259003229384833230860835932102188554584726961157428731005303824765010448787783092405484877270866262929249835357511257240695257383712998678783867203729862389748479544182529617016127696274698977354768783322953544530146467246388677414728266015740559716945411998758771963005329593695077453620459697763852862500670921958294611020510182685816724748786538409649107889302204850576969273890208085568650491309957945903007778096760472198231329261524219876318658224530863327454282863412844923997121346266139744280578932734790249170393491120341028201368953946902688328178468040783512931518585452160921001940048134636635072729321910267787169904432719142440835118853006138535340245240725519557232050755837541294694188743876037383801383919225263717519276612782627655204746115579634363526208365815756216907547418493366422428387494450523954839479401121806287248638300363683878244010940428799763724688060845798133325681996990365956658055843429652660729222555689535814673712255776970185299556015025569163978746756684615575466837208564378879134211839680217705507246845638741503028920351425093452094529250718900544687085508426492094516366897366349108771509939311596696702869294178083332100308790722159461814433447374558527639141284774840920793318254046020338925408210398693444336187453703477587514171388829579242196470437354517087996717275700332332530125338050999511393660565371824576450040366964875663992533395643195195412453978733518793591224468574368374124743936365846731999524674390641175422274713051319126488097206969301070096631586420042129714033700182058022155467931553369430160823845446845073863545094654708079674416406408196931983747673479071483628240188934685644966087518624647396467270486222150351666073967476208331405313955813554558790856274434376179078020197692548671653509438036803835501311936081375259655549132159342540514634264462909355714752284176590139989266179189544706065945790865987602114548044070374046932211208403051671343793200123861285087323285683724925196236688436630251575521131010767801119963620106217957101233939537912510319833667957508317294919978540399762970907918688344163145655747909270435737864992998396504303878663576429586750679789028095588645173207351695279454929647921203763749300892287336826922030763535932194139583212580163386529044022652276848218499141369528776903928782824999392223709372690183466619488835083719107146396754107493215859404672447130205654179216841826978839664064034726851961886154886328579129869664698447565680807559994052902130347695725487790377927101594869234157415884597592468642877366778971350826683935464769960777830697040648250389492026926762124284752714252602529576491649281151742491358003515343108150732362837203250913561269303669404977446172329916656491285071341977475159727559188361812586307075646583396638534574178809525144321296508117320273870168079618868908393652650482209940713723598744158851358921595518330608554042283525434905636481464170629358981924563748928521135082657405286988903651440663766129962233066190027514433631595811291635502092355674941296401678558836797476689292040253603577432014112080319013015472123779654941934780574880501449357005845466070868167897646748652306851600817588084498862057693177919599327537871233380621738253347195225362562213265731670702949249776952356949395692336098711707664707048400331318298221902609090793693916621500164666585837235868481542247538674812644177540599452728758712112744365822120231761591416930132398083820365793857888638129918220441088565432367539216024735451942718101995828217459509918338959040463051920447874576822948723137521524583852665336665812691221123524397230181651346455418270213899644614005796424084094682852361597974123592430170604488073955034471482390933602378212479219661471802197385670501994176248064834292365544107932016242890124873198198608592466552846767691944337449891697700095179951107383383008125980476642594814631368506762967963527753925935354755956908539034004590090039319064632822534309035218837595108111147080724357647970986994854504728649999878847418978556959087768698195850418635644918542072584061755093710033978153321446902771345798309500909116672323560458015496797177265384887561890215694892180917161162005802735020410228699308967006801182124657657770540442564631477478050778646833971810229797392304267729597715304726740453746834824230407789281514511079601586708963718171634610917319547971712813345048510870568236921807278860595478419012611575339393124477057896778720837140032518492360097624483374281682347837275815196472470610927237981427847660566043554552309847884302427569267587268134993881456966074236821656422508401160577539257612384407899962857526642687217405324999783933890503821423110484354568131408937400518322288243323238602326615272610803447505909135090383269342430713176577934085732388642881041225212347899034908115774662724555662827661262641372965375268733719061145078738275908399513745146267665021083361466454572094450950931635995200972468706082943166591144611901057335389789633337543864832976746216952210917349788302387965785260609329519810627070370207936056671634469869538654447551607711670576910205100764563570151425102938411093462279629160591482725371775735198330536943335100776613406654785174140213445257610038773521193118661684833310723689101119412941290005974673338458357933532345415642853604042791828102948800376427260548620479354929408945724632794703523003571834077675169510710409990859035479888788267752031308190434481480149226395592534592331385627049002734226731011161539764993045302986164555352539392675662222103231702387654138767453933740659977093868650918637536568959766790338313576262147546106980816201908615607201588442336341359788349470175738061301143297480771844965477343634673173261701163476619841566631769941521200806993698451872155659565128419617778722892270376993461928461125816311573360761385467578042093850553638856011007831956497597050216664077680092993165220563996835118794682161287414377628499997221030393541248976007631650356959789798641650304008858154706306628371326402615458990475101032698073053126913979300650202990761056165681555154559046976644531775102962762917139429687512638083255416967732404295370403324035010699952016826634065981587096903176686979689047033625170435802689157582848003582102472710821792815932268264937205759286687153221131277201405818886497372057382838733781294723133926579851254502771942349832008919693061206498054507504459252805540395704298315656330003301600240760319705388735216523970790587106910157525579887420071833659207544785982456407965649403466018719499213880157011985444944664952944893141356775544136513086069798774947987736915786405644334259671166594829657933689527109035414162409788224991493900100125185765178911772502391156680400450973018318693735516260348984098877199530061353161280181497799176076508435943285725473511953584194931829813061517952640239133330760529646201620608539426280069161486221433242560438118869781567194276821118746132158670405725871426741005908736752414858207205833079578931246357580509730574211755878539666204173341925722231350009799103104907417845572351473527391650005451926077289573642940844046693065682895245543695544225283883697399826216009676112077385638663843396214304002605139620987617921725618802651406471174192561340087427735236191543089227933280583131661119337343669408911728567369889001363072230017085421862783738873920125379806388864960134534016706648046521099275200833153836557479783650747465902055920370180052098590070747703600603878572100746614299912817171235097140433884701101286357187481458148747486808931309140974021552732169341503181267752815738407092026114768151564846737107172091999277084840713037123156606489955446669563282469221679880177402204012132653952814949486559151433414521845208548427401891622634461388226712453793961621823476952078846662604351230530725721055111204259281753750794288925465212713788234515699905566890588537794930710146325373383148206759864032839308184981543389210374685379982828575172760111647878088463974260648225209874857584790111127558145266928689252752683086394947698046667708242054364090530516861956729397979146883351972647308629178065594951631304019292745162738647163510977365327305618055193778306325430574234726143619172454026380419909207556386013095491010638510218189472021540075709039863993399895512641313428983872041097564155744394324618515418032613613843622714059607284791992784395568733926594638365217433749386304636426854505643110872296152566997107698743392927862618689930983248645535774537936835633102642154592968289692434733804946933325193941023361023165717361162990261411809751178517906777585662389049871311459331109687416264582301055708210211750290289458381566564939201877136398532347358180710252195235597909792286777789573991933874860959850424112755830632569573284853789816499741301489409754181989757707923397214989750660304642915586029275551772333293250414554338749452732108473133052489014832057009814470446691011795460343314260972769958423503379155105755744712142459105797377244184454968822752574232350416807630470506036654738544743326439609462228328836465069823791493750878043479794110785867661411174961294307291183267628077784161090871664660709712299017524853893572776023164817419552725020619137820586501715424168763209937510498748426716452442592240524937342754596479117010079454303343599992389701159415100499594793001495846487860314275318949865225512120805327641707173709702699153371779832317960103867868182111924465588976665034418703113854532045636030094018213135967466888970754419666711187726163670878390608846011712173476726875774867239286794521244001901530952156248432506354352209499867392931098547941040523680309011598760080773230409765882263514200340745622701964178251524404722397523460981083565500361960154695369867594918031904726560408151213641340701936066426657797646063666696027481336407252996983360311179908834361495248837875675537701920403707579509073527576096482194912526422961279568723409990545061946642171718096805522892123909429740418845212835657764127086227609277876170065286381767217683468921708414030411151785308272254328416972937000965358348798682045922184635083310207431961165435559677263771186055012824358847822426582363508852077818674900322387385131221390865995892133726881925025518922390305708211847425361997648615501353936910305778453150500225801509361780016802716220189462462546037520370992107846211010695232059027501030007031623606879457915944344386569731514450174254133161535052934165470365810357066078208810056933891343079612124299683048635267114827221666676551037261646506465335063980582670093554456312868760459541465591438548065893624521596025178180119094731295161858660400972497042998277986153338354965147265690025558606027545766097940597050731051058888578784435154971462704909457947524476671636911593905526823170119460966536423102314382220293336233400326072317739579809907066912261984378624767268113409024950769338383399561197768762717325251128622956003275523470583769922937310277862369649600165768410490554946168340318717933817452477899722293373500625749601157906403090446961817954912850957597461404967189264569504040511193042917420591373661059223852673130709049278007204552299015891812529384058683932612767747440254033856883224401863616677671029543047488440094104952949704724776093786514953573335891646281295207095385857189455340176453032264946460498128833679225507964471169632492956010317702176003403491081757811337427409677274726553946935051868830625893530369811928363347649443111547850119706351011379141309640961549247499200418231390965204930758185631633823254546850618794042985307472189071617675279811079530895289669680895068778963215405879566399401952852441791332233652856714925632683236130175680892916940067733718148915719790018942934043441445198830644710602740604182213217825857466434976363137404514441478235365702416033709056304297994163220878958752877373486434227067692081032509092545385083548450982662789841068902191778789453649053257541118709862465433401424066994679555567133059695682673030904952955393306674769794973330950285424674814883753496260420097949069781547108056036222464212003234240853411072089478191089931410937886181155447043936653101443794070927661121478773735360073126398036079948995153075381607598533187729704662083648393927119455620579463526849285364469753411462264944836286312589475316933465587790229922414700249402221301312647079874762558895249996578490087829369749453610699728392748807662122424228166693523395638739246519917658112342576018937118865559719812434018835684210961347971303131824418815453404226248001671347265728155900174231326358739158316607362695755859033046592286490611159516891548919388272317303923610108990169230598587165126260911406509041643772238356719777974648969685819201126583428859364255211015489559618690326609435568685857355300934178803214654108368368530395827643959804029661882532049980069330848249774516119434081778564720275099885773283321855250093122887289384978233203273176791161962012123446448492660676621546516243358646773306388151863221953542916225669922076339771737102657527831570127544258804942004502707761693667962423398747496261614519539146409365457164603755218133010028356835105666313757434100604462542405697264609805089761868344109581043203066346194506309144305866239711079354479022287872157193613045418202834090079486105435873317221255193997710628153075944707194609722890899759671988881033200063228457296119462987048860968382623765494605923622963372061812377282850209798447113181861401110507866127075887360656368656564125579253765114361883048030236324622723525263022931716794726119015783761445732817998871675693419136045968162040340869183401195349500466760569523042634533699219458533067271667966106576260569124777555217447695010599832019919583090563333773109606481886436021854372352611185952186651977139420924380891388683436039797253798786909441775963404392702848490052234930222007709961080280352961537630250370547899101271351160533597245718972759880593178876114266380751764173092795641216343669710608412935690636877768656397893697893901693230318022332791808717686720018348499387245355683598215158213055427352779229308441379268488315551366180955405083840841834662837250420194688578576509209258280729857432737204546132464909270901103609075928421792635071928982804470289601188622409910093893110808270654134776353671426376139259014523843405946384739128884535615752249687461424538646097649322751777960488935929771521037313330518407683549560029157541607210799225357728131259519236430929218394661734272632266492762679732455436038789480047108545493794274957747200088764853927888364237905919817130856566511110007523084427860217148992341915956351165559065064369042653991867083360321212667152342236885628846465793144711910928847275293646334204328137754148934055288222972672953575527919022195330027699369451583947065192831389528917700281842217134095308041554458468649750699567013831248877535240228760883553281787744831251567457509385018846476109450270341263712640396955440915096484953050206088874147271370491939725631988566641068344184815823628301882520554645032646565259222828833530874043176414908940609154264382244973065707141013507554545882988714823342995514406551364216963614508390066276848281361254265368154905726519938540332557103513991527483215932541407754640767933107977855640318802714495039173026893350915705504356469806170342685446062460833716524191771985091866955954874408702652956000828059537134132093813225205615291164327110700780359507728484170796584718979818498123809844047118009437077900676740809221131203486959647992466397113850742649121757492815844670283617953778721997501292864042621460278389717165888538775941820897399999460193021706201708965989464115606017175557027645671528428037402797732636746805191172392975488554989498304945006413558310364735840521337397710452823653617150720936228738861079228671720841495604918980132971414485891608380796371842231250135756238958765904821057156610440374314221459748649178334968204018155875326766046661733352322450065810954670158950261572552175935262100748120377033229148882423140577291890216915560554943838826926515813857638753110231207290623538966023374360028152046535155674663315217717408761811500325965363226722801077938966026507273408337854142721050712159003714050882887925924118480379236624067695525943060059206949866656165972475993740671273922722104867180468155993686189444323995514833878872797412592036974017171108792563222613241384333241133368800354904217791232606792170295872018598706082919409647804569828927993322607196974563457726649478492691718994857537190373972641973572112324248302721608979892836243621523267975076541234111137208228049820673815973489576817576917697073082785291450589790421641062215636299596489227777059071762314697397383420177960525377477332867674573677166599197388407220295092591103530685393292919923587679021351175352983616439303747465964021858520073162823506339608358873247783952197945009629032125809443856681375530147266502130770750988333600132864629630525643251925935731998168443830696267991313865869150868891451587601274601208878219617281030181267779115712756932045565584670353847034873075837980785907156841039153649872462563845382779672114246079047632839128851590600174759526652161482000548850483297892501761046266185298626589250109432337503334489521369717297815105332922002001081798638320904412368771047193079879449463199546704365731638598791444978443245806167818240943732079712267741135815533474763531150782108441336357784579469429516549906276913079140348951527960845616328761340136324720339699504814137768819261159560374496199915715869385550401534437716805931399392158102193336350742373733321597270043622984997800123704003711293784425905586103330486921364552365839217372746403467554176544354140285920532003085373463582687405831602344632863610438311946697886890594551339298790621635617297671355606271201916343231986598387726032225129523804774811169231786063585600936024664652168681251631172080351436268173348892918578863565155933048286518451879834660688463407321687776639885541819133046599142827469355005449175859169114665705251839523399303624955645389554520188787873373921858185583672143434861338317032772327916783901988056044826002268076982117686133046805776041699576382647277909875100861315327686047968277178758736620068909024457715689495412076833361460040263367096404705964592665380292692825811635010785222313050526166349694247162751682924553596778969910746412026438820054825686610787143518634399742272943093248443468955074747940535670683754442184607632957778498394157819006284392062342096165325803566847608625651953578410661543491575168641557975718924999262781748117343130668643974260248221824774660124502258758332170799206913986633249253937902145005647112042206739364911955905958125123070029836598950571955661328373588323976756735210190747428892974323789173876556170584486127146714191461127573501669107479429321406101655260020274914701482569066963106345410835331181744838768093098594806424372504109860727041742504473495044927925023619381218908490347559095137302344380443697618225854788270447368925137970184789326758945494457040149920487005874503161188741102797377103484877862764849266141295632456168716189712918182229284410009437032907334373950019309733730958008255588386933863012788279321862088909154464665038695320832546904701301212269571740768948121762738171918333761985735620270308777497744136095971544976485939591893957047771870503591017170967025138802039112198043992718551471666155454121492944674396814067422727573069376370587117618582041747701365427341079069359743660819414411315550380796164917951271469856070902810804510855570523042096885345522693227207848233976728232024245145446078447269816832466384212916551561863702704731042517023678501041901964911963307228239397848066382932531551546285054810603846061971561905951486957815347387404184638480956238914153922100309354388798190081775741336967390240362056511925360662852984018980049083128898101400554828405042100806919888652038283541762317835664322066969276478358587143925401516536456023658581437427059761919359564609651571599952500230891318802224538192070710998124376244044113028765994320801479582493414317005410093983378818646129181717632129847824961983476768283926366184485276964289930513373562889673689609650342165883697125588055377042211420929574527758570290043116608534436252174918739293442363444496071762941958910567262365138702062196169009708381182682598656013862379695336092215164119036257916941697238383729959825057619864073100540722452397705444428336420892391888593901247714317793308846187058015560294987234383653869347103347816539366141557934809742262834540538721564307784028079810860434260747177467004881240122566666038379760064043329958991761018975635983826972819344938703086408333150315385500503975501354976236897597341187162624059269146035135433106068282611496797388555385421925272473330211605500657410104704878368781206509477095750055633216791282923298810473240389039522931470467102417568931187226791816945407580700036139104748888543918486830031482926244722528796612740087078180325840107712565473249616885483708036479130571533148379740077243035439808373930630703367874948862706348442343903825082951897319694222926807944722989563762380185799040546278752164039201515669710641949747999845888534791911008926149282036935252909744967995384916444059558532857941644281812424825284532534292823492139610653860544812387926589922398563131141842110244881826508748649016226437365101694477832633613879040147899605919890477211157851586124214768003871589801094770394131413663769281554583004460750132867286046602143119552589555018963602342861252526258994734816546039678621239952110378198409633605671207718144603593017863274471740079935891021819555421256805909272122339245110474396744221999640340904528521224045949130015691931858560718625282044656451590846432014449120161510310983833849649063817655439287980660796490578809291352574053101676293436665194775220083912823541989737105057337992230611496358961445642410012269955406099522560823788940447967694894690185812738380780663654612089447489816748031717794794862067414672744240276887295112034539150213299570751347288329053224031276732323864226316812284675477298801568307660020108830972953739485127160104915051281599117953968307925810160546283969379647676381148727426796811694072295812542886218295086330597415042494068854964697778504699259082460087732624298403056261999041979704999194290144992824734868380397824796766611059481499550871446269611063856178710425638664659035960199998868543258757247945054997751881687945541772490538590752564959617069719491534862966726813215081018938821778021878253557990480344350851914179393107292706658819939520598402673110531717591352389007632838945344899625599979598701550819793039713962607742844760313887484666655999640373525299714898331980411528574385042575501582807778317254098573869031488161219559270395781337815283317855670876788616803555619838287665709739814884157018712912386863798236398101630836989738080287627869161368697047662211962290756391652770895464167850689158564139405599233732758521172436647224167409248437144575952709730719122391492062555206942693505740139099440273661920530335017085233977390125793478954618889604579725931028909671910172785821824309568277583768290962129544891699349138672200379295265715449941936882446136806439212035110624621896697680544551260506946745911560229353400652151260659887133202500359056176950668263990063348062771638377309123194773962627359643222194933682562765959513757175469009459012505187282921901635479731036092724878119860539637233945637645162496786546641003616459095478219032357886072215357472168169547501755189007948278299986950262527453979565772945660169481090952453327647404448479871952557853298191808425841906392402031245051853184437837937253302067373452894096641316141347544207903167259630439048450976956364215436836906662281786343246496116161875879748013396694781572115856986142786789509330220259826454680373446213172760087586815199599545644032373919739466371562879812311265145964437300617653601441314532017589724261009835625452564323440360353267130709549322458898293178320183358093478608889118765560481805040137559430889429692357518651715680758933528449634746751723388274469990644941361873998327986547679273692791190818882356966782607292143117786022251397392252550044264435642090024985344065551156559143473976275758333550321232213088793808273729765684985736110003418363313810588503936244693821428631338693788219718839356589145995235556140683561754447885770882368675200667037814430154725217725896718896317109557906960501417506819497320026748796710573729181131276193716400232992780452154777893402279008460701374170693297023742231962836538573900666510146632557789982854839686543855623087933830582558582980370590124857413145310526198894916990079375483466201862906219740325901369134440979287104064389951919456899983705132695808803382090939965044574334737069987681374097190778015903590053025280645148887248004849560041027813300012991339308603990564927728261249931084114010354574006953413912625807873157559788739735435682204029735920473362720401615941078017085729478990727621255134764772207577659600950771113840464690104172169871953099107491248857630070771326868640882629991495724742486889183930826430466505976330142114165664571267979101446640998334505404879295340912578383419890729246585993897791380542065877772660893594353016255828170757907310976168203129997969076112965832208137520688647833331226258240857162117655053750322793337641059121110116537030878198712727093136230663865234075240742913027394651490754915247012764245702274480547245961406954960371156051071595097338757989012824554733212016045129829579751095551910719690457235886391379338121099759680518513587510983611405613247687717751962563977297293552866275990364243550461651492520012783281864855451962512442662910894155832857540951867828389767161938137684411998324772190016729356881572906351581952203593872438624767463498265056766853681386171792514071496217043807720278432916826750106281632048644227317247590373095441149732450040826437701308417134712469787972776293865473409889963977128167264830117457494252903719490681882189816304506349990329545918323987687489656552513536659295338676074125138067987870243534492641236884238967685212840647688530654458685364438542745453331900952165941442480337330429246078171577111492374587635763825914116376350354911780711900975204670152373168270517794640542737094399858887816834248760026659881458659927011767391628478486708525993806070194444060074365415603559545530717517641607260950636770826089681725681844265790455423809563727832335059597409476419084434195521848495618567216661904236371259990159852832373055103662596710271016482591033137699942269064147780416560279124568943619674344379973610850338364424173829875676676918971829806283596693979154495553577095465120064676173237946945797277789030485188373186911214597457058505871078792216498999832149184743087656004957287150278640480233841489651387159132659692488864337750833293409550710825519730566520858177833047213743088935289124846302680383811461799255241839475877943879459614924449750238370961988833297538618614648975922224792404218672813370853920918803448447742799851127138757292756958791887958352539315629739194787548845585380322442868780967171020486992387437511603520629883034167304585067806244768686293819589101150801277359663571639785512698127925204831643239111550894931032483689724289042406797894998451163909659983659770050468003314094055615502239341200016362657060567732802929972548832496808298369253484105263305564199768918255222132874817436529559556217721582719249159092630958197132175889655182240890887803596741862817565450162806243059440027189840571164006674200499851846146199051793129278999861618176368443277783650205040279122746110630981575824433120732737104358086867474845929939970795809822573176843091378208755198420957051989927760168306687503319391353844189180747283096412353973606621089371140467241970013968571963462056853218875793227198633835223172717049863894626801673414861745775717648298832893521239820016988707652211549697807691358292043505841842317337337986546132457391418677903368999636689899843322588897569732086857743400308681163215175918314198793953583468384701401616984027639200987108294626572871959739653555617490020579794673814566746206767731568327968379781495782269720065404260390396876836947266980377590254452225455251835263761244759140880600988916726425924381524006109049184922764132543041954588160582645581644817062767749531901007108896350411448907947858281372957721169683124653377748151329881791146528606673533028696391316116748642517884247256159220135974091014275994794465210919704675173197921325748346662915015848773273267014089383094606358138550884028795145426705723298023393727068946269865975148523584237800248405483758834409795290008206520431822894838896251613829722749588259924284811391011477046685227714697138392336012446362052888724650272966893375623554028574157979676063750773140683301865360854833896110577363255588474016944831116516514742616756130414461619933957868426040776701512498155128459906137987444000359435256791788249713230424644968892217677265002392988229066627428246887956202209613959965102165914324065181272805598091038079515000224713609394824846171493434635836150024927971643588931612761837767957532056357003852762927732743899056494476707616577486361901030220477394912101476998635696923612123742384195177469317519395041885372537115260200743716333948055676698405412723939406222824818690851819764165231011417790089399209668081415244357546617489723129591333354857144529744311770309917905844636625534135447890527459053266645798813210422193763732955020592587794162088843709096559611440694550566168662105385623157442412718860601133525780250118207422952874066802476242459647418370312321357606375848062750351531353193684316388965501477717781380891603031057159856405805174140312062034132005378762509735400764630800375701099721862714843876032518463927573780497445076714568692999250835656312296519597805011202109992290537838998547027562302876827289981098990785087844803424262939425794484216785569302879428454046164966587455515001874827524558424288590901789523246213794560758565201170720602913284608817742387268367545633453360084633593945772225750878400612122985373954820588062693999095959855279714096398792149489237793815821922068202142884860833694153635647793295904256223009677191673582582979634673518200287944388340300859659106915558301908246470179788888809386228146324030118920474260929614063988197507073806663536165011082373407595376219264746389315277198190620614465601881959780489659729933928219669871959112841305502061769042365341665848088244519149085611715290104705235623153751985332820095491688985257929602232937029948857081350181144637431460343961008352883695236386557402985988899191500168167453859529336830223627639157123570418804909487447084340620842681819920211406252339914959669683343191363703821691259187456632052673610653496654046229328648861609525729126319328962035227586614296541330239211349492380894429418112450509591946612125985057411088791335126972717734286037316647845602760330854443585893428363015099277125273824117764613249744014115306661343365553833531673610069848736143211558144176164235246003137964203510007462088972640218559856875583112337711687069836898083779353408165609177175341568049571669659106774492978654251444957174208743525928545825219464629518852032512468807399878895676953942440940426589240699375594754596725974342317018112169751290896634455330282042632277250623356168462809770023766165812910616821927939014689111269246323272593792759747136601081064671406312290173967763520587295930471496543674634795088020133604524582836083172099372301919022385765141562446348816016828857146171906679684894201396157069921402754488030321594454983392322730667429252010639022458600224511984184901197361529371642157944203376785238141031486543288149312847624012485066560721234569887077825349963483703193879085975366470279817654994858031066142143343651403980797880753559461086285614838338556120182435608442764493167555290308838891690576000137860101154948872715013553651150195839692121052496740978060758783920925233499650543385081219995204551070176336681336705876260643896118463698825529309433730994510915503492432142158048791740767181487144965838907470115952402425016060135767985945181176615594111262476431035418037168964419342995864436957616229493005883864551006116002712151534199963882293106581817172521402629215976541809521383799983656338904021888327818441745321050143539065151332641210375971198447476379786435803406263130250207664234090603071197323301322815659108856494672359381713121170191952944716605483600127976570866330419095113624267846458466585817597949382889385516578904219688085865948968212875403704812092811146138352373928094033458442002218772973920535254347624908375318092536120707691618125870281149971745945259898459145083595722834076729478324434087068973609059204076131700716124410078141034866069017290232231225565660636563345755345508302216060274767178821514032223786516035196155252885238388458053029904846231831079345626282770377252026811418806390266269506251056711467866877934837911172983028578299829630300752594196468233566802740542630219072697938684108422186077461379339871058778309630181993899867226508767166635908302359021068150760046482058746940379200556206110305361126595947251728646673903205704855873352587805274459900491494155923519215494543746529413198149409261790754097209885060681870321932549337656891616957628751031982619169527854974529689007799239394760534426858802469226199263362265410879190895001484761438767729395121555853084527314677087972245885985043802002470232122782903676727367912681435987298276072406902904734454498568554278802273293601758185080048907016514769983221646278251644931671849432812753828233727878506891537770436446473473100898256551328426993797358480794541829515475830482701503007270854824802824478168333584233349923741846464807184516631068945855887493989938870476448831922349298104572542191870485858717136333493771152357241801097602907542866002660403239107173616649531466931435475676648115913311980149725149821064813226236078126101717516324300299467775663237744592559193123601029773316849600598277430903586050414063043447947504075553186636476765052133237294771882953841869131033812735898449095830884022757935670186278485986164289912964710228809390780954575886692235946102920598586010473465126331301686926271312067290063801512084873206589128123945668991763423220090078769689839823567580667047505622405596491097952490778854464878002328491638664075516821328804759598295678796041347295862897974162361567510111006280818317541342172641834888791844015030412492995505466364978062503159003838289808933987690524819775555594667965872890043714394472265645698386511490988057290446464726233881973233556312355740279648426436392792692644815794451207529740968542308758397253915539897396954327799976828527373010164343655649112239488473045916686123613326704708397566368603077391800251889014059076714482334822442899622590532175597765092109327266357614546999675769349546655438343991830095019615643246341739406773227742770292524323992462182852955309434044426059988641111658029325605428407616611448602114973091134941765000923601084296623729178226640027485799650965544479362425595640559985623376888332102259652340486534860603556251735944321704086120122854564741900681492317350260784013169921467063273385163086744960492487382848915725118030532209594996665273754978097353121366132985377810101625201120448187753183329747002092462503059961553025519684617964204335656671176991412930090343494848633297881685917818052241811049914035218433970851487410865186955230457708851793057193756574089804410877127522996643175071442770639738591686089339659655102119428360966367947518769552402152473867486205736199826806429764230901874338170372460371251518080395691923407988506618058774983680647621637978216983549848358880777074156725407933817186886399263739192427861310418678554093920908054202443714473348938016737881340630064336778236707151377390953311559383524634715033029832132281318836645562670464250671271997338973713626737833119092136778757060698221511017825687441426539109882036947717604129977508663250964995865526427595936358657495610498193879273470668736421898826754583941664051655944700194249310159206329291372082540195837062219636442401419374452242751302031837666431296991798488736580272533214722633973923978948194167266259190168024965510809504476306558406136734541542803271659015741242020822791690173707747856922456547109184228407716260018397928403150023425951381303572623315798374909399696669746336412408004471440362346429701118678634965250359934503396644933784478383603572828738206527392486176557920015845850377674077072581289869070217849455974116750653382288579749853916918232666673498001920197099278999636757871480372840688560341015920764917044213975437152587722772198735792344174748551846782122732321312383450770763936119941766719856389908782595138012368649784689353707322864103046608208464255195865916472093927742141418241522187323890561190009902182732492625722991429566627976339782220460818853100635438590712155197600861914163101640485711455228288925687585230922172967526630855758915862754723181849012294435983525255711965487166117491379317139133319586331644118090392262773790788656558242670140659797107093867595217228520291813207187033381858139690296237179567441584337420791627170310538778102593790193967070210778123737340663103266592271852337247202925217502641721842368475906757706186030897902958656693557220274531027472635033093119472391350740538554733661796561825912637331548127716446355766189900622437318130702264327328216048418807709044099092863963711653490725682658345390558304939837584705241225704643760451148991261354563395098156657694695480467433680193379242245610217242642218517633259212109168815466117585575839208923573429012508354019869194481956941626708182027030212200269101390498132772737591508577100060199613458566505034124573957664482584530602733252438774255742092029478809236883411193120959882187554879859613548218935214103447639549348287782471480944300043310211677390324433077385576501833364524764490064888669242390598412710997050983020390097940778231312230748355170139124786899795185395227791010477899106606971520768650925574676866805441632065200742689722152730360413802145647450912013522336036189669359868939242300481115725467622288735333276747924855773402113407275583353716133522901895318728248397905912173950606661791399029949088098108957061684245244370932757778765219881921504202928508779709312585713637849806171316245370261255969775212398239572602117309520212052812270181936273201384263801785684672796151288177780090412366024237413967787528353253942383978270871877944867561320862884846750015231752066280075311639207857011531216251331898485830350914555297732071869868990311715223558738399057252942598489879468715377550581203983880113449141280233807521643471226971911561945366837662203054462908134396516676869390907449229302229569019634716172020883888009299918738434188216989379354637060898465164116014011960417763714004673091259313967665883392246537656633443756482656931460558552975045180791118151506152552726826783332356662214031107471497046410449525868693010415570899155054191629511726779118543480520163499493832095011084033196667501807247052937943272320350179049718381944628112666997029934336176007792315008366431134968812861806320446915119640398276190676707119970339007677376738690134360117458391133724762139617456047848093554467133325829039708150427384466779329225673437633866443560304958963871538827978631710441485582616646076351864902729126668863546477939468260535774211707454789948006178530281836374238409000263483165486155757952047893919952453801800929565127445540039253164945487648646867740082162785259953640856463646968320176855990906678758609222167006433120998106316750537478127483282575995911853282764568785317919222686896674972632459932803028541289183186640395390055118264622015205206963378802551258562453790966988543786294176197040326925684395094135346421068967842058832478336343247815904116697801493957832836267473106512325871742341928954557586273686810091067923664330294366902395227188072647994236319653708504592301707377036099419787404343001512498374597377651022152908385476189555884676541791161833902504518726217112150890091853386879611823095887897406680484623377590442597281801914524937835357745115730819262347684179325769841211178593006451813738665745366310711755470021478456234858145782876829460635905339917987581013837355069114593135838943456795779534024871497571251766283127892692640567217780639816043231267154804966746780446684718033409932932384150030063904857414832039858168558715966680354683342080063348588460733354165868564055937920964601045317154464945969184263569047666194620379924475538140801895528034087187698545181320930352985928818162113297692945737195697588258713406522924173124412802449720224699109777344147978653440341802206612635143575420070986367005142023693665795147993834166735834420206987112286740644250318452673461412989415192550333752184133150320746056289144713752595562002691138084063432818049481555145393831243671659376115339531509039021437879244489728402212198801007207985683449913481279516952906175355045994337088696372445553020795665531584024859254061913296388562692794049590480976837561788884258835356349763311112728780743288304518560197704478163550683157617452667948069724370646229129262004876239886643629193393957894493787604195213123114246078572624257236903436473690705519763884513783516715837158088701718267162323761274733911082007041966327992697464680381897456424608735215623773096442271274340930774219725752113244540993527084194320321200150278142091532218590500301444976275733350377494200909245166883860573888630599205838514553187152663153381149211121375319054231456175736933325035830459185856090753096756997413361674112498881877063520160233725392349739399633544436019238523790993333974681620593493864779111425722325563693076928181257759837507267656983412787224826523662260491606835150982521233614865313331336765315069053181851683053829863035246183095781178516572275283377500222409037529899256483609373716412529981075520542100788043417409900582476531415914271999379561777585201231878836457904580937033627890847063777585922373547199938598005569328309348279123084486066974257141900958367405361343406674227810746564180940449029734920540234192584972546071550303777707961566491991819425917907955386454837649519869914290741490741173972913317170905113656518895726296582541887671678157198697269802061865182667693242700552248829989081015214699630680502411433496257415308801936777904323024676450648317816620822285694966107051270782796969694611173345571052217252161547914150490082360948981785556624692887652704155374559045273806186248958983997923466947362228881058694117080607613822977797779791838788520667471237095334107448788913251006883976763476364631971337387465869476070947064998905487907617870554798604168840365355767260515445785913630860568275437767467230874581956288274206595752133068459181454815533101625927260841570019106785386826244700846853629249386326587045041351502874017976704302203199392490734370035906300879110643178502213790494662067217687433745618235884012001563368843821846152045218197908417115461766254397477218455112156904355193477758286259219895779777415007604488476043754723676068259506433572774616711584315534458664987871991780805228167791919213593264607228827167742351805158969340942068025291907424381272715748739321701394176184660219405487393220889998726906321719906056145343495833771251106557891737199543710302591419312248454679880383879438030871331914210615064150802955269799843779053303276694995576628859539870631437117645282376551812338849482281995266536826309706653386073846284390519345156696720331040809453973656034328068756233433601785419122778657104313982946833198188169608614963014110496620564451221090227553069388356070131353399487749529363916688825539849874488805698238289111894166067381387578144720485660246880642480705573776249899587366437986868062153789160098673701702856047133524086363225277132360779713923593459055806589706559206836039239319791861822196477605796109348379603065083661053489221037360291905648513409434580375237932969559458108072321283012721153287874963393799543177159807748251287083049158525864840549890042525006751040258218018346399789889196445579937015969708679419886128888718514669189327706827973753678848191281312594435585075686592472393159680023319650724357476269419391563303690245007479803870162573117138967473183066681370227471812177456936877234640181915241739472596644871789215934472396753121204795049573681134742546614455838408342450452714283129666201883688820985768769520454168511427377576167271732785885455689701818174122685599348003095051328693078791657672909394092153051366012224811835742627598890354486062841378709763514472253980712010816536944478250605430481847311120397686557293604388801766426066045171562707475142946047863738758270971582198049785642215700420756849052897800374901593906664891765163275673098719511079946046322227075172770992330943721429782269396151588560111719019016355179834725213787046939178024040833847515556509377627590849187807455211518065749211524492125068752768500168293272133549093300597046337291326475385976938029892774273031735940651344743504264351793227980026157377756756298173248709507616451856544193664147019955283967564051951703224072544490491547898009195270565762672457476286103418000379403109329647166607157759961943458812630396727273187367759297100988487620409501951338513355358613540298250630287212183178912934213240946127301542190816220084468358602100200721426928011605887642430037432107526240434353237952830735764537522086239008789981857411695132941842817184217039623561832631200953897859439020061597824515180690978493928936010707506644472224295123878017507471779058629961497471485864792240477133747338396775497351998379060392243675869614747203302063981239552454478896186101030084746862406472653903492563174170252779161323240222793786675224952147593717018796122654760635288104606577109234675123419200599266887901999702378244130146002977121961854295881002860812165457839309368387558441504095072210684947072288166190207205993097937946414935835553437761221468097645090083870922204524317425319282571800187826541780777187013509899572463931745905541482152362647401466907143586600994753793865474717826190768247486587100125846244479713555245855691099325509390466224876943238058244985809939119999133571722206192269283505007157422176768031977599193058738728770008987841730980891166469008780493234208427573456897463043912657412432206620597676408253427335229116915954700109126299025229009417671531867829158321326254253905737970107707860445675284125065342326798176257946816850381290301953647898352188860076154064609933892982662185747707681209281345319715833137565433998627813298877504396061185063337576812605408587587513979067085715668804114519805511318240124128574515285162515021937613883199833538675746322554944126890153640882957150804581043377898783935310372238977364418259116631762606172402074532330686483623334589799599004187331034952482944681693042134777905679238786296027157514115112745768874277153962851114554525714546102382046985861023734768625966632529108993403839533890119394444963286182426435052574135698228312831326725829089012594515003198231073426561914895662902598386254339329367151080022909633833168715730269696405304745682701105465777141313969813413621992638213573110946626776828938369593579320976569022953867144665707942184803300349508225782871206232068960848841178300367634299786424667680197743645134103673002117232939207666244924753646059577970458817735657553834131201888788197841230758922068058712304526568868523293260698825708062113246337013119958782833826069596878289408726941120797987031497904400805150915213782770195328553007343854490191504874617078175657834960884673712023693951321610970449350467341668859931935045134295700612727420663429079825178516105974157485064544697057441214137102255434509055243273690939201001465401780555662952378512114637688225621215961507112804982385341653048473147937366933407630445943286488345068209787671928585872787137094336050089793015422395429208517824770156226421799636280774642510265707317546077104890253775123859453090678564536291557467553085050381173567898348583096120776277496129831287170189883796736776457491022764053461402048405639303325812568175034258735441654875041810441363790270265709737346088888830929246833939669545697714111753194193536721318165924310122998458496437192480711023776083964560174744031831695865497803013010477492399940813052827848754194765792517204394279131926841105883278342027530261298346224838605736896921498940213807946108080369139188456238187627286422462949530571051904914953919073158588955988155656562965962940586618920963817728035075287374811086173097748938771268730392785094120081138590644010425253037757772863729140048354572636956010245141684474330688001131681583781973242747081085574125539700242533673590483508500246026846565154657968022512502812462050794220696934600295114945935905943851952793887845613132102306227419109634594221778767929485908588085402305886896495374341994180612242251955371587620425789255847730927274068469743729926283949603718944696754769926990782645098302730520862157488133881925832162909868411302780458528779494830227716980797574724739406880789132571662674035119888281011866236008950351563978234065944601028709003140672878839563622645585803068862289261147238480103194953983134724149921164276778875341493401690112142862320791827659144340830934612863792876298791473080258554444121381974252968004121415813219606111401835237770574323754819945129670925947153509466552290471889060637288744279109497548620396449440145571533798566968967257067635060342570584891148452286141771165195699505743198586406359637020912466479431566979505247654156073743865528439082852380553947282426993795511874158020122149437580433383389605860640305811804189952849418601642511372880578910681191860528137109864279613455292175694235740618877246727433011293924032658012666047388015996077731268301913373833483202228655276599808538472418458571138850931939725868635637745405958013542782751018302298167755577245834029791135198807626435804415988982279120667298919462486847109277946293672344815808391322664757667768020935090411982028031763426483784013865937751921814249515820132101121125693914190098890167317428059325596477665449281669895142409467030511715249059921771820060191054149075059311405996517686298436934137356934323213306777987821793408954955808470688798984060427218183426519285454283502834942241490625760179615782159926553996409042533683584097712647374789175565469419262768670735949166537841285945688784521943313916518111630838747688802112670086250025810252312267611624329708703233046525869615434278773145872128712466898706548697647148575346018359290889005616848156230356541132818555417260779420882377449070801486010680543879676981331569198777869492506920715646464841228439381851910689503543671408223833820430078186738394019204027907761191735895053351134269920756820983594086173265420246892363795762563032151324479431259629931531920456019618093139676113575921174350683075667590047211218409470235102130151381597058326274390024149029809020419130520508415091099806424120025089563648064560936591980709316359656556846441836845570305025741159470206423331997024183128450208098074844808791305033152536605349144323734274631165920350508036680402274351760771977747071259758657073070492019304053388421871382072657748033881601280483545952576156495993050859080982570101187194689051388344707308476763909102816956235319987341520595849359828031421144831619166529458222187721186404826618659028291873580391888392511886544550211752623771112608430171850042019284632360565591874404558456779850931877506877996795388263396084630354005582121671537118233737247764076147912434546150898220931552981985243844963439945482641013358415008066776819805691142110118552488405675236977678164463939434531804933733468831234189364325151562907684919832061704477220090807200203203205012784847134139136474461959729984275678626036258658170828143463757872749292833971342033491036737248148700888040210928432363494159824493524216529719018618748743722344519028341514260389849379160087671756019827496779717011565524873745383724376693666458601890174471100322791943867172966258837046901100953317180371103487167619192237125226885571421924358614523212188684533521206841124423163832986726831828143138264189203593481115036744363428675507414336697903187254570327860051052526547413506657997824925315674695952836443283809407862725458844566355877791929186936219677109762245460708694078559953042987205182275536843433573652520322766305677787148191296341607327796772466218392188058362024792443287234057647193956982035210986685102831681331023908724499821564148837507457215007469938245815982625494529650379214481866946081656280166389286134074421225007804437813110080298380222592141908983543956634648843635517185802676001932950813611004824041121901596644845320216168422647803451355701399889506496731507457237568674157954949019926621689080282154473089870360915175312578356893518512008152474726271825096169801234931338803914886156327446006493242144159322963750570909452073221417708421446252481402533077696601331481189622741404684396543697244224914232702175904357397970327269966311891904122657507774895946292991353150399545551351148956885114530363187944046218826952102038204537269082760444218364827279826409849321016596162258863670392368268438934871070834232829376747832659653063757322365695672542288511729193668194237518130985306129170389598419536784970474273640592926582344552142108441810694509632613120880645256068135642328010189808714728817467996954910467138784685773072551537752169816630367778626282276110358703180853982585221328216378532921964368951679698096904887846637436711810521698769434436978522493199949243622765532114164271019195653161045942051609730313198428621083475743680635075259652122083034519162150341081394233582248240565273942807293458783284912235771367615739600847453824027437512409896852933712701445876500705252995997933038574879891006331642650850038685397897519454954850528761487604142478491141463016015346746538202103461857491957672929024326403098764544768309687130119020677113430498263918118338065543293860324055330242304082931256165833080254880953206516849870790873337596404473299975474465664796442270612907908051893494201035131804024808896360630066440943010926080517049684939812744143855051067211306169326442258931768749084487053709621766161775983299347059974682742493379740247532088637962478571966833614268309011360238105372968276640200172201943455508880017262999676208137152826164687843816706851955838083190765533886564804157437095482296930280894119091077933658538510805425042934913119769331502717277342565784640754224706476644140787781088544123940736929815366608032248886176013157423025587957532224462098634834055823268467339317292912321449816804651266686361042803283945037382718616053508271415669381926766015463200892298225409275765034563469172901826107375886240913923718141694683153957903974974565246864443293361331397168928913617588580572149595795404710766837975115484539361654082528614322948967171400969729116527064018386059788710085912500267225017332514856907513493977047586898419229413352982909932393229878372931059769374629016151976811257251402120245009040049428126930520507460418257664328132318369548615576462863887965333150043450448390683920853538415990572017078008841088375033417756538780605032207992410820761528437504798283852716548670005914013254000306375968169245657549565004260432153779674226708304343409020392785586878073220081165866060227599026695095930088081238812380687616185050829834380166221482915214978296540189439572911627593442633878643171579049610320443860290055516242051448989971371323629701984564271573803098658483931382255598583747040369624712868757581295914142257712255254021951104643503423183170833553254758905964193867552703704340643126666803861726390668347260337607406022552834463067985760267362929987749630954177950629064367590355484080568017012637121334103191810774503224169456917248136177935315693647175170091044001839948639422206740076375673224017257099665579367272838834518683264123114995280198749913069071671874075201320984998898733775075448883543518991087074646481962986868988268530098268770464139821015573604106513597766423003314441610400278739256974874032423566375881860757017462828866824520502705363688526302135849312839115507615847753141241803903641291614937484086406003502652662910163130542344740225967668144215574895831085670940240962113589518648984496952809996208968248814204420877883816703895640095206717241777305747234565067763562089513432475672472913145020363833938045464628098105286812426637584994111347596082052681855812986479451949993295248704624827597895832964556508318727879521781898310305792405136321424605645607530183573384184669815579374996044059114106504434857135601740100082807148393715692185426964192088731833977574817465090229734010840685707699290322496496853059463907700464704277190496784458414482815496584201559588758163028508437359349021477884452255687689671259205391540136210781310610401846455327884561776569496371788252854773549024465988999371042757360360876376818924239334337065181592782709790358524819810839388562083880651989108593176973204030188492517982315178480782473447530615165759353545790829988331023852369626623275932507785892136750046710739663263546709237465361107404620065951238278881806290699016153772043371852616016188512952746949653977883263869613040957990699356456352031468530513257688600835625162265754128257194292863144267031892001239743811979387054705668354111119378322828884839288762787128266350629166389609110617934450997538918012189887914762991854346010920709262182962285988422473458058435306381876642799807835854614048714905598309476890998357718515905841190372890167582422134183478582185033345398531431195171780018374020470360514229188653602555122569112788389986556145811974802472767286991402468330979013874175808601356294635584896608822098860389824745998254858900363483031650025002730956046945252641012406337812808952633469582771625887859235297405329164091391319569563508924614477402150243746773532025184112182606705108416013430480137165847750023994389904699328120997154630787179039401635502719627314271063352795874513619910646747888001305236323883645438618151072556594360505598661078210763924323012531784032966682000239528737502848100976713537972559050499121260900605182986116602907660497280511830965837778841773809294692372666984713273810997385104593046610226397314774110300743448466909980543357498583106377104344730709633615540441751654723187506072731892761070860802865153719430477408737040432609914756708994537587383403905950181168797339759888286718088045916317353692271492661156968084138382127755146308004444101169080712557239725554470958600059541049485305422600458058399587831919664665942782818461217185264006413679016942814547033743320286173639362493356117568028693773578675388763791881241881561300853065074782019484122483605474115374481139565154742689399262166774172220229904032276509126734672131763744981683623589500662725242919972669095197539886130636654542616560863823071289572917195179421633669209395123730480527598964584695015551387063867173145661881337444074184238274958970624294421822455773340871049499452726188840764782846017149753815357270031058444242630558541469607556847096756738352738315851271312863400204368059287224039521867914612117114355891566865011464217618451403546239285100418654415120842122954738459269292721341792424323479127977413964061278740601665860494544091427479739682908491115326371601033712294577704451711942602331917826789809528828725017196357212693631053844774782854216951030552708686242878544674009433473615521509028302780652753226473336794837845359894773319371878388312228357961749026964153887890756181719525218670246157891047700351430506493792350721316937841297837932210164947643315235168927220273659569944768141519572432927976398914855310068043267427231930604212948919400294516113230141913141097168073272132864345203642646121530456693281441027557254032099008924134208763144730881080619352497861705177951639430382878278643879197124638799565459522394426262836571704562241857858154817874382102706062765975705432205506112193090346300155563478198430430200099393363860168775451751307157751615726126025295656062607617753727347094446240539666202166355059124527461343947194495566744272892421932438773039842354490701468187749701403040499508403368522567586155853696396846501623861471850353468988557747739594614228808352107062938286611230214031737343451270945073948379423363121931645718418755728811092576632887384154522348797604081466177129990500481534018786214218659433292831862924552745811111942378937794634368998018817436037242740487591417822427482604519809279708847922624291600583416273291649121568116124905192606047649324448462722198433667093938942617424569742862088975051742247460982637095572908859329201701212362314620088224746472688045189607358281476481904695608278603900747860517339371052974259196693636337218240627089091812901076672993251664294267752797270717720075821618395886725538053578084156066136766409771311957228731834916233504402973001868565054154127000373905516742943140719395132569506917982548138190252549714439422404183949507932245143924876045266800511398423232620751202867836412618679148678156176887631197047336259788004404426499367638070054116784462677155240533749679478721040055103211414358472072765638652525769059779545467483582308737652367947592246489854044742323565685803136606600282434917715893018510043833994063122586157295132300775462212267644021727910655123218434710318163871639189576778317655373448638056677388644787396530750054268373085924012261219620446793619649770785150158656696619424852368199325602531068394971635512926790139493504412414571784516133800401815839000325597008217026791627603313412691940942913833807362652824448121220057886877781565504551047050616762386819511873681749821428280211832577346673478797685718124111407210427874381676801353955739954134391240303631284349186510031713517227947650495584711408848338488297875550672769733885454333837288525710433519253844322419481353023902740031259204354412246874708357602214287587513868301417462446683853729579741151524911688512810510638074190501843161639928924712255515437196527004740845253000585097987392667070418402297539741419804473598521858711374398795942759924855090399323109313245616329025359178026895875837224748307503331742874922231963414075592290892153712943700936925238849421872801641897514736009368805402959716691500750573751249297815001045877611898835483985005149276490128212415865697256022748960534375221816628003507804785086740945991127723113216070265670667662527184082450642695837567115687373633975057746837549386783638543855553944382255562798172854678173355129394746468391855409212695771209028422681978873128187235792907372579404083279570107431720650302152919578159351398410309727742713952654311908027819448849059717640710742807354365080221556438543259623303601882850595444672062803778998810383166854319176214244177202629832314145138417233107591104906026715218882717865485807408530441892400308637682203069385140059173085798349583669591456605327037001331398805136405943607732489373072261569176229561736833313638621776566719860319171562535953003179625537413121638665097691989869243882935283923973857835664417053031754656632433915204763849772758635668446510139531176779819562634450441839193953289172340360128008023224125563715852979730219077675202441783659814558419966733150617996748250538968310427229008608011091314864067655862242259284099993212962222565005436006148896601868067804496293147038405436488436177021275949201492596217721808731929967309600245665225620634210981230906919643849689390421501428620946338315450018808118529267063215339233785532178584861743258561138635065167884103343650548505515878693407752436372664672081571820819611361143593119979209784168086594308821741184332937175073643567035279830218672822111755052394332602950044833692469305146404842303198320951400993477673263867241348039036257762844531241805347231375503524158197460742948943305024287231113703836895179627000821223811111800223095689212059724422267992385418347686561342618622671872417330924381722012715292760929812498250430465220998871161795793886756709110816326815805434848893859453751850730196163444677123615221768649723657643608826600498360706827443012519839100319522621466698293688155221574910314727316617425022745715704445011799011535617221525738931595237927558189215093967795993948688927258392580616115848158134591082398278898537168851582957541453466128450442592484465144952505518434975481486223069331233403627566748232785558810825413181308386671540059773436072472171347690857396736641179429816087254632073744333221398506798251805947028144527570140947842612196699002035895161691950830290696931719306784832168723015029221648084905489906711771783023640187898330663444638428627623605081848248348732748826461403122742515129166635362737495471866002127409290457479896542103478063252681633502010990350026285070607146179996915627221218551676862886356075827687067772873400229706596107470604997367012095708832126541492416571398315378925197634226385155914773386410252033509256816637144424578210235889673920745114627431544644417061050370863142021569720551508421230111479768871067642322457044565677609938402361820471399104394702345672204357351740338598297287251336980974792695456468604918602575427586870456413984116021343461629883910494725632359705661265443588315043360731668286115114928559502759311405322938655822533377602341179117324962867418298488820101012031274065252040115821949225121404279248191406452125706132410597643274382433243108453155936218385943871220293587310719224620055438057191978254769117047028267813050195737044891275888425021723482267699952561806041223360687016365498101557936402195333989685760493087055044963744737126198790650228094458145646563558400217557518881768989049728558250195718535935275264104562619141160211986443110427971607255089959082354739689992442060316351322454924752098293130524886309275415683390173621276479978708449529507003970451217944877111583010130797997958383542824001832408552095744890978991555360690674936647620258539403612790510768207339426184198710168899866056707279150371516674918468490358126685483795891340433095138217965737615143816971705580699187113538492685560635828055368793362984154994407667352421832693977727624292529914826437739911276284250413366511964593707239297835735760960146234991376396444476851707759107165558285079850578565597439405233430478263026252016407597812710616364649810849984589666624751089973004401344685985801965751004558995835545283757861256686653727183808992734511870044873253210082851386510899610110658545222045480505045778130873117502875393765337788488424301834061878878711960256312178746029808094777079789887038288744705404383260853631766987997896525511170736808262357375218075971898658423870862688280808564252207667402856319959793920034498824451743615070594021330012201783339731723144671864504449933816478856015402779321566980674736984134628493383582993367884953228716747114991376900550925741181766972788665243014893294750812252577994595222177791283676807570572637645594278522286870837971548329318877671248792482929922631180802059383764151470871532658705312868449138930046891367115316904641416482410231190185984675664659158131351997438599086978317309215253966241800964482686783505391631753919423146922449415383938466855436292170146826897211440611505181680798491854087755465336569959484216431886000320530527981245122690017839564434488162261816420208506840400766707571601119090307478181658990014967500247819394628783142014011844482129281500122610011740349613687367917231772457606356370446646114054839701525782981856018150750945816779738178012747296670632729841264856062599611989897234783355302291219325748220737469839145824710420038114193788781772508551530060658344049202892734970115963434124592891060490324190158025656015155209720790905413511353323701873461197362478675168316290692408288451579604145307111674816304201110601454338321296528524852637893465209689451361519307135788973090813080679452952120339111904354348959533461690923402197369535493764684781889168223984266727161397716207376344198617642137054195919271655550820227353480506121358843381803518005855806379877093370294233532317174067520826801455541824252690148646481912319900958167912259381698624707826688135969965001170436751348155339615906453624438738798983483779930047787989007778989526134764235791505208992027564144271989994400730279446885538347486722463387987092642789705848808564417592684566269479811185256875366136800458737244726314676208005709210750972744577847078798330864431085539103650130822695973547137159340497411780312214699994336251480804747527420004390077206858410708686162236895874763632864184988392015518767223929169596075494128152994362704501336165974182700533193965366109643192642465076003567578999676759306428466734752765405980267535044609420180636304044052785337741320276854393122018071180655257825011487967216203941861573483105921387844284127162135308826471459975744823996558329208984912996131889906599265572471492590889465940649317576386280602963563110374454165554961972499949812060772051946059277261422330874126746768289983833577627994259532243147552645589850127089787923362066299333957137207673583537049297494583945767486126144236209346768417999726348802811454098843063010192004723839029119536239799594159520151791806224942447167712331762436498098915208383842006637433118052045700725445194313279441025436943884025309605676504538129757145273731872727767501654298212830413608297417880772863384728175210676340333788896259169530951173780996011174164510148077046114026855650429854422071732689546255080784501856765412389216556173797265070801125077788847980540695818297926233258034846470574148098132417672086743194437062425593810691635063454640010994139340384595586643002937236850431289863835709385542741133806350555743105490474376721738653211651198771237307862632759580239240025210853072480484381437052987342714825148252968395084638213865532051956017161439077777381052519912380702858709413141290428822399780723564074758244627666031380343075108190041463384394335365153897921019009168791581491976591640995584279382096462597063448882539242311266018645691594638634220172531960931396733026422032774092161105483821273127167322065533526107348811364153193693652590666279699872910970235300728980414465284169726436771727418490964247927089049687995278282629424526759206427239320793493292860805364653364091897777372364201604071755735394584803913947889371508507664302988103999489119124343884247382561690544367540822464445044126052602974225233849342594437701248782797383283362879818231135693548376691043204505559936573580899275188146179109528087084908618615836824464500991394746963347770127060415477932489673159710818823778539528983906109113989860465337873574651546460287434363288140398536654210632100852930170106683727843063452422414041558201948019874946181081381192068242798881948299690202453847915518455391109132034517610467288987117390328690694802456948230690799906016388510839736841301469270657816685488803406719322533005528440607201676115848830432741121510101588700623707892243080559195756987460446887760204293781671208360673616413367227109267405957865389649918333886948751371553175918649514134164506937313094919480452393509749206250762425602081308515001934825304821110839355373370056297923152529843909080996774426200140143600736346646821542293246601589592007364612699282697695109371452461685385509659077730126900694937248798377087220501788086713134630850680016252502798820833723528403154002181178910139319362210639566720560980286692485113476173727742877552472997598574926938506798486784730143868646478682346419149419458799005128013387793934542066420599367604690152588540877799906573562995317316329364268022747287445835145118307382868481170611138743571539151467367991668620725959273117554062894477896747364690965337353102588397895423997418601221495837082056069159780261573497797911901308383959948321508285585115851457205168535248005239130205174234991112008043538254228809921121028854427039515479256216553156983223517477216374387075391258469355804127328130052027400165812735771339808419064834512531492798681025111662367633099752448538673470689988418518366823022923587048258246969855729508503323927043315928084518495732292398591574011968416632856260022452851563499747566842461464951568738902064516252890963070668402696941354176457977203320460256950825070925659454406303483636486229218619114177923665669180899630705484729090220798636104155896290985595989319034502667728302863431114912716976364615979103676452181430416320520975453740117124907037998324203269895307545907599620309938048709375089089180690377616672438256641585395309291426755695343366965517882354980583581100171566226073359923829895508936206956219450428020691245211473493147307708914156362499000723880930541641916173371450672036112300806942161198249787026595029735700620592626543041747686687066372104195250439648020815348129372130095897502012422508369490190871634226017506941737740101538953177745183062999553628447989402627147561945883669380198981762519023048292659031683349204162283703375987478166219598415206801802458663768008693989401791426977048988550072591820401564376356791500383710375645673794899167247169747917189248286035080403351812705428496926277758718473033167952378698719012165625776134832510178684670276901983629114467473676566675873004632451270977670704732311119480062341104921956639669365948052515745924663718094401318215149435804089348050851366678716289973910072927610715544043991765841819351692064015060031406081161898505775776171580964394248611724868553534967572103291670825377733687893810372121121711182065378237297650424303520252523721486263538026308009914940961812585923225762772301917800672567868783182918326275796770709114289432536447112229682915080579286191073190054205182576199446308816630477875335177307961657167254026572783151217865509973506051046189189012590560701256522816834498727019356596825103432748068590716480100364070998301664373172330300013675283485573417772544221820129129830381842373285274676451343611545608735413016738084484417328374881556701179469826285075438111257649553646292845379286492908989424556714429668790123467211877279838395946540600182906376516896348717932762403737595477543680736155552006262706997843358718769835719879111549067898697746349754915956332183106863007077790344040155313913966388849935649614510551457679013096561810393019642939130250183430496072958089006274047410600648986205232767407425634516052108426288193523043421740914414978194504810666149039700115440568715999870259536328698862530131056661403017014700184544751889778086220755597868018036770994861535115799628894381359631412762769922024210105247236717391736245138513460553036948418240446734981344840720127108977936851489043661513184365605237835065061419598513148011822946287088285207125541794202345944907182009017716212342530944095492763138048651626263595090671799996631126221803329030775102357822662987050549966457460449235493828308117345897404864432460106642206353319439056221713094738584689733078124674162182167248441938808916772765303060923843349548422029001701365686095917483222706394090983263128663296561723393793193805140987574000639380788108478227997372831857341654591150616016372867949182350185045647078002693607266074992241140279675591959379747377499161829675552373486953667138974438601221174563244269778222635068474681836497658839418933261702155247714587769962500710821517998499122723270865858847688258570701910394957246160030533522109149806498224971071143554278153861399276362070776582874824579581984852229782567269407262945005728456366159982637245467416842716404702466266335490970444954921309985010533032583813429918205978286424044205381583498905522017620828497416976694197189699644999122242459000594022773756919138409211845894655946612135919387337465593285475737067474701479341628049380728044640957219997488674788646355523903114034705407242173518026129904904789804842312485757755058409650373252338234788827030997989512831555252246656945486356754589148754166498974028648767015715051302537625140095609304814263583528807512425510252775082514727445896281836755826016254671947577723010188952703989472485545750808060191738126676954572194115623148076334053874894779078895764052786828089253152164841939356448502776919653945339059415988781875542440617573684601275925678520550944731298544193636880885938947626415514457821941523407286742198760353559156284802821312083110967271508718747965245384541126037230629681317625411439369623167297236094799019185971040942913086525221773174783429433763522040580799334682361851128152863111177612688557664670289892402503345477790486093788911779228798543507427377144141136889761545147200540256718014180162997779184567171715359188595611361111671528563557111349926378703515868469813407550283502079906133133396112521876406814360767130357299078571099470430097907611370862412804602559023488296912091542407512682490241056979883906965507699130341119590150387580102470657752294284317411870284585354314992360651246474320501228445236193304928671182308134778830974979354161954299244527464660825312825913859679747927041539202327972687352372679954213595562556368467208058772014665574121678159108031422553567420613414361166699490620483603745803943196945755278972744617775434446254819100467789043251395960901253638077784159869214648042782189154027491116307069239805330921150463197504943404224345405556441177264158848963702626567786480087790272192275298333413173832370683853621638583383579306144454523398377609441618646085301305671034010760910256852623118753728499736936891919921119373617055583108477088445586609506521525745962930950189451736578414593432247562253520322638355145659082251236207572789666774197220121447329181631925670923381989059558836522215382493639897906572648940773453808780573381294158231275116893180760978487210412692859422930430247338053923685798134491264873283720472223059890649976591329622694419893664873528067954422321726253896114086433345113609364366887682661249754292685554877992378605508614646519420421511167597208643722095684856571785847998138098032915098274992582094901327369182890779126347930444027251402458956847072516741892321431040665194081449390783689244684955810497931039132551786127969073268458825356157270881465509994418061930523023673308652173905495427423956864489630312766440969806439690460138270791407058320256813482710885818565560827614412239874732920473869086103311976086250594052345329336911101980677846322297382480236664812744685920710932231328885675102393232815385704424919105339559326595180010453895596601373938993058945901552542555696202086773847185680431249668780548853832180135983622914410284052223492185955507016995909634508718521305581079809454925381098422460608455694774830566454122152115600477396072897924140144009367495057204750045761768413465456869105225667436724024639153485495647489021701400981149820909734049775448974127866412696667631167033933347869720658131481495181029279860669169438372083537566127208790829708604371227886170551099130567071986935304218856329309786777326839231990775938335748924629843494654579373624241409635559869173517951860317967156733840239575431291562721813378629913162925831018187373844682305104312669915501938326855093449540871357610029788914565898433725168141292332136080785879789269534344913446809290094311712180760813746324149350989934612087481059088957434694032391149297126504913282286704834485050437695529940061967947443756881356912532174992442933366504710999139495956477957736883459154781750323048853552171228737179217349791663565371842233760460414645861568948218903744966866574256995895999541604429471889914770674559005332827844094836330548724179370107725522639139179109880603335714506557977083805586153746589124824901625184999140629588926691566639548689654085891224424659508254850522544503224789576779424423659275693290423473676076831303918645651954552334681701610058980978505562491707230777771839392929663253394821738724343890706993984350671768380884933512236745481596350964982502726305280252976855824928553943674384082473234346963651651760308674607227849879606450677084677392998048535995307464232424442699450571325961042048682053648070096986988275750927360499052959858546768352883882899591972331277002762465018598528912823471971088655821059529503383865859289673927923561990214296758295468639330814350408101172012530564402677022280409410134485979915737199190588418975319634761166902590084258199911286995196952556138826889543104463811438902942244792936802311951730719120324323893465635542573436793347068867886096677567920957469214747924730212925266543154078332244277257163495590809880068051446878081159413073239656156661140141942282939941297910052347641520273043054153462038826861648495100724368030360106702650245283976244540027634588169522699606084620783497526885421398068103625662781778349924424793867521844600279643283877685081476902917538971295693975362994404486703826952938322202983630040617437411711470176821957009433739854861507220679692976937107644554801396569983556099889262215990261346586533247976474265519248142219453318763543440913165166915904559641678954902636449479359433254076313723789475831915525597505246519642900331160585723172902040615449637599290503468387859567766803291726264170232949693946726106708399574663698653014747369562895935509850701961943341562554872084667884434432165704900757463661021645194613576939295869005774667609414327638259540409749703850671976098525071380926164845263077283753025840684364885100058414729332924246634476796227379451998939367833354337968753857620069019850717522655681523380252215597924721980139523009703261602926170885645120864143571552882535848004007028495693048609731455227992309695660202846521091435179218825423273985390913203384445688912837118002584005804742184198890187991863910882173560002606240234172235571927578987296461141679672251980829685357184669759286922466009342848706837910841045792890946028890063483072660226145596325065444513992616498686060556996955788532105157648663221682910757523581771536583769113292414307196567066836269957641859183745620144999510887969523561659545579646318760521299623004496777817224736898032024331244506784405827023004246784365669624133470780815031032567048182084788495131443428416971172250431544033624925888418865717571281420005106584827677642623486626491902534982756465829720661286191162563540684690252799844733631912205921262283708412313405390198824517128035771409208537285380951508805227997124495119594176756420023939637440345074295206008753234504827854622026605711084831761233774473786493076940095631281889851867355219648397371107880250653101412146580920660037144407754650015291954902892773866454741827118931960302371662239585297455882649425633907357330488662899730290231920461205911557634190816854909521850579018794285271170619591157037545415965783930805881428303379605571519271343540323804752589544983856913892347720000501138279666162952086801842575819628679383618812852018058138888891579013831549759861368482192577997634589756985052393901840474801053129859031092788715496080133187951580405592903062256117091462371186413998238205868653565752496024532870467224284205810027437631606649556100936586259479755755392081497023417219947989229590134000065649833827792570891089755766453122346922730927825391798269666367322540388564600617449542046845860314711077028193923764732601543051631582334540659158130166012752275368941814134123385533464339404574156720269003396798747443417200189142451238185325074958221422999603638526988558097384034441303503141163918281075005849242714211755351065513748326461505582100493409294644067974113331866352018651170066101802373948129558127003365662817562072856504569886996259681533911567112146171115947702603308696978850968298868673803876758459877212476949395800072295097371911882377515472769520866700617180914829395409602109439110577212614203186391493992245594749785439557258893567819336623349403884801215028871877893694058337376204187101419755500833546836223933206707126437543843257593285323743252651647511665032820389297413969323422255951493303896074260923448568781645959091875136634117938625207610524604440279097521484476626289519218770570589324616481005937942798506068264735759984860001420451364607510195931797465942246105383290724648612113178896089093584573549545018358552781973113815384267781984596067132826219481710197836746392406633309107228455300204685908081315206853724581759245341509152734010310784199669558237934429949306256744025844301050251591330130980397876153715345992852647545507412684059187015901200665526267514770019106755696789982822129316448045793648299123079236473601172103700766013251039756198371626963180609139753380731428038474251455396652297696540957531182446505493092606657212124200826188783954944589525333707961537902200069383154380191909305127438308360809584368850361698872143253865472370598928055774643980780683951677598189553703607536579595086248936350937790158929694401970903444618536990198304772574563683380526034263768577834056139408461708417701039147228124850842252874910698963087470472382107695452594996152102049107853897512385093554119858630451014453556291049675178454062216367691077364454940024967213682615463290929494865230009236123632880547557278512220301070356686801850471097554625758138231837148735498177108164822958985284303972365945657313416578443165227096826828580702509947407079736114077502161053252597485207805819167499527169737604987922601006070078430886014295135352615156609278941517216873259474670328497435385552653658037023893615852217785715518478848409533846816255491399020782402149530710019380034653234143732266468122427532108642074676121927203018937448174891798352465633525701988560300239544020070426821129803919747427489732394360098212885124763266092428541592584883995350888543204810229692071456485364845967596843495261589682504084913411113518868225070351101821269336939024822797696912815120798002083773358355516653550236622862007856759074285441634657416259496770153938631748748271336013807362307161896182522507744301074403953810757826350051530209841074372593705861357687294999999999545022486537528706028243119959581970)
class Decryptor:
def __init__(self,msg,uuid):
self.criptographed_msg = msg
self.inverted_msg = ''
self.decryptographed_msg = ''
self.uuid = int(uuid)
self.node = int(self._getPrimer() // self.uuid)
def decrypt(self):
decrypted_msg = []
decrypted_msg = self.criptographed_msg.split('@')
if len(decrypted_msg)>1:
decrypted_msg.pop()
# print(decrypted_msg)
final_msg = []
for x in decrypted_msg:
final_msg.append(int(self.node//int(x)))
# print(final_msg)
self.inverted_msg=''.join(chr(i) for i in final_msg)
# print(self.inverted_msg)
self.decryptographed_msg = self._revert(self.inverted_msg)
return self.decryptographed_msg
def _revert(self,msg):
return msg[::-1]
def _getPrimer(self):
return int(14889444574204132554780645847239791660302627399279532418527128942521323936106447531030997113218033717475283440142358756005197751832658564918429319597082295063433434510973136992053423106411405952647678767468193322117818493754771079862112265347927886299421244723581697946442467372269911156615468898349878577880899273633363565129754335286257452179055411135678548030295382592318290404619188080666720079222244571059309881538873940476999622792071943193965077120657269659128778891780444893214525405268925811066972135872605813039683144951084398145854211844200148437701610642903895817082977059418889948793270160812797274143481859080774599648655190062672294171521513754528281191030824461144012351159456852196747038826579037625519936415833523853151542818455868825953589547210298809847780883701686351419725240132772231534427225747181306147625815374655866269118381029260722922742741591677805540986193572204715936611931996160718058420541094365289984777531682622451908706025415912905755515034019195752086990922805950586823483423433390222157805175447893152068114144372052179721953250909235527812846017542915009972903387013545695298798195320350480795142078820863181303301447893410049938809455111231101759512706475179910893305478968476738845311528956294865410389965240118794320230435982271872731945392862234043546115519206647266152947365666491343980517913524133584754719822227043388948929318395674897931865702725164400479229622242295788968435733349412339814209907503634531584014992355905105152022144724440227062589567552831347259132359157427762069987246226694367770209990555277196120271441974172256327014788875746679124199366714820470229716090665964657712569235389178681061603854163358405200016225195673967146876492494867746446903248286792594583448144637816858382679167552340846715800589130776357209833960997051753835959845972392961630281757197948832984801393805798045615405758687738625458851970408170833341277613140279962436235669244277131822651023538185961839314606582745607505245516679921541267831030874556394034080539903165597271724466499101784698299639425307607480799713800784507146075897701462244102623923688549199040362239051115037239765884472754925261950233838768997072160454726690363728261075630868392922558992198427292657169642094901339854872309371396098196888310182277160960191570936096818063132464630015801550485471753977702445169961676559013908321043252243873235324406663353861983808879451650295622820476518935980373939666631169200343587494296098854279527552356855375126623245944395202991646005399999923801822624310208184982948769365533292206132647198294811169743683993355976987974930955023234966439599006564085423061103428244589439521075497160359822511128949129202231897327108555961069438781770131614441685157857081050023685868390795994569254904531673869187368552861718694771774854002784337628007956776070022608536807517839650666870241788002131942049083021544260824154115722969256967502675661014023424641192963009190878192222135720797145475983997905153529120046061849130603031714627864253371895963724428837034542006561505063169307024058325351104253896482023711792604852022840588383191569450190058072480472099517495817476348119593831324891126008419561832651441610635028897807138233517659811156775865637086084358306199333620666213815032051552336808926116049895781634416898446801019937039200207934709023422449930352930534830364461631359999857221835294250520825321722772250152983777337351921002779593650623241614825306367548525690851957815907221172064840134036138268814342151514895669614318677143428234865095446493955154526689526452138712750027300805586081866018185030876090938309172691629758112330222197228965695872683692175304838796727655081184177480383392476618156442677111164383752549472912149431485949469508215572646573477723467393711741523028941008072907168860689771658207438492691168271196315607744109599250062802538210321592471139254162947630098509353531863961985911999764259264797744453417356720836404273185010339425200153698376923714613517950176039183758908828901469234512472706473263461602717371720516997958644776017990064639190540594127826302581748122203498340446219211021995729755873000518693786221174961826397958078759667713862394146824055894008394118551909220322674739399031646217485653286542347615523569194940849916317599662436601959110847436232027348728328382280038207248907099205796712422114136102361165926818663931224763935168931919560950276700231527291957791690253043866820412828224012493218029240674073139264094285414395261600723676951457825480169682720258167777430204762630739364104286720561311501262031350517337293688263544418114530454977612408549340119828324868844306462641450952397273189851121464910358778782068461128368627428950567272786715899677207491635419043274241727515638015404907847912310553504253203188881204125597653983333463250186819800936176212528124945870243867867323544540471056474899535841839310034779576084380553148557601211071497019290198513589823800688172385432659832313135406784959937017000405736695450564525514309958648972817184053279627125061184618801730847481980464416650512001304348359281449001984369344282363026844069702795605005225234756431275052739237928318212866369463682882013196878851903709910321184124695565744997586698663296368212065482871109470239125925925146373974321413620497860179543363024884768405393381377149145771581104133023724229962864348826821065241721087817204436306041474182174010010044249352087799157896789965536880846023677266552455569059567512452274889115665993453258077488670072582993319098257140715480482827140913756802489683170496545062795113806647452666025473904337083534096200227355291305175753791746506222667300841061924867716526512592202038405216075351873935592658854724018658510858402731892968988031341161657135065109767315103480217340893850687280630217136662497274208015481008678374871767361496208666712274503355671965382619968106582246106672420286694652657119568892476969801498352489267441204700190623200652293394577474764963786111519692901004085678494931900580241105024145944688152015306060950058612462116773405676011712021772936717577290532159181414933047199128102077495097207363539607199976218030061442831392280960920333057023296056079602264802445478845637061562364349114154535998411323684636937040177657388146126116044116886112961748382974475285572742560479764774480923145833906624172132889671221876999519763410271578098532155273764551331171182449033186072162294229953835940179425273362720098535274234010940482972804242949130658354750407455994291106638842850696211314265785528693499744341786379207473578971172467379877559839188890918033511354425957544861324920765976838329521914202517596258401474960955596048740760917054523236248684721224051053757970312577497764909437407825038813339513787663100509584329447783754294417743231667945357128505819874969367468260051602043757236116303200816856893152441818462733659928814308742487658511511919016957147058125553563170241635684154540143542484506368161751230606271994406259945556978883414150243376474900452008945606276885887591325779829514622801885817805492606526533188588994997164961119429422203417691892489664989657245663648758909469700005471508084471512675043922035815621022293865375461254626603672491389115627008613161422326111105512814434799745727090322421856329877583366479719872564393631070235174769712021327334871424382567826346911751421319137461471390061149915469530594368116088899155902353413133905618968149217282362555492768366212821651671837638758922139289463480206358062389006482384607920574600580820044613574581526589912037607325097137357172766532583414196159260530915764646439903491113531202433405097091857554806707519723436355629132710409356491588232801568776039193751042999269379953713170009048874486490380061337498070313187135338133115394691389481099598596780657189064271577599670940317648287061494947654318310126720686001276738963717560687940092784492797762167775910224749480654337599534858573285795922445515611843375361657467002047934692482334576174656953922355079844871439629675916166640196701299039797200043829638150111684062580425956560162106224442288655758053753513646307475882126880628905710468441456489388792734274320929698383930242216749785624025208491687515166469595935705843541741667913756022234352358496388200404212690558073200019682246334888099567389456596699189820955728603745509618911177862601585075294289307292882326966926656564994955700883992632549703526161894580187390885868489215677350382160962811829938800864995326034207923480882570466736620157023212791591962632494283281275895166603328766724175316789352616150706251957267672723071161838553504278357458628737012926456179705922755586283512683865152326213854417788547771625378310466844634684879001978394526901451218426824961147400408921343364949705300702225672993490240255945890849156884018048461251372854941913704401744285054975227707711411981848279233293607782051403412534822822408676714867220887806863036947365954250395311129421215560000027530959810640544045862110591439519550652824553584280756461410380424409564156890418218293611424065833644017845963006477708884154342357331573678601148932502575296203328506389220779674410185092321265169599945428254375197182341784664701186412820247562869740778971549747791027431900771101404799397088463043020262059755401975003725366906826939609556020917577293531045278545434773975446694072352932072513435904684512039153067187952268637908484791667344711490992402667243573212052294355079556095644367455666810106084638255646432709938172673406089989848851005478826329818602400624412534932830136969003372256665498595846330230386454285944237348815900495187927301261943178084688610524512255121928002679226753524800611771106501412134875357087119791271463568784521526398323317913996764701921031465646053060367494330332248342351241451285400544745489051165646398630062564242573151055044216019775379684306297203103633741878893556792933505238716168040401633094785834383360734318689042610531723594213814712426570282853420235994395523279274386614451971808222747726977332223386063431314905711075864998846097222236917809238888245496206136078172933734198762448851380933251919820315835043320508510979763579385262103450748441136275066548410363586352894189960693966242891523970787820811660832434768930116546119628586401913023078398986467539355166878260017276699561065485057899681124288140153610233034607659759464422745240682939725822337883975954146990434318746918153190184745237404826889435019833686013984808686013686238586298713436799504413737492404541270307602170572880412461803442517838105676740458422369722351742822213339306756470546403285797275462429557362819009831904008567405699752918289020260206953109167182312206689476222791839783385430155523381214354908065672359552541891961155545666832439643786197074964154991338725560945463380160842368843337622371691345633160438275691502276296924262379573944621561721982551725550226590434572805183242017690706254473474434125735536949747213077709011618455697958736099253412193872987580716429011238121207553841463075628452546930897823491393511399927725337230005251684331122788060700979551674827805491226855426222848156864143294572685942179021637709842835316035036776145765937885899666948933466373988983140838722043478258455138740154957322251132033991051012963460350600122095731474559644627490395071282422941299367184580139528760894402599396810677646672379768772991286240623822717081061748078350811075713927623701333559553653049062315604134423855049918249843154920445100392665399260492131278831274471618532198327005935635664202087612176806373097549799556720054019626076753681185185191211358252106203855169566759062838999853085539805134028402172523720327940260257075235157098802863414882291952683020559088282113998881644338692317046216315940420509100649339780397560081270620691777540464975377453931146128096526382132306698600269358550649333539141676864238810881295878258030702068273919113481893421183982446315226728578229959616127037824846726691479391821902529695462612872720738792827765896804757732795420562448199274596302175986266444218299565690233317628622586547602750389601666800165647512998827046331411750462266076991301585485915079656567411065761178695166120656880183348005347780046956073440930340098591185631038503817591934642426890082072051615111966444059606015478769111488807998918393539267676562778984260391809650332440267955572884278009991823291936838839765373006849666246345203926728212192927726243427800551609062495967883093371629642151683947135773694013029532495453922824532449582863363240922882972333742555245118576472529339515250833569367762040668974227819784194861468893903918885037040040326778674175140037577872195793337843287347311703392039287069811403579554597029074183668986145772979642881334600889978679174915238076503845936562711853781134216951363133484003511107088800104232701120464464791533453831646006944102483456287806407799765274359905881142984538171780100097785645139260600548491855369259726300321553266337872426120252460155474134947126239183459481135629825520133023050231309830066572130366451109904136100105333887416496277554565312390362061556580915452667643119868785847716541089371736067656480113937210532734066531534056715714701362291205230842087482555080099338302548485395872667455048166239318222592638281700317889741174551039988045810441091842657546526530970708016541840794096945730281736012994941522993036346928078561923188766075612373865149283606312103506348273934220821473783114636679263231746695288634784418746773024524480889576297947901855244040556622856821628700602301635578914055173221401326471262281136607814984910697018487813015328880871297937754468881344990494205357885861230430741926162237643617094486943213370157303562126814326270763262515619993968161860061418309861378855373843218032670672280962629691573404202980401973356180254237370148904743898499462683272295819928821523267210489694205784450935747986394615359319023522058410289309429292344526141635317889927836080631677022902318265993746482868904470271378100355333592626968001541324565566921037533941647990593826962972778461912165376527949664551662070296855895937445802899589892300352280899634284967270371496321596797257584584484207636906282290779606907361791185492386272909617356481561825284172006043682410772200247430094275098185671784615914930238348577112878900312675690400468311863429159732294303279185748567652279371017190100777990573286364261871198989027726519350955275244884379725038985599022829104858254204472102582664918250965853534745075620551922643709843651521473043348450301466273225668621031080676670582083552038037514733469259246369458295973800012788187363617174807426856437507983418077101757966878194085000461883385917228759817896453402469869402723770085819284122142271428548463881068572171591324914291457581777814272046080598124708031530287265288222356268828787126272506947311570766356636574664979777696403661359123678483118542003489067693321337471886474516257205012545338050639927239958617189775369878015946542554391842761733931412172986337251296385428996727958767001398470304637862776969139248120080715005353384908663837376276866453724652751865006604509630447226478431832313095723677630042507895239713695015135594365388321378256360112763122427114367605378119425345557410215089755871139904339319074350365194149255553026290003010793612972226606695766992157650695253581027441132044574161590276885682638274380285775809227912843603740946039322111910514226836261864341237105247768434539966596598329262631893764097160212121612122486674148048884911561602170880695986176161227311983086569310483579487598801723939696005677407774431157400695512360619165168282858495500851208920918720898132487735535655022535687048760878867375168933173224667904616355453181952761211057287085072434538281187121499090617334383140957969222057887029369421129764644317155528282105635835744493138829196889817246094552525297440275942858734101155353870777435535975075731443884646628319826621184122926869451417485211968720211424209746380866623621991286069277078966190128275042602300292249873573049704685799135883687819785501102426125743923525118199507688796925178875687256104807870622309959554827315739564652773101374429160013990081784888841600902065263924942737093056303013673903543839893749720230264511546891376806309508470657375818507769642540721936560935742344826731400342318489718217399880318119227504815020859910187101450262955488747884718888788411794806089708745953305174445583437480736767026743735028708636873171603399963432985982853886377713909954692362301187619887545227739459305013088978698588521851953721337731583740509952276969891010491607301427915210926151135200263212303455177266863671394716947574380483166211418059594415316677775698703837796699837718855168491824940020336404301285850243006312356146165945135204712830604988689217753572056502383793967923604140002527942556853779067155320305973109373786295440102991403449104675244201721440645149451215613624505116502773894529183364913781643233683096788448511533397231148124789790160030329457753286712578111663460167053960298906454538056044432911893305577538564330500404509665832391589152447679243487398337140453696155605396928804335056991968282513561767074255023636256345094093068221430333532350500064153762779908608594782054919492102291998981976662027357739033838696464587995151722050629801080174603190123340055242962900700053363013502081523490796928318325091190917904709804124219003640161494407836065192838882034801083551273926546493651135304885714511048689226652784878485013335027081148162926627427061275959861665396674294430698689150425904203617913258547213973122275438508084187951778438261682928158669797995158809749035431867449539287519710049265633960686548597692654861386167641474259261151520485436728925197150658134635425204890520488423959528039316970749327972123353110548787740704178497893841398530528339769434271306594507255588648299622857219813526118621364101523456347102092025513202364077570990376851977841769259602674051448856984824717162006619768596800211947081503080408379549835415336482886644658349035583617411358485172159052954334049964213995829586774852698995520838271449240488879220670502867651864305026404547910907165192564324897810992324873644921866497503234424531853673433683431915667785772331692036032254582066476018068287543596698113995211834571027556545873245718901512347237065440499581913773789397780049048523627930111428308744862258263506994802715220059416431454771121628954652025364316831189124917143543178065159726124384347389346726054949052034848676199967208450631273009014627429120444754571497463718283791704997705003319553393847153019400846200727495313100709914662662277039419820162167680456746454985730886285088352819285022321851799621391356721002155030523504332860227686781559745595504663042455207377040410687335982733740586706183783747691200435552665962938034112502496191703261214443999107186023572566115410880780712462750843185597307648419385387804923357192034725760533418026876909307666047140120273807324306800991119980607503185425993439696018352486230410382299307703103252155700404199928735639914003582763396792749098499475470447875987353443351506132439732972927322643881077882924013525227575923803167605593186310064693459113634511648311272445273740578549401108388477733087710897824628940555080694533589491848776414697553953518232562268286480717323862066489198848698724404580734006250029843244483646772537784524278889268779501978545162248345004395014113715646952472968350155804496608759698854083225926812503945834663155054246188665721734553309277506232223025774669894286165962437575810415039712837069674389496223989810642631869531646296583103444622854319651831364110576665324497676567253581562136425744175232333499269308000102724163791756674977260451780817145856313522609391912767555554203374900697289155311063718312048983271122550114122010410398695649813959682008136268523477127365886473795666475175421449532574296182309025950179180141915904188800927578937528149568162528928644638390027116955928773883415719971142954090248715577222949229376544894046393104426054149142838225466107094452636370862059281469445449098212181485448353427761949411166880166961348903381067581359469174146410994630833607858362452323781164023197574974507878453915683282721871102486425805433198784634233510921533266569124333692675097783157413550639375214348645990126490351846859690560530081140697344134697905552032595980871920040897667792391282671441449584999771934771023242258818318633184417199026707045550890710950532447180399316082098826458166487656548789780980929362932328911050183938713136189655854984311479878010163273119035270705879228851113921632522194883580639260939584145754267034647679877897151301505931154015132127369773670425291569480539713029766710444393244051060316018646074894139299743188334970617012159594675938944891793891323485652481301262926229871540885736851601767089517750404998367269654048794869258948060685963287059641378764800153080578900825167425144628027372716423715307884124386295007701879967208051830332197365749179941270931970563793802947546361692247951844967899605540614951143095130613239441948506217688427009063284893293040259176642089292621802972765534782710237781595154190678512245893368840679838938535684051175605929841324106620724288913744183521493710529061609588773800001386596796279712050307155689970761394275437947234021886734307008528421175259433783301480272288733285990412066310447328079668008476155435071492084710912701171787840960703100962474469972425694917884853416698891747707403231283719349392339198424278432857678627645386538821910387255702982409670849896380343178110610485609879295781137437735967943703067649734706584087001860015698333924319640726483859199383486709821741102308968165678284493800270038834089239504103489762371831439342644332974730242795339727153950916318486728854138867982083406621526209296017111983747071635501406293497102080303007996916706383265261525968815617167504288578809516186020041758200488136564176306378476797570772482877092052392935581423710959434608109470388086941340582508198250932098605056962879205451784169479328406344816286421944645628694630912627119649003810561858880506642885374134888843227826014434070581008317495248034283388434970901219395317744439512473789419800254133826512361493643496289267270415519919010535395258612131079705352077689824861995451211564842631807921968301535256994391891235229253370976416974325562645554291393318297932301443377136600963716830409186383107330587481988039133586162800978196639539410914942843679246080865027059098036228057578495322874965276930073466552612767389392844349070331699541880414538924808143421782568738348439550019584206314582777781623042110232493392404711914117973909846572750493080125843212150703567414903002435011158817209838198494458365581360251688547025918036601697735354640727184386216381057901003296743855848154390921681885489625711440682898504218022043132147750321199652470455524904411486875946356435388646786831901858535434963076499094622442484025773875070349701777764263406111207524849039485180795002174677553550221881470582785716590854038771219398999991954928404333445180286944964796400423605583959768037037751120146987666629351448209549077774776893198061455211821408463715211830695814380356874942209484612883282386435540061586317398228672616561578778111983943683918739893904415977535147374897972946931827745176482369762419152366472719610345388366632789192613018981430547283570877490068178771240605685908614746700985437130314758557146215740295287176905519509736280118495843365022720548183989396992597357162567865815324026607915651698618329737357112907801710886694790396738944083224959908867118561338238974491207610283718487707789665103761164524421360970876412369652570918427218749285166426605984707410396221976425888885047047223315487713784362130114482975919766690666983722563980407224175069637687671203759580805063193816649036612723836340773466425276875232600490000646498447324034081256878827367914639328364844043969531654415667972857676175079394018027613744152728756974853219881061001704592929642852888186758334516987007571796094714579249720154018380988387516333992817824584480125803532009813776757750074797154902176515851364600376479127751434049525708240122740313599980510602468050099849495214589650146808807217503003506698793165043842899077372560787558433493829881054377762351749391548617276788426547445137551687677499238635829900762540467268733659967141340709469077213274692804878809729360499376368629191311387328506189008977759638139284129054821497092274266301009854160032445375529542130733261465112857451331486166304434936912508115426970649700452266800429619863153743104988400254885131700966322699454659719432813611390997479279488639321911780150070552113493707260295083843250239169556550514226975151612233476332125508041221849596024701227796397286161030828665156789609586348897876382680554027037728716099672632913617224417046060687937262634671765327000343526450841163164767302298412634364890288670298095056439978774381811986169422902953686344553927538314989331736574188318449403686964256112728623709586772155726217179344356588767571586898407748578681852514466000789932705302844822284071840582593859147577724966550206358031170988006151249024550253564384025887658959686856880927769453000942095892561559483872612628341331438091399548330589156361644674053619850483532950084470997631926488885928558208195437425981113527941632347662732043849597987806483834595784198766334355937239212835653202884330184177816686947666770846853534748725822397118347608536181258051161954992310492912567714381005168348531183848546006382217911097820133154499242689076700072439660342930989289021894534042000350875044376895294281969181599588903295297511821512225863108085810245615162026124276625968812583327125547357710704870740964137344819278444425909164305117481606266800495741421531505872501212327152519011582188943633618914212209496101883537247608839994117319448280806748606477300519447518420025053242675724175722659491896542652908108676989986275943981329506794136057329010480311124171768967234152817701627768464787455604798923937443795164482831828124767941415916637019102540525585407603417015768610289296477081010730727289721572679863900818920878864248156143789424464358341316442426036604798955059563565805270501592571413412632146569267122943646622822811582652675327524526333651111776266750357559714873185265725851496289846784730318423495227776519338794687425470384004588362246994382848920478929705175200557407036654635218082487200539391335096726930531284200817380267570213224632401331560189838983382960485783568982628078608457842190299306494356441974107111783437193054211672791247859039752334382114826046062441183996340266827715188678032469795432891317420320529198949434304782928688322673980389533011553016209382269356896217821848568682025832102087229903591021985342142949461637848459289150372505582176294351778897645199854319661499535404254581476595856063836638432093448264699124408499223739646640967038691452325545100982910224295368490901279409733393348406473942561988014319910344451183988919959107799887117680985854127921489432636945424257773315698420489246273664188206728515250143517715300631510410398029243364740043189414908588839951372660227949442392096680829373494454314861244387423532421062966759624367106123395813801309845268643641024396803377608002121110522449576457049580968645818756916271272323465509203937568310792952840669766374698125493865002899999181052685259828761784238238546319973212576140009328864048688760114366252583594871011190857514366911263355245535740621762898485609648992984590305493086006035425938719286098753293535188108989732696256688735968114521721954980439319778542986375670159270819670101447653293179839865277682062765442253650626042742181276912471776269353780857585293646255030336732156150775932260757894584556319771037649059672513752580609417622280583523945177392542571742854600546510516026756796047277427061050019773147796612775872175250279175421253342094079780985294317967542611020195569986044387040302537705935326015957825303189075886473874710477032178612652191660338012865510774655238436595573118171480141131457071955966001167738997349109413644579301239749767518529649978238110184155446502890390072779763763156349657046604603248074615278168679260736795117406658098164094273311195903617870038289366597592350936587981363582671000421186203881370764742364873833956662477684706356184681341238677724436361547826535131900181874083489583446114043650225208663227392491741753221631384781864966354097593978065823597093171210498945032052934591006275065931727460553006050327465507162980208048831034253139453164390987438944698053862794991439280410836053340254252128411545715304867852529733309214562520529633024954142544791301146932950573506833383839006178684787731435382971951118901184447292161825662192833137100574144773657150444082816746304745559942643989660219325192604901607820474106064933059081725343397564803322304832623735810664917513033527589982442636091016178963615166582890805544498923550875253794435710578288565655167286718088426602172366597997208481194605847748080858364393670048482855954631457319577763443673044875386037671239271408765185505340774478778260148222110753571180744356019751849227474509652330448370123469485793850523149433775637748717890832911295399645230234193029729204044823734508467949030621262972874885488919767170457580265755650561255609340100609883110144759070412333706617823915753749151234914197393965808050353680349626648269967305143684862366175730581490942222470383653262727778382389839699595312955933755588876583970722093276469061677365733783966294363402415075357703787031984500428832965789534033880971009695025962132584310935524140014301079404986708206983307634425464808602632751680689752484671587413809529776458161837333853611343203875919037044813725634853068872593665967735473735018532140417082301135972228099271705515182094653500746539198357174722919619410948873884109748340208515244993824811906524240420459236421653635000226753780322092859041223406442480571867329615606428406286666089538873244858022840328753047554461559293547542551567098401114702924714455970061353790604124676815657813219397776429635224185894616389709438064251885930951346580472183675958329480366123537485642460486824026041384490663609433718837709129438761310938209429252122093839392110179179454572832559788979069640173176426784406820888169611792180489544296768872303817825021172492382334636125893081491554176580991119291834199324582740032972740010069336948471131107925853938441264104824332390053782616059743887744417772376653528944458207958230866021667197076044907737370577781698086628837670418200249747763833044653003217732899802391710956135049063810480897197403834836367457358554918901642920334678715645153158066931952865025865878226225155992431236921496108183164060350401069738810220798140385108582352896408344250581741034247550430184509370079021349163090194864770765333574331136422415459953920531364151906624004403258820526281897388341534739607024924640065496694993658085648776084263346713561356524897859334830046251563193585441318768265970310958159679606778229268101357767608179120972163356744715755569771362017323084246014628712904883617420146300457042213446365600664427628025414624858334751195149969257244387714837333236397472729344219403533090484910222270079418789712046039694715452051923418174544053429068493627003442922829571245158394362025272908928870712407657488159353676394271954274658572803429281298620042435836612103203923604626945817054683807504470218692263222881333910389466718088110885525740846295264545463062934692854073214021135863208509424315499070810868979378610029437584773564372101370585891272694377790307491398879125914396675296530551653552443310390609695007046507562912719657892024350535093068086716138091475428163663054160030116000716850344829547148580407858903586930519515407506384090299154286234194926599174085145921211149546348634530458104178810439724627529745296231976822468216167195751498809238435468317420713219028259758176371041490915820661304606307036486312924553211377798490690656056537179170342671217239060272471433565405775304765122412312408750144956013426600603961172257771020441900314201540460884664923048364521440184255887009514314355897805176580864170491310527953997410165526955139123917130725545929027214286931208365711871392339811138947306562957691529189016177295158091855406159345206746883038489742075701234317502386304587968409392946960530053111634191127664036013937568701203162042675723667550571374968744106582490135241198787005507124641927011098581585970197031688020848877091114275354562505902335272971757624945583210780956235432673457769136047778042337214253781721312457032603066167324196551414070061493121940867703621346374896754401868617685202497025235978226605433532317928126224817119479396408529116034977391747184291612796078477470495321239427471698571554449755253297329489232907725210033043728030877021274590880055810512509650406134100840452391942082814834467117676043592626907029872271641373574455606914555671960678153847137195351907291185821393727517951658144982184763616037394726911483786082433111322422597705246095729096495648517905942465288725180739010144759253495211739008083638741545615898636087776154451848865050292763391112130337998263699758913438764521809289766251293484042690564581969525948032392142340159346624865937391170665604020056979855402129380555498653197759343045177747424430290219420889602814259283255874508157674616799406207892610797047607700609569739272627624355665776539852609085370481236699174857463258057580442803227704359803082154220062526894410950866552446243828693281783986808067326183957514610794212871725915188936405556949817413900255699057265642212501235276596988894110230562412737911787251833391040985319317171403233912657093796125877647879525329558883452155146606341660700998757254923754252413901494025121074803201820828603514507318444818726915467474486862828778846867200466506828142517450717733273188396558197477430320261615607789608234259239322556933044542208801443134939280020315657009927143306204789811861771109353677847752770571978292035710742110383429514385165991016229218527958460324632702077083986886901431581406057754709253933427913528658619736592370418869743905276522749886911734726738964712043797512450545778143403661918234340398889487658468055914020904532592989080382138275813261451721031270112244449976587354728334764601109818346995010523855405968482596706950007498992529561332291996325729579227542163577069459597760058367846520113074948555146936195552996657633248585148180031656517550167779195500544002947116917356392042008764868070423036200018029080164485301572316022075561920283822598828953019746583006651503031539067620612812674482345965491682094941493715972044965678314624540745103288908815143862214891782398858998211436068714973545586264641253161643059848041698995421188808818059366458350230511504175766410675865667207484205444972822166061039408416717339347075640429410233496240570083958158697767115403424638933180958738891064955199086042252442546408745562291466385912049337397922891550216790859974802961946818802746572270424596887118554787912531675731716550658475671448728409509041667715964661545907368249058833779023844365823663996406006572430652880574874913567992346314009718041572550697292732382842292874533559499640381855161465963224610045740112773948215596308040386123689934511803512075778897472706436266022638440123438110067074363335743902075531153761160637100965139031968680604129002486273822882193697217192167796225305261247030716405098180251538190906027189591874359815231141626185464313788396308821219071839522889690744220715825343376226456554929173930328399764370966113686019585827800605154560558163498888204724446668019381208612340316779334812762108685895441478566282059540223954019653411443886033512768817209120540306222289507492660857021562121548649928880357499478418009760783599597958956947191200006637481394082869397819555495733540681510647288391550660152072328152487749094550486997803137767223263900522231049688180947790228522651902016771492826073236347831306711331400903536656162284454133871684477432224253066152283402065398297375393781827505649627826923818183250446564410989677218924210096275071403618731626919877104743737050837734279534108083415072142580106248821076282564402006704387265077760536965647885234198970073222809456552796380795100493002739669993760405449676250222871195977059297963849873625632909958384067422136640406357877517306789292073897972010255762095105313952527891774431424167377952741061026810912628105868441843758650146971243189482475735448824167639825036081747912769761524216986688437624174774339864583529720953590167408579805770062041398435345038591743034965593247470960419445623079876798312698235903661971772957785289614772059442833358401295926569330830745419163531929330375280554984644242405975079934630141543296928696978782763384189068216734301754084083217570721152623794787232627659617251395039840183298240119354245103350732188276842151157131358520931753672424606580409601816435650212752652579568083399071237544203720509573288875502834312487873697957097661539723125444829621269665688234127309667146304553464175786751591604062839981990548474753588872361309533564861979696517830332863515920016877615744293766535812810371225499683174918931033030910767741199315124469047828422395807709651388435816466548233605704449155640974585791504764138197179257941747784971632092248981332095560092320823614474440660687160250572489960758002342610415792905802858683592710556832706323205334893450256961643868277542852390262559088738950089082785266085293479220024513001343156744371421792892502364105138188481586395465714993088539392103970911858196438067479322758059489862133632066953361265471789356773602893322699701288491273338129805314249496464425730512878289010547601127810348759423792864385570691391195221831525416039920330850209347117883819576793270764641293333194039976359646320778026429957455580573254114124384629173599367752654067350156111025269279084492175912296453970782168707160730850166292071978825778211307750140128111939495748776936988269314605026412824640071278841166476316885827688264152490113771663160697535710583438105885274231316053221085554695632710889604073007459297138634471629562439905526284579015876744614067895500303062937644452770474159483324732109875320820190781837720280476350177154232189435904140208637378259512732271841097450955182473555363583723418015901770513206788370790483521782009269848570618575235026083609178219649604307874938004112365501678128824780715692788838186873627266503318850294952677863182078491294082136096666354888868435064572533023399145684142010598913707115993438287534295765599428962303879795835510667519095361469897786955055694168462558962911063489324750047224157130511949288193820827666281900183292642262742046647859253949874290415146661639649175702689487824938773301899926118951332061517004594010800418892023947021175647288657023640252362933941089657804332827803048917791603509191040646249123046994430370453218023595186402304165930213242051358133692382742060040600201626837908932766451593083950954757220453273008708583783729704627194226104851955386159352120165485881749117171861472246172898523883828073709792822382497893629036524323224936266366151572529058780063607284688614884835192952694893544037479347294845985434125108800062836004652894945199454521095799786027526248958669990087466358485186481571644784734719367684952350159292697663665293722645762285771424127838733923387965642924043608649790497455124173651932850279256065311701266285089959805173812547158111897030553997443376417579718304219328028813098312812549230823090522541335452071787299642800397513361834772093032668473874436448627090033261961963211739013155067359181262930016090966936478461289275492456879786837915357307325928942663184010990056815330753185168698996099357121474097081712632615670315387817286272214334435698083695582512728682298810164362235155797038840302587976280396132368545191288339282660628216844445143774005604724128549815594544647914988028858138942496421930183502137340825263688259554492715720253120436429912725110909043018828044500989662627802598966616107941754514160795246842600246356533175154937048586318470055337196996162510816053679905465218554235942759166993534456988773604967636143759671789775382419101214705787191846103085548081500920582153014974513320145132157473246341169581964526950696818235382557743540161463203109040597823502961671847251988883886975592447291149136248479160801859287893399360368685271754342230716565589237980316762447760469990315246572265341480905640448327116245362096771180473014690385111125210571874828417957698784705680071660319863763080298588546457085354344792816775329393005611364718033916253308421164722351275271552313759332351643402147807665127522580461726270297309965996147880479730552448919246805434302265122761268955878026191966986672043034502866563948087180051749749627353854292098305590928949928963245457164437790484179079119495101481486727935879378078347940874992912796950527050419976862093512247008377658209321924999074037486362454298417863797053163158258341776295306580343777282378416408055008013325126711325281021610664576898086271506758716272000355799470935794107269547929368769160834114554170838233367423947065994061805642764832659817424504482165357720343972775269577410602584455758448791630827007009028574103109374617004112919923758820336689765797775008172732459855091718120629623070764836206209904957810180429068175160110703120597508597187501588042399873782478964262152316669918764756806475832352429168716152682722782005321597505305588701681970984208960925417057613971246320752047095201312970696990491229732377066624538739693094269350412729350058398035876433798722279929531590150213233034548655820148381989775721021180203995544598653913121430011806291244748453043253933928113908855083171238221822097115829391786200317122528211766326515456360569323787462036227401042449498420787120956885359040455646201426137198928857533129342923703487524817101408736063402108791415903721544318014774642538257916601321064511683813417389231889046452417142162441555936005878968431450049518827193907020386338092959999810860494542642972530652684470255117873334975369699511796895615935433669989062171432577344274609992494710278035053807280983659967359537014941341139868354567977707452888764419723881514653706834310534080291135648388732786076569250671704457697575305602859752903065120860544793236681033130966849925023432468548168076535349263928165647971352912505668384553953324472260367933847070013293228381129603000235666627027528846961267274268358991513021465942199866942130924584061749218390447837609791321337722900485635643280412482591984673942115501079555486989882709122718921802443306310947524058722877658546060756886237377331806108617804343847248530557005793090215715017457889734688943529486777050308370213197936200636444355837629282278227536025704096728479385875773157446592199042750707854930054672880538558367085189533703796890936316728777541745556613760091449714467672734213805725896015014720043370845136243677428898469641673293357571188836957690513904181300736517780707879764196694289906972373363846076221481615639289383657207732289004370903480118436976869955581426557428821367832537112488099457581632542193993940900389683992172465622866784541242854480297826278609490707822586721075952094033438309514787943285287735197262202750314612127156194372319576273898106881537562613305545545674708618295066120091091335299696442411021333712550220829444041108308838750075803795169022338521863308187504486686346737372070405017603886886988281397938548937389961822702551873167700062368398740808229284032634557522643191587560305657994056296574066155323628868654255956860856930982766373825527695577487100742600786028859030738988881738659375302926193494154274398377005144256489768013321007312173582472039161405919761912176249920110394279204343816388841611995961105295260250881112949855669346332298113574926561479116746575154108269631704160308725678688522648367246660206765001855252923463358920303508487435828100826772482203436581346860479504333419246968462680203781896650166373479794129193551350775517164042369220601183429463191499014486712597632572460991145605829118117039989597783505201391282148901633587890302539027869311836168542214530195870769594278414719190692098721489987181196046760566718432155854423343262805710702070069557341642728604914761350421962525343616422296166042590481126336030624319519294435211049276917691542939653598988987259717506185489405096903205583579472841304092651026823220520370547226646010984315285576823677677357211531525479152170059057732738148784072347040277621171593633802645056882717357200683354135692023771787084078582733906543972012857473211296283385139826027285170008173446038743823313774363462962493559386537948721021980374654998056010029087720202310139810536440551815985737979302060729658485904645600057689268716560438240841656689576137363343656010874234939464584843881448723342012166832026541158341978369637962309805853741245757416734067399389226748360074689587002944436924512493176909936807102901898158576719756124682505599405231086032296815351744586182747552487518308878461544515717365455307031478809640376142315082152276103981166797318371706148998944995439424822493089721041083601016651395053599282222958371459993382483993825828184018688079060939238137637754023488918926585661882544541327695737754089360910518987963765458708325147403117653031341042744907191979319786103194047344124854288438490991764543930235828011233515336331559415531919395020226035004954249251483741263629430839142462185631753827568086952183860279617301392032206718276921931222335310515828137480484587489169611444063090213140306027674166225280204473279579473886580865057887696938228959595211453014598578499091518469812468940778694115831501796364763538893214076428621313670159985365369379967393794155549752896756641551454699614309405440341351367534984469884682004675658243771611223577442450964883915703049888534978992148345937764003222882644805873472839791677612931213179658753182462229492400753256522506541789326262710929592343048431775701600929288841855443461075687009114075882545700279381676486935742607832144311750358069468553608763687543761537677228551609723146382107384958521538147341926045105727822129329128390147351292429275355471250240383638124523412934539441106472556457197752841972384627755452172228127028369709065532982355547521728784144066510676555522752886685948969459683883814598133365745709892273462417478143684587197717850654988715412142811363193198547199967625188884879829565061321494676231992698909938381301871247879143891055609668028330592564391494678412741160679086581758770326252945479195664311651368405415688121649608147325285135931532834365061942231130038416898863778033930477194251710608306009754053920587647850820047641353899802547976911790586951517724234615788330615582079363294379683983663573800520531452974136999814223495719651829526619175558695650441720675172583293703882324447371202110782950057137951871219187649428477787247443315078497941305077691714440898107767308309707837753571287366901590026083820487956094929777740611069475009422767056927425023613324188252542065714663519110856434143970979557471790076227611250179211053007628941827064835933427812267390394137442316973334527039333034402447757024048964198008222506437360142027306593006704477503019840177087548476126522325381652052577757243846233676911203143737346561762784375891601740794869812127941626969901183481230891961487360788883076804044034670820522583123580623950390650688747071822027914524873182203870980250135555299941095642133168708122566425942895684203884729148681775218945067140230036714197268838629584216414790752422004230927494406263018187652710126347362747748244222517735450163316702054844271605405417876909598200279448384237734349369673067370607950578327017154749585490661795632352226426871631748120505816282991153277650619849560028773614439701138016229100635735242023955988477201543651186596580581231907321934873859028968879237519800513687952685840747616823566835772317631419909220034224302880258387177348463123670932144116109479688738518983411513801589867419288621218115182358757567153240629863009575737127851056966296222157735598648303010319145410939475429666851399373246996824557264944736525479044203114062663037821692943975049876250877825888426189038138504042389868898861842597008272269571190708786583723442224195689520693674628609233425521859646697796238436572750957677205303858514860534158539898953823472226753234666974673242759954027132941455323925960586210690141608166608132706051433546951470284301062588138408275033107533245243312692708734652861064558182658268796408747973564500281033096384064389692458533897703159249685769250277822905465490057593893546107691871414102363241312900614856325571700056516480937541115232817123885746347395100699875071667682801367486455012755466965098069096105253028275496271789430068371422573916043342301409150587623923574502100877911117695438931131691386282134278898500307444855197680671053895414309444808310656515192367139081058100583245993852676039129739566657717961658121133993816515125984903684033222166209441902067907645648879185031454511829251516108293915880068039490512035257597203850272563411612634908819980764400589285459260527998283132974137216799186179358782363185766288484177872812866595585724640014680391015509204155184589675394098607380502172406041320566320621995325510689985014558276600991215755012864102228314975278729741809587202775664970212022273294256319201636253966718837996707844099094156838496599081743194583127136678875767439661766452320832816688237887600413398001747149220258985765181596265546090413425020722482375724237879412339432284145990920933804405877865260580750178516024532957701954474894414714911777324669190673190480862289944867310241987769908924552245620340284763647857398046568180828868754957444750841188365555838003155026536257872179893292054831125315005775707408871997646967210176793650659315260930913368036072484954041502504538702911058732889278140431066800575079273921800684206068013376741425836543827615808834975754158191583353204165098649865627630853220912374573456430560791899602564357312466915943047925395852751114333724676035327652062640223612751322346074919443454005310899918834933712330268559539109107719263848130373621694358970234883987703170452566647946824328422324848371129552469522266960806136235980318139033519683095408762787499890767130088717247219387465572910830866276590392423301449744211190648853740627227435717572141454385151688241920429698228506590217690918891494002552513285786382530175893394354230623155538488997069110333502584527527172131127925565281719995776432770337170763310067707453277185214843806970148975924223434133673204089389779608302391240048770349057794294041543503815868444727953671826944629646561253263610497629567697995765841911953512143016277311990968669831496674905609543751437084879406302213814307832326602498762850735192795331773254728490281965346455884912018275747698057326515175448297819767129093497675651405525805959520646912987520619901077374489947591657013083683236343732843970416922816087877260164249706103947984870421593732747362495448528241015206358065575716971992035331028052891664395830671281335867610234162008713899358167607351244448074896772955995304186349054896541212894179412718048834567216807842077300716033036154079325414992380981086935792415863953340679349484221646774525799533866165573095743663157675736762950759009434621397501034436337698062235868160132343449537829233702240752294107207935975156800773596998327188433560747489508910308952271910345977592912617196336143113413992009955872080338922050315378835675715766179269631505246230130395977689467951647926953562080671440063814902506163808608467121485207086338920565951304101425334878644615246212337640317215681263515535912285217433815527436444851936540465016856840615079704484544725354034440188630369614508098640201973248972559258125029673293997055990963598113578286672353377394271618323234796616292805285062935572792191997503340119306277876268403229297210251503125150834772003574684343316391320740392073580198931824268625962034044069217156975856527362557392137780792757270616011805102921619091829550173412639567618846688514101664228712006136617436890607007036974515221969033300435002483151213106708960663929624580552670796771250928605716092758926595258567350968755716156852641823904645021011874189028014939557333968201273201560271096768064223269316486957625662950885165046764578028859231594225301503380592166900035719604633449154362991121828560433968802693335752833419314833580528571943705075829380693993881556218827059171617998466876304500429728261681246615204329669581154744990433630340134935046030047288468751007536299859838094148253669042464437640273539804506994660164244739009804733170823759412856766489072533125950049254546449360923420973440276049068794275842582126919641336591155144803071373122364544932741488407146807388049455020586750340449980222031501785086120944993247590752859783548276047195945764504312315559526711595304598418190876282179696185661660746263239811362388022840441869091993841629677278662298746888328759389265051733741756827006302790526638442069160105750654604194210440687879384772865386672590861278741765861795686548523715010827738093441279271516460197437585711617440758812598562685989238455888625231745675491578320007890493439603971998384427421496197583274042925273560415847618020996421375851595381104298155510881131529258734817420582985261692781228366139722121930612840393160884953896980027444491900280527486619806198872852865941583694488960811436016899616605484319788726498775895753688267649702368023913998607944150481607429222014593293043819455161830953379954626068953463962255506853512097198043327223713832798435049123857237082744901221684696799220864202155631404022208338040852613399406554441237703390684842303419341406112131379855291623893888583297543463301693679560002624880973808539140803811285365213331909212800862429825142281275673285046190988552874838405131454539628562249047933912011332818485964989164301741762953919657763273819916628019868699528144051759823352819456710533238314980250726996282675012532723354501402028242364355794380099627331165180551007760980358022589735957836409629224077096739145463124105453706019930627692102166875319521294777075170691416358042202569291891994939177712909489698180014903911649628117210108318049581187926960851092785325544632190846665213189486565663238930288988768770015834251025738940717517151208065783496811022217690726648079581485466792866582978517058428561002088150907363575627547422784736531857798357126791846074953901359817638347025783172995702464819381428265209852967790977350706598578815204533525471385895325750677914376412079498125978613600967396342243683160460633264395806884526352148334672966576407569268929638160119510657242126945461348511912060199017825177073180145121584498622316325767608876261372562335555972313166631640329531231095596097936623902052758253061012561522839438335999194698975466639544179464200451964962834685382437063543985374791915362376606063605972946608510016925522240517422810235168265025976986013123832932960154084946216227113074996975665196080221929509332190163120329430383864099787609895860563704673257132285390506234569478276951011282511342131474351310195525662119264682765937375002062723682024537337443172690765611467316714783639970214722206165717636236704867657319519394530200809556653542494374770253018746983009154225261513679694053529284552614067250450509273229240174097945167767865395980032579662504738520072635199386531404058172463564342925340693072688969908914864012903245358941402222024700907615668846954553922803221063300821804630964295999458646978961610196165422397536582163089707546366029981167626204282444697416274906740970601243089780335316691273482106718292649766148260622463766083899576377204855595927742188526619069399772333024496952393366586386893817422368497028515736297525621736516038519654638008409705378338492684501167202372052368418407951140275232059204157434558544386787494350959284168649810460856141707603458502750683452204716342140267773000666153793900833896851906063603023103246268437131104594060678817229467982576230417554950226692620167887307468943999064152939635402455465760530902582048235444146350914898813861720655841158622461237978006683152048819675741847213312647345631321678216562286805188526247314591971197504933415145738673261081465840330673847514952090008426761634056468290932812455783615521854067421561791301131039407816332314638345606818162577433886930767951789012203242057995648815857431704053488038568858036094883435659861200354548757809323402960043474239924559670473083031950531611505956689856543911902978461067693578672224783531488630304789299465737510906740749052324742161615076151621763171805506099064423829638670533113474652246172821260949145601925028961811735686199764767019207396019920047720047342726764325849158632132915123472117416869524183220702106232033182063427512559433944777387566513781063091623369019307104504085299647403251627540454598007616144290889875038585573184300206536266357332994652128732931993628388984212974055583571292445745918345772430943074343716236431945019087746085927160477718490659001215774692695428955126458405655385458894672633584712654504838565786151857318604979728874044954567203100018479613362607072316087784064479299559646353410262304894896487901641906987731217903636257862047940466935218948302022836088112992146027464991549347297236867192527528819919894048815844227146807018419552864618599899004786317149665253961048663242776307639457703001290124191219193080053974761854072820705774733476551706805690240065854395492217919621238755488530104047885301580426372722214675363152043156952686378190746620888515465841012520981470786036895566233551502805762108200114692756091002092847810259701002863776765572523481428411606083099077593871534130885596165744706679101754285261449216184926115233404982587339695665704128735441497725440590252096892828498311361669199071849948024947553307276246490089274866018734313891691850833661555253091455194778949435821925576201680373254023266459140843150763412259726678692523668850960324468070472408643500060728705306645692576690574993641562460264632827259378964109371830023648947895808686952642192130996879993928985807661410382276026060719152308925835850246010776477845166358660653099360764626796573917881622236279998616589050081481560987057191095099999656257349254252936797802529658738040289584111608281229210185753728882279569174732180684775396832719821979607860560041213927175523364218963547093156085601516928542034710142326626718341966749156791828065831127006710901540054547259193894229307404156039535294420515814500979375109839052689475868049555011053858924314596344792387266004297891090393239970928127464721041406435218685739522287135532597142073448265404209998158213907532617271371525468142454413980085275313224225658501829812684932897969728305127975491191274670665678628310827622751410320419316691607388559948499454158654694706455881786381279793419882058358518884691715555749957071320557086341885470887435719735176110493642934030690517673514201573685555315051063239400790573559429336942511493388324971445635944668613998491429009524270821136314802818600682463877256793093622520235371275206389256854914787673726886368740707487871883758125120277558441918176998921603691111761823562163388567316843342760981668481052862792910890515102331343716648644252736916216300390412940211866064808836573452969104183706051690016605959091425808298144362269189984962240949704822470864898416882035573010841841638875384129401956920731947020626607830604828691921006064678611937025822877304227020808819619174309238815111803670577895744438222634513375453359263104181956680925204915314747839006436064994580108576988816432253112734455392398312746002058361944964152336670336553458075054343249070022145614096246226385306460993019109630791626751846176574630389780398780363700807987963118814520335016689292592021324284855885256740257731031713469292373853347192072084832458947378429133819395791926899789756441580217513475231678627223562064280317322810498066157227230293363058672433871347798625866204444074819905676063952022440852192674394152066450015740616271186730835691231702183968101492363881243227418740675188730187293401360659540841663211576660565690332122707232688293518479368091124022983630240070596878171892441061170783659514517148152390060386654094880338914721126488227316223995422482028823237555622908009789448047337641425175569651847144595793037841001122791983934520312320360061702434744956251521032511114199552346121092421744704837980066623743146375553599005459195925696297175587402701308398988417205571053999959807313995093145216251977583656569851053319024216837346174007852726453692574081270005073582572308193376618554936616798188066212262817013350489225769057295679188382738535420420544532240241624313541272701400154030407395802292716007783773367574101693230015158768393932956078853081461699923671559348887892987746492470636134443852077038441897592275628894913169908598582521028581989740919582371951471788046944702091601633758214840204414107711752632549864613459116412183384819042438770951181210549739081711651389767739192541419900862413458678507654832532734975977110004907283982702054616517360761899107912442838615512138458917999690728333064335278076928354999283715721108823592516194739775872303787862912741744184027359623975182808433504556230918307854416711798716507615869370796264364877006271115441988087173342748378245838556394819101782916435758528047022541916425426256599577594992729355380580208637202929390097811380680894071202244637832063316454857645123987960167342582753405082329780314037185917414553329446133253341142837143039099091859138229058214593561429223535384906531678867009073797912559675590528255913209400388422369036944429260107878333955868330415457367790684717613555178491118570209716986379187479079095932100987905818890068779348185536009333986313535615365032726574026128022114314261514309391496400436773330082376786409077334567676659976425913679972042643571122609661333152368884185044060362308310430118231402948898433153100052129083788129494704422118509441674107248659044129789786413391537771362465848383230814059137578051145833860256599033475327223552697379757964084540266780255155886375410849819278287808446352585114488567829852509676725025833275963197205897630446510019468726461640246398738829627206874461662761622994728189621766331280374771104808038211736286391595595865079907422089742271891943446390587644209026143396812551932967520827042454283289976530331180745754450019232471777486480411275729413595831346734790532397958739585343406168215309049723581996620515406352509223034160604742695552806983846847530232987611141718333888124185365617226176228395481318726221241464452154053776318871467114457889710242833547597372978669678977382944296884716637975246554216532753729118715159022548355711556630437010025597524927975230675304552399079666225973189335269059937263201600044632135372662553291185812467999358809278117655443210430923179215932523718581233265282151510281989087904079634144214152463022212423827056763081120004013531975513949086478052644112235816358865767814477727419335820322255371352612762358042942818357273662618962881287346660166996503261875323294895919044804429764979348855632554693032157292398257336871908115392918033415932935608777233407278197817122030790506107457238232468264237711456306505653867847336718179023979700736046961049264386939424613159210053782533754446797606272571034816476760843899572238807586906967643057024335349347257259312222767918119138513266318691843482038732784724534901619079866833890500083162852596947859626039319456719534557084231140803422887374009198676025802064875015435468232341301833254694748731756581161427093828463055675593628080052140680597447765980194166890294889194394351682654783939394621654878384621663442980642508590434735710159125012097875429650493801345360477300973849130789513258880020103236896096784181068441894687334547467317073056767523108752350323923858491320580417314842388590618668734009556357091185440371838520461030927020583181156012587416860091726271072006861727424923868841387611153077202733157484809491114634323968529068225262630031425899437103163189486222686204606011429099603129241558341999410868023409934802218067993905207063668627938773692005562556440898415959257377868211002764618676485771757014144801301655654272249994845091427409663228383527240984754021542649553617055048021394163745410537731031967333896690626203046460344442085871131770160521886464377840832642025923296559991123299465707721528364194850599212395599277482892335771767490790591515075872910160996426273451910944833029605950170976772002517448070845053954420332356168698627579294445314356752328566397535248811637107370524493714265096639546733784000275746997721161080740749164170170944490937848067773491544691530107873958381762335125662509320995027135433926575296158250310187339432101878180722593963966094271134928411443910870277553061496246913237753199108082798698510266160706488561451410379306800484779977119533081533472399855410021114691202118898476840942545492820751416614803559657156684532395910742279664467824285767931023602999750206791371053975970856915769668113655560679320939188280580590296502249425787091911036207693789435758675277647784796803584719993469318314616720247951461071206349238544670001080172559766379326751491258564269546852102242537844084698037615652525018213044547412080036594772419499907889351863644513181825806694127014184839409090549627425373506976640102941076594299005669832720747695967255888574921973643159933911248371464831617081651251707651317795104257337063821741691697514440803091965404483766719310895117235229974967498713051766197247538200277531149463839292154555323146842370341964145393263827347801014286690064450241442449548718958108731437448061999829747146888534271802759893713579341907645800128529717992213536857317964717543362674394203122009676948853772986361657039183608875354654503129100857707316957959027321462917740802928786869716431353739235284224314087728521516212318150058837409248509687661816158599844496576451608949651000918835014838825746109918244031609417336755660941385979205789882508267580199576445147993679381184382308768101692701202826567140605392194521848327473493227307376465859839716477203047422003912227432168798945476270802665559844124222553621271770138746903547174279712841404958843106326793010835945179056176184547926452859888835350286679372086715769645628998845874324685168439986553288053319016386013918078191344017330820322597657417220485165601160859482348465456807045465838935013445609978188213272521450743163537952374085742437379382416595810308307147528127562653301749891242359821762029974399299335065304766448518683358353031868290256412449657898514382434672411536165343081475160046508289546814293239908520443983396720729610606385030530231498211844455179243876419230741264832411995802323657345712759655116019324781077051532800676038509558431490577197477422704368668379149290988227377530675370136806637392937541676763128424889456705525501335713715504596102315398846268758458677238215721490056134762951035450200389001452862283949690174563782838450047554048100305173308958873315368223993488825391032235343003643859244597065925162226968993224441391845050044619722036234371176965660846534323871660313653454579383495788197680696578307582421621855352748480149717638053520148230729747252287606712299709013903110844480166118842662403365426521209848807375485198647861212542591548640272859464717236228684676903097229800506260747098890635728916036696747689685111891489067467008076293457385233890717797648913917858255349992669550862821712741058128707264977866081156987530195862697026494261996519801118670372822603419983419554555419212739191403977988424052709458810782348800279689704041092796316909677394580662002569684613617960442474864092655880631828106286867985152234527379847807152866318693734267719564564735874933864971583153848980501891549415565625008778114912156677984961089271109131680372821306058074005174822912410202285932081178299166347769700800109755053975739370598685518157788184918887714821868664348482234456890848343445313675761173870435148558756185015242518518184864669934463685073497899516663778040247056696240497521285851452781842498039415443338751614203818699873208883458844636715847791525424009894792412701612859392099276783027897315808695398014324149886295640218729370052574997786506625578353396527405392079626489456853612825656031743454383475265002169062470404803853788901443522354656047706014806468655785531620281638678920361491332304666369905007384624160357858214044229518387267085640260403863753609986268446202085114269327193841581459944743196518841009309662660701413834402881598345243236205254932876207384224128768985442997232372358266242439444913760026853211668685409810128989160507523931226960340953340825140265822100948798753900925308763496617837009742235294495399867905995020376664333095721818889700649349702999877903563248266599405355323057946138143283761048911294137365347534057001637850440085553033579304986695315434452281629363974786642175782011030619318294531457882373314062106910498675104021302054794190561735994223636864085338128964463040715155731984072725889145059598846535023842408875221146321066261835769213866913378305898833662195658757123623984682264999018342297930814073277523166806320227900561175544319693762004931880371703621561085377398837558212988003300318771596887427135818332378354743131741781785469253852835080835109137279727857034933450323338903833828644920745613331403447813020615361024365091727298312061660544374432701220456356907334109138236081272705094822581386481125180019491723442200095458435719416508249360666319489298264956716150249216955298951116946662352611693827513720196751868341806972306987494817613168923152212610979933825146918492391707313499000433900741232659028567248246874812806134679535350756024316406901745624427327373514542503058802610877420242337124952627296097702098975635551014433875442559840444800511276335077624513010539731682624981884157154802504040145369660246382974434680453559835832317714890994042355651800981284210324036044572285559430254552544796972683528281218628840403918635470397919690463485839006446128039570417258086832675634319491542808651521188159344712977988181663593537159132265123473534013562354869623128722793332668793897404507384551377847276315555371947156568238331838050033723041180296995756913982263735291545916339244280895188321754526437923336485744137122215515597480642824463751228028340657686989940831374992749483097740477461964506962110789725866888221494710141203068680185524330558376309988759464641996043642368799538629828797190186327326906984518766167119328699465154488080883878778009046899618929858996805927598689523344404200165272860297858759653859909306414295160815336818498794376811272453074466902645457689293953172964964967609093269972307192257700054041246783001965499618087015938270586727390912688881695924013122944928427550636746309608927859005744115422454172307869742117126238099035208847197170624979057997907174693487663918688221524423083920748420089722567585160428802586612027238525191448035749318336979946685177823208506268737629268142264973887409721103511489963691791591841240748265424654634719061784928163034919216634999131587862966631899058147844198482640415962674022681295030854773268274776951482064621856713648412547752836685831449107865183926358030564165376265598416443753861916649443324836112116352807589357760317066705780698425166876341979261911080832036643331776934389934061052284040248516300862448586510819088146814541889613405516363178384684980856670136809836527803956234408783346594446483552209467701541918261108766530734567215788046428642766436911500105814923057938662156899290814204048216534947727128229840083198324487874086706487050558521829048104682576063017856642553479936630366879342502758064400088916288546867386793028676471251458712739320149316841315873362532473432264860172447424161125500571047117929869692537251695702190036598509448090378500038047109961500160886515072149728699544826123893075051492209329940027621469936366655549878648868356440092548773334076469709520327411878633272943626397288104784495431347442525870399207511960375196192813125890917848421294925038753706905101680574504646429338317851977785812592759143203376693970591828672723587495760137484068116764186888452240553781387601936291893807278670045497405476366839901329186996999770911026156981779278808764407981614883087010398731720991249261668283840477123937613751303966984384939627368123875070328221341632062684221036862177586461387504246454212031692252160223880357359779557733836378100217078288938352066313068380685693246534522629656533675558975124614965522029674016706651064591158220053986358981972827135993669949580733065200720974380100822234718556743181489086649626985860025886450544976714813438950315833852353151985872127363457378696534517525225664964378338706632550699662899754082782608153431566292051183999660068940146390303399529093073240013483004473681911941404891555203079511160257496090504924634750389465003855765300903681168147182735913401344248299833713349363339482896551423907946930446086163195924059103294562646987729355012692825601587426595508373594173939100878954612934994851256344771687614389096588767598422066942406871695111734664199222263375062918084565732317380014210642048690130090484939459115996046925385923772849998194095132718821215767691420539561784121793749294055833283069255032069422755612385725664235362423303572722797826901668539668814540361677177680180957535475656143486257366310611233504853632324861242170779177395514737315978749707945691372768914880425889442447746882518299159309709863338249743593669193901001424046815688209462461998963727899759633359481495888211368488903600712824732649984814273128626628610526935323694226809571576035264445052384672058682344297061535481006950061290005539835621662926384298144082966075739390194575784345029478642046378039840870180816127766162357235539601033334540057023141694920823358386887357798596852194024001929672803799509548551245494580186016123029668761735064024699491757019985978142384479365504984394268183676905690397620944191128482214032772493924147254670766376576721094099176112177586033701112351665564843971894200172424517974372731115528575694547682872572923922704177158969252585439406431929074351795718857993629803357390354141838136087669757156870474095520349341894044153687844090131209394929833616156991357536303068955874864445585622309097465195023539645674812518464743797555379827621427469351776009525931897567748625062146440257006520716720019860682762217830984730659701325621677484717596024994053933484032373576822547904393802455434467308831943717770553895492871815520619511808080713006907083123071974623919927071324897914890057634184295795106401197022697338600252093366417267844239773672301519343099414211992922716018307374643994801209952202587276829022580571616419618688893593467435199113991405062673739777110578006328129446323403916311297355699876114876628529325468112417740538080690468412468644930270791057535631320504182779624878045433039935953535277278851765955846828160947188694584648101337027281781142268852884651790047039309831636678970767027713868438955232546309323521302691731966229424308407100809524815777674357968812495063057566422103872375061312102454448071572633922147188829849755647052097484909863612950790305937836882421260253081026051364333166242094526436649512798619880443919160563305042210644767261707083441854487983073462389495098103851739324117173613163811093791665916553344962251625158260976773386290651818230096275486114689931644761441952627329040490358481324268423852328683605739547435404968907644957487557062768115013832487800909466368549391719373997754633232387456363605979013028590154762250623990490557172426601418883783712757498790832874715286988735349655473141420330399216610091770644419329685858126931224721313153028761593394454536981971324748729654743020187197672871879473442997582238370543348629231491145132162027989834979644851572484173216375276695416261680466879132603063543541404826210835011652637224986157962089790347107224405557975537837559430166710761851217298864583106964917591477075684293177744011146199900745718497643817527165928401716626096461344227280669388711570110264633980313520590977448097348132161735986138822476438559231505051815878639481629716683608597531649976819277632824049325729300127433904124781388462060738465444159409186013003778482299817915101979861354100695721148030664353042215358869191466984073880436091689719592808817054124169961436873681901738815169512547438708236769636055379539487964616281460839768121091520710135087273979612302634303319226212028110044149945450329663743527171836342024836532753285701801625956721292223365959245846839396680179999969199767709845914658137847802234285831268684231071121599979689543987422180535242703186397904152036139904379771925313102758953051892358995823630876000678210071196493177474279682098125655691869158983015207185667938392882571235022560018932850677756377074058807888927226182520388401168250374370359889202526148281249197673893692083565966969229257326958941858400685780975331276480013783298584967999044589331580009856727908937877558317997017571892215680870614829607536899151225475210559411702860721965442214761832766251360631615564652666934020548884008341152255699127920378116263816004916383379446067992431424543378133621580522278049005173163198773595958630550468309357396329494058617934494408422570158500652928622634391293916896098577173090598741858138097940782124649462630777571164506320954541479673362707460104520619749037201509154326124169114623596149871299237279197930520204575010802981454905001497192065519439854584709911168811453338021735849812160099820546434971283730936874074270506124820663261875468577948980285283771818964722138737702863966216083780005702147604858535594449912593074627934755968315432741563063411614475990744977215679919433420409324779695763341542203124565248061287199030744796748268068893912235822393656899692485964210590020587082715292177307790302233924032619510817958799473474793614079864296464392509672828712904356299366921763399607429961349519051009253542095362671579700703266716011191599961996357392432523480161292603407572087953423502662098080759210060194273933443923355095832764104862593122708984812885231632222378757683939963065832001509984317358807394120609707003078567555023051039219601815252371041764941681660503971551824734002274513595005249176636750437782527983558187415946389371021429698227291984721955526022467301877321915182756827468162628900894564485114106712690269967548968693238832794250577317690770005763687388997941918944808880324872629299923969122903375554678593107270265383905057643057268225069071131543800707891127351727818916018180407609945692102700168686306854864515960649195453982328942378762566512914443000244437581349119984764294690287301276132806038196557496022301433228802024184760988447266803290125863658802767777620217237370434475966820261795747543422298857250440393062546993959111695164004412500092479173474467840787608409700697911059196446753843156778366727095129452266246462230907946232722158827418558647602717760792074627130951896196844392865521100170744905191686076491678004164201521084473264289452318131542302287533093757994172028820585415883003237279152704078873502692311373498060131058017296793020324276723981612961711401385523406681443937886595416424014394967309233892554323901455393396097501083497101409368712584097416002013557281817565341448244478832924166934843769825371253367001398549705459699392873581456475111278620855645752291390655423097368776674357350406149286967377177459929179872474020756076136457201577230147194154107228367074376852203567848450957883129766296210373104877810140106882943258770806121948652948971849258482499267530142183027640628671991552614803455782536180271696350231015119214113576856905146614986934637596354388307252133288688324546342825113346865849807141071340592553290775424548028521435021165005926809693809444099680586761959914252138739363435256336928052386437702219705283530737961273508988793109422750318368164503500910585047700960875481400989630583679604729080961921596957710077229798107831204706858272161589278766958679847482940239949148752025174436182973178032619164700986480387248303337386015493300804736260619060622314522495141656831026561189152449200390739562597931278862679601594310366933507057739759151772539651380466601070009280261240704742820146543938335356077017257990939134935931275863406422038337569464693239889004833778642146543888691745271278117316501386151570077882168135563350294957077938293306994711563381206412773569287759175582867891209152999090577354656919371660331154239675944257171796812191674245398198422402895925284312321826386730041917804511944536162827343874957343858253464137679920999396712290425475922019837156979402084068274560309915423595467188531067552489789761823985357015792634183207320848664483617939370146475628854637880319568368204489312079826883759388345301011941578081943347100590382529992498820828632860004138335449266418581280108188381297541191126947626644072489193621001984330943827607886124687482059146272699153869473764212946123726367071016937873484485783467741880706750114370997932258989912453608904608395957635603092867789968891118782783240676299339572810925551467522523046734253230212002743208047905946649395925538617326897305296578865464437737473374565094708931637117797882179693656063835402501702045286241061643047898604780105856540625830274353792966032788112081156638869895675526345259490153886932119169882761840698826378279951492547551091756112092937241584864593554105580886117070216089562582253587334811552437615326309043272579728161457851240785767688440382304182471663519342314296780942856867274804227455873576370975214771692344342461264977213187807214963139978723032384259031806576648797692274714900668960233302728530292848358898880903447074109768445622280306052499667018142322448204851310018045793035046424425496209355493719227664522475353611159757590060456035592602442554260658621545035028097329340514512281615077334033051576950890553847507695861871397761877100828937561274031226667752949216031002354290338431535078910108968413998059176620020007847854156608402784340599500670083548486502853742215012353497247368741685938413628838314141659507437627683590741173376060173596317909744854772113035540916158940866361609588919771142571811171082015394549383224455321191032232383739840434301718865910418308742627413817693275567920762961829884395138549212386252875686653340470721951873030930795234403159579933065238568493415261352688316548098289828171721722317795829215461649932124938001674462752231027051195147296429063187425884599948546277141361296968258837689210078108763277830519825437218050878869482064274292331829379196813849009660093099843249277000754492671817854990220724803310707495985179079829348661161017284015432742709695994851129570994602423489521453140529462301485298147836006374718420271470790269496133518973743088094290686548080128212325058751639487303386937915338863037628838581509812047285941675784425147784599609538852978666768926375326320402582069011083496353479178745735096030524378824012784394183864485959583418118138652126641488318497365866774597653703033073028919295745363728095048883514484658587495155144856340659847814522947163160608322814471544675603153363197551362048191117370308412053792944747928190528540860859144468174899490400473334744419173777245641768399472748520923333895551571792615796755551657310215205689111352303601040371057936191847658963252278584373385776928651998530803006919812956207862678050754940973195781767363395124646299925975879925217447728242890358892164833957224707677231446467569066926305102712896929923093167331320823691869753133514343181921893747416686685759923084121189534153848271152377384466334749251467414729767838103385798507584226225692899257886947162362669210023579457535612753515093626227101891775885069025969655789579740146116312092872730414308170108899247321026317275489765991704589526681933246144586457428756593542814988495930561122543484577454810592620117761283166946204463133806511315137934630588495198049811366542015558451691081158641378354433112679301166741776676893469378514143388224878702497475978116788929605283989143413994626898089591561397429079718977670547320745506416346739044520285240137269693732929318846915887881049519259946456239314599695124203123341259661897896062549833465266905368668575889244089798291877711973810700572720031746008324467719002444648882432411507444394440500520927859350046005478709715431704702747179891816380474237748146527800581530558694373639906274464869323466416807440767668186152702607286739419830837193591169594058151401845097310985705057851107322993628676474572806424563125256022498774605290932530029356756909373991052614744051081131836694398121419141424514564269703868266233254691404985378404217422467551852643651896828195110624815040383111182615069892597778147842699169022682658439787530986041123500245554526309339203430095483556286126598767585465526087631175193243998721126566213542848557017185482246674116666727205271908364971167182578070659508039873517344505611531508579390145480833991273363548838261474956125411646300624989164009554633089033397283455726545299986964779211113152528670770401049129189645901051868864809210152033104864784335717349980310344065211511042895618858439402477253355676832983922975518533132177015207394971643278099581009433290337325430660737850060351019817509943732598927850824262593450049245570946072984590120412623591873983567455427538616794565797527511247410482244416969387152493963352666344198655029323389607611438615669300704052928577539804898944369155546452393322863453439052671435633545699793606310638103479619189039228229792456791197515950823678159442365992591548036839787122403977911042424876321181906861513497140965947488942322935741752057174231918522871823773799977564800595705151151352967679723343706628102482543521244151977808568830995325708405085195680948811362618027739653564961994655381228451045684490642807200567438711317781539993418981347548753667698915490991150156100274154137385177836422779463352487938530367501516482472925770911770634296498403385156701780784264711345035307317262880341386007213889450693608187293919551327401867072086569106758459837889512206723794131219220871020843619109499145951330030495244048326603520673583744503131353559661417581320199963120424353245580751783104583607149690613451997777320463190760410253343983392929745433377532109023624438458355047785789829429594992935686565093467676872982793508495105828708675889864831304721367900252454735256607684739368879443920018844674519937047604377590668893972573425534930403888504342819604432752907787509322319437992651296796098819400484346463449778682168555523799707992182060948789752449787809210449784315228480550853105577156086899482685844958612668298850602670394571472114334926929054489202204812371944798542364252531812336131591944360341334127983013012745828875451036125008889243680849101436854385578693096873736408455750683695314235734712190762561422124748647586315472413881958767335984491979975557278373611587767215851154102065184398929192868542344933277124915526447009938247979076902567905884174681764156952939643896882236543813854123436489593975403243351551765792773683931848054946767186536145539763929155566103776103644999674839113693581348615243332492506294699277251552826968367075160037731774662270973356949301860335316218514994222514761568461649606568985266510199325361640151423800546150756044944758435826290726298223244775088491255485829106201517637356224757051425423569756635355511968544592374151407968050276531822906275013459050574435580759523118223266012272615871196432046956428669136173986162662648693309032602952237417253457032268244670615697013578884864711925053846431148628436423904608405919347540406280153023358429899194234564734900782737071242057155475414044594644012150091738522284707821225518456496519613588837013169144824739982212264182842145155047010308549025768438085570261742885773170405335599377138310274928063964724036640279022516298290417198860504500155578530899290811456030721995176631373399270325608810842850895279526943704629184164510675163593099979323289517449153991159251503400271978207993057140179002356291026106009747760085143835637997995650531358360987626912122207920038784301764368268866594860961334596292376698346680421911262432615004142767822770131865332544197966646706742588729687543181754444315968675713321152640825004990099985224658890045718147041366277985183438340294852805700044726544173088964489681980905765378088090497220636437483937029938954531723053928235406531804689702556769442983748101777754249836823430622493020282793848678863286182173597419246044936232381322605780786208765788867671669948925945271864477786275688290507727910465489928981706096359975273784304462398285415821751776372052619520053483391439584387893852313495117398259289769361252392421866538053454323535950307207115657236651493044713055017744286425860637055764901767717785416021629303477011450952429337713045831856766046042750694636574077824127232164435607061329954209436478681036394021857875470009137624557320154626955091381031938903535627700009888548433051185608278530773671311014319245066393244118398511598217456297130887586560138398688243651127486974430280988983122091676877929119698422041582890311734995652430427359641315233287582218207208765838843680422425074807751179847511535238754347150151630401641665744027883751056757950569611046023840759068079005908164464275907050841708697440015661416832536774355766528434099789766315687380246091238529734015491141474124417352217135758414951635190579724271561070948958292525387672681625262222669140882670462506920580910612682509935810226329109204728895252555945689570052541202922362715081505467453532311389053227453427689721590338852062643743620667835298048022419080831087043063753149288384865281354880766792445183484810630294052216570861221975072878888626549689563412319605333608518311743955146984597839517339166723661324615458681445523373455253698820567656955221384713546439073208134809800544603213872590707751535800143101163217352271844810275158882946155714722739078082405855032815489743033482229921098773451276062005365090782232913932294301421394099245674398032776523721275532317407492229112722295766413446480362460614258049239682352655813061328838088596304973169893474763778024695653486740213583019432655813154926652390822805653283898098669559490876620999725835370782825759761722086312144527420440079444310724582715584021892549394330112387784095387743122830829699403556833737556940823578030506573391841793898890217102527087992382045719467486095667404283121337664428747573104315747296120393732659239046050775372944057606792142078793308787219253307452364216267980495332313141328549571899542404256172077360888563364509496497509661258486180127493020008492933354832421456904524311413317752442948488819118966569962783924855923926077633166072532328314242732956145869978737364099322278295803195937651801423025537729509110468496494673488604521703139415970314298037057801600628318075000005946018471567094167745777630353742542443684197871580551110784077008094857064294977432506097014422832835816681216880120200910938030402640329004334674214062867353925384875634364605115332289188091605258260558103047916983151716252120735241954184132212892841268841357946027445972312892766997638488032610084483744011117988580065170197165319718737001235963274642103076284396460046593079795965444943920523421191141578692070564874047471982963227861292022990975911356835853175135715473318754006071321006519469998553084191973699235975229231153378110772116101503084701429528853258199931231754184004739961909773586666110379589059888605040123092857985706072969437917367865836222929835628989185225301566910346578712194570528317215874885551626436173489091630537691009393333113239910700372546960379206907450715509426399607715133488436623360639954882298990947666062443435909840645133287669451741697366338212542112683164013764995989085840794619456223572740335135287054993166018920397383970976057193916047317879118291046501588079970650012774646075324405176326715549664301127497332833493852641247172892872507491427275600164616315624997916977248709295126331876681655471875999561776478183135548982050291247647001335807707660221608349694239041638057279923071388770594055313648501614918164525491523153232188025699874977454408751838431078549378891354061077392430299285449271921614167660002300362212207209503858393210208103653646713634423792268035475429982765724730530133413424386356636160275249607243480107953142655239230243007525071839713544456448911843119893474939178194483471264049012706851875419316648199416400236848347874272605996770120407039540320701166613575833164411810315092716172390088507260255613989297341544812629424041233769662079277119252267119454062961678903276410539111620976517948117220486020449945169325397649088022395129315629458796183759782414550125289898403235394627285570278173485448807203855332012355538362132521682963439865032422297056734311406775491077832867713114276976133542404818801640950870649284965054070430120511667897962591518143538095027134119156621643142511608016070895496672379881936246775711890137841158248008137332511058889120648504798782741711135280398080105013528739177211767061277029031769414365823980075075241517235085454795406713409150404700918870169163648324932929529520953532267000355774257167278945495583925129531764827388925374261151037462482176718415945100360397422113043015674763870702233829170543009790425840172539726450834927377895552648234581974872872540144734764297812932184122353355493934567140691628040190929004197328658912366093940632554044062209677384228127094207003415978262872063579580490077819944344134156240708147923836430555448655534957623262981376372540725118244536815312240717531825234788667040595264379242380537842827740764184209802083276344338496111101603980135545320758715009713007470994896845705146167845320050244970903433007361083645406849319847270687101380497733176943543135837571158270291482403529501451485347624311701885411323252409955994346211771677103874453494572272776701587248701779381093133551881589274580639468746227801384224782416907248865979222018237213059481664709898916259849620822324393557489458138388630490774102847565602585261813843227295368443836551759038865807224535450036705575565761725425647630575827830636459029041045849817927484123487881783028728523613420930074545742961251750197219496214854313497085011954706970120313198752566249040859010711173472849812567244763656327306886290448016546770411454682946089378439960968849781007802563941460288699369033258011638723772046415010310424724874003027826404424306536132721571581376237612634128505730925527057829245025379643532716683964472831702434683248614688933692624024362120511117547264110593725550018285603454038359854153845934662634571177923185706670323661967434949849329963843788016375209448396414473368420112023886106007475059481929737248607671813113125773852315187048025720895603765801511863010516309444205955461299733016411514663981294352662731165704679078093475103034408163038419490603812741760807869782642646622907790663655931844417102379229377097609196466724096367241653828723531266856264387501026357440724502578566736055004804343690283356191557502500433295245374342412713658543565501443064318526553234999253806342687518148455261838217062338468833993503208402552318454471486840589798305694981311767364696070699006248559547252843549293249228438154677056921326684366025926141330176886656139631263048367732680507178331776010439883016910502707085248487196530716800397042444919277089300905794228734390919885179890520675635966273638188553815956403460252283946010042979849799041707695596604428338381659994455333727378788614915269211805460535000687449447742760575403968121765089522872601877022800712937830922114075005923787576272258331606560369053079687511373558663799655260357788509398865044770043790479339407710577500699614250382812885492211928812456487511014341860202625092269640518734095885381176568784491284131542357269503017763901286919104131076443017026653117813699306184884087699412732206697731558749689242058601031646965741217904411427122294244812903029023364496712640280848038661626542772516758494993520182339264611567533010384884055593035849251483528964138015079845748449146743123948238563284371132849731682901931253802087059287000307812920641183250496869725019868043198012374327981067174993528572597001718850732834177767806881799784707571598293520703694798112044947912815652199526827316188271361289832762879892868275945104677908576535602014779886138584203890770966310861986350276495953295286645891438997361779881885642384269511518409031252593329529948997651982874337415686354768662643154676512765029103794226107395439246474748748705457179463357986971256726258619769369516432962542396093068647845803313342334394797854396187160241918325059730672052721408747981510612051902987110985871518031366301220541745493949745701578940622571192210515136579022975190338211156914684420963771788841740535072240688955561427101305821425969421016224759834634047517356638244414933462024596204914489196595699368950038689261417812341529766313480762315275079093536615256846797049751435990329471249367835518335071125820684677515656500844662833066153553999914216108857002267016975683683309655982382519605255585321238500034080264740184031623178673999529629995330491173596869666010168794847445043543014659165098975489562690719607335278546371789403783166390089047101838172745930560059513347008374819141314761221323826190205055600371933573210189796665597783340436329579855870043465192790214770594381918332471973287205544397008321327266383481206712877784248771102683069868217272898281298004105698826318426275178157953017567604883369690256726178370324911179383269955626057435878822523840405987890311601862948799372323311782545813068292133330807400644956997940572013168384923962078836016280094023904535800612457218666411454049780485065361086177133345136118711292116978652198448122060799804966472776304823762197166721686527894660120774080092385837757284639704570035553270133875995002488111265565215172549468662751997898300493612677481238038826847397065321724538479552797891311961501671628452938765870082604693764802740385807479837800810462587852417052152244403811008511620281842761435853606491408892771098405553989349254700855887241829670138947886016910174020863547124895854879029104554152081085846031186664209059533021368591533286100298447457713444120894233228953110828074783924126518624061582649270915258374542066334020933323915093435997869498096271775942235921753774441778650291850437920937649087359220501598083566139773995020690947512567561525081420419912548151017621281652194399122331021400609479605570499490890585155162009615043988176134872703815435502665139857197727687924231125452509256960931738875783642912729182974529274415425478760285548834750899959920790908016375010043824436168933020257541361370335260459049153466255097603564061509333977282572896582249261449297406040991151130703457455190987984489821942003813947347826232757647197984383219411970613411280906930285674027245171940516110054642975696476657133116910497269872424777417888701256519657532210393438531975739733161462000161024720903164497816774502417160388068150772588277835778559851973903917084927680109911224523409978750794179561608298357249515612783553123384829866621916850594381386657917727548630484662665537607918820318364578529934317966201802762600047400189077921184039124017629880294645056994113494962135635024099537122262594114041243329980252219857087736753930715931251665191947818169940828733072914687937108672355225767125151527659997517072509458705324244932800578942702260741552849199100396918440802203015782806111083095985349281392991021305979121696766292394223445963058639198844215987560535104866219259675518096209607236910287844628265732428238680029643097040796348258485419560519350999816144277109230237720675725562730543513047689641142077758926690468633832967000319796210600789134829626761613046133005571179516530586500954351582732988420140280911662179550231293192378709644195444955538631813053051234402709356012042126334744506056870110519626403090360953891469972855287681086086574430365554576999289880257498361768416700594819102819317710834249616063549273217459644664947096530582552809355893185267399385355036187982474335016405769716543399407573169661531706866752873725060174550189111433008748344667631425960506771487423287034859259103117512456547095309278875780682811262305658227356647662556237535186686148331991359924892781308854690999789148168622075409274195745846200624955248635309126506749601222318723877393187946121050462023673011206835282729721777064968017658437270400861696113005833070660676044089898860552115647198436680407107638271123434611422709387447404964196651822489804305055616820620820702837128677573730127099648242953277375675972277993974835846321636030956640404558996772156612777167503309709537672261819649448724341590442465110091037822904279376620647024927446849837261609636792146455134785587440590900748531325552750529904995100939304680037298985786514429756617160433984345270907196305397527596636660330513661217750176163376385324870623497817746049274830656010560958325422677540303288329019406688923512784940780955457961758819649836908328369183858888004614691055164872100829484085109813048596934461977764507493358611959656228108829573331900424371592701496117727628234188142876262292136532747894667291394333593655162680547535107481342763938451438143755830512991519970699774287252990482526485882957244766594006383856263705227748093650705460208197097811060666678876409550014592610177691182415549595576344049111007195438036634846524892355742607310915359948290417117844471555335800382206932611591091122315150243962512223839184325389848417550039028877750177867557089341633320756963725844648292029960929061240428070423380402130683686825232163141432190280367451553471436743080396180944352359960296815223463057253080024664746840998347316943847368637019323084450977078722932066295007282271961776930506152166651143131724488990501507234157081005031640975246780831573659543250675073984721728970347723753121397288113874626234432978344419418359082700650120374113434299537207026421791804621308088389676946101893103388530382681256594770347356590851463490989448908997552322107750741186861765449683459842059571506065441090802224358801448032991753471388065358389115974812363497748653030113371040617246682121561586834248177313774526638417602675936036368805654935230551044449518595683551720871075243307439352826433659519242005826311104480862443431600058361489926813575358107794567539280257639611600878476659714797925329516503775456708001376454620355314058147039452010259630653175922951593441439799132310366078576790823316847747858468337611746976164535005977819375496655025541716950128911584892284852292612241494302072383425031751266052264028827789231075497999786534121400433030981686203100922772043065067082440710486795780924238746281412474192385495073080223351309793509206796858308663864199421845309147922552068041476444959147720818981447610684617527978445724664955915685779447049716425384028580053924180533409006457840336978102873780281388872523723529235748977685117843248139117133860794532635912667277946933859470818082633592439939809901654065714647885474787988015279762498368847879383261452323506694089538950130541980218548131421372527468420528249419686452043184934631809879008901584657998494668199343859192927130383216344975037245569237951445591638162630788958443051341627432997049074219190855126795026532580802462321516441821602276935195842943430175012468893282719822529058225672646756444108277628053057185444714237855150169908183046722496919261222976249881491783186844595819751516043285112899462608681251343052815128870099845779173527649487808665740137016608719869842669612277641765575507160135342655529974281950783479415745561356517779538754674762215877039569844180450445411515672282770215204681972922405000184183159652462460645210598160003279860323173183416871846835654399207230402116377132515754604521239139707019011637377543430114662807217326695022752596728349302170231269204690692290972753089942711897024992909817986205248400918217770445328516069805181822058666301747690627317751124069135889677283275752909954059944611481268206296273469215204839584247870068027395706102062850513285615072454696469404960896564303972302519113318677953383154635505358536627104116997066908367129408937132961418987389950221352276278304062342333882003954834024249593223727902411207142338678934312972102465027270754949823420285981680937063118437424071357474289587119290761686187533031524141224890775030283367049234023476751657139436262993979473778373593007331031974911309424181519076480935659131187633835262369790438663782727554429810398784605313751011016625768451102419305791671315118444604039360076483371675848817855165438042255539573766197030363059556857030693496465404575254164511831388749871142451412848882967110954183270987737523917424744700208970883688218086403918306813934825359984164907981337262207099520093737880667526906589664151284815357744429212937420426266212178544077281565911409234820913493238779403845637688416394991071829179717528929192313663514443900275644311266991523894042952707372829797680206068658126990969705506512042151764600550560079925474915880444270628445006854008862747972866540905978661396195281040471733342938281271020331895465719756010946509922915576863256450801880962122853605294901555003824780709844437649218356520994627610543501996461609964590647301806216165740419861620551679885336703197476431639250134569686501973058520184511034038863066701638489620095324365040178179382663810930717947410752399272675775331202707384369138150516028686867290411361229465691393750004543857443271292775933213390086081375581716118829334852183412224075927903057672209480358906252209504967631703255178657324117195071503979311980164315187343193275975196165953937465426871310198285889886008013205532383754411391545488489482605153863165336719323303821771027247444242104952409169811673557717759934190766174143956146431163262528114713293444230124293382033168660114403744572346142464485937416577813030259221013519338165486038123595042920929558538035192149097129924469796569798772822793168505310525933296804527510876639213727070106365547924204817829436021802262255727845103579685734041570999790352151520405352939536797393993720637649171786977446630430921733737651571496221155377258374122561072643784767809723428836901245126569781154298085624309918416718242339575864757798979254939780063547409141245045278568193105458554203419056946193693295602423740576060724360231897414053515439754413034819322068994810900064985954961954010106996375845442604456228416699984304500220571153317409684677101139313973493588981999204853900948513418905264150302510682340258408336489223672126839287542888632241557144251971360139701343559294409065075292316290611897681535078541824369974061646195382730387718724020339767594844497735529558835684746764002421591809319520731939214157124722450494202148220778166762833670351815090717589616935775439834088747535975871214942078529598223388348332935681987986504279083236166876488298707071329221854456191902284006703752336745457029676874092262450518488534188834488576850534622074497812668733038471785830303810189633745458040256681494761845045059928260712997038805676612127858473552673424159241771722448509936280594784234604999493713352714497252270730492484696985613012151075779101828466225740436396488954534995899042485500009392182548244737789638264638934886282178524848402387929810238174484560037273129005548529737575267416632577306092392470431245161920361807782767962641247767587643066335284588784143828205973912836998123365591921434479387336050499752605910342788738268779075745088480432981181090980351713665499038748820237598946934836945559237948543533676795116471918727498306916074425513279160421061201168558844127966081486995133593430168597420424375479596429538425558355841127626268004107759670793354956286430444111719772311545935758428965628030859898569819930572536546258996501854339154650341778402603931069620471980112450142400441851003764484970542912869937284315039234836680938875867109038908336401011594516838622695410440722903982986361497344591835494277816924400390546148696951612120586736810398328252472178132819826852692154280131365682159235196616348410692163086794830090919925985644694305133029778601729944260967840654448976645561345607234325069483867890078653516622130555717252499499192980222585573592298292070215991038330096518555751391728352426957006220021888968734309706264563178215182570888027471243732089884534402936138978545461412316256017686536477346762354901274986223338857243549735675369315009803216051058686779996491396808938884934632980974665798178478464496021208845283836338960565312923904373100033884730133252693992478055044636469484803339683071566413474294560330371874064623827648238317761901005459911387418380200562627650737706197821123417319666637449816761378641080907336790531450087888700953990209261595255567024835624980678663488960595981391173167834148744679772382717495257765956721238393502468644537729877062656600395335161589911864627250220383833561384691718876750642669719177481776763052465810761315363361977330492319581021336667614080902873734117508414391274484204637132233403454209042766540751007382403416306761874432246911123012786680113980277743164372074052824336434241560943831231748315337594636978013716406881205553317835680209523399309271151511651874227275705311799209880217410006282661618080255087835322218088671331750010719463232797151357435155882652114443086238555388105913256070584731637314091909048553872459880294161906223292345723148082505253213238161878904473363991320724100606625567087825484823685291510787652638596368150182065600801372928957702536590819366451120409058887300302469906351839477482935522187328654182809116621729541780808192792826590264635657233425013671512546723558652869820110808791447197695963781782151459815843474814159261478407173020473669429856054315612275038586289361591300107551246746529256750979090043722112882119118386881527722130875555480798119517834285763492161660980968852606715882389977651017787006676877815727831021684826965306911015207816354937080403310483926730030164046987724673717568963217342994199421050121239364836962758744409482278278112286483425832776592855858793358315239018861591451594327223964666655295677157616915681517267797632080029337547546626460002015304882711858725060133980386886391113021046716593294501564447430459759953082451572121464793824194918021228630341274236168321343978976927758297793531035853411510605206608823618852626876892309300846392970899357118869236883344811742656674426611639975107048884794756655372770806359380271503453826194813308775113393971939520309790523166948884378226121619339002069660568030092445654156808239256568707632329395977832013743849558296052469751580374625987634417609179374581654363079746259921441089546090929029348792615778942682081804201448443474707747317504882415487231540759319711661430122257205101105362625935497618221459595034940545386184408829879709539109139931155094943010915436784825526258571704546055176622180357796642203609197683108662539710804695844961739849711003955845155279520263382448810016584612350353440987333721982341057501406557205169847846397862599504381047827446744035372465951890418832396091099889317164991371082791759801473878154675501739646964757315494959477264700480607077618748546166939899013324667393891828150567143101554649708770913543228504891486149124140690941422973048768645807641252140178931852376260757771852999023918051872836716609492013766217367124561704763237128858267903279265373035886913470764744638237314431121399483196258050819365763797460985869162821215147619515286492313977169892821098898341449734972107624326150369960062226700309883546774480151355699188292732309447619152488784444193112389106346785007658157427957148738541321374686345563356830940076612088231486983777517327782889205611514356914917891637015265472352600441542131536524648176077236753220724066677874420277327567367689959382026133796116390876061864720793769022746801362566714279062976716647080381117740408336784538143858374385623716054778963169490518537117784809060412001106921958653363314084693440176197359457791373702020513364560329902096113752897881232265927935078474165627751810064317406810577495249147150211148790014218669852052194040952951484970428440875966763196250969698785925849884865670520719356693828422041260764624222287914514476659583076419027303578362617791620829355007686754801061591540790858330813771481852787650853707126538533276302164754686133043256626804420981310387364940017734871354226279961565620449948306938275885842570716547037138000907741416437095676228011129035088255075701408795712147919893872725988560568606585445294741785271185609926211717355718483613286147857606940188384471549452056950503990649328258277060236212462670794536427820500502460054096296695083774824845513302601502955345223713651039737851004936543884172856628926080578107638116679960850765260477794342580395042097384816700013931920820576700021098049853016623546769453183947316574240824625566319667401131947354299204797762336639259261555753681084001163555298254399914483097552650506614867585933021155573174106711388317035777050814466865726010135167811889318696344671184947628954785399382714767591575751610817855667151371694290276354853813558110888290121836976755603845542001394532009434229862862124102784674963237516934362625592538651013541407372140054702378506206780684766270478001664174700586742560062344614929611262012493516096544892632529881477458842749239517129538722324223207801509502636460306311981996556269898074818163154361028930386137491881499381224129440510871089137111539120326442409987567882873545828490672141998589317406641924208627980809569031457095799375964200876351353595699983607540838444994316062579948414308353064066033944264628078605363834881249847074654501036051317540448476635064247007353449021511488101213622825588402748849885267997224045712267800950877125567298876629318799102591216877720999248132166537309599306040363622196608198613082519762084373123247148704477173912401757038884735359650031033559245617769872600935706607819408011234380179711619491025231251088876823760210389068719829790888690770061720812485180243631787120554188011282600725520241919057121795478089324478366423169867774944001146434608091825952101986688255125834507621589106135958017703397497572722293839158658725023724065542442670206516462505411014044952700833691637823459390799343516756563576619395533838967340827116674198220467062756341051518602220558082962085515827468308995730179646582118394084232312107936693706994433245560941145245476006540753004165160965126383529646470245974812111496562993200809889199064577141338172240925155492697635305565624354996653383304077408024303728784851259339765433964213136642962051866750064269361790207059583089885676633557558104988769848380107637150250287457323905971790050671782959841669880746610134405738871442396185656360008170598377499928600668878971053692798866594196118910037800190506323308673939717594885954903750974416698805123235028784449665551724564504520496761708788280707577411681532142169940957794585285112792740755894810180252192094163872200250919868761312553986542879438918945113731517595121314089555295900737676010813005387988121999025979843610024420165479366948145416086790439907900868673766768269311563190181064862700994867950760702286305662148534258400099740050649515581285026344083167299475370550616720598085575138953296037963102442704296320628062351431761886167402168361653889169222262133927357056229800706753277204343792969251597071099313031184693992822788416326429819541604334959823142259003229384833230860835932102188554584726961157428731005303824765010448787783092405484877270866262929249835357511257240695257383712998678783867203729862389748479544182529617016127696274698977354768783322953544530146467246388677414728266015740559716945411998758771963005329593695077453620459697763852862500670921958294611020510182685816724748786538409649107889302204850576969273890208085568650491309957945903007778096760472198231329261524219876318658224530863327454282863412844923997121346266139744280578932734790249170393491120341028201368953946902688328178468040783512931518585452160921001940048134636635072729321910267787169904432719142440835118853006138535340245240725519557232050755837541294694188743876037383801383919225263717519276612782627655204746115579634363526208365815756216907547418493366422428387494450523954839479401121806287248638300363683878244010940428799763724688060845798133325681996990365956658055843429652660729222555689535814673712255776970185299556015025569163978746756684615575466837208564378879134211839680217705507246845638741503028920351425093452094529250718900544687085508426492094516366897366349108771509939311596696702869294178083332100308790722159461814433447374558527639141284774840920793318254046020338925408210398693444336187453703477587514171388829579242196470437354517087996717275700332332530125338050999511393660565371824576450040366964875663992533395643195195412453978733518793591224468574368374124743936365846731999524674390641175422274713051319126488097206969301070096631586420042129714033700182058022155467931553369430160823845446845073863545094654708079674416406408196931983747673479071483628240188934685644966087518624647396467270486222150351666073967476208331405313955813554558790856274434376179078020197692548671653509438036803835501311936081375259655549132159342540514634264462909355714752284176590139989266179189544706065945790865987602114548044070374046932211208403051671343793200123861285087323285683724925196236688436630251575521131010767801119963620106217957101233939537912510319833667957508317294919978540399762970907918688344163145655747909270435737864992998396504303878663576429586750679789028095588645173207351695279454929647921203763749300892287336826922030763535932194139583212580163386529044022652276848218499141369528776903928782824999392223709372690183466619488835083719107146396754107493215859404672447130205654179216841826978839664064034726851961886154886328579129869664698447565680807559994052902130347695725487790377927101594869234157415884597592468642877366778971350826683935464769960777830697040648250389492026926762124284752714252602529576491649281151742491358003515343108150732362837203250913561269303669404977446172329916656491285071341977475159727559188361812586307075646583396638534574178809525144321296508117320273870168079618868908393652650482209940713723598744158851358921595518330608554042283525434905636481464170629358981924563748928521135082657405286988903651440663766129962233066190027514433631595811291635502092355674941296401678558836797476689292040253603577432014112080319013015472123779654941934780574880501449357005845466070868167897646748652306851600817588084498862057693177919599327537871233380621738253347195225362562213265731670702949249776952356949395692336098711707664707048400331318298221902609090793693916621500164666585837235868481542247538674812644177540599452728758712112744365822120231761591416930132398083820365793857888638129918220441088565432367539216024735451942718101995828217459509918338959040463051920447874576822948723137521524583852665336665812691221123524397230181651346455418270213899644614005796424084094682852361597974123592430170604488073955034471482390933602378212479219661471802197385670501994176248064834292365544107932016242890124873198198608592466552846767691944337449891697700095179951107383383008125980476642594814631368506762967963527753925935354755956908539034004590090039319064632822534309035218837595108111147080724357647970986994854504728649999878847418978556959087768698195850418635644918542072584061755093710033978153321446902771345798309500909116672323560458015496797177265384887561890215694892180917161162005802735020410228699308967006801182124657657770540442564631477478050778646833971810229797392304267729597715304726740453746834824230407789281514511079601586708963718171634610917319547971712813345048510870568236921807278860595478419012611575339393124477057896778720837140032518492360097624483374281682347837275815196472470610927237981427847660566043554552309847884302427569267587268134993881456966074236821656422508401160577539257612384407899962857526642687217405324999783933890503821423110484354568131408937400518322288243323238602326615272610803447505909135090383269342430713176577934085732388642881041225212347899034908115774662724555662827661262641372965375268733719061145078738275908399513745146267665021083361466454572094450950931635995200972468706082943166591144611901057335389789633337543864832976746216952210917349788302387965785260609329519810627070370207936056671634469869538654447551607711670576910205100764563570151425102938411093462279629160591482725371775735198330536943335100776613406654785174140213445257610038773521193118661684833310723689101119412941290005974673338458357933532345415642853604042791828102948800376427260548620479354929408945724632794703523003571834077675169510710409990859035479888788267752031308190434481480149226395592534592331385627049002734226731011161539764993045302986164555352539392675662222103231702387654138767453933740659977093868650918637536568959766790338313576262147546106980816201908615607201588442336341359788349470175738061301143297480771844965477343634673173261701163476619841566631769941521200806993698451872155659565128419617778722892270376993461928461125816311573360761385467578042093850553638856011007831956497597050216664077680092993165220563996835118794682161287414377628499997221030393541248976007631650356959789798641650304008858154706306628371326402615458990475101032698073053126913979300650202990761056165681555154559046976644531775102962762917139429687512638083255416967732404295370403324035010699952016826634065981587096903176686979689047033625170435802689157582848003582102472710821792815932268264937205759286687153221131277201405818886497372057382838733781294723133926579851254502771942349832008919693061206498054507504459252805540395704298315656330003301600240760319705388735216523970790587106910157525579887420071833659207544785982456407965649403466018719499213880157011985444944664952944893141356775544136513086069798774947987736915786405644334259671166594829657933689527109035414162409788224991493900100125185765178911772502391156680400450973018318693735516260348984098877199530061353161280181497799176076508435943285725473511953584194931829813061517952640239133330760529646201620608539426280069161486221433242560438118869781567194276821118746132158670405725871426741005908736752414858207205833079578931246357580509730574211755878539666204173341925722231350009799103104907417845572351473527391650005451926077289573642940844046693065682895245543695544225283883697399826216009676112077385638663843396214304002605139620987617921725618802651406471174192561340087427735236191543089227933280583131661119337343669408911728567369889001363072230017085421862783738873920125379806388864960134534016706648046521099275200833153836557479783650747465902055920370180052098590070747703600603878572100746614299912817171235097140433884701101286357187481458148747486808931309140974021552732169341503181267752815738407092026114768151564846737107172091999277084840713037123156606489955446669563282469221679880177402204012132653952814949486559151433414521845208548427401891622634461388226712453793961621823476952078846662604351230530725721055111204259281753750794288925465212713788234515699905566890588537794930710146325373383148206759864032839308184981543389210374685379982828575172760111647878088463974260648225209874857584790111127558145266928689252752683086394947698046667708242054364090530516861956729397979146883351972647308629178065594951631304019292745162738647163510977365327305618055193778306325430574234726143619172454026380419909207556386013095491010638510218189472021540075709039863993399895512641313428983872041097564155744394324618515418032613613843622714059607284791992784395568733926594638365217433749386304636426854505643110872296152566997107698743392927862618689930983248645535774537936835633102642154592968289692434733804946933325193941023361023165717361162990261411809751178517906777585662389049871311459331109687416264582301055708210211750290289458381566564939201877136398532347358180710252195235597909792286777789573991933874860959850424112755830632569573284853789816499741301489409754181989757707923397214989750660304642915586029275551772333293250414554338749452732108473133052489014832057009814470446691011795460343314260972769958423503379155105755744712142459105797377244184454968822752574232350416807630470506036654738544743326439609462228328836465069823791493750878043479794110785867661411174961294307291183267628077784161090871664660709712299017524853893572776023164817419552725020619137820586501715424168763209937510498748426716452442592240524937342754596479117010079454303343599992389701159415100499594793001495846487860314275318949865225512120805327641707173709702699153371779832317960103867868182111924465588976665034418703113854532045636030094018213135967466888970754419666711187726163670878390608846011712173476726875774867239286794521244001901530952156248432506354352209499867392931098547941040523680309011598760080773230409765882263514200340745622701964178251524404722397523460981083565500361960154695369867594918031904726560408151213641340701936066426657797646063666696027481336407252996983360311179908834361495248837875675537701920403707579509073527576096482194912526422961279568723409990545061946642171718096805522892123909429740418845212835657764127086227609277876170065286381767217683468921708414030411151785308272254328416972937000965358348798682045922184635083310207431961165435559677263771186055012824358847822426582363508852077818674900322387385131221390865995892133726881925025518922390305708211847425361997648615501353936910305778453150500225801509361780016802716220189462462546037520370992107846211010695232059027501030007031623606879457915944344386569731514450174254133161535052934165470365810357066078208810056933891343079612124299683048635267114827221666676551037261646506465335063980582670093554456312868760459541465591438548065893624521596025178180119094731295161858660400972497042998277986153338354965147265690025558606027545766097940597050731051058888578784435154971462704909457947524476671636911593905526823170119460966536423102314382220293336233400326072317739579809907066912261984378624767268113409024950769338383399561197768762717325251128622956003275523470583769922937310277862369649600165768410490554946168340318717933817452477899722293373500625749601157906403090446961817954912850957597461404967189264569504040511193042917420591373661059223852673130709049278007204552299015891812529384058683932612767747440254033856883224401863616677671029543047488440094104952949704724776093786514953573335891646281295207095385857189455340176453032264946460498128833679225507964471169632492956010317702176003403491081757811337427409677274726553946935051868830625893530369811928363347649443111547850119706351011379141309640961549247499200418231390965204930758185631633823254546850618794042985307472189071617675279811079530895289669680895068778963215405879566399401952852441791332233652856714925632683236130175680892916940067733718148915719790018942934043441445198830644710602740604182213217825857466434976363137404514441478235365702416033709056304297994163220878958752877373486434227067692081032509092545385083548450982662789841068902191778789453649053257541118709862465433401424066994679555567133059695682673030904952955393306674769794973330950285424674814883753496260420097949069781547108056036222464212003234240853411072089478191089931410937886181155447043936653101443794070927661121478773735360073126398036079948995153075381607598533187729704662083648393927119455620579463526849285364469753411462264944836286312589475316933465587790229922414700249402221301312647079874762558895249996578490087829369749453610699728392748807662122424228166693523395638739246519917658112342576018937118865559719812434018835684210961347971303131824418815453404226248001671347265728155900174231326358739158316607362695755859033046592286490611159516891548919388272317303923610108990169230598587165126260911406509041643772238356719777974648969685819201126583428859364255211015489559618690326609435568685857355300934178803214654108368368530395827643959804029661882532049980069330848249774516119434081778564720275099885773283321855250093122887289384978233203273176791161962012123446448492660676621546516243358646773306388151863221953542916225669922076339771737102657527831570127544258804942004502707761693667962423398747496261614519539146409365457164603755218133010028356835105666313757434100604462542405697264609805089761868344109581043203066346194506309144305866239711079354479022287872157193613045418202834090079486105435873317221255193997710628153075944707194609722890899759671988881033200063228457296119462987048860968382623765494605923622963372061812377282850209798447113181861401110507866127075887360656368656564125579253765114361883048030236324622723525263022931716794726119015783761445732817998871675693419136045968162040340869183401195349500466760569523042634533699219458533067271667966106576260569124777555217447695010599832019919583090563333773109606481886436021854372352611185952186651977139420924380891388683436039797253798786909441775963404392702848490052234930222007709961080280352961537630250370547899101271351160533597245718972759880593178876114266380751764173092795641216343669710608412935690636877768656397893697893901693230318022332791808717686720018348499387245355683598215158213055427352779229308441379268488315551366180955405083840841834662837250420194688578576509209258280729857432737204546132464909270901103609075928421792635071928982804470289601188622409910093893110808270654134776353671426376139259014523843405946384739128884535615752249687461424538646097649322751777960488935929771521037313330518407683549560029157541607210799225357728131259519236430929218394661734272632266492762679732455436038789480047108545493794274957747200088764853927888364237905919817130856566511110007523084427860217148992341915956351165559065064369042653991867083360321212667152342236885628846465793144711910928847275293646334204328137754148934055288222972672953575527919022195330027699369451583947065192831389528917700281842217134095308041554458468649750699567013831248877535240228760883553281787744831251567457509385018846476109450270341263712640396955440915096484953050206088874147271370491939725631988566641068344184815823628301882520554645032646565259222828833530874043176414908940609154264382244973065707141013507554545882988714823342995514406551364216963614508390066276848281361254265368154905726519938540332557103513991527483215932541407754640767933107977855640318802714495039173026893350915705504356469806170342685446062460833716524191771985091866955954874408702652956000828059537134132093813225205615291164327110700780359507728484170796584718979818498123809844047118009437077900676740809221131203486959647992466397113850742649121757492815844670283617953778721997501292864042621460278389717165888538775941820897399999460193021706201708965989464115606017175557027645671528428037402797732636746805191172392975488554989498304945006413558310364735840521337397710452823653617150720936228738861079228671720841495604918980132971414485891608380796371842231250135756238958765904821057156610440374314221459748649178334968204018155875326766046661733352322450065810954670158950261572552175935262100748120377033229148882423140577291890216915560554943838826926515813857638753110231207290623538966023374360028152046535155674663315217717408761811500325965363226722801077938966026507273408337854142721050712159003714050882887925924118480379236624067695525943060059206949866656165972475993740671273922722104867180468155993686189444323995514833878872797412592036974017171108792563222613241384333241133368800354904217791232606792170295872018598706082919409647804569828927993322607196974563457726649478492691718994857537190373972641973572112324248302721608979892836243621523267975076541234111137208228049820673815973489576817576917697073082785291450589790421641062215636299596489227777059071762314697397383420177960525377477332867674573677166599197388407220295092591103530685393292919923587679021351175352983616439303747465964021858520073162823506339608358873247783952197945009629032125809443856681375530147266502130770750988333600132864629630525643251925935731998168443830696267991313865869150868891451587601274601208878219617281030181267779115712756932045565584670353847034873075837980785907156841039153649872462563845382779672114246079047632839128851590600174759526652161482000548850483297892501761046266185298626589250109432337503334489521369717297815105332922002001081798638320904412368771047193079879449463199546704365731638598791444978443245806167818240943732079712267741135815533474763531150782108441336357784579469429516549906276913079140348951527960845616328761340136324720339699504814137768819261159560374496199915715869385550401534437716805931399392158102193336350742373733321597270043622984997800123704003711293784425905586103330486921364552365839217372746403467554176544354140285920532003085373463582687405831602344632863610438311946697886890594551339298790621635617297671355606271201916343231986598387726032225129523804774811169231786063585600936024664652168681251631172080351436268173348892918578863565155933048286518451879834660688463407321687776639885541819133046599142827469355005449175859169114665705251839523399303624955645389554520188787873373921858185583672143434861338317032772327916783901988056044826002268076982117686133046805776041699576382647277909875100861315327686047968277178758736620068909024457715689495412076833361460040263367096404705964592665380292692825811635010785222313050526166349694247162751682924553596778969910746412026438820054825686610787143518634399742272943093248443468955074747940535670683754442184607632957778498394157819006284392062342096165325803566847608625651953578410661543491575168641557975718924999262781748117343130668643974260248221824774660124502258758332170799206913986633249253937902145005647112042206739364911955905958125123070029836598950571955661328373588323976756735210190747428892974323789173876556170584486127146714191461127573501669107479429321406101655260020274914701482569066963106345410835331181744838768093098594806424372504109860727041742504473495044927925023619381218908490347559095137302344380443697618225854788270447368925137970184789326758945494457040149920487005874503161188741102797377103484877862764849266141295632456168716189712918182229284410009437032907334373950019309733730958008255588386933863012788279321862088909154464665038695320832546904701301212269571740768948121762738171918333761985735620270308777497744136095971544976485939591893957047771870503591017170967025138802039112198043992718551471666155454121492944674396814067422727573069376370587117618582041747701365427341079069359743660819414411315550380796164917951271469856070902810804510855570523042096885345522693227207848233976728232024245145446078447269816832466384212916551561863702704731042517023678501041901964911963307228239397848066382932531551546285054810603846061971561905951486957815347387404184638480956238914153922100309354388798190081775741336967390240362056511925360662852984018980049083128898101400554828405042100806919888652038283541762317835664322066969276478358587143925401516536456023658581437427059761919359564609651571599952500230891318802224538192070710998124376244044113028765994320801479582493414317005410093983378818646129181717632129847824961983476768283926366184485276964289930513373562889673689609650342165883697125588055377042211420929574527758570290043116608534436252174918739293442363444496071762941958910567262365138702062196169009708381182682598656013862379695336092215164119036257916941697238383729959825057619864073100540722452397705444428336420892391888593901247714317793308846187058015560294987234383653869347103347816539366141557934809742262834540538721564307784028079810860434260747177467004881240122566666038379760064043329958991761018975635983826972819344938703086408333150315385500503975501354976236897597341187162624059269146035135433106068282611496797388555385421925272473330211605500657410104704878368781206509477095750055633216791282923298810473240389039522931470467102417568931187226791816945407580700036139104748888543918486830031482926244722528796612740087078180325840107712565473249616885483708036479130571533148379740077243035439808373930630703367874948862706348442343903825082951897319694222926807944722989563762380185799040546278752164039201515669710641949747999845888534791911008926149282036935252909744967995384916444059558532857941644281812424825284532534292823492139610653860544812387926589922398563131141842110244881826508748649016226437365101694477832633613879040147899605919890477211157851586124214768003871589801094770394131413663769281554583004460750132867286046602143119552589555018963602342861252526258994734816546039678621239952110378198409633605671207718144603593017863274471740079935891021819555421256805909272122339245110474396744221999640340904528521224045949130015691931858560718625282044656451590846432014449120161510310983833849649063817655439287980660796490578809291352574053101676293436665194775220083912823541989737105057337992230611496358961445642410012269955406099522560823788940447967694894690185812738380780663654612089447489816748031717794794862067414672744240276887295112034539150213299570751347288329053224031276732323864226316812284675477298801568307660020108830972953739485127160104915051281599117953968307925810160546283969379647676381148727426796811694072295812542886218295086330597415042494068854964697778504699259082460087732624298403056261999041979704999194290144992824734868380397824796766611059481499550871446269611063856178710425638664659035960199998868543258757247945054997751881687945541772490538590752564959617069719491534862966726813215081018938821778021878253557990480344350851914179393107292706658819939520598402673110531717591352389007632838945344899625599979598701550819793039713962607742844760313887484666655999640373525299714898331980411528574385042575501582807778317254098573869031488161219559270395781337815283317855670876788616803555619838287665709739814884157018712912386863798236398101630836989738080287627869161368697047662211962290756391652770895464167850689158564139405599233732758521172436647224167409248437144575952709730719122391492062555206942693505740139099440273661920530335017085233977390125793478954618889604579725931028909671910172785821824309568277583768290962129544891699349138672200379295265715449941936882446136806439212035110624621896697680544551260506946745911560229353400652151260659887133202500359056176950668263990063348062771638377309123194773962627359643222194933682562765959513757175469009459012505187282921901635479731036092724878119860539637233945637645162496786546641003616459095478219032357886072215357472168169547501755189007948278299986950262527453979565772945660169481090952453327647404448479871952557853298191808425841906392402031245051853184437837937253302067373452894096641316141347544207903167259630439048450976956364215436836906662281786343246496116161875879748013396694781572115856986142786789509330220259826454680373446213172760087586815199599545644032373919739466371562879812311265145964437300617653601441314532017589724261009835625452564323440360353267130709549322458898293178320183358093478608889118765560481805040137559430889429692357518651715680758933528449634746751723388274469990644941361873998327986547679273692791190818882356966782607292143117786022251397392252550044264435642090024985344065551156559143473976275758333550321232213088793808273729765684985736110003418363313810588503936244693821428631338693788219718839356589145995235556140683561754447885770882368675200667037814430154725217725896718896317109557906960501417506819497320026748796710573729181131276193716400232992780452154777893402279008460701374170693297023742231962836538573900666510146632557789982854839686543855623087933830582558582980370590124857413145310526198894916990079375483466201862906219740325901369134440979287104064389951919456899983705132695808803382090939965044574334737069987681374097190778015903590053025280645148887248004849560041027813300012991339308603990564927728261249931084114010354574006953413912625807873157559788739735435682204029735920473362720401615941078017085729478990727621255134764772207577659600950771113840464690104172169871953099107491248857630070771326868640882629991495724742486889183930826430466505976330142114165664571267979101446640998334505404879295340912578383419890729246585993897791380542065877772660893594353016255828170757907310976168203129997969076112965832208137520688647833331226258240857162117655053750322793337641059121110116537030878198712727093136230663865234075240742913027394651490754915247012764245702274480547245961406954960371156051071595097338757989012824554733212016045129829579751095551910719690457235886391379338121099759680518513587510983611405613247687717751962563977297293552866275990364243550461651492520012783281864855451962512442662910894155832857540951867828389767161938137684411998324772190016729356881572906351581952203593872438624767463498265056766853681386171792514071496217043807720278432916826750106281632048644227317247590373095441149732450040826437701308417134712469787972776293865473409889963977128167264830117457494252903719490681882189816304506349990329545918323987687489656552513536659295338676074125138067987870243534492641236884238967685212840647688530654458685364438542745453331900952165941442480337330429246078171577111492374587635763825914116376350354911780711900975204670152373168270517794640542737094399858887816834248760026659881458659927011767391628478486708525993806070194444060074365415603559545530717517641607260950636770826089681725681844265790455423809563727832335059597409476419084434195521848495618567216661904236371259990159852832373055103662596710271016482591033137699942269064147780416560279124568943619674344379973610850338364424173829875676676918971829806283596693979154495553577095465120064676173237946945797277789030485188373186911214597457058505871078792216498999832149184743087656004957287150278640480233841489651387159132659692488864337750833293409550710825519730566520858177833047213743088935289124846302680383811461799255241839475877943879459614924449750238370961988833297538618614648975922224792404218672813370853920918803448447742799851127138757292756958791887958352539315629739194787548845585380322442868780967171020486992387437511603520629883034167304585067806244768686293819589101150801277359663571639785512698127925204831643239111550894931032483689724289042406797894998451163909659983659770050468003314094055615502239341200016362657060567732802929972548832496808298369253484105263305564199768918255222132874817436529559556217721582719249159092630958197132175889655182240890887803596741862817565450162806243059440027189840571164006674200499851846146199051793129278999861618176368443277783650205040279122746110630981575824433120732737104358086867474845929939970795809822573176843091378208755198420957051989927760168306687503319391353844189180747283096412353973606621089371140467241970013968571963462056853218875793227198633835223172717049863894626801673414861745775717648298832893521239820016988707652211549697807691358292043505841842317337337986546132457391418677903368999636689899843322588897569732086857743400308681163215175918314198793953583468384701401616984027639200987108294626572871959739653555617490020579794673814566746206767731568327968379781495782269720065404260390396876836947266980377590254452225455251835263761244759140880600988916726425924381524006109049184922764132543041954588160582645581644817062767749531901007108896350411448907947858281372957721169683124653377748151329881791146528606673533028696391316116748642517884247256159220135974091014275994794465210919704675173197921325748346662915015848773273267014089383094606358138550884028795145426705723298023393727068946269865975148523584237800248405483758834409795290008206520431822894838896251613829722749588259924284811391011477046685227714697138392336012446362052888724650272966893375623554028574157979676063750773140683301865360854833896110577363255588474016944831116516514742616756130414461619933957868426040776701512498155128459906137987444000359435256791788249713230424644968892217677265002392988229066627428246887956202209613959965102165914324065181272805598091038079515000224713609394824846171493434635836150024927971643588931612761837767957532056357003852762927732743899056494476707616577486361901030220477394912101476998635696923612123742384195177469317519395041885372537115260200743716333948055676698405412723939406222824818690851819764165231011417790089399209668081415244357546617489723129591333354857144529744311770309917905844636625534135447890527459053266645798813210422193763732955020592587794162088843709096559611440694550566168662105385623157442412718860601133525780250118207422952874066802476242459647418370312321357606375848062750351531353193684316388965501477717781380891603031057159856405805174140312062034132005378762509735400764630800375701099721862714843876032518463927573780497445076714568692999250835656312296519597805011202109992290537838998547027562302876827289981098990785087844803424262939425794484216785569302879428454046164966587455515001874827524558424288590901789523246213794560758565201170720602913284608817742387268367545633453360084633593945772225750878400612122985373954820588062693999095959855279714096398792149489237793815821922068202142884860833694153635647793295904256223009677191673582582979634673518200287944388340300859659106915558301908246470179788888809386228146324030118920474260929614063988197507073806663536165011082373407595376219264746389315277198190620614465601881959780489659729933928219669871959112841305502061769042365341665848088244519149085611715290104705235623153751985332820095491688985257929602232937029948857081350181144637431460343961008352883695236386557402985988899191500168167453859529336830223627639157123570418804909487447084340620842681819920211406252339914959669683343191363703821691259187456632052673610653496654046229328648861609525729126319328962035227586614296541330239211349492380894429418112450509591946612125985057411088791335126972717734286037316647845602760330854443585893428363015099277125273824117764613249744014115306661343365553833531673610069848736143211558144176164235246003137964203510007462088972640218559856875583112337711687069836898083779353408165609177175341568049571669659106774492978654251444957174208743525928545825219464629518852032512468807399878895676953942440940426589240699375594754596725974342317018112169751290896634455330282042632277250623356168462809770023766165812910616821927939014689111269246323272593792759747136601081064671406312290173967763520587295930471496543674634795088020133604524582836083172099372301919022385765141562446348816016828857146171906679684894201396157069921402754488030321594454983392322730667429252010639022458600224511984184901197361529371642157944203376785238141031486543288149312847624012485066560721234569887077825349963483703193879085975366470279817654994858031066142143343651403980797880753559461086285614838338556120182435608442764493167555290308838891690576000137860101154948872715013553651150195839692121052496740978060758783920925233499650543385081219995204551070176336681336705876260643896118463698825529309433730994510915503492432142158048791740767181487144965838907470115952402425016060135767985945181176615594111262476431035418037168964419342995864436957616229493005883864551006116002712151534199963882293106581817172521402629215976541809521383799983656338904021888327818441745321050143539065151332641210375971198447476379786435803406263130250207664234090603071197323301322815659108856494672359381713121170191952944716605483600127976570866330419095113624267846458466585817597949382889385516578904219688085865948968212875403704812092811146138352373928094033458442002218772973920535254347624908375318092536120707691618125870281149971745945259898459145083595722834076729478324434087068973609059204076131700716124410078141034866069017290232231225565660636563345755345508302216060274767178821514032223786516035196155252885238388458053029904846231831079345626282770377252026811418806390266269506251056711467866877934837911172983028578299829630300752594196468233566802740542630219072697938684108422186077461379339871058778309630181993899867226508767166635908302359021068150760046482058746940379200556206110305361126595947251728646673903205704855873352587805274459900491494155923519215494543746529413198149409261790754097209885060681870321932549337656891616957628751031982619169527854974529689007799239394760534426858802469226199263362265410879190895001484761438767729395121555853084527314677087972245885985043802002470232122782903676727367912681435987298276072406902904734454498568554278802273293601758185080048907016514769983221646278251644931671849432812753828233727878506891537770436446473473100898256551328426993797358480794541829515475830482701503007270854824802824478168333584233349923741846464807184516631068945855887493989938870476448831922349298104572542191870485858717136333493771152357241801097602907542866002660403239107173616649531466931435475676648115913311980149725149821064813226236078126101717516324300299467775663237744592559193123601029773316849600598277430903586050414063043447947504075553186636476765052133237294771882953841869131033812735898449095830884022757935670186278485986164289912964710228809390780954575886692235946102920598586010473465126331301686926271312067290063801512084873206589128123945668991763423220090078769689839823567580667047505622405596491097952490778854464878002328491638664075516821328804759598295678796041347295862897974162361567510111006280818317541342172641834888791844015030412492995505466364978062503159003838289808933987690524819775555594667965872890043714394472265645698386511490988057290446464726233881973233556312355740279648426436392792692644815794451207529740968542308758397253915539897396954327799976828527373010164343655649112239488473045916686123613326704708397566368603077391800251889014059076714482334822442899622590532175597765092109327266357614546999675769349546655438343991830095019615643246341739406773227742770292524323992462182852955309434044426059988641111658029325605428407616611448602114973091134941765000923601084296623729178226640027485799650965544479362425595640559985623376888332102259652340486534860603556251735944321704086120122854564741900681492317350260784013169921467063273385163086744960492487382848915725118030532209594996665273754978097353121366132985377810101625201120448187753183329747002092462503059961553025519684617964204335656671176991412930090343494848633297881685917818052241811049914035218433970851487410865186955230457708851793057193756574089804410877127522996643175071442770639738591686089339659655102119428360966367947518769552402152473867486205736199826806429764230901874338170372460371251518080395691923407988506618058774983680647621637978216983549848358880777074156725407933817186886399263739192427861310418678554093920908054202443714473348938016737881340630064336778236707151377390953311559383524634715033029832132281318836645562670464250671271997338973713626737833119092136778757060698221511017825687441426539109882036947717604129977508663250964995865526427595936358657495610498193879273470668736421898826754583941664051655944700194249310159206329291372082540195837062219636442401419374452242751302031837666431296991798488736580272533214722633973923978948194167266259190168024965510809504476306558406136734541542803271659015741242020822791690173707747856922456547109184228407716260018397928403150023425951381303572623315798374909399696669746336412408004471440362346429701118678634965250359934503396644933784478383603572828738206527392486176557920015845850377674077072581289869070217849455974116750653382288579749853916918232666673498001920197099278999636757871480372840688560341015920764917044213975437152587722772198735792344174748551846782122732321312383450770763936119941766719856389908782595138012368649784689353707322864103046608208464255195865916472093927742141418241522187323890561190009902182732492625722991429566627976339782220460818853100635438590712155197600861914163101640485711455228288925687585230922172967526630855758915862754723181849012294435983525255711965487166117491379317139133319586331644118090392262773790788656558242670140659797107093867595217228520291813207187033381858139690296237179567441584337420791627170310538778102593790193967070210778123737340663103266592271852337247202925217502641721842368475906757706186030897902958656693557220274531027472635033093119472391350740538554733661796561825912637331548127716446355766189900622437318130702264327328216048418807709044099092863963711653490725682658345390558304939837584705241225704643760451148991261354563395098156657694695480467433680193379242245610217242642218517633259212109168815466117585575839208923573429012508354019869194481956941626708182027030212200269101390498132772737591508577100060199613458566505034124573957664482584530602733252438774255742092029478809236883411193120959882187554879859613548218935214103447639549348287782471480944300043310211677390324433077385576501833364524764490064888669242390598412710997050983020390097940778231312230748355170139124786899795185395227791010477899106606971520768650925574676866805441632065200742689722152730360413802145647450912013522336036189669359868939242300481115725467622288735333276747924855773402113407275583353716133522901895318728248397905912173950606661791399029949088098108957061684245244370932757778765219881921504202928508779709312585713637849806171316245370261255969775212398239572602117309520212052812270181936273201384263801785684672796151288177780090412366024237413967787528353253942383978270871877944867561320862884846750015231752066280075311639207857011531216251331898485830350914555297732071869868990311715223558738399057252942598489879468715377550581203983880113449141280233807521643471226971911561945366837662203054462908134396516676869390907449229302229569019634716172020883888009299918738434188216989379354637060898465164116014011960417763714004673091259313967665883392246537656633443756482656931460558552975045180791118151506152552726826783332356662214031107471497046410449525868693010415570899155054191629511726779118543480520163499493832095011084033196667501807247052937943272320350179049718381944628112666997029934336176007792315008366431134968812861806320446915119640398276190676707119970339007677376738690134360117458391133724762139617456047848093554467133325829039708150427384466779329225673437633866443560304958963871538827978631710441485582616646076351864902729126668863546477939468260535774211707454789948006178530281836374238409000263483165486155757952047893919952453801800929565127445540039253164945487648646867740082162785259953640856463646968320176855990906678758609222167006433120998106316750537478127483282575995911853282764568785317919222686896674972632459932803028541289183186640395390055118264622015205206963378802551258562453790966988543786294176197040326925684395094135346421068967842058832478336343247815904116697801493957832836267473106512325871742341928954557586273686810091067923664330294366902395227188072647994236319653708504592301707377036099419787404343001512498374597377651022152908385476189555884676541791161833902504518726217112150890091853386879611823095887897406680484623377590442597281801914524937835357745115730819262347684179325769841211178593006451813738665745366310711755470021478456234858145782876829460635905339917987581013837355069114593135838943456795779534024871497571251766283127892692640567217780639816043231267154804966746780446684718033409932932384150030063904857414832039858168558715966680354683342080063348588460733354165868564055937920964601045317154464945969184263569047666194620379924475538140801895528034087187698545181320930352985928818162113297692945737195697588258713406522924173124412802449720224699109777344147978653440341802206612635143575420070986367005142023693665795147993834166735834420206987112286740644250318452673461412989415192550333752184133150320746056289144713752595562002691138084063432818049481555145393831243671659376115339531509039021437879244489728402212198801007207985683449913481279516952906175355045994337088696372445553020795665531584024859254061913296388562692794049590480976837561788884258835356349763311112728780743288304518560197704478163550683157617452667948069724370646229129262004876239886643629193393957894493787604195213123114246078572624257236903436473690705519763884513783516715837158088701718267162323761274733911082007041966327992697464680381897456424608735215623773096442271274340930774219725752113244540993527084194320321200150278142091532218590500301444976275733350377494200909245166883860573888630599205838514553187152663153381149211121375319054231456175736933325035830459185856090753096756997413361674112498881877063520160233725392349739399633544436019238523790993333974681620593493864779111425722325563693076928181257759837507267656983412787224826523662260491606835150982521233614865313331336765315069053181851683053829863035246183095781178516572275283377500222409037529899256483609373716412529981075520542100788043417409900582476531415914271999379561777585201231878836457904580937033627890847063777585922373547199938598005569328309348279123084486066974257141900958367405361343406674227810746564180940449029734920540234192584972546071550303777707961566491991819425917907955386454837649519869914290741490741173972913317170905113656518895726296582541887671678157198697269802061865182667693242700552248829989081015214699630680502411433496257415308801936777904323024676450648317816620822285694966107051270782796969694611173345571052217252161547914150490082360948981785556624692887652704155374559045273806186248958983997923466947362228881058694117080607613822977797779791838788520667471237095334107448788913251006883976763476364631971337387465869476070947064998905487907617870554798604168840365355767260515445785913630860568275437767467230874581956288274206595752133068459181454815533101625927260841570019106785386826244700846853629249386326587045041351502874017976704302203199392490734370035906300879110643178502213790494662067217687433745618235884012001563368843821846152045218197908417115461766254397477218455112156904355193477758286259219895779777415007604488476043754723676068259506433572774616711584315534458664987871991780805228167791919213593264607228827167742351805158969340942068025291907424381272715748739321701394176184660219405487393220889998726906321719906056145343495833771251106557891737199543710302591419312248454679880383879438030871331914210615064150802955269799843779053303276694995576628859539870631437117645282376551812338849482281995266536826309706653386073846284390519345156696720331040809453973656034328068756233433601785419122778657104313982946833198188169608614963014110496620564451221090227553069388356070131353399487749529363916688825539849874488805698238289111894166067381387578144720485660246880642480705573776249899587366437986868062153789160098673701702856047133524086363225277132360779713923593459055806589706559206836039239319791861822196477605796109348379603065083661053489221037360291905648513409434580375237932969559458108072321283012721153287874963393799543177159807748251287083049158525864840549890042525006751040258218018346399789889196445579937015969708679419886128888718514669189327706827973753678848191281312594435585075686592472393159680023319650724357476269419391563303690245007479803870162573117138967473183066681370227471812177456936877234640181915241739472596644871789215934472396753121204795049573681134742546614455838408342450452714283129666201883688820985768769520454168511427377576167271732785885455689701818174122685599348003095051328693078791657672909394092153051366012224811835742627598890354486062841378709763514472253980712010816536944478250605430481847311120397686557293604388801766426066045171562707475142946047863738758270971582198049785642215700420756849052897800374901593906664891765163275673098719511079946046322227075172770992330943721429782269396151588560111719019016355179834725213787046939178024040833847515556509377627590849187807455211518065749211524492125068752768500168293272133549093300597046337291326475385976938029892774273031735940651344743504264351793227980026157377756756298173248709507616451856544193664147019955283967564051951703224072544490491547898009195270565762672457476286103418000379403109329647166607157759961943458812630396727273187367759297100988487620409501951338513355358613540298250630287212183178912934213240946127301542190816220084468358602100200721426928011605887642430037432107526240434353237952830735764537522086239008789981857411695132941842817184217039623561832631200953897859439020061597824515180690978493928936010707506644472224295123878017507471779058629961497471485864792240477133747338396775497351998379060392243675869614747203302063981239552454478896186101030084746862406472653903492563174170252779161323240222793786675224952147593717018796122654760635288104606577109234675123419200599266887901999702378244130146002977121961854295881002860812165457839309368387558441504095072210684947072288166190207205993097937946414935835553437761221468097645090083870922204524317425319282571800187826541780777187013509899572463931745905541482152362647401466907143586600994753793865474717826190768247486587100125846244479713555245855691099325509390466224876943238058244985809939119999133571722206192269283505007157422176768031977599193058738728770008987841730980891166469008780493234208427573456897463043912657412432206620597676408253427335229116915954700109126299025229009417671531867829158321326254253905737970107707860445675284125065342326798176257946816850381290301953647898352188860076154064609933892982662185747707681209281345319715833137565433998627813298877504396061185063337576812605408587587513979067085715668804114519805511318240124128574515285162515021937613883199833538675746322554944126890153640882957150804581043377898783935310372238977364418259116631762606172402074532330686483623334589799599004187331034952482944681693042134777905679238786296027157514115112745768874277153962851114554525714546102382046985861023734768625966632529108993403839533890119394444963286182426435052574135698228312831326725829089012594515003198231073426561914895662902598386254339329367151080022909633833168715730269696405304745682701105465777141313969813413621992638213573110946626776828938369593579320976569022953867144665707942184803300349508225782871206232068960848841178300367634299786424667680197743645134103673002117232939207666244924753646059577970458817735657553834131201888788197841230758922068058712304526568868523293260698825708062113246337013119958782833826069596878289408726941120797987031497904400805150915213782770195328553007343854490191504874617078175657834960884673712023693951321610970449350467341668859931935045134295700612727420663429079825178516105974157485064544697057441214137102255434509055243273690939201001465401780555662952378512114637688225621215961507112804982385341653048473147937366933407630445943286488345068209787671928585872787137094336050089793015422395429208517824770156226421799636280774642510265707317546077104890253775123859453090678564536291557467553085050381173567898348583096120776277496129831287170189883796736776457491022764053461402048405639303325812568175034258735441654875041810441363790270265709737346088888830929246833939669545697714111753194193536721318165924310122998458496437192480711023776083964560174744031831695865497803013010477492399940813052827848754194765792517204394279131926841105883278342027530261298346224838605736896921498940213807946108080369139188456238187627286422462949530571051904914953919073158588955988155656562965962940586618920963817728035075287374811086173097748938771268730392785094120081138590644010425253037757772863729140048354572636956010245141684474330688001131681583781973242747081085574125539700242533673590483508500246026846565154657968022512502812462050794220696934600295114945935905943851952793887845613132102306227419109634594221778767929485908588085402305886896495374341994180612242251955371587620425789255847730927274068469743729926283949603718944696754769926990782645098302730520862157488133881925832162909868411302780458528779494830227716980797574724739406880789132571662674035119888281011866236008950351563978234065944601028709003140672878839563622645585803068862289261147238480103194953983134724149921164276778875341493401690112142862320791827659144340830934612863792876298791473080258554444121381974252968004121415813219606111401835237770574323754819945129670925947153509466552290471889060637288744279109497548620396449440145571533798566968967257067635060342570584891148452286141771165195699505743198586406359637020912466479431566979505247654156073743865528439082852380553947282426993795511874158020122149437580433383389605860640305811804189952849418601642511372880578910681191860528137109864279613455292175694235740618877246727433011293924032658012666047388015996077731268301913373833483202228655276599808538472418458571138850931939725868635637745405958013542782751018302298167755577245834029791135198807626435804415988982279120667298919462486847109277946293672344815808391322664757667768020935090411982028031763426483784013865937751921814249515820132101121125693914190098890167317428059325596477665449281669895142409467030511715249059921771820060191054149075059311405996517686298436934137356934323213306777987821793408954955808470688798984060427218183426519285454283502834942241490625760179615782159926553996409042533683584097712647374789175565469419262768670735949166537841285945688784521943313916518111630838747688802112670086250025810252312267611624329708703233046525869615434278773145872128712466898706548697647148575346018359290889005616848156230356541132818555417260779420882377449070801486010680543879676981331569198777869492506920715646464841228439381851910689503543671408223833820430078186738394019204027907761191735895053351134269920756820983594086173265420246892363795762563032151324479431259629931531920456019618093139676113575921174350683075667590047211218409470235102130151381597058326274390024149029809020419130520508415091099806424120025089563648064560936591980709316359656556846441836845570305025741159470206423331997024183128450208098074844808791305033152536605349144323734274631165920350508036680402274351760771977747071259758657073070492019304053388421871382072657748033881601280483545952576156495993050859080982570101187194689051388344707308476763909102816956235319987341520595849359828031421144831619166529458222187721186404826618659028291873580391888392511886544550211752623771112608430171850042019284632360565591874404558456779850931877506877996795388263396084630354005582121671537118233737247764076147912434546150898220931552981985243844963439945482641013358415008066776819805691142110118552488405675236977678164463939434531804933733468831234189364325151562907684919832061704477220090807200203203205012784847134139136474461959729984275678626036258658170828143463757872749292833971342033491036737248148700888040210928432363494159824493524216529719018618748743722344519028341514260389849379160087671756019827496779717011565524873745383724376693666458601890174471100322791943867172966258837046901100953317180371103487167619192237125226885571421924358614523212188684533521206841124423163832986726831828143138264189203593481115036744363428675507414336697903187254570327860051052526547413506657997824925315674695952836443283809407862725458844566355877791929186936219677109762245460708694078559953042987205182275536843433573652520322766305677787148191296341607327796772466218392188058362024792443287234057647193956982035210986685102831681331023908724499821564148837507457215007469938245815982625494529650379214481866946081656280166389286134074421225007804437813110080298380222592141908983543956634648843635517185802676001932950813611004824041121901596644845320216168422647803451355701399889506496731507457237568674157954949019926621689080282154473089870360915175312578356893518512008152474726271825096169801234931338803914886156327446006493242144159322963750570909452073221417708421446252481402533077696601331481189622741404684396543697244224914232702175904357397970327269966311891904122657507774895946292991353150399545551351148956885114530363187944046218826952102038204537269082760444218364827279826409849321016596162258863670392368268438934871070834232829376747832659653063757322365695672542288511729193668194237518130985306129170389598419536784970474273640592926582344552142108441810694509632613120880645256068135642328010189808714728817467996954910467138784685773072551537752169816630367778626282276110358703180853982585221328216378532921964368951679698096904887846637436711810521698769434436978522493199949243622765532114164271019195653161045942051609730313198428621083475743680635075259652122083034519162150341081394233582248240565273942807293458783284912235771367615739600847453824027437512409896852933712701445876500705252995997933038574879891006331642650850038685397897519454954850528761487604142478491141463016015346746538202103461857491957672929024326403098764544768309687130119020677113430498263918118338065543293860324055330242304082931256165833080254880953206516849870790873337596404473299975474465664796442270612907908051893494201035131804024808896360630066440943010926080517049684939812744143855051067211306169326442258931768749084487053709621766161775983299347059974682742493379740247532088637962478571966833614268309011360238105372968276640200172201943455508880017262999676208137152826164687843816706851955838083190765533886564804157437095482296930280894119091077933658538510805425042934913119769331502717277342565784640754224706476644140787781088544123940736929815366608032248886176013157423025587957532224462098634834055823268467339317292912321449816804651266686361042803283945037382718616053508271415669381926766015463200892298225409275765034563469172901826107375886240913923718141694683153957903974974565246864443293361331397168928913617588580572149595795404710766837975115484539361654082528614322948967171400969729116527064018386059788710085912500267225017332514856907513493977047586898419229413352982909932393229878372931059769374629016151976811257251402120245009040049428126930520507460418257664328132318369548615576462863887965333150043450448390683920853538415990572017078008841088375033417756538780605032207992410820761528437504798283852716548670005914013254000306375968169245657549565004260432153779674226708304343409020392785586878073220081165866060227599026695095930088081238812380687616185050829834380166221482915214978296540189439572911627593442633878643171579049610320443860290055516242051448989971371323629701984564271573803098658483931382255598583747040369624712868757581295914142257712255254021951104643503423183170833553254758905964193867552703704340643126666803861726390668347260337607406022552834463067985760267362929987749630954177950629064367590355484080568017012637121334103191810774503224169456917248136177935315693647175170091044001839948639422206740076375673224017257099665579367272838834518683264123114995280198749913069071671874075201320984998898733775075448883543518991087074646481962986868988268530098268770464139821015573604106513597766423003314441610400278739256974874032423566375881860757017462828866824520502705363688526302135849312839115507615847753141241803903641291614937484086406003502652662910163130542344740225967668144215574895831085670940240962113589518648984496952809996208968248814204420877883816703895640095206717241777305747234565067763562089513432475672472913145020363833938045464628098105286812426637584994111347596082052681855812986479451949993295248704624827597895832964556508318727879521781898310305792405136321424605645607530183573384184669815579374996044059114106504434857135601740100082807148393715692185426964192088731833977574817465090229734010840685707699290322496496853059463907700464704277190496784458414482815496584201559588758163028508437359349021477884452255687689671259205391540136210781310610401846455327884561776569496371788252854773549024465988999371042757360360876376818924239334337065181592782709790358524819810839388562083880651989108593176973204030188492517982315178480782473447530615165759353545790829988331023852369626623275932507785892136750046710739663263546709237465361107404620065951238278881806290699016153772043371852616016188512952746949653977883263869613040957990699356456352031468530513257688600835625162265754128257194292863144267031892001239743811979387054705668354111119378322828884839288762787128266350629166389609110617934450997538918012189887914762991854346010920709262182962285988422473458058435306381876642799807835854614048714905598309476890998357718515905841190372890167582422134183478582185033345398531431195171780018374020470360514229188653602555122569112788389986556145811974802472767286991402468330979013874175808601356294635584896608822098860389824745998254858900363483031650025002730956046945252641012406337812808952633469582771625887859235297405329164091391319569563508924614477402150243746773532025184112182606705108416013430480137165847750023994389904699328120997154630787179039401635502719627314271063352795874513619910646747888001305236323883645438618151072556594360505598661078210763924323012531784032966682000239528737502848100976713537972559050499121260900605182986116602907660497280511830965837778841773809294692372666984713273810997385104593046610226397314774110300743448466909980543357498583106377104344730709633615540441751654723187506072731892761070860802865153719430477408737040432609914756708994537587383403905950181168797339759888286718088045916317353692271492661156968084138382127755146308004444101169080712557239725554470958600059541049485305422600458058399587831919664665942782818461217185264006413679016942814547033743320286173639362493356117568028693773578675388763791881241881561300853065074782019484122483605474115374481139565154742689399262166774172220229904032276509126734672131763744981683623589500662725242919972669095197539886130636654542616560863823071289572917195179421633669209395123730480527598964584695015551387063867173145661881337444074184238274958970624294421822455773340871049499452726188840764782846017149753815357270031058444242630558541469607556847096756738352738315851271312863400204368059287224039521867914612117114355891566865011464217618451403546239285100418654415120842122954738459269292721341792424323479127977413964061278740601665860494544091427479739682908491115326371601033712294577704451711942602331917826789809528828725017196357212693631053844774782854216951030552708686242878544674009433473615521509028302780652753226473336794837845359894773319371878388312228357961749026964153887890756181719525218670246157891047700351430506493792350721316937841297837932210164947643315235168927220273659569944768141519572432927976398914855310068043267427231930604212948919400294516113230141913141097168073272132864345203642646121530456693281441027557254032099008924134208763144730881080619352497861705177951639430382878278643879197124638799565459522394426262836571704562241857858154817874382102706062765975705432205506112193090346300155563478198430430200099393363860168775451751307157751615726126025295656062607617753727347094446240539666202166355059124527461343947194495566744272892421932438773039842354490701468187749701403040499508403368522567586155853696396846501623861471850353468988557747739594614228808352107062938286611230214031737343451270945073948379423363121931645718418755728811092576632887384154522348797604081466177129990500481534018786214218659433292831862924552745811111942378937794634368998018817436037242740487591417822427482604519809279708847922624291600583416273291649121568116124905192606047649324448462722198433667093938942617424569742862088975051742247460982637095572908859329201701212362314620088224746472688045189607358281476481904695608278603900747860517339371052974259196693636337218240627089091812901076672993251664294267752797270717720075821618395886725538053578084156066136766409771311957228731834916233504402973001868565054154127000373905516742943140719395132569506917982548138190252549714439422404183949507932245143924876045266800511398423232620751202867836412618679148678156176887631197047336259788004404426499367638070054116784462677155240533749679478721040055103211414358472072765638652525769059779545467483582308737652367947592246489854044742323565685803136606600282434917715893018510043833994063122586157295132300775462212267644021727910655123218434710318163871639189576778317655373448638056677388644787396530750054268373085924012261219620446793619649770785150158656696619424852368199325602531068394971635512926790139493504412414571784516133800401815839000325597008217026791627603313412691940942913833807362652824448121220057886877781565504551047050616762386819511873681749821428280211832577346673478797685718124111407210427874381676801353955739954134391240303631284349186510031713517227947650495584711408848338488297875550672769733885454333837288525710433519253844322419481353023902740031259204354412246874708357602214287587513868301417462446683853729579741151524911688512810510638074190501843161639928924712255515437196527004740845253000585097987392667070418402297539741419804473598521858711374398795942759924855090399323109313245616329025359178026895875837224748307503331742874922231963414075592290892153712943700936925238849421872801641897514736009368805402959716691500750573751249297815001045877611898835483985005149276490128212415865697256022748960534375221816628003507804785086740945991127723113216070265670667662527184082450642695837567115687373633975057746837549386783638543855553944382255562798172854678173355129394746468391855409212695771209028422681978873128187235792907372579404083279570107431720650302152919578159351398410309727742713952654311908027819448849059717640710742807354365080221556438543259623303601882850595444672062803778998810383166854319176214244177202629832314145138417233107591104906026715218882717865485807408530441892400308637682203069385140059173085798349583669591456605327037001331398805136405943607732489373072261569176229561736833313638621776566719860319171562535953003179625537413121638665097691989869243882935283923973857835664417053031754656632433915204763849772758635668446510139531176779819562634450441839193953289172340360128008023224125563715852979730219077675202441783659814558419966733150617996748250538968310427229008608011091314864067655862242259284099993212962222565005436006148896601868067804496293147038405436488436177021275949201492596217721808731929967309600245665225620634210981230906919643849689390421501428620946338315450018808118529267063215339233785532178584861743258561138635065167884103343650548505515878693407752436372664672081571820819611361143593119979209784168086594308821741184332937175073643567035279830218672822111755052394332602950044833692469305146404842303198320951400993477673263867241348039036257762844531241805347231375503524158197460742948943305024287231113703836895179627000821223811111800223095689212059724422267992385418347686561342618622671872417330924381722012715292760929812498250430465220998871161795793886756709110816326815805434848893859453751850730196163444677123615221768649723657643608826600498360706827443012519839100319522621466698293688155221574910314727316617425022745715704445011799011535617221525738931595237927558189215093967795993948688927258392580616115848158134591082398278898537168851582957541453466128450442592484465144952505518434975481486223069331233403627566748232785558810825413181308386671540059773436072472171347690857396736641179429816087254632073744333221398506798251805947028144527570140947842612196699002035895161691950830290696931719306784832168723015029221648084905489906711771783023640187898330663444638428627623605081848248348732748826461403122742515129166635362737495471866002127409290457479896542103478063252681633502010990350026285070607146179996915627221218551676862886356075827687067772873400229706596107470604997367012095708832126541492416571398315378925197634226385155914773386410252033509256816637144424578210235889673920745114627431544644417061050370863142021569720551508421230111479768871067642322457044565677609938402361820471399104394702345672204357351740338598297287251336980974792695456468604918602575427586870456413984116021343461629883910494725632359705661265443588315043360731668286115114928559502759311405322938655822533377602341179117324962867418298488820101012031274065252040115821949225121404279248191406452125706132410597643274382433243108453155936218385943871220293587310719224620055438057191978254769117047028267813050195737044891275888425021723482267699952561806041223360687016365498101557936402195333989685760493087055044963744737126198790650228094458145646563558400217557518881768989049728558250195718535935275264104562619141160211986443110427971607255089959082354739689992442060316351322454924752098293130524886309275415683390173621276479978708449529507003970451217944877111583010130797997958383542824001832408552095744890978991555360690674936647620258539403612790510768207339426184198710168899866056707279150371516674918468490358126685483795891340433095138217965737615143816971705580699187113538492685560635828055368793362984154994407667352421832693977727624292529914826437739911276284250413366511964593707239297835735760960146234991376396444476851707759107165558285079850578565597439405233430478263026252016407597812710616364649810849984589666624751089973004401344685985801965751004558995835545283757861256686653727183808992734511870044873253210082851386510899610110658545222045480505045778130873117502875393765337788488424301834061878878711960256312178746029808094777079789887038288744705404383260853631766987997896525511170736808262357375218075971898658423870862688280808564252207667402856319959793920034498824451743615070594021330012201783339731723144671864504449933816478856015402779321566980674736984134628493383582993367884953228716747114991376900550925741181766972788665243014893294750812252577994595222177791283676807570572637645594278522286870837971548329318877671248792482929922631180802059383764151470871532658705312868449138930046891367115316904641416482410231190185984675664659158131351997438599086978317309215253966241800964482686783505391631753919423146922449415383938466855436292170146826897211440611505181680798491854087755465336569959484216431886000320530527981245122690017839564434488162261816420208506840400766707571601119090307478181658990014967500247819394628783142014011844482129281500122610011740349613687367917231772457606356370446646114054839701525782981856018150750945816779738178012747296670632729841264856062599611989897234783355302291219325748220737469839145824710420038114193788781772508551530060658344049202892734970115963434124592891060490324190158025656015155209720790905413511353323701873461197362478675168316290692408288451579604145307111674816304201110601454338321296528524852637893465209689451361519307135788973090813080679452952120339111904354348959533461690923402197369535493764684781889168223984266727161397716207376344198617642137054195919271655550820227353480506121358843381803518005855806379877093370294233532317174067520826801455541824252690148646481912319900958167912259381698624707826688135969965001170436751348155339615906453624438738798983483779930047787989007778989526134764235791505208992027564144271989994400730279446885538347486722463387987092642789705848808564417592684566269479811185256875366136800458737244726314676208005709210750972744577847078798330864431085539103650130822695973547137159340497411780312214699994336251480804747527420004390077206858410708686162236895874763632864184988392015518767223929169596075494128152994362704501336165974182700533193965366109643192642465076003567578999676759306428466734752765405980267535044609420180636304044052785337741320276854393122018071180655257825011487967216203941861573483105921387844284127162135308826471459975744823996558329208984912996131889906599265572471492590889465940649317576386280602963563110374454165554961972499949812060772051946059277261422330874126746768289983833577627994259532243147552645589850127089787923362066299333957137207673583537049297494583945767486126144236209346768417999726348802811454098843063010192004723839029119536239799594159520151791806224942447167712331762436498098915208383842006637433118052045700725445194313279441025436943884025309605676504538129757145273731872727767501654298212830413608297417880772863384728175210676340333788896259169530951173780996011174164510148077046114026855650429854422071732689546255080784501856765412389216556173797265070801125077788847980540695818297926233258034846470574148098132417672086743194437062425593810691635063454640010994139340384595586643002937236850431289863835709385542741133806350555743105490474376721738653211651198771237307862632759580239240025210853072480484381437052987342714825148252968395084638213865532051956017161439077777381052519912380702858709413141290428822399780723564074758244627666031380343075108190041463384394335365153897921019009168791581491976591640995584279382096462597063448882539242311266018645691594638634220172531960931396733026422032774092161105483821273127167322065533526107348811364153193693652590666279699872910970235300728980414465284169726436771727418490964247927089049687995278282629424526759206427239320793493292860805364653364091897777372364201604071755735394584803913947889371508507664302988103999489119124343884247382561690544367540822464445044126052602974225233849342594437701248782797383283362879818231135693548376691043204505559936573580899275188146179109528087084908618615836824464500991394746963347770127060415477932489673159710818823778539528983906109113989860465337873574651546460287434363288140398536654210632100852930170106683727843063452422414041558201948019874946181081381192068242798881948299690202453847915518455391109132034517610467288987117390328690694802456948230690799906016388510839736841301469270657816685488803406719322533005528440607201676115848830432741121510101588700623707892243080559195756987460446887760204293781671208360673616413367227109267405957865389649918333886948751371553175918649514134164506937313094919480452393509749206250762425602081308515001934825304821110839355373370056297923152529843909080996774426200140143600736346646821542293246601589592007364612699282697695109371452461685385509659077730126900694937248798377087220501788086713134630850680016252502798820833723528403154002181178910139319362210639566720560980286692485113476173727742877552472997598574926938506798486784730143868646478682346419149419458799005128013387793934542066420599367604690152588540877799906573562995317316329364268022747287445835145118307382868481170611138743571539151467367991668620725959273117554062894477896747364690965337353102588397895423997418601221495837082056069159780261573497797911901308383959948321508285585115851457205168535248005239130205174234991112008043538254228809921121028854427039515479256216553156983223517477216374387075391258469355804127328130052027400165812735771339808419064834512531492798681025111662367633099752448538673470689988418518366823022923587048258246969855729508503323927043315928084518495732292398591574011968416632856260022452851563499747566842461464951568738902064516252890963070668402696941354176457977203320460256950825070925659454406303483636486229218619114177923665669180899630705484729090220798636104155896290985595989319034502667728302863431114912716976364615979103676452181430416320520975453740117124907037998324203269895307545907599620309938048709375089089180690377616672438256641585395309291426755695343366965517882354980583581100171566226073359923829895508936206956219450428020691245211473493147307708914156362499000723880930541641916173371450672036112300806942161198249787026595029735700620592626543041747686687066372104195250439648020815348129372130095897502012422508369490190871634226017506941737740101538953177745183062999553628447989402627147561945883669380198981762519023048292659031683349204162283703375987478166219598415206801802458663768008693989401791426977048988550072591820401564376356791500383710375645673794899167247169747917189248286035080403351812705428496926277758718473033167952378698719012165625776134832510178684670276901983629114467473676566675873004632451270977670704732311119480062341104921956639669365948052515745924663718094401318215149435804089348050851366678716289973910072927610715544043991765841819351692064015060031406081161898505775776171580964394248611724868553534967572103291670825377733687893810372121121711182065378237297650424303520252523721486263538026308009914940961812585923225762772301917800672567868783182918326275796770709114289432536447112229682915080579286191073190054205182576199446308816630477875335177307961657167254026572783151217865509973506051046189189012590560701256522816834498727019356596825103432748068590716480100364070998301664373172330300013675283485573417772544221820129129830381842373285274676451343611545608735413016738084484417328374881556701179469826285075438111257649553646292845379286492908989424556714429668790123467211877279838395946540600182906376516896348717932762403737595477543680736155552006262706997843358718769835719879111549067898697746349754915956332183106863007077790344040155313913966388849935649614510551457679013096561810393019642939130250183430496072958089006274047410600648986205232767407425634516052108426288193523043421740914414978194504810666149039700115440568715999870259536328698862530131056661403017014700184544751889778086220755597868018036770994861535115799628894381359631412762769922024210105247236717391736245138513460553036948418240446734981344840720127108977936851489043661513184365605237835065061419598513148011822946287088285207125541794202345944907182009017716212342530944095492763138048651626263595090671799996631126221803329030775102357822662987050549966457460449235493828308117345897404864432460106642206353319439056221713094738584689733078124674162182167248441938808916772765303060923843349548422029001701365686095917483222706394090983263128663296561723393793193805140987574000639380788108478227997372831857341654591150616016372867949182350185045647078002693607266074992241140279675591959379747377499161829675552373486953667138974438601221174563244269778222635068474681836497658839418933261702155247714587769962500710821517998499122723270865858847688258570701910394957246160030533522109149806498224971071143554278153861399276362070776582874824579581984852229782567269407262945005728456366159982637245467416842716404702466266335490970444954921309985010533032583813429918205978286424044205381583498905522017620828497416976694197189699644999122242459000594022773756919138409211845894655946612135919387337465593285475737067474701479341628049380728044640957219997488674788646355523903114034705407242173518026129904904789804842312485757755058409650373252338234788827030997989512831555252246656945486356754589148754166498974028648767015715051302537625140095609304814263583528807512425510252775082514727445896281836755826016254671947577723010188952703989472485545750808060191738126676954572194115623148076334053874894779078895764052786828089253152164841939356448502776919653945339059415988781875542440617573684601275925678520550944731298544193636880885938947626415514457821941523407286742198760353559156284802821312083110967271508718747965245384541126037230629681317625411439369623167297236094799019185971040942913086525221773174783429433763522040580799334682361851128152863111177612688557664670289892402503345477790486093788911779228798543507427377144141136889761545147200540256718014180162997779184567171715359188595611361111671528563557111349926378703515868469813407550283502079906133133396112521876406814360767130357299078571099470430097907611370862412804602559023488296912091542407512682490241056979883906965507699130341119590150387580102470657752294284317411870284585354314992360651246474320501228445236193304928671182308134778830974979354161954299244527464660825312825913859679747927041539202327972687352372679954213595562556368467208058772014665574121678159108031422553567420613414361166699490620483603745803943196945755278972744617775434446254819100467789043251395960901253638077784159869214648042782189154027491116307069239805330921150463197504943404224345405556441177264158848963702626567786480087790272192275298333413173832370683853621638583383579306144454523398377609441618646085301305671034010760910256852623118753728499736936891919921119373617055583108477088445586609506521525745962930950189451736578414593432247562253520322638355145659082251236207572789666774197220121447329181631925670923381989059558836522215382493639897906572648940773453808780573381294158231275116893180760978487210412692859422930430247338053923685798134491264873283720472223059890649976591329622694419893664873528067954422321726253896114086433345113609364366887682661249754292685554877992378605508614646519420421511167597208643722095684856571785847998138098032915098274992582094901327369182890779126347930444027251402458956847072516741892321431040665194081449390783689244684955810497931039132551786127969073268458825356157270881465509994418061930523023673308652173905495427423956864489630312766440969806439690460138270791407058320256813482710885818565560827614412239874732920473869086103311976086250594052345329336911101980677846322297382480236664812744685920710932231328885675102393232815385704424919105339559326595180010453895596601373938993058945901552542555696202086773847185680431249668780548853832180135983622914410284052223492185955507016995909634508718521305581079809454925381098422460608455694774830566454122152115600477396072897924140144009367495057204750045761768413465456869105225667436724024639153485495647489021701400981149820909734049775448974127866412696667631167033933347869720658131481495181029279860669169438372083537566127208790829708604371227886170551099130567071986935304218856329309786777326839231990775938335748924629843494654579373624241409635559869173517951860317967156733840239575431291562721813378629913162925831018187373844682305104312669915501938326855093449540871357610029788914565898433725168141292332136080785879789269534344913446809290094311712180760813746324149350989934612087481059088957434694032391149297126504913282286704834485050437695529940061967947443756881356912532174992442933366504710999139495956477957736883459154781750323048853552171228737179217349791663565371842233760460414645861568948218903744966866574256995895999541604429471889914770674559005332827844094836330548724179370107725522639139179109880603335714506557977083805586153746589124824901625184999140629588926691566639548689654085891224424659508254850522544503224789576779424423659275693290423473676076831303918645651954552334681701610058980978505562491707230777771839392929663253394821738724343890706993984350671768380884933512236745481596350964982502726305280252976855824928553943674384082473234346963651651760308674607227849879606450677084677392998048535995307464232424442699450571325961042048682053648070096986988275750927360499052959858546768352883882899591972331277002762465018598528912823471971088655821059529503383865859289673927923561990214296758295468639330814350408101172012530564402677022280409410134485979915737199190588418975319634761166902590084258199911286995196952556138826889543104463811438902942244792936802311951730719120324323893465635542573436793347068867886096677567920957469214747924730212925266543154078332244277257163495590809880068051446878081159413073239656156661140141942282939941297910052347641520273043054153462038826861648495100724368030360106702650245283976244540027634588169522699606084620783497526885421398068103625662781778349924424793867521844600279643283877685081476902917538971295693975362994404486703826952938322202983630040617437411711470176821957009433739854861507220679692976937107644554801396569983556099889262215990261346586533247976474265519248142219453318763543440913165166915904559641678954902636449479359433254076313723789475831915525597505246519642900331160585723172902040615449637599290503468387859567766803291726264170232949693946726106708399574663698653014747369562895935509850701961943341562554872084667884434432165704900757463661021645194613576939295869005774667609414327638259540409749703850671976098525071380926164845263077283753025840684364885100058414729332924246634476796227379451998939367833354337968753857620069019850717522655681523380252215597924721980139523009703261602926170885645120864143571552882535848004007028495693048609731455227992309695660202846521091435179218825423273985390913203384445688912837118002584005804742184198890187991863910882173560002606240234172235571927578987296461141679672251980829685357184669759286922466009342848706837910841045792890946028890063483072660226145596325065444513992616498686060556996955788532105157648663221682910757523581771536583769113292414307196567066836269957641859183745620144999510887969523561659545579646318760521299623004496777817224736898032024331244506784405827023004246784365669624133470780815031032567048182084788495131443428416971172250431544033624925888418865717571281420005106584827677642623486626491902534982756465829720661286191162563540684690252799844733631912205921262283708412313405390198824517128035771409208537285380951508805227997124495119594176756420023939637440345074295206008753234504827854622026605711084831761233774473786493076940095631281889851867355219648397371107880250653101412146580920660037144407754650015291954902892773866454741827118931960302371662239585297455882649425633907357330488662899730290231920461205911557634190816854909521850579018794285271170619591157037545415965783930805881428303379605571519271343540323804752589544983856913892347720000501138279666162952086801842575819628679383618812852018058138888891579013831549759861368482192577997634589756985052393901840474801053129859031092788715496080133187951580405592903062256117091462371186413998238205868653565752496024532870467224284205810027437631606649556100936586259479755755392081497023417219947989229590134000065649833827792570891089755766453122346922730927825391798269666367322540388564600617449542046845860314711077028193923764732601543051631582334540659158130166012752275368941814134123385533464339404574156720269003396798747443417200189142451238185325074958221422999603638526988558097384034441303503141163918281075005849242714211755351065513748326461505582100493409294644067974113331866352018651170066101802373948129558127003365662817562072856504569886996259681533911567112146171115947702603308696978850968298868673803876758459877212476949395800072295097371911882377515472769520866700617180914829395409602109439110577212614203186391493992245594749785439557258893567819336623349403884801215028871877893694058337376204187101419755500833546836223933206707126437543843257593285323743252651647511665032820389297413969323422255951493303896074260923448568781645959091875136634117938625207610524604440279097521484476626289519218770570589324616481005937942798506068264735759984860001420451364607510195931797465942246105383290724648612113178896089093584573549545018358552781973113815384267781984596067132826219481710197836746392406633309107228455300204685908081315206853724581759245341509152734010310784199669558237934429949306256744025844301050251591330130980397876153715345992852647545507412684059187015901200665526267514770019106755696789982822129316448045793648299123079236473601172103700766013251039756198371626963180609139753380731428038474251455396652297696540957531182446505493092606657212124200826188783954944589525333707961537902200069383154380191909305127438308360809584368850361698872143253865472370598928055774643980780683951677598189553703607536579595086248936350937790158929694401970903444618536990198304772574563683380526034263768577834056139408461708417701039147228124850842252874910698963087470472382107695452594996152102049107853897512385093554119858630451014453556291049675178454062216367691077364454940024967213682615463290929494865230009236123632880547557278512220301070356686801850471097554625758138231837148735498177108164822958985284303972365945657313416578443165227096826828580702509947407079736114077502161053252597485207805819167499527169737604987922601006070078430886014295135352615156609278941517216873259474670328497435385552653658037023893615852217785715518478848409533846816255491399020782402149530710019380034653234143732266468122427532108642074676121927203018937448174891798352465633525701988560300239544020070426821129803919747427489732394360098212885124763266092428541592584883995350888543204810229692071456485364845967596843495261589682504084913411113518868225070351101821269336939024822797696912815120798002083773358355516653550236622862007856759074285441634657416259496770153938631748748271336013807362307161896182522507744301074403953810757826350051530209841074372593705861357687294999999999545022486537528706028243119959581970) | 6,180.123077 | 200,020 | 0.99826 | 213 | 401,708 | 1,882.43662 | 0.239437 | 0.00021 | 0.000224 | 0.000135 | 0.998282 | 0.998282 | 0.000379 | 0.000175 | 0 | 0 | 0 | 0.996999 | 0.001222 | 401,708 | 65 | 200,021 | 6,180.123077 | 0.002358 | 0.000154 | 0 | 0.170213 | 0 | 0 | 0.000017 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | null | 0 | 0.042553 | null | null | 0.021277 | 0 | 0 | 1 | null | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
8bd278aac58d9ce5dca1dacbaea4e85f72fbb57c | 32 | py | Python | Mundo 1/ArquivosComCores/File 001.py | PedroHenriqueSimoes/Exercicios-Python | 702a819d508dd7878b88fb676559d899237ac761 | [
"MIT"
] | 1 | 2020-04-30T21:32:01.000Z | 2020-04-30T21:32:01.000Z | Mundo 1/ArquivosComCores/File 001.py | PedroHenriqueSimoes/Exercicios-Python | 702a819d508dd7878b88fb676559d899237ac761 | [
"MIT"
] | 1 | 2021-10-05T02:00:04.000Z | 2021-10-05T02:00:04.000Z | Mundo 1/ArquivosComCores/File 001.py | PedroHenriqueSimoes/Exercicios-Python | 702a819d508dd7878b88fb676559d899237ac761 | [
"MIT"
] | null | null | null | print('\033[32mOlá Mundo\033[m') | 32 | 32 | 0.71875 | 6 | 32 | 3.833333 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.258065 | 0.03125 | 32 | 1 | 32 | 32 | 0.483871 | 0 | 0 | 0 | 0 | 0 | 0.69697 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
477d1c92232d20511bfeecb71771dacc07a51d14 | 6,057 | py | Python | rds_client/resources/contacts.py | MarcosVs98/RDStationClient | 64041360a70cbf3845f460ad5831214ad80a9507 | [
"MIT"
] | null | null | null | rds_client/resources/contacts.py | MarcosVs98/RDStationClient | 64041360a70cbf3845f460ad5831214ad80a9507 | [
"MIT"
] | null | null | null | rds_client/resources/contacts.py | MarcosVs98/RDStationClient | 64041360a70cbf3845f460ad5831214ad80a9507 | [
"MIT"
] | null | null | null | from abc import ABC, abstractmethod
from resources.resource import RDStationResource
"""
ref: https://developers.rdstation.com/en/reference/contacts
"""
class RDContactsResource(RDStationResource):
"""
The main object of the RD Station API is the Contact and, in order to be able to manage
the Contacts information in an RD Station account, we provide some endpoints that bring
a lot of flexibility of integration with your solution.
ref: https://developers.rdstation.com/en/reference/contacts
"""
path = 'plataform'
def __init__(self, client):
super(RDContactsResource, self).__init__(client)
@abstractmethod
def __call__(self):
pass
class RDContactsUUID(RDContactsResource):
"""
Returns data about a specific Contact per UUID.
ref: https://developers.rdstation.com/en/reference/contacts
"""
path = "/".join((RDContactsResource.path, "plataform", "contacts"))
def __call__(self, uuid, **kwargs):
"""
:uuid : type: string : The unique uuid associated to each RD Station Contact.
:param kwargs: type: dict args
:return: json response
{
"name": "RD Station Developer",
"email": "contact@example.com",
"job_title": "Developer",
"bio": "This documentation explains the RD Station API.",
"website": "https://developers.rdstation.com/",
"linkedin": "rd_station",
"personal_phone": "+55 48 3037-3600",
"city": "Florianópolis",
"state": "SC",
"country": "Brasil",
"tags": ["developer", "rdstation", "api"],
"extra_emails": ["contact2@example.com"],
"cf_custom_field_2": "custom field value2",
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": "granted"
}
]
}
"""
# set uuid
RDContactsUUID.url = "/".join((RDContactsUUID.path, uuid))
return self._get(self, **kwargs)
def _get(self, **kwargs):
return self.send_response("GET", **kwargs)
class RDContactsEmail(RDContactsResource):
"""
Returns data about a specific Contact per E-mail.
ref: https://developers.rdstation.com/en/reference/contacts
"""
path = "/".join((RDContactsResource.path, "plataform", "contacts"))
def __call__(self, email, **kwargs):
"""
:uuid : type: string : The unique uuid associated to each RD Station Contact.
:param kwargs: type: dict args
:return: json response
{
"name": "RD Station Developer",
"email": "contact@example.com",
"job_title": "Developer",
"bio": "This documentation explains the RD Station API.",
"website": "https://developers.rdstation.com/",
"linkedin": "rd_station",
"personal_phone": "+55 48 3037-3600",
"city": "Florianópolis",
"state": "SC",
"country": "Brasil",
"tags": ["developer", "rdstation", "api"],
"extra_emails": ["contact2@example.com"],
"cf_custom_field_2": "custom field value2",
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": "granted"
}
]
}
"""
# set email
RDContactsEmail.url = "/".join((RDContactsEmail.path, f'email:{email}'))
return self._get(self, **kwargs)
def _get(self, **kwargs):
return self.send_response("GET", **kwargs)
class RDUpdateContactPerUUID(RDContactsResource):
"""
Updates the properties of a Contact per UIID.
ref: https://developers.rdstation.com/en/reference/contacts
"""
path = "/".join((RDContactsResource.path, "plataform", "contacts"))
def __call__(self, uuid, body, **kwargs):
"""
:uuid : type: string : The unique uuid associated to each RD Station Contact.
:body: type: dict : Request Body Default Parameters
:param kwargs: type: dict args
:return: json response
{
"name": "RD Station Developer",
"email": "contact@example.com",
"job_title": "Developer",
"bio": "This documentation explains the RD Station API.",
"website": "https://developers.rdstation.com/",
"linkedin": "rd_station",
"personal_phone": "+55 48 3037-3600",
"city": "Florianópolis",
"state": "SC",
"country": "Brasil",
"tags": ["developer", "rdstation", "api"],
"extra_emails": ["contact2@example.com"],
"cf_custom_field_2": "custom field value2",
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": "granted"
}
]
}
"""
# set email
RDUpdateContactPerUUID.path = "/".join((RDUpdateContactPerUUID.path, uuid))
return self._patch(self, **kwargs)
def _patch(self, **kwargs):
return self.send_response("PATCH", **kwargs)
class RDUpsertContactIndentifier(RDContactsResource):
"""
Updates the properties of a Contact per UIID.
ref: https://developers.rdstation.com/en/reference/contacts
"""
path = "/".join((RDContactsResource.path, "plataform", "contacts"))
def __call__(self, identifier, value, **kwargs):
"""
:identifier : type: string : The api_identifier of the Contact Field that uniquely identifies the Lead.
Currently only email or uuid are supported.
:value: type: string : The value for the given identifier
e.g. contact@example.org or 5408c5a3-4711-4f2e-8d0b-13407a3e30f3.
:param kwargs: type: dict args
:return: json response
{
"name": "RD Station Developer",
"email": "contact@example.com",
"job_title": "Developer",
"bio": "This documentation explains the RD Station API.",
"website": "https://developers.rdstation.com/",
"linkedin": "rd_station",
"personal_phone": "+55 48 3037-3600",
"city": "Florianópolis",
"state": "SC",
"country": "Brasil",
"tags": ["developer", "rdstation", "api"],
"extra_emails": ["contact2@example.com"],
"cf_custom_field_2": "custom field value2",
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": "granted"
}
]
}
"""
# set email
RDUpsertContactIndentifier.path = "/".join((RDUpsertContactIndentifier.path, f"{identifier}:{value}"))
return self._pach(self, **kwargs)
def _patch(self, **kwargs):
return self.send_response("PATCH", **kwargs)
# end-of-file | 28.842857 | 105 | 0.65511 | 678 | 6,057 | 5.744838 | 0.233038 | 0.039281 | 0.061617 | 0.06932 | 0.730167 | 0.730167 | 0.730167 | 0.730167 | 0.690372 | 0.676765 | 0 | 0.016832 | 0.185901 | 6,057 | 210 | 106 | 28.842857 | 0.773068 | 0.676903 | 0 | 0.378378 | 0 | 0 | 0.077457 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.27027 | false | 0.027027 | 0.054054 | 0.108108 | 0.810811 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 7 |
9a1848681730f9011d128530612873f3390fbb57 | 52,982 | py | Python | datasets/h36m.py | zengwang430521/Deformable-DETR | 311842a97e3cc82a7674ce77c141a0618f62197f | [
"Apache-2.0"
] | null | null | null | datasets/h36m.py | zengwang430521/Deformable-DETR | 311842a97e3cc82a7674ce77c141a0618f62197f | [
"Apache-2.0"
] | null | null | null | datasets/h36m.py | zengwang430521/Deformable-DETR | 311842a97e3cc82a7674ce77c141a0618f62197f | [
"Apache-2.0"
] | null | null | null | import os.path as osp
import mmcv
import numpy as np
from mmcv.parallel import DataContainer as DC
from torch.utils.data import Dataset
from .transforms import (ImageTransform, BboxTransform, MaskTransform,
SegMapTransform, Numpy2Tensor)
from .utils import to_tensor, random_scale, flip_kp, flip_pose, rot_aa
from .extra_aug import ExtraAugmentation
from .custom import CustomDataset
import os.path as osp
import tensorboardX
import math
import json
import pickle
import matplotlib.pyplot as plt
from mmdetection.mmdet.models.utils.smpl_utils import batch_rodrigues
import random
import cv2
from copy import deepcopy
import scipy
import scipy.misc
# import seaborn as sns
import torch
# import png
denormalize = lambda x: x * np.array([0.229, 0.224, 0.225])[None, None, :] + np.array([0.485, 0.456, 0.406])[None, None,
:]
import pycocotools.mask as mask_util
def rot2DPts(x, y, rotMat):
new_x = rotMat[0, 0] * x + rotMat[0, 1] * y + rotMat[0, 2]
new_y = rotMat[1, 0] * x + rotMat[1, 1] * y + rotMat[1, 2]
return new_x, new_y
class H36MDataset(Dataset):
"""Custom dataset for detection.
Annotation format:
[
{
'filename': 'a.jpg',
'width': 1280,
'height': 720,
'ann': {
'bboxes': <np.ndarray> (n, 4),
'labels': <np.ndarray> (n, ),
'bboxes_ignore': <np.ndarray> (k, 4),
'labels_ignore': <np.ndarray> (k, 4) (optional field)
}
},
...
]
The `ann` field is optional for testing.
"""
# CLASSES = None
CLASSES = ('Human',)
def __init__(self,
ann_file,
img_prefix,
img_scale,
img_norm_cfg,
multiscale_mode='value',
size_divisor=None,
proposal_file=None,
num_max_proposals=1000,
flip_ratio=0,
with_mask=True,
with_crowd=True,
with_label=True,
with_semantic_seg=False,
seg_prefix=None,
seg_scale_factor=1,
extra_aug=None,
resize_keep_ratio=True,
test_mode=False,
with_shape=True,
with_kpts3d=True,
with_kpts2d=True,
with_pose=True,
with_trans=True,
max_samples=-1, # Commonly used in validating
noise_factor=0.4,
square_bbox=True,
rot_factor=0,
sample_weight=1,
with_dp=False,
mosh_path=None,
ignore_3d=False,
ignore_smpl=False,
with_nr=False,
sample_by_persons=False,
use_poly=False,
**kwargs,
):
# prefix of images path
self.img_prefix = img_prefix
# load annotations (and proposals)
self.img_infos = self.load_annotations(ann_file)
self.max_samples = max_samples
if proposal_file is not None:
self.proposals = self.load_proposals(proposal_file)
else:
self.proposals = None
# filter images with no annotation during training
if not test_mode and False:
valid_inds = self._filter_imgs()
self.img_infos = [self.img_infos[i] for i in valid_inds]
if self.proposals is not None:
self.proposals = [self.proposals[i] for i in valid_inds]
# Select a subset for quick validation
if self.max_samples > 0:
self.img_infos = random.sample(self.img_infos, max_samples)
# self.img_infos = self.img_infos[:max_samples]
# (long_edge, short_edge) or [(long1, short1), (long2, short2), ...]
self.img_scales = img_scale if isinstance(img_scale,
list) else [img_scale]
assert mmcv.is_list_of(self.img_scales, tuple)
# normalization configs
self.img_norm_cfg = img_norm_cfg
# multi-scale mode (only applicable for multi-scale training)
self.multiscale_mode = multiscale_mode
assert multiscale_mode in ['value', 'range']
# max proposals per image
self.num_max_proposals = num_max_proposals
# flip ratio
self.flip_ratio = flip_ratio
assert flip_ratio >= 0 and flip_ratio <= 1
# padding border to ensure the image size can be divided by
# size_divisor (used for FPN)
self.size_divisor = size_divisor
# with mask or not (reserved field, takes no effect)
self.with_mask = with_mask
# some datasets provide bbox annotations as ignore/crowd/difficult,
# if `with_crowd` is True, then these info is returned.
self.with_crowd = with_crowd
# with label is False for RPN
self.with_label = with_label
# with semantic segmentation (stuff) annotation or not
self.with_seg = with_semantic_seg
# prefix of semantic segmentation map path
self.seg_prefix = seg_prefix
# rescale factor for segmentation maps
self.seg_scale_factor = seg_scale_factor
# in test mode or not
self.test_mode = test_mode
# For dataset with SMPL shape parameters
self.with_shape = with_shape
# For dataset with joints rotation matrix in SMPL model
self.with_kpts3d = with_kpts3d
# For dataset with 2D pose
self.with_kpts2d = with_kpts2d
# For dataset with camera parameters in SMPL model
self.with_trans = with_trans
# For pose in axis angle of the joints
self.with_pose = with_pose
# Densepose annotations
self.with_dp = with_dp
# noise factor for color jittering
self.noise_factor = noise_factor
# Whether to adjust bbox to square manually..
self.square_bbox = square_bbox
# Rotation facotr
self.rot_factor = rot_factor
# Mosh dataset for generator
self.mosh_path = None # mosh_path
# set group flag for the sampler
if not self.test_mode and False:
self._set_group_flag()
# transforms
self.img_transform = ImageTransform(
size_divisor=self.size_divisor, **self.img_norm_cfg)
self.bbox_transform = BboxTransform()
self.mask_transform = MaskTransform()
self.seg_transform = SegMapTransform(self.size_divisor)
self.numpy2tensor = Numpy2Tensor()
# if use extra augmentation
if extra_aug is not None:
self.extra_aug = ExtraAugmentation(**extra_aug)
else:
self.extra_aug = None
# image rescale if keep ratio
self.resize_keep_ratio = resize_keep_ratio
self.sample_weight = sample_weight
if sample_by_persons:
persons_cnt = np.zeros(len(self.img_infos))
for i in range(len(self.img_infos)):
persons_cnt[i] = self.get_ann_info(i)['kpts2d'].shape[0]
self.density = sample_weight * persons_cnt / persons_cnt.sum()
else:
self.density = sample_weight * np.ones(len(self.img_infos)) / len(self.img_infos)
self.ignore_3d = ignore_3d
self.ignore_smpl = ignore_smpl
self.with_nr = with_nr
self.use_poly = use_poly
if self.mosh_path:
mosh = np.load(mosh_path)
self.mosh_shape = mosh['shape'].copy()
self.mosh_pose = mosh['pose'].copy()
self.mosh_sample_list = range(self.mosh_shape.shape[0])
def __len__(self):
return len(self.img_infos)
def load_annotations(self, ann_file):
"""
filename:
height: 1000
width: commonly 1002 in h36m
:param ann_file:
:return:
"""
with open(ann_file, 'rb') as f:
raw_infos = pickle.load(f)
return raw_infos
def load_proposals(self, proposal_file):
return mmcv.load(proposal_file)
def get_ann_info(self, idx):
"""
:param idx:
:return:A dict of the following iterms:
bboxes: [x1, y1, x2, y2]
labels: number
kpts3d: (24, 4)
kpts2d: (24, 3)
pose: (72,)
shape: (10,)
cam: (3,) (The trans in SMPL model)
"""
# Visualization needed
raw_info = deepcopy(self.img_infos[idx])
bbox = raw_info['bbox']
if self.square_bbox:
center = np.array([int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)])
bbox_size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
half_size = int(math.floor(bbox_size / 2))
square_bbox = np.array(
[center[0] - half_size, center[1] - half_size, center[0] + half_size, center[1] + half_size])
else:
square_bbox = np.array(bbox)
# Here comes a problem, what if the bbox overflows on the corner?
# They will be args passed to `model.train_forward` if we overwrite `CustomDataset`.
return {'bboxes': square_bbox.reshape(1, -1).astype(np.float32), # (1,4)
# There will be only one person here.
'labels': np.array([1]),
'kpts3d': raw_info['S'][np.newaxis].astype(np.float32), # (1, 24,4) extra chanel for visibility
'kpts2d': raw_info['part'][np.newaxis].astype(np.float32), # (1, 24,3) extra chanel for visibility
'pose': raw_info['pose'].reshape(-1, 3)[np.newaxis].astype(np.float32), # (1, 24, 3)
'shape': raw_info['shape'][np.newaxis].astype(np.float32), # (1,10)
'trans': raw_info['trans'][np.newaxis].astype(np.float32), # (1, 3)
'has_smpl': np.array([1])
} # I think `1` represents the first class
def _filter_imgs(self, min_size=32):
"""Filter images too small."""
valid_inds = []
for i, img_info in enumerate(self.img_infos):
if min(img_info['width'], img_info['height']) >= min_size:
valid_inds.append(i)
return valid_inds
def _set_group_flag(self):
"""Set flag according to image aspect ratio.
Images with aspect ratio greater than 1 will be set as group 1,
otherwise group 0.
"""
self.flag = np.zeros(len(self), dtype=np.uint8)
for i in range(len(self)):
img_info = self.img_infos[i]
if img_info['width'] / img_info['height'] > 1:
self.flag[i] = 1
def _rand_another(self, idx):
pool = np.where(self.flag == self.flag[idx])[0]
return np.random.choice(pool)
def __getitem__(self, idx):
# if self.test_mode:
# return self.prepare_test_img(idx)
while True:
data = self.prepare_train_img(idx)
if data is None:
idx = self._rand_another(idx)
continue
return data
@staticmethod
def val(runner, dataloader, **kwargs):
from IPython import embed
embed()
pass
@staticmethod
def annToRLE(ann):
h, w = ann['height'], ann['width']
segm = ann['segmentation']
if type(segm) == list:
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = mask_util.frPyObjects(segm, h, w)
rle = mask_util.merge(rles)
elif type(segm['counts']) == list:
# uncompressed RLE
rle = mask_util.frPyObjects(segm, h, w)
else:
# rle
rle = ann['segmentation']
return rle
def prepare_train_img(self, idx):
img_info = deepcopy(self.img_infos[idx])
# load image
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
img_info['height'], img_info['width'] = img.shape[:2]
raw_shape = img.shape
# Color jittering:
pn = np.random.uniform(1 - self.noise_factor, 1 + self.noise_factor, 3)
img[:, :, 0] = np.minimum(255.0, np.maximum(0.0, img[:, :, 0] * pn[0]))
img[:, :, 1] = np.minimum(255.0, np.maximum(0.0, img[:, :, 1] * pn[1]))
img[:, :, 2] = np.minimum(255.0, np.maximum(0.0, img[:, :, 2] * pn[2]))
# load proposals if necessary
if self.proposals is not None:
proposals = self.proposals[idx][:self.num_max_proposals]
# no proposals are just ignored, but they can be used for
# training in concept.
if len(proposals) == 0:
return None
if not (proposals.shape[1] == 4 or proposals.shape[1] == 5):
raise AssertionError(
'proposals should have shapes (n, 4) or (n, 5), '
'but found {}'.format(proposals.shape))
if proposals.shape[1] == 5:
scores = proposals[:, 4, None]
proposals = proposals[:, :4]
else:
scores = None
ann = self.get_ann_info(idx)
if self.ignore_3d:
ann['kpts3d'] = np.zeros_like(ann['kpts3d'])
if self.ignore_smpl:
ann['has_smpl'] = np.zeros_like(ann['has_smpl'])
gt_bboxes = ann['bboxes']
gt_labels = ann['labels']
if self.with_crowd:
gt_bboxes_ignore = ann['bboxes_ignore']
# skip the image if there is no valid gt bbox
if len(gt_bboxes) == 0:
return None
# extra augmentation
if self.extra_aug is not None:
img, gt_bboxes, gt_labels = self.extra_aug(img, gt_bboxes,
gt_labels)
# apply transforms
flip = True if np.random.rand() < self.flip_ratio else False
# randomly sample a scale
img_scale = random_scale(self.img_scales, self.multiscale_mode)
img, img_shape, pad_shape, scale_factor = self.img_transform(img, img_scale, flip,
keep_ratio=self.resize_keep_ratio)
# Force padding for the issue of multi-GPU training
padded_img = np.zeros((img.shape[0], img_scale[1], img_scale[0]), dtype=img.dtype)
padded_img[:, :img.shape[-2], :img.shape[-1]] = img
img = padded_img
if self.with_nr:
padded_scene = np.zeros((img.shape[-2], img.shape[-1]), dtype=np.uint8)
if self.with_nr:
has_mask = True
# if 'dp_mask_path' in ann:
# raw_mask = cv2.imread(osp.join(self.img_prefix, ann['dp_mask_path']), cv2.IMREAD_UNCHANGED)
# elif 'segmentation' in ann and self.use_poly:
if 'segmentation' in ann and self.use_poly:
assert 'COCO' in ann['filename'], "Only support coco segmentation now"
raw_mask = np.zeros((ann['height'], ann['width']), dtype=np.uint8)
for i, seg in enumerate(ann['segmentation']):
ori_mask = mask_util.decode(
self.annToRLE({'width': ann['width'], 'height': ann['height'], 'segmentation': seg}))
raw_mask[ori_mask > 0] = i + 1
else:
has_mask = False
padded_scene = np.zeros((img.shape[-2], img.shape[-1]), dtype=np.uint8)
if has_mask:
target_shape = int(np.round(raw_shape[1] * scale_factor)), int(np.round(raw_shape[0] * scale_factor))
resized_mask = cv2.resize(raw_mask, target_shape, interpolation=cv2.INTER_NEAREST)
if flip:
resized_mask = np.flip(resized_mask, axis=1)
padded_scene[:resized_mask.shape[-2], :resized_mask.shape[-1]] = resized_mask
if self.with_seg:
gt_seg = mmcv.imread(
osp.join(self.seg_prefix, img_info['file_name'].replace(
'jpg', 'png')),
flag='unchanged')
gt_seg = self.seg_transform(gt_seg.squeeze(), img_scale, flip)
gt_seg = mmcv.imrescale(
gt_seg, self.seg_scale_factor, interpolation='nearest')
gt_seg = gt_seg[None, ...]
if self.proposals is not None:
proposals = self.bbox_transform(proposals, img_shape, scale_factor,
flip)
proposals = np.hstack(
[proposals, scores]) if scores is not None else proposals
gt_bboxes = self.bbox_transform(gt_bboxes, img_shape, scale_factor,
flip)
if self.with_crowd:
gt_bboxes_ignore = self.bbox_transform(gt_bboxes_ignore, img_shape,
scale_factor, flip)
if self.with_mask:
gt_masks = self.mask_transform(ann['masks'], pad_shape,
scale_factor, flip)
if self.with_shape:
gt_shapes = ann['shape']
if self.with_kpts2d:
gt_kpts2d = ann['kpts2d']
# Rescale the 2D keypoints now.
s_kpts2d = np.zeros_like(gt_kpts2d)
s_kpts2d[..., -1] = gt_kpts2d[..., -1]
s_kpts2d[..., :-1] = gt_kpts2d[..., :-1] * scale_factor
gt_kpts2d = s_kpts2d
if flip:
for i, kp in enumerate(gt_kpts2d):
gt_kpts2d[i] = flip_kp(kp, img_shape[1]) # img is (C, H, W)
# NOTE: I use the img_shape to avoid the influence of padding.
if self.with_kpts3d:
gt_kpts3d = ann['kpts3d']
if flip:
for i, kp in enumerate(gt_kpts3d):
gt_kpts3d[i] = flip_kp(kp, 0) # Not the image width as the pose is centered by hip.
if self.with_trans:
gt_trans = ann['trans']
if self.with_pose:
gt_poses = ann['pose']
if flip:
for i, ps in enumerate(gt_poses):
gt_poses[i] = flip_pose(ps.reshape(-1)).reshape(-1, 3)
if self.with_dp:
dp_num_pts = ann['dp_num_pts']
dp_x = ann['dp_x']
dp_y = ann['dp_y']
dp_U = ann['dp_U']
dp_V = ann['dp_V']
dp_I = ann['dp_I']
dp_x = img_shape[1] - dp_x
if not self.rot_factor == 0 and np.random.uniform() > 0.6:
rot = min(2 * self.rot_factor,
max(-2 * self.rot_factor, np.random.randn() * self.rot_factor))
rot_rad = -rot * np.pi / 180
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
rot_mat = np.eye(3)
rot_mat[0, :2] = [cs, -sn]
rot_mat[1, :2] = [sn, cs]
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
rot_mat[0, :2] = [cs, -sn]
rot_mat[1, :2] = [sn, cs]
# As we are rotating around the center.
t_mat = np.eye(3)
res = img.shape[1:]
t_mat[0, 2] = -res[1] / 2
t_mat[1, 2] = -res[0] / 2
t_inv = t_mat.copy()
t_inv[:2, 2] *= -1
rot_mat2d = t_inv @ rot_mat @ t_mat
# Things to change:
# kpts2d and 3d
# img and bbox
# On GraphCMR, they only rotate on the first 3 entries. So I think it apply to ours.
for i in range(gt_poses.shape[0]):
gt_poses[i, 0] = rot_aa(gt_poses[i, 0], rot)
gt_kpts3d[i, :, :-1] = (rot_mat @ gt_kpts3d[i, :, :-1].T).T
gt_kpts2d[i, :, :-1] = (rot_mat2d @ gt_kpts2d[i, :, ].T).T[..., :-1]
if sum(gt_kpts2d[i, ..., -1]) > 0:
x_min, y_min, _ = gt_kpts2d[i, gt_kpts2d[i, ..., -1] > 0].min(0)
x_max, y_max, _ = gt_kpts2d[i, gt_kpts2d[i, ..., -1] > 0].max(0)
else:
# If there is no valida ktps, we will use gt_bboxes instead.
x_min, y_min = rot2DPts(gt_bboxes[i][0], gt_bboxes[i][1], rot_mat2d)
x_max, y_max = rot2DPts(gt_bboxes[i][2], gt_bboxes[i][3], rot_mat2d)
bbox_w, bbox_h = x_max - x_min, y_max - y_min
bbox_center = (x_min + x_max) / 2, (y_min + y_max) / 2
_, im_w, im_h = img.shape
x_min, y_min = max(0, bbox_center[0] - bbox_w * 0.55), max(0, bbox_center[1] - bbox_h * 0.55)
x_max, y_max = min(im_w, bbox_center[0] + bbox_w * 0.55), min(im_h, bbox_center[1] + bbox_h * 0.55)
bbox = np.array([x_min, y_min, x_max, y_max], dtype=np.float32)
if self.square_bbox:
center = np.array([int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)])
bbox_size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
half_size = int(math.floor(bbox_size / 2))
square_bbox = np.array(
[center[0] - half_size, center[1] - half_size, center[0] + half_size, center[1] + half_size])
bbox = square_bbox.astype(np.float32).copy()
gt_bboxes[i] = bbox
if self.with_dp:
dp_x, dp_y = rot2DPts(dp_x, dp_y, rot_mat2d)
img_raw = cv2.cvtColor((denormalize(img.transpose([1, 2, 0])) * 255).astype(np.uint8).copy(),
cv2.COLOR_BGR2RGB)
img_rotated = scipy.misc.imrotate(img_raw, rot)
# For debug
img = mmcv.imnormalize(img_rotated, self.img_transform.mean, self.img_transform.std,
self.img_transform.to_rgb).transpose([2, 0, 1])
ori_shape = (img_info['height'], img_info['width'], 3)
img_meta = dict(
ori_shape=ori_shape,
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=flip,
idx=idx,
file_name=img_info['filename']
)
data = dict(
img=DC(to_tensor(img), stack=True),
img_meta=DC(img_meta, cpu_only=True),
gt_bboxes=DC(to_tensor(gt_bboxes)))
if self.proposals is not None:
data['proposals'] = DC(to_tensor(proposals))
if self.with_label:
data['gt_labels'] = DC(to_tensor(gt_labels))
if self.with_crowd:
data['gt_bboxes_ignore'] = DC(to_tensor(gt_bboxes_ignore))
if self.with_mask:
data['gt_masks'] = DC(gt_masks, cpu_only=True)
if self.with_seg:
data['gt_semantic_seg'] = DC(to_tensor(gt_seg), stack=True)
if self.with_pose:
data['gt_poses'] = DC(to_tensor(gt_poses))
if self.with_kpts2d:
# Filter out un-used kpts.
kpts_filter = gt_kpts2d[..., -1].sum(-1) < 8
if gt_kpts2d.shape[0] == 1:
gt_kpts2d[kpts_filter] = 0
data['gt_kpts2d'] = DC(to_tensor(gt_kpts2d))
if self.with_kpts3d:
data['gt_kpts3d'] = DC(to_tensor(gt_kpts3d))
if self.with_shape:
data['gt_shapes'] = DC(to_tensor(gt_shapes))
if self.with_trans:
data['gt_trans'] = DC(to_tensor(gt_trans))
if self.with_dp:
data['dp_x'] = DC(to_tensor(dp_x))
data['dp_y'] = DC(to_tensor(dp_y))
data['dp_U'] = DC(to_tensor(dp_U))
data['dp_V'] = DC(to_tensor(dp_V))
data['dp_I'] = DC(to_tensor(dp_I))
data['dp_num_pts'] = DC(to_tensor(dp_num_pts))
# if self.with_shape = DC(to_tensor(gt_shape))
if self.with_nr:
data['scene'] = DC(to_tensor(padded_scene))
data['has_smpl'] = DC(to_tensor(ann['has_smpl']))
if self.mosh_path:
sampled_idxs = np.array(random.sample(self.mosh_sample_list, 36))
mosh_pose = torch.tensor(deepcopy(self.mosh_pose[sampled_idxs].astype(np.float32)))
mosh_shape = torch.tensor(deepcopy(self.mosh_shape[sampled_idxs].astype(np.float32)))
mosh_bs = mosh_shape.shape[0]
mosh_pose_shape = torch.cat([batch_rodrigues(mosh_pose.view(-1, 3)).view(mosh_bs, -1), mosh_shape], dim=1)
data['mosh'] = DC(mosh_pose_shape)
return data
def prepare_test_img(self, idx):
"""Prepare an image for testing (multi-scale and flipping)"""
img_info = self.img_infos[idx]
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
if self.proposals is not None:
proposal = self.proposals[idx][:self.num_max_proposals]
if not (proposal.shape[1] == 4 or proposal.shape[1] == 5):
raise AssertionError(
'proposals should have shapes (n, 4) or (n, 5), '
'but found {}'.format(proposal.shape))
else:
proposal = None
def prepare_single(img, scale, flip, proposal=None):
_img, img_shape, pad_shape, scale_factor = self.img_transform(
img, scale, flip, keep_ratio=self.resize_keep_ratio)
_img = to_tensor(_img)
_img_meta = dict(
ori_shape=(img_info['height'], img_info['width'], 3),
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=flip)
if proposal is not None:
if proposal.shape[1] == 5:
score = proposal[:, 4, None]
proposal = proposal[:, :4]
else:
score = None
_proposal = self.bbox_transform(proposal, img_shape,
scale_factor, flip)
_proposal = np.hstack(
[_proposal, score]) if score is not None else _proposal
_proposal = to_tensor(_proposal)
else:
_proposal = None
return _img, _img_meta, _proposal
imgs = []
img_metas = []
proposals = []
for scale in self.img_scales:
_img, _img_meta, _proposal = prepare_single(
img, scale, False, proposal)
imgs.append(_img)
img_metas.append(DC(_img_meta, cpu_only=True))
proposals.append(_proposal)
if self.flip_ratio > 0:
_img, _img_meta, _proposal = prepare_single(
img, scale, True, proposal)
imgs.append(_img)
img_metas.append(DC(_img_meta, cpu_only=True))
proposals.append(_proposal)
data = dict(img=imgs, img_meta=img_metas)
if self.proposals is not None:
data['proposals'] = proposals
return data
class MyH36MDataset(Dataset):
"""Custom dataset for detection.
Annotation format:
[
{
'filename': 'a.jpg',
'width': 1280,
'height': 720,
'ann': {
'bboxes': <np.ndarray> (n, 4),
'labels': <np.ndarray> (n, ),
'bboxes_ignore': <np.ndarray> (k, 4),
'labels_ignore': <np.ndarray> (k, 4) (optional field)
}
},
...
]
The `ann` field is optional for testing.
"""
# CLASSES = None
CLASSES = ('Human',)
def __init__(self,
ann_file,
img_prefix,
img_scale,
img_norm_cfg,
multiscale_mode='value',
size_divisor=None,
proposal_file=None,
num_max_proposals=1000,
flip_ratio=0,
with_mask=True,
with_crowd=True,
with_label=True,
with_semantic_seg=False,
seg_prefix=None,
seg_scale_factor=1,
extra_aug=None,
resize_keep_ratio=True,
test_mode=False,
with_shape=True,
with_kpts3d=True,
with_kpts2d=True,
with_pose=True,
with_trans=True,
max_samples=-1, # Commonly used in validating
noise_factor=0.4,
square_bbox=True,
rot_factor=0,
sample_weight=1,
with_dp=False,
mosh_path=None,
ignore_3d=False,
ignore_smpl=False,
with_nr=False,
sample_by_persons=False,
use_poly=False,
**kwargs,
):
# prefix of images path
self.img_prefix = img_prefix
# load annotations (and proposals)
self.img_infos = self.load_annotations(ann_file)
self.max_samples = max_samples
if proposal_file is not None:
self.proposals = self.load_proposals(proposal_file)
else:
self.proposals = None
# filter images with no annotation during training
if not test_mode and False:
valid_inds = self._filter_imgs()
self.img_infos = [self.img_infos[i] for i in valid_inds]
if self.proposals is not None:
self.proposals = [self.proposals[i] for i in valid_inds]
# Select a subset for quick validation
if self.max_samples > 0:
self.img_infos = random.sample(self.img_infos, max_samples)
# self.img_infos = self.img_infos[:max_samples]
# (long_edge, short_edge) or [(long1, short1), (long2, short2), ...]
self.img_scales = img_scale if isinstance(img_scale,
list) else [img_scale]
assert mmcv.is_list_of(self.img_scales, tuple)
# normalization configs
self.img_norm_cfg = img_norm_cfg
# multi-scale mode (only applicable for multi-scale training)
self.multiscale_mode = multiscale_mode
assert multiscale_mode in ['value', 'range']
# max proposals per image
self.num_max_proposals = num_max_proposals
# flip ratio
self.flip_ratio = flip_ratio
assert flip_ratio >= 0 and flip_ratio <= 1
# padding border to ensure the image size can be divided by
# size_divisor (used for FPN)
self.size_divisor = size_divisor
# with mask or not (reserved field, takes no effect)
self.with_mask = with_mask
# some datasets provide bbox annotations as ignore/crowd/difficult,
# if `with_crowd` is True, then these info is returned.
self.with_crowd = with_crowd
# with label is False for RPN
self.with_label = with_label
# with semantic segmentation (stuff) annotation or not
self.with_seg = with_semantic_seg
# prefix of semantic segmentation map path
self.seg_prefix = seg_prefix
# rescale factor for segmentation maps
self.seg_scale_factor = seg_scale_factor
# in test mode or not
self.test_mode = test_mode
# For dataset with SMPL shape parameters
self.with_shape = with_shape
# For dataset with joints rotation matrix in SMPL model
self.with_kpts3d = with_kpts3d
# For dataset with 2D pose
self.with_kpts2d = with_kpts2d
# For dataset with camera parameters in SMPL model
self.with_trans = with_trans
# For pose in axis angle of the joints
self.with_pose = with_pose
# Densepose annotations
self.with_dp = with_dp
# noise factor for color jittering
self.noise_factor = noise_factor
# Whether to adjust bbox to square manually..
self.square_bbox = square_bbox
# Rotation facotr
self.rot_factor = rot_factor
# Mosh dataset for generator
self.mosh_path = None # mosh_path
# set group flag for the sampler
if not self.test_mode and False:
self._set_group_flag()
# transforms
self.img_transform = ImageTransform(
size_divisor=self.size_divisor, **self.img_norm_cfg)
self.bbox_transform = BboxTransform()
self.mask_transform = MaskTransform()
self.seg_transform = SegMapTransform(self.size_divisor)
self.numpy2tensor = Numpy2Tensor()
# if use extra augmentation
if extra_aug is not None:
self.extra_aug = ExtraAugmentation(**extra_aug)
else:
self.extra_aug = None
# image rescale if keep ratio
self.resize_keep_ratio = resize_keep_ratio
self.sample_weight = sample_weight
if sample_by_persons:
persons_cnt = np.zeros(len(self.img_infos))
for i in range(len(self.img_infos)):
persons_cnt[i] = self.get_ann_info(i)['kpts2d'].shape[0]
self.density = sample_weight * persons_cnt / persons_cnt.sum()
else:
self.density = sample_weight * np.ones(len(self.img_infos)) / len(self.img_infos)
self.ignore_3d = ignore_3d
self.ignore_smpl = ignore_smpl
self.with_nr = with_nr
self.use_poly = use_poly
if self.mosh_path:
mosh = np.load(mosh_path)
self.mosh_shape = mosh['shape'].copy()
self.mosh_pose = mosh['pose'].copy()
self.mosh_sample_list = range(self.mosh_shape.shape[0])
def __len__(self):
return len(self.img_infos)
def load_annotations(self, ann_file):
"""
filename:
height: 1000
width: commonly 1002 in h36m
:param ann_file:
:return:
"""
with open(ann_file, 'rb') as f:
raw_infos = pickle.load(f)
return raw_infos
def load_proposals(self, proposal_file):
return mmcv.load(proposal_file)
def get_ann_info(self, idx):
"""
:param idx:
:return:A dict of the following iterms:
bboxes: [x1, y1, x2, y2]
labels: number
kpts3d: (24, 4)
kpts2d: (24, 3)
pose: (72,)
shape: (10,)
cam: (3,) (The trans in SMPL model)
"""
# Visualization needed
raw_info = deepcopy(self.img_infos[idx])
bbox = raw_info['bbox']
if self.square_bbox:
center = np.array([int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)])
bbox_size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
half_size = int(math.floor(bbox_size / 2))
square_bbox = np.array(
[center[0] - half_size, center[1] - half_size, center[0] + half_size, center[1] + half_size])
else:
square_bbox = np.array(bbox)
# Here comes a problem, what if the bbox overflows on the corner?
# They will be args passed to `model.train_forward` if we overwrite `CustomDataset`.
return {'bboxes': square_bbox.reshape(1, -1).astype(np.float32), # (1,4)
# There will be only one person here.
'labels': np.array([1]),
'kpts3d': raw_info['S'][np.newaxis].astype(np.float32), # (1, 24,4) extra chanel for visibility
'kpts2d': raw_info['part'][np.newaxis].astype(np.float32), # (1, 24,3) extra chanel for visibility
'pose': raw_info['pose'].reshape(-1, 3)[np.newaxis].astype(np.float32), # (1, 24, 3)
'shape': raw_info['shape'][np.newaxis].astype(np.float32), # (1,10)
'trans': raw_info['trans'][np.newaxis].astype(np.float32), # (1, 3)
'has_smpl': np.array([1])
} # I think `1` represents the first class
def _filter_imgs(self, min_size=32):
"""Filter images too small."""
valid_inds = []
for i, img_info in enumerate(self.img_infos):
if min(img_info['width'], img_info['height']) >= min_size:
valid_inds.append(i)
return valid_inds
def _set_group_flag(self):
"""Set flag according to image aspect ratio.
Images with aspect ratio greater than 1 will be set as group 1,
otherwise group 0.
"""
self.flag = np.zeros(len(self), dtype=np.uint8)
for i in range(len(self)):
img_info = self.img_infos[i]
if img_info['width'] / img_info['height'] > 1:
self.flag[i] = 1
def _rand_another(self, idx):
pool = np.where(self.flag == self.flag[idx])[0]
return np.random.choice(pool)
def __getitem__(self, idx):
# if self.test_mode:
# return self.prepare_test_img(idx)
while True:
data = self.prepare_train_img(idx)
if data is None:
idx = self._rand_another(idx)
continue
return data
@staticmethod
def val(runner, dataloader, **kwargs):
from IPython import embed
embed()
pass
@staticmethod
def annToRLE(ann):
h, w = ann['height'], ann['width']
segm = ann['segmentation']
if type(segm) == list:
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = mask_util.frPyObjects(segm, h, w)
rle = mask_util.merge(rles)
elif type(segm['counts']) == list:
# uncompressed RLE
rle = mask_util.frPyObjects(segm, h, w)
else:
# rle
rle = ann['segmentation']
return rle
def prepare_train_img(self, idx):
img_info = deepcopy(self.img_infos[idx])
# load image
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
img_info['height'], img_info['width'] = img.shape[:2]
raw_shape = img.shape
# Color jittering:
pn = np.random.uniform(1 - self.noise_factor, 1 + self.noise_factor, 3)
img[:, :, 0] = np.minimum(255.0, np.maximum(0.0, img[:, :, 0] * pn[0]))
img[:, :, 1] = np.minimum(255.0, np.maximum(0.0, img[:, :, 1] * pn[1]))
img[:, :, 2] = np.minimum(255.0, np.maximum(0.0, img[:, :, 2] * pn[2]))
# load proposals if necessary
if self.proposals is not None:
proposals = self.proposals[idx][:self.num_max_proposals]
# no proposals are just ignored, but they can be used for
# training in concept.
if len(proposals) == 0:
return None
if not (proposals.shape[1] == 4 or proposals.shape[1] == 5):
raise AssertionError(
'proposals should have shapes (n, 4) or (n, 5), '
'but found {}'.format(proposals.shape))
if proposals.shape[1] == 5:
scores = proposals[:, 4, None]
proposals = proposals[:, :4]
else:
scores = None
ann = self.get_ann_info(idx)
if self.ignore_3d:
ann['kpts3d'] = np.zeros_like(ann['kpts3d'])
if self.ignore_smpl:
ann['has_smpl'] = np.zeros_like(ann['has_smpl'])
gt_bboxes = ann['bboxes']
gt_labels = ann['labels']
if self.with_crowd:
gt_bboxes_ignore = ann['bboxes_ignore']
# skip the image if there is no valid gt bbox
if len(gt_bboxes) == 0:
return None
# extra augmentation
if self.extra_aug is not None:
img, gt_bboxes, gt_labels = self.extra_aug(img, gt_bboxes,
gt_labels)
# apply transforms
flip = True if np.random.rand() < self.flip_ratio else False
# randomly sample a scale
img_scale = random_scale(self.img_scales, self.multiscale_mode)
img, img_shape, pad_shape, scale_factor = self.img_transform(img, img_scale, flip,
keep_ratio=self.resize_keep_ratio)
# Force padding for the issue of multi-GPU training
padded_img = np.zeros((img.shape[0], img_scale[1], img_scale[0]), dtype=img.dtype)
padded_img[:, :img.shape[-2], :img.shape[-1]] = img
img = padded_img
if self.with_nr:
padded_scene = np.zeros((img.shape[-2], img.shape[-1]), dtype=np.uint8)
if self.with_nr:
has_mask = True
# if 'dp_mask_path' in ann:
# raw_mask = cv2.imread(osp.join(self.img_prefix, ann['dp_mask_path']), cv2.IMREAD_UNCHANGED)
# elif 'segmentation' in ann and self.use_poly:
if 'segmentation' in ann and self.use_poly:
assert 'COCO' in ann['filename'], "Only support coco segmentation now"
raw_mask = np.zeros((ann['height'], ann['width']), dtype=np.uint8)
for i, seg in enumerate(ann['segmentation']):
ori_mask = mask_util.decode(
self.annToRLE({'width': ann['width'], 'height': ann['height'], 'segmentation': seg}))
raw_mask[ori_mask > 0] = i + 1
else:
has_mask = False
padded_scene = np.zeros((img.shape[-2], img.shape[-1]), dtype=np.uint8)
if has_mask:
target_shape = int(np.round(raw_shape[1] * scale_factor)), int(np.round(raw_shape[0] * scale_factor))
resized_mask = cv2.resize(raw_mask, target_shape, interpolation=cv2.INTER_NEAREST)
if flip:
resized_mask = np.flip(resized_mask, axis=1)
padded_scene[:resized_mask.shape[-2], :resized_mask.shape[-1]] = resized_mask
if self.with_seg:
gt_seg = mmcv.imread(
osp.join(self.seg_prefix, img_info['file_name'].replace(
'jpg', 'png')),
flag='unchanged')
gt_seg = self.seg_transform(gt_seg.squeeze(), img_scale, flip)
gt_seg = mmcv.imrescale(
gt_seg, self.seg_scale_factor, interpolation='nearest')
gt_seg = gt_seg[None, ...]
if self.proposals is not None:
proposals = self.bbox_transform(proposals, img_shape, scale_factor,
flip)
proposals = np.hstack(
[proposals, scores]) if scores is not None else proposals
gt_bboxes = self.bbox_transform(gt_bboxes, img_shape, scale_factor,
flip)
if self.with_crowd:
gt_bboxes_ignore = self.bbox_transform(gt_bboxes_ignore, img_shape,
scale_factor, flip)
if self.with_mask:
gt_masks = self.mask_transform(ann['masks'], pad_shape,
scale_factor, flip)
if self.with_shape:
gt_shapes = ann['shape']
if self.with_kpts2d:
gt_kpts2d = ann['kpts2d']
# Rescale the 2D keypoints now.
s_kpts2d = np.zeros_like(gt_kpts2d)
s_kpts2d[..., -1] = gt_kpts2d[..., -1]
s_kpts2d[..., :-1] = gt_kpts2d[..., :-1] * scale_factor
gt_kpts2d = s_kpts2d
if flip:
for i, kp in enumerate(gt_kpts2d):
gt_kpts2d[i] = flip_kp(kp, img_shape[1]) # img is (C, H, W)
# NOTE: I use the img_shape to avoid the influence of padding.
if self.with_kpts3d:
gt_kpts3d = ann['kpts3d']
if flip:
for i, kp in enumerate(gt_kpts3d):
gt_kpts3d[i] = flip_kp(kp, 0) # Not the image width as the pose is centered by hip.
if self.with_trans:
gt_trans = ann['trans']
if self.with_pose:
gt_poses = ann['pose']
if flip:
for i, ps in enumerate(gt_poses):
gt_poses[i] = flip_pose(ps.reshape(-1)).reshape(-1, 3)
if self.with_dp:
dp_num_pts = ann['dp_num_pts']
dp_x = ann['dp_x']
dp_y = ann['dp_y']
dp_U = ann['dp_U']
dp_V = ann['dp_V']
dp_I = ann['dp_I']
dp_x = img_shape[1] - dp_x
if not self.rot_factor == 0 and np.random.uniform() > 0.6:
rot = min(2 * self.rot_factor,
max(-2 * self.rot_factor, np.random.randn() * self.rot_factor))
rot_rad = -rot * np.pi / 180
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
rot_mat = np.eye(3)
rot_mat[0, :2] = [cs, -sn]
rot_mat[1, :2] = [sn, cs]
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
rot_mat[0, :2] = [cs, -sn]
rot_mat[1, :2] = [sn, cs]
# As we are rotating around the center.
t_mat = np.eye(3)
res = img.shape[1:]
t_mat[0, 2] = -res[1] / 2
t_mat[1, 2] = -res[0] / 2
t_inv = t_mat.copy()
t_inv[:2, 2] *= -1
rot_mat2d = t_inv @ rot_mat @ t_mat
# Things to change:
# kpts2d and 3d
# img and bbox
# On GraphCMR, they only rotate on the first 3 entries. So I think it apply to ours.
for i in range(gt_poses.shape[0]):
gt_poses[i, 0] = rot_aa(gt_poses[i, 0], rot)
gt_kpts3d[i, :, :-1] = (rot_mat @ gt_kpts3d[i, :, :-1].T).T
gt_kpts2d[i, :, :-1] = (rot_mat2d @ gt_kpts2d[i, :, ].T).T[..., :-1]
if sum(gt_kpts2d[i, ..., -1]) > 0:
x_min, y_min, _ = gt_kpts2d[i, gt_kpts2d[i, ..., -1] > 0].min(0)
x_max, y_max, _ = gt_kpts2d[i, gt_kpts2d[i, ..., -1] > 0].max(0)
else:
# If there is no valida ktps, we will use gt_bboxes instead.
x_min, y_min = rot2DPts(gt_bboxes[i][0], gt_bboxes[i][1], rot_mat2d)
x_max, y_max = rot2DPts(gt_bboxes[i][2], gt_bboxes[i][3], rot_mat2d)
bbox_w, bbox_h = x_max - x_min, y_max - y_min
bbox_center = (x_min + x_max) / 2, (y_min + y_max) / 2
_, im_w, im_h = img.shape
x_min, y_min = max(0, bbox_center[0] - bbox_w * 0.55), max(0, bbox_center[1] - bbox_h * 0.55)
x_max, y_max = min(im_w, bbox_center[0] + bbox_w * 0.55), min(im_h, bbox_center[1] + bbox_h * 0.55)
bbox = np.array([x_min, y_min, x_max, y_max], dtype=np.float32)
if self.square_bbox:
center = np.array([int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)])
bbox_size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
half_size = int(math.floor(bbox_size / 2))
square_bbox = np.array(
[center[0] - half_size, center[1] - half_size, center[0] + half_size, center[1] + half_size])
bbox = square_bbox.astype(np.float32).copy()
gt_bboxes[i] = bbox
if self.with_dp:
dp_x, dp_y = rot2DPts(dp_x, dp_y, rot_mat2d)
img_raw = cv2.cvtColor((denormalize(img.transpose([1, 2, 0])) * 255).astype(np.uint8).copy(),
cv2.COLOR_BGR2RGB)
img_rotated = scipy.misc.imrotate(img_raw, rot)
# For debug
img = mmcv.imnormalize(img_rotated, self.img_transform.mean, self.img_transform.std,
self.img_transform.to_rgb).transpose([2, 0, 1])
ori_shape = (img_info['height'], img_info['width'], 3)
img_meta = dict(
ori_shape=ori_shape,
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=flip,
idx=idx,
file_name=img_info['filename']
)
data = dict(
img=DC(to_tensor(img), stack=True),
img_meta=DC(img_meta, cpu_only=True),
gt_bboxes=DC(to_tensor(gt_bboxes)))
if self.proposals is not None:
data['proposals'] = DC(to_tensor(proposals))
if self.with_label:
data['gt_labels'] = DC(to_tensor(gt_labels))
if self.with_crowd:
data['gt_bboxes_ignore'] = DC(to_tensor(gt_bboxes_ignore))
if self.with_mask:
data['gt_masks'] = DC(gt_masks, cpu_only=True)
if self.with_seg:
data['gt_semantic_seg'] = DC(to_tensor(gt_seg), stack=True)
if self.with_pose:
data['gt_poses'] = DC(to_tensor(gt_poses))
if self.with_kpts2d:
# Filter out un-used kpts.
kpts_filter = gt_kpts2d[..., -1].sum(-1) < 8
if gt_kpts2d.shape[0] == 1:
gt_kpts2d[kpts_filter] = 0
data['gt_kpts2d'] = DC(to_tensor(gt_kpts2d))
if self.with_kpts3d:
data['gt_kpts3d'] = DC(to_tensor(gt_kpts3d))
if self.with_shape:
data['gt_shapes'] = DC(to_tensor(gt_shapes))
if self.with_trans:
data['gt_trans'] = DC(to_tensor(gt_trans))
if self.with_dp:
data['dp_x'] = DC(to_tensor(dp_x))
data['dp_y'] = DC(to_tensor(dp_y))
data['dp_U'] = DC(to_tensor(dp_U))
data['dp_V'] = DC(to_tensor(dp_V))
data['dp_I'] = DC(to_tensor(dp_I))
data['dp_num_pts'] = DC(to_tensor(dp_num_pts))
# if self.with_shape = DC(to_tensor(gt_shape))
if self.with_nr:
data['scene'] = DC(to_tensor(padded_scene))
data['has_smpl'] = DC(to_tensor(ann['has_smpl']))
if self.mosh_path:
sampled_idxs = np.array(random.sample(self.mosh_sample_list, 36))
mosh_pose = torch.tensor(deepcopy(self.mosh_pose[sampled_idxs].astype(np.float32)))
mosh_shape = torch.tensor(deepcopy(self.mosh_shape[sampled_idxs].astype(np.float32)))
mosh_bs = mosh_shape.shape[0]
mosh_pose_shape = torch.cat([batch_rodrigues(mosh_pose.view(-1, 3)).view(mosh_bs, -1), mosh_shape], dim=1)
data['mosh'] = DC(mosh_pose_shape)
return data
def prepare_test_img(self, idx):
"""Prepare an image for testing (multi-scale and flipping)"""
img_info = self.img_infos[idx]
img = mmcv.imread(osp.join(self.img_prefix, img_info['filename']))
if self.proposals is not None:
proposal = self.proposals[idx][:self.num_max_proposals]
if not (proposal.shape[1] == 4 or proposal.shape[1] == 5):
raise AssertionError(
'proposals should have shapes (n, 4) or (n, 5), '
'but found {}'.format(proposal.shape))
else:
proposal = None
def prepare_single(img, scale, flip, proposal=None):
_img, img_shape, pad_shape, scale_factor = self.img_transform(
img, scale, flip, keep_ratio=self.resize_keep_ratio)
_img = to_tensor(_img)
_img_meta = dict(
ori_shape=(img_info['height'], img_info['width'], 3),
img_shape=img_shape,
pad_shape=pad_shape,
scale_factor=scale_factor,
flip=flip)
if proposal is not None:
if proposal.shape[1] == 5:
score = proposal[:, 4, None]
proposal = proposal[:, :4]
else:
score = None
_proposal = self.bbox_transform(proposal, img_shape,
scale_factor, flip)
_proposal = np.hstack(
[_proposal, score]) if score is not None else _proposal
_proposal = to_tensor(_proposal)
else:
_proposal = None
return _img, _img_meta, _proposal
imgs = []
img_metas = []
proposals = []
for scale in self.img_scales:
_img, _img_meta, _proposal = prepare_single(
img, scale, False, proposal)
imgs.append(_img)
img_metas.append(DC(_img_meta, cpu_only=True))
proposals.append(_proposal)
if self.flip_ratio > 0:
_img, _img_meta, _proposal = prepare_single(
img, scale, True, proposal)
imgs.append(_img)
img_metas.append(DC(_img_meta, cpu_only=True))
proposals.append(_proposal)
data = dict(img=imgs, img_meta=img_metas)
if self.proposals is not None:
data['proposals'] = proposals
return data
| 41.135093 | 120 | 0.541373 | 6,789 | 52,982 | 4.006186 | 0.071439 | 0.01809 | 0.018384 | 0.008824 | 0.971983 | 0.971983 | 0.970292 | 0.970292 | 0.970292 | 0.970292 | 0 | 0.023954 | 0.348364 | 52,982 | 1,287 | 121 | 41.167055 | 0.763823 | 0.13916 | 0 | 0.963597 | 0 | 0 | 0.034183 | 0 | 0 | 0 | 0 | 0 | 0.012848 | 1 | 0.031049 | false | 0.002141 | 0.026767 | 0.004283 | 0.091006 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d04e710188bbdb302d7fcbc55f90d1173e709dc7 | 7,220 | py | Python | apicomponents/repository.py | tonnyhideyori/dependencytrack-pywrap | 58d4a8ac8862bbdb7007ab483f38f5871ab55c48 | [
"MIT"
] | null | null | null | apicomponents/repository.py | tonnyhideyori/dependencytrack-pywrap | 58d4a8ac8862bbdb7007ab483f38f5871ab55c48 | [
"MIT"
] | 5 | 2021-11-18T20:35:12.000Z | 2021-11-25T19:03:16.000Z | apicomponents/repository.py | tonnyhideyori/dependencytrack-pywrap | 58d4a8ac8862bbdb7007ab483f38f5871ab55c48 | [
"MIT"
] | 2 | 2021-11-15T19:58:15.000Z | 2021-11-23T12:55:04.000Z | import json
class DependencyTrackRepository(object):
def list_repository(self, pageSize=100):
"""Returns a list of all repositories
Args:
pageSize (int, optional): [description]. Defaults to 100.
Returns:
List: Returns a list of all repositories.
"""
respositorylist = list()
pageNumber = 1
response = self.session.get(self.apicall + f"/v1/repository", params={'pageSize': pageSize, 'pageNumber': pageNumber})
for repository in range(0, len(response.json())):
respositorylist.append(response.json()[repository-1])
while len(response.json()) == pageSize:
pageNumber += 1
response = self.session.get(self.apicall + f"/v1/repository", params={'pageSize': pageSize, 'pageNumber': pageNumber})
for repository in range(0, len(response.json())):
respositorylist.append(response.json()[repository-1])
if response.status_code == 200:
return respositorylist
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
def update_repository(self, uuid, identifier, type, url, resolutionOrder=0, enable=True, internal=True):
"""Update a specific repository
Args:
uuid ([type]): [description]
identifier (string): identity name of the repository
type (string): The type of repositories to add. eg MAVEN, NPM, GEM, PYPI, NUGET, HEX, COMPOSER, CARGO, GO_MODULES, UNSUPPORTED
url ([type]): [description]
resolutionOrder (int, optional): . Defaults to 0.
enable (bool, optional): . Defaults to True.
internal (bool, optional): . Defaults to True.
Returns:
dictionary : example Value {
"type": "MAVEN",
"identifier": "string",
"url": "string",
"resolutionOrder": 6,
"enabled": true,
"internal": true,
"uuid": "579720aa-e150-4b92-abff-2b6bb5dd7af9"
}
"""
data = {
"uuid": uuid,
"type": type,
"url": url,
"resolutionOder": resolutionOrder,
"enable": enable,
"internal": internal,
"identifier": identifier
}
response = self.session.post(self.apicall + f"/v1/repository",data=json.dumps(data))
if response.status_code == 200:
return ("Successful operation")
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
def create_repository(self, identifier, type, url, resolutionOrder=0, enable=True, internal=True):
""" Create a new repository
Args:
identifier (string): identity name of the repository
type (string): The type of repositories to add. eg MAVEN, NPM, GEM, PYPI, NUGET, HEX, COMPOSER, CARGO, GO_MODULES, UNSUPPORTED
url ([type]): [description]
resolutionOrder (int, optional): . Defaults to 0.
enable (bool, optional): . Defaults to True.
internal (bool, optional): . Defaults to True.
Returns:
dictionary : example Value {
"type": "MAVEN",
"identifier": "string",
"url": "string",
"resolutionOrder": 6,
"enabled": true,
"internal": true,
"uuid": "579720aa-e150-4b92-abff-2b6bb5dd7af9"
}
"""
data = {
"type": type,
"url": url,
"resolutionOder": resolutionOrder,
"enable": enable,
"internal": internal,
"identifier": identifier
}
response = self.session.put(self.apicall + f"/v1/repository", data=json.dumps(data))
if response.status_code == 201:
return ("Successful operation")
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
def get_latest_repository(self,purl):
"""Attempts to resolve the latest version of the component available in the configured repositories
Args:
purl (string): The Package URL for the component to query
Returns:
dictionary : example Value{
"repositoryType": "MAVEN",
"namespace": "string",
"name": "string",
"latestVersion": "string",
"published": "2021-12-02T16:50:56.704Z",
"lastCheck": "2021-12-02T16:50:56.704Z"
}
"""
response = self.session.get(self.apicall + f"/v1/repository/latest", params={'purl':purl})
if response.status_code==200:
return response.json()
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
def get_repositoryByType(self,type, pageSize=100):
"""
Returns repositories that support the specific type
Args:
type (string): The type of repositories to retrieve. eg MAVEN, NPM, GEM, PYPI, NUGET, HEX, COMPOSER, CARGO, GO_MODULES, UNSUPPORTED
pageSize (int, optional): [description]. Defaults to 100.
Returns:
List : list of repositories that support the specific type.
"""
respositorylist = list()
pageNumber = 1
response = self.session.get(self.apicall + f"/v1/repository/{type}", params={'pageSize': pageSize, 'pageNumber': pageNumber})
for repository in range(0, len(response.json())):
respositorylist.append(response.json()[repository-1])
while len(response.json()) == pageSize:
pageNumber += 1
response = self.session.get(self.apicall + f"/v1/repository/{type}", params={'pageSize': pageSize, 'pageNumber': pageNumber})
for repository in range(0, len(response.json())):
respositorylist.append(response.json()[repository-1])
if response.status_code == 200:
return respositorylist
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
def delete_repository(self, uuid):
"""Deletes a repository
Args:
uuid (string): the UUID of the repository to delete
"""
response = self.session.delete(self.apicall + f"/v1/repository/{uuid}")
if response.status_code >= 200 or response.status_code <= 299:
return ("Successful operation")
else:
return (f"{(response.content).decode('utf-8')}, {response.status_code}")
| 44.84472 | 145 | 0.527562 | 670 | 7,220 | 5.650746 | 0.18806 | 0.048072 | 0.061807 | 0.029583 | 0.811939 | 0.799525 | 0.745642 | 0.736926 | 0.736926 | 0.667195 | 0 | 0.028664 | 0.357341 | 7,220 | 160 | 146 | 45.125 | 0.787284 | 0.398892 | 0 | 0.753425 | 0 | 0 | 0.192663 | 0.115598 | 0 | 0 | 0 | 0 | 0 | 1 | 0.082192 | false | 0 | 0.013699 | 0 | 0.273973 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d0870e4fde428825e6014ca0e44f1ba21b99477b | 1,039 | py | Python | autogl/module/_feature/graph/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
] | 824 | 2020-11-30T14:38:07.000Z | 2022-03-19T10:14:04.000Z | autogl/module/_feature/graph/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
] | 38 | 2020-12-21T12:32:57.000Z | 2022-01-31T02:32:05.000Z | autogl/module/_feature/graph/__init__.py | dedsec-9/AutoGL | 487f2b2f798b9b1363ad5dc100fb410b12222e06 | [
"MIT"
] | 85 | 2020-12-21T05:16:09.000Z | 2022-03-28T08:44:22.000Z | from .netlsd import SgNetLSD
from .base import BaseGraph
from .nx import (
register_nx,
NxGraph,
nxfunc,
NxLargeCliqueSize,
NxAverageClusteringApproximate,
NxDegreeAssortativityCoefficient,
NxDegreePearsonCorrelationCoefficient,
NxHasBridge,
NxGraphCliqueNumber,
NxGraphNumberOfCliques,
NxTransitivity,
NxAverageClustering,
NxIsConnected,
NxNumberConnectedComponents,
NxIsDistanceRegular,
NxLocalEfficiency,
NxGlobalEfficiency,
NxIsEulerian,
)
__all__ = [
"SgNetLSD",
"BaseGraph",
"register_nx",
"NxGraph",
"nxfunc",
"NxLargeCliqueSize",
"NxAverageClusteringApproximate",
"NxDegreeAssortativityCoefficient",
"NxDegreePearsonCorrelationCoefficient",
"NxHasBridge",
"NxGraphCliqueNumber",
"NxGraphNumberOfCliques",
"NxTransitivity",
"NxAverageClustering",
"NxIsConnected",
"NxNumberConnectedComponents",
"NxIsDistanceRegular",
"NxLocalEfficiency",
"NxGlobalEfficiency",
"NxIsEulerian",
]
| 22.586957 | 44 | 0.717036 | 52 | 1,039 | 14.211538 | 0.5 | 0.027064 | 0.046008 | 0.062246 | 0.893099 | 0.893099 | 0.893099 | 0.893099 | 0.893099 | 0.893099 | 0 | 0 | 0.200192 | 1,039 | 45 | 45 | 23.088889 | 0.88929 | 0 | 0 | 0 | 0 | 0 | 0.334937 | 0.142445 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.068182 | 0 | 0.068182 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d08978a698c411adfd2375951c9f9f2e6722f5cc | 9,623 | py | Python | rlpyt/experiments/configs/dm_control/qpg/sac/dm_control_sac.py | csingh27sewts/rlpyt | 4252eb63515c9e68c0674fb010d2c6dbfdac9122 | [
"MIT"
] | 17 | 2019-10-07T03:37:08.000Z | 2022-02-10T15:33:22.000Z | rlpyt/experiments/configs/dm_control/qpg/sac/dm_control_sac.py | csingh27/Learning-To-Manipulate-Deformable-Objects-without-Demonstration | 4252eb63515c9e68c0674fb010d2c6dbfdac9122 | [
"MIT"
] | 1 | 2021-09-09T08:49:43.000Z | 2021-09-09T08:49:43.000Z | rlpyt/experiments/configs/dm_control/qpg/sac/dm_control_sac.py | csingh27/Learning-To-Manipulate-Deformable-Objects-without-Demonstration | 4252eb63515c9e68c0674fb010d2c6dbfdac9122 | [
"MIT"
] | 6 | 2020-06-24T10:34:46.000Z | 2021-07-19T01:57:49.000Z |
import copy
configs = dict()
config = dict(
agent=dict(
q_model_kwargs=dict(hidden_sizes=[256, 256]),
model_kwargs=dict(hidden_sizes=[256, 256]),
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=2e5,
log_interval_steps=1e4,
),
sampler=dict(
batch_T=1,
batch_B=32,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=50,
),
env=dict(
domain='cloth_v0',
task='easy',
max_path_length=1200,
task_kwargs=dict(reward='diagonal')
),
)
configs["sac_state_clothv0"] = config
config = dict(
agent=dict(
ModelCls='PiConvModel',
QModelCls='QofMuConvModel',
q_model_kwargs=dict(channels=(64, 64, 64),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
model_kwargs=dict(channels=(64, 64, 64),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=2e5,
log_interval_steps=1e4,
),
sampler=dict(
is_pixel=True,
batch_T=1,
batch_B=16,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=50,
),
env=dict(
domain='cloth_v0',
task='easy',
max_path_length=1200,
task_kwargs=dict(reward='diagonal'),
pixel_wrapper_kwargs=dict(observation_key='pixels', pixels_only=True,
render_kwargs=dict(width=64, height=64))
),
)
configs["sac_pixels_clothv0"] = config
config = copy.deepcopy(configs['sac_state_clothv0'])
config['env']['domain'] = 'cloth_v8'
config['env']['task_kwargs']['mode'] = 'corners'
config['env']['task_kwargs']['distance_weight'] = 0.0
configs["sac_state_clothv8"] = config
config = copy.deepcopy(configs['sac_pixels_clothv0'])
config['env']['domain'] = 'cloth_v0'
config['env']['task_kwargs']['mode'] = 'corners'
config['env']['task_kwargs']['distance_weight'] = 0.0
configs["sac_pixels_clothv8"] = config
config = copy.deepcopy(configs['sac_state_clothv8'])
config['env']['domain'] = 'cloth_v7'
config['env']['task_kwargs']['mode'] = 'corners'
config['env']['task_kwargs']['distance_weight'] = 0.0
configs["sac_state_clothv7"] = config
config = copy.deepcopy(configs['sac_pixels_clothv8'])
config['env']['domain'] = 'cloth_v8'
config['env']['task_kwargs']['mode'] = 'corners'
config['env']['task_kwargs']['distance_weight'] = 0.0
configs["sac_pixels_clothv8"] = config
config = copy.deepcopy(configs['sac_state_clothv8'])
config['env']['domain'] = 'cloth_sim_state'
config['env']['max_path_length'] = 30
config['env']['task_kwargs'] = dict(mode='corners')
config['agent']['q_model_kwargs']['n_tile'] = 20
configs["sac_state_cloth_sim"] = config
config = copy.deepcopy(configs['sac_pixels_clothv8'])
config['env']['domain'] = 'cloth_v8'
config['env']['max_path_length'] = 30
del config['env']['task_kwargs']
config['agent']['q_model_kwargs']['n_tile'] = 20
configs["sac_pixels_cloth_sim"] = config
config = copy.deepcopy(configs['sac_state_clothv0'])
config['runner']['n_steps'] = 1e6
config['env']['domain'] = 'rope_v1'
config['env']['max_path_length'] = 1000
del config['env']['task_kwargs']
configs["sac_state_ropev1"] = config
config = copy.deepcopy(configs['sac_pixels_clothv0'])
config['runner']['n_steps'] = 1e6
config['env']['domain'] = 'rope_v1'
config['env']['max_path_length'] = 1000
del config['env']['task_kwargs']
configs["sac_pixels_ropev1"] = config
config = dict(
sac_module='sac_v2',
sac_agent_module='sac_agent_v2',
name='',
agent=dict(
ModelCls='PiMlpModel',
q_model_kwargs=dict(hidden_sizes=[256, 256]),
model_kwargs=dict(hidden_sizes=[256, 256]),
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=5e5,
log_interval_steps=1e4,
),
sampler=dict(
batch_T=1,
batch_B=32,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=10,
),
env=dict(
domain='cloth_corner',
task='easy',
max_path_length=120,
task_kwargs=dict(random_location=True)
),
)
configs["sac_state_cloth_corner"] = config
config = dict(
state_keys=None,
info_keys=None,
sac_module='sac_v2',
sac_agent_module='sac_agent_v2',
name='',
agent=dict(
ModelCls='GumbelPiConvModel',
QModelCls='QofMuConvModel',
q_model_kwargs=dict(channels=(64, 64, 4),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
model_kwargs=dict(channels=(64, 64, 4),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
n_qs=2,
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=3e5,
log_interval_steps=1e4,
),
sampler=dict(
is_pixel=True,
batch_T=1,
batch_B=16,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=50,
),
env=dict(
domain='cloth_corner',
task='easy',
max_path_length=120,
pixel_wrapper_kwargs=dict(observation_key='pixels', pixels_only=False, # to not take away non pixel obs
render_kwargs=dict(width=64, height=64, camera_id=0)),
task_kwargs=dict(random_location=True, pixels_only=True, train_mode=True) # to not return positions and only pick location
),
)
configs["sac_pixels_cloth_corner"] = config
config = dict(
sac_module='sac_v2',
sac_agent_module='sac_agent_v2',
name='',
agent=dict(
ModelCls='PiMlpModel',
q_model_kwargs=dict(hidden_sizes=[256, 256]),
model_kwargs=dict(hidden_sizes=[256, 256]),
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=5e5,
log_interval_steps=1e4,
),
sampler=dict(
batch_T=1,
batch_B=32,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=50,
),
env=dict(
domain='rope_v2',
task='easy',
max_path_length=200,
task_kwargs=dict(random_location=True)
),
)
configs["sac_state_rope_v2"] = config
config = dict(
state_keys=None,
info_keys=None,
sac_module='sac_v2',
sac_agent_module='sac_agent_v2',
name='',
agent=dict(
ModelCls='PiConvModel',
QModelCls='QofMuConvModel',
q_model_kwargs=dict(channels=(64, 64, 4),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
model_kwargs=dict(channels=(64, 64, 4),
kernel_sizes=(3, 3, 3), strides=(2, 2, 2),
hidden_sizes=[256, 256]),
n_qs=2,
),
algo=dict(
discount=0.99,
batch_size=1024,
target_update_tau=0.005,
target_update_interval=1,
learning_rate=6e-4,
reparameterize=True,
policy_output_regularization=0.0,
reward_scale=1,
replay_ratio=128,
),
model=dict(),
optim=dict(),
runner=dict(
n_steps=5e5,
log_interval_steps=1e4,
),
sampler=dict(
is_pixel=True,
batch_T=1,
batch_B=16,
max_decorrelation_steps=0,
eval_n_envs=10,
eval_max_steps=20000,
eval_max_trajectories=50,
),
env=dict(
domain='rope_sac',
task='easy',
max_path_length=200,
pixel_wrapper_kwargs=dict(observation_key='pixels', pixels_only=False, # to not take away non pixel obs
render_kwargs=dict(width=64, height=64, camera_id=0)),
task_kwargs=dict() # to not return positions and only pick location
),
)
configs["sac_pixels_rope"] = config
| 27.573066 | 130 | 0.59576 | 1,199 | 9,623 | 4.495413 | 0.117598 | 0.046382 | 0.033395 | 0.037848 | 0.960853 | 0.940631 | 0.92115 | 0.9141 | 0.911132 | 0.85102 | 0 | 0.065344 | 0.266861 | 9,623 | 348 | 131 | 27.652299 | 0.698653 | 0.016107 | 0 | 0.884735 | 0 | 0 | 0.131896 | 0.004756 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.003115 | 0 | 0.003115 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d09066a0ddfd85b11a312016da444c3da11a3600 | 2,851 | py | Python | Text/Fizz Buzz/tests.py | fossabot/IdeaBag2-Solutions | 73b554d9796510fc86e5fc55016732aa866266c6 | [
"MIT"
] | 10 | 2018-07-06T22:05:45.000Z | 2021-05-22T11:29:04.000Z | Text/Fizz Buzz/tests.py | jarik-marwede/IdeaBag2-Projects | c5fe9524ef03a6ebc098ab8aaee7448f5b877828 | [
"MIT"
] | 22 | 2018-07-13T17:16:43.000Z | 2022-01-11T11:16:08.000Z | Text/Fizz Buzz/tests.py | jarik-marwede/IdeaBag2-Projects | c5fe9524ef03a6ebc098ab8aaee7448f5b877828 | [
"MIT"
] | 1 | 2020-06-13T18:53:51.000Z | 2020-06-13T18:53:51.000Z | #!/usr/bin/env python3
import unittest
from fizz_buzz import fizzbuzz, xfizzbuzz
class Test(unittest.TestCase):
def test_fizzbuzz(self):
self.assertEqual(fizzbuzz(), [1, 2, 'Fizz', 4, 'Buzz', 'Fizz',
7, 8, 'Fizz', 'Buzz', 11, 'Fizz',
13, 14, 'FizzBuzz', 16, 17, 'Fizz',
19, 'Buzz', 'Fizz', 22, 23, 'Fizz',
'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz',
31, 32, 'Fizz', 34, 'Buzz', 'Fizz',
37, 38, 'Fizz', 'Buzz', 41, 'Fizz',
43, 44, 'FizzBuzz', 46, 47, 'Fizz',
49, 'Buzz', 'Fizz', 52, 53, 'Fizz',
'Buzz', 56, 'Fizz', 58, 59, 'FizzBuzz',
61, 62, 'Fizz', 64, 'Buzz', 'Fizz',
67, 68, 'Fizz', 'Buzz', 71, 'Fizz',
73, 74, 'FizzBuzz', 76, 77, 'Fizz',
79, 'Buzz', 'Fizz', 82, 83, 'Fizz',
'Buzz', 86, 'Fizz', 88, 89, 'FizzBuzz',
91, 92, 'Fizz', 94, 'Buzz', 'Fizz',
97, 98, 'Fizz', 'Buzz'])
def test_xfizzbuz(self):
self.assertEqual(list(xfizzbuzz()), [1, 2, 'Fizz', 4, 'Buzz', 'Fizz',
7, 8, 'Fizz', 'Buzz', 11, 'Fizz',
13, 14, 'FizzBuzz', 16, 17, 'Fizz',
19, 'Buzz', 'Fizz', 22, 23, 'Fizz',
'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz',
31, 32, 'Fizz', 34, 'Buzz', 'Fizz',
37, 38, 'Fizz', 'Buzz', 41, 'Fizz',
43, 44, 'FizzBuzz', 46, 47, 'Fizz',
49, 'Buzz', 'Fizz', 52, 53, 'Fizz',
'Buzz', 56, 'Fizz', 58, 59, 'FizzBuzz',
61, 62, 'Fizz', 64, 'Buzz', 'Fizz',
67, 68, 'Fizz', 'Buzz', 71, 'Fizz',
73, 74, 'FizzBuzz', 76, 77, 'Fizz',
79, 'Buzz', 'Fizz', 82, 83, 'Fizz',
'Buzz', 86, 'Fizz', 88, 89, 'FizzBuzz',
91, 92, 'Fizz', 94, 'Buzz', 'Fizz',
97, 98, 'Fizz', 'Buzz'])
if __name__ == "__main__":
unittest.main()
| 57.02 | 84 | 0.293932 | 236 | 2,851 | 3.504237 | 0.317797 | 0.145103 | 0.045949 | 0.016929 | 0.756953 | 0.756953 | 0.756953 | 0.756953 | 0.756953 | 0.756953 | 0 | 0.160348 | 0.555945 | 2,851 | 49 | 85 | 58.183673 | 0.492891 | 0.007366 | 0 | 0.780488 | 0 | 0 | 0.152704 | 0 | 0 | 0 | 0 | 0 | 0.04878 | 1 | 0.04878 | false | 0 | 0.04878 | 0 | 0.121951 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
d0c50ebf45abbc85ca07468ba4981d76792e8fd0 | 36,679 | py | Python | scripts/betterX_user-story-daily-files.py | eliasall/BetterX-Cloud | c6796f1207ced4ad3c63fd56df08ecf5ece613e1 | [
"Apache-2.0"
] | null | null | null | scripts/betterX_user-story-daily-files.py | eliasall/BetterX-Cloud | c6796f1207ced4ad3c63fd56df08ecf5ece613e1 | [
"Apache-2.0"
] | null | null | null | scripts/betterX_user-story-daily-files.py | eliasall/BetterX-Cloud | c6796f1207ced4ad3c63fd56df08ecf5ece613e1 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
# coding: utf8
import os, urllib, hmac, binascii, base64, hashlib, urllib2, json, pprint, simplejson, sys, time, csv
import MySQLdb
from optparse import OptionParser
import codecs
from warnings import filterwarnings
filterwarnings('ignore', category = MySQLdb.Warning)
host = ''
user = ''
password = ''
db = ''
path = ''
mainquery = '''SELECT
betterX._user_webSessions.uid as uid,
dayofyear(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `dayOfYear`, count(*) as cnt
FROM betterX._user_webSessions
left join betterX.setup on betterX.setup.uid = betterX._user_webSessions.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where dayofyear(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) is not null
group by betterX._user_webSessions.uid, dayofyear(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by count(*) desc'''
locationsQuery = """SELECT betterX._user_webSessions.userTimestamp as `timestamp`, a.latitude as lat, a.longitude as lon,
replace(
CONCAT(
'<strong>', betterX._user_webSessions.location_address, '</strong>', '<br/>', 'Accuracy:', cast(a.accuracy as char(10)),
'<br/>', 'LocationSessions: ' , cast(b.CntLocationSessions as char(10)),
'<br/>', 'TodaysLocationSessions: ', cast(c.CntTodaysLocationSessions as char(10)),
'<br/>', 'LocationDomains: ', cast(b.CntLocationDomains as char(10)),
'<br/>', 'TodaysLocationDomains: ', cast(c.CntTodaysLocationDomains as char(10)),
'<br/>', 'LocationDomainList: ', cast(b.LocationDomainsList as char(250)),
'<br/>', 'TodaysLocationDomainList: ', cast(c.TodaysLocationDomainsList as char(250))
) collate utf8_unicode_ci
,
',', '|') collate utf8_unicode_ci as `desc`
FROM betterX._user_webSessions
left join
(
select _user_geolocations.address, min(_user_locations.accuracy) as accuracy, max(_user_geolocations.latitude) as latitude, max(_user_geolocations.longitude) as longitude
from _user_geolocations
left join _user_locations on _user_locations.latitude = _user_geolocations.latitude and _user_locations.longitude = _user_geolocations.longitude
where _user_geolocations.address is not null and _user_geolocations.latitude is not null and _user_geolocations.longitude is not null
group by address
) as a on a.address = betterX._user_webSessions.location_address
left join
(
select uid, location_address, count(*) as CntLocationSessions, count(distinct(domain)) as CntLocationDomains, GROUP_CONCAT(distinct(domain)) as LocationDomainsList
from betterX._user_webSessions
where location_address is not null
group by uid, location_address
order by uid, location_address
) as b on b.uid = betterX._user_webSessions.uid and b.location_address = betterX._user_webSessions.location_address
left join
(
select uid, dayofyear(betterX._user_webSessions.userTime) as `day`, location_address, count(*) as CntTodaysLocationSessions, count(distinct(domain)) as CntTodaysLocationDomains, GROUP_CONCAT(distinct(domain)) as TodaysLocationDomainsList
from betterX._user_webSessions
where location_address is not null and betterX._user_webSessions.userTime is not null
group by uid, dayofyear(betterX._user_webSessions.userTime), location_address
order by uid, dayofyear(betterX._user_webSessions.userTime), location_address
) as c on c.uid = betterX._user_webSessions.uid and c.location_address = betterX._user_webSessions.location_address and c.`day` = dayofyear(betterX._user_webSessions.userTime)
where betterX._user_webSessions.uid = @userid
and dayofyear(betterX._user_webSessions.userTime) = @userday
and betterX._user_webSessions.location_address is not null and a.latitude is not null and a.longitude is not null
group by `timestamp`, lat, lon, `desc`
order by betterX._user_webSessions.userTimestamp asc
"""
metricsList = [
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'pageTitle as `value`','name_pageTitle'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'pageOnContentLoad as `value`','time_pageOnContentLoad'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'pageOnLoad as `value`','time_pageOnLoad'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'origin as `value`','origin'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'time as `value`','time_total'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'connection as `value`','time_connection'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'blocked as `value`','time_blocked'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'dns as `value`','time_dns'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'connect as `value`','time_connect'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'send as `value`','time_send'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'wait as `value`','time_wait'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'receive as `value`','time_receive'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'`ssl` as `value`','time_ssl'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'beforeRequestCacheEntries as `value`','cache_beforeRequestCacheEntries'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'afterRequestCacheEntries as `value`','cache_afterRequestCacheEntries'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'hitCount as `value`','cache_hitCount'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'method as `value`','http_method'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'url as `value`','name_url'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'httpVersionRequest as `value`','http_httpVersionRequest'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'cookieNumberRequest as `value`','cookie_cookieNumberRequest'],
#["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_UserAgent as `value`','header_UserAgent'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_Accept as `value`','type_header_Accept'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_AcceptEncoding as `value`','encoding_header_AcceptEncoding'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ConnectionRequest as `value`','connection_header_ConnectionRequest'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ContentLengthRequest as `value`','size_header_ContentLengthRequest'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_KeepAliveRequest as `value`','connection_header_KeepAliveRequest'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'headerSize as `value`','size_headerSize'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'bodySizeRequest as `value`','size_bodySizeRequest'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'status as `value`','http_status'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'statusText as `value`','http_statusText'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'httpVersionResponse as `value`','http_httpVersionResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'cookieNumberResponse as `value`','cookie_cookieNumberResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'cookieNumberRequest as `value`','cookie_cookieNumberRequest'],
#["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_Server as `value`','header_Server'],
#["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_XPoweredBy as `value`','header_XPoweredBy'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ContentEncoding as `value`','encoding_header_ContentEncoding'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ContentLengthResponse as `value`','size_header_ContentLengthResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_KeepAliveResponse as `value`','connection_header_KeepAliveResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ConnectionResponse as `value`','connection_header_ConnectionResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'header_ContentType as `value`','type_header_ContentType'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'redirectUrl as `value`','redirect_redirectUrl'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'headersSize as `value`','size_headersSize'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'bodySizeResponse as `value`','size_bodySizeResponse'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'content_size as `value`','size_content_size'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'content_compression as `value`','type_content_compression'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'content_mimeType as `value`','type_content_mimeType'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'content_encoding as `value`','encoding_content_encoding'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'domain as `value`','name_domain'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'title as `value`','name_title'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'Speed_MediaLoadingTime as `value`','time_Speed_MediaLoadingTime'],
#["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'Speed_Percentile as `value`','Speed_Percentile'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'Category1 as `value`','name_Category1'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'durationTab as `value`','time_durationTab'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'estimateDuration as `value`','time_estimateDuration'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'location_address as `value`','location_location_address'],
["UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`",'location_accuracy as `value`','location_location_accuracy']
]
readingsList = [
["apps", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.apps.`timestamp` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(distinct(app)), ',', '|') as `value`
FROM betterX.apps
left join betterX.setup on betterX.setup.uid = betterX.apps.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.apps.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.apps.`timestamp` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.apps.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.apps.`timestamp` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.apps.`timestamp` asc
"""],
["battery_level",
"""select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MIN(`level`) as `value`
FROM betterX.sensor_battery
left join betterX.setup on betterX.setup.uid = betterX.sensor_battery.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_battery.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_battery.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_battery.`epoch` asc
"""],
["battery_temp","""
select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MIN(`temp`) as `value`
FROM betterX.sensor_battery
left join betterX.setup on betterX.setup.uid = betterX.sensor_battery.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_battery.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_battery.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_battery.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_battery.`epoch` asc
"""],
["connection_connected", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
cast(MIN(`connected`) as unsigned) as `value`
FROM betterX.sensor_connection
left join betterX.setup on betterX.setup.uid = betterX.sensor_connection.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connection.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connection.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connection.`epoch` asc
"""],
["connection_connecting", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
cast(MIN(`connecting`) as unsigned) as `value`
FROM betterX.sensor_connection
left join betterX.setup on betterX.setup.uid = betterX.sensor_connection.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connection.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connection.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connection.`epoch` asc
"""],
["connection_available", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
cast(MIN(`available`) as unsigned) as `value`
FROM betterX.sensor_connection
left join betterX.setup on betterX.setup.uid = betterX.sensor_connection.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connection.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connection.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connection.`epoch` asc
"""],
["connection_networkType", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`networkType`)), ',', '|') as `value`
FROM betterX.sensor_connection
left join betterX.setup on betterX.setup.uid = betterX.sensor_connection.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connection.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connection.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connection.`epoch` asc
"""],
["connection_roaming", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`roaming`)), ',', '|') as `value`
FROM betterX.sensor_connection
left join betterX.setup on betterX.setup.uid = betterX.sensor_connection.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connection.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connection.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connection.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connection.`epoch` asc
"""],
["connection_strength", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connectionStrength.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MIN(`strength`) as `value`
FROM betterX.sensor_connectionStrength
left join betterX.setup on betterX.setup.uid = betterX.sensor_connectionStrength.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_connectionStrength.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connectionStrength.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_connectionStrength.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_connectionStrength.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_connectionStrength.`epoch` asc
"""],
["network_ssid", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`ssid`)), ',', '|') as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_state", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`detailedState`)), ',', '|') as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_internet", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`hasInternet`)), ',', '|') as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_linkSpeed", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MIN(`linkSpeed`) as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_mobile", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`mobileStatus`)), ',', '|') as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_signalStrength", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MIN(`signalStrength`) as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["network_wifi", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`wifiStatus`)), ',', '|') as `value`
FROM betterX.network
left join betterX.setup on betterX.setup.uid = betterX.network.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.network.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.network.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.network.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.network.`epoch` asc
"""],
["phoneState", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_phoneState.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(
trim(CONCAT(
if (left(`data`, 10) = 'CALL_STATE', trim(`data`), ''),
if (left(`data`, 13) = 'DATA_ACTIVITY', trim(`data`), ''),
if (left(`data`, 14) = 'DATA_CONNECTED', trim(`data`), ''),
if (left(`data`, 17) = 'DATA_DISCONNECTED', trim(`data`), ''),
if (left(`data`, 14) = 'DATA_SUSPENDED', trim(`data`), ''),
if (left(`data`, 20) = 'STATE_EMERGENCY_ONLY', trim(left(`data`, locate(' ', `data`))), ''),
if (left(`data`, 16) = 'STATE_IN_SERVICE', trim(left(`data`, locate(' ', `data`))), ''),
if (left(`data`, 20) = 'STATE_OUT_OF_SERVICE', trim(left(`data`, locate(' ', `data`))), ''),
if (left(`data`, 15) = 'STATE_POWER_OFF', trim(left(`data`, locate(' ', `data`))), '')
)) COLLATE utf8_unicode_ci)), ',' , '|') as `value`
FROM betterX.sensor_phoneState
left join betterX.setup on betterX.setup.uid = betterX.sensor_phoneState.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_phoneState.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_phoneState.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_phoneState.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_phoneState.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_phoneState.`epoch` asc
"""],
["phoneScreen", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_screen.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
replace(GROUP_CONCAT(DISTINCT(`status`)), ',', '|') as `value`
FROM betterX.sensor_screen
left join betterX.setup on betterX.setup.uid = betterX.sensor_screen.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_screen.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_screen.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_screen.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_screen.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_screen.`epoch` asc
"""],
["steps", """select
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_stepCounter.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) as `timestamp`,
MAX(stepCount) as `value`
FROM betterX.sensor_stepCounter
left join betterX.setup on betterX.setup.uid = betterX.sensor_stepCounter.uid
left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone
where betterX.sensor_stepCounter.uid = @userid
and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_stepCounter.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = @userday
group by betterX.sensor_stepCounter.uid,
UNIX_TIMESTAMP(CONVERT_TZ(from_unixtime( cast(cast(betterX.sensor_stepCounter.`epoch` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr))
order by betterX.sensor_stepCounter.`epoch` asc
"""]
]
try:
conn = MySQLdb.connect (host, user, password, db, charset='utf8')
except:
print ">> Unable to connect...exit"
sys.exit()
else:
cursor = conn.cursor()
cursor.execute (mainquery)
rows = cursor.fetchall()
numrows = int(cursor.rowcount)
mainFile = codecs.open(path + 'index.csv' , 'wb', 'utf-8')
mainFile.write('userid,fileTypeName,dayofYear' + "\n")
for i in range(numrows):
userID = str(rows[i][0])
userDay = rows[i][1]
userRecordCount = rows[i][2]
for j in metricsList:
attr1 = str(j[0])
attr2 = str(j[1])
fileName = str(j[2])
q = "select " + attr1 + "," + attr2 + " from betterX._user_webSessions left join betterX.setup on betterX.setup.uid = betterX._user_webSessions.uid left join betterX._user_timeZones on betterX._user_timeZones.tzone_raw = betterX.setup.timezone where betterX._user_webSessions.uid = '" + userID + "' and dayofyear(CONVERT_TZ(from_unixtime( cast(cast(`pageStartTime` as char(10)) as unsigned) ), 'UTC', betterX._user_timeZones.tzone_abbr)) = " + str(userDay) + " order by pageStartTime asc"
cursor.execute(q)
rows2 = cursor.fetchall()
numrows2 = int(cursor.rowcount)
if (numrows2 > 0):
mainFile.write(str(userID) + "," + str(fileName) + "," + str(userDay) + "\n")
myfile = codecs.open(path + userID + '_' + fileName + '_' + str(userDay) + '.csv' , 'wb', 'utf-8')
myfile.write('timestamp' + "," + 'value' + "\n")
for i2 in range(numrows2):
try:
enc = str(str(rows2[i2][0]) + "," + str(rows2[i2][1])).encode("utf-8")
except:
enc = ' '
myfile.write(enc + "\n")
myfile.close()
for k in readingsList:
readingsName = str(k[0])
readingsSQL = str(k[1])
readingsSQL = readingsSQL.replace("@userid", str("'" + userID + "'"))
readingsSQL = readingsSQL.replace("@userday", str(userDay))
cursor.execute(readingsSQL)
rowsK = cursor.fetchall()
numrowsK = int(cursor.rowcount)
if (numrowsK > 0):
mainFile.write(str(userID) + "," + readingsName + "," + str(userDay) + "\n")
myfile = codecs.open(path + userID + '_' + readingsName + '_' + str(userDay) + '.csv' , 'wb', 'utf-8')
myfile.write('timestamp' + "," + 'value' + "\n")
for iK in range(numrowsK):
try:
enc = str(str(rowsK[iK][0]) + "," + str(rowsK[iK][1])).encode("utf-8")
except:
enc = ' '
myfile.write(enc + "\n")
myfile.close()
qL = locationsQuery.replace("@userid", str("'" + userID + "'"))
qL = qL.replace("@userday", str(userDay))
cursor.execute(qL)
rowsL = cursor.fetchall()
numrowsL = int(cursor.rowcount)
if (numrowsL > 0):
mainFile.write(str(userID) + "," + 'locations' + "," + str(userDay) + "\n")
myfileL = codecs.open(path + userID + '_' + 'locations' + '_' + str(userDay) + '.csv' , 'wb', 'utf-8')
myfileL.write('timestamp,lat,lon,desc' + "\n")
for iL in range(numrowsL):
try:
encL = str(str(rowsL[iL][0]) + "," + str(rowsL[iL][1]) + "," + str(rowsL[iL][2]) + "," + str(rowsL[iL][3])).encode("utf-8")
except:
encL = ' '
myfileL.write(encL + "\n")
myfileL.close()
#break;
mainFile.close()
cursor.close()
conn.close() | 81.508889 | 492 | 0.761853 | 4,969 | 36,679 | 5.400081 | 0.058764 | 0.075839 | 0.118511 | 0.128573 | 0.798643 | 0.778743 | 0.763239 | 0.759214 | 0.752916 | 0.743972 | 0 | 0.009477 | 0.088007 | 36,679 | 450 | 493 | 81.508889 | 0.792682 | 0.023528 | 0 | 0.371158 | 0 | 0.293144 | 0.893981 | 0.521141 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.004728 | 0.01182 | null | null | 0.004728 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
ef71eb8899acec7d885a018db9c3dbf5eac58bfe | 290 | py | Python | anamic/simulator/__init__.py | brouhardlab/anamic | 0e61e4aeb999ba91fdf0e21b55f2e132e94f94bc | [
"BSD-3-Clause"
] | 4 | 2019-03-27T09:49:42.000Z | 2021-06-09T12:42:03.000Z | anamic/simulator/__init__.py | hadim/anamic | 0e61e4aeb999ba91fdf0e21b55f2e132e94f94bc | [
"BSD-3-Clause"
] | 7 | 2019-03-03T16:46:23.000Z | 2019-03-03T17:01:59.000Z | anamic/simulator/__init__.py | hadim/anamic | 0e61e4aeb999ba91fdf0e21b55f2e132e94f94bc | [
"BSD-3-Clause"
] | 1 | 2019-03-27T09:49:46.000Z | 2019-03-27T09:49:46.000Z | from .structure import get_structure_parameters
from .structure import generate_uniform_taper
from .structure import get_dimer_positions
from .structure import get_mt_tips
from .mt_simulator import dimers_builder
from .mt_simulator import MicrotubuleSimulator
from .fov import create_fov
| 29 | 47 | 0.872414 | 40 | 290 | 6.025 | 0.45 | 0.215768 | 0.315353 | 0.273859 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.103448 | 290 | 9 | 48 | 32.222222 | 0.926923 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
efb72435c360bddd044c19ec9156636a9727ad0c | 1,102 | py | Python | tests/rules/test_same.py | bakurits/Validator | 4e666cf3cb2805e44baa257fed77df44662e6f86 | [
"MIT"
] | null | null | null | tests/rules/test_same.py | bakurits/Validator | 4e666cf3cb2805e44baa257fed77df44662e6f86 | [
"MIT"
] | null | null | null | tests/rules/test_same.py | bakurits/Validator | 4e666cf3cb2805e44baa257fed77df44662e6f86 | [
"MIT"
] | null | null | null | from validator.rules import Same
from validator.rules_wrapper import RulesWrapper as RW
def test_same_01():
req = {"old_pass": "password", "new_pass": "password"}
rule = {"new_pass": [Same("old_pass")]}
rw = RW(req, rule)
rw.run()
assert rw.get_result()
req = {"old_val": 5, "new_val": 5}
rule = {"new_val": [Same("old_val")]}
rw = RW(req, rule)
rw.run()
assert rw.get_result()
req = {"old_arr": [1, 2, 3], "new_arr": [1, 2, 3]}
rule = {"new_arr": [Same("old_arr")]}
rw = RW(req, rule)
rw.run()
assert rw.get_result()
def test_same_02():
req = {"old_pass": "old_password", "new_pass": "new_password"}
rule = {"new_pass": [Same("old_pass")]}
rw = RW(req, rule)
rw.run()
assert not rw.get_result()
req = {"old_val": 5, "new_val": 6}
rule = {"new_val": [Same("old_val")]}
rw = RW(req, rule)
rw.run()
assert not rw.get_result()
req = {"old_arr": [1, 2, 3], "new_arr": [1, 2, 3, 4, 5]}
rule = {"new_arr": [Same("old_arr")]}
rw = RW(req, rule)
rw.run()
assert not rw.get_result()
| 25.627907 | 66 | 0.561706 | 174 | 1,102 | 3.344828 | 0.183908 | 0.061856 | 0.072165 | 0.113402 | 0.723368 | 0.723368 | 0.723368 | 0.723368 | 0.723368 | 0.689003 | 0 | 0.026036 | 0.233212 | 1,102 | 42 | 67 | 26.238095 | 0.662722 | 0 | 0 | 0.705882 | 0 | 0 | 0.196007 | 0 | 0 | 0 | 0 | 0 | 0.176471 | 1 | 0.058824 | false | 0.117647 | 0.058824 | 0 | 0.117647 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 7 |
efe2596dcb8a3f118c63067dd406352bf0425ad5 | 220 | py | Python | SimpleCV/MachineLearning/__init__.py | nikhilgk/SimpleCV | ee64451c16db1f40b4da221115273020a6a7b01a | [
"BSD-3-Clause"
] | 2 | 2016-04-30T12:23:05.000Z | 2022-03-02T00:01:10.000Z | SimpleCV/MachineLearning/__init__.py | nikhilgk/SimpleCV | ee64451c16db1f40b4da221115273020a6a7b01a | [
"BSD-3-Clause"
] | null | null | null | SimpleCV/MachineLearning/__init__.py | nikhilgk/SimpleCV | ee64451c16db1f40b4da221115273020a6a7b01a | [
"BSD-3-Clause"
] | 2 | 2015-04-16T12:14:55.000Z | 2019-08-07T14:12:04.000Z | from SimpleCV.MachineLearning.SVMClassifier import *
from SimpleCV.MachineLearning.TreeClassifier import *
from SimpleCV.MachineLearning.KNNClassifier import *
from SimpleCV.MachineLearning.NaiveBayesClassifier import *
| 44 | 59 | 0.872727 | 20 | 220 | 9.6 | 0.4 | 0.25 | 0.5625 | 0.515625 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.072727 | 220 | 4 | 60 | 55 | 0.941176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
efe6d780809a295977e3ea2ddc400d74483e1f2f | 20 | py | Python | ex3_study_drills.py | BjornChrisnach/Learn_python_3_The_hard_way | ab187c4755d4878724761bbe5f28678fce27cfc7 | [
"MIT"
] | null | null | null | ex3_study_drills.py | BjornChrisnach/Learn_python_3_The_hard_way | ab187c4755d4878724761bbe5f28678fce27cfc7 | [
"MIT"
] | null | null | null | ex3_study_drills.py | BjornChrisnach/Learn_python_3_The_hard_way | ab187c4755d4878724761bbe5f28678fce27cfc7 | [
"MIT"
] | null | null | null | print(4 + 5 * 8 / 4) | 20 | 20 | 0.45 | 5 | 20 | 1.8 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | 0.3 | 20 | 1 | 20 | 20 | 0.357143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
eff6ef5f20c546cbc20bdf3c79671f86b767c7b7 | 12,619 | py | Python | hyperts/tests/dl/dl_wrappers_test.py | DataCanvasIO/HyperTS | b2560daf8f08748691e7bd9efd14cc5f881186a3 | [
"Apache-2.0"
] | 13 | 2021-11-15T08:07:54.000Z | 2022-03-27T18:21:20.000Z | hyperts/tests/dl/dl_wrappers_test.py | DataCanvasIO/HyperTS | b2560daf8f08748691e7bd9efd14cc5f881186a3 | [
"Apache-2.0"
] | 34 | 2021-11-26T01:34:49.000Z | 2022-03-31T06:28:39.000Z | hyperts/tests/dl/dl_wrappers_test.py | DataCanvasIO/HyperTS | b2560daf8f08748691e7bd9efd14cc5f881186a3 | [
"Apache-2.0"
] | 3 | 2021-11-15T08:07:57.000Z | 2022-03-18T07:35:49.000Z | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import numpy as np
from hyperts.datasets import *
from hyperts.utils.metrics import rmse, mape, accuracy_score
from hyperts.utils import consts
from hyperts.utils import get_tool_box
from hyperts.framework.wrappers.dl_wrappers import DeepARWrapper, HybirdRNNWrapper, LSTNetWrapper
class Test_DL_Wrappers():
def test_univariate_forecast_deepar(self):
X, y = load_random_univariate_forecast_dataset(return_X_y=True)
tb = get_tool_box(X)
X = tb.simple_numerical_imputer(X, mode='mode')
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_UNIVARIATE_FORECAST
timestamp = 'ds'
fit_kwargs = {
'epochs': 5,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'lstm',
'rnn_units': 10,
'rnn_layers': 2,
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = DeepARWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_univariate_forecast_rnn(self):
X, y = load_random_univariate_forecast_dataset(return_X_y=True)
tb = get_tool_box(X)
X = tb.simple_numerical_imputer(X, mode='mode')
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_UNIVARIATE_FORECAST
timestamp = 'ds'
fit_kwargs = {
'epochs': 5,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'simple_rnn',
'rnn_units': 10,
'rnn_layers': 2,
'learning_rate': 0.001,
'loss': 'mae',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_multivariate_forecast_with_covariables_rnn(self):
X, y = load_network_traffic(return_X_y=True)
tb = get_tool_box(X)
y = tb.simple_numerical_imputer(y)
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_FORECAST
timestamp = 'TimeStamp'
fit_kwargs = {
'epochs': 5,
'batch_size': 16,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'lstm',
'rnn_units': 10,
'rnn_layers': 2,
'learning_rate': 0.001,
'loss': 'mae',
'out_activation': 'sigmoid',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_multivariate_forecast_no_covariables_rnn(self):
X, y = load_network_traffic(return_X_y=True)
tb = get_tool_box(X)
y = tb.simple_numerical_imputer(y)
X = X[['TimeStamp']]
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_FORECAST
timestamp = 'TimeStamp'
fit_kwargs = {
'epochs': 5,
'batch_size': 16,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'gru',
'rnn_units': 10,
'rnn_layers': 2,
'learning_rate': 0.001,
'loss': 'mse',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_univariate_classification_rnn(self):
X, y = load_arrow_head(return_X_y=True)
tb = get_tool_box(X)
X_train, X_test, y_train, y_test = tb.random_train_test_split(X, y, test_size=0.2)
task = consts.Task_UNIVARIATE_MULTICALSS
fit_kwargs = {
'epochs': 10,
'batch_size': 16,
}
init_kwargs = {
'task': task,
'rnn_type': 'simple_rnn',
'rnn_units': 10,
'rnn_layers': 3,
'learning_rate': 0.001,
'reducelr_patience': 15,
'earlystop_patience': 20,
'x_scale': np.random.choice(['z_score', 'scale-none'], size=1)[0]
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print('accuracy:', acc)
assert acc >= 0
def test_multivariate_classification_rnn(self):
X, y = load_basic_motions(return_X_y=True)
tb = get_tool_box(X)
X_train, X_test, y_train, y_test = tb.random_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_MULTICALSS
fit_kwargs = {
'epochs': 10,
'batch_size': 16,
}
init_kwargs = {
'task': task,
'rnn_type': 'simple_rnn',
'rnn_units': 10,
'rnn_layers': 2,
'learning_rate': 0.001,
'x_scale': np.random.choice(['z_score', 'scale-none'], size=1)[0]
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print('accuracy:', acc)
assert acc >= 0
def test_univariate_forecast_lstnet(self):
X, y = load_random_univariate_forecast_dataset(return_X_y=True)
tb = get_tool_box(X)
X = tb.simple_numerical_imputer(X, mode='mode')
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_UNIVARIATE_FORECAST
timestamp = 'ds'
fit_kwargs = {
'epochs': 10,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'simple_rnn',
'skip_rnn_type': 'simple_rnn',
'cnn_filters': 16,
'kernel_size': 3,
'rnn_units': 10,
'rnn_layers': 2,
'skip_rnn_units': 10,
'skip_rnn_layers': 2,
'skip_period': 3,
'ar_order': 3,
'learning_rate': 0.001,
'loss': 'mae',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = LSTNetWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_multivariate_forecast_with_covariables_lstnet(self):
X, y = load_network_traffic(return_X_y=True)
tb = get_tool_box(X)
y = tb.simple_numerical_imputer(y)
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_FORECAST
timestamp = 'TimeStamp'
fit_kwargs = {
'epochs': 10,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'simple_rnn',
'skip_rnn_type': 'simple_rnn',
'cnn_filters': 16,
'kernel_size': 3,
'rnn_units': 10,
'rnn_layers': 2,
'skip_rnn_units': 10,
'skip_rnn_layers': 2,
'skip_period': 3,
'ar_order': 3,
'learning_rate': 0.001,
'loss': 'mae',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = LSTNetWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_multivariate_forecast_no_covariables_lstnet(self):
X, y = load_network_traffic(return_X_y=True)
tb = get_tool_box(X)
y = tb.simple_numerical_imputer(y)
X = X[['TimeStamp']]
X_train, X_test, y_train, y_test = tb.temporal_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_FORECAST
timestamp = 'TimeStamp'
fit_kwargs = {
'epochs': 10,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'timestamp': timestamp,
'rnn_type': 'simple_rnn',
'skip_rnn_type': 'simple_rnn',
'cnn_filters': 16,
'kernel_size': 3,
'rnn_units': 10,
'rnn_layers': 2,
'skip_rnn_units': 10,
'skip_rnn_layers': 2,
'skip_period': 3,
'ar_order': 3,
'learning_rate': 0.001,
'loss': 'mae',
'y_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0]
}
model = LSTNetWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
score_rmse = rmse(y_test, y_pred)
score_mape = mape(y_test, y_pred)
print('rmse:', score_rmse)
print('mape:', score_mape)
assert score_rmse >= 0
assert score_mape >= 0
def test_univariate_classification_lstnet():
X, y = load_arrow_head(return_X_y=True)
tb = get_tool_box(X)
X_train, X_test, y_train, y_test = tb.random_train_test_split(X, y, test_size=0.2)
task = consts.Task_UNIVARIATE_MULTICALSS
fit_kwargs = {
'epochs': 10,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'rnn_type': 'simple_rnn',
'rnn_units': 10,
'rnn_layers': 2,
'learning_rate': 0.001,
'x_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0],
}
model = HybirdRNNWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print('accuracy:', acc)
assert acc >= 0
def test_multivariate_classification_lstnet():
X, y = load_basic_motions(return_X_y=True)
tb = get_tool_box(X)
X_train, X_test, y_train, y_test = tb.random_train_test_split(X, y, test_size=0.2)
task = consts.Task_MULTIVARIATE_MULTICALSS
fit_kwargs = {
'epochs': 100,
'batch_size': 8,
}
init_kwargs = {
'task': task,
'rnn_type': 'lstm',
'skip_rnn_type': 'gru',
'cnn_filters': 16,
'kernel_size': 3,
'rnn_units': 10,
'rnn_layers': 2,
'skip_rnn_units': 10,
'skip_rnn_layers': 2,
'skip_period': 0,
'ar_order': 0,
'learning_rate': 0.001,
'x_scale': np.random.choice(['min_max', 'max_abs'], size=1)[0],
}
model = LSTNetWrapper(fit_kwargs, **init_kwargs)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print('accuracy:', acc)
assert acc >= 0 | 28.357303 | 97 | 0.56201 | 1,608 | 12,619 | 4.066542 | 0.075249 | 0.030586 | 0.023551 | 0.027527 | 0.934547 | 0.924759 | 0.922618 | 0.922618 | 0.922618 | 0.917266 | 0 | 0.023876 | 0.316269 | 12,619 | 445 | 98 | 28.357303 | 0.734006 | 0 | 0 | 0.845029 | 0 | 0 | 0.134311 | 0 | 0 | 0 | 0 | 0 | 0.052632 | 1 | 0.032164 | false | 0 | 0.020468 | 0 | 0.055556 | 0.052632 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
ef5fb5874d876cc60e67211834999066917cc779 | 46 | py | Python | utils/core/managers/__init__.py | rkisdp/rkisdp.django.backend | 771481cdeea6a101305c4819b06b839266ce6921 | [
"MIT"
] | null | null | null | utils/core/managers/__init__.py | rkisdp/rkisdp.django.backend | 771481cdeea6a101305c4819b06b839266ce6921 | [
"MIT"
] | null | null | null | utils/core/managers/__init__.py | rkisdp/rkisdp.django.backend | 771481cdeea6a101305c4819b06b839266ce6921 | [
"MIT"
] | null | null | null | from .timestampable import TimeStampableMixin
| 23 | 45 | 0.891304 | 4 | 46 | 10.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.086957 | 46 | 1 | 46 | 46 | 0.97619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
322a0695b1b432e64cb39b7f23af19fafd5f07c9 | 67,596 | py | Python | sdk/python/pulumi_oci/kms/outputs.py | EladGabay/pulumi-oci | 6841e27d4a1a7e15c672306b769912efbfd3ba99 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2021-08-17T11:14:46.000Z | 2021-12-31T02:07:03.000Z | sdk/python/pulumi_oci/kms/outputs.py | pulumi-oci/pulumi-oci | 6841e27d4a1a7e15c672306b769912efbfd3ba99 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-09-06T11:21:29.000Z | 2021-09-06T11:21:29.000Z | sdk/python/pulumi_oci/kms/outputs.py | pulumi-oci/pulumi-oci | 6841e27d4a1a7e15c672306b769912efbfd3ba99 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-08-24T23:31:30.000Z | 2022-01-02T19:26:54.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GeneratedKeyKeyShape',
'KeyKeyShape',
'KeyReplicaDetails',
'KeyRestoreFromFile',
'KeyRestoreFromObjectStore',
'KeyVersionReplicaDetails',
'VaultReplicaDetails',
'VaultRestoreFromFile',
'VaultRestoreFromObjectStore',
'GetKeyKeyShapeResult',
'GetKeyReplicaDetailsResult',
'GetKeyRestoreFromFileResult',
'GetKeyRestoreFromObjectStoreResult',
'GetKeyVersionReplicaDetailsResult',
'GetKeyVersionsFilterResult',
'GetKeyVersionsKeyVersionResult',
'GetKeyVersionsKeyVersionReplicaDetailsResult',
'GetKeysFilterResult',
'GetKeysKeyResult',
'GetKeysKeyKeyShapeResult',
'GetKeysKeyReplicaDetailsResult',
'GetKeysKeyRestoreFromFileResult',
'GetKeysKeyRestoreFromObjectStoreResult',
'GetReplicationStatusReplicaDetailResult',
'GetVaultReplicaDetailsResult',
'GetVaultReplicasFilterResult',
'GetVaultReplicasVaultReplicaResult',
'GetVaultRestoreFromFileResult',
'GetVaultRestoreFromObjectStoreResult',
'GetVaultsFilterResult',
'GetVaultsVaultResult',
'GetVaultsVaultReplicaDetailsResult',
'GetVaultsVaultRestoreFromFileResult',
'GetVaultsVaultRestoreFromObjectStoreResult',
]
@pulumi.output_type
class GeneratedKeyKeyShape(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "curveId":
suggest = "curve_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in GeneratedKeyKeyShape. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
GeneratedKeyKeyShape.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
GeneratedKeyKeyShape.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
algorithm: str,
length: int,
curve_id: Optional[str] = None):
"""
:param str algorithm: The algorithm used by a key's key versions to encrypt or decrypt.
:param int length: The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
:param str curve_id: Supported curve IDs for ECDSA keys.
"""
pulumi.set(__self__, "algorithm", algorithm)
pulumi.set(__self__, "length", length)
if curve_id is not None:
pulumi.set(__self__, "curve_id", curve_id)
@property
@pulumi.getter
def algorithm(self) -> str:
"""
The algorithm used by a key's key versions to encrypt or decrypt.
"""
return pulumi.get(self, "algorithm")
@property
@pulumi.getter
def length(self) -> int:
"""
The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
"""
return pulumi.get(self, "length")
@property
@pulumi.getter(name="curveId")
def curve_id(self) -> Optional[str]:
"""
Supported curve IDs for ECDSA keys.
"""
return pulumi.get(self, "curve_id")
@pulumi.output_type
class KeyKeyShape(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "curveId":
suggest = "curve_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in KeyKeyShape. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
KeyKeyShape.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
KeyKeyShape.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
algorithm: str,
length: int,
curve_id: Optional[str] = None):
"""
:param str algorithm: The algorithm used by a key's key versions to encrypt or decrypt.
:param int length: The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
:param str curve_id: Supported curve IDs for ECDSA keys.
"""
pulumi.set(__self__, "algorithm", algorithm)
pulumi.set(__self__, "length", length)
if curve_id is not None:
pulumi.set(__self__, "curve_id", curve_id)
@property
@pulumi.getter
def algorithm(self) -> str:
"""
The algorithm used by a key's key versions to encrypt or decrypt.
"""
return pulumi.get(self, "algorithm")
@property
@pulumi.getter
def length(self) -> int:
"""
The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
"""
return pulumi.get(self, "length")
@property
@pulumi.getter(name="curveId")
def curve_id(self) -> Optional[str]:
"""
Supported curve IDs for ECDSA keys.
"""
return pulumi.get(self, "curve_id")
@pulumi.output_type
class KeyReplicaDetails(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "replicationId":
suggest = "replication_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in KeyReplicaDetails. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
KeyReplicaDetails.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
KeyReplicaDetails.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
replication_id: Optional[str] = None):
"""
:param str replication_id: ReplicationId associated with a key operation
"""
if replication_id is not None:
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> Optional[str]:
"""
ReplicationId associated with a key operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class KeyRestoreFromFile(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "contentLength":
suggest = "content_length"
elif key == "restoreKeyFromFileDetails":
suggest = "restore_key_from_file_details"
elif key == "contentMd5":
suggest = "content_md5"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in KeyRestoreFromFile. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
KeyRestoreFromFile.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
KeyRestoreFromFile.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
content_length: str,
restore_key_from_file_details: str,
content_md5: Optional[str] = None):
"""
:param str content_length: (Updatable) content length of key's backup binary file
:param str restore_key_from_file_details: Key backup file content.
:param str content_md5: (Updatable) content md5 hashed value of key's backup file
"""
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "restore_key_from_file_details", restore_key_from_file_details)
if content_md5 is not None:
pulumi.set(__self__, "content_md5", content_md5)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
"""
(Updatable) content length of key's backup binary file
"""
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="restoreKeyFromFileDetails")
def restore_key_from_file_details(self) -> str:
"""
Key backup file content.
"""
return pulumi.get(self, "restore_key_from_file_details")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> Optional[str]:
"""
(Updatable) content md5 hashed value of key's backup file
"""
return pulumi.get(self, "content_md5")
@pulumi.output_type
class KeyRestoreFromObjectStore(dict):
def __init__(__self__, *,
destination: str,
bucket: Optional[str] = None,
namespace: Optional[str] = None,
object: Optional[str] = None,
uri: Optional[str] = None):
"""
:param str destination: (Updatable) Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
:param str bucket: (Updatable) Name of the bucket where key was backed up
:param str namespace: (Updatable) Namespace of the bucket where key was backed up
:param str object: (Updatable) Object containing the backup
:param str uri: (Updatable) Pre-authenticated-request-uri of the backup
"""
pulumi.set(__self__, "destination", destination)
if bucket is not None:
pulumi.set(__self__, "bucket", bucket)
if namespace is not None:
pulumi.set(__self__, "namespace", namespace)
if object is not None:
pulumi.set(__self__, "object", object)
if uri is not None:
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def destination(self) -> str:
"""
(Updatable) Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
"""
return pulumi.get(self, "destination")
@property
@pulumi.getter
def bucket(self) -> Optional[str]:
"""
(Updatable) Name of the bucket where key was backed up
"""
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def namespace(self) -> Optional[str]:
"""
(Updatable) Namespace of the bucket where key was backed up
"""
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> Optional[str]:
"""
(Updatable) Object containing the backup
"""
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> Optional[str]:
"""
(Updatable) Pre-authenticated-request-uri of the backup
"""
return pulumi.get(self, "uri")
@pulumi.output_type
class KeyVersionReplicaDetails(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "replicationId":
suggest = "replication_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in KeyVersionReplicaDetails. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
KeyVersionReplicaDetails.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
KeyVersionReplicaDetails.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
replication_id: Optional[str] = None):
"""
:param str replication_id: ReplicationId associated with a key version operation
"""
if replication_id is not None:
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> Optional[str]:
"""
ReplicationId associated with a key version operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class VaultReplicaDetails(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "replicationId":
suggest = "replication_id"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in VaultReplicaDetails. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
VaultReplicaDetails.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
VaultReplicaDetails.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
replication_id: Optional[str] = None):
"""
:param str replication_id: ReplicationId associated with a vault operation
"""
if replication_id is not None:
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> Optional[str]:
"""
ReplicationId associated with a vault operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class VaultRestoreFromFile(dict):
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "contentLength":
suggest = "content_length"
elif key == "restoreVaultFromFileDetails":
suggest = "restore_vault_from_file_details"
elif key == "contentMd5":
suggest = "content_md5"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in VaultRestoreFromFile. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
VaultRestoreFromFile.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
VaultRestoreFromFile.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
content_length: str,
restore_vault_from_file_details: str,
content_md5: Optional[str] = None):
"""
:param str content_length: content length of vault's backup binary file
:param str restore_vault_from_file_details: Vault backup file content
:param str content_md5: (Updatable) content md5 hashed value of vault's backup file
"""
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "restore_vault_from_file_details", restore_vault_from_file_details)
if content_md5 is not None:
pulumi.set(__self__, "content_md5", content_md5)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
"""
content length of vault's backup binary file
"""
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="restoreVaultFromFileDetails")
def restore_vault_from_file_details(self) -> str:
"""
Vault backup file content
"""
return pulumi.get(self, "restore_vault_from_file_details")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> Optional[str]:
"""
(Updatable) content md5 hashed value of vault's backup file
"""
return pulumi.get(self, "content_md5")
@pulumi.output_type
class VaultRestoreFromObjectStore(dict):
def __init__(__self__, *,
destination: str,
bucket: Optional[str] = None,
namespace: Optional[str] = None,
object: Optional[str] = None,
uri: Optional[str] = None):
"""
:param str destination: (Updatable) Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
:param str bucket: (Updatable) Name of the bucket where vault was backed up
:param str namespace: (Updatable) Namespace of the bucket where vault was backed up
:param str object: (Updatable) Object containing the backup
:param str uri: (Updatable) Pre-authenticated-request-uri of the backup* `restore_trigger` - (Optional) (Updatable) An optional property when flipped triggers restore from restore option provided in config file.
"""
pulumi.set(__self__, "destination", destination)
if bucket is not None:
pulumi.set(__self__, "bucket", bucket)
if namespace is not None:
pulumi.set(__self__, "namespace", namespace)
if object is not None:
pulumi.set(__self__, "object", object)
if uri is not None:
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def destination(self) -> str:
"""
(Updatable) Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
"""
return pulumi.get(self, "destination")
@property
@pulumi.getter
def bucket(self) -> Optional[str]:
"""
(Updatable) Name of the bucket where vault was backed up
"""
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def namespace(self) -> Optional[str]:
"""
(Updatable) Namespace of the bucket where vault was backed up
"""
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> Optional[str]:
"""
(Updatable) Object containing the backup
"""
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> Optional[str]:
"""
(Updatable) Pre-authenticated-request-uri of the backup* `restore_trigger` - (Optional) (Updatable) An optional property when flipped triggers restore from restore option provided in config file.
"""
return pulumi.get(self, "uri")
@pulumi.output_type
class GetKeyKeyShapeResult(dict):
def __init__(__self__, *,
algorithm: str,
curve_id: str,
length: int):
"""
:param str algorithm: The algorithm used by a key's key versions to encrypt or decrypt.
:param str curve_id: Supported curve IDs for ECDSA keys.
:param int length: The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
"""
pulumi.set(__self__, "algorithm", algorithm)
pulumi.set(__self__, "curve_id", curve_id)
pulumi.set(__self__, "length", length)
@property
@pulumi.getter
def algorithm(self) -> str:
"""
The algorithm used by a key's key versions to encrypt or decrypt.
"""
return pulumi.get(self, "algorithm")
@property
@pulumi.getter(name="curveId")
def curve_id(self) -> str:
"""
Supported curve IDs for ECDSA keys.
"""
return pulumi.get(self, "curve_id")
@property
@pulumi.getter
def length(self) -> int:
"""
The length of the key in bytes, expressed as an integer. Supported values include the following:
* AES: 16, 24, or 32
* RSA: 256, 384, or 512
* ECDSA: 32, 48, or 66
"""
return pulumi.get(self, "length")
@pulumi.output_type
class GetKeyReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a key operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a key operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetKeyRestoreFromFileResult(dict):
def __init__(__self__, *,
content_length: str,
content_md5: str,
restore_key_from_file_details: str):
"""
:param str content_length: content length of key's backup binary file
:param str content_md5: content md5 hashed value of key's backup file
:param str restore_key_from_file_details: Key backup file content
"""
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "content_md5", content_md5)
pulumi.set(__self__, "restore_key_from_file_details", restore_key_from_file_details)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
"""
content length of key's backup binary file
"""
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> str:
"""
content md5 hashed value of key's backup file
"""
return pulumi.get(self, "content_md5")
@property
@pulumi.getter(name="restoreKeyFromFileDetails")
def restore_key_from_file_details(self) -> str:
"""
Key backup file content
"""
return pulumi.get(self, "restore_key_from_file_details")
@pulumi.output_type
class GetKeyRestoreFromObjectStoreResult(dict):
def __init__(__self__, *,
bucket: str,
destination: str,
namespace: str,
object: str,
uri: str):
"""
:param str bucket: Name of the bucket where key was backed up
:param str destination: Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
:param str namespace: Namespace of the bucket where key was backed up
:param str object: Object containing the backup
:param str uri: Pre-authenticated-request-uri of the backup
"""
pulumi.set(__self__, "bucket", bucket)
pulumi.set(__self__, "destination", destination)
pulumi.set(__self__, "namespace", namespace)
pulumi.set(__self__, "object", object)
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def bucket(self) -> str:
"""
Name of the bucket where key was backed up
"""
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def destination(self) -> str:
"""
Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
"""
return pulumi.get(self, "destination")
@property
@pulumi.getter
def namespace(self) -> str:
"""
Namespace of the bucket where key was backed up
"""
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> str:
"""
Object containing the backup
"""
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> str:
"""
Pre-authenticated-request-uri of the backup
"""
return pulumi.get(self, "uri")
@pulumi.output_type
class GetKeyVersionReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a key version operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a key version operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetKeyVersionsFilterResult(dict):
def __init__(__self__, *,
name: str,
values: Sequence[str],
regex: Optional[bool] = None):
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "values", values)
if regex is not None:
pulumi.set(__self__, "regex", regex)
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def values(self) -> Sequence[str]:
return pulumi.get(self, "values")
@property
@pulumi.getter
def regex(self) -> Optional[bool]:
return pulumi.get(self, "regex")
@pulumi.output_type
class GetKeyVersionsKeyVersionResult(dict):
def __init__(__self__, *,
compartment_id: str,
id: str,
is_primary: bool,
key_id: str,
key_version_id: str,
management_endpoint: str,
public_key: str,
replica_details: 'outputs.GetKeyVersionsKeyVersionReplicaDetailsResult',
restored_from_key_id: str,
restored_from_key_version_id: str,
state: str,
time_created: str,
time_of_deletion: str,
vault_id: str):
"""
:param str compartment_id: The OCID of the compartment that contains this key version.
:param str id: The OCID of the key version.
:param bool is_primary: A boolean that will be true when key version is primary, and will be false when key version is a replica from a primary key version.
:param str key_id: The OCID of the key.
:param str key_version_id: The OCID of the key version.
:param str management_endpoint: The service endpoint to perform management operations against. Management operations include 'Create,' 'Update,' 'List,' 'Get,' and 'Delete' operations. See Vault Management endpoint.
:param str public_key: The public key in PEM format. (This value pertains only to RSA and ECDSA keys.)
:param 'GetKeyVersionsKeyVersionReplicaDetailsArgs' replica_details: KeyVersion replica details
:param str restored_from_key_version_id: The OCID of the key version from which this key version was restored.
:param str state: The key version's current lifecycle state. Example: `ENABLED`
:param str time_created: The date and time this key version was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: "2018-04-03T21:10:29.600Z"
:param str time_of_deletion: An optional property to indicate when to delete the key version, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2019-04-03T21:10:29.600Z`
:param str vault_id: The OCID of the vault that contains this key version.
"""
pulumi.set(__self__, "compartment_id", compartment_id)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "is_primary", is_primary)
pulumi.set(__self__, "key_id", key_id)
pulumi.set(__self__, "key_version_id", key_version_id)
pulumi.set(__self__, "management_endpoint", management_endpoint)
pulumi.set(__self__, "public_key", public_key)
pulumi.set(__self__, "replica_details", replica_details)
pulumi.set(__self__, "restored_from_key_id", restored_from_key_id)
pulumi.set(__self__, "restored_from_key_version_id", restored_from_key_version_id)
pulumi.set(__self__, "state", state)
pulumi.set(__self__, "time_created", time_created)
pulumi.set(__self__, "time_of_deletion", time_of_deletion)
pulumi.set(__self__, "vault_id", vault_id)
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The OCID of the compartment that contains this key version.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter
def id(self) -> str:
"""
The OCID of the key version.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="isPrimary")
def is_primary(self) -> bool:
"""
A boolean that will be true when key version is primary, and will be false when key version is a replica from a primary key version.
"""
return pulumi.get(self, "is_primary")
@property
@pulumi.getter(name="keyId")
def key_id(self) -> str:
"""
The OCID of the key.
"""
return pulumi.get(self, "key_id")
@property
@pulumi.getter(name="keyVersionId")
def key_version_id(self) -> str:
"""
The OCID of the key version.
"""
return pulumi.get(self, "key_version_id")
@property
@pulumi.getter(name="managementEndpoint")
def management_endpoint(self) -> str:
"""
The service endpoint to perform management operations against. Management operations include 'Create,' 'Update,' 'List,' 'Get,' and 'Delete' operations. See Vault Management endpoint.
"""
return pulumi.get(self, "management_endpoint")
@property
@pulumi.getter(name="publicKey")
def public_key(self) -> str:
"""
The public key in PEM format. (This value pertains only to RSA and ECDSA keys.)
"""
return pulumi.get(self, "public_key")
@property
@pulumi.getter(name="replicaDetails")
def replica_details(self) -> 'outputs.GetKeyVersionsKeyVersionReplicaDetailsResult':
"""
KeyVersion replica details
"""
return pulumi.get(self, "replica_details")
@property
@pulumi.getter(name="restoredFromKeyId")
def restored_from_key_id(self) -> str:
return pulumi.get(self, "restored_from_key_id")
@property
@pulumi.getter(name="restoredFromKeyVersionId")
def restored_from_key_version_id(self) -> str:
"""
The OCID of the key version from which this key version was restored.
"""
return pulumi.get(self, "restored_from_key_version_id")
@property
@pulumi.getter
def state(self) -> str:
"""
The key version's current lifecycle state. Example: `ENABLED`
"""
return pulumi.get(self, "state")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time this key version was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: "2018-04-03T21:10:29.600Z"
"""
return pulumi.get(self, "time_created")
@property
@pulumi.getter(name="timeOfDeletion")
def time_of_deletion(self) -> str:
"""
An optional property to indicate when to delete the key version, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2019-04-03T21:10:29.600Z`
"""
return pulumi.get(self, "time_of_deletion")
@property
@pulumi.getter(name="vaultId")
def vault_id(self) -> str:
"""
The OCID of the vault that contains this key version.
"""
return pulumi.get(self, "vault_id")
@pulumi.output_type
class GetKeyVersionsKeyVersionReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a key version operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a key version operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetKeysFilterResult(dict):
def __init__(__self__, *,
name: str,
values: Sequence[str],
regex: Optional[bool] = None):
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "values", values)
if regex is not None:
pulumi.set(__self__, "regex", regex)
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def values(self) -> Sequence[str]:
return pulumi.get(self, "values")
@property
@pulumi.getter
def regex(self) -> Optional[bool]:
return pulumi.get(self, "regex")
@pulumi.output_type
class GetKeysKeyResult(dict):
def __init__(__self__, *,
compartment_id: str,
current_key_version: str,
defined_tags: Mapping[str, Any],
desired_state: str,
display_name: str,
freeform_tags: Mapping[str, Any],
id: str,
is_primary: bool,
key_shape: 'outputs.GetKeysKeyKeyShapeResult',
management_endpoint: str,
protection_mode: str,
replica_details: 'outputs.GetKeysKeyReplicaDetailsResult',
restore_from_file: 'outputs.GetKeysKeyRestoreFromFileResult',
restore_from_object_store: 'outputs.GetKeysKeyRestoreFromObjectStoreResult',
restore_trigger: bool,
restored_from_key_id: str,
state: str,
time_created: str,
time_of_deletion: str,
vault_id: str):
"""
:param str compartment_id: The OCID of the compartment.
:param str current_key_version: The OCID of the key version used in cryptographic operations. During key rotation, the service might be in a transitional state where this or a newer key version are used intermittently. The `currentKeyVersion` property is updated when the service is guaranteed to use the new key version for all subsequent encryption operations.
:param Mapping[str, Any] defined_tags: Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
:param str display_name: A user-friendly name for the key. It does not have to be unique, and it is changeable. Avoid entering confidential information.
:param Mapping[str, Any] freeform_tags: Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
:param str id: The OCID of the key.
:param bool is_primary: A boolean that will be true when key is primary, and will be false when key is a replica from a primary key.
:param 'GetKeysKeyKeyShapeArgs' key_shape: The cryptographic properties of a key.
:param str management_endpoint: The service endpoint to perform management operations against. Management operations include 'Create,' 'Update,' 'List,' 'Get,' and 'Delete' operations. See Vault Management endpoint.
:param str protection_mode: A key's protection mode indicates how the key persists and where cryptographic operations that use the key are performed. A protection mode of `HSM` means that the key persists on a hardware security module (HSM) and all cryptographic operations are performed inside the HSM. A protection mode of `SOFTWARE` means that the key persists on the server, protected by the vault's RSA wrapping key which persists on the HSM. All cryptographic operations that use a key with a protection mode of `SOFTWARE` are performed on the server.
:param 'GetKeysKeyReplicaDetailsArgs' replica_details: Key replica details
:param str state: The key's current lifecycle state. Example: `ENABLED`
:param str time_created: The date and time the key was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
:param str time_of_deletion: An optional property indicating when to delete the key, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2019-04-03T21:10:29.600Z`
:param str vault_id: The OCID of the vault that contains this key.
"""
pulumi.set(__self__, "compartment_id", compartment_id)
pulumi.set(__self__, "current_key_version", current_key_version)
pulumi.set(__self__, "defined_tags", defined_tags)
pulumi.set(__self__, "desired_state", desired_state)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "freeform_tags", freeform_tags)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "is_primary", is_primary)
pulumi.set(__self__, "key_shape", key_shape)
pulumi.set(__self__, "management_endpoint", management_endpoint)
pulumi.set(__self__, "protection_mode", protection_mode)
pulumi.set(__self__, "replica_details", replica_details)
pulumi.set(__self__, "restore_from_file", restore_from_file)
pulumi.set(__self__, "restore_from_object_store", restore_from_object_store)
pulumi.set(__self__, "restore_trigger", restore_trigger)
pulumi.set(__self__, "restored_from_key_id", restored_from_key_id)
pulumi.set(__self__, "state", state)
pulumi.set(__self__, "time_created", time_created)
pulumi.set(__self__, "time_of_deletion", time_of_deletion)
pulumi.set(__self__, "vault_id", vault_id)
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The OCID of the compartment.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter(name="currentKeyVersion")
def current_key_version(self) -> str:
"""
The OCID of the key version used in cryptographic operations. During key rotation, the service might be in a transitional state where this or a newer key version are used intermittently. The `currentKeyVersion` property is updated when the service is guaranteed to use the new key version for all subsequent encryption operations.
"""
return pulumi.get(self, "current_key_version")
@property
@pulumi.getter(name="definedTags")
def defined_tags(self) -> Mapping[str, Any]:
"""
Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
"""
return pulumi.get(self, "defined_tags")
@property
@pulumi.getter(name="desiredState")
def desired_state(self) -> str:
return pulumi.get(self, "desired_state")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
A user-friendly name for the key. It does not have to be unique, and it is changeable. Avoid entering confidential information.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="freeformTags")
def freeform_tags(self) -> Mapping[str, Any]:
"""
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
"""
return pulumi.get(self, "freeform_tags")
@property
@pulumi.getter
def id(self) -> str:
"""
The OCID of the key.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="isPrimary")
def is_primary(self) -> bool:
"""
A boolean that will be true when key is primary, and will be false when key is a replica from a primary key.
"""
return pulumi.get(self, "is_primary")
@property
@pulumi.getter(name="keyShape")
def key_shape(self) -> 'outputs.GetKeysKeyKeyShapeResult':
"""
The cryptographic properties of a key.
"""
return pulumi.get(self, "key_shape")
@property
@pulumi.getter(name="managementEndpoint")
def management_endpoint(self) -> str:
"""
The service endpoint to perform management operations against. Management operations include 'Create,' 'Update,' 'List,' 'Get,' and 'Delete' operations. See Vault Management endpoint.
"""
return pulumi.get(self, "management_endpoint")
@property
@pulumi.getter(name="protectionMode")
def protection_mode(self) -> str:
"""
A key's protection mode indicates how the key persists and where cryptographic operations that use the key are performed. A protection mode of `HSM` means that the key persists on a hardware security module (HSM) and all cryptographic operations are performed inside the HSM. A protection mode of `SOFTWARE` means that the key persists on the server, protected by the vault's RSA wrapping key which persists on the HSM. All cryptographic operations that use a key with a protection mode of `SOFTWARE` are performed on the server.
"""
return pulumi.get(self, "protection_mode")
@property
@pulumi.getter(name="replicaDetails")
def replica_details(self) -> 'outputs.GetKeysKeyReplicaDetailsResult':
"""
Key replica details
"""
return pulumi.get(self, "replica_details")
@property
@pulumi.getter(name="restoreFromFile")
def restore_from_file(self) -> 'outputs.GetKeysKeyRestoreFromFileResult':
return pulumi.get(self, "restore_from_file")
@property
@pulumi.getter(name="restoreFromObjectStore")
def restore_from_object_store(self) -> 'outputs.GetKeysKeyRestoreFromObjectStoreResult':
return pulumi.get(self, "restore_from_object_store")
@property
@pulumi.getter(name="restoreTrigger")
def restore_trigger(self) -> bool:
return pulumi.get(self, "restore_trigger")
@property
@pulumi.getter(name="restoredFromKeyId")
def restored_from_key_id(self) -> str:
return pulumi.get(self, "restored_from_key_id")
@property
@pulumi.getter
def state(self) -> str:
"""
The key's current lifecycle state. Example: `ENABLED`
"""
return pulumi.get(self, "state")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time the key was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
"""
return pulumi.get(self, "time_created")
@property
@pulumi.getter(name="timeOfDeletion")
def time_of_deletion(self) -> str:
"""
An optional property indicating when to delete the key, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2019-04-03T21:10:29.600Z`
"""
return pulumi.get(self, "time_of_deletion")
@property
@pulumi.getter(name="vaultId")
def vault_id(self) -> str:
"""
The OCID of the vault that contains this key.
"""
return pulumi.get(self, "vault_id")
@pulumi.output_type
class GetKeysKeyKeyShapeResult(dict):
def __init__(__self__, *,
algorithm: str,
curve_id: str,
length: int):
"""
:param str algorithm: The algorithm used by a key's key versions to encrypt or decrypt data. Currently, support includes AES, RSA, and ECDSA algorithms.
:param str curve_id: The curve ID of the keys. (This pertains only to ECDSA keys.)
:param int length: The length of the key in bytes, expressed as an integer. Supported values include 16, 24, or 32.
"""
pulumi.set(__self__, "algorithm", algorithm)
pulumi.set(__self__, "curve_id", curve_id)
pulumi.set(__self__, "length", length)
@property
@pulumi.getter
def algorithm(self) -> str:
"""
The algorithm used by a key's key versions to encrypt or decrypt data. Currently, support includes AES, RSA, and ECDSA algorithms.
"""
return pulumi.get(self, "algorithm")
@property
@pulumi.getter(name="curveId")
def curve_id(self) -> str:
"""
The curve ID of the keys. (This pertains only to ECDSA keys.)
"""
return pulumi.get(self, "curve_id")
@property
@pulumi.getter
def length(self) -> int:
"""
The length of the key in bytes, expressed as an integer. Supported values include 16, 24, or 32.
"""
return pulumi.get(self, "length")
@pulumi.output_type
class GetKeysKeyReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a key operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a key operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetKeysKeyRestoreFromFileResult(dict):
def __init__(__self__, *,
content_length: str,
content_md5: str,
restore_key_from_file_details: str):
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "content_md5", content_md5)
pulumi.set(__self__, "restore_key_from_file_details", restore_key_from_file_details)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> str:
return pulumi.get(self, "content_md5")
@property
@pulumi.getter(name="restoreKeyFromFileDetails")
def restore_key_from_file_details(self) -> str:
return pulumi.get(self, "restore_key_from_file_details")
@pulumi.output_type
class GetKeysKeyRestoreFromObjectStoreResult(dict):
def __init__(__self__, *,
bucket: str,
destination: str,
namespace: str,
object: str,
uri: str):
pulumi.set(__self__, "bucket", bucket)
pulumi.set(__self__, "destination", destination)
pulumi.set(__self__, "namespace", namespace)
pulumi.set(__self__, "object", object)
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def bucket(self) -> str:
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def destination(self) -> str:
return pulumi.get(self, "destination")
@property
@pulumi.getter
def namespace(self) -> str:
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> str:
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> str:
return pulumi.get(self, "uri")
@pulumi.output_type
class GetReplicationStatusReplicaDetailResult(dict):
def __init__(__self__, *,
region: str,
status: str):
"""
:param str region: The replica region
:param str status: Replication status associated with a replicationId
"""
pulumi.set(__self__, "region", region)
pulumi.set(__self__, "status", status)
@property
@pulumi.getter
def region(self) -> str:
"""
The replica region
"""
return pulumi.get(self, "region")
@property
@pulumi.getter
def status(self) -> str:
"""
Replication status associated with a replicationId
"""
return pulumi.get(self, "status")
@pulumi.output_type
class GetVaultReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a vault operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a vault operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetVaultReplicasFilterResult(dict):
def __init__(__self__, *,
name: str,
values: Sequence[str],
regex: Optional[bool] = None):
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "values", values)
if regex is not None:
pulumi.set(__self__, "regex", regex)
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def values(self) -> Sequence[str]:
return pulumi.get(self, "values")
@property
@pulumi.getter
def regex(self) -> Optional[bool]:
return pulumi.get(self, "regex")
@pulumi.output_type
class GetVaultReplicasVaultReplicaResult(dict):
def __init__(__self__, *,
crypto_endpoint: str,
management_endpoint: str,
region: str,
status: str):
"""
:param str crypto_endpoint: The vault replica's crypto endpoint
:param str management_endpoint: The vault replica's management endpoint
:param str region: Region to which vault is replicated to
:param str status: The vault replica's status
"""
pulumi.set(__self__, "crypto_endpoint", crypto_endpoint)
pulumi.set(__self__, "management_endpoint", management_endpoint)
pulumi.set(__self__, "region", region)
pulumi.set(__self__, "status", status)
@property
@pulumi.getter(name="cryptoEndpoint")
def crypto_endpoint(self) -> str:
"""
The vault replica's crypto endpoint
"""
return pulumi.get(self, "crypto_endpoint")
@property
@pulumi.getter(name="managementEndpoint")
def management_endpoint(self) -> str:
"""
The vault replica's management endpoint
"""
return pulumi.get(self, "management_endpoint")
@property
@pulumi.getter
def region(self) -> str:
"""
Region to which vault is replicated to
"""
return pulumi.get(self, "region")
@property
@pulumi.getter
def status(self) -> str:
"""
The vault replica's status
"""
return pulumi.get(self, "status")
@pulumi.output_type
class GetVaultRestoreFromFileResult(dict):
def __init__(__self__, *,
content_length: str,
content_md5: str,
restore_vault_from_file_details: str):
"""
:param str content_length: content length of vault's backup binary file
:param str content_md5: content md5 hashed value of vault's backup file
:param str restore_vault_from_file_details: Vault backup file content
"""
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "content_md5", content_md5)
pulumi.set(__self__, "restore_vault_from_file_details", restore_vault_from_file_details)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
"""
content length of vault's backup binary file
"""
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> str:
"""
content md5 hashed value of vault's backup file
"""
return pulumi.get(self, "content_md5")
@property
@pulumi.getter(name="restoreVaultFromFileDetails")
def restore_vault_from_file_details(self) -> str:
"""
Vault backup file content
"""
return pulumi.get(self, "restore_vault_from_file_details")
@pulumi.output_type
class GetVaultRestoreFromObjectStoreResult(dict):
def __init__(__self__, *,
bucket: str,
destination: str,
namespace: str,
object: str,
uri: str):
"""
:param str bucket: Name of the bucket where vault was backed up
:param str destination: Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
:param str namespace: Namespace of the bucket where vault was backed up
:param str object: Object containing the backup
:param str uri: Pre-authenticated-request-uri of the backup
"""
pulumi.set(__self__, "bucket", bucket)
pulumi.set(__self__, "destination", destination)
pulumi.set(__self__, "namespace", namespace)
pulumi.set(__self__, "object", object)
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def bucket(self) -> str:
"""
Name of the bucket where vault was backed up
"""
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def destination(self) -> str:
"""
Type of backup to restore from. Values of "BUCKET", "PRE_AUTHENTICATED_REQUEST_URI" are supported
"""
return pulumi.get(self, "destination")
@property
@pulumi.getter
def namespace(self) -> str:
"""
Namespace of the bucket where vault was backed up
"""
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> str:
"""
Object containing the backup
"""
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> str:
"""
Pre-authenticated-request-uri of the backup
"""
return pulumi.get(self, "uri")
@pulumi.output_type
class GetVaultsFilterResult(dict):
def __init__(__self__, *,
name: str,
values: Sequence[str],
regex: Optional[bool] = None):
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "values", values)
if regex is not None:
pulumi.set(__self__, "regex", regex)
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def values(self) -> Sequence[str]:
return pulumi.get(self, "values")
@property
@pulumi.getter
def regex(self) -> Optional[bool]:
return pulumi.get(self, "regex")
@pulumi.output_type
class GetVaultsVaultResult(dict):
def __init__(__self__, *,
compartment_id: str,
crypto_endpoint: str,
defined_tags: Mapping[str, Any],
display_name: str,
freeform_tags: Mapping[str, Any],
id: str,
is_primary: bool,
management_endpoint: str,
replica_details: 'outputs.GetVaultsVaultReplicaDetailsResult',
restore_from_file: 'outputs.GetVaultsVaultRestoreFromFileResult',
restore_from_object_store: 'outputs.GetVaultsVaultRestoreFromObjectStoreResult',
restore_trigger: bool,
restored_from_vault_id: str,
state: str,
time_created: str,
time_of_deletion: str,
vault_type: str):
"""
:param str compartment_id: The OCID of the compartment.
:param str crypto_endpoint: The service endpoint to perform cryptographic operations against. Cryptographic operations include [Encrypt](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/EncryptedData/Encrypt), [Decrypt](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/DecryptedData/Decrypt), and [GenerateDataEncryptionKey](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/GeneratedKey/GenerateDataEncryptionKey) operations.
:param Mapping[str, Any] defined_tags: Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
:param str display_name: A user-friendly name for the vault. It does not have to be unique, and it is changeable. Avoid entering confidential information.
:param Mapping[str, Any] freeform_tags: Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
:param str id: The OCID of the vault.
:param bool is_primary: A boolean that will be true when vault is primary, and will be false when vault is a replica from a primary vault.
:param str management_endpoint: The service endpoint to perform management operations against. Management operations include "Create," "Update," "List," "Get," and "Delete" operations.
:param 'GetVaultsVaultReplicaDetailsArgs' replica_details: Vault replica details
:param str restored_from_vault_id: The OCID of the vault from which this vault was restored, if it was restored from a backup file. If you restore a vault to the same region, the vault retains the same OCID that it had when you backed up the vault.
:param str state: The vault's current lifecycle state. Example: `DELETED`
:param str time_created: The date and time this vault was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
:param str time_of_deletion: An optional property to indicate when to delete the vault, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
:param str vault_type: The type of vault. Each type of vault stores the key with different degrees of isolation and has different options and pricing.
"""
pulumi.set(__self__, "compartment_id", compartment_id)
pulumi.set(__self__, "crypto_endpoint", crypto_endpoint)
pulumi.set(__self__, "defined_tags", defined_tags)
pulumi.set(__self__, "display_name", display_name)
pulumi.set(__self__, "freeform_tags", freeform_tags)
pulumi.set(__self__, "id", id)
pulumi.set(__self__, "is_primary", is_primary)
pulumi.set(__self__, "management_endpoint", management_endpoint)
pulumi.set(__self__, "replica_details", replica_details)
pulumi.set(__self__, "restore_from_file", restore_from_file)
pulumi.set(__self__, "restore_from_object_store", restore_from_object_store)
pulumi.set(__self__, "restore_trigger", restore_trigger)
pulumi.set(__self__, "restored_from_vault_id", restored_from_vault_id)
pulumi.set(__self__, "state", state)
pulumi.set(__self__, "time_created", time_created)
pulumi.set(__self__, "time_of_deletion", time_of_deletion)
pulumi.set(__self__, "vault_type", vault_type)
@property
@pulumi.getter(name="compartmentId")
def compartment_id(self) -> str:
"""
The OCID of the compartment.
"""
return pulumi.get(self, "compartment_id")
@property
@pulumi.getter(name="cryptoEndpoint")
def crypto_endpoint(self) -> str:
"""
The service endpoint to perform cryptographic operations against. Cryptographic operations include [Encrypt](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/EncryptedData/Encrypt), [Decrypt](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/DecryptedData/Decrypt), and [GenerateDataEncryptionKey](https://docs.cloud.oracle.com/iaas/api/#/en/key/latest/GeneratedKey/GenerateDataEncryptionKey) operations.
"""
return pulumi.get(self, "crypto_endpoint")
@property
@pulumi.getter(name="definedTags")
def defined_tags(self) -> Mapping[str, Any]:
"""
Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
"""
return pulumi.get(self, "defined_tags")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
A user-friendly name for the vault. It does not have to be unique, and it is changeable. Avoid entering confidential information.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter(name="freeformTags")
def freeform_tags(self) -> Mapping[str, Any]:
"""
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
"""
return pulumi.get(self, "freeform_tags")
@property
@pulumi.getter
def id(self) -> str:
"""
The OCID of the vault.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="isPrimary")
def is_primary(self) -> bool:
"""
A boolean that will be true when vault is primary, and will be false when vault is a replica from a primary vault.
"""
return pulumi.get(self, "is_primary")
@property
@pulumi.getter(name="managementEndpoint")
def management_endpoint(self) -> str:
"""
The service endpoint to perform management operations against. Management operations include "Create," "Update," "List," "Get," and "Delete" operations.
"""
return pulumi.get(self, "management_endpoint")
@property
@pulumi.getter(name="replicaDetails")
def replica_details(self) -> 'outputs.GetVaultsVaultReplicaDetailsResult':
"""
Vault replica details
"""
return pulumi.get(self, "replica_details")
@property
@pulumi.getter(name="restoreFromFile")
def restore_from_file(self) -> 'outputs.GetVaultsVaultRestoreFromFileResult':
return pulumi.get(self, "restore_from_file")
@property
@pulumi.getter(name="restoreFromObjectStore")
def restore_from_object_store(self) -> 'outputs.GetVaultsVaultRestoreFromObjectStoreResult':
return pulumi.get(self, "restore_from_object_store")
@property
@pulumi.getter(name="restoreTrigger")
def restore_trigger(self) -> bool:
return pulumi.get(self, "restore_trigger")
@property
@pulumi.getter(name="restoredFromVaultId")
def restored_from_vault_id(self) -> str:
"""
The OCID of the vault from which this vault was restored, if it was restored from a backup file. If you restore a vault to the same region, the vault retains the same OCID that it had when you backed up the vault.
"""
return pulumi.get(self, "restored_from_vault_id")
@property
@pulumi.getter
def state(self) -> str:
"""
The vault's current lifecycle state. Example: `DELETED`
"""
return pulumi.get(self, "state")
@property
@pulumi.getter(name="timeCreated")
def time_created(self) -> str:
"""
The date and time this vault was created, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
"""
return pulumi.get(self, "time_created")
@property
@pulumi.getter(name="timeOfDeletion")
def time_of_deletion(self) -> str:
"""
An optional property to indicate when to delete the vault, expressed in [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format. Example: `2018-04-03T21:10:29.600Z`
"""
return pulumi.get(self, "time_of_deletion")
@property
@pulumi.getter(name="vaultType")
def vault_type(self) -> str:
"""
The type of vault. Each type of vault stores the key with different degrees of isolation and has different options and pricing.
"""
return pulumi.get(self, "vault_type")
@pulumi.output_type
class GetVaultsVaultReplicaDetailsResult(dict):
def __init__(__self__, *,
replication_id: str):
"""
:param str replication_id: ReplicationId associated with a vault operation
"""
pulumi.set(__self__, "replication_id", replication_id)
@property
@pulumi.getter(name="replicationId")
def replication_id(self) -> str:
"""
ReplicationId associated with a vault operation
"""
return pulumi.get(self, "replication_id")
@pulumi.output_type
class GetVaultsVaultRestoreFromFileResult(dict):
def __init__(__self__, *,
content_length: str,
content_md5: str,
restore_vault_from_file_details: str):
pulumi.set(__self__, "content_length", content_length)
pulumi.set(__self__, "content_md5", content_md5)
pulumi.set(__self__, "restore_vault_from_file_details", restore_vault_from_file_details)
@property
@pulumi.getter(name="contentLength")
def content_length(self) -> str:
return pulumi.get(self, "content_length")
@property
@pulumi.getter(name="contentMd5")
def content_md5(self) -> str:
return pulumi.get(self, "content_md5")
@property
@pulumi.getter(name="restoreVaultFromFileDetails")
def restore_vault_from_file_details(self) -> str:
return pulumi.get(self, "restore_vault_from_file_details")
@pulumi.output_type
class GetVaultsVaultRestoreFromObjectStoreResult(dict):
def __init__(__self__, *,
bucket: str,
destination: str,
namespace: str,
object: str,
uri: str):
pulumi.set(__self__, "bucket", bucket)
pulumi.set(__self__, "destination", destination)
pulumi.set(__self__, "namespace", namespace)
pulumi.set(__self__, "object", object)
pulumi.set(__self__, "uri", uri)
@property
@pulumi.getter
def bucket(self) -> str:
return pulumi.get(self, "bucket")
@property
@pulumi.getter
def destination(self) -> str:
return pulumi.get(self, "destination")
@property
@pulumi.getter
def namespace(self) -> str:
return pulumi.get(self, "namespace")
@property
@pulumi.getter
def object(self) -> str:
return pulumi.get(self, "object")
@property
@pulumi.getter
def uri(self) -> str:
return pulumi.get(self, "uri")
| 37.449307 | 569 | 0.639431 | 7,786 | 67,596 | 5.333419 | 0.048035 | 0.024443 | 0.043202 | 0.063141 | 0.899485 | 0.890526 | 0.874151 | 0.861051 | 0.857607 | 0.847156 | 0 | 0.009997 | 0.258595 | 67,596 | 1,804 | 570 | 37.470067 | 0.818601 | 0.313095 | 0 | 0.859633 | 1 | 0.006422 | 0.16047 | 0.055938 | 0 | 0 | 0 | 0 | 0 | 1 | 0.177064 | false | 0 | 0.005505 | 0.033945 | 0.353211 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
322d38e67571d1d5dd6dd7e9678f8116a1532285 | 140 | py | Python | django_xfields/db/models/__init__.py | leviplj/django_xfields | 6108173f1d24b71b69bd1634f411b0ad5383f948 | [
"MIT"
] | null | null | null | django_xfields/db/models/__init__.py | leviplj/django_xfields | 6108173f1d24b71b69bd1634f411b0ad5383f948 | [
"MIT"
] | null | null | null | django_xfields/db/models/__init__.py | leviplj/django_xfields | 6108173f1d24b71b69bd1634f411b0ad5383f948 | [
"MIT"
] | null | null | null | from django_xfields.db.models.fields import * # NOQA
from django_xfields.db.models.fields import __all__ as fields_all
__all__ = fields_all | 35 | 65 | 0.828571 | 22 | 140 | 4.727273 | 0.454545 | 0.192308 | 0.326923 | 0.365385 | 0.711538 | 0.711538 | 0.711538 | 0 | 0 | 0 | 0 | 0 | 0.107143 | 140 | 4 | 66 | 35 | 0.832 | 0.028571 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.666667 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 7 |
327d4152ab6a08db250396cb66e5e10696cd0176 | 4,076 | py | Python | website/apps/website/models.py | stahlnow/paulhaller | ccdfd59aa87b1e8bb9111066ae9c939d0871bb22 | [
"MIT"
] | null | null | null | website/apps/website/models.py | stahlnow/paulhaller | ccdfd59aa87b1e8bb9111066ae9c939d0871bb22 | [
"MIT"
] | 8 | 2020-02-12T00:08:09.000Z | 2022-03-11T23:17:48.000Z | website/apps/website/models.py | stahlnow/paulhaller | ccdfd59aa87b1e8bb9111066ae9c939d0871bb22 | [
"MIT"
] | null | null | null | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.utils.timezone import now
# from website.managers import PublicManager
from ckeditor.fields import RichTextField
class Post(models.Model):
"""Post model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User)
body = RichTextField(_('body'), )
status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
# objects = PublicManager()
class Meta:
verbose_name = _('post')
verbose_name_plural = _('posts')
db_table = 'website_posts'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
@models.permalink
def get_absolute_url(self):
return 'post_detail', (), {'slug': self.slug}
# def get_previous_post(self):
# return self.get_previous_by_publish(status__gte=2)
#
# def get_next_post(self):
# return self.get_next_by_publish(status__gte=2)
class Poem(models.Model):
"""Poem model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User)
body = RichTextField(_('body'), )
status = models.IntegerField(_('status'),choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
# objects = PublicManager()
class Meta:
verbose_name = _('poem')
verbose_name_plural = _('poems')
db_table = 'website_poems'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
@models.permalink
def get_absolute_url(self):
return 'poem_detail', (), {'slug': self.slug}
# def get_previous_post(self):
# return self.get_previous_by_publish(status__gte=2)
#
# def get_next_post(self):
# return self.get_next_by_publish(status__gte=2)
class Letter(models.Model):
"""Letter model."""
STATUS_CHOICES = (
(1, _('Draft')),
(2, _('Public')),
)
title = models.CharField(_('title'), max_length=200)
slug = models.SlugField(_('slug'), unique_for_date='publish')
author = models.ForeignKey(User)
body = RichTextField(_('body'), )
status = models.IntegerField(_('status'),choices=STATUS_CHOICES, default=2)
allow_comments = models.BooleanField(_('allow comments'), default=True)
publish = models.DateTimeField(_('publish'), default=now)
created = models.DateTimeField(_('created'), auto_now_add=True)
modified = models.DateTimeField(_('modified'), auto_now=True)
# objects = PublicManager()
class Meta:
verbose_name = _('letter')
verbose_name_plural = _('letters')
db_table = 'website_letters'
ordering = ('-publish',)
get_latest_by = 'publish'
def __unicode__(self):
return u'%s' % self.title
@models.permalink
def get_absolute_url(self):
return 'letter_detail', (), {'slug': self.slug}
# def get_previous_post(self):
# return self.get_previous_by_publish(status__gte=2)
#
# def get_next_post(self):
# return self.get_next_by_publish(status__gte=2)
| 31.596899 | 80 | 0.651374 | 462 | 4,076 | 5.424242 | 0.179654 | 0.047885 | 0.03352 | 0.043097 | 0.826417 | 0.826417 | 0.826417 | 0.826417 | 0.826417 | 0.826417 | 0 | 0.00743 | 0.207556 | 4,076 | 128 | 81 | 31.84375 | 0.768421 | 0.156771 | 0 | 0.7125 | 0 | 0 | 0.114311 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.075 | false | 0 | 0.0625 | 0.075 | 0.6625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
0882ec7658c71ba6669d64071add47fa7c53faa7 | 40 | py | Python | src/convert2snn.py | EtienneMueller/Convert2SNN | 6d97fc8953e85e2391586d58a521239440d508ba | [
"MIT"
] | 1 | 2021-12-27T14:52:38.000Z | 2021-12-27T14:52:38.000Z | src/convert2snn.py | EtienneMueller/Convert2SNN | 6d97fc8953e85e2391586d58a521239440d508ba | [
"MIT"
] | null | null | null | src/convert2snn.py | EtienneMueller/Convert2SNN | 6d97fc8953e85e2391586d58a521239440d508ba | [
"MIT"
] | null | null | null | def convert():
return "placeholder"
| 13.333333 | 24 | 0.675 | 4 | 40 | 6.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | 40 | 2 | 25 | 20 | 0.84375 | 0 | 0 | 0 | 0 | 0 | 0.275 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | true | 0 | 0 | 0.5 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 7 |
08f3b107dfba540c25ceb4dbc977c1ac4bb09e9d | 212 | py | Python | ramda/multiply_test.py | Rafi993/pyramda | 4fa7fe28d5eaa798b702d28bdd3948515cb88f48 | [
"MIT"
] | 56 | 2018-08-06T08:44:58.000Z | 2022-03-17T09:49:03.000Z | ramda/multiply_test.py | Rafi993/pyramda | 4fa7fe28d5eaa798b702d28bdd3948515cb88f48 | [
"MIT"
] | 28 | 2019-06-17T11:09:52.000Z | 2022-02-18T16:59:21.000Z | ramda/multiply_test.py | slavaGanzin/pyramda | 4fa7fe28d5eaa798b702d28bdd3948515cb88f48 | [
"MIT"
] | 5 | 2019-09-18T09:24:38.000Z | 2021-07-21T08:40:23.000Z | from .multiply import multiply
from ramda.private.asserts import assert_equal
def multiply_nocurry_test():
assert_equal(multiply(3, 6), 18)
def multiply_curry_test():
assert_equal(multiply(3)(6), 18)
| 19.272727 | 46 | 0.759434 | 31 | 212 | 4.967742 | 0.483871 | 0.214286 | 0.194805 | 0.298701 | 0.350649 | 0.350649 | 0.350649 | 0 | 0 | 0 | 0 | 0.043716 | 0.136792 | 212 | 10 | 47 | 21.2 | 0.797814 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
3e9e01d770b4e5cb8726091f7798118fec89e04d | 2,215 | py | Python | integrationTest/test_first.py | nikosias/tarantool_example | 566687d1464acaea8f1170c9c1d0d95320513a73 | [
"CC0-1.0"
] | null | null | null | integrationTest/test_first.py | nikosias/tarantool_example | 566687d1464acaea8f1170c9c1d0d95320513a73 | [
"CC0-1.0"
] | null | null | null | integrationTest/test_first.py | nikosias/tarantool_example | 566687d1464acaea8f1170c9c1d0d95320513a73 | [
"CC0-1.0"
] | null | null | null | import requests
import pytest
import uuid
class Test_Request():
_url =False
@pytest.fixture(autouse=True)
def _pass_fixture_value(self, url):
self._url = url
def test_keyNotFound(self):
r=requests.post(self._url+'/kv',data = {})
assert(r.status_code == 400)
def test_POST(self):
key = str(uuid.uuid4())
r=requests.post(self._url+'/kv',data = {"key":key, "value":"\"value\""})
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.post(self._url+'/kv',data = {"key":key, "value":"\"value\""})
assert(r.status_code == 409)
r=requests.post(self._url+'/kv',data = {"key": str(uuid.uuid4()), "value":"value\""})
assert(r.status_code == 400)
def test_GET(self):
key = str(uuid.uuid4())
r=requests.post(self._url+'/kv',data = {"key":key, "value":"\"value\""})
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.get(self._url+'/kv/'+key)
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.get(self._url+'/kv/'+str(uuid.uuid4()))
assert(r.status_code == 404)
def test_PUT(self):
key = str(uuid.uuid4())
r=requests.post(self._url+'/kv',data = {"key":key, "value":"\"value\""})
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.put(self._url+'/kv/'+key,data = {"key":key, "value":"\"value1\""})
assert(r.status_code == 200)
assert(r.text == '"value1"')
r=requests.put(self._url+'/kv/'+str(uuid.uuid4()))
assert(r.status_code == 404)
r=requests.put(self._url+'/kv/'+key,data = {"key":key, "value":"value1\""})
assert(r.status_code == 400)
def test_DELETE(self):
key = str(uuid.uuid4())
r=requests.post(self._url+'/kv',data = {"key":key, "value":"\"value\""})
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.delete(self._url+'/kv/'+key)
assert(r.status_code == 200)
assert(r.text == '"value"')
r=requests.put(self._url+'/kv/'+key)
assert(r.status_code == 404)
| 33.059701 | 93 | 0.547178 | 296 | 2,215 | 3.962838 | 0.121622 | 0.12532 | 0.107417 | 0.202899 | 0.836317 | 0.83376 | 0.815004 | 0.738278 | 0.687127 | 0.687127 | 0 | 0.030769 | 0.23702 | 2,215 | 66 | 94 | 33.560606 | 0.663314 | 0 | 0 | 0.538462 | 0 | 0 | 0.082167 | 0 | 0 | 0 | 0 | 0 | 0.403846 | 1 | 0.115385 | false | 0.019231 | 0.057692 | 0 | 0.211538 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
3eede0ec6c4d5354d58990cc682c9709424200c7 | 7,989 | py | Python | HOZO/hozo/data_hyper_cleaning_bo.py | jsgubin/HOZOG | cae6ac386d1b43c70d269e47e10ba4a4ac7aed4a | [
"MIT"
] | 4 | 2021-04-19T21:01:56.000Z | 2021-09-05T06:54:47.000Z | HOZO/hozo/data_hyper_cleaning_bo.py | jsgubin/HOZOG | cae6ac386d1b43c70d269e47e10ba4a4ac7aed4a | [
"MIT"
] | 1 | 2022-01-24T21:32:42.000Z | 2022-01-24T21:32:42.000Z | HOZO/hozo/data_hyper_cleaning_bo.py | jsgubin/HOZOG | cae6ac386d1b43c70d269e47e10ba4a4ac7aed4a | [
"MIT"
] | null | null | null | import numpy as np
from scipy import sparse
from sklearn import linear_model
from scipy.special import expit
from sklearn.utils.extmath import log_logistic, safe_sparse_dot
from sklearn.model_selection import cross_val_score
import tensorflow as tf
import time
import hozo
class DataHyperCleaningBO(linear_model.base.BaseEstimator,
linear_model.base.LinearClassifierMixin):
def __init__(
self, data, T=2000, lr=.1, loss_function='ce'):
self.data = data
self.T = T
self.lr = lr
if(loss_function == 'ce'):
self.cost_func = self.cost_func_ce
elif(loss_function == '01'):
self.cost_func = self.cost_func_01
else:
print('Please specify a valid loss function')
def black_box_function(self, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20):
np.random.seed(0)
x = tf.placeholder(tf.float32, name='x')
y = tf.placeholder(tf.float32, name='y')
model = hozo.LinearModel(x, 28 * 28, 10)
tmp_lambdak=np.ones(self.data.train.num_examples)*0.0
part_size = int(np.ceil(self.data.train.num_examples / 20))
for p_idx in range(20):
if p_idx == 19:
true_idx = p_idx + 1
# print('true_idx',true_idx)
tmp_lambdak[part_size*p_idx:]=np.ones(self.data.train.num_examples-19*part_size)*eval('x'+str(true_idx))
else:
# print(part_size*p_idx)
# print(part_size*(p_idx+1)-1)
# print(tmp_part_lambdak[p_idx])
true_idx = p_idx + 1
# print(eval('x'+str(true_idx)))
tmp_lambdak[part_size*p_idx:(part_size*(p_idx+1))]=np.ones(part_size)*eval('x'+str(true_idx))
saver=None
# print(tmp_lambdak)
f = self.cost_func(saver, model, y, self.data, self.T, self.lr, tmp_lambdak, name='Test')
return f
def black_box_function100(self, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, \
x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, \
x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, \
x31, x32, x33, x34, x35, x36, x37, x38, x39, x40, \
x41, x42, x43, x44, x45, x46, x47, x48, x49, x50, \
x51, x52, x53, x54, x55, x56, x57, x58, x59, x60, \
x61, x62, x63, x64, x65, x66, x67, x68, x69, x70, \
x71, x72, x73, x74, x75, x76, x77, x78, x79, x80, \
x81, x82, x83, x84, x85, x86, x87, x88, x89, x90, \
x91, x92, x93, x94, x95, x96, x97, x98, x99, x100):
np.random.seed(0)
x = tf.placeholder(tf.float32, name='x')
y = tf.placeholder(tf.float32, name='y')
print('Call function')
model = hozo.LinearModel(x, 28 * 28, 10)
tmp_lambdak=np.ones(self.data.train.num_examples)*0.0
part_size = int(np.ceil(self.data.train.num_examples / 100))
for p_idx in range(100):
if p_idx == 99:
true_idx = p_idx + 1
tmp_lambdak[part_size*p_idx:]=np.ones(self.data.train.num_examples-99*part_size)*eval('x'+str(true_idx))
else:
# print(part_size*p_idx)
# print(part_size*(p_idx+1)-1)
# print(tmp_part_lambdak[p_idx])
true_idx = p_idx + 1
# print(eval('x'+str(true_idx)))
tmp_lambdak[part_size*p_idx:(part_size*(p_idx+1))]=np.ones(part_size)*eval('x'+str(true_idx))
saver=None
# print(tmp_lambdak)
f = self.cost_func(saver, model, y, self.data, self.T, self.lr, tmp_lambdak, name='Test')
return f
def cost_func_ce(self, saver, model, y, data, T, lr, lmd=None, name=None):
# TODO other optimizers?
"""
BASELINE EXECUTION (valid also for oracle and final training,
with optimized values of lambda)
:param saver: `Saver` object (can be None)
:param name: optional name for the saver
:param data: `Datasets` object
:param T: number of iterations
:param lmd: weights for the examples, if None sets to 1.
:param model: a model (should comply with `rf.Network`)
:param y: placeholder for output
:param lr: learning rate
:return:
"""
# if saver: saver.save_setting(vars(), append_string=name)
x = model.inp[0]
# def _train_and_valid_s():
# return {x: np.vstack((data.train.data, data.validation.data)),
# y: np.vstack((data.train.target, data.validation.target))}
train_s = data.train.create_supplier(x, y)
valid_s = data.validation.create_supplier(x, y)
error2 = tf.reduce_mean(lmd * hozo.cross_entropy_loss(y, model.out))
correct_prediction2 = tf.equal(tf.argmax(model.out, 1), tf.argmax(y, 1))
accuracy2 = tf.reduce_mean(tf.cast(correct_prediction2, "float"))
error = tf.reduce_mean(hozo.cross_entropy_loss(y, model.out))
opt = tf.train.GradientDescentOptimizer(lr)
ts1 = opt.minimize(error2, var_list=model.var_list)
# saver related
if saver:
saver.clear_items()
saver.add_items(
'Test Accuracy', accuracy2, tst_s,
)
with tf.Session(config=hozo.CONFIG_GPU_GROWTH).as_default():
tf.variables_initializer(model.var_list).run()
for _ in range(T):
ts1.run(feed_dict=train_s())
if saver: saver.save(name)
baseline_test_accuracy = accuracy2.eval(feed_dict=valid_s())
test_error = error.eval(feed_dict=valid_s())
# print('baseline_test_accuracy',baseline_test_accuracy)
# return 1-baseline_test_accuracy
return -test_error
def cost_func_01(self, saver, model, y, data, T, lr, lmd=None, name=None):
# TODO other optimizers?
"""
BASELINE EXECUTION (valid also for oracle and final training,
with optimized values of lambda)
:param saver: `Saver` object (can be None)
:param name: optional name for the saver
:param data: `Datasets` object
:param T: number of iterations
:param lmd: weights for the examples, if None sets to 1.
:param model: a model (should comply with `rf.Network`)
:param y: placeholder for output
:param lr: learning rate
:return:
"""
# if saver: saver.save_setting(vars(), append_string=name)
x = model.inp[0]
# def _train_and_valid_s():
# return {x: np.vstack((data.train.data, data.validation.data)),
# y: np.vstack((data.train.target, data.validation.target))}
train_s = data.train.create_supplier(x, y)
valid_s = data.validation.create_supplier(x, y)
error2 = tf.reduce_mean(lmd * hozo.cross_entropy_loss(y, model.out))
correct_prediction2 = tf.equal(tf.argmax(model.out, 1), tf.argmax(y, 1))
accuracy2 = tf.reduce_mean(tf.cast(correct_prediction2, "float"))
error = tf.reduce_mean(hozo.cross_entropy_loss(y, model.out))
opt = tf.train.GradientDescentOptimizer(lr)
ts1 = opt.minimize(error2, var_list=model.var_list)
# saver related
if saver:
saver.clear_items()
saver.add_items(
'Test Accuracy', accuracy2, tst_s,
)
with tf.Session(config=hozo.CONFIG_GPU_GROWTH).as_default():
tf.variables_initializer(model.var_list).run()
for _ in range(T):
ts1.run(feed_dict=train_s())
if saver: saver.save(name)
baseline_test_accuracy = accuracy2.eval(feed_dict=valid_s())
test_error = error.eval(feed_dict=valid_s())
# print('baseline_test_accuracy',baseline_test_accuracy)
return baseline_test_accuracy-1
# return -test_error | 42.494681 | 124 | 0.593691 | 1,108 | 7,989 | 4.107401 | 0.25 | 0.017579 | 0.019776 | 0.026368 | 0.805537 | 0.796748 | 0.782465 | 0.782465 | 0.780927 | 0.780927 | 0 | 0.055896 | 0.285643 | 7,989 | 188 | 125 | 42.494681 | 0.741545 | 0.227062 | 0 | 0.580357 | 0 | 0 | 0.018004 | 0 | 0 | 0 | 0 | 0.010638 | 0 | 1 | 0.044643 | false | 0 | 0.080357 | 0 | 0.169643 | 0.017857 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
eb454dcbc7cdf4b27d08fa4609b5a839a3e4d319 | 3,199 | py | Python | mycube.py | marcmenem/learnopengl | 9b58874f23f58d390edbc8c31af3bb3d87921c38 | [
"CC0-1.0"
] | null | null | null | mycube.py | marcmenem/learnopengl | 9b58874f23f58d390edbc8c31af3bb3d87921c38 | [
"CC0-1.0"
] | null | null | null | mycube.py | marcmenem/learnopengl | 9b58874f23f58d390edbc8c31af3bb3d87921c38 | [
"CC0-1.0"
] | null | null | null |
import numpy as np
vertices = np.array([ ## with textures
-0.5, -0.5, -0.5, 0.0, 0.0,
0.5, -0.5, -0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, -0.5, 1.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, 0.5, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
0.5, -0.5, -0.5, 1.0, 1.0,
0.5, -0.5, 0.5, 1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0,
-0.5, 0.5, -0.5, 0.0, 1.0,
0.5, 0.5, -0.5, 1.0, 1.0,
0.5, 0.5, 0.5, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0
], dtype=np.float32)
verticeswithnormals = np.array([ ## with textures and normals
-0.5, -0.5, -0.5, 0.0, 0.0, 0.0, 0.0, -1.0,
0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 1.0, 1.0, 0.0, 0.0, -1.0,
0.5, 0.5, -0.5, 1.0, 1.0, 0.0, 0.0, -1.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, -1.0,
-0.5, -0.5, -0.5, 0.0, 0.0, 0.0, 0.0, -1.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0, 0.0, 0.0, 1.0,
0.5, 0.5, 0.5, 1.0, 1.0, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0,
-0.5, 0.5, 0.5, 1.0, 0.0, -1.0, 0.0, 0.0,
-0.5, 0.5, -0.5, 1.0, 1.0, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0, -1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0, -1.0, 0.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0, -1.0, 0.0, 0.0,
-0.5, 0.5, 0.5, 1.0, 0.0, -1.0, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 0.0, 1.0, 1.0, 0.0, 0.0,
0.5, -0.5, -0.5, 0.0, 1.0, 1.0, 0.0, 0.0,
0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0, 0.0, -1.0, 0.0,
0.5, -0.5, -0.5, 1.0, 1.0, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0, -1.0, 0.0,
0.5, -0.5, 0.5, 1.0, 0.0, 0.0, -1.0, 0.0,
-0.5, -0.5, 0.5, 0.0, 0.0, 0.0, -1.0, 0.0,
-0.5, -0.5, -0.5, 0.0, 1.0, 0.0, -1.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0,
0.5, 0.5, -0.5, 1.0, 1.0, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0,
0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0,
-0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0,
-0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 0.0
], dtype=np.float32)
| 34.397849 | 61 | 0.329478 | 958 | 3,199 | 1.100209 | 0.016701 | 0.611006 | 0.572106 | 0.54649 | 0.888046 | 0.888046 | 0.888046 | 0.888046 | 0.888046 | 0.888046 | 0 | 0.440075 | 0.332291 | 3,199 | 92 | 62 | 34.771739 | 0.053371 | 0.012191 | 0 | 0.688312 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.012987 | 0 | 0.012987 | 0 | 0 | 0 | 1 | null | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 |
de634857a583a35a91886213b9a2140389defbb2 | 104 | py | Python | entity/cards/LETLT_038/__init__.py | x014/lushi_script | edab2b88e3f0de8139de2541ab2daa331f777c0e | [
"MIT"
] | 102 | 2021-10-20T09:06:39.000Z | 2022-03-28T13:35:11.000Z | entity/cards/LETLT_038/__init__.py | x014/lushi_script | edab2b88e3f0de8139de2541ab2daa331f777c0e | [
"MIT"
] | 98 | 2021-10-19T16:13:27.000Z | 2022-03-27T13:27:49.000Z | entity/cards/LETLT_038/__init__.py | x014/lushi_script | edab2b88e3f0de8139de2541ab2daa331f777c0e | [
"MIT"
] | 55 | 2021-10-19T03:56:50.000Z | 2022-03-25T08:25:26.000Z | # -*- coding: utf-8 -*-
import entity.cards.LETLT_038.LETLT_038
import entity.cards.LETLT_038.LETLT_038
| 26 | 39 | 0.769231 | 17 | 104 | 4.470588 | 0.470588 | 0.421053 | 0.447368 | 0.578947 | 0.868421 | 0.868421 | 0.868421 | 0 | 0 | 0 | 0 | 0.136842 | 0.086538 | 104 | 3 | 40 | 34.666667 | 0.663158 | 0.201923 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 12 |
a0e0544263ab4b1cb74fe88b7a0efd57ff97d7d0 | 7,114 | py | Python | project/Support/Code/actions/shortcuts/form/loaded.py | fael07/Blog-Django-with-CBV | 269747b2e663a34b99acae6368db49c6ad37c2b8 | [
"MIT"
] | null | null | null | project/Support/Code/actions/shortcuts/form/loaded.py | fael07/Blog-Django-with-CBV | 269747b2e663a34b99acae6368db49c6ad37c2b8 | [
"MIT"
] | null | null | null | project/Support/Code/actions/shortcuts/form/loaded.py | fael07/Blog-Django-with-CBV | 269747b2e663a34b99acae6368db49c6ad37c2b8 | [
"MIT"
] | null | null | null | loaded_forms = {
'login_form': [
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_email">Email:</label>\n'
' <input type="text" name="email" id="id_email" '
'placeholder="Digite seu email" inputmode="email">\n'
' \n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'email'},
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_password">Senha:</label>\n'
' <input type="password" name="password" id="id_password" '
'placeholder="Digite sua senha">\n'
' <div class="block-forgot-password"><a href="/nova-senha/informar-email">Esqueceu a '
'senha?</a></div>\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'password'}
],
'fast_login_form': """
<div class="field-group">
<label for="id_email">Email:</label>
<input type="text" name="email" id="id_email" placeholder="Digite seu email" inputmode="email">
<div class="error"></div>
</div>
<div class="field-group">
<label for="id_password">Senha:</label>
<input type="password" name="password" id="id_password" placeholder="Digite sua senha">
<div class="block-forgot-password"><a href="/nova-senha/informar-email">Esqueceu a senha?</a></div>
<div class="error"></div>
</div>
""",
'register_form':[
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_name">Nome:</label>\n'
' <input type="text" name="name" id="id_name" '
'placeholder="Digite seu nome">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'name'},
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_email">Email:</label>\n'
' <input type="text" name="email" id="id_email" '
'placeholder="Digite seu email" inputmode="email">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'email'},
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_password">Senha:</label>\n'
' <input type="password" name="password" id="id_password" '
'placeholder="Digite sua senha">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'password'},
{'html': '\n'
' <div class="field-group">\n'
' <label for="id_confirm_password">Confirmar '
'senha:</label>\n'
' <input type="password" name="confirm_password" '
'id="id_confirm_password" placeholder="Confirme sua senha">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'confirm_password'}
],
'fast_register_form': """
<div class="field-group">
<label for="id_name">Nome:</label>
<input type="text" name="name" id="id_name" placeholder="Digite seu nome">
<div class="error"></div>
</div>
<div class="field-group">
<label for="id_email">Email:</label>
<input type="text" name="email" id="id_email" placeholder="Digite seu email" inputmode="email">
<div class="error"></div>
</div>
<div class="field-group">
<label for="id_password">Senha:</label>
<input type="password" name="password" id="id_password" placeholder="Digite sua senha">
<div class="error"></div>
</div>
<div class="field-group">
<label for="id_confirm_password">Confirmar senha:</label>
<input type="password" name="confirm_password" id="id_confirm_password" placeholder="Confirme sua senha">
<div class="error"></div>
</div>
""",
'password_form': [
{'html': '\n'
' <div class="ag-form-group">\n'
' <label for="current_password" class="ag-label">Senha '
'atual:</label>\n'
' <input type="password" name="current_password" '
'id="id_current_password" class="input" placeholder="Digite sua '
'senha atual">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'current_password'},
{'html': '\n'
' <div class="ag-form-group">\n'
' <label for="new_password" class="ag-label">Nova '
'senha:</label>\n'
' <input type="password" name="new_password" '
'id="id_new_password" class="input" placeholder="Digite sua nova '
'senha">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'new_password'},
{'html': '\n'
' <div class="ag-form-group">\n'
' <label for="confirm_new_password" '
'class="ag-label">Confirmar senha:</label>\n'
' <input type="password" name="confirm_new_password" '
'id="id_confirm_new_password" class="input" placeholder="Corfirme '
'sua nova senha">\n'
' <div class="error"></div>\n'
' </div>\n'
' ',
'name': 'confirm_new_password'}
],
'fast_password_form': """
<div class="ag-form-group">
<label for="current_password" class="ag-label">Senha atual:</label>
<input type="password" name="current_password" id="id_current_password" class="input" placeholder="Digite sua senha atual">
<div class="error"></div>
</div>
<div class="ag-form-group">
<label for="new_password" class="ag-label">Nova senha:</label>
<input type="password" name="new_password" id="id_new_password" class="input" placeholder="Digite sua nova senha">
<div class="error"></div>
</div>
<div class="ag-form-group">
<label for="confirm_new_password" class="ag-label">Confirmar senha:</label>
<input type="password" name="confirm_new_password" id="id_confirm_new_password" class="input" placeholder="Confirme sua nova senha">
<div class="error"></div>
</div>
"""
} | 43.378049 | 144 | 0.453613 | 705 | 7,114 | 4.470922 | 0.062411 | 0.096447 | 0.054251 | 0.091371 | 0.962563 | 0.955267 | 0.946383 | 0.93401 | 0.897208 | 0.874048 | 0 | 0 | 0.377565 | 7,114 | 164 | 145 | 43.378049 | 0.711834 | 0 | 0 | 0.668874 | 0 | 0.046358 | 0.739986 | 0.226283 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.251656 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 8 |
19bca3953528e59857928a0b1384d0c69efa8455 | 113 | py | Python | num_gen/servers/__init__.py | cnobile2012/tutorial_05 | d3411fdac64c123e02fcf4ad018cf8016d201807 | [
"MIT"
] | null | null | null | num_gen/servers/__init__.py | cnobile2012/tutorial_05 | d3411fdac64c123e02fcf4ad018cf8016d201807 | [
"MIT"
] | null | null | null | num_gen/servers/__init__.py | cnobile2012/tutorial_05 | d3411fdac64c123e02fcf4ad018cf8016d201807 | [
"MIT"
] | null | null | null | # Load all public packages.
from .server_01 import Server as Server01
from .server_02 import Server as Server02
| 22.6 | 41 | 0.80531 | 18 | 113 | 4.944444 | 0.666667 | 0.224719 | 0.314607 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.084211 | 0.159292 | 113 | 4 | 42 | 28.25 | 0.852632 | 0.221239 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
19ffbd550bbbca30239008494d99ab2151783e6b | 7,916 | py | Python | tests/server/test_grpc_server_errors.py | crazytruth/interstellar | 48b26293eebe680c03cf0c7e2571a39a3b7f1628 | [
"MIT"
] | null | null | null | tests/server/test_grpc_server_errors.py | crazytruth/interstellar | 48b26293eebe680c03cf0c7e2571a39a3b7f1628 | [
"MIT"
] | null | null | null | tests/server/test_grpc_server_errors.py | crazytruth/interstellar | 48b26293eebe680c03cf0c7e2571a39a3b7f1628 | [
"MIT"
] | null | null | null | import pytest
from insanic.conf import settings
from interstellar import config as common_config
from interstellar.server import InterstellarServer, config as server_config
# from interstellar.server.log import interstellar_server_error_log
# from interstellar.server.server import interstellar_request_handler
from interstellar.server.server.handlers import RequestHandler
from grpclib.encoding.proto import ProtoCodec
@pytest.fixture()
def mock_h2_stream():
class MockStream:
closable = False
id = 4
async def send_headers(self, headers, end_stream):
pass
return MockStream()
@pytest.fixture(autouse=True)
def load_settings():
InterstellarServer.load_config(settings, common_config)
InterstellarServer.load_config(settings, server_config)
class TestRequestHandlerErrors:
async def test_method_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "GET")]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" not in dict_headers
assert "grpc-message" not in dict_headers
assert dict_headers[':status'] == "405"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, None, None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
async def test_no_method_headers_error(self, mock_h2_stream, monkeypatch):
headers = []
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" not in dict_headers
assert "grpc-message" not in dict_headers
assert dict_headers[':status'] == "405"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, None, None, object)
result = await handler.handle()
assert result is None
# assert len(send_header_called) > 0
async def test_content_type_missing_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "POST")]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "415"
assert dict_headers['grpc-status'] == "2"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, None, None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
@pytest.mark.parametrize(
"content_type",
("application/json",
"application/grpc",
"application/grpc+",
"application/grpc+ape")
)
async def test_content_type_invalid_error(self, mock_h2_stream, monkeypatch, content_type):
class MockCodec:
__content_subtype__ = "asd"
headers = [(":method", "POST"), ("content-type", content_type)]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "415"
assert dict_headers['grpc-status'] == "2"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, MockCodec(), None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
async def test_te_missing_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "POST"), ("content-type", 'application/grpc+proto')]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "400"
assert dict_headers['grpc-status'] == "2"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, ProtoCodec(), None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
async def test_te_invalid_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "POST"), ("content-type", 'application/grpc+proto'), ('te', "asda")]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "400"
assert dict_headers['grpc-status'] == "2"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, ProtoCodec(), None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
async def test_path_missing_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "POST"), ("content-type", 'application/grpc+proto'),
('te', "trailers")]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "200"
assert dict_headers['grpc-status'] == "12"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, ProtoCodec(), None, object)
result = await handler.handle()
assert result is None
# assert len(send_header_called) > 0
async def test_path_invalid_error(self, mock_h2_stream, monkeypatch):
headers = [(":method", "POST"), ("content-type", 'application/grpc+proto'),
('te', "trailers"), (':path', "asdad")]
send_header_called = []
async def mock_send_header(headers, end_stream):
dict_headers = dict(headers)
assert ":status" in dict_headers
assert "grpc-status" in dict_headers
assert "grpc-message" in dict_headers
assert dict_headers[':status'] == "200"
assert dict_headers['grpc-status'] == "12"
send_header_called.append(True)
monkeypatch.setattr(mock_h2_stream, 'send_headers', mock_send_header)
handler = RequestHandler({}, mock_h2_stream, headers, ProtoCodec(), None, object)
result = await handler.handle()
assert result is None
assert len(send_header_called) > 0
| 33.542373 | 99 | 0.644138 | 902 | 7,916 | 5.386918 | 0.101996 | 0.122247 | 0.111957 | 0.093846 | 0.825067 | 0.812307 | 0.812307 | 0.796254 | 0.786993 | 0.786993 | 0 | 0.011207 | 0.256064 | 7,916 | 235 | 100 | 33.685106 | 0.81389 | 0.025644 | 0 | 0.707792 | 0 | 0 | 0.108199 | 0.011417 | 0 | 0 | 0 | 0 | 0.337662 | 1 | 0.012987 | false | 0.006494 | 0.038961 | 0 | 0.090909 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
c2297be5093491db12d5f4fc605c0f4d9431f871 | 184 | py | Python | nswatcher/policies/StaticPolicy.py | paraita/ns-watcher | 8554c0d9ab76028ac93887ac15b00c279ba19841 | [
"MIT"
] | null | null | null | nswatcher/policies/StaticPolicy.py | paraita/ns-watcher | 8554c0d9ab76028ac93887ac15b00c279ba19841 | [
"MIT"
] | null | null | null | nswatcher/policies/StaticPolicy.py | paraita/ns-watcher | 8554c0d9ab76028ac93887ac15b00c279ba19841 | [
"MIT"
] | null | null | null | def build_policy_cmd(policy):
return f"org.ow2.proactive.resourcemanager.nodesource.policy.StaticPolicy" \
f" {policy['userAccessType']} {policy['providerAccessType']}"
| 46 | 80 | 0.733696 | 19 | 184 | 7 | 0.736842 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006211 | 0.125 | 184 | 3 | 81 | 61.333333 | 0.819876 | 0 | 0 | 0 | 0 | 0 | 0.663043 | 0.652174 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0 | 0.333333 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 7 |
dff05cab2390d5451979fbb9d9a184482ee5af40 | 244 | py | Python | src/home/views.py | Deepak27004/carecoop | 01229c1f9d1c89e595d7f4ca62a07e780522118b | [
"MIT"
] | null | null | null | src/home/views.py | Deepak27004/carecoop | 01229c1f9d1c89e595d7f4ca62a07e780522118b | [
"MIT"
] | null | null | null | src/home/views.py | Deepak27004/carecoop | 01229c1f9d1c89e595d7f4ca62a07e780522118b | [
"MIT"
] | 5 | 2017-11-06T14:15:19.000Z | 2020-10-02T14:51:37.000Z |
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = "index.html"
# -*- coding: utf-8 -*-
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name="home/index.html"
| 18.769231 | 45 | 0.770492 | 30 | 244 | 6.2 | 0.533333 | 0.107527 | 0.16129 | 0.236559 | 0.827957 | 0.827957 | 0.827957 | 0.827957 | 0.827957 | 0.827957 | 0 | 0.00463 | 0.114754 | 244 | 12 | 46 | 20.333333 | 0.856481 | 0.086066 | 0 | 0.666667 | 0 | 0 | 0.114155 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 8 |
a0701c215148f9a3049a5d561d2087f02f8bc9ba | 410 | py | Python | python/numpy/q7_np_array_mathematics.py | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | python/numpy/q7_np_array_mathematics.py | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | python/numpy/q7_np_array_mathematics.py | mxdzi/hackerrank | 4455f73e4479a4204b2e1167253f6a02351aa5b7 | [
"MIT"
] | null | null | null | import numpy
def main():
N, M = list(map(int, input().split()))
arrayA = numpy.array([input().split() for _ in range(N)], int)
arrayB = numpy.array([input().split() for _ in range(N)], int)
print(arrayA + arrayB)
print(arrayA - arrayB)
print(arrayA * arrayB)
print(arrayA // arrayB)
print(arrayA % arrayB)
print(arrayA ** arrayB)
if __name__ == "__main__":
main()
| 20.5 | 66 | 0.6 | 53 | 410 | 4.45283 | 0.377358 | 0.279661 | 0.432203 | 0.466102 | 0.720339 | 0.720339 | 0.720339 | 0.720339 | 0.720339 | 0.432203 | 0 | 0 | 0.229268 | 410 | 19 | 67 | 21.578947 | 0.746835 | 0 | 0 | 0 | 0 | 0 | 0.019512 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0.076923 | 0 | 0.153846 | 0.461538 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
cd1c87549c4df1162efdef08c3465777bfe219a1 | 5,696 | py | Python | etl.py | t2wan/DSC180A-CheckPoint1 | ba80688667688fb3068974bcb8d684906f606907 | [
"Apache-2.0"
] | 1 | 2021-09-16T05:54:07.000Z | 2021-09-16T05:54:07.000Z | etl.py | t2wan/DSC180A-CheckPoint1 | ba80688667688fb3068974bcb8d684906f606907 | [
"Apache-2.0"
] | null | null | null | etl.py | t2wan/DSC180A-CheckPoint1 | ba80688667688fb3068974bcb8d684906f606907 | [
"Apache-2.0"
] | 1 | 2020-10-29T18:05:37.000Z | 2020-10-29T18:05:37.000Z | '''
etl.py contains to download data
'''
import subprocess
#import os
def get_data(input_file):
'''
download and save data to
'''
#if os.path.exists("auto_phrase.sh"):
#os.remove("auto_phrase.sh")
if input_file == 'DBLP.5k.txt':
with open ('auto_phrase.sh', 'w') as rsh:
rsh.write('''\
#!/bin/bash
# In effect, the commands below check to see if we're running in a Docker container--in that case, the (default)
# "data" and "models" directories will have been renamed, in order to avoid conflicts with mounted directories
# with the same names.
#
# DATA_DIR is the default directory for reading data files. Because this directory contains not only the default
# dataset, but also language-specific files and "BAD_POS_TAGS.TXT", in most cases it's a bad idea to change it.
# However, when this script is run from a Docker container, it's perfectly fine for the user to mount an external
# directory called "data" and read the corpus from there, since the directory holding the language-specific files
# and "BAD_POS_TAGS.txt" will have been renamed to "default_data".
if [ -d "default_data" ]; then
DATA_DIR=${DATA_DIR:- default_data}
else
DATA_DIR=${DATA_DIR:- data}
fi
# MODEL is the directory in which the resulting model will be saved.
if [ -d "models" ]; then
MODELS_DIR=${MODELS_DIR:- models}
else
MODELS_DIR=${MODELS_DIR:- default_models}
fi
MODEL=${MODEL:- ${MODELS_DIR}/DBLP}
# RAW_TRAIN is the input of AutoPhrase, where each line is a single document.
DEFAULT_TRAIN=${DATA_DIR}/EN/DBLP.5k.txt
RAW_TRAIN=${RAW_TRAIN:- $DEFAULT_TRAIN}
# When FIRST_RUN is set to 1, AutoPhrase will run all preprocessing.
# Otherwise, AutoPhrase directly starts from the current preprocessed data in the tmp/ folder.
FIRST_RUN=${FIRST_RUN:- 1}
# When ENABLE_POS_TAGGING is set to 1, AutoPhrase will utilize the POS tagging in the phrase mining.
# Otherwise, a simple length penalty mode as the same as SegPhrase will be used.
ENABLE_POS_TAGGING=${ENABLE_POS_TAGGING:- 1}
# A hard threshold of raw frequency is specified for frequent phrase mining, which will generate a candidate set.
MIN_SUP=${MIN_SUP:- 10}
# You can also specify how many threads can be used for AutoPhrase
THREAD=${THREAD:- 10}
COMPILE=${COMPILE:- 1}
### Begin: Suggested Parameters ###
MAX_POSITIVES=-1
LABEL_METHOD=DPDN
RAW_LABEL_FILE=${RAW_LABEL_FILE:-""}
### End: Suggested Parameters ###
green=`tput setaf 2`
reset=`tput sgr0`
if [ $COMPILE -eq 1 ]; then
echo ${green}===Compilation===${reset}
bash compile.sh
fi
mkdir -p tmp
mkdir -p ${MODEL}
if [ $RAW_TRAIN == $DEFAULT_TRAIN ] && [ ! -e $DEFAULT_TRAIN ]; then
echo ${green}===Downloading Toy Dataset===${reset}
curl http://dmserv2.cs.illinois.edu/data/DBLP.txt.gz --output ${DEFAULT_TRAIN}.gz
gzip -d ${DEFAULT_TRAIN}.gz -f
fi
### END Compilation###
''')
else:
with open ('auto_phrase.sh', 'w') as rsh:
rsh.write('''\
#!/bin/bash
# In effect, the commands below check to see if we're running in a Docker container--in that case, the (default)
# "data" and "models" directories will have been renamed, in order to avoid conflicts with mounted directories
# with the same names.
#
# DATA_DIR is the default directory for reading data files. Because this directory contains not only the default
# dataset, but also language-specific files and "BAD_POS_TAGS.TXT", in most cases it's a bad idea to change it.
# However, when this script is run from a Docker container, it's perfectly fine for the user to mount an external
# directory called "data" and read the corpus from there, since the directory holding the language-specific files
# and "BAD_POS_TAGS.txt" will have been renamed to "default_data".
if [ -d "default_data" ]; then
DATA_DIR=${DATA_DIR:- default_data}
else
DATA_DIR=${DATA_DIR:- data}
fi
# MODEL is the directory in which the resulting model will be saved.
if [ -d "models" ]; then
MODELS_DIR=${MODELS_DIR:- models}
else
MODELS_DIR=${MODELS_DIR:- default_models}
fi
MODEL=${MODEL:- ${MODELS_DIR}/DBLP}
# RAW_TRAIN is the input of AutoPhrase, where each line is a single document.
DEFAULT_TRAIN=${DATA_DIR}/EN/DBLP.txt
RAW_TRAIN=${RAW_TRAIN:- $DEFAULT_TRAIN}
# When FIRST_RUN is set to 1, AutoPhrase will run all preprocessing.
# Otherwise, AutoPhrase directly starts from the current preprocessed data in the tmp/ folder.
FIRST_RUN=${FIRST_RUN:- 1}
# When ENABLE_POS_TAGGING is set to 1, AutoPhrase will utilize the POS tagging in the phrase mining.
# Otherwise, a simple length penalty mode as the same as SegPhrase will be used.
ENABLE_POS_TAGGING=${ENABLE_POS_TAGGING:- 1}
# A hard threshold of raw frequency is specified for frequent phrase mining, which will generate a candidate set.
MIN_SUP=${MIN_SUP:- 10}
# You can also specify how many threads can be used for AutoPhrase
THREAD=${THREAD:- 10}
COMPILE=${COMPILE:- 1}
### Begin: Suggested Parameters ###
MAX_POSITIVES=-1
LABEL_METHOD=DPDN
RAW_LABEL_FILE=${RAW_LABEL_FILE:-""}
### End: Suggested Parameters ###
green=`tput setaf 2`
reset=`tput sgr0`
if [ $COMPILE -eq 1 ]; then
echo ${green}===Compilation===${reset}
bash compile.sh
fi
mkdir -p tmp
mkdir -p ${MODEL}
if [ $RAW_TRAIN == $DEFAULT_TRAIN ] && [ ! -e $DEFAULT_TRAIN ]; then
echo ${green}===Downloading Toy Dataset===${reset}
curl http://dmserv2.cs.illinois.edu/data/DBLP.txt.gz --output ${DEFAULT_TRAIN}.gz
gzip -d ${DEFAULT_TRAIN}.gz -f
fi
### END Compilation###
''')
subprocess.run(['brew','install','gcc6'])
subprocess.run(['brew','update'])
subprocess.run(['chmod','+x','auto_phrase.sh'])
subprocess.run(['./auto_phrase.sh'])
return | 38.486486 | 117 | 0.716117 | 890 | 5,696 | 4.469663 | 0.225843 | 0.021116 | 0.0181 | 0.019105 | 0.930618 | 0.930618 | 0.930618 | 0.930618 | 0.930618 | 0.930618 | 0 | 0.006536 | 0.16731 | 5,696 | 148 | 118 | 38.486486 | 0.832174 | 0.023174 | 0 | 0.896 | 0 | 0.112 | 0.935379 | 0.111372 | 0 | 0 | 0 | 0 | 0 | 1 | 0.008 | false | 0 | 0.008 | 0 | 0.024 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
cd2ac194f5d1efc58d84a23b8a934afab165da42 | 39,443 | py | Python | tests/conftest.py | emmilco/itunes-iap | 2b744356b9cdeb7c6b6a01b84757c705e057bc1b | [
"BSD-2-Clause-FreeBSD"
] | 119 | 2015-03-06T12:31:57.000Z | 2021-11-09T07:43:23.000Z | tests/conftest.py | emmilco/itunes-iap | 2b744356b9cdeb7c6b6a01b84757c705e057bc1b | [
"BSD-2-Clause-FreeBSD"
] | 51 | 2015-03-30T21:23:01.000Z | 2022-02-04T19:49:12.000Z | tests/conftest.py | emmilco/itunes-iap | 2b744356b9cdeb7c6b6a01b84757c705e057bc1b | [
"BSD-2-Clause-FreeBSD"
] | 43 | 2015-01-21T20:33:27.000Z | 2022-02-04T19:46:32.000Z | # coding: utf-8
import json
import itunesiap
import pytest
from pytest_lazyfixture import lazy_fixture
def _raw_receipt_legacy():
return '''ewoJInNpZ25hdHVyZSIgPSAiQW1vSjJDNFhra1hXcngwbDBwMUVCMkhqdndWRkJPN3NxaHRPYVpYWXNtd29PblU4dkNYNWZJWFV6SmpwWVpwVGJ1bTJhWW5kci9uOHlBc2czUXc0WUZHMUtCbEpLSjU2c1gzcEpmWTRZd2hEMmJsdm1lZVowZ0FXKzNiajBRWGVjUWJORTk5b2duK09janY2U3dFSEdpdkRIY0FRNzBiMTYxekdpbTk2WHVKTkFBQURWekNDQTFNd2dnSTdvQU1DQVFJQ0NHVVVrVTNaV0FTMU1BMEdDU3FHU0liM0RRRUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2Y21sMGVURXpNREVHQTFVRUF3d3FRWEJ3YkdVZ2FWUjFibVZ6SUZOMGIzSmxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1CNFhEVEE1TURZeE5USXlNRFUxTmxvWERURTBNRFl4TkRJeU1EVTFObG93WkRFak1DRUdBMVVFQXd3YVVIVnlZMmhoYzJWU1pXTmxhWEIwUTJWeWRHbG1hV05oZEdVeEd6QVpCZ05WQkFzTUVrRndjR3hsSUdsVWRXNWxjeUJUZEc5eVpURVRNQkVHQTFVRUNnd0tRWEJ3YkdVZ1NXNWpMakVMTUFrR0ExVUVCaE1DVlZNd2daOHdEUVlKS29aSWh2Y05BUUVCQlFBRGdZMEFNSUdKQW9HQkFNclJqRjJjdDRJclNkaVRDaGFJMGc4cHd2L2NtSHM4cC9Sd1YvcnQvOTFYS1ZoTmw0WElCaW1LalFRTmZnSHNEczZ5anUrK0RyS0pFN3VLc3BoTWRkS1lmRkU1ckdYc0FkQkVqQndSSXhleFRldngzSExFRkdBdDFtb0t4NTA5ZGh4dGlJZERnSnYyWWFWczQ5QjB1SnZOZHk2U01xTk5MSHNETHpEUzlvWkhBZ01CQUFHamNqQndNQXdHQTFVZEV3RUIvd1FDTUFBd0h3WURWUjBqQkJnd0ZvQVVOaDNvNHAyQzBnRVl0VEpyRHRkREM1RllRem93RGdZRFZSMFBBUUgvQkFRREFnZUFNQjBHQTFVZERnUVdCQlNwZzRQeUdVakZQaEpYQ0JUTXphTittVjhrOVRBUUJnb3Foa2lHOTJOa0JnVUJCQUlGQURBTkJna3Foa2lHOXcwQkFRVUZBQU9DQVFFQUVhU2JQanRtTjRDL0lCM1FFcEszMlJ4YWNDRFhkVlhBZVZSZVM1RmFaeGMrdDg4cFFQOTNCaUF4dmRXLzNlVFNNR1k1RmJlQVlMM2V0cVA1Z204d3JGb2pYMGlreVZSU3RRKy9BUTBLRWp0cUIwN2tMczlRVWU4Y3pSOFVHZmRNMUV1bVYvVWd2RGQ0TndOWXhMUU1nNFdUUWZna1FRVnk4R1had1ZIZ2JFL1VDNlk3MDUzcEdYQms1MU5QTTN3b3hoZDNnU1JMdlhqK2xvSHNTdGNURXFlOXBCRHBtRzUrc2s0dHcrR0szR01lRU41LytlMVFUOW5wL0tsMW5qK2FCdzdDMHhzeTBiRm5hQWQxY1NTNnhkb3J5L0NVdk02Z3RLc21uT09kcVRlc2JwMGJzOHNuNldxczBDOWRnY3hSSHVPTVoydG04bnBMVW03YXJnT1N6UT09IjsKCSJwdXJjaGFzZS1pbmZvIiA9ICJld29KSW05eWFXZHBibUZzTFhCMWNtTm9ZWE5sTFdSaGRHVXRjSE4wSWlBOUlDSXlNREV5TFRBNUxUSXdJREU0T2pNeE9qTTRJRUZ0WlhKcFkyRXZURzl6WDBGdVoyVnNaWE1pT3dvSkluVnVhWEYxWlMxcFpHVnVkR2xtYVdWeUlpQTlJQ0kwTW1NeFlqTmtORFUxTmpNNE1qQmtaRGxoTlRsak56bGhOelUyTkRFd01ERm1ZemcxWlRNNUlqc0tDU0p2Y21sbmFXNWhiQzEwY21GdWMyRmpkR2x2YmkxcFpDSWdQU0FpTVRBd01EQXdNREExTmpFMk1UYzJOQ0k3Q2draVluWnljeUlnUFNBaU1TNHdJanNLQ1NKMGNtRnVjMkZqZEdsdmJpMXBaQ0lnUFNBaU1UQXdNREF3TURBMU5qRTJNVGMyTkNJN0Nna2ljWFZoYm5ScGRIa2lJRDBnSWpFaU93b0pJbTl5YVdkcGJtRnNMWEIxY21Ob1lYTmxMV1JoZEdVdGJYTWlJRDBnSWpFek5EZ3hPVEV3T1RneE9USWlPd29KSW5CeWIyUjFZM1F0YVdRaUlEMGdJa0poZEhSc1pVZHZiR1ExTUNJN0Nna2lhWFJsYlMxcFpDSWdQU0FpTlRVME5EazVNekExSWpzS0NTSmlhV1FpSUQwZ0ltTnZiUzUyWVc1cGJHeGhZbkpsWlhwbExtbG5kVzVpWVhSMGJHVWlPd29KSW5CMWNtTm9ZWE5sTFdSaGRHVXRiWE1pSUQwZ0lqRXpORGd4T1RFd09UZ3hPVElpT3dvSkluQjFjbU5vWVhObExXUmhkR1VpSUQwZ0lqSXdNVEl0TURrdE1qRWdNREU2TXpFNk16Z2dSWFJqTDBkTlZDSTdDZ2tpY0hWeVkyaGhjMlV0WkdGMFpTMXdjM1FpSUQwZ0lqSXdNVEl0TURrdE1qQWdNVGc2TXpFNk16Z2dRVzFsY21sallTOU1iM05mUVc1blpXeGxjeUk3Q2draWIzSnBaMmx1WVd3dGNIVnlZMmhoYzJVdFpHRjBaU0lnUFNBaU1qQXhNaTB3T1MweU1TQXdNVG96TVRvek9DQkZkR012UjAxVUlqc0tmUT09IjsKCSJlbnZpcm9ubWVudCIgPSAiU2FuZGJveCI7CgkicG9kIiA9ICIxMDAiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==''' # noqa
raw_receipt_legacy = pytest.fixture(scope='session')(_raw_receipt_legacy)
@pytest.fixture(scope='session')
def itunes_response_legacy1(raw_receipt_legacy):
response = itunesiap.verify(raw_receipt_legacy, env=itunesiap.env.sandbox)
return getattr(response, '_')
@pytest.fixture(scope='session')
def itunes_response_legacy2():
return {
u'status': 0,
u'receipt': {
u'purchase_date_pst': u'2013-01-01 00:00:00 America/Los_Angeles',
u'product_id': u'TestProduction1',
u'original_transaction_id': u'1000000012345678',
u'unique_identifier': u'bcbdb3d45543920dd9sd5c79a72948001fc22a39',
u'original_purchase_date_pst': u'2013-01-01 00:00:00 America/Los_Angeles',
u'original_purchase_date': u'2013-01-01 00:00:00 Etc/GMT',
u'bvrs': u'1.0',
u'original_purchase_date_ms': u'1348200000000',
u'purchase_date': u'2013-01-01 00:00:00 Etc/GMT',
u'item_id': u'500000000',
u'purchase_date_ms': u'134820000000',
u'bid': u'org.youknowone.itunesiap',
u'transaction_id': u'1000000012345678',
u'quantity': u'1'
}
}
@pytest.fixture(scope='session')
def itunes_autorenew_response_legacy():
"""https://gist.github.com/lxcid/4187607"""
return json.loads('''{
"status": 0,
"latest_receipt_info": {
"original_purchase_date_ms": "1354432554000",
"original_purchase_date_pst": "2012-12-01 23:15:54 America/Los_Angeles",
"transaction_id": "1000000059630000",
"quantity": "1",
"bid": "com.example.001",
"original_transaction_id": "1000000059630000",
"bvrs": "7",
"expires_date_formatted": "2012-12-02 08:15:54 Etc/GMT",
"purchase_date": "2012-12-02 07:15:54 Etc/GMT",
"expires_date": "1354436154000",
"product_id": "com.example.premium.1y",
"purchase_date_ms": "1354432554000",
"expires_date_formatted_pst": "2012-12-02 00:15:54 America/Los_Angeles",
"purchase_date_pst": "2012-12-01 23:15:54 America/Los_Angeles",
"original_purchase_date": "2012-12-02 07:15:54 Etc/GMT",
"item_id": "580190000",
"web_order_line_item_id": "1000000026430000",
"unique_identifier": "0000b0090000"
},
"receipt": {
"original_purchase_date_ms": "1354432554000",
"original_purchase_date_pst": "2012-12-01 23:15:54 America/Los_Angeles",
"transaction_id": "1000000059630000",
"quantity": "1",
"bid": "com.example.001",
"original_transaction_id": "1000000059630000",
"bvrs": "7",
"expires_date_formatted": "2012-12-02 08:15:54 Etc/GMT",
"purchase_date": "2012-12-02 07:15:54 Etc/GMT",
"expires_date": "1354436154000",
"product_id": "com.example.premium.1y",
"purchase_date_ms": "1354432554000",
"expires_date_formatted_pst": "2012-12-02 00:15:54 America/Los_Angeles",
"purchase_date_pst": "2012-12-01 23:15:54 America/Los_Angeles",
"original_purchase_date": "2012-12-02 07:15:54 Etc/GMT",
"item_id": "580190000",
"web_order_line_item_id": "1000000026430000",
"unique_identifier": "0000b0090000"
},
"latest_receipt": "__ACTUAL_BASE64_ENCODED_RECEIPT"
}''')
@pytest.fixture(scope='session')
def itunes_autorenew_response1():
return {
u'status': 0,
u'receipt': {
u'original_purchase_date_pst': u'2013-01-01 00:00:00 America/Los_Angeles',
u'version_external_identifier': 0,
u'original_purchase_date': u'2013-01-01 07:00:00 Etc/GMT',
u'in_app': [
{
u'is_trial_period': u'false',
u'purchase_date_pst': u'2013-05-18 20:21:09 America/Los_Angeles',
u'product_id': u'org.itunesiap',
u'original_transaction_id': u'1000000155715958',
u'original_purchase_date_pst': u'2013-05-18 19:29:45 America/Los_Angeles',
u'original_purchase_date': u'2013-05-19 02:29:45 Etc/GMT',
u'original_purchase_date_ms': u'1432002585000',
u'purchase_date': u'2013-05-19 03:21:09 Etc/GMT',
u'purchase_date_ms': u'1432005669000',
u'transaction_id': u'1000000155715958',
u'quantity': u'1'
},
{
u'is_trial_period': u'false',
u'purchase_date_pst': u'2013-05-19 20:21:09 America/Los_Angeles',
u'product_id': u'org.itunesiap',
u'original_transaction_id': u'1000000155718067',
u'original_purchase_date_pst': u'2013-05-18 19:37:10 America/Los_Angeles',
u'original_purchase_date': u'2013-05-19 02:37:10 Etc/GMT',
u'original_purchase_date_ms': u'1432003030000',
u'purchase_date': u'2013-05-19 03:21:09 Etc/GMT',
u'purchase_date_ms': u'1432005669000',
u'transaction_id': u'1000000155718067',
u'quantity': u'1'
}
]
}
}
@pytest.fixture(scope='session')
def itunes_autorenew_response2():
"""Contributed by Jonas Petersen @jox"""
return json.loads(r'''{
"status": 0,
"environment": "Sandbox",
"receipt": {
"receipt_type": "ProductionSandbox",
"adam_id": 0,
"app_item_id": 0,
"bundle_id": "com.example.app",
"application_version": "8",
"download_id": 0,
"version_external_identifier": 0,
"receipt_creation_date": "2017-07-25 09:01:20 Etc/GMT",
"receipt_creation_date_ms": "1500973280000",
"receipt_creation_date_pst": "2017-07-25 02:01:20 America/Los_Angeles",
"request_date": "2017-07-27 09:51:59 Etc/GMT",
"request_date_ms": "1501149119587",
"request_date_pst": "2017-07-27 02:51:59 America/Los_Angeles",
"original_purchase_date": "2013-08-01 07:00:00 Etc/GMT",
"original_purchase_date_ms": "1375340400000",
"original_purchase_date_pst": "2013-08-01 00:00:00 America/Los_Angeles",
"original_application_version": "1.0",
"in_app": [
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318012065",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:13:24 Etc/GMT",
"purchase_date_ms": "1500884004000",
"purchase_date_pst": "2017-07-24 01:13:24 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:18:24 Etc/GMT",
"expires_date_ms": "1500884304000",
"expires_date_pst": "2017-07-24 01:18:24 America/Los_Angeles",
"web_order_line_item_id": "1000000035712036",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318014271",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:20:19 Etc/GMT",
"purchase_date_ms": "1500884419000",
"purchase_date_pst": "2017-07-24 01:20:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:25:19 Etc/GMT",
"expires_date_ms": "1500884719000",
"expires_date_pst": "2017-07-24 01:25:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035712037",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318015678",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:25:19 Etc/GMT",
"purchase_date_ms": "1500884719000",
"purchase_date_pst": "2017-07-24 01:25:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:30:19 Etc/GMT",
"expires_date_ms": "1500885019000",
"expires_date_pst": "2017-07-24 01:30:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035712099",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318021093",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:32:23 Etc/GMT",
"purchase_date_ms": "1500885143000",
"purchase_date_pst": "2017-07-24 01:32:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:37:23 Etc/GMT",
"expires_date_ms": "1500885443000",
"expires_date_pst": "2017-07-24 01:37:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712148",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318022372",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:37:23 Etc/GMT",
"purchase_date_ms": "1500885443000",
"purchase_date_pst": "2017-07-24 01:37:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:42:23 Etc/GMT",
"expires_date_ms": "1500885743000",
"expires_date_pst": "2017-07-24 01:42:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712240",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318024256",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:42:23 Etc/GMT",
"purchase_date_ms": "1500885743000",
"purchase_date_pst": "2017-07-24 01:42:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:47:23 Etc/GMT",
"expires_date_ms": "1500886043000",
"expires_date_pst": "2017-07-24 01:47:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712292",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318060909",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:21:48 Etc/GMT",
"purchase_date_ms": "1500891708000",
"purchase_date_pst": "2017-07-24 03:21:48 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:26:48 Etc/GMT",
"expires_date_ms": "1500892008000",
"expires_date_pst": "2017-07-24 03:26:48 America/Los_Angeles",
"web_order_line_item_id": "1000000035712361",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318063451",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:26:51 Etc/GMT",
"purchase_date_ms": "1500892011000",
"purchase_date_pst": "2017-07-24 03:26:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:31:51 Etc/GMT",
"expires_date_ms": "1500892311000",
"expires_date_pst": "2017-07-24 03:31:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713600",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318065205",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:31:51 Etc/GMT",
"purchase_date_ms": "1500892311000",
"purchase_date_pst": "2017-07-24 03:31:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:36:51 Etc/GMT",
"expires_date_ms": "1500892611000",
"expires_date_pst": "2017-07-24 03:36:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713658",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318066018",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:36:51 Etc/GMT",
"purchase_date_ms": "1500892611000",
"purchase_date_pst": "2017-07-24 03:36:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:41:51 Etc/GMT",
"expires_date_ms": "1500892911000",
"expires_date_pst": "2017-07-24 03:41:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713715",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318067267",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:42:17 Etc/GMT",
"purchase_date_ms": "1500892937000",
"purchase_date_pst": "2017-07-24 03:42:17 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:47:17 Etc/GMT",
"expires_date_ms": "1500893237000",
"expires_date_pst": "2017-07-24 03:47:17 America/Los_Angeles",
"web_order_line_item_id": "1000000035713778",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318069609",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:47:17 Etc/GMT",
"purchase_date_ms": "1500893237000",
"purchase_date_pst": "2017-07-24 03:47:17 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:52:17 Etc/GMT",
"expires_date_ms": "1500893537000",
"expires_date_pst": "2017-07-24 03:52:17 America/Los_Angeles",
"web_order_line_item_id": "1000000035713845",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318407192",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:01:19 Etc/GMT",
"purchase_date_ms": "1500973279000",
"purchase_date_pst": "2017-07-25 02:01:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:06:19 Etc/GMT",
"expires_date_ms": "1500973579000",
"expires_date_pst": "2017-07-25 02:06:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035713887",
"is_trial_period": "false"
}
]
},
"latest_receipt_info": [
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318012065",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:13:24 Etc/GMT",
"purchase_date_ms": "1500884004000",
"purchase_date_pst": "2017-07-24 01:13:24 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:18:24 Etc/GMT",
"expires_date_ms": "1500884304000",
"expires_date_pst": "2017-07-24 01:18:24 America/Los_Angeles",
"web_order_line_item_id": "1000000035712036",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318014271",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:20:19 Etc/GMT",
"purchase_date_ms": "1500884419000",
"purchase_date_pst": "2017-07-24 01:20:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:25:19 Etc/GMT",
"expires_date_ms": "1500884719000",
"expires_date_pst": "2017-07-24 01:25:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035712037",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318015678",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:25:19 Etc/GMT",
"purchase_date_ms": "1500884719000",
"purchase_date_pst": "2017-07-24 01:25:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:30:19 Etc/GMT",
"expires_date_ms": "1500885019000",
"expires_date_pst": "2017-07-24 01:30:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035712099",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318021093",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:32:23 Etc/GMT",
"purchase_date_ms": "1500885143000",
"purchase_date_pst": "2017-07-24 01:32:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:37:23 Etc/GMT",
"expires_date_ms": "1500885443000",
"expires_date_pst": "2017-07-24 01:37:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712148",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318022372",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:37:23 Etc/GMT",
"purchase_date_ms": "1500885443000",
"purchase_date_pst": "2017-07-24 01:37:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:42:23 Etc/GMT",
"expires_date_ms": "1500885743000",
"expires_date_pst": "2017-07-24 01:42:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712240",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318024256",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 08:42:23 Etc/GMT",
"purchase_date_ms": "1500885743000",
"purchase_date_pst": "2017-07-24 01:42:23 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 08:47:23 Etc/GMT",
"expires_date_ms": "1500886043000",
"expires_date_pst": "2017-07-24 01:47:23 America/Los_Angeles",
"web_order_line_item_id": "1000000035712292",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318060909",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:21:48 Etc/GMT",
"purchase_date_ms": "1500891708000",
"purchase_date_pst": "2017-07-24 03:21:48 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:26:48 Etc/GMT",
"expires_date_ms": "1500892008000",
"expires_date_pst": "2017-07-24 03:26:48 America/Los_Angeles",
"web_order_line_item_id": "1000000035712361",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318063451",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:26:51 Etc/GMT",
"purchase_date_ms": "1500892011000",
"purchase_date_pst": "2017-07-24 03:26:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:31:51 Etc/GMT",
"expires_date_ms": "1500892311000",
"expires_date_pst": "2017-07-24 03:31:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713600",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318065205",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:31:51 Etc/GMT",
"purchase_date_ms": "1500892311000",
"purchase_date_pst": "2017-07-24 03:31:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:36:51 Etc/GMT",
"expires_date_ms": "1500892611000",
"expires_date_pst": "2017-07-24 03:36:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713658",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318066018",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:36:51 Etc/GMT",
"purchase_date_ms": "1500892611000",
"purchase_date_pst": "2017-07-24 03:36:51 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:41:51 Etc/GMT",
"expires_date_ms": "1500892911000",
"expires_date_pst": "2017-07-24 03:41:51 America/Los_Angeles",
"web_order_line_item_id": "1000000035713715",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318067267",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:42:17 Etc/GMT",
"purchase_date_ms": "1500892937000",
"purchase_date_pst": "2017-07-24 03:42:17 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:47:17 Etc/GMT",
"expires_date_ms": "1500893237000",
"expires_date_pst": "2017-07-24 03:47:17 America/Los_Angeles",
"web_order_line_item_id": "1000000035713778",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318069609",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-24 10:47:17 Etc/GMT",
"purchase_date_ms": "1500893237000",
"purchase_date_pst": "2017-07-24 03:47:17 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-24 10:52:17 Etc/GMT",
"expires_date_ms": "1500893537000",
"expires_date_pst": "2017-07-24 03:52:17 America/Los_Angeles",
"web_order_line_item_id": "1000000035713845",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318407192",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:01:19 Etc/GMT",
"purchase_date_ms": "1500973279000",
"purchase_date_pst": "2017-07-25 02:01:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:06:19 Etc/GMT",
"expires_date_ms": "1500973579000",
"expires_date_pst": "2017-07-25 02:06:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035713887",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318408761",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:06:19 Etc/GMT",
"purchase_date_ms": "1500973579000",
"purchase_date_pst": "2017-07-25 02:06:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:11:19 Etc/GMT",
"expires_date_ms": "1500973879000",
"expires_date_pst": "2017-07-25 02:11:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035725079",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318410476",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:11:19 Etc/GMT",
"purchase_date_ms": "1500973879000",
"purchase_date_pst": "2017-07-25 02:11:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:16:19 Etc/GMT",
"expires_date_ms": "1500974179000",
"expires_date_pst": "2017-07-25 02:16:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035725139",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318413351",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:16:19 Etc/GMT",
"purchase_date_ms": "1500974179000",
"purchase_date_pst": "2017-07-25 02:16:19 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:21:19 Etc/GMT",
"expires_date_ms": "1500974479000",
"expires_date_pst": "2017-07-25 02:21:19 America/Los_Angeles",
"web_order_line_item_id": "1000000035725196",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318417975",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:23:30 Etc/GMT",
"purchase_date_ms": "1500974610000",
"purchase_date_pst": "2017-07-25 02:23:30 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:28:30 Etc/GMT",
"expires_date_ms": "1500974910000",
"expires_date_pst": "2017-07-25 02:28:30 America/Los_Angeles",
"web_order_line_item_id": "1000000035725250",
"is_trial_period": "false"
},
{
"quantity": "1",
"product_id": "testproduct",
"transaction_id": "1000000318420598",
"original_transaction_id": "1000000318012065",
"purchase_date": "2017-07-25 09:28:30 Etc/GMT",
"purchase_date_ms": "1500974910000",
"purchase_date_pst": "2017-07-25 02:28:30 America/Los_Angeles",
"original_purchase_date": "2017-07-24 08:13:25 Etc/GMT",
"original_purchase_date_ms": "1500884005000",
"original_purchase_date_pst": "2017-07-24 01:13:25 America/Los_Angeles",
"expires_date": "2017-07-25 09:33:30 Etc/GMT",
"expires_date_ms": "1500975210000",
"expires_date_pst": "2017-07-25 02:33:30 America/Los_Angeles",
"web_order_line_item_id": "1000000035725368",
"is_trial_period": "false"
}
],
"latest_receipt": "DUMMY_RECEIPT:_A_BASE64_ENCODED_RECEIPT_DATA_WILL_BE_HERE",
"pending_renewal_info": [
{
"expiration_intent": "1",
"auto_renew_product_id": "testproduct",
"is_in_billing_retry_period": "0",
"product_id": "testproduct",
"auto_renew_status": "0"
}
]
}''')
@pytest.fixture(scope='session')
def itunes_autorenew_response3():
"""Contributed by François Dupayrat @FrancoisDupayrat"""
return json.loads(r'''{
"auto_renew_status": 1,
"status": 0,
"auto_renew_product_id": "******************************",
"receipt":{
"original_purchase_date_pst":"2017-06-28 07:31:51 America/Los_Angeles",
"unique_identifier":"******************************",
"original_transaction_id":"******************************",
"expires_date":"1506524970000",
"transaction_id":"******************************",
"quantity":"1",
"product_id":"******************************",
"item_id":"******************************",
"bid":"******************************",
"unique_vendor_identifier":"******************************",
"web_order_line_item_id":"******************************",
"bvrs":"1.1.6",
"expires_date_formatted":"2017-09-27 15:09:30 Etc/GMT",
"purchase_date":"2017-09-27 15:04:30 Etc/GMT",
"purchase_date_ms":"1506524670000",
"expires_date_formatted_pst":"2017-09-27 08:09:30 America/Los_Angeles",
"purchase_date_pst":"2017-09-27 08:04:30 America/Los_Angeles",
"original_purchase_date":"2017-06-28 14:31:51 Etc/GMT",
"original_purchase_date_ms":"1498660311000"
},
"latest_receipt_info":{
"original_purchase_date_pst":"2017-06-28 07:31:51 America/Los_Angeles",
"unique_identifier":"******************************",
"original_transaction_id":"******************************",
"expires_date":"******************************",
"transaction_id":"******************************",
"quantity":"1",
"product_id":"******************************",
"item_id":"******************************",
"bid":"******************************",
"unique_vendor_identifier":"******************************",
"web_order_line_item_id":"******************************",
"bvrs":"1.1.6",
"expires_date_formatted":"2017-09-27 15:09:30 Etc/GMT",
"purchase_date":"2017-09-27 15:04:30 Etc/GMT",
"purchase_date_ms":"1506524670000",
"expires_date_formatted_pst":"2017-09-27 08:09:30 America/Los_Angeles",
"purchase_date_pst":"2017-09-27 08:04:30 America/Los_Angeles",
"original_purchase_date":"2017-06-28 14:31:51 Etc/GMT",
"original_purchase_date_ms":"1498660311000"
},
"latest_receipt":"******************************"
}''')
@pytest.fixture(params=[
lazy_fixture('itunes_autorenew_response1'),
lazy_fixture('itunes_autorenew_response2'),
lazy_fixture('itunes_autorenew_response3'),
])
def itunes_autorenew_response(request):
return request.param
| 51.762467 | 3,065 | 0.621454 | 4,320 | 39,443 | 5.377546 | 0.059491 | 0.120356 | 0.05441 | 0.053162 | 0.790668 | 0.783996 | 0.768972 | 0.74943 | 0.745556 | 0.736688 | 0 | 0.228281 | 0.234237 | 39,443 | 761 | 3,066 | 51.830486 | 0.540856 | 0.003625 | 0 | 0.725304 | 0 | 0 | 0.943207 | 0.316091 | 0 | 1 | 0 | 0 | 0 | 1 | 0.010825 | false | 0 | 0.005413 | 0.005413 | 0.027064 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 |
f83c2c2d711f1b12871076efd965b1f4e22f6ebe | 176 | py | Python | tests/test_print_metadata.py | mmore500/nbmetalog | 670f8ad76a587d8848c81e4f790c31c96402f8b0 | [
"MIT"
] | null | null | null | tests/test_print_metadata.py | mmore500/nbmetalog | 670f8ad76a587d8848c81e4f790c31c96402f8b0 | [
"MIT"
] | 1 | 2021-09-02T16:08:58.000Z | 2021-09-02T16:08:58.000Z | tests/test_print_metadata.py | mmore500/nbmetalog | 670f8ad76a587d8848c81e4f790c31c96402f8b0 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
'''
`dub` tests for `nbmetalog` package.
'''
import pytest
from nbmetalog import nbmetalog as nbm
def test_print_metadata():
nbm.print_metadata()
| 13.538462 | 38 | 0.715909 | 24 | 176 | 5.125 | 0.75 | 0.211382 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.159091 | 176 | 12 | 39 | 14.666667 | 0.831081 | 0.323864 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | true | 0 | 0.5 | 0 | 0.75 | 0.5 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 7 |
3e39670317f92a3b20f249445e0b26bb95175921 | 4,823 | py | Python | tests/test_matadj.py | manik-hossain/torchkbnufft | 07376b15c9d4b7b5c82233f80e60b9f44b075fd9 | [
"MIT"
] | null | null | null | tests/test_matadj.py | manik-hossain/torchkbnufft | 07376b15c9d4b7b5c82233f80e60b9f44b075fd9 | [
"MIT"
] | null | null | null | tests/test_matadj.py | manik-hossain/torchkbnufft | 07376b15c9d4b7b5c82233f80e60b9f44b075fd9 | [
"MIT"
] | null | null | null | import sys
import numpy as np
import torch
from torchkbnufft import (AdjKbNufft, AdjMriSenseNufft, KbInterpBack,
KbInterpForw, KbNufft, MriSenseNufft)
from torchkbnufft.math import inner_product
norm_tol = 1e-10
def test_interp_2d_matadj():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 2, klength)).to(dtype)
adjkbinterp_ob = KbInterpBack(
im_size=(20, 25), grid_size=im_size, numpoints=(4, 6))
adjkbinterp_matadj_ob = KbInterpBack(
im_size=(20, 25), grid_size=im_size, numpoints=(4, 6), matadj=True)
x_normal = adjkbinterp_ob(y, ktraj)
x_matadj = adjkbinterp_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) / torch.norm(x_normal) < norm_tol
def test_nufft_2d_matadj():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 2, klength)).to(dtype)
adjkbnufft_ob = AdjKbNufft(
im_size=im_size, numpoints=(4, 6))
adjkbnufft_matadj_ob = AdjKbNufft(
im_size=im_size, numpoints=(4, 6), matadj=True)
x_normal = adjkbnufft_ob(y, ktraj)
x_matadj = adjkbnufft_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) / torch.norm(x_normal) < norm_tol
def test_mrisensenufft_2d_matadj():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 2, klength)).to(dtype)
smap_sz = (nslice, ncoil, 2) + im_size
smap = torch.randn(*smap_sz).to(dtype)
adjsensenufft_ob = AdjMriSenseNufft(smap=smap, im_size=im_size)
adjsensenufft_matadj_ob = AdjMriSenseNufft(
smap=smap, im_size=im_size, matadj=True)
x_normal = adjsensenufft_ob(y, ktraj)
x_matadj = adjsensenufft_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) / torch.norm(x_normal) < norm_tol
def test_interp_3d_adjoint():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (11, 33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 3, klength)).to(dtype)
adjkbinterp_ob = KbInterpBack(
im_size=(5, 20, 25), grid_size=im_size, numpoints=(2, 4, 6))
adjkbinterp_matadj_ob = KbInterpBack(
im_size=(5, 20, 25), grid_size=im_size, numpoints=(2, 4, 6), matadj=True)
x_normal = adjkbinterp_ob(y, ktraj)
x_matadj = adjkbinterp_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) < norm_tol
def test_nufft_3d_matadj():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (11, 33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 3, klength)).to(dtype)
adjkbnufft_ob = AdjKbNufft(
im_size=im_size, numpoints=(2, 4, 6))
adjkbnufft_matadj_ob = AdjKbNufft(
im_size=im_size, numpoints=(2, 4, 6), matadj=True)
x_normal = adjkbnufft_ob(y, ktraj)
x_matadj = adjkbnufft_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) / torch.norm(x_normal) < norm_tol
def test_mrisensenufft_3d_matadj():
dtype = torch.double
nslice = 2
ncoil = 4
im_size = (11, 33, 24)
klength = 112
y = np.random.normal(size=(nslice, ncoil, klength)) + \
1j*np.random.normal(size=(nslice, ncoil, klength))
y = torch.tensor(np.stack((np.real(y), np.imag(y)), axis=2)).to(dtype)
ktraj = torch.randn(*(nslice, 3, klength)).to(dtype)
smap_sz = (nslice, ncoil, 2) + im_size
smap = torch.randn(*smap_sz).to(dtype)
adjsensenufft_ob = AdjMriSenseNufft(smap=smap, im_size=im_size)
adjsensenufft_matadj_ob = AdjMriSenseNufft(
smap=smap, im_size=im_size, matadj=True)
x_normal = adjsensenufft_ob(y, ktraj)
x_matadj = adjsensenufft_matadj_ob(y, ktraj)
assert torch.norm(x_normal - x_matadj) / torch.norm(x_normal) < norm_tol
| 29.230303 | 81 | 0.654779 | 708 | 4,823 | 4.275424 | 0.097458 | 0.063429 | 0.055501 | 0.071358 | 0.932607 | 0.924678 | 0.924678 | 0.924678 | 0.906178 | 0.906178 | 0 | 0.033133 | 0.205266 | 4,823 | 164 | 82 | 29.408537 | 0.756588 | 0 | 0 | 0.801802 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.054054 | 1 | 0.054054 | false | 0 | 0.045045 | 0 | 0.099099 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
3e48afd7ea7f5f2bbb2ff077b35d0d9ae7ce43b0 | 265 | py | Python | deco/__init__.py | mfojtak/decor | 203979351635a6794c91200fca4a14296ec9bc37 | [
"MIT"
] | 1 | 2019-09-05T07:23:19.000Z | 2019-09-05T07:23:19.000Z | deco/__init__.py | mfojtak/decor | 203979351635a6794c91200fca4a14296ec9bc37 | [
"MIT"
] | 2 | 2020-10-25T17:41:08.000Z | 2020-10-26T16:48:19.000Z | deco/__init__.py | mfojtak/deco | 203979351635a6794c91200fca4a14296ec9bc37 | [
"MIT"
] | null | null | null | #from deco import tokenizers
#from deco import schedules
#from deco import layers
#from deco import nodes
#from deco import executors
#from deco import sources
#from deco import sinks
#from deco.deco import get_custom_objects
from deco.deco import default_executor
| 26.5 | 41 | 0.826415 | 41 | 265 | 5.268293 | 0.365854 | 0.333333 | 0.453704 | 0.166667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135849 | 265 | 9 | 42 | 29.444444 | 0.943231 | 0.792453 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
3e610201c7fda9ffd562212b4107287177968857 | 26,518 | py | Python | annofabcli/statistics/visualization/dataframe/cumulative_productivity.py | kurusugawa-computer/annofab-cli | 8edad492d439bc8fe64e9471464f545d07aba8b7 | [
"MIT"
] | 9 | 2019-07-22T23:54:05.000Z | 2020-11-05T06:26:04.000Z | annofabcli/statistics/visualization/dataframe/cumulative_productivity.py | kurusugawa-computer/annofab-cli | 8edad492d439bc8fe64e9471464f545d07aba8b7 | [
"MIT"
] | 389 | 2019-07-03T04:39:11.000Z | 2022-03-28T14:06:11.000Z | annofabcli/statistics/visualization/dataframe/cumulative_productivity.py | kurusugawa-computer/annofab-cli | 8edad492d439bc8fe64e9471464f545d07aba8b7 | [
"MIT"
] | 1 | 2021-08-30T14:22:04.000Z | 2021-08-30T14:22:04.000Z | # pylint: disable=too-many-lines
"""
累積の生産性に関する内容
"""
from __future__ import annotations
import abc
import logging
from pathlib import Path
from typing import Optional
import bokeh
import bokeh.layouts
import bokeh.palettes
import pandas
from bokeh.plotting import ColumnDataSource, figure
from annofabcli.statistics.linegraph import (
add_legend_to_figure,
create_hover_tool,
get_color_from_palette,
get_plotted_user_id_list,
plot_line_and_circle,
write_bokeh_graph,
)
logger = logging.getLogger(__name__)
class AbstractRoleCumulativeProductivity(abc.ABC):
"""ロールごとの累積の生産性をプロットするための抽象クラス"""
PLOT_WIDTH = 1200
PLOT_HEIGHT = 600
def __init__(self, df: pandas.DataFrame, phase: str) -> None:
self.df = df
self.phase = phase
self.phase_name = self._get_phase_name(phase)
self.df_cumulative = self._get_cumulative_dataframe()
self.default_user_id_list = self._get_default_user_id_list()
@staticmethod
def _get_phase_name(phase: str) -> str:
if phase == "annotation":
return "教師付"
elif phase == "inspection":
return "検査"
elif phase == "acceptance":
return "受入"
raise RuntimeError(f"phase='{phase}'が対象外です。")
def _get_default_user_id_list(self) -> list[str]:
return (
self.df.sort_values(by=f"first_{self.phase}_started_datetime", ascending=False)[
f"first_{self.phase}_user_id"
]
.dropna()
.unique()
.tolist()
)
def _validate_df_for_output(self, output_file: Path) -> bool:
if len(self.df) == 0:
logger.warning(f"データが0件のため、{output_file} は出力しません。")
return False
if len(self.default_user_id_list) == 0:
logger.warning(
f"{self.phase_name} 作業したタスクが0件なので('first_{self.phase}_user_id'がすべて空欄)、{output_file} を出力しません。"
)
return False
return True
@abc.abstractmethod
def _get_cumulative_dataframe(self) -> pandas.DataFrame:
pass
@abc.abstractmethod
def plot_annotation_metrics(self, output_file: Path, target_user_id_list: Optional[list[str]] = None):
pass
@abc.abstractmethod
def plot_input_data_metrics(self, output_file: Path, target_user_id_list: Optional[list[str]] = None):
pass
class AnnotatorCumulativeProductivity(AbstractRoleCumulativeProductivity):
def __init__(self, df: pandas.DataFrame):
super().__init__(df, phase="annotation")
def _get_cumulative_dataframe(self) -> pandas.DataFrame:
"""
累積情報が格納されたDataFrameを生成する。
"""
# 教師付の開始時刻でソートして、indexを更新する
df = self.df.sort_values(["first_annotation_user_id", "first_annotation_started_datetime"]).reset_index(
drop=True
)
# タスクの累計数を取得するために設定する
df["task_count"] = 1
# 教師付の作業者でgroupby
groupby_obj = df.groupby("first_annotation_user_id")
# 作業時間の累積値
df["cumulative_annotation_worktime_hour"] = groupby_obj["annotation_worktime_hour"].cumsum()
df["cumulative_acceptance_worktime_hour"] = groupby_obj["acceptance_worktime_hour"].cumsum()
df["cumulative_inspection_worktime_hour"] = groupby_obj["inspection_worktime_hour"].cumsum()
# タスク完了数、差し戻し数など
df["cumulative_inspection_count"] = groupby_obj["inspection_count"].cumsum()
df["cumulative_annotation_count"] = groupby_obj["annotation_count"].cumsum()
df["cumulative_input_data_count"] = groupby_obj["input_data_count"].cumsum()
df["cumulative_task_count"] = groupby_obj["task_count"].cumsum()
df["cumulative_number_of_rejections"] = groupby_obj["number_of_rejections"].cumsum()
df["cumulative_number_of_rejections_by_inspection"] = groupby_obj["number_of_rejections_by_inspection"].cumsum()
df["cumulative_number_of_rejections_by_acceptance"] = groupby_obj["number_of_rejections_by_acceptance"].cumsum()
# 元に戻す
df = df.drop(["task_count"], axis=1)
return df
def plot_annotation_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
生産性を教師付作業者ごとにプロットする。
Args:
df:
first_annotation_user_id_list:
Returns:
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積のアノテーション数と教師付作業時間",
y_column_name="cumulative_annotation_worktime_hour",
y_axis_label="教師付作業時間[hour]",
),
dict(
title="累積のアノテーション数と検査作業時間",
y_column_name="cumulative_inspection_worktime_hour",
y_axis_label="検査作業時間[hour]",
),
dict(
title="累積のアノテーション数と受入作業時間",
y_column_name="cumulative_acceptance_worktime_hour",
y_axis_label="受入作業時間[hour]",
),
dict(
title="累積のアノテーション数と検査コメント数",
y_column_name="cumulative_inspection_count",
y_axis_label="検査コメント数",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="アノテーション数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_annotation_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_annotation_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_annotation_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_annotation_user_id",
"first_annotation_username",
"first_annotation_started_datetime",
"annotation_worktime_hour",
"inspection_worktime_hour",
"acceptance_worktime_hour",
"annotation_count",
"input_data_count",
"inspection_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
def plot_input_data_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
教師付者の累積値を入力データ単位でプロットする。
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積の入力データ数と教師付作業時間",
y_column_name="cumulative_annotation_worktime_hour",
y_axis_label="教師付作業時間[hour]",
),
dict(
title="累積の入力データ数と検査作業時間",
y_column_name="cumulative_inspection_worktime_hour",
y_axis_label="検査作業時間[hour]",
),
dict(
title="累積の入力データ数と受入作業時間",
y_column_name="cumulative_acceptance_worktime_hour",
y_axis_label="受入作業時間[hour]",
),
dict(
title="累積の入力データ数と検査コメント数",
y_column_name="cumulative_inspection_count",
y_axis_label="検査コメント数",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="入力データ数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_annotation_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_annotation_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_input_data_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_annotation_user_id",
"first_annotation_username",
"first_annotation_started_datetime",
"annotation_worktime_hour",
"inspection_worktime_hour",
"acceptance_worktime_hour",
"annotation_count",
"input_data_count",
"inspection_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
def plot_task_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
教師付者の累積値を入力データ単位でプロットする。
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積のタスク数と教師付作業時間",
y_column_name="cumulative_annotation_worktime_hour",
y_axis_label="教師付作業時間[hour]",
),
dict(
title="累積のタスク数と差し戻し回数(検査フェーズ)",
y_column_name="cumulative_number_of_rejections_by_inspection",
y_axis_label="差し戻し回数(検査フェーズ)",
),
dict(
title="累積のタスク数と差し戻し回数(受入フェーズ)",
y_column_name="cumulative_number_of_rejections_by_acceptance",
y_axis_label="差し戻し回数(受入フェーズ)",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="タスク数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_annotation_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_annotation_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_task_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_annotation_user_id",
"first_annotation_username",
"first_annotation_started_datetime",
"annotation_worktime_hour",
"annotation_count",
"input_data_count",
"number_of_rejections_by_inspection",
"number_of_rejections_by_acceptance",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
class InspectorCumulativeProductivity(AbstractRoleCumulativeProductivity):
def __init__(self, df: pandas.DataFrame):
super().__init__(df, phase="inspection")
def _get_cumulative_dataframe(self) -> pandas.DataFrame:
"""
最初のアノテーション作業の開始時刻の順にソートして、検査者に関する累計値を算出する
Args:
task_df: タスク一覧のDataFrame. 列が追加される
"""
df = self.df.sort_values(["first_inspection_user_id", "first_inspection_started_datetime"]).reset_index(
drop=True
)
groupby_obj = df.groupby("first_inspection_user_id")
# 作業時間の累積値
df["cumulative_inspection_worktime_hour"] = groupby_obj["inspection_worktime_hour"].cumsum()
df["cumulative_inspection_count"] = groupby_obj["inspection_count"].cumsum()
df["cumulative_annotation_count"] = groupby_obj["annotation_count"].cumsum()
df["cumulative_input_data_count"] = groupby_obj["input_data_count"].cumsum()
return df
def plot_annotation_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
生産性を検査作業者ごとにプロットする。
Args:
df:
first_inspection_user_id_list:
Returns:
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積のアノテーション数と検査作業時間",
y_column_name="cumulative_inspection_worktime_hour",
y_axis_label="検査作業時間[hour]",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="アノテーション数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_inspection_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_inspection_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_annotation_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_inspection_user_id",
"first_inspection_username",
"first_inspection_started_datetime",
"inspection_worktime_hour",
"annotation_count",
"input_data_count",
"inspection_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
def plot_input_data_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
検査者の累積値を入力データ単位でプロットする。
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積の入力データ数と検査作業時間",
y_column_name="cumulative_inspection_worktime_hour",
y_axis_label="検査作業時間[hour]",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="入力データ数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_inspection_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_inspection_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_input_data_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_inspection_user_id",
"first_inspection_username",
"first_inspection_started_datetime",
"inspection_worktime_hour",
"annotation_count",
"input_data_count",
"inspection_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
class AcceptorCumulativeProductivity(AbstractRoleCumulativeProductivity):
def __init__(self, df: pandas.DataFrame):
super().__init__(df, phase="acceptance")
def _get_cumulative_dataframe(self) -> pandas.DataFrame:
"""
最初のアノテーション作業の開始時刻の順にソートして、受入者に関する累計値を算出する
"""
df = self.df.sort_values(["first_acceptance_user_id", "first_acceptance_started_datetime"]).reset_index(
drop=True
)
groupby_obj = df.groupby("first_acceptance_user_id")
# 作業時間の累積値
df["cumulative_acceptance_worktime_hour"] = groupby_obj["acceptance_worktime_hour"].cumsum()
df["cumulative_annotation_count"] = groupby_obj["annotation_count"].cumsum()
df["cumulative_input_data_count"] = groupby_obj["input_data_count"].cumsum()
return df
def plot_annotation_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
生産性を受入作業者ごとにプロットする。
Args:
df:
first_acceptance_user_id_list:
Returns:
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積のアノテーション数と受入作業時間",
y_column_name="cumulative_acceptance_worktime_hour",
y_axis_label="受入作業時間[hour]",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="アノテーション数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_acceptance_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_acceptance_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_annotation_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_acceptance_user_id",
"first_acceptance_username",
"first_acceptance_started_datetime",
"acceptance_worktime_hour",
"annotation_count",
"input_data_count",
"inspection_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
def plot_input_data_metrics(
self,
output_file: Path,
target_user_id_list: Optional[list[str]] = None,
):
"""
受入者の累積値を入力データ単位でプロットする。
"""
if not self._validate_df_for_output(output_file):
return
logger.debug(f"{output_file} を出力します。")
if target_user_id_list is not None:
user_id_list = target_user_id_list
else:
user_id_list = self.default_user_id_list
user_id_list = get_plotted_user_id_list(user_id_list)
fig_info_list = [
dict(
title="累積の入力データ数と受入作業時間",
y_column_name="cumulative_acceptance_worktime_hour",
y_axis_label="受入作業時間[hour]",
),
]
figs: list[bokeh.plotting.Figure] = []
for fig_info in fig_info_list:
figs.append(
figure(
plot_width=self.PLOT_WIDTH,
plot_height=self.PLOT_HEIGHT,
title=fig_info["title"],
x_axis_label="入力データ数",
y_axis_label=fig_info["y_axis_label"],
)
)
for user_index, user_id in enumerate(user_id_list):
df_subset = self.df_cumulative[self.df_cumulative["first_acceptance_user_id"] == user_id]
if df_subset.empty:
logger.debug(f"dataframe is empty. user_id = {user_id}")
continue
source = ColumnDataSource(data=df_subset)
color = get_color_from_palette(user_index)
username = df_subset.iloc[0]["first_acceptance_username"]
for fig, fig_info in zip(figs, fig_info_list):
plot_line_and_circle(
fig,
x_column_name="cumulative_input_data_count",
y_column_name=fig_info["y_column_name"],
source=source,
legend_label=username,
color=color,
)
hover_tool = create_hover_tool(
[
"task_id",
"phase",
"status",
"first_acceptance_user_id",
"first_acceptance_username",
"first_acceptance_started_datetime",
"acceptance_worktime_hour",
"annotation_count",
"input_data_count",
"acceptance_count",
]
)
for fig in figs:
fig.add_tools(hover_tool)
add_legend_to_figure(fig)
write_bokeh_graph(bokeh.layouts.column(figs), output_file)
| 32.900744 | 120 | 0.563165 | 2,739 | 26,518 | 5.014239 | 0.071924 | 0.056793 | 0.05825 | 0.026795 | 0.86588 | 0.8361 | 0.809961 | 0.795908 | 0.779889 | 0.779889 | 0 | 0.001164 | 0.352176 | 26,518 | 805 | 121 | 32.941615 | 0.7983 | 0.025417 | 0 | 0.76699 | 0 | 0.001618 | 0.193962 | 0.123184 | 0 | 0 | 0 | 0 | 0 | 1 | 0.032362 | false | 0.004854 | 0.017799 | 0.001618 | 0.087379 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
e49ab17aad365ded4ddce656b42b544eab2d1e96 | 6,033 | py | Python | short-truth-NNE.py | Jah-On/short-truth | 54138ca8a5eae7672f97265f57a20a6d60c7863b | [
"CC0-1.0"
] | null | null | null | short-truth-NNE.py | Jah-On/short-truth | 54138ca8a5eae7672f97265f57a20a6d60c7863b | [
"CC0-1.0"
] | null | null | null | short-truth-NNE.py | Jah-On/short-truth | 54138ca8a5eae7672f97265f57a20a6d60c7863b | [
"CC0-1.0"
] | null | null | null | import httpx
import time
import datetime
import sys
if (len(sys.argv) != 2):
raise Exception("Invalid arguments!")
baseURL = ["https://cdn.finra.org/equity/regsho/daily/", "shvol", ".txt"]
def main(args):
ticker = bytes(args[1].upper(), "utf-8")
request = httpx.get("https://finance.yahoo.com/quote/" + args[1])
if (request.status_code != 200):
raise Exception("Symbol not found!")
data = request.read()
symdex = data.find(b'floatShares":{"raw":')
floatShares = int(data[symdex + 20 : symdex + data[symdex:].index(b',')])
totalShortVolume = 0
failedRequests = 0
year = "2009"
for month in ["08", "09", "10", "11", "12"]:
for day in ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"]:
for exchange in ["FNYX", "FNSQ", "FNQC"]:
pastTime = time.time()
try:
request = httpx.get(baseURL[0] + exchange + baseURL[1] + year + month + day + baseURL[2])
except:
failedRequests += 1
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
if (request.status_code != 200):
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
data = request.read()
symdex = data.find(b'|' + ticker + b'|')
if (symdex == -1):
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
try:
data = data[data[:symdex].rfind(b'\n') + 1 : symdex + data[symdex:].find(b'\r')]
dataList = data.split(b'|')
offset = 6 - len(dataList)
# Data format --> Date|Symbol|ShortVolume|ShortExemptVolume|TotalVolume|Market OR Date|Symbol|ShortVolume|TotalVolume|Market
totalVolume = int(dataList[4 - offset])
if (offset):
shortVolume = int(dataList[2])
else:
shortVolume = int(dataList[2]) - int(dataList[3])
nonShortVolume = totalVolume - shortVolume
uncoveredVolume = shortVolume - nonShortVolume
totalShortVolume += uncoveredVolume
if (totalShortVolume < 0):
totalShortVolume = 0
except:
pass
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
for year in ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021"]:
for month in ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]:
for day in ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"]:
for exchange in ["FNYX", "FNSQ", "FNQC"]:
pastTime = time.time()
try:
request = httpx.get(baseURL[0] + exchange + baseURL[1] + year + month + day + baseURL[2])
except:
failedRequests += 1
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
if (request.status_code != 200):
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
data = request.read()
symdex = data.find(b'|GME|')
if (symdex == -1):
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
continue
try:
data = data[data[:symdex].rfind(b'\n') + 1 : symdex + data[symdex:].find(b'\n') - 1]
dataList = data.split(b'|')
offset = 6 - len(dataList)
# Data format --> Date|Symbol|ShortVolume|ShortExemptVolume|TotalVolume|Market OR Date|Symbol|ShortVolume|TotalVolume|Market
totalVolume = int(dataList[4 - offset])
if (offset):
shortVolume = int(dataList[2])
else:
shortVolume = int(dataList[2]) - int(dataList[3])
nonShortVolume = totalVolume - shortVolume
uncoveredVolume = shortVolume - nonShortVolume
totalShortVolume += uncoveredVolume
if (totalShortVolume < 0):
totalShortVolume = 0
except:
pass
try:
time.sleep(1 - (time.time() - pastTime))
except:
pass
print("Failed requests: " + str(failedRequests))
print(totalShortVolume)
print("or ...")
print(str(round((totalShortVolume/floatShares) * 100, 2)) + "% of the current float.")
if (__name__ == "__main__"):
main(sys.argv) | 48.264 | 210 | 0.403613 | 520 | 6,033 | 4.661538 | 0.280769 | 0.033003 | 0.039604 | 0.042904 | 0.760726 | 0.75165 | 0.75165 | 0.739274 | 0.739274 | 0.739274 | 0 | 0.081445 | 0.458644 | 6,033 | 125 | 211 | 48.264 | 0.660747 | 0.04061 | 0 | 0.764706 | 0 | 0 | 0.077601 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.008403 | false | 0.084034 | 0.033613 | 0 | 0.042017 | 0.033613 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 7 |
e4a70a557d7b07bb2d919a5b0ded03285aed5d1b | 2,505 | py | Python | tests/test_traverse.py | camminady/PLEIP | ddb06f70a47a75742e9bb61a18188a0f54eaa6d8 | [
"MIT"
] | null | null | null | tests/test_traverse.py | camminady/PLEIP | ddb06f70a47a75742e9bb61a18188a0f54eaa6d8 | [
"MIT"
] | null | null | null | tests/test_traverse.py | camminady/PLEIP | ddb06f70a47a75742e9bb61a18188a0f54eaa6d8 | [
"MIT"
] | 1 | 2020-02-20T10:14:49.000Z | 2020-02-20T10:14:49.000Z | from pleip.traverse import nextcell
import numpy as np
import pytest
def test_nextcell_horiverti():
pos = np.array([0.5, 0.5])
velocity = np.array([0.0, 1.0])
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == 0
assert nextj == 1
assert np.isclose(dist, 0.5)
velocity = np.array([1.0, 0.0])
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == 1
assert nextj == 0
assert np.isclose(dist, 0.5)
velocity = np.array([0.0, -1.0])
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == 0
assert nextj == -1
assert np.isclose(dist, 0.5)
velocity = np.array([-1.0, 0.0])
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == -1
assert nextj == 0
assert np.isclose(dist, 0.5)
def test_nextcell_diagonal():
pos = np.array([0.5, 0.5])
sq2 = np.sqrt(2)
velocity = np.array([1.0, 1.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == 1
assert nextj == 1
assert np.isclose(dist, 1 / sq2)
velocity = np.array([1.0, -1.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == 1
assert nextj == -1
assert np.isclose(dist, 1 / sq2)
velocity = np.array([-1.0, 1.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == -1
assert nextj == 1
assert np.isclose(dist, 1 / sq2)
velocity = np.array([-1.0, -1.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
assert nexti == -1
assert nextj == -1
assert np.isclose(dist, 1 / sq2)
def test_nextcell_rais():
pos = np.array([2.5, 0.5])
sq2 = np.sqrt(2)
velocity = np.array([1.0, 1.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
with pytest.raises(ValueError):
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
pos = np.array([0.5, 0.5])
velocity = np.array([0.0, 0.0]) / sq2
x0, x1, y0, y1 = 0.0, 1.0, 0.0, 1.0
with pytest.raises(ValueError):
nexti, nextj, dist = nextcell(pos, velocity, x0, x1, y0, y1)
| 30.54878 | 68 | 0.560479 | 459 | 2,505 | 3.045752 | 0.076253 | 0.055794 | 0.05794 | 0.062947 | 0.902718 | 0.902718 | 0.902718 | 0.89485 | 0.89485 | 0.89485 | 0 | 0.139009 | 0.259082 | 2,505 | 81 | 69 | 30.925926 | 0.614224 | 0 | 0 | 0.779412 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | 1 | 0.044118 | false | 0 | 0.044118 | 0 | 0.088235 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
e4ee68a9bef4f1a33f0114073960167dd13d5770 | 6,476 | py | Python | tasks-deploy/caesar/check.py | irdkwmnsb/lkshl-ctf | e5c0200ddc8ba73df5f321b87b9763fb1bbaba57 | [
"MIT"
] | 3 | 2021-03-30T06:27:58.000Z | 2021-04-03T17:56:35.000Z | tasks-deploy/caesar/check.py | irdkwmnsb/lkshl-ctf | e5c0200ddc8ba73df5f321b87b9763fb1bbaba57 | [
"MIT"
] | null | null | null | tasks-deploy/caesar/check.py | irdkwmnsb/lkshl-ctf | e5c0200ddc8ba73df5f321b87b9763fb1bbaba57 | [
"MIT"
] | null | null | null | def check(attempt, context):
if attempt.answer == flags[attempt.participant.id % len(flags)]:
return Checked(True)
if attempt.answer in flags:
return CheckedPlagiarist(False, flags.index(attempt.answer))
return Checked(False)
flags = ['LKL{crypto_w4rmup_YesVN4L9}', 'LKL{crypto_w4rmup_udLGbxyV}', 'LKL{crypto_w4rmup_aGPd7oFA}', 'LKL{crypto_w4rmup_0ir81k3D}', 'LKL{crypto_w4rmup_rebcCnXt}', 'LKL{crypto_w4rmup_lMtaXSCm}', 'LKL{crypto_w4rmup_6GDFQsrm}', 'LKL{crypto_w4rmup_P8JhAshL}', 'LKL{crypto_w4rmup_zGS0AjJ8}', 'LKL{crypto_w4rmup_MGPS7FXV}', 'LKL{crypto_w4rmup_htgKfgiR}', 'LKL{crypto_w4rmup_8FfbMsZB}', 'LKL{crypto_w4rmup_79gKWm9u}', 'LKL{crypto_w4rmup_IBL3i44l}', 'LKL{crypto_w4rmup_fSFHnr95}', 'LKL{crypto_w4rmup_2658kKMF}', 'LKL{crypto_w4rmup_xUXIYB0Q}', 'LKL{crypto_w4rmup_SAVYZWA7}', 'LKL{crypto_w4rmup_nHbdknpA}', 'LKL{crypto_w4rmup_GLmfFKZe}', 'LKL{crypto_w4rmup_93miPFxR}', 'LKL{crypto_w4rmup_yZdkHlbT}', 'LKL{crypto_w4rmup_E1eIRs9l}', 'LKL{crypto_w4rmup_6FpYH6Fj}', 'LKL{crypto_w4rmup_7TiGj5VP}', 'LKL{crypto_w4rmup_JMQ7bc0s}', 'LKL{crypto_w4rmup_2PrUofZO}', 'LKL{crypto_w4rmup_MsZt0NSg}', 'LKL{crypto_w4rmup_S8GhLUcD}', 'LKL{crypto_w4rmup_Hmwwb9Yx}', 'LKL{crypto_w4rmup_RTC3M2XK}', 'LKL{crypto_w4rmup_40NMFD5X}', 'LKL{crypto_w4rmup_aTA7BSax}', 'LKL{crypto_w4rmup_STHle92F}', 'LKL{crypto_w4rmup_aDUQTVVF}', 'LKL{crypto_w4rmup_20a1QP64}', 'LKL{crypto_w4rmup_PmhxgbbF}', 'LKL{crypto_w4rmup_jvsj70uX}', 'LKL{crypto_w4rmup_QWkDLrWK}', 'LKL{crypto_w4rmup_8nNgZA7w}', 'LKL{crypto_w4rmup_OdV5hzEf}', 'LKL{crypto_w4rmup_rhMtl2Bd}', 'LKL{crypto_w4rmup_mywSOQdu}', 'LKL{crypto_w4rmup_eRInheC3}', 'LKL{crypto_w4rmup_ej35J2DT}', 'LKL{crypto_w4rmup_FIT2x8JJ}', 'LKL{crypto_w4rmup_t1vmXyJ6}', 'LKL{crypto_w4rmup_HQT9LYL4}', 'LKL{crypto_w4rmup_2OFxAGfR}', 'LKL{crypto_w4rmup_GnIbsDpy}', 'LKL{crypto_w4rmup_PnRYdJg2}', 'LKL{crypto_w4rmup_Hr0O1XC8}', 'LKL{crypto_w4rmup_ddi57Ub7}', 'LKL{crypto_w4rmup_o2EGaHNN}', 'LKL{crypto_w4rmup_ZW7HUkPa}', 'LKL{crypto_w4rmup_bB8sh87N}', 'LKL{crypto_w4rmup_nN4Zaq7A}', 'LKL{crypto_w4rmup_AS52IA7i}', 'LKL{crypto_w4rmup_RxspmsIY}', 'LKL{crypto_w4rmup_vnX8jzXy}', 'LKL{crypto_w4rmup_4Qj28CkF}', 'LKL{crypto_w4rmup_kbrYe8Ev}', 'LKL{crypto_w4rmup_xxbHXATB}', 'LKL{crypto_w4rmup_T6XNZMaF}', 'LKL{crypto_w4rmup_LPCBeUia}', 'LKL{crypto_w4rmup_inE1Hf9A}', 'LKL{crypto_w4rmup_kHXgZC95}', 'LKL{crypto_w4rmup_T2qKX5Ea}', 'LKL{crypto_w4rmup_IUGgrVhI}', 'LKL{crypto_w4rmup_Zz5LWvqi}', 'LKL{crypto_w4rmup_hJyboebI}', 'LKL{crypto_w4rmup_SzB2DgJM}', 'LKL{crypto_w4rmup_YnfhgzMt}', 'LKL{crypto_w4rmup_7AbXycC8}', 'LKL{crypto_w4rmup_l3ZyzejC}', 'LKL{crypto_w4rmup_2V1fCuAR}', 'LKL{crypto_w4rmup_GkY1CYJX}', 'LKL{crypto_w4rmup_q8F3J2gH}', 'LKL{crypto_w4rmup_mTwmSxqh}', 'LKL{crypto_w4rmup_mMM3nLfV}', 'LKL{crypto_w4rmup_POuE66LJ}', 'LKL{crypto_w4rmup_BI6118p5}', 'LKL{crypto_w4rmup_Rb81YuRf}', 'LKL{crypto_w4rmup_idBCYLUN}', 'LKL{crypto_w4rmup_DEju0psL}', 'LKL{crypto_w4rmup_WyFbVTWA}', 'LKL{crypto_w4rmup_0ZLsltbL}', 'LKL{crypto_w4rmup_RE3MEMew}', 'LKL{crypto_w4rmup_aVWWpya1}', 'LKL{crypto_w4rmup_BdtOGbmh}', 'LKL{crypto_w4rmup_PYpIJBmF}', 'LKL{crypto_w4rmup_h0bqv7pN}', 'LKL{crypto_w4rmup_AHlPJiaC}', 'LKL{crypto_w4rmup_wlmcsnvZ}', 'LKL{crypto_w4rmup_kvss81xx}', 'LKL{crypto_w4rmup_TyenyOjw}', 'LKL{crypto_w4rmup_PPeWEyGR}', 'LKL{crypto_w4rmup_5w5Qcbt4}', 'LKL{crypto_w4rmup_gSwiR0Zu}', 'LKL{crypto_w4rmup_0f7whbwX}', 'LKL{crypto_w4rmup_eq8CHMKv}', 'LKL{crypto_w4rmup_rF0xyqtz}', 'LKL{crypto_w4rmup_IuBqDwpG}', 'LKL{crypto_w4rmup_l6qoJHKf}', 'LKL{crypto_w4rmup_4B974gN6}', 'LKL{crypto_w4rmup_FuldoyoC}', 'LKL{crypto_w4rmup_dx7YucVN}', 'LKL{crypto_w4rmup_MCHQ93WG}', 'LKL{crypto_w4rmup_mghCUFhO}', 'LKL{crypto_w4rmup_iHt34E0C}', 'LKL{crypto_w4rmup_9akUgSXk}', 'LKL{crypto_w4rmup_jF6e3Mwj}', 'LKL{crypto_w4rmup_1W4AxnqL}', 'LKL{crypto_w4rmup_YyPl7y9I}', 'LKL{crypto_w4rmup_9xOuDfB4}', 'LKL{crypto_w4rmup_yg5ZiO3G}', 'LKL{crypto_w4rmup_9lYFmLJt}', 'LKL{crypto_w4rmup_XmmvApYC}', 'LKL{crypto_w4rmup_NjsqOJLC}', 'LKL{crypto_w4rmup_XeMkRgco}', 'LKL{crypto_w4rmup_kG2b29ku}', 'LKL{crypto_w4rmup_QltTLlt4}', 'LKL{crypto_w4rmup_AGDrpOGW}', 'LKL{crypto_w4rmup_uOtEPXuG}', 'LKL{crypto_w4rmup_IodYJGeH}', 'LKL{crypto_w4rmup_l7P8Wf8T}', 'LKL{crypto_w4rmup_WtnmZDVU}', 'LKL{crypto_w4rmup_RPNDV9E5}', 'LKL{crypto_w4rmup_iZVfhJy5}', 'LKL{crypto_w4rmup_qleq07wU}', 'LKL{crypto_w4rmup_RNpePkQj}', 'LKL{crypto_w4rmup_bqHXaipK}', 'LKL{crypto_w4rmup_xh0ddQMx}', 'LKL{crypto_w4rmup_HDspGfeH}', 'LKL{crypto_w4rmup_nks23yVP}', 'LKL{crypto_w4rmup_xYs4xx6l}', 'LKL{crypto_w4rmup_wbVvGKbp}', 'LKL{crypto_w4rmup_IMXjUtJe}', 'LKL{crypto_w4rmup_WI0DvgLI}', 'LKL{crypto_w4rmup_TX3YH1Wm}', 'LKL{crypto_w4rmup_mSa0lwpf}', 'LKL{crypto_w4rmup_5mz4QdNp}', 'LKL{crypto_w4rmup_LnfZxiuZ}', 'LKL{crypto_w4rmup_vCsMEtCg}', 'LKL{crypto_w4rmup_kHLyb3aH}', 'LKL{crypto_w4rmup_88qr06fC}', 'LKL{crypto_w4rmup_zR9v6CEi}', 'LKL{crypto_w4rmup_yQ3hqdtk}', 'LKL{crypto_w4rmup_8K4kQjyl}', 'LKL{crypto_w4rmup_hQMJCrCf}', 'LKL{crypto_w4rmup_V2y45Z5Z}', 'LKL{crypto_w4rmup_3KBWsmsM}', 'LKL{crypto_w4rmup_YVMZGpJf}', 'LKL{crypto_w4rmup_bomM3U1i}', 'LKL{crypto_w4rmup_RgZIW6CW}', 'LKL{crypto_w4rmup_lDgdKvNS}', 'LKL{crypto_w4rmup_VblQZXQO}', 'LKL{crypto_w4rmup_kbgxlVwh}', 'LKL{crypto_w4rmup_0MIjHfpK}', 'LKL{crypto_w4rmup_D43tmfbJ}', 'LKL{crypto_w4rmup_vtWM04yj}', 'LKL{crypto_w4rmup_cXP3nvWr}', 'LKL{crypto_w4rmup_6E1ybnjN}', 'LKL{crypto_w4rmup_4CmZIY4u}', 'LKL{crypto_w4rmup_txFDi90i}', 'LKL{crypto_w4rmup_F1tl5ps2}', 'LKL{crypto_w4rmup_QsrE73Yx}', 'LKL{crypto_w4rmup_uwxWrL9J}', 'LKL{crypto_w4rmup_C8BUElTA}', 'LKL{crypto_w4rmup_l59ffsEg}', 'LKL{crypto_w4rmup_C2IWIQoj}', 'LKL{crypto_w4rmup_q9fuhXAE}', 'LKL{crypto_w4rmup_wYTUg5Sk}', 'LKL{crypto_w4rmup_ukh3zXHn}', 'LKL{crypto_w4rmup_2pSc8ffF}', 'LKL{crypto_w4rmup_tUI2d2MH}', 'LKL{crypto_w4rmup_23CUVOaU}', 'LKL{crypto_w4rmup_TvKrb5DT}', 'LKL{crypto_w4rmup_unOgsaeY}', 'LKL{crypto_w4rmup_OeQrkykn}', 'LKL{crypto_w4rmup_Jpi6mlZV}', 'LKL{crypto_w4rmup_6qWUo8Au}', 'LKL{crypto_w4rmup_qv0ILPJh}', 'LKL{crypto_w4rmup_mr3bZ5jQ}', 'LKL{crypto_w4rmup_AvbtVqAE}', 'LKL{crypto_w4rmup_rZLywZX6}', 'LKL{crypto_w4rmup_ee2TDg12}', 'LKL{crypto_w4rmup_nqZL7WeH}', 'LKL{crypto_w4rmup_14nxd0jb}', 'LKL{crypto_w4rmup_GaBCVUwC}', 'LKL{crypto_w4rmup_edU4pUmb}', 'LKL{crypto_w4rmup_Fa0736qI}', 'LKL{crypto_w4rmup_LcwRkgOT}', 'LKL{crypto_w4rmup_GQUA6GxD}', 'LKL{crypto_w4rmup_pudKLMxT}', 'LKL{crypto_w4rmup_w467yR8V}', 'LKL{crypto_w4rmup_XnbApZkZ}', 'LKL{crypto_w4rmup_z5Lo78bl}', 'LKL{crypto_w4rmup_2TBlow1N}', 'LKL{crypto_w4rmup_x3O4w4cQ}'] | 719.555556 | 6,208 | 0.80034 | 832 | 6,476 | 5.748798 | 0.264423 | 0.376333 | 0.627221 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.075004 | 0.040611 | 6,476 | 9 | 6,208 | 719.555556 | 0.694833 | 0 | 0 | 0 | 0 | 0 | 0.83475 | 0.83475 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
5f7705f87dc1d2eb268931d3a9d752e388ee6994 | 164 | py | Python | {{cookiecutter.repo_name}}/tests/unit/test_{{cookiecutter.package_name}}_main.py | gautamdivgi/cookiecutter-python-thin | 10922e313f525019547ee4cebed4fc131edde033 | [
"Apache-2.0"
] | null | null | null | {{cookiecutter.repo_name}}/tests/unit/test_{{cookiecutter.package_name}}_main.py | gautamdivgi/cookiecutter-python-thin | 10922e313f525019547ee4cebed4fc131edde033 | [
"Apache-2.0"
] | null | null | null | {{cookiecutter.repo_name}}/tests/unit/test_{{cookiecutter.package_name}}_main.py | gautamdivgi/cookiecutter-python-thin | 10922e313f525019547ee4cebed4fc131edde033 | [
"Apache-2.0"
] | null | null | null | from {{cookiecutter.package_name}}.{{cookiecutter.package_name}}_main import main
def test_{{cookiecutter.package_name}}_main():
assert 'hello world' == main() | 41 | 81 | 0.756098 | 20 | 164 | 5.9 | 0.55 | 0.483051 | 0.584746 | 0.457627 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.091463 | 164 | 4 | 82 | 41 | 0.791946 | 0 | 0 | 0 | 0 | 0 | 0.066667 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 0 | null | null | 0 | 0.333333 | null | null | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 7 |
5f95b39ae64c1b52ec012e8296e219c7134e3840 | 248,935 | py | Python | iengage_client/apis/question_api.py | iEngage/python-sdk | 76cc6ed697d7599ce9af74124c12d33ad5aff419 | [
"Apache-2.0"
] | null | null | null | iengage_client/apis/question_api.py | iEngage/python-sdk | 76cc6ed697d7599ce9af74124c12d33ad5aff419 | [
"Apache-2.0"
] | null | null | null | iengage_client/apis/question_api.py | iEngage/python-sdk | 76cc6ed697d7599ce9af74124c12d33ad5aff419 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Stakeholder engagement API
This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers.
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class QuestionApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def add_answer(self, question_id, answer, logged_in_user_id, access_token, client_token, **kwargs):
"""
Answer the specified question
Allows the user to answer the question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_answer(question_id, answer, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str answer: answer (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_answer_with_http_info(question_id, answer, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.add_answer_with_http_info(question_id, answer, logged_in_user_id, access_token, client_token, **kwargs)
return data
def add_answer_with_http_info(self, question_id, answer, logged_in_user_id, access_token, client_token, **kwargs):
"""
Answer the specified question
Allows the user to answer the question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_answer_with_http_info(question_id, answer, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str answer: answer (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'answer', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `add_answer`")
# verify the required parameter 'answer' is set
if ('answer' not in params) or (params['answer'] is None):
raise ValueError("Missing the required parameter `answer` when calling `add_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `add_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `add_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `add_answer`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'answer' in params:
form_params.append(('answer', params['answer']))
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_question(self, category_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Share question without attachment
Allows the user to share question without attachment. Returns the question object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_question(category_id, question_title, question_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str question_title: Question Title (required)
:param str question_description: Describe question (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_question_with_http_info(category_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.add_question_with_http_info(category_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs)
return data
def add_question_with_http_info(self, category_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Share question without attachment
Allows the user to share question without attachment. Returns the question object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_question_with_http_info(category_id, question_title, question_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str question_title: Question Title (required)
:param str question_description: Describe question (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'question_title', 'question_description', 'logged_in_user_id', 'access_token', 'client_token']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `add_question`")
# verify the required parameter 'question_title' is set
if ('question_title' not in params) or (params['question_title'] is None):
raise ValueError("Missing the required parameter `question_title` when calling `add_question`")
# verify the required parameter 'question_description' is set
if ('question_description' not in params) or (params['question_description'] is None):
raise ValueError("Missing the required parameter `question_description` when calling `add_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `add_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `add_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `add_question`")
collection_formats = {}
resource_path = '/questions'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'category_id' in params:
form_params.append(('categoryId', params['category_id']))
if 'question_title' in params:
form_params.append(('questionTitle', params['question_title']))
if 'question_description' in params:
form_params.append(('questionDescription', params['question_description']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_question_0(self, body, body2, body3, logged_in_user_id, access_token, client_token, **kwargs):
"""
Share question with attachment
Allows the user to share question with attachment. Returns the question object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_question_0(body, body2, body3, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int body: categoryId (required)
:param str body2: questionTitle (required)
:param str body3: questionDescription (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param list[Attachment] body4:
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.add_question_0_with_http_info(body, body2, body3, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.add_question_0_with_http_info(body, body2, body3, logged_in_user_id, access_token, client_token, **kwargs)
return data
def add_question_0_with_http_info(self, body, body2, body3, logged_in_user_id, access_token, client_token, **kwargs):
"""
Share question with attachment
Allows the user to share question with attachment. Returns the question object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.add_question_0_with_http_info(body, body2, body3, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int body: categoryId (required)
:param str body2: questionTitle (required)
:param str body3: questionDescription (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param list[Attachment] body4:
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'body2', 'body3', 'logged_in_user_id', 'access_token', 'client_token', 'body4']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_question_0" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `add_question_0`")
# verify the required parameter 'body2' is set
if ('body2' not in params) or (params['body2'] is None):
raise ValueError("Missing the required parameter `body2` when calling `add_question_0`")
# verify the required parameter 'body3' is set
if ('body3' not in params) or (params['body3'] is None):
raise ValueError("Missing the required parameter `body3` when calling `add_question_0`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `add_question_0`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `add_question_0`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `add_question_0`")
collection_formats = {}
resource_path = '/questions/attachment'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
if 'body4' in params:
body_params = params['body4']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['multipart/form-data'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_question_category(self, name, description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Create question category
Creates a question category. Returns the created question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_question_category(name, description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: Name (required)
:param str description: description (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int organization_id: OrganizationId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_question_category_with_http_info(name, description, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.create_question_category_with_http_info(name, description, logged_in_user_id, access_token, client_token, **kwargs)
return data
def create_question_category_with_http_info(self, name, description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Create question category
Creates a question category. Returns the created question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_question_category_with_http_info(name, description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: Name (required)
:param str description: description (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int organization_id: OrganizationId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'description', 'logged_in_user_id', 'access_token', 'client_token', 'organization_id', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_question_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `create_question_category`")
# verify the required parameter 'description' is set
if ('description' not in params) or (params['description'] is None):
raise ValueError("Missing the required parameter `description` when calling `create_question_category`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `create_question_category`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `create_question_category`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `create_question_category`")
collection_formats = {}
resource_path = '/questions/categories'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'organization_id' in params:
form_params.append(('OrganizationId', params['organization_id']))
if 'name' in params:
form_params.append(('name', params['name']))
if 'description' in params:
form_params.append(('description', params['description']))
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategory',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_answer(self, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete answer
Allows the user to delete an answer. Returns the deleted answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_answer(answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_answer_with_http_info(answer_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.delete_answer_with_http_info(answer_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def delete_answer_with_http_info(self, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete answer
Allows the user to delete an answer. Returns the deleted answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_answer_with_http_info(answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['answer_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `delete_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `delete_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `delete_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `delete_answer`")
collection_formats = {}
resource_path = '/questions/answers/{answerId}'.replace('{format}', 'json')
path_params = {}
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_question(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete question
Allows the user to delete a question. Returns the deleted answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_question(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.delete_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def delete_question_with_http_info(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete question
Allows the user to delete a question. Returns the deleted answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `delete_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `delete_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `delete_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `delete_question`")
collection_formats = {}
resource_path = '/questions/{questionId}'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_question_category(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete question category
Allows the user to delete the question category. Returns the deleted question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_question_category(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.delete_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def delete_question_category_with_http_info(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Delete question category
Allows the user to delete the question category. Returns the deleted question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_question_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `delete_question_category`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `delete_question_category`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `delete_question_category`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `delete_question_category`")
collection_formats = {}
resource_path = '/questions/categories/{categoryId}'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['categoryId'] = params['category_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategory',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def dislike_answer(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Dislike answer
Allows the user to dislike the answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dislike_answer(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.dislike_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.dislike_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def dislike_answer_with_http_info(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Dislike answer
Allows the user to dislike the answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.dislike_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'answer_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method dislike_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `dislike_answer`")
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `dislike_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `dislike_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `dislike_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `dislike_answer`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers/{answerId}/dislike'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_answers(self, question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of answers by questionId
Returns the list of answers by questionId
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_answers(question_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswerList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_answers_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_answers_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_answers_with_http_info(self, question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of answers by questionId
Returns the list of answers by questionId
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_answers_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswerList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_answers" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `get_answers`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_answers`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_answers`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_answers`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_answers`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_answers`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswerList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_friends_questions(self, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions shared by friends
Returns the list of questions shared by friends
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_friends_questions(question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_friends_questions_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_friends_questions_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_friends_questions_with_http_info(self, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions shared by friends
Returns the list of questions shared by friends
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_friends_questions_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_status', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'category_id', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_friends_questions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_status' is set
if ('question_status' not in params) or (params['question_status'] is None):
raise ValueError("Missing the required parameter `question_status` when calling `get_friends_questions`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_friends_questions`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_friends_questions`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_friends_questions`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_friends_questions`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_friends_questions`")
collection_formats = {}
resource_path = '/questions/friends'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'question_status' in params:
query_params['questionStatus'] = params['question_status']
if 'category_id' in params:
query_params['categoryId'] = params['category_id']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_question(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get question by id
Returns the question by id
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_question(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_question_with_http_info(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get question by id
Returns the question by id
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `get_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_question`")
collection_formats = {}
resource_path = '/questions/{questionId}'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_question_categories(self, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get the list of question categories
Returns the list of question categories
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_question_categories(start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategoryList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_question_categories_with_http_info(start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_question_categories_with_http_info(start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_question_categories_with_http_info(self, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get the list of question categories
Returns the list of question categories
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_question_categories_with_http_info(start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategoryList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_question_categories" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_question_categories`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_question_categories`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_question_categories`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_question_categories`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_question_categories`")
collection_formats = {}
resource_path = '/questions/categories'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategoryList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_questions_for_user(self, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of all questions visible to the user
Returns the list of all questions visible to the user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_questions_for_user(question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_questions_for_user_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_questions_for_user_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_questions_for_user_with_http_info(self, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of all questions visible to the user
Returns the list of all questions visible to the user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_questions_for_user_with_http_info(question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_status', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'category_id', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_questions_for_user" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_status' is set
if ('question_status' not in params) or (params['question_status'] is None):
raise ValueError("Missing the required parameter `question_status` when calling `get_questions_for_user`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_questions_for_user`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_questions_for_user`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_questions_for_user`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_questions_for_user`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_questions_for_user`")
collection_formats = {}
resource_path = '/questions'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'question_status' in params:
query_params['questionStatus'] = params['question_status']
if 'category_id' in params:
query_params['categoryId'] = params['category_id']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_recommend_question(self, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended questions
Returns the list of recommended questions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommend_question(start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_recommend_question_with_http_info(start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_recommend_question_with_http_info(start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_recommend_question_with_http_info(self, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended questions
Returns the list of recommended questions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommend_question_with_http_info(start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_recommend_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_recommend_question`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_recommend_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_recommend_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_recommend_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_recommend_question`")
collection_formats = {}
resource_path = '/questions/recommend'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_recommended_questions_from_db(self, user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended questions from DB
Returns the list of recommended questions from DB
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommended_questions_from_db(user_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_recommended_questions_from_db_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_recommended_questions_from_db_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_recommended_questions_from_db_with_http_info(self, user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended questions from DB
Returns the list of recommended questions from DB
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommended_questions_from_db_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['user_id', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_recommended_questions_from_db" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'user_id' is set
if ('user_id' not in params) or (params['user_id'] is None):
raise ValueError("Missing the required parameter `user_id` when calling `get_recommended_questions_from_db`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_recommended_questions_from_db`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_recommended_questions_from_db`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_recommended_questions_from_db`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_recommended_questions_from_db`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_recommended_questions_from_db`")
collection_formats = {}
resource_path = '/questions/{userId}/recommendedQuestions'.replace('{format}', 'json')
path_params = {}
if 'user_id' in params:
path_params['userId'] = params['user_id']
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_recommended_users_from_db(self, question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended Users from DB
Returns the list of recommended users from DB
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommended_users_from_db(question_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)userId<br/>2)firstName<br/>3)lastName<br/>4)profileImage<br/><b>A) Available values-</b><br/>1)userId<br/>2)firstName<br/>3)lastName<br/>4)emailId<br/>5)profileImage<br/>6)birthDate<br/>7)currentUserFollowing<br/>8)currentUserFriend<br/>9)equityScore
:return: VerveResponseUserList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_recommended_users_from_db_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_recommended_users_from_db_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_recommended_users_from_db_with_http_info(self, question_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of recommended Users from DB
Returns the list of recommended users from DB
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_recommended_users_from_db_with_http_info(question_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)userId<br/>2)firstName<br/>3)lastName<br/>4)profileImage<br/><b>A) Available values-</b><br/>1)userId<br/>2)firstName<br/>3)lastName<br/>4)emailId<br/>5)profileImage<br/>6)birthDate<br/>7)currentUserFollowing<br/>8)currentUserFriend<br/>9)equityScore
:return: VerveResponseUserList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_recommended_users_from_db" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `get_recommended_users_from_db`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_recommended_users_from_db`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_recommended_users_from_db`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_recommended_users_from_db`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_recommended_users_from_db`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_recommended_users_from_db`")
collection_formats = {}
resource_path = '/questions/{questionId}/recommendedUsers'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseUserList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_user_questions(self, user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions shared by user
Returns the list of questions shared by specific user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_questions(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_user_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_user_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_user_questions_with_http_info(self, user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions shared by user
Returns the list of questions shared by specific user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['user_id', 'question_status', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'category_id', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_user_questions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'user_id' is set
if ('user_id' not in params) or (params['user_id'] is None):
raise ValueError("Missing the required parameter `user_id` when calling `get_user_questions`")
# verify the required parameter 'question_status' is set
if ('question_status' not in params) or (params['question_status'] is None):
raise ValueError("Missing the required parameter `question_status` when calling `get_user_questions`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_user_questions`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_user_questions`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_user_questions`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_user_questions`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_user_questions`")
collection_formats = {}
resource_path = '/questions/{userId}/shared'.replace('{format}', 'json')
path_params = {}
if 'user_id' in params:
path_params['userId'] = params['user_id']
query_params = {}
if 'question_status' in params:
query_params['questionStatus'] = params['question_status']
if 'category_id' in params:
query_params['categoryId'] = params['category_id']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_user_subscribed_question_categories(self, user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of question categories subscribed by the user
Returns the list of question categories subscribed by the user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_subscribed_question_categories(user_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategoryList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_user_subscribed_question_categories_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_user_subscribed_question_categories_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_user_subscribed_question_categories_with_http_info(self, user_id, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of question categories subscribed by the user
Returns the list of question categories subscribed by the user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_subscribed_question_categories_with_http_info(user_id, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategoryList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['user_id', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_user_subscribed_question_categories" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'user_id' is set
if ('user_id' not in params) or (params['user_id'] is None):
raise ValueError("Missing the required parameter `user_id` when calling `get_user_subscribed_question_categories`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_user_subscribed_question_categories`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_user_subscribed_question_categories`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_user_subscribed_question_categories`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_user_subscribed_question_categories`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_user_subscribed_question_categories`")
collection_formats = {}
resource_path = '/questions/categories/{userId}/subscribe'.replace('{format}', 'json')
path_params = {}
if 'user_id' in params:
path_params['userId'] = params['user_id']
query_params = {}
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategoryList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_user_subscribed_questions(self, user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions subscribed by user
Returns the list of questions subscribed by specific user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_subscribed_questions(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_user_subscribed_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.get_user_subscribed_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def get_user_subscribed_questions_with_http_info(self, user_id, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of questions subscribed by user
Returns the list of questions subscribed by specific user
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_user_subscribed_questions_with_http_info(user_id, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int user_id: userId (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param int category_id: categoryId
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['user_id', 'question_status', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'category_id', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_user_subscribed_questions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'user_id' is set
if ('user_id' not in params) or (params['user_id'] is None):
raise ValueError("Missing the required parameter `user_id` when calling `get_user_subscribed_questions`")
# verify the required parameter 'question_status' is set
if ('question_status' not in params) or (params['question_status'] is None):
raise ValueError("Missing the required parameter `question_status` when calling `get_user_subscribed_questions`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `get_user_subscribed_questions`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `get_user_subscribed_questions`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `get_user_subscribed_questions`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `get_user_subscribed_questions`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `get_user_subscribed_questions`")
collection_formats = {}
resource_path = '/questions/{userId}/subscribe'.replace('{format}', 'json')
path_params = {}
if 'user_id' in params:
path_params['userId'] = params['user_id']
query_params = {}
if 'question_status' in params:
query_params['questionStatus'] = params['question_status']
if 'category_id' in params:
query_params['categoryId'] = params['category_id']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def like_answer(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Like answer
Allows the user to like the answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.like_answer(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.like_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.like_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def like_answer_with_http_info(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Like answer
Allows the user to like the answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.like_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'answer_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method like_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `like_answer`")
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `like_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `like_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `like_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `like_answer`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers/{answerId}/like'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def mark_as_an_answer(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Mark answer as a answer
Marks the answer as accepted. This means the user is satisfied with the answer & then the question will go into closed state
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.mark_as_an_answer(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.mark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.mark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def mark_as_an_answer_with_http_info(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Mark answer as a answer
Marks the answer as accepted. This means the user is satisfied with the answer & then the question will go into closed state
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.mark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'answer_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method mark_as_an_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `mark_as_an_answer`")
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `mark_as_an_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `mark_as_an_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `mark_as_an_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `mark_as_an_answer`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers/{answerId}/mark'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def search_questions(self, search_text, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of matching questions
Returns the list of matching questions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.search_questions(search_text, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search_text: Search Text, keywords to search (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.search_questions_with_http_info(search_text, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.search_questions_with_http_info(search_text, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs)
return data
def search_questions_with_http_info(self, search_text, question_status, start, end, logged_in_user_id, access_token, client_token, **kwargs):
"""
Get list of matching questions
Returns the list of matching questions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.search_questions_with_http_info(search_text, question_status, start, end, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str search_text: Search Text, keywords to search (required)
:param str question_status: Question status <br/> 1) ALL <br/> 2) UNREPLIED <br/> 3) REPLIED <br/> 4) CLOSED (required)
:param int start: start, initial value start from 0 (required)
:param int end: end (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['search_text', 'question_status', 'start', 'end', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method search_questions" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'search_text' is set
if ('search_text' not in params) or (params['search_text'] is None):
raise ValueError("Missing the required parameter `search_text` when calling `search_questions`")
# verify the required parameter 'question_status' is set
if ('question_status' not in params) or (params['question_status'] is None):
raise ValueError("Missing the required parameter `question_status` when calling `search_questions`")
# verify the required parameter 'start' is set
if ('start' not in params) or (params['start'] is None):
raise ValueError("Missing the required parameter `start` when calling `search_questions`")
# verify the required parameter 'end' is set
if ('end' not in params) or (params['end'] is None):
raise ValueError("Missing the required parameter `end` when calling `search_questions`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `search_questions`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `search_questions`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `search_questions`")
collection_formats = {}
resource_path = '/questions/search'.replace('{format}', 'json')
path_params = {}
query_params = {}
if 'search_text' in params:
query_params['searchText'] = params['search_text']
if 'question_status' in params:
query_params['questionStatus'] = params['question_status']
if 'start' in params:
query_params['start'] = params['start']
if 'end' in params:
query_params['end'] = params['end']
if 'fields' in params:
query_params['fields'] = params['fields']
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionList',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def subscribe_question(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Subscribe question
Allows the user to subscribe a question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.subscribe_question(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.subscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.subscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def subscribe_question_with_http_info(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Subscribe question
Allows the user to subscribe a question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.subscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method subscribe_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `subscribe_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `subscribe_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `subscribe_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `subscribe_question`")
collection_formats = {}
resource_path = '/questions/{questionId}/subscribe'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def subscribe_question_category(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Subscribe question category
Returns the subscribed question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.subscribe_question_category(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.subscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.subscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def subscribe_question_category_with_http_info(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Subscribe question category
Returns the subscribed question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.subscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method subscribe_question_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `subscribe_question_category`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `subscribe_question_category`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `subscribe_question_category`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `subscribe_question_category`")
collection_formats = {}
resource_path = '/questions/categories/{categoryId}/subscribe'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['categoryId'] = params['category_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/x-www-form-urlencoded'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategory',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def unmark_as_an_answer(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unmark answer as a answer
Unmarks the answer. This will remove the marked answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unmark_as_an_answer(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.unmark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.unmark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def unmark_as_an_answer_with_http_info(self, question_id, answer_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unmark answer as a answer
Unmarks the answer. This will remove the marked answer.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unmark_as_an_answer_with_http_info(question_id, answer_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param int answer_id: answerId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'answer_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method unmark_as_an_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `unmark_as_an_answer`")
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `unmark_as_an_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `unmark_as_an_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `unmark_as_an_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `unmark_as_an_answer`")
collection_formats = {}
resource_path = '/questions/{questionId}/answers/{answerId}/unmark'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def unsubscribe_question(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unsubscribe question
Allows the user to unsubscribe a question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unsubscribe_question(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.unsubscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.unsubscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def unsubscribe_question_with_http_info(self, question_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unsubscribe question
Allows the user to unsubscribe a question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unsubscribe_question_with_http_info(question_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method unsubscribe_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `unsubscribe_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `unsubscribe_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `unsubscribe_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `unsubscribe_question`")
collection_formats = {}
resource_path = '/questions/{questionId}/unsubscribe'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def unsubscribe_question_category(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unsubscribe question category
Returns the unsubscribed question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unsubscribe_question_category(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.unsubscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.unsubscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, **kwargs)
return data
def unsubscribe_question_category_with_http_info(self, category_id, logged_in_user_id, access_token, client_token, **kwargs):
"""
Unsubscribe question category
Returns the unsubscribed question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.unsubscribe_question_category_with_http_info(category_id, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method unsubscribe_question_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `unsubscribe_question_category`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `unsubscribe_question_category`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `unsubscribe_question_category`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `unsubscribe_question_category`")
collection_formats = {}
resource_path = '/questions/categories/{categoryId}/unsubscribe'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['categoryId'] = params['category_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategory',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_answer(self, answer_id, answer, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update answer
Allows the user to update an answer. Returns the updated answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_answer(answer_id, answer, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int answer_id: answerId (required)
:param str answer: answer (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_answer_with_http_info(answer_id, answer, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.update_answer_with_http_info(answer_id, answer, logged_in_user_id, access_token, client_token, **kwargs)
return data
def update_answer_with_http_info(self, answer_id, answer, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update answer
Allows the user to update an answer. Returns the updated answer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_answer_with_http_info(answer_id, answer, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int answer_id: answerId (required)
:param str answer: answer (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/><b>A) Available values -</b><br/>1)answerId<br/>2)answerDescription<br/>3)createdDate<br/>4)questionId<br/>5)answeringUser<br/>6)isMarkedAnswer<br/>7)noOfLikes<br/>8)noOfDislikes<br/>9)replyCount<br/>10)isLiked<br/>11)isDisliked
:return: VerveResponseAnswer
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['answer_id', 'answer', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_answer" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'answer_id' is set
if ('answer_id' not in params) or (params['answer_id'] is None):
raise ValueError("Missing the required parameter `answer_id` when calling `update_answer`")
# verify the required parameter 'answer' is set
if ('answer' not in params) or (params['answer'] is None):
raise ValueError("Missing the required parameter `answer` when calling `update_answer`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `update_answer`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `update_answer`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `update_answer`")
collection_formats = {}
resource_path = '/questions/answers/{answerId}'.replace('{format}', 'json')
path_params = {}
if 'answer_id' in params:
path_params['answerId'] = params['answer_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'answer' in params:
form_params.append(('answer', params['answer']))
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseAnswer',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_question(self, question_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update question
Allows the user to update question. Returns the updated question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_question(question_id, question_title, question_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str question_title: Question Title (required)
:param str question_description: Describe Question (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_question_with_http_info(question_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.update_question_with_http_info(question_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs)
return data
def update_question_with_http_info(self, question_id, question_title, question_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update question
Allows the user to update question. Returns the updated question
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_question_with_http_info(question_id, question_title, question_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int question_id: questionId (required)
:param str question_title: Question Title (required)
:param str question_description: Describe Question (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)createdDate<br/><b>A) Available values-</b><br/>1)questionId<br/>2)questionTitle<br/>3)questionDescription<br/>4)issuer<br/>5)noOfAnswers<br/>6)isClosed<br/>7)createdDate<br/>8)lastUpdatedDate<br/>9)videoId<br/>10)fileURL<br/>11)isSubscribed<br/>12)sentiment</br>13)entity
:return: VerveResponseQuestion
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['question_id', 'question_title', 'question_description', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_question" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'question_id' is set
if ('question_id' not in params) or (params['question_id'] is None):
raise ValueError("Missing the required parameter `question_id` when calling `update_question`")
# verify the required parameter 'question_title' is set
if ('question_title' not in params) or (params['question_title'] is None):
raise ValueError("Missing the required parameter `question_title` when calling `update_question`")
# verify the required parameter 'question_description' is set
if ('question_description' not in params) or (params['question_description'] is None):
raise ValueError("Missing the required parameter `question_description` when calling `update_question`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `update_question`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `update_question`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `update_question`")
collection_formats = {}
resource_path = '/questions/{questionId}'.replace('{format}', 'json')
path_params = {}
if 'question_id' in params:
path_params['questionId'] = params['question_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'question_title' in params:
form_params.append(('questionTitle', params['question_title']))
if 'question_description' in params:
form_params.append(('questionDescription', params['question_description']))
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestion',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_question_category(self, category_id, category_name, category_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update question category
Allows the user to update the question category. Returns the updated question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_question_category(category_id, category_name, category_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str category_name: Category Name (required)
:param str category_description: Describe category (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_question_category_with_http_info(category_id, category_name, category_description, logged_in_user_id, access_token, client_token, **kwargs)
else:
(data) = self.update_question_category_with_http_info(category_id, category_name, category_description, logged_in_user_id, access_token, client_token, **kwargs)
return data
def update_question_category_with_http_info(self, category_id, category_name, category_description, logged_in_user_id, access_token, client_token, **kwargs):
"""
Update question category
Allows the user to update the question category. Returns the updated question category
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_question_category_with_http_info(category_id, category_name, category_description, logged_in_user_id, access_token, client_token, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int category_id: categoryId (required)
:param str category_name: Category Name (required)
:param str category_description: Describe category (required)
:param str logged_in_user_id: User id of logged / authenticated user (required)
:param str access_token: Unique session token for user. To get access token user will have to authenticate (required)
:param str client_token: Use the Client Token. Please generate it from the Applications section under the Production & Sandbox tabs (required)
:param str fields: Filter fields in result list<br/> <b>A) Default values -</b> <br/>1)categoryId<br/>2)categoryName<br/><b>A) Available values -</b> <br/>1)categoryId<br/>2)categoryName<br/>3)categoryDescription<br/>4)createdDate<br/>5)isSubscribed
:return: VerveResponseQuestionCategory
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['category_id', 'category_name', 'category_description', 'logged_in_user_id', 'access_token', 'client_token', 'fields']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_question_category" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'category_id' is set
if ('category_id' not in params) or (params['category_id'] is None):
raise ValueError("Missing the required parameter `category_id` when calling `update_question_category`")
# verify the required parameter 'category_name' is set
if ('category_name' not in params) or (params['category_name'] is None):
raise ValueError("Missing the required parameter `category_name` when calling `update_question_category`")
# verify the required parameter 'category_description' is set
if ('category_description' not in params) or (params['category_description'] is None):
raise ValueError("Missing the required parameter `category_description` when calling `update_question_category`")
# verify the required parameter 'logged_in_user_id' is set
if ('logged_in_user_id' not in params) or (params['logged_in_user_id'] is None):
raise ValueError("Missing the required parameter `logged_in_user_id` when calling `update_question_category`")
# verify the required parameter 'access_token' is set
if ('access_token' not in params) or (params['access_token'] is None):
raise ValueError("Missing the required parameter `access_token` when calling `update_question_category`")
# verify the required parameter 'client_token' is set
if ('client_token' not in params) or (params['client_token'] is None):
raise ValueError("Missing the required parameter `client_token` when calling `update_question_category`")
collection_formats = {}
resource_path = '/questions/categories/{categoryId}'.replace('{format}', 'json')
path_params = {}
if 'category_id' in params:
path_params['categoryId'] = params['category_id']
query_params = {}
header_params = {}
if 'logged_in_user_id' in params:
header_params['loggedInUserId'] = params['logged_in_user_id']
if 'access_token' in params:
header_params['accessToken'] = params['access_token']
if 'client_token' in params:
header_params['clientToken'] = params['client_token']
form_params = []
local_var_files = {}
if 'category_name' in params:
form_params.append(('categoryName', params['category_name']))
if 'category_description' in params:
form_params.append(('categoryDescription', params['category_description']))
if 'fields' in params:
form_params.append(('fields', params['fields']))
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/x-www-form-urlencoded'])
# Authentication setting
auth_settings = ['default']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='VerveResponseQuestionCategory',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| 58.189575 | 430 | 0.637544 | 29,248 | 248,935 | 5.209963 | 0.011078 | 0.022444 | 0.035437 | 0.041344 | 0.990806 | 0.988437 | 0.984335 | 0.980943 | 0.977432 | 0.971388 | 0 | 0.005486 | 0.271452 | 248,935 | 4,277 | 431 | 58.20318 | 0.834722 | 0.400591 | 0 | 0.813303 | 0 | 0 | 0.256971 | 0.04788 | 0 | 0 | 0 | 0 | 0 | 1 | 0.027982 | false | 0 | 0.003211 | 0 | 0.072936 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
5fc169c980f434aeb17eba21e510d73d21aaa81a | 52,217 | py | Python | sdk/python/pulumi_alicloud/alb/listener.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 42 | 2019-03-18T06:34:37.000Z | 2022-03-24T07:08:57.000Z | sdk/python/pulumi_alicloud/alb/listener.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 152 | 2019-04-15T21:03:44.000Z | 2022-03-29T18:00:57.000Z | sdk/python/pulumi_alicloud/alb/listener.py | pulumi/pulumi-alicloud | 9c34d84b4588a7c885c6bec1f03b5016e5a41683 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2020-08-26T17:30:07.000Z | 2021-07-05T01:37:45.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['ListenerArgs', 'Listener']
@pulumi.input_type
class ListenerArgs:
def __init__(__self__, *,
listener_port: pulumi.Input[int],
listener_protocol: pulumi.Input[str],
load_balancer_id: pulumi.Input[str],
access_log_record_customized_headers_enabled: Optional[pulumi.Input[bool]] = None,
access_log_tracing_config: Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']] = None,
acl_config: Optional[pulumi.Input['ListenerAclConfigArgs']] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]] = None,
default_actions: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]] = None,
dry_run: Optional[pulumi.Input[bool]] = None,
gzip_enabled: Optional[pulumi.Input[bool]] = None,
http2_enabled: Optional[pulumi.Input[bool]] = None,
idle_timeout: Optional[pulumi.Input[int]] = None,
listener_description: Optional[pulumi.Input[str]] = None,
quic_config: Optional[pulumi.Input['ListenerQuicConfigArgs']] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
xforwarded_for_config: Optional[pulumi.Input['ListenerXforwardedForConfigArgs']] = None):
"""
The set of arguments for constructing a Listener resource.
:param pulumi.Input[int] listener_port: The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
:param pulumi.Input[str] listener_protocol: Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
:param pulumi.Input[str] load_balancer_id: The ALB Instance Id.
:param pulumi.Input[bool] access_log_record_customized_headers_enabled: Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
:param pulumi.Input['ListenerAccessLogTracingConfigArgs'] access_log_tracing_config: Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
:param pulumi.Input['ListenerAclConfigArgs'] acl_config: The configurations of the access control lists (ACLs). See the following `Block acl_config`.
:param pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]] certificates: The Certificates.
:param pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]] default_actions: The Default Rule Action List. See the following `Block default_actions`.
:param pulumi.Input[bool] dry_run: The dry run.
:param pulumi.Input[bool] gzip_enabled: Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
:param pulumi.Input[bool] http2_enabled: Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
:param pulumi.Input[int] idle_timeout: Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
:param pulumi.Input[str] listener_description: The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
:param pulumi.Input['ListenerQuicConfigArgs'] quic_config: Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
:param pulumi.Input[int] request_timeout: The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
:param pulumi.Input[str] security_policy_id: Security Policy.
:param pulumi.Input[str] status: The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
:param pulumi.Input['ListenerXforwardedForConfigArgs'] xforwarded_for_config: xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
pulumi.set(__self__, "listener_port", listener_port)
pulumi.set(__self__, "listener_protocol", listener_protocol)
pulumi.set(__self__, "load_balancer_id", load_balancer_id)
if access_log_record_customized_headers_enabled is not None:
pulumi.set(__self__, "access_log_record_customized_headers_enabled", access_log_record_customized_headers_enabled)
if access_log_tracing_config is not None:
pulumi.set(__self__, "access_log_tracing_config", access_log_tracing_config)
if acl_config is not None:
pulumi.set(__self__, "acl_config", acl_config)
if certificates is not None:
pulumi.set(__self__, "certificates", certificates)
if default_actions is not None:
pulumi.set(__self__, "default_actions", default_actions)
if dry_run is not None:
pulumi.set(__self__, "dry_run", dry_run)
if gzip_enabled is not None:
pulumi.set(__self__, "gzip_enabled", gzip_enabled)
if http2_enabled is not None:
pulumi.set(__self__, "http2_enabled", http2_enabled)
if idle_timeout is not None:
pulumi.set(__self__, "idle_timeout", idle_timeout)
if listener_description is not None:
pulumi.set(__self__, "listener_description", listener_description)
if quic_config is not None:
pulumi.set(__self__, "quic_config", quic_config)
if request_timeout is not None:
pulumi.set(__self__, "request_timeout", request_timeout)
if security_policy_id is not None:
pulumi.set(__self__, "security_policy_id", security_policy_id)
if status is not None:
pulumi.set(__self__, "status", status)
if xforwarded_for_config is not None:
pulumi.set(__self__, "xforwarded_for_config", xforwarded_for_config)
@property
@pulumi.getter(name="listenerPort")
def listener_port(self) -> pulumi.Input[int]:
"""
The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
"""
return pulumi.get(self, "listener_port")
@listener_port.setter
def listener_port(self, value: pulumi.Input[int]):
pulumi.set(self, "listener_port", value)
@property
@pulumi.getter(name="listenerProtocol")
def listener_protocol(self) -> pulumi.Input[str]:
"""
Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
"""
return pulumi.get(self, "listener_protocol")
@listener_protocol.setter
def listener_protocol(self, value: pulumi.Input[str]):
pulumi.set(self, "listener_protocol", value)
@property
@pulumi.getter(name="loadBalancerId")
def load_balancer_id(self) -> pulumi.Input[str]:
"""
The ALB Instance Id.
"""
return pulumi.get(self, "load_balancer_id")
@load_balancer_id.setter
def load_balancer_id(self, value: pulumi.Input[str]):
pulumi.set(self, "load_balancer_id", value)
@property
@pulumi.getter(name="accessLogRecordCustomizedHeadersEnabled")
def access_log_record_customized_headers_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
"""
return pulumi.get(self, "access_log_record_customized_headers_enabled")
@access_log_record_customized_headers_enabled.setter
def access_log_record_customized_headers_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "access_log_record_customized_headers_enabled", value)
@property
@pulumi.getter(name="accessLogTracingConfig")
def access_log_tracing_config(self) -> Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']]:
"""
Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
"""
return pulumi.get(self, "access_log_tracing_config")
@access_log_tracing_config.setter
def access_log_tracing_config(self, value: Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']]):
pulumi.set(self, "access_log_tracing_config", value)
@property
@pulumi.getter(name="aclConfig")
def acl_config(self) -> Optional[pulumi.Input['ListenerAclConfigArgs']]:
"""
The configurations of the access control lists (ACLs). See the following `Block acl_config`.
"""
return pulumi.get(self, "acl_config")
@acl_config.setter
def acl_config(self, value: Optional[pulumi.Input['ListenerAclConfigArgs']]):
pulumi.set(self, "acl_config", value)
@property
@pulumi.getter
def certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]]:
"""
The Certificates.
"""
return pulumi.get(self, "certificates")
@certificates.setter
def certificates(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]]):
pulumi.set(self, "certificates", value)
@property
@pulumi.getter(name="defaultActions")
def default_actions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]:
"""
The Default Rule Action List. See the following `Block default_actions`.
"""
return pulumi.get(self, "default_actions")
@default_actions.setter
def default_actions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]):
pulumi.set(self, "default_actions", value)
@property
@pulumi.getter(name="dryRun")
def dry_run(self) -> Optional[pulumi.Input[bool]]:
"""
The dry run.
"""
return pulumi.get(self, "dry_run")
@dry_run.setter
def dry_run(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "dry_run", value)
@property
@pulumi.getter(name="gzipEnabled")
def gzip_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
"""
return pulumi.get(self, "gzip_enabled")
@gzip_enabled.setter
def gzip_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "gzip_enabled", value)
@property
@pulumi.getter(name="http2Enabled")
def http2_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
"""
return pulumi.get(self, "http2_enabled")
@http2_enabled.setter
def http2_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "http2_enabled", value)
@property
@pulumi.getter(name="idleTimeout")
def idle_timeout(self) -> Optional[pulumi.Input[int]]:
"""
Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
"""
return pulumi.get(self, "idle_timeout")
@idle_timeout.setter
def idle_timeout(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "idle_timeout", value)
@property
@pulumi.getter(name="listenerDescription")
def listener_description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
"""
return pulumi.get(self, "listener_description")
@listener_description.setter
def listener_description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "listener_description", value)
@property
@pulumi.getter(name="quicConfig")
def quic_config(self) -> Optional[pulumi.Input['ListenerQuicConfigArgs']]:
"""
Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
"""
return pulumi.get(self, "quic_config")
@quic_config.setter
def quic_config(self, value: Optional[pulumi.Input['ListenerQuicConfigArgs']]):
pulumi.set(self, "quic_config", value)
@property
@pulumi.getter(name="requestTimeout")
def request_timeout(self) -> Optional[pulumi.Input[int]]:
"""
The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
"""
return pulumi.get(self, "request_timeout")
@request_timeout.setter
def request_timeout(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "request_timeout", value)
@property
@pulumi.getter(name="securityPolicyId")
def security_policy_id(self) -> Optional[pulumi.Input[str]]:
"""
Security Policy.
"""
return pulumi.get(self, "security_policy_id")
@security_policy_id.setter
def security_policy_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "security_policy_id", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter(name="xforwardedForConfig")
def xforwarded_for_config(self) -> Optional[pulumi.Input['ListenerXforwardedForConfigArgs']]:
"""
xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
return pulumi.get(self, "xforwarded_for_config")
@xforwarded_for_config.setter
def xforwarded_for_config(self, value: Optional[pulumi.Input['ListenerXforwardedForConfigArgs']]):
pulumi.set(self, "xforwarded_for_config", value)
@pulumi.input_type
class _ListenerState:
def __init__(__self__, *,
access_log_record_customized_headers_enabled: Optional[pulumi.Input[bool]] = None,
access_log_tracing_config: Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']] = None,
acl_config: Optional[pulumi.Input['ListenerAclConfigArgs']] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]] = None,
default_actions: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]] = None,
dry_run: Optional[pulumi.Input[bool]] = None,
gzip_enabled: Optional[pulumi.Input[bool]] = None,
http2_enabled: Optional[pulumi.Input[bool]] = None,
idle_timeout: Optional[pulumi.Input[int]] = None,
listener_description: Optional[pulumi.Input[str]] = None,
listener_port: Optional[pulumi.Input[int]] = None,
listener_protocol: Optional[pulumi.Input[str]] = None,
load_balancer_id: Optional[pulumi.Input[str]] = None,
quic_config: Optional[pulumi.Input['ListenerQuicConfigArgs']] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
xforwarded_for_config: Optional[pulumi.Input['ListenerXforwardedForConfigArgs']] = None):
"""
Input properties used for looking up and filtering Listener resources.
:param pulumi.Input[bool] access_log_record_customized_headers_enabled: Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
:param pulumi.Input['ListenerAccessLogTracingConfigArgs'] access_log_tracing_config: Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
:param pulumi.Input['ListenerAclConfigArgs'] acl_config: The configurations of the access control lists (ACLs). See the following `Block acl_config`.
:param pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]] certificates: The Certificates.
:param pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]] default_actions: The Default Rule Action List. See the following `Block default_actions`.
:param pulumi.Input[bool] dry_run: The dry run.
:param pulumi.Input[bool] gzip_enabled: Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
:param pulumi.Input[bool] http2_enabled: Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
:param pulumi.Input[int] idle_timeout: Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
:param pulumi.Input[str] listener_description: The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
:param pulumi.Input[int] listener_port: The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
:param pulumi.Input[str] listener_protocol: Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
:param pulumi.Input[str] load_balancer_id: The ALB Instance Id.
:param pulumi.Input['ListenerQuicConfigArgs'] quic_config: Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
:param pulumi.Input[int] request_timeout: The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
:param pulumi.Input[str] security_policy_id: Security Policy.
:param pulumi.Input[str] status: The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
:param pulumi.Input['ListenerXforwardedForConfigArgs'] xforwarded_for_config: xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
if access_log_record_customized_headers_enabled is not None:
pulumi.set(__self__, "access_log_record_customized_headers_enabled", access_log_record_customized_headers_enabled)
if access_log_tracing_config is not None:
pulumi.set(__self__, "access_log_tracing_config", access_log_tracing_config)
if acl_config is not None:
pulumi.set(__self__, "acl_config", acl_config)
if certificates is not None:
pulumi.set(__self__, "certificates", certificates)
if default_actions is not None:
pulumi.set(__self__, "default_actions", default_actions)
if dry_run is not None:
pulumi.set(__self__, "dry_run", dry_run)
if gzip_enabled is not None:
pulumi.set(__self__, "gzip_enabled", gzip_enabled)
if http2_enabled is not None:
pulumi.set(__self__, "http2_enabled", http2_enabled)
if idle_timeout is not None:
pulumi.set(__self__, "idle_timeout", idle_timeout)
if listener_description is not None:
pulumi.set(__self__, "listener_description", listener_description)
if listener_port is not None:
pulumi.set(__self__, "listener_port", listener_port)
if listener_protocol is not None:
pulumi.set(__self__, "listener_protocol", listener_protocol)
if load_balancer_id is not None:
pulumi.set(__self__, "load_balancer_id", load_balancer_id)
if quic_config is not None:
pulumi.set(__self__, "quic_config", quic_config)
if request_timeout is not None:
pulumi.set(__self__, "request_timeout", request_timeout)
if security_policy_id is not None:
pulumi.set(__self__, "security_policy_id", security_policy_id)
if status is not None:
pulumi.set(__self__, "status", status)
if xforwarded_for_config is not None:
pulumi.set(__self__, "xforwarded_for_config", xforwarded_for_config)
@property
@pulumi.getter(name="accessLogRecordCustomizedHeadersEnabled")
def access_log_record_customized_headers_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
"""
return pulumi.get(self, "access_log_record_customized_headers_enabled")
@access_log_record_customized_headers_enabled.setter
def access_log_record_customized_headers_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "access_log_record_customized_headers_enabled", value)
@property
@pulumi.getter(name="accessLogTracingConfig")
def access_log_tracing_config(self) -> Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']]:
"""
Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
"""
return pulumi.get(self, "access_log_tracing_config")
@access_log_tracing_config.setter
def access_log_tracing_config(self, value: Optional[pulumi.Input['ListenerAccessLogTracingConfigArgs']]):
pulumi.set(self, "access_log_tracing_config", value)
@property
@pulumi.getter(name="aclConfig")
def acl_config(self) -> Optional[pulumi.Input['ListenerAclConfigArgs']]:
"""
The configurations of the access control lists (ACLs). See the following `Block acl_config`.
"""
return pulumi.get(self, "acl_config")
@acl_config.setter
def acl_config(self, value: Optional[pulumi.Input['ListenerAclConfigArgs']]):
pulumi.set(self, "acl_config", value)
@property
@pulumi.getter
def certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]]:
"""
The Certificates.
"""
return pulumi.get(self, "certificates")
@certificates.setter
def certificates(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerCertificateArgs']]]]):
pulumi.set(self, "certificates", value)
@property
@pulumi.getter(name="defaultActions")
def default_actions(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]:
"""
The Default Rule Action List. See the following `Block default_actions`.
"""
return pulumi.get(self, "default_actions")
@default_actions.setter
def default_actions(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['ListenerDefaultActionArgs']]]]):
pulumi.set(self, "default_actions", value)
@property
@pulumi.getter(name="dryRun")
def dry_run(self) -> Optional[pulumi.Input[bool]]:
"""
The dry run.
"""
return pulumi.get(self, "dry_run")
@dry_run.setter
def dry_run(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "dry_run", value)
@property
@pulumi.getter(name="gzipEnabled")
def gzip_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
"""
return pulumi.get(self, "gzip_enabled")
@gzip_enabled.setter
def gzip_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "gzip_enabled", value)
@property
@pulumi.getter(name="http2Enabled")
def http2_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
"""
return pulumi.get(self, "http2_enabled")
@http2_enabled.setter
def http2_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "http2_enabled", value)
@property
@pulumi.getter(name="idleTimeout")
def idle_timeout(self) -> Optional[pulumi.Input[int]]:
"""
Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
"""
return pulumi.get(self, "idle_timeout")
@idle_timeout.setter
def idle_timeout(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "idle_timeout", value)
@property
@pulumi.getter(name="listenerDescription")
def listener_description(self) -> Optional[pulumi.Input[str]]:
"""
The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
"""
return pulumi.get(self, "listener_description")
@listener_description.setter
def listener_description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "listener_description", value)
@property
@pulumi.getter(name="listenerPort")
def listener_port(self) -> Optional[pulumi.Input[int]]:
"""
The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
"""
return pulumi.get(self, "listener_port")
@listener_port.setter
def listener_port(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "listener_port", value)
@property
@pulumi.getter(name="listenerProtocol")
def listener_protocol(self) -> Optional[pulumi.Input[str]]:
"""
Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
"""
return pulumi.get(self, "listener_protocol")
@listener_protocol.setter
def listener_protocol(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "listener_protocol", value)
@property
@pulumi.getter(name="loadBalancerId")
def load_balancer_id(self) -> Optional[pulumi.Input[str]]:
"""
The ALB Instance Id.
"""
return pulumi.get(self, "load_balancer_id")
@load_balancer_id.setter
def load_balancer_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "load_balancer_id", value)
@property
@pulumi.getter(name="quicConfig")
def quic_config(self) -> Optional[pulumi.Input['ListenerQuicConfigArgs']]:
"""
Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
"""
return pulumi.get(self, "quic_config")
@quic_config.setter
def quic_config(self, value: Optional[pulumi.Input['ListenerQuicConfigArgs']]):
pulumi.set(self, "quic_config", value)
@property
@pulumi.getter(name="requestTimeout")
def request_timeout(self) -> Optional[pulumi.Input[int]]:
"""
The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
"""
return pulumi.get(self, "request_timeout")
@request_timeout.setter
def request_timeout(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "request_timeout", value)
@property
@pulumi.getter(name="securityPolicyId")
def security_policy_id(self) -> Optional[pulumi.Input[str]]:
"""
Security Policy.
"""
return pulumi.get(self, "security_policy_id")
@security_policy_id.setter
def security_policy_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "security_policy_id", value)
@property
@pulumi.getter
def status(self) -> Optional[pulumi.Input[str]]:
"""
The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
"""
return pulumi.get(self, "status")
@status.setter
def status(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "status", value)
@property
@pulumi.getter(name="xforwardedForConfig")
def xforwarded_for_config(self) -> Optional[pulumi.Input['ListenerXforwardedForConfigArgs']]:
"""
xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
return pulumi.get(self, "xforwarded_for_config")
@xforwarded_for_config.setter
def xforwarded_for_config(self, value: Optional[pulumi.Input['ListenerXforwardedForConfigArgs']]):
pulumi.set(self, "xforwarded_for_config", value)
class Listener(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
access_log_record_customized_headers_enabled: Optional[pulumi.Input[bool]] = None,
access_log_tracing_config: Optional[pulumi.Input[pulumi.InputType['ListenerAccessLogTracingConfigArgs']]] = None,
acl_config: Optional[pulumi.Input[pulumi.InputType['ListenerAclConfigArgs']]] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerCertificateArgs']]]]] = None,
default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None,
dry_run: Optional[pulumi.Input[bool]] = None,
gzip_enabled: Optional[pulumi.Input[bool]] = None,
http2_enabled: Optional[pulumi.Input[bool]] = None,
idle_timeout: Optional[pulumi.Input[int]] = None,
listener_description: Optional[pulumi.Input[str]] = None,
listener_port: Optional[pulumi.Input[int]] = None,
listener_protocol: Optional[pulumi.Input[str]] = None,
load_balancer_id: Optional[pulumi.Input[str]] = None,
quic_config: Optional[pulumi.Input[pulumi.InputType['ListenerQuicConfigArgs']]] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
xforwarded_for_config: Optional[pulumi.Input[pulumi.InputType['ListenerXforwardedForConfigArgs']]] = None,
__props__=None):
"""
Provides a Application Load Balancer (ALB) Listener resource.
For information about Application Load Balancer (ALB) Listener and how to use it, see [What is Listener](https://www.alibabacloud.com/help/doc-detail/214348.htm).
> **NOTE:** Available in v1.133.0+.
## Import
Application Load Balancer (ALB) Listener can be imported using the id, e.g.
```sh
$ pulumi import alicloud:alb/listener:Listener example <id>
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] access_log_record_customized_headers_enabled: Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
:param pulumi.Input[pulumi.InputType['ListenerAccessLogTracingConfigArgs']] access_log_tracing_config: Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
:param pulumi.Input[pulumi.InputType['ListenerAclConfigArgs']] acl_config: The configurations of the access control lists (ACLs). See the following `Block acl_config`.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerCertificateArgs']]]] certificates: The Certificates.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]] default_actions: The Default Rule Action List. See the following `Block default_actions`.
:param pulumi.Input[bool] dry_run: The dry run.
:param pulumi.Input[bool] gzip_enabled: Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
:param pulumi.Input[bool] http2_enabled: Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
:param pulumi.Input[int] idle_timeout: Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
:param pulumi.Input[str] listener_description: The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
:param pulumi.Input[int] listener_port: The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
:param pulumi.Input[str] listener_protocol: Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
:param pulumi.Input[str] load_balancer_id: The ALB Instance Id.
:param pulumi.Input[pulumi.InputType['ListenerQuicConfigArgs']] quic_config: Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
:param pulumi.Input[int] request_timeout: The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
:param pulumi.Input[str] security_policy_id: Security Policy.
:param pulumi.Input[str] status: The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
:param pulumi.Input[pulumi.InputType['ListenerXforwardedForConfigArgs']] xforwarded_for_config: xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: ListenerArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Provides a Application Load Balancer (ALB) Listener resource.
For information about Application Load Balancer (ALB) Listener and how to use it, see [What is Listener](https://www.alibabacloud.com/help/doc-detail/214348.htm).
> **NOTE:** Available in v1.133.0+.
## Import
Application Load Balancer (ALB) Listener can be imported using the id, e.g.
```sh
$ pulumi import alicloud:alb/listener:Listener example <id>
```
:param str resource_name: The name of the resource.
:param ListenerArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(ListenerArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
access_log_record_customized_headers_enabled: Optional[pulumi.Input[bool]] = None,
access_log_tracing_config: Optional[pulumi.Input[pulumi.InputType['ListenerAccessLogTracingConfigArgs']]] = None,
acl_config: Optional[pulumi.Input[pulumi.InputType['ListenerAclConfigArgs']]] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerCertificateArgs']]]]] = None,
default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None,
dry_run: Optional[pulumi.Input[bool]] = None,
gzip_enabled: Optional[pulumi.Input[bool]] = None,
http2_enabled: Optional[pulumi.Input[bool]] = None,
idle_timeout: Optional[pulumi.Input[int]] = None,
listener_description: Optional[pulumi.Input[str]] = None,
listener_port: Optional[pulumi.Input[int]] = None,
listener_protocol: Optional[pulumi.Input[str]] = None,
load_balancer_id: Optional[pulumi.Input[str]] = None,
quic_config: Optional[pulumi.Input[pulumi.InputType['ListenerQuicConfigArgs']]] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
xforwarded_for_config: Optional[pulumi.Input[pulumi.InputType['ListenerXforwardedForConfigArgs']]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = ListenerArgs.__new__(ListenerArgs)
__props__.__dict__["access_log_record_customized_headers_enabled"] = access_log_record_customized_headers_enabled
__props__.__dict__["access_log_tracing_config"] = access_log_tracing_config
__props__.__dict__["acl_config"] = acl_config
__props__.__dict__["certificates"] = certificates
__props__.__dict__["default_actions"] = default_actions
__props__.__dict__["dry_run"] = dry_run
__props__.__dict__["gzip_enabled"] = gzip_enabled
__props__.__dict__["http2_enabled"] = http2_enabled
__props__.__dict__["idle_timeout"] = idle_timeout
__props__.__dict__["listener_description"] = listener_description
if listener_port is None and not opts.urn:
raise TypeError("Missing required property 'listener_port'")
__props__.__dict__["listener_port"] = listener_port
if listener_protocol is None and not opts.urn:
raise TypeError("Missing required property 'listener_protocol'")
__props__.__dict__["listener_protocol"] = listener_protocol
if load_balancer_id is None and not opts.urn:
raise TypeError("Missing required property 'load_balancer_id'")
__props__.__dict__["load_balancer_id"] = load_balancer_id
__props__.__dict__["quic_config"] = quic_config
__props__.__dict__["request_timeout"] = request_timeout
__props__.__dict__["security_policy_id"] = security_policy_id
__props__.__dict__["status"] = status
__props__.__dict__["xforwarded_for_config"] = xforwarded_for_config
super(Listener, __self__).__init__(
'alicloud:alb/listener:Listener',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
access_log_record_customized_headers_enabled: Optional[pulumi.Input[bool]] = None,
access_log_tracing_config: Optional[pulumi.Input[pulumi.InputType['ListenerAccessLogTracingConfigArgs']]] = None,
acl_config: Optional[pulumi.Input[pulumi.InputType['ListenerAclConfigArgs']]] = None,
certificates: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerCertificateArgs']]]]] = None,
default_actions: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]]] = None,
dry_run: Optional[pulumi.Input[bool]] = None,
gzip_enabled: Optional[pulumi.Input[bool]] = None,
http2_enabled: Optional[pulumi.Input[bool]] = None,
idle_timeout: Optional[pulumi.Input[int]] = None,
listener_description: Optional[pulumi.Input[str]] = None,
listener_port: Optional[pulumi.Input[int]] = None,
listener_protocol: Optional[pulumi.Input[str]] = None,
load_balancer_id: Optional[pulumi.Input[str]] = None,
quic_config: Optional[pulumi.Input[pulumi.InputType['ListenerQuicConfigArgs']]] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
security_policy_id: Optional[pulumi.Input[str]] = None,
status: Optional[pulumi.Input[str]] = None,
xforwarded_for_config: Optional[pulumi.Input[pulumi.InputType['ListenerXforwardedForConfigArgs']]] = None) -> 'Listener':
"""
Get an existing Listener resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] access_log_record_customized_headers_enabled: Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
:param pulumi.Input[pulumi.InputType['ListenerAccessLogTracingConfigArgs']] access_log_tracing_config: Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
:param pulumi.Input[pulumi.InputType['ListenerAclConfigArgs']] acl_config: The configurations of the access control lists (ACLs). See the following `Block acl_config`.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerCertificateArgs']]]] certificates: The Certificates.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ListenerDefaultActionArgs']]]] default_actions: The Default Rule Action List. See the following `Block default_actions`.
:param pulumi.Input[bool] dry_run: The dry run.
:param pulumi.Input[bool] gzip_enabled: Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
:param pulumi.Input[bool] http2_enabled: Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
:param pulumi.Input[int] idle_timeout: Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
:param pulumi.Input[str] listener_description: The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
:param pulumi.Input[int] listener_port: The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
:param pulumi.Input[str] listener_protocol: Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
:param pulumi.Input[str] load_balancer_id: The ALB Instance Id.
:param pulumi.Input[pulumi.InputType['ListenerQuicConfigArgs']] quic_config: Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
:param pulumi.Input[int] request_timeout: The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
:param pulumi.Input[str] security_policy_id: Security Policy.
:param pulumi.Input[str] status: The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
:param pulumi.Input[pulumi.InputType['ListenerXforwardedForConfigArgs']] xforwarded_for_config: xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _ListenerState.__new__(_ListenerState)
__props__.__dict__["access_log_record_customized_headers_enabled"] = access_log_record_customized_headers_enabled
__props__.__dict__["access_log_tracing_config"] = access_log_tracing_config
__props__.__dict__["acl_config"] = acl_config
__props__.__dict__["certificates"] = certificates
__props__.__dict__["default_actions"] = default_actions
__props__.__dict__["dry_run"] = dry_run
__props__.__dict__["gzip_enabled"] = gzip_enabled
__props__.__dict__["http2_enabled"] = http2_enabled
__props__.__dict__["idle_timeout"] = idle_timeout
__props__.__dict__["listener_description"] = listener_description
__props__.__dict__["listener_port"] = listener_port
__props__.__dict__["listener_protocol"] = listener_protocol
__props__.__dict__["load_balancer_id"] = load_balancer_id
__props__.__dict__["quic_config"] = quic_config
__props__.__dict__["request_timeout"] = request_timeout
__props__.__dict__["security_policy_id"] = security_policy_id
__props__.__dict__["status"] = status
__props__.__dict__["xforwarded_for_config"] = xforwarded_for_config
return Listener(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="accessLogRecordCustomizedHeadersEnabled")
def access_log_record_customized_headers_enabled(self) -> pulumi.Output[bool]:
"""
Indicates whether the access log has a custom header field. Valid values: true and false. Default value: false.
"""
return pulumi.get(self, "access_log_record_customized_headers_enabled")
@property
@pulumi.getter(name="accessLogTracingConfig")
def access_log_tracing_config(self) -> pulumi.Output[Optional['outputs.ListenerAccessLogTracingConfig']]:
"""
Xtrace Configuration Information. See the following `Block access_log_tracing_config`.
"""
return pulumi.get(self, "access_log_tracing_config")
@property
@pulumi.getter(name="aclConfig")
def acl_config(self) -> pulumi.Output[Optional['outputs.ListenerAclConfig']]:
"""
The configurations of the access control lists (ACLs). See the following `Block acl_config`.
"""
return pulumi.get(self, "acl_config")
@property
@pulumi.getter
def certificates(self) -> pulumi.Output[Optional[Sequence['outputs.ListenerCertificate']]]:
"""
The Certificates.
"""
return pulumi.get(self, "certificates")
@property
@pulumi.getter(name="defaultActions")
def default_actions(self) -> pulumi.Output[Optional[Sequence['outputs.ListenerDefaultAction']]]:
"""
The Default Rule Action List. See the following `Block default_actions`.
"""
return pulumi.get(self, "default_actions")
@property
@pulumi.getter(name="dryRun")
def dry_run(self) -> pulumi.Output[Optional[bool]]:
"""
The dry run.
"""
return pulumi.get(self, "dry_run")
@property
@pulumi.getter(name="gzipEnabled")
def gzip_enabled(self) -> pulumi.Output[bool]:
"""
Whether to Enable Gzip Compression, as a Specific File Type on a Compression. Valid values: `false`, `true`. Default Value: `true`. .
"""
return pulumi.get(self, "gzip_enabled")
@property
@pulumi.getter(name="http2Enabled")
def http2_enabled(self) -> pulumi.Output[bool]:
"""
Whether to Enable HTTP/2 Features. Valid Values: `True` Or `False`. Default Value: `True`.
"""
return pulumi.get(self, "http2_enabled")
@property
@pulumi.getter(name="idleTimeout")
def idle_timeout(self) -> pulumi.Output[int]:
"""
Specify the Connection Idle Timeout Value: `1` to `60`. Unit: Seconds.
"""
return pulumi.get(self, "idle_timeout")
@property
@pulumi.getter(name="listenerDescription")
def listener_description(self) -> pulumi.Output[Optional[str]]:
"""
The description of the listener. The description must be 2 to 256 characters in length. The name can contain only the characters in the following string: `/^([^\\x00-\\xff]|[\w.,;/@-]){2,256}$/`.
"""
return pulumi.get(self, "listener_description")
@property
@pulumi.getter(name="listenerPort")
def listener_port(self) -> pulumi.Output[int]:
"""
The ALB Instance Front-End, and Those of the Ports Used. Value: `1` to `65535`.
"""
return pulumi.get(self, "listener_port")
@property
@pulumi.getter(name="listenerProtocol")
def listener_protocol(self) -> pulumi.Output[str]:
"""
Snooping Protocols. Valid Values: `HTTP`, `HTTPS` Or `QUIC`.
"""
return pulumi.get(self, "listener_protocol")
@property
@pulumi.getter(name="loadBalancerId")
def load_balancer_id(self) -> pulumi.Output[str]:
"""
The ALB Instance Id.
"""
return pulumi.get(self, "load_balancer_id")
@property
@pulumi.getter(name="quicConfig")
def quic_config(self) -> pulumi.Output['outputs.ListenerQuicConfig']:
"""
Configuration Associated with the QuIC Listening. See the following `Block quic_config`.
"""
return pulumi.get(self, "quic_config")
@property
@pulumi.getter(name="requestTimeout")
def request_timeout(self) -> pulumi.Output[int]:
"""
The Specified Request Timeout Time. Value: `1` to `180`. Unit: Seconds. Default Value: `60`. If the Timeout Time Within the Back-End Server Has Not Answered the ALB Will Give up Waiting, the Client Returns the HTTP 504 Error Code.
"""
return pulumi.get(self, "request_timeout")
@property
@pulumi.getter(name="securityPolicyId")
def security_policy_id(self) -> pulumi.Output[str]:
"""
Security Policy.
"""
return pulumi.get(self, "security_policy_id")
@property
@pulumi.getter
def status(self) -> pulumi.Output[str]:
"""
The state of the listener. Valid Values: `Running` Or `Stopped`. Valid values: `Running`: The listener is running. `Stopped`: The listener is stopped.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter(name="xforwardedForConfig")
def xforwarded_for_config(self) -> pulumi.Output['outputs.ListenerXforwardedForConfig']:
"""
xforwardfor Related Attribute Configuration. See the following `Block xforwarded_for_config`.
"""
return pulumi.get(self, "xforwarded_for_config")
| 53.501025 | 280 | 0.681617 | 6,047 | 52,217 | 5.652224 | 0.047462 | 0.084964 | 0.085052 | 0.030018 | 0.947131 | 0.939875 | 0.930162 | 0.922613 | 0.917084 | 0.89871 | 0 | 0.0063 | 0.209644 | 52,217 | 975 | 281 | 53.555897 | 0.82188 | 0.331942 | 0 | 0.856164 | 1 | 0 | 0.160127 | 0.079605 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166096 | false | 0.001712 | 0.011986 | 0 | 0.277397 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
ffd015ce1d9d27ceb8a2650cf83eab732996fe9c | 227 | py | Python | packages/ekstep_data_pipelines/common/infra_commons/storage/exceptions.py | jeevan-revaneppa-hirethanad/audio-to-speech-pipeline | a5bd7f0321834507e4157eb1aea8659cd205bf1c | [
"MIT"
] | 23 | 2021-03-20T13:24:37.000Z | 2022-03-26T19:02:33.000Z | packages/ekstep_data_pipelines/common/infra_commons/storage/exceptions.py | jeevan-revaneppa-hirethanad/audio-to-speech-pipeline | a5bd7f0321834507e4157eb1aea8659cd205bf1c | [
"MIT"
] | 10 | 2021-04-06T14:00:35.000Z | 2022-03-16T12:27:13.000Z | packages/ekstep_data_pipelines/common/infra_commons/storage/exceptions.py | jeevan-revaneppa-hirethanad/audio-to-speech-pipeline | a5bd7f0321834507e4157eb1aea8659cd205bf1c | [
"MIT"
] | 16 | 2021-03-30T10:57:34.000Z | 2022-03-23T01:07:19.000Z | class FileNotFoundException(Exception):
def __init__(self, value, *args, **kwargs):
self.value = value
class PathDoesNotExist(Exception):
def __init__(self, value, *args, **kwargs):
self.value = value
| 25.222222 | 47 | 0.674009 | 24 | 227 | 6.041667 | 0.416667 | 0.248276 | 0.22069 | 0.275862 | 0.675862 | 0.675862 | 0.675862 | 0.675862 | 0.675862 | 0.675862 | 0 | 0 | 0.202643 | 227 | 8 | 48 | 28.375 | 0.801105 | 0 | 0 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
0838d41f86ab3e5d4980458b79842c22118be1f0 | 22,350 | py | Python | scenarios/scenarios.py | wuminghui100/bridge-maintenance-optimizer | 1f4b7a5e74a56a508f33acb8ea0c7a7cbc870e9d | [
"MIT"
] | null | null | null | scenarios/scenarios.py | wuminghui100/bridge-maintenance-optimizer | 1f4b7a5e74a56a508f33acb8ea0c7a7cbc870e9d | [
"MIT"
] | null | null | null | scenarios/scenarios.py | wuminghui100/bridge-maintenance-optimizer | 1f4b7a5e74a56a508f33acb8ea0c7a7cbc870e9d | [
"MIT"
] | null | null | null | import numpy as np
import os
def save_trans(tran_real, name):
dirpath = os.path.dirname(os.path.abspath(__file__))
path = dirpath
if not os.path.exists(path):
os.makedirs(path)
print(path)
np.save(path+'\\'+name+'.npy', trans_real)
trans_real = np.zeros(shape=[10,4,5,5])
#scenarios 1
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 1.00, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.82, 0.09, 0.09],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.91, 0.09, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.12, 0.88, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.14, 0.86, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.15, 0.85, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.16, 0.84, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.17, 0.83, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.18, 0.82, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario1')
#scenarios 2
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 1.00, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.82, 0.09, 0.09],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.91, 0.09, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.11, 0.89, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.11, 0.89, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.12, 0.88, 0.00, 0.00],
[0.00, 0.00, 0.12, 0.88, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.13, 0.87, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.13, 0.87, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.14, 0.86, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.15, 0.85, 0.00, 0.00],
[0.00, 0.00, 0.15, 0.85, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.16, 0.84, 0.00, 0.00],
[0.00, 0.00, 0.16, 0.84, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.17, 0.83, 0.00, 0.00],
[0.00, 0.00, 0.17, 0.83, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.18, 0.82, 0.00, 0.00],
[0.00, 0.00, 0.18, 0.82, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario2')
#scenarios 3
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 0.50, 0.50],
[0.00, 0.00, 0.00, 1.00, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.82, 0.09, 0.09],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.14, 0.86, 0.00, 0.00],
[0.00, 0.00, 0.91, 0.09, 0.00],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.20, 0.80, 0.00, 0.00],
[0.00, 0.00, 0.20, 0.80, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.20, 0.80, 0.00, 0.00],
[0.00, 0.00, 0.20, 0.80, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.25, 0.75, 0.00, 0.00],
[0.00, 0.00, 0.25, 0.75, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.25, 0.75, 0.00, 0.00],
[0.00, 0.00, 0.25, 0.75, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.25, 0.75, 0.00, 0.00],
[0.00, 0.00, 0.25, 0.75, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.00, 0.30, 0.70, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.00, 0.30, 0.70, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.00, 0.30, 0.70, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.35, 0.65, 0.00, 0.00],
[0.00, 0.00, 0.35, 0.65, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.35, 0.65, 0.00, 0.00],
[0.00, 0.00, 0.35, 0.65, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario3')
#scenarios 4-6: different maintenance effects
#scenario 4
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.40, 0.30, 0.30],
[0.00, 0.00, 0.30, 0.40, 0.30],
[0.00, 0.00, 0.20, 0.40, 0.40],
[0.00, 0.00, 0.00, 0.20, 0.80],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.20, 0.80, 0.00, 0.00],
[0.00, 0.00, 0.85, 0.15, 0.00],
[0.00, 0.00, 0.00, 0.30, 0.70],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.00, 0.90, 0.10, 0.00],
[0.00, 0.00, 0.00, 0.40, 0.60],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.12, 0.88, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.14, 0.86, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.15, 0.85, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.16, 0.84, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.17, 0.83, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.18, 0.82, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario4')
#scenario 5
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.30, 0.40, 0.30],
[0.00, 0.00, 0.20, 0.40, 0.40],
[0.00, 0.00, 0.10, 0.50, 0.40],
[0.00, 0.00, 0.00, 0.10, 0.90],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.20, 0.80, 0.00, 0.00],
[0.00, 0.10, 0.80, 0.10, 0.00],
[0.00, 0.00, 0.80, 0.15, 0.05],
[0.00, 0.00, 0.00, 0.20, 0.80],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.20, 0.80, 0.00, 0.00],
[0.00, 0.00, 0.80, 0.20, 0.00],
[0.00, 0.00, 0.00, 0.25, 0.75],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.12, 0.88, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.14, 0.86, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.15, 0.85, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.16, 0.84, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.17, 0.83, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.18, 0.82, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario5')
#scenario 6
#real world transition based on reasonable assumption
# action 3, replace: raw 0, 3,4,are based on assumption
trans_real[:, 3]=[[0.00, 0.00, 0.20, 0.40, 0.40],
[0.00, 0.00, 0.10, 0.50, 0.40],
[0.00, 0.00, 0.00, 0.40, 0.60],
[0.00, 0.00, 0.00, 0.00, 1.00],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 2, reh: raw 0, 3,4,are based on assumption
trans_real[:, 2]=[[0.00, 0.10, 0.80, 0.10, 0.00],
[0.00, 0.00, 0.80, 0.20, 0.00],
[0.00, 0.00, 0.60, 0.25, 0.15],
[0.00, 0.00, 0.00, 0.10, 0.90],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 1, repair: raw 0,- 3,4,are based on assumption
trans_real[:, 1]=[[0.00, 0.30, 0.70, 0.00, 0.00],
[0.00, 0.10, 0.80, 0.10, 0.00],
[0.00, 0.00, 0.70, 0.20, 0.10],
[0.00, 0.00, 0.00, 0.20, 0.80],
[0.00, 0.00, 0.00, 0.00, 1.00]]
# action 0, nothing: raw 0, 3,4,are based on assumption
# age affects deterioration, trans_his[i] means age 10i~10(i+1)
trans_real[0, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.45, 0.55]]
trans_real[1, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.11, 0.89, 0.00],
[0.00, 0.00, 0.00, 0.47, 0.53]]
trans_real[2, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.12, 0.88, 0.00],
[0.00, 0.00, 0.00, 0.49, 0.51]]
trans_real[3, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.50, 0.50]]
trans_real[4, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.13, 0.87, 0.00],
[0.00, 0.00, 0.00, 0.52, 0.48]]
trans_real[5, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.14, 0.86, 0.00],
[0.00, 0.00, 0.00, 0.53, 0.47]]
trans_real[6, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.02, 0.98, 0.00, 0.00],
[0.00, 0.00, 0.15, 0.85, 0.00],
[0.00, 0.00, 0.00, 0.55, 0.45]]
trans_real[7, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.16, 0.84, 0.00],
[0.00, 0.00, 0.00, 0.57, 0.43]]
trans_real[8, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.17, 0.83, 0.00],
[0.00, 0.00, 0.00, 0.58, 0.42]]
trans_real[9, 0]=[[1.00, 0.00, 0.00, 0.00, 0.00],
[0.00, 1.00, 0.00, 0.00, 0.00],
[0.00, 0.03, 0.97, 0.00, 0.00],
[0.00, 0.00, 0.18, 0.82, 0.00],
[0.00, 0.00, 0.00, 0.60, 0.40]]
save_trans(trans_real, 'scenario6') | 48.69281 | 64 | 0.390604 | 4,669 | 22,350 | 1.847505 | 0.024416 | 0.46812 | 0.562486 | 0.706701 | 0.958729 | 0.958498 | 0.958498 | 0.957802 | 0.957802 | 0.955715 | 0 | 0.434687 | 0.368725 | 22,350 | 459 | 65 | 48.69281 | 0.176696 | 0.092304 | 0 | 0.913793 | 0 | 0 | 0.003032 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.002463 | false | 0 | 0.004926 | 0 | 0.007389 | 0.002463 | 0 | 0 | 1 | null | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 |
084b094ffe50f8ca464f375dcc48df8822955862 | 42 | py | Python | test_oper.py | RobinsonWang/rookie | f08ee38bf1063a78d931703bac17a3eaa379603b | [
"MIT"
] | null | null | null | test_oper.py | RobinsonWang/rookie | f08ee38bf1063a78d931703bac17a3eaa379603b | [
"MIT"
] | null | null | null | test_oper.py | RobinsonWang/rookie | f08ee38bf1063a78d931703bac17a3eaa379603b | [
"MIT"
] | null | null | null | print("10/3=",10/3)
print("10//3=",10//3)
| 14 | 21 | 0.52381 | 10 | 42 | 2.2 | 0.3 | 0.545455 | 0.727273 | 0.909091 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | 0.047619 | 42 | 2 | 22 | 21 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0.261905 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | null | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 11 |
f228c484c2acc7598f87fa2849b4700ed88bbf31 | 6,823 | py | Python | django_realtime/consumers.py | keepexploring/smartbiogas | ca663435b05666113e3c0cb55e6f087c61497208 | [
"MIT"
] | null | null | null | django_realtime/consumers.py | keepexploring/smartbiogas | ca663435b05666113e3c0cb55e6f087c61497208 | [
"MIT"
] | 10 | 2017-11-24T12:15:40.000Z | 2022-02-10T06:41:32.000Z | django_realtime/consumers.py | keepexploring/smartbiogas | ca663435b05666113e3c0cb55e6f087c61497208 | [
"MIT"
] | null | null | null | import re
import logging
from channels import Channel, Group
from channels.sessions import channel_session
from channels.auth import channel_session_user, channel_session_user_from_http
from channels.generic.websockets import JsonWebsocketConsumer
import json
#from utilities import update_dashboard
log = logging.getLogger(__name__)
import pdb
from utilities import send_data
connections={'current_users':[]}
def connection_groups(**kwargs):
"""
Called to return the list of groups to automatically add/remove
this connection to/from.
"""
return ["dashboard"]
@channel_session_user_from_http
def ws_add_dashboard(message, **kwargs):
"""
Perform things on connection start
"""
# pdb.set_trace()
user = message.user
#groupName = 'test'
Group("hellothere",channel_layer=message.channel_layer).add(message.reply_channel)
#Group(groupName).add(Channel("abc"))
# data = {'name':'andrew','uid':'asdasdsad','data':[1,2,3,45,5,4,6,4,3],'broken_biogas':22,'working_biogas':78}
# Group("hellothere",channel_layer=message.channel_layer).send({"text": json.dumps(data)})
message.reply_channel.send({"accept": True})
message.channel_session['rooms'] = []
send_data()
#update_dashboard(Group)
#connections['current_users'].append({'reply_channel':message.reply_channel,"group":"hellothere","channel_layer":message.channel_layer})
#pdb.set_trace()
def receive(content):
"""
Called when a message is received with either text or bytes
filled out.
"""
channel_session_user = True
http_user = True
@channel_session_user
def ws_disconnect_dashboard(message):
"""
Perform things on connection close
"""
Group("hellothere").discard(message.reply_channel)
@channel_session_user
def ws_message_dashboard(message):
# pdb.set_trace()
print("sending!!")
print(message.content['text'])
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session
def msg_consumer_dashboard(message):
# Save to model
#room = message.content['room']
#ChatMessage.objects.create(
# room=room,
# message=message.content['message'],
#)
# Broadcast to listening sockets
#Group("chat-%s" % room).send({
# "text": message.content['message'],
# })
#pdb.set_trace()
# data = {'name':'andrew','uid':'asdasdsad','data':[1,2,3,45,5,4,6,4,3],'broken_biogas':23,'working_biogas':45}
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
#Channel('update-data').send({"room": "test",
# "message": json.dumps(data)},immediately=True)
@channel_session_user_from_http
def ws_add_technicians(message, **kwargs):
"""
Perform things on connection start
"""
# pdb.set_trace()
user = message.user
#groupName = 'test'
Group("hellothere",channel_layer=message.channel_layer).add(message.reply_channel)
#Group(groupName).add(Channel("abc"))
data = {'name':'andrew','uid':'asdasdsad','data':[1,2,3,45,5,4,6,4,3],'broken_biogas':22,'working_biogas':78}
Group("hellothere",channel_layer=message.channel_layer).send({"text": json.dumps(data)})
message.reply_channel.send({"accept": True})
message.channel_session['rooms'] = []
def receive(content):
"""
Called when a message is received with either text or bytes
filled out.
"""
channel_session_user = True
http_user = True
@channel_session_user
def ws_disconnect_technicians(message):
"""
Perform things on connection close
"""
Group("hellothere").discard(message.reply_channel)
@channel_session_user
def ws_message_technicians(message):
print(message.content['text'])
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session
def msg_consumer_technicians(message):
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session_user_from_http
def ws_add_jobs(message, **kwargs):
"""
Perform things on connection start
"""
# pdb.set_trace()
user = message.user
#groupName = 'test'
Group("hellothere",channel_layer=message.channel_layer).add(message.reply_channel)
#Group(groupName).add(Channel("abc"))
data = {'name':'andrew','uid':'asdasdsad','data':[1,2,3,45,5,4,6,4,3],'broken_biogas':22,'working_biogas':78}
Group("hellothere",channel_layer=message.channel_layer).send({"text": json.dumps(data)})
message.reply_channel.send({"accept": True})
message.channel_session['rooms'] = []
def receive(content):
"""
Called when a message is received with either text or bytes
filled out.
"""
channel_session_user = True
http_user = True
@channel_session_user
def ws_disconnect_jobs(message):
"""
Perform things on connection close
"""
Group("hellothere").discard(message.reply_channel)
@channel_session_user
def ws_message_jobs(message):
print(message.content['text'])
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session
def msg_consumer_jobs(message):
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session_user_from_http
def ws_add_biogas(message, **kwargs):
"""
Perform things on connection start
"""
# pdb.set_trace()
user = message.user
#groupName = 'test'
Group("hellothere",channel_layer=message.channel_layer).add(message.reply_channel)
#Group(groupName).add(Channel("abc"))
data = {'name':'andrew','uid':'asdasdsad','data':[1,2,3,45,5,4,6,4,3],'broken_biogas':22,'working_biogas':78}
Group("hellothere",channel_layer=message.channel_layer).send({"text": json.dumps(data)})
message.reply_channel.send({"accept": True})
message.channel_session['rooms'] = []
def receive(content):
"""
Called when a message is received with either text or bytes
filled out.
"""
channel_session_user = True
http_user = True
@channel_session_user
def ws_disconnect_biogas(message):
"""
Perform things on connection close
"""
Group("hellothere").discard(message.reply_channel)
@channel_session_user
def ws_message_biogas(message):
print(message.content['text'])
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
@channel_session
def msg_consumer_biogas(message):
Group('hellothere',channel_layer=message.channel_layer).send({"text": message.content['text']},immediately=True)
| 32.032864 | 139 | 0.702623 | 857 | 6,823 | 5.399067 | 0.129522 | 0.088178 | 0.070024 | 0.0992 | 0.802248 | 0.796628 | 0.796628 | 0.786687 | 0.779339 | 0.779339 | 0 | 0.012048 | 0.148468 | 6,823 | 213 | 140 | 32.032864 | 0.784337 | 0.265719 | 0 | 0.680412 | 0 | 0 | 0.108609 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.216495 | false | 0 | 0.092784 | 0 | 0.319588 | 0.051546 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
f2879c563750610c39aed8b82a5dd4a482dee5f9 | 68,610 | py | Python | benchmarks/SimResults/_bigLittle_hrrs_spec_tugberk_heteroFair/cmp_libquantum/power.py | TugberkArkose/MLScheduler | e493b6cbf7b9d29a2c9300d7dd6f0c2f102e4061 | [
"Unlicense"
] | null | null | null | benchmarks/SimResults/_bigLittle_hrrs_spec_tugberk_heteroFair/cmp_libquantum/power.py | TugberkArkose/MLScheduler | e493b6cbf7b9d29a2c9300d7dd6f0c2f102e4061 | [
"Unlicense"
] | null | null | null | benchmarks/SimResults/_bigLittle_hrrs_spec_tugberk_heteroFair/cmp_libquantum/power.py | TugberkArkose/MLScheduler | e493b6cbf7b9d29a2c9300d7dd6f0c2f102e4061 | [
"Unlicense"
] | null | null | null | power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate Leakage': 0.00662954,
'Peak Dynamic': 0.0,
'Runtime Dynamic': 0.0,
'Subthreshold Leakage': 0.0691322,
'Subthreshold Leakage with power gating': 0.0259246},
'Core': [{'Area': 32.6082,
'Execution Unit/Area': 8.2042,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202689,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.0,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.122718,
'Execution Unit/Instruction Scheduler/Area': 2.17927,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00115349,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.20978,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.150883,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.017004,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00962066,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00730101,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 1.00996,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00529112,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 2.07911,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.261274,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0800117,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0455351,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 4.84781,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.841232,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000856399,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.55892,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.149848,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0178624,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00897339,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.562005,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.114878,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0641291,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.149141,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 5.15239,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00546962,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0395522,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0404512,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0395522,
'Execution Unit/Register Files/Runtime Dynamic': 0.0459208,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0442632,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00607074,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0955743,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.270307,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0920413,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0345155,
'Execution Unit/Runtime Dynamic': 1.4863,
'Execution Unit/Subthreshold Leakage': 1.83518,
'Execution Unit/Subthreshold Leakage with power gating': 0.709678,
'Gate Leakage': 0.372997,
'Instruction Fetch Unit/Area': 5.86007,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00130741,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00130741,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00114712,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000448642,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000581084,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00434303,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0122366,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0590479,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0388867,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 2.47353,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.176495,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.132077,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 4.81393,
'Instruction Fetch Unit/Runtime Dynamic': 0.364038,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932587,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.408542,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.063204,
'L2/Runtime Dynamic': 0.018992,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80969,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.90354,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.350286,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0351387,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0215603,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0215603,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 2.00577,
'Load Store Unit/Runtime Dynamic': 0.478175,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0531641,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.106328,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591622,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283406,
'Memory Management Unit/Area': 0.434579,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0188681,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0198171,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00813591,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.153795,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0289344,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.344913,
'Memory Management Unit/Runtime Dynamic': 0.0487515,
'Memory Management Unit/Subthreshold Leakage': 0.0769113,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0399462,
'Peak Dynamic': 16.9419,
'Renaming Unit/Area': 0.369768,
'Renaming Unit/FP Front End RAT/Area': 0.168486,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.33511,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925,
'Renaming Unit/Free List/Area': 0.0414755,
'Renaming Unit/Free List/Gate Leakage': 4.15911e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0401324,
'Renaming Unit/Free List/Runtime Dynamic': 0.00771531,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000670426,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000377987,
'Renaming Unit/Gate Leakage': 0.00863632,
'Renaming Unit/Int Front End RAT/Area': 0.114751,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.00038343,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.86945,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0794183,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 0.0871336,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime Dynamic': 2.48339,
'Subthreshold Leakage': 6.21877,
'Subthreshold Leakage with power gating': 2.58311},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202689,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.0,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0544967,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0879011,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0443695,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.186767,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.0623287,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 3.94466,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00228584,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0165296,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0169052,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0165296,
'Execution Unit/Register Files/Runtime Dynamic': 0.019191,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0348231,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.097504,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 0.911528,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000555527,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000555527,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000488666,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000191797,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000242844,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00184256,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00515476,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0162514,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.03372,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0733465,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0551969,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 3.30241,
'Instruction Fetch Unit/Runtime Dynamic': 0.151792,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0264186,
'L2/Runtime Dynamic': 0.00806193,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.51139,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.144555,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.00887313,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.00887313,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.55329,
'Load Store Unit/Runtime Dynamic': 0.197187,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0218796,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.0437593,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.00776515,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00816185,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.0642731,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0120244,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.233721,
'Memory Management Unit/Runtime Dynamic': 0.0201862,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 12.65,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00245874,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0280561,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0305148,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 1.31927,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202689,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.0,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0543858,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0877222,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0442792,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.186387,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.0622007,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 3.94441,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00228118,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0164956,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0168708,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0164956,
'Execution Unit/Register Files/Runtime Dynamic': 0.0191519,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0347516,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.0973553,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 0.91096,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00055455,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00055455,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000487884,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000191532,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.00024235,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00183933,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0051429,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0162183,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.03162,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.0732292,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0550846,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 3.3002,
'Instruction Fetch Unit/Runtime Dynamic': 0.151514,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0264745,
'L2/Runtime Dynamic': 0.00815115,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.51155,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.144781,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0088786,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.00887866,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.55348,
'Load Store Unit/Runtime Dynamic': 0.197446,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0218931,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.0437865,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.00776993,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00816746,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.0641423,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0120051,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.233599,
'Memory Management Unit/Runtime Dynamic': 0.0201726,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 12.6476,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00245374,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0279993,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0304531,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 1.3187,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.0,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.202689,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.0,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.0539447,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.0870107,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0439201,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.184875,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.061698,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 3.94343,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.0,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00226268,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0163623,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0167339,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0163623,
'Execution Unit/Register Files/Runtime Dynamic': 0.0189966,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0344708,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.0964748,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 0.908413,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.000550901,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.000550901,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.000484815,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000190405,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000240384,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.001827,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.00510401,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0160867,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.02326,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.072582,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.0546378,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 3.29143,
'Instruction Fetch Unit/Runtime Dynamic': 0.150238,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0263117,
'L2/Runtime Dynamic': 0.00815812,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 1.50915,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.143636,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.00880081,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.00880074,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 1.55071,
'Load Store Unit/Runtime Dynamic': 0.195839,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0217013,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.0434022,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.00770186,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.00809685,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.0636224,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.011899,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.232962,
'Memory Management Unit/Runtime Dynamic': 0.0199959,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 12.6343,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.0,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00243383,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0277715,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.0302053,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 1.31285,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328}],
'DRAM': {'Area': 0,
'Gate Leakage': 0,
'Peak Dynamic': 6.4247750445005885,
'Runtime Dynamic': 6.4247750445005885,
'Subthreshold Leakage': 4.252,
'Subthreshold Leakage with power gating': 4.252},
'L3': [{'Area': 61.9075,
'Gate Leakage': 0.0484137,
'Peak Dynamic': 0.304743,
'Runtime Dynamic': 0.0987163,
'Subthreshold Leakage': 6.80085,
'Subthreshold Leakage with power gating': 3.32364}],
'Processor': {'Area': 191.908,
'Gate Leakage': 1.53485,
'Peak Dynamic': 55.1786,
'Peak Power': 88.2908,
'Runtime Dynamic': 6.53292,
'Subthreshold Leakage': 31.5774,
'Subthreshold Leakage with power gating': 13.9484,
'Total Cores/Area': 128.669,
'Total Cores/Gate Leakage': 1.4798,
'Total Cores/Peak Dynamic': 54.8738,
'Total Cores/Runtime Dynamic': 6.43421,
'Total Cores/Subthreshold Leakage': 24.7074,
'Total Cores/Subthreshold Leakage with power gating': 10.2429,
'Total L3s/Area': 61.9075,
'Total L3s/Gate Leakage': 0.0484137,
'Total L3s/Peak Dynamic': 0.304743,
'Total L3s/Runtime Dynamic': 0.0987163,
'Total L3s/Subthreshold Leakage': 6.80085,
'Total L3s/Subthreshold Leakage with power gating': 3.32364,
'Total Leakage': 33.1122,
'Total NoCs/Area': 1.33155,
'Total NoCs/Gate Leakage': 0.00662954,
'Total NoCs/Peak Dynamic': 0.0,
'Total NoCs/Runtime Dynamic': 0.0,
'Total NoCs/Subthreshold Leakage': 0.0691322,
'Total NoCs/Subthreshold Leakage with power gating': 0.0259246}} | 75.065646 | 124 | 0.682087 | 8,082 | 68,610 | 5.784459 | 0.064712 | 0.123551 | 0.112941 | 0.093433 | 0.941626 | 0.934332 | 0.921348 | 0.895786 | 0.867337 | 0.848513 | 0 | 0.131964 | 0.224326 | 68,610 | 914 | 125 | 75.065646 | 0.746482 | 0 | 0 | 0.664114 | 0 | 0 | 0.657402 | 0.048097 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
8a90ec229f863d38e78770931e9cc75826efa903 | 3,425 | py | Python | demo_scenes_rand_size.py | jyf588/pytorch-rl-bullet | 3ac1835d01e658b2078126895ffa0eb11304abb4 | [
"MIT"
] | null | null | null | demo_scenes_rand_size.py | jyf588/pytorch-rl-bullet | 3ac1835d01e658b2078126895ffa0eb11304abb4 | [
"MIT"
] | null | null | null | demo_scenes_rand_size.py | jyf588/pytorch-rl-bullet | 3ac1835d01e658b2078126895ffa0eb11304abb4 | [
"MIT"
] | null | null | null | SCENES = {
1: [
{
"shape": "box",
"color": "yellow",
"position": [0.15, 0.7, 0, 0],
},
{
"shape": "box",
"color": "green",
"position": [0.2, 0.4, 0, 0],
},
{
"shape": "cylinder",
"color": "blue",
"position": [0.1, -0.05, 0, 0],
},
{
"shape": "box",
"color": "yellow",
"position": [0.0, 0.1, 0, 0],
},
],
2: [
{
"shape": "box",
"color": "yellow",
"position": [0.15, 0.7, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "green",
"position": [0.1, -0.06, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "blue",
"position": [0.2, 0.4, 0, 0],
"size": "large",
},
{
"shape": "box",
"color": "yellow",
"position": [0.3, 0.3, 0, 0],
"size": "large",
},
],
3: [
{
"shape": "box",
"color": "yellow",
"position": [0.15, 0.7, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "green",
"position": [0.1, -0.06, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "blue",
"position": [0.1, 0.3, 0, 0],
"size": "large",
},
{
"shape": "box",
"color": "yellow",
"position": [0.2, 0.4, 0, 0],
"size": "large",
},
],
# 4: [
# {
# "shape": "box",
# "color": "yellow",
# "position": [0.15, 0.7, 0, 0],
# "size": "large",
# },
# {
# "shape": "cylinder",
# "color": "green",
# "position": [0.1, -0.06, 0.16, 0],
# "size": "large",
# },
# {
# "shape": "cylinder",
# "color": "blue",
# "position": [0.1, 0.3, 0, 0],
# "size": "large",
# },
# {
# "shape": "box",
# "color": "yellow",
# "position": [0.2, 0.4, 0, 0],
# "size": "large",
# },
# {
# "shape": "cylinder",
# "color": "red",
# "position": [0.1, -0.06, 0.0, 0],
# "size": "large",
# },
# ],
4: [
{
"shape": "box",
"color": "yellow",
"position": [0.15, 0.7, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "green",
"position": [0.2, 0.4, 0.16, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "blue",
"position": [0.0, -0.06, 0, 0],
"size": "large",
},
{
"shape": "box",
"color": "yellow",
"position": [0.1, 0.3, 0, 0],
"size": "large",
},
{
"shape": "cylinder",
"color": "red",
"position": [0.2, 0.4, 0.0, 0],
"size": "large",
},
],
}
| 24.119718 | 48 | 0.277372 | 288 | 3,425 | 3.298611 | 0.076389 | 0.054737 | 0.189474 | 0.185263 | 0.981053 | 0.96 | 0.916842 | 0.902105 | 0.84 | 0.84 | 0 | 0.090855 | 0.505109 | 3,425 | 141 | 49 | 24.29078 | 0.469617 | 0.192993 | 0 | 0.564815 | 0 | 0 | 0.220066 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 |
8a962af0c6b3c44955d6ed2cb6ad92f7235587a2 | 23,523 | py | Python | tests/functional/validators/test_validators_all_variable_uses_defined.py | matt-koevort/tartiflette | 5777866b133d846ce4f8aa03f735fa81832896cd | [
"MIT"
] | 530 | 2019-06-04T11:45:36.000Z | 2022-03-31T09:29:56.000Z | tests/functional/validators/test_validators_all_variable_uses_defined.py | matt-koevort/tartiflette | 5777866b133d846ce4f8aa03f735fa81832896cd | [
"MIT"
] | 242 | 2019-06-04T11:53:08.000Z | 2022-03-28T07:06:27.000Z | tests/functional/validators/test_validators_all_variable_uses_defined.py | matt-koevort/tartiflette | 5777866b133d846ce4f8aa03f735fa81832896cd | [
"MIT"
] | 36 | 2019-06-21T06:40:27.000Z | 2021-11-04T13:11:16.000Z | import pytest
@pytest.mark.parametrize(
"query,expected",
[
(
"""
query {
catOrDog(id: $a) { name }
}
""",
{
"data": None,
"errors": [
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 3, "column": 36}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Undefined Variable < a > in anonymous Operation.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 3, "column": 30},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
],
},
),
(
"""
query {
... {
catOrDog(id: $a) {
name @skip(if: $b)
knowCommands @include(if: $b)
}
}
}
""",
{
"data": None,
"errors": [
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 5, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field knowCommands doesn't exist on CatOrDog",
"path": ["catOrDog", "knowCommands"],
"locations": [{"line": 6, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Undefined Variable < a > in anonymous Operation.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 4, "column": 34},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < b > in anonymous Operation.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 5, "column": 40},
{"line": 6, "column": 51},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
],
},
),
(
"""
query {
... {
catOrDog(id: $a) {
name @skip(if: $b)
knowCommands @include(if: $b)
}
}
}
query anotherQuery($a: Int) {
... {
catOrDog(id: $a) {
name @skip(if: $b)
knowCommands @include(if: $b)
}
}
}
""",
{
"data": None,
"errors": [
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 5, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field knowCommands doesn't exist on CatOrDog",
"path": ["catOrDog", "knowCommands"],
"locations": [{"line": 6, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 13, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field knowCommands doesn't exist on CatOrDog",
"path": ["catOrDog", "knowCommands"],
"locations": [{"line": 14, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Anonymous operation must be the only defined operation.",
"path": None,
"locations": [{"line": 2, "column": 13}],
"extensions": {
"rule": "5.2.2.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Lone-Anonymous-Operation",
"tag": "lone-anonymous-operation",
},
},
{
"message": "Undefined Variable < a > in anonymous Operation.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 4, "column": 34},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < b > in anonymous Operation.",
"path": None,
"locations": [
{"line": 2, "column": 13},
{"line": 5, "column": 40},
{"line": 6, "column": 51},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < b > in Operation < anotherQuery >.",
"path": None,
"locations": [
{"line": 10, "column": 13},
{"line": 13, "column": 40},
{"line": 14, "column": 51},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Can't use < $a / Int > for type < Int! >.",
"path": ["catOrDog"],
"locations": [
{"line": 10, "column": 32},
{"line": 12, "column": 34},
],
"extensions": {
"rule": "5.8.5",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Usages-are-Allowed",
"tag": "all-variable-usages-are-allowed",
},
},
],
},
),
(
"""
fragment DogFragment on Dog {
name @skip(if: $c)
doesKnowCommand(command: $d)
... {
tryThis @include(if: $f)
}
...anotherDogFragment
}
fragment anotherDogFragment on Dog {
aField(id: $f)
}
query {
... {
catOrDog(id: $a) {
name @skip(if: $b)
knowCommands @include(if: $b)
}
}
}
query anotherQuery($a: Int) {
... {
catOrDog(id: $a) {
name @skip(if: $b)
knowCommands @include(if: $b)
...DogFragment
}
}
}
""",
{
"data": None,
"errors": [
{
"message": "Provided Argument < command > doesn't exist on field < Dog.doesKnowCommand >.",
"path": ["doesKnowCommand"],
"locations": [{"line": 4, "column": 33}],
"extensions": {
"rule": "5.4.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Argument-Names",
"tag": "argument-names",
},
},
{
"message": "Missing mandatory argument < dogCommand > in field < Dog.doesKnowCommand >.",
"path": ["doesKnowCommand"],
"locations": [{"line": 4, "column": 17}],
"extensions": {
"rule": "5.4.2.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Required-Arguments",
"tag": "required-arguments",
},
},
{
"message": "Field tryThis doesn't exist on Dog",
"path": ["tryThis"],
"locations": [{"line": 6, "column": 21}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field aField doesn't exist on Dog",
"path": ["aField"],
"locations": [{"line": 12, "column": 17}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 18, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field knowCommands doesn't exist on CatOrDog",
"path": ["catOrDog", "knowCommands"],
"locations": [{"line": 19, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field name doesn't exist on CatOrDog",
"path": ["catOrDog", "name"],
"locations": [{"line": 26, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Field knowCommands doesn't exist on CatOrDog",
"path": ["catOrDog", "knowCommands"],
"locations": [{"line": 27, "column": 25}],
"extensions": {
"rule": "5.3.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types",
"tag": "field-selections-on-objects-interfaces-and-unions-types",
},
},
{
"message": "Anonymous operation must be the only defined operation.",
"path": None,
"locations": [{"line": 15, "column": 13}],
"extensions": {
"rule": "5.2.2.1",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-Lone-Anonymous-Operation",
"tag": "lone-anonymous-operation",
},
},
{
"message": "Undefined Variable < a > in anonymous Operation.",
"path": None,
"locations": [
{"line": 15, "column": 13},
{"line": 17, "column": 34},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < b > in anonymous Operation.",
"path": None,
"locations": [
{"line": 15, "column": 13},
{"line": 18, "column": 40},
{"line": 19, "column": 51},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < b > in Operation < anotherQuery >.",
"path": None,
"locations": [
{"line": 23, "column": 13},
{"line": 26, "column": 40},
{"line": 27, "column": 51},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < f > in Operation < anotherQuery >.",
"path": None,
"locations": [
{"line": 23, "column": 13},
{"line": 12, "column": 28},
{"line": 6, "column": 42},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < c > in Operation < anotherQuery >.",
"path": None,
"locations": [
{"line": 23, "column": 13},
{"line": 3, "column": 32},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Undefined Variable < d > in Operation < anotherQuery >.",
"path": None,
"locations": [
{"line": 23, "column": 13},
{"line": 4, "column": 42},
],
"extensions": {
"rule": "5.8.3",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Uses-Defined",
"tag": "all-variable-uses-defined",
},
},
{
"message": "Can't use < $a / Int > for type < Int! >.",
"path": ["catOrDog"],
"locations": [
{"line": 23, "column": 32},
{"line": 25, "column": 34},
],
"extensions": {
"rule": "5.8.5",
"spec": "June 2018",
"details": "https://graphql.github.io/graphql-spec/June2018/#sec-All-Variable-Usages-are-Allowed",
"tag": "all-variable-usages-are-allowed",
},
},
],
},
),
],
)
@pytest.mark.asyncio
@pytest.mark.ttftt_engine
async def test_validators_all_variable_uses_defined(query, expected, engine):
assert await engine.execute(query) == expected
| 47.521212 | 150 | 0.339242 | 1,595 | 23,523 | 4.999373 | 0.079624 | 0.050539 | 0.058315 | 0.073865 | 0.912215 | 0.901304 | 0.896288 | 0.896288 | 0.895912 | 0.880361 | 0 | 0.046966 | 0.525698 | 23,523 | 494 | 151 | 47.617409 | 0.667742 | 0 | 0 | 0.62181 | 0 | 0.067285 | 0.373766 | 0.05167 | 0 | 0 | 0 | 0 | 0.00232 | 1 | 0 | true | 0 | 0.00232 | 0 | 0.00232 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
8a973cafb0b20026a0fcf491c59bd705338bb6c8 | 108,933 | py | Python | buildcoef2d.py | TiKeil/Masterthesis-LOD | 03c1c6748a0464165a666bd9f4f933bc8e4f233b | [
"Apache-2.0"
] | null | null | null | buildcoef2d.py | TiKeil/Masterthesis-LOD | 03c1c6748a0464165a666bd9f4f933bc8e4f233b | [
"Apache-2.0"
] | null | null | null | buildcoef2d.py | TiKeil/Masterthesis-LOD | 03c1c6748a0464165a666bd9f4f933bc8e4f233b | [
"Apache-2.0"
] | 1 | 2020-03-30T08:49:13.000Z | 2020-03-30T08:49:13.000Z | # This file is part of the master thesis "Variational crimes in the Localized orthogonal decomposition method":
# https://github.com/TiKeil/Masterthesis-LOD.git
# Copyright holder: Tim Keil
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
import numpy as np
import random
class Coefficient2d:
def __init__(self,NWorldFine,
bg=0.01,
val=1,
length=1,
thick=1,
space=1,
probfactor = 10,
right=0,
down=0,
diagr1=0,
diagr2=0,
diagl1=0,
diagl2=0,
LenSwitch=None,
thickSwitch=None,
equidistant=None,
ChannelHorizontal=None,
ChannelVertical=None,
BoundarySpace=None,
Boxes2n=None,
Channels2n=None,
NewShapes=None,
RandomInverse=None,
TestExample=None):
'''
2dCoefficient
'''
self.NWorldFine = NWorldFine
self.bg = bg
self.val = val
#basic properties
self.length = length
self.thick = thick
self.space = space
#probability
self.probfactor = probfactor
#shapes
self.right = right
self.down = down
self.diagr1 = diagr1
self.diagr2 = diagr2
self.diagl1 = diagl1
self.diagl2 = diagl2
#more features
self.LenSwitch = LenSwitch
self.thickSwitch = thickSwitch
self.equidistant = equidistant
self.ChannelHorizontal = ChannelHorizontal
self.ChannelVertical = ChannelVertical
self.BoundarySpace = BoundarySpace
self.Boxes2n = Boxes2n
self.Channels2n = Channels2n
#additional memory
self.Matrix = None
self.RandomMatrix = None
#the shaperemember has 1 := 7
self.ShapeRemember = None
self.ShapeRememberOriginal = None
#channelsafer
self.Channelsafer = None
self.nomore = 0
self.NewShapes = NewShapes
#newshapes
self.Shapes = 0
self.ShapeMatrixes = np.array([])
self.ShapeSizes = np.array([])
self.ShapeIndex = [0]
self.ShapeCoords = []
self.CoordsIndex = [0]
#valuecount
self.valuecounter = None
self.TestExample = TestExample
def NewShape(self, ShapeBuildMatrix):
'''
you need to enumerate the new shapes by yourself
'''
self.Shapes += 1
Sizing = np.shape(ShapeBuildMatrix)
self.ShapeIndex.append(Sizing[0]*Sizing[1]+self.ShapeIndex[self.Shapes-1])
Shaping = ShapeBuildMatrix.flatten()
self.ShapeMatrixes = np.append(self.ShapeMatrixes,Shaping)
Shapesizes = self.ShapeSizes.flatten()
Shapesizes= np.append(Shapesizes,Sizing)
self.ShapeSizes = np.reshape(Shapesizes,(self.Shapes,2))
#search indizes
NumberOfShapes = Sizing[0]
LengthPosition = []
ThickPosition = []
ShapeCoords = []
ShapeCoords.extend([0,0])
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = ShapeBuildMatrix[shape][1] #what length
ShapeThick = ShapeBuildMatrix[shape][2] #what thick
ShapeShapes = ShapeBuildMatrix[shape][4]
ShapeInverser = ShapeBuildMatrix[shape][3] #how many shapes
pxs = ShapeCoords[shape*2]
pys = ShapeCoords[shape*2+1]
for i in range(0,ShapeShapes):
LengthPosition = ShapeBuildMatrix[shape][5+2*i] #where regarding length
ThickPosition = ShapeBuildMatrix[shape][6+2*i]
px, py = self.SearchShapeIndex(ShapeIndex, LengthPosition, ThickPosition)
px *= ShapeInverser
py *= ShapeInverser
ShapeCoords.extend([pxs+px,pys+py])
self.ShapeCoords.extend(ShapeCoords)
summand = self.CoordsIndex[self.Shapes-1]
self.CoordsIndex.append(summand + 2*NumberOfShapes)
return 0
########################### IndexSearch ###################################
def SearchShapeIndex(self, Shape, LengthPosition, ThickPosition):
if Shape == 1:
px = ThickPosition
py = LengthPosition
elif Shape == 2:
px = ThickPosition+LengthPosition
py = LengthPosition
elif Shape == 3:
px = LengthPosition
py = LengthPosition+ThickPosition
elif Shape == 4:
px = LengthPosition
py = ThickPosition
elif Shape ==5:
px = ThickPosition+LengthPosition
py = -LengthPosition
elif Shape == 6:
px = LengthPosition
py = -LengthPosition+ThickPosition
return px, py
############### BUILD FUNCTION #################
def BuildCoefficient(self):
#random seed
random.seed(20)
#regain properties
NWorldFine = self.NWorldFine
bg = self.bg
val = self.val
#basic properties
thick = self.thick
space = self.space
#more features
LenSwitch = self.LenSwitch
thickSwitch = self.thickSwitch
equidistant = self.equidistant
ChannelHorizontal = self.ChannelHorizontal
ChannelVertical = self.ChannelVertical
BoundarySpace = self.BoundarySpace
#essential
A = np.zeros(NWorldFine)
B = A.copy()
#initial for shape remember
S = np.array([])
#for remember
shapecounter = 0
#add not included coefficients
#Maybe improve
if self.Channels2n:
self.down = True
self.length = NWorldFine[0]
self.thick = 1
self.space = 1
#EvenChannels
Abase = np.zeros(NWorldFine[1])
for i in range(2,NWorldFine[1]/2-1,2):
shapecounter += 1
S = np.append(S,[4,self.length,1])
Abase[i] = val-bg
Abase[i+NWorldFine[1]/2-1] = val-bg
AbaseCube = np.tile(Abase[...,np.newaxis], [NWorldFine[0],1])
AbaseCube = AbaseCube[...,np.newaxis]
ABase = AbaseCube.flatten()
A = ABase.reshape(NWorldFine)
A += bg
S = np.reshape(S,(shapecounter,3))
self.ShapeRemember = S
self.ShapeRememberOriginal = S
self.Matrix = A
self.RandomMatrix = A
return A
if self.Boxes2n:
self.right = True
self.length = 1
self.thick = 1
self.space = 1
#annas coeff for even boxes
A = np.zeros(NWorldFine)
A += bg
for i in range(2,NWorldFine[0]/2-1,2):
for j in range(2,NWorldFine[1]/2-1,2):
A[i][j]= val
A[i+NWorldFine[0]/2-1][j]= val
#shaperemember
shapecounter += 1
S = np.append(S,[1,1,1])
for k in range(NWorldFine[1]/2+1,NWorldFine[1]-2,2):
A[i][k]= val
A[i+NWorldFine[0]/2-1][k]= val
#shaperemember
shapecounter += 1
S = np.append(S,[1,1,1])
S = np.reshape(S,(shapecounter,3))
self.Matrix=A
self.ShapeRemember = S
self.ShapeRememberOriginal = S
self.RandomMatrix = A
return A
np.random.seed(0)
if self.probfactor > 0:
valorbg = np.ones(self.probfactor)*bg #percentage
valorbg[0] = val
if self.probfactor < 0:
valorbg = np.ones(-self.probfactor)*val #percentage
valorbg[0] = bg
LenList = []
LenList.append(self.length)
if LenSwitch is not None:
assert(equidistant is None)
LenList = LenSwitch #must be a list
#channelspecial
c = 0 # initial loop constant
if ChannelVertical:
assert(ChannelHorizontal is None)
LenList = [NWorldFine[0]]
c = 1
if ChannelHorizontal:
assert(ChannelVertical is None)
LenList = [NWorldFine[1]]
c = 1
thickList = []
thickList.append(thick)
if thickSwitch is not None:
assert(equidistant is None)
thickList = thickSwitch #must be a list
if ChannelVertical:
starti = 0
endi = NWorldFine[0]
else:
starti = 1
endi = NWorldFine[0]-1
if ChannelHorizontal:
startj = 0
endj = NWorldFine[1]
else:
startj = 1
endj = NWorldFine[1]-1
#Boundaryspace
b = 0 #boundary initial
if BoundarySpace:
if space == 0:
spacing = 1
else:
spacing = space
if ChannelVertical is not True:
starti = spacing
endi = NWorldFine[0]-spacing
if ChannelHorizontal is not True:
startj = spacing
endj = NWorldFine[1]-spacing
b = spacing -1
if self.TestExample:
startj=22
for i in range(starti,endi):
#special for channel
for j in range(startj,endj):
# print "i" + str(i)
# print "j" + str(j)
#can we do something here?
if A[i][j] == 0:
#will we do something here?
A[i][j] = random.sample(valorbg,1)[0]
if equidistant:
A[i][j] = 1 #yes sure
#if yes then
if A[i][j] == 1:
#len randomizing
Len = random.sample(LenList,1)[0]
thick = random.sample(thickList,1)[0]
#yes but first go back to zero
A[i][j] = 0
stop = 0 #initial for loop change
#build zuf
if ChannelVertical:
zuf = [4]
elif ChannelHorizontal:
zuf = [1]
else:
zuf = []
zuf.extend([self.right*1,self.down*4,self.diagr1*2,self.diagr2*3,self.diagl1*5,self.diagl2*6])
for s in range(0,self.Shapes):
#IMMPORTANT
zuf.append(s+7)
zuf = list(filter(lambda x: x!=0 ,zuf))
zuf1 = random.sample(zuf,1)[0] #chooses shape
'''
1 : right
2 : right diag1
3 : right diag2
4 : down
5 : left diag1
6 : left diag2
7+: new shapes
'''
########### investigate ##########
#does it fit into the grid
ShapeResults = []
ShapeResults.append(self.InvestigateRight(A, i, j, Len, thick, b, c, Channel=ChannelHorizontal))
ShapeResults.append(self.InvestigateDiagr1(A, i, j, Len, thick, b, c))
ShapeResults.append(self.InvestigateDiagr2(A, i, j, Len, thick, b, c))
ShapeResults.append(self.InvestigateDown(A, i, j, Len, thick, b, c, Channel=ChannelVertical))
ShapeResults.append(self.InvestigateDiagl1(A, i, j, Len, thick, b, c))
ShapeResults.append(self.InvestigateDiagl2(A, i, j, Len, thick, b, c))
for s in range(0,self.Shapes):
#rebuildMatrix
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
ShapeResults.append(self.InvestigateNewShapes(NewShapeMatrix, ShapeCoords, A, i, j, b, c))
for z in range(0,100): #arbitrary
if ShapeResults[zuf1-1] == 0:
zuf1 = random.sample(zuf,1)[0]
stop = 1
else:
stop = 0
break
if stop == 1:
continue
#shape remember
shapecounter += 1
S = np.append(S,[zuf1,Len,thick])
############################### keine if-abfragen zum crash mehr notwendig ###############
if zuf1 == 1:
A, B = self.BuildRight(A, B, i, j, val, bg, Len, thick, space)
elif zuf1 == 2:
A, B = self.BuildDiagr1(A, B, i, j, val, bg, Len, thick, space)
elif zuf1 == 3:
A, B = self.BuildDiagr2(A, B, i, j, val, bg, Len, thick, space)
elif zuf1 == 4:
A, B = self.BuildDown(A, B, i, j, val, bg, Len, thick, space)
elif zuf1 == 5:
A, B = self.BuildDiagl1(A, B, i, j, val, bg, Len, thick, space)
elif zuf1 == 6:
A, B = self.BuildDiagl2(A, B, i, j, val, bg, Len, thick, space)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, B = self.BuildNewShapes(NewShapeMatrix, ShapeCoords, A, B, i, j, val, bg, space)
#search for all values
valuecounter = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j] == 1:
valuecounter += 1
self.valuecounter = valuecounter
S = np.reshape(S,(shapecounter,3))
#print S
B += bg
self.Matrix = B
self.ShapeRemember = S
self.ShapeRememberOriginal = S
self.RandomMatrix = B
return B
########################### investigation ##################################
def InvestigateRight(self, A, i, j, Len, thick, b, c, inv = 1, Channel=None):
if Channel:
b1 = b
b2 = 0
else:
b1 = b
b2 = b
NWorldFine = self.NWorldFine
result = 1
if j+inv*(Len) < NWorldFine[1]-b2+c and j+inv*(Len) > -1+b2 and i+inv*(thick) < NWorldFine[0]-b1 and i+inv*(thick) > -1+b1:
for k in range(0,int(inv*(Len)),inv):
#rechts
for l in range(0,int(inv*thick),inv):
if i+l < NWorldFine[0] and i+l > -1 and j+k < NWorldFine[1] and j+k > -1:
if A[i+l][j+k] != 0:
result = 0
else:
result = 0
else:
result = 0
return result
def InvestigateDiagr1(self, A, i, j, Len, thick, b, c, inv = 1):
NWorldFine = self.NWorldFine
result = 1
if j+inv*Len < NWorldFine[1]-b and j+inv*Len > -1+b and i+inv*(Len+1+thick-1) < NWorldFine[0]-b and i+inv*(Len+1+thick-1) > -1+b:
for k in range(0,int(inv*Len),inv):
#rechts diag1
for l in range(0,int(inv*(thick+1)),inv):
if A[i+l+k][j+k] != 0:
result = 0
else:
result = 0
return result
def InvestigateDiagr2(self, A, i, j, Len, thick, b, c, inv = 1):
NWorldFine = self.NWorldFine
result = 1
if j+inv*(Len+thick) < NWorldFine[1]-b and j+inv*(Len+thick) > -1+b and i+inv*(Len) < NWorldFine[0]-b and i+inv*(Len) > -1+b:
for k in range(0,int(inv*Len),inv):
#rechts diag2
for l in range(0,int(inv*(thick+1)),inv):
if A[i+k][j+k+l] != 0:
result = 0
else:
result = 0
return result
def InvestigateDown(self, A, i, j, Len, thick, b, c, inv = 1, Channel = None):
if Channel:
b1 = b
b2 = 0
else:
b1 = b
b2 = b
NWorldFine = self.NWorldFine
result = 1
if j+inv*(thick) < NWorldFine[1]-b1 and j+inv*(thick) > -1+b1 and i+inv*(Len)-c < NWorldFine[0]-b2 and i+inv*(Len) > -1 +b2:
for k in range(0,int(inv*Len),inv):
#down
for l in range(0,int(inv*thick),inv):
if i+k < NWorldFine[0] and i+k > -1 and j+l < NWorldFine[1] and j+l > -1:
if A[i+k][j+l] != 0:
result= 0
else:
result = 0
return result
def InvestigateDiagl1(self, A, i, j, Len, thick, b, c, inv = 1):
NWorldFine = self.NWorldFine
result = 1
if j-inv*Len > -1+b and j-inv*Len < NWorldFine[1]-b and i+inv*(Len+thick) < NWorldFine[0]-b and i+inv*(Len+thick) >-1+b:
for k in range(0,int(inv*Len),inv):
#links diag1
for l in range(0,int(inv*(thick+1)),inv):
if i+l+k < NWorldFine[0] and i+l+k > -1 and j-k < NWorldFine[1] and j-k > -1:
if A[i+l+k][j-k] != 0:
result = 0
else:
result = 0
return result
def InvestigateDiagl2(self, A, i, j, Len, thick, b, c, inv = 1):
NWorldFine = self.NWorldFine
result = 1
if j-inv*(Len) > -1+b and j-inv*(Len) < NWorldFine[1] and i+inv*(Len) < NWorldFine[0]-b and i+inv*(Len) >-1+b and j+inv*(thick+1) < NWorldFine[1]-b and j+inv*(thick+1) > -1+b:
for k in range(0,int(inv*Len),inv):
#links diag2
for l in range(0,int(inv*(thick+1)),inv):
if A[i+k][j-k+l] != 0:
result = 0
else:
result = 0
return result
def InvestigateNewShapes(self, ShapeBuildMatrix, ShapeCoords, A, i, j, b, c):
NumberOfShapes = np.shape(ShapeBuildMatrix)[0]
resulttotal = 0
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thickness
ShapeInverser = int(ShapeBuildMatrix[shape][3]) #what direction
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
#basic shape
if ShapeIndex == 1:
result = self.InvestigateRight(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
elif ShapeIndex == 2:
result = self.InvestigateDiagr1(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
elif ShapeIndex == 3:
result = self.InvestigateDiagr2(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
elif ShapeIndex == 4:
result = self.InvestigateDown(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
elif ShapeIndex == 5:
result = self.InvestigateDiagl1(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
elif ShapeIndex == 6:
result = self.InvestigateDiagl2(A, int(i+px), int(j+py), ShapeLength, ShapeThick, b, c, ShapeInverser)
resulttotal += result
if np.sum(resulttotal) == NumberOfShapes:
result = 1
else:
result = 0
return result
################################# Build #########################################
def BuildRight(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#rechts
for l in range(0,int(inv*thick),inv):
A[i+l][j+k] = 1
B[i+l][j+k] = (val-bg)
for s in range(inv,int(inv*(space+1)),inv):
if i-s>-1 and i-s < NWorldFine[0]:
if A[i-s][j+k] != 1:
A[i-s][j+k] = bg
if i+inv*(thick-1)+s < NWorldFine[0] and i+inv*(thick-1)+s > -1:
if A[i+int(inv*(thick-1))+s][j+k] != 1:
A[i+int(inv*(thick-1))+s][j+k] = bg
for r in range(0,int(inv*(2*space+thick)),inv):
for s in range(0,int(inv*space),inv):
if i+r-inv*space < NWorldFine[0] and i+r-inv*space >-1 and j+inv*Len+s < NWorldFine[1] and j+inv*Len+s >-1:
if A[i+r-inv*space][j+int(inv*Len)+s] != 1:
A[i+r-inv*space][j+int(inv*Len)+s] = bg
if i+r-inv*space < NWorldFine[0] and i+r-inv*space > -1 and j-inv-s > -1 and j-inv-s < NWorldFine[1]:
if A[i+r-inv*space][j-inv-s] != 1:
A[i+r-inv*space][j-inv-s] = bg
return A, B
def BuildDiagr1(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#rechts diag1
for l in range(0,int(inv*(thick+1)),inv):
A[i+l+k][j+k] = 1
B[i+l+k][j+k] = (val-bg)
for s in range(inv,int(inv*(space+2)),inv):
if i-s+k>-1 and i-s+k < NWorldFine[0]:
if A[i-s+k][j+k] != 1:
A[i-s+k][j+k] = bg
if i+inv*thick+s+k < NWorldFine[0] and i+inv*thick+s+k >-1:
if A[i+inv*thick+s+k][j+k] != 1:
A[i+inv*thick+s+k][j+k] = bg
for r in range(0,int(inv*(2*(space+1)+thick-1)),inv):
for s in range(0,int(inv*space),inv):
if i+inv*(Len-space-1)+r > -1 and i+inv*(Len-space-1)+r < NWorldFine[0] and j+inv*Len+s < NWorldFine[1] and j+inv*Len+s > -1:
if A[i+inv*(Len-space-1)+r][j+int(inv*Len)+s] != 1:
A[i+inv*(Len-space-1)+r][j+int(inv*Len)+s] = bg
for r in range(0,int(inv*(2*space+thick+1)),inv):
for s in range(0,int(inv*space),inv):
if i+r-inv*space < NWorldFine[0] and i+r-inv*space > -1 and j-inv-s > -1 and j-inv-s < NWorldFine[1]:
if A[i+r-inv*space][j-inv-s] != 1:
A[i+r-inv*space][j-inv-s] = bg
if i+inv*(Len+thick+space) < NWorldFine[0] and i+inv*(Len+thick+space) >-1:
if A[i+inv*(Len+thick+space)][j+inv*(Len-1)] == bg:
A[i+inv*(Len+thick+space)][j+inv*(Len-1)] = 0
return A, B
def BuildDiagr2(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#rechts diag2
for l in range(0,int(inv*(thick+1)),inv):
A[i+k][j+k+l] = 1
B[i+k][j+k+l] = (val-bg)
for s in range(inv,int(inv*(space+2)),inv):
if j-s+k>-1 and j-s+k < NWorldFine[1] and i+k < NWorldFine[0] and i+k > -1:
if A[i+k][j-s+k] != 1:
A[i+k][j-s+k] = bg
if j+inv*(thick)+s+k < NWorldFine[1] and j+inv*(thick)+s+k > -1:
if A[i+k][j+k+inv*thick+s] != 1:
A[i+k][j+k+inv*thick+s] = bg
for r in range(0,int(inv*(space)),inv):
for s in range(0,inv*(2*space+1+thick),inv):
if i-inv-r < NWorldFine[0] and i-inv-r >-1 and j-inv*space+s < NWorldFine[1] and j-inv*space+s > -1:
if A[i-inv-r][j-inv*space+s] != 1:
A[i-inv-r][j-inv*space+s] = bg
for r in range(0,int(inv*space),inv):
for s in range(0,int(inv*(2*(space+1)+thick-1)),inv):
if i+inv*Len+r < NWorldFine[0] and i+inv*Len+r > -1 and j+inv*(Len-space-1)+s < NWorldFine[1] and j+inv*(Len-space-1)+s > -1:
if A[i+inv*Len+r][j+inv*(Len-space-1)+s] != 1:
A[i+inv*Len+r][j+inv*(Len-space-1)+s] = bg
if j+inv*(Len+thick+space) < NWorldFine[1]:
if A[i+inv*(Len-1)][j+inv*(Len+thick+space)] == bg:
A[i+inv*(Len-1)][j+inv*(Len+thick+space)] = 0
return A, B
def BuildDown(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#down
for l in range(0,int(inv*thick),inv):
A[i+k][j+l] = 1
B[i+k][j+l] = (val-bg)
for s in range(inv,int(inv*(space+1)),inv):
if j-s>-1 and j-s < NWorldFine[1]:
if A[i+k][j-s] != 1:
A[i+k][j-s] = bg
if j+inv*(thick-1)+s < NWorldFine[1] and j+inv*(thick-1)+s > -1:
if A[i+k][j+inv*(thick-1)+s] != 1:
A[i+k][j+inv*(thick-1)+s] = bg
for r in range(0,int(inv*space),inv):
for s in range(0,inv*(2*space+thick),inv):
if i+inv*Len+r < NWorldFine[0] and i+inv*Len+r >-1 and j-inv*space+s < NWorldFine[1] and j-inv*space+s > -1:
if A[i+inv*Len+r][j-inv*space+s] != 1:
A[i+inv*Len+r][j-inv*space+s] = bg
for r in range(0,int(inv*(space)),inv):
for s in range(0,inv*(2*space+thick),inv):
if i-inv-r < NWorldFine[0] and i-inv-r >-1 and j-inv*space+s < NWorldFine[1] and j-inv*space+s > -1:
if A[i-inv-r][j-inv*space+s] != 1:
A[i-inv-r][j-inv*space+s] = bg
return A, B
def BuildDiagl1(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#links diag1
for l in range(0,int(inv*(thick+1)),inv):
A[i+l+k][j-k] = 1
B[i+l+k][j-k] = (val-bg)
for s in range(inv,int(inv*(space+2)),inv):
if i-s+k>-1 and i-s+k < NWorldFine[0]:
if A[i-s+k][j-k] != 1:
A[i-s+k][j-k] = bg
if i+inv*thick+s+k < NWorldFine[0] and i+inv*thick+s+k >-1:
if A[i+inv*thick+s+k][j-k] != 1:
A[i+inv*thick+s+k][j-k] = bg
for r in range(0,int(inv*(2*(space+1)+thick-1)),inv):
for s in range(0,inv*space,inv):
if i+inv*(Len-space-1)+r > -1 and i+inv*(Len-space-1)+r < NWorldFine[0] and j-inv*Len-s > -1 and j-inv*Len-s < NWorldFine[1]:
if A[i+inv*(Len-space-1)+r][j-inv*Len-s] != 1:
A[i+inv*(Len-space-1)+r][j-inv*Len-s] = bg
for r in range(0,int(inv*(2*space+thick+1)),inv):
for s in range(0,inv*space,inv):
if i+r-inv*space < NWorldFine[0] and i+r-inv*space > -1 and j+inv+s < NWorldFine[1] and j+inv+s >-1:
if A[i+r-inv*space][j+inv+s] != 1:
A[i+r-inv*space][j+inv+s] = bg
if i+inv*(Len+thick+space) < NWorldFine[0] and i+inv*(Len+thick+space) > -1:
if A[i+inv*(Len+thick+space)][j+inv*(-Len+1)]==bg:
A[i+inv*(Len+thick+space)][j+inv*(-Len+1)] = 0
return A, B
def BuildDiagl2(self, A, B, i, j, val, bg, Len, thick, space, inv = 1):
NWorldFine = self.NWorldFine
for k in range(0,int(inv*Len),inv):
#links diag2
for l in range(0,int(inv*(thick+1)),inv):
A[i+k][j-k+l] = 1
B[i+k][j-k+l] = (val-bg)
for s in range(inv,int(inv*(space+2)),inv):
if j-k+s+inv*thick < NWorldFine[1] and j-k+s+inv*thick >-1:
if A[i+k][j-k+s+inv*thick] != 1:
A[i+k][j-k+s+inv*thick] = bg
if j-s-k > -1 and j-s-k < NWorldFine[1]:
if A[i+k][j-k-s] != 1:
A[i+k][j-k-s] = bg
for r in range(0,int(inv*space),inv):
for s in range(0,int(inv*(2*(space+1)+thick-1)),inv):
if i+inv*Len+r < NWorldFine[0] and i+inv*Len+r > -1 and j+inv*(1-Len-space)+s < NWorldFine[1] and j+inv*(1-Len-space)+s > -1:
if A[i+inv*Len+r][j+inv*(1-Len-space)+s] != 1:
A[i+inv*Len+r][j+inv*(1-Len-space)+s] = bg
for r in range(0,int(inv*(space)),inv):
for s in range(0,inv*(2*space+1+thick),inv):
if i-inv-r < NWorldFine[0] and i-inv-r >-1 and j-inv*space+s < NWorldFine[1] and j-inv*space+s > -1:
if A[i-inv-r][j-inv*(space)+s] != 1:
A[i-inv-r][j-inv*(space)+s] = bg
return A, B
def BuildNewShapes(self, ShapeBuildMatrix, ShapeCoords, A, B, i, j, val, bg, space):
NumberOfShapes = np.shape(ShapeBuildMatrix)[0]
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thick
ShapeInverser = int(ShapeBuildMatrix[shape][3])
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
#basic shape
if ShapeIndex == 1:
A, B = self.BuildRight(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
elif ShapeIndex == 2:
A, B = self.BuildDiagr1(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
elif ShapeIndex == 3:
A, B = self.BuildDiagr2(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
elif ShapeIndex == 4:
A, B = self.BuildDown(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
elif ShapeIndex == 5:
A, B = self.BuildDiagl1(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
elif ShapeIndex == 6:
A, B = self.BuildDiagl2(A, B, int(i+px), int(j+py), val, bg, ShapeLength, ShapeThick, space, ShapeInverser)
return A,B
################################# RANDOM ##############################################
################# Value Change ##############################
def RandomValueChange(self,
ratio=0.1,
probfactor=1,
randomvalue=None,
negative=None,
ShapeRestriction=True,
ShapeWave=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Original = True,
NewShapeChange=True):
#Changes Value randomly or certainly
'''
Ratio = amount of defect : 0.1 = 10 % of the reference value
probfactor = defines the percentage of the possibility of the defect. 1 = 100% , 20 = 5% maybe change this
randomvalue = if true then a intervall of ratios is required
negative = if true also negative defects are allowed
'''
#remember stuff
assert(self.ShapeRemember is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
C = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
C = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
A = C.copy()
#ratio
ratioList = [ratio]
if randomvalue is not None:
ratioList = randomvalue
#negative
if negative:
for i in range(0,np.size(ratioList)):
ratioList.append(-ratioList[i])
#probability
if probfactor > 0:
decision = np.zeros(probfactor)
decision[0] = 1
if probfactor < 0:
decision = np.ones(probfactor)
decision[0] = 0
#for remember
shapecounter = -1
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
if ShapeRestriction:
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]==1:
shapecounter += 1
#find the right shape
#regain the shape length and thicknes
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
ratiocur = random.sample(ratioList,1)[0]
decide = random.sample(decision,1)[0]
if zuf1 == 1:
A, C = self.ValueChangeRight(A, C, i, j, ChangeRight, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 2:
A, C = self.ValueChangeDiagr1(A, C, i, j, ChangeDiagr1, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 3:
A, C = self.ValueChangeDiagr2(A, C, i, j, ChangeDiagr2, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 4:
A, C = self.ValueChangeDown(A, C, i, j, ChangeDown, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 5:
A, C = self.ValueChangeDiagl1(A, C, i, j, ChangeDiagl1, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 6:
A, C = self.ValueChangeDiagl2(A, C, i, j, ChangeDiagl2, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C = self.ValueChangeNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, ShapeChange[s], decide, decision, ShapeWave, ratioList, ratiocur, val)
else:
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]==1:
if random.sample(decision,1)[0] == 1:
C[i][j] += random.sample(ratioList,1)[0] * val
self.RandomMatrix = C
return C
def ValueChangeRight(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
for l in range(0,inv*thick,inv):
#forget about this shape
A[i+l][j+k] = 0
if Change:
#rechts
if decide == 1:
for l in range(0,inv*thick,inv):
#change it
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+l][j+k] += random.sample(ratioList,1)[0] * val
else:
C[i+l][j+k] += ratiocur * val
return A, C
def ValueChangeDiagr1(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
#rechts diag1
for l in range(0,inv*(thick+1),inv):
A[i+l+k][j+k] = 0
if Change:
if decide == 1:
for l in range(0,inv*(thick+1),inv):
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+l+k][j+k] += random.sample(ratioList,1)[0] * val
else:
C[i+l+k][j+k] += ratiocur * val
return A, C
def ValueChangeDiagr2(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
#rechts diag2
for l in range(0,inv*(thick+1),inv):
A[i+k][j+k+l] = 0
if Change:
if decide == 1:
for l in range(0,inv*(thick+1),inv):
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+k][j+k+l] += random.sample(ratioList,1)[0] * val
else:
C[i+k][j+k+l] += ratiocur * val
return A, C
def ValueChangeDown(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
#down
for l in range(0,inv*thick,inv):
A[i+k][j+l] = 0
if Change:
if decide == 1:
for l in range(0,inv*thick,inv):
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+k][j+l] += random.sample(ratioList,1)[0] * val
else:
C[i+k][j+l] += ratiocur * val
return A, C
def ValueChangeDiagl1(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
#links diag1
for l in range(0,inv*(thick+1),inv):
A[i+l+k][j-k] = 0
if Change:
if decide == 1:
for l in range(0,inv*(thick+1),inv):
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+l+k][j-k] += random.sample(ratioList,1)[0] * val
else:
C[i+l+k][j-k] += ratiocur * val
return A, C
def ValueChangeDiagl2(self, A, C, i, j, Change, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick, inv = 1):
for k in range(0,inv*Len,inv):
#links diag2
for l in range(0,inv*(thick+1),inv):
A[i+k][j-k+l] = 0
if Change:
if decide == 1:
for l in range(0,inv*(thick+1),inv):
if ShapeWave:
if random.sample(decision,1)[0] == 1:
C[i+k][j-k+l] += random.sample(ratioList,1)[0] * val
else:
C[i+k][j-k+l] += ratiocur * val
return A, C
def ValueChangeNewShapes(self, ShapeBuildMatrix, ShapeCoords, A, C, i, j, ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val):
NumberOfShapes = np.shape(ShapeBuildMatrix)[0]
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thick
ShapeInverser = int(ShapeBuildMatrix[shape][3])
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
if ShapeIndex == 1:
A, C = self.ValueChangeRight(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 2:
A, C = self.ValueChangeDiagr1(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 3:
A, C = self.ValueChangeDiagr2(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 4:
A, C = self.ValueChangeDown(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 5:
A, C = self.ValueChangeDiagl1(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 6:
A, C = self.ValueChangeDiagl2(A, C, int(i+px), int(j+py), ShapeChange, decide, decision, ShapeWave, ratioList, ratiocur, val, ShapeLength, ShapeThick, ShapeInverser)
return A,C
def SpecificValueChange(self, Number = None,
ratio=0.1,
probfactor=1,
randomvalue=None,
negative=None,
ShapeRestriction=True,
ShapeWave=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Original = True,
NewShapeChange=True):
#Changes Value randomly or certainly
'''
Ratio = amount of defect : 0.1 = 10 % of the reference value
probfactor = defines the percentage of the possibility of the defect. 1 = 100% , 20 = 5% maybe change this
randomvalue = if true then a intervall of ratios is required
negative = if true also negative defects are allowed
'''
#remember stuff
assert(self.ShapeRemember is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
C = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
C = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
A = C.copy()
if Number is None:
Number = [int(round(np.shape(S)[0]/2.,0))]
#ratio
ratioList = [ratio]
if randomvalue is not None:
ratioList = randomvalue
#negative
if negative:
for i in range(0,np.size(ratioList)):
ratioList.append(-ratioList[i])
if probfactor > 0:
decision = np.zeros(probfactor)
decision[0] = 1
if probfactor < 0:
decision = np.ones(probfactor)
decision[0] = 0
#for remember
shapecounter = -1
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
if ShapeRestriction:
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]==1:
shapecounter += 1
#find the right shape
#regain the shape length and thicknes
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
ratiocur = random.sample(ratioList,1)[0]
decide = random.sample(decision,1)[0]
NumberList = filter(lambda x: x == shapecounter,Number)
if np.size(NumberList) == 1:
decide = 1
else:
decide = 0
NumberList = filter(lambda x: x == shapecounter,Number)
if np.size(NumberList) == 1:
move = 1
else:
move = 0
if zuf1 == 1:
A, C = self.ValueChangeRight(A, C, i, j, ChangeRight, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 2:
A, C = self.ValueChangeDiagr1(A, C, i, j, ChangeDiagr1, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 3:
A, C = self.ValueChangeDiagr2(A, C, i, j, ChangeDiagr2, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 4:
A, C = self.ValueChangeDown(A, C, i, j, ChangeDown, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 5:
A, C = self.ValueChangeDiagl1(A, C, i, j, ChangeDiagl1, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
elif zuf1 == 6:
A, C = self.ValueChangeDiagl2(A, C, i, j, ChangeDiagl2, decide, decision, ShapeWave, ratioList, ratiocur, val, Len, thick)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C = self.ValueChangeNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, ShapeChange[s], decide, decision, ShapeWave, ratioList, ratiocur, val)
self.RandomMatrix = C
return C
##################################### Vanish ###################################
def RandomVanish(self,
probfactor=1,
PartlyVanish=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Original = True,
NewShapeChange=True):
#remember stuff
assert(self.ShapeRememberOriginal is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
bg = self.bg
C = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
C = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
A = C.copy()
#probability
if probfactor > 0:
decision = np.ones(probfactor) * val
decision[0] = bg
if probfactor < 0:
decision = np.ones(probfactor) * bg
decision[0] = val
#for remember
shapecounter = -1
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
shapecounter += 1
#find the right shape
for s in range(shapecounter,np.shape(S)[0]):
if S[s][0] == 0:
shapecounter += 1
else:
break
#regain the shape length and thicknes
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
vanish = random.sample(decision,1)[0]
#initial diecounter
died = 0
if zuf1 == 1:
A, C, died = self.VanishRight(A, C, i, j, Len, thick, ChangeRight, PartlyVanish, decision, vanish)
elif zuf1 == 2:
A, C, died = self.VanishDiagr1(A, C, i, j, Len, thick, ChangeDiagr1 , PartlyVanish, decision, vanish)
elif zuf1 == 3:
A, C, died = self.VanishDiagr2(A, C, i, j, Len, thick, ChangeDiagr2 , PartlyVanish, decision, vanish)
elif zuf1 == 4:
A, C, died = self.VanishDown(A, C, i, j, Len, thick, ChangeDown, PartlyVanish, decision, vanish)
elif zuf1 == 5:
A, C, died = self.VanishDiagl1(A, C, i, j, Len, thick, ChangeDiagl1, PartlyVanish, decision, vanish)
elif zuf1 == 6:
A, C, died = self.VanishDiagl2(A, C, i, j, Len, thick, ChangeDiagl2, PartlyVanish, decision, vanish)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C, died = self.VanishNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, ShapeChange[s], PartlyVanish, decision, vanish)
if died == bg:
S[shapecounter][0] = 0
self.RandomMatrix = C
return C
def VanishRight(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
for l in range(0,inv*thick,inv):
#forget about this shape
A[i+l][j+k] = 0
if Change:
#rechts
for l in range(0,inv*thick,inv):
#change it
if PartlyVanish:
C[i+l][j+k] = random.sample(decision,1)[0]
else:
C[i+l][j+k] = vanish
died = vanish
return A, C, died
def VanishDiagr1(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
#rechts diag1
for l in range(0,inv*(thick+1),inv):
A[i+l+k][j+k] = 0
if Change:
for l in range(0,inv*(thick+1),inv):
if PartlyVanish:
C[i+l+k][j+k] = random.sample(decision,1)[0]
else:
C[i+l+k][j+k] = vanish
died = vanish
return A, C, died
def VanishDiagr2(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
#rechts diag2
for l in range(0,inv*(thick+1),inv):
A[i+k][j+k+l] = 0
if Change:
for l in range(0,inv*(thick+1),inv):
if PartlyVanish:
C[i+k][j+k+l] = random.sample(decision,1)[0]
else:
C[i+k][j+k+l] = vanish
died = vanish
return A, C, died
def VanishDown(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
#down
for l in range(0,inv*thick,inv):
A[i+k][j+l] = 0
if Change:
for l in range(0,inv*thick,inv):
if PartlyVanish:
C[i+k][j+l] = random.sample(decision,1)[0]
else:
C[i+k][j+l] = vanish
died = vanish
return A, C, died
def VanishDiagl1(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
#links diag1
for l in range(0,inv*(thick+1),inv):
A[i+l+k][j-k] = 0
if Change:
for l in range(0,inv*(thick+1),inv):
if PartlyVanish:
C[i+l+k][j-k] = random.sample(decision,1)[0]
else:
C[i+l+k][j-k] = vanish
died = vanish
return A, C, died
def VanishDiagl2(self, A, C, i, j, Len, thick, Change, PartlyVanish, decision, vanish, inv = 1):
died = 0
for k in range(0,inv*Len,inv):
#links diag2
for l in range(0,inv*(thick+1),inv):
A[i+k][j-k+l] = 0
if Change:
for l in range(0,inv*(thick+1),inv):
if PartlyVanish:
C[i+k][j-k+l] = random.sample(decision,1)[0]
else:
C[i+k][j-k+l] = vanish
died = vanish
return A, C, died
def VanishNewShapes(self, ShapeBuildMatrix, ShapeCoords, A, C, i, j, ShapeChange, PartlyVanish, decision, vanish):
died = 0
NumberOfShapes = np.shape(ShapeBuildMatrix)[0]
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thick
ShapeInverser = int(ShapeBuildMatrix[shape][3])
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
if ShapeIndex == 1:
A, C, died = self.VanishRight(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
elif ShapeIndex == 2:
A, C, died = self.VanishDiagr1(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
elif ShapeIndex == 3:
A, C, died = self.VanishDiagr2(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
elif ShapeIndex == 4:
A, C, died = self.VanishDown(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
elif ShapeIndex == 5:
A, C, died = self.VanishDiagl1(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
elif ShapeIndex == 6:
A, C, died = self.VanishDiagl2(A, C, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeChange, PartlyVanish, decision, vanish, ShapeInverser)
return A,C, died
def SpecificVanish(self, Number = None,
probfactor=1,
PartlyVanish=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Original = True,
NewShapeChange=True):
#remember stuff
assert(self.ShapeRememberOriginal is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
bg = self.bg
C = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
C = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
A = C.copy()
if Number is None:
Number = [int(round(np.shape(S)[0]/2.,0))]
#probability
decision = np.ones(probfactor) * val
decision[0] = bg
#for remember
shapecounter = -1
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
shapecounter += 1
NumberList = filter(lambda x: x == shapecounter,Number)
if NumberList is not []:
#find the right shape
#regain the shape length and thicknes
for s in range(shapecounter,np.shape(S)[0]):
if S[s][0] == 0:
shapecounter += 1
else:
break
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
vanish = random.sample(decision,1)[0]
NumberList = filter(lambda x: x == shapecounter,Number)
if np.size(NumberList) == 1:
vanish = bg
else:
vanish = val
#initial diecounter
died = 0
if zuf1 == 1:
A, C, died = self.VanishRight(A, C, i, j, Len, thick, ChangeRight, PartlyVanish, decision, vanish)
elif zuf1 == 2:
A, C, died = self.VanishDiagr1(A, C, i, j, Len, thick, ChangeDiagr1 , PartlyVanish, decision, vanish)
elif zuf1 == 3:
A, C, died = self.VanishDiagr2(A, C, i, j, Len, thick, ChangeDiagr2 , PartlyVanish, decision, vanish)
elif zuf1 == 4:
A, C, died = self.VanishDown(A, C, i, j, Len, thick, ChangeDown, PartlyVanish, decision, vanish)
elif zuf1 == 5:
A, C, died = self.VanishDiagl1(A, C, i, j, Len, thick, ChangeDiagl1, PartlyVanish, decision, vanish)
elif zuf1 == 6:
A, C, died = self.VanishDiagl2(A, C, i, j, Len, thick, ChangeDiagl2, PartlyVanish, decision, vanish)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C, died = self.VanishNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, ShapeChange[s], PartlyVanish, decision, vanish)
if died == bg:
S[shapecounter][0] = 0
self.RandomMatrix = C
return C
###################################### MOVE #############################################
def RandomMove(self,
probfactor=1,
steps=1,
randomstep=None,
randomDirection=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Right=1,
BottomRight=0,
Bottom=0,
BottomLeft=0,
Left=0,
TopLeft=0,
Top=0,
TopRight=0,
Original = True,
NewShapeChange = True):
#remember stuff
assert(self.ShapeRememberOriginal is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
bg = self.bg
A = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
A = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
C = np.zeros(NWorldFine)
C += bg
#probability
if probfactor > 0:
decision = np.zeros(probfactor)
decision[0] = 1
if probfactor < 0:
decision = np.ones(probfactor)
decision[0] = 0
#steplist
stepList = [steps]
if randomstep is not None:
stepList = randomstep
MoveList = [Right*1,BottomRight*2,Bottom*3,BottomLeft*4,Left*5,TopLeft*6,Top*7,TopRight*8]
MoveList = list(filter(lambda x: x!=0 ,MoveList))
#for remember
shapecounter = -1
#initial boundaryfailcounter
nomore = 0
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
shapecounter += 1
#find the right shape
#regain the shape length and thicknes
for s in range(shapecounter,np.shape(S)[0]):
if S[s][0] == 0:
shapecounter += 1
else:
break
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
move = random.sample(decision,1)[0]
step = random.sample(stepList,1)[0]
direction = random.sample(MoveList,1)[0]
if direction == 1:
m1 = 0
m2 = step
elif direction == 2:
m1 = step
m2 = step
elif direction == 3:
m1 = step
m2 = 0
elif direction == 4:
m1 = step
m2 = -step
elif direction == 5:
m1 = 0
m2 = -step
elif direction == 6:
m1 = -step
m2 = -step
elif direction == 7:
m1 = -step
m2 = 0
elif direction == 8:
m1 = -step
m2 = step
if randomDirection:
for i in range(0,np.size(stepList)):
stepList.append(-stepList[i])
stepList.append(0)
m1 = random.sample(stepList,1)[0]
m2 = random.sample(stepList,1)[0]
if zuf1 == 1:
C = self.MoveRight(A, C, i, j, m1, m2, Len, thick, ChangeRight, move)
A, nomore = self.KillingRight(A, i, j, Len, thick)
elif zuf1 == 2:
C = self.MoveDiagr1(A, C, i, j, m1, m2, Len, thick, ChangeDiagr1, move)
A, nomore = self.KillingDiagr1(A, i, j, Len, thick)
elif zuf1 == 3:
C = self.MoveDiagr2(A, C, i, j, m1, m2, Len, thick, ChangeDiagr2, move)
A, nomore = self.KillingDiagr2(A, i, j, Len, thick)
elif zuf1 == 4:
C = self.MoveDown(A, C, i, j, m1, m2, Len, thick, ChangeDown, move)
A, nomore = self.KillingDown(A, i, j, Len, thick)
elif zuf1 == 5:
C = self.MoveDiagl1(A, C, i, j, m1, m2, Len, thick, ChangeDiagl1, move)
A, nomore = self.KillingDiagl1(A, i, j, Len, thick)
elif zuf1 == 6:
C = self.MoveDiagl2(A, C, i, j, m1, m2, Len, thick, ChangeDiagl2, move)
A, nomore = self.KillingDiagl2(A, i, j, Len, thick)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C, died = self.MoveNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, m1, m2, ShapeChange[s], move)
self.nomore = nomore
self.RandomMatrix = C
return C
##### MOVE ###############
def MoveRight(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
if Change:
if move ==1:
if i+inv*(thick)+m1 < NWorldFine[0] and i+inv*(thick)+m1 > -1 and j+inv*(Len)+m2 < NWorldFine[1] and j+inv*(Len)+m2 >-1:
#rechts
for l in range(0,inv*thick,inv):
#change it
C[i+l+m1][j+k+m2] = A[i+l][j+k]
else:
for l in range(0,inv*thick,inv):
#change it
C[i+l][j+k] = A[i+l][j+k]
return C
def MoveDiagr1(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
#rechts diag1
if Change:
if move ==1:
if i+inv*(thick+Len-1)+m1 < NWorldFine[0] and i+inv*(thick+Len-1)+m1 > -1 and j+inv*(Len-1)+m2 < NWorldFine[1] and j+inv*(Len-1)+m2 >-1:
for l in range(0,inv*(thick+1),inv):
C[i+l+k+m1][j+k+m2] = A[i+l+k][j+k]
else:
for l in range(0,inv*(thick+1),inv):
C[i+l+k][j+k] = A[i+l+k][j+k]
return C
def MoveDiagr2(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
#rechts diag2
if Change:
if move ==1:
if i+inv*(Len-1)+m1 < NWorldFine[0] and i+inv*(Len-1)+m1 > -1 and j+inv*(thick+Len-1)+m2 < NWorldFine[1] and j+inv*(thick+Len-1)+m2 >-1:
for l in range(0,inv*(thick+1),inv):
C[i+k+m1][j+k+l+m2] = A[i+k][j+k+l]
else:
for l in range(0,inv*(thick+1),inv):
C[i+k][j+k+l] = A[i+k][j+k+l]
return C
def MoveDown(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
#down
if Change:
if move ==1:
if i+inv*(Len-1)+m1 < NWorldFine[0] and i+inv*(Len-1)+m1 > -1 and j+inv*(thick-1)+m2 < NWorldFine[1] and j+inv*(thick-1)+m2 >-1:
for l in range(0,inv*thick,inv):
C[i+k+m1][j+l+m2] = A[i+k][j+l]
else:
for l in range(0,inv*thick,inv):
C[i+k][j+l] = A[i+k][j+l]
return C
def MoveDiagl1(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
#links diag1
if Change:
if move ==1:
if i+inv*(Len-1+thick)+m1 < NWorldFine[0] and i+inv*(Len-1+thick)+m1 > -1 and j+inv*(1-Len)+m2 < NWorldFine[1] and j+inv*(1-Len)+m2 >-1:
for l in range(0,inv*(thick+1),inv):
C[i+l+k+m1][j-k+m2] = A[i+l+k][j-k]
else:
for l in range(0,inv*(thick+1),inv):
C[i+l+k][j-k] = A[i+l+k][j-k]
return C
def MoveDiagl2(self, A, C, i, j, m1, m2, Len, thick, Change, move, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
#links diag2
if Change:
if move ==1:
if i+inv*(Len-1)+m1 < NWorldFine[0] and i+inv*(Len-1)+m1 > -1 and j+inv*(thick+1-Len)+m2 < NWorldFine[1] and j+inv*(thick+1-Len)+m2 >-1:
for l in range(0,inv*(thick+1),inv):
C[i+k+m1][j-k+l+m2] = A[i+k][j-k+l]
else:
for l in range(0,inv*(thick+1),inv):
C[i+k][j-k+l] = A[i+k][j-k+l]
return C
########################## Killing ######################################
def KillingRight(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*thick,inv):
if i+l < NWorldFine[0] and j+k < NWorldFine[1]:
#forget about this shape
A[i+l][j+k] = 0
else:
nomore = 1
return A, nomore
def KillingDiagr1(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*(thick+1),inv):
if i+k < NWorldFine[0] and j+k < NWorldFine[1] and i+k >-1 and j+k >-1:
A[i+l+k][j+k] = 0
else:
nomore = 1
return A, nomore
def KillingDiagr2(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*(thick+1),inv):
if i+k < NWorldFine[0] and j+k+l < NWorldFine[1]:
A[i+k][j+k+l] = 0
else:
nomore = 1
return A, nomore
def KillingDown(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*thick,inv):
if i+k < NWorldFine[0] and j+l < NWorldFine[1]:
A[i+k][j+l] = 0
else:
nomore = 1
return A, nomore
def KillingDiagl1(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*(thick+1),inv):
if i+k+l < NWorldFine[0] and j-k > -1:
A[i+l+k][j-k] = 0
else:
nomore = 1
return A, nomore
def KillingDiagl2(self, A, i, j, Len, thick, inv = 1):
nomore = 0
NWorldFine = self.NWorldFine
for k in range(0,inv*Len,inv):
for l in range(0,inv*(thick+1),inv):
if i+k < NWorldFine[0] and j-k+l < NWorldFine[1] and j-k+l > -1:
A[i+k][j-k+l] = 0
else:
nomore = 1
return A, nomore
def MoveNewShapes(self, ShapeBuildMatrix, ShapeCoords, A, C, i, j, m1, m2, ShapeChange, move):
nomore = 0
NumberOfShapes = np.shape(ShapeBuildMatrix)[0]
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thick
ShapeInverser = int(ShapeBuildMatrix[shape][3])
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
if ShapeIndex == 1:
C = self.MoveRight(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
elif ShapeIndex == 2:
C = self.MoveDiagr1(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
elif ShapeIndex == 3:
C = self.MoveDiagr2(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
elif ShapeIndex == 4:
C = self.MoveDown(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
elif ShapeIndex == 5:
C = self.MoveDiagl1(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
elif ShapeIndex == 6:
C = self.MoveDiagl2(A, C, int(i+px), int(j+py), m1, m2, ShapeLength, ShapeThick, ShapeChange, move, ShapeInverser)
#killing
for shape in range(0,NumberOfShapes):
#put them together uniquely with the following properties
ShapeIndex = ShapeBuildMatrix[shape][0] #what shape
ShapeLength = int(ShapeBuildMatrix[shape][1]) #what length
ShapeThick = int(ShapeBuildMatrix[shape][2]) #what thick
ShapeInverser = int(ShapeBuildMatrix[shape][3])
px = ShapeCoords[shape*2]
py = ShapeCoords[shape*2+1]
if ShapeIndex == 1:
A, nomore = self.KillingRight(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 2:
A, nomore = self.KillingDiagr1(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 3:
A, nomore = self.KillingDiagr2(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 4:
A, nomore = self.KillingDown(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 5:
A, nomore = self.KillingDiagl1(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
elif ShapeIndex == 6:
A, nomore = self.KillingDiagl2(A, int(i+px), int(j+py), ShapeLength, ShapeThick, ShapeInverser)
return A,C, nomore
def SpecificMove(self, Number = None,
probfactor=1,
steps=1,
randomstep=None,
randomDirection=None,
ChangeRight=1,
ChangeDown=1,
ChangeDiagr1=1,
ChangeDiagr2=1,
ChangeDiagl1=1,
ChangeDiagl2=1,
Right=1,
BottomRight=0,
Bottom=0,
BottomLeft=0,
Left=0,
TopLeft=0,
Top=0,
TopRight=0,
Original = True,
NewShapeChange = True):
#remember stuff
assert(self.ShapeRememberOriginal is not None)
assert(self.RandomMatrix is not None)
NWorldFine = self.NWorldFine
val = self.val
bg = self.bg
A = self.RandomMatrix.copy()
S = self.ShapeRemember.copy()
if Original:
A = self.Matrix.copy()
S = self.ShapeRememberOriginal.copy()
C = np.zeros(NWorldFine)
C += bg
#probability
decision = np.zeros(probfactor)
decision[0] = 1
if Number is None:
Number = [int(round(np.shape(S)[0]/2.,0))]
#steplist
stepList = [steps]
if randomstep is not None:
stepList = randomstep
MoveList = [Right*1,BottomRight*2,Bottom*3,BottomLeft*4,Left*5,TopLeft*6,Top*7,TopRight*8]
MoveList = list(filter(lambda x: x!=0 ,MoveList))
#for remember
shapecounter = -1
#initial boundaryfailcounter
nomore = 0
#NEwShapeChange
ShapeChange = np.zeros(self.Shapes)
if NewShapeChange == True:
ShapeChange = np.ones(self.Shapes)
else:
for shape in range(0,int(self.Shapes)):
if NewShapeChange[shape] == 0:
ShapeChange[shape] = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
shapecounter += 1
#find the right shape
#regain the shape length and thicknes
for s in range(shapecounter,np.shape(S)[0]):
if S[s][0] == 0:
shapecounter += 1
else:
break
zuf1 = int(S[shapecounter][0])
Len = int(S[shapecounter][1])
thick = int(S[shapecounter][2])
move = random.sample(decision,1)[0]
step = random.sample(stepList,1)[0]
direction = random.sample(MoveList,1)[0]
NumberList = filter(lambda x: x == shapecounter,Number)
if np.size(NumberList) == 1:
move = 1
else:
move = 0
if direction == 1:
m1 = 0
m2 = step
elif direction == 2:
m1 = step
m2 = step
elif direction == 3:
m1 = step
m2 = 0
elif direction == 4:
m1 = step
m2 = -step
elif direction == 5:
m1 = 0
m2 = -step
elif direction == 6:
m1 = -step
m2 = -step
elif direction == 7:
m1 = -step
m2 = 0
elif direction == 8:
m1 = -step
m2 = step
if randomDirection:
for i in range(0,np.size(stepList)):
stepList.append(-stepList[i])
stepList.append(0)
m1 = random.sample(stepList,1)[0]
m2 = random.sample(stepList,1)[0]
if zuf1 == 1:
C = self.MoveRight(A, C, i, j, m1, m2, Len, thick, ChangeRight, move)
A, nomore = self.KillingRight(A, i, j, Len, thick)
elif zuf1 == 2:
C = self.MoveDiagr1(A, C, i, j, m1, m2, Len, thick, ChangeDiagr1, move)
A, nomore = self.KillingDiagr1(A, i, j, Len, thick)
elif zuf1 == 3:
C = self.MoveDiagr2(A, C, i, j, m1, m2, Len, thick, ChangeDiagr2, move)
A, nomore = self.KillingDiagr2(A, i, j, Len, thick)
elif zuf1 == 4:
C = self.MoveDown(A, C, i, j, m1, m2, Len, thick, ChangeDown, move)
A, nomore = self.KillingDown(A, i, j, Len, thick)
elif zuf1 == 5:
C = self.MoveDiagl1(A, C, i, j, m1, m2, Len, thick, ChangeDiagl1, move)
A, nomore = self.KillingDiagl1(A, i, j, Len, thick)
elif zuf1 == 6:
C = self.MoveDiagl2(A, C, i, j, m1, m2, Len, thick, ChangeDiagl2, move)
A, nomore = self.KillingDiagl2(A, i, j, Len, thick)
for s in range(0,self.Shapes):
#rebuildMatrix
if zuf1 == 7+s:
NewShapeMatrix = self.ShapeMatrixes[self.ShapeIndex[s]:self.ShapeIndex[s+1]]
NewShapeMatrix = np.reshape(NewShapeMatrix,(int(self.ShapeSizes[s][0]),int(self.ShapeSizes[s][1])))
ShapeCoords = self.ShapeCoords[self.CoordsIndex[s]:self.CoordsIndex[s+1]]
A, C, died = self.MoveNewShapes(NewShapeMatrix, ShapeCoords, A, C, i, j, m1, m2, ShapeChange[s], move)
self.nomore = nomore
self.RandomMatrix = C
return C
def ChannelVerticalRandomize(self, probfactor=10,
LU = 1,
RU = 1,
LO = 1,
RO = 1,
Original=True):
assert(self.ChannelVertical)
NWorldFine = self.NWorldFine
bg = self.bg
A = self.RandomMatrix.copy()
if Original:
A = self.Matrix.copy()
B = self.Matrix.copy()
if self.Channelsafer is None:
CS = self.Matrix.copy()
else:
CS = self.Channelsafer
O = self.Matrix.copy()
if probfactor > 0:
decision = np.zeros(probfactor)
decision[0] = 1
if probfactor < 0:
decision = np.ones(probfactor)
decision[0] = 0
DirectionListori = [LU*1,RU*2,LO*3,RO*4]
DirectionListori = list(filter(lambda x: x!=0 ,DirectionListori))
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
DirectionList = DirectionListori
#get thick
thick = 0
for k in range(0,NWorldFine[1]):
if O[i][j+k]!=bg and O[i][j+k]!=0:
thick += 1
A[i][j+k] = 0
else:
break
#get length
spacelu = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if stop == 1:
break
for l in range(0,thick):
if j-k > -1 and i-l > -1:
if CS[i-l][j-k] == bg or CS[i-l][j-k] == 0:
spacelu += 1
else:
stop = 1
else:
stop = 1
break
spacelu /= thick
spacelo = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if stop == 1:
break
for l in range(0,thick):
if j-k > -1 and i+l < NWorldFine[0]:
if CS[i+l][j-k] == bg or CS[i+l][j-k] == 0:
spacelo += 1
else:
stop = 1
else:
stop = 1
break
spacelo /= thick
spacelreal = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if j-k > -1:
if O[i][j-k] == bg or O[i][j-k] == 0:
spacelreal += 1
else:
break
else:
break
spaceru = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if stop == 1:
break
for l in range(0,thick):
if j+k+thick-1 < NWorldFine[1] and i-l > -1:
if CS[i-l][j+k+thick-1] == bg or CS[i-l][j+k+thick-1] == 0:
spaceru += 1
else:
stop = 1
else:
stop = 1
break
spaceru /= thick
spacero = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if stop == 1:
break
for l in range(0,thick):
if j+k+thick-1 < NWorldFine[1] and i+l < NWorldFine[0]:
if CS[i+l][j+k+thick-1] == bg or CS[i+l][j+k+thick-1] == 0:
spacero += 1
else:
stop = 1
else:
stop = 1
break
spacero /= thick
spacerreal = 0.
stop = 0
for k in range(1,NWorldFine[1]):
if j+k+thick-1 < NWorldFine[1]:
if O[i][j+k+thick-1] == bg or O[i][j+k+thick-1] == 0:
spacerreal += 1
else:
break
else:
break
if spacelreal != spacelo:
DirectionList = list(filter(lambda x: x!=1 ,DirectionList))
if spacelreal != spacelu:
DirectionList = list(filter(lambda x: x!=3 ,DirectionList))
if spacerreal != spacero:
DirectionList = list(filter(lambda x: x!=2,DirectionList))
if spacerreal != spaceru:
DirectionList = list(filter(lambda x: x!=4,DirectionList))
if spacelo ==0 or spacelu == 0:
DirectionList = list(filter(lambda x: x!=1 and x!=3 ,DirectionList))
if spacero ==0 or spaceru == 0:
DirectionList = list(filter(lambda x: x!=2 and x!=4 ,DirectionList))
matu = 0
for k in range(1,NWorldFine[0]):
if i+k < NWorldFine[0]:
if CS[i+k][j]!=bg and CS[i+k][j]!=0:
matu += 1
else:
break
else:
break
mato = 0
for k in range(1,NWorldFine[0]):
if i-k > -1:
if CS[i-k][j]!=bg and CS[i-k][j]!=0:
mato += 1
else:
break
else:
break
if mato < spacelo or matu+1 < thick:
DirectionList = list(filter(lambda x: x!=3 ,DirectionList))
if mato < spacero or matu+1 < thick:
DirectionList = list(filter(lambda x: x!=4 ,DirectionList))
if matu < spacelu or mato+1 < thick:
DirectionList = list(filter(lambda x: x!=1 ,DirectionList))
if matu < spaceru or mato+1 < thick:
DirectionList = list(filter(lambda x: x!=2 ,DirectionList))
if np.size(DirectionList) != 0:
direction = random.sample(DirectionList,1)[0]
else:
continue
if random.sample(decision,1)[0] == 0:
continue
if direction == 1:
#LU
for k in range(1,int(spacelu+1)):
for l in range(0,thick):
B[i-l][j-k] = B[i+k][j+l]
CS[i+k][j+l] = 0
B[i+k][j+l] = bg
A[i+k][j+l] = 0
elif direction == 2:
#Ru
for k in range(1,int(spaceru+1)):
for l in range(0,thick):
B[i-l][j+thick-1+k] = B[i+k][j+l]
CS[i+k][j+l] = 0
B[i+k][j+l] = bg
A[i+k][j+l] = 0
elif direction == 3:
#LO
for k in range(1,int(spacelo+1)):
for l in range(0,thick):
B[i+l][j-k] = B[i-k][j+l]
CS[i-k][j+l] = 0
A[i-k][j+l] = 0
B[i-k][j+l] = bg
elif direction == 4:
#RO
for k in range(1,int(spacero+1)):
for l in range(0,thick):
B[i+l][j+thick-1+k] = B[i-k][j+l]
CS[i-k][j+l] = 0
B[i-k][j+l] = bg
A[i-k][j+l] = 0
self.Channelsafe = CS
self.RandomMatrix = B
return B
def ChannelHorizontalRandomize(self, probfactor=10,
LU = 1,
RU = 1,
LO = 1,
RO = 1,
Original=True):
assert(self.ChannelHorizontal)
NWorldFine = self.NWorldFine
bg = self.bg
A = self.RandomMatrix.copy()
if Original:
A = self.Matrix.copy()
B = self.Matrix.copy()
if self.Channelsafer is None:
CS = self.Matrix.copy()
else:
CS = self.Channelsafer
O = self.Matrix.copy()
if probfactor > 0:
decision = np.zeros(probfactor)
decision[0] = 1
if probfactor < 0:
decision = np.ones(probfactor)
decision[0] = 0
DirectionListori = [LU*1,RU*2,LO*3,RO*4]
DirectionListori = list(filter(lambda x: x!=0 ,DirectionListori))
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j]!=bg and A[i][j]!=0:
DirectionList = DirectionListori
#get thick
thick = 0
for k in range(0,NWorldFine[0]):
if O[i+k][j]!=bg and O[i+k][j]!=0:
thick += 1
A[i+k][j] = 0
else:
break
#get length
spacelu = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if stop == 1:
break
for l in range(0,thick):
if i-k > -1 and j-l > -1:
if CS[i-k][j-l] == bg or CS[i-k][j-l] == 0:
spacelu += 1
else:
stop = 1
else:
stop = 1
break
spacelu /= thick
spacelo = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if stop == 1:
break
for l in range(0,thick):
if i-k > -1 and j+l < NWorldFine[1]:
if CS[i-k][j+l] == bg or CS[i-k][j+l] == 0:
spacelo += 1
else:
stop = 1
else:
stop = 1
break
spacelo /= thick
spacelreal = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if i-k > -1:
if O[i-k][j] == bg or O[i-k][j] == 0:
spacelreal += 1
else:
break
else:
break
spaceru = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if stop == 1:
break
for l in range(0,thick):
if i+k+thick-1 < NWorldFine[0] and j-l > -1:
if CS[i+k+thick-1][j-l] == bg or CS[i+k+thick-1][j-l] == 0:
spaceru += 1
else:
stop = 1
else:
stop = 1
break
spaceru /= thick
spacero = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if stop == 1:
break
for l in range(0,thick):
if i+k+thick-1 < NWorldFine[0] and j+l < NWorldFine[1]:
if CS[i+k+thick-1][j+l] == bg or CS[i+k+thick-1][j+l] == 0:
spacero += 1
else:
stop = 1
else:
stop = 1
break
spacero /= thick
spacerreal = 0.
stop = 0
for k in range(1,NWorldFine[0]):
if i+k+thick-1 < NWorldFine[0]:
if O[i+k+thick-1][j] == bg or O[i+k+thick-1][j] == 0:
spacerreal += 1
else:
break
else:
break
if spacelreal != spacelo:
DirectionList = list(filter(lambda x: x!=1 ,DirectionList))
if spacelreal != spacelu:
DirectionList = list(filter(lambda x: x!=3 ,DirectionList))
#print DirectionList
if spacerreal != spacero:
DirectionList = list(filter(lambda x: x!=2,DirectionList))
if spacerreal != spaceru:
DirectionList = list(filter(lambda x: x!=4,DirectionList))
#print DirectionList
if spacelo ==0 or spacelu == 0:
DirectionList = list(filter(lambda x: x!=1 and x!=3 ,DirectionList))
if spacero ==0 or spaceru == 0:
DirectionList = list(filter(lambda x: x!=2 and x!=4 ,DirectionList))
#print DirectionList
matu = 0
for k in range(1,NWorldFine[1]):
if j+k < NWorldFine[1]:
if CS[i][j+k]!=bg and CS[i][j+k]!=0:
matu += 1
else:
break
else:
break
mato = 0
for k in range(1,NWorldFine[1]):
if j-k > -1:
if CS[i][j-k]!=bg and CS[i][j-k]!=0:
mato += 1
else:
break
else:
break
if mato < spacelo or matu < thick:
DirectionList = list(filter(lambda x: x!=3 ,DirectionList))
if mato < spacero or matu < thick:
DirectionList = list(filter(lambda x: x!=4 ,DirectionList))
if matu < spacelu or mato < thick:
DirectionList = list(filter(lambda x: x!=1 ,DirectionList))
if matu < spaceru or mato < thick:
DirectionList = list(filter(lambda x: x!=2 ,DirectionList))
if np.size(DirectionList) != 0:
direction = random.sample(DirectionList,1)[0]
else:
continue
if random.sample(decision,1)[0] == 0:
continue
if direction == 1:
#LU
for k in range(1,int(spacelu+1)):
for l in range(0,thick):
B[i-k][j-l] = B[i+l][j+k]
CS[i+l][j+k] = 0
B[i+l][j+k] = bg
A[i+l][j+k] = 0
elif direction == 2:
#RU
for k in range(1,int(spaceru+1)):
for l in range(0,thick):
B[i+thick-1+k][j-l] = B[i+l][j+k]
CS[i+l][j+k] = 0
B[i+l][j+k] = bg
A[i+l][j+k] = 0
elif direction == 3:
#LO
for k in range(1,int(spacelo+1)):
for l in range(0,thick):
B[i-k][j+l] = B[i+l][j-k]
CS[i+l][j-k] = 0
A[i+l][j-k] = 0
B[i+l][j-k] = bg
elif direction == 4:
#RO
for k in range(1,int(spacero+1)):
for l in range(0,thick):
B[i+thick-1+k][j+l] = B[i+l][j-k]
CS[i+l][j-k] = 0
B[i+l][j-k] = bg
A[i+l][j-k] = 0
self.Channelsafe = CS
self.RandomMatrix = B
return B
def ExtremeRandomizer(self, Vanish=True, ValueChange=None, Move=None, Original = True, Number=None):
NWorldFine = self.NWorldFine
bg = self.bg
A = self.RandomMatrix.copy()
if Original:
A = self.Matrix.copy()
if Number is None:
Number = self.valuecounter[int(self.valuecounter/2.)]
valuecounter = 0
for i in range(0,NWorldFine[0]):
for j in range(0,NWorldFine[1]):
if A[i][j] == 1:
valuecounter += 1
NumberList = filter(lambda x: x == valuecounter,Number)
if np.size(NumberList) == 1:
if Vanish:
A[i][j] = bg
if ValueChange is not None:
A[i][j] = ValueChange
if Move is not None:
if Move[0]+i > -1 and Move[0]+i < NWorldFine[0] and Move[1]+j > -1 and Move[1]+j < NWorldFine[1]:
A[i+Move[0]][j+Move[1]] = A[i][j]
A[i][j] = bg
self.RandomMatrix = A
return A
| 42.601877 | 183 | 0.416467 | 11,776 | 108,933 | 3.852157 | 0.034817 | 0.033948 | 0.031744 | 0.017459 | 0.85228 | 0.835571 | 0.816569 | 0.789101 | 0.761898 | 0.753103 | 0 | 0.034763 | 0.471326 | 108,933 | 2,557 | 184 | 42.601877 | 0.752926 | 0.036545 | 0 | 0.734631 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009221 | 1 | 0.027664 | false | 0 | 0.001025 | 0 | 0.057377 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
8ab0e66cd38df78235c5cdee2be64f1b42423c04 | 593 | py | Python | scripts/server_test.py | SimonbJohnson/hdx_info | 0acc107608040adad2e7fba18a9f35ff1b59d90e | [
"MIT"
] | null | null | null | scripts/server_test.py | SimonbJohnson/hdx_info | 0acc107608040adad2e7fba18a9f35ff1b59d90e | [
"MIT"
] | null | null | null | scripts/server_test.py | SimonbJohnson/hdx_info | 0acc107608040adad2e7fba18a9f35ff1b59d90e | [
"MIT"
] | null | null | null | import requests
import json
data = {'hxlData' : [['organisation','reached'],['#org','#reached'],['BRC',20],['ARC',30]]}
r = requests.post('http://127.0.0.1:3000/charts', json=data)
#r = requests.post('http://httpbin.org/post', json=data)
print(r.status_code)
print(r.json())
r = requests.post('http://127.0.0.1:3000/maps', json=data)
#r = requests.post('http://httpbin.org/post', json=data)
print(r.status_code)
print(r.json())
r = requests.post('http://127.0.0.1:3000/text', json=data)
#r = requests.post('http://httpbin.org/post', json=data)
print(r.status_code)
print(r.json()) | 21.178571 | 91 | 0.659359 | 98 | 593 | 3.959184 | 0.265306 | 0.14433 | 0.201031 | 0.262887 | 0.773196 | 0.773196 | 0.773196 | 0.773196 | 0.773196 | 0.703608 | 0 | 0.062731 | 0.086003 | 593 | 28 | 92 | 21.178571 | 0.653137 | 0.278246 | 0 | 0.5 | 0 | 0 | 0.29108 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0.5 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
76ea213ad7a1e3b783974f0a64302a9ebc3f1574 | 16,580 | py | Python | engine/tests/test_form_team.py | ainterr/scoring_engine | d986eef08dcb819add20ed87d91239f887f62daa | [
"MIT"
] | null | null | null | engine/tests/test_form_team.py | ainterr/scoring_engine | d986eef08dcb819add20ed87d91239f887f62daa | [
"MIT"
] | 7 | 2016-02-24T21:01:22.000Z | 2017-01-04T03:22:44.000Z | engine/tests/test_form_team.py | ainterr/scoring_engine | d986eef08dcb819add20ed87d91239f887f62daa | [
"MIT"
] | 2 | 2016-03-04T17:04:48.000Z | 2020-01-30T21:03:49.000Z | from django.test import TransactionTestCase
from django.core.exceptions import ValidationError
from .. import models, forms
# TODO: IPv6 tests
import logging
logging.disable(logging.ERROR)
class TeamFormTests(TransactionTestCase):
form_class = forms.ModelFormFactory(models.Team)
def test_malformed_team_form(self):
"""Should not be able to submit a form for teams with malformed data"""
# Too little data
data = {}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'], ['This field is required.'])
data = {'name':'Team1'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'], ['This field is required.'])
data = {'subnet':'192.168.1.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'], ['This field is required.'])
data = {'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'], ['This field is required.'])
data = {'name':'Team1', 'subnet':'192.168.1.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['This field is required.'])
data = {'name':'Team1', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'], ['This field is required.'])
data = {'subnet':'192.168.1.0', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'], ['This field is required.'])
# Malformed arguments
## Name
data = {'name':'', 'subnet':'192.168.1.0', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team should not have a blank name.'])
data = {'name':None, 'subnet':'192.168.1.0', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team should not have a blank name.'])
data = {'name':'a'*21, 'subnet':'192.168.1.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['Ensure this value has at most 20 characters (it has 21).'])
## Subnet
data = {'name':'Team1', 'subnet':None, 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'blah', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.1688.1.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.-168.1.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.168.1', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'300.0.1.0', 'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
## Netmask
data = {'name':'Team1', 'subnet':'300.0.1.0', 'netmask':None}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.168.1.0', 'netmask':'what'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.168.1.0',
'netmask':'255.3255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.168.1.0',
'netmask':'255.255.-255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'192.168.1', 'netmask':'255.255.255'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
data = {'name':'Team1', 'subnet':'300.0.1.0', 'netmask':'255.450.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnet/netmask should be a valid IP network.'])
def test_team_same_names_form(self):
"""Teams with the same name are not allowed in form submissions"""
models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
data = {'name':'Team1', 'subnet':'192.168.2.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['Team with this Name already exists.'])
def test_team_overlapping_subnet_form(self):
"""Teams with overlapping subnets are not allowed in form submissions"""
models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
data = {'name':'Team2', 'subnet':'192.168.1.128',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnets should not overlap.'])
models.Team.objects.create(
name='Team3', subnet='192.168.2.128', netmask='255.255.255.0')
data = {'name':'Team4', 'subnet':'192.168.2.197',
'netmask':'255.255.255.128'}
form = self.form_class(data)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnets should not overlap.'])
def test_team_correct_form(self):
"""Correctly created teams should be allowed in form submissions"""
self.assertEqual(models.Team.objects.count(), 0)
data = {'name':'Team1', 'subnet':'192.168.1.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(models.Team.objects.count(), 1)
data = {'name':'Team2', 'subnet':'192.168.2.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(models.Team.objects.count(), 2)
# Smaller subnets
data = {'name':'Team3', 'subnet':'192.168.3.0',
'netmask':'255.255.255.128'}
form = self.form_class(data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(models.Team.objects.count(), 3)
data = {'type':'team', 'name':'Team4', 'subnet':'192.168.3.129',
'netmask':'255.255.255.128'}
form = self.form_class(data)
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(models.Team.objects.count(), 4)
def test_team_default_credentials_form(self):
"""New teams should be populated with default credentials
if they are available when team forms are submitted"""
# Creating a new team w/ no default creds set
self.assertEqual(models.Credential.objects.count(), 0)
data = {'name':'Team1', 'subnet':'192.168.1.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
form.save()
self.assertEqual(models.Credential.objects.count(), 0)
c = models.Credential.objects.create( # Default Credential w/o service
team=None, default=None, username='test', password='toor')
self.assertEqual(models.Credential.objects.count(), 2)
data = {'name':'Team2', 'subnet':'192.168.2.0',
'netmask':'255.255.255.0'}
form = self.form_class(data)
form.save()
self.assertEqual(models.Credential.objects.count(), 3)
def test_team_malformed_edit_form(self):
"""Team forms should raise an error when edited with malformed data"""
t = models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
data = {'name':'Team1', 'subnet':'192.168.1.0',
'netmask':'255.255.255.0'}
## Name
data['name'] = ''
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['This field is required.'])
data['name'] = None
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['This field is required.'])
data['name'] = 'a'*21
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['Ensure this value has at most 20 characters (it has 21).'])
## Subnet
data['name'] = 'Team1'
data['subnet'] = None
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['This field is required.'])
data['subnet'] = 'blah'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['Enter a valid IPv4 or IPv6 address.'])
data['subnet'] = '192.1688.1.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['Enter a valid IPv4 or IPv6 address.'])
data['subnet'] = '192.-168.1.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['Enter a valid IPv4 or IPv6 address.'])
data['subnet'] = '192.168.1'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['Enter a valid IPv4 or IPv6 address.'])
data['subnet'] = '300.0.1.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subnet'],
['Enter a valid IPv4 or IPv6 address.'])
## Netmask
data['subnet'] = '192.168.1.0'
data['netmask'] = None
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['This field is required.'])
data['netmask'] = 'what'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['Enter a valid IPv4 or IPv6 address.'])
data['netmask'] = '255.3255.255.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['Enter a valid IPv4 or IPv6 address.'])
data['netmask'] = '255.255.-255.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['Enter a valid IPv4 or IPv6 address.'])
data['netmask'] = '255.255.255'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['Enter a valid IPv4 or IPv6 address.'])
data['netmask'] = '255.450.255.0'
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['netmask'],
['Enter a valid IPv4 or IPv6 address.'])
def test_team_edit_same_name_form(self):
"""Teams with the same name are not allowed in form submissions,
when editing"""
models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
t = models.Team.objects.create(
name='Team2', subnet='192.168.2.0', netmask='255.255.255.0')
data = {'name':'Team1', 'subnet':'192.168.2.0',
'netmask':'255.255.255.0'}
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['name'],
['Team with this Name already exists.'])
def test_team_edit_overlapping_subnet_form(self):
"""Teams with overlapping subnets are not allowed in form submissions"""
models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
t = models.Team.objects.create(
name='Team2', subnet='192.168.2.0', netmask='255.255.255.0')
data = {'name':'Team2', 'subnet':'192.168.1.128',
'netmask':'255.255.255.0'}
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnets should not overlap.'])
models.Team.objects.create(
name='Team3', subnet='192.168.3.0', netmask='255.255.255.128')
t = models.Team.objects.create(
name='Team4', subnet='192.168.3.128', netmask='255.255.255.128')
data = {'name':'Team4', 'subnet':'192.168.3.128',
'netmask':'255.255.255.0'}
form = self.form_class(data, instance=t)
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['__all__'],
['Team subnets should not overlap.'])
def test_team_edit_form(self):
"""Fields should be properly updated when a team is edited in form
submissions"""
t = models.Team.objects.create(
name='Team1', subnet='192.168.1.0', netmask='255.255.255.0')
data = {'id':t.pk, 'type':'team', 'name':'Team2',
'subnet':'192.168.1.0', 'netmask':'255.255.255.0'}
form = self.form_class(data, instance=t)
self.assertTrue(form.is_valid())
form.save()
t = models.Team.objects.get(pk=t.pk) # Reload from DB
self.assertEqual(t.name, 'Team2')
data['subnet'] = '192.168.2.0'
form = self.form_class(data, instance=t)
self.assertTrue(form.is_valid())
form.save()
t = models.Team.objects.get(pk=t.pk) # Reload from DB
self.assertEqual(t.subnet, '192.168.2.0')
data['netmask'] = '255.255.255.128'
form = self.form_class(data, instance=t)
self.assertTrue(form.is_valid())
form.save()
t = models.Team.objects.get(pk=t.pk) # Reload from DB
self.assertEqual(t.netmask, '255.255.255.128')
| 40.938272 | 80 | 0.583776 | 2,115 | 16,580 | 4.477069 | 0.069504 | 0.054494 | 0.065899 | 0.093357 | 0.889429 | 0.882564 | 0.865139 | 0.855423 | 0.855423 | 0.852044 | 0 | 0.077209 | 0.252413 | 16,580 | 404 | 81 | 41.039604 | 0.686729 | 0.052774 | 0 | 0.75625 | 0 | 0 | 0.249904 | 0 | 0 | 0 | 0 | 0.002475 | 0.328125 | 1 | 0.028125 | false | 0.003125 | 0.0125 | 0 | 0.046875 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
76f2f1182459b0a477b6f92fdaf4e02d9ee74e22 | 134 | py | Python | tests/test_utils.py | DavisDmitry/pyCubes | f234b9d3df959401c96c9314d5fd319524c27763 | [
"MIT"
] | 8 | 2021-09-27T04:45:14.000Z | 2022-03-14T12:42:53.000Z | tests/test_utils.py | DavisDmitry/pyCubes | f234b9d3df959401c96c9314d5fd319524c27763 | [
"MIT"
] | 57 | 2021-10-08T07:08:31.000Z | 2022-03-04T07:30:07.000Z | tests/test_utils.py | DavisDmitry/pyCubes | f234b9d3df959401c96c9314d5fd319524c27763 | [
"MIT"
] | null | null | null | import uuid
from cubes import utils
def test_generate_uuid():
assert isinstance(utils.generate_uuid("_Smesharik_"), uuid.UUID)
| 16.75 | 68 | 0.776119 | 18 | 134 | 5.5 | 0.611111 | 0.242424 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.134328 | 134 | 7 | 69 | 19.142857 | 0.853448 | 0 | 0 | 0 | 1 | 0 | 0.08209 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0.25 | true | 0 | 0.5 | 0 | 0.75 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
76f49c50807bfffc35d1132f367a666d7b2c2cb3 | 4,121 | py | Python | uer/encoders/mixed_encoder.py | nju-websoft/TSQA | d0b3f0c3a5e55a46fc5d281cae09597aa7f76e2e | [
"Apache-2.0"
] | 12 | 2020-12-19T05:26:49.000Z | 2022-03-30T13:20:46.000Z | uer/encoders/mixed_encoder.py | nju-websoft/TSQA | d0b3f0c3a5e55a46fc5d281cae09597aa7f76e2e | [
"Apache-2.0"
] | null | null | null | uer/encoders/mixed_encoder.py | nju-websoft/TSQA | d0b3f0c3a5e55a46fc5d281cae09597aa7f76e2e | [
"Apache-2.0"
] | null | null | null | # -*- encoding:utf-8 -*-
import torch
import torch.nn as nn
class RcnnEncoder(nn.Module):
def __init__(self, args):
super(RcnnEncoder, self).__init__()
self.emb_size = args.emb_size
self.hidden_size= args.hidden_size
self.kernel_size = args.kernel_size
self.layers_num = args.layers_num
self.rnn = nn.LSTM(input_size=args.emb_size,
hidden_size=args.hidden_size,
num_layers=args.layers_num,
dropout=args.dropout,
batch_first=True)
self.drop = nn.Dropout(args.dropout)
self.conv_1 = nn.Conv2d(1, args.hidden_size, (args.kernel_size, args.emb_size))
self.conv = nn.ModuleList([nn.Conv2d(args.hidden_size, args.hidden_size, (args.kernel_size, 1)) \
for _ in range(args.layers_num-1)])
def forward(self, emb, seg):
batch_size, seq_len, _ = emb.size()
hidden = self.init_hidden(batch_size, emb.device)
output, hidden = self.rnn(emb, hidden)
output = self.drop(output)
padding = torch.zeros([batch_size, self.kernel_size-1, self.emb_size]).to(emb.device)
hidden = torch.cat([padding, output], dim=1).unsqueeze(1) # batch_size, 1, seq_length+width-1, emb_size
hidden = self.conv_1(hidden)
padding = torch.zeros([batch_size, self.hidden_size, self.kernel_size-1, 1]).to(emb.device)
hidden = torch.cat([padding, hidden], dim=2)
for i, conv_i in enumerate(self.conv):
hidden = conv_i(hidden)
hidden = torch.cat([padding, hidden], dim=2)
hidden = hidden[:,:,self.kernel_size-1:,:]
output = hidden.transpose(1,2).contiguous().view(batch_size, seq_len, self.hidden_size)
return output
def init_hidden(self, batch_size, device):
return (torch.zeros(self.layers_num, batch_size, self.hidden_size, device=device),
torch.zeros(self.layers_num, batch_size, self.hidden_size, device=device))
class CrnnEncoder(nn.Module):
def __init__(self, args):
super(CrnnEncoder, self).__init__()
self.emb_size = args.emb_size
self.hidden_size= args.hidden_size
self.kernel_size = args.kernel_size
self.layers_num = args.layers_num
self.conv_1 = nn.Conv2d(1, args.hidden_size, (args.kernel_size, args.emb_size))
self.conv = nn.ModuleList([nn.Conv2d(args.hidden_size, args.hidden_size, (args.kernel_size, 1)) \
for _ in range(args.layers_num-1)])
self.rnn = nn.LSTM(input_size=args.emb_size,
hidden_size=args.hidden_size,
num_layers=args.layers_num,
dropout=args.dropout,
batch_first=True)
self.drop = nn.Dropout(args.dropout)
def forward(self, emb, seg):
batch_size, seq_len, _ = emb.size()
padding = torch.zeros([batch_size, self.kernel_size-1, self.emb_size]).to(emb.device)
emb = torch.cat([padding, emb], dim=1).unsqueeze(1) # batch_size, 1, seq_length+width-1, emb_size
hidden = self.conv_1(emb)
padding = torch.zeros([batch_size, self.hidden_size, self.kernel_size-1, 1]).to(emb.device)
hidden = torch.cat([padding, hidden], dim=2)
for i, conv_i in enumerate(self.conv):
hidden = conv_i(hidden)
hidden = torch.cat([padding, hidden], dim=2)
hidden = hidden[:,:,self.kernel_size-1:,:]
output = hidden.transpose(1,2).contiguous().view(batch_size, seq_len, self.hidden_size)
hidden = self.init_hidden(batch_size, emb.device)
output, hidden = self.rnn(output, hidden)
output = self.drop(output)
return output
def init_hidden(self, batch_size, device):
return (torch.zeros(self.layers_num, batch_size, self.hidden_size, device=device),
torch.zeros(self.layers_num, batch_size, self.hidden_size, device=device))
| 42.484536 | 112 | 0.60859 | 546 | 4,121 | 4.369963 | 0.106227 | 0.092205 | 0.058676 | 0.060352 | 0.941744 | 0.91995 | 0.91995 | 0.887678 | 0.887678 | 0.887678 | 0 | 0.012974 | 0.270565 | 4,121 | 96 | 113 | 42.927083 | 0.780772 | 0.026693 | 0 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.083333 | false | 0 | 0.027778 | 0.027778 | 0.194444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
0a54582a99dfe2254359d69352b15d8f6fba36e3 | 181 | py | Python | TestDemo/test_zssq.py | mocne/handerCode | bd6f9c1c5ec9a2e8be79146748f19a430ba30074 | [
"MIT"
] | 1 | 2018-04-21T13:54:56.000Z | 2018-04-21T13:54:56.000Z | TestDemo/test_zssq.py | mocne/handerCode | bd6f9c1c5ec9a2e8be79146748f19a430ba30074 | [
"MIT"
] | null | null | null | TestDemo/test_zssq.py | mocne/handerCode | bd6f9c1c5ec9a2e8be79146748f19a430ba30074 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import DriverInit.initAppiumDriver
DriverInit.initAppiumDriver.initAppiumWithInfo('com.ushaqi.zhuishushenqi', 'com.ushaqi.zhuishushenqi.ui.SplashActivity') | 36.2 | 120 | 0.80663 | 17 | 181 | 8.588235 | 0.705882 | 0.356164 | 0.30137 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005848 | 0.055249 | 181 | 5 | 120 | 36.2 | 0.847953 | 0.116022 | 0 | 0 | 0 | 0 | 0.415094 | 0.415094 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.