text:
.. _api_geosubmit2:
.. _api_geosubmit_latest:

==================================
Geosubmit Version 2: /v2/geosubmit
==================================

**Purpose:** Submit data about nearby Bluetooth beacons, cell or WiFi networks.

.. contents::
   :local:

Request
=======

Geosubmit requests are submitted using an HTTP POST request to the URL::

    https://location.services.mozilla.com/v2/geosubmit?key=<API_KEY>

There is an earlier :ref:`api_geosubmit` v1 API, with a slightly different and
less extensive field list.

Geosubmit requests are submitted using an HTTP POST request with a JSON body.

Here is an example body:

.. code-block:: javascript

    {"items": [{
        "timestamp": 1405602028568,
        "position": {
            "latitude": -22.7539192,
            "longitude": -43.4371081,
            "accuracy": 10.0,
            "age": 1000,
            "altitude": 100.0,
            "altitudeAccuracy": 50.0,
            "heading": 45.0,
            "pressure": 1013.25,
            "speed": 3.6,
            "source": "gps"
        },
        "bluetoothBeacons": [
            {
                "macAddress": "ff:23:45:67:89:ab",
                "age": 2000,
                "name": "beacon",
                "signalStrength": -110
            }
        ],
        "cellTowers": [
            {
                "radioType": "lte",
                "mobileCountryCode": 208,
                "mobileNetworkCode": 1,
                "locationAreaCode": 2,
                "cellId": 12345,
                "age": 3000,
                "asu": 31,
                "primaryScramblingCode": 5,
                "serving": 1,
                "signalStrength": -51,
                "timingAdvance": 1
            }
        ],
        "wifiAccessPoints": [
            {
                "macAddress": "01:23:45:67:89:ab",
                "age": 5000,
                "channel": 6,
                "frequency": 2437,
                "radioType": "802.11n",
                "signalToNoiseRatio": 13,
                "signalStrength": -77
            },
            {
                "macAddress": "23:45:67:89:ab:cd"
            }
        ]
    }]}

Field Definition
================

Requests always need to contain a batch of :term:`reports`. Each :term:`report`
must contain at least one entry in the ``bluetoothBeacons`` or ``cellTowers``
array or two entries in the ``wifiAccessPoints`` array.

Almost all of the fields are optional. For Bluetooth and WiFi records the
``macAddress`` field is required.

Global Fields
-------------

timestamp
    The time of observation of the data, measured in milliseconds since the
    UNIX epoch. Can be omitted if the observation time is very recent. The age
    values in each section are relative to this timestamp.

Position Fields
---------------

The position block contains information about where and when the data was
observed.

latitude
    The latitude of the observation (WSG 84).

longitude
    The longitude of the observation (WSG 84).

accuracy
    The accuracy of the observed position in meters.

altitude
    The altitude at which the data was observed in meters above sea-level.

altitudeAccuracy
    The accuracy of the altitude estimate in meters.

age
    The age of the position data (in milliseconds).

heading
    The heading field denotes the direction of travel of the device and is
    specified in degrees, where 0° ≤ heading < 360°, counting clockwise
    relative to the true north.

pressure
    The air pressure in hPa (millibar).

speed
    The speed field denotes the magnitude of the horizontal component of
    the device's current velocity and is specified in meters per second.

source
    The source of the position information. If the field is omitted, "gps"
    is assumed. The term ``gps`` is used to cover all types of satellite based
    positioning systems including Galileo and Glonass. Other possible values
    are ``manual`` for a position entered manually into the system and
    ``fused`` for a position obtained from a combination of other sensors or
    outside service queries.

Bluetooth Beacon Fields
-----------------------

macAddress
    The address of the Bluetooth Low Energy (BLE) beacon.

name
    The name of the BLE beacon.

age
    The number of milliseconds since this BLE beacon was last seen.

signalStrength
    The measured signal strength of the BLE beacon in dBm.

Cell Tower Fields
-----------------

radioType
    The type of radio network; one of ``gsm``, ``wcdma`` or ``lte``.

mobileCountryCode
    The mobile country code.

mobileNetworkCode
    The mobile network code.

locationAreaCode
    The location area code for GSM and WCDMA networks. The tracking area
    code for LTE networks.

cellId
    The cell id or cell identity.

age
    The number of milliseconds since this cell was last seen.

asu
    The arbitrary strength unit indicating the signal strength if a
    direct signal strength reading is not available.

primaryScramblingCode
    The primary scrambling code for WCDMA and physical cell id for LTE.

serving
    A value of ``1`` indicates this as the serving cell, a value of ``0``
    indicates a neighboring cell.

signalStrength
    The signal strength for this cell network, either the RSSI or RSCP.

timingAdvance
    The timing advance value for this cell tower when available.

Wifi Access Point Fields
------------------------

macAddress
    The BSSID of the Wifi network.

    Hidden Wifi networks must not be collected.

radioType
    The Wifi radio type; one of ``802.11a``, ``802.11b``, ``802.11g``,
    ``802.11n``, ``802.11ac``.

age
    The number of milliseconds since this Wifi network was detected.

channel
    The channel is a number specified by the IEEE which represents a
    small band of frequencies.

frequency
    The frequency in MHz of the channel over which the client is
    communicating with the access point.

signalStrength
    The received signal strength (RSSI) in dBm.

signalToNoiseRatio
    The current signal to noise ratio measured in dB.

ssid
    The SSID of the Wifi network.

    Wifi networks with a SSID ending in ``_nomap`` must not be collected.

Response
========

Successful requests return a HTTP 200 response with a body of an empty
JSON object.


text:
package com.cc.mobilesafe.Activity;

import java.lang.annotation.Annotation;

