text:
({
    init: function() {

    },

    handleMouseDown: function(cmp, evt, helper) {
        helper.handleMouseDown(cmp, evt);
    },

    handleChange: function(cmp, evt, helper) {
        var advanced = evt.source.get('v.value');
        cmp.set('v.advanced', advanced);
    },

    handlePress: function(cmp, evt, helper) {
        var advanced = cmp.get('v.advanced');
        var body = $A.newCmp({componentDef: 'aura:unescapedHtml', attributes: {values: {value: '
This is the panel
'}}})
        var bigTarget = cmp.find('bigTarget').getElement();
        var littleTarget = cmp.find('littleTarget').getElement();
        var value = cmp.find('direction').get('v.value');
        var pad = parseInt(cmp.find('pad').get('v.value'),10);
        var padTop = cmp.find('padTop').get('v.value');
        var isInside;
        isInside = cmp.find('isInside').get('v.value');

        var panelConfig ={
            referenceElement: isInside ? bigTarget : littleTarget,
            showCloseButton: false,
            closeOnClickOut: true,
            useTransition: false,
            body  : body,
            direction: value,
            showPointer: false,
            boundingElement: isInside ? window : bigTarget,
            inside: isInside,
            pad: pad,
            padTop: padTop !== undefined ? parseInt(padTop, 10) : undefined
        };

        if(cmp.find('isAdvanced').get('v.value')) {
            delete panelConfig.direction;
            panelConfig.advanced = true;
            panelConfig.align = cmp.find('align').get('v.value');
            panelConfig.targetAlign = cmp.find('targetAlign').get('v.value');
        }

        $A.get('e.ui:createPanel').setParams({
            panelType   :'panel',
            visible: true,
            panelConfig : panelConfig
        }).fire();
    }
})


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use yii\widgets\MaskedInput;

/* @var $this yii\web\View */
/* @var $model app\models\TaSetoranPotonganRinc */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['id' => $model->formName()]); ?>

    <?= $form->field($model, 'pembayaran')->radioList([1 => 'Bank', 2 => 'Tunai'], [
                'item' => function ($index, $label, $name, $checked, $value) {
                    return '' . Html::radio($name, $checked, ['value'  => $value]) . $label . '';
                }
            ]); ?>

    <?= $form->field($model, 'kd_potongan')->widget(Select2::classname(), [
            'data' => ArrayHelper::map(
                \app\models\RefPotongan::find()->all()
                ,'kd_potongan','nm_potongan'),
            'options' => ['placeholder' => 'Pilih Jenis Potongan ...'],
            'pluginOptions' => [
                'allowClear' => true
            ],
        ]) ?>

    <?= $form->field($model, 'nilai', ['enableClientValidation' => false])->widget(MaskedInput::classname(), [
                'clientOptions' => [
                    'alias' =>  'decimal',
                    'groupSeparator' => '.',
                    'radixPoint'=>',',
                    'autoGroup' => true,
                    'removeMaskOnSubmit' => true,
                ],
        ]) ?>

    <?= $form->field($model, 'keterangan')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Simpan' : 'Simpan', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

<?php $script = <<<JS
$('form#{$model->formName()}').on('beforeSubmit',function(e)
{
    var \$form = $(this);
    $.post(
        \$form.attr("action"), //serialize Yii2 form
        \$form.serialize()
    )
        .done(function(result){
            if(result == 1)
            {
                $("#myModal").modal('hide'); //hide modal after submit
                //$(\$form).trigger("reset"); //reset form to reuse it to input
                $.pjax.reload({container:'#ta-setoran-potongan-rinc-pjax'});
            }else
            {
                $("#message").html(result);
            }
        }).fail(function(){
            console.log("server error");
        });
    return false;
});

JS;
$this->registerJs($script);
?>

redpajama_set_name: RedPajamaGithub


text:
package com.github.jvmgo.instructions.comparisons;

import com.github.jvmgo.instructions.base.BranchInstruction;
import com.github.jvmgo.rtda.Frame;
import com.github.jvmgo.rtda.OperandStack;

public class if_icmpgt extends BranchInstruction {
    @Override
    public int getOpCode() {
        return 0xa3;
    }

    @Override
    public void execute(Frame frame) throws Exception {
        OperandStack operandStack = frame.getOperandStack();
        int v2 = operandStack.popInt();
        int v1 = operandStack.popInt();
        if (v2 < v1) {
            branch(frame,offset);
        }
    }
}


text:
layout: "archive"
title: "Archives"
header-img: "img/header_img/archive-bg.png"
comments: false
date: 2017-03-20 20:49:56
description: "Hey, this is archives"
---


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>My ReactJS Project</title>
  <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Open+Sans' rel='stylesheet' type='text/css' />
  <link rel="stylesheet" href="/build/css/style.css" />
</head>
<body>
  <div id="main">
    <!-- This is where our React app will go -->
  </div>

  <script src="/build/main.js"></script>
</body>
</html>


text:
class AnalyticsWorker < Workling::Base
  def potential_invited(options)
    #Hit.create :potential_user_id => options[:potential_user_id], :action => "invited"
  end

  def potential_converted(options)
    #Hit.create :potential_user_id => options[:potential_user_id], :action => "converted"
  end

  def status(options)
    #results = Blackbook.get(options[:key], options[:username], options[:password])
    results = '123'
    Workling::Return.set(options[:uid], results)
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Öst. bot. Z. (1902)

#### Original name
Puccinia cirsii-eriophori Jacky, 1899

### Remarks
null


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using DotSpatial.Data;
using DotSpatial.Modeling.Forms;
using DotSpatial.Modeling.Forms.Parameters;

namespace DotSpatial.Tools
{
    /// <summary>
    /// Class for creating voronoi (Thiessen) polygons.
    /// </summary>
    public class Voronoi : Tool
    {
        #region Fields

        private Parameter[] _inputParam;
        private Parameter[] _outputParam;

        #endregion

        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Voronoi"/> class.
        /// </summary>
        public Voronoi()
        {
            Name = TextStrings.ThiessenPolygons;
            Category = TextStrings.Analysis;
            Description = TextStrings.VoronoiDescription;
            ToolTip = TextStrings.CreateVoronoiPolygons;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the input paramater array.
        /// </summary>
        public override Parameter[] InputParameters => _inputParam;

        /// <summary>
        /// Gets the output paramater array.
        /// </summary>
        public override Parameter[] OutputParameters => _outputParam;

        #endregion

        #region Methods

        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if successful.
        /// </summary>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>True if executed successfully.</returns>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input = _inputParam[0].Value as IFeatureSet;
            input?.FillAttributes();

            if (!(_outputParam[0].Value is IFeatureSet output)) return false;

            Analysis.Voronoi.VoronoiPolygons(input, output, true);
            output.Save();
            return true;
        }

        /// <summary>
        /// The Parameter array should be populated with default values here.
        /// </summary>
        public override void Initialize()
        {
            _inputParam = new Parameter[1];
            _inputParam[0] = new PointFeatureSetParam(TextStrings.PointFeatureSet);

            _outputParam = new Parameter[2];
            _outputParam[0] = new PolygonFeatureSetParam(TextStrings.PolygonFeatureSet);
            _outputParam[1] = new BooleanParam(TextStrings.OutputParameter_AddToMap, TextStrings.OutputParameter_AddToMap_CheckboxText, true);
        }

        #endregion
    }
}


text:
title: "Configure user rights"
excerpt: ""
---
[block:callout]
{
  "type": "danger",
  "title": "This feature is only available for administrators!"
}
[/block]
In the **User rights** tab, you can:
* decide whether the user can register himself or not, and select a default group and an expiration date for the new users
* decide whether you automatically logoff after closing the VDI or not
* enable the creation of teams
[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/a5eee17-configuration_userrights_201.png",
        "configuration_userrights_201.png",
        2546,
        1354,
        "#046cb4"
      ]
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Registration, default group and expiration date"
}
[/block]
In the **User rights** tab, tick or untick the box next to "User can register himself" to decide if users can register themselves.

**DEFAULT GROUP**
If users can register themselves, you can choose a default group. All new users who registered themselves will then automatically join the default group.

To do so, click on the name of the group to make it the default one.
Your changes are automatically taken into account.
[block:callout]
{
  "type": "success",
  "title": "You have successfully defined a default group for new users!"
}
[/block]
**EXPIRATION DATE**
You can also enter an expiration date which will apply to all new users who registered themselves.

1. Enter the number of days you want the new users to have access to Nanocloud Software.
2. Click :fa-check: to validate your changes.

Your changes are automatically taken into account.
[block:callout]
{
  "type": "success",
  "title": "You have successfully defined an expiration date for new users!"
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Logoff after closing the VDI"
}
[/block]
When you are in the VDI, on the right of the top bar, you have two buttons:
* :fa-power-off: to disconnect from your Windows session
* :fa-home: to redirect you to the main portal while keeping your VDI session open in the background

If you tick the "Logoff after closing VDI" box, the :fa-home: button will not be available anymore. Users will only have the possibility to disconnect from the Windows session everytime they close the VDI.
[block:callout]
{
  "type": "success",
  "title": "Your logoff configuration changes have successfully been taken into account!"
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Computation credits"
}
[/block]
You can set usage limits for the users, for example to be able to set trial periods or to limit resources consumption.

How computation credits work on Nanocloud is easy: the users will not be able to exceed a number of computation credits per month. When the threshold is reached, the user cannot launch an application anymore, until the end of the month.

You just have to enter your chosen amount of credits limits in the provided area, and it will apply to all users.
[block:callout]
{
  "type": "info",
  "title": "Computation credits only apply to users who use AWS."
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Enable teams"
}
[/block]
For any member to be able to create teams, you just have to tick or untick **Enable team**.


text:
/**
 *
 */
package org.saiku.reporting.core.adapter;

import java.awt.Color;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * @author mg
 *
 */
public class ColorAdapter extends XmlAdapter<String,Color> {

	public Color unmarshal(String s) {
		return Color.decode(s.replaceFirst("#", "0x"));
	}
	public String marshal(Color c) {
		int colInt = c.getRGB();
		String str = Integer.toHexString(colInt);
		return str.replaceFirst("ff", "#");
	}
}


text:
import { combineReducers } from 'redux';
import { getPage } from 'helpers/DataClient';
import path from 'path';
const cheerio = require('cheerio');

// load prismjs (code highlighting) only client side for now
// Loading it from server side and client side causes double
// code tokenization. Too painful to fix it. rage quit.
let Prism;
if (!__SERVER__) {
  Prism = require('prismjs');
  (__PRISMJS_LANGUAGES__ || []).forEach(item => require('prismjs/components/prism-' + item));
}

// ------------------------------------
// Constants
// ------------------------------------
export const SELECT_PAGE = 'SELECT_PAGE';
export const CURRENT_DOCUMENT_PATH = 'CURRENT_DOCUMENT_PATH';
export const REQUEST_PAGE = 'REQUEST_PAGE';
export const RECEIVE_PAGE = 'RECEIVE_PAGE';
export const PAGE_NOT_FOUND = 'PAGE_NOT_FOUND';

// ------------------------------------
// Actions
// ------------------------------------
export function selectPage(pageName) {
  return {
    type: SELECT_PAGE,
    pageName
  };
}

function currentDocumentPath(documentPath) {
  return {
    type: CURRENT_DOCUMENT_PATH,
    documentPath
  };
}

export function requestPage(pageName) {
  return {
    type: REQUEST_PAGE,
    pageName
  };
}

function pageNotFound(pageName) {
  return {
    type: PAGE_NOT_FOUND,
    pageName
  };
}

export function receivePage(pageName, jsonldDoc, data) {
  let baseHtml = data.text;
  const basePath = jsonldDoc.substring(0, jsonldDoc.lastIndexOf('/') + 1);

  // Doing some stuff that require browser only API (chiefly DOM things)
  if ( !__SERVER__) {
    // Highlight code blocks
    const doc = (new DOMParser).parseFromString(baseHtml, 'text/html');
    const codeBlocks = doc.querySelectorAll('code[class*="language-"]');
    let iterator;
    for (iterator = 0; iterator < codeBlocks.length; iterator++) {
      Prism.highlightElement(codeBlocks[iterator]);
    }
    baseHtml = doc.body.innerHTML;
  }

  const wrap = cheerio.load(baseHtml);

  wrap('a').each((index, anchor) => {
    const $anchor = wrap(anchor);
    const href = $anchor.attr('href');
    if (/^(?:[a-z]+:)?\/\//i.test(href)) {
            // Make absolute URLs in target blank
      $anchor.attr('target', '_blank');
    } else {
      // Convert relative JSON-LD URLs
      $anchor.attr('href', './' + href.replace(/index\.jsonld/, '').replace(/\.jsonld/, ''));
    }
  });

  wrap('img').each((index, image) => {
    const $image = wrap(image);
    const src = $image.attr('src');
        // Convert relative URLs
    if (!/^(?:[a-z]+:)?\/\//i.test(src)) {
      const picUrl = path.join('/data', basePath, src);
      $image.attr('src', picUrl);
    }
  });

  return {
    type: RECEIVE_PAGE,
    pageName,
    data: {...data, text: wrap.html()}
  };
}

export function fetchPage(pageName) {
    // Thunk middleware knows how to handle functions.
    // It passes the dispatch method as an argument to the function,
    // thus making it able to dispatch actions itself.

  return (dispatch) => {
    dispatch(requestPage(pageName));
    let jsonldDoc = pageName;
    if (jsonldDoc === '' || jsonldDoc.endsWith('/')) {
      jsonldDoc = jsonldDoc + 'index';
    }

    dispatch(currentDocumentPath(jsonldDoc));

    return getPage(`/data/${jsonldDoc}.jsonld`)
              .then(data => {
                dispatch(receivePage(pageName, jsonldDoc, data));
              }, () => {
                dispatch(pageNotFound(pageName));
              })
              ;
  };
}

// ------------------------------------
// Action Handlers
// ------------------------------------

// ------------------------------------
// Reducer
// ------------------------------------
function selectedPage(state = '', action) {
  switch (action.type) {
    case SELECT_PAGE:
      return action.pageName || '';
    default:
      return state;
  }
}

const initialCurrentDocumentState = {
  path: null
};

function currentDocument(state = initialCurrentDocumentState, action) {
  switch (action.type) {
    case CURRENT_DOCUMENT_PATH:
      return {...state, path: action.documentPath || null};

    default:
      return state;
  }
}

function pages(state = {}, action) {
  switch (action.type) {
    case PAGE_NOT_FOUND:
      return Object.assign({}, state, {
        [action.pageName]: { isFetching: false, data: {}, notFound: true }
      });
    case REQUEST_PAGE:
      return Object.assign({}, state, {
        [action.pageName]: { isFetching: true, data: {}, notFound: false}
      });
    case RECEIVE_PAGE:
      return Object.assign({}, state, {
        [action.pageName]: { isFetching: false, data: action.data, notFound: false }
      });
    default:
      return state;
  }
}

const pageReducer = combineReducers({
  pages,
  selectedPage,
  currentDocument
});

export default pageReducer;


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.11
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.badlogic.gdx.physics.bullet.collision;

public final class ePLANE_INTERSECTION_TYPE {
	public final static int G_BACK_PLANE = 0;
	public final static int G_COLLIDE_PLANE = G_BACK_PLANE + 1;
	public final static int G_FRONT_PLANE = G_COLLIDE_PLANE + 1;
}


text:
package org.terracotta.quartz.wrappers;

import org.quartz.JobDetail;
import org.quartz.spi.OperableTrigger;

public class DefaultWrapperFactory implements WrapperFactory {

  @Override
  public JobWrapper createJobWrapper(JobDetail jobDetail) {
    return new JobWrapper(jobDetail);
  }

  @Override
  public TriggerWrapper createTriggerWrapper(OperableTrigger trigger, boolean jobDisallowsConcurrence) {
    return new TriggerWrapper(trigger, jobDisallowsConcurrence);
  }

}


text:
import { FilterActions } from '../../src/actions/action.types';
import { setSearchTemplate, toggleActiveFilter } from '../../src/actions/filter.actions';

describe('Filter actions test', () => {
	it('Should create setting new search template action', () => {
		const template: string = 'templ';

		const expectedAction: Object = {
			type: FilterActions[FilterActions.SET_SEARCH_TEMPLATE],
			data: template
		};

		expect(setSearchTemplate(template)).toEqual(expectedAction);
	});

	it('Should create filter toggle action', () => {
		const toggle: boolean = true;

		const expectedAction: Object = {
			type: FilterActions[FilterActions.TOGGLE_ACTIVE_FILTER],
			data: toggle
		};

		expect(toggleActiveFilter(toggle)).toEqual(expectedAction);
	});
});


text:
package probe

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"

	"knative.dev/networking/pkg/http/header"
	"knative.dev/networking/pkg/prober"
	"knative.dev/pkg/network"
	_ "knative.dev/pkg/system/testing"
)

func TestProbeHandlerSuccessfulProbe(t *testing.T) {
	const body = "Inner Body"
	cases := []struct {
		name    string
		options []interface{}
		want    bool
		expErr  bool
	}{{
		name: "successful probe when both headers are specified",
		options: []interface{}{
			prober.WithHeader(header.ProbeKey, header.ProbeValue),
			prober.WithHeader(header.HashKey, "foo-bar-baz"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not specified",
		options: []interface{}{
			prober.WithHeader(header.HashKey, "foo-bar-baz"),
			prober.ExpectsBody(body),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(header.HashKey, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "forwards to inner handler when probe header is not 'probe'",
		options: []interface{}{
			prober.WithHeader(header.ProbeKey, "queue"),
			prober.WithHeader(header.HashKey, "foo-bar-baz"),
			prober.ExpectsBody(body),
			prober.ExpectsHeader(header.ProbeKey, "true"),
			// Validates the header is stripped before forwarding to the inner handler
			prober.ExpectsHeader(header.HashKey, "false"),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		want: true,
	}, {
		name: "failed probe when hash header is not present",
		options: []interface{}{
			prober.WithHeader(header.ProbeKey, header.ProbeValue),
			prober.ExpectsStatusCodes([]int{http.StatusOK}),
		},
		expErr: true,
	}}

	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, ok := r.Header[header.ProbeKey]
		w.Header().Set(header.ProbeKey, strconv.FormatBool(ok))
		_, ok = r.Header[header.HashKey]
		w.Header().Set(header.HashKey, strconv.FormatBool(ok))
		w.Write([]byte(body))
	})
	h = NewHandler(h)
	ts := httptest.NewServer(h)
	defer ts.Close()

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := prober.Do(context.Background(), network.AutoTransport, ts.URL, c.options...)
			if err != nil && !c.expErr {
				t.Errorf("prober.Do() = %v, no error expected", err)
			}
			if err == nil && c.expErr {
				t.Errorf("prober.Do() = nil, expected an error")
			}
			if got != c.want {
				t.Errorf("Probe result = %t, want: %t", got, c.want)
			}
		})
	}
}

func BenchmarkProbeHandlerNoProbeHeader(b *testing.B) {
	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
	h = NewHandler(h)
	resp := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)

	b.Run("sequential-no-header", func(b *testing.B) {
		for j := 0; j < b.N; j++ {
			h.ServeHTTP(resp, req)
		}
	})

	b.Run("parallel-no-header", func(b *testing.B) {
		b.RunParallel(func(pb *testing.PB) {
			for pb.Next() {
				h.ServeHTTP(resp, req)
			}
		})
	})
}

