repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
---|---|---|
ivan-kyosev-gs/legend-engine | legend-engine-executionPlan-execution/src/main/java/org/finos/legend/engine/plan/execution/result/json/JsonStreamingResult.java | // Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.finos.legend.engine.plan.execution.result.json;
import com.fasterxml.jackson.core.JsonGenerator;
import org.eclipse.collections.impl.factory.Lists;
import org.finos.legend.engine.plan.execution.result.Result;
import org.finos.legend.engine.plan.execution.result.ResultVisitor;
import org.finos.legend.engine.plan.execution.result.StreamingResult;
import org.finos.legend.engine.plan.execution.result.builder.Builder;
import org.finos.legend.engine.plan.execution.result.serialization.SerializationFormat;
import org.finos.legend.engine.plan.execution.result.serialization.Serializer;
import java.util.function.Consumer;
public class JsonStreamingResult extends StreamingResult
{
private final Consumer<JsonGenerator> jsonStream;
private final Result childResult;
private final Builder builder;
@Deprecated
public JsonStreamingResult(Consumer<JsonGenerator> jsonStream)
{
this(jsonStream, null);
}
public JsonStreamingResult(Consumer<JsonGenerator> jsonStream, Result result)
{
super(Lists.mutable.empty());
this.childResult = result;
this.jsonStream = jsonStream;
this.builder = new Builder("json");
}
@Override
public <T> T accept(ResultVisitor<T> resultVisitor)
{
return resultVisitor.visit(this);
}
@Override
public Builder getResultBuilder()
{
return this.builder;
}
public Consumer<JsonGenerator> getJsonStream()
{
return jsonStream;
}
@Override
public void close()
{
if (this.childResult != null)
{
this.childResult.close();
}
}
@Override
public Serializer getSerializer(SerializationFormat format)
{
switch (format)
{
case PURE:
return new JsonStreamToPureFormatSerializer(this);
case RAW:
return new JsonStreamToPureFormatSerializer(this);
case DEFAULT:
return new JsonStreamToJsonDefaultSerializer(this);
default:
this.close();
throw new RuntimeException(format.toString() + " format not currently supported with JsonStreamingResult");
}
}
}
|
stinsonga/geo-prime-workspace | work/exampleLvDP.js | <gh_stars>0
function my_function335(){
//02134417749050445973843731917364iQnevdGdztTkeYNsnecfHtHYefkMRLwa
}
function my_function582(){
//22082324650280060759547568446288sDzocWxGbdBrrmPkwEPnhTaApdHPANoU
}
function my_function277(){
//17965697719055740664321442004531xnKaUipPSarjFsZpzwTNHxLKtOosyPGh
}
function my_function715(){
//52105001856577537634088350477923EGDaLMePudTXAflskaBQZCnIPUTmCYDo
}
function my_function942(){
//12668678106358023529468035432766bpqCrshbIfihEELaRuAwQBsDNcpKaKMX
}
function my_function656(){
//28003012977799130446426577576194HJuMiAaKOLVwxQgXicwybWtspFMZmOhX
}
function my_function192(){
//44975893687949944791945186052091wBAAxmlUEQrlzzOgTpKfGDKZafaLnWng
}
function my_function146(){
//41186340146488759266234955276018ncbHQeCdGmfKiQvMrzfxDvpkMuzgTlOh
}
function my_function878(){
//40075393332647633656118364883905QVVHvMoRSomwcTFGMIrhchprKzRwPOwc
}
function my_function894(){
//59670568032986922747921046918445RvISNzrbodXoWZlyxKdBPRTrqUNFtzQW
}
function my_function623(){
//36983926377559621545599867621775yFARwUDcPKqHIQoCSYvFNihJGWMoeysC
}
function my_function044(){
//92670872515913380264255243913773MqMOWBXHnArCFUkPErmpaTLpXLDqrxLR
}
function my_function256(){
//12996036151883462678753312939359QepbbqkQGfPrnasRfuzCBqcEQNKMbVvZ
}
function my_function451(){
//47667938397877522448074474590306BoPoSgiQoMndpqFbDIWGbaSWJbMmIwfF
}
|
fruitboy1226/cli-bak | vendor/github.com/containerd/continuity/syscallx/syscall_windows.go | <filename>vendor/github.com/containerd/continuity/syscallx/syscall_windows.go<gh_stars>100-1000
package syscallx
import (
"syscall"
"unsafe"
)
type reparseDataBuffer struct {
ReparseTag uint32
ReparseDataLength uint16
Reserved uint16
// GenericReparseBuffer
reparseBuffer byte
}
type mountPointReparseBuffer struct {
SubstituteNameOffset uint16
SubstituteNameLength uint16
PrintNameOffset uint16
PrintNameLength uint16
PathBuffer [1]uint16
}
type symbolicLinkReparseBuffer struct {
SubstituteNameOffset uint16
SubstituteNameLength uint16
PrintNameOffset uint16
PrintNameLength uint16
Flags uint32
PathBuffer [1]uint16
}
const (
_IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
_SYMLINK_FLAG_RELATIVE = 1
)
// Readlink returns the destination of the named symbolic link.
func Readlink(path string, buf []byte) (n int, err error) {
fd, err := syscall.CreateFile(syscall.StringToUTF16Ptr(path), syscall.GENERIC_READ, 0, nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_OPEN_REPARSE_POINT|syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
if err != nil {
return -1, err
}
defer syscall.CloseHandle(fd)
rdbbuf := make([]byte, syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
var bytesReturned uint32
err = syscall.DeviceIoControl(fd, syscall.FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil)
if err != nil {
return -1, err
}
rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0]))
var s string
switch rdb.ReparseTag {
case syscall.IO_REPARSE_TAG_SYMLINK:
data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
if data.Flags&_SYMLINK_FLAG_RELATIVE == 0 {
if len(s) >= 4 && s[:4] == `\??\` {
s = s[4:]
switch {
case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar
// do nothing
case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar
s = `\\` + s[4:]
default:
// unexpected; do nothing
}
} else {
// unexpected; do nothing
}
}
case _IO_REPARSE_TAG_MOUNT_POINT:
data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer))
p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0]))
s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2])
if len(s) >= 4 && s[:4] == `\??\` { // \??\C:\foo\bar
if len(s) < 48 || s[:11] != `\??\Volume{` {
s = s[4:]
}
} else {
// unexpected; do nothing
}
default:
// the path is not a symlink or junction but another type of reparse
// point
return -1, syscall.ENOENT
}
n = copy(buf, []byte(s))
return n, nil
}
|
zraees/sms-project | client/src/app/routes/ui/containers/icons/FlagIcons.js | import React from 'react'
import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../../components'
export default class FlagIcons extends React.Component {
state = {
search: ''
}
shouldComponentUpdate(nextProps, nextState) {
if (this.state.search != nextState.search) {
let $container = $(this.refs.demoContainer);
if (nextState.search) {
$(".demo-icon-font", $container).hide();
$(".demo-icon-font img", $container)
.filter(function () {
var r = new RegExp(nextState.search, 'i');
return r.test($(this).attr('class') + $(this).attr('alt'))
})
.closest(".demo-icon-font").show();
$(".alert, h2", $container).hide()
} else {
$(".demo-icon-font", $container).show();
$(".alert, h2", $container).show()
}
}
return true
}
onSearchChange = (value)=> {
this.setState({
search: value
})
}
render() {
return (
<div id="content">
<div className="row">
<BigBreadcrumbs items={['UI Elements', 'Icons', 'Flags']} icon="fa fa-fw fa-flag"
className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/>
<Stats />
</div>
{/* widget grid */}
<WidgetGrid>
<div className="well well-sm">
<div className="input-group">
<input className="form-control input-lg"
value={this.state.search}
onChange={event => this.onSearchChange(event.target.value)}
placeholder="Search for an icon..."/>
<span className="input-group-addon"><i className="fa fa-fw fa-lg fa-search"/></span>
</div>
</div>
{/* row */}
{/* row */}
<div className="row">
{/* NEW WIDGET START */}
<article className="col-sm-12">
{/* Widget ID (each widget will need unique ID)*/}
<JarvisWidget colorbutton={false} editbutton={false} togglebutton={false}
deletebutton={false} color="purple">
<header>
<h2>World Flag </h2>
</header>
{/* widget div*/}
<div>
{/* widget content */}
<div className="widget-body" ref="demoContainer">
<div className="alert alert-info">
<i className="fa fa-exclamation"/> Please note: flag images has a base class
for image <code>
flag flag-*</code>. A full example of this in use will be as follows: <code>
img class="flag flag-us"
src="img/blank.gif"</code>
</div>
<h2 >Africa</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-dz" src="assets/img/blank.gif" alt="Algeria"/>
Algeria
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ao" src="assets/img/blank.gif" alt="Angola"/>
Angola
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bj" src="assets/img/blank.gif" alt="Benin"/>
Benin
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bw" src="assets/img/blank.gif"
alt="Botswana"/> Botswana
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bf" src="assets/img/blank.gif"
alt="Burkina Faso"/> Burkina Faso
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bi" src="assets/img/blank.gif" alt="Burundi"/>
Burundi
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cm" src="assets/img/blank.gif"
alt="Cameroon"/> Cameroon
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cv" src="assets/img/blank.gif"
alt="Cape Verde"/> Cape Verde
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cf" src="assets/img/blank.gif"
alt="Central African Republic"/> Central African Republic
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-td" src="assets/img/blank.gif" alt="Chad"/>
Chad
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-km" src="assets/img/blank.gif" alt="Comoros"/>
Comoros
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cg" src="assets/img/blank.gif" alt="Congo"/>
Congo
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cd" src="assets/img/blank.gif"
alt="Congo, The Democratic Republic of the"/> Congo, The Democratic
Republic of the
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ci" src="assets/img/blank.gif"
alt="Côte d'Ivoire"/> Côte d'Ivoire
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-dj" src="assets/img/blank.gif"
alt="Djibouti"/> Djibouti
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-eg" src="assets/img/blank.gif" alt="Egypt"/>
Egypt
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gq" src="assets/img/blank.gif"
alt="Equatorial Guinea"/> Equatorial Guinea
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-er" src="assets/img/blank.gif" alt="Eritrea"/>
Eritrea
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-et" src="assets/img/blank.gif"
alt="Ethiopia"/> Ethiopia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ga" src="assets/img/blank.gif" alt="Gabon"/>
Gabon
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gm" src="assets/img/blank.gif" alt="Gambia"/>
Gambia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gh" src="assets/img/blank.gif" alt="Ghana"/>
Ghana
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gn" src="assets/img/blank.gif" alt="Guinea"/>
Guinea
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gw" src="assets/img/blank.gif"
alt="Guinea-Bissau"/> Guinea-Bissau
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ke" src="assets/img/blank.gif" alt="Kenya"/>
Kenya
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ls" src="assets/img/blank.gif" alt="Lesotho"/>
Lesotho
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lr" src="assets/img/blank.gif" alt="Liberia"/>
Liberia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ly" src="assets/img/blank.gif" alt="Libya"/>
Libya
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mg" src="assets/img/blank.gif"
alt="Madagascar"/> Madagascar
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mw" src="assets/img/blank.gif" alt="Malawi"/>
Malawi
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ml" src="assets/img/blank.gif" alt="Mali"/>
Mali
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mr" src="assets/img/blank.gif"
alt="Mauritania"/> Mauritania
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mu" src="assets/img/blank.gif"
alt="Mauritius"/> Mauritius
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-yt" src="assets/img/blank.gif" alt="Mayotte"/>
Mayotte
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ma" src="assets/img/blank.gif" alt="Morocco"/>
Morocco
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mz" src="assets/img/blank.gif"
alt="Mozambique"/> Mozambique
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-na" src="assets/img/blank.gif" alt="Namibia"/>
Namibia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ne" src="assets/img/blank.gif" alt="Niger"/>
Niger
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ng" src="assets/img/blank.gif" alt="Nigeria"/>
Nigeria
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-rw" src="assets/img/blank.gif" alt="Rwanda"/>
Rwanda
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-re" src="assets/img/blank.gif"
alt="Réunion"/> Réunion
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sh" src="assets/img/blank.gif"
alt="Saint Helena"/> Saint Helena
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-st" src="assets/img/blank.gif"
alt="Sao Tome and Principe"/> Sao Tome and Principe
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sn" src="assets/img/blank.gif" alt="Senegal"/>
Senegal
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sc" src="assets/img/blank.gif"
alt="Seychelles"/> Seychelles
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sl" src="assets/img/blank.gif"
alt="Sierra Leone"/> Sierra Leone
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-so" src="assets/img/blank.gif" alt="Somalia"/>
Somalia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-za" src="assets/img/blank.gif"
alt="South Africa"/> South Africa
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ss" src="assets/img/blank.gif"
alt="South Sudan"/> South Sudan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sd" src="assets/img/blank.gif" alt="Sudan"/>
Sudan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sz" src="assets/img/blank.gif"
alt="Swaziland"/> Swaziland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tz" src="assets/img/blank.gif"
alt="Tanzania"/> Tanzania
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tg" src="assets/img/blank.gif" alt="Togo"/>
Togo
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tn" src="assets/img/blank.gif" alt="Tunisia"/>
Tunisia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ug" src="assets/img/blank.gif" alt="Uganda"/>
Uganda
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-eh" src="assets/img/blank.gif"
alt="Western Sahara"/> Western Sahara
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-zm" src="assets/img/blank.gif" alt="Zambia"/>
Zambia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-zw" src="assets/img/blank.gif"
alt="Zimbabwe"/> Zimbabwe
</div>
</div>
<h2 >America</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ai" src="assets/img/blank.gif"
alt="Anguilla"/> Anguilla
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ag" src="assets/img/blank.gif"
alt="Antigua and Barbuda"/> Antigua and Barbuda
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ar" src="assets/img/blank.gif"
alt="Argentina"/> Argentina
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-aw" src="assets/img/blank.gif" alt="Aruba"/>
Aruba
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bs" src="assets/img/blank.gif" alt="Bahamas"/>
Bahamas
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bb" src="assets/img/blank.gif"
alt="Barbados"/> Barbados
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bz" src="assets/img/blank.gif" alt="Belize"/>
Belize
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bm" src="assets/img/blank.gif" alt="Bermuda"/>
Bermuda
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bo" src="assets/img/blank.gif"
alt="Bolivia, Plurinational State of"/> Bolivia, Plurinational
State of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-br" src="assets/img/blank.gif" alt="Brazil"/>
Brazil
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ca" src="assets/img/blank.gif" alt="Canada"/>
Canada
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ky" src="assets/img/blank.gif"
alt="Cayman Islands"/> Cayman Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cl" src="assets/img/blank.gif" alt="Chile"/>
Chile
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-co" src="assets/img/blank.gif"
alt="Colombia"/> Colombia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cr" src="assets/img/blank.gif"
alt="Costa Rica"/> Costa Rica
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cu" src="assets/img/blank.gif" alt="Cuba"/>
Cuba
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cw" src="assets/img/blank.gif"
alt="Curaçao"/> Curaçao
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-dm" src="assets/img/blank.gif"
alt="Dominica"/> Dominica
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-do" src="assets/img/blank.gif"
alt="Dominican Republic"/> Dominican Republic
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ec" src="assets/img/blank.gif" alt="Ecuador"/>
Ecuador
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sv" src="assets/img/blank.gif"
alt="El Salvador"/> El Salvador
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fk" src="assets/img/blank.gif"
alt="Falkland Islands (Malvinas)"/> Falkland Islands (Malvinas)
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gf" src="assets/img/blank.gif"
alt="French Guiana"/> French Guiana
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gl" src="assets/img/blank.gif"
alt="Greenland"/> Greenland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gd" src="assets/img/blank.gif" alt="Grenada"/>
Grenada
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gp" src="assets/img/blank.gif"
alt="Guadeloupe"/> Guadeloupe
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gt" src="assets/img/blank.gif"
alt="Guatemala"/> Guatemala
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gy" src="assets/img/blank.gif" alt="Guyana"/>
Guyana
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ht" src="assets/img/blank.gif" alt="Haiti"/>
Haiti
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-hn" src="assets/img/blank.gif"
alt="Honduras"/> Honduras
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-jm" src="assets/img/blank.gif" alt="Jamaica"/>
Jamaica
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mq" src="assets/img/blank.gif"
alt="Martinique"/> Martinique
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mx" src="assets/img/blank.gif" alt="Mexico"/>
Mexico
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ms" src="assets/img/blank.gif"
alt="Montserrat"/> Montserrat
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-an" src="assets/img/blank.gif"
alt="Netherlands Antilles"/> Netherlands Antilles
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ni" src="assets/img/blank.gif"
alt="Nicaragua"/> Nicaragua
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pa" src="assets/img/blank.gif" alt="Panama"/>
Panama
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-py" src="assets/img/blank.gif"
alt="Paraguay"/> Paraguay
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pe" src="assets/img/blank.gif" alt="Peru"/>
Peru
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pr" src="assets/img/blank.gif"
alt="Puerto Rico"/> Puerto Rico
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kn" src="assets/img/blank.gif"
alt="Saint Kitts and Nevis"/> Saint Kitts and Nevis
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lc" src="assets/img/blank.gif"
alt="Saint Lucia"/> Saint Lucia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pm" src="assets/img/blank.gif"
alt="Saint Pierre and Miquelon"/> Saint Pierre and Miquelon
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-vc" src="assets/img/blank.gif"
alt="Saint Vincent and the Grenadines"/> Saint Vincent and the
Grenadines
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sx" src="assets/img/blank.gif"
alt="Sint Maarten"/> Sint Maarten
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sr" src="assets/img/blank.gif"
alt="Suriname"/> Suriname
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tt" src="assets/img/blank.gif"
alt="Trinidad and Tobago"/> Trinidad and Tobago
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tc" src="assets/img/blank.gif"
alt="Turks and Caicos Islands"/> Turks and Caicos Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-us" src="assets/img/blank.gif"
alt="United States"/> United States
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-uy" src="assets/img/blank.gif" alt="Uruguay"/>
Uruguay
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ve" src="assets/img/blank.gif"
alt="Venezuela, Bolivarian Republic of"/> Venezuela, Bolivarian
Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-vg" src="assets/img/blank.gif"
alt="Virgin Islands, British"/> Virgin Islands, British
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-vi" src="assets/img/blank.gif"
alt="Virgin Islands, U.S."/> Virgin Islands, U.S.
</div>
</div>
<h2 >Asia</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-af" src="assets/img/blank.gif"
alt="Afghanistan"/> Afghanistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-am" src="assets/img/blank.gif" alt="Armenia"/>
Armenia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-az" src="assets/img/blank.gif"
alt="Azerbaijan"/> Azerbaijan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bh" src="assets/img/blank.gif" alt="Bahrain"/>
Bahrain
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bd" src="assets/img/blank.gif"
alt="Bangladesh"/> Bangladesh
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bt" src="assets/img/blank.gif" alt="Bhutan"/>
Bhutan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bn" src="assets/img/blank.gif"
alt="Brunei Darussalam"/> Brunei Darussalam
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kh" src="assets/img/blank.gif"
alt="Cambodia"/> Cambodia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cn" src="assets/img/blank.gif" alt="China"/>
China
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cy" src="assets/img/blank.gif" alt="Cyprus"/>
Cyprus
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ge" src="assets/img/blank.gif" alt="Georgia"/>
Georgia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-hk" src="assets/img/blank.gif"
alt="Hong Kong"/> Hong Kong
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-in" src="assets/img/blank.gif" alt="India"/>
India
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-id" src="assets/img/blank.gif"
alt="Indonesia"/> Indonesia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ir" src="assets/img/blank.gif"
alt="Iran, Islamic Republic of"/> Iran, Islamic Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-iq" src="assets/img/blank.gif" alt="Iraq"/>
Iraq
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-il" src="assets/img/blank.gif" alt="Israel"/>
Israel
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-jp" src="assets/img/blank.gif" alt="Japan"/>
Japan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-jo" src="assets/img/blank.gif" alt="Jordan"/>
Jordan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kz" src="assets/img/blank.gif"
alt="Kazakhstan"/> Kazakhstan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kp" src="assets/img/blank.gif"
alt="Korea, Democratic People's Republic of"/> Korea, Democratic
People's Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kr" src="assets/img/blank.gif"
alt="Korea, Republic of"/> Korea, Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kw" src="assets/img/blank.gif" alt="Kuwait"/>
Kuwait
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kg" src="assets/img/blank.gif"
alt="Kyrgyzstan"/> Kyrgyzstan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-la" src="assets/img/blank.gif"
alt="Lao People's Democratic Republic"/> Lao People's Democratic
Republic
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lb" src="assets/img/blank.gif" alt="Lebanon"/>
Lebanon
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mo" src="assets/img/blank.gif" alt="Macao"/>
Macao
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-my" src="assets/img/blank.gif"
alt="Malaysia"/> Malaysia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mv" src="assets/img/blank.gif"
alt="Maldives"/> Maldives
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mn" src="assets/img/blank.gif"
alt="Mongolia"/> Mongolia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mm" src="assets/img/blank.gif" alt="Myanmar"/>
Myanmar
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-np" src="assets/img/blank.gif" alt="Nepal"/>
Nepal
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-om" src="assets/img/blank.gif" alt="Oman"/>
Oman
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pk" src="assets/img/blank.gif"
alt="Pakistan"/> Pakistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ps" src="assets/img/blank.gif"
alt="Palestinian Territory, Occupied"/> Palestinian Territory,
Occupied
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ph" src="assets/img/blank.gif"
alt="Philippines"/> Philippines
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-qa" src="assets/img/blank.gif" alt="Qatar"/>
Qatar
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sa" src="assets/img/blank.gif"
alt="Saudi Arabia"/> Saudi Arabia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sg" src="assets/img/blank.gif"
alt="Singapore"/> Singapore
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lk" src="assets/img/blank.gif"
alt="Sri Lanka"/> Sri Lanka
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sy" src="assets/img/blank.gif"
alt="Syrian Arab Republic"/> Syrian Arab Republic
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tw" src="assets/img/blank.gif"
alt="Taiwan, Province of China"/> Taiwan, Province of China
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tj" src="assets/img/blank.gif"
alt="Tajikistan"/> Tajikistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-th" src="assets/img/blank.gif"
alt="Thailand"/> Thailand
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tl" src="assets/img/blank.gif"
alt="Timor-Leste"/> Timor-Leste
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tr" src="assets/img/blank.gif" alt="Turkey"/>
Turkey
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tm" src="assets/img/blank.gif"
alt="Turkmenistan"/> Turkmenistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ae" src="assets/img/blank.gif"
alt="United Arab Emirates"/> United Arab Emirates
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-uz" src="assets/img/blank.gif"
alt="Uzbekistan"/> Uzbekistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-vn" src="assets/img/blank.gif"
alt="Viet Nam"/> Viet Nam
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ye" src="assets/img/blank.gif" alt="Yemen"/>
Yemen
</div>
</div>
<h2 >Australia and Oceania</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-as" src="assets/img/blank.gif"
alt="American Samoa"/> American Samoa
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-au" src="assets/img/blank.gif"
alt="Australia"/> Australia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ck" src="assets/img/blank.gif"
alt="Cook Islands"/> Cook Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fj" src="assets/img/blank.gif" alt="Fiji"/>
Fiji
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pf" src="assets/img/blank.gif"
alt="French Polynesia"/> French Polynesia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gu" src="assets/img/blank.gif" alt="Guam"/>
Guam
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ki" src="assets/img/blank.gif"
alt="Kiribati"/> Kiribati
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mh" src="assets/img/blank.gif"
alt="Marshall Islands"/> Marshall Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fm" src="assets/img/blank.gif"
alt="Micronesia, Federated States of"/> Micronesia, Federated
States of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nr" src="assets/img/blank.gif" alt="Nauru"/>
Nauru
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nc" src="assets/img/blank.gif"
alt="New Caledonia"/> New Caledonia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nz" src="assets/img/blank.gif"
alt="New Zealand"/> New Zealand
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nu" src="assets/img/blank.gif" alt="Niue"/>
Niue
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nf" src="assets/img/blank.gif"
alt="Norfolk Island"/> Norfolk Island
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mp" src="assets/img/blank.gif"
alt="Northern Mariana Islands"/> Northern Mariana Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pw" src="assets/img/blank.gif" alt="Palau"/>
Palau
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pg" src="assets/img/blank.gif"
alt="Papua New Guinea"/> Papua New Guinea
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pn" src="assets/img/blank.gif"
alt="Pitcairn"/> Pitcairn
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ws" src="assets/img/blank.gif" alt="Samoa"/>
Samoa
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sb" src="assets/img/blank.gif"
alt="Solomon Islands"/> Solomon Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tk" src="assets/img/blank.gif" alt="Tokelau"/>
Tokelau
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-to" src="assets/img/blank.gif" alt="Tonga"/>
Tonga
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tv" src="assets/img/blank.gif" alt="Tuvalu"/>
Tuvalu
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-vu" src="assets/img/blank.gif" alt="Vanuatu"/>
Vanuatu
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-wf" src="assets/img/blank.gif"
alt="Wallis and Futuna"/> Wallis and Futuna
</div>
</div>
<h2 >Europe</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-al" src="assets/img/blank.gif" alt="Albania"/>
Albania
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ad" src="assets/img/blank.gif" alt="Andorra"/>
Andorra
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-at" src="assets/img/blank.gif" alt="Austria"/>
Austria
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-by" src="assets/img/blank.gif" alt="Belarus"/>
Belarus
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-be" src="assets/img/blank.gif" alt="Belgium"/>
Belgium
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ba" src="assets/img/blank.gif"
alt="Bosnia and Herzegovina"/> Bosnia and Herzegovina
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bg" src="assets/img/blank.gif"
alt="Bulgaria"/> Bulgaria
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-hr" src="assets/img/blank.gif" alt="Croatia"/>
Croatia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-cz" src="assets/img/blank.gif"
alt="Czech Republic"/> Czech Republic
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-dk" src="assets/img/blank.gif" alt="Denmark"/>
Denmark
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ee" src="assets/img/blank.gif" alt="Estonia"/>
Estonia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fo" src="assets/img/blank.gif"
alt="Faroe Islands"/> Faroe Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fi" src="assets/img/blank.gif" alt="Finland"/>
Finland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-fr" src="assets/img/blank.gif" alt="France"/>
France
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-de" src="assets/img/blank.gif" alt="Germany"/>
Germany
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gi" src="assets/img/blank.gif"
alt="Gibraltar"/> Gibraltar
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gr" src="assets/img/blank.gif" alt="Greece"/>
Greece
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-va" src="assets/img/blank.gif"
alt="Holy See (Vatican City State)"/> Holy See (Vatican City State)
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-hu" src="assets/img/blank.gif" alt="Hungary"/>
Hungary
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-is" src="assets/img/blank.gif" alt="Iceland"/>
Iceland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ie" src="assets/img/blank.gif" alt="Ireland"/>
Ireland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-it" src="assets/img/blank.gif" alt="Italy"/>
Italy
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lv" src="assets/img/blank.gif" alt="Latvia"/>
Latvia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-li" src="assets/img/blank.gif"
alt="Liechtenstein"/> Liechtenstein
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lt" src="assets/img/blank.gif"
alt="Lithuania"/> Lithuania
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-lu" src="assets/img/blank.gif"
alt="Luxembourg"/> Luxembourg
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mk" src="assets/img/blank.gif"
alt="Macedonia, The Former Yugoslav Republic of"/> Macedonia, The
Former Yugoslav Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mt" src="assets/img/blank.gif" alt="Malta"/>
Malta
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-md" src="assets/img/blank.gif"
alt="Moldova, Republic of"/> Moldova, Republic of
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-mc" src="assets/img/blank.gif" alt="Monaco"/>
Monaco
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-me" src="assets/img/blank.gif"
alt="Montenegro"/> Montenegro
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-nl" src="assets/img/blank.gif"
alt="Netherlands"/> Netherlands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-no" src="assets/img/blank.gif" alt="Norway"/>
Norway
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pl" src="assets/img/blank.gif" alt="Poland"/>
Poland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-pt" src="assets/img/blank.gif"
alt="Portugal"/> Portugal
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ro" src="assets/img/blank.gif" alt="Romania"/>
Romania
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ru" src="assets/img/blank.gif"
alt="Russian Federation"/> Russian Federation
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sm" src="assets/img/blank.gif"
alt="San Marino"/> San Marino
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-rs" src="assets/img/blank.gif" alt="Serbia"/>
Serbia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-sk" src="assets/img/blank.gif"
alt="Slovakia"/> Slovakia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-si" src="assets/img/blank.gif"
alt="Slovenia"/> Slovenia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-es" src="assets/img/blank.gif" alt="Spain"/>
Spain
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-se" src="assets/img/blank.gif" alt="Sweden"/>
Sweden
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ch" src="assets/img/blank.gif"
alt="Switzerland"/> Switzerland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ua" src="assets/img/blank.gif" alt="Ukraine"/>
Ukraine
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gb" src="assets/img/blank.gif"
alt="United Kingdom"/> United Kingdom
</div>
</div>
<h2 >Other areas</h2>
<div className="row">
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-bv" src="assets/img/blank.gif"
alt="Bouvet Island"/> Bouvet Island
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-io" src="assets/img/blank.gif"
alt="British Indian Ocean Territory"/> British Indian Ocean
Territory
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-ic" src="assets/img/blank.gif"
alt="Canary Islands"/> Canary Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-catalonia" src="assets/img/blank.gif"
alt="Catalonia"/> Catalonia
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-england" src="assets/img/blank.gif"
alt="England"/> England
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-eu" src="assets/img/blank.gif"
alt="European Union"/> European Union
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-tf" src="assets/img/blank.gif"
alt="French Southern Territories"/> French Southern Territories
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gg" src="assets/img/blank.gif"
alt="Guernsey"/> Guernsey
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-hm" src="assets/img/blank.gif"
alt="Heard Island and McDonald Islands"/> Heard Island and McDonald
Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-im" src="assets/img/blank.gif"
alt="Isle of Man"/> Isle of Man
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-je" src="assets/img/blank.gif" alt="Jersey"/>
Jersey
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-kurdistan" src="assets/img/blank.gif"
alt="Kurdistan"/> Kurdistan
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-scotland" src="assets/img/blank.gif"
alt="Scotland"/> Scotland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-somaliland" src="assets/img/blank.gif"
alt="Somaliland"/> Somaliland
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-gs" src="assets/img/blank.gif"
alt="South Georgia and the South Sandwich Islands"/> South Georgia
and the South Sandwich Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-um" src="assets/img/blank.gif"
alt="United States Minor Outlying Islands"/> United States Minor
Outlying Islands
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-wales" src="assets/img/blank.gif"
alt="Wales"/> Wales
</div>
<div className="col-xs-6 col-md-3 col-sm-4 demo-icon-font">
<img className="flag flag-zanzibar" src="assets/img/blank.gif"
alt="Zanzibar"/> Zanzibar
</div>
</div>
</div>
{/* end widget content */}
</div>
{/* end widget div */}
</JarvisWidget>
{/* end widget */}
</article>
{/* WIDGET END */}
</div>
</WidgetGrid>
</div>
)
}
} |
ducnm98/howdyapp | src/components/SpeakingMatchingItem/SpeakingMatchingItem.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Popup from '../Popup';
import RequestForm from '../RequestForm';
import Link from '../Link';
import s from './SpeakingMatchingItem.css';
class SpeakingMatchingItem extends React.Component {
constructor(props) {
super(props);
this.state = { isOpen: false };
};
openPopup = () => {
this.setState({
isOpen: true
});
};
closePopup = () => {
this.setState({
isOpen: false
});
};
render() {
const model = this.props.model;
return (
<div className="grid grid_3">
<div className={s.hoverItem}>
<div className="nicdark_section">
<div className="nicdark_section nicdark_position_relative" style={{ height: '266px' }}>
<img alt="" className="nicdark_section"
src={`${model.avatar}`}
/>
</div>
<div className="nicdark_section nicdark_padding_20 nicdark_box_sizing_border_box">
<h2><strong>{model.displayName}</strong></h2>
<div className="nicdark_section nicdark_height_10"></div>
{/* <h6 className="nicdark_text_transform_uppercase nicdark_color_grey">Food Teacher</h6> */}
<div className="nicdark_section nicdark_height_20"></div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean egestas magna at porttitor vehicula.
</p>
<div className="nicdark_section nicdark_height_20"></div>
<div className="nicdark_width_50_percentage nicdark_width_50_percentage_all_iphone nicdark_float_right nicdark_text_align_right">
<button className="nicdark_display_inline_block nicdark_border_2_solid_green nicdark_color_white nicdark_color_green_hover nicdark_bg_white_hover nicdark_bg_green nicdark_first_font nicdark_padding_8 nicdark_border_radius_3 nicdark_font_size_13 nicdark_float_right " onClick={this.openPopup}>
<NAME>
</button>
<Popup show={this.state.isOpen}>
<RequestForm onClose={this.closePopup}></RequestForm>
</Popup>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default withStyles(s)(SpeakingMatchingItem)
|
ABinLin/framework-boot | framework-boot-util/src/main/java/com/farerboy/framework/boot/util/encryption/Md5Util.java | <reponame>ABinLin/framework-boot
package com.farerboy.framework.boot.util.encryption;
import com.farerboy.framework.boot.util.AssertUtil;
import com.farerboy.framework.boot.util.ByteUtil;
import com.farerboy.framework.boot.util.encryption.exception.EncryptionException;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* MD5 加密
* @author farerboy
*/
public class Md5Util {
public static final String MD5 = "MD5";
public static final String HMACMD5 = "HMACMD5";
private static String toHexString(byte[] byteArray) {
AssertUtil.notEmpty(byteArray,"Md5 to hex string param byte array can not be null !");
final StringBuilder hexString = new StringBuilder();
for (int i = 0; i < byteArray.length; i++) {
//0~F前面不零
if ((byteArray[i] & 0xff) < 0x10){
hexString.append("0");
}
hexString.append(Integer.toHexString(0xFF & byteArray[i]));
}
return hexString.toString();
}
private static String encodeToString(byte[] encodeBytes,boolean upperCase){
String md5 = toHexString(encodeBytes);
if(upperCase){
md5 = md5.toUpperCase();
}
return md5;
}
public static String encodeToString(String content){
return encodeToString(content,false);
}
public static String encodeToString(String content,boolean upperCase){
byte[] encodeBytes = encode(content);
return encodeToString(encodeBytes,upperCase);
}
public static String encodeToString(String content, String key){
return encodeToString(content,key,false);
}
public static String encodeToString(String content, String key,boolean upperCase) {
byte[] encodeBytes = encode(content,key);
return encodeToString(encodeBytes,upperCase);
}
public static byte[] encode(byte[] contentBytes){
MessageDigest md ;
try {
md = MessageDigest.getInstance(MD5);
}catch (NoSuchAlgorithmException e){
throw new EncryptionException("NoSuchAlgorithmException",e);
}
return md.digest(contentBytes);
}
public static byte[] encode(String content) {
return encode(ByteUtil.getByte(content));
}
public static byte[] encode(byte[] contentBytes,String key){
try {
SecretKey sk = null;
if (key == null) {
KeyGenerator kg = KeyGenerator.getInstance(HMACMD5);
sk = kg.generateKey();
} else {
byte[] keyBytes = ByteUtil.getByte(key);
sk = new SecretKeySpec(keyBytes, HMACMD5);
}
Mac mac = Mac.getInstance(HMACMD5);
mac.init(sk);
byte[] result = mac.doFinal(contentBytes);
return result;
}catch (NoSuchAlgorithmException e){
throw new EncryptionException("NoSuchAlgorithmException",e);
}catch (InvalidKeyException e) {
throw new EncryptionException("InvalidKeyException",e);
}
}
public static byte[] encode(String content, String key) {
return encode(ByteUtil.getByte(content),key);
}
}
|
agnesnatasya/Be-Tree | server/main.cpp | // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
#include <pthread.h>
#include <sched.h>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <csignal>
#include <numa.h>
#include "network/configuration.hpp"
#include "network/fasttransport.hpp"
#include "common/gflags.hpp"
#include "storage_server.hpp"
#include <boost/thread/thread.hpp>
using namespace std;
void server_thread_func(StorageServerApp *storageApp,
network::Configuration config,
uint8_t numa_node, uint8_t thread_id) {
std::string local_uri = config.GetServerAddress(FLAGS_serverIndex).host;
// TODO: provide mapping function from thread_id to numa_node
// for now assume it's round robin
// TODO: get rid of the hardcoded number of request types
//int ht_ct = boost::thread::hardware_concurrency();
network::FastTransport *transport = new network::FastTransport(config,
local_uri,
//FLAGS_numServerThreads,
1,
//ht_ct,
4,
0,
numa_node,
thread_id);
// last_transport = transport;
StorageServer *ss = new StorageServer(
config, FLAGS_serverIndex,
(network::FastTransport *)transport,
storageApp);
transport->Run();
}
//void signal_handler( int signal_num ) {
// last_transport->Stop();
// last_replica->PrintStats();
// global_server->PrintStats();
//
// // terminate program
// exit(signal_num);
//}
int
main(int argc, char **argv)
{
// signal(SIGINT, signal_handler);
gflags::ParseCommandLineFlags(&argc, &argv, true);
if (FLAGS_configFile == "") {
fprintf(stderr, "option --configFile is required\n");
return EXIT_FAILURE;
}
// if (FLAGS_keysFile == "") {
// fprintf(stderr, "option --keysFile is required\n");
// return EXIT_FAILURE;
// }
if (FLAGS_serverIndex == -1) {
fprintf(stderr, "option --serverIndex is required\n");
return EXIT_FAILURE;
}
// Load configuration
std::ifstream configStream(FLAGS_configFile);
if (configStream.fail()) {
fprintf(stderr, "unable to read configuration file: %s\n", FLAGS_configFile.c_str());
}
network::Configuration config(configStream);
if (FLAGS_serverIndex >= config.n) {
fprintf(stderr, "server index %d is out of bounds; "
"only %d servers defined\n", FLAGS_serverIndex, config.n);
}
// create replica threads
// bind round robin on the availlable numa nodes
if (numa_available() == -1) {
PPanic("NUMA library not available.");
}
//int nn_ct = numa_max_node() + 1;
//int ht_ct = boost::thread::hardware_concurrency()/boost::thread::physical_concurrency(); // number of hyperthreads
// TODO: start the app on all available cores to regulate frequency boosting
// int ht_ct = boost::thread::hardware_concurrency();
// std::vector<std::thread> thread_arr(FLAGS_numServerThreads);
// std::vector<std::thread> thread_arr(ht_ct);
std::vector<std::thread> thread_arr(1);
StorageServerApp *storageApp = new StorageServerApp();
// for (uint8_t i = 0; i < FLAGS_numServerThreads; i++) {
// for (uint8_t i = 0; i < ht_ct; i++) {
for (uint8_t i = 0; i < 1; i++) {
// thread_arr[i] = std::thread(server_thread_func, server, config, i%nn_ct, i);
// erpc::bind_to_core(thread_arr[i], i%nn_ct, i/nn_ct);
// uint8_t numa_node = (i % 4 < 2)?0:1;
// uint8_t idx = i/4 + (i % 2) * 20;
uint8_t numa_node = 0;
uint8_t idx = i;
thread_arr[i] = std::thread(server_thread_func, storageApp, config, numa_node, i);
// TODO: erpc:bind_to_core causes Bus Errors
//erpc::bind_to_core(thread_arr[i], numa_node, idx);
}
for (auto &thread : thread_arr) thread.join();
return 0;
}
|
meashishsaini/BOW | docs/html/search/functions_4.js | var searchData=
[
['dataresetter',['DataResetter',['../_b_o_w-a_01film_01guessing_01game_8cpp.html#a48d94754ebff71d662296b454681612f',1,'BOW-a film guessing game.cpp']]],
['datasorter',['DataSorter',['../_b_o_w-a_01film_01guessing_01game_8cpp.html#a844b65907b85d1b68843603a3d530f46',1,'BOW-a film guessing game.cpp']]]
];
|
pulumi/pulumi-mongodbatlas | sdk/go/mongodbatlas/getLdapVerify.go | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package mongodbatlas
import (
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// `LdapVerify` describes a LDAP Verify.
//
// > **NOTE:** Groups and projects are synonymous terms. You may find **group_id** in the official documentation.
func LookupLdapVerify(ctx *pulumi.Context, args *LookupLdapVerifyArgs, opts ...pulumi.InvokeOption) (*LookupLdapVerifyResult, error) {
var rv LookupLdapVerifyResult
err := ctx.Invoke("mongodbatlas:index/getLdapVerify:getLdapVerify", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
// A collection of arguments for invoking getLdapVerify.
type LookupLdapVerifyArgs struct {
// Unique identifier for the Atlas project associated with the verification request.
ProjectId string `pulumi:"projectId"`
// Unique identifier of a request to verify an LDAP configuration.
RequestId string `pulumi:"requestId"`
}
// A collection of values returned by getLdapVerify.
type LookupLdapVerifyResult struct {
// The user DN that Atlas uses to connect to the LDAP server.
BindUsername string `pulumi:"bindUsername"`
// (Required) The hostname or IP address of the LDAP server.
Hostname string `pulumi:"hostname"`
// The provider-assigned unique ID for this managed resource.
Id string `pulumi:"id"`
// One or more links to sub-resources. The relations in the URLs are explained in the Web Linking Specification.
Links []GetLdapVerifyLink `pulumi:"links"`
// LDAP ConfigurationThe port to which the LDAP server listens for client connections.
Port int `pulumi:"port"`
ProjectId string `pulumi:"projectId"`
// The unique identifier for the request to verify the LDAP over TLS/SSL configuration.
RequestId string `pulumi:"requestId"`
// The current status of the LDAP over TLS/SSL configuration.
Status string `pulumi:"status"`
// Array of validation messages related to the verification of the provided LDAP over TLS/SSL configuration details.
Validations []GetLdapVerifyValidation `pulumi:"validations"`
}
|
scbedd/azure-sdk-for-node | lib/services/batchaiManagement/lib/models/nodeSetup.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Node setup settings.
*
*/
class NodeSetup {
/**
* Create a NodeSetup.
* @member {object} [setupTask] Setup task. Setup task to run on cluster
* nodes when nodes got created or rebooted. The setup task code needs to be
* idempotent. Generally the setup task is used to download static data that
* is required for all jobs that run on the cluster VMs and/or to
* download/install software.
* @member {string} [setupTask.commandLine] The command line to be executed
* on each cluster's node after it being allocated or rebooted. The command
* is executed in a bash subshell as a root.
* @member {array} [setupTask.environmentVariables] A collection of user
* defined environment variables to be set for setup task.
* @member {array} [setupTask.secrets] A collection of user defined
* environment variables with secret values to be set for the setup task.
* Server will never report values of these variables back.
* @member {string} [setupTask.stdOutErrPathPrefix] The prefix of a path
* where the Batch AI service will upload the stdout, stderr and execution
* log of the setup task.
* @member {string} [setupTask.stdOutErrPathSuffix] A path segment appended
* by Batch AI to stdOutErrPathPrefix to form a path where stdout, stderr and
* execution log of the setup task will be uploaded. Batch AI creates the
* setup task output directories under an unique path to avoid conflicts
* between different clusters. The full path can be obtained by concatenation
* of stdOutErrPathPrefix and stdOutErrPathSuffix.
* @member {object} [mountVolumes] Mount volumes. Mount volumes to be
* available to setup task and all jobs executing on the cluster. The volumes
* will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT
* environment variable.
* @member {array} [mountVolumes.azureFileShares] A collection of Azure File
* Shares that are to be mounted to the cluster nodes.
* @member {array} [mountVolumes.azureBlobFileSystems] A collection of Azure
* Blob Containers that are to be mounted to the cluster nodes.
* @member {array} [mountVolumes.fileServers] A collection of Batch AI File
* Servers that are to be mounted to the cluster nodes.
* @member {array} [mountVolumes.unmanagedFileSystems] A collection of
* unmanaged file systems that are to be mounted to the cluster nodes.
* @member {object} [performanceCountersSettings] Performance counters
* settings. Settings for performance counters collecting and uploading.
* @member {object} [performanceCountersSettings.appInsightsReference] Azure
* Application Insights information for performance counters reporting. If
* provided, Batch AI will upload node performance counters to the
* corresponding Azure Application Insights account.
* @member {object}
* [performanceCountersSettings.appInsightsReference.component] Azure
* Application Insights component resource ID.
* @member {string}
* [performanceCountersSettings.appInsightsReference.component.id] The ID of
* the resource
* @member {string}
* [performanceCountersSettings.appInsightsReference.instrumentationKey]
* Value of the Azure Application Insights instrumentation key.
* @member {object}
* [performanceCountersSettings.appInsightsReference.instrumentationKeySecretReference]
* KeyVault Store and Secret which contains Azure Application Insights
* instrumentation key. One of instrumentationKey or
* instrumentationKeySecretReference must be specified.
* @member {object}
* [performanceCountersSettings.appInsightsReference.instrumentationKeySecretReference.sourceVault]
* Fully qualified resource indentifier of the Key Vault.
* @member {string}
* [performanceCountersSettings.appInsightsReference.instrumentationKeySecretReference.sourceVault.id]
* The ID of the resource
* @member {string}
* [performanceCountersSettings.appInsightsReference.instrumentationKeySecretReference.secretUrl]
* The URL referencing a secret in the Key Vault.
*/
constructor() {
}
/**
* Defines the metadata of NodeSetup
*
* @returns {object} metadata of NodeSetup
*
*/
mapper() {
return {
required: false,
serializedName: 'NodeSetup',
type: {
name: 'Composite',
className: 'NodeSetup',
modelProperties: {
setupTask: {
required: false,
serializedName: 'setupTask',
type: {
name: 'Composite',
className: 'SetupTask'
}
},
mountVolumes: {
required: false,
serializedName: 'mountVolumes',
type: {
name: 'Composite',
className: 'MountVolumes'
}
},
performanceCountersSettings: {
required: false,
serializedName: 'performanceCountersSettings',
type: {
name: 'Composite',
className: 'PerformanceCountersSettings'
}
}
}
}
};
}
}
module.exports = NodeSetup;
|
YegorKozlov/acs-aem-commons | bundle/src/test/java/com/adobe/acs/commons/remoteassets/impl/RemoteAssetsTestUtil.java | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2019 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.remoteassets.impl;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.commons.io.IOUtils;
import org.apache.sling.serviceusermapping.impl.MappingConfigAmendment;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class RemoteAssetsTestUtil {
public static final String TEST_SERVER_URL = "https://remote-aem-server:4502";
public static final String TEST_SERVER_USERNAME = "admin";
public static final String TEST_SERVER_PASSWORD = "<PASSWORD>";
public static final String TEST_TAGS_PATH_A = "/etc/tags/a";
public static final String TEST_TAGS_PATH_B = "/etc/tags/b";
public static final String TEST_DAM_PATH_A = "/content/dam/a";
public static final String TEST_DAM_PATH_B = "/content/dam/b";
public static final int TEST_RETRY_DELAY = 30;
public static final int TEST_SAVE_INTERVAL = 500;
public static final String TEST_WHITELISTED_SVC_USER_A = "user_a";
public static final String TEST_WHITELISTED_SVC_USER_B = "user_b";
public static byte[] getBytes(InputStream inputStream) throws IOException {
byte[] fileBytes = null;
try {
fileBytes = IOUtils.toByteArray(inputStream);
} finally {
inputStream.close();
}
return fileBytes;
}
public static byte[] getPlaceholderAsset(String fileExt) throws IOException {
return getBytes(ClassLoader.getSystemResourceAsStream("remoteassets/remote_asset." + fileExt));
}
public static Map<String, Object> getRemoteAssetsConfigs() {
Map<String, Object> remoteAssetsConfigs = new HashMap<>();
remoteAssetsConfigs.put("server.url", TEST_SERVER_URL);
remoteAssetsConfigs.put("server.user", TEST_SERVER_USERNAME);
remoteAssetsConfigs.put("server.pass", TEST_SERVER_PASSWORD);
remoteAssetsConfigs.put("server.insecure", false);
remoteAssetsConfigs.put("tag.paths", new String[]{TEST_TAGS_PATH_A, "", TEST_TAGS_PATH_B});
remoteAssetsConfigs.put("dam.paths", new String[]{TEST_DAM_PATH_A, "", TEST_DAM_PATH_B});
remoteAssetsConfigs.put("retry.delay", TEST_RETRY_DELAY);
remoteAssetsConfigs.put("save.interval", TEST_SAVE_INTERVAL);
remoteAssetsConfigs.put("whitelisted.service.users", new String[]{TEST_WHITELISTED_SVC_USER_A, "", TEST_WHITELISTED_SVC_USER_B});
return remoteAssetsConfigs;
}
public static void setupRemoteAssetsServiceUser(AemContext context) {
Map<String, Object> serviceUserMapperConfig = new HashMap<>();
serviceUserMapperConfig.put("user.mapping", context.bundleContext().getBundle().getSymbolicName() + ":remote-assets=acs-commons-remote-assets-service");
context.registerInjectActivateService(new MappingConfigAmendment(), serviceUserMapperConfig);
}
}
|
therealjgrant/frontity | packages/connect/src/connect.js | <reponame>therealjgrant/frontity
import {
useState,
useEffect,
useMemo,
memo,
useRef,
createContext,
useContext,
} from "react";
import { warn } from "@frontity/error";
import { observe, unobserve } from "@frontity/observer-util";
const COMPONENT = Symbol("owner component");
/**
* A React context that stores the store of Frontity Connect.
*/
const context = createContext({});
/**
* The Provider of the store context, to be used in the root of the React
* application.
*/
export const Provider = context.Provider;
/**
* A flag to know when a connected component is being rendered.
*/
let isConnected = false;
/**
* The default options of connect.
*/
const defaultOptions = {
/**
* Define if `connect` should inject the store props in the component, or only
* make it reactive. Useful when the store is accessed via `useConnect` and
* the props are passed down an HTML node.
*/
injectProps: true,
};
/**
* Connect a React component with the Frontity connect store and make it
* reactive to its changes.
*
* @param Comp - The React component to be connected.
* @param options - The connect options, defined in {@link defaultOptions}.
*
* @returns The same Component, but reactive and with the store included in the
* props.
*/
export function connect(Comp, options) {
const isFunctionalComp = !(Comp.prototype && Comp.prototype.isReactComponent);
options = options ? { ...defaultOptions, ...options } : defaultOptions;
let ReactiveComp;
if (isFunctionalComp) {
// Use a hook based reactive wrapper.
ReactiveComp = (props) => {
// Dummy setState to update the component.
const [, setState] = useState();
// Use a ref to store the reaction because we want to do some annotations.
const reaction = useRef();
// Create a memoized reactive wrapper of the original component (render)
// at the very first run of the component function.
const render = useMemo(
() => {
reaction.current = observe(Comp, {
scheduler: () => {
// Trigger a new rerender if the component has already been
// mounted.
if (reaction.current.mounted) setState({});
// Annotate it as "changed" if the component has not been mounted
// yet.
else reaction.current.changedBeforeMounted = true;
},
lazy: true,
});
// Initialize a flag to know if the component was finally mounted.
reaction.current.mounted = false;
// Initialize a flag to know if the was reaction was invalidated
// before the component was mounted.
reaction.current.changedBeforeMounted = false;
return reaction.current;
},
// Adding the original Comp here is necessary to make HMR work. It does
// not affect behavior otherwise.
// eslint-disable-next-line react-hooks/exhaustive-deps
[Comp]
);
useEffect(() => {
// Mark the component as mounted.
reaction.current.mounted = true;
// If there was a change before the component was mounted, trigger a
// new rerender.
if (reaction.current.changedBeforeMounted) setState({});
// Cleanup the reactive connections when the component is unmounted.
return () => unobserve(reaction.current);
}, []);
// Extract the Frontity store from the context.
const { state, actions, libraries } = useContext(context);
// The isConnected flag is used to warn users that try to use `useConnect`
// in a non-connected component.
isConnected = true;
try {
// Run the reactive render instead of the original one and inject the
// props if necessary.
return render({
...props,
...(options.injectProps && state && { state }),
...(options.injectProps && actions && { actions }),
...(options.injectProps && libraries && { libraries }),
});
} finally {
isConnected = false;
}
};
} else {
/**
* Wrap the component to extract the store from the context and pass it
* down to the final component. Also, make the render method reactive.
*/
class ReactiveClassComp extends Comp {
/**
* Initialize the wrapper.
*
* @param props - The props passed to the original component.
* @param context - The React context.
*/
constructor(props, context) {
super(props, context);
// Create some state to be able to rerender the component later.
this.state = this.state || {};
this.state[COMPONENT] = this;
// Make the render method reactive.
this.render = observe(this.render, {
scheduler: () => this.setState({}),
lazy: true,
});
}
/**
* The render method of this React Class.
*
* @returns The same Component but with the store injected as props.
*/
render() {
const { state, actions, libraries } = this.context;
const props = { ...this.props, state, actions, libraries };
return <Comp {...props} />;
}
/**
* React should trigger updates on prop changes, while handles
* store changes.
*
* @param nextProps - The props of the next render.
* @param nextState - The state of the next render.
* @returns Whether the component should rerender or not.
*/
shouldComponentUpdate(nextProps, nextState) {
const { props, state } = this;
// Respect the case when the user defines a shouldComponentUpdate.
if (super.shouldComponentUpdate) {
return super.shouldComponentUpdate(nextProps, nextState);
}
// Return true if it is a reactive render or the state changes.
if (state !== nextState) {
return true;
}
// The component should also update if any of its props shallowly
// changed value.
const keys = Object.keys(props);
const nextKeys = Object.keys(nextProps);
return (
nextKeys.length !== keys.length ||
nextKeys.some((key) => props[key] !== nextProps[key])
);
}
/**
* Remove the reaction when the component is unmounted.
*/
componentWillUnmount() {
// Call user defined componentWillUnmount.
if (super.componentWillUnmount) {
super.componentWillUnmount();
}
// Clean up memory used.
unobserve(this.render);
}
}
// Attach the context and pass the compnent up.
ReactiveClassComp.contextType = context;
ReactiveComp = ReactiveClassComp;
}
// Make sure we display the correct name.
ReactiveComp.displayName = Comp.displayName || Comp.name;
// Static props are inherited by class components, but have to be copied for
// function components.
if (isFunctionalComp) {
Object.keys(Comp).forEach((key) => {
ReactiveComp[key] = Comp[key];
});
}
return isFunctionalComp ? memo(ReactiveComp) : ReactiveComp;
}
/**
* React hook that returns the Frontity store in connected components.
*
* @returns The Frontity store (state, actions, libraries...).
*/
export const useConnect = () => {
if (!isConnected)
warn(
"Warning: useConnect() is being used in a non connected component, " +
"therefore the component won't update on state changes. " +
"Please wrap your component with connect().\n"
);
return useContext(context);
};
|
william-xian/rap | src/mail/rap_mail_ssl_module.c |
/*
* Copyright (C) <NAME>
* Copyright (C) Rap, Inc.
*/
#include <rap_config.h>
#include <rap_core.h>
#include <rap_mail.h>
#define RAP_DEFAULT_CIPHERS "HIGH:!aNULL:!MD5"
#define RAP_DEFAULT_ECDH_CURVE "auto"
static void *rap_mail_ssl_create_conf(rap_conf_t *cf);
static char *rap_mail_ssl_merge_conf(rap_conf_t *cf, void *parent, void *child);
static char *rap_mail_ssl_enable(rap_conf_t *cf, rap_command_t *cmd,
void *conf);
static char *rap_mail_ssl_starttls(rap_conf_t *cf, rap_command_t *cmd,
void *conf);
static char *rap_mail_ssl_password_file(rap_conf_t *cf, rap_command_t *cmd,
void *conf);
static char *rap_mail_ssl_session_cache(rap_conf_t *cf, rap_command_t *cmd,
void *conf);
static rap_conf_enum_t rap_mail_starttls_state[] = {
{ rap_string("off"), RAP_MAIL_STARTTLS_OFF },
{ rap_string("on"), RAP_MAIL_STARTTLS_ON },
{ rap_string("only"), RAP_MAIL_STARTTLS_ONLY },
{ rap_null_string, 0 }
};
static rap_conf_bitmask_t rap_mail_ssl_protocols[] = {
{ rap_string("SSLv2"), RAP_SSL_SSLv2 },
{ rap_string("SSLv3"), RAP_SSL_SSLv3 },
{ rap_string("TLSv1"), RAP_SSL_TLSv1 },
{ rap_string("TLSv1.1"), RAP_SSL_TLSv1_1 },
{ rap_string("TLSv1.2"), RAP_SSL_TLSv1_2 },
{ rap_string("TLSv1.3"), RAP_SSL_TLSv1_3 },
{ rap_null_string, 0 }
};
static rap_conf_enum_t rap_mail_ssl_verify[] = {
{ rap_string("off"), 0 },
{ rap_string("on"), 1 },
{ rap_string("optional"), 2 },
{ rap_string("optional_no_ca"), 3 },
{ rap_null_string, 0 }
};
static rap_conf_deprecated_t rap_mail_ssl_deprecated = {
rap_conf_deprecated, "ssl", "listen ... ssl"
};
static rap_command_t rap_mail_ssl_commands[] = {
{ rap_string("ssl"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_FLAG,
rap_mail_ssl_enable,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, enable),
&rap_mail_ssl_deprecated },
{ rap_string("starttls"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_mail_ssl_starttls,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, starttls),
rap_mail_starttls_state },
{ rap_string("ssl_certificate"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_array_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, certificates),
NULL },
{ rap_string("ssl_certificate_key"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_array_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, certificate_keys),
NULL },
{ rap_string("ssl_password_file"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_mail_ssl_password_file,
RAP_MAIL_SRV_CONF_OFFSET,
0,
NULL },
{ rap_string("ssl_dhparam"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, dhparam),
NULL },
{ rap_string("ssl_ecdh_curve"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, ecdh_curve),
NULL },
{ rap_string("ssl_protocols"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_1MORE,
rap_conf_set_bitmask_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, protocols),
&rap_mail_ssl_protocols },
{ rap_string("ssl_ciphers"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, ciphers),
NULL },
{ rap_string("ssl_prefer_server_ciphers"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_FLAG,
rap_conf_set_flag_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, prefer_server_ciphers),
NULL },
{ rap_string("ssl_session_cache"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE12,
rap_mail_ssl_session_cache,
RAP_MAIL_SRV_CONF_OFFSET,
0,
NULL },
{ rap_string("ssl_session_tickets"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_FLAG,
rap_conf_set_flag_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, session_tickets),
NULL },
{ rap_string("ssl_session_ticket_key"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_array_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, session_ticket_keys),
NULL },
{ rap_string("ssl_session_timeout"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_sec_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, session_timeout),
NULL },
{ rap_string("ssl_verify_client"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_enum_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, verify),
&rap_mail_ssl_verify },
{ rap_string("ssl_verify_depth"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_num_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, verify_depth),
NULL },
{ rap_string("ssl_client_certificate"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, client_certificate),
NULL },
{ rap_string("ssl_trusted_certificate"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, trusted_certificate),
NULL },
{ rap_string("ssl_crl"),
RAP_MAIL_MAIN_CONF|RAP_MAIL_SRV_CONF|RAP_CONF_TAKE1,
rap_conf_set_str_slot,
RAP_MAIL_SRV_CONF_OFFSET,
offsetof(rap_mail_ssl_conf_t, crl),
NULL },
rap_null_command
};
static rap_mail_module_t rap_mail_ssl_module_ctx = {
NULL, /* protocol */
NULL, /* create main configuration */
NULL, /* init main configuration */
rap_mail_ssl_create_conf, /* create server configuration */
rap_mail_ssl_merge_conf /* merge server configuration */
};
rap_module_t rap_mail_ssl_module = {
RAP_MODULE_V1,
&rap_mail_ssl_module_ctx, /* module context */
rap_mail_ssl_commands, /* module directives */
RAP_MAIL_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
RAP_MODULE_V1_PADDING
};
static rap_str_t rap_mail_ssl_sess_id_ctx = rap_string("MAIL");
static void *
rap_mail_ssl_create_conf(rap_conf_t *cf)
{
rap_mail_ssl_conf_t *scf;
scf = rap_pcalloc(cf->pool, sizeof(rap_mail_ssl_conf_t));
if (scf == NULL) {
return NULL;
}
/*
* set by rap_pcalloc():
*
* scf->listen = 0;
* scf->protocols = 0;
* scf->dhparam = { 0, NULL };
* scf->ecdh_curve = { 0, NULL };
* scf->client_certificate = { 0, NULL };
* scf->trusted_certificate = { 0, NULL };
* scf->crl = { 0, NULL };
* scf->ciphers = { 0, NULL };
* scf->shm_zone = NULL;
*/
scf->enable = RAP_CONF_UNSET;
scf->starttls = RAP_CONF_UNSET_UINT;
scf->certificates = RAP_CONF_UNSET_PTR;
scf->certificate_keys = RAP_CONF_UNSET_PTR;
scf->passwords = RAP_CONF_UNSET_PTR;
scf->prefer_server_ciphers = RAP_CONF_UNSET;
scf->verify = RAP_CONF_UNSET_UINT;
scf->verify_depth = RAP_CONF_UNSET_UINT;
scf->builtin_session_cache = RAP_CONF_UNSET;
scf->session_timeout = RAP_CONF_UNSET;
scf->session_tickets = RAP_CONF_UNSET;
scf->session_ticket_keys = RAP_CONF_UNSET_PTR;
return scf;
}
static char *
rap_mail_ssl_merge_conf(rap_conf_t *cf, void *parent, void *child)
{
rap_mail_ssl_conf_t *prev = parent;
rap_mail_ssl_conf_t *conf = child;
char *mode;
rap_pool_cleanup_t *cln;
rap_conf_merge_value(conf->enable, prev->enable, 0);
rap_conf_merge_uint_value(conf->starttls, prev->starttls,
RAP_MAIL_STARTTLS_OFF);
rap_conf_merge_value(conf->session_timeout,
prev->session_timeout, 300);
rap_conf_merge_value(conf->prefer_server_ciphers,
prev->prefer_server_ciphers, 0);
rap_conf_merge_bitmask_value(conf->protocols, prev->protocols,
(RAP_CONF_BITMASK_SET|RAP_SSL_TLSv1
|RAP_SSL_TLSv1_1|RAP_SSL_TLSv1_2));
rap_conf_merge_uint_value(conf->verify, prev->verify, 0);
rap_conf_merge_uint_value(conf->verify_depth, prev->verify_depth, 1);
rap_conf_merge_ptr_value(conf->certificates, prev->certificates, NULL);
rap_conf_merge_ptr_value(conf->certificate_keys, prev->certificate_keys,
NULL);
rap_conf_merge_ptr_value(conf->passwords, prev->passwords, NULL);
rap_conf_merge_str_value(conf->dhparam, prev->dhparam, "");
rap_conf_merge_str_value(conf->ecdh_curve, prev->ecdh_curve,
RAP_DEFAULT_ECDH_CURVE);
rap_conf_merge_str_value(conf->client_certificate,
prev->client_certificate, "");
rap_conf_merge_str_value(conf->trusted_certificate,
prev->trusted_certificate, "");
rap_conf_merge_str_value(conf->crl, prev->crl, "");
rap_conf_merge_str_value(conf->ciphers, prev->ciphers, RAP_DEFAULT_CIPHERS);
conf->ssl.log = cf->log;
if (conf->listen) {
mode = "listen ... ssl";
} else if (conf->enable) {
mode = "ssl";
} else if (conf->starttls != RAP_MAIL_STARTTLS_OFF) {
mode = "starttls";
} else {
return RAP_CONF_OK;
}
if (conf->file == NULL) {
conf->file = prev->file;
conf->line = prev->line;
}
if (conf->certificates == NULL) {
rap_log_error(RAP_LOG_EMERG, cf->log, 0,
"no \"ssl_certificate\" is defined for "
"the \"%s\" directive in %s:%ui",
mode, conf->file, conf->line);
return RAP_CONF_ERROR;
}
if (conf->certificate_keys == NULL) {
rap_log_error(RAP_LOG_EMERG, cf->log, 0,
"no \"ssl_certificate_key\" is defined for "
"the \"%s\" directive in %s:%ui",
mode, conf->file, conf->line);
return RAP_CONF_ERROR;
}
if (conf->certificate_keys->nelts < conf->certificates->nelts) {
rap_log_error(RAP_LOG_EMERG, cf->log, 0,
"no \"ssl_certificate_key\" is defined "
"for certificate \"%V\" and "
"the \"%s\" directive in %s:%ui",
((rap_str_t *) conf->certificates->elts)
+ conf->certificates->nelts - 1,
mode, conf->file, conf->line);
return RAP_CONF_ERROR;
}
if (rap_ssl_create(&conf->ssl, conf->protocols, NULL) != RAP_OK) {
return RAP_CONF_ERROR;
}
cln = rap_pool_cleanup_add(cf->pool, 0);
if (cln == NULL) {
rap_ssl_cleanup_ctx(&conf->ssl);
return RAP_CONF_ERROR;
}
cln->handler = rap_ssl_cleanup_ctx;
cln->data = &conf->ssl;
if (rap_ssl_certificates(cf, &conf->ssl, conf->certificates,
conf->certificate_keys, conf->passwords)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
if (conf->verify) {
if (conf->client_certificate.len == 0 && conf->verify != 3) {
rap_log_error(RAP_LOG_EMERG, cf->log, 0,
"no ssl_client_certificate for ssl_verify_client");
return RAP_CONF_ERROR;
}
if (rap_ssl_client_certificate(cf, &conf->ssl,
&conf->client_certificate,
conf->verify_depth)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
if (rap_ssl_trusted_certificate(cf, &conf->ssl,
&conf->trusted_certificate,
conf->verify_depth)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
if (rap_ssl_crl(cf, &conf->ssl, &conf->crl) != RAP_OK) {
return RAP_CONF_ERROR;
}
}
if (rap_ssl_ciphers(cf, &conf->ssl, &conf->ciphers,
conf->prefer_server_ciphers)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
if (rap_ssl_dhparam(cf, &conf->ssl, &conf->dhparam) != RAP_OK) {
return RAP_CONF_ERROR;
}
if (rap_ssl_ecdh_curve(cf, &conf->ssl, &conf->ecdh_curve) != RAP_OK) {
return RAP_CONF_ERROR;
}
rap_conf_merge_value(conf->builtin_session_cache,
prev->builtin_session_cache, RAP_SSL_NONE_SCACHE);
if (conf->shm_zone == NULL) {
conf->shm_zone = prev->shm_zone;
}
if (rap_ssl_session_cache(&conf->ssl, &rap_mail_ssl_sess_id_ctx,
conf->certificates, conf->builtin_session_cache,
conf->shm_zone, conf->session_timeout)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
rap_conf_merge_value(conf->session_tickets,
prev->session_tickets, 1);
#ifdef SSL_OP_NO_TICKET
if (!conf->session_tickets) {
SSL_CTX_set_options(conf->ssl.ctx, SSL_OP_NO_TICKET);
}
#endif
rap_conf_merge_ptr_value(conf->session_ticket_keys,
prev->session_ticket_keys, NULL);
if (rap_ssl_session_ticket_keys(cf, &conf->ssl, conf->session_ticket_keys)
!= RAP_OK)
{
return RAP_CONF_ERROR;
}
return RAP_CONF_OK;
}
static char *
rap_mail_ssl_enable(rap_conf_t *cf, rap_command_t *cmd, void *conf)
{
rap_mail_ssl_conf_t *scf = conf;
char *rv;
rv = rap_conf_set_flag_slot(cf, cmd, conf);
if (rv != RAP_CONF_OK) {
return rv;
}
if (scf->enable && (rap_int_t) scf->starttls > RAP_MAIL_STARTTLS_OFF) {
rap_conf_log_error(RAP_LOG_EMERG, cf, 0,
"\"starttls\" directive conflicts with \"ssl on\"");
return RAP_CONF_ERROR;
}
if (!scf->listen) {
scf->file = cf->conf_file->file.name.data;
scf->line = cf->conf_file->line;
}
return RAP_CONF_OK;
}
static char *
rap_mail_ssl_starttls(rap_conf_t *cf, rap_command_t *cmd, void *conf)
{
rap_mail_ssl_conf_t *scf = conf;
char *rv;
rv = rap_conf_set_enum_slot(cf, cmd, conf);
if (rv != RAP_CONF_OK) {
return rv;
}
if (scf->enable == 1 && (rap_int_t) scf->starttls > RAP_MAIL_STARTTLS_OFF) {
rap_conf_log_error(RAP_LOG_EMERG, cf, 0,
"\"ssl\" directive conflicts with \"starttls\"");
return RAP_CONF_ERROR;
}
if (!scf->listen) {
scf->file = cf->conf_file->file.name.data;
scf->line = cf->conf_file->line;
}
return RAP_CONF_OK;
}
static char *
rap_mail_ssl_password_file(rap_conf_t *cf, rap_command_t *cmd, void *conf)
{
rap_mail_ssl_conf_t *scf = conf;
rap_str_t *value;
if (scf->passwords != RAP_CONF_UNSET_PTR) {
return "is duplicate";
}
value = cf->args->elts;
scf->passwords = rap_ssl_read_password_file(cf, &value[1]);
if (scf->passwords == NULL) {
return RAP_CONF_ERROR;
}
return RAP_CONF_OK;
}
static char *
rap_mail_ssl_session_cache(rap_conf_t *cf, rap_command_t *cmd, void *conf)
{
rap_mail_ssl_conf_t *scf = conf;
size_t len;
rap_str_t *value, name, size;
rap_int_t n;
rap_uint_t i, j;
value = cf->args->elts;
for (i = 1; i < cf->args->nelts; i++) {
if (rap_strcmp(value[i].data, "off") == 0) {
scf->builtin_session_cache = RAP_SSL_NO_SCACHE;
continue;
}
if (rap_strcmp(value[i].data, "none") == 0) {
scf->builtin_session_cache = RAP_SSL_NONE_SCACHE;
continue;
}
if (rap_strcmp(value[i].data, "builtin") == 0) {
scf->builtin_session_cache = RAP_SSL_DFLT_BUILTIN_SCACHE;
continue;
}
if (value[i].len > sizeof("builtin:") - 1
&& rap_strncmp(value[i].data, "builtin:", sizeof("builtin:") - 1)
== 0)
{
n = rap_atoi(value[i].data + sizeof("builtin:") - 1,
value[i].len - (sizeof("builtin:") - 1));
if (n == RAP_ERROR) {
goto invalid;
}
scf->builtin_session_cache = n;
continue;
}
if (value[i].len > sizeof("shared:") - 1
&& rap_strncmp(value[i].data, "shared:", sizeof("shared:") - 1)
== 0)
{
len = 0;
for (j = sizeof("shared:") - 1; j < value[i].len; j++) {
if (value[i].data[j] == ':') {
break;
}
len++;
}
if (len == 0) {
goto invalid;
}
name.len = len;
name.data = value[i].data + sizeof("shared:") - 1;
size.len = value[i].len - j - 1;
size.data = name.data + len + 1;
n = rap_parse_size(&size);
if (n == RAP_ERROR) {
goto invalid;
}
if (n < (rap_int_t) (8 * rap_pagesize)) {
rap_conf_log_error(RAP_LOG_EMERG, cf, 0,
"session cache \"%V\" is too small",
&value[i]);
return RAP_CONF_ERROR;
}
scf->shm_zone = rap_shared_memory_add(cf, &name, n,
&rap_mail_ssl_module);
if (scf->shm_zone == NULL) {
return RAP_CONF_ERROR;
}
scf->shm_zone->init = rap_ssl_session_cache_init;
continue;
}
goto invalid;
}
if (scf->shm_zone && scf->builtin_session_cache == RAP_CONF_UNSET) {
scf->builtin_session_cache = RAP_SSL_NO_BUILTIN_SCACHE;
}
return RAP_CONF_OK;
invalid:
rap_conf_log_error(RAP_LOG_EMERG, cf, 0,
"invalid session cache \"%V\"", &value[i]);
return RAP_CONF_ERROR;
}
|
ZhuoZhuoCrayon/AcousticKeyBoard-Web | apps/keyboard/handler/common.py | <filename>apps/keyboard/handler/common.py
# -*- coding: utf-8 -*-
import logging
from typing import Any, Dict, List
from celery.result import AsyncResult
from django.utils.translation import ugettext_lazy as _
from djangocli.constants import LogModule
logger = logging.getLogger(LogModule.APPS)
class CommonHandler:
@staticmethod
def batch_celery_results(task_ids: str) -> List[Dict[str, Any]]:
celery_results = []
for task_id in task_ids:
task_info_obj = AsyncResult(task_id)
celery_result = {
"date_done": task_info_obj.date_done,
"task_id": task_info_obj.task_id,
"result": task_info_obj.result,
"status": task_info_obj.status,
"state": task_info_obj.state,
}
# Exception不能被序列化
if isinstance(celery_result["result"], Exception):
celery_result["result"] = str(celery_result["result"])
celery_results.append(celery_result)
logger.info(
_("task_id -> {task_id}, celery_result -> {celery_result}").format(
task_id=task_id, celery_result=celery_result
)
)
return celery_results
|
gustavo-mendel/my-college-projects | accs-programacao-basica/lista5/E6.cpp | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int mat[n][n];
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
cin >> mat[i][j];
}
}
int harry = 0, rony = 0;
int x, y;
cin >> x >> y;
for (int i=0; i<n; i++) {
harry += mat[x][i];
rony += mat[i][y];
}
if (x == y) {
harry -= mat[x][y];
}
else if (y > x) {
harry -= mat[x][y];
}
else {
rony -= mat[x][y];
}
cout << "Harry " << harry << endl;
cout << "Ron " << rony << endl;
}
|
gauravl612/Insights | PlatformService/src/main/java/com/cognizant/devops/platformservice/rest/querycaching/service/QueryCachingConstants.java | <reponame>gauravl612/Insights<filename>PlatformService/src/main/java/com/cognizant/devops/platformservice/rest/querycaching/service/QueryCachingConstants.java
/*******************************************************************************
* Copyright 2017 Cognizant Technology Solutions
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.cognizant.devops.platformservice.rest.querycaching.service;
import com.cognizant.devops.platformcommons.config.ApplicationConfigProvider;
public interface QueryCachingConstants {
String ES_HOST = ApplicationConfigProvider.getInstance().getEndpointData().getElasticSearchEndpoint();
String ES_CACHE_INDEX = ApplicationConfigProvider.getInstance().getQueryCache().getEsCacheIndex();
String DEFAULT_ES_CACHE_INDEX = "neo4j-cached-results/querycacheresult";
String METADATA = "metadata";
String STATEMENT = "statement";
String STATEMENTS = "statements";
String TEST_DATABASE = "testDB";
String RESULT_CACHE = "resultCache";
String CACHING_TYPE = "cachingType";
String START_TIME = "startTime";
String END_TIME = "endTime";
String CACHING_VALUE = "cachingValue";
String LOAD_CACHETIME_QUERY_FROM_RESOURCES = "/querycachingesquery/esQueryWithTime.json";
String LOAD_CACHEVARIANCE_QUERY_FROM_RESOURCES = "/querycachingesquery/esQueryWithVariance.json";
String QUERY_HASH = "queryHash";
String QUERY_CACHE = "__queryCache__";
String FIXED_TIME = "Fixed Time";
String CACHED_STARTTIME = "__cachedStartTime__";
String CACHED_ENDTIME = "__cachedEndTime__";
String START_TIME_IN_STATEMENT_REPLACE = "?START_TIME?";
String END_TIME_IN_STATEMENT_REPLACE = "?END_TIME?";
String START_TIME_RANGE = "startTimeRange";
String END_TIME_RANGE = "endTimeRange";
String START_TIME_REPLACE = "__startTime__";
String END_TIME_REPLACE = "__endTime__";
String CURRENT_TIME = "__currentTime__";
String CACHED_PREVIOUS_TIME = "__cachePreviousTime__";
String HAS_EXPIRED = "hasExpired";
String CREATION_TIME = "creationTime";
String QUERY_EXECUTION_TIME = "queryExecutionTime";
String NEO4J_RESULT_CREATION_TIME = "neo4jResultCreationTime";
int ZEROTH_INDEX = 0;
String CACHE_RESULT = "cacheResult";
String NEW_STATEMENT = "newStatement";
String START_TIME_IN_MS = "startTimeInMs";
String END_TIME_IN_MS = "endTimeInMs";
String CYPHER_QUERY = "cypherQuery";
}
|
ShapeShiftOS-WIP/android_build_soong | ui/build/ninja.go | <gh_stars>1-10
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build
import (
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"android/soong/ui/metrics"
"android/soong/ui/status"
)
// Constructs and runs the Ninja command line with a restricted set of
// environment variables. It's important to restrict the environment Ninja runs
// for hermeticity reasons, and to avoid spurious rebuilds.
func runNinjaForBuild(ctx Context, config Config) {
ctx.BeginTrace(metrics.PrimaryNinja, "ninja")
defer ctx.EndTrace()
// Sets up the FIFO status updater that reads the Ninja protobuf output, and
// translates it to the soong_ui status output, displaying real-time
// progress of the build.
fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
nr := status.NewNinjaReader(ctx, ctx.Status.StartTool(), fifo)
defer nr.Close()
executable := config.PrebuiltBuildTool("ninja")
args := []string{
"-d", "keepdepfile",
"-d", "keeprsp",
"-d", "stats",
"--frontend_file", fifo,
}
args = append(args, config.NinjaArgs()...)
var parallel int
if config.UseRemoteBuild() {
parallel = config.RemoteParallel()
} else {
parallel = config.Parallel()
}
args = append(args, "-j", strconv.Itoa(parallel))
if config.keepGoing != 1 {
args = append(args, "-k", strconv.Itoa(config.keepGoing))
}
args = append(args, "-f", config.CombinedNinjaFile())
args = append(args,
"-o", "usesphonyoutputs=yes",
"-w", "dupbuild=err",
"-w", "missingdepfile=err")
cmd := Command(ctx, config, "ninja", executable, args...)
// Set up the nsjail sandbox Ninja runs in.
cmd.Sandbox = ninjaSandbox
if config.HasKatiSuffix() {
// Reads and executes a shell script from Kati that sets/unsets the
// environment Ninja runs in.
cmd.Environment.AppendFromKati(config.KatiEnvFile())
}
// Allow both NINJA_ARGS and NINJA_EXTRA_ARGS, since both have been
// used in the past to specify extra ninja arguments.
if extra, ok := cmd.Environment.Get("NINJA_ARGS"); ok {
cmd.Args = append(cmd.Args, strings.Fields(extra)...)
}
if extra, ok := cmd.Environment.Get("NINJA_EXTRA_ARGS"); ok {
cmd.Args = append(cmd.Args, strings.Fields(extra)...)
}
ninjaHeartbeatDuration := time.Minute * 5
// Get the ninja heartbeat interval from the environment before it's filtered away later.
if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
// For example, "1m"
overrideDuration, err := time.ParseDuration(overrideText)
if err == nil && overrideDuration.Seconds() > 0 {
ninjaHeartbeatDuration = overrideDuration
}
}
// Filter the environment, as ninja does not rebuild files when environment
// variables change.
//
// Anything listed here must not change the output of rules/actions when the
// value changes, otherwise incremental builds may be unsafe. Vars
// explicitly set to stable values elsewhere in soong_ui are fine.
//
// For the majority of cases, either Soong or the makefiles should be
// replicating any necessary environment variables in the command line of
// each action that needs it.
if cmd.Environment.IsEnvTrue("ALLOW_NINJA_ENV") {
ctx.Println("Allowing all environment variables during ninja; incremental builds may be unsafe.")
} else {
cmd.Environment.Allow(append([]string{
// Set the path to a symbolizer (e.g. llvm-symbolizer) so ASAN-based
// tools can symbolize crashes.
"ASAN_SYMBOLIZER_PATH",
"HOME",
"JAVA_HOME",
"LANG",
"LC_MESSAGES",
"OUT_DIR",
"PATH",
"PWD",
// https://docs.python.org/3/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE
"PYTHONDONTWRITEBYTECODE",
"TMPDIR",
"USER",
// TODO: remove these carefully
// Options for the address sanitizer.
"ASAN_OPTIONS",
// The list of Android app modules to be built in an unbundled manner.
"TARGET_BUILD_APPS",
// The variant of the product being built. e.g. eng, userdebug, debug.
"TARGET_BUILD_VARIANT",
// The product name of the product being built, e.g. aosp_arm, aosp_flame.
"TARGET_PRODUCT",
// b/147197813 - used by art-check-debug-apex-gen
"EMMA_INSTRUMENT_FRAMEWORK",
// RBE client
"RBE_compare",
"RBE_exec_root",
"RBE_exec_strategy",
"RBE_invocation_id",
"RBE_log_dir",
"RBE_num_retries_if_mismatched",
"RBE_platform",
"RBE_remote_accept_cache",
"RBE_remote_update_cache",
"RBE_server_address",
// TODO: remove old FLAG_ variables.
"FLAG_compare",
"FLAG_exec_root",
"FLAG_exec_strategy",
"FLAG_invocation_id",
"FLAG_log_dir",
"FLAG_platform",
"FLAG_remote_accept_cache",
"FLAG_remote_update_cache",
"FLAG_server_address",
// ccache settings
"CCACHE_COMPILERCHECK",
"CCACHE_SLOPPINESS",
"CCACHE_BASEDIR",
"CCACHE_CPP2",
"CCACHE_DIR",
}, config.BuildBrokenNinjaUsesEnvVars()...)...)
}
cmd.Environment.Set("DIST_DIR", config.DistDir())
cmd.Environment.Set("SHELL", "/bin/bash")
// Print the environment variables that Ninja is operating in.
ctx.Verboseln("Ninja environment: ")
envVars := cmd.Environment.Environ()
sort.Strings(envVars)
for _, envVar := range envVars {
ctx.Verbosef(" %s", envVar)
}
// Poll the Ninja log for updates regularly based on the heartbeat
// frequency. If it isn't updated enough, then we want to surface the
// possibility that Ninja is stuck, to the user.
done := make(chan struct{})
defer close(done)
ticker := time.NewTicker(ninjaHeartbeatDuration)
defer ticker.Stop()
ninjaChecker := &ninjaStucknessChecker{
logPath: filepath.Join(config.OutDir(), ".ninja_log"),
}
go func() {
for {
select {
case <-ticker.C:
ninjaChecker.check(ctx, config)
case <-done:
return
}
}
}()
ctx.Status.Status("Starting ninja...")
cmd.RunAndStreamOrFatal()
}
// A simple struct for checking if Ninja gets stuck, using timestamps.
type ninjaStucknessChecker struct {
logPath string
prevModTime time.Time
}
// Check that a file has been modified since the last time it was checked. If
// the mod time hasn't changed, then assume that Ninja got stuck, and print
// diagnostics for debugging.
func (c *ninjaStucknessChecker) check(ctx Context, config Config) {
info, err := os.Stat(c.logPath)
var newModTime time.Time
if err == nil {
newModTime = info.ModTime()
}
if newModTime == c.prevModTime {
// The Ninja file hasn't been modified since the last time it was
// checked, so Ninja could be stuck. Output some diagnostics.
ctx.Verbosef("ninja may be stuck; last update to %v was %v. dumping process tree...", c.logPath, newModTime)
// The "pstree" command doesn't exist on Mac, but "pstree" on Linux
// gives more convenient output than "ps" So, we try pstree first, and
// ps second
commandText := fmt.Sprintf("pstree -pal %v || ps -ef", os.Getpid())
cmd := Command(ctx, config, "dump process tree", "bash", "-c", commandText)
output := cmd.CombinedOutputOrFatal()
ctx.Verbose(string(output))
ctx.Verbosef("done\n")
}
c.prevModTime = newModTime
}
|
djeada/Nauka-programowania | src/JavaScript/02_Instrukcje_sterujace/Zad5.js | <gh_stars>1-10
var Main = /** @class */ (function() {
function Main() {}
Main.main = function(args) {
console.info("podaj trzy liczby:");
var rl = require('readline-sync');
var a = rl.question('');
var b = rl.question('');
var c = rl.question('');
if (a >= b && a >= c) {
if (b >= c) {
console.info(c);
console.info(b);
console.info(a);
} else {
console.info(b);
console.info(c);
console.info(a);
}
} else if (c >= b && c >= a) {
if (a >= b) {
console.info(b);
console.info(a);
console.info(c);
} else {
console.info(a);
console.info(b);
console.info(c);
}
} else {
if (a >= c) {
console.info(c);
console.info(a);
console.info(b);
} else {
console.info(a);
console.info(c);
console.info(b);
}
}
};
return Main;
}());
Main["__class"] = "Main";
Main.main(null);
|
rccarper/aws-sdk-java-v2 | codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AbstractMemberSetters.java | <filename>codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/AbstractMemberSetters.java
/*
* Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.codegen.poet.model;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.lang.model.element.Modifier;
import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel;
import software.amazon.awssdk.codegen.model.intermediate.MemberModel;
import software.amazon.awssdk.codegen.model.intermediate.ShapeModel;
import software.amazon.awssdk.codegen.poet.PoetExtensions;
import software.amazon.awssdk.core.SdkBytes;
/**
* Abstract implementation of {@link MemberSetters} to share common functionality.
*/
abstract class AbstractMemberSetters implements MemberSetters {
protected final PoetExtensions poetExtensions;
private final ShapeModel shapeModel;
private final MemberModel memberModel;
private final TypeProvider typeProvider;
private final ServiceModelCopiers serviceModelCopiers;
AbstractMemberSetters(IntermediateModel intermediateModel,
ShapeModel shapeModel,
MemberModel memberModel,
TypeProvider typeProvider) {
this.shapeModel = shapeModel;
this.memberModel = memberModel;
this.typeProvider = typeProvider;
this.serviceModelCopiers = new ServiceModelCopiers(intermediateModel);
this.poetExtensions = new PoetExtensions(intermediateModel);
}
protected MethodSpec.Builder fluentAbstractSetterDeclaration(ParameterSpec parameter, TypeName returnType) {
return fluentSetterDeclaration(parameter, returnType).addModifiers(Modifier.ABSTRACT);
}
protected MethodSpec.Builder fluentAbstractSetterDeclaration(String methodName,
ParameterSpec parameter,
TypeName returnType) {
return setterDeclaration(methodName, parameter, returnType).addModifiers(Modifier.ABSTRACT);
}
protected MethodSpec.Builder fluentDefaultSetterDeclaration(ParameterSpec parameter, TypeName returnType) {
return fluentSetterDeclaration(parameter, returnType).addModifiers(Modifier.DEFAULT);
}
protected MethodSpec.Builder fluentSetterBuilder(TypeName returnType) {
return fluentSetterBuilder(memberAsParameter(), returnType);
}
protected MethodSpec.Builder fluentSetterBuilder(String methodName, TypeName returnType) {
return fluentSetterBuilder(methodName, memberAsParameter(), returnType);
}
protected MethodSpec.Builder fluentSetterBuilder(ParameterSpec setterParam, TypeName returnType) {
return fluentSetterBuilder(memberModel().getFluentSetterMethodName(), setterParam, returnType);
}
protected MethodSpec.Builder fluentSetterBuilder(String methodName, ParameterSpec setterParam, TypeName returnType) {
return MethodSpec.methodBuilder(methodName)
.addParameter(setterParam)
.addAnnotation(Override.class)
.returns(returnType)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
}
protected MethodSpec.Builder beanStyleSetterBuilder() {
return beanStyleSetterBuilder(memberAsBeanStyleParameter(), memberModel().getBeanStyleSetterMethodName());
}
protected MethodSpec.Builder deprecatedBeanStyleSetterBuilder() {
return beanStyleSetterBuilder(memberAsBeanStyleParameter(), memberModel().getDeprecatedBeanStyleSetterMethodName());
}
protected MethodSpec.Builder beanStyleSetterBuilder(ParameterSpec setterParam, String methodName) {
return MethodSpec.methodBuilder(methodName)
.addParameter(setterParam)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
}
protected CodeBlock copySetterBody() {
return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N", serviceModelCopiers.copyMethodName());
}
protected CodeBlock fluentSetterWithEnumCollectionsParameterMethodBody() {
return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N",
serviceModelCopiers.enumToStringCopyMethodName());
}
protected CodeBlock copySetterBodyWithModeledEnumParameter() {
return copySetterBody("this.$1N = $2T.$3N($1N)", "this.$1N = $1N",
serviceModelCopiers.enumToStringCopyMethodName());
}
protected CodeBlock copySetterBuilderBody() {
if (memberModel.hasBuilder()) {
return copySetterBody("this.$1N = $1N != null ? $2T.$3N($1N.build()) : null",
"this.$1N = $1N != null ? $1N.build() : null",
serviceModelCopiers.copyMethodName());
}
if (memberModel.isCollectionWithBuilderMember()) {
return copySetterBody("this.$1N = $2T.$3N($1N)", null, serviceModelCopiers.builderCopyMethodName());
}
return copySetterBody();
}
protected CodeBlock beanCopySetterBody() {
if (memberModel.isSdkBytesType()) {
return sdkBytesSetter();
}
if (memberModel.isList() && memberModel.getListModel().getListMemberModel().isSdkBytesType()) {
return sdkBytesListSetter();
}
if (memberModel.isMap() && memberModel.getMapModel().getValueModel().isSdkBytesType()) {
return sdkBytesMapValueSetter();
}
return copySetterBuilderBody();
}
private CodeBlock sdkBytesSetter() {
return CodeBlock.of("$1N($2N == null ? null : $3T.fromByteBuffer($2N));",
memberModel.getFluentSetterMethodName(), fieldName(),
SdkBytes.class);
}
private CodeBlock sdkBytesListSetter() {
return CodeBlock.of("$1N($2N == null ? null : $2N.stream().map($3T::fromByteBuffer).collect($4T.toList()));",
memberModel.getFluentSetterMethodName(), fieldName(),
SdkBytes.class, Collectors.class);
}
private CodeBlock sdkBytesMapValueSetter() {
return CodeBlock.of("$1N($2N == null ? null : " +
"$2N.entrySet().stream()" +
".collect($4T.toMap(e -> e.getKey(), e -> $3T.fromByteBuffer(e.getValue()))));",
memberModel.getFluentSetterMethodName(), fieldName(),
SdkBytes.class, Collectors.class);
}
protected ParameterSpec memberAsParameter() {
return ParameterSpec.builder(typeProvider.parameterType(memberModel), fieldName()).build();
}
protected ParameterSpec memberAsBeanStyleParameter() {
if (memberModel.hasBuilder()) {
TypeName builderName = poetExtensions.getModelClass(memberModel.getC2jShape()).nestedClass("BuilderImpl");
return ParameterSpec.builder(builderName, fieldName()).build();
}
if (memberModel.isList()) {
MemberModel listMember = memberModel.getListModel().getListMemberModel();
if (hasBuilder(listMember)) {
TypeName memberName = poetExtensions.getModelClass(listMember.getC2jShape()).nestedClass("BuilderImpl");
TypeName listType = ParameterizedTypeName.get(ClassName.get(Collection.class), memberName);
return ParameterSpec.builder(listType, fieldName()).build();
} else if (listMember.isSdkBytesType()) {
TypeName listType = ParameterizedTypeName.get(Collection.class, ByteBuffer.class);
return ParameterSpec.builder(listType, fieldName()).build();
}
}
if (memberModel.isMap()) {
MemberModel keyModel = memberModel.getMapModel().getKeyModel();
TypeName keyType = typeProvider.getTypeNameForSimpleType(keyModel.getVariable().getVariableType());
MemberModel valueModel = memberModel.getMapModel().getValueModel();
TypeName valueType = null;
if (hasBuilder(valueModel)) {
valueType = poetExtensions.getModelClass(valueModel.getC2jShape()).nestedClass("BuilderImpl");
} else if (valueModel.isSdkBytesType()) {
valueType = TypeName.get(ByteBuffer.class);
}
if (valueType != null) {
TypeName mapType = ParameterizedTypeName.get(ClassName.get(Map.class), keyType, valueType);
return ParameterSpec.builder(mapType, fieldName()).build();
}
}
if (memberModel.isSdkBytesType()) {
return ParameterSpec.builder(ByteBuffer.class, fieldName()).build();
}
return memberAsParameter();
}
protected ShapeModel shapeModel() {
return shapeModel;
}
protected MemberModel memberModel() {
return memberModel;
}
protected String fieldName() {
return memberModel.getVariable().getVariableName();
}
private MethodSpec.Builder fluentSetterDeclaration(ParameterSpec parameter, TypeName returnType) {
return setterDeclaration(memberModel().getFluentSetterMethodName(), parameter, returnType);
}
private MethodSpec.Builder setterDeclaration(String methodName, ParameterSpec parameter, TypeName returnType) {
return MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PUBLIC)
.addParameter(parameter)
.returns(returnType);
}
private CodeBlock copySetterBody(String copyAssignment, String regularAssignment, String copyMethodName) {
Optional<ClassName> copierClass = serviceModelCopiers.copierClassFor(memberModel);
return copierClass.map(className -> CodeBlock.builder().addStatement(copyAssignment,
fieldName(),
className,
copyMethodName)
.build())
.orElseGet(() -> CodeBlock.builder().addStatement(regularAssignment, fieldName()).build());
}
private boolean hasBuilder(MemberModel model) {
return model != null && model.hasBuilder();
}
}
|
hirokiuedaRcast/karkinos | src/main/java/jp/ac/utokyo/karkinos/noisefilter/AFDepthMatrix.java | /*
Copyright <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jp.ac.utokyo.karkinos.noisefilter;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math.distribution.NormalDistribution;
import org.apache.commons.math.distribution.NormalDistributionImpl;
import org.apache.commons.math.stat.descriptive.SummaryStatistics;
import jp.ac.utokyo.rcast.karkinos.exec.KarkinosProp;
import jp.ac.utokyo.rcast.karkinos.exec.SNVHolder;
import jp.ac.utokyo.rcast.karkinos.utils.CalcUtils;
public class AFDepthMatrix {
List<BinData> binlist;
int binsize = 20;
public AFDepthMatrix(List<BinData> binlist, int binsize) {
this.binlist = binlist;
this.binsize = binsize;
}
public float getPval(float adjusttedAF, float readdepth) {
try {
double x = Math.log(readdepth - c1) / (Math.log(a1) * b1);
double sd = Math.abs(x * 0.5);
if (x < 0) {
return 0;
}
NormalDistribution nd = new NormalDistributionImpl(0, sd);
return (float) (1 - nd.cumulativeProbability(adjusttedAF));
} catch (Exception ex) {
}
return 1;
}
public void regSNV(SNVHolder snv, float tratio) {
int depth = (int) (snv.getTumor().getTotalcnt() * tratio);
double tr = CalcUtils.getTumorrateAdjustedRatio(snv, tratio);
int depthindex = getDIndex(depth);
BinData bd = binlist.get(depthindex);
bd.setSNV(depth, tr);
}
public void sortList() {
for (BinData bd : binlist) {
bd.sortList();
}
}
public void EMmethod(float tratio) {
int idx = 0;
for (BinData bd : binlist) {
boolean firstBin = (idx == 0);
boolean lastBin = (idx >= getMaxBinIdx(tratio));
//boolean lastBin = false;
boolean lowdepthbin = (bd.getLdepth() < 20);
if (firstBin || lastBin || lowdepthbin) {
idx++;
continue;
}
if (bd.getSamplesize() <= 10) {
continue;
}
if (bd.getDepth() >= 100) {
continue;
}
// excute EM method to separat noise to signal
try {
bd.em();
} catch (Exception ex) {
ex.printStackTrace();
}
idx++;
}
//
SummaryStatistics ss = new SummaryStatistics();
boolean atleast_one = false;
for (BinData bd : binlist) {
if (bd.isEmExcuted()) {
atleast_one = true;
ss.addValue(bd.getNumCandidate());
}
}
if (atleast_one) {
for (BinData bd : binlist) {
bd.setPredictedCandnum((int) ss.getMean());
}
}
}
private int getMaxBinIdx(float tratio) {
if (binlist.size() == 0) {
return 0;
}
BinData laste = binlist.get(binlist.size() - 1);
int ld = laste.getLdepth();
int dpethadj = Math.round((ld * tratio));
int idx = 0;
for (BinData bd : binlist) {
if (bd.includepeth(dpethadj)) {
return idx;
}
idx++;
}
return idx;
}
public void regHetroSNP(SNVHolder snv, float tumorContentsRatio) {
int depth = (int) snv.getTumor().getTotalcnt();
double tr = getTR(snv, tumorContentsRatio);
double secondAlleleF = getSecondAlleleF(snv, tumorContentsRatio);
int depthindex = getDIndex(depth);
BinData bd = binlist.get(depthindex);
bd.setHetroSNPAF(depth, tr);
bd.setSecondAF(depth, secondAlleleF);
}
private double getTR(SNVHolder snv, float tumorContentsRatio) {
double tAF = snv.getTumor().getRatio();
double diffr = (0.5 - tAF) / tumorContentsRatio;
return diffr + 0.5;
}
private double getSecondAlleleF(SNVHolder snv, float tumorContentsRatio) {
double tAF = snv.getTumor().getSecondRatio();
double diffr = (0.5 - tAF) / tumorContentsRatio;
return diffr + 0.5;
}
private int getDIndex(int depth) {
int ret = 0;
for (int n = 0; n < binlist.size(); n++) {
int deptht = binlist.get(n).getUdepth();
if (depth < deptht) {
ret = n;
break;
}
}
if (ret < 0)
ret = 0;
if (ret >= binsize)
ret = binsize - 1;
return ret;
}
public void calcregresion() {
// border cond
List<Point2D> raiodapthlist = new ArrayList<Point2D>();
for (BinData bd : binlist) {
if (bd.getDepth() <= 100) {
raiodapthlist.add(new Point2D.Double(bd.getAFBorder(), bd
.getDepth()));
}
}
calcRegression(raiodapthlist);
}
double a1 = 0;
double b1 = 0;
double c1 = 0;
private void calcRegression(List<Point2D> list) {
// 1.regression by 2nd degree polynomial
// int n = 0;
double X = 0;
double X2 = 0;
// double X3 = 0;
// double X4 = 0;
//
//
// double Y = 0;
// double XY = 0;
// double X2Y = 0;
if (list.size() <= 3)
return;
// // LSM to find 2nd degree eq
// for (Point2D point : list) {
//
// //
// double x0 = point.getX();
// double y0 = point.getY();
// double x2 = Math.pow(x0, 2);
// double x3 = Math.pow(x0, 3);
// double x4 = x2 * x2;
//
// X += x0;
// X2 += x2;
// X3 += x3;
// X4 += x4;
//
//
// n++;
//
// Y += y0;
// XY += x0 * y0;
// X2Y += x2 * y0;
//
// }
// // resolve equation
//
// double[][] vals = { { n, X, X2 }, { X, X2, X3 }, { X2, X3, X4 } };
// double[] rhs = { Y, XY, X2Y };
//
// RealMatrix rm = new Array2DRowRealMatrix(vals);
// try {
// DecompositionSolver solver = new LUDecompositionImpl(rm).getSolver();
// RealVector b = new ArrayRealVector(rhs);
// RealVector x = solver.solve(b);
// a1 = x.getEntry(2);
// b1 = x.getEntry(1);
// c1 = x.getEntry(0);
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
int n = list.size();
double zmin = Integer.MAX_VALUE;
// 3 regression by exponental
for (float z0 = 0f; z0 < 0.1; z0 = z0 + 0.01f) {
X = 0;
X2 = 0;
double InY = 0;
double XInY = 0;
int size = 0;
for (Point2D point : list) {
size++;
double x0 = point.getX();
double y0 = point.getY();
x0 = x0 - z0;
double lnY0 = Math.log(y0 - z0);
InY += lnY0;
XInY += x0 * lnY0;
double x2 = Math.pow(x0, 2);
X += x0;
X2 += x2;
}
if (n != size) {
continue;
}
double eb = (n * XInY - X * InY) / (n * X2 - X * X);
double ea = (X2 * InY - XInY * X) / (n * X2 - X * X);
ea = Math.exp(ea);
double z = 0;
for (Point2D point : list) {
double x0 = point.getX();
double y0 = point.getY();
double y = ea * Math.exp(eb * (x0 - z0));
double diff = y0 - y;
z = z + Math.pow(diff, 2);
}
if (zmin == 0 || zmin > z) {
zmin = z;
a1 = ea;
b1 = eb;
c1 = z0;
}
}
}
public double func(float x) {
// double y = _func(x);
// double localmin = (-1*b1)/(2*a1);
// if(x>localmin){
// y = _func((float)localmin);
// }
if ((a1 == 0) && (b1 == 0) && (c1 == 0) || (b1 > 0)) {
double y = a1fix * Math.exp(b1fix * x);
if (y < 0)
y = 0;
return y;
}
double y = a1 * Math.exp(b1 * (x - c1));
if (y < 0)
y = 0;
return y;
}
public boolean reject(int depth_c, float adjusttedAF,
boolean highErrorSample) {
boolean reject = _reject(depth_c, adjusttedAF);
if (!reject) {
if ((depth_c <= 100)
&& (adjusttedAF < KarkinosProp.mintumorratioForFilter1)) {
reject = true;
}
}
if (highErrorSample) {
if (reject) {
if (adjusttedAF > 0.6 && depth_c >= 30) {
reject = false;
}
if (adjusttedAF > 0.8) {
reject = false;
}
}
} else {
if (reject) {
if (adjusttedAF > 0.2 && depth_c >= 10) {
reject = false;
}
if (adjusttedAF > 0.3) {
reject = false;
}
}
}
return reject;
}
public boolean _reject(int depth_c, float adjusttedAF) {
if ((a1 == 0) && (b1 == 0) && (c1 == 0) || (b1 > 0)) {
return defultreject(depth_c, adjusttedAF);
}
double y = func(adjusttedAF);
return depth_c < y;
// //case 1 no list
// if((raiodapthlist==null)||(raiodapthlist.size()==0)){
// return defultreject(depth_c,adjusttedAF);
// }
// double x = getTargetX(depth_c,raiodapthlist);
// if(adjusttedAF<=x){
// return true;
// }else{
// return false;
// }
}
static final double a1fix = 1.51;
static final double b1fix = -1.68;
public static boolean defultreject(int depth_c, float x) {
// y=-500x+200
// double y = (-500*adjusttedAF)+200;
// if(y<0)y=0;
// if(depth_c<=20){
// return true;
// }
double y = a1fix * Math.exp(b1fix * x);
if (y < 0)
y = 0;
return depth_c < y;
}
}
|
meghabh/twu-biblioteca-megha | src/main/java/com/twu/menuoptions/CheckedOutItems.java | package com.twu.menuoptions;
import com.twu.biblioteca.UserAuthentication;
import com.twu.biblioteca.Output;
import com.twu.biblioteca.Repository;
import com.twu.io.InputReader;
import java.util.ArrayList;
import java.util.List;
public class CheckedOutItems implements MenuOptions {
private String type;
private UserAuthentication userAuthentication;
private List<String> items;
public CheckedOutItems(String type, UserAuthentication userAuthentication) {
this.type = type;
this.userAuthentication = userAuthentication;
items = new ArrayList<>();
}
@Override
public Output performAction(InputReader consoleInputReader, Repository repository) {
items = repository.getCheckedOutItems(type);
return new Output(items);
}
}
|
zhangyu345293721/leetcode | src/leetcodejava/tree/HouseRobber337.java | package leetcodejava.tree;
import org.junit.Assert;
import org.junit.Test;
/**
* This is the solution of No. 337 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/house-robber-iii
* <p>
* The description of problem is as follow:
* ==========================================================================================================
* 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
* <p>
* 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
* <p>
* 示例 1:
* <p>
* 输入: [3,2,3,null,3,null,1]
* <p>
* 3
* / \
* 2 3
* \ \
* 3 1
* <p>
* 输出: 7
* 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
* 示例 2:
* <p>
* 输入: [3,4,5,1,3,null,1]
* <p>
* 3
* / \
* 4 5
* / \ \
* 1 3 1
* <p>
* 输出: 9
* 解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/house-robber-iii
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* ==========================================================================================================
*
* @author zhangyu (<EMAIL>)
*/
public class HouseRobber337 {
@Test
public void houseRobberTest() {
Integer[] arr = {3, 2, 3, null, 3, null, 1};
TreeNode root = TreeNode.createBinaryTreeByArray(arr);
int result = rob(root);
System.out.println(result);
Assert.assertEquals(result, 7);
}
/**
* 找出抢劫最大结果
*
* @param root 根节点
* @return 最大值
*/
public int rob(TreeNode root) {
int[] result = helper(root);
return Math.max(result[0], result[1]);
}
/**
* 帮助方法
*
* @param node 节点
* @return 数组
*/
public int[] helper(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
if (node.left == null && node.right == null) {
return new int[]{node.val, 0};
}
int[] l = helper(node.left);
int[] r = helper(node.right);
return new int[]{node.val + l[1] + r[1], Math.max(l[0], l[1]) + Math.max(r[0], r[1])};
}
/**
* 找出抢劫最大结果
*
* @param root 根节点
* @return 最大值
*/
public int rob2(TreeNode root) {
if (root == null) {
return 0;
}
// 计算左右子树的子树节点值
int val = 0;
if (root.left != null) {
val += rob2(root.left.left) + rob2(root.left.right);
}
if (root.right != null) {
val += rob2(root.right.left) + rob2(root.right.right);
}
// 比较左右子树的值和与节点和左右子树的子树和大小
return Math.max(val + root.val, rob2(root.left) + rob2(root.right));
}
}
|
pablosjv/aco-spark | src/main/scala/org/chocosolver/solver/search/loop/move/MoveLearnBinaryTDR.java | <filename>src/main/scala/org/chocosolver/solver/search/loop/move/MoveLearnBinaryTDR.java
/**
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2017, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.search.loop.move;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.explanations.Explanation;
import org.chocosolver.solver.search.loop.learn.LearnExplained;
import org.chocosolver.solver.search.strategy.assignments.DecisionOperator;
import org.chocosolver.solver.search.strategy.decision.Decision;
import org.chocosolver.solver.search.strategy.decision.DecisionPath;
import org.chocosolver.solver.search.strategy.decision.IntDecision;
import org.chocosolver.solver.search.strategy.strategy.AbstractStrategy;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.Variable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
/**
* A combination of Move and Learn which results in tabu Decision-repair[1] (TDR) with binary decisions.
* <p>
* [1]: <NAME>, <NAME>, Local search with constraint propagation and conflict-based heuristics, AI-139 (2002).
* <p>
* Created by cprudhom on 04/11/2015.
* Project: choco.
*/
public class MoveLearnBinaryTDR extends LearnExplained implements Move {
private static final boolean DEBUG = true;
/**
* Internal reference to Move for simulating multiple extension.
*/
private final Move move;
/**
* List of "n" last conflicts.
*/
private List<List<IntDecision>> gamma;
/**
* Limited size of conflicts to store in the tabu list.
*/
private int s;
/**
* The neigbhor of the current decision path.
*/
private IntDecision[] neighbor;
/**
* Current decision in CD.
*/
private int current;
/**
* Ordered list (decreasing weight) of decisions in k.
*/
private TIntObjectHashMap<TIntObjectHashMap<TObjectDoubleMap<DecisionOperator>>> weights;
/**
* An array to maintain ordered the index of decision in the conflict.
*/
private TreeMap<Integer, Double> L;
/**
* Indicates that no neighnor has been found, and the search can then stop.
*/
private boolean stop = false;
private MoveLearnBinaryTDR(Model aModel, Move move, int tabuListSize) {
super(aModel, false, false);
this.move = move;
this.s = tabuListSize;
this.gamma = new ArrayList<>();
this.weights = new TIntObjectHashMap<>(16, .5f, -1);
this.neighbor = new IntDecision[0];
this.current = 0;
this.L = new TreeMap<>();
}
@Override
public boolean extend(Solver solver) {
boolean extend;
// as we observe the number of backtracks, no limit can be reached on extend()
if (current < neighbor.length) {
DecisionPath dp = solver.getDecisionPath();
assert neighbor[current] != null;
dp.pushDecision(neighbor[current++]);
solver.getEnvironment().worldPush();
extend = true;
} else /*cut will checker with propagation */ {
// TODO: incomplete, have to deal with gamma when extending
extend = move.extend(solver);
}
return extend;
}
@Override
public boolean repair(Solver solver) {
boolean repair;
if (current < neighbor.length) {
solver.restart();
// check stop conditionsn for instance, when no compatible decision path can be computed
repair = !stop;
} else {
repair = move.repair(solver);
}
return repair;
}
/**
* {@inheritDoc} main reason we implement this Learn.
*/
@Override
public void onFailure(Solver solver) {
super.onFailure(solver);
neighbor(solver);
}
private void neighbor(Solver solver) {
Explanation expl = getLastExplanation();
List<IntDecision> k = extractConlict(solver, expl);
// add k to the list of conflicts
gamma.add(k);
// remove the oldest element in gamma if the tabu size is met
if (gamma.size() > s) {
List<IntDecision> r = gamma.remove(0);
// update weight of decisions
decWeight(r);
}
// prepare getting the decision of k in decreasing order wrt to their weights
if (DEBUG) {
System.out.printf("G:\n");
for (List<IntDecision> g : gamma) {
System.out.printf("\t");
for (int i = g.size() - 1; i > -1; i--) {
IntDecision d = g.get(i);
System.out.printf("%s %s %d, ",
d.getDecisionVariable().getName(),
d.getDecOp(),
d.getDecisionValue());
}
System.out.printf("\n");
}
}
boolean compatible;
System.out.printf("CD:\n");
do {
int j = L.lastKey();
IntDecision d = neighbor[j].flip();
neighbor[j].free();
neighbor[j] = d;
if (DEBUG) System.out.printf("\t%s ? \n", Arrays.toString(neighbor));
compatible = isCDcompatible();
if (!compatible) {
d = neighbor[j].flip();
neighbor[j].free();
neighbor[j] = d;
}
L.remove(j);
} while (!compatible && !L.isEmpty());
if (DEBUG) System.out.printf("%s\n", compatible);
stop = !compatible;
}
/**
* Check if CD is compatible with any conflict of gamma.
*
* @return <tt>true</tt> if all conflicts of gamma are compatible with CD, <tt>false</tt> otherwise.
*/
private boolean isCDcompatible() {
boolean compatible = true;
// iteration over all stored conflicts
// the last conflict added is ignored, since it is trivially compatible with any CD
for (int i = 0; i < gamma.size() - 1 && compatible; i++) {
if (isSubsetOfNeighbor(gamma.get(i))) {
compatible = false;
}
}
return compatible;
}
/**
* Returns <tt>true</tt> if <code>conflict</code> is contained in <code>neighbor</code>, <tt>false</tt> otherwise.
*
* @param conflict one of the stored conflict
* @return <tt>true</tt> if <code>conflict</code> is contained in <code>neighbor</code>, <tt>false</tt> otherwise.
*/
private boolean isSubsetOfNeighbor(List<IntDecision> conflict) {
boolean subset = true;
// for all decisions in the conflict
for (int j = 0; j < conflict.size() && subset; j++) {
IntVar var = conflict.get(j).getDecisionVariable();
int val = conflict.get(j).getDecisionValue();
DecisionOperator dop = conflict.get(j).getDecOp();
boolean contains = false;
// iteration over decisions in the neighbor
for (int k = 0; k < neighbor.length && !contains; k++) {
// if the decision is not found, the neighbor is not in conflict
contains = (dop == neighbor[k].getDecOp()
&& var == neighbor[k].getDecisionVariable()
&& val == neighbor[k].getDecisionValue());
}
subset = contains;
}
return subset;
}
private void incWeight(List<IntDecision> k, int i, double w) {
TIntObjectHashMap<TObjectDoubleMap<DecisionOperator>> _w1 = weights.get(k.get(i).getDecisionVariable().getId());
if (_w1 == null) {
_w1 = new TIntObjectHashMap<>(10, .5f, Integer.MAX_VALUE);
weights.put(k.get(i).getDecisionVariable().getId(), _w1);
}
TObjectDoubleMap<DecisionOperator> _w2 = _w1.get(k.get(i).getDecisionValue());
if (_w2 == null) {
_w2 = new TObjectDoubleHashMap<>(10, .5f, 0);
_w1.put(k.get(i).getDecisionValue(), _w2);
}
_w2.adjustOrPutValue(k.get(i).getDecOp(), w, w);
}
private void decWeight(List<IntDecision> k) {
int size = k.size();
double w = -1d / size;
for (int i = 0; i < size; i++) {
TIntObjectHashMap<TObjectDoubleMap<DecisionOperator>> _w1 = weights.get(k.get(i).getDecisionVariable().getId());
TObjectDoubleMap<DecisionOperator> _w2 = _w1.get(k.get(i).getDecisionValue());
_w2.adjustValue(k.get(i).getDecOp(), w);
}
}
private double getWeight(List<IntDecision> k, int i) {
TIntObjectHashMap<TObjectDoubleMap<DecisionOperator>> _w1 = weights.get(k.get(i).getDecisionVariable().getId());
TObjectDoubleMap<DecisionOperator> _w2 = _w1.get(k.get(i).getDecisionValue());
return _w2.get(k.get(i).getDecOp());
}
private List<IntDecision> extractConlict(Solver solver, Explanation lastExplanation) {
int offset = solver.getSearchWorldIndex();
int wi = solver.getEnvironment().getWorldIndex() - 1;
int k = wi - offset;
int size = lastExplanation.getDecisions().cardinality();
double w = 1d / size;
// prepare internal data for record
current = 0;
neighbor = new IntDecision[k];
L.clear();
// start iteration over decisions
List<IntDecision> md = new ArrayList<>();
DecisionPath dp = solver.getDecisionPath();
int last = dp.size() - 1;
Decision decision;
IntDecision id;
if (DEBUG) System.out.printf("Conflict: ");
while (last > 0) { // all decisions needs to be explored
decision = dp.getDecision(last--);
id = (IntDecision) decision.duplicate();
if (decision.triesLeft() != id.triesLeft() - 1) {
id.flip();
}
neighbor[--k] = id;
if (lastExplanation.getDecisions().get(wi)) {
md.add(id);
incWeight(md, md.size() - 1, w);
L.put(k, getWeight(md, md.size() - 1));
if (DEBUG) System.out.printf("%s, ", neighbor[k]);
}
wi--;
}
if (DEBUG) System.out.printf("\n");
assert md.size() == size;
return md;
}
//****************************************************************************************************************//
//********************************* BASIC IMPLEMENTATIONS ********************************************************//
//****************************************************************************************************************//
@Override
public boolean init() {
return move.init();
}
@Override
public <V extends Variable> AbstractStrategy<V> getStrategy() {
return move.getStrategy();
}
@Override
public <V extends Variable> void setStrategy(AbstractStrategy<V> aStrategy) {
move.setStrategy(aStrategy);
}
@Override
public List<Move> getChildMoves() {
return move.getChildMoves();
}
@Override
public void setChildMoves(List<Move> someMoves) {
move.setChildMoves(someMoves);
}
@Override
public void setTopDecisionPosition(int position) {
move.setTopDecisionPosition(position);
}
}
|
openid-certification/-conformance-suite | src/main/java/net/openid/conformance/openid/client/logout/OIDCCClientTestRPInitLogout.java | <filename>src/main/java/net/openid/conformance/openid/client/logout/OIDCCClientTestRPInitLogout.java
package net.openid.conformance.openid.client.logout;
import com.google.common.base.Strings;
import net.openid.conformance.condition.as.logout.EnsureClientHasAtLeastOneOfBackOrFrontChannelLogoutUri;
import net.openid.conformance.testmodule.PublishTestModule;
import net.openid.conformance.variant.ClientRegistration;
import net.openid.conformance.variant.VariantConfigurationFields;
@PublishTestModule(
testName = "oidcc-client-test-rp-init-logout",
displayName = "OIDCC: Relying party test, RP initiated logout.",
summary = "The client is expected to make an authorization request " +
"(also a token request and a optionally a userinfo request when applicable)," +
" then terminate the session by calling the end_session_endpoint (RP-Initiated Logout)," +
" at this point the conformance suite will " +
" send a back channel logout request to the RP if only backchannel_logout_uri is set" +
" or will send a front channel logout request to the RP if only frontchannel_logout_uri is set" +
" or will send both front and back channel logout requests" +
" if both backchannel_logout_uri and frontchannel_logout_uri are set," +
" then the RP is expected to handle post logout URI redirect." +
" Corresponds to rp-init-logout in the old test suite.",
profile = "OIDCC",
configurationFields = {
}
)
@VariantConfigurationFields(parameter = ClientRegistration.class, value = "static_client", configurationFields = {
"client.backchannel_logout_uri",
"client.frontchannel_logout_uri"
})
/**
* OIDCCClientTestRPInitLogoutInvalidState and OIDCCClientTestRPInitLogoutNoState extend this class
* don't forget to update them if you modify this class
*
* This test (and tests extending this one) sends both back channel and front channel logout requests
* at the same time if both endpoints are defined.
* Python tests were doing the same and confirmed by Filip that this is intended behavior.
*
*/
public class OIDCCClientTestRPInitLogout extends AbstractOIDCCClientLogoutTest
{
protected boolean clientHasBackChannelLogoutUri = false;
protected boolean clientHasFrontChannelLogoutUri = false;
@Override
protected boolean finishTestIfAllRequestsAreReceived() {
if( receivedAuthorizationRequest && receivedEndSessionRequest) {
if(clientHasBackChannelLogoutUri && clientHasFrontChannelLogoutUri) {
if(receivedFrontChannelLogoutCompletedCallback && sentBackChannelLogoutRequest) {
fireTestFinished();
return true;
}
} else if(clientHasBackChannelLogoutUri) {
if(sentBackChannelLogoutRequest) {
fireTestFinished();
return true;
}
} else if(clientHasFrontChannelLogoutUri) {
if(receivedFrontChannelLogoutCompletedCallback) {
fireTestFinished();
return true;
}
}
}
return false;
}
@Override
protected Object handleEndSessionEndpointRequest(String requestId) {
receivedEndSessionRequest = true;
callAndStopOnFailure(EnsureClientHasAtLeastOneOfBackOrFrontChannelLogoutUri.class);
clientHasFrontChannelLogoutUri = !Strings.isNullOrEmpty(env.getString("client", "frontchannel_logout_uri"));
clientHasBackChannelLogoutUri = !Strings.isNullOrEmpty(env.getString("client", "backchannel_logout_uri"));
if(clientHasBackChannelLogoutUri) {
//this must be created before the session is actually removed from env
createLogoutToken();
}
Object viewToReturn = super.handleEndSessionEndpointRequest(requestId);
if(clientHasBackChannelLogoutUri) {
sendBackChannelLogoutRequest();
}
return viewToReturn;
}
@Override
protected Object createEndSessionEndpointResponse() {
if(clientHasFrontChannelLogoutUri) {
createFrontChannelLogoutRequestUrl();
return createFrontChannelLogoutModelAndView(false);
} else {
return super.createEndSessionEndpointResponse();
}
}
}
|
Maxul/sgx_vmx_protocol | Sandbox/qemu-sgx-master/slirp/tftp.h | /* tftp defines */
#ifndef SLIRP_TFTP_H
#define SLIRP_TFTP_H
#define TFTP_SESSIONS_MAX 20
#define TFTP_SERVER 69
#define TFTP_RRQ 1
#define TFTP_WRQ 2
#define TFTP_DATA 3
#define TFTP_ACK 4
#define TFTP_ERROR 5
#define TFTP_OACK 6
#define TFTP_FILENAME_MAX 512
struct tftp_t {
struct udphdr udp;
uint16_t tp_op;
union {
struct {
uint16_t tp_block_nr;
uint8_t tp_buf[512];
} tp_data;
struct {
uint16_t tp_error_code;
uint8_t tp_msg[512];
} tp_error;
char tp_buf[512 + 2];
} x;
} __attribute__((packed));
struct tftp_session {
Slirp *slirp;
char *filename;
int fd;
struct sockaddr_storage client_addr;
uint16_t client_port;
uint32_t block_nr;
int timestamp;
};
void tftp_input(struct sockaddr_storage *srcsas, struct mbuf *m);
#endif
|
TR-API-Samples/Example.EMA.Java.ValueAddObjects | src/com/refinitiv/platformservices/rt/objects/data/OmmTimeImpl.java | /*
* Copyright 2021 Refinitiv
*
* DISCLAIMER: This source code has been written by Refinitiv for the only
* purpose of illustrating articles published on the Refinitiv Developer
* Community. It has not been tested for usage in production environments.
* Refinitiv cannot be held responsible for any issues that may happen if
* these objects or the related source code is used in production or any other
* client environment.
*
* Refinitiv Developer Community: https://developers.refinitiv.com
*
*/
package com.refinitiv.platformservices.rt.objects.data;
import com.refinitiv.ema.access.DataType;
import com.refinitiv.ema.access.OmmTime;
/**
*
* In-memory implementation of the <code>OmmTime</code> interface.
*/
class OmmTimeImpl extends DataImpl implements OmmTime
{
private final int hour;
private final int minute;
private final int second;
private final int millisecond;
private final int microsecond;
private final int nanosecond;
private final String valueAsString;
/**
* Copy the given <code>OmmTime</code>
* @param ommTime the <code>OmmTime</code> to copy.
*/
public OmmTimeImpl(OmmTime ommTime)
{
super(ommTime);
this.hour = ommTime.hour();
this.minute = ommTime.minute();
this.second = ommTime.second();
this.millisecond = ommTime.millisecond();
this.microsecond = ommTime.microsecond();
this.nanosecond = ommTime.nanosecond();
this.valueAsString = ommTime.toString();
}
@Override
public int dataType()
{
return DataType.DataTypes.TIME;
}
@Override
public int hour()
{
return hour;
}
@Override
public int minute()
{
return minute;
}
@Override
public int second()
{
return second;
}
@Override
public int millisecond()
{
return millisecond;
}
@Override
public int microsecond()
{
return microsecond;
}
@Override
public int nanosecond()
{
return nanosecond;
}
@Override
public String toString()
{
return valueAsString;
}
} |
devibizsys/unip | app_app_pub/src/main/webapp/app/js/wf/WFUserAssistEditView2Controller.js | var WFUserAssistEditView2Controller = WFUserAssistEditView2ControllerBase.extend({}); |
Simcon/dotNetify | _archive/src/react/dotnetify-react.scope.js | /*
Copyright 2017 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Support using AMD or CommonJS that loads our app.js, or being placed in <script> tag.
(function (factory) {
if (typeof exports === "object" && typeof module === "object") {
module.exports = factory(require('create-react-class'), require('prop-types'), require('dotnetify'));
}
else if (typeof define === "function" && define["amd"]) {
define(['create-react-class', 'prop-types', 'dotnetify'], factory);
}
else {
factory(createReactClass, PropTypes, dotnetify);
}
}
(function (createReactClass, PropTypes, dotnetify) {
// The <Scope> component uses React's 'context' to pass down the component hierarchy the name of the back-end view model
// of the parent component, so that when the child component connects to its back-end view model, the child view model
// instance is created within the scope of the parent view model.
// The <Scope> component also provides the 'connect' function for a component to connect to the back-end view model and
// injects properties and dispatch functions into the component.
dotnetify.react.Scope = createReactClass({
displayName: "Scope",
version: "1.1.0",
propTypes: { vm: PropTypes.string },
contextTypes: { scoped: PropTypes.func },
childContextTypes: {
scoped: PropTypes.func.isRequired,
connect: PropTypes.func.isRequired
},
scoped: function scoped(vmId) {
var scope = this.context.scoped ? this.context.scoped(this.props.vm) : this.props.vm;
return scope ? scope + "." + vmId : vmId;
},
getChildContext: function getChildContext() {
var _this = this;
return {
scoped: function scoped(vmId) {
return _this.scoped(vmId);
},
connect: function connect(vmId, component, options) {
component.vmId = _this.scoped(vmId);
component.vm = dotnetify.react.connect(component.vmId, component, options);
component.dispatch = function (state) { return component.vm.$dispatch(state); };
component.dispatchState = function (state) {
component.vm.State(state);
component.vm.$dispatch(state);
};
return window.vmStates ? window.vmStates[component.vmId] : null;
}
};
},
render: function render() {
return this.props.children;
}
});
return dotnetify.react.Scope;
})) |
TISparta/competitive-programming-solutions | UVa/Competitive_Programming_Exercises/03-Problem_Solving_Paradigms/03-Greedy/01-Classical_Usually_Easier/01193.cpp | <filename>UVa/Competitive_Programming_Exercises/03-Problem_Solving_Paradigms/03-Greedy/01-Classical_Usually_Easier/01193.cpp
#include <bits/stdc++.h>
#define SIZE 1010
using namespace std;
int n, d, ans, tc, j, x, y;
pair <double, double> v[SIZE];
bool check;
double dx;
int main(){
while(scanf("%d %d", &n, &d), n | d){
check = true;
for(int i = 0; i < n; i++){
scanf("%d %d", &x, &y);
if(y > d) check = false;
dx = sqrt(d * d - y * y);
v[i] = make_pair(x + dx, x - dx);
}
sort(v ,v + n);
ans = 0;
for(int i = 0; check && i < n; ans++){
for(j = i; j <n && v[i].first >= v[j].second; j++) ;
i = j;
}
ans = check ? ans : -1;
printf("Case %d: %d\n", ++tc, ans);
}
return(0);
}
|
ant0ine/phantomjs | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGFETileElement.cpp | <gh_stars>10-100
/*
* Copyright (C) 2004, 2005, 2007 <NAME> <<EMAIL>>
* Copyright (C) 2004, 2005 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG) && ENABLE(FILTERS)
#include "SVGFETileElement.h"
#include "Attribute.h"
#include "FilterEffect.h"
#include "SVGFilterBuilder.h"
#include "SVGNames.h"
#include "SVGRenderStyle.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_STRING(SVGFETileElement, SVGNames::inAttr, In1, in1)
inline SVGFETileElement::SVGFETileElement(const QualifiedName& tagName, Document* document)
: SVGFilterPrimitiveStandardAttributes(tagName, document)
{
}
PassRefPtr<SVGFETileElement> SVGFETileElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new SVGFETileElement(tagName, document));
}
void SVGFETileElement::parseMappedAttribute(Attribute* attr)
{
const String& value = attr->value();
if (attr->name() == SVGNames::inAttr)
setIn1BaseValue(value);
else
SVGFilterPrimitiveStandardAttributes::parseMappedAttribute(attr);
}
void SVGFETileElement::svgAttributeChanged(const QualifiedName& attrName)
{
SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(attrName);
if (attrName == SVGNames::inAttr)
invalidate();
}
void SVGFETileElement::synchronizeProperty(const QualifiedName& attrName)
{
SVGFilterPrimitiveStandardAttributes::synchronizeProperty(attrName);
if (attrName == anyQName() || attrName == SVGNames::inAttr)
synchronizeIn1();
}
AttributeToPropertyTypeMap& SVGFETileElement::attributeToPropertyTypeMap()
{
DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ());
return s_attributeToPropertyTypeMap;
}
void SVGFETileElement::fillAttributeToPropertyTypeMap()
{
AttributeToPropertyTypeMap& attributeToPropertyTypeMap = this->attributeToPropertyTypeMap();
SVGFilterPrimitiveStandardAttributes::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap);
attributeToPropertyTypeMap.set(SVGNames::inAttr, AnimatedString);
}
PassRefPtr<FilterEffect> SVGFETileElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
{
FilterEffect* input1 = filterBuilder->getEffectById(in1());
if (!input1)
return 0;
RefPtr<FilterEffect> effect = FETile::create(filter);
effect->inputEffects().append(input1);
return effect.release();
}
}
#endif // ENABLE(SVG)
|
lastweek/source-freebsd | src/share/examples/tests/tests/plain/printf_test.c | /* $FreeBSD$ */
/*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright 2013 Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Google Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/*
* INTRODUCTION
*
* This plain test program mimics the structure and contents of its
* ATF-based counterpart. It attempts to represent various test cases
* in different separate functions and just calls them all from main().
*
* In reality, plain test programs can be much simpler. All they have
* to do is return 0 on success and non-0 otherwise.
*/
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
snprintf__two_formatters(void)
{
char buffer[128];
if (snprintf(buffer, sizeof(buffer), "%s, %s!", "Hello",
"tests") <= 0)
errx(EXIT_FAILURE, "snprintf with two formatters failed");
if (strcmp(buffer, "Hello, tests!") != 0)
errx(EXIT_FAILURE, "Bad formatting: got %s", buffer);
}
static void
snprintf__overflow(void)
{
char buffer[10];
if (snprintf(buffer, sizeof(buffer), "0123456789abcdef") != 16)
errx(EXIT_FAILURE, "snprintf did not return the expected "
"number of characters");
if (strcmp(buffer, "012345678") != 0)
errx(EXIT_FAILURE, "Bad formatting: got %s", buffer);
}
static void
fprintf__simple_string(void)
{
FILE *file;
char buffer[128];
size_t length;
const char *contents = "This is a message\n";
file = fopen("test.txt", "w+");
if (fprintf(file, "%s", contents) <= 0)
err(EXIT_FAILURE, "fprintf failed to write to file");
rewind(file);
length = fread(buffer, 1, sizeof(buffer) - 1, file);
if (length != strlen(contents))
err(EXIT_FAILURE, "fread failed");
buffer[length] = '\0';
fclose(file);
if (strcmp(buffer, contents) != 0)
errx(EXIT_FAILURE, "Written and read data differ");
/* Of special note here is that we are NOT deleting the temporary
* files we created in this test. Kyua takes care of this cleanup
* automatically and tests can (and should) rely on this behavior. */
}
int
main(void)
{
/* If you have read the printf_test.c counterpart in the atf/
* directory, you may think that the sequencing of tests below and
* the exposed behavior to the user is very similar. But you'd be
* wrong.
*
* There are two major differences with this and the ATF version.
* The first is that the code below has no provisions to detect
* failures in one test and continue running the other tests: the
* first failure causes the whole test program to exit. The second
* is that this particular main() has no arguments: without ATF,
* all test programs may expose a different command-line interface,
* and this is an issue for consistency purposes. */
snprintf__two_formatters();
snprintf__overflow();
fprintf__simple_string();
return EXIT_SUCCESS;
}
|
yangfancoming/mockito | src/main/java/org/mockito/invocation/Location.java |
package org.mockito.invocation;
import org.mockito.NotExtensible;
/**
* Describes the location of something in the source code.
*/
@NotExtensible
public interface Location {
/**
* Human readable location in the source code, see {@link Invocation#getLocation()}
*
* @return location
*/
String toString();
/**
* Source file of this location
*
* @return source file
* @since 2.24.6
*/
String getSourceFile();
}
|
taolinqu/ds4p | DS4P/access-control-service/common-library/src/main/java/org/hl7/v3/ActRelationshipHasComponent.java | package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
@XmlType(name="ActRelationshipHasComponent")
@XmlEnum
public enum ActRelationshipHasComponent
{
COMP,
ARR,
CTRLV,
DEP;
public String value() {
return name();
}
public static ActRelationshipHasComponent fromValue(String v) {
return valueOf(v);
}
}
|
AlexGuti14/harvesting-tfg | harvesting-dashboard/frontend/src/backend/cereal.js | <reponame>AlexGuti14/harvesting-tfg<filename>harvesting-dashboard/frontend/src/backend/cereal.js
import {doGet} from "./common";
function getCerealData(params, callback){
//console.log("### GetHistoryData", params);
doGet("/cereal/aggregate", params, callback)
}
function getCerealMarkets(params, callback){
doGet("/cereal/markets", params, callback)
}
export {getCerealData,getCerealMarkets}
|
rreusser/demos | regl-sketches/src/012/invert-camera.js | const invert = require('gl-mat4/invert');
module.exports = function (regl) {
let m1 = [];
let m2 = [];
return regl({
uniforms: {
iview: ctx => invert(m1, ctx.view),
iproj: ctx => invert(m2, ctx.projection),
}
});
}
|
OAGi/Score | score-http/score-repo/src/main/java/org/oagi/score/repo/api/impl/jooq/entity/tables/Bcc.java | <reponame>OAGi/Score
/*
* This file is generated by jOOQ.
*/
package org.oagi.score.repo.api.impl.jooq.entity.tables;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.TableImpl;
import org.jooq.types.ULong;
import org.oagi.score.repo.api.impl.jooq.entity.Indexes;
import org.oagi.score.repo.api.impl.jooq.entity.Keys;
import org.oagi.score.repo.api.impl.jooq.entity.Oagi;
import org.oagi.score.repo.api.impl.jooq.entity.tables.records.BccRecord;
/**
* A BCC represents a relationship/association between an ACC and a BCCP.
* It creates a data element for an ACC.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Bcc extends TableImpl<BccRecord> {
private static final long serialVersionUID = 1L;
/**
* The reference instance of <code>oagi.bcc</code>
*/
public static final Bcc BCC = new Bcc();
/**
* The class holding records for this type
*/
@Override
public Class<BccRecord> getRecordType() {
return BccRecord.class;
}
/**
* The column <code>oagi.bcc.bcc_id</code>. A internal, primary database key of an BCC.
*/
public final TableField<BccRecord, ULong> BCC_ID = createField(DSL.name("bcc_id"), SQLDataType.BIGINTUNSIGNED.nullable(false).identity(true), this, "A internal, primary database key of an BCC.");
/**
* The column <code>oagi.bcc.guid</code>. A globally unique identifier (GUID).
*/
public final TableField<BccRecord, String> GUID = createField(DSL.name("guid"), SQLDataType.CHAR(32).nullable(false), this, "A globally unique identifier (GUID).");
/**
* The column <code>oagi.bcc.cardinality_min</code>. Minimum cardinality of the TO_BCCP_ID. The valid values are non-negative integer.
*/
public final TableField<BccRecord, Integer> CARDINALITY_MIN = createField(DSL.name("cardinality_min"), SQLDataType.INTEGER.nullable(false), this, "Minimum cardinality of the TO_BCCP_ID. The valid values are non-negative integer.");
/**
* The column <code>oagi.bcc.cardinality_max</code>. Maximum cardinality of the TO_BCCP_ID. The valid values are integer -1 and up. Specifically, -1 means unbounded. 0 means prohibited or not to use.',
*/
public final TableField<BccRecord, Integer> CARDINALITY_MAX = createField(DSL.name("cardinality_max"), SQLDataType.INTEGER, this, "Maximum cardinality of the TO_BCCP_ID. The valid values are integer -1 and up. Specifically, -1 means unbounded. 0 means prohibited or not to use.',");
/**
* The column <code>oagi.bcc.to_bccp_id</code>. TO_BCCP_ID is a foreign key to an BCCP table record. It is basically pointing to a child data element of the FROM_ACC_ID.
Note that for the BCC history records, this column always points to the BCCP_ID of the current record of a BCCP.',
*/
public final TableField<BccRecord, ULong> TO_BCCP_ID = createField(DSL.name("to_bccp_id"), SQLDataType.BIGINTUNSIGNED.nullable(false), this, "TO_BCCP_ID is a foreign key to an BCCP table record. It is basically pointing to a child data element of the FROM_ACC_ID. \n\nNote that for the BCC history records, this column always points to the BCCP_ID of the current record of a BCCP.',");
/**
* The column <code>oagi.bcc.from_acc_id</code>. FROM_ACC_ID is a foreign key pointing to an ACC record. It is basically pointing to a parent data element (type) of the TO_BCCP_ID.
Note that for the BCC history records, this column always points to the ACC_ID of the current record of an ACC.
*/
public final TableField<BccRecord, ULong> FROM_ACC_ID = createField(DSL.name("from_acc_id"), SQLDataType.BIGINTUNSIGNED.nullable(false), this, "FROM_ACC_ID is a foreign key pointing to an ACC record. It is basically pointing to a parent data element (type) of the TO_BCCP_ID. \n\nNote that for the BCC history records, this column always points to the ACC_ID of the current record of an ACC.");
/**
* The column <code>oagi.bcc.seq_key</code>. @deprecated since 2.0.0. This indicates the order of the associations among other siblings. A valid value is positive integer. The SEQ_KEY at the CC side is localized. In other words, if an ACC is based on another ACC, SEQ_KEY of ASCCs or BCCs of the former ACC starts at 1 again.
*/
public final TableField<BccRecord, Integer> SEQ_KEY = createField(DSL.name("seq_key"), SQLDataType.INTEGER, this, "@deprecated since 2.0.0. This indicates the order of the associations among other siblings. A valid value is positive integer. The SEQ_KEY at the CC side is localized. In other words, if an ACC is based on another ACC, SEQ_KEY of ASCCs or BCCs of the former ACC starts at 1 again.");
/**
* The column <code>oagi.bcc.entity_type</code>. This is a code list: 0 = ATTRIBUTE and 1 = ELEMENT. An expression generator may or may not use this information. This column is necessary because some of the BCCs are xsd:attribute and some are xsd:element in the OAGIS 10.x.
*/
public final TableField<BccRecord, Integer> ENTITY_TYPE = createField(DSL.name("entity_type"), SQLDataType.INTEGER, this, "This is a code list: 0 = ATTRIBUTE and 1 = ELEMENT. An expression generator may or may not use this information. This column is necessary because some of the BCCs are xsd:attribute and some are xsd:element in the OAGIS 10.x. ");
/**
* The column <code>oagi.bcc.den</code>. DEN (dictionary entry name) of the BCC. This column can be derived from QUALIFIER and OBJECT_CLASS_TERM of the FROM_ACC_ID and DEN of the TO_BCCP_ID as QUALIFIER + "_ " + OBJECT_CLASS_TERM + ". " + DEN.
*/
public final TableField<BccRecord, String> DEN = createField(DSL.name("den"), SQLDataType.VARCHAR(200).nullable(false), this, "DEN (dictionary entry name) of the BCC. This column can be derived from QUALIFIER and OBJECT_CLASS_TERM of the FROM_ACC_ID and DEN of the TO_BCCP_ID as QUALIFIER + \"_ \" + OBJECT_CLASS_TERM + \". \" + DEN. ");
/**
* The column <code>oagi.bcc.definition</code>. This is a documentation or description of the BCC. Since BCC is business context independent, this is a business context independent description of the BCC. Since there are definitions also in the BCCP (as referenced by TO_BCCP_ID column) and the BDT under that BCCP, the definition in the BCC is a specific description about the relationship between the ACC (as in FROM_ACC_ID) and the BCCP.
*/
public final TableField<BccRecord, String> DEFINITION = createField(DSL.name("definition"), SQLDataType.CLOB, this, "This is a documentation or description of the BCC. Since BCC is business context independent, this is a business context independent description of the BCC. Since there are definitions also in the BCCP (as referenced by TO_BCCP_ID column) and the BDT under that BCCP, the definition in the BCC is a specific description about the relationship between the ACC (as in FROM_ACC_ID) and the BCCP.");
/**
* The column <code>oagi.bcc.definition_source</code>. This is typically a URL identifying the source of the DEFINITION column.
*/
public final TableField<BccRecord, String> DEFINITION_SOURCE = createField(DSL.name("definition_source"), SQLDataType.VARCHAR(100), this, "This is typically a URL identifying the source of the DEFINITION column.");
/**
* The column <code>oagi.bcc.created_by</code>. Foreign key to the APP_USER table referring to the user who creates the entity.
This column never change between the history and the current record. The history record should have the same value as that of its current record.
*/
public final TableField<BccRecord, ULong> CREATED_BY = createField(DSL.name("created_by"), SQLDataType.BIGINTUNSIGNED.nullable(false), this, "Foreign key to the APP_USER table referring to the user who creates the entity.\n\nThis column never change between the history and the current record. The history record should have the same value as that of its current record.");
/**
* The column <code>oagi.bcc.owner_user_id</code>. Foreign key to the APP_USER table. This is the user who owns the entity, is allowed to edit the entity, and who can transfer the ownership to another user.
The ownership can change throughout the history, but undoing shouldn't rollback the ownership.
*/
public final TableField<BccRecord, ULong> OWNER_USER_ID = createField(DSL.name("owner_user_id"), SQLDataType.BIGINTUNSIGNED.nullable(false), this, "Foreign key to the APP_USER table. This is the user who owns the entity, is allowed to edit the entity, and who can transfer the ownership to another user.\n\nThe ownership can change throughout the history, but undoing shouldn't rollback the ownership.");
/**
* The column <code>oagi.bcc.last_updated_by</code>. Foreign key to the APP_USER table referring to the last user who has updated the record.
In the history record, this should always be the user who is editing the entity (perhaps except when the ownership has just been changed).
*/
public final TableField<BccRecord, ULong> LAST_UPDATED_BY = createField(DSL.name("last_updated_by"), SQLDataType.BIGINTUNSIGNED.nullable(false), this, "Foreign key to the APP_USER table referring to the last user who has updated the record. \n\nIn the history record, this should always be the user who is editing the entity (perhaps except when the ownership has just been changed).");
/**
* The column <code>oagi.bcc.creation_timestamp</code>. Timestamp when the revision of the BCC was created.
This never change for a revision.
*/
public final TableField<BccRecord, LocalDateTime> CREATION_TIMESTAMP = createField(DSL.name("creation_timestamp"), SQLDataType.LOCALDATETIME(6).nullable(false), this, "Timestamp when the revision of the BCC was created. \n\nThis never change for a revision.");
/**
* The column <code>oagi.bcc.last_update_timestamp</code>. The timestamp when the record was last updated.
The value of this column in the latest history record should be the same as that of the current record. This column keeps the record of when the change has occurred.
*/
public final TableField<BccRecord, LocalDateTime> LAST_UPDATE_TIMESTAMP = createField(DSL.name("last_update_timestamp"), SQLDataType.LOCALDATETIME(6).nullable(false), this, "The timestamp when the record was last updated.\n\nThe value of this column in the latest history record should be the same as that of the current record. This column keeps the record of when the change has occurred.");
/**
* The column <code>oagi.bcc.state</code>. Deleted, WIP, Draft, QA, Candidate, Production, Release Draft, Published. This the revision life cycle state of the BCC.
State change can't be undone. But the history record can still keep the records of when the state was changed.
*/
public final TableField<BccRecord, String> STATE = createField(DSL.name("state"), SQLDataType.VARCHAR(20), this, "Deleted, WIP, Draft, QA, Candidate, Production, Release Draft, Published. This the revision life cycle state of the BCC.\n\nState change can't be undone. But the history record can still keep the records of when the state was changed.");
/**
* The column <code>oagi.bcc.is_deprecated</code>. Indicates whether the CC is deprecated and should not be reused (i.e., no new reference to this record should be created).
*/
public final TableField<BccRecord, Byte> IS_DEPRECATED = createField(DSL.name("is_deprecated"), SQLDataType.TINYINT.nullable(false), this, "Indicates whether the CC is deprecated and should not be reused (i.e., no new reference to this record should be created).");
/**
* The column <code>oagi.bcc.replacement_bcc_id</code>. This refers to a replacement if the record is deprecated.
*/
public final TableField<BccRecord, ULong> REPLACEMENT_BCC_ID = createField(DSL.name("replacement_bcc_id"), SQLDataType.BIGINTUNSIGNED, this, "This refers to a replacement if the record is deprecated.");
/**
* The column <code>oagi.bcc.is_nillable</code>. @deprecated since 2.0.0 in favor of impossibility of nillable association (element reference) in XML schema.
Indicate whether the field can have a NULL This is corresponding to the nillable flag in the XML schema.
*/
public final TableField<BccRecord, Byte> IS_NILLABLE = createField(DSL.name("is_nillable"), SQLDataType.TINYINT.nullable(false).defaultValue(DSL.inline("0", SQLDataType.TINYINT)), this, "@deprecated since 2.0.0 in favor of impossibility of nillable association (element reference) in XML schema.\n\nIndicate whether the field can have a NULL This is corresponding to the nillable flag in the XML schema.");
/**
* The column <code>oagi.bcc.default_value</code>. This set the default value at the association level.
*/
public final TableField<BccRecord, String> DEFAULT_VALUE = createField(DSL.name("default_value"), SQLDataType.CLOB, this, "This set the default value at the association level. ");
/**
* The column <code>oagi.bcc.fixed_value</code>. This column captures the fixed value constraint. Default and fixed value constraints cannot be used at the same time.
*/
public final TableField<BccRecord, String> FIXED_VALUE = createField(DSL.name("fixed_value"), SQLDataType.CLOB, this, "This column captures the fixed value constraint. Default and fixed value constraints cannot be used at the same time.");
/**
* The column <code>oagi.bcc.prev_bcc_id</code>. A self-foreign key to indicate the previous history record.
*/
public final TableField<BccRecord, ULong> PREV_BCC_ID = createField(DSL.name("prev_bcc_id"), SQLDataType.BIGINTUNSIGNED, this, "A self-foreign key to indicate the previous history record.");
/**
* The column <code>oagi.bcc.next_bcc_id</code>. A self-foreign key to indicate the next history record.
*/
public final TableField<BccRecord, ULong> NEXT_BCC_ID = createField(DSL.name("next_bcc_id"), SQLDataType.BIGINTUNSIGNED, this, "A self-foreign key to indicate the next history record.");
private Bcc(Name alias, Table<BccRecord> aliased) {
this(alias, aliased, null);
}
private Bcc(Name alias, Table<BccRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment("A BCC represents a relationship/association between an ACC and a BCCP. It creates a data element for an ACC. "), TableOptions.table());
}
/**
* Create an aliased <code>oagi.bcc</code> table reference
*/
public Bcc(String alias) {
this(DSL.name(alias), BCC);
}
/**
* Create an aliased <code>oagi.bcc</code> table reference
*/
public Bcc(Name alias) {
this(alias, BCC);
}
/**
* Create a <code>oagi.bcc</code> table reference
*/
public Bcc() {
this(DSL.name("bcc"), null);
}
public <O extends Record> Bcc(Table<O> child, ForeignKey<O, BccRecord> key) {
super(child, key, BCC);
}
@Override
public Schema getSchema() {
return Oagi.OAGI;
}
@Override
public List<Index> getIndexes() {
return Arrays.<Index>asList(Indexes.BCC_BCC_GUID_IDX, Indexes.BCC_BCC_LAST_UPDATE_TIMESTAMP_DESC_IDX);
}
@Override
public Identity<BccRecord, ULong> getIdentity() {
return (Identity<BccRecord, ULong>) super.getIdentity();
}
@Override
public UniqueKey<BccRecord> getPrimaryKey() {
return Keys.KEY_BCC_PRIMARY;
}
@Override
public List<UniqueKey<BccRecord>> getKeys() {
return Arrays.<UniqueKey<BccRecord>>asList(Keys.KEY_BCC_PRIMARY);
}
@Override
public List<ForeignKey<BccRecord, ?>> getReferences() {
return Arrays.<ForeignKey<BccRecord, ?>>asList(Keys.BCC_TO_BCCP_ID_FK, Keys.BCC_FROM_ACC_ID_FK, Keys.BCC_CREATED_BY_FK, Keys.BCC_OWNER_USER_ID_FK, Keys.BCC_LAST_UPDATED_BY_FK, Keys.BCC_REPLACEMENT_BCC_ID_FK, Keys.BCC_PREV_BCC_ID_FK, Keys.BCC_NEXT_BCC_ID_FK);
}
private transient Bccp _bccp;
private transient Acc _acc;
private transient AppUser _bccCreatedByFk;
private transient AppUser _bccOwnerUserIdFk;
private transient AppUser _bccLastUpdatedByFk;
private transient Bcc _bccReplacementBccIdFk;
private transient Bcc _bccPrevBccIdFk;
private transient Bcc _bccNextBccIdFk;
public Bccp bccp() {
if (_bccp == null)
_bccp = new Bccp(this, Keys.BCC_TO_BCCP_ID_FK);
return _bccp;
}
public Acc acc() {
if (_acc == null)
_acc = new Acc(this, Keys.BCC_FROM_ACC_ID_FK);
return _acc;
}
public AppUser bccCreatedByFk() {
if (_bccCreatedByFk == null)
_bccCreatedByFk = new AppUser(this, Keys.BCC_CREATED_BY_FK);
return _bccCreatedByFk;
}
public AppUser bccOwnerUserIdFk() {
if (_bccOwnerUserIdFk == null)
_bccOwnerUserIdFk = new AppUser(this, Keys.BCC_OWNER_USER_ID_FK);
return _bccOwnerUserIdFk;
}
public AppUser bccLastUpdatedByFk() {
if (_bccLastUpdatedByFk == null)
_bccLastUpdatedByFk = new AppUser(this, Keys.BCC_LAST_UPDATED_BY_FK);
return _bccLastUpdatedByFk;
}
public Bcc bccReplacementBccIdFk() {
if (_bccReplacementBccIdFk == null)
_bccReplacementBccIdFk = new Bcc(this, Keys.BCC_REPLACEMENT_BCC_ID_FK);
return _bccReplacementBccIdFk;
}
public Bcc bccPrevBccIdFk() {
if (_bccPrevBccIdFk == null)
_bccPrevBccIdFk = new Bcc(this, Keys.BCC_PREV_BCC_ID_FK);
return _bccPrevBccIdFk;
}
public Bcc bccNextBccIdFk() {
if (_bccNextBccIdFk == null)
_bccNextBccIdFk = new Bcc(this, Keys.BCC_NEXT_BCC_ID_FK);
return _bccNextBccIdFk;
}
@Override
public Bcc as(String alias) {
return new Bcc(DSL.name(alias), this);
}
@Override
public Bcc as(Name alias) {
return new Bcc(alias, this);
}
/**
* Rename this table
*/
@Override
public Bcc rename(String name) {
return new Bcc(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Bcc rename(Name name) {
return new Bcc(name, null);
}
}
|
chrismattmann/oodt | xmlquery/src/main/java/org/apache/oodt/xmlquery/CompressedObjectCodec.java | <filename>xmlquery/src/main/java/org/apache/oodt/xmlquery/CompressedObjectCodec.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.oodt.xmlquery;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.StreamCorruptedException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.oodt.commons.io.Base64DecodingInputStream;
import org.apache.oodt.commons.io.Base64EncodingOutputStream;
import org.apache.oodt.commons.io.NullOutputStream;
import org.apache.oodt.commons.util.XML;
import org.apache.oodt.commons.io.CountingOutputStream;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/** A result encoder/decoder for compressed, serialized objects.
*
* This codec uses a GZIP compressed serialized object format for objects.
*
* @author Kelly
*/
class CompressedObjectCodec implements Codec {
public Node encode(Object object, Document doc) throws DOMException {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
try {
Base64EncodingOutputStream base64 = new Base64EncodingOutputStream(byteArray);
GZIPOutputStream gzip = new GZIPOutputStream(base64);
ObjectOutputStream objStream = new ObjectOutputStream(gzip);
objStream.writeObject(object);
objStream.close();
} catch (IOException cantHappen) {}
Element value = doc.createElement("resultValue");
value.appendChild(doc.createCDATASection(byteArray.toString()));
return value;
}
public Object decode(Node node) throws ClassNotFoundException, InvalidClassException, StreamCorruptedException,
OptionalDataException {
String encodedValue;
if (node.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE)
encodedValue = node.getFirstChild().getNodeValue();
else
encodedValue = XML.text(node);
Object rc = null;
try {
ByteArrayInputStream byteArray = new ByteArrayInputStream(encodedValue.getBytes());
Base64DecodingInputStream base64 = new Base64DecodingInputStream(byteArray);
GZIPInputStream gzip = new GZIPInputStream(base64);
ObjectInputStream objStream = new ObjectInputStream(gzip);
rc = objStream.readObject();
objStream.close();
} catch (InvalidClassException ex) {
throw ex;
} catch (StreamCorruptedException ex) {
throw ex;
} catch (OptionalDataException ex) {
throw ex;
} catch (IOException cantHappen) {}
return rc;
}
public InputStream getInputStream(Object value) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(value);
oos.close();
baos.close();
return new ByteArrayInputStream(baos.toByteArray());
}
public long sizeOf(Object obj) {
try {
CountingOutputStream c = new CountingOutputStream(new NullOutputStream());
ObjectOutputStream stream = new ObjectOutputStream(c);
stream.writeObject(obj);
stream.close();
return c.getBytesWritten();
} catch (IOException ex) {
throw new IllegalStateException("I/O exception " + ex.getClass().getName() + " can't happen, yet did: "
+ ex.getMessage());
}
}
}
|
zealoussnow/chromium | chrome/browser/ui/views/media_router/web_contents_display_observer_view_unittest.cc | <reponame>zealoussnow/chromium
// Copyright 2018 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.
#include <memory>
#include <utility>
#include "base/bind.h"
#include "chrome/browser/ui/views/media_router/web_contents_display_observer_view.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/public/browser/web_contents.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/display.h"
#include "ui/gfx/geometry/rect.h"
namespace media_router {
class MockCallback {
public:
MOCK_METHOD0(OnDisplayChanged, void());
};
class TestWebContentsDisplayObserverView
: public WebContentsDisplayObserverView {
public:
TestWebContentsDisplayObserverView(content::WebContents* web_contents,
base::RepeatingCallback<void()> callback,
const display::Display& test_display)
: WebContentsDisplayObserverView(web_contents, std::move(callback)),
test_display_(test_display) {}
void set_test_display(const display::Display& test_display) {
test_display_ = test_display;
}
private:
display::Display GetDisplayNearestWidget() const override {
return test_display_;
}
display::Display test_display_;
};
class WebContentsDisplayObserverViewTest
: public ChromeRenderViewHostTestHarness {
public:
WebContentsDisplayObserverViewTest()
: ChromeRenderViewHostTestHarness(), display1_(101), display2_(102) {}
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
web_contents_ = CreateTestWebContents();
display_observer_ = std::make_unique<TestWebContentsDisplayObserverView>(
web_contents_.get(),
base::BindRepeating(&MockCallback::OnDisplayChanged,
base::Unretained(&callback_)),
display1_);
}
void TearDown() override {
display_observer_.reset();
web_contents_.reset();
ChromeRenderViewHostTestHarness::TearDown();
}
protected:
std::unique_ptr<content::WebContents> web_contents_;
std::unique_ptr<TestWebContentsDisplayObserverView> display_observer_;
MockCallback callback_;
const display::Display display1_;
const display::Display display2_;
};
TEST_F(WebContentsDisplayObserverViewTest, NotifyWhenDisplayChanges) {
// Bounds change without display change should not trigger the callback.
display_observer_->OnWidgetBoundsChanged(nullptr, gfx::Rect(0, 0, 500, 500));
// If the widget is in a different display after moving, the callback should
// be called.
display_observer_->set_test_display(display2_);
EXPECT_CALL(callback_, OnDisplayChanged());
display_observer_->OnWidgetBoundsChanged(nullptr,
gfx::Rect(1920, 0, 500, 500));
EXPECT_EQ(display2_.id(), display_observer_->GetCurrentDisplay().id());
}
} // namespace media_router
|
Watch-Later/REDM | DmMain/src/Core/Event/DMEventMgr.cpp | <gh_stars>10-100
#include "DmMainAfx.h"
#include "DMEventMgr.h"
namespace DM
{
DMEventItem::DMEventItem(DWORD dwEventID):m_dwEventID(dwEventID)
{
}
DMEventItem::~DMEventItem()
{
for (UINT i=0; i<m_EvtSlots.GetCount(); i++)
{
delete m_EvtSlots[i];
}
m_EvtSlots.RemoveAll();
}
bool DMEventItem::Subscribe(const DMSlotFunctorBase&slot)
{
if (-1!=FindSlotFunctor(slot))
{
return false;
}
m_EvtSlots.Add(slot.Clone());
return true;
}
bool DMEventItem::UnSubscribe(const DMSlotFunctorBase&slot)
{
int idx = FindSlotFunctor(slot);
if (-1==idx)
{
return false;
}
delete m_EvtSlots[idx];
m_EvtSlots.RemoveAt(idx);
return true;
}
int DMEventItem::FindSlotFunctor(const DMSlotFunctorBase&slot)
{
for (UINT i=0; i<m_EvtSlots.GetCount(); i++)
{
if (m_EvtSlots[i]->Equal(slot))
{
return i;
}
}
return -1;
}
//------------------------------DMEventMgr
DMEventMgr::DMEventMgr(void)
:m_bMuted(false)
{
}
DMEventMgr::~DMEventMgr()
{
RemoveAllEvent();
}
void DMEventMgr::AddEvent(const DWORD dwEventID)
{
if (!IsEventPresent(dwEventID))
{
m_EvtArr.Add(new DMEventItem(dwEventID));
}
}
void DMEventMgr::RemoveEvent(const DWORD dwEventID)
{
for (UINT i=0; i<m_EvtArr.GetCount(); i++)
{
if (m_EvtArr[i]->GetEventID() == dwEventID)
{
delete m_EvtArr[i];
m_EvtArr.RemoveAt(i);
return;
}
}
}
bool DMEventMgr::IsEventPresent(const DWORD dwEventID)
{
return GetEventObject(dwEventID) != NULL;
}
DMEventItem *DMEventMgr::GetEventObject(const DWORD dwEventID)
{
for (UINT i=0; i<m_EvtArr.GetCount(); i++)
{
if (m_EvtArr[i]->GetEventID() == dwEventID)
{
return m_EvtArr[i];
}
}
return NULL;
}
void DMEventMgr::RemoveAllEvent(void)
{
for (UINT i=0; i<m_EvtArr.GetCount(); i++)
{
delete m_EvtArr[i];
}
m_EvtArr.RemoveAll();
}
bool DMEventMgr::SubscribeEvent(const DWORD dwEventID, const DMSlotFunctorBase & subscriber)
{
if (!IsEventPresent(dwEventID))
{
m_EvtArr.Add(new DMEventItem(dwEventID));
}
return GetEventObject(dwEventID)->Subscribe(subscriber);
}
bool DMEventMgr::UnSubscribeEvent(const DWORD dwEventID, const DMSlotFunctorBase & subscriber)
{
if (!IsEventPresent(dwEventID))
{
return false;
}
return GetEventObject(dwEventID)->UnSubscribe(subscriber);
}
void DMEventMgr::FireEvent(DMEventArgs& Args )
{
// find event object
DMEventItem* ev = GetEventObject(Args.GetEventID());
// fire the event if present and set is not muted
if ((ev != 0) && !m_bMuted)
{
(*ev)(Args);
}
}
bool DMEventMgr::IsMuted()
{
return m_bMuted;
}
void DMEventMgr::SetMuted(bool bMuted)
{
m_bMuted = bMuted;
}
}//namespace DM |
DongerZone/o3de | Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Core/CoreNodes.cpp | <gh_stars>1-10
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "CoreNodes.h"
#include <Data/DataMacros.h>
#include <Data/DataTrait.h>
#include <Execution/ExecutionState.h>
#include <ScriptCanvas/Core/Attributes.h>
#include <ScriptCanvas/Core/EBusHandler.h>
#include <ScriptCanvas/Grammar/DebugMap.h>
#include <ScriptCanvas/Libraries/Core/AzEventHandler.h>
#include <ScriptCanvas/Libraries/Core/ContainerTypeReflection.h>
#include <ScriptCanvas/Libraries/Libraries.h>
#include <ScriptCanvas/Core/SubgraphInterface.h>
namespace ContainerTypeReflection
{
#define SCRIPT_CANVAS_CALL_REFLECT_ON_TRAITS(TYPE)\
TraitsReflector<TYPE##Type>::Reflect(reflectContext);
using namespace AZStd;
using namespace ScriptCanvas;
// use this to reflect on demand reflection targets in the appropriate place
class ReflectOnDemandTargets
{
public:
AZ_TYPE_INFO(ReflectOnDemandTargets, "{FE658DB8-8F68-4E05-971A-97F398453B92}");
AZ_CLASS_ALLOCATOR(ReflectOnDemandTargets, AZ::SystemAllocator, 0);
ReflectOnDemandTargets() = default;
~ReflectOnDemandTargets() = default;
static void Reflect(AZ::ReflectContext* reflectContext)
{
using namespace ScriptCanvas::Data;
// First Macro creates a list of all of the types, that is invoked using the second macro.
SCRIPT_CANVAS_PER_DATA_TYPE(SCRIPT_CANVAS_CALL_REFLECT_ON_TRAITS);
}
};
#undef SCRIPT_CANVAS_CALL_REFLECT_ON_TRAITS
}
namespace ScriptCanvas
{
namespace Library
{
void Core::Reflect(AZ::ReflectContext* reflection)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializeContext->Class<Core, LibraryDefinition>()
->Version(1)
;
if (AZ::EditContext* editContext = serializeContext->GetEditContext())
{
editContext->Class<Core>("Core", "")->
ClassElement(AZ::Edit::ClassElements::EditorData, "")->
Attribute(AZ::Edit::Attributes::Icon, "Icons/ScriptCanvas/Libraries/Core.png")->
Attribute(AZ::Edit::Attributes::CategoryStyle, ".time")->
Attribute(ScriptCanvas::Attributes::Node::TitlePaletteOverride, "TimeNodeTitlePalette")
;
}
}
Nodes::Core::EBusEventEntry::Reflect(reflection);
Nodes::Core::AzEventEntry::Reflect(reflection);
Nodes::Core::Internal::ScriptEventEntry::Reflect(reflection);
Nodes::Core::Internal::ScriptEventBase::Reflect(reflection);
Nodes::Core::Internal::Nodeling::Reflect(reflection);
ContainerTypeReflection::ReflectOnDemandTargets::Reflect(reflection);
// reflected to go over the network
ExecutionState::Reflect(reflection);
Grammar::Variable::Reflect(reflection);
Grammar::FunctionPrototype::Reflect(reflection);
// reflect to build nodes that are built from sub graph definitions
Grammar::SubgraphInterface::Reflect(reflection);
// used to speed up the broadcast of debug information from Lua
Grammar::ReflectDebugSymbols(reflection);
//ContainerTypeReflection::TraitsReflector<AzFramework::SliceInstantiationTicket>::Reflect(reflection);
SlotExecution::Map::Reflect(reflection);
EBusHandler::Reflect(reflection);
}
void Core::InitNodeRegistry(NodeRegistry& nodeRegistry)
{
using namespace ScriptCanvas::Nodes::Core;
AddNodeToRegistry<Core, Error>(nodeRegistry);
AddNodeToRegistry<Core, ErrorHandler>(nodeRegistry);
AddNodeToRegistry<Core, Method>(nodeRegistry);
AddNodeToRegistry<Core, MethodOverloaded>(nodeRegistry);
AddNodeToRegistry<Core, BehaviorContextObjectNode>(nodeRegistry);
AddNodeToRegistry<Core, Start>(nodeRegistry);
AddNodeToRegistry<Core, ScriptCanvas::Nodes::Core::String>(nodeRegistry);
AddNodeToRegistry<Core, EBusEventHandler>(nodeRegistry);
AddNodeToRegistry<Core, AzEventHandler>(nodeRegistry);
AddNodeToRegistry<Core, ExtractProperty>(nodeRegistry);
AddNodeToRegistry<Core, ForEach>(nodeRegistry);
AddNodeToRegistry<Core, GetVariableNode>(nodeRegistry);
AddNodeToRegistry<Core, SetVariableNode>(nodeRegistry);
AddNodeToRegistry<Core, ReceiveScriptEvent>(nodeRegistry);
AddNodeToRegistry<Core, SendScriptEvent>(nodeRegistry);
AddNodeToRegistry<Core, Repeater>(nodeRegistry);
AddNodeToRegistry<Core, FunctionCallNode>(nodeRegistry);
AddNodeToRegistry<Core, FunctionDefinitionNode>(nodeRegistry);
// Nodeables
AddNodeToRegistry<Core, Nodes::RepeaterNodeableNode>(nodeRegistry);
}
AZStd::vector<AZ::ComponentDescriptor*> Core::GetComponentDescriptors()
{
return AZStd::vector<AZ::ComponentDescriptor*>({
ScriptCanvas::Nodes::Core::Error::CreateDescriptor(),
ScriptCanvas::Nodes::Core::ErrorHandler::CreateDescriptor(),
ScriptCanvas::Nodes::Core::Method::CreateDescriptor(),
ScriptCanvas::Nodes::Core::MethodOverloaded::CreateDescriptor(),
ScriptCanvas::Nodes::Core::BehaviorContextObjectNode::CreateDescriptor(),
ScriptCanvas::Nodes::Core::Start::CreateDescriptor(),
ScriptCanvas::Nodes::Core::String::CreateDescriptor(),
ScriptCanvas::Nodes::Core::EBusEventHandler::CreateDescriptor(),
ScriptCanvas::Nodes::Core::AzEventHandler::CreateDescriptor(),
ScriptCanvas::Nodes::Core::ExtractProperty::CreateDescriptor(),
ScriptCanvas::Nodes::Core::ForEach::CreateDescriptor(),
ScriptCanvas::Nodes::Core::GetVariableNode::CreateDescriptor(),
ScriptCanvas::Nodes::Core::SetVariableNode::CreateDescriptor(),
ScriptCanvas::Nodes::Core::ReceiveScriptEvent::CreateDescriptor(),
ScriptCanvas::Nodes::Core::SendScriptEvent::CreateDescriptor(),
ScriptCanvas::Nodes::Core::Repeater::CreateDescriptor(),
ScriptCanvas::Nodes::Core::FunctionCallNode::CreateDescriptor(),
ScriptCanvas::Nodes::Core::FunctionDefinitionNode::CreateDescriptor(),
// Nodeables
ScriptCanvas::Nodes::RepeaterNodeableNode::CreateDescriptor(),
});
}
}
}
|
giantchen2012/poplibs | tests/popsolver/Sum.cpp | <filename>tests/popsolver/Sum.cpp
// Copyright (c) 2018 Graphcore Ltd. All rights reserved.
#include "Constraint.hpp"
#include "Scheduler.hpp"
#include <memory>
#define BOOST_TEST_MODULE Sum
#include <boost/test/unit_test.hpp>
using namespace popsolver;
BOOST_AUTO_TEST_CASE(PropagateNoChange) {
Variable a(0), b(1), c(2);
auto sum = std::unique_ptr<Sum>(new Sum(c, {a, b}));
Domains domains;
domains.push_back({DataType{7}, DataType{8}}); // a
domains.push_back({DataType{2}, DataType{5}}); // b
domains.push_back({DataType{9}, DataType{13}}); // c
Scheduler scheduler(domains, {sum.get()});
bool success = sum->propagate(scheduler);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{7});
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{8});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{5});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{9});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{13});
}
BOOST_AUTO_TEST_CASE(PropagateResult) {
Variable a(0), b(1), c(2);
auto sum = std::unique_ptr<Sum>(new Sum(c, {a, b}));
Domains domains;
domains.push_back({DataType{7}, DataType{8}}); // a
domains.push_back({DataType{2}, DataType{5}}); // b
domains.push_back({DataType{1}, DataType{20}}); // c
Scheduler scheduler(domains, {sum.get()});
bool success = sum->propagate(scheduler);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{7});
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{8});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{5});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{9});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{13});
}
BOOST_AUTO_TEST_CASE(PropagateOperands) {
Variable a(0), b(1), c(2);
auto sum = std::unique_ptr<Sum>(new Sum(c, {a, b}));
Domains domains;
domains.push_back({DataType{7}, DataType{1000}}); // a
domains.push_back({DataType{0}, DataType{9}}); // b
domains.push_back({DataType{9}, DataType{13}}); // c
Scheduler scheduler(domains, {sum.get()});
bool success = sum->propagate(scheduler);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{7});
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{13});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{0});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{6});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{9});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{13});
}
BOOST_AUTO_TEST_CASE(PropagateBoth) {
Variable a(0), b(1), c(2);
auto sum = std::unique_ptr<Sum>(new Sum(c, {a, b}));
Domains domains;
domains.push_back({DataType{7}, DataType{8}}); // a
domains.push_back({DataType{0}, DataType{5}}); // b
domains.push_back({DataType{9}, DataType{20}}); // c
Scheduler scheduler(domains, {sum.get()});
bool success = sum->propagate(scheduler);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{7});
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{8});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{1});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{5});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{9});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{13});
}
BOOST_AUTO_TEST_CASE(AvoidOverflow) {
Variable a(0), b(1), c(2);
auto sum = std::unique_ptr<Sum>(new Sum(c, {a, b}));
Domains domains;
domains.push_back({DataType{1}, DataType::max() - DataType{1}}); // a
domains.push_back({DataType{2}, DataType::max() - DataType{1}}); // b
domains.push_back({DataType{20}, DataType{21}}); // c
Scheduler scheduler(domains, {sum.get()});
bool success = sum->propagate(scheduler);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].min(), DataType{1});
BOOST_CHECK_EQUAL(scheduler.getDomains()[a].max(), DataType{19});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].min(), DataType{2});
BOOST_CHECK_EQUAL(scheduler.getDomains()[b].max(), DataType{20});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].min(), DataType{20});
BOOST_CHECK_EQUAL(scheduler.getDomains()[c].max(), DataType{21});
}
|
ecrc/bemfmm | include/fmm/partition.h | <reponame>ecrc/bemfmm<filename>include/fmm/partition.h
#ifndef partition_h
#define partition_h
#include "logger.h"
#include "sort.h"
#include "hilbert_key.h"
#if EXAFMM_USE_PARMETIS
#include "parmetis_wrapper.h"
#endif
#include <numeric>
namespace exafmm {
//! Handles all the partitioning of domains
class Partition {
typedef std::vector<int64_t> VHilbert; //!< Type of Hilbert key vectors
typedef std::pair<int64_t, int64_t> KeyPair; //!< Type of Hilbert Key Pair
private:
const int mpirank; //!< Rank of MPI communicator
const int mpisize; //!< Size of MPI communicator
const int numBins; //!< Number of sampling bins
int numLevels; //!< Levels of MPI rank binary tree
int * rankDispl; //!< Displacement of MPI rank group
int * rankCount; //!< Size of MPI rank group
int * rankColor; //!< Color of MPI rank group
int * rankKey; //!< Key of MPI rank group
int * rankMap; //!< Map partition to MPI rank group
int * sendDispl; //!< Displacement of bodies to send per rank
int * sendCount; //!< Count of bodies to send per rank
int * scanHist; //!< Scan of histogram
int * countHist; //!< Body count histogram
float * weightHist; //!< Body weight histogram
float * globalHist; //!< Global body weight histogram
Bounds * rankBounds; //!< Bounds of each rank
Bodies buffer; //!< MPI communication buffer for bodies
VHilbert range; //!< Key ranges for ranks
VHilbert::iterator rangeBegin; //!< begin iterator of range
VHilbert::iterator rangeEnd; //!< end iterator of range
KeyPair globalKeyBounds; //!< Global key bounds
private:
//! Generate Space-filling order (Hilbert) from given the particles structure and returns min/max orders
KeyPair assignSFCtoBodies(Bodies& bodies, Bounds const& bounds, uint32_t& order) {
real_t const& _min = min(bounds.Xmin); // get min of all dimensions
real_t const& _max = max(bounds.Xmax); // get max of all dimensions
uint64_t min_h = 0xFFFFFFFFFFFFFFFF; // initialize min Hilbert order
uint64_t max_h = 0ull; // initialize max Hilbert order
//order = cast_coord(ceil(log(mpisize) / log(8))) + 1; // get needed bits to represent Hilbert order in each dimension
order = 21;
uint32_t nbins = 1 << order;
real_t diameter = _max - _min; // set domain's diameter
assert(order <= 21); // maximum key is 63 bits
B_iter begin = bodies.begin(); // bodies begin iterator
for (int i = 0; i < bodies.size(); ++i) { // loop over bodies
B_iter B = begin + i; // Capture body iterator
int position[3] = { // initialize shifted position
cast_coord((B->X[0] - _min) / diameter * nbins),
cast_coord((B->X[1] - _min) / diameter * nbins),
cast_coord((B->X[2] - _min) / diameter * nbins)
};
#if 1
axesToTranspose(position, order); // get transposed Hilbert order
B->ICELL = flattenTransposedKey(position, order); // generate 1 flat Hilbert order (useful for efficient sorting)
#else
B->ICELL = getHilbert(position, order);
#endif
if (B->ICELL > max_h) // update min/max hilbert orders
max_h = B->ICELL;
else if (B->ICELL < min_h)
min_h = B->ICELL;
} // end loop
return std::make_pair(min_h, max_h); // return min/max tuple
}
//! Gets the rank based on the key given the range
inline int getPartitionNumber(int64_t const& key) {
VHilbert::iterator low = std::lower_bound(rangeBegin, rangeEnd, key);//!< get iterator of first element that is >= input key
if (low > rangeBegin) {
return (low - rangeBegin) - 1;
}
return 0;
}
//! updates range parameters
void updateRangeParameters(VHilbert const& rg) {
range = rg;
rangeBegin = range.begin();
rangeEnd = range.end();
globalKeyBounds.first = range[0];
globalKeyBounds.second = range[mpisize];
}
//! applies partition sort algorithm to sort through particles based on Hilbert index
void hilbertPartitionSort(VHilbert& keys, int64_t lbound, int64_t rbound, VHilbert&rq, int64_t pivot = 0, size_t depth = 0) {
VHilbert right;
VHilbert left;
for (int i = 0; i < keys.size(); ++i) {
if (keys[i] >= pivot)
right.push_back(keys[i]);
else left.push_back(keys[i]);
}
size_t sendSize[2];
sendSize[0] = right.size();
sendSize[1] = left.size();
size_t size_d[2];
MPI_Allreduce(sendSize, size_d, 2, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); // Reduce domain SUM
float diff = 0.0f;
size_t max = std::max(size_d[0], size_d[1]);
size_t min = std::min(size_d[0], size_d[1]);
diff = (max - min) / float(max);
size_t templ = lbound;
size_t tempr = rbound;
while (diff > 0.05f && tempr - templ > 1) {
if (size_d[0] > size_d[1]) {
templ = pivot;
pivot += (tempr - pivot) >> 1;
}
else if (size_d[1] > size_d[0]) {
tempr = pivot;
pivot -= (pivot - templ) >> 1;
}
right.clear();
left.clear();
for (int i = 0; i < keys.size(); ++i) {
if (keys[i] >= pivot)
right.push_back(keys[i]);
else left.push_back(keys[i]);
}
sendSize[0] = right.size();
sendSize[1] = left.size();
MPI_Allreduce(sendSize, size_d, 2, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); // Reduce domain SUM
max = std::max(size_d[0], size_d[1]);
min = std::min(size_d[0], size_d[1]);
diff = (max - min) / float(max);
}
rq.push_back(pivot);
if (2 << depth < mpisize) {
hilbertPartitionSort(left , lbound, pivot, rq, lbound + ((pivot - lbound) >> 1), depth + 1);
hilbertPartitionSort(right, pivot, rbound, rq, pivot + ((rbound - pivot) >> 1), depth + 1);
}
}
public:
//! Constructor
Partition(int _mpirank, int _mpisize): mpirank(_mpirank), mpisize(_mpisize), numBins(16) {
rankDispl = new int [mpisize]; // Allocate displacement of MPI rank group
rankCount = new int [mpisize]; // Allocate size of MPI rank group
rankColor = new int [mpisize]; // Allocate color of MPI rank group
rankKey = new int [mpisize]; // Allocate key of MPI rank group
rankMap = new int [mpisize]; // Allocate map for partition to MPI rank group
sendDispl = new int [mpisize]; // Allocate displacement of bodies to send per rank
sendCount = new int [mpisize]; // Allocate count of bodies to send per rank
scanHist = new int [numBins]; // Allocate scan of histogram
countHist = new int [numBins]; // Allocate body count histogram
weightHist = new float [numBins]; // Allocate body weight histogram
globalHist = new float [numBins]; // Allocate global body weight histogram
rankBounds = new Bounds [mpisize]; // Allocate bounds of each rank
numLevels = 0; // Initialize levels of MPI rank binary tree
int size = mpisize - 1; // Initialize size of MPI rank binary tree
while (size > 0) { // While there are bits to process
size >>= 1; // Bitshift MPI size
numLevels++; // Increment levels of MPI rank binary tree
} // End while for bits to process
}
//! Destructor
~Partition() {
delete[] rankDispl; // Deallocate displacement of MPI rank group
delete[] rankCount; // Deallocate size of MPI rank group
delete[] rankColor; // Deallocate color of MPI rank group
delete[] rankKey; // Deallocate key of MPI rank group
delete[] rankMap; // Deallocate map for partition to MPI rank group
delete[] sendDispl; // Deallocate displacement of bodies to send per rank
delete[] sendCount; // Deallocate count of bodies to send per rank
delete[] scanHist; // Deallocate scan of histogram
delete[] countHist; // Deallocate body count histogram
delete[] weightHist; // Deallocate body weight histogram
delete[] globalHist; // Deallocate global body weight histogram
delete[] rankBounds; // Deallocate bounds of each rank
}
//! Partitioning by orthogonal recursive bisection
Bounds bisection(Bodies & bodies, Bounds globalBounds) {
logger::startTimer("Partition"); // Start timer
for (int irank = 0; irank < mpisize; irank++) { // Loop over MPI ranks
rankDispl[irank] = 0; // Initialize displacement of MPI rank group
rankCount[irank] = mpisize; // Initialize size of MPI rank group
rankColor[irank] = 0; // Initialize color of MPI rank group
rankKey[irank] = 0; // Initialize key of MPI rank group
rankMap[irank] = 0; // Initialize map to MPI rank group
sendDispl[irank] = 0; // Initialize displacement of bodies to send per rank
sendCount[irank] = bodies.size(); // Initialize count of bodies to send per rank
rankBounds[irank] = globalBounds; // Initialize bounds of each rank
} // End loop over MPI ranks
buffer = bodies; // Resize sort buffer
for (int level = 0; level < numLevels; level++) { // Loop over levels of MPI rank binary tree
int numPartitions = rankColor[mpisize - 1] + 1; // Number of partitions in current level
for (int ipart = 0; ipart < numPartitions; ipart++) { // Loop over partitions
int irank = rankMap[ipart]; // Map partition to MPI rank
Bounds bounds = rankBounds[irank]; // Bounds of current rank
int direction = 0; // Initialize direction of partitioning
real_t length = 0; // Initialize length of partition
for (int d = 0; d < 3; d++) { // Loop over dimensions
if (length < (bounds.Xmax[d] - bounds.Xmin[d])) { // If present dimension is longer
direction = d; // Update direction to current dimension
length = (bounds.Xmax[d] - bounds.Xmin[d]); // Update length to current dimension
} // End if for longer dimension
} // End loop over dimensions
int rankSplit = rankCount[irank] / 2; // MPI rank splitter
int oldRankCount = rankCount[irank]; // Old MPI rank count
int bodyBegin = 0; // Initialize body begin index
int bodyEnd = sendCount[irank]; // Initialize body end index
B_iter B = bodies.begin() + sendDispl[irank]; // Body begin iterator of current partition
float localWeightSum = 0; // Initialize local sum of weights in current partition
for (int b = bodyBegin; b < bodyEnd; b++) { // Loop over bodies in current partition
localWeightSum += B[b].WEIGHT; // Add weights of body to local sum
} // End loop over bodies in current partition
float globalWeightSum; // Declare global sum of weights in current partition
MPI_Allreduce(&localWeightSum, &globalWeightSum, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);// Reduce sum of weights
float globalSplit = globalWeightSum * rankSplit / oldRankCount;// Global weight splitter index
float globalOffset = 0; // Initialize global weight offset
real_t xmax = bounds.Xmax[direction]; // Upper bound of partition
real_t xmin = bounds.Xmin[direction]; // Lower bound of partition
real_t dx = (xmax - xmin) / numBins; // Length of bins
if (rankSplit > 0) { // If the partition requires splitting
for (int binRefine = 0; binRefine < 3; binRefine++) { // Loop for bin refinement
for (int ibin = 0; ibin < numBins; ibin++) { // Loop over bins
countHist[ibin] = 0; // Initialize body count histogram
weightHist[ibin] = 0; // Initialize body weight histogram
} // End loop over bins
for (int b = bodyBegin; b < bodyEnd; b++) { // Loop over bodies
real_t x = B[b].X[direction]; // Coordinate of body in current direction
int ibin = (x - xmin + EPS) / (dx + EPS); // Assign bin index to body
if (ibin >= numBins) ibin = numBins - 1; // Account for floating point errors
countHist[ibin]++; // Increment body count histogram
weightHist[ibin] += B[b].WEIGHT; // Increment body weight histogram
} // End loop over bodies
scanHist[0] = countHist[0]; // Initialize scan array
for (int ibin = 1; ibin < numBins; ibin++) { // Loop over bins
scanHist[ibin] = scanHist[ibin - 1] + countHist[ibin]; // Inclusive scan for body count histogram
} // End loop over bins
for (int b = bodyEnd - 1; b >= bodyBegin; b--) { // Loop over bodies backwards
real_t x = B[b].X[direction]; // Coordinate of body in current direction
int ibin = (x - xmin + EPS) / (dx + EPS); // Assign bin index to body
if (ibin >= numBins) ibin = numBins - 1; // Account for floating point errors
scanHist[ibin]--; // Decrement scanned histogram
int bnew = scanHist[ibin] + bodyBegin; // New index of sorted body
buffer[bnew] = B[b]; // Copy body to sort buffer
} // End loop over bodies backwards
for (int b = bodyBegin; b < bodyEnd; b++) { // Loop over bodies
B[b] = buffer[b]; // Copy back bodies from buffer
} // End loop over bodies
MPI_Allreduce(weightHist, globalHist, numBins, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD);// Reduce weight histogram
int splitBin = 0; // Initialize bin splitter
while (globalOffset < globalSplit) { // While scan of global histogram is less than splitter
globalOffset += globalHist[splitBin]; // Scan global histogram
splitBin++; // Increment bin count
} // End while for global histogram scan
splitBin--; // Move back one bin
globalOffset -= globalHist[splitBin]; // Decrement offset accordingly
xmax = xmin + (splitBin + 1) * dx; // Zoom in to current bin by redefining upper
xmin = xmin + splitBin * dx; // and lower bounds of partition
dx = (xmax - xmin) / numBins; // Update length of partition accordingly
scanHist[0] = 0; // Initialize scan array
for (int ibin = 1; ibin < numBins; ibin++) { // Loop over bins
scanHist[ibin] = scanHist[ibin - 1] + countHist[ibin - 1]; // Exclusive scan of body count histogram
} // End loop over bins
bodyBegin += scanHist[splitBin]; // Update body begin index
bodyEnd = bodyBegin + countHist[splitBin]; // Update body end index
} // End loop for bin refinement
} // End if for splitting partition
int rankBegin = rankDispl[irank]; // Save current range of MPI ranks
int rankEnd = rankBegin + rankCount[irank]; // so that they don't get overwritten
for (irank = rankBegin; irank < rankEnd; irank++) { // Loop over current range of MPI ranks
rankSplit = rankCount[irank] / 2; // MPI rank splitter
if (irank - rankDispl[irank] < rankSplit) { // If on left side of splitter
rankCount[irank] = rankSplit; // Count is the splitter index
rankColor[irank] = rankColor[irank] * 2; // Color is doubled
rankBounds[irank].Xmax[direction] = xmin; // Update right bound with splitter
sendCount[irank] = bodyBegin; // Send body count is the begin index
} else { // If on right side of splitter
rankDispl[irank] += rankSplit; // Update displacement with splitter index
rankCount[irank] -= rankSplit; // Count is remainder of splitter index
rankColor[irank] = rankColor[irank] * 2 + 1; // Color is doubled plus one
rankBounds[irank].Xmin[direction] = xmin; // Update left bound
sendDispl[irank] += bodyBegin; // Increment send body displacement
sendCount[irank] -= bodyBegin; // Decrement send body count
} // End if for side of splitter
if (level == numLevels - 1) rankColor[irank] = rankDispl[irank]; // Special case for final rank color
rankKey[irank] = irank - rankDispl[irank]; // Rank key is determined from rank displacement
} // End loop over current range of MPI ranks
} // End loop over partitions
int ipart = 0; // Initialize partition index
for (int irank = 0; irank < mpisize; irank++) { // Loop over MPI ranks
if (rankKey[irank] == 0) { // If rank key is zero it's a new group
rankMap[ipart] = rankDispl[irank]; // Update rank map with rank displacement
ipart++; // Increment partition index
} // End if for new group
} // End loop over MPI ranks
} // End loop over levels of MPI rank binary tree
B_iter B = bodies.begin(); // Body begin iterator
for (int irank = 0; irank < mpisize; irank++) { // Loop over MPI ranks
int bodyBegin = sendDispl[irank]; // Body begin index for current rank
int bodyEnd = bodyBegin + sendCount[irank]; // Body end index for current rank
for (int b = bodyBegin; b < bodyEnd; b++, B++) { // Loop over bodies in current rank
B->IRANK = irank; // Copy MPI rank to body
} // End loop over bodies in current rank
} // End loop over MPI ranks
logger::stopTimer("Partition"); // Stop timer
logger::startTimer("Sort"); // Start timer (for consistency)
logger::stopTimer("Sort"); // Stop timer (for consistency)
return rankBounds[mpirank]; // Return local bounds
}
//! Partition bodies with geometric octsection
Bounds octsection(Bodies & bodies, Bounds global) {
logger::startTimer("Partition"); // Start timer
int size = mpisize; // Initialize MPI size counter
int Npartition[3] = {1, 1, 1}; // Number of partitions in each direction
int d = 0; // Initialize dimension counter
while (size != 1) { // Divide domain while counter is not one
Npartition[d] <<= 1; // Divide this dimension
d = (d + 1) % 3; // Increment dimension
size >>= 1; // Right shift the bits of counter
} // End while loop for domain subdivision
real_t Xpartition[3]; // Size of partitions in each direction
for (d = 0; d < 3; d++) { // Loop over dimensions
Xpartition[d] = (global.Xmax[d] - global.Xmin[d]) / Npartition[d];// Size of partition in each direction
} // End loop over dimensions
int iX[3]; // Index vector
iX[0] = mpirank % Npartition[0]; // x index of partition
iX[1] = mpirank / Npartition[0] % Npartition[1]; // y index
iX[2] = mpirank / Npartition[0] / Npartition[1]; // z index
Bounds local; // Local bounds
for (d = 0; d < 3; d++) { // Loop over dimensions
local.Xmin[d] = global.Xmin[d] + iX[d] * Xpartition[d]; // Xmin of local domain at current rank
local.Xmax[d] = global.Xmin[d] + (iX[d] + 1) * Xpartition[d];// Xmax of local domain at current rank
} // End loop over dimensions
for (B_iter B = bodies.begin(); B != bodies.end(); B++) { // Loop over bodies
int ic = 0; // Residual index
if (B->ICELL < 0) ic = B->ICELL; // Use first body in group
for (d = 0; d < 3; d++) { // Loop over dimensions
iX[d] = int(((B + ic)->X[d] - global.Xmin[d]) / Xpartition[d]); // Index vector of partition
} // End loop over dimensions
B->IRANK = iX[0] + Npartition[0] * (iX[1] + iX[2] * Npartition[1]);// Set send rank
assert(0 <= B->IRANK && B->IRANK < mpisize);
} // End loop over bodies
logger::stopTimer("Partition"); // Stop timer
logger::startTimer("Sort"); // Start timer
Sort sort; // Instantiate sort class
bodies = sort.irank(bodies); // Sort bodies according to IRANK
logger::stopTimer("Sort"); // Stop timer
return local;
}
struct bodyComparer {
bool operator() (Body i,Body j) { return (i.ICELL<j.ICELL); }
} comparer;
#if EXAFMM_USE_PARMETIS
void partitionParmetis(Bodies & bodies, Bounds globalBounds) {
logger::startTimer("Partition"); // Start timer
//int64_t ndims = 3;
int ndims = 3;
//std::vector<double> xyz(bodies.size()*ndims);
std::vector<float> xyz(bodies.size()*ndims);
for(int i = 0; i < bodies.size(); ++i) {
xyz[i*ndims + 0] = bodies[i].X[0];
xyz[i*ndims + 1] = bodies[i].X[1];
xyz[i*ndims + 2] = bodies[i].X[2];
}
std::vector<int> part(bodies.size());
MPI_Comm comm = MPI_COMM_WORLD;
size_t bodyCount = bodies.size();
size_t* counts = new size_t[mpisize];
MPI_Allgather(&bodyCount, 1, MPI_UNSIGNED_LONG_LONG,
counts, 1, MPI_UNSIGNED_LONG_LONG,
MPI_COMM_WORLD);
if(bodyCount > 0)
parmetis_wrapper::partitionCoodsParmetis(counts, &xyz[0], &part[0], &ndims, mpisize, &comm);
else
parmetis_wrapper::partitionCoodsParmetis(counts, NULL, &part[0], &ndims, mpisize, &comm);
for(int i = 0; i < bodies.size(); ++i) {
bodies[i].IRANK = part[i];
}
delete[] counts;
logger::startTimer("Sort");
Sort sort;
bodies = sort.irank(bodies);
logger::stopTimer("Sort");
logger::stopTimer("Partition"); // Start timer
}
#endif
void partitionHilbert(Bodies & bodies, Bounds globalBounds) {
logger::startTimer("Partition"); // Start timer
if (mpisize > 1) {
uint32_t depth;
KeyPair localHilbertBounds = assignSFCtoBodies(bodies, globalBounds, depth);
uint64_t min, max;
MPI_Allreduce(&localHilbertBounds.first, &min, 1, MPI_UNSIGNED_LONG_LONG, MPI_MIN, MPI_COMM_WORLD);// Reduce domain Xmin
MPI_Allreduce(&localHilbertBounds.second, &max, 1, MPI_UNSIGNED_LONG_LONG, MPI_MAX, MPI_COMM_WORLD);// Reduce domain Xmax
globalKeyBounds = std::make_pair(min, max);
uint64_t lbound = globalKeyBounds.first;
uint64_t rbound = globalKeyBounds.second;
VHilbert rq;
rq.reserve(mpisize + 1);
rq.push_back(lbound); rq.push_back(rbound);
int64_t startPivot = lbound + ((rbound - lbound) >> 1);
VHilbert keys(bodies.size());
// keys.reserve(bodies.size());
int index = 0;
logger::startTimer("Sort Hilbert");
std::sort(bodies.begin(), bodies.end(), comparer);
logger::stopTimer("Sort Hilbert");
if(bodies.size() > 0) {
uint64_t prev_icell = bodies.begin()->ICELL;
for (B_iter B = bodies.begin()+1; B != bodies.end(); ++B){
if(B->ICELL == prev_icell) {
int inc = 1;
B->ICELL+=1;
B_iter B0 = B+1;
while(B0 < bodies.end() && B0->ICELL == prev_icell){
inc++;
B0->ICELL+=inc;
B0++;
}
B0--;
} else {
prev_icell = B->ICELL;
}
}
}
for (B_iter B = bodies.begin(); B != bodies.end(); ++B){
keys[index++] = B->ICELL;
}
hilbertPartitionSort(keys, lbound, rbound, rq, startPivot);
std::sort(rq.begin(), rq.end());
updateRangeParameters(rq);
for (B_iter B = bodies.begin(); B != bodies.end(); ++B) {
B->IRANK = getPartitionNumber(B->ICELL); // Get partition
assert(B->IRANK >= 0 && B->IRANK < mpisize); // Make sure rank is within communication size
}
// std::cout << "number of collisions: " << index << std::endl;
} else {
for (B_iter B = bodies.begin(); B != bodies.end(); ++B)
B->IRANK = mpirank;
}
logger::stopTimer("Partition"); // Stop timer
logger::startTimer("Sort");
Sort sort;
bodies = sort.irank(bodies);
logger::stopTimer("Sort");
}
//! Wrapper for partitioning
Bounds partition(Bodies& bodies, Bounds globalBounds, const char* partitioingType) {
Bounds localBounds;
switch (partitioingType[0]) {
case 'h':
partitionHilbert(bodies, globalBounds);
break;
case 'b':
localBounds = bisection(bodies, globalBounds);
break;
case 'o':
localBounds = octsection(bodies, globalBounds);
break;
case 'p':
#if EXAFMM_USE_PARMETIS
partitionParmetis(bodies, globalBounds);
break;
#else
std::cout << "Warning: required parmetis partitioning is not supported" << std::endl;
#endif
default:
localBounds = bisection(bodies, globalBounds);
}
return localBounds;
}
//! Send bodies back to where they came from
void unpartition(Bodies & bodies) {
logger::startTimer("Sort"); // Start timer
Sort sort; // Instantiate sort class
bodies = sort.irank(bodies); // Sort bodies according to IRANK
logger::stopTimer("Sort"); // Stop timer
}
};
}
#endif
|
fraunhofer-iais/IAIS-Python-Snippets | Data/Transform/Set timestamp as index.py | # Set timestamp as index
format = '%Y-%m-%d %H:%M:%S.%f'
data['time'] = pd.to_datetime(data['time'], format=format)
data = data.set_index(['time'])
data = data.sort_index() |
Ken-Utsunomiya/SnackTrack-Server | src/suggestion/controller.js | <filename>src/suggestion/controller.js
import { db } from '../db/index.js'
import { errorCode } from '../util/error.js'
const Suggestions = db.suggestions
const Users = db.users
export const addSuggestion = async (req, res) => {
try {
const suggestion = req.body
const userId = suggestion.suggested_by
const user = await Users.findByPk(userId)
if (!user) {
return res.status(404).json({ error: 'userid does not exist in the users table.' })
}
const suggestionText = suggestion.suggestion_text
if (!suggestionText || !suggestionText.trim()) {
return res.status(400).json({ error: 'suggestionText is empty.' })
}
const result = await Suggestions.create(suggestion)
return res.status(201).json(result)
} catch (err) {
return res.status(errorCode(err)).json({ error: err.message })
}
}
export const getSuggestions = async (_, res) => {
try {
const response = await Suggestions.findAll()
return res.status(200).json({ suggestions: response })
} catch (err) {
return res.status(errorCode(err)).json({ error: err.message })
}
}
export const deleteSuggestions = async(_, res) => {
try {
await Suggestions.destroy({ where: { }, force: true })
return res.status(204).json()
} catch (err) {
return res.status(errorCode(err)).json({ error: err.message })
}
}
|
PKUfudawei/cmssw | HLTrigger/Configuration/python/HLT_75e33/modules/hltParticleFlowSuperClusterECALL1Seeded_cfi.py | <gh_stars>1-10
import FWCore.ParameterSet.Config as cms
hltParticleFlowSuperClusterECALL1Seeded = cms.EDProducer("PFECALSuperClusterProducer",
BeamSpot = cms.InputTag("hltOnlineBeamSpot"),
ClusteringType = cms.string('Mustache'),
ESAssociation = cms.InputTag("hltParticleFlowClusterECALL1Seeded"),
EnergyWeight = cms.string('Raw'),
PFBasicClusterCollectionBarrel = cms.string('hltParticleFlowBasicClusterECALBarrel'),
PFBasicClusterCollectionEndcap = cms.string('hltParticleFlowBasicClusterECALEndcap'),
PFBasicClusterCollectionPreshower = cms.string('hltParticleFlowBasicClusterECALPreshower'),
PFClusters = cms.InputTag("hltParticleFlowClusterECALL1Seeded"),
PFSuperClusterCollectionBarrel = cms.string('hltParticleFlowSuperClusterECALBarrel'),
PFSuperClusterCollectionEndcap = cms.string('hltParticleFlowSuperClusterECALEndcap'),
PFSuperClusterCollectionEndcapWithPreshower = cms.string('hltParticleFlowSuperClusterECALEndcapWithPreshower'),
applyCrackCorrections = cms.bool(False),
barrelRecHits = cms.InputTag("hltRechitInRegionsECAL","EcalRecHitsEB"),
doSatelliteClusterMerge = cms.bool(False),
dropUnseedable = cms.bool(False),
endcapRecHits = cms.InputTag("hltRechitInRegionsECAL","EcalRecHitsEE"),
etawidth_SuperClusterBarrel = cms.double(0.04),
etawidth_SuperClusterEndcap = cms.double(0.04),
isOOTCollection = cms.bool(False),
phiwidth_SuperClusterBarrel = cms.double(0.6),
phiwidth_SuperClusterEndcap = cms.double(0.6),
regressionConfig = cms.PSet(
ecalRecHitsEB = cms.InputTag("hltEcalRecHitL1Seeded","EcalRecHitsEB"),
ecalRecHitsEE = cms.InputTag("hltEcalRecHitL1Seeded","EcalRecHitsEE"),
isHLT = cms.bool(True),
regressionKeyEB = cms.string('pfscecal_EBCorrection_online'),
regressionKeyEE = cms.string('pfscecal_EECorrection_online'),
uncertaintyKeyEB = cms.string('pfscecal_EBUncertainty_online'),
uncertaintyKeyEE = cms.string('pfscecal_EEUncertainty_online')
),
satelliteClusterSeedThreshold = cms.double(50.0),
satelliteMajorityFraction = cms.double(0.5),
seedThresholdIsET = cms.bool(True),
thresh_PFClusterBarrel = cms.double(0.5),
thresh_PFClusterES = cms.double(0.5),
thresh_PFClusterEndcap = cms.double(0.5),
thresh_PFClusterSeedBarrel = cms.double(1.0),
thresh_PFClusterSeedEndcap = cms.double(1.0),
thresh_SCEt = cms.double(10.0),
useDynamicDPhiWindow = cms.bool(True),
useRegression = cms.bool(True),
use_preshower = cms.bool(True),
verbose = cms.untracked.bool(False)
)
|
theodi/office-calendar | features/support/vcr.rb | <filename>features/support/vcr.rb
require 'vcr'
require 'webmock/cucumber'
VCR.configure do |c|
# Automatically filter all secure details that are stored in the environment
ignore_env = %w{SHLVL RUNLEVEL GUARD_NOTIFY DRB COLUMNS USER LOGNAME LINES}
(ENV.keys-ignore_env).select{|x| x =~ /\A[A-Z_]*\Z/}.each do |key|
c.filter_sensitive_data("<#{key}>") { ENV[key] }
end
c.filter_sensitive_data("<KEY>") do |interaction|
interaction.response.body.match(/SID=[a-z0-9_-]+[\s]+LSID=[a-z0-9_-]+[\s]+Auth=([a-z0-9_-]+)/i)
end
c.ignore_localhost = true
c.default_cassette_options = { :record => :once }
c.cassette_library_dir = 'fixtures/vcr_cassettes'
c.hook_into :webmock
end
VCR.cucumber_tags do |t|
t.tag '@vcr', use_scenario_name: true
end |
networkmodeling/V2X-Hub | src/tmx/Asn_J2735/include/asn_j2735_r41/BrakeSystemStatus.h | /*
* Generated by asn1c-0.9.27 (http://lionet.info/asn1c)
* From ASN.1 module "DSRC"
* found in "../J2735_R41_Source_mod.ASN"
* `asn1c -gen-PER -fcompound-names -fincludes-quoted`
*/
#ifndef _BrakeSystemStatus_H_
#define _BrakeSystemStatus_H_
#include "asn_application.h"
/* Including external dependencies */
#include "OCTET_STRING.h"
#ifdef __cplusplus
extern "C" {
#endif
/* BrakeSystemStatus */
typedef OCTET_STRING_t BrakeSystemStatus_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_BrakeSystemStatus;
asn_struct_free_f BrakeSystemStatus_free;
asn_struct_print_f BrakeSystemStatus_print;
asn_constr_check_f BrakeSystemStatus_constraint;
ber_type_decoder_f BrakeSystemStatus_decode_ber;
der_type_encoder_f BrakeSystemStatus_encode_der;
xer_type_decoder_f BrakeSystemStatus_decode_xer;
xer_type_encoder_f BrakeSystemStatus_encode_xer;
per_type_decoder_f BrakeSystemStatus_decode_uper;
per_type_encoder_f BrakeSystemStatus_encode_uper;
#ifdef __cplusplus
}
#endif
#endif /* _BrakeSystemStatus_H_ */
#include "asn_internal.h"
|
schroedinger-survey/frontend | src/components/submissions/SubmissionSpotlight.js | <filename>src/components/submissions/SubmissionSpotlight.js
import React, {useEffect, useState} from "react";
import {sortQuestions} from "../utils/SortQuestions";
import SubmissionAPIHandler from "../../calls/submission";
import {createPaginationMarker} from "../utils/PageMarker";
import {EuropeanTime} from "../utils/TimeConverter";
import Logger from "../../utils/Logger";
const log = new Logger("src/components/submissions/SubmissionSpotlight.js");
/**
* Shows all submissions belonging to a survey
* Each submission can be looked at individually
* @param props - survey and submissionCount
* @returns {JSX.Element}
* @constructor
*/
const SubmissionSpotlight = (props) => {
const {survey} = props;
const {submissionCount} = props;
const itemsPerPage = 5;
const [submissions, setSubmissions] = useState([]);
const [spotlight, setSpotlight] = useState({});
const [renamed, setRenamed] = useState(false);
const [constrainedOptions, setConstrainedOptions] = useState(new Map());
useEffect(() => {
if(survey !== undefined){
getSubmissions();
setupConstrainedQuestionOptions()
}
}, [props])
/**
* Fetch the submissions from api - DO NOT CACHE it needs to be fetched for each survey individually
* fetches only if survey was correctly passed trough props
**/
const getSubmissions = async (pageNumber = 0) => {
// eslint-disable-next-line no-undefined
if (survey !== undefined) {
const apiResponse = await SubmissionAPIHandler.submissionGet(survey.id, pageNumber, itemsPerPage)
setSubmissions(apiResponse.data);
}
}
/**
* Creates a Map,
* mapping the positions of the question in the survey to the answer options Map(2 => [y, n]);
* scenario: shown behind chosen answer of user
**/
const setupConstrainedQuestionOptions = () => {
if(survey !== undefined){
let sortedConstrainedQuestions = new Map();
try{
for (let i = 0; i < survey.constrained_questions.length; i++) {
sortedConstrainedQuestions.set(survey.constrained_questions[i].position, survey.constrained_questions[i].options)
}
} catch (e) {
log.error(e);
}
setConstrainedOptions(sortedConstrainedQuestions);
}
}
/**
* Renames some of the properties of the fetched submission json file
* for easier use with util functions like sortQuestions
**/
const renameSubmissionProperties = (submission) => {
for (let i = 0; i < submission.constrained_answers.length; i++) {
submission.constrained_answers[i].question_text = submission.constrained_answers[i].constrained_question_question_text;
submission.constrained_answers[i].position = submission.constrained_answers[i].constrained_question_position;
submission.constrained_answers[i].answer = submission.constrained_answers[i].constrained_question_chose_option;
}
for (let i = 0; i < submission.freestyle_answers.length; i++) {
submission.freestyle_answers[i].question_text = submission.freestyle_answers[i].freestyle_question_question_text;
submission.freestyle_answers[i].position = submission.freestyle_answers[i].freestyle_question_position;
submission.freestyle_answers[i].answer = submission.freestyle_answers[i].freestyle_question_answer;
}
}
/**
* If user clicks on submission from list of submissions the Spotlight is reset
* the submissions properties are renamed and the boolean flag for Rename is set, ending the loading
**/
const changeSubmission = async (submission) => {
await renameSubmissionProperties(submission);
setSpotlight(submission);
setRenamed(true);
}
/**
* The Options belonging to an constrained question are returned as a string
* it uses the Map constrainedOptions, created and mapped in setupConstrainedQuestionOptions
* scenario: behind the chosen answer these are shown as a overview
**/
const showOptions = (key) => {
const options = constrainedOptions.get(key);
if(options !== undefined){
let optionValues = [];
for (let i = 0; i < options.length; i++) {
optionValues.push(options[i].answer);
}
return "(" + optionValues.join(", ") + ")";
} else {
return "";
}
}
/**
* Creates the Pagination for the list of submissions
* calls createPaginationMarker
* returns the JSX element resulting from createPaginationMarker
* gives the callback function changePage as onClick function
* changePage fetches the submissions based on the index (number of pagination marker) used as page_number in fetch call
**/
const submissionPagination = () => {
const changePage = async (index) => {
await getSubmissions(index);
}
const pages = Math.ceil(submissionCount / itemsPerPage);
return createPaginationMarker(pages, changePage);
}
return (
<div>
{/* eslint-disable-next-line no-undefined */}
{survey !== undefined && (
<div className={"submission_spotlight_sub_list"}>
<h3 className={"sub_spotlight_section_title"}>Submissions (newest first)</h3>
{submissionCount > itemsPerPage && submissionPagination()}
<ul className={"submissions_list_ul"}>
{submissions.map((submission, i) => (
<li key={i} className={"submission_spotlight_list_items"} onClick={() => {
changeSubmission(submission)
}}>{EuropeanTime(submission.created.substr(0, 10))}</li>
))}
</ul>
</div>
)}
<hr/>
{survey !== undefined && (
<div className={"submission_spotlight_selected_sub"}>
{renamed &&
sortQuestions(
spotlight.constrained_answers,
spotlight.freestyle_answers,
"position",
"constrained_questions_option_id").map((item, i) => (
<div key={i} style={{
border: "1px solid lightgrey",
borderRadius: "8px",
padding: "5px",
marginBottom: "5px"
}}>
<p><span
style={{fontWeight: "bold"}}>Question {item.question.position + 1}:</span> {item.question.question_text}
</p>
<p style={{fontSize: "12px"}}>
<span style={{fontWeight: "bold", fontSize: "16px"}}>Answer:</span> <span
style={{fontSize: "16px"}}>{item.question.answer}</span> {item.type === "constrained" ? showOptions(item.question.position) : ""}
</p>
</div>
))}
</div>
)}
</div>
)
}
export default SubmissionSpotlight; |
MayBeDied/a2web | Monitor-framework/src/main/java/com/monitor/framework/query/entity/BeforeInit.java | package com.monitor.framework.query.entity;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.digester3.annotations.rules.ObjectCreate;
import org.apache.commons.digester3.annotations.rules.SetNext;
@ObjectCreate(pattern="queryContext/query/beforeInit")
public class BeforeInit {
List<BeforeCall> beforeCallList;
public BeforeInit(){
beforeCallList=new ArrayList<BeforeCall>();
}
public void setBeforeCallList(List<BeforeCall> beforeCallList) {
this.beforeCallList = beforeCallList;
}
@SetNext
public void addBeforeCall(BeforeCall call){
beforeCallList.add(call);
}
public List<BeforeCall> getBeforeCallList() {
return beforeCallList;
}
}
|
SamanFekri/BookRecommendation | puresvd.py | from sklearn.utils.extmath import randomized_svd
import scipy.sparse as sps
import numpy as np
class PureSVDRecommender():
""" PureSVDRecommender"""
RECOMMENDER_NAME = "PureSVDRecommender"
def __init__(self, verbose=True):
self.URM_train = None
self.USER_factors = None
self.ITEM_factors = None
def _get_cold_user_mask(self):
self._cold_user_mask = np.ediff1d(self.URM_train.indptr) == 0
return self._cold_user_mask
def _get_cold_item_mask(self):
self._cold_item_mask = np.ediff1d(self.URM_train.tocsc().indptr) == 0
return self._cold_item_mask
def fit(self, URM_train, num_factors=600, random_seed=None, **similarity_args):
self.URM_train = URM_train
print("Computing SVD decomposition...")
U, Sigma, VT = randomized_svd(self.URM_train,
n_components=num_factors,
# n_iter=5,
random_state=random_seed)
s_Vt = sps.diags(Sigma) * VT
self.USER_factors = U
self.ITEM_factors = s_Vt.T
self.item_scores = np.dot(self.USER_factors, self.ITEM_factors.T)
print("Computing SVD decomposition... Done!")
def _compute_item_score_postprocess_for_cold_items(self, item_scores):
"""
Remove cold items from the computed item scores, setting them to -inf
:param item_scores:
:return:
"""
# Set as -inf all cold items scores
if self._get_cold_item_mask().any():
item_scores[:, self._get_cold_item_mask()] = - np.ones_like(
item_scores[:, self._get_cold_item_mask()]) * np.inf
return item_scores
def get_expected_values(self, user_id, normalized_ratings=False):
item_scores = self.item_scores[user_id]
item_scores = np.squeeze(np.asarray(item_scores))
# Normalize ratings
if normalized_ratings and np.amax(item_scores) > 0:
item_scores = item_scores / np.linalg.norm(item_scores)
return item_scores
def recommend(self, user_id, cutoff=10, **similarity_args):
if np.isscalar(user_id):
user_id = np.atleast_1d(user_id)
single_user = True
else:
single_user = False
recoms = []
for uid in user_id:
expected_ratings = self.get_expected_values(uid)
recommended_items = np.flip(np.argsort(expected_ratings), 0)
unseen_items_mask = np.in1d(recommended_items, self.URM_train[uid].indices,
assume_unique=True, invert=True)
recommended_items = recommended_items[unseen_items_mask]
recoms.append(recommended_items[0:cutoff])
if single_user:
return recoms[0]
else:
return recoms
def get_URM_train(self):
return self.URM_train
if __name__ == '__main__':
recommender = PureSVDRecommender() |
WargulWB/javaExampleProject | src/main/java/jep/example/general/lambda/LambdaExpressionExample.java | package jep.example.general.lambda;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import jep.example.AbstractExample;
import jep.example.general.StreamApiExample;
public class LambdaExpressionExample extends AbstractExample {
@Override
public void run(String... arguments) {
logln("This first example shows the usage of the functional interface "
+ MathFunction.class.getSimpleName() + "\n"
+ "to define a mathematical operation via a lambda expression and how to calculate the result.");
MathFunction<Integer> f = (x1, x2) -> x1 + x2;
int a = 5;
int b = 3;
int y = f.apply(a, b);
logln("The function is defined as: (x1, x2) -> x1 + x2");
logln("The parameters are: x1=a:=" + a + ", x2=b:=" + b);
logln(">> The result is y=" + y);
logLineSeparator();
logln("The function can be redefined.");
logln("We redefine the function as : (x1, x2) -> x1 * x2");
f = (x1, x2) -> x1 * x2;
y = f.apply(a, b);
logln(">> The result is y=" + y + " for x1=a:=" + a + ", x2=b:=" + b);
logLineSeparator();
logln("We actually would not need to define our own interface.");
logln("We can use the " + Function.class.getSimpleName() + "-interface of the package "
+ getPackageNameOfClass(Function.class) + ".");
logln("We define the function as the increment function: (x) -> ++x");
Function<Integer, Integer> g = x -> ++x;
y = g.apply(a);
logln(">> The result is y=" + y + " for x=a:=" + a);
logLineSeparator();
logln("The " + Function.class.getSimpleName()
+ "-interface only allows one parameter our previous examples required two parameters.");
logln("We can use the " + BiFunction.class.getSimpleName()
+ "-interface which will allow exactly that.");
BiFunction<Integer, Integer, Integer> h = (x1, x2) -> x1 + x2;
y = h.apply(a, b);
logln("We define the function as: (x1, x2) -> x1 + x2");
logln(">> The result is y=" + y + " for x1=a:=" + a + ", x2=b:=" + b);
logLineSeparator();
logln("The " + BiFunction.class.getSimpleName()
+ "-interface also shows how you can assemble a function chain.");
h = h.andThen(g);
logln("We redefine the function h: h':=g(h(x,y)), were h:=(x1,x2) -> x1 + x2 and g:=x -> ++x");
y = h.apply(a, b);
logln(">> The result is y=" + y + " for x1=a:=" + a + ", x2=b:=" + b);
logLineSeparator();
logln("In most situations a lambda expression will not be assigned to a variable but rather be given to a method.");
logln("A quite common example is the Stream API - see "
+ StreamApiExample.class.getSimpleName() + " for details.");
logln("We can use a functional interface as a method parameter, which actually allows us to give an implementation via an lambda expression a parameter.");
logln("We use the local method check(BiFunction<Integer, Integer, Boolean>,int,int):boolean and define the function as: (x1, x2) -> x1 > x2");
boolean result = check((x1, x2) -> x1 > x2, a, b);
logln(">> The result is '" + result + "' for x1=a:=" + a + ", x2=b:=" + b);
result = check((x1, x2) -> x1 > x2, b, a);
logln(">> The result is '" + result + "' for x1=b:=" + b + ", x2=a:=" + a);
logLineSeparator();
logln("Until this point we only defined mathematical/logical functions over numbers.");
logln("But as the generic " + Function.class.getSimpleName() + "-, and "
+ BiFunction.class.getSimpleName()
+ "-interface allready suggest we can define lambda expressions for any kind of object.");
Person kai = new Person("<NAME>", 58);
Person thorsten = new Person("<NAME>", 51);
logln("Let's assume we have two persons:");
logln(kai);
logln(thorsten);
int ageComparisonValue =
apply((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()), kai, thorsten);
logln("We define our function as: (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())");
logln(">> For p1:=" + kai + " and p2:=" + thorsten + " the function returns y="
+ ageComparisonValue + " (meaning Kai is older than Thorsten)");
logLineSeparator();
logln("The above example is quite similar to the " + Comparator.class.getName()
+ " which can for example be used to sort elements within a stream.");
Set<Person> persons = new HashSet<>();
persons.add(kai);
persons.add(thorsten);
logln("Assume we have a set of " + kai + " and " + thorsten + ".");
logln("We can use the above lambda expression as " + Comparator.class.getSimpleName()
+ "-implementation to sort the elements within the sets stream by age.");
logln("The resulting list is: ");
List<Person> sortedPersons =
persons.stream().sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
.collect(Collectors.toList());
int i = 0;
for (Person person : sortedPersons) {
log(person);
if (i < sortedPersons.size() - 1) {
log(", ");
}
i++;
}
logln();
logLineSeparator();
logln("In some situations a class may provide a static method which serves the purpose you want to achieve with a certain lambda expression.");
logln("In this case you can write '<className>::<methodName>' as your lambda expression.");
logln("The only requirement is that the methods arguments match the arguments of the lambda expressions fuctional interfaces method.");
logln("We define a static method " + LambdaExpressionExample.class.getSimpleName()
+ "#compareByAge(Person,Person):int which we than use for sorting the sets stream like in the above example.");
sortedPersons = persons.stream().sorted(LambdaExpressionExample::compareByAge)
.collect(Collectors.toList());
logln("The resulting list is: ");
sortedPersons =
persons.stream().sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
.collect(Collectors.toList());
i = 0;
for (Person person : sortedPersons) {
log(person);
if (i < sortedPersons.size() - 1) {
log(", ");
}
i++;
}
logln();
logLineSeparator();
logln("Often the actual parameters are stored inside a certain object, the lambda expressions defines how this internal state is to be handled.");
logln("A good example are the stream API methods.");
logln("We will store some integers as data in an instance of "
+ DataStorage.class.getSimpleName()
+ " and return the maximal value stored via the "
+ DataStorage.class.getSimpleName() + "#select()\n"
+ "method using a lambda expression - which returns the maximal value - as "
+ SelectionFunction.class.getSimpleName() + " instance.");
DataStorage<Integer> dataStorage = new DataStorage<>(1, 4, 80, 1_013, 104, 12, 612);
log("The stored data is:");
i = 0;
for (int x : dataStorage.getDataAsUnmodifiableSet()) {
log(x);
if (i < dataStorage.getDataAsUnmodifiableSet().size() - 1) {
log(", ");
}
i++;
}
logln();
Optional<Integer> optionalMax = dataStorage.select(data -> {
if (data.size() == 0) {
return null;
}
Iterator<Integer> itr = data.iterator();
int max = itr.next();
while (itr.hasNext()) {
int current = itr.next();
if (current > max) {
max = current;
}
}
return max;
});
if (optionalMax.isPresent()) {
logln(">> The maximal value stored in the data storage was: " + optionalMax.get());
} else {
logln(">> The data storage did not contain any data.");
}
}
/**
* Compares the ages of the two given persons via {@link Integer#compare(int, int)}.
*
* @param p1 first parameter
* @param p2 second parameter
* @return
* @see Integer#compare(int, int)
*/
private static int compareByAge(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
/**
* Returns the result of the application of the given <code>function</code> to the given
* parameter <code>p1</code> and <code>p2</code>.
*
* @param functionwhich is to be applied
* @param p1 first parameter
* @param p2 second parameter
* @return result of the function application
* @see BiFunction
*/
private int apply(BiFunction<Person, Person, Integer> function, Person p1, Person p2) {
return function.apply(p1, p2);
}
/**
* Returns the result of the application of the given <code>function</code> to the given
* parameter <code>x1</code> and <code>x2</code>.
*
* @param function which is to be applied
* @param x1 first parameter
* @param x2 second parameter
* @return result of the function application
* @see BiFunction
*/
private boolean check(BiFunction<Integer, Integer, Boolean> function, int x1, int x2) {
return function.apply(x1, x2);
}
@Override
public Class<?>[] getRelevantClasses() {
Class<?>[] relevantClasses =
{LambdaExpressionExample.class, MathFunction.class, Person.class, DataStorage.class,
SelectionFunction.class, Function.class, BiFunction.class};
return relevantClasses;
}
@Override
public String getBundleKey() {
return "example.lambdaExpression";
}
}
|
tkwtokyo/ThinMP_Android | app/src/main/java/tokyo/tkw/thinmp/listener/PlaylistDialogClickListener.java | <reponame>tkwtokyo/ThinMP_Android
package tokyo.tkw.thinmp.listener;
import android.app.Activity;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import tokyo.tkw.thinmp.music.Music;
import tokyo.tkw.thinmp.register.add.PlaylistAdder;
public class PlaylistDialogClickListener implements View.OnClickListener {
private String playlistId;
private Music music;
private AlertDialog dialog;
public PlaylistDialogClickListener(String playlistId, Music music, AlertDialog dialog) {
this.playlistId = playlistId;
this.music = music;
this.dialog = dialog;
}
@Override
public void onClick(View view) {
PlaylistAdder playlistAdder = PlaylistAdder.createInstance();
playlistAdder.add(playlistId, music);
Activity activity = ((Activity) view.getContext());
if (activity instanceof ScreenUpdateListener) {
((ScreenUpdateListener) activity).screenUpdate();
}
dialog.dismiss();
}
}
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | platform/lib/all-deps/com/cyc/webservice/client/api/url/QueryApiURLs.java | package com.cyc.webservice.client.api.url;
import com.cyc.cat.common.url.BaseURLStringLibrary;
import com.cyc.cat.common.url.URLString;
import com.cyc.cat.common.url.URLString.Parameter;
import com.cyc.cat.common.url.URLString.Protocol;
import java.io.Serializable;
/**
*
* @author nwinant
*/
public class QueryApiURLs extends BaseURLStringLibrary implements Serializable {
// Constructors
public QueryApiURLs(Protocol protocol, String host, Integer port) {
super(protocol, host, port);
}
public QueryApiURLs(String host, Integer port) {
super(host, port);
}
public QueryApiURLs() {
super();
}
// Public
/**
* @deprecated
*/
public URLString getResultsForQuery(String queryId) {
return makeURL(RESULTS_PATH, new Parameter("queryId", queryId));
}
public URLString beginAsyncQuery(String queryId) {
return makeURL(BEGIN_ASYNC_QUERY_PATH, new Parameter("queryId", queryId));
}
public URLString getAsyncQueryResults(String ticketId) {
return makeURL(ASYNC_QUERY_RESULTS_PATH, new Parameter("ticketId", ticketId));
}
public URLString forgetCachedQueryResults() {
return makeURL(FORGET_CACHED_PATH);
}
/**
* @deprecated
*/
public URLString destroyOneInference(String inferenceID) {
return makeURL(DESTROY_INFERENCE_PATH, new Parameter("inferenceID", inferenceID));
}
public URLString getUUID() {
return makeURL(UUID_PATH);
}
public URLString relinquishTicket(String ticketId) {
return makeURL(getTicketActionPath(ticketId, TICKET_RELINQUISH_ACTION));
}
public URLString getInferenceIdentifier(String ticketId) {
return makeURL(getTicketActionPath(ticketId, TICKET_INFERENCE_ID_ACTION));
}
public URLString justifyAnswer(String ticketId, String answerId) {
return makeURL(JUSTIFY_ANSWER_PATH, new Parameter("ticketId", ticketId), new Parameter("answerId", answerId));
}
// Protected
@Override
protected String getBasePath() { return BASE_PATH; }
protected String getTicketActionPath(String ticketId, String action) {
return TICKET_PATH + "/" + ticketId + action;
}
// Internal
private static final long serialVersionUID = 1L;
static final public String BASE_PATH = "/query";
static final public String INFERENCE_PATH = "/inference";
static final public String ANSWERER_PATH = "/answerer";
static final public String TICKET_BASE_PATH = "/ticket";
static final public String JUSTIFY_PATH = "/justification";
static final public String RESULTS_BASE_PATH = "/results";
static final public String BEGIN_ASYNC_QUERY_BASE_PATH = "/beginAsyncQuery";
static final public String ASYNC_QUERY_RESULTS_BASE_PATH = "/asyncQueryResults";
static final public String FORGET_CACHED_BASE_PATH = "/forgetCachedQueryResults";
static final public String DESTROY_INFERENCE_BASE_PATH = "/destroyOneInference";
static final public String UUID_BASE_PATH = "/uuid";
static final public String JUSTIFY_ANSWER_BASE_PATH = "/justify";
static final public String TICKET_INFERENCE_ID_ACTION = "/inferenceIdentifier";
static final public String TICKET_RESULTS_ACTION = "/results";
static final public String TICKET_RELINQUISH_ACTION = "/relinquish";
static final public String RESULTS_PATH = INFERENCE_PATH + ANSWERER_PATH + RESULTS_BASE_PATH;
static final public String BEGIN_ASYNC_QUERY_PATH = INFERENCE_PATH + ANSWERER_PATH + BEGIN_ASYNC_QUERY_BASE_PATH;
static final public String ASYNC_QUERY_RESULTS_PATH = INFERENCE_PATH + ANSWERER_PATH + ASYNC_QUERY_RESULTS_BASE_PATH;
static final public String FORGET_CACHED_PATH = INFERENCE_PATH + ANSWERER_PATH + FORGET_CACHED_BASE_PATH;
static final public String DESTROY_INFERENCE_PATH = INFERENCE_PATH + ANSWERER_PATH + DESTROY_INFERENCE_BASE_PATH;
static final public String UUID_PATH = INFERENCE_PATH + ANSWERER_PATH + UUID_BASE_PATH;
static final public String TICKET_PATH = INFERENCE_PATH + TICKET_BASE_PATH;
static final public String JUSTIFY_ANSWER_PATH = JUSTIFY_PATH + JUSTIFY_ANSWER_BASE_PATH;
} |
18730298725/aliyun-openapi-java-sdk | aliyun-java-sdk-oos/src/main/java/com/aliyuncs/oos/transform/v20190601/CreateSecretParameterResponseUnmarshaller.java | <reponame>18730298725/aliyun-openapi-java-sdk<gh_stars>0
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.oos.transform.v20190601;
import com.aliyuncs.oos.model.v20190601.CreateSecretParameterResponse;
import com.aliyuncs.oos.model.v20190601.CreateSecretParameterResponse.Parameter;
import com.aliyuncs.transform.UnmarshallerContext;
public class CreateSecretParameterResponseUnmarshaller {
public static CreateSecretParameterResponse unmarshall(CreateSecretParameterResponse createSecretParameterResponse, UnmarshallerContext _ctx) {
createSecretParameterResponse.setRequestId(_ctx.stringValue("CreateSecretParameterResponse.RequestId"));
Parameter parameter = new Parameter();
parameter.setId(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Id"));
parameter.setName(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Name"));
parameter.setCreatedDate(_ctx.stringValue("CreateSecretParameterResponse.Parameter.CreatedDate"));
parameter.setCreatedBy(_ctx.stringValue("CreateSecretParameterResponse.Parameter.CreatedBy"));
parameter.setUpdatedDate(_ctx.stringValue("CreateSecretParameterResponse.Parameter.UpdatedDate"));
parameter.setUpdatedBy(_ctx.stringValue("CreateSecretParameterResponse.Parameter.UpdatedBy"));
parameter.setDescription(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Description"));
parameter.setShareType(_ctx.stringValue("CreateSecretParameterResponse.Parameter.ShareType"));
parameter.setParameterVersion(_ctx.integerValue("CreateSecretParameterResponse.Parameter.ParameterVersion"));
parameter.setType(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Type"));
parameter.setConstraints(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Constraints"));
parameter.setKeyId(_ctx.stringValue("CreateSecretParameterResponse.Parameter.KeyId"));
parameter.setTags(_ctx.stringValue("CreateSecretParameterResponse.Parameter.Tags"));
createSecretParameterResponse.setParameter(parameter);
return createSecretParameterResponse;
}
} |