text:
.ult-hide {
    display: none !important
}
button.overlay-show,
button.overlay-show-cornershape,
button.overlay-show-genie,
button.overlay-show-boxes,
img.overlay-show,
img.overlay-show-cornershape,
img.overlay-show-genie,
img.overlay-show-boxes,
span.overlay-show,
div.ult-overlay-close {
    cursor: pointer
}
.btn-modal {
    display: block;
    margin: 2px;
    padding: 8px 13px;
    font-size: 14px;
    line-height: 1.5;
    border-radius: 3px
}
.btn-modal-lg {
    padding: 10px 16px;
    font-size: 18px;
    line-height: 1.33;
    border-radius: 6px
}
.btn-modal-sm {
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
    border-radius: 3px
}
.btn-modal-md {
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.5;
    border-radius: 3px
}
.btn-modal-block {
    display: block;
    width: 100%;
    padding-right: 0;
    padding-left: 0
}
.btn-modal:active {
    box-shadow: none;
    outline: 0
}
button.ult-align-center {
    margin: 0 auto;
    display: block
}
button.ult-align-left {
    float: left
}
button.ult-align-right {
    float: right
}
img.ult-modal-img {
    box-shadow: none;
    border: 0;
    max-width: 100%;
    display: block
}
img.ult-modal-inside-img {
    width: 48px;
    vertical-align: middle;
    padding: 5px 0;
    box-shadow: none;
    border: 0
}
img.ult-align-center {
    margin: 0 auto
}
img.ult-align-left {
    float: left
}
img.ult-align-right {
    float: right
}
span.ult-align-left {
    text-align: left
}
span.ult-align-center {
    text-align: center;
    display: table;
    margin: 0 auto
}
span.ult-align-right {
    display: block;
    text-align: right
}
.ult-overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(28, 28, 28, 0.9);
    z-index: 9999;
    z-index: 16777271;
    visibility: hidden
}
.ult_modal-auto-top.ult-open {
    display: block;
    overflow: auto;
    overflow-y: scroll
}
.ult-overlay-close {
    width: 80px;
    height: 80px;
    position: fixed;
    right: 35px;
    top: 35px;
    overflow: hidden;
    border: 0;
    background: url('../img/cross.png') no-repeat center center;
    text-indent: 200%;
    color: transparent;
    outline: 0;
    z-index: 9999
}
.ult-overlay .ult-overlay-close:active {
    box-shadow: none !important;
    outline: 0 !important
}
.ult_modal {
    width: 400px;
    max-width: 100%;
    transition: all 300ms ease-in;
    z-index: 99;
    display: block;
    margin: 0 auto;
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
    -webkit-perspective: 1200px;
    -o-perspective: 1200px;
    -moz-perspective: 1200px;
    -ms-perspective: 1200px;
    perspective: 1200px
}
.ult_modal-auto-top .ult_modal {
    margin: 35px auto;
    top: 0;
    -webkit-transform: translate(0);
    -o-transform: translate(0);
    -moz-transform: translate(0);
    -ms-transform: translate(0);
    transform: translate(0)
}
.ult_modal-content {
    -webkit-border-radius: 8px;
    -moz-border-radius: 8px;
    -o-border-radius: 8px;
    -ms-border-radius: 8px;
    border-radius: 8px;
    -webkit-box-shadow: 0 0 7px #404040;
    -moz-box-shadow: 0 0 7px #404040;
    -o-box-shadow: 0 0 7px #404040;
    -ms-box-shadow: 0 0 7px #404040;
    box-shadow: 0 0 7px #404040;
    overflow: hidden
}
.ult_modal-header {
    border-bottom: 1px solid #e5e5e5;
    font-size: 16px;
    background: #fff
}
.ult_modal-header>.modal-icon {
    font-size: 2em;
    display: table-cell;
    vertical-align: middle;
    padding: 0 0 0 20px
}
h3.ult_modal-title {
    color: inherit;
    display: table-cell;
    vertical-align: middle;
    margin: 0;
    padding: 10px 20px;
    font-size: 1em;
    line-height: 1.5em
}
.ult_modal-body {
    padding: 15px 20px;
    background: #fff;
    max-width: 100%;
    overflow: hidden;
    line-height: 1.5em
}
.ult_modal-body p {
    margin-bottom: 1em
}
.ult_modal-body img {
    max-width: 100%
}
.ult-overlay iframe,
.ult-overlay object {
    opacity: 0;
    position: absolute;
    z-index: -99999;
    max-width: 100%
}
.ult-overlay.ult-open iframe,
.ult-overlay.ult-open object {
    opacity: 1;
    position: relative;
    z-index: 9999;
    z-index: 16777271
}
.ult_modal.ult-small {
    width: 35%
}
.ult_modal.ult-medium {
    width: 60%
}
.ult_modal.ult-container {
    width: 96%
}
.ult_modal.ult-block {
    width: auto;
    max-width: 90%;
    display: table
}
.overlay-fade {
    opacity: 0;
    visibility: hidden;
    -webkit-transition: opacity .5s, visibility .5s;
    -moz-transition: opacity .5s, visibility .5s;
    -o-transition: opacity .5s, visibility .5s;
    -ms-transition: opacity .5s, visibility .5s;
    transition: opacity .5s, visibility .5s
}
.overlay-fade.ult-open {
    opacity: 1;
    visibility: visible;
    -webkit-transition: opacity .5s;
    -moz-transition: opacity .5s;
    -o-transition: opacity .5s;
    -ms-transition: opacity .5s;
    transition: opacity .5s
}
.overlay-fade .ult_modal-content {
    opacity: .4;
    -webkit-transform: translateY(0);
    -moz-transform: translateY(0);
    -o-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0);
    -webkit-transition: -webkit-transform .5s, opacity .5s;
    -moz-transition: -moz-transform .5s, opacity .5s;
    -o-transition: -o-transform .5s, opacity .5s;
    -ms-transition: -ms-transform .5s, opacity .5s;
    transition: transform .5s, opacity .5s
}
.overlay-fade.ult-open .ult_modal-content {
    opacity: 1
}
.overlay-fade.ult-close .ult_modal-content {
    -webkit-transform: translateY(25%);
    -moz-transform: translateY(25%);
    -o-transform: translateY(25%);
    -ms-transform: translateY(25%);
    transform: translateY(25%)
}
.overlay-corner {
    opacity: 0;
    visibility: hidden;
    -webkit-transform: translateY(50px) translateX(50px);
    -moz-transform: translateY(50px) translateX(50px);
    -o-transform: translateY(50px) translateX(50px);
    -ms-transform: translateY(50px) translateX(50px);
    transform: translateY(50px) translateX(50px);
    -webkit-transition: opacity .5s, -webkit-transform .5s, visibility .5s;
    -moz-transition: opacity .5s, -moz-transform .5s, visibility .5s;
    -o-transition: opacity .5s, -o-transform .5s, visibility .5s;
    -ms-transition: opacity .5s, -ms-transform .5s, visibility .5s;
    transition: opacity .5s, transform .5s, visibility .5s
}
.overlay-corner.ult-open {
    opacity: 1;
    visibility: visible;
    -webkit-transform: translateY(0) translateX(0);
    -moz-transform: translateY(0) translateX(0);
    -o-transform: translateY(0) translateX(0);
    -ms-transform: translateY(0) translateX(0);
    transform: translateY(0) translateX(0);
    -webkit-transition: opacity .5s, -webkit-transform .5s;
    -moz-transition: opacity .5s, -moz-transform .5s;
    -o-transition: opacity .5s, -o-transform .5s;
    -ms-transition: opacity .5s, -ms-transform .5s;
    transition: opacity .5s, transform .5s
}
.overlay-cornerbottomright,
.overlay-cornerbottomleft,
.overlay-cornertopleft,
.overlay-cornertopright {
    opacity: 0;
    visibility: hidden;
    -webkit-transition: opacity .5s, -webkit-transform .5s, visibility .5s;
    -moz-transition: opacity .5s, -moz-transform .5s, visibility .5s;
    -o-transition: opacity .5s, -o-transform .5s, visibility .5s;
    -ms-transition: opacity .5s, -ms-transform .5s, visibility .5s;
    transition: opacity .5s, transform .5s, visibility .5s
}
.overlay-cornerbottomright.ult-open,
.overlay-cornerbottomleft.ult-open,
.overlay-cornertopleft.ult-open,
.overlay-cornertopright.ult-open {
    opacity: 1;
    visibility: visible;
    -webkit-transform: translateY(0) translateX(0);
    -moz-transform: translateY(0) translateX(0);
    -o-transform: translateY(0) translateX(0);
    -ms-transform: translateY(0) translateX(0);
    transform: translateY(0) translateX(0);
    -webkit-transition: opacity .5s, -webkit-transform .5s;
    -moz-transition: opacity .5s, -moz-transform .5s;
    -o-transition: opacity .5s, -o-transform .5s;
    -ms-transition: opacity .5s, -ms-transform .5s;
    transition: opacity .5s, transform .5s
}
.overlay-cornerbottomright {
    -webkit-transform: translateY(200px) translateX(200px);
    -moz-transform: translateY(200px) translateX(200px);
    -o-transform: translateY(200px) translateX(200px);
    -ms-transform: translateY(200px) translateX(200px);
    transform: translateY(200px) translateX(200px)
}
.overlay-cornerbottomleft {
    -webkit-transform: translateY(200px) translateX(-200px);
    -moz-transform: translateY(200px) translateX(-200px);
    -o-transform: translateY(200px) translateX(-200px);
    -ms-transform: translateY(200px) translateX(-200px);
    transform: translateY(200px) translateX(-200px)
}
.overlay-cornertopleft {
    -webkit-transform: translateY(-200px) translateX(-200px);
    -moz-transform: translateY(-200px) translateX(-200px);
    -o-transform: translateY(-200px) translateX(-200px);
    -ms-transform: translateY(-200px) translateX(-200px);
    transform: translateY(-200px) translateX(-200px)
}
.overlay-cornertopright {
    -webkit-transform: translateY(-200px) translateX(200px);
    -moz-transform: translateY(-200px) translateX(200px);
    -o-transform: translateY(-200px) translateX(200px);
    -ms-transform: translateY(-200px) translateX(200px);
    transform: translateY(-200px) translateX(200px)
}
.overlay-slidedown,
.overlay-slideup,
.overlay-slideleft,
.overlay-slideright {
    visibility: hidden;
    -webkit-transition: -webkit-transform .4s ease-in-out, visibility .4s;
    -moz-transition: -moz-transform .4s ease-in-out, visibility .4s;
    -o-transition: -o-transform .4s ease-in-out, visibility .4s;
    -ms-transition: -ms-transform .4s ease-in-out, visibility .4s;
    transition: transform .4s ease-in-out, visibility .4s
}
.overlay-slidedown.ult-open,
.overlay-slideup.ult-open,
.overlay-slideleft.ult-open,
.overlay-slideright.ult-open {
    visibility: visible;
    -webkit-transition: -webkit-transform .4s ease-in-out;
    -moz-transition: -moz-transform .4s ease-in-out;
    -o-transition: -o-transform .4s ease-in-out;
    -ms-transition: -ms-transform .4s ease-in-out;
    transition: transform .4s ease-in-out
}
.overlay-slidedown {
    -webkit-transform: translateY(-100%);
    -moz-transform: translateY(-100%);
    -o-transform: translateY(-100%);
    -ms-transform: translateY(-100%);
    transform: translateY(-100%)
}
.overlay-slidedown.ult-open {
    -webkit-transform: translateY(0);
    -moz-transform: translateY(0);
    -o-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0)
}
.overlay-slideup {
    -webkit-transform: translateY(100%);
    -moz-transform: translateY(100%);
    -o-transform: translateY(100%);
    -ms-transform: translateY(100%);
    transform: translateY(100%)
}
.overlay-slideup.ult-open {
    -webkit-transform: translateY(0);
    -moz-transform: translateY(0);
    -o-transform: translateY(0);
    -ms-transform: translateY(0);
    transform: translateY(0)
}
.overlay-slideleft {
    -webkit-transform: translateX(100%);
    -moz-transform: translateX(100%);
    -o-transform: translateX(100%);
    -ms-transform: translateX(100%);
    transform: translateX(100%)
}
.overlay-slideleft.ult-open {
    -webkit-transform: translateX(0);
    -moz-transform: translateX(0);
    -o-transform: translateX(0);
    -ms-transform: translateX(0);
    transform: translateX(0)
}
.overlay-slideright {
    -webkit-transform: translateX(-100%);
    -moz-transform: translateX(-100%);
    -o-transform: translateX(-100%);
    -ms-transform: translateX(-100%);
    transform: translateX(-100%)
}
.overlay-slideright.ult-open {
    -webkit-transform: translateX(0);
    -moz-transform: translateX(0);
    -o-transform: translateX(0);
    -ms-transform: translateX(0);
    transform: translateX(0)
}
.overlay-zoomin,
.overlay-zoomout {
    visibility: hidden;
    opacity: 0;
    -webkit-transition: -webkit-transform .2s, opacity .2s, visibility .2s;
    -moz-transition: -moz-transform .2s, opacity .2s, visibility .2s;
    -o-transition: -o-transform .2s, opacity .2s, visibility .2s;
    -ms-transition: -ms-transform .2s, opacity .2s, visibility .2s;
    transition: transform .2s, opacity .2s, visibility .2s
}
.overlay-zoomin.ult-open,
.overlay-zoomout.ult-open {
    visibility: visible;
    opacity: 1;
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -o-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    -webkit-transition: -webkit-transform .4s, opacity .4s;
    -moz-transition: -moz-transform .4s, opacity .4s;
    -o-transition: -o-transform .4s, opacity .4s;
    -ms-transition: -ms-transform .4s, opacity .4s;
    transition: transform .4s, opacity .4s
}
.overlay-zoomin {
    -webkit-transform: scale(1.5);
    -moz-transform: scale(1.5);
    -o-transform: scale(1.5);
    -ms-transform: scale(1.5);
    transform: scale(1.5)
}
.overlay-zoomout {
    -webkit-transform: scale(0.5);
    -moz-transform: scale(0.5);
    -o-transform: scale(0.5);
    -ms-transform: scale(0.5);
    transform: scale(0.5)
}
.overlay-doorhorizontal {
    visibility: hidden;
    width: 0;
    left: 50%;
    -webkit-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -o-transform: translateX(-50%);
    -ms-transform: translateX(-50%);
    transform: translateX(-50%);
    -webkit-transition: width .5s .3s, visibility .8s;
    -moz-transition: width .5s .3s, visibility .8s;
    -o-transition: width .5s .3s, visibility .8s;
    -ms-transition: width .5s .3s, visibility .8s;
    transition: width .5s .3s, visibility .8s
}
.overlay-doorhorizontal.ult-open {
    visibility: visible;
    width: 100%;
    -webkit-transition: width .5s;
    -moz-transition: width .5s;
    -o-transition: width .5s;
    -ms-transition: width .5s;
    transition: width .5s
}
.overlay-doorhorizontal .ult_modal-content,
.overlay-doorhorizontal .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .5s;
    -moz-transition: opacity .5s;
    -o-transition: opacity .5s;
    -ms-transition: opacity .5s;
    transition: opacity .5s
}
.overlay-doorhorizontal.ult-open .ult_modal-content,
.overlay-doorhorizontal.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .5s;
    -moz-transition-delay: .5s;
    -o-transition-delay: .5s;
    -ms-transition-delay: .5s;
    transition-delay: .5s
}
.overlay-doorhorizontal.ult-close .ult_modal-content,
.overlay-doorhorizontal.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.overlay-doorvertical {
    visibility: hidden;
    width: 100%;
    height: 0;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
    -webkit-transition: height .5s .3s, visibility .8s;
    -moz-transition: height .5s .3s, visibility .8s;
    -o-transition: height .5s .3s, visibility .8s;
    -ms-transition: height .5s .3s, visibility .8s;
    transition: height .5s .3s, visibility .8s
}
.overlay-doorvertical.ult-open {
    visibility: visible;
    height: 100%;
    -webkit-transition: height .5s;
    -moz-transition: height .5s;
    -o-transition: height .5s;
    -ms-transition: height .5s;
    transition: height .5s
}
.overlay-doorvertical .ult_modal-content,
.overlay-doorvertical .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .3s .5s;
    -moz-transition: opacity .3s .5s;
    -o-transition: opacity .3s .5s;
    -ms-transition: opacity .3s .5s;
    transition: opacity .3s .5s
}
.overlay-doorvertical.ult-open .ult_modal-content,
.overlay-doorvertical.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .5s;
    -moz-transition-delay: .5s;
    -o-transition-delay: .5s;
    -ms-transition-delay: .5s;
    transition-delay: .5s
}
.overlay-doorvertical.ult-close .ult_modal-content,
.overlay-doorvertical.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.overlay-cornershape {
    background: transparent;
    visibility: hidden;
    -webkit-transition: visibility .5s;
    -moz-transition: visibility .5s;
    -o-transition: visibility .5s;
    -ms-transition: visibility .5s;
    transition: visibility .5s
}
.overlay-cornershape.ult-open {
    visibility: visible;
    -webkit-transition: none;
    -moz-transition: none;
    -o-transition: none;
    -ms-transition: none;
    transition: none
}
.overlay-cornershape svg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%
}
.overlay-cornershape .overlay-path {
    fill: rgba(28, 28, 28, 0.9)
}
.overlay-cornershape .ult_modal-content,
.overlay-cornershape .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .4s;
    -moz-transition: opacity .4s;
    -o-transition: opacity .4s;
    -ms-transition: opacity .4s;
    transition: opacity .4s
}
.overlay-cornershape.ult-open .ult_modal-content,
.overlay-cornershape.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .4s;
    -moz-transition-delay: .4s;
    -o-transition-delay: .4s;
    -ms-transition-delay: .4s;
    transition-delay: .4s
}
.overlay-cornershape.ult-close .ult_modal-content,
.overlay-cornershape.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.overlay-boxes {
    background: transparent;
    visibility: hidden;
    -webkit-transition: visibility .8s;
    -moz-transition: visibility .8s;
    -o-transition: visibility .8s;
    -ms-transition: visibility .8s;
    transition: visibility .8s
}
.overlay-boxes.ult-open {
    visibility: visible;
    -webkit-transition: none;
    -moz-transition: none;
    -o-transition: none;
    -ms-transition: none;
    transition: none
}
.overlay-boxes svg {
    position: absolute;
    top: 0;
    left: 0
}
.overlay-boxes svg path {
    fill: rgba(28, 28, 28, 1);
    display: none
}
.overlay-boxes .ult_modal-content,
.overlay-boxes .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .5s .8s;
    -moz-transition: opacity .5s .8s;
    -o-transition: opacity .5s .8s;
    -ms-transition: opacity .5s .8s;
    transition: opacity .5s .8s
}
.overlay-boxes.ult-open .ult_modal-content,
.overlay-boxes.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .8s;
    -moz-transition-delay: .8s;
    -o-transition-delay: .8s;
    -ms-transition-delay: .8s;
    transition-delay: .8s
}
.overlay-boxes.ult-close .ult_modal-content,
.overlay-boxes.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.overlay-boxes {
    background: transparent;
    visibility: hidden;
    -webkit-transition: visibility .8s;
    -moz-transition: visibility .8s;
    -o-transition: visibility .8s;
    -ms-transition: visibility .8s;
    transition: visibility .8s
}
.overlay-boxes.ult-open {
    visibility: visible;
    -webkit-transition: none;
    -moz-transition: none;
    -o-transition: none;
    -ms-transition: none;
    transition: none
}
.overlay-boxes svg {
    position: absolute;
    top: 0;
    left: 0
}
.overlay-boxes svg path {
    fill: rgba(28, 28, 28, 1);
    display: none
}
.overlay-boxes .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .5s .8s;
    -moz-transition: opacity .5s .8s;
    -o-transition: opacity .5s .8s;
    -ms-transition: opacity .5s .8s;
    transition: opacity .5s .8s
}
.overlay-boxes.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .8s;
    -moz-transition-delay: .8s;
    -o-transition-delay: .8s;
    -ms-transition-delay: .8s;
    transition-delay: .8s
}
.overlay-boxes.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.overlay-simplegenie {
    visibility: hidden;
    -webkit-transform: translateY(60%) scale(0);
    -moz-transform: translateY(60%) scale(0);
    -o-transform: translateY(60%) scale(0);
    -ms-transform: translateY(60%) scale(0);
    transform: translateY(60%) scale(0);
    -webkit-transition: -webkit-transform .4s, visibility .4s;
    -moz-transition: -moz-transform .4s, visibility .4s;
    -o-transition: -o-transform .4s, visibility .4s;
    -ms-transition: -ms-transform .4s, visibility .4s;
    transition: transform .4s, visibility .4s
}
.overlay-simplegenie.ult-open {
    visibility: visible;
    -webkit-transform: translateY(0) scale(1);
    -moz-transform: translateY(0) scale(1);
    -o-transform: translateY(0) scale(1);
    -ms-transform: translateY(0) scale(1);
    transform: translateY(0) scale(1);
    -webkit-transition: -webkit-transform .4s;
    -moz-transition: -moz-transform .4s;
    -o-transition: -o-transform .4s;
    -ms-transition: -ms-transform .4s;
    transition: transform .4s
}
.overlay-genie {
    background: transparent;
    visibility: hidden;
    opacity: 0;
    -webkit-transition: opacity .3s .2s, visibility .6s;
    -moz-transition: opacity .3s .2s, visibility .6s;
    -o-transition: opacity .3s .2s, visibility .6s;
    -ms-transition: opacity .3s .2s, visibility .6s;
    transition: opacity .3s .2s, visibility .6s
}
.overlay-genie.ult-open {
    visibility: visible;
    opacity: 1;
    -webkit-transition: opacity .3s;
    -moz-transition: opacity .3s;
    -o-transition: opacity .3s;
    -ms-transition: opacity .3s;
    transition: opacity .3s
}
.overlay-genie svg {
    position: fixed;
    top: 0;
    left: 0
}
.overlay-genie .overlay-path {
    fill: rgba(28, 28, 28, 0.9)
}
.overlay-genie .ult_modal-content {
    opacity: 0;
    -webkit-transform: scale(0.8) translateY(-48%);
    -moz-transform: scale(0.8) translateY(-48%);
    -o-transform: scale(0.8) translateY(-48%);
    -ms-transform: scale(0.8) translateY(-48%);
    transform: scale(0.8) translateY(-48%);
    -webkit-transition: opacity .3s .3s, -webkit-transform .3s .3s;
    -moz-transition: opacity .3s .3s, -moz-transform .3s .3s;
    -o-transition: opacity .3s .3s, -o-transform .3s .3s;
    -ms-transition: opacity .3s .3s, -ms-transform .3s .3s;
    transition: opacity .3s .3s, transform .3s .3s
}
.overlay-genie .ult-overlay-close {
    opacity: 0;
    -webkit-transition: opacity .3s;
    -moz-transition: opacity .3s;
    -o-transition: opacity .3s;
    -ms-transition: opacity .3s;
    transition: opacity .3s
}
.overlay-genie.ult-open .ult_modal-content,
.overlay-genie.ult-open .ult-overlay-close {
    opacity: 1;
    -webkit-transition-delay: .3s;
    -moz-transition-delay: .3s;
    -o-transition-delay: .3s;
    -ms-transition-delay: .3s;
    transition-delay: .3s
}
.overlay-genie.ult-open .ult_modal-content {
    -webkit-transform: scale(1) translateY(0);
    -moz-transform: scale(1) translateY(0);
    -o-transform: scale(1) translateY(0);
    -ms-transform: scale(1) translateY(0);
    transform: scale(1) translateY(0)
}
.overlay-genie.ult-close .ult_modal-content,
.overlay-genie.ult-close .ult-overlay-close {
    -webkit-transition-delay: 0;
    -moz-transition-delay: 0;
    -o-transition-delay: 0;
    -ms-transition-delay: 0;
    transition-delay: 0
}
.ult_modal div.ult_modal-body>iframe {
    display: none
}
.ult-open>.ult_modal div.ult_modal-body>iframe {
    display: block
}
div.ult_modal-body .fluid-width-video-wrapper {
    padding: 0 !important;
}
@media(max-width:767px) {
    .ult_modal.ult-small, .ult_modal.ult-medium, .ult_modal.ult-container {
        width: 80%
    }
    .ult_modal.ult-block {
        max-width: 80%
    }
    .ult-overlay-close {
        width: 24px;
        height: 24px;
        right: 5px;
        top: 5px
    }
}