func BenchmarkProbeHandlerWithProbeHeader(b *testing.B) {
	req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
	req.Header.Set(header.ProbeKey, header.ProbeValue)
	req.Header.Set(header.HashKey, "ok")
	var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
	h = NewHandler(h)
	b.Run("sequential-probe-header", func(b *testing.B) {
		resp := httptest.NewRecorder()
		for j := 0; j < b.N; j++ {
			h.ServeHTTP(resp, req)
		}
	})

	b.Run("parallel-probe-header", func(b *testing.B) {
		b.RunParallel(func(pb *testing.PB) {
			// Need to create a separate response writer because of the header mutation at the end of ServeHTTP
			respParallel := httptest.NewRecorder()
			for pb.Next() {
				h.ServeHTTP(respParallel, req)
			}
		})
	})
}


text:
package org.traccar.protocol;

import org.jboss.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.helper.BitUtil;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.Parser;
import org.traccar.helper.PatternBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.CellTower;
import org.traccar.model.Network;
import org.traccar.model.Position;
import org.traccar.model.WifiAccessPoint;

import java.net.SocketAddress;
import java.util.Date;
import java.util.regex.Pattern;

public class WatchProtocolDecoder extends BaseProtocolDecoder {

    public WatchProtocolDecoder(WatchProtocol protocol) {
        super(protocol);
    }