import com.cc.mobilesafe.R;
import com.cc.mobilesafe.R.id;
import com.cc.mobilesafe.R.layout;
import com.cc.mobilesafe.R.menu;
import com.cc.mobilesafe.Utils.ConstantValue;
import com.cc.mobilesafe.Utils.SpUtils;
import com.cc.mobilesafe.Utils.ToastUtil;
import com.lidroid.xutils.view.annotation.event.OnClick;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class Setup3Activity extends BaseSetupActivity {

	private Context context;
	private EditText et_safenum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup3);
		this.context = this;

		initUI();

	}

	/**
	 * 初始化ui布局
	 */
	private void initUI() {
		// TODO 自动生成的方法存根
		et_safenum = (EditText) findViewById(R.id.et_safenum);
		String temp = SpUtils.getString(context, ConstantValue.SAFE_CONTACT_NUM, "");
		if (!TextUtils.isEmpty(temp)) {
			et_safenum.setText(temp);
		}

		findViewById(R.id.btn_selectcontact).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根

				Intent intent = new Intent(context, ContactListActivity.class);
				startActivityForResult(intent, 0);

			}
		});

		findViewById(R.id.btn_SetupNext).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				showNextPage();
			}
		});

		findViewById(R.id.btn_SetupBack).setOnClickListener( new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				showPrePage();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 返回到当前页面后处理接收的结果
		switch (requestCode) {
		case 0:
			if (data != null) {
				String phoneNum = data.getStringExtra("phoneNum");
				phoneNum = phoneNum.replace("-", "").replace(" ", "").trim();
				et_safenum.setText(phoneNum);
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	protected void showPrePage() {

		startActivity(new Intent(context, Setup2Activity.class));
		overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_in_out_anim);
		finish();
	}

	@Override
	protected void showNextPage() {

		String num = et_safenum.getText().toString().trim();
		if (!TextUtils.isEmpty(num)) {
			SpUtils.putString(context, ConstantValue.SAFE_CONTACT_NUM, num);
			startActivity(new Intent(context, Setup4Activity.class));
			overridePendingTransition(R.anim.next_in_anim, R.anim.next_in_out_anim);
			finish();
		}else{
			ToastUtil.show(context, "请输入安全号码");
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
extern crate html5ever;
extern crate html5ever_dom_sink;
extern crate rand;
extern crate tendril;

use std::str::FromStr;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;

use html5ever::Attribute;
use html5ever::tree_builder::interface::TreeSink;
use html5ever_dom_sink::common::NodeEnum;
use html5ever_dom_sink::rcdom::Handle;
use html5ever_dom_sink::rcdom::RcDom;
use regex::Captures;
use regex::Regex;

use wiki::Wiki;

use ::START_MARKER;
use ::END_MARKER;

/// Represents, and owns all behavior related to, the contents of the HTML page shown to the
/// user. This includes fetching the rendered article from Wikipedia, replacing its contents with
/// the rendered wikitext, and processing/removing merge markers.
///
/// The API to this struct comprises two methods: Page::new() constructs a new Page. It should be
/// called early, so the Page can start fetching article HTML from Wikipedia.
/// Page:replace_body_and_remove_merge_markers() processes the merge markers in the rendered
/// wikitext and puts the header and footer around it.
pub struct Page {
    /// The string used as a placeholder for the article body in the page skeleton.
    placeholder: String,
    /// The Receiver that will receive the page skeleton when it's been fetched and processed.
    page_skeleton_receiver: Receiver<Result<String, String>>,
}

impl Page {
    /// Creates a new Page representing the article at `title`. This kicks off a background thread
    /// that fetches the current article HTML from Wikipedia. Because of that, it should be called
    /// as early as possible (as soon as the title being served is known), so that the page fetch
    /// stays off the critical path for page load.
    pub fn new(title: &str, wiki: Wiki) -> Page {
        let placeholder = format!("WMW_PLACEHOLDER_{}", rand::random::<u64>());
        let page_skeleton_receiver =
            Page::spawn_page_skeleton_fetch_thread(title, placeholder.clone(), wiki);
        Page {
            placeholder: placeholder,
            page_skeleton_receiver: page_skeleton_receiver,
        }
    }

    /// This finishes the HTML processing - it replaces the merge markers in `article_body` with
    /// HTML tags, and inserts the resulting HTML into the page skeleton.
    pub fn replace_body_and_remove_merge_markers(&self, article_body: String)
                                                 -> Result<String, String> {
        match self.page_skeleton_receiver.recv() {
            Ok(Ok(page_skeleton)) => {
                let finished_article_body = process_merge_markers(article_body);
                Ok(page_skeleton.replace(&self.placeholder, &finished_article_body))
            },
            Ok(Err(msg))=> Err(msg),
            Err(err) => Err(format!("error: {}", err)),
        }
    }

    fn spawn_page_skeleton_fetch_thread(title: &str, placeholder: String, wiki: Wiki)
                                  -> Receiver<Result<String, String>> {
        let (page_skeleton_sender, page_skeleton_receiver) = channel::<Result<String, String>>();
        let title = title.to_owned().clone();
        thread::Builder::new().name(format!("fetch-skeleton-{}", title)).spawn(move|| {
            page_skeleton_sender.send(
                match wiki.get_current_page_content(&title) {
                    Ok(content) =>
                        replace_node_with_placeholder(&content, "mw-content-text", &placeholder),
                    Err(msg) => Err(msg),
                }).unwrap();
        });
        page_skeleton_receiver
    }
}

fn replace_node_with_placeholder(original_html: &str, div_id: &str, placeholder: &str)
    -> Result<String, String> {
    let html = tendril::StrTendril::from_str(original_html).unwrap();
    let mut dom: RcDom = html5ever::parse(html5ever::one_input(html), Default::default());

    let handle = try!(find_node_by_id(&dom.get_document(), div_id));
    let child_handles =
        (&handle.borrow().children).into_iter().map(|child| child.clone()).collect::<Vec<_>>();
    for child_handle in child_handles {
        dom.remove_from_parent(child_handle);
    }
    dom.append(handle,
               html5ever::tree_builder::interface::NodeOrText::AppendText(
                   tendril::StrTendril::from_str(placeholder).unwrap()));
    let mut serialized: Vec<u8> = vec![];
    try_display!(
        html5ever::serialize::serialize(&mut serialized, &dom.document, Default::default()),
        "Failed to serialize modified HTML");
    Ok(try_display!(String::from_utf8(serialized),
                    "Error converting serialized HTML to UTF-8 string"))
}

fn find_node_by_id(handle: &Handle, id: &str) -> Result<Handle, String> {
    fn has_matching_id(attributes: &Vec<Attribute>, id: &str) -> bool {
        return attributes.into_iter().any(
            |attribute| attribute.name.local.as_slice() == "id" &&
                format!("{}", attribute.value) == id);
    }

    let node = handle.borrow();
    match node.node {
        NodeEnum::Element(_, ref attributes) if has_matching_id(attributes, id) => Ok(handle.clone()),
        _ => (&node.children).into_iter()
            .map(|child| find_node_by_id(child, id))
            .filter(|result| result.is_ok())
            .map(|result| result.unwrap())
            .next().ok_or(format!("No node with ID {} found", id)),
    }
}

/// Removes merge markers that are inside HTML tags, and replaces the others with  tags.
fn process_merge_markers(html: String) -> String {
    let start_regex = Regex::new(&format!("{}([0-9]+){}", START_MARKER, START_MARKER)).unwrap();
    let end_regex = Regex::new(&format!("{}[0-9]+{}", END_MARKER, END_MARKER)).unwrap();

    let html = remove_merge_markers(html);
    let html = start_regex.replace_all(
        &html, |captures: &Captures| format!("",
                                             captures.at(1).unwrap()));
    end_regex.replace_all(&html, "")
}

fn remove_merge_markers(html: String) -> String {
    // Finds markers where the end, but not the start, is inside a tag.
    let regex1 = Regex::new(&format!(
        r"{}[0-9]+{}([^{}]*?)<([^>]*?){}[0-9]+{}([^>]*?)>",
        START_MARKER, START_MARKER, END_MARKER, END_MARKER, END_MARKER)).unwrap();
    // Finds markers where the start, but not the end, is inside a tag.
    let regex2 = Regex::new(&format!(
        r"<([^>]*?){}[0-9]+{}([^>]*?)>([^{}]*?){}[0-9]+{}",
        START_MARKER, START_MARKER, END_MARKER, END_MARKER, END_MARKER)).unwrap();
    // Finds markers where both the start and end are inside tags.
    let regex3 = Regex::new(&format!(
        r"<([^>]*?){}[0-9]+{}([^>]*?)>([^{}{}]*?)<([^>]*?){}[0-9]+{}([^>]*?)>",
        START_MARKER, START_MARKER, START_MARKER, END_MARKER, END_MARKER, END_MARKER)).unwrap();
    let html = regex1.replace_all(
        &html, |captures: &Captures|
        format!("{}<{}{}>", captures.at(1).unwrap(), captures.at(2).unwrap(),
                captures.at(3).unwrap()));
    let html = regex2.replace_all(
        &html, |captures: &Captures|
        format!("<{}{}>{}", captures.at(1).unwrap(), captures.at(2).unwrap(),
                captures.at(3).unwrap()));
    regex3.replace_all(
        &html, |captures: &Captures|
        format!("<{}{}>{}<{}{}>", captures.at(1).unwrap(), captures.at(2).unwrap(),
                captures.at(3).unwrap(), captures.at(4).unwrap(), captures.at(5).unwrap()))
}

#[cfg(test)]
mod tests {
    use super::{remove_merge_markers, replace_node_with_placeholder};
    use ::START_MARKER;
    use ::END_MARKER;

    fn test_process_merge_markers() {
        let html = format!(
            "{}456{}{}456{}{}123{}t",
            START_MARKER, START_MARKER, END_MARKER, END_MARKER,
            START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        let expected_regex =
            regex!("]*>");
        assert!(expected_regex.is_match(&html));
    }

    #[test]
    fn test_remove_merge_markers_keep() {
        let html = format!("{}456{}{}456{}",
                           START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        assert_eq!(html.clone(), remove_merge_markers(html));
    }

    #[test]
    fn test_remove_merge_markers_keep_one_remove_one() {
        let html = format!(
            "{}234{}text{}234{}{}567{}",
            START_MARKER, START_MARKER, END_MARKER, END_MARKER, START_MARKER, START_MARKER,
            END_MARKER, END_MARKER);
        let expected = format!(
            "{}234{}text{}234{}",
            START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        assert_eq!(expected, remove_merge_markers(html));
    }

    #[test]
    fn test_remove_merge_markers_end_inside_tag() {
        let html = format!("{}123{}",
                           START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        let expected = "";
        assert_eq!(expected, remove_merge_markers(html));
    }

    #[test]
    fn test_remove_merge_markers_start_inside_tag() {
        let html = format!("{}123{}",
                           START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        let expected = "";
        assert_eq!(expected, remove_merge_markers(html));
    }

    #[test]
    fn test_remove_merge_markers_both_inside_tag() {
        let html = format!("text",
                           START_MARKER, START_MARKER, END_MARKER, END_MARKER);
        let expected = "text";
        assert_eq!(expected, remove_merge_markers(html));
    }

    #[test]
    fn test_replace_html_content() {
        let original_html = "

original text

Other text

";
        let expected_html = "

replaced text

Other text

";
        let processed_html = replace_node_with_placeholder(original_html, "mw-content-text", "replaced text").unwrap();
        assert_eq!(expected_html, processed_html);
    }
}


text:
**Namespace:** [OfficeDevPnP.Core.Entities](OfficeDevPnP.Core.Entities.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public VariationLabelEntity()
```
## See also
- [VariationLabelEntity](OfficeDevPnP.Core.Entities.VariationLabelEntity.md)
- [OfficeDevPnP.Core.Entities](OfficeDevPnP.Core.Entities.md)


text:
/**
 * @author   Fabrice Sommavilla <fs@physalix.com>
 * @company  Physalix
 * @version  0.1
 * @date     22/01/2017
 */

"use strict";

import React, {Component, PropTypes} from 'react';
import Helmet from 'react-helmet';
import Geosuggest from 'react-bootstrap-geosuggest';
import auth from '../utils/auth';
var config = require('config');
var Recaptcha = require('react-recaptcha');
import {
    FormControl,
    FormGroup,
    Button,
    Radio
} from 'react-bootstrap';

export default class Signup extends Component {

    constructor(props) {
        super(props);
        this.handlePasswordInput = this.handlePasswordInput.bind(this);
        this.onSuggestSelect = this.onSuggestSelect.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.verifyCaptcha = this.verifyCaptcha.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
        this.state = {
            gender: '',
            type: '',
            message: '',
            email: '',
            username: '',
            firstname: '',
            lastname: '',
            password: '',
            confirmPassword: '',
            city: null,
            longitude: null,
            latitude: null,
            placeId: null,
            recaptcha: false
        };
    }

    handleChange(e) {
        this.state.hasChanged = true;
        this.state.message = "";
        this.renderMessage();
        this.state[e.target.name] = e.target.value;
        this.forceUpdate();
    }

    handlePasswordInput(e) {
        if (this.state.password && e.target.value !== this.state.password) {
            this.setState({type: 'danger', message: 'Passwords must match!'});
        }
        this.state.message = "";
        this.renderMessage();
        this.setState({confirmPassword: e.target.value});
    }

    onSuggestSelect(suggest) {
        if (suggest) {
            this.setState({
                city: suggest.label,
                latitude: suggest.location.lat,
                longitude: suggest.location.lng,
                placeId: suggest.placeId
            });
        }
    }

    signin(token) {
        fetch(`http://${config.api.host}:${config.api.port}/users`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'x-api-key': token
            },
            body: JSON.stringify({
                gender: this.state.gender,
                email: this.state.email,
                username: this.state.username,
                password: this.state.password,
                firstname: this.state.firstname,
                lastname: this.state.lastname,
                group: "user",
                location: {
                    place: this.state.city,
                    placeId: this.state.placeId,
                    coords: {
                        "type": "Point",
                        "coordinates": [this.state.longitude, this.state.latitude]
                    }
                }
            })
        }).then(function (res) {
            switch (res.status) {
                case 200:
                    this.setState({type: 'success', message: 'Resgistration successful'});
                    window.location.replace("/signup-success");
                    break;
                case 409:
                    this.setState({type: 'warning', message: 'Duplicate email'});
                    break;
                case 500:
                    this.setState({type: 'error', message: 'Error while registration'});
                    break;
            }
        }.bind(this));
    }

    onSubmit(e) {
        e.preventDefault();
        var canProceed = this.state.email && this.state.password && this.state.confirmPassword && this.state.username;

        if (!this.state.recaptcha) {
            this.setState({type: 'warning', message: 'The captcha is not valid'});
        }

        if (this.state.recaptcha && canProceed) {
            auth.login(
                config.api.user,
                config.api.password,
                function (token, res) {
                    if (res.ok && token) {
                        this.setState({type: 'info', message: 'Saving...'});
                        this.signin(token);
                    }
                }.bind(this),
                false
            );
        }
    }

    renderMessage() {
        if (this.state.message.length > 0) {
            return (
                <div className={`alert alert-${this.state.type}`} role="alert">{this.state.message}

            );
        }
        return "";
    }

    verifyCaptcha() {
        this.setState({recaptcha: true, type: '', message: ''});
    }

    onloadCaptcha() {
    }

    render() {
        return (

                <Helmet title="Sign Up"/>
                <form id="signupForm" name="signupForm" onSubmit={this.onSubmit}>

                        <FormGroup controlId="formGender">
                            <Radio inline
                                   name="gender"
                                   value="f"
                                   required
                                   onChange={this.handleChange}
                                   checked={this.state.gender === 'f'}>Female</Radio>
                            <Radio inline
                                   name="gender"
                                   value="m"
                                   required
                                   onChange={this.handleChange}
                                   checked={this.state.gender === 'm'}>Male</Radio>
                            <FormControl.Feedback />
                        </FormGroup>
                        <FormGroup controlId="formEmail">
                            <FormControl
                                type="email"
                                name="email"
                                ref="email"
                                title="Email is not valid"
                                value={this.state.email || ""}
                                required={true}
                                placeholder="Email address"
                                onChange={this.handleChange}
                            />
                        </FormGroup>
                        <FormGroup controlId="formUsername">
                            <FormControl
                                type="username"
                                name="username"
                                ref="username"
                                value={this.state.username || ""}
                                required={true}
                                title="Username is not valid"
                                placeholder="Username"
                                maxLength="100"
                                onChange={this.handleChange}
                            />
                        </FormGroup>
                        <FormGroup controlId="formPassword">
                            <FormControl
                                type="password"
                                name="password"
                                ref="password"
                                value={this.state.password || ""}
                                required={true}
                                title="Password is not valid"
                                placeholder="Password"
                                maxLength="100"
                                onChange={this.handleChange}
                            />
                        </FormGroup>
                        <FormGroup controlId="formConfirmPassword">
                            <FormControl
                                type="password"
                                name="confirmPassword"
                                ref="confirmPassword"
                                value={this.state.confirmPassword || ""}
                                required={true}
                                title="Password is not valid"
                                placeholder="Confirm password"
                                maxLength="100"
                                onChange={this.handlePasswordInput}
                            />
                        </FormGroup>
                        <FormGroup controlId="formFirstname">
                            <FormControl
                                type="text"
                                name="firstname"
                                ref="firstname"
                                value={this.state.firstname || ""}
                                required={true}
                                title="Firstname is not valid"
                                placeholder="Firstname"
                                maxLength="100"
                                onChange={this.handleChange}
                            />
                        </FormGroup>
                        <FormGroup controlId="formLastname">
                            <FormControl
                                type="text"
                                name="lastname"
                                ref="lastname"
                                value={this.state.lastname || ""}
                                required={true}
                                title="Lastname is not valid"
                                placeholder="Lastname"
                                maxLength="100"
                                onChange={this.handleChange}
                            />
                        </FormGroup>

                            <Geosuggest placeholder="City" required types={['(cities)']} onSuggestSelect={this.onSuggestSelect}/>

                        <Recaptcha
                            sitekey={config.recaptchaId}
                            render="explicit"
                            verifyCallback={this.verifyCaptcha}
                            onloadCallback={this.onloadCaptcha}/>

                        { this.renderMessage() }

                        <Button type="submit" className="signup-button btn btn-primary">
                            {this.state.isSaving ? 'Saving...' : 'Create Account'}
                        </Button>

                </form>

        );
    }
}


text:
/* -----------------------------------------------------------------------------
 *
 * (c) The GHC Team 1998-2006
 *
 * Tidying up a thread when it stops running
 *
 * ---------------------------------------------------------------------------*/

// #include "PosixSource.h"
#include "Rts.h"

#include "ThreadPaused.h"
#include "sm/Storage.h"
#include "Updates.h"
#include "RaiseAsync.h"
#include "Trace.h"
#include "Threads.h"

#include <string.h> // for memmove()

/* -----------------------------------------------------------------------------
 * Stack squeezing
 *
 * Code largely pinched from old RTS, then hacked to bits.  We also do
 * lazy black holing here.
 *
 * -------------------------------------------------------------------------- */

struct stack_gap { StgWord gap_size; struct stack_gap *next_gap; };

static struct stack_gap *
updateAdjacentFrames (Capability *cap, StgTSO *tso, StgUpdateFrame *upd,
                      uint32_t count, struct stack_gap *next)
{
    StgClosure *updatee;
    struct stack_gap *gap;
    uint32_t i;

    // The first one (highest address) is the frame we take the
    // "master" updatee from; all the others will be made indirections
    // to this one.  It is essential that we do it this way around: we
    // used to make the lowest-addressed frame the "master" frame and
    // shuffle it down, but a bad case cropped up (#5505) where this
    // happened repeatedly, generating a chain of indirections which
    // the GC repeatedly traversed (indirection chains longer than one
    // are not supposed to happen).  So now after identifying a block
    // of adjacent update frames we walk downwards again updating them
    // all to point to the highest one, before squeezing out all but
    // the highest one.
    updatee = upd->updatee;
    count--;

    upd--;
    gap = (struct stack_gap*)upd;

    for (i = count; i > 0; i--, upd--) {
        /*
         * Check two things: that the two update frames
         * don't point to the same object, and that the
         * updatee_bypass isn't already an indirection.
         * Both of these cases only happen when we're in a
         * block hole-style loop (and there are multiple
         * update frames on the stack pointing to the same
         * closure), but they can both screw us up if we
         * don't check.
         */
        if (upd->updatee != updatee && !closure_IND(upd->updatee)) {
            updateThunk(cap, tso, upd->updatee, updatee);
        }
    }

    gap->gap_size = count * sizeofW(StgUpdateFrame);
    gap->next_gap = next;

    return gap;
}

static void
stackSqueeze(Capability *cap, StgTSO *tso, StgPtr bottom)
{
    StgPtr frame;
    uint32_t adjacent_update_frames;
    struct stack_gap *gap;

    // Stage 1:
    //    Traverse the stack upwards, replacing adjacent update frames
    //    with a single update frame and a "stack gap".  A stack gap
    //    contains two values: the size of the gap, and the distance
    //    to the next gap (or the stack top).

    frame = tso->stackobj->sp;

    ASSERT(frame < bottom);

    adjacent_update_frames = 0;
    gap = (struct stack_gap *) (frame - sizeofW(StgUpdateFrame));

    while (frame <= bottom)
    {
        switch (get_ret_itbl((StgClosure *)frame)->i.type) {

        case UPDATE_FRAME:
        {
            if (adjacent_update_frames > 0) {
                TICK_UPD_SQUEEZED();
            }
            adjacent_update_frames++;

            frame += sizeofW(StgUpdateFrame);
            continue;
        }

        default:
            // we're not in a gap... check whether this is the end of a gap
            // (an update frame can't be the end of a gap).
            if (adjacent_update_frames > 1) {
                gap = updateAdjacentFrames(cap, tso,
                                           (StgUpdateFrame*)(frame - sizeofW(StgUpdateFrame)),
                                           adjacent_update_frames, gap);
            }
            adjacent_update_frames = 0;

            frame += stack_frame_sizeW((StgClosure *)frame);
            continue;
        }
    }

    if (adjacent_update_frames > 1) {
        gap = updateAdjacentFrames(cap, tso,
                                   (StgUpdateFrame*)(frame - sizeofW(StgUpdateFrame)),
                                   adjacent_update_frames, gap);
    }

    // Now we have a stack with gap-structs in it, and we have to walk down
    // shoving the stack up to fill in the gaps.  A diagram might
    // help:
    //
    //    +| ********* |
    //     | ********* | <- sp
    //     |           |
    //     |           | <- gap_start
    //     | ......... |                |
    //     | stack_gap | <- gap         | chunk_size
    //     | ......... |                |
    //     | ......... | <- gap_end     v
    //     | ********* |
    //     | ********* |
    //     | ********* |
    //    -| ********* |
    //
    // 'sp'  points the the current top-of-stack
    // 'gap' points to the stack_gap structure inside the gap
    // *****   indicates real stack data
    // .....   indicates gap
    // <empty> indicates unused
    //
    {
        StgWord8 *sp;
        StgWord8 *gap_start, *next_gap_start, *gap_end;
        uint32_t chunk_size;

        next_gap_start = (StgWord8*)gap + sizeof(StgUpdateFrame);
        sp = next_gap_start;

        while ((StgPtr)gap > tso->stackobj->sp) {

            // we're working in *bytes* now...
            gap_start = next_gap_start;
            gap_end = gap_start - gap->gap_size * sizeof(W_);

            gap = gap->next_gap;
            next_gap_start = (StgWord8*)gap + sizeof(StgUpdateFrame);

            chunk_size = gap_end - next_gap_start;
            sp -= chunk_size;
            memmove(sp, next_gap_start, chunk_size);
        }

        tso->stackobj->sp = (StgPtr)sp;
    }
}

/* -----------------------------------------------------------------------------
 * Pausing a thread
 *
 * We have to prepare for GC - this means doing lazy black holing
 * here.  We also take the opportunity to do stack squeezing if it's
 * turned on.
 * -------------------------------------------------------------------------- */
void
threadPaused(Capability *cap, StgTSO *tso)
{
    StgClosure *frame;
    const StgRetInfoTable *info;
    const StgInfoTable *bh_info;
    const StgInfoTable *cur_bh_info USED_IF_THREADS;
    StgClosure *bh;
    StgPtr stack_end;
    uint32_t words_to_squeeze = 0;
    uint32_t weight           = 0;
    uint32_t weight_pending   = 0;
    bool prev_was_update_frame = false;
    StgWord heuristic_says_squeeze;

    // Check to see whether we have threads waiting to raise
    // exceptions, and we're not blocking exceptions, or are blocked
    // interruptibly.  This is important; if a thread is running with
    // TSO_BLOCKEX and becomes blocked interruptibly, this is the only
    // place we ensure that the blocked_exceptions get a chance.
    maybePerformBlockedException (cap, tso);
    if (tso->what_next == ThreadKilled) { return; }

    // NB. Updatable thunks *must* be blackholed, either by eager blackholing or
    // lazy blackholing.  See Note [upd-black-hole] in sm/Scav.c.

    stack_end = tso->stackobj->stack + tso->stackobj->stack_size;

    frame = (StgClosure *)tso->stackobj->sp;

    while ((P_)frame < stack_end) {
        info = get_ret_itbl(frame);

        switch (info->i.type) {

        case UPDATE_FRAME:

            // If we've already marked this frame, then stop here.
            if (frame->header.info == (StgInfoTable *)&stg_marked_upd_frame_info) {
                if (prev_was_update_frame) {
                    words_to_squeeze += sizeofW(StgUpdateFrame);
                    weight += weight_pending;
                    weight_pending = 0;
                }
                goto end;
            }

            SET_INFO(frame, (StgInfoTable *)&stg_marked_upd_frame_info);

            bh = ((StgUpdateFrame *)frame)->updatee;
            bh_info = bh->header.info;

#ifdef THREADED_RTS
        retry:
#endif
            // Note [suspend duplicate work]
            //
            // If the info table is a WHITEHOLE or a BLACKHOLE, then
            // another thread has claimed it (via the SET_INFO()
            // below), or is in the process of doing so.  In that case
            // we want to suspend the work that the current thread has
            // done on this thunk and wait until the other thread has
            // finished.
            //
            // If eager blackholing is taking place, it could be the
            // case that the blackhole points to the current
            // TSO. e.g.:
            //
            //    this thread                   other thread
            //    --------------------------------------------------------
            //                                  c->indirectee = other_tso;
            //                                  c->header.info = EAGER_BH
            //                                  threadPaused():
            //                                    c->header.info = WHITEHOLE
            //                                    c->indirectee = other_tso
            //    c->indirectee = this_tso;
            //    c->header.info = EAGER_BH
            //                                    c->header.info = BLACKHOLE
            //    threadPaused()
            //    *** c->header.info is now BLACKHOLE,
            //        c->indirectee  points to this_tso
            //
            // So in this case do *not* suspend the work of the
            // current thread, because the current thread will become
            // deadlocked on itself.  See #5226 for an instance of
            // this bug.
            //
            if ((bh_info == &stg_WHITEHOLE_info ||
                 bh_info == &stg_BLACKHOLE_info)
                &&
                ((StgInd*)bh)->indirectee != (StgClosure*)tso)
            {
                debugTrace(DEBUG_squeeze,
                           "suspending duplicate work: %ld words of stack",
                           (long)((StgPtr)frame - tso->stackobj->sp));

                // If this closure is already an indirection, then
                // suspend the computation up to this point.
                // NB. check raiseAsync() to see what happens when
                // we're in a loop (#2783).
                suspendComputation(cap,tso,(StgUpdateFrame*)frame);

                // Now drop the update frame, and arrange to return
                // the value to the frame underneath:
                tso->stackobj->sp = (StgPtr)frame + sizeofW(StgUpdateFrame) - 2;
                tso->stackobj->sp[1] = (StgWord)bh;
                ASSERT(bh->header.info != &stg_TSO_info);
                tso->stackobj->sp[0] = (W_)&stg_enter_info;

                // And continue with threadPaused; there might be
                // yet more computation to suspend.
                frame = (StgClosure *)(tso->stackobj->sp + 2);
                prev_was_update_frame = false;
                continue;
            }

            // zero out the slop so that the sanity checker can tell
            // where the next closure is.
            OVERWRITING_CLOSURE(bh);

            // an EAGER_BLACKHOLE or CAF_BLACKHOLE gets turned into a
            // BLACKHOLE here.
#ifdef THREADED_RTS
            // first we turn it into a WHITEHOLE to claim it, and if
            // successful we write our TSO and then the BLACKHOLE info pointer.
            cur_bh_info = (const StgInfoTable *)
                cas((StgVolatilePtr)&bh->header.info,
                    (StgWord)bh_info,
                    (StgWord)&stg_WHITEHOLE_info);

            if (cur_bh_info != bh_info) {
                bh_info = cur_bh_info;
                goto retry;
            }
#endif

            // The payload of the BLACKHOLE points to the TSO
            ((StgInd *)bh)->indirectee = (StgClosure *)tso;
            write_barrier();
            SET_INFO(bh,&stg_BLACKHOLE_info);

            // .. and we need a write barrier, since we just mutated the closure:
            recordClosureMutated(cap,bh);

            // We pretend that bh has just been created.
            LDV_RECORD_CREATE(bh);

            frame = (StgClosure *) ((StgUpdateFrame *)frame + 1);
            if (prev_was_update_frame) {
                words_to_squeeze += sizeofW(StgUpdateFrame);
                weight += weight_pending;
                weight_pending = 0;
            }
            prev_was_update_frame = true;
            break;

        case UNDERFLOW_FRAME:
        case STOP_FRAME:
            goto end;

            // normal stack frames; do nothing except advance the pointer
        default:
        {
            uint32_t frame_size = stack_frame_sizeW(frame);
            weight_pending += frame_size;
            frame = (StgClosure *)((StgPtr)frame + frame_size);
            prev_was_update_frame = false;
        }
        }
    }

end:
    // Should we squeeze or not?  Arbitrary heuristic: we squeeze if
    // the number of words we have to shift down is less than the
    // number of stack words we squeeze away by doing so.
    // The threshold was bumped from 5 to 8 as a result of #2797
    heuristic_says_squeeze = ((weight <= 8 && words_to_squeeze > 0)
                            || weight < words_to_squeeze);

    debugTrace(DEBUG_squeeze,
        "words_to_squeeze: %d, weight: %d, squeeze: %s",
        words_to_squeeze, weight,
        heuristic_says_squeeze ? "YES" : "NO");

    if (RtsFlags.GcFlags.squeezeUpdFrames == true &&
        heuristic_says_squeeze) {
        stackSqueeze(cap, tso, (StgPtr)frame);
        tso->flags |= TSO_SQUEEZED;
        // This flag tells threadStackOverflow() that the stack was
        // squeezed, because it may not need to be expanded.
    } else {
        tso->flags &= ~TSO_SQUEEZED;
    }
}


text:
/**
 *
 *
 */
(function () {
    'use strict';
    CPM.namespace('console.components');

    (function (components, core) {

        components.SplitView = Backbone.View.extend({

            initialize: function (options) {
                this.id = options.id || this.$el.attr('id');
                this.profile = core.console.getProfile().get(this.id, 'split', {
                    horizontal: undefined,
                    vertical: undefined,
                    left: true,
                    top: true
                });
                this.horizontalSplit = core.getWidget(this.$el,
                    '#split-view-horizontal-split', components.HorizontalSplitPane);
                this.verticalSplit = core.getWidget(this.$el,
                    '#split-view-vertical-split', components.VerticalSplitPane);
                if (this.profile.left) {
                    this.horizontalSplit.setPosition(this.horizontalSplit.checkPosition(this.profile.horizontal));
                } else {
                    this.closeLeft(false);
                }
                if (this.profile.top) {
                    this.verticalSplit.setPosition(this.verticalSplit.checkPosition(this.profile.vertical));
                } else {
                    this.closeTop(false);
                }
                this.horizontalSplit.$el.on('splitpaneresize', _.bind(this.onResize, this));
                this.verticalSplit.$el.on('splitpaneresize', _.bind(this.onResize, this));
                this.$openLeft = this.$('#split-view-horizontal-split > .open-left a');
                this.$closeLeft = this.$('#split-view-horizontal-split > .split-pane-component.right-pane > .close-left a');
                this.$openTop = this.$('#split-view-vertical-split > .open-top a');
                this.$closeTop = this.$('#split-view-vertical-split > .split-pane-component.bottom-pane > .close-top a');
                this.$openLeft.click(_.bind(this.openLeft, this));
                this.$closeLeft.click(_.bind(this.closeLeft, this));
                this.$openTop.click(_.bind(this.openTop, this));
                this.$closeTop.click(_.bind(this.closeTop, this));
            },

            openLeft: function (event) {
                this.profile.left = true;
                this.$el.addClass('left-open');
                this.horizontalSplit.setPosition(this.horizontalSplit.checkPosition(this.profile.horizontal));
                if (event) {
                    event.preventDefault();
                    this.stateChanged();
                }
                return false;
            },

            closeLeft: function (event) {
                this.profile.left = false;
                this.$el.removeClass('left-open');
                this.horizontalSplit.setPosition(0);
                if (event) {
                    event.preventDefault();
                    this.stateChanged();
                }
                return false;
            },

            openTop: function (event) {
                this.profile.top = true;
                this.$el.addClass('top-open');
                this.verticalSplit.setPosition(this.verticalSplit.checkPosition(this.profile.vertical));
                if (event) {
                    event.preventDefault();
                    this.stateChanged();
                }
                return false;
            },

            closeTop: function (event) {
                this.profile.top = false;
                this.$el.removeClass('top-open');
                this.verticalSplit.setPosition(0);
                if (event) {
                    event.preventDefault();
                    this.stateChanged();
                }
                return false;
            },

            onResize: function () {
                var last = _.clone(this.profile);
                if (this.profile.left) {
                    this.profile.horizontal = this.horizontalSplit.getPosition();
                }
                if (this.profile.top) {
                    this.profile.vertical = this.verticalSplit.getPosition();
                }
                if (!_.isEqual(last, this.profile)) {
                    this.stateChanged();
                }
            },

            stateChanged: function () {
                core.console.getProfile().set(this.id, 'split', this.profile);
                this.horizontalSplit.stateChanged();
                this.verticalSplit.stateChanged();
            }
        });

        /**
         */
        components.SplitPane = Backbone.View.extend({

            initialize: function (options) {
                this.$components = this.$('> .split-pane-component');
                this.$first = $(this.$components[0]);
                this.$second = $(this.$components[1]);
                this.$divider = this.$('> .split-pane-divider');
                this.$el.splitPane();
            },

            checkPosition: function (position) {
                if (position !== undefined) {
                    var minPosition = this.getMinPosition();
                    var maxPosition = this.getMaxPosition();
                    if (position < minPosition) {
                        position = minPosition;
                    }
                    if (position > maxPosition) {
                        position = maxPosition;
                    }
                }
                return position;
            },

            stateChanged: function () {
                this.$first.children().each(function () {
                    $(this).resize();
                });
                this.$second.children().each(function () {
                    $(this).resize();
                });
            }
        });

        /**
         */
        components.HorizontalSplitPane = components.SplitPane.extend({

            getPosition: function () {
                if (this.$el.hasClass('fixed-left')) {
                    return parseInt(this.$divider.css('left'));
                } else {
                    return parseInt(this.$divider.css('right'));
                }
            },

            setPosition: function (position) {
                if (position !== undefined) {
                    if (this.$el.hasClass('fixed-left')) {
                        this.$first.css('width', position + 'px');
                        this.$divider.css('left', position + 'px');
                        this.$second.css('left', position + 'px');
                    } else {
                        this.$second.css('width', position + 'px');
                        this.$divider.css('right', position + 'px');
                        this.$first.css('right', position + 'px');
                    }
                }
            },

            getMinPosition: function () {
                if (this.$el.hasClass('fixed-left')) {
                    return parseInt(this.$first.css('min-width') || '0');
                } else {
                    return parseInt(this.$second.css('min-width') || '0');
                }
            },

            getMaxPosition: function () {
                var width = parseInt(this.$el.width());
                if (this.$el.hasClass('fixed-left')) {
                    return Math.max(width - parseInt(this.$second.css('min-width') || '0'), 0);
                } else {
                    return Math.max(width - parseInt(this.$first.css('min-width') || '0'), 0);
                }
            }
        });

        /**
         */
        components.VerticalSplitPane = components.SplitPane.extend({

            getPosition: function () {
                if (this.$el.hasClass('fixed-top')) {
                    return parseInt(this.$divider.css('top'));
                } else {
                    return parseInt(this.$divider.css('bottom'));
                }
            },

            setPosition: function (position) {
                if (position !== undefined) {
                    if (this.$el.hasClass('fixed-top')) {
                        this.$first.css('height', position + 'px');
                        this.$divider.css('top', position + 'px');
                        this.$second.css('top', position + 'px');
                    } else {
                        this.$second.css('height', position + 'px');
                        this.$divider.css('bottom', position + 'px');
                        this.$first.css('bottom', position + 'px');
                    }
                }
            },

            getMinPosition: function () {
                if (this.$el.hasClass('fixed-top')) {
                    return parseInt(this.$first.css('min-height') || '0');
                } else {
                    return parseInt(this.$second.css('min-height') || '0');
                }
            },

            getMaxPosition: function () {
                var height = parseInt(this.$el.height());
                if (this.$el.hasClass('fixed-top')) {
                    return Math.max(height - parseInt(this.$second.css('min-height') || '0'), 0);
                } else {
                    return Math.max(height - parseInt(this.$first.css('min-height') || '0'), 0);
                }
            }
        });

    })(CPM.console.components, CPM.core);

})();


text:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Infrastructure.Web.SmartTable;
using SimplCommerce.Module.Core.Extensions;
using SimplCommerce.Module.Core.Models;
using SimplCommerce.Module.Core.Services;
using SimplCommerce.Module.News.Areas.News.ViewModels;
using SimplCommerce.Module.News.Models;
using SimplCommerce.Module.News.Services;

namespace SimplCommerce.Module.News.Areas.News.Controllers
{
    [Area("News")]
    [Authorize(Roles = "admin")]
    [Route("api/news-items")]
    public class NewsItemApiController : Controller
    {
        private readonly IRepository<NewsItem> _newsItemRepository;
        private readonly INewsItemService _newsItemService;
        private readonly IMediaService _mediaService;
        private readonly IWorkContext _workContext;

        public NewsItemApiController(IRepository<NewsItem> newsItemRepository, INewsItemService newsItemService, IMediaService mediaService, IWorkContext workContext)
        {
            _newsItemRepository = newsItemRepository;
            _newsItemService = newsItemService;
            _mediaService = mediaService;
            _workContext = workContext;
        }

        [HttpPost("grid")]
        public IActionResult Get([FromBody] SmartTableParam param)
        {
            var query = _newsItemRepository.Query().Where(x => !x.IsDeleted);

            if (param.Search.PredicateObject != null)
            {
                dynamic search = param.Search.PredicateObject;

                if (search.Name != null)
                {
                    string name = search.Name;
                    query = query.Where(x => x.Name.Contains(name));
                }

                if (search.CreatedOn != null)
                {
                    if (search.CreatedOn.before != null)
                    {
                        DateTimeOffset before = search.CreatedOn.before;
                        query = query.Where(x => x.CreatedOn <= before);
                    }

                    if (search.CreatedOn.after != null)
                    {
                        DateTimeOffset after = search.CreatedOn.after;
                        query = query.Where(x => x.CreatedOn >= after);
                    }
                }
            }

            var newsItems = query.ToSmartTableResult(
                param,
                x => new
                {
                    Id = x.Id,
                    Name = x.Name,
                    Slug = x.Slug,
                    IsPublished = x.IsPublished,
                    CreatedOn = x.CreatedOn
                });
            return Json(newsItems);
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> Get(long id)
        {
            var newsItem = await _newsItemRepository.Query()
               .Include(x => x.ThumbnailImage)
               .Include(x => x.Categories)
               .FirstOrDefaultAsync(x => x.Id == id);

            if(newsItem == null)
            {
                return NotFound();
            }

            var model = new NewsItemForm()
            {
                Name = newsItem.Name,
                Id = newsItem.Id,
                Slug = newsItem.Slug,
                MetaTitle = newsItem.MetaTitle,
                MetaKeywords = newsItem.MetaKeywords,
                MetaDescription = newsItem.MetaDescription,
                ShortContent = newsItem.ShortContent,
                FullContent = newsItem.FullContent,
                IsPublished = newsItem.IsPublished,
                ThumbnailImageUrl = _mediaService.GetThumbnailUrl(newsItem.ThumbnailImage),
                NewsCategoryIds = newsItem.Categories.Select( x => x.CategoryId).ToList()
            };

            return Json(model);
        }

        [HttpPost]
        public async Task<IActionResult> Post(NewsItemForm model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var currentUser = await _workContext.GetCurrentUser();
            var newsItem = new NewsItem
            {
                Name = model.Name,
                Slug = model.Slug,
                MetaTitle = model.MetaTitle,
                MetaKeywords = model.MetaKeywords,
                MetaDescription = model.MetaDescription,
                ShortContent = model.ShortContent,
                FullContent = model.FullContent,
                IsPublished = model.IsPublished,
                CreatedBy = currentUser,
                LatestUpdatedBy = currentUser
            };

            foreach (var categoryId in model.NewsCategoryIds)
            {
                var newsItemCategory = new NewsItemCategory
                {
                    CategoryId = categoryId
                };
                newsItem.AddNewsItemCategory(newsItemCategory);
            }

            await SaveServiceMedia(model.ThumbnailImage, newsItem);
            _newsItemService.Create(newsItem);
            return CreatedAtAction(nameof(Get), new { id = newsItem.Id }, null);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> Put(long id, NewsItemForm model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var newsItem = await _newsItemRepository.Query()
               .Include(x => x.ThumbnailImage)
               .Include(x => x.Categories)
               .FirstOrDefaultAsync(x => x.Id == id);
            if(newsItem == null)
            {
                return NotFound();
            }

            var currentUser = await _workContext.GetCurrentUser();

            newsItem.Name = model.Name;
            newsItem.Slug = model.Slug;
            newsItem.MetaTitle = model.MetaTitle;
            newsItem.MetaKeywords = model.MetaKeywords;
            newsItem.MetaDescription = model.MetaDescription;
            newsItem.ShortContent = model.ShortContent;
            newsItem.FullContent = model.FullContent;
            newsItem.IsPublished = model.IsPublished;
            newsItem.LatestUpdatedOn = DateTimeOffset.Now;
            newsItem.LatestUpdatedBy = currentUser;

            AddOrDeleteCategories(model, newsItem);

            if (model.ThumbnailImage != null && newsItem.ThumbnailImage != null)
            {
                await _mediaService.DeleteMediaAsync(newsItem.ThumbnailImage);
            }

            await SaveServiceMedia(model.ThumbnailImage, newsItem);
            _newsItemService.Update(newsItem);
            return Accepted();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(long id)
        {
            var newsItem = await _newsItemRepository.Query().FirstOrDefaultAsync(x => x.Id == id);
            if (newsItem == null)
            {
                return NotFound();
            }

            await _newsItemService.Delete(newsItem);
            return NoContent();
        }

        private async Task<string> SaveFile(IFormFile file)
        {
            var originalFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Value.Trim('"');
            var fileName = $"{Guid.NewGuid()}{Path.GetExtension(originalFileName)}";
            await _mediaService.SaveMediaAsync(file.OpenReadStream(), fileName, file.ContentType);
            return fileName;
        }

        private async Task SaveServiceMedia(IFormFile image, NewsItem newsItem)
        {
            if (image != null)
            {
                var fileName = await SaveFile(image);
                if (newsItem.ThumbnailImage != null)
                {
                    newsItem.ThumbnailImage.FileName = fileName;
                }
                else
                {
                    newsItem.ThumbnailImage = new Media { FileName = fileName };
                }
            }
        }

        private void AddOrDeleteCategories(NewsItemForm model, NewsItem newsItem)
        {
            foreach (var categoryId in model.NewsCategoryIds)
            {
                if (newsItem.Categories.Any(x => x.CategoryId == categoryId))
                {
                    continue;
                }

                var newsItemCategory = new NewsItemCategory
                {
                    CategoryId = categoryId
                };
                newsItem.AddNewsItemCategory(newsItemCategory);
            }

            var deletedNewsItemCategories =
                newsItem.Categories.Where(newsItemCategory => !model.NewsCategoryIds.Contains(newsItemCategory.CategoryId))
                    .ToList();

            foreach (var deletedNewsItemCategory in deletedNewsItemCategories)
            {
                deletedNewsItemCategory.NewsItem = null;
                newsItem.Categories.Remove(deletedNewsItemCategory);
            }
        }
    }
}


text:
namespace Ra {
namespace Gui {

/// A Flight manipulator for Cameras.
class RA_GUIBASE_API FlightCameraManipulator : public CameraManipulator,
                                               public KeyMappingManageable<FlightCameraManipulator>
{
    Q_OBJECT
    friend class KeyMappingManageable<FlightCameraManipulator>;

  public:
    FlightCameraManipulator( uint width, uint height );
    explicit FlightCameraManipulator( const FlightCameraManipulator& other );
    explicit FlightCameraManipulator( const CameraManipulator& other );
    virtual ~FlightCameraManipulator();

    KeyMappingManager::Context mappingContext();
    bool handleMousePressEvent( QMouseEvent* event,
                                const Qt::MouseButtons& buttons,
                                const Qt::KeyboardModifiers& modifiers,
                                int key ) override;
    bool handleMouseReleaseEvent( QMouseEvent* event ) override;
    bool handleMouseMoveEvent( QMouseEvent* event,
                               const Qt::MouseButtons& buttons,
                               const Qt::KeyboardModifiers& modifiers,
                               int key ) override;
    bool handleWheelEvent( QWheelEvent* event ) override;

    bool handleKeyPressEvent( QKeyEvent* event,
                              const KeyMappingManager::KeyMappingAction& action ) override;
    bool handleKeyReleaseEvent( QKeyEvent* event ) override;

    void toggleRotateAround();
    void setCamera( Engine::Camera* camera ) override;

  public slots:
    void setCameraPosition( const Core::Vector3& position ) override;
    void setCameraTarget( const Core::Vector3& target ) override;
    void fitScene( const Core::Aabb& aabb ) override;

    void resetCamera() override;

  protected:
    virtual void handleCameraRotate( Scalar dx, Scalar dy );
    virtual void handleCameraPan( Scalar dx, Scalar dy );
    virtual void handleCameraZoom( Scalar dx, Scalar dy );
    virtual void handleCameraZoom( Scalar z );

  protected:
    /// x-position of the mouse on the screen at the manipulation start.
    Scalar m_lastMouseX{0_ra};

    /// y-position of the mouse on the screen at the manipulation start.
    Scalar m_lastMouseY{0_ra};

    /// Whether the corresponding camera movement is active or not.
    bool m_rotateAround;
    bool m_cameraRotateMode;
    bool m_cameraPanMode;
    bool m_cameraZoomMode;

  private:
    void initializeFixedUpVector();
    Ra::Core::Vector3 m_fixUpVector{0_ra, 1_ra, 0_ra};
    Scalar m_flightSpeed{1._ra};
    static void configureKeyMapping_impl();

#define KeyMappingFlightManipulator      \
    KMA_VALUE( FLIGHTMODECAMERA_ROTATE ) \
    KMA_VALUE( FLIGHTMODECAMERA_PAN )    \
    KMA_VALUE( FLIGHTMODECAMERA_ZOOM )   \
    KMA_VALUE( FLIGHTMODECAMERA_ROTATE_AROUND )

#define KMA_VALUE( XX ) static KeyMappingManager::KeyMappingAction XX;
    KeyMappingFlightManipulator
#undef KMA_VALUE
};

} // namespace Gui
} // namespace Ra

#endif // RADIUMENGINE_FLIGHTCAMERAMANIPULATOR_HPP


text:
package org.deeplearning4j.nn.params;

import org.deeplearning4j.nn.api.ParamInitializer;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.BatchNormalization;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.indexing.NDArrayIndex;

import java.util.*;

/**
 * Batch normalization variable init
 */

public class BatchNormalizationParamInitializer implements ParamInitializer {

    private static final BatchNormalizationParamInitializer INSTANCE = new BatchNormalizationParamInitializer();

    public static BatchNormalizationParamInitializer getInstance() {
        return INSTANCE;
    }

    public static final String GAMMA = "gamma";
    public static final String BETA = "beta";
    public static final String GLOBAL_MEAN = "mean";
    public static final String GLOBAL_VAR = "var";

    public static List<String> keys() {
        return Arrays.asList(GAMMA, BETA, GLOBAL_MEAN, GLOBAL_VAR);
    }

    @Override
    public int numParams(NeuralNetConfiguration conf) {
        return numParams(conf.getLayer());
    }

    @Override
    public int numParams(Layer l) {
        BatchNormalization layer = (BatchNormalization) l;
        //Parameters in batch norm:
        //gamma, beta, global mean estimate, global variance estimate
        // latter 2 are treated as parameters, which greatly simplifies spark training and model serialization

        if (layer.isLockGammaBeta()) {
            //Special case: gamma and beta are fixed values for all outputs -> no parameters for gamma and  beta in this case
            return 2 * layer.getNOut();
        } else {
            //Standard case: gamma and beta are learned per output; additional 2*nOut for global mean/variance estimate
            return 4 * layer.getNOut();
        }
    }

    @Override
    public Map<String, INDArray> init(NeuralNetConfiguration conf, INDArray paramView, boolean initializeParams) {
        Map<String, INDArray> params = Collections.synchronizedMap(new LinkedHashMap<String, INDArray>());
        // TODO setup for RNN
        BatchNormalization layer = (BatchNormalization) conf.getLayer();
        int nOut = layer.getNOut();

        int meanOffset = 0;
        if (!layer.isLockGammaBeta()) { //No gamma/beta parameters when gamma/beta are locked
            INDArray gammaView = paramView.get(NDArrayIndex.point(0), NDArrayIndex.interval(0, nOut));
            INDArray betaView = paramView.get(NDArrayIndex.point(0), NDArrayIndex.interval(nOut, 2 * nOut));

            params.put(GAMMA, createGamma(conf, gammaView, initializeParams));
            conf.addVariable(GAMMA);
            params.put(BETA, createBeta(conf, betaView, initializeParams));
            conf.addVariable(BETA);

            meanOffset = 2 * nOut;
        }

        INDArray globalMeanView =
                        paramView.get(NDArrayIndex.point(0), NDArrayIndex.interval(meanOffset, meanOffset + nOut));
        INDArray globalVarView = paramView.get(NDArrayIndex.point(0),
                        NDArrayIndex.interval(meanOffset + nOut, meanOffset + 2 * nOut));

        if (initializeParams) {
            globalMeanView.assign(0);
            globalVarView.assign(1);
        }

        params.put(GLOBAL_MEAN, globalMeanView);
        conf.addVariable(GLOBAL_MEAN);
        params.put(GLOBAL_VAR, globalVarView);
        conf.addVariable(GLOBAL_VAR);

        return params;
    }

    @Override
    public Map<String, INDArray> getGradientsFromFlattened(NeuralNetConfiguration conf, INDArray gradientView) {
        BatchNormalization layer = (BatchNormalization) conf.getLayer();
        int nOut = layer.getNOut();

        Map<String, INDArray> out = new LinkedHashMap<>();
        int meanOffset = 0;
        if (!layer.isLockGammaBeta()) {
            INDArray gammaView = gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(0, nOut));
            INDArray betaView = gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(nOut, 2 * nOut));
            out.put(GAMMA, gammaView);
            out.put(BETA, betaView);
            meanOffset = 2 * nOut;
        }

        out.put(GLOBAL_MEAN,
                        gradientView.get(NDArrayIndex.point(0), NDArrayIndex.interval(meanOffset, meanOffset + nOut)));
        out.put(GLOBAL_VAR, gradientView.get(NDArrayIndex.point(0),
                        NDArrayIndex.interval(meanOffset + nOut, meanOffset + 2 * nOut)));

        return out;
    }

    private INDArray createBeta(NeuralNetConfiguration conf, INDArray betaView, boolean initializeParams) {
        BatchNormalization layer = (BatchNormalization) conf.getLayer();
        if (initializeParams)
            betaView.assign(layer.getBeta());
        return betaView;
    }

    private INDArray createGamma(NeuralNetConfiguration conf, INDArray gammaView, boolean initializeParams) {
        BatchNormalization layer = (BatchNormalization) conf.getLayer();
        if (initializeParams)
            gammaView.assign(layer.getGamma());
        return gammaView;
    }
}


text:
'use strict';

module.exports = function (callback) {
  var self = this;
  this.cluster.restart(function (err) {
    if (err) {
      self.i18n.writeLn('REPL_RESTART_FAIL');
    } else {
      self.i18n.writeLn('REPL_RESTARTED');
    }
    callback();
  });
};


text:
package org.gradle.api.internal.artifacts.transform;

import org.gradle.api.artifacts.component.ComponentArtifactIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactVisitor;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvedArtifactSet;
import org.gradle.api.internal.attributes.AttributeContainerInternal;

import java.io.File;
import java.util.Map;

public class TransformCompletion implements ResolvedArtifactSet.Completion {
    private final AttributeContainerInternal attributes;
    private final ResolvedArtifactSet.Completion delegate;
    private final Map<ComponentArtifactIdentifier, TransformationOperation> artifactResults;
    private final Map<File, TransformationOperation> fileResults;

    public TransformCompletion(ResolvedArtifactSet.Completion delegate, AttributeContainerInternal attributes, Map<ComponentArtifactIdentifier, TransformationOperation> artifactResults, Map<File, TransformationOperation> fileResults) {
        this.delegate = delegate;
        this.attributes = attributes;
        this.artifactResults = artifactResults;
        this.fileResults = fileResults;
    }

    @Override
    public void visit(ArtifactVisitor visitor) {
        delegate.visit(new TransformingArtifactVisitor(visitor, attributes, artifactResults, fileResults));
    }
}


text:
using Android.App;
using Android.Content.PM;
using Android.OS;
using Xamarin.Forms;
using Android.Content;
using Android.Graphics;
using Xamarin.Forms.Platform.Android;

namespace ShareExample.Droid
{
    [Activity(Label = "ShareExample.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        const int ShareImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Forms.Init(this, bundle);

            LoadApplication(new App());

            MessagingCenter.Subscribe<ImageSource> (this, "Share", Share, null);
        }

        async void Share (ImageSource imageSource)
        {
            var intent = new Intent (Intent.ActionSend);
            intent.SetType ("image/png");

            var handler = new ImageLoaderSourceHandler();
            var bitmap = await handler.LoadImageAsync(imageSource, this);

            var path = Environment.GetExternalStoragePublicDirectory (Environment.DirectoryDownloads
                + Java.IO.File.Separator + "logo.png");

            using (var os = new System.IO.FileStream (path.AbsolutePath, System.IO.FileMode.Create)) {
                bitmap.Compress (Bitmap.CompressFormat.Png, 100, os);
            }

            intent.PutExtra (Intent.ExtraStream, Android.Net.Uri.FromFile (path));

            var intentChooser = Intent.CreateChooser (intent, "Share via");

            StartActivityForResult (intentChooser, ShareImageId);
        }
    }
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Example</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="app.css">

    <comments comment-data="comments"></comments>

        <commenter action="addParentComment" toggle="true"></commenter>


text:
# function-whitespace-after

Require or disallow whitespace after functions.

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1) scale(3); }
/**                           ↑
 *                   This space */
```

This rule does not check for space immediately after `)` if the very next character is `,`, `)`, `/` or `}`, allowing some of the patterns exemplified below.

The [`fix` option](../../../docs/user-guide/usage/options.md#fix) can automatically fix all of the problems reported by this rule.

## Options

`string`: `"always"|"never"`

### `"always"`

There _must always_ be whitespace after the function.

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1)scale(3); }
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1) scale(3); }
```

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1)     scale(3); }
```

<!-- prettier-ignore -->
```css
a {
  transform:
    translate(1, 1)
    scale(3);
}
```

<!-- prettier-ignore -->
```css
/* notice the two closing parentheses without a space between */
a { top: calc(1 * (1 + 3)); }
```

<!-- prettier-ignore -->
```css
/* notice the ), with no space after the closing parenthesis */
a { padding: calc(1 * 2px), calc(2 * 5px); }
```

### `"never"`

There _must never_ be whitespace after the function.

The following patterns are considered problems:

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1) scale(3); }
```