text:
package pl.edu.pja.organization;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import sim.engine.SimState;

public abstract class Organization extends SimState {

    private static final long serialVersionUID = 9048955491941212328L;

    public Organization(long seed) {
        super(seed);
    }

    public abstract Set<Employee> getCoworkers(Employee emp);

    public abstract Set<Employee> getSubordinates(Employee emp);

    public abstract Optional<Employee> getManager(Employee emp);

    public abstract double getKnowledgeUsabilityRate();

    public abstract List<Result> getResults();

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	PostProcessSelectionOutline.cpp: Post processing outline effect.
=============================================================================*/

#include "RendererPrivate.h"
#include "PostProcessing.h"
#include "SceneFilterRendering.h"
#include "PostProcessSelectionOutline.h"
#include "OneColorShader.h"
#include "SceneUtils.h"

///////////////////////////////////////////
// FRCPassPostProcessSelectionOutlineColor
///////////////////////////////////////////

void FRCPassPostProcessSelectionOutlineColor::Process(FRenderingCompositePassContext& Context)
{
	SCOPED_DRAW_EVENT(Context.RHICmdList, PostProcessSelectionOutlineBuffer);

	const FPooledRenderTargetDesc* SceneColorInputDesc = GetInputDesc(ePId_Input0);

	if(!SceneColorInputDesc)
	{
		// input is not hooked up correctly
		return;
	}

	const FViewInfo& View = Context.View;
	FIntRect ViewRect = View.ViewRect;
	FIntPoint SrcSize = SceneColorInputDesc->Extent;

	// Get the output render target
	const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);

