text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:2] <= 1)

                     @variable(m, -3.3773826343471955 <= q <= 0.8255956851677421)

                     add_NL_constraint(m, :((-0.5817410001457377 + -0.38051045291676777*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.828517562717189*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.13996198025628548*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))))/(1 + exp(-(-0.5817410001457377 + -0.38051045291676777*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.828517562717189*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.13996198025628548*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))))))) + (-0.08252400134510385 + 0.3442818429504264*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.7813134096358496*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.5888247957791601*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))))/(1 + exp(-(-0.08252400134510385 + 0.3442818429504264*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.7813134096358496*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.5888247957791601*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))))))) + (-0.2140493400207517 + 0.6401317985056014*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.4453350709432602*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + 0.9148591417614278*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))))/(1 + exp(-(-0.2140493400207517 + 0.6401317985056014*(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.7752766980375418 + 0.20887750352529233*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + -0.43558326218422394*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + -0.5061279411570236*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + -0.4453350709432602*(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(-0.31567568822764036 + 0.26872838410166544*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.5533650825489542*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.11778701597368801*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))))))) + 0.9148591417614278*(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))/(1 + exp(-(0.6085123540494801 + -0.012952465394535206*(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2]))/(1 + exp(-(0.3913052313874794 + -0.22863414084682043*$(x[1]) + 0.3783772947965627*$(x[2])))) + 0.6228552648202648*(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2]))/(1 + exp(-(-0.4746875961429966 + 0.3096610657098613*$(x[1]) + -0.16020248217350597*$(x[2])))) + 0.7276708970518393*(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2]))/(1 + exp(-(0.7539608271466713 + -0.29418097465562054*$(x[1]) + -0.3042211456088699*$(x[2])))))))))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
"Simulation controls"
global NUMBER_OF_WALKS = 100
global MAX_STEPS_PER_WALK = Int(floor(20 * 60 / 0.0000027))
# twenty minutes in experiment

"Solvent Diffusion Step Sizes (microns per 2.7 microseconds)"
STEP_SIZE_DICT = Dict("water" => 0.1, "enz" => 0.005, "ppd" => 0.001)
const WATER_STEP_SIZE = 0.1
const ENZ_STEP_SIZE = 0.005
const PPD_STEP_SIZE = 0.001

"Sensor/Walls Coordinates"
const WALL_Y = 0.0
const SENSOR_WIDTH = 25.0
const SENSOR_SPACING = 25.0
const SENSOR_SPAWN_LEFT_X = 0.0
const SENSOR_SPAWN_RIGHT_X = SENSOR_SPAWN_LEFT_X + SENSOR_WIDTH
const SENSOR_SECOND_LEFT_X = SENSOR_SPAWN_RIGHT_X + SENSOR_SPACING
const SENSOR_SECOND_RIGHT_X = SENSOR_SECOND_LEFT_X + SENSOR_WIDTH
const SENSOR_THIRD_LEFT_X = SENSOR_SECOND_RIGHT_X + SENSOR_SPACING
const SENSOR_THIRD_RIGHT_X = SENSOR_THIRD_LEFT_X + SENSOR_WIDTH
const SENSOR_FOURTH_LEFT_X = SENSOR_THIRD_RIGHT_X + SENSOR_SPACING
const SENSOR_FOURTH_RIGHT_X = SENSOR_FOURTH_LEFT_X + SENSOR_WIDTH

"PPD Layer Dimensions (for spawn)"
const PPD_MAX_Y = 0.15
const PPD_MIN_Y = 0.0
const PPD_LEFT_X = 0.0
const PPD_RIGHT_X = 25.0

"Enzyme Layer Dimensions (for spawn, other sensors are standardized)"
const ENZYME_MAX_Y = 3.0
const ENZYME_SPACING = 21.0
const ENZYME_WIDTH = 29.0
const ENZYME_LEFT_X = -2.0
const ENZYME_RIGHT_X = ENZYME_LEFT_X + ENZYME_WIDTH
const ZONE_ONE_RIGHT_X = ENZYME_RIGHT_X + 0.5 * ENZYME_SPACING
const ZONE_TWO_RIGHT_X = ZONE_ONE_RIGHT_X + ENZYME_SPACING + ENZYME_WIDTH
const ZONE_THREE_RIGHT_X = ZONE_TWO_RIGHT_X + ENZYME_SPACING + ENZYME_WIDTH

"Spawn inside main enzyme layer"
const BORDER_CORRECTION = 0.001
const SPAWN_LEFT_X = ENZYME_LEFT_X + BORDER_CORRECTION
const SPAWN_RIGHT_X = ENZYME_RIGHT_X - BORDER_CORRECTION
const SPAWN_ENZYME_MAX_Y = ENZYME_MAX_Y - BORDER_CORRECTION
const SPAWN_LENGTH = SPAWN_RIGHT_X - SPAWN_LEFT_X + 2 * SPAWN_ENZYME_MAX_Y

"Enzyme-Water Corners"
const CORNER_CUT_IN_ENZ = ENZ_STEP_SIZE * sqrt(2) / 2
const CORNER_CUT_IN_WATER = WATER_STEP_SIZE * sqrt(2) / 2
# test set: locationbools here
const WATER_TO_ENZ_NORTHEAST = [ENZYME_RIGHT_X - CORNER_CUT_IN_ENZ, ENZYME_MAX_Y - CORNER_CUT_IN_ENZ]
const WATER_TO_ENZ_NORTHWEST = [ENZYME_LEFT_X + CORNER_CUT_IN_ENZ, ENZYME_MAX_Y - CORNER_CUT_IN_ENZ]
const ENZ_TO_WATER_NORTHEAST = [ENZYME_RIGHT_X + CORNER_CUT_IN_WATER, ENZYME_MAX_Y + CORNER_CUT_IN_WATER]
const ENZ_TO_WATER_NORTHWEST = [ENZYME_LEFT_X - CORNER_CUT_IN_WATER, ENZYME_MAX_Y + CORNER_CUT_IN_WATER]

"PPD-Enzyme Corners"
const CORNER_CUT_IN_PPD = PPD_STEP_SIZE * sqrt(2) / 2
const ENZ_TO_PPD_NORTHEAST = [PPD_RIGHT_X - CORNER_CUT_IN_PPD, PPD_MAX_Y - CORNER_CUT_IN_PPD]
const ENZ_TO_PPD_NORTHWEST = [PPD_LEFT_X + CORNER_CUT_IN_PPD, PPD_MAX_Y - CORNER_CUT_IN_PPD]
const PPD_TO_ENZ_NORTHEAST = [PPD_RIGHT_X + CORNER_CUT_IN_ENZ, PPD_MAX_Y + CORNER_CUT_IN_ENZ]
const PPD_TO_ENZ_NORTHWEST = [PPD_LEFT_X - CORNER_CUT_IN_ENZ, PPD_MAX_Y + CORNER_CUT_IN_ENZ]

"Escape Bound Limits"
const ESCAPE_X = 4 * SENSOR_WIDTH + 4 * SENSOR_SPACING
const ESCAPE_Y = ESCAPE_X