The following patterns are _not_ considered problems:

<!-- prettier-ignore -->
```css
a { transform: translate(1, 1)scale(3); }
```


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.tonybeltramelli.mobile.facedroidtactoegobelinsproject;

public final class R {
    public static final class array {
        public static final int array_difficulty=0x7f070000;
        public static final int array_difficulty_values=0x7f070001;
    }
    public static final class attr {
    }
    public static final class color {
        public static final int color_background=0x7f050000;
        public static final int color_dark_grey=0x7f050007;
        public static final int color_light_dark_blue=0x7f050005;
        public static final int color_light_grey=0x7f050008;
        public static final int color_light_soft_blue=0x7f050006;
        public static final int color_medium_dark_blue=0x7f050003;
        public static final int color_medium_soft_blue=0x7f050004;
        public static final int color_strong_dark_blue=0x7f050001;
        public static final int color_strong_soft_blue=0x7f050002;
    }
    public static final class drawable {
        public static final int against_pawn=0x7f020000;
        public static final int button_custom=0x7f020001;
        public static final int button_inactive=0x7f020002;
        public static final int ic_action_search=0x7f020003;
        public static final int ic_launcher=0x7f020004;
        public static final int player_pawn=0x7f020005;
        public static final int splash_screen=0x7f020006;
    }
    public static final class id {
        public static final int button_about=0x7f0a000f;
        public static final int button_against_computer=0x7f0a000b;
        public static final int button_against_human=0x7f0a000c;
        public static final int button_back_home=0x7f0a000a;
        public static final int button_email_view=0x7f0a0011;
        public static final int button_from_camera=0x7f0a0003;
        public static final int button_from_library=0x7f0a0004;
        public static final int button_message=0x7f0a000e;
        public static final int button_navigate=0x7f0a0001;
        public static final int button_ok=0x7f0a0006;
        public static final int button_play=0x7f0a000d;
        public static final int button_play_again=0x7f0a0009;
        public static final int button_preferences=0x7f0a0010;
        public static final int button_send=0x7f0a001b;
        public static final int button_sms_view=0x7f0a0012;
        public static final int customImageContainer=0x7f0a0005;
        public static final int email_textfield=0x7f0a0016;
        public static final int email_view=0x7f0a0014;
        public static final int end_game_label=0x7f0a0008;
        public static final int end_game_title=0x7f0a0007;
        public static final int menu_settings=0x7f0a001c;
        public static final int message_content=0x7f0a001a;
        public static final int message_view_switcher=0x7f0a0013;
        public static final int phone_textfield=0x7f0a0019;
        public static final int sms_view=0x7f0a0017;
        public static final int title_about=0x7f0a0000;
        public static final int title_email=0x7f0a0015;
        public static final int title_sms=0x7f0a0018;
        public static final int webView=0x7f0a0002;
    }
    public static final class layout {
        public static final int activity_about_page=0x7f030000;
        public static final int activity_custom_picture=0x7f030001;
        public static final int activity_endgame_page=0x7f030002;
        public static final int activity_game_page=0x7f030003;
        public static final int activity_main=0x7f030004;
        public static final int activity_message_page=0x7f030005;
        public static final int activity_splash_screen=0x7f030006;
    }
    public static final class menu {
        public static final int settings_menu=0x7f090000;
    }
    public static final class string {
        public static final int app_name=0x7f060000;
        public static final int button_about_content=0x7f06000f;
        public static final int button_about_page_content=0x7f060012;
        /**  game
 game
         */
        public static final int button_against_computer=0x7f060013;
        public static final int button_against_human=0x7f060014;
        public static final int button_back_home_content=0x7f060028;
        public static final int button_email_view_switcher=0x7f06001c;
        public static final int button_from_camera_content=0x7f060021;
        public static final int button_from_library_content=0x7f060022;
        public static final int button_message_content=0x7f06000e;
        public static final int button_play_again_content=0x7f060027;
        /**  main
 main
         */
        public static final int button_play_content=0x7f06000d;
        public static final int button_preferences_content=0x7f060010;
        public static final int button_send=0x7f06001b;
        public static final int button_sms_view_switcher=0x7f06001d;
        public static final int choose_message=0x7f060034;
        public static final int computer_player=0x7f06002b;
        public static final int email_subject=0x7f06001a;
        public static final int error_email=0x7f060031;
        public static final int error_email_not_valid=0x7f060030;
        /**  informations
 informations
         */
        public static final int error_message_content=0x7f06002f;
        public static final int error_sms=0x7f060032;
        public static final int first_player=0x7f060029;
        public static final int image_view_description=0x7f060023;
        public static final int label_equal=0x7f060026;
        public static final int label_win=0x7f060025;
        public static final int loader_message=0x7f06002e;
        /**  loader
 loader
         */
        public static final int loader_title=0x7f06002d;
        public static final int owner_player=0x7f06002c;
        public static final int second_player=0x7f06002a;
        public static final int settings_button_image_key=0x7f060008;
        public static final int settings_color_key=0x7f06000a;
        public static final int settings_color_title=0x7f060005;
        public static final int settings_default_key=0x7f06000c;
        public static final int settings_difficulty_desc=0x7f060003;
        public static final int settings_difficulty_key=0x7f06000b;
        /**  preferences
 preferences
         */
        public static final int settings_difficulty_title=0x7f060002;
        public static final int settings_image_default_title=0x7f060004;
        public static final int settings_image_desc=0x7f060007;
        public static final int settings_image_key=0x7f060009;
        public static final int settings_image_title=0x7f060006;
        public static final int success_sms=0x7f060033;
        /**  message
 message
         */
        public static final int textview_account_hint=0x7f060016;
        public static final int textview_password_hint=0x7f060017;
        public static final int textview_to_hint=0x7f060018;
        public static final int textview_to_message=0x7f060019;
        /**  about
 about
         */
        public static final int title_about_page_content=0x7f060011;
        public static final int title_activity_main=0x7f060001;
        /**  custom picture
 custom picture
         */
        public static final int title_custom_picture_content=0x7f060020;
        public static final int title_email_sender=0x7f06001e;
        /**  win screen
 win screen
         */
        public static final int title_endgame=0x7f060024;
        public static final int title_sms_sender=0x7f06001f;
        public static final int to_play=0x7f060015;
    }
    public static final class style {
        public static final int AppTheme=0x7f080000;
    }
    public static final class xml {
        public static final int preferences=0x7f040000;
    }
}