	// Set the render target/viewport.
	SetRenderTarget(Context.RHICmdList, FTextureRHIParamRef(), DestRenderTarget.TargetableTexture);
	// This is a reversed Z depth surface, so 0.0f is the far plane.
	Context.RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, (float)ERHIZBuffer::FarPlane, true, 0, FIntRect());
	Context.SetViewportAndCallRHI(ViewRect);

	if (View.Family->EngineShowFlags.Selection)
	{
		FHitProxyDrawingPolicyFactory::ContextType FactoryContext;

		//@todo - use memstack
		TMap<FName, int32> ActorNameToStencilIndex;
		TMap<const FPrimitiveSceneProxy*, int32> IndividuallySelectedProxies;
		ActorNameToStencilIndex.Add(NAME_BSP, 1);

		Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
		Context.RHICmdList.SetBlendState(TStaticBlendStateWriteMask<CW_NONE, CW_NONE, CW_NONE, CW_NONE>::GetRHI());

		for (int32 MeshBatchIndex = 0; MeshBatchIndex < View.DynamicMeshElements.Num(); MeshBatchIndex++)
		{
			const FMeshBatchAndRelevance& MeshBatchAndRelevance = View.DynamicMeshElements[MeshBatchIndex];
			const FPrimitiveSceneProxy* PrimitiveSceneProxy = MeshBatchAndRelevance.PrimitiveSceneProxy;

#if WITH_EDITOR
			// Selected actors should be subdued if any component is individually selected
			bool bActorSelectionColorIsSubdued = View.bHasSelectedComponents;
#else
			bool bActorSelectionColorIsSubdued = false;
#endif
			if (PrimitiveSceneProxy->IsSelected() && MeshBatchAndRelevance.Mesh->bUseSelectionOutline)
			{
				const int32* AssignedStencilIndexPtr = PrimitiveSceneProxy->IsIndividuallySelected() ? IndividuallySelectedProxies.Find( PrimitiveSceneProxy ) : ActorNameToStencilIndex.Find(PrimitiveSceneProxy->GetOwnerName());

				if (!AssignedStencilIndexPtr)
				{
					if( PrimitiveSceneProxy->IsIndividuallySelected() )
					{
						// Any component that is individually selected should have a stencil value of < 128 so that it can have a unique color.  We offset the value by 2 because 0 means no selection and 1 is for bsp
						int32 StencilValue = IndividuallySelectedProxies.Num() % 126 + 2;
						AssignedStencilIndexPtr = &IndividuallySelectedProxies.Add(PrimitiveSceneProxy, StencilValue);
					}
					else
					{
						// If we are subduing actor color highlight then use the top level bits to indicate that to the shader.
						int32 StencilValue = bActorSelectionColorIsSubdued ? ActorNameToStencilIndex.Num() % 128 + 128 : ActorNameToStencilIndex.Num() % 126 + 2;
						AssignedStencilIndexPtr = &ActorNameToStencilIndex.Add(PrimitiveSceneProxy->GetOwnerName(), StencilValue);
					}
				}

				// Note that the stencil value will overflow with enough selected objects
				Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<true, CF_DepthNearOrEqual, true, CF_Always, SO_Keep, SO_Keep, SO_Replace>::GetRHI(), *AssignedStencilIndexPtr);

				const FMeshBatch& MeshBatch = *MeshBatchAndRelevance.Mesh;
				FHitProxyDrawingPolicyFactory::DrawDynamicMesh(Context.RHICmdList, View, FactoryContext, MeshBatch, false, true, MeshBatchAndRelevance.PrimitiveSceneProxy, MeshBatch.BatchHitProxyId);
			}
		}

		// to get an outline around the objects if it's partly outside of the screen
		{
			FIntRect InnerRect = ViewRect;

			// 1 as we have an outline that is that thick
			InnerRect.InflateRect(-1);

			// We could use Clear with InnerRect but this is just an optimization - on some hardware it might do a full clear (and we cannot disable yet)
			//			RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, 0.0f, true, 0, InnerRect);
			// so we to 4 clears - one for each border.

			// top
			Context.RHICmdList.SetScissorRect(true, ViewRect.Min.X, ViewRect.Min.Y, ViewRect.Max.X, InnerRect.Min.Y);
			Context.RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, (float)ERHIZBuffer::FarPlane, true, 0, FIntRect());
			// bottom
			Context.RHICmdList.SetScissorRect(true, ViewRect.Min.X, InnerRect.Max.Y, ViewRect.Max.X, ViewRect.Max.Y);
			Context.RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, (float)ERHIZBuffer::FarPlane, true, 0, FIntRect());
			// left
			Context.RHICmdList.SetScissorRect(true, ViewRect.Min.X, ViewRect.Min.Y, InnerRect.Min.X, ViewRect.Max.Y);
			Context.RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, (float)ERHIZBuffer::FarPlane, true, 0, FIntRect());
			// right
			Context.RHICmdList.SetScissorRect(true, InnerRect.Max.X, ViewRect.Min.Y, ViewRect.Max.X, ViewRect.Max.Y);
			Context.RHICmdList.Clear(false, FLinearColor(0, 0, 0, 0), true, (float)ERHIZBuffer::FarPlane, true, 0, FIntRect());

			Context.RHICmdList.SetScissorRect(false, 0, 0, 0, 0);
		}
	}

	// Resolve to the output
	Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}

FPooledRenderTargetDesc FRCPassPostProcessSelectionOutlineColor::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
	FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;

	Ret.Reset();

	Ret.Format = PF_DepthStencil;
	Ret.Flags = TexCreate_None;
	Ret.TargetableFlags = TexCreate_DepthStencilTargetable;
	Ret.DebugName = TEXT("SelectionDepthStencil");
	Ret.NumSamples = FSceneRenderTargets::Get_FrameConstantsOnly().GetEditorMSAACompositingSampleCount();

	return Ret;
}

///////////////////////////////////////////
// FRCPassPostProcessSelectionOutline
///////////////////////////////////////////

/**
 * Pixel shader for rendering the selection outline
 */
template<uint32 MSAASampleCount>
class FPostProcessSelectionOutlinePS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FPostProcessSelectionOutlinePS, Global);

	static bool ShouldCache(EShaderPlatform Platform)
	{
		if(!IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5))
		{
			if(MSAASampleCount > 1)
			{
				return false;
			}
		}

		return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
	}

	static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
	{
		FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
		OutEnvironment.SetDefine( TEXT("MSAA_SAMPLE_COUNT"), MSAASampleCount);
	}

	/** Default constructor. */
	FPostProcessSelectionOutlinePS() {}