"Safe Bound Limits"
const MARGIN_OF_COLLISION = 2 * WATER_STEP_SIZE
const SAFE_MIN_Y = ENZYME_MAX_Y + MARGIN_OF_COLLISION
const SAFE_MAX_Y = ESCAPE_Y - MARGIN_OF_COLLISION
const SAFE_MAX_X = ESCAPE_X - MARGIN_OF_COLLISION

ext: jl

max_stars_repo_name: s-y-wu/HMCResearchRandomWalks

max_issues_repo_name: s-y-wu/HMCResearchRandomWalks

max_forks_repo_name: s-y-wu/HMCResearchRandomWalks


text:
#=

# 106: 1D Nonlinear Diffusion equation
([source code](SOURCE_URL))

Solve the nonlinear diffusion equation

```math
\partial_t u -\Delta u^m = 0
```
in $\Omega=(-1,1)$ with homogeneous Neumann boundary condtions using the implicit Euler method.

This equation is also called  "porous medium equation".
The Barenblatt solution is an exact solution of this problem which for m>1 has a finite support.
We initialize this problem with the exact solution for $t=t_0=0.001$.

(see Barenblatt, G. I. "On nonsteady motions of gas and fluid in porous medium." Appl. Math. and Mech.(PMM) 16.1 (1952): 67-78.)
=#

module Example106_NonlinearDiffusion1D
using Printf
using VoronoiFVM
using ExtendableGrids
using GridVisualize

function barenblatt(x,t,m)
    tx=t^(-1.0/(m+1.0))
    xx=x*tx
    xx=xx*xx
    xx=1- xx*(m-1)/(2.0*m*(m+1));
    if xx<0.0
        xx=0.0
    end
    return tx*xx^(1.0/(m-1.0))
end

function main(;n=20,m=2,Plotter=nothing,verbose=false, unknown_storage=:sparse,tend=0.01,tstep=0.0001,DiffEq=nothing)

    ## Create a one-dimensional discretization
    h=1.0/convert(Float64,n/2)
    X=collect(-1:h:1)
    grid=VoronoiFVM.Grid(X)

    ## Flux function which describes the flux
    ## between neigboring control volumes
    function flux!(f,u0,edge)
        u=unknowns(edge,u0)
        f[1]=u[1,1]^m-u[1,2]^m
    end

    ## Storage term
    function storage!(f,u,node)
        f[1]=u[1]
    end

    ## Create a physics structure
    physics=VoronoiFVM.Physics(
        flux=flux!,
        storage=storage!)

    ## Create a finite volume system - either
    ## in the dense or  the sparse version.
    ## The difference is in the way the solution object
    ## is stored - as dense or as sparse matrix
    sys=VoronoiFVM.System(grid,physics,unknown_storage=unknown_storage)

    ## Add species 1 to region 1
    enable_species!(sys,1,[1])

    ## Create a solution array
    inival=unknowns(sys)
    t0=0.001

    ## Broadcast the initial value
    inival[1,:].=map(x->barenblatt(x,t0,m),X)

    ## Create solver control info for constant time step size
    control=VoronoiFVM.NewtonControl()
    control.verbose=verbose
    control.Δt_min=tstep
    control.Δt_max=tstep
    control.Δt=tstep
    control.Δu_opt=1

    if isnothing(DiffEq)
        tsol=solve(inival,sys,[t0,tend],control=control)
    else
        tsol=solve(DiffEq,inival,sys,[t0,tend])
    end

    p=GridVisualizer(Plotter=Plotter,layout=(2,1),fast=true)
    for i=1:length(tsol)
        time=tsol.t[i]
        scalarplot!(p[1,1],grid,tsol[1,:,i],title=@sprintf("numerical, t=%.3g",time))
        scalarplot!(p[2,1],grid,map(x->barenblatt(x,time,m),grid),title=@sprintf("exact, t=%.3g",time))
        reveal(p)
    end
    return sum(tsol[end])
end

function test()
    testval=46.66666666647518
    main(unknown_storage=:sparse) ≈ testval && main(unknown_storage=:dense) ≈ testval
end

end


text:
function Well44497b()
    return Well44497b(())
end

function Well44497b(arg0::Vector{jint})
    return Well44497b((Vector{jint},), arg0)
end

function Well44497b(arg0::jint)
    return Well44497b((jint,), arg0)
end

function Well44497b(arg0::jlong)
    return Well44497b((jlong,), arg0)
end

function next_int(obj::Well44497b)
    return jcall(obj, "nextInt", jint, ())
end


text:
const f32 = UInt32(0) # 32-bit floating point values
const c32 = UInt32(1) # 32-bit complex floating point values
const f64 = UInt32(2) # 64-bit complex floating point values
const c64 = UInt32(3) # 64-bit complex floating point values
const b8  = UInt32(4) #  8-bit boolean values
const s32 = UInt32(5) # 32-bit signed integral values
const u32 = UInt32(6) # 32-bit unsigned integral values
const u8  = UInt32(7) #  8-bit unsigned integral values
const s64 = UInt32(8) # 64-bit signed integral values
const u64 = UInt32(9) # 64-bit unsigned integral values

aftype(::Type{Float32})          = f32
aftype(::Type{Complex{Float32}}) = c32
aftype(::Type{Float64})          = f64
aftype(::Type{Complex{Float64}}) = c64
aftype(::Type{Bool})             = b8
aftype(::Type{Int32})            = s32
aftype(::Type{UInt32})           = u32
aftype(::Type{UInt8})            = u8
aftype(::Type{Int64})            = s64
aftype(::Type{UInt64})           = u64

function jltype(af_dtype)
    if af_dtype == f32
        return Float32
    elseif af_dtype == c32
        return Complex{Float32}
    elseif af_dtype == f64
        return Float64
    elseif af_dtype == c64
        return Complex{Float64}
    elseif af_dtype == b8
        return Bool
    elseif af_dtype == s32
        return Int32
    elseif af_dtype == u32
        return UInt32
    elseif af_dtype == u8
        return UInt8
    elseif af_dtype == s64
        return Int64
    elseif af_dtype == u64
        return UInt64
    end
end

function af_promote{T,S}(::Type{T},::Type{S})
    if T == S
        return T
    elseif T == Complex{Float64} || S == Complex{Float64}
        return Complex{Float64}
    elseif T == Complex{Float32} || S == Complex{Float32}
        (T == Float64 || S == Float64) && return Complex{Float64}
        return Complex{Float32}
    elseif T == Float64 || S == Float64
        return Float64
    elseif T == Float32 || S == Float32
        return Float32
    elseif T == UInt64 || S == UInt64
        return UInt64
    elseif T == Int64 || S == Int64
        return Int64
    elseif T == UInt32 || S == UInt32
        return UInt32
    elseif T == Int32 || S == Int32
        return Int32
    elseif T == UInt8 || S == UInt8
        return UInt8
    elseif T == Bool || S == Bool
        return Bool
    else
        return Float32
    end