text:
"use strict";

const BaseSerializer = require("./base");
const P = require("../packets");
const { MoleculerServerError } = require("../errors");

/**
 * Apache Thrift Serializer for Moleculer
 *
 * http://thrift.apache.org/
 *
 * Download Thrift compiler: https://thrift.apache.org/download
 *
 * @class ThriftSerializer
 */
class ThriftSerializer extends BaseSerializer {

	/**
	 * Initialize Serializer
	 *
	 * @param {any} broker
	 *
	 * @memberof Serializer
	 */
	init(broker) {
		super.init(broker);

		try {
			const Thrift = require("thrift");
			this.TBufferedTransport = Thrift.TBufferedTransport;
			this.TBinaryProtocol = Thrift.TBinaryProtocol;

			const transport = new Thrift.TBufferedTransport(null, (res) => this.serialized = res);
			this.protocol = new Thrift.TBinaryProtocol(transport);

		} catch(err) {
			/* istanbul ignore next */
			this.broker.fatal("The 'thrift' package is missing! Please install it with 'npm install thrift --save' command!", err, true);
		}

		this.packets = require("./thrift/gen-nodejs/packets_types.js");
	}

	getPacketFromType(type) {
		switch(type) {
			case P.PACKET_EVENT: return this.packets.PacketEvent;
			case P.PACKET_REQUEST: return this.packets.PacketRequest;
			case P.PACKET_RESPONSE: return this.packets.PacketResponse;
			case P.PACKET_DISCOVER: return this.packets.PacketDiscover;
			case P.PACKET_INFO: return this.packets.PacketInfo;
			case P.PACKET_DISCONNECT: return this.packets.PacketDisconnect;
			case P.PACKET_HEARTBEAT: return this.packets.PacketHeartbeat;
			case P.PACKET_PING: return this.packets.PacketPing;
			case P.PACKET_PONG: return this.packets.PacketPong;
			case P.PACKET_GOSSIP_HELLO: return this.packets.PacketGossipHello;
			case P.PACKET_GOSSIP_REQ: return this.packets.PacketGossipRequest;
			case P.PACKET_GOSSIP_RES: return this.packets.PacketGossipResponse;
		}
	}