public:
	FPostProcessPassParameters PostprocessParameter;
	FDeferredPixelShaderParameters DeferredParameters;
	FShaderParameter OutlineColor;
	FShaderParameter SubduedOutlineColor;
	FShaderParameter BSPSelectionIntensity;
	FShaderResourceParameter PostprocessInput1MS;
	FShaderResourceParameter EditorPrimitivesStencil;
	FShaderParameter EditorRenderParams;

	/** Initialization constructor. */
	FPostProcessSelectionOutlinePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{
		PostprocessParameter.Bind(Initializer.ParameterMap);
		DeferredParameters.Bind(Initializer.ParameterMap);
		OutlineColor.Bind(Initializer.ParameterMap, TEXT("OutlineColor"));
		SubduedOutlineColor.Bind(Initializer.ParameterMap, TEXT("SubduedOutlineColor"));
		BSPSelectionIntensity.Bind(Initializer.ParameterMap, TEXT("BSPSelectionIntensity"));
		PostprocessInput1MS.Bind(Initializer.ParameterMap, TEXT("PostprocessInput1MS"));
		EditorRenderParams.Bind(Initializer.ParameterMap, TEXT("EditorRenderParams"));
		EditorPrimitivesStencil.Bind(Initializer.ParameterMap,TEXT("EditorPrimitivesStencil"));
	}

	void SetPS(const FRenderingCompositePassContext& Context)
	{
		const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();

		FGlobalShader::SetParameters(Context.RHICmdList, ShaderRHI, Context.View);

		DeferredParameters.Set(Context.RHICmdList, ShaderRHI, Context.View);

		const FPostProcessSettings& Settings = Context.View.FinalPostProcessSettings;
		const FSceneViewFamily& ViewFamily = *(Context.View.Family);
		FSceneViewState* ViewState = (FSceneViewState*)Context.View.State;

		PostprocessParameter.SetPS(ShaderRHI, Context, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI());

		// PostprocessInput1MS and EditorPrimitivesStencil
		{
			FRenderingCompositeOutputRef* OutputRef = Context.Pass->GetInput(ePId_Input1);

			check(OutputRef);

			FRenderingCompositeOutput* Input = OutputRef->GetOutput();

			check(Input);

			TRefCountPtr<IPooledRenderTarget> InputPooledElement = Input->RequestInput();

			check(InputPooledElement);

			FTexture2DRHIRef& TargetableTexture = (FTexture2DRHIRef&)InputPooledElement->GetRenderTargetItem().TargetableTexture;

			SetTextureParameter(Context.RHICmdList, ShaderRHI, PostprocessInput1MS, TargetableTexture);

			if(EditorPrimitivesStencil.IsBound())
			{
				// cache the stencil SRV to avoid create calls each frame (the cache element is stored in the state)
				if(ViewState->SelectionOutlineCacheKey != TargetableTexture)
				{
					// release if not the right one (as the internally SRV stores a pointer to the texture we cannot get a false positive)
					ViewState->SelectionOutlineCacheKey.SafeRelease();
					ViewState->SelectionOutlineCacheValue.SafeRelease();
				}

				if(!ViewState->SelectionOutlineCacheValue)
				{
					// create if needed
					ViewState->SelectionOutlineCacheKey = TargetableTexture;
					ViewState->SelectionOutlineCacheValue = RHICreateShaderResourceView(TargetableTexture, 0, 1, PF_X24_G8);
				}

				SetSRVParameter(Context.RHICmdList, ShaderRHI, EditorPrimitivesStencil, ViewState->SelectionOutlineCacheValue);
		}
		}

#if WITH_EDITOR
		{
			FLinearColor OutlineColorValue = Context.View.SelectionOutlineColor;
			FLinearColor SubduedOutlineColorValue = Context.View.SubduedSelectionOutlineColor;
			OutlineColorValue.A = GEngine->SelectionHighlightIntensity;

			SetShaderValue(Context.RHICmdList, ShaderRHI, OutlineColor, OutlineColorValue);
			SetShaderValue(Context.RHICmdList, ShaderRHI, SubduedOutlineColor, SubduedOutlineColorValue);
			SetShaderValue(Context.RHICmdList, ShaderRHI, BSPSelectionIntensity, GEngine->BSPSelectionHighlightIntensity);
		}
#else
		check(!"This shader is not used outside of the Editor.");
#endif

		{
			static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataFloat(TEXT("r.Editor.MovingPattern"));

			FLinearColor Value(0, CVar->GetValueOnRenderThread(), 0, 0);

			if(!ViewFamily.bRealtimeUpdate)
			{
				// no animation if realtime update is disabled
				Value.G = 0;
			}

			SetShaderValue(Context.RHICmdList, ShaderRHI, EditorRenderParams, Value);
		}
	}

	// FShader interface.
	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		Ar << PostprocessParameter << OutlineColor << SubduedOutlineColor << BSPSelectionIntensity << DeferredParameters << PostprocessInput1MS << EditorPrimitivesStencil << EditorRenderParams;
		return bShaderHasOutdatedParameters;
	}

	static const TCHAR* GetSourceFilename()
	{
		return TEXT("PostProcessSelectionOutline");
	}

	static const TCHAR* GetFunctionName()
	{
		return TEXT("MainPS");
	}
};

// #define avoids a lot of code duplication
#define VARIATION1(A) typedef FPostProcessSelectionOutlinePS<A> FPostProcessSelectionOutlinePS##A; \
	IMPLEMENT_SHADER_TYPE2(FPostProcessSelectionOutlinePS##A, SF_Pixel);

VARIATION1(1)			VARIATION1(2)			VARIATION1(4)			VARIATION1(8)
#undef VARIATION1

template <uint32 MSAASampleCount>
static void SetSelectionOutlineShaderTempl(const FRenderingCompositePassContext& Context)
{
	TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
	TShaderMapRef<FPostProcessSelectionOutlinePS<MSAASampleCount> > PixelShader(Context.GetShaderMap());

	static FGlobalBoundShaderState BoundShaderState;

	SetGlobalBoundShaderState(Context.RHICmdList, Context.GetFeatureLevel(), BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);

	PixelShader->SetPS(Context);
}

void FRCPassPostProcessSelectionOutline::Process(FRenderingCompositePassContext& Context)
{
	SCOPED_DRAW_EVENT(Context.RHICmdList, PostProcessSelectionOutline);
	const FPooledRenderTargetDesc* SceneColorInputDesc = GetInputDesc(ePId_Input0);
	const FPooledRenderTargetDesc* SelectionColorInputDesc = GetInputDesc(ePId_Input1);

	if (!SceneColorInputDesc || !SelectionColorInputDesc)
	{
		// input is not hooked up correctly
		return;
	}

	const FSceneView& View = Context.View;
	FIntRect ViewRect = View.ViewRect;
	FIntPoint SrcSize = SceneColorInputDesc->Extent;

	const FSceneRenderTargetItem& DestRenderTarget = PassOutputs[0].RequestSurface(Context);

	// Set the view family's render target/viewport.
	SetRenderTarget(Context.RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef());
	Context.RHICmdList.Clear(true, FLinearColor::Black, false, (float)ERHIZBuffer::FarPlane, false, 0, ViewRect);
	Context.SetViewportAndCallRHI(ViewRect);

	// set the state
	Context.RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
	Context.RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
	Context.RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());

	const uint32 MSAASampleCount = FSceneRenderTargets::Get(Context.RHICmdList).GetEditorMSAACompositingSampleCount();

	if(MSAASampleCount == 1)
	{
		SetSelectionOutlineShaderTempl<1>(Context);
	}
	else if(MSAASampleCount == 2)
	{
		SetSelectionOutlineShaderTempl<2>(Context);
	}
	else if(MSAASampleCount == 4)
	{
		SetSelectionOutlineShaderTempl<4>(Context);
	}
	else if(MSAASampleCount == 8)
	{
		SetSelectionOutlineShaderTempl<8>(Context);
	}
	else
	{
		// not supported, internal error
		check(0);
	}

	// Draw a quad mapping scene color to the view's render target
	TShaderMapRef<FPostProcessVS> VertexShader(Context.GetShaderMap());
	DrawRectangle(
		Context.RHICmdList,
		0, 0,
		ViewRect.Width(), ViewRect.Height(),
		ViewRect.Min.X, ViewRect.Min.Y,
		ViewRect.Width(), ViewRect.Height(),
		ViewRect.Size(),
		SrcSize,
		*VertexShader,
		EDRF_UseTriangleOptimization);

	Context.RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}

FPooledRenderTargetDesc FRCPassPostProcessSelectionOutline::ComputeOutputDesc(EPassOutputId InPassOutputId) const
{
	FPooledRenderTargetDesc Ret = GetInput(ePId_Input0)->GetOutput()->RenderTargetDesc;

	Ret.DebugName = TEXT("SelectionComposited");

	return Ret;
}


text:
#ifndef TYPEDEFS_H
#define TYPEDEFS_H

#include <limits>

// Necessary workaround for Windows as VS doesn't implement C99
#ifdef _MSC_VER
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

template <typename digitT> digitT round(digitT x) { return std::floor(x + 0.5); }
#endif

typedef unsigned int NodeID;
typedef unsigned int EdgeID;
typedef int EdgeWeight;

constexpr NodeID SPECIAL_NODEID = std::numeric_limits<unsigned>::max();
constexpr EdgeID SPECIAL_EDGEID = std::numeric_limits<unsigned>::max();
constexpr unsigned INVALID_NAMEID = std::numeric_limits<unsigned>::max();
constexpr EdgeWeight INVALID_EDGE_WEIGHT = std::numeric_limits<int>::max();

#endif /* TYPEDEFS_H */


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.bookmarkswidget;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.StrictMode;
import android.support.annotation.BinderThread;
import android.support.annotation.UiThread;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

import com.google.android.apps.chrome.appwidget.bookmarks.BookmarkThumbnailWidgetProvider;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Log;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkItem;
import org.chromium.chrome.browser.bookmarks.BookmarkBridge.BookmarkModelObserver;
import org.chromium.chrome.browser.bookmarks.BookmarkModel;
import org.chromium.chrome.browser.favicon.LargeIconBridge;
import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback;
import org.chromium.chrome.browser.init.ChromeBrowserInitializer;
import org.chromium.chrome.browser.partnerbookmarks.PartnerBookmarksShim;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.util.IntentUtils;
import org.chromium.chrome.browser.widget.RoundedIconGenerator;
import org.chromium.components.bookmarks.BookmarkId;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import javax.annotation.Nullable;

/**
 * Service to support the bookmarks widget.
 *
 * This provides the list of bookmarks to show in the widget via a RemoteViewsFactory (the
 * RemoteViews equivalent of an Adapter), and updates the widget when the bookmark model changes.
 *
 * Threading note: Be careful! Android calls some methods in this class on the UI thread and others
 * on (multiple) binder threads. Additionally, all interaction with the BookmarkModel must happen on
 * the UI thread. To keep the situation clear, every non-static method is annotated with either
 * {@link UiThread} or {@link BinderThread}.
 */
public class BookmarkWidgetService extends RemoteViewsService {

    private static final String TAG = "BookmarkWidget";
    private static final String ACTION_CHANGE_FOLDER_SUFFIX = ".CHANGE_FOLDER";
    private static final String PREF_CURRENT_FOLDER = "bookmarkswidget.current_folder";
    private static final String EXTRA_FOLDER_ID = "folderId";

    @UiThread
    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        int widgetId = IntentUtils.safeGetIntExtra(intent, AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
        if (widgetId < 0) {
            Log.w(TAG, "Missing EXTRA_APPWIDGET_ID!");
            return null;
        }
        return new BookmarkAdapter(this, widgetId);
    }

    static String getChangeFolderAction(Context context) {
        return context.getPackageName() + ACTION_CHANGE_FOLDER_SUFFIX;
    }