end

typealias dim Int
#=typealias dim4 Union{Tuple{dim}, Tuple{dim,dim}, Tuple{dim,dim,dim}, Tuple{dim,dim,dim,dim}}

function dims_to_dim4(dims)
	if length(dims) == 1
        (dims[1],)
    elseif length(dims) == 2
        (dims[1], dims[2])
    elseif length(dims) == 3
        (dims[1], dims[2], dims[3])
    elseif length(dims) == 4
        (dims[1], dims[2], dims[3], dims[4])
    else
        throw(ArgumentError("Too many dimensions"))
    end
end=#


text:
using DiscreteChoice
using JLD2
using ForwardDiff
using Optim

@load "example/data/homo.jld2" Y X β ξ
@load "example/data/hetero.jld2" Y X β_mean ξ σ

@code_warntype llk_sample(Y, X, β, ξ)

ccp(Y,X)

llk_sample(Y::Vector, X::Matrix, β_mean::Vector, ξ::Vector, σ::Vector; n_sim = 100)

res_homo = opt_homo(Y, X, vcat(β, ξ))
res_hetero = opt_hetero(Y, X, vcat(β_mean, ξ, σ); n_sim=5)

Optim.minimizer(res_homo) .- vcat(β, ξ)
Optim.minimizer(res_hetero) .- vcat(β_mean, ξ, σ)

f = para -> -llk_sample(Y, X, para[1:K], para[K+1:end]) # take negative to minimize
g = TwiceDifferentiable(f, init_guess; autodiff=:forward)

K = 5
J = 10
f_try = para -> -llk_sample(Y, X, para[1:K], para[K+1:K+J-1], para[K+J:end]; n_sim=100)
ForwardDiff.gradient(f_try, vcat(β_mean, ξ, σ))


text:
@testset "Stream" begin
    @testset "AbstractStream" begin
        elements = 10
        df = DataFrame(x = [1:elements ...], y = [1:elements ...])
        conn = EasyStream.TablesConnector(df)
        stream = EasyStream.BatchStream(conn)
        qnt_loops = 0
        for data in stream
            qnt_loops = qnt_loops + 1
        end

        EasyStream.reset!(stream)

        qnt_loops_reset = 0
        for data in stream
            qnt_loops_reset = qnt_loops_reset + 1
        end

        @test qnt_loops == qnt_loops_reset
    end

    @testset "BatchStream" begin
        elements = 100
        df = DataFrame(x = [1:elements ...], y = [1:elements ...])
        conn = EasyStream.TablesConnector(df)

        batch = 10
        stream = EasyStream.BatchStream(conn, batch = batch)
        data = EasyStream.listen(stream)
        @test size(data)[1] == batch
        @test size(data)[2] == size(df)[2]

        elements = 5
        df = DataFrame(x = [1:elements ...], y = [1:elements ...])
        conn = EasyStream.TablesConnector(df)

        batch = 10
        stream = EasyStream.BatchStream(conn, batch = batch)
        data = EasyStream.listen(stream)
        @test size(data)[1] < batch
        @test size(data)[2] == size(df)[2]
        @test size(data)[1] == elements

        elements = 5
        df = DataFrame(x = [1:elements ...], y = [1:elements ...])
        conn = EasyStream.TablesConnector(df)

        stream = EasyStream.BatchStream(conn)
        i = 0
        for data in stream
            @test size(data)[1] == 1
            @test size(data)[2] == size(df)[2]
            i = i + 1
        end

        elements = 100
        df = DataFrame(x = [1:elements ...], y = [1:elements ...])
        conn = EasyStream.TablesConnector(df)

        batch = 100

        stream = EasyStream.BatchStream(conn, batch = batch)
        i = 0
        for data in stream
            @test size(data)[1] == batch
            @test size(data)[2] == size(df)[2]
            i = i + 1
        end

        @test i == Int(elements ./ batch)
    end

end


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "argp_standalone"
version = v"1.3.0"