	/**
	 * Serializer a JS object to Buffer
	 *
	 * @param {Object} obj
	 * @param {String} type of packet
	 * @returns {Buffer}
	 *
	 * @memberof Serializer
	 */
	serialize(obj, type) {
		const P = this.getPacketFromType(type);
		if (!P) {
			/* istanbul ignore next */
			throw new MoleculerServerError("Invalid packet type!", 500, "INVALID_PACKET_TYPE");
		}

		this.serializeCustomFields(type, obj);

		const t = new P(obj);
		t.write(this.protocol);
		this.protocol.flush();
		return this.serialized;
	}

	/**
	 * Deserialize Buffer to JS object
	 *
	 * @param {Buffer} buf
	 * @param {String} type of packet
	 * @returns {Object}
	 *
	 * @memberof Serializer
	 */
	deserialize(buf, type) {
		const P = this.getPacketFromType(type);
		if (!P) {
			/* istanbul ignore next */
			throw new MoleculerServerError("Invalid packet type!", 500, "INVALID_PACKET_TYPE");
		}

		let obj;
		const transport = this.TBufferedTransport.receiver(reader => {
			const protocol = new this.TBinaryProtocol(reader);
			const t = new P();
			t.read(protocol);
			obj = t;
		});

		transport(buf);

		this.deserializeCustomFields(type, obj);

		return obj;
	}
}