    static SharedPreferences getWidgetState(Context context, int widgetId) {
        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
        StrictMode.allowThreadDiskWrites();
        try {
            return context.getSharedPreferences(
                    String.format("widgetState-%d", widgetId),
                    Context.MODE_PRIVATE);
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }

    static void deleteWidgetState(Context context, int widgetId) {
        SharedPreferences preferences = getWidgetState(context, widgetId);
        if (preferences != null) preferences.edit().clear().apply();
    }

    static void changeFolder(Context context, Intent intent) {
        int widgetId = IntentUtils.safeGetIntExtra(intent, AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
        String serializedFolder = IntentUtils.safeGetStringExtra(intent, EXTRA_FOLDER_ID);
        if (widgetId >= 0 && serializedFolder != null) {
            SharedPreferences prefs = getWidgetState(context, widgetId);
            prefs.edit().putString(PREF_CURRENT_FOLDER, serializedFolder).apply();
            AppWidgetManager.getInstance(context)
                    .notifyAppWidgetViewDataChanged(widgetId, R.id.bookmarks_list);
        }
    }

    /**
     * Holds data describing a bookmark or bookmark folder.
     */
    private static class Bookmark {
        public String title;
        public String url;
        public BookmarkId id;
        public BookmarkId parentId;
        public boolean isFolder;
        public Bitmap favicon;

        public static Bookmark fromBookmarkItem(BookmarkItem item) {
            if (item == null) return null;

            Bookmark bookmark = new Bookmark();
            bookmark.title = item.getTitle();
            bookmark.url = item.getUrl();
            bookmark.id = item.getId();
            bookmark.parentId = item.getParentId();
            bookmark.isFolder = item.isFolder();
            return bookmark;
        }
    }

    /**
     * Holds the list of bookmarks in a folder, as well as information about the folder itself and
     * its parent folder, if any.
     */
    private static class BookmarkFolder {
        public Bookmark folder;
        @Nullable public Bookmark parent;
        public final List<Bookmark> children = new ArrayList<>();
    }

    /**
     * Called when the BookmarkLoader has finished loading the bookmark folder.
     */
    private interface BookmarkLoaderCallback {
        @UiThread
        void onBookmarksLoaded(BookmarkFolder folder);
    }

    /**
     * Loads a BookmarkFolder asynchronously, and returns the result via BookmarkLoaderCallback.
     *
     * This class must be used only on the UI thread.
     */
    @UiThread
    private static class BookmarkLoader {
        private BookmarkLoaderCallback mCallback;
        private BookmarkFolder mFolder;
        private BookmarkModel mBookmarkModel;
        private LargeIconBridge mLargeIconBridge;
        private RoundedIconGenerator mIconGenerator;
        private int mMinIconSizeDp;
        private int mDisplayedIconSize;
        private int mCornerRadius;
        private int mRemainingTaskCount;

        BookmarkLoader(Context context, final BookmarkId folderId,
                BookmarkLoaderCallback callback) {
            mCallback = callback;

            Resources res = context.getResources();
            mLargeIconBridge = new LargeIconBridge(
                    Profile.getLastUsedProfile().getOriginalProfile());
            mMinIconSizeDp = (int) res.getDimension(R.dimen.default_favicon_min_size);
            mDisplayedIconSize = res.getDimensionPixelSize(R.dimen.default_favicon_size);
            mCornerRadius = res.getDimensionPixelSize(R.dimen.default_favicon_corner_radius);
            int textSize = res.getDimensionPixelSize(R.dimen.default_favicon_icon_text_size);
            int iconColor =
                    ApiCompatibilityUtils.getColor(res, R.color.default_favicon_background_color);
            mIconGenerator = new RoundedIconGenerator(mDisplayedIconSize, mDisplayedIconSize,
                    mCornerRadius, iconColor, textSize);

            mRemainingTaskCount = 1;
            mBookmarkModel = new BookmarkModel();
            mBookmarkModel.runAfterBookmarkModelLoaded(new Runnable() {
                @Override
                public void run() {
                    loadBookmarks(folderId);
                }
            });
        }

        private void loadBookmarks(BookmarkId folderId) {
            mFolder = new BookmarkFolder();

            // Load the requested folder if it exists. Otherwise, fall back to the default folder.
            if (folderId != null) {
                mFolder.folder = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
                        folderId));
            }
            if (mFolder.folder == null) {
                folderId = mBookmarkModel.getDefaultFolder();
                mFolder.folder = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
                        folderId));
            }

            mFolder.parent = Bookmark.fromBookmarkItem(mBookmarkModel.getBookmarkById(
                    mFolder.folder.parentId));

            List<BookmarkItem> items = mBookmarkModel.getBookmarksForFolder(folderId);

            // Move folders to the beginning of the list.
            Collections.sort(items, new Comparator<BookmarkItem>() {
                @Override
                public int compare(BookmarkItem lhs, BookmarkItem rhs) {
                    return lhs.isFolder() == rhs.isFolder() ? 0 : lhs.isFolder() ? -1 : 1;
                }
            });

            for (BookmarkItem item : items) {
                Bookmark bookmark = Bookmark.fromBookmarkItem(item);
                loadFavicon(bookmark);
                mFolder.children.add(bookmark);
            }

            taskFinished();
        }

        private void loadFavicon(final Bookmark bookmark) {
            if (bookmark.isFolder) return;

            mRemainingTaskCount++;
            LargeIconCallback callback = new LargeIconCallback() {
                @Override
                public void onLargeIconAvailable(Bitmap icon, int fallbackColor) {
                    if (icon == null) {
                        mIconGenerator.setBackgroundColor(fallbackColor);
                        icon = mIconGenerator.generateIconForUrl(bookmark.url);
                    } else {
                        icon = Bitmap.createScaledBitmap(icon, mDisplayedIconSize,
                                mDisplayedIconSize, true);
                    }
                    bookmark.favicon = icon;
                    taskFinished();
                }
            };
            mLargeIconBridge.getLargeIconForUrl(bookmark.url, mMinIconSizeDp, callback);
        }

        private void taskFinished() {
            mRemainingTaskCount--;
            if (mRemainingTaskCount == 0) {
                mCallback.onBookmarksLoaded(mFolder);
                destroy();
            }
        }

        private void destroy() {
            mBookmarkModel.destroy();
            mLargeIconBridge.destroy();
        }
    }

    /**
     * Provides the RemoteViews, one per bookmark, to be shown in the widget.
     */
    private static class BookmarkAdapter implements RemoteViewsService.RemoteViewsFactory {

        // Can be accessed on any thread
        private final Context mContext;
        private final int mWidgetId;
        private final SharedPreferences mPreferences;

        // Accessed only on the UI thread
        private BookmarkModel mBookmarkModel;

        // Accessed only on binder threads.
        private BookmarkFolder mCurrentFolder;

        @UiThread
        public BookmarkAdapter(Context context, int widgetId) {
            mContext = context;
            mWidgetId = widgetId;
            mPreferences = getWidgetState(mContext, mWidgetId);
        }

        @UiThread
        @SuppressFBWarnings("DM_EXIT")
        @Override
        public void onCreate() {
            // Required to be applied here redundantly to prevent crashes in the cases where the
            // package data is deleted or the Chrome application forced to stop.
            try {
                ChromeBrowserInitializer.getInstance(mContext).handleSynchronousStartup();
            } catch (ProcessInitException e) {
                Log.e(TAG, "Failed to start browser process.", e);
                // Since the library failed to initialize nothing in the application
                // can work, so kill the whole application not just the activity
                System.exit(-1);
            }
            if (isWidgetNewlyCreated()) {
                RecordUserAction.record("BookmarkNavigatorWidgetAdded");
            }

            // Partner bookmarks need to be loaded explicitly.
            PartnerBookmarksShim.kickOffReading(mContext);

            mBookmarkModel = new BookmarkModel();
            mBookmarkModel.addObserver(new BookmarkModelObserver() {
                @Override
                public void bookmarkModelLoaded() {
                    // Do nothing. No need to refresh.
                }

                @Override
                public void bookmarkModelChanged() {
                    refreshWidget();
                }
            });
        }

        @UiThread
        private boolean isWidgetNewlyCreated() {
            // This method relies on the fact that PREF_CURRENT_FOLDER is not yet
            // set when onCreate is called for a newly created widget.
            String serializedFolder = mPreferences.getString(PREF_CURRENT_FOLDER, null);
            return serializedFolder == null;
        }

        @UiThread
        private void refreshWidget() {
            mContext.sendBroadcast(new Intent(
                    BookmarkWidgetProvider.getBookmarkAppWidgetUpdateAction(mContext),
                    null, mContext, BookmarkThumbnailWidgetProvider.class)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId));
        }

        // ---------------------------------------------------------------- //
        // Methods below this line are called on binder threads.            //
        // ---------------------------------------------------------------- //
        // Different methods may be called on *different* binder threads,   //
        // but the system ensures that the effects of each method call will //
        // be visible before the next method is called. Thus, additional    //
        // synchronization is not needed when accessing mCurrentFolder.     //
        // ---------------------------------------------------------------- //

        @BinderThread
        @Override
        public void onDestroy() {
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mBookmarkModel != null) mBookmarkModel.destroy();
                }
            });
            deleteWidgetState(mContext, mWidgetId);
        }

        @BinderThread
        @Override
        public void onDataSetChanged() {
            updateBookmarkList();
        }

        @BinderThread
        private void updateBookmarkList() {
            BookmarkId folderId = BookmarkId
                    .getBookmarkIdFromString(mPreferences.getString(PREF_CURRENT_FOLDER, null));
            mCurrentFolder = loadBookmarks(folderId);
            mPreferences.edit().putString(PREF_CURRENT_FOLDER, mCurrentFolder.folder.id.toString())
                    .apply();
        }

        @BinderThread
        private BookmarkFolder loadBookmarks(final BookmarkId folderId) {
            final LinkedBlockingQueue<BookmarkFolder> resultQueue = new LinkedBlockingQueue<>(1);
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new BookmarkLoader(mContext, folderId, new BookmarkLoaderCallback() {
                        @Override
                        public void onBookmarksLoaded(BookmarkFolder folder) {
                            resultQueue.add(folder);
                        }
                    });
                }
            });
            try {
                return resultQueue.take();
            } catch (InterruptedException e) {
                return null;
            }
        }

        @BinderThread
        private Bookmark getBookmarkForPosition(int position) {
            if (mCurrentFolder == null) return null;

            // The position 0 is saved for an entry of the current folder used to go up.
            // This is not the case when the current node has no parent (it's the root node).
            if (mCurrentFolder.parent != null) {
                if (position == 0) return mCurrentFolder.folder;
                position--;
            }
            return mCurrentFolder.children.get(position);
        }

        @BinderThread
        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @BinderThread
        @Override
        public boolean hasStableIds() {
            return false;
        }

        @BinderThread
        @Override
        public int getCount() {
            if (mCurrentFolder == null) return 0;
            return mCurrentFolder.children.size() + (mCurrentFolder.parent != null ? 1 : 0);
        }

        @BinderThread
        @Override
        public long getItemId(int position) {
            return getBookmarkForPosition(position).id.getId();
        }

        @BinderThread
        @Override
        public RemoteViews getLoadingView() {
            return new RemoteViews(mContext.getPackageName(), R.layout.bookmark_widget_item);
        }

        @BinderThread
        @Override
        public RemoteViews getViewAt(int position) {
            if (mCurrentFolder == null) {
                Log.w(TAG, "No current folder data available.");
                return null;
            }

            Bookmark bookmark = getBookmarkForPosition(position);
            if (bookmark == null) {
                Log.w(TAG, "Couldn't get bookmark for position %d", position);
                return null;
            }

            String title = bookmark.title;
            String url = bookmark.url;
            BookmarkId id = (bookmark == mCurrentFolder.folder)
                    ? mCurrentFolder.parent.id
                    : bookmark.id;

            RemoteViews views = new RemoteViews(mContext.getPackageName(),
                    R.layout.bookmark_widget_item);

            // Set the title of the bookmark. Use the url as a backup.
            views.setTextViewText(R.id.title, TextUtils.isEmpty(title) ? url : title);

            if (bookmark == mCurrentFolder.folder) {
                views.setImageViewResource(R.id.favicon, R.drawable.back_normal);
            } else if (bookmark.isFolder) {
                views.setImageViewResource(R.id.favicon, R.drawable.bookmark_folder);
            } else {
                views.setImageViewBitmap(R.id.favicon, bookmark.favicon);
            }

            Intent fillIn;
            if (bookmark.isFolder) {
                fillIn = new Intent(getChangeFolderAction(mContext))
                        .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mWidgetId)
                        .putExtra(EXTRA_FOLDER_ID, id.toString());
            } else {
                fillIn = new Intent(Intent.ACTION_VIEW);
                if (!TextUtils.isEmpty(url)) {
                    fillIn = fillIn.addCategory(Intent.CATEGORY_BROWSABLE)
                            .setData(Uri.parse(url));
                } else {
                    fillIn = fillIn.addCategory(Intent.CATEGORY_LAUNCHER);
                }
            }
            views.setOnClickFillInIntent(R.id.list_item, fillIn);
            return views;
        }
    }
}


text:
package com.github.twostone.leaderboard.model.score;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.twostone.leaderboard.model.base.AbstractEntity;

import javax.persistence.Entity;

@SuppressWarnings("serial")
@Entity
public class PartialScore extends AbstractEntity implements Comparable<PartialScore> {
  private String name;
  private long value;

  private PartialScore() {
    super();
  }

  @JsonCreator
  public PartialScore(
      @JsonProperty("name") String name,
      @JsonProperty("value") long value) {
    this();
    this.name = name;
    this.value = value;
  }