    private static final Pattern PATTERN = new PatternBuilder()
            .text("[")
            .expression("(..)").text("*")        // manufacturer
            .number("(d+)").text("*")            // equipment id
            .number("xxxx").text("*")            // length
            .expression("([^,]+)")               // type
            .expression("(.*)")                  // content
            .compile();

    private static final Pattern PATTERN_POSITION = new PatternBuilder()
            .text(",")
            .number("(dd)(dd)(dd),")             // date (ddmmyy)
            .number("(dd)(dd)(dd),")             // time
            .expression("([AV]),")               // validity
            .number(" *(-?d+.d+),")              // latitude
            .expression("([NS]),")
            .number(" *(-?d+.d+),")              // longitude
            .expression("([EW])?,")
            .number("(d+.d+),")                  // speed
            .number("(d+.?d*),")                 // course
            .number("(d+.?d*),")                 // altitude
            .number("(d+),")                     // satellites
            .number("(d+),")                     // rssi
            .number("(d+),")                     // battery
            .number("(d+),")                     // steps
            .number("d+,")                       // tumbles
            .number("(x+),")                     // status
            .expression("([^\\]]*)")             // cell and wifi
            .text("]").optional()
            .compile();

    private void sendResponse(Channel channel, String manufacturer, String id, String content) {
        if (channel != null) {
            channel.write(String.format(
                    "[%s*%s*%04x*%s]", manufacturer, id, content.length(), content));
        }
    }

    private String decodeAlarm(int status) {
        if (BitUtil.check(status, 0)) {
            return Position.ALARM_LOW_BATTERY;
        } else if (BitUtil.check(status, 1)) {
            return Position.ALARM_GEOFENCE_EXIT;
        } else if (BitUtil.check(status, 2)) {
            return Position.ALARM_GEOFENCE_ENTER;
        } else if (BitUtil.check(status, 3)) {
            return Position.ALARM_OVERSPEED;
        } else if (BitUtil.check(status, 16)) {
            return Position.ALARM_SOS;
        } else if (BitUtil.check(status, 17)) {
            return Position.ALARM_LOW_BATTERY;
        } else if (BitUtil.check(status, 18)) {
            return Position.ALARM_GEOFENCE_EXIT;
        } else if (BitUtil.check(status, 19)) {
            return Position.ALARM_GEOFENCE_ENTER;
        }
        return null;
    }

    private void decodeTail(Position position, String data) {
        String[] values = data.split(",");
        int index = 0;

        Network network = new Network();

        int cellCount = Integer.parseInt(values[index++]);
        index += 1; // timing advance
        int mcc = Integer.parseInt(values[index++]);
        int mnc = Integer.parseInt(values[index++]);

        for (int i = 0; i < cellCount; i++) {
            network.addCellTower(CellTower.from(mcc, mnc,
                    Integer.parseInt(values[index++]), Integer.parseInt(values[index++]),
                    Integer.parseInt(values[index++])));
        }

        if (index < values.length && !values[index].isEmpty()) {
            int wifiCount = Integer.parseInt(values[index++]);

            for (int i = 0; i < wifiCount; i++) {
                index += 1; // wifi name
                network.addWifiAccessPoint(WifiAccessPoint.from(
                        values[index++], Integer.parseInt(values[index++])));
            }
        }

        if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) {
            position.setNetwork(network);
        }
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        Parser parser = new Parser(PATTERN, (String) msg);
        if (!parser.matches()) {
            return null;
        }

        String manufacturer = parser.next();
        String id = parser.next();
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, id);
        if (deviceSession == null) {
            return null;
        }

        String type = parser.next();
        String content = parser.next();

        if (type.equals("LK")) {

            sendResponse(channel, manufacturer, id, "LK");

            if (!content.isEmpty()) {
                String[] values = content.split(",");
                if (values.length >= 4) {
                    Position position = new Position();
                    position.setProtocol(getProtocolName());
                    position.setDeviceId(deviceSession.getDeviceId());

                    getLastLocation(position, null);

                    position.set(Position.KEY_BATTERY, values[3]);

                    return position;
                }
            }

        } else if (type.equals("UD") || type.equals("UD2") || type.equals("AL")) {

            if (type.equals("AL")) {
                sendResponse(channel, manufacturer, id, "AL");
            }

            parser = new Parser(PATTERN_POSITION, content);
            if (!parser.matches()) {
                return null;
            }

            Position position = new Position();
            position.setProtocol(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            DateBuilder dateBuilder = new DateBuilder()
                    .setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt())
                    .setTime(parser.nextInt(), parser.nextInt(), parser.nextInt());
            position.setTime(dateBuilder.getDate());

            position.setValid(parser.next().equals("A"));
            position.setLatitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_HEM));
            position.setLongitude(parser.nextCoordinate(Parser.CoordinateFormat.DEG_HEM));
            position.setSpeed(UnitsConverter.knotsFromKph(parser.nextDouble()));
            position.setCourse(parser.nextDouble());
            position.setAltitude(parser.nextDouble());

            position.set(Position.KEY_SATELLITES, parser.nextInt());
            position.set(Position.KEY_RSSI, parser.nextInt());
            position.set(Position.KEY_BATTERY, parser.nextInt());

            position.set("steps", parser.nextInt());

            position.set(Position.KEY_ALARM, decodeAlarm(parser.nextInt(16)));

            decodeTail(position, parser.next());

            return position;

        } else if (type.equals("TKQ")) {

            sendResponse(channel, manufacturer, id, "TKQ");

        } else if (type.equals("PULSE")) {

            Position position = new Position();
            position.setProtocol(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());
            getLastLocation(position, new Date());
            position.setValid(false);
            String pulse = content.substring(1);
            position.set("pulse", pulse);
            position.set(Position.KEY_RESULT, pulse);
            return position;

        }

        return null;
    }

}


text:
title: Configuration order for persistence
summary: When configuring persistence, order is very important
tags:
- Persistence
redirects:
- nservicebus/persistence-order
---

When configuring persistence in NServiceBus Version 5, order is very important.
The last configured persistence option wins.
Lets have a look at some examples.

### Example 1

In this example the last configuration option will override all previous options.

snippet:PersistenceOrder_Incorrect

### Example 2

In this example all configuration options are explicit.

snippet:PersistenceOrder_Explicit

### Example 3

This example sets the default persistence first thing and then overrides more explicit options.

snippet:PersistenceOrder_Correct


text:
//
//  RSFCommand.h
//  Jestful
//
//  Created by 杨昌沛 on 16/5/26.
//  Copyright © 2016年 qfoxtech. All rights reserved.
//

#ifndef RSFCommand_h
#define RSFCommand_h

#import <Foundation/Foundation.h>
#import "RSFAnnotation.h"

@protocol RSFCommand <NSObject>

-(NSString *)value;

-(NSArray<NSString *> *)produces;

-(NSArray<NSString *> *)consumes;

+(NSString *)name;

+(BOOL)acceptBody;

+(BOOL)returnBody;

+(BOOL)idempotent;

@end

#endif /* RSFCommand_h */


text:
package numbers

object `package` {

  def oneto(x: Int): Range = (1 to x)

}


text:
import React from 'react'
import ReactDOM from 'react-dom'
import { mapValues, isString, isNil, forOwn, isEmpty } from 'lodash'

import { createInputModel } from './InputModel.js'
import { CheckboxInput } from './CheckboxInput.jsx'

var info = {
	remembermodel: null,
	remembervalue: true,
	updateRemember: function(value) {
		info.remembervalue = value
		display()
	},
	supermodel: null,
	supervalue: null,
	updateSuper: function(value) {
		info.supervalue = value
		display()
	}
}

function loadData() {
	info.remembermodel = createInputModel({value:info.remembervalue, listeners:[info.updateRemember]})
	info.supermodel = createInputModel({value:null, listeners:[info.updateSuper]})
}

loadData()

function display() {
	var content = (

			<form>
				<CheckboxInput model={info.remembermodel} label="Remember" />
				<CheckboxInput model={info.supermodel} label="Super" selectedValue="Batman" />
				<button type="submit" className="btn btn-lg btn-primary btn-block" onClick={info.submitRequest}
						disabled={(!info.remembermodel.isValid() || !info.supermodel.isValid())}>Submit</button>
			</form>

Remember Value {Boolean(info.remembervalue).toString()}

Super Value {info.supervalue}

	)

	ReactDOM.render(
	  content,
	  document.getElementById('target')
	)
}
display()


text:
package com.notcmput301.habitbook;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.provider.Settings;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.notcmput301.habitbook.R.id.location;

/**
 * Activity for displaying HabitEvent Details
 *
 * @author NOTcmput301
 * @version 1.0
 * @since 1.0
 */
public class HabitEventDetailsActivity extends AppCompatActivity {

    private User loggedInUser;
    private HabitEvent habitEvent;
    private HabitTypeSingleton HTS;
    private ArrayList<HabitType> habitTypes;
    private NetworkHandler nH;

    private LocationManager locationManager;
    private LocationListener listener;
    private Location currentlocation = null;
    private EditText titleE;
    private EditText commentE;
    private Button addPicB;
    private Button backB;
    private Button location;
    private CircleImageView imageV;
    private Gson gson = new Gson();