module.exports = ThriftSerializer;


text:
<!doctype html>

<title>TractionDialogBox Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">

Click the button to open the dialog.

TractionDialogBox Demo

TractionDialogBox Open Events (most recent on top)


text:
all:
	@echo "Please understand what you are doing, first."
	@false

.include <bsd.own.mk>
.include "${NETBSDSRCDIR}/distrib/common/Makefile.distrib"

COMPRESS_PROGRAM=${TOOL_GZIP}
GZIP_FLAGS= ${GZIP_N_FLAG}

SETSENV=	DESTDIR=${DESTDIR:Q} \
		MACHINE=${MACHINE:Q} \
		MACHINE_ARCH=${MACHINE_ARCH:Q} \
		AWK=${TOOL_AWK:Q} \
		CKSUM=${TOOL_CKSUM:Q} \
		DB=${TOOL_DB:Q} \
		HOST_SH=${HOST_SH:Q} \
		MAKE=${MAKE:Q} \
		MKTEMP=${TOOL_MKTEMP:Q} \
		MTREE=${TOOL_MTREE:Q} \
		PAX=${TOOL_PAX:Q} \
		COMPRESS_PROGRAM=${COMPRESS_PROGRAM:Q} \
		GZIP=${GZIP_FLAGS:Q} \
		PKG_CREATE=${TOOL_PKG_CREATE:Q} \
		SED=${TOOL_SED:Q} \
		TSORT=${TSORT:Q}