  public String getName() {
    return this.name;
  }

  public long getValue() {
    return this.value;
  }
  public void setValue(long value) {
    this.value = value;
  }

  @Override
  public int compareTo(PartialScore o) {
    return Long.compare(this.value, o.value);
  }

}


text:
import tomviz.operators

class TestOperator(tomviz.operators.Operator):

    def transform_scalars(self, data):
        self.progress.message = 'Is there anyone out there?'


text:
package apollo.config;

import java.util.Vector;

import org.apache.log4j.*;

import apollo.datamodel.RangeI;
import apollo.datamodel.SeqFeatureI;
import apollo.datamodel.StrandedFeatureSetI;
import apollo.util.FeatureList;

/** This adapter just uses the name of the result to name the annot. In other words the
    annots are pre named. So its really not much of a name adapter. This is simpler than
    DefaultNameAdapter, and perhaps this should be Default(?). Not sure if
    SimpleNameAdapter is a good name for this - PreNamedNameAdapter?
    UseResultNameAdapter? ResultNameAdapter? ...? OneLevelNameAdapter?
    i think this is prtty much for 1 level annots*/

public class SimpleNameAdapter extends DefaultNameAdapter {

  // -----------------------------------------------------------------------
  // Class/static variables
  // -----------------------------------------------------------------------

  protected final static Logger logger = LogManager.getLogger(SimpleNameAdapter.class);

  /** Annot suffix could come from config, or even be grounds for a new name adapter.
      For now just hardwiring in - needed to differentiate annot name from result
      for commiting to chado db (violates unique constraint) */
  private static final boolean addAnnotSuffix = true;

  public String generateName(StrandedFeatureSetI annots,
                             String curation_name,
                             SeqFeatureI feature, Vector resultFeats) {
    if (resultFeats == null || resultFeats.size() == 0) {
      logger.debug("no result for SimpleNameAdapter to name annot with");
      return super.generateName(annots,curation_name,feature);
    }

    RangeI firstResult = (RangeI)resultFeats.get(0);
    // check for no name? null?
    String name = firstResult.getName();
    if (addAnnotSuffix)
      name += "-annot" + getSuffixNumber(name,annots);
    return name;
  }

  /** Return 1 + highest suffix number in use */
  private int getSuffixNumber(String resultName,StrandedFeatureSetI annots) {
    String nameRegexp = resultName+"-annot\\d+";
    // true -> regexp, true -> kidNamesOverParent
    FeatureList anns = annots.findFeaturesByAllNames(nameRegexp,true,true);
    if (anns.isEmpty())
      return 1;
    int index = resultName.length() + "-annot".length();
    int largestSuffixNumber = 0;
    for (int i=0; i<anns.size(); i++) {
      SeqFeatureI ann = anns.getFeature(i);
      String numString = ann.getName().substring(index);
      try {
        int sfxNum = Integer.valueOf(numString).intValue();
        if (sfxNum > largestSuffixNumber)
          largestSuffixNumber = sfxNum;
      } catch (NumberFormatException e) {}
    }
    return largestSuffixNumber + 1;
  }

  /** this is a workaround until we actually have 1-level annots. for annots that
      should be 1 level but still have transcripts, name the transcript with the
      gene name. the transcript name is what shows up in the main window, without
      this you would see a temp name */
  public String generateName(StrandedFeatureSetI annots,
                             String curation_name,
                             SeqFeatureI feature) {

    if (isTranscriptOfOneLevelAnnot(feature))
      return feature.getRefFeature().getName();

    return super.generateName(annots,curation_name,feature);
  }

  /** In other words is this a false transcript */
  private boolean isTranscriptOfOneLevelAnnot(SeqFeatureI feat) {
    if (!feat.isTranscript())
      return false;
    String annotType = feat.getRefFeature().getFeatureType();
    FeatureProperty fp =Config.getPropertyScheme().getFeatureProperty(annotType);
    return fp.isOneLevel();
  }

}


text:
import sys, glob, os
sys.path.insert(0, glob.glob(os.path.join(os.path.dirname(__file__),'../../lib/py/build/lib.*'))[0])

import unittest
import time
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--genpydir', type='string', dest='genpydir',
                  default='gen-py',
                  help='include this local directory in sys.path for locating generated code')
parser.add_option("--port", type="int", dest="port",
    help="connect to server at port")
parser.add_option("--host", type="string", dest="host",
    help="connect to server")
parser.add_option("--zlib", action="store_true", dest="zlib",
    help="use zlib wrapper for compressed transport")
parser.add_option("--ssl", action="store_true", dest="ssl",
    help="use SSL for encrypted transport")
parser.add_option("--http", dest="http_path",
    help="Use the HTTP transport with the specified path")
parser.add_option('-v', '--verbose', action="store_const",
    dest="verbose", const=2,
    help="verbose output")
parser.add_option('-q', '--quiet', action="store_const",
    dest="verbose", const=0,
    help="minimal output")
parser.add_option('--protocol',  dest="proto", type="string",
    help="protocol to use, one of: accel, binary, compact, json")
parser.add_option('--transport',  dest="trans", type="string",
    help="transport to use, one of: buffered, framed")
parser.set_defaults(framed=False, http_path=None, verbose=1, host='localhost', port=9090, proto='binary')
options, args = parser.parse_args()

script_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(script_dir, options.genpydir))

from ThriftTest import ThriftTest, SecondService
from ThriftTest.ttypes import *
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.transport import THttpClient
from thrift.transport import TZlibTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.protocol import TJSONProtocol

class AbstractTest(unittest.TestCase):
  def setUp(self):
    if options.http_path:
      self.transport = THttpClient.THttpClient(options.host, port=options.port, path=options.http_path)
    else:
      if options.ssl:
        from thrift.transport import TSSLSocket
        socket = TSSLSocket.TSSLSocket(options.host, options.port, validate=False)
      else:
        socket = TSocket.TSocket(options.host, options.port)
      # frame or buffer depending upon args
      self.transport = TTransport.TBufferedTransport(socket)
      if options.trans == 'framed':
        self.transport = TTransport.TFramedTransport(socket)
      elif options.trans == 'buffered':
        self.transport = TTransport.TBufferedTransport(socket)
      elif options.trans == '':
        raise AssertionError('Unknown --transport option: %s' % options.trans)
      if options.zlib:
        self.transport = TZlibTransport.TZlibTransport(self.transport, 9)
    self.transport.open()
    protocol = self.protocol_factory.getProtocol(self.transport)
    self.client = ThriftTest.Client(protocol)

  def tearDown(self):
    # Close!
    self.transport.close()

  def testVoid(self):
    self.client.testVoid()

  def testString(self):
    self.assertEqual(self.client.testString('Python' * 20), 'Python' * 20)
    self.assertEqual(self.client.testString(''), '')

  def testByte(self):
    self.assertEqual(self.client.testByte(63), 63)
    self.assertEqual(self.client.testByte(-127), -127)

  def testI32(self):
    self.assertEqual(self.client.testI32(-1), -1)
    self.assertEqual(self.client.testI32(0), 0)

  def testI64(self):
    self.assertEqual(self.client.testI64(1), 1)
    self.assertEqual(self.client.testI64(-34359738368), -34359738368)

  def testDouble(self):
    self.assertEqual(self.client.testDouble(-5.235098235), -5.235098235)
    self.assertEqual(self.client.testDouble(0), 0)
    self.assertEqual(self.client.testDouble(-1), -1)

  # TODO: def testBinary(self)	...

  def testStruct(self):
    x = Xtruct()
    x.string_thing = "Zero"
    x.byte_thing = 1
    x.i32_thing = -3
    x.i64_thing = -5
    y = self.client.testStruct(x)
    self.assertEqual(y, x)

  def testNest(self):
    inner = Xtruct(string_thing="Zero", byte_thing=1, i32_thing=-3,
      i64_thing=-5)
    x = Xtruct2(struct_thing=inner, byte_thing=0, i32_thing=0)
    y = self.client.testNest(x)
    self.assertEqual(y, x)

  def testMap(self):
    x = {0:1, 1:2, 2:3, 3:4, -1:-2}
    y = self.client.testMap(x)
    self.assertEqual(y, x)

  def testSet(self):
    x = set([8, 1, 42])
    y = self.client.testSet(x)
    self.assertEqual(y, x)

  def testList(self):
    x = [1, 4, 9, -42]
    y = self.client.testList(x)
    self.assertEqual(y, x)

  def testEnum(self):
    x = Numberz.FIVE
    y = self.client.testEnum(x)
    self.assertEqual(y, x)

  def testTypedef(self):
    x = 0xffffffffffffff # 7 bytes of 0xff
    y = self.client.testTypedef(x)
    self.assertEqual(y, x)

  def testMapMap(self):
    # does not work: dict() is not a hashable type, so a dict() cannot be used as a key in another dict()
    #x = { {1:10, 2:20}, {1:100, 2:200, 3:300}, {1:1000, 2:2000, 3:3000, 4:4000} }
    try:
      y = self.client.testMapMap()
    except:
      pass

  def testMulti(self):
    xpected = Xtruct(string_thing='Hello2', byte_thing=74, i32_thing=0xff00ff, i64_thing=0xffffffffd0d0)
    y = self.client.testMulti(xpected.byte_thing,
          xpected.i32_thing,
          xpected.i64_thing,
          { 0:'abc' },
          Numberz.FIVE,
          0xf0f0f0)
    self.assertEqual(y, xpected)

  def testException(self):
    self.client.testException('Safe')
    try:
      self.client.testException('Xception')
      self.fail("should have gotten exception")
    except Xception, x:
      self.assertEqual(x.errorCode, 1001)
      self.assertEqual(x.message, 'Xception')
      # TODO ensure same behavior for repr within generated python variants
      # ensure exception's repr method works
      #x_repr = repr(x)
      #self.assertEqual(x_repr, 'Xception(errorCode=1001, message=\'Xception\')')

    try:
      self.client.testException("throw_undeclared")
      self.fail("should have thrown exception")
    except Exception: # type is undefined
      pass

  def testOneway(self):
    start = time.time()
    self.client.testOneway(1) # type is int, not float
    end = time.time()
    self.assertTrue(end - start < 3,
                    "oneway sleep took %f sec" % (end - start))

  def testOnewayThenNormal(self):
    self.client.testOneway(1) # type is int, not float
    self.assertEqual(self.client.testString('Python'), 'Python')

class NormalBinaryTest(AbstractTest):
  protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()

class CompactTest(AbstractTest):
  protocol_factory = TCompactProtocol.TCompactProtocolFactory()

class JSONTest(AbstractTest):
  protocol_factory = TJSONProtocol.TJSONProtocolFactory()

class AcceleratedBinaryTest(AbstractTest):
  protocol_factory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()

def suite():
  suite = unittest.TestSuite()
  loader = unittest.TestLoader()
  if options.proto == 'binary': # look for --proto on cmdline
    suite.addTest(loader.loadTestsFromTestCase(NormalBinaryTest))
  elif options.proto == 'accel':
    suite.addTest(loader.loadTestsFromTestCase(AcceleratedBinaryTest))
  elif options.proto == 'compact':
    suite.addTest(loader.loadTestsFromTestCase(CompactTest))
  elif options.proto == 'json':
    suite.addTest(loader.loadTestsFromTestCase(JSONTest))
  else:
    raise AssertionError('Unknown protocol given with --protocol: %s' % options.proto)
  return suite

class OwnArgsTestProgram(unittest.TestProgram):
    def parseArgs(self, argv):
        if args:
            self.testNames = args
        else:
            self.testNames = (self.defaultTest,)
        self.createTests()