    /**
     * Called when the activity is first created.
     *
     * @param savedInstanceState previous instance of activity
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habit_event_details);

        Intent receiver = getIntent();
        String u = receiver.getExtras().getString("passedUser");
        String e = receiver.getExtras().getString("passedHabitEvent");

        loggedInUser = gson.fromJson(u, User.class);
        habitEvent = gson.fromJson(e, HabitEvent.class);
        HTS=HabitTypeSingleton.getInstance();
        habitTypes=HTS.getHabitTypes();
        nH = new NetworkHandler(this);

        commentE = (EditText) findViewById(R.id.HED_Comment);
        commentE.setText(habitEvent.getComment());
        try {
            CircleImageView imageV = (CircleImageView) findViewById(R.id.HED_Image);
            imageV.setImageBitmap(habitEvent.imageToBitmap());
        }catch (Exception e1){

        }

        //Checks if Network Connection is detected.
        BroadcastReceiver br = new NetworkStateChangeReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(br, filter);
        location = (Button) findViewById(R.id.GetLocation);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Double la = location.getLatitude();
                Double lo = location.getLongitude();
                String s = la.toString()+"  "+lo.toString();
                currentlocation = location;
                Toast.makeText(HabitEventDetailsActivity.this, s, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);
            }
        };

        //Checks if Network Connection is detected.

        configure_button();
    }

    void configure_button(){
        // first check for permissions
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
                        ,10);
            }
            return;
        }
        // this code won't execute IF permissions are not allowed, because in the line above there is return statement.
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //noinspection MissingPermission
                locationManager.requestLocationUpdates("gps", 500, 0, listener);
            }
        });
    }

    /**
     * Updates HabitEvent with provided info
     *
     * @param view view of current activity info
     */
    public void update(View view){

        String comment = commentE.getText().toString();
        if (comment.length() > 20){
            Toast.makeText(this, "comment should be less than 20 characters", Toast.LENGTH_SHORT).show();
            return;
        }

        if (nH.isNetworkAvailable() && habitTypes.size() == 0){
            habitTypes = nH.getHabitList(loggedInUser.getUsername());
            HTS.setHabitTypes(habitTypes);
        }

        for(int i=0; i < habitTypes.size(); i++){

            HabitType h = habitTypes.get(i);
            ArrayList<HabitEvent> he = h.getEvents();

            for (int j =0; j < he.size(); j++){
                HabitEvent eve = he.get(j);

                if (eve.getComment().equals(habitEvent.getComment())){

                    if (nH.isNetworkAvailable()){
                        nH.deleteHabitType(h);
                        h.removeHabitEvent(eve);
                        habitEvent.setComment(comment);
                        if (currentlocation != null) {
                            habitEvent.setLatitude(currentlocation.getLatitude());
                            habitEvent.setLongitude(currentlocation.getLongitude());
                        }
                        h.addHabitEvent(habitEvent);
                        nH.addHabitType(h);
                    }else{
                        nH.putString("d", gson.toJson(h));
                        h.removeHabitEvent(eve);
                        habitEvent.setComment(comment);
                        h.addHabitEvent(habitEvent);
                        nH.putString("au", gson.toJson(h));
                    }
                    habitTypes.set(i, h);
                    HTS.setHabitTypes(habitTypes);
                    break;
                }
            }
        }
        back();
    }

    /**
     * Deletes a HabitEvent.
     *
     * @param view view of current activity status
     */
    public void delete(View view){

        if (nH.isNetworkAvailable() && habitTypes.size() == 0){
            habitTypes=nH.getHabitList(loggedInUser.getUsername());
            HTS.setHabitTypes(habitTypes);
        }

        for(int i=0; i < habitTypes.size(); i++){

            HabitType h = habitTypes.get(i);
            ArrayList<HabitEvent> he = h.getEvents();

            for (int j =0; j < he.size(); j++){
                HabitEvent eve = he.get(j);

                if (eve.getComment().equals(habitEvent.getComment())){

                    if (nH.isNetworkAvailable()){
                        nH.deleteHabitType(h);
                        h.removeHabitEvent(eve);
                        nH.addHabitType(h);
                    }else{
                        nH.putString("d", gson.toJson(h));
                        h.removeHabitEvent(eve);
                        nH.putString("au", gson.toJson(h));
                    }
                    habitTypes.set(i, h);
                    HTS.setHabitTypes(habitTypes);
                    break;
                }
            }
        }
        back();
    }

    /**
     * return to previous activity
     *
     */
    public void back(){
        Intent habitEventHistory = new Intent(HabitEventDetailsActivity.this, HabitEventHistory2.class);

        habitEventHistory.putExtra("passedUser", gson.toJson(loggedInUser));

        finish();
        startActivity(habitEventHistory);
    }

    /**
     * return to previous activity
     *
     * @param view view of current activity status
     */
    public void back(View view){
        back();
    }
}


text:
<?php

namespace App\Http\Requests;

class OrganizationDeleteFormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [];
    }
}


text:
#import "XCUIElement+FBTap.h"

#import "FBRunLoopSpinner.h"
#import "FBLogger.h"
#import "XCUIElement+Utilities.h"
#import "XCElementSnapshot-Hitpoint.h"
#import "XCEventGenerator.h"
#import "XCSynthesizedEventRecord.h"

@implementation XCUIElement (FBTap)

- (BOOL)fb_tapWithError:(NSError **)error
{
  [self fb_waitUntilFrameIsStable];
  __block BOOL didSucceed;
  [FBRunLoopSpinner spinUntilCompletion:^(void(^completion)()){
    CGPoint hitPoint = self.isHittable ? self.lastSnapshot.hitPoint : [self coordinateWithNormalizedOffset:CGVectorMake(0.5, 0.5)].screenPoint;
    [[XCEventGenerator sharedGenerator] tapAtPoint:hitPoint orientation:self.interfaceOrientation handler:^(XCSynthesizedEventRecord *record, NSError *commandError) {
      if (commandError) {
        [FBLogger logFmt:@"Failed to perform tap: %@", commandError];
      }
      if (error) {
        *error = commandError;
      }
      didSucceed = (commandError == nil);
      completion();
    }];
  }];
  return didSucceed;
}

@end


text:
module Vec {
    export type Tuple = [number, number];

    export interface Obj {
        x: number;
        y: number;
    }
}