SETSCMD=	cd ${.CURDIR} && \
		${SETSENV} \
		${HOST_SH}

MAKETARS_FLAGS=
.if ${MKX11} != "no"
MAKESRCTARS_X11_FLAGS=	-x ${X11SRCDIR}
.endif
.if ${MKEXTSRC} != "no"
MAKESRCTARS_EXTSRC_FLAGS=	-y ${EXTSRCSRCDIR}
.endif
.if ${MKX11} != "no"
MAKEFLIST_X11_FLAGS=	,x
.endif
.if ${MKEXTSRC} != "no"
MAKEFLIST_EXTSRC_FLAGS=	,ext
.endif
MAKEFLIST_FLAGS=	-L base${MAKEFLIST_X11_FLAGS}${MAKEFLIST_EXTSRC_FLAGS}
MAKESRCTARS_FLAGS= 	-N ${NETBSDSRCDIR}/etc

.if ${MAKEVERBOSE} < 2
MAKETARS_FLAGS+=	-q
MAKESRCTARS_FLAGS+= 	-q
.endif

.if !defined(MAKETARSETS)
MAKETARSETS!= ${SETSCMD} ./makeflist -l ${MAKEFLIST_FLAGS}
.endif

print_have_gcc: .PHONY
	@echo ${HAVE_GCC}

print_machine: .PHONY
	@echo ${MACHINE}

print_machine_arch: .PHONY
	@echo ${MACHINE_ARCH}

print_machine_cpu: .PHONY
	@echo ${MACHINE_CPU}

print_object_fmt: .PHONY
	@echo ${OBJECT_FMT}

print_toolchain_missing: .PHONY
	@echo "${TOOLCHAIN_MISSING}"

print_mkvars \
print_set_lists_base print_set_lists_x print_set_lists_ext \
list_set_lists_base list_set_lists_x list_set_lists_ext \
list_set_files_base list_set_files_x list_set_files_ext \
		: .PHONY
	@${SETSENV}; rundir="${.CURDIR}"; . ./sets.subr; ${.TARGET}

#
# METALOG MANIPULATION TARGETS
#
# METALOG is the name of a metadata log file, and is set in <bsd.own.mk>
# if MKUNPRIVED is not "no".
#
# METALOG.unpriv is a command line option passed to various scripts;
# it is either blank or "-M ${METALOG}.sanitised", depending on the
# MKUNPRIVED flag.
#
# The sanitise_METALOG target creates METALOG.sanitised from METALOG,
# without modifying METALOG itself.  This is used near the end of
# a build, after build products have been installed in DESTDIR
# and corresponding lines have been added to METALOG, but before
# METALOG.sanitised is used in the creation of sets in RELEASEDIR.
# For update builds, METALOG.sanitised has duplicates merged (keeping
# only the last of multiple entries for the same item), but for clean
# builds it's an error if a file or directory name appears twice.
# METALOG.sanitised is always sorted and has timestamps removed.
#
# The clean_METALOG target either deletes METALOG, or replaces METALOG with
# a sanitised version of itself, depending on the MKUPDATE flag, and
# deletes old METALOG.* files.  This is intended to be used at the start
# of a build, to ensure that repeated MKUPDATE builds do not cause
# unbounded growth of METALOG.
#