if __name__ == "__main__":
  OwnArgsTestProgram(defaultTest="suite", testRunner=unittest.TextTestRunner(verbosity=1))


text:
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Web.Template.Tests
    ( tests
    ) where

import Test.Framework
import Test.HUnit hiding (Test)

import qualified Data.Map as M

import Hakyll.Web.Page
import Hakyll.Web.Template
import Hakyll.Web.Template.Read
import TestSuite.Util

tests :: [Test]
tests = fromAssertions "applyTemplate"
    -- Hakyll templates
    [ applyTemplateAssertion readTemplate applyTemplate
        "bar" "$foo$" [("foo", "bar")]

    , applyTemplateAssertion readTemplate applyTemplate
        "$ barqux" "$$ $foo$$bar$" [("foo", "bar"), ("bar", "qux")]

    , applyTemplateAssertion readTemplate applyTemplate
        "$foo$" "$foo$" []

    -- Hamlet templates
    , applyTemplateAssertion readHamletTemplate applyTemplate
        "<title>notice</title>A paragraph"
        "\n\
        \    <title>#{title}\n\
        \\n\
        \    A paragraph\n"
        [("title", "notice")]

    -- Missing keys
    , let missing "foo" = "bar"
          missing "bar" = "qux"
          missing x     = reverse x
      in applyTemplateAssertion readTemplate (applyTemplateWith missing)
        "bar foo ver" "$foo$ $bar$ $rev$" [("bar", "foo")]
    ]

-- | Utility function to create quick template tests
--
applyTemplateAssertion :: (String -> Template)
                       -> (Template -> Page String -> Page String)
                       -> String
                       -> String
                       -> [(String, String)]
                       -> Assertion
applyTemplateAssertion parser apply expected template page =
    expected @=? pageBody (apply (parser template) (fromMap $ M.fromList page))


text:
var extend = require("extend");
var ByteBuffer = require('bytebuffer');
var bignum = require('browserify-bignum');
var timeHelper = require('../helpers/time.js');

var private = {}, self = null,
	library = null, modules = null;
private.types = {};

//constructor
function Transaction(cb, _library) {
	self = this;
	library = _library;
	cb(null, self);
}

//public methods
Transaction.prototype.create = function (data) {
	if (!private.types[data.type]) {
		throw Error('Unknown transaction type ' + data.type);
	}

	if (!data.sender) {
		throw Error("Can't find sender");
	}

	if (!data.keypair) {
		throw Error("Can't find keypair");
	}

	var trs = {
		type: data.type,
		amount: 0,
		senderId: data.sender.address,
		senderPublicKey: data.sender.publicKey,
		timestamp: timeHelper.getNow(),
		token: "XCR",
		asset: {}
	};

	trs = private.types[trs.type].create.call(self, data, trs);

	var trsBytes = self.getBytes(trs);
	trs.signature = modules.api.crypto.sign(data.keypair, trsBytes);

	trsBytes = self.getBytes(trs);
	trs.id = modules.api.crypto.getId(trsBytes);

	trs.fee = private.types[trs.type].calculateFee.call(self, trs);

	return trs;
}

Transaction.prototype.attachAssetType = function (typeId, instance) {
	if (instance && typeof instance.create == 'function' && typeof instance.getBytes == 'function' &&
		typeof instance.calculateFee == 'function' && typeof instance.verify == 'function' &&
		typeof instance.apply == 'function' && typeof instance.undo == 'function' &&
		typeof instance.applyUnconfirmed == 'function' && typeof instance.undoUnconfirmed == 'function' &&
		typeof instance.save == 'function' && typeof instance.dbRead == 'function' &&
		typeof instance.ready == 'function' && typeof instance.normalize == 'function'
	) {
		private.types[typeId] = instance;
	} else {
		throw Error('Invalid instance interface');
	}
}

Transaction.prototype.getBytes = function (trs, skipSignature) {
	if (!private.types[trs.type]) {
		throw Error('Unknown transaction type ' + trs.type);
	}

	try {
		var assetBytes = private.types[trs.type].getBytes.call(self, trs, skipSignature);
		var assetSize = assetBytes ? assetBytes.length : 0;

		var tokenBytes = [];
		if (trs.token != "XCR") {
			tokenBytes = new Buffer(trs.token, 'utf8');
		}

		var bb = new ByteBuffer(1 + 4 + 32 + 8 + 8 + 64 + 64 + assetSize + tokenBytes.length, true);
		bb.writeByte(trs.type);
		bb.writeInt(trs.timestamp);

		var senderPublicKeyBuffer = new Buffer(trs.senderPublicKey, 'hex');
		for (var i = 0; i < senderPublicKeyBuffer.length; i++) {
			bb.writeByte(senderPublicKeyBuffer[i]);
		}

		if (trs.recipientId) {
			var recipient = trs.recipientId.slice(0, -1);
			recipient = bignum(recipient).toBuffer({size: 8});

			for (var i = 0; i < 8; i++) {
				bb.writeByte(recipient[i] || 0);
			}
		} else {
			for (var i = 0; i < 8; i++) {
				bb.writeByte(0);
			}
		}

		bb.writeLong(trs.amount);

		if (tokenBytes.length > 0) {
			for (var i = 0; i < tokenBytes.length; i++) {
				bb.writeByte(tokenBytes[i]);
			}
		}

		if (assetSize > 0) {
			for (var i = 0; i < assetSize; i++) {
				bb.writeByte(assetBytes[i]);
			}
		}

		if (!skipSignature && trs.signature) {
			var signatureBuffer = new Buffer(trs.signature, 'hex');
			for (var i = 0; i < signatureBuffer.length; i++) {
				bb.writeByte(signatureBuffer[i]);
			}
		}

		bb.flip();
	} catch (e) {
		throw Error(e.toString());
	}
	return bb.toBuffer();
}

Transaction.prototype.process = function (trs, sender, cb) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	try {
		var trsBytes = self.getBytes(trs);
		var txId = modules.api.crypto.getId(trsBytes);
	} catch (e) {
		return setImmediate(cb, "Can't get transaction id");
	}
	if (trs.id && trs.id != txId) {
		return setImmediate(cb, "Invalid transaction id");
	} else {
		trs.id = txId;
	}

	modules.blockchain.transactions.getUnconfirmedTransaction(trs.id, function (err, tx) {
		if (err || tx) {
			return cb(err ? err.toString() : "This transaction in unconfirmed list already");
		}

		modules.api.transactions.getTransaction(trs.id, function (err, data) {
			if (err != "Transaction not found") {
				return cb("Can't process transaction, transaction already confirmed");
			}

			cb(null, trs);
		});
	});
}

Transaction.prototype.verifySignature = function (trs, publicKey, signature) {
	if (!private.types[trs.type]) {
		throw Error('Unknown transaction type ' + trs.type);
	}

	if (!signature) return false;

	try {
		var bytes = self.getBytes(trs, true);
		var res = modules.api.crypto.verify(publicKey, signature, bytes);
	} catch (e) {
		throw Error(e.toString());
	}

	return res;
}

Transaction.prototype.verify = function (trs, sender, cb, scope) { //inheritance
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	//check sender
	if (!sender) {
		return setImmediate(cb, "Can't find sender");
	}

	//verify signature
	try {
		var valid = self.verifySignature(trs, trs.senderPublicKey, trs.signature);
	} catch (e) {
		return setImmediate(cb, e.toString());
	}
	if (!valid) {
		return setImmediate(cb, "Can't verify transaction signature");
	}

	//check sender
	if (trs.senderId != sender.address) {
		return setImmediate(cb, "Invalid sender id: " + trs.id);
	}

	//calc fee
	var fee = private.types[trs.type].calculateFee.call(self, trs);
	if (fee === false || fee === undefined || trs.fee != fee) {
		return setImmediate(cb, "Invalid transaction type/fee: " + trs.id);
	}
	//check amount
	if (trs.amount < 0 || trs.amount > 100000000 * Math.pow(10, 8) || String(trs.amount).indexOf('.') >= 0 || trs.amount.toString().indexOf('e') >= 0) {
		return setImmediate(cb, "Invalid transaction amount: " + trs.id);
	}

	if (trs.timestamp > timeHelper.getNow()) {
		return setImmediate(cb, "Can't process transaction, it sent in feature");
	}

	private.types[trs.type].verify(trs, sender, cb, scope);
}

Transaction.prototype.ready = function (trs, sender, cb, scope) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	private.types[trs.type].ready(trs, sender, cb, scope);
}

Transaction.prototype.apply = function (trs, sender, cb, scope) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	private.types[trs.type].apply(trs, sender, cb, scope);
}

Transaction.prototype.undo = function (trs, sender, cb, scope) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	private.types[trs.type].undo(trs, sender, cb, scope);
}

Transaction.prototype.applyUnconfirmed = function (trs, sender, cb, scope) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	private.types[trs.type].applyUnconfirmed(trs, sender, cb, scope);
}

Transaction.prototype.undoUnconfirmed = function (trs, sender, cb, scope) {
	if (!private.types[trs.type]) {
		return setImmediate(cb, 'Unknown transaction type ' + trs.type);
	}

	private.types[trs.type].undoUnconfirmed(trs, sender, cb, scope);
}

Transaction.prototype.save = function (trs, cb) {
	if (!private.types[trs.type]) {
		return cb('Unknown transaction type ' + trs.type);
	}

	modules.api.sql.insert({
		table: "transactions",
		values: {
			id: trs.id,
			type: trs.type,
			timestamp: trs.timestamp,
			senderId: trs.senderId,
			senderPublicKey: trs.senderPublicKey,
			recipientId: trs.recipientId,
			amount: trs.amount,
			fee: trs.fee,
			signature: trs.signature,
			blockId: trs.blockId,
			token: trs.token == "XCR" ? null : trs.token
		}
	}, function (err) {
		if (err) {
			return cb(err);
		}
		private.types[trs.type].save(trs, cb);
	});
}

Transaction.prototype.normalize = function (tx, cb) {
	if (!private.types[tx.type]) {
		return cb('Unknown transaction type ' + tx.type);
	}

	for (var i in tx) {
		if (tx[i] === null || typeof tx[i] === 'undefined') {
			delete tx[i];
		}
	}

	library.validator.validate(tx, {
		type: "object",
		properties: {
			id: {
				type: "string"
			},
			type: {
				type: "integer"
			},
			timestamp: {
				type: "integer"
			},
			senderId: {
				type: "string"
			},
			senderPublicKey: {
				type: "string",
				format: "publicKey"
			},
			recipientId: {
				type: "string"
			},
			amount: {
				type: "integer",
				minimum: 0
			},
			fee: {
				type: "integer",
				minimum: 0
			},
			signature: {
				type: "string",
				format: "signature"
			},
			blockId: {
				type: "string"
			},
			token: {
				type: "string"
			},
			asset: {
				type: "object"
			}
		},
		required: ['id', 'type', 'timestamp', 'senderPublicKey']
	}, function (err) {
		if (err) {
			return cb(err[0].message);
		}

		private.types[tx.type].normalize.call(self, tx.asset, cb);
	});
}

Transaction.prototype.dbRead = function (row) {
	if (!row.t_id) {
		return null;
	}

	var trs = {
		id: row.t_id,
		type: row.t_type,
		timestamp: row.t_timestamp,
		senderId: row.t_senderId,
		senderPublicKey: row.t_senderPublicKey,
		recipientId: row.t_recipientId,
		amount: row.t_amount,
		fee: row.t_fee,
		signature: row.t_signature,
		blockId: row.t_blockId,
		token: row.t_token || "XCR",
		asset: {}
	};

	if (!private.types[trs.type]) {
		return cb('Unknown transaction type ' + trs.type);
	}

	var asset = private.types[trs.type].dbRead(row);
	if (asset) {
		trs.asset = extend(trs.asset, asset);
	}

	return trs;
}