# Collection of sources required to build argp-standalone
sources = [
    ArchiveSource("http://www.lysator.liu.se/~nisse/misc/argp-standalone-$(version.major).$(version.minor).tar.gz",
                  "dec79694da1319acd2238ce95df57f3680fea2482096e483323fddf3d818d8be"),
    FileSource("https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt", "8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643"; filename="LICENSE"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/argp-*/
CFLAGS="-fPIC" ./configure --prefix=${prefix} --build=${MACHTYPE} --host=${target}
make -j${nproc}
install_license $WORKSPACE/srcdir/LICENSE
install -D -m644 argp.h ${includedir}/argp.h
install -D -m755 libargp.a ${libdir}/libargp.a
"""

# Select Unix platforms
platforms = [p for p in supported_platforms() if Sys.islinux(p) && libc(p) == "musl"]

# The products that we will ensure are always built
products = [
    FileProduct("lib/libargp.a", :libargp),
    FileProduct("include/argp.h", :argp_h),
]

# Dependencies that must be installed before this package can be built
dependencies = Dependency[
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)

max_stars_repo_name: waralex/Yggdrasil

max_issues_repo_name: waralex/Yggdrasil

max_forks_repo_name: waralex/Yggdrasil


text:
using ..BasisDefinition, ..DynamicDefinition, ..Contractors, ..Mod1DynamicDefinition, ..PwDynamicDefinition
using ValidatedNumerics, LinearAlgebra
import Base: iterate
import ..BasisDefinition: one_vector, integral_covector, is_integral_preserving, strong_norm, weak_norm, aux_norm

"""
Equispaced Ulam basis on [0,1] of size n
"""
struct Ulam{T<:AbstractVector} <:Basis
	p::T
	# TODO: check in constructor that p is sorted, starts with 0 and ends with 1
end

Ulam(n::Integer) = Ulam(LinRange(0., 1., n+1))
Base.length(B::Ulam) = length(B.p) - 1

function BasisDefinition.is_dual_element_empty(::Ulam, d)
	return isempty(d[1])
end

Base.length(S::DualComposedWithDynamic{<:Ulam, <:Dynamic}) = length(S.basis) * nbranches(S.dynamic)

"""
Returns dual elements which are pairs (i, (a,b))
i is an interval index, and (a,b) are the endpoints of its preimage
"""
function Base.iterate(S::DualComposedWithDynamic{<:Ulam, <:Dynamic}, state = (1, 1, nothing))
	# a = preim(S.dynamic, k, S.basis.p[i], S.ϵ) is cached in the state (when i \neq 1)
	i, k, a = state

	if k == nbranches(S.dynamic)+1
		return nothing
	end

	if a == nothing
		@assert i==1
		a = preim(S.dynamic, k, S.basis.p[i], S.ϵ)
	end

	# a = preim(S.dynamic, k, S.basis.p[i], S.ϵ) # moved into state
	b = preim(S.dynamic, k, S.basis.p[i+1], S.ϵ)

	if isempty(a) && !isempty(b)
		ep = endpoints(S.dynamic)
		if orientation(S.dynamic, k) > 0
			a = convert(typeof(b), ep[k])
		else
			a = convert(typeof(b), ep[k+1])
		end
	elseif isempty(b) && !isempty(a)
		ep = endpoints(S.dynamic)
		if orientation(S.dynamic, k) > 0
			b = convert(typeof(a), ep[k+1])
		else
			b = convert(typeof(a), ep[k])
		end
	end

	if i == length(S.basis)
		return ((i, (a, b)), (1, k+1, nothing))
	else
		return ((i, (a, b)), (i+1, k, b))
	end
end

Base.eltype(f::DualComposedWithDynamic{<:Ulam, <:Dynamic}) = Tuple{Int64,Tuple{Interval{Float64},Interval{Float64}}}

"""
Returns the indices of the elements of the Ulam basis that intersect with the interval y
We do not assume an order of a and b; this should not matter unless
the preimages are computed with very low accuracy
We assume, though, that y comes from the (possibly inexact) numerical approximation
of an interval in [0,1], i.e., we restrict to y ∩ [0,1]
"""
function BasisDefinition.nonzero_on(B::Ulam, (a, b))
	y = hull(a, b)

	# finds in which semi-open interval [p[k], p[k+1]) y.lo and y.hi fall
	lo = searchsortedlast(B.p, y.lo)
	hi = searchsortedlast(B.p, y.hi)

	# they may be n+1 if y.hi==1
	lo = clamp(lo, 1, length(B))
	hi = clamp(hi, 1, length(B))

	return (lo, hi)
end

"""
Relative measure of the intersection of (a,b) wrt the whole interval (c,d)
Assumes that a,b and c,d are sorted correctly
"""
function relative_measure((a,b)::Tuple{<:Interval,<:Interval}, (c,d)::Tuple{<:Interval,<:Interval})
	# this is a bit lazy because we could compute orientations and tell which is which
	# but it won't matter unless a,b are computed with very low precision
	a, b = min(a,b), max(a,b)

	lower = max(a, c)
	upper = min(b, d)
	intersection = max(upper - lower, 0) / (d-c)
	return intersection
end

"""
Given a preimage of an interval ```I_i```, this iterator returns
its relative intersection with all the elements of the Ulam basis that
have nonzero intersection with it
"""
function Base.iterate(S::ProjectDualElement{BT,DT}, state = S.j_min) where {BT<:Ulam,DT}
	if state == S.j_max+1
		return nothing
	end
	j = state
	x = relative_measure(S.dual_element,
			(Interval(S.basis.p[j]),
			Interval(S.basis.p[j+1])))
	return (j, x), state+1
end
Base.eltype(f::ProjectDualElement{<:Ulam, DT}) where{DT} = Tuple{Int64,Interval{Float64}}

BasisDefinition.evaluate(B::Ulam{T}, i, x) where {T} = (x>(i-1)/n) && (x<i/n) ? 1 : 0

BasisDefinition.evaluate_integral(B::Ulam{S}, i, T::Type) where{S} = T(i)/length(B)

function Base.iterate(S::AverageZero{Ulam{T}}, state = 1) where{T}
	n = length(S.basis)
	if state == n
		return nothing
	end
	v = zeros(Float64, n)
	v[1] = 1
	v[state+1]=-1
	return (v, state+1)
end

BasisDefinition.is_refinement(Bf::Ulam, Bc::Ulam) = Bc.p ⊆ Bf.p

function integral_covector(B::Ulam{T}) where{T}
	n = length(B)
	return 1/n * ones(Interval{Float64}, n)'
end

is_integral_preserving(B::Ulam{T}) where {T} = true

function one_vector(B::Ulam)
	return ones(length(B))
end

BasisDefinition.strong_norm(B::Ulam) = TotalVariation
BasisDefinition.weak_norm(B::Ulam) = L1
BasisDefinition.aux_norm(B::Ulam) = L1

# See BasisDefinition for docs on these constants
# These must be rounded up correctly!

BasisDefinition.weak_projection_error(B::Ulam) = 0.5 ⊘₊ Float64(length(B), RoundDown)
BasisDefinition.aux_normalized_projection_error(B::Ulam) = 0.
BasisDefinition.strong_weak_bound(B::Ulam) = Float64(length(B), RoundUp)
BasisDefinition.aux_weak_bound(B::Ulam) = 1.
BasisDefinition.weak_by_strong_and_aux_bound(B::Ulam) = (0., 1.)
BasisDefinition.bound_weak_norm_from_linalg_norm(B::Ulam) = (1., 0.)
BasisDefinition.bound_linalg_norm_L1_from_weak(B::Ulam) = 1.
BasisDefinition.bound_linalg_norm_L∞_from_weak(B::Ulam) = Float64(length(B), RoundUp)
BasisDefinition.bound_weak_norm_abstract(B::Ulam) = 1.

function BasisDefinition.invariant_measure_strong_norm_bound(B::Ulam, D::Dynamic)
	A, B = dfly(strong_norm(B), aux_norm(B), D)
	@assert A < 1.
	return B ⊘₊ (1. ⊖₋ A)
end

using RecipesBase
using LaTeXStrings

"""
Plots a function in the Ulam basis
"""
@recipe function f(B::Ulam, w::AbstractVector)

	legend --> :bottomright

	if eltype(w) <: Interval
		w = mid.(w)
	end

	@series begin
		seriestype --> :steppost
		label --> L"f_{\delta}"
		ylims --> (0, NaN)
		B.p, vcat(w, w[end])
	end
end

"""
Displays error on a function in the Ulam basis

The w argument is unused, but kept for compatibility with other functions
for different bases
"""
@recipe function f(B::Ulam, error::Number, w=nothing)

	if isfinite(error)
		@series begin
			seriestype --> :path
			seriesalpha --> 0.5
			fillrange --> 0
			label --> "L1 Error"
			[0; sqrt(error)], [sqrt(error); sqrt(error)]
		end
	end
end


text:
## Exercise 7-3
## The built-in function Meta.parse takes a string and transforms it into an expression. This expression can be evaluated in Julia with the function Core.eval. For example:

## julia> expr = Meta.parse("1+2*3")
## :(1 + 2 * 3)
## julia> eval(expr)
## 7
## julia> expr = Meta.parse("sqrt(π)")
## :(sqrt(π))
## julia> eval(expr)
## 1.7724538509055159

## Write a function called evalloop that iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters done, and then return the value of the last expression it evaluated.
println("Ans: ")

function evalloop()
    while true
        print("eval>> ")
        expr = readline()
        if lowercase(expr) == "done"
            break
        end
        expr = Meta.parse(expr)
        println(eval(expr))
    end
end

evalloop()

println("End.")


text:
# Sparsification sketch of a matrix
#
# Danny Perry (dperry@cs.utah.edu)
# April 2015
#

using Debug

# Random sparsification that preserves eigen spectrum of A
# Theorem 1 from Achlioptas, "Fast computation of low rank matrix approximations", STOC 2001
# http://web.stanford.edu/class/ee378b/papers/achlioptas.pdf
#
# A - matrix to sparsify
# sparsity - controls amount sparsity, 1 <= s <= (m+n)/(log(m+n)^6)
#            sparse terms will be chosen w.p. (1-1/s)
#
function RandomSparsify(A, sparsity)
	n = size(A,1)
	d = size(A,2)
	s = sparsity

	entries = n*d
	I = zeros(Int32,int(.5*entries))
	J = zeros(Int32,int(.5*entries))
	V = zeros(typeof(A[1,1]), int(.5*entries))
	k = int(0)

	for i=1:n
		for j=1:d
			if rand() < 1.0/s
				#B[i,j] = s * A[i,j]
				k += 1
				if k > size(I,1)
					append!(I, zeros(typeof(I[1]),int(.25*size(I,1))))
					append!(J, zeros(typeof(J[1]),int(.25*size(J,1))))
					append!(V, zeros(typeof(V[1]),int(.25*size(V,1))))
				end
				I[k] = i
				J[k] = j
				V[k] = s*A[i,j]
			#else
			# B[i,j] = 0  # implied via sparse matrix
			end
		end
	end
	println("sparse k: ", k)

	I = I[1:k]
	J = J[1:k]
	V = V[1:k]

	B = sparse(I,J,V,n,d)
end

# Random sparsification that preserves eigen spectrum of A
# Theorem 2 from Achlioptas, "Fast computation of low rank matrix approximations", STOC 2001
# http://web.stanford.edu/class/ee378b/papers/achlioptas.pdf
#
# A - matrix to sparsify
#
# returns sparse binary matrix B with non-zero entries = 2,
# however estimates should use matrix  b*(B .- 1), so that each
# entry is either +b or -b.
#
# returns B,b
function RandomRoundSparsify(A)
	n = size(A,1)
	d = size(A,2)

	entries = n*d
	I = zeros(Int32,int(.5*entries))
	J = zeros(Int32,int(.5*entries))
	V = zeros(typeof(A[1,1]), int(.5*entries))
	k = int(0)

	b = maximum(abs(A))
	for i=1:n
		for j=1:d
			p = .5 + A[i,j] / (2*b)
			if rand() < p
				#B[i,j] = 2
				k += 1
				if k > size(I,1)
					append!(I, zeros(typeof(I[1]),int(.25*size(I,1))))
					append!(J, zeros(typeof(J[1]),int(.25*size(J,1))))
					append!(V, zeros(typeof(V[1]),int(.25*size(V,1))))
				end
				I[k] = i
				J[k] = j
				V[k] = 2

			#else
			# B[i,j] = 0  # implied via sparse matrix
			end
		end
	end

	I = I[1:k]
	J = J[1:k]
	V = V[1:k]

	B = sparse(I,J,V,n,d)
	B,b
end


text:
@testset "block utils" begin
    blocks = """
        ABC
        @@c1,c2 DEF@@
        GHI
        """ |> md_blockifier
    div = blocks[1]
    @test typeof(div) == FP.Block
    @test div.name == :DIV
    @test FP.get_classes(div) == "c1 c2"
end

@testset "prepare text" begin
    p = raw"""
        \ \# \@ \` \{ \} \* \_
        Hello
        """ |> FP.md_partition
    s = FP.prepare_text(p[1])
    @test s isa String
    @test isapproxstr(s, """
        \ # @ ` { } * _
        Hello
        """)
    p = raw"""
        *
         ----
        \\
        """ |> FP.md_partition

    @test eltype(p) == FP.Block
    @test p[1].name == :TEXT
    @test p[2].name == :HRULE
    @test p[3].name == :TEXT
    @test p[4].name == :LINEBREAK
    @test p[5].name == :P_BREAK

    # # no clash with tables
    # p = raw"""
    # | x   | y   |
    # | --- | --- |
    # | 0 | 1 |
    # """ |> FP.md_partition
    # @test p[1].name == :TEXT
    # @test length(p) == 1

    t = raw"""
        abc \\
          --------
        <
        """ |> FP.md_partition
    @test t[1].name == :TEXT
    @test t[2].name == :LINEBREAK
    @test t[3].name == :HRULE
    @test FP.prepare_text(t[4]) == "\n<"

    # emoji
    p = raw"""
        A :ghost: and :smile: but :foo:
        """ |> FP.md_partition
    @test FP.prepare_text(p[1]) // "A 👻 and 😄 but :foo:"
end

@testset "preptext2" begin
    s = raw"abc \{ *"
    b = s |> FP.md_partition |> first
    r = FP.prepare_text(b)
    @test r // "abc { *"
    r = FP.prepare_text(b; tohtml=false)
    @test r // "abc \\{ \\*"
end


text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: polly
using AWS.Compat
using AWS.UUIDs

"""
    delete_lexicon(lexicon_name)
    delete_lexicon(lexicon_name, params::Dict{String,<:Any})

Deletes the specified pronunciation lexicon stored in an AWS Region. A lexicon which has
been deleted is not available for speech synthesis, nor is it possible to retrieve it using
either the GetLexicon or ListLexicon APIs. For more information, see Managing Lexicons.

# Arguments
- `lexicon_name`: The name of the lexicon to delete. Must be an existing lexicon in the
  region.

"""
delete_lexicon(LexiconName; aws_config::AbstractAWSConfig=global_aws_config()) = polly("DELETE", "/v1/lexicons/$(LexiconName)"; aws_config=aws_config)
delete_lexicon(LexiconName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("DELETE", "/v1/lexicons/$(LexiconName)", params; aws_config=aws_config)

"""
    describe_voices()
    describe_voices(params::Dict{String,<:Any})

Returns the list of voices that are available for use when requesting speech synthesis.
Each voice speaks a specified language, is either male or female, and is identified by an
ID, which is the ASCII version of the voice name.  When synthesizing speech (
SynthesizeSpeech ), you provide the voice ID for the voice you want from the list of voices
returned by DescribeVoices. For example, you want your news reader application to read news
in a specific language, but giving a user the option to choose the voice. Using the
DescribeVoices operation you can provide the user with a list of available voices to select
from.  You can optionally specify a language code to filter the available voices. For
example, if you specify en-US, the operation returns a list of all available US English
voices.  This operation requires permissions to perform the polly:DescribeVoices action.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Engine"`: Specifies the engine (standard or neural) used by Amazon Polly when
  processing input text for speech synthesis.
- `"IncludeAdditionalLanguageCodes"`: Boolean value indicating whether to return any
  bilingual voices that use the specified language as an additional language. For instance,
  if you request all languages that use US English (es-US), and there is an Italian voice
  that speaks both Italian (it-IT) and US English, that voice will be included if you specify
  yes but not if you specify no.
- `"LanguageCode"`:  The language identification tag (ISO 639 code for the language
  name-ISO 3166 country code) for filtering the list of voices returned. If you don't specify
  this optional parameter, all available voices are returned.
- `"NextToken"`: An opaque pagination token returned from the previous DescribeVoices
  operation. If present, this indicates where to continue the listing.
"""
describe_voices(; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/voices"; aws_config=aws_config)
describe_voices(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/voices", params; aws_config=aws_config)

"""
    get_lexicon(lexicon_name)
    get_lexicon(lexicon_name, params::Dict{String,<:Any})

Returns the content of the specified pronunciation lexicon stored in an AWS Region. For
more information, see Managing Lexicons.

# Arguments
- `lexicon_name`: Name of the lexicon.

"""
get_lexicon(LexiconName; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/lexicons/$(LexiconName)"; aws_config=aws_config)
get_lexicon(LexiconName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/lexicons/$(LexiconName)", params; aws_config=aws_config)

"""
    get_speech_synthesis_task(task_id)
    get_speech_synthesis_task(task_id, params::Dict{String,<:Any})

Retrieves a specific SpeechSynthesisTask object based on its TaskID. This object contains
information about the given speech synthesis task, including the status of the task, and a
link to the S3 bucket containing the output of the task.

# Arguments
- `task_id`: The Amazon Polly generated identifier for a speech synthesis task.

"""
get_speech_synthesis_task(TaskId; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/synthesisTasks/$(TaskId)"; aws_config=aws_config)
get_speech_synthesis_task(TaskId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/synthesisTasks/$(TaskId)", params; aws_config=aws_config)

"""
    list_lexicons()
    list_lexicons(params::Dict{String,<:Any})

Returns a list of pronunciation lexicons stored in an AWS Region. For more information, see
Managing Lexicons.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"NextToken"`: An opaque pagination token returned from previous ListLexicons operation.
  If present, indicates where to continue the list of lexicons.
"""
list_lexicons(; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/lexicons"; aws_config=aws_config)
list_lexicons(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/lexicons", params; aws_config=aws_config)

"""
    list_speech_synthesis_tasks()
    list_speech_synthesis_tasks(params::Dict{String,<:Any})

Returns a list of SpeechSynthesisTask objects ordered by their creation date. This
operation can filter the tasks by their status, for example, allowing users to list only
tasks that are completed.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: Maximum number of speech synthesis tasks returned in a List operation.
- `"NextToken"`: The pagination token to use in the next request to continue the listing of
  speech synthesis tasks.
- `"Status"`: Status of the speech synthesis tasks returned in a List operation
"""
list_speech_synthesis_tasks(; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/synthesisTasks"; aws_config=aws_config)
list_speech_synthesis_tasks(params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("GET", "/v1/synthesisTasks", params; aws_config=aws_config)

"""
    put_lexicon(content, lexicon_name)
    put_lexicon(content, lexicon_name, params::Dict{String,<:Any})

Stores a pronunciation lexicon in an AWS Region. If a lexicon with the same name already
exists in the region, it is overwritten by the new lexicon. Lexicon operations have
eventual consistency, therefore, it might take some time before the lexicon is available to
the SynthesizeSpeech operation. For more information, see Managing Lexicons.

# Arguments
- `content`: Content of the PLS lexicon as string data.
- `lexicon_name`: Name of the lexicon. The name must follow the regular express format
  [0-9A-Za-z]{1,20}. That is, the name is a case-sensitive alphanumeric string up to 20
  characters long.

"""
put_lexicon(Content, LexiconName; aws_config::AbstractAWSConfig=global_aws_config()) = polly("PUT", "/v1/lexicons/$(LexiconName)", Dict{String, Any}("Content"=>Content); aws_config=aws_config)
put_lexicon(Content, LexiconName, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("PUT", "/v1/lexicons/$(LexiconName)", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("Content"=>Content), params)); aws_config=aws_config)

"""
    start_speech_synthesis_task(output_format, output_s3_bucket_name, text, voice_id)
    start_speech_synthesis_task(output_format, output_s3_bucket_name, text, voice_id, params::Dict{String,<:Any})

Allows the creation of an asynchronous synthesis task, by starting a new
SpeechSynthesisTask. This operation requires all the standard information needed for speech
synthesis, plus the name of an Amazon S3 bucket for the service to store the output of the
synthesis task and two optional parameters (OutputS3KeyPrefix and SnsTopicArn). Once the
synthesis task is created, this operation will return a SpeechSynthesisTask object, which
will include an identifier of this task as well as the current status.

# Arguments
- `output_format`: The format in which the returned output will be encoded. For audio
  stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json.
- `output_s3_bucket_name`: Amazon S3 bucket name to which the output file will be saved.
- `text`: The input text to synthesize. If you specify ssml as the TextType, follow the
  SSML format for the input text.
- `voice_id`: Voice ID to use for the synthesis.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Engine"`: Specifies the engine (standard or neural) for Amazon Polly to use when
  processing input text for speech synthesis. Using a voice that is not supported for the
  engine selected will result in an error.
- `"LanguageCode"`: Optional language code for the Speech Synthesis request. This is only
  necessary if using a bilingual voice, such as Aditi, which can be used for either Indian
  English (en-IN) or Hindi (hi-IN).  If a bilingual voice is used and no language code is
  specified, Amazon Polly will use the default language of the bilingual voice. The default
  language for any voice is the one returned by the DescribeVoices operation for the
  LanguageCode parameter. For example, if no language code is specified, Aditi will use
  Indian English rather than Hindi.
- `"LexiconNames"`: List of one or more pronunciation lexicon names you want the service to
  apply during synthesis. Lexicons are applied only if the language of the lexicon is the
  same as the language of the voice.
- `"OutputS3KeyPrefix"`: The Amazon S3 key prefix for the output speech file.
- `"SampleRate"`: The audio frequency specified in Hz. The valid values for mp3 and
  ogg_vorbis are \"8000\", \"16000\", \"22050\", and \"24000\". The default value for
  standard voices is \"22050\". The default value for neural voices is \"24000\". Valid
  values for pcm are \"8000\" and \"16000\" The default value is \"16000\".
- `"SnsTopicArn"`: ARN for the SNS topic optionally used for providing status notification
  for a speech synthesis task.
- `"SpeechMarkTypes"`: The type of speech marks returned for the input text.
- `"TextType"`: Specifies whether the input text is plain text or SSML. The default value
  is plain text.
"""
start_speech_synthesis_task(OutputFormat, OutputS3BucketName, Text, VoiceId; aws_config::AbstractAWSConfig=global_aws_config()) = polly("POST", "/v1/synthesisTasks", Dict{String, Any}("OutputFormat"=>OutputFormat, "OutputS3BucketName"=>OutputS3BucketName, "Text"=>Text, "VoiceId"=>VoiceId); aws_config=aws_config)
start_speech_synthesis_task(OutputFormat, OutputS3BucketName, Text, VoiceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("POST", "/v1/synthesisTasks", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("OutputFormat"=>OutputFormat, "OutputS3BucketName"=>OutputS3BucketName, "Text"=>Text, "VoiceId"=>VoiceId), params)); aws_config=aws_config)

"""
    synthesize_speech(output_format, text, voice_id)
    synthesize_speech(output_format, text, voice_id, params::Dict{String,<:Any})

Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input must be
valid, well-formed SSML. Some alphabets might not be available with all the voices (for
example, Cyrillic might not be read at all by English voices) unless phoneme mapping is
used. For more information, see How it Works.

# Arguments
- `output_format`:  The format in which the returned output will be encoded. For audio
  stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json.  When
  pcm is used, the content returned is audio/pcm in a signed 16-bit, 1 channel (mono),
  little-endian format.
- `text`:  Input text to synthesize. If you specify ssml as the TextType, follow the SSML
  format for the input text.
- `voice_id`:  Voice ID to use for the synthesis. You can get a list of available voice IDs
  by calling the DescribeVoices operation.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Engine"`: Specifies the engine (standard or neural) for Amazon Polly to use when
  processing input text for speech synthesis. For information on Amazon Polly voices and
  which voices are available in standard-only, NTTS-only, and both standard and NTTS formats,
  see Available Voices.  NTTS-only voices  When using NTTS-only voices such as Kevin (en-US),
  this parameter is required and must be set to neural. If the engine is not specified, or is
  set to standard, this will result in an error.  Type: String Valid Values: standard |
  neural  Required: Yes  Standard voices  For standard voices, this is not required; the
  engine parameter defaults to standard. If the engine is not specified, or is set to
  standard and an NTTS-only voice is selected, this will result in an error.
- `"LanguageCode"`: Optional language code for the Synthesize Speech request. This is only
  necessary if using a bilingual voice, such as Aditi, which can be used for either Indian
  English (en-IN) or Hindi (hi-IN).  If a bilingual voice is used and no language code is
  specified, Amazon Polly will use the default language of the bilingual voice. The default
  language for any voice is the one returned by the DescribeVoices operation for the
  LanguageCode parameter. For example, if no language code is specified, Aditi will use
  Indian English rather than Hindi.
- `"LexiconNames"`: List of one or more pronunciation lexicon names you want the service to
  apply during synthesis. Lexicons are applied only if the language of the lexicon is the
  same as the language of the voice. For information about storing lexicons, see PutLexicon.
- `"SampleRate"`: The audio frequency specified in Hz. The valid values for mp3 and
  ogg_vorbis are \"8000\", \"16000\", \"22050\", and \"24000\". The default value for
  standard voices is \"22050\". The default value for neural voices is \"24000\". Valid
  values for pcm are \"8000\" and \"16000\" The default value is \"16000\".
- `"SpeechMarkTypes"`: The type of speech marks returned for the input text.
- `"TextType"`:  Specifies whether the input text is plain text or SSML. The default value
  is plain text. For more information, see Using SSML.
"""
synthesize_speech(OutputFormat, Text, VoiceId; aws_config::AbstractAWSConfig=global_aws_config()) = polly("POST", "/v1/speech", Dict{String, Any}("OutputFormat"=>OutputFormat, "Text"=>Text, "VoiceId"=>VoiceId); aws_config=aws_config)
synthesize_speech(OutputFormat, Text, VoiceId, params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()) = polly("POST", "/v1/speech", Dict{String, Any}(mergewith(_merge, Dict{String, Any}("OutputFormat"=>OutputFormat, "Text"=>Text, "VoiceId"=>VoiceId), params)); aws_config=aws_config)


text:
# This file is a part of H3DDetectorSystems.jl, licensed under the MIT License (MIT).

struct PolarisEvents
    evt_no::Vector{Int32}               # Event number
    evt_nhits::Vector{Int32}            # Number of hits
    evt_t::Vector{Int64}                # Event time, nanoseconds
    evt_issync::Vector{Bool}            # True is sync event
    hit_detno::VectorOfVectors{Int32}   # Detector number
    hit_x::VectorOfVectors{Int32}       # Position in µm,
    hit_y::VectorOfVectors{Int32}       # Position in µm,
    hit_z::VectorOfVectors{Int32}       # Position in µm,
    hit_edep::VectorOfVectors{Int32}    # Energy deposition in eV
    hit_t::VectorOfVectors{Int64}       # Hit time, nanoseconds
end

export PolarisEvents

PolarisEvents() = PolarisEvents(
    Vector{Int32}(), Vector{Int32}(), Vector{Int64}(), Vector{Bool}(),
    VectorOfVectors{Int32}(), VectorOfVectors{Int32}(), VectorOfVectors{Int32}(),
    VectorOfVectors{Int32}(), VectorOfVectors{Int32}(), VectorOfVectors{Int64}()
)

Base.NamedTuple(events::PolarisEvents) = (
    evt_no = events.evt_no,
    evt_t = deepmap(x -> x * u"ns", events.evt_t),
    evt_nhits = events.evt_nhits,
    evt_issync = events.evt_issync,
    hit_edep = deepmap(x -> x * u"eV", events.hit_edep),
    hit_t = deepmap(x -> x * u"ns", events.hit_t),
    hit_detno = events.hit_detno,
    hit_x = deepmap(x -> x * u"μm", events.hit_x),
    hit_y = deepmap(x -> x * u"μm", events.hit_y),
    hit_z = deepmap(x -> x * u"μm", events.hit_z),
)

Base.convert(::Type{NamedTuple}, events::PolarisEvents) = NamedTuple(events)

function Base.read!(
    input::IO, events::PolarisEvents;
    max_nevents::Int = typemax(Int),
    max_time::Float64 = Inf
)
    time_in_ns(timestamp::UInt64) = Int64(timestamp) * 10

    try
        evtno_offset = if !isempty(events.evt_no)
            Int(last(events.evt_no))
        else
            zero(Int)
        end

        hit_detno = Vector{Int32}()
        hit_x = Vector{Int32}()
        hit_y = Vector{Int32}()
        hit_z = Vector{Int32}()
        hit_edep = Vector{Int32}()
        hit_t = Vector{Int64}()

        start_time = time_ns()
        nevents::Int = 0

        while !eof(input) && (nevents < max_nevents) && ((time_ns() - start_time) * 1E-9 < max_time)
            nevents += 1
            nhits_tmp = ntoh(read(input, UInt8))
            evtno = nevents + evtno_offset

            # evtno % 100000 == 0 && info("Reading event $evtno")

            resize!(hit_detno, 0)
            resize!(hit_x, 0)
            resize!(hit_y, 0)
            resize!(hit_z, 0)
            resize!(hit_edep, 0)
            resize!(hit_t, 0)

            nhits::Int = 0
            t::Int64 = -1
            issync::Bool = false

            if nhits_tmp == 0
                # @debug "nhits_tmp == 0, skipping 23 bytes"
                read(input, UInt64)
                read(input, UInt64)
                read(input, UInt32)
                read(input, UInt16)
                read(input, UInt8)
            else
                if nhits_tmp == 122
                    issync = true
                    synchdr = read(input, PolarisSyncHeader)
                    (synchdr.n < 2) && @error "Invalid sync event in data stream, missing timestamp"
                    for i in 1:synchdr.n
                        syncvalue = read(input, PolarisSyncValue)
                        if i == 2
                            t = time_in_ns(syncvalue.x)
                            # @debug "sync_t" t syncvalue.x
                        end
                    end
                    @assert t >= 0
                else
                    nhits = Int(nhits_tmp)
                    (1 <= nhits <= 121) || throw(ErrorException("Invalid number of hits ($nhits) in datastream"))
                    evthdr = read(input, PolarisEventHeader)
                    t = time_in_ns(evthdr.timestamp)
                    for i in 1:nhits
                        hit = read(input, PolarisHit)

                        push!(hit_detno, hit.detno)
                        push!(hit_x, hit.x)
                        push!(hit_y, hit.y)
                        push!(hit_z, hit.z)
                        push!(hit_edep, hit.edep)
                        push!(hit_t, t)
                    end
                end

                push!(events.evt_no, evtno)
                push!(events.evt_nhits, nhits)
                push!(events.evt_t, t)
                push!(events.evt_issync, issync)
                push!(events.hit_detno, hit_detno)
                push!(events.hit_x, hit_x)
                push!(events.hit_y, hit_y)
                push!(events.hit_z, hit_z)
                push!(events.hit_edep, hit_edep)
                push!(events.hit_t, hit_t)
            end
        end
    catch err
        if isa(err, EOFError)
            @info "Input was truncated."
        else
            rethrow()
        end
    end
    events
end

Base.read(input::IO, ::Type{PolarisEvents}; kwargs...) = read!(input, PolarisEvents(); kwargs...)


text:
function trinary_to_decimal(str)
    dec = 0
    for (i, ch) in enumerate(reverse(str))
        d = Int(ch) - 48
        if !(0 <= d <= 2)
            return 0
        end
        dec += d * 3^(i - 1)
    end
    return dec
end

max_stars_repo_name: twolodzko/Learning

max_issues_repo_name: twolodzko/Learning

max_forks_repo_name: twolodzko/Learning


text:
"""
	gmtbegin(name::String=""; fmt)

Start a GMT session in modern mode (GMT >= 6).
'name' contains the figure name with or without extension. If an extension is used
(e.g. "map.pdf") it is used to select the image format.

As an alternative use 'fmt' as a string or symbol containing the format (ps, pdf, png, PNG, tif, jpg, eps).

By default name="GMTplot" and fmt="ps"
"""
function gmtbegin(name::String=""; fmt=nothing, verbose=nothing)
	FirstModern[1] = true			# To know if we need to compute -R in plot. Due to a GMT6.0 BUG
	cmd = "begin"       # Default name (GMTplot.ps) is set in gmt_main()
	(name != "") && (cmd *= " " * get_format(name, fmt))
	(verbose !== nothing) && (cmd *= " -V" * string(verbose))
	gmt_restart()		# Always start with a clean session
	gmt(cmd)
	return nothing
end

"""
	gmtend(show=false, verbose=nothing)

Ends a GMT session in modern mode (GMT >= 6) and optionaly shows the figure
"""
function gmtend(arg=nothing; show=false, verbose=nothing)
	# To show either do gmtend(whatever) or gmt(show=true)
	cmd = "end"
	(arg !== nothing || show != 0) && (cmd *= " show")
	(verbose !== nothing) && (cmd *= " -V" * string(verbose))
	gmt(cmd)
	IamModern[1] = false;	FirstModern[1] = false
	return nothing
end

"""
	function gmtfig(name::String; fmt=nothing, opts="")

Set attributes for the current modern mode session figure.
'name' name of the new (or resumed) figure. It may contain an extension.
'fmt'  figures graphics format (or formats, e.g. fmt="eps,pdf"). Not needed if 'name' has extension
'opts' Sets one or more comma-separated options (and possibly arguments) that can be passed to psconvert when preparing this figure.
"""
function gmtfig(name::String; fmt=nothing, opts="")
	(!IamModern[1]) && error("Not in modern mode. Must run 'gmtbegin' first")

	cmd = "figure"       # Default name (GMTplot.ps) is set in gmt_main()
	(name == "") && error("figure name cannot be empty")
	cmd *= " " * get_format(name, fmt)
	(opts != "") && (cmd *= " " * opts)
	gmt(cmd)
	return nothing
end

function inset(fim=nothing; stop=false, kwargs...)

	d = KW(kwargs)
	cmd, = parse_common_opts(d, "", [:c :F :V_params], true)
	cmd  = parse_these_opts(cmd, d, [[:M :margins], [:N :no_clip]])
	#cmd  = parse_type_anchor(d, cmd, [[:D :inset :inset_box]])
	cmd = parse_type_anchor(d, cmd, [:D :inset :inset_box],
	                        (map=("-g", arg2str, 1), outside=("J", nothing, 1), inside=("j", nothing, 1), norm=("-n", arg2str, 1), paper=("-x", arg2str, 1), anchor=("", arg2str, 2), width="+w", size="+w", justify="+j", offset=("+o", arg2str), save="+s", translate="_+t", units="_+u"), 'j')

	do_show = false
	if (fim !== nothing)
		t = lowercase(string(fim))
		if (t == "end" || t == "stop" || t == "show")  stop = true  end
		if (t == "show")  do_show = true  end
	end

	if (!stop)
		(dbg_print_cmd(d, cmd) !== nothing) && return cmd		# Vd=2 cause this return
		(!IamModern[1]) && error("Not in modern mode. Must run 'gmtbegin' first")
		gmt("inset begin " * cmd);
	else
		(!IamModern[1]) && error("Not in modern mode. Must run 'gmtbegin' first")
		gmt("inset end");
		(do_show || haskey(d, :show)) && gmt("end" * show)
	end
end

function get_format(name, fmt=nothing, d=nothing)
	# Get the fig name and format. If format not specified, default to FMT (ps)
	# NAME is supposed to always exist (otherwise, errors)
	fname, ext = splitext(string(name))
	if (ext != "")
		fname *= " " * ext[2:end]
	elseif (fmt !== nothing)
		fname *= " " * string(fmt)      # No checking
	elseif (d !== nothing)
		if (haskey(d, :fmt))  fname *= " " * string(d[:fmt])
		else                  fname *= " " * FMT[1]		# Then use default format
		end
	else
		fname *= " " * FMT[1]
	end
	return fname
end


text:
# the loop version of loop

function move_loop2!(x)
    # firstly, compact x so that there are no gaps
    # however cells are not yet merged
    @inbounds for i in 1:3
        if 0 < x[i] == x[i+1]
            x[i] += 1
            x[i+1] = 0
        end
    end

    # now the data is compact; we combine it
    @inbounds if (x[1] != 0) && (x[1] == x[2])
        x[1] += 1
        if (x[3] != 0)  && (x[3] == x[4])
            x[2], x[3], x[4] = x[3] + 1, 0 , 0
        else
            x[2], x[3], x[4] = x[3], x[4], 0
        end
    elseif (x[2] != 0) && (x[2] == x[3])
        x[2] += 1
        x[3], x[4] = x[4], 0
    elseif (x[3] != 0) && (x[3] == x[4])
        x[3] += 1
        x[4] = 0
    end

    x
end