export = Vec;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='FileModel',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
                ('test_file', models.FileField(null=True, blank=True, upload_to='fileapp/')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package cn.ieclipse.af.demo.sample.appui;

import cn.ieclipse.af.demo.sample.ButtonListFragment;

/**
 * Description
 *
 * @author Jamling
 */
public class TabAppFragment extends ButtonListFragment {
    @Override
    public CharSequence getTitle() {
        return "App struct";
    }

    @Override
    protected Class[] getActivities() {
        return new Class[]{
            AfActivitySample.class, AfActivityImmersiveSample.class, LoadingActivitySample.class, FileChooserSample.class,
            H5Sample.class, AfFragmentSample.class, RadioTabSample.class, ImageBrowserSample.class, AfDownloadSample
            .class, SearchSample.class
        };
    }
}


text:
por [Daniel Monza](https://uy.linkedin.com/in/daniel-monza-62515112)

## Tabla de Contenidos

  1. [Glosario](#glosario)
  1. [Configuración de Internet Information Server (IIS)](#configuración-de-internet-information-server-(iis))
  1. [Deploy de la aplicación GeneXus](#deploy-de-la-aplicación-genexus)

## Glosario

- IIS : Internet Information Services
- RDP : Remote Desktop
- HSTS: HTTP Strict Transport Security

## Configuración de Internet Information Server (IIS)

### Instalar Asp.Net 4.0 o superior y WebSockets

![IIS Features](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/features.png)

Es utilizado por GeneXus para enviar WebNotifications.

### Instalar módulo Rewrite

El módulo rewrite tiene varios usos, entre ellos sirve para publicar servicios rest en GeneXus.

Para ello, primero se debe instalar Microsoft Web Platform Installer:

https://www.microsoft.com/web/downloads/platform.aspx

### Crear la carpeta donde se publicará la aplicación

Para ello, siempre nos conviene crear una carpeta donde estarán todas nuestras aplicaciones, Ej.: C:\Sites

### Crear sitio en IIS

![New Site](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/newsite.png)

### Activar autenticación mediante Application Pool

Dentro del sitio creado en IIS accedemos a "Authentication\Anonymous Authentication":

![Auth](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/authentication.PNG)

Luego creamos la carpeta de nuestra app, ej.: c:\Sites\MyApp

### Permisos de acceso para el usuario del application pool

El usuario se valida según: IIS AppPool\[nombre de application pool]

![Permisos](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/grants.png)

### Agregar HSTS Header

Si queremos que nuestro sitio sea accedido solo bajo HTTPS, es encesario definir el encabezado HSTS. De esta forma, los navegadores interpreten que nuestro sitio debe ser accedido de forma segura.

Para ello, accedemos a nuestro sitio dentro del IIS e ingresamos al módulo "HTTP Response Headers" donde agregamos el siguiente encabezado:

Name : Strict-Transport-Security
Value: max-age=108000; includeSubDomains; preload

max-age: Tiempo en segundos que el navegador recordará la configuración.
includeSubDomains: Incluir sub-dominios en la configuración HSTS
preload: Indica que se agregará el dominio a la lista Chromium, safari e IE para su revisión.

![IIS Features](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/hsts.png)

### Aislamiento del exterior
Corroborar que nuestro sitio sea únicametne accesible por los puertos TCP 80 y TCP 443 desde el exterior.

Tener en cuenta si accedemos al servidor por RDP, filtrar el acceso para que solo se pueda ingresar desde la IP pública desde donde estamos accediento. Lo mismo para la base de datos.

**[Volver al inicio](#tabla-de-contenidos)**

## Deploy de la aplicación GeneXus

### Configurar encripción de parámetros

Para configurar ésta propiedad, revisar la siguiente url:

https://wiki.genexus.com/commwiki/servlet/wiki?8068,Encrypt%20URL%20Parameters%20property

### Cambiar clave de encripción por defecto

Se pueden generar nuevas claves con la función [GetEncryptionKey](https://wiki.genexus.com/commwiki/servlet/wiki?8385,GetEncryptionKey+Function) de GeneXus.

En GeneXus 15 esto se puede hacer directamente desde la opción Deploy.

Aquí dejo los links para hacerlo en versiones anteriores a GeneXus 15.

https://www.genexus.com/developers/websac?en,,,29874;;

https://www.genexus.com/developers/websac?en,,,29369;;

### Configurar Servidor de Sesiones

1. Configurar "Session State" según las imágenes siguientes:

![IIS Features](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/sessionstate.png)
![Timeout](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/sessionstate2.png)

2. Luego se debe iniciar y dejar automático el servicio "ASP.NET State Service".

### Definir página por defecto

Como GeneXus generea la aplicación Asp.Net de forma compilada (con dll's), es necesario crear en la carpeta base (donde está el web.config), un archivo con el nombre de nuestro Webpanel por defecto, ej.: home.aspx

Luego en IIS, dentro de nuestro sitio, en el módulo "Default Document", agregamos el hombre de nuestro panel por defecto "home.aspx".

Lo mejor es que solo quede éste, de forma que no haya posibilidad que quede otro panel por defecto, ya sea por un descuido o intrusión.

![Default Page](https://raw.githubusercontent.com/sincrum/genexus/master/deploynet/default_document.PNG)

## A tener en cuenta

No subir el developer menu.

### En caso de publicar Webservices
Hacerlo stateless, o sea, no especificar manejador de sesiones.

Generalmente los webservices no necesitan manejar sesión y si se especifica, se puede incurrir en problemas de performance por lockeo de sesiones.

### Forticlient vulnerability scan

**[Volver al inicio](#tabla-de-contenidos)**


text:
// 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 com.cloud.async;

public interface AsyncJobExecutor {
	public AsyncJobManager getAsyncJobMgr();
	public void setAsyncJobMgr(AsyncJobManager asyncMgr);
	public SyncQueueItemVO getSyncSource();
	public void setSyncSource(SyncQueueItemVO syncSource);
	public AsyncJobVO getJob();
	public void setJob(AsyncJobVO job);
	public void setFromPreviousSession(boolean value);
	public boolean isFromPreviousSession();

	/**
	 *
	 * 	otherwise return false and once the executor finally has completed with the sync source,
	 *  it needs to call AsyncJobManager.releaseSyncSource
	 *
	 *  if executor does not have a sync source, always return true
	 */
	public boolean execute();
}


text:
'use strict';

var GetIntrinsic = require('get-intrinsic');

var $TypeError = GetIntrinsic('%TypeError%');

var $getProto = require('../helpers/getProto');

var Type = require('./Type');

// https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof

module.exports = function OrdinaryGetPrototypeOf(O) {
	if (Type(O) !== 'Object') {
		throw new $TypeError('Assertion failed: O must be an Object');
	}
	if (!$getProto) {
		throw new $TypeError('This environment does not support fetching prototypes.');
	}
	return $getProto(O);
};


text:
package uk.theretiredprogrammer.authentication;

import javax.json.JsonObject;
import javax.json.stream.JsonGenerator;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.annotation.WebServlet;
import uk.theretiredprogrammer.jeelibrary.GetServlet;
import uk.theretiredprogrammer.jeelibrary.IdandstampEntity;

/**
 * Servlet to handle request to get an Application entity, selected using its
 * primary Key.
 *
 * (Class generated by NetBeans Platform Code Generator tools using script.xml.
 * Do not edit this file. Apply any changes to the definition file and
 * regenerate all files.)
 *
 * @author Richard Linsdale (richard at theretiredprogrammer.uk)
 */
@WebServlet("/Userpermission/get")
public class UserpermissionGetServlet extends GetServlet<Userpermission, Integer> {

    @PersistenceContext(unitName = "authentication2_PU")
    private EntityManager em;

    /**
     * Constructor
     */
    public UserpermissionGetServlet() {
        super(Userpermission.class);
    }

    @Override
    public String getServletInfo() {
        return "authentication/Userpermission/get Servlet";
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    @Override
    protected Integer getPK(JsonObject command) {
        return IdandstampEntity.getPK(command);
    }

    @Override
    protected void writePK(JsonGenerator generator, Integer pkey) {
        IdandstampEntity.writePK(generator, pkey);
    }
}


text:
// This file was generated by modules-webmake (modules for web) project
// see: https://github.com/medikoo/modules-webmake

window.schema = (function (modules) {
  var getModule, getRequire, require;
  getModule = (function (wrap) {
    return function (scope, tree, path, fullpath) {
      var name, dir, exports = {}, module = { exports: exports }, fn, isDir;
      path = path.split('/');
      name = path.pop();
      if (!name) {
        isDir = true;
        name = path.pop();
      }
      if ((name === '.') || (name === '..')) {
        path.push(name);
        name = '';
      }
      while ((dir = path.shift())) {
        if (dir === '..') {
          scope = tree.pop();
        } else if (dir !== '.') {
          tree.push(scope);
          scope = scope[dir];
        }
      }
      if (name) {
        if (!isDir && scope[name + '.js']) {
          name += '.js';
        }
        if (typeof scope[name] === 'object') {
          tree.push(scope);
          scope = scope[name];
          name = 'index.js';
        }
      } else {
        name = 'index.js';
      }
      fn = scope[name];
      if (!fn) {
        throw new Error("Could not find module '" + fullpath + "'");
      }
      scope[name] = wrap(module);
      fn.call(exports, exports, module, getRequire(scope, tree));
      return module.exports;
    };
  }(function (cmodule) {
    return function (ignore, module) {
      module.exports = cmodule.exports;
    };
  }));
  require = function (scope, tree, fullpath) {
    var name, path = fullpath, t = fullpath.charAt(0);
    if (t === '/') {
      path = path.slice(1);
      scope = modules['/'];
      tree = [];
    } else if (t !== '.') {
      name = path.split('/', 1)[0];
      scope = modules[name];
      tree = [];
      path = path.slice(name.length + 1) || scope[':mainpath:'];
    }
    return getModule(scope, tree, path, fullpath);
  };
  getRequire = function (scope, tree) {
    return function (path) {
      return require(scope, [].concat(tree), path);
    };
  };
  return getRequire(modules, []);
})
({
  "schemajs": {
    "lib": {
      "rules.js": function (exports, module, require) {
        var Rules = function(param, rules)
        {
          this.param = param;
          this.rules = rules;
        };

        Rules.prototype.Error = function(message, rule, value)
        {
          switch(typeof(this.rules.error))
          {
            case 'string':
              message = this.rules.error;
              break;

            case 'object':

              if(this.rules.error[rule])
              {
                message = this.rules.error[rule];
              }
              else if(this.rules.error['default'])
              {
                message = this.rules.error['default'];
              }

              break;
          }

           if(_.isString(value))
              message = message.replace(/%v/, value.toString());

           if(_.isString(rule))
              message = message.replace(/%r/, rule);

          return message.replace(/%p/, this.param).replace(/%v/, "value").replace(/%r/, "rule");
        };

        Rules.prototype.apply = function(value)
        {
          if(_.isEmpty(value) && !_.isUndefined(this.rules['default']))
          {
            value = this.rules['default'];
          }

          if(this.rules.required)
          {
            if(this.rules.required && _.isUndefined(value))
            {
              throw this.Error("%p is a required parameter", "required", value);
            }
          }

          // if null is allowed, then no more rules need to be run
          if(this.rules.allownull && _.isNull(value)) return value;

          // if value is not required and is undefined, no more rules need to be run
          if(_.isUndefined(value)) return value;

          if(this.rules.filters)
          {
            value = this.filter(value);
          }

          if(this.rules.type)
          {
              if(typeof(this.rules.type) == "string" && typeof(is[this.rules.type]) == "function")
              {
                 if(!is[this.rules.type](value))
                    throw this.Error("%p is not a " + this.rules.type, "type", value);
              }
              else if(typeof(this.rules.type == "function"))
              {
                 if(!this.rules.type(value))
                    throw this.Error("%p is not a valid type", "type", value);
              }
              else
              {
                 throw this.Error("%p is not a valid type", "type", value);
              }
          }

          if(this.rules.properties)
          {
            this.check(value);
          }

          return value;
        };

        Rules.prototype.filter = function(value)
        {
          switch(typeof(this.rules.filters))
          {
            case 'function':
              value = this.rules.filters(value);
              break;

            case 'string':

              if(typeof(filters[this.rules.filters]) === 'function')
              {
                value = filters[this.rules.filters](value);
              }

              break;

            case 'object':

              if(_.isArray(this.rules.filters))
              {
                this.rules.filters.forEach(function(filter) { value = filters[filter](value); });
              }

              break;
          }

          return value;
        };

        Rules.prototype.check = function(value)
        {
          switch(typeof(this.rules.properties))
          {
            case 'function':

              if(!this.rules.properties(value))
                throw this.Error("%p is not valid");

              break;

            case 'object':

              var properties = _.keys(this.rules.properties);

              for(var i = 0; i < properties.length; i++)
              {
                var property = properties[i];

                if(typeof(checks[property]) === "function")
                {
                  var args = this.rules.properties[property];

                  if(!checks[property].apply(null, [value, args]))
                    throw this.Error("%p failed %r with %v", property);
                }
                else if(typeof(this.rules.properties[property]) === "function")
                {
                  if(!this.rules.properties[property].apply(null, [value]))
                    throw this.Error("%p failed on %r with %v", property);
                }
              }

              break;
          }
        };

        var checks =
        {
          'max': function(value, length)
          {
              if(_.isArray(value) || typeof(value) == "string")
              {
                 return value.length <= length;
              }
              else if(typeof(value) == "number")
              {
                 return value <= length;
              }
              else
              {
                 return false;
              }
          },

          'min': function(value, length)
          {
              if(_.isArray(value) || typeof(value) == "string")
              {
                 return value.length >= length;
              }
              else if(typeof(value) == "number")
              {
                 return value >= length;
              }
              else
              {
                 return false;
              }
          },

          'regex': function(value, regex)
          {
            return regex.test(value);
          },

          'in': function(value, list)
          {
            return list.indexOf(value) != -1;
          }
        };

        var is =
        {
          'string+': function(value)
          {
            return typeof(value) == 'string' && value.length && !(/^\s+$/.test(value));
          },

           'string': function(value)
          {
            return typeof(value) == 'string';
          },

           'alphanum': function(value)
           {
              return (/^[a-zA-Z0-9]+$/i).test(value) && typeof(value) == 'string';
           },

           'alpha': function(value)
           {
              return (/^[a-zA-Z]+$/i).test(value);
           },

          'object': function(value)
          {
            return typeof(value) == 'object' && !_.isArray(value);
          },

          'array': function(value)
          {
             return _.isArray(value);
          },

          'date': function(value)
          {
              // getTime() allows us to check if date is valid
            return _.isDate(value) && !isNaN(value.getTime());
          },

          'number': function(value)
          {
              return typeof(value) == 'number' && !isNaN(value);
          },

          'int': function(value)
          {
            return typeof(value) == 'number' && value % 1 === 0 && !isNaN(value);
          },

          'boolean': function(value)
          {
            return _.isBoolean(value);
          },

          'float': function(value)
          {
            return typeof(value) == 'number' && !isNaN(value);
          },

          'email': function(value)
          {
            return (/[a-zA-Z0-9!#$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?\^_`{|}~\-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?/).test(value);
          },

          'url': function(value)
          {
            return (/^(http(s)?:\/\/)?([\w\-]+\.{1})*(([\w\-]*){1}(\.{1}[A-Za-z]{2,4}){1}){1}(\:{1}\d*)?([\?\/|\#]+[\@\~\;\+\'\#\,\.\%\-\/\&\?\=\w\$\s]*)*$/i).test(value);
          },

          'zipcode': function(value)
          {
            return (/\d{5}/).test(value);
          }
        };

        var filters =
        {
          'toInt': function(value)
          {
            var num = parseInt(value, 10);
            return _.isNaN(num) ? null : num;
          },

          'toFloat': function(value)
          {
            var num = parseFloat(value, 10);
            return _.isNaN(num) ? null : num;
          },

          'toString': function(value)
          {
            return value.toString();
          },

          'toDate': function(value)
          {
            return new Date(value);
          },

          'toBoolean': function(value)
          {
            if(value === 1 || value === true || /true|on|yes|1/.test(value))
              return true;
            else if(value === 0 || value === false || /false|off|no|0/.test(value))
              return false;
            else
              return value;
          },

          'trim': function(value)
          {
            return _.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
          },

          'lowercase': function(value)
          {
            return _.isString(value) ? value.toLowerCase() : value;
          },

          'uppercase': function(value)
          {
            return _.isString(value) ? value.toUpperCase() : value;
          }
        };

        exports.create = function(param, rules) { return new Rules(param, rules); };
        exports.types = is;
        exports.filters = filters;
        exports.properties = checks;
      },
      "schema.js": function (exports, module, require) {
        var rules = require('./rules.js');

        var Schema = function(schema) {
          this.schema = schema;
        };

        var checkObject = function(schema, key, errors, values, get) {
          var value;

          _.keys(schema.schema).forEach(function(param) {
            try {

              // if undefined, don't store it
              value = rules.create(key + "." + param, schema.schema[param]).apply(get(key)[param]);

              if (!_.isUndefined(value)) {
                values[key][param] = value;
              }
            } catch (error) {
              if (!errors[key] || typeof(errors[key]) != 'object') errors[key] = {};

              errors[key][param] = error;
            }
          });
        };

        var checkArray = function(schema, key, errors, values, get) {
          values[key].forEach(function(value, index) {
            try {
              if(schema.schema.schema) {
                // if array has another schema, then we want objects!
                value = rules.create(key, {type:'object'}).apply(value);
                var results = (new Schema(schema.schema.schema)).validate(value);
                if(!results.valid)
                {
                  errors[key] = errors[key] || [];
                  errors[key][index] = results.errors;
                }
                values[key][index] = results.data;
              }
              else
                values[key][index] = rules.create(key + "[" + index + "]", schema.schema).apply(value);
            } catch (error) {
              if (!_.isArray(errors[key])) errors[key] = [];
              errors[key][index] = error;
            }
          });
        };

        /*jshint loopfunc:true*/

        Schema.prototype.validate = function(data) {
          var params = _.keys(this.schema);
          var errors = {};
          var values = {};
          var value;
          var get = typeof(data) == "function" ? data : function(p) {
              return data[p];
            };

          for (var i = 0; i < params.length; i++) {
            var schema = this.schema[params[i]];

            try {

              // if undefined, don't store it.
              value = rules.create(params[i], schema).apply(get(params[i]));

              if (!_.isUndefined(value)) {
                values[params[i]] = value;
              }

              // does this rule contain embedded schemas
              if (typeof(schema.schema) == "object" && !_.isArray(schema.schema) && _.keys(schema.schema).length && !_.isUndefined(values[params[i]])) {
                if (schema.type == "object") {
                  //checkObject(schema, params[i], errors, values, get);
                  var results = (new Schema(schema.schema)).validate(values[params[i]]);

                  if(!results.valid)
                    errors[params[i]] = results.errors;
                  values[params[i]] = results.data;
                } else if (schema.type == "array") {
                  checkArray(schema, params[i], errors, values, get);
                }
              }
            } catch (error) {
              errors[params[i]] = error;
            }
          }

          return {
            data: values,
            errors: errors,
            valid: _.keys(errors).length === 0
          };
        };

        exports.types = rules.types;
        exports.test = function(value, schema) {
          return (new Schema({
            input: schema
          })).validate({
            input: value
          });
        };
        exports.properties = rules.properties;
        exports.filters = rules.filters;
        exports.create = function(schema) {
          return new Schema(schema);
        };
        exports.middleware = function(schema) {
          return function(req, res, next) {
            req.form = new Schema(schema).validate(req.route.method == "post" ? req.body : req.query);
            next();
          };
        };
      }
    },
    "schema.js": function (exports, module, require) {
      module.exports = require("./lib/schema.js");
    }
  }
})("schemajs/schema");


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
    /// The nullable state of an rvalue computed in <see cref="NullableWalker"/>.
    /// When in doubt we conservatively use <see cref="NullableFlowState.NotNull"/>
    /// to minimize diagnostics.
    /// </summary>
    internal enum NullableFlowState : byte
    {
        NotNull,
        MaybeNull
    }
}


text:
namespace open_spiel {

// A GameParameter can be used in 3 contexts:
// - when defining the parameters for a game, with their optional default value
//   and whether they are mandatory or not.
// - when specifying in Python a parameter value.
// - when passing a parametrization of additional Observer fields.
//
class GameParameter;

using GameParameters = std::map<std::string, GameParameter>;
std::string GameParametersToString(const GameParameters& game_params);
GameParameter GameParameterFromString(const std::string& str);
GameParameters GameParametersFromString(const std::string& game_string);

inline constexpr const char* kDefaultNameDelimiter = "=";
inline constexpr const char* kDefaultParameterDelimiter = "|||";
inline constexpr const char* kDefaultInternalDelimiter = "***";

class GameParameter {
 public:
  enum class Type { kUnset = -1, kInt, kDouble, kString, kBool, kGame };

  explicit GameParameter(Type type = Type::kUnset, bool is_mandatory = false)
      : is_mandatory_(is_mandatory), type_(type) {}

  explicit GameParameter(int value, bool is_mandatory = false)
      : is_mandatory_(is_mandatory), int_value_(value), type_(Type::kInt) {}

  explicit GameParameter(double value, bool is_mandatory = false)
      : is_mandatory_(is_mandatory),
        double_value_(value),
        type_(Type::kDouble) {}

  explicit GameParameter(std::string value, bool is_mandatory = false)
      : is_mandatory_(is_mandatory),
        string_value_(value),
        type_(Type::kString) {}

  // Allows construction of a `GameParameter` from a string literal. This method
  // is not subsumed by the previous method, even if value can be converted to a
  // std::string, because the [C++ standard][iso] requires that the *standard
  // conversion sequence* (see §13.3.3.1.1)
  // `(const char[]) -> const char* -> bool` take precedence over the
  // *user-defined conversion sequence*
  // `(const char[]) -> const char* -> std::string` defined in the standard
  // library.
  // [iso]: http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2011/n3242.pdf
  explicit GameParameter(const char* value, bool is_mandatory = false)
      : is_mandatory_(is_mandatory),
        string_value_(value),
        type_(Type::kString) {}

  explicit GameParameter(bool value, bool is_mandatory = false)
      : is_mandatory_(is_mandatory), bool_value_(value), type_(Type::kBool) {}

  explicit GameParameter(GameParameters value,
                         bool is_mandatory = false)
      : is_mandatory_(is_mandatory),
        game_value_(std::move(value)),
        type_(Type::kGame) {}

  bool has_int_value() const { return type_ == Type::kInt; }
  bool has_double_value() const { return type_ == Type::kDouble; }
  bool has_string_value() const { return type_ == Type::kString; }
  bool has_bool_value() const { return type_ == Type::kBool; }
  bool has_game_value() const { return type_ == Type::kGame; }
  Type type() const { return type_; }

  bool is_mandatory() const { return is_mandatory_; }

  // A readable string format, for display purposes; does not distinguish
  // types in ambiguous cases, e.g. string True vs boolean True.
  std::string ToString() const;

  // An unambiguous string representation, including type information.
  // Used for __repr__ in the Python interface.
  std::string ToReprString() const;

  // Everything necessary to reconstruct the parameter in string form:
  // type <delimiter> value <delimiter> is_mandatory.
  std::string Serialize(
      const std::string& delimiter = kDefaultInternalDelimiter) const;

  int int_value() const {
    SPIEL_CHECK_TRUE(type_ == Type::kInt);
    return int_value_;
  }

  double double_value() const {
    SPIEL_CHECK_TRUE(type_ == Type::kDouble);
    return double_value_;
  }

  const std::string& string_value() const {
    SPIEL_CHECK_TRUE(type_ == Type::kString);
    return string_value_;
  }

  bool bool_value() const {
    SPIEL_CHECK_TRUE(type_ == Type::kBool);
    return bool_value_;
  }

  const GameParameters& game_value() const {
    SPIEL_CHECK_TRUE(type_ == Type::kGame);
    return game_value_;
  }

  // Access values via param.value<T>().
  // There are explicit specializations of this function that call the
  // ***_value() functions above, however they are defined in game_parameters.cc
  // to avoid compilation problems on some older compilers.
  template <typename T>
  T value() const;

  template <typename T>
  T value_with_default(T default_value) const;

  bool operator==(const GameParameter& rhs) const {
    switch (type_) {
      case Type::kInt:
        return rhs.has_int_value() && int_value_ == rhs.int_value();
      case Type::kDouble:
        return rhs.has_double_value() && double_value_ == rhs.double_value();
      case Type::kString:
        return rhs.has_string_value() && string_value_ == rhs.string_value();
      case Type::kBool:
        return rhs.has_bool_value() && bool_value_ == rhs.bool_value();
      case Type::kGame:
        return rhs.has_game_value() && game_value_ == rhs.game_value();
      case Type::kUnset:
        return rhs.type_ == Type::kUnset;
    }
    std::cerr << "Unrecognized parameter type in operator=="
              << ", returning false." << std::endl;
    return false;
  }
  bool operator!=(const GameParameter& rhs) const { return !(*this == rhs); }

 private:
  bool is_mandatory_;

  // Default initializations are required here. This is because some games mark
  // parameters as not mandatory and also do not specify default values when
  // registering the game type.. instead, setting the documented defaults upon
  // game creation (often due to missing information at registration time).
  // This causes a problem when inspecting the game types themselves, even after
  // the game is created via Game::GetType(), which returns the type as it was
  // when it was registered. These initial values are used for those cases.
  int int_value_ = 0;
  double double_value_ = 0.0;
  std::string string_value_ = "";
  bool bool_value_ = false;
  GameParameters game_value_ = {};
  Type type_;
};

std::string GameParameterTypeToString(const GameParameter::Type& type);

// Game Parameters and Game Parameter Serialization/Deserialization form:
// param_name=type/value/is_mandatory|param_name_2=type2/value2/is_mandatory2
// assumes none of the delimeters appears in the string values
std::string SerializeGameParameters(
    const GameParameters& game_params,
    const std::string& name_delimiter = kDefaultNameDelimiter,
    const std::string& parameter_delimeter = kDefaultParameterDelimiter);
GameParameters DeserializeGameParameters(
    const std::string& data,
    const std::string& name_delimiter = kDefaultNameDelimiter,
    const std::string& parameter_delimeter = kDefaultParameterDelimiter);
GameParameter DeserializeGameParameter(
    const std::string& data,
    const std::string& delimiter = kDefaultInternalDelimiter);

inline bool IsParameterSpecified(const GameParameters& table,
                                 const std::string& key) {
  return table.find(key) != table.end();
}

template <typename T>
T ParameterValue(const GameParameters& params, const std::string& key,
                 absl::optional<T> default_value = absl::nullopt) {
  auto iter = params.find(key);
  if (iter == params.end()) {
    if (!default_value.has_value()) {
      SpielFatalError(absl::StrCat("Cannot find parameter and no default "
                                   "value passed for key: ", key));
    }

    return *default_value;
  } else {
    return iter->second.value<T>();
  }
}

}  // namespace open_spiel

#endif  // OPEN_SPIEL_GAME_PARAMETERS_H_


text:
package com.github.dm.jrt.operator;

import com.github.dm.jrt.core.channel.Channel;
import com.github.dm.jrt.core.invocation.Invocation;
import com.github.dm.jrt.core.invocation.InvocationFactory;
import com.github.dm.jrt.core.invocation.TemplateInvocation;
import com.github.dm.jrt.core.util.ConstantConditions;
import com.github.dm.jrt.function.PredicateDecorator;

import org.jetbrains.annotations.NotNull;

import static com.github.dm.jrt.core.util.Reflection.asArgs;

/**
 * Factory of invocations verifying that any of the inputs satisfies a specific conditions.
 * <p>
 * Created by davide-maestroni on 05/02/2016.
 *
 * @param <IN> the input data type.
 */
class AnyMatchInvocationFactory<IN> extends InvocationFactory<IN, Boolean> {

  private final PredicateDecorator<? super IN> mFilterPredicate;

  /**
   * Constructor.
   *
   * @param filterPredicate the predicate defining the condition.
   */
  AnyMatchInvocationFactory(@NotNull final PredicateDecorator<? super IN> filterPredicate) {
    super(asArgs(ConstantConditions.notNull("predicate instance", filterPredicate)));
    mFilterPredicate = filterPredicate;
  }

  @NotNull
  @Override
  public Invocation<IN, Boolean> newInvocation() {
    return new AnyMatchInvocation<IN>(mFilterPredicate);
  }

  /**
   * Invocation verifying that any of the inputs satisfies a specific conditions.
   *
   * @param <IN> the input data type.
   */
  private static class AnyMatchInvocation<IN> extends TemplateInvocation<IN, Boolean> {

    private final PredicateDecorator<? super IN> mFilterPredicate;

    private boolean mIsMatch;

    /**
     * Constructor.
     *
     * @param filterPredicate the predicate defining the condition.
     */
    private AnyMatchInvocation(@NotNull final PredicateDecorator<? super IN> filterPredicate) {
      mFilterPredicate = filterPredicate;
    }

    @Override
    public void onComplete(@NotNull final Channel<Boolean, ?> result) {
      if (!mIsMatch) {
        result.pass(false);
      }
    }

    @Override
    public void onInput(final IN input, @NotNull final Channel<Boolean, ?> result) throws
        Exception {
      if (!mIsMatch && mFilterPredicate.test(input)) {
        mIsMatch = true;
        result.pass(true);
      }
    }

    @Override
    public void onRestart() {
      mIsMatch = false;
    }
  }
}


text:
package edu.softserve.zoo.advice;

import edu.softserve.zoo.dto.InvalidRequestDto;
import edu.softserve.zoo.validation.InvalidRequestProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * This class is used for handling exceptions related to invalid data provided by user.
 *
 * @author Andrii Abramov on 6/9/16.
 */
@ControllerAdvice
public class InvalidRequestAdvice {

    @Autowired
    private InvalidRequestProcessor<InvalidRequestDto> invalidRequestProcessor;

    /**
     * Handles the situation when user providel invalid request.
     * The trigger for validation is @{@link javax.validation.Valid} annotation.
     *
     * @param ex exception provided bt Spring
     * @return generated response with provided info
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public InvalidRequestDto handleInvalidRequest(MethodArgumentNotValidException ex) {
        return invalidRequestProcessor.processFieldErrors(ex.getBindingResult().getFieldErrors());
    }

}


text:
/*global describe, it, before */

var assert = require('assert'),
  should = require('should');

var servers = require('./helpers/server'),
  mqtt = require('..');

var KEY = __dirname + '/helpers/tls-key.pem';
var CERT = __dirname + '/helpers/tls-cert.pem';

var options = {
  keyPath: KEY,
  certPath: CERT,
  rejectUnauthorized : false
};

var PORT = (process.env.PORT || 1883) + 1; //port collides with other tests so +1

describe("SecureClient", function () {
  before(function () {
    this.server = servers.init_secure_server(PORT, KEY, CERT);
  });

  it("should connect", function (done) {
    var client = mqtt.createSecureClient(PORT, 'localhost', options);

    client.on('connect', function (packet) {
      done();
    });
    client.on('error', function (err) {
      should.not.exist(err);
      done();
    });

  });
});


text:
namespace poirot {

MinidumpProcessor::MinidumpProcessor(const base::FilePath& input_minidump)
    : input_minidump_(input_minidump), processed_(false) {
}

bool MinidumpProcessor::ProcessDump() {
  DCHECK(!input_minidump_.empty());
  DCHECK(!processed_);
  minidump::FileMinidump minidump;

  if (!minidump.Open(input_minidump_)) {
    LOG(ERROR) << "Unable to open the minidump.";
    return false;
  }

  // Get the Kasko stream from the minidump.
  minidump::Minidump::Stream stream =
      minidump.FindNextStream(nullptr, kasko::api::kProtobufStreamType);
  if (!stream.IsValid()) {
    LOG(ERROR) << "Unable to read the Kasko stream.";
    return false;
  }

  // Read the stream content and initialize the protobuf with it.
  std::string stream_content;
  if (!stream.ReadAndAdvanceBytes(stream.remaining_length(), &stream_content)) {
    LOG(ERROR) << "Unable to read the minidump bytes.";
    return false;
  }
  if (!protobuf_value_.ParseFromString(stream_content)) {
    LOG(ERROR) << "Unable to parse the protobuf from the Kasko stream.";
    return false;
  }
  processed_ = true;
  return true;
}

bool MinidumpProcessor::GenerateJsonOutput(FILE* file) {
  DCHECK_NE(static_cast<FILE*>(nullptr), file);
  DCHECK(processed_);

  std::string out_str;
  if (!crashdata::ToJson(true, &protobuf_value_, &out_str)) {
    LOG(ERROR) << "Unable to convert the protobuf to JSON.";
    return false;
  }
  ::fprintf(file, "%s", out_str.c_str());
  return true;
}

} // namespace poirot


text:
package org.apache.flink.streaming.api.checkpoint;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.FlinkException;

/**
 * Sources that implement this interface do not trigger checkpoints when receiving a trigger message
 * from the checkpoint coordinator, but when their input data/events indicate that a checkpoint
 * should be triggered.
 *
 *
Since sources cannot simply create a new checkpoint on their own, this mechanism always goes
 * together with a {@link WithMasterCheckpointHook hook on the master side}. In a typical setup, the
 * hook on the master tells the source system (for example the message queue) to prepare a
 * checkpoint. The exact point when the checkpoint is taken is then controlled by the event stream
 * received from the source, and triggered by the source function (implementing this interface) in
 * Flink when seeing the relevant events.
 *
 * @param <T> Type of the elements produced by the source function
 * @param <CD> The type of the data stored in the checkpoint by the master that triggers
 */
@PublicEvolving
public interface ExternallyInducedSource<T, CD>
        extends SourceFunction<T>, WithMasterCheckpointHook<CD> {

    /**
     * Sets the checkpoint trigger through which the source can trigger the checkpoint.
     *
     * @param checkpointTrigger The checkpoint trigger to set
     */
    void setCheckpointTrigger(CheckpointTrigger checkpointTrigger);

    // ------------------------------------------------------------------------

    /**
     * Through the {@code CheckpointTrigger}, the source function notifies the Flink source operator
     * when to trigger the checkpoint.
     */
    interface CheckpointTrigger {

        /**
         * Triggers a checkpoint. This method should be called by the source when it sees the event
         * that indicates that a checkpoint should be triggered.
         *
         *
When this method is called, the parallel operator instance in which the calling source
         * function runs will perform its checkpoint and insert the checkpoint barrier into the data
         * stream.
         *
         * @param checkpointId The ID that identifies the checkpoint.
         * @throws FlinkException Thrown when the checkpoint could not be triggered, for example
         *     because of an invalid state or errors when storing the checkpoint state.
         */
        void triggerCheckpoint(long checkpointId) throws FlinkException;
    }
}


text:
foam.CLASS({
  package: 'foam.box',
  name: 'BroadcastRegistry',
  extends: 'foam.box.BoxRegistryBox',

  requires: [
    'foam.box.Box',
    'foam.box.RoundRobinBox'
  ],
  exports: [ 'as registry' ],

  classes: [
    {
      name: 'Registration',

      documentation: `Mapping between registered names and boxes returned
          from registering with the delegates.`,

      properties: [
        {
          class: 'String',
          name: 'name',
          documentation: `Name under which registration was stored in
              BroadcastRegistry.`
        },
        {
          class: 'Array',
          of: 'String',
          name: 'delegateNames',
          documentation: `Name under which registration delegate services
              are registered.`
        },
        {
          class: 'FObjectProperty',
          of: 'foam.box.Box',
          name: 'registeredBox',
          documentation: `Box returned from BroadcastRegistry.register() SUPER()
              implementation.`
        }
      ]
    }
  ],

  properties: [
    {
      class: 'Array',
      of: 'foam.box.BoxRegistryBox',
      name: 'delegates',
      documentation: 'Delegates that recieve register()/unregister() calls.',
    },
    {
      class: 'FObjectProperty',
      of: 'foam.box.MultiDelegateBox',
      name: 'dispatchBoxPrototype',
      documentation: `Prototype that is clone()d to produce a box that
          encapsulates dispatch to services registered in "delegates".`,
      factory: function() { return this.RoundRobinBox.create(); }
    },
    {
      class: 'Array',
      // of: 'Registration',
      name: 'registrations_',
      documentation: `Array of Registration bindings used to coordinate
          unregister() among self and delegates.`
    }
  ],

  methods: [
    function register(name, service, box) {
      var delegates = this.delegates;
      var dispatchDelegates = new Array(delegates.length);
      var dispatchDelegateNames = new Array(delegates.length);
      for ( var i = 0; i < delegates.length; i++ ) {
        var delegateName = dispatchDelegateNames[i] = foam.uuid.randomGUID();
        dispatchDelegates[i] = delegates[i].register(delegateName, null, box);
      }
      var dispatchBox = this.dispatchBoxPrototype.clone(this);
      dispatchBox.delegates = dispatchDelegates;

      var ret = this.SUPER(name, service, dispatchBox);
      this.registrations_.push(this.Registration.create({
        name: name,
        delegateNames: dispatchDelegateNames,
        registeredBox: ret
      }));

      return ret;
    },
    function unregister(nameOrBox) {
      var registeredBox;
      var inputIsBox = this.Box.isInstance(nameOrBox);
      if ( inputIsBox ) {
        registeredBox = nameOrBox;
      } else {
        registeredBox = this.registry_[nameOrBox].exportBox;
        // When name is known, unregister it.
        this.SUPER(nameOrBox);
      }

      var registration;
      var registrations = this.registrations_;
      for ( var i = 0; i < registrations.length; i++ ) {
        if ( registrations[i].registeredBox !== registeredBox )
          continue;

        // When name was previously unknown, remove from registry_ now that
        // it is known.
        if ( inputIsBox ) delete this.registry_[registrations[i].name];

        registration = registrations[i];
        break;
      }

      foam.assert(registration,
                  'BroadcastRegistry expects to find registration');

      var delegates = this.delegates;
      for ( var i = 0; i < delegates.length; i++ ) {
        delegates[i].unregister(registration.delegateNames[i]);
      }
    }
  ]
});


text:
/**
 *
 * 日    期:12-5-31
 */
package com.appleframework.rest.impl;

import com.appleframework.rest.AbstractRestRequest;
import com.appleframework.rest.RestContext;
import com.appleframework.rest.ServiceMethodDefinition;
import com.appleframework.rest.ServiceMethodHandler;
import com.appleframework.rest.annotation.*;
import org.springframework.context.ApplicationContext;
import org.testng.annotations.Test;

import java.util.List;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;

/**
 * <pre>
 * 功能说明:
 * </pre>
 *
 * @author 陈雄华
 * @version 1.0
 */
public class DefaultRestContextTest {

	@Test
	public void testWithoutGroupService() {
		ApplicationContext context = mock(ApplicationContext.class);
		when(context.getBeanNamesForType(Object.class)).thenReturn(new String[] { "service1" });
		Class withoutGroupServiceClass = WithoutGroupService.class;
		when(context.getType("service1")).thenReturn(withoutGroupServiceClass);

		RestContext registryMethod = new DefaultRestContext(context);
		ServiceMethodHandler handler = registryMethod.getServiceMethodHandler("service.method1");
		ServiceMethodDefinition definition = handler.getServiceMethodDefinition();
		assertNotNull(definition);
		assertEquals(definition.getMethod(), "service.method1");
		assertEquals(definition.getMethodTitle(), "测试方法1");
		assertEquals(definition.getMethodGroup(), "GROUP1");
		assertEquals(definition.getMethodGroupTitle(), "分组1");

		assertEquals(definition.getTags(), new String[] { "TAG1", "TAG2" });
		assertEquals(definition.getTimeout(), 100);
	}

	@SuppressWarnings("unchecked")
	@Test
	public void testWithGroupService() {
		ApplicationContext context = mock(ApplicationContext.class);

		when(context.getBeanNamesForType(Object.class)).thenReturn(new String[] { "service1" });
		Class withGroupServiceClass = WithGroupService.class;
		when(context.getType("service1")).thenReturn(withGroupServiceClass);
		RestContext restContext = new DefaultRestContext(context);

		// method1:都在ServiceMethodGroup中定义,在ServiceMethod中直接采用
		ServiceMethodHandler handler = restContext.getServiceMethodHandler("service.method1");
		ServiceMethodDefinition definition = handler.getServiceMethodDefinition();
		assertNotNull(definition);
		assertEquals(definition.getMethod(), "service.method1");
		assertEquals(definition.getMethodTitle(), "测试方法1");
		assertEquals(definition.getMethodGroup(), "GROUP1");
		assertEquals(definition.getMethodGroupTitle(), "分组1");
		assertEquals(definition.getTags(), new String[] { "TAG1", "TAG2" });
		assertEquals(definition.getTimeout(), 100);

		// method2:在ServiceMethodGroup中定义,在ServiceMethod显式覆盖之
		ServiceMethodHandler handler2 = restContext.getServiceMethodHandler("service.method2");
		ServiceMethodDefinition definition2 = handler2.getServiceMethodDefinition();
		assertNotNull(definition2);
		assertEquals(definition2.getMethod(), "service.method2");
		assertEquals(definition2.getMethodTitle(), "测试方法2");
		assertEquals(definition2.getMethodGroup(), "GROUP2");
		assertEquals(definition2.getMethodGroupTitle(), "分组2");
		assertEquals(definition2.getTags(), new String[] { "TAG11", "TAG21" });
		assertEquals(definition2.getTimeout(), 200);
	}

	@Test
	public void testIngoreSignField() {
		ApplicationContext context = mock(ApplicationContext.class);

		when(context.getBeanNamesForType(Object.class)).thenReturn(new String[] { "method1" });
		Class serviceClass = IgnoreSignRestRequestService.class;
		when(context.getType("method1")).thenReturn(serviceClass);

		RestContext restContext = new DefaultRestContext(context);

		ServiceMethodHandler method1 = restContext.getServiceMethodHandler("method1");
		List<String> ignoreSignFieldNames = method1.getIgnoreSignFieldNames();
		assertNotNull(ignoreSignFieldNames);
		assertEquals(ignoreSignFieldNames.size(), 4);
		assertTrue(ignoreSignFieldNames.contains("field1"));
		assertTrue(ignoreSignFieldNames.contains("field3"));
		assertTrue(ignoreSignFieldNames.contains("sign"));
	}

	@ServiceMethodBean
	public class IgnoreSignRestRequestService {

		@ServiceMethod(method = "method1")
		public Object method1(FooRestRequest request) {
			return null;
		}
	}

	public class FooRestRequest extends AbstractRestRequest {

		private String field1;

		private String field2;

		private int field3;

		private int field4;

		public String getField1() {
			return field1;
		}

		public void setField1(String field1) {
			this.field1 = field1;
		}

		public String getField2() {
			return field2;
		}

		public void setField2(String field2) {
			this.field2 = field2;
		}

		public int getField3() {
			return field3;
		}

		public void setField3(int field3) {
			this.field3 = field3;
		}

		public int getField4() {
			return field4;
		}

		public void setField4(int field4) {
			this.field4 = field4;
		}
	}

	@ServiceMethodBean
	public class WithoutGroupService {

		@ServiceMethod(method = "service.method1", title = "测试方法1", group = "GROUP1", groupTitle = "分组1", tags = {
				"TAG1",
				"TAG2" }, timeout = 100)
		public Object service1() {
			return null;
		}
	}

	@ServiceMethodBean(group = "GROUP1", groupTitle = "分组1", tags = { "TAG1", "TAG2" }, timeout = 100)
	public class WithGroupService {

		@ServiceMethod(method = "service.method1", title = "测试方法1")
		public Object service1() {
			return null;
		}

		@ServiceMethod(method = "service.method2", title = "测试方法2", group = "GROUP2", groupTitle = "分组2", tags = {
				"TAG11",
				"TAG21" }, timeout = 200)
		public Object service2() {
			return null;
		}
	}

	@Test
	public void annotationTest() {
	}

	public static void main(String[] args) {
		System.out.println("中国人民!");
	}

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: pdbdata.h
//

// ===========================================================================

#ifndef PDBDATA_H_
#define PDBDATA_H_

#include "umisc.h"
#include "palclr.h"

struct SymMethodInfo;
struct SymLexicalScope;
struct SymVariable;
struct SymUsingNamespace;
struct SymConstant;
struct SequencePoint;
struct DocumentInfo;
struct MethodInfo;

extern "C" const GUID ILDB_VERSION_GUID_FSR;
extern "C" const GUID ILDB_VERSION_GUID;

#define ILDB_MINOR_VERSION_NUMBER 0
#define ILDB_SIGNATURE "_ildb_signature"
#define ILDB_SIGNATURE_SIZE (16)

typedef struct PDBInfo {

    // Entry point of the PE
    mdMethodDef         m_userEntryPoint;

    UINT32 m_CountOfMethods;
    UINT32 m_CountOfScopes;
    UINT32 m_CountOfVars;
    UINT32 m_CountOfUsing;
    UINT32 m_CountOfConstants;
    UINT32 m_CountOfDocuments;
    UINT32 m_CountOfSequencePoints;
    UINT32 m_CountOfBytes;
    UINT32 m_CountOfStringBytes;

public:
    PDBInfo()
    {
        memset(this, 0, sizeof(PDBInfo));
        // Make sure m_userEntryPoint initialized correctly
        _ASSERTE(mdTokenNil == 0);
    }

#if BIGENDIAN
    void ConvertEndianness() {
        m_userEntryPoint = VAL32(m_userEntryPoint);
        m_CountOfMethods = VAL32(m_CountOfMethods);
        m_CountOfScopes = VAL32(m_CountOfScopes);
        m_CountOfVars = VAL32(m_CountOfVars);
        m_CountOfUsing = VAL32(m_CountOfUsing);
        m_CountOfConstants = VAL32(m_CountOfConstants);
        m_CountOfSequencePoints = VAL32(m_CountOfSequencePoints);
        m_CountOfDocuments = VAL32(m_CountOfDocuments);
        m_CountOfBytes = VAL32(m_CountOfBytes);
        m_CountOfStringBytes = VAL32(m_CountOfStringBytes);
    }
#else
    void ConvertEndianness() {}
#endif

} PDBInfo;

// The signature, Guid version + PDBInfo data
#define ILDB_HEADER_SIZE (ILDB_SIGNATURE_SIZE + sizeof(GUID) + sizeof(PDBInfo) )

typedef struct PDBDataPointers
{
    SymMethodInfo * m_pMethods;   // Method information
    SymLexicalScope *m_pScopes;   // Scopes
    SymVariable *m_pVars;         // Local Variables
    SymUsingNamespace *m_pUsings; // list of using/imports
    SymConstant *m_pConstants;    // Constants
    DocumentInfo *m_pDocuments;   // Documents
    SequencePoint *m_pSequencePoints;  // Sequence Points
    // Array of various bytes (variable signature, etc)
    BYTE *m_pBytes;
    // Strings
    BYTE *m_pStringsBytes;
} PDBDataPointers;

#endif /* PDBDATA_H_ */