Transaction.prototype.onBind = function (_modules) {
	modules = _modules;
}

//export
module.exports = Transaction;


text:
package de.intarsys.tools.converter;

/**
 * A placeholder type for creating conversions to a "canonical" type.
 *

 * Canonical conversion takes place when no explicit registered converters for
 * the types are found. The source object is converted to a canonical format,
 * after this the conversion to the target type is relaunched.
 *

 * A canonical format should have a one to one relationship to the objects of
 * the original type. i.e. given the original type, an object that is equal to
 * the original one can be constructed.
 *

 * Example

 * Date <--> milliseconds
 */
public class Canonical {

}


text:
001
018
019    package org.apache.hadoop.yarn.api.records;
020
021    import org.apache.hadoop.classification.InterfaceAudience.Private;
022    import org.apache.hadoop.classification.InterfaceAudience.Public;
023    import org.apache.hadoop.classification.InterfaceStability.Stable;
024    import org.apache.hadoop.classification.InterfaceStability.Unstable;
025    import org.apache.hadoop.yarn.util.Records;
026
027    /**
028     * Contains various scheduling metrics to be reported by UI and CLI.
029     */
030    @Public
031    @Stable
032    public abstract class ApplicationResourceUsageReport {
033
034      @Private
035      @Unstable
036      public static ApplicationResourceUsageReport newInstance(
037          int numUsedContainers, int numReservedContainers, Resource usedResources,
038          Resource reservedResources, Resource neededResources) {
039        ApplicationResourceUsageReport report =
040            Records.newRecord(ApplicationResourceUsageReport.class);
041        report.setNumUsedContainers(numUsedContainers);
042        report.setNumReservedContainers(numReservedContainers);
043        report.setUsedResources(usedResources);
044        report.setReservedResources(reservedResources);
045        report.setNeededResources(neededResources);
046        return report;
047      }
048
049      /**
050       * Get the number of used containers
051       * @return the number of used containers
052       */
053      @Public
054      @Stable
055      public abstract int getNumUsedContainers();
056
057      /**
058       * Set the number of used containers
059       * @param num_containers the number of used containers
060       */
061      @Private
062      @Unstable
063      public abstract void setNumUsedContainers(int num_containers);
064
065      /**
066       * Get the number of reserved containers
067       * @return the number of reserved containers
068       */
069      @Private
070      @Unstable
071      public abstract int getNumReservedContainers();
072
073      /**
074       * Set the number of reserved containers
075       * @param num_reserved_containers the number of reserved containers
076       */
077      @Private
078      @Unstable
079      public abstract void setNumReservedContainers(int num_reserved_containers);
080
081      /**
082       * Get the used <code>Resource</code>
083       * @return the used <code>Resource</code>
084       */
085      @Public
086      @Stable
087      public abstract Resource getUsedResources();
088
089      @Private
090      @Unstable
091      public abstract void setUsedResources(Resource resources);
092
093      /**
094       * Get the reserved <code>Resource</code>
095       * @return the reserved <code>Resource</code>
096       */
097      @Public
098      @Stable
099      public abstract Resource getReservedResources();
100
101      @Private
102      @Unstable
103      public abstract void setReservedResources(Resource reserved_resources);
104
105      /**
106       * Get the needed <code>Resource</code>
107       * @return the needed <code>Resource</code>
108       */
109      @Public
110      @Stable
111      public abstract Resource getNeededResources();
112
113      @Private
114      @Unstable
115      public abstract void setNeededResources(Resource needed_resources);
116    }


text:
public class Cat extends Animal {

	public Cat(String nome, int idade) {
		super(nome, idade);
	}

	public void falar() {
		System.out.println("O gato está miando.");
	}
}


text:
class ScumblrTask::Sketchy < ScumblrTask::Base
  def self.task_type_name
    "Sketchy Task"
  end

  def self.task_category
    "Generic"
  end

  def self.options
    return super.merge({
      :saved_result_filter=> {name: "Result Filter",
                              description: "Only screenshot results matching the given filter",
                              required: false,
                              type: :saved_result_filter
                              },
      :saved_event_filter => { name: "Event Filter",
                               description: "Only screenshot results with events matching the event filter",
                               required: false,
                               type: :saved_event_filter
                               },
      :limit_to_results_without_attachments => { name: "Limit to Results without Attachments",
                                                 description: "Only request screenshots for results with no attachments",
                                                 required: false,
                                                 type: :boolean,
                                                 default: true
                                                 },
      :status_code_only => { name: "Status Code Only",
                             description: "Have Sketchy check for status code changes without rendering a screenshot",
                             required: false,
                             type: :boolean,
                             default: false
                             }
    })
  end

  def self.description
    "Create request screenshots and/or status codes for results from Sketchy."
  end

  def self.config_options
    {:sketchy_url =>{ name: "Sketchy URL",
      description: "URL where Sketchy is deployed Example: https://sketchy.internal/api/v1.0/capture",
      required: true
      },
      :sketchy_use_ssl =>{ name: "Sketchy SSL",
      description: "Should Scumblr use SSL when connecting to Sketchy",
      required: false
      },
      :sketchy_access_token =>{ name: "Sketchy Access Token",
      description: "Access token required by Sketchy (if defined)",
      required: false
      },
      :sketchy_verify_ssl =>{ name: "Sketchy Verify SSL",
      description: "Should Scumblr verify the SSL certificate provided by Sketchy?",
      required: false
      }

    }

  end

  def initialize(options={})
    # Do setup

    @return_batched_results = false
    super
  end

  def run

    @options.each do |k,v|
      puts "Option #{k}: #{v}"
    end

    status_code_only = @options[:status_code_only] == 1 || @options[:status_code_only] == '1' || @options[:status_code_only] == true

    if(@options[:limit_to_results_without_attachments] == 1 || @options[:limit_to_results_without_attachments] == '1' || @options[:limit_to_results_without_attachments] == true)

      @results = @results.includes(:result_attachments).where('result_attachments.id is null').references(:result_attachments)
    end

    @results = @results.find_each(batch_size:10)

    result_ids = []
    @results.each do |r|
      result_ids << r.id
    end

    # puts "Result ids: #{result_ids}"
    ScreenshotSyncTaskRunner.perform_async(result_ids, status_code_only)

    return []

  end
end


text:
import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';

export default class Home extends React.Component<RouteComponentProps<{}>, {}> {
    public render() {
        return <div>

        </div>;
    }
}


text:
// LIALinkedInAuthorizationViewController.m
//
// Copyright (c) 2013 Ancientprogramming
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "LIALinkedInAuthorizationViewController.h"
#import "NSString+LIAEncode.h"

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

NSString *kLinkedInErrorDomain = @"LIALinkedInERROR";
NSString *kLinkedInDeniedByUser = @"the+user+denied+your+request";

@interface LIALinkedInAuthorizationViewController ()
@property(nonatomic, strong) UIWebView *authenticationWebView;
@property(nonatomic, copy) LIAAuthorizationCodeFailureCallback failureCallback;
@property(nonatomic, copy) LIAAuthorizationCodeSuccessCallback successCallback;
@property(nonatomic, copy) LIAAuthorizationCodeCancelCallback cancelCallback;
@property(nonatomic, strong) LIALinkedInApplication *application;
@end

@interface LIALinkedInAuthorizationViewController (UIWebViewDelegate) <UIWebViewDelegate>

@end

@implementation LIALinkedInAuthorizationViewController

BOOL handlingRedirectURL;

- (id)initWithApplication:(LIALinkedInApplication *)application success:(LIAAuthorizationCodeSuccessCallback)success cancel:(LIAAuthorizationCodeCancelCallback)cancel failure:(LIAAuthorizationCodeFailureCallback)failure {
    self = [super init];
    if (self) {
        self.application = application;
        self.successCallback = success;
        self.cancelCallback = cancel;
        self.failureCallback = failure;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

	if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {

		self.edgesForExtendedLayout = UIRectEdgeNone;
	}

	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(tappedCancelButton:)];
	self.navigationItem.leftBarButtonItem = cancelButton;

  self.authenticationWebView = [[UIWebView alloc] init];
  self.authenticationWebView.delegate = self;
  self.authenticationWebView.scalesPageToFit = YES;
  [self.view addSubview:self.authenticationWebView];
}

- (void)viewDidAppear:(BOOL)animated {
    NSString *linkedIn = [NSString stringWithFormat:@"https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%@&scope=%@&state=%@&redirect_uri=%@", self.application.clientId, self.application.grantedAccessString, self.application.state, [self.application.redirectURL LIAEncode]];
    [self.authenticationWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:linkedIn]]];
}

- (void)viewWillLayoutSubviews {
  [super viewWillLayoutSubviews];
  self.authenticationWebView.frame = self.view.bounds;
}

#pragma mark UI Action Methods

- (void)tappedCancelButton:(id)sender {
  self.cancelCallback();
}

@end

@implementation LIALinkedInAuthorizationViewController (UIWebViewDelegate)

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *url = [[request URL] absoluteString];

    //prevent loading URL if it is the redirectURL
    handlingRedirectURL = [url hasPrefix:self.application.redirectURL];

    if (handlingRedirectURL) {
        if ([url rangeOfString:@"error"].location != NSNotFound) {
            BOOL accessDenied = [url rangeOfString:kLinkedInDeniedByUser].location != NSNotFound;
            if (accessDenied) {
                self.cancelCallback();
            } else {
                NSError *error = [[NSError alloc] initWithDomain:kLinkedInErrorDomain code:1 userInfo:[[NSMutableDictionary alloc] init]];
                self.failureCallback(error);
            }
        } else {
            NSString *receivedState = [self extractGetParameter:@"state" fromURLString: url];
            //assert that the state is as we expected it to be
            if ([self.application.state isEqualToString:receivedState]) {
                //extract the code from the url
                NSString *authorizationCode = [self extractGetParameter:@"code" fromURLString: url];
                self.successCallback(authorizationCode);
            } else {
                NSError *error = [[NSError alloc] initWithDomain:kLinkedInErrorDomain code:2 userInfo:[[NSMutableDictionary alloc] init]];
                self.failureCallback(error);
            }
        }
    }
    return !handlingRedirectURL;
}

- (NSString *)extractGetParameter: (NSString *) parameterName fromURLString:(NSString *)urlString {
    NSMutableDictionary *mdQueryStrings = [[NSMutableDictionary alloc] init];
    urlString = [[urlString componentsSeparatedByString:@"?"] objectAtIndex:1];
    for (NSString *qs in [urlString componentsSeparatedByString:@"&"]) {
        [mdQueryStrings setValue:[[[[qs componentsSeparatedByString:@"="] objectAtIndex:1]
                stringByReplacingOccurrencesOfString:@"+" withString:@" "]
                stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                          forKey:[[qs componentsSeparatedByString:@"="] objectAtIndex:0]];
    }
    return [mdQueryStrings objectForKey:parameterName];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if (!handlingRedirectURL)
        self.failureCallback(error);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

	/*fix for the LinkedIn Auth window - it doesn't scale right when placed into
	 a webview inside of a form sheet modal. If we transform the HTML of the page
	 a bit, and fix the viewport to 540px (the width of the form sheet), the problem
	 is solved.
	*/
	if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
		NSString* js =
		@"var meta = document.createElement('meta'); "
		@"meta.setAttribute( 'name', 'viewport' ); "
		@"meta.setAttribute( 'content', 'width = 540px, initial-scale = 1.0, user-scalable = yes' ); "
		@"document.getElementsByTagName('head')[0].appendChild(meta)";

		[webView stringByEvaluatingJavaScriptFromString: js];
	}
}

@end