METALOG_REMOVE_DUPLICATES= \
	${TOOL_AWK} '{ a[$$1] = $$0; } END { for (f in a) print a[f]; }'

.if ${MKUNPRIVED} == "no"
METALOG.unpriv=
sanitise_METALOG: .PHONY
	@true
clean_METALOG: .PHONY
	@true
.else	# MKUNPRIVED
METALOG.unpriv= -M ${METALOG}.sanitised
sanitise_METALOG: .PHONY ${METALOG}.sanitised
${METALOG}.sanitised: ${METALOG}
	<${METALOG} \
	    ${${MKUPDATE} != "no" :? ${METALOG_REMOVE_DUPLICATES} | :} \
	    sort | ${TOOL_MTREE} -CSM -k all -R time -N ${NETBSDSRCDIR}/etc \
	    >${METALOG}.new
	mv ${METALOG}.new ${METALOG}.sanitised
.if defined(RCSMETALOG)
	. ./metalog.subr; \
	xrcs_descr="build distribution METALOG"; \
	xrcs_msg="$$(date)"; \
	xrcs_cur=${METALOG}.sanitised; \
	xrcs update
.endif
.if ${MKUPDATE} == "no" || !exists(${METALOG})
clean_METALOG: .PHONY
	rm -f ${METALOG} ${METALOG}.*
.else	# MKUPDATE
clean_METALOG: .PHONY ${METALOG}.sanitised
	mv ${METALOG}.sanitised ${METALOG}
.if defined(RCSMETALOG)
	[ -f ${METALOG}.sanitised,v ] && mv ${METALOG}.sanitised,v ${METALOG},v
.endif
	rm -f ${METALOG}.*
.if defined(RCSMETALOG)
	[ -f ${METALOG},v ] && mv ${METALOG},v ${METALOG}.sanitised,v
.endif
.endif	# MKUPDATE
.endif	# MKUNPRIVED

#
# FILE LIST TARGETS
#

# This target has debugging value only, really.
makeflist: .PHONY .PRECIOUS check_DESTDIR
	${SETSCMD} ./makeflist ${MAKEFLIST_FLAGS}

checkflist: .PRECIOUS .PHONY check_DESTDIR sanitise_METALOG
	${SETSCMD} ${.CURDIR}/checkflist \
	    ${MAKEFLIST_FLAGS} ${CHECKFLIST_FLAGS} ${METALOG.unpriv}

checkflist-x11: .PHONY check_DESTDIR
	${SETSCMD} ./checkflist -x ${CHECKFLIST_FLAGS}

checkflist-extsrc: .PHONY check_DESTDIR
	${SETSCMD} ./checkflist -y ${CHECKFLIST_FLAGS}

.if defined(DESTDIR) && ${DESTDIR} != ""
checkflist_if_DESTDIR: checkflist
.else
checkflist_if_DESTDIR:
.endif

#
# SET BUILDING TARGETS
#

TARDIR=		${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/sets
SOURCETARDIR=	${RELEASEDIR}/source/sets

# If MAKETARS_SERIAL is set to "YES" or "yes", then the tar sets will be
# made in series, even if make's "-j" flag requests multiple parallel
# jobs.  This is useful on systems that exhibit poor performance when
# running multiple parallel disk-intensive operations.  The default is
# MAKETARS_SERIAL=NO, which will obey the "-j" flag passed to the make
# command.
#
MAKETARS_SERIAL?= NO
.if empty(MAKETARS_SERIAL:M[Yy][Ee][Ss])
_MAKETARS_WAIT= # empty
.else
_MAKETARS_WAIT= .WAIT
.endif

maketars: .PRECIOUS .PHONY check_DESTDIR check_RELEASEDIR \
		sanitise_METALOG checkflist_if_DESTDIR .WAIT \
		maketarsetup .WAIT \
		${MAKETARSETS:@.TARS.@${_MAKETARS_WAIT} do-${.TARS.}@}
	@true

maketarsetup: .EXEC
.if defined(DESTDIR) && ${DESTDIR} != ""
	${_MKMSG} "execute  checkflist"
	cd ${.CURDIR}; ${MAKE} checkflist
.endif
	mkdir -p ${TARDIR}
	for i in MD5 SHA512; do \
		rm -f ${TARDIR}/$$i ${TARDIR}/$$i.tmp; \
	done

makesetfiles: .PHONY sanitise_METALOG
	${_MKMSG_CREATE} "set lists"
	${SETSCMD} ./maketars -S -d ${DESTDIR:S,^$,/,} ${MAKETARS_FLAGS} \
	    ${METALOG.unpriv} \
	    -N ${NETBSDSRCDIR}/etc ${MAKEFLIST_FLAGS} -t ${TARDIR}

.for tar in ${MAKETARSETS}
do-${tar}: .PHONY sanitise_METALOG
	${_MKMSG_CREATE} "${tar}.tgz"
	${SETSCMD} ./maketars -d ${DESTDIR:S,^$,/,} ${MAKETARS_FLAGS} \
	    ${METALOG.unpriv} \
	    -N ${NETBSDSRCDIR}/etc -t ${TARDIR} ${tar} \
	|| { rm -f ${TARDIR}/${tar}.tgz; false; }
.endfor

makesrctars: .PRECIOUS .PHONY check_RELEASEDIR
	${_MKMSG_CREATE} "source tar files"
	mkdir -p ${SOURCETARDIR}
	${SETSCMD} ./makesrctars ${MAKESRCTARS_FLAGS} \
	    ${MAKESRCTARS_X11_FLAGS} ${MAKESRCTARS_EXTSRC_FLAGS} \
	    ${NETBSDSRCDIR} ${SOURCETARDIR}

makesums: .PRECIOUS .PHONY check_RELEASEDIR .WAIT \
		${MAKETARSETS:@.TARS.@do-sum-${.TARS.}@}
	for i in MD5 SHA512; do \
		mv ${TARDIR}/$$i.tmp ${TARDIR}/$$i; \
	done

.for tar in ${MAKETARSETS}
do-sum-${tar}: .PHONY do-${tar}
	${_MKMSG_CREATE} "${tar} checksums"
	${MAKESUMS} -t ${TARDIR} ${tar}.tgz
	for i in MD5 SHA512; do \
		${TOOL_CAT} ${TARDIR}/$$i >> ${TARDIR}/$$i.tmp; \
	done
.endfor
.ORDER: ${MAKETARSETS:@.TARS.@do-sum-${.TARS.}@}

installsets: .PHONY check_DESTDIR sanitise_METALOG
.if !defined(INSTALLDIR)
	@echo "setenv INSTALLDIR before doing that!"
	@false
.endif
	${SETSCMD} ./maketars -d ${DESTDIR:S,^$,/,} ${MAKETARS_FLAGS} \
	    ${METALOG.unpriv} -N ${NETBSDSRCDIR}/etc \
	    ${MAKEFLIST_FLAGS} -i ${INSTALLDIR} ${INSTALLSETS}

# Should we ignore errors like extra or missing files in the flists?
SLOPPY_FLIST?= NO
.if !empty(SLOPPY_FLIST:M[Yy][Ee][Ss])
CHECKFLIST_FLAGS+=	-e -m
REGPKG.sloppy=		-m
.endif

.if ${MAKEVERBOSE} == 0
REGPKG.verbose?= -q
.elif ${MAKEVERBOSE} == 1
REGPKG.verbose?=
.else	# MAKEVERBOSE >= 2
REGPKG.verbose?= -v
.endif
REGPKG.force?=		# -f, or empty
REGPKG.cache?= -c	# -c, or empty
REGPKG.update:= ${MKUPDATE:tl:Nno:C/..*/-u/}
SYSPKGSETS?= all
makesyspkgs: .PHONY check_DESTDIR check_RELEASEDIR \
		sanitise_METALOG checkflist_if_DESTDIR
	mkdir -p ${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/syspkgs
	${SETSCMD} ${.CURDIR}/regpkgset \
	    ${REGPKG.verbose} ${REGPKG.force} ${REGPKG.sloppy} \
	    ${REGPKG.cache} ${REGPKG.update} \
	    -d ${DESTDIR:S,^$,/,} ${METALOG.unpriv} \
	    -N ${NETBSDSRCDIR}/etc \
	    -t ${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/syspkgs ${SYSPKGSETS}

makesyspkgsums: .PHONY check_RELEASEDIR
	${MAKESUMS} -t ${RELEASEDIR}/${RELEASEMACHINEDIR}/binary/syspkgs

# Update the "deps" file.
# XXX: Why is "deps" checked in to the source tree, instead of
# just being created as necessary?
makedeps: .PHONY
	${SETSCMD} ./syspkgdeps all >${.CURDIR}/deps

# Sort the lists files
sortlists: .PHONY
	find ${.CURDIR}/lists \! \( -name CVS -prune \) \! -name .#\* \
	    -type f -print \
	| while read f ; do \
	    ${_MKSHMSG} "sorting $${f#${.CURDIR}/}" ; \
	    { grep '^#' "$$f" ; \
	      grep -v '^#' "$$f" | sort ; \
	    } | cat -s >"$$f".tmp; \
	    if cmp "$$f" "$$f".tmp >/dev/null; then \
	      : "$$f is unchanged" ; \
	      rm "$$f".tmp ; \
	    else \
	      mv "$$f".tmp "$$f" ; \
	    fi ; \
	  done

#
# MAIN ENTRY POINTS
#

syspkgs: .PHONY makesyspkgs .WAIT makesyspkgsums
	@true

sets: .PHONY maketars .WAIT makesums
	@true

sourcesets: .PHONY makesrctars
	@true

.include <bsd.files.mk>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VsanHostClusterStatus extends DynamicData {
  public String uuid;
  public String nodeUuid;
  public String health;
  public VsanHostClusterStatusState nodeState;
  public String[] memberUuid;

  public String getUuid() {
    return this.uuid;
  }

  public String getNodeUuid() {
    return this.nodeUuid;
  }

  public String getHealth() {
    return this.health;
  }

  public VsanHostClusterStatusState getNodeState() {
    return this.nodeState;
  }

  public String[] getMemberUuid() {
    return this.memberUuid;
  }

  public void setUuid(String uuid) {
    this.uuid=uuid;
  }

  public void setNodeUuid(String nodeUuid) {
    this.nodeUuid=nodeUuid;
  }

  public void setHealth(String health) {
    this.health=health;
  }

  public void setNodeState(VsanHostClusterStatusState nodeState) {
    this.nodeState=nodeState;
  }

  public void setMemberUuid(String[] memberUuid) {
    this.memberUuid=memberUuid;
  }
}