text:
@import UIKit;
#import <ResearchKit/ORKDefines.h>
#import <ResearchKit/ORKStepViewController.h>

NS_ASSUME_NONNULL_BEGIN

/**
 The `ORKImageCaptureStepViewController` class represents the step view controller that
 corresponds to an `ORKImageCaptureStep` class.

 It is not usually necessary to instantiate this view controller directly.
 Instead, add an image capture step to a task, and present the task in a task
 view controller.
 */
ORK_CLASS_AVAILABLE
@interface ORKImageCaptureStepViewController : ORKStepViewController

@end

NS_ASSUME_NONNULL_END


text:
/*

  DEBUG CHILDREN

  Just add the debug class to any element to see outlines on its
  children.

*/

.debug * { outline: 1px solid gold; }

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">

	<title>TSU Exam Finder - გამოცდის ადგილები</title>
	<meta name="description" content="წინასწარ გაიგე რომელ სექტორში რა ადგილას წერ გამოცდას.">
	<meta name="keywords" content="tsu,exams,gamocdebi,finder,თსუ,გამოცდები,განრიგი,ცხრილი,სექტორი,ადგილი,შუალედური,კოლოქვიუმი">
	<meta name="author" content="Levan Velijanashvili">

	<meta property="og:title" content="გამოცდის ადგილები (თსუ)">
	<meta property="og:image" content="{{ url('assets/og-image.png') }}">
	<meta property="og:url" content="{{ url() }}">
	<meta property="og:description" content="წინასწარ გაიგე რომელ სექტორში რა ადგილას წერ გამოცდას.">

	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">

	<link rel="icon" href="{{ url('assets/logo.png') }}">
	<link rel="shortcut icon" href="{{ url('assets/logo.png') }}">
	<link rel="apple-touch-icon" href="{{ url('assets/logo.png') }}">
	<link rel="apple-touch-icon" sizes="76x76" href="{{ url('assets/dist/ios/logo-76.png') }}">
	<link rel="apple-touch-icon" sizes="120x120" href="{{ url('assets/dist/ios/logo-120.png') }}">
	<link rel="apple-touch-icon" sizes="152x152" href="{{ url('assets/dist/ios/logo-152.png') }}">

	<link rel="stylesheet" href="{{ url('lib/bootstrap/dist/css/bootstrap.min.css') }}">
	<link rel="stylesheet" href="{{ url('lib/alk-life/css/alk-life.min.css') }}">
	<link rel="stylesheet" href="{{ url('lib/sweetalert/dist/sweetalert.css') }}">
	<link rel="stylesheet" href="{{ url('css/dist/main.min.css') }}">

		<form id="main-form" action="details" method="post">

გამოცდის ადგილები (თსუ)

					<input type="text" id="input-name" name="name" class="form-control input-lg floatlabel" placeholder="სახელი" autocapitalize="none" required autofocus>

					<input type="text" id="input-last" name="last" class="form-control input-lg floatlabel" placeholder="გვარი" autocapitalize="none" required>

					<input type="submit" class="btn-block" value="Go!">

						@foreach ($dates as $date)
							{{ $date['title'] }}
							@if ($date['active'])
								<input type="hidden" name="date" class="input-dynamic-date" value="{{ $date['value'] }}">
							@endif
						@endforeach

					{{ $time }}
					<input type="hidden" name="time" class="input-dynamic-time" value="{{ $time }}">

		</form>

				Made with ♥ by Stichoza, vectors by Freepik

				School vector designed by Freepik

				Made with ♥ by Stichoza
				· Fork it on GitHub

		+
		+
		<input type="tel" class="input-dynamic-time input-sweetalert-time" value="{{ $time }}">
		-
		-


text:
if [ "$1" == "" ]; then
    TARGET_HOSTNAME=$HOSTNAME
else
    TARGET_HOSTNAME=$1
fi

# fix hostname
sed -ri s/localhost/$TARGET_HOSTNAME/ /etc/hadoop/conf.mine/core-site.xml
sed -ri s/localhost/$TARGET_HOSTNAME/ /etc/hadoop/conf.mine/hdfs-site.xml
sed -ri s/localhost/$TARGET_HOSTNAME/ /etc/hadoop/conf.mine/mapred-site.xml
sed -ri s/localhost/$TARGET_HOSTNAME/ /etc/hadoop/conf.mine/yarn-site.xml


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dialogflow.v2.model;

/**
 * Configuration for the version.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowCxV3EnvironmentVersionConfig extends com.google.api.client.json.GenericJson {

  /**
   * Required. Format: projects//locations//agents//flows//versions/.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String version;

  /**
   * Required. Format: projects//locations//agents//flows//versions/.
   * @return value or {@code null} for none
   */
  public java.lang.String getVersion() {
    return version;
  }

  /**
   * Required. Format: projects//locations//agents//flows//versions/.
   * @param version version or {@code null} for none
   */
  public GoogleCloudDialogflowCxV3EnvironmentVersionConfig setVersion(java.lang.String version) {
    this.version = version;
    return this;
  }

  @Override
  public GoogleCloudDialogflowCxV3EnvironmentVersionConfig set(String fieldName, Object value) {
    return (GoogleCloudDialogflowCxV3EnvironmentVersionConfig) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDialogflowCxV3EnvironmentVersionConfig clone() {
    return (GoogleCloudDialogflowCxV3EnvironmentVersionConfig) super.clone();
  }

}


text:
package com.soulgalore.servlet.thumbnail;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutionException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 *

 * A resize image servlet, that can resize an image on demand. Will resize an
 * already existing original image to different configured size(s).
 *
 * User scenario:
 *

 *

 *
Access the servlet with a name that holds the new size of the original
 * image /SERVLET/?img=MY_ORIGINAL_IMAGE-120x94.png (need to be of the
 * format of {@link Thumbnail#MATCHING_NAME_REGEXP}

 *
The servlet will check if the original image exist (named
 * MY_ORIGINAL_IMAGE.png in this example), meaning it is a valid request

 *
if the new size is configured, the image can

 *
The servlet will check if that size of the image already exist on disk,
 * if it exist, it will be returned.
 *

 *
If the images don't exist, the thumbnail of the requested size will be
 * created by the calling thread. The creation is thread safe and only one thread
 * can create the one & same thumbnail (but other threads can create others, at the same time).

 *
The image is returned

 *

 *
 *

 * The servlet needs to be configured by the following parameters:
 *

 *
{@link #INIT_PARAMETER_VALID_SIZES} that will configure the valid image
 * sizes. Configure by the format: 460x360,220x172,120x94

 *
{@link #INIT_PARAMETER_ORIGINAL_WEB_DIR} that is the relative path to the
 * orignals web folder.

 *
{@link #INIT_PARAMETER_THUMB_WEB_DIR} that is the base web dir for the
 * thumbnails.

 *
{@link #INIT_PARAMETER_IMG_REQUEST_PARAMETER} that is the name of the
 * request parameter that will hold the value of the image that you want to
 * fetch.

 *

 *

 *
 *

 * Note: No cache header is added within the servlet.
 *

 *
 *
 *
 *
 */
public class ThumbnailServlet extends HttpServlet {

	/**
	 * The name of the servlet init parameter for the request parameter.
	 */
	private static final String INIT_PARAMETER_IMG_REQUEST_PARAMETER = "image-request-parameter-name";

	/**
	 * The name of the servlet init parameter for where the original images are
	 * located.
	 */
	private static final String INIT_PARAMETER_ORIGINAL_WEB_DIR = "originals-dir";
	/**
	 * The name of the servlet init parameter for the base dir for thumbnail
	 * images.
	 */
	private static final String INIT_PARAMETER_THUMB_WEB_DIR = "thumbs-dir";

	/**
	 * The name of the servlet init parameter for valid image sizes.
	 */
	private static final String INIT_PARAMETER_VALID_SIZES = "valid-sizes";

	private static final long serialVersionUID = -2092311650388075782L;

	/**
	 * Only a number to make sure thumbnails aren't created more than once (at a
	 * time).
	 */
	private static final int CACHE_MAX_SIZE = 10000;

	/**
	 * My logger.
	 */
	private final transient Logger logger = LoggerFactory
			.getLogger(ThumbnailServlet.class);

	/**
	 * Cache.
	 */
	private final Cache<Thumbnail, File> cache = CacheBuilder.newBuilder()
			.maximumSize(CACHE_MAX_SIZE).build();

	/**
	 * The factory classes, used to create thumbnail objects.
	 */
	private transient ThumbnailFetcher factory;

	/**
	 * Directory for originals.
	 */
	private String originalsDir;

	/**
	 * The name of the request parameter.
	 */
	private String requestParameterName;

	/**
	 * Web thumbnail directory.
	 */
	private String thumbsDir;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		final String sizes = config
				.getInitParameter(INIT_PARAMETER_VALID_SIZES);

		final Set<String> validSizes = new HashSet<String>();
		if (sizes != null) {
			final StringTokenizer token = new StringTokenizer(sizes, ",");
			while (token.hasMoreTokens()) {
				validSizes.add(token.nextToken());
			}
		} else
			logger.info("Running " + getServletName()
					+ " without configured valid "
					+ "sizes, use the servlet init parameter "
					+ INIT_PARAMETER_VALID_SIZES + " to set it up.");

		requestParameterName = config
				.getInitParameter(INIT_PARAMETER_IMG_REQUEST_PARAMETER);
		thumbsDir = config.getInitParameter(INIT_PARAMETER_THUMB_WEB_DIR);
		originalsDir = config.getInitParameter(INIT_PARAMETER_ORIGINAL_WEB_DIR);

		factory = new ThumbnailFetcher(getServletContext().getRealPath("/")
				+ originalsDir, getServletContext()
				.getRealPath("/" + thumbsDir), validSizes);

		logger.info(getServletName()
				+ " is configured with request parameter name:"
				+ requestParameterName + " originalsDir:" + originalsDir
				+ " thumbDir:" + thumbsDir + " and valid sizes:"
				+ (sizes == null ? "" : sizes));
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		final String thumbnailName = req.getParameter(requestParameterName);

		if (logger.isDebugEnabled())
			logger.debug("Get thumbnail named {}", thumbnailName);

		if (thumbnailName == null) {
			if (logger.isDebugEnabled())
				logger.debug("Accessed with no thumbnail name");
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
					Thumbnail.ERROR_MESSAGE_THUMBNAIL_NAME_IS_NOT_VALID);
			return;
		}

		try {
			final Thumbnail thumbnail = factory.get(thumbnailName);

			if (!doTheThumbnailExist(thumbnail)) {

				try {
					// kind of a simple hack to make sure only
					// one thread creates the actual thumbnail,
					// think the Memoizer
					cache.get(thumbnail, new ImageMagickFileThumbnailCreator(
							thumbnail));
				} catch (ExecutionException e) {
					if (logger.isErrorEnabled())
						logger.error("Couldn't create thumbnail", e.getCause());
					resp.sendError(
							HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
							Thumbnail.ERROR_MESSAGE_THUMBNAIL_NOT_CREATED);
					return;
				}
			}
			returnTheThumbnail(req, resp, thumbnail);
		} catch (ThumbnailException e1) {
			if (logger.isDebugEnabled())
				logger.debug("Thumbnail not created beacuse {}", e1.getReason());
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e1.getReason());
			return;
		} catch (IOException e) {
			if (logger.isErrorEnabled())
				logger.error("Couldn't create thumbnail", e);
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					Thumbnail.ERROR_MESSAGE_THUMBNAIL_NOT_CREATED);
			return;
		}

	}

	/**
	 * Check if the thumbnail already exists.
	 *
	 * @param thumbnail
	 *            the thumbnail
	 * @return true if the thumbnails exist
	 */
	protected boolean doTheThumbnailExist(Thumbnail thumbnail) {
		final File theImageThumbnail = new File(thumbnail.getDestinationDir()
				+ thumbnail.getImageFileName());

		return theImageThumbnail.exists();
	}

	/**
	 * Return the thumbnail to the user.
	 *
	 * @param req
	 *            the request
	 * @param resp
	 *            the response
	 * @param thumbnail
	 *            the thumbnail that will be returned
	 * @throws ServletException
	 *             if the thumbnail couldn't be delivered
	 * @throws IOException
	 *             if the thumbnail couldn't be delivered
	 */
	protected void returnTheThumbnail(HttpServletRequest req,
			HttpServletResponse resp, Thumbnail thumbnail)
			throws ServletException, IOException {
		final RequestDispatcher rd = getServletContext().getRequestDispatcher(
				"/" + thumbsDir + thumbnail.getGeneratedFilePath()
						+ thumbnail.getImageFileName());
		rd.forward(req, resp);
	}
}


text:
(function () {
    'use strict';

    // from http://stackoverflow.com/questions/14859266/input-autofocus-attribute
    angular.module('ng').directive('ngFocus', function($timeout) {
        return {
            link: function ( scope, element, attrs ) {
                scope.$watch( attrs.ngFocus, function ( val ) {
                    if ( angular.isDefined( val ) && val ) {
                        $timeout( function () { element[0].focus(); } );
                    }
                }, true);

                element.bind('blur', function () {
                    if ( angular.isDefined( attrs.ngFocusLost ) ) {
                        scope.$apply( attrs.ngFocusLost );

                    }
                });
            }
        };
    });

    var directives = angular.module('bid.directives', []);

    directives.directive('patientJqgridSearch', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var elem = angular.element(element),
                    table = angular.element('#' + attrs.patientJqgridSearch),
                    eventType = elem.data('event-type'),
                    timeoutHnd,
                    filter = function (time) {
                        var field = elem.data('search-field'),
                            value = elem.data('search-value'),
                            type = elem.data('field-type') || 'string',
                            url = parseUri(jQuery('#' + attrs.patientJqgridSearch).jqGrid('getGridParam', 'url')),
                            query = {},
                            params = '?',
                            array = [],
                            prop;

                        for (prop in url.queryKey) {
                            if (prop !== field) {
                                query[prop] = url.queryKey[prop];
                            }
                        }

                        switch (type) {
                        case 'boolean':
                            query[field] = url.queryKey[field].toLowerCase() !== 'true';

                            if (query[field]) {
                                elem.find('i').removeClass('icon-ban-circle').addClass('icon-ok');
                            } else {
                                elem.find('i').removeClass('icon-ok').addClass('icon-ban-circle');
                            }
                            break;
                        case 'array':
                            if (elem.children().hasClass("icon-ok")) {
                                elem.children().removeClass("icon-ok").addClass("icon-ban-circle");
                            } else if (elem.children().hasClass("icon-ban-circle")) {
                                elem.children().removeClass("icon-ban-circle").addClass("icon-ok");
                                array.push(value);
                            }
                            angular.forEach(url.queryKey[field].split(','), function (val) {
                                if (angular.element('#' + val).children().hasClass("icon-ok")) {
                                    array.push(val);
                                }
                            });

                            query[field] = array.join(',');
                            break;
                        default:
                            query[field] = elem.val();
                        }

                        for (prop in query) {
                            params += prop + '=' + query[prop] + '&';
                        }

                        params = params.slice(0, params.length - 1);

                        if (timeoutHnd) {
                            clearTimeout(timeoutHnd);
                        }

                        timeoutHnd = setTimeout(function () {
                            jQuery('#' + attrs.patientJqgridSearch).jqGrid('setGridParam', {
                                page: 1,
                                url: '../bid/vax' /* + params */
                            }).trigger('reloadGrid');
                        }, time || 0);
                    };

                switch (eventType) {
                case 'keyup':
                    elem.keyup(function () {
                        filter(500);
                    });
                    break;
                case 'change':
                    elem.change(filter);
                    break;
                default:
                    elem.click(filter);
                }
            }
        };
    });

    directives.directive('patientGrid', function($compile, $http, $templateCache) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                try {
                    if (typeof($('#outsidePatientTable')[0].grid) !== 'undefined') {
                        return;
                    }
                }
                catch (e) {
                    return;
                }

                var elem = angular.element(element), filters;

                elem.jqGrid({
                    url: '../bid/vax',
                    datatype: 'json',
                    jsonReader:{
                        repeatitems:false
                    },
                    colModel: [{
                        name: 'externalId',
                        index: 'externalId',
                        width: 50
                    }, {
                        name: 'lastName',
                        index: 'lastName',
                        width: 50
                    }, {
                        name: 'firstName',
                        index: 'firstName',
                        width: 50
                    }, {
                        name: 'dateOfBirth',
                        index: 'dateOfBirth',
                        width: 80
                    }, {
                        name: 'gender',
                        index: 'gender',
                        width: 40
                    }, {
                        name: 'vaxSchedule',
                        index: 'vaxSchedule',
                        width: 50,
                        sortable: false,
                        formatter: function() {
                            return '<button ng-click="showSchedule()">View</button>';
                        }
                    }],
                    pager: '#' + attrs.patientGrid,
                    sortname: 'externalId',
                    sortorder: 'asc',
                    viewrecords: true,
                    gridComplete: function () {
                        angular.forEach(['externalId', 'lastName', 'firstName', 'dateOfBirth', 'gender',
                            'vaxSchedule'], function (value) {
                            elem.jqGrid('setLabel', value, scope.msg('bid.patient.' + value));
                        });
                        angular.forEach(elem.find('button'), function(value) {
                            $compile(value)(scope);
                        });
                        $('#outsidePatientTable').children('div').width('100%');
                        $('.ui-jqgrid-htable').addClass("table-lightblue");
                        $('.ui-jqgrid-btable').addClass("table-lightblue");
                        $('.ui-jqgrid-htable').width('100%');
                        $('.ui-jqgrid-bdiv').width('100%');
                        $('.ui-jqgrid-hdiv').width('100%');
                        $('.ui-jqgrid-view').width('100%');
                        $('#t_patientTable').width('auto');
                        $('.ui-jqgrid-pager').width('100%');
                        $('.ui-jqgrid-hbox').css({'padding-right':'0'});
                        $('.ui-jqgrid-hbox').width('100%');
                        $('#outsidePatientTable').children('div').each(function() {
                            $(this).find('table').width('100%');
                        });
                    }
                });
            }
        };
    });

    directives.directive('vaxGrid', function($compile, $http, $templateCache) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                try {
                    if (typeof($('#outsideVaxTable')[0].grid) !== 'undefined') {
                        return;
                    }
                }
                catch (e) {
                    return;
                }

                var elem = angular.element(element), filters;

                elem.jqGrid({
                    url: '../bid/vax',
                    datatype: 'json',
                    jsonReader:{
                        repeatitems:false
                    },
                    colModel: [{
                        name: 'externalId',
                        index: 'externalId',
                        width: 50
                    }, {
                        name: 'lastName',
                        index: 'lastName',
                        width: 50
                    }, {
                        name: 'firstName',
                        index: 'firstName',
                        width: 50
                    }, {
                        name: 'dateOfBirth',
                        index: 'dateOfBirth',
                        width: 80
                    }, {
                        name: 'gender',
                        index: 'gender',
                        width: 40
                    }, {
                        name: 'vaxSchedule',
                        index: 'vaxSchedule',
                        width: 50
                        }
                    }],
                    pager: '#' + attrs.vaxGrid,
                    sortname: 'externalId',
                    sortorder: 'asc',
                    viewrecords: true,
                    gridComplete: function () {
                        angular.forEach(['externalId', 'lastName', 'firstName', 'dateOfBirth', 'gender',
                            'vaxSchedule'], function (value) {
                            elem.jqGrid('setLabel', value, scope.msg('bid.patient.' + value));
                        });
                        $('#outsideVaxTable').children('div').width('100%');
                        $('.ui-jqgrid-htable').addClass("table-lightblue");
                        $('.ui-jqgrid-btable').addClass("table-lightblue");
                        $('.ui-jqgrid-htable').width('100%');
                        $('.ui-jqgrid-bdiv').width('100%');
                        $('.ui-jqgrid-hdiv').width('100%');
                        $('.ui-jqgrid-view').width('100%');
                        $('#t_patientTable').width('auto');
                        $('.ui-jqgrid-pager').width('100%');
                        $('.ui-jqgrid-hbox').css({'padding-right':'0'});
                        $('.ui-jqgrid-hbox').width('100%');
                        $('#outsideVaxTable').children('div').each(function() {
                            $(this).find('table').width('100%');
                        });
                    }
                });
            }
        };
    });

}());


text:
# Get Started

Here is a **short tour** for this **Amazing** ORM 😉

The full code is in [sample.cpp](../sample/sample.cpp).

## Preparation

Before we start, Include **src** into your Project:

- `ORMLite.h`
- **SQLite3** Dependency

> If you haven't installed **SQLite3**,
> you can find the zip file of `sqlite3.h` and `sqlite3.c` in `/src`

## Including *ORM Lite*

``` cpp
#include "ORMLite.h"
using namespace BOT_ORM;
using namespace BOT_ORM::Expression;

struct UserModel
{
    int user_id;
    std::string user_name;
    double credit_count;

    Nullable<int> age;
    Nullable<double> salary;
    Nullable<std::string> title;

    // Inject ORM-Lite into this Class :-)
    ORMAP ("UserModel", user_id, user_name, credit_count,
           age, salary, title);
};
```

`Nullable<T>` helps us construct `Nullable` Value in C++,
which is described in the [Document](orm-lite.md) 😁

In this sample, `ORMAP ("UserModel", ...)` do that:
- `Class UserModel` will be mapped into `TABLE UserModel`;
- NOT `Nullable` members will be mapped as `NOT NULL`;
- `int, double, std::string` will be mapped into
  `INT, REAL, TEXT` respectively;
- The first entry `id` will be set as the **Primary Key** of the Table;

And then we define and inject other 2 Classes in this sample:

``` cpp
struct SellerModel
{
    int seller_id;
    std::string seller_name;
    double credit_count;

    // Inject ORM-Lite into this Class :-)
    ORMAP ("SellerModel", seller_id, seller_name, credit_count);
};

struct OrderModel
{
    int order_id;
    int user_id;
    int seller_id;
    std::string product_name;
    Nullable<double> fee;

    // Inject ORM-Lite into this Class :-)
    ORMAP ("OrderModel", order_id, user_id, seller_id,
           product_name, fee);
};
```

## Field Extracting

- `FieldExtractor`

``` cpp
// Define more Query Helper Objects and their Field Extractor
UserModel user;
SellerModel seller;
OrderModel order;
auto field = FieldExtractor { user, seller, order };

// Extract Field from 'field'
// For example: field (user.user_name)
//   => Retrieve the field of user_name in UserModel table
```

## Working on *Database* with *ORMapper*

- `ORMapper`

``` cpp
// Open a Connection with 'sample.db'
ORMapper mapper ("sample.db");
```

## Create or Drop Tables

- `ORMapper.CreateTbl`
- `ORMapper.DropTbl`
- `Expression`

``` cpp
// Create Table with Constraints
mapper.CreateTbl (
    UserModel {},
    Constraint::Default (field (user.salary), 1000.0));

// Remarks:
// CREATE TABLE UserModel(
//   user_id INTEGER NOT NULL PRIMARY KEY,
//   user_name TEXT NOT NULL,
//   credit_count REAL NOT NULL,
//   age INTEGER,
//   salary REAL DEFAULT 1000,
//   title TEXT);

mapper.CreateTbl (
    SellerModel {},
    Constraint::Check (field (seller.credit_count) > 0.0));

// Remarks:
// CREATE TABLE SellerModel(
//   seller_id INTEGER NOT NULL PRIMARY KEY,
//   seller_name TEXT NOT NULL,
//   credit_count REAL NOT NULL,
//   CHECK (credit_count > 0));

mapper.CreateTbl (
    OrderModel {},
    Constraint::Reference (
        field (order.user_id), field (user.user_id)),
    Constraint::Reference (
        field (order.seller_id), field (seller.seller_id)),
    Constraint::Unique (Constraint::CompositeField {
        field (order.product_name), field (order.fee) }));

// Remarks:
// CREATE TABLE OrderModel(
//   order_id INTEGER NOT NULL PRIMARY KEY,
//   user_id INTEGER NOT NULL,
//   seller_id INTEGER NOT NULL,
//   product_name TEXT NOT NULL,
//   fee REAL,
//   FOREIGN KEY (user_id) REFERENCES UserModel(user_id),
//   FOREIGN KEY (seller_id) REFERENCES SellerModel(seller_id),
//   UNIQUE (product_name, fee));

...

// Drop Tables
mapper.DropTbl (UserModel {});
mapper.DropTbl (SellerModel {});
mapper.DropTbl (OrderModel {});
```

#### User Model

| user_id| user_name| credit_count|    age|  salary|  title|
|--------|----------|-------------|-------|--------|-------|
|       0|      John|          0.2|     21|  1000.0| `null`|
|       1|      Jack|          0.4| `null`|    3.14| `null`|
|       2|      Jess|          0.6| `null`|  1000.0|    Dr.|
|     ...|       ...|          ...|    ...|     ...|    ...|

#### Seller Model

| seller_id| seller_name| credit_count|
|----------|------------|-------------|
|       ...|         ...|          ...|

#### Order Model

| order_id| user_id| seller_id| product_name| fee|
|---------|--------|----------|-------------|----|
|      ...|     ...|       ...|          ...| ...|

## Basic CRUD

- `ORMapper.Insert` (Create)
- `ORMapper.Query`  (Read)
- `ORMapper.Update` (Update)
- `ORMapper.Delete` (Delete)
- `ORMapper.Transaction`
- `Table Constraints`

``` cpp
std::vector<UserModel> initObjs =
{
    { 0, "John", 0.2, 21, nullptr, nullptr },
    { 1, "Jack", 0.4, nullptr, 3.14, nullptr },
    { 2, "Jess", 0.6, nullptr, nullptr, std::string ("Dr.") }
};

// Insert Values with Primary Key
for (const auto &obj : initObjs)
    mapper.Insert (obj);

initObjs[1].salary = nullptr;
initObjs[1].title = "St.";

// Update Entity by Primary Key (WHERE UserModel.id = 1)
mapper.Update (initObjs[1]);

// Delete Entity by Primary Key (WHERE UserModel.id = 2)
mapper.Delete (initObjs[2]);

// Transactional Statements
try
{
    mapper.Transaction ([&] ()
    {
        mapper.Delete (initObjs[0]);  // OK
        mapper.Insert (UserModel {
            1, "Joke", 0, nullptr, nullptr, nullptr
        });  // Failed
    });
}
catch (const std::exception &ex)
{
    // If any statement Failed, throw an exception

    std::cout << ex.what () << std::endl;
    // SQL error: 'UNIQUE constraint failed: UserModel.id'

    // Remarks:
    // mapper.Delete (initObjs[0]); will not applied :-)
}

// Select All to List
auto result1 = mapper.Query (UserModel {}).ToList ();

// decltype (result1) == std::list<UserModel>
// result1 = [{ 0, 0.2, "John", 21,   1000, null  },
//            { 1, 0.4, "Jack", null, null, "St." }]

// Table Constraints
try
{
    // Insert Values without Primary Key
    mapper.Insert (SellerModel { 0, "John Inc.", 0.0 }, false);
}
catch (const std::exception &ex)
{
    std::cout << ex.what () << std::endl;
    // SQL error: 'CHECK constraint failed: SellerModel'
}
```

## Batch Operations

- `ORMapper.InsertRange`
- `ORMapper.UpdateRange`

``` cpp
std::vector<UserModel> dataToSeed;
for (int i = 50; i < 100; i++)
    dataToSeed.emplace_back (UserModel {
        i, "July_" + std::to_string (i), i * 0.2,
        nullptr, nullptr, nullptr
});

// Insert by Batch Insert
mapper.Transaction ([&] () {
    mapper.InsertRange (dataToSeed);
});

for (size_t i = 0; i < 20; i++)
{
    dataToSeed[i + 30].age = 30 + (int) i / 2;
    dataToSeed[i + 20].title = "Mr. " + std::to_string (i);
}

// Update by Batch Update
mapper.Transaction ([&] () {
    // Note that: it will erase the default value of 'salary'
    mapper.UpdateRange (dataToSeed);
});
```

## Single-Table Query

- `Expression`
- `Aggregate`
- `Queryable.Where`
- `Queryable.OrderBy`
- `Queryable.Take`
- `Queryable.Skip`
- `Queryable.Select`

``` cpp
// Select by Condition
auto result2 = mapper.Query (UserModel {})
    .Where (
        field (user.user_name) & std::string ("July%") &&
        (field (user.age) >= 32 &&
         field (user.title) != nullptr)
    )
    .OrderByDescending (field (user.age))
    .OrderBy (field (user.user_id))
    .Take (3)
    .Skip (1)
    .ToVector ();

// Remarks:
// SELECT * FROM UserModel
// WHERE (user_name LIKE 'July%' AND
//       (age >= 32 AND title IS NOT NULL))
// ORDER BY age DESC, user_id
// LIMIT 3 OFFSET 1

// decltype (result2) == std::vector<UserModel>
// result2 = [{ 89, 17.8, "July_89", 34, null, "Mr. 19" },
//            { 86, 17.2, "July_86", 33, null, "Mr. 16" },
//            { 87, 17.4, "July_87", 33, null, "Mr. 17" }]

// Calculate Aggregate Function
auto avg = mapper.Query (UserModel {})
    .Where (field (user.user_name) & std::string ("July%"))
    .Aggregate (Avg (field (user.credit_count)));

// Remarks:
// SELECT AVG (credit_count) FROM UserModel
// WHERE (user_name LIKE 'July%')

// avg = 14.9

auto count = mapper.Query (UserModel {})
    .Where (field (user.user_name) | std::string ("July%"))
    .Aggregate (Count ());

// Remarks:
// SELECT COUNT (*) FROM UserModel
// WHERE (user_name NOT LIKE 'July%')

// count = 2
```

## Update / Delete by Statement

- `Expression`
- `ORMapper.Update`
- `ORMapper.Delete`

``` cpp
// Update by Condition
mapper.Update (
    UserModel {},
    (field (user.age) = 10) &&
    (field (user.credit_count) = 1.0),
    field (user.user_name) == std::string ("July"));

// Remarks:
// UPDATE UserModel SET age = 10,credit_count = 1.0
// WHERE (user_name = 'July')

// Delete by Condition
mapper.Delete (UserModel {},
               field (user.user_id) >= 90);

// Remarks:
// DELETE FROM UserModel WHERE (id >= 90)
```

## Multi-Table Query

- `Expression`
- `Aggregate`
- `Queryable.Join`
- `Queryable.LeftJoin`
- `Queryable.Select`
- `Queryable.GroupBy`
- `Queryable.Having`
- `Queryable.Union`

``` cpp
mapper.Transaction ([&] ()
{
    for (size_t i = 0; i < 50; i++)
    {
        mapper.Insert (
            SellerModel { (int) i + 50,
            "Seller " + std::to_string (i), 3.14 });
        mapper.Insert (
            OrderModel { 0,
            (int) i / 2 + 50,
            (int) i / 4 + 50,
            "Item " + std::to_string (i),
            i * 0.5 }, false);
    }
});

// Join Tables for Query
auto joinedQuery = mapper.Query (UserModel {})
    .Join (OrderModel {},
           field (user.user_id) ==
           field (order.user_id))
    .LeftJoin (SellerModel {},
               field (seller.seller_id) ==
               field (order.seller_id))
    .Where (field (user.user_id) >= 65);

// Get Result to List
auto result3 = joinedQuery.ToList ();

// Remarks:
// SELECT * FROM UserModel
//               JOIN OrderModel
//               ON UserModel.user_id=OrderModel.user_id
//               LEFT JOIN SellerModel
//               ON SellerModel.seller_id=OrderModel.seller_id
// WHERE (UserModel.user_id>=65)

// decltype (result3) == std::list<std::tuple<Nullable<..>, ..>>
// result3 = [(65, "July_65", 13, null, null, null,
//             31, 65, 57, "Item 30", 15,
//             57, "Seller 7", 3.14),
//            (65, "July_65", 13, null, null, null,
//             32, 65, 57, "Item 31", 15.5,
//             57, "Seller 7", 3.14),
//            ... ]

// Group & Having ~
auto result4 = joinedQuery
    .Select (field (order.user_id),
             field (user.user_name),
             Avg (field (order.fee)))
    .GroupBy (field (user.user_name))
    .Having (Sum (field (order.fee)) >= 40.5)
    .Skip (3)
    .ToList ();

// Remarks:
// SELECT OrderModel.user_id,
//        UserModel.user_name,
//        AVG (OrderModel.fee)
// FROM UserModel
//      JOIN OrderModel
//      ON UserModel.user_id=OrderModel.user_id
//      LEFT JOIN SellerModel
//      ON SellerModel.seller_id=OrderModel.seller_id
// WHERE (UserModel.user_id>=65)
// GROUP BY UserModel.user_name
// HAVING SUM (OrderModel.fee)>=40.5
// LIMIT ~0 OFFSET 3

// decltype (result4) == std::list<std::tuple<Nullable<..>, ..>>
// result4 = [(73, "July_73", 23.25),
//            (74, "July_74", 24.25)]

// Compound Select
// Results are Nullable-Tuples
auto result5 = mapper.Query (OrderModel {})
    .Select (field (order.product_name), field (order.user_id))
    .Where (field (order.user_id) == 50)
    .Union (
        joinedQuery
        .Select (field (user.user_name), field (order.order_id))
    )
    .Take (4)
    .ToList ();

// Remarks:
// SELECT OrderModel.product_name,
//        OrderModel.user_id
// FROM OrderModel
//      WHERE (OrderModel.user_id==50)
// UNION
// SELECT UserModel.user_name,
//        OrderModel.order_id
// FROM UserModel
//      JOIN OrderModel
//      ON UserModel.user_id=OrderModel.user_id
//      LEFT JOIN SellerModel
//      ON SellerModel.seller_id=OrderModel.seller_id
//      WHERE (UserModel.user_id>=65)
// LIMIT 4;

// decltype (result5) == std::list<std::tuple<Nullable<..>, ..>>
// result5 = [("Item 0", 50),
//            ("Item 1", 50),
//            ("July_65", 31),
//            ("July_65", 32)]
```

## Wrapping Up

This little ORM is very cool, enjoy it. 😇

See the **[Full Document Here](orm-lite.md)**.


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es6id: 21.2.5.11
description: Behavior when error thrown while coercing `string` argument
info: >
    [...]
    3. Let S be ToString(string).
    4. ReturnIfAbrupt(S).
features: [Symbol.split]
---*/

var uncoercibleObj = {
  toString: function() {
    throw new Test262Error();
  }
};

assert.throws(Test262Error, function() {
  /./[Symbol.split](uncoercibleObj);
});

assert.throws(TypeError, function() {
  /./[Symbol.split](Symbol.split);
});


text:
export function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text,
  };
}

export function deleteTodo(index) {
  return {
    type: 'DELETE_TODO',
    index,
  };
}

function receiveTodos(todos) {
  return {
    type: 'RECEIVE_TODOS',
    todos,
  };
}

export function getTodos() {
  return async (dispatch, getState, { graphqlRequest }) => {
    const { data } = await graphqlRequest('{todo{text}}');
    dispatch(receiveTodos(data.todo));
  };
}

export function showEditor() {
  return {
    type: 'SHOW_EDITOR',
  };
}

export function hideEditor() {
  return {
    type: 'HIDE_EDITOR',
  };
}


text:
package org.mcisb.ontology.kegg;

import java.util.*;
import org.junit.*;
import org.mcisb.ontology.*;

/**
 *
 * @author Neil Swainston
 */
public class KeggGenomeUtilsTest
{
	/**
	 *
	 */
	private KeggGenomeUtils utils = KeggGenomeUtils.getInstance();

	/**
	 *
	 * @throws Exception
	 */
	public KeggGenomeUtilsTest() throws Exception
	{
		// No implementation.
	}

	/**
	 *
	 * @throws Exception
	 */
	@Test
	public void getOrganism() throws Exception
	{
		final OntologyTerm ontologyTerm = utils.getOntologyTerm( "sce" ); //$NON-NLS-1$
		test( ontologyTerm );
	}

	/**
	 *
	 * @throws Exception
	 */
	@Test
	public void getOrganismFromTaxonomyId() throws Exception
	{
		// Assert.assertTrue( utils.getOrganism( 4565 ).getId().equals( "etae" ) ); //$NON-NLS-1$
		Assert.assertTrue( utils.getOrganism( 559292 ).getId().equals( "sce" ) ); //$NON-NLS-1$
	}

	/**
	 *
	 * @throws Exception
	 */
	@SuppressWarnings("static-method")
	@Test
	public void getOrganismIds() throws Exception
	{
		Assert.assertTrue( Arrays.binarySearch( KeggGenomeUtils.getOrganismIds(), "etae" ) != -1 ); //$NON-NLS-1$
	}

	/**
	 *
	 * @param ontologyTerm
	 * @throws Exception
	 */
	public void test( final OntologyTerm ontologyTerm ) throws Exception
	{
		final Collection<String> synonyms = new HashSet<>( Arrays.asList( "YEAST", "559292" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		final String NAME = "Saccharomyces cerevisiae S288c"; //$NON-NLS-1$
		final OntologyTerm taxonomyTerm = OntologyUtils.getInstance().getOntologyTerm( Ontology.TAXONOMY, "559292" ); //$NON-NLS-1$
		Assert.assertTrue( ontologyTerm.getSynonyms().equals( synonyms ) );
		Assert.assertTrue( ontologyTerm.getName().equals( NAME ) );
		Assert.assertTrue( utils.getOrganisms().contains( ontologyTerm ) );
		Assert.assertTrue( ontologyTerm.getXrefs().keySet().contains( taxonomyTerm ) );
	}
}


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

using Zu.WebBrowser.BrowserOptions;

namespace Zu.Chrome
{
    public class ChromeDriverWebStorage: IWebStorage
    {
        private IAsyncChromeDriver _asyncChromeDriver;

        public ChromeDriverWebStorage(IAsyncChromeDriver asyncChromeDriver)
        {
            _asyncChromeDriver = asyncChromeDriver;
        }

        public ILocalStorage LocalStorage => throw new System.NotImplementedException();

        public ISessionStorage SessionStorage => throw new System.NotImplementedException();
    }
}


text:
<?php

namespace BBC;

/**
 * Class HtmlParser
 *
 * @package BBC
 */
class HtmlParser
{
	/** @var array tags that are stand alone */
	protected $empty_tags = array('br', 'hr');
	/** @var array tags we will allow */
	protected $closable_tags = array('b', 'u', 'i', 's', 'em', 'ins', 'del', 'pre', 'blockquote');

	/**
	 * HtmlParser constructor.
	 */
	public function __construct()
	{
		// Commented only for testing purposes
		//require_once(SUBSDIR . '/Attachments.subs.php');

		$empty_tags = $this->empty_tags;
		$closable_tags = $this->closable_tags;

		call_integration_hook('integrate_html_parser_load', array(&$empty_tags, &$closable_tags));
		$this->empty_tags = $empty_tags;
		$this->closable_tags = $closable_tags;
	}

	/**
	 * Calls the functions to parse the handful of allowable HTML tags
	 *
	 * @param $data
	 */
	public function parse($data)
	{
		$data = $this->anchorTags($data);

		$data = $this->emptyTags($data);

		$data = $this->closableTags($data);

		return $this->imageTags($data);
	}

	/**
	 * Sets the width/height of image tags
	 *
	 * @param int $width
	 * @param int $height
	 *
	 * @return $this
	 */
	public function setImageWidthHeight($width, $height)
	{
		$this->image_width = (int) $width;
		$this->image_height = (int) $height;

		return $this;
	}

	/**
	 * Convert <a tags to [url
	 *
	 * @param $data
	 */
	protected function anchorTags($data)
	{
		// Changes empty_tags as $tag)
		{
			$data = str_replace(array('<' . $tag . '>', '<' . $tag . '/>', '<' . $tag . ' />'), '[' . $tag . ' /]', $data);
		}

		return $data;
	}

	/**
	 * Converts simple closable tags to equivalent BBC codes
	 *
	 * @param $data
	 */
	protected function closableTags($data)
	{
		foreach ($this->closable_tags as $tag)
		{
			$diff = substr_count($data, '<' . $tag . '>') - substr_count($data, '</' . $tag . '>');
			$data = strtr($data, array('<' . $tag . '>' => '<' . $tag . '>', '</' . $tag . '>' => '</' . $tag . '>'));

			// Stray open tags, close them all!
			if ($diff > 0)
			{
				$data = $data . str_repeat('</' . $tag . '>', $diff);
			}
		}

		return $data;
	}

	/**
	 * Converts <img tags to [IMG bbc code while handing height and width attributes
	 *
	 * @param $data
	 */
	protected function imageTags($data)
	{
		global $modSettings;

		// Do  - with security... action= -> action-.
		preg_match_all('~<img\s+src=((?:")?)((?:https?://)\S+?)\\1(?:\s+alt=(".*?"|\S*?))?(?:\s?/)?>~i', $data, $matches, PREG_PATTERN_ORDER);
		if (!empty($matches[0]))
		{
			$replaces = array();
			require_once(SUBSDIR . '/Attachments.subs.php');
			foreach ($matches[2] as $match => $imgtag)
			{
				$alt = empty($matches[3][$match]) ? '' : ' alt=' . preg_replace('~^"|"$~', '', $matches[3][$match]);

				// Remove action= from the URL - no funny business, now.
				if (preg_match('~action(=|%3d)(?!dlattach)~i', $imgtag) !== 0)
				{
					$imgtag = preg_replace('~action(?:=|%3d)(?!dlattach)~i', 'action-', $imgtag);
				}

				// Check if the image is larger than allowed.
				// @todo - We should seriously look at deprecating some of this in favour of CSS resizing.
				if (!empty($modSettings['max_image_width']) && !empty($modSettings['max_image_height']))
				{
					// For images, we'll want this
					list ($width, $height) = url_image_size($imgtag);

					if (!empty($modSettings['max_image_width']) && $width > $modSettings['max_image_width'])
					{
						$height = (int) (($modSettings['max_image_width'] * $height) / $width);
						$width = $modSettings['max_image_width'];
					}

					if (!empty($modSettings['max_image_height']) && $height > $modSettings['max_image_height'])
					{
						$width = (int) (($modSettings['max_image_height'] * $width) / $height);
						$height = $modSettings['max_image_height'];
					}

					// Set the new image tag.
					$replaces[$matches[0][$match]] = '[img width=' . $width . ' height=' . $height . $alt . ']' . $imgtag . '[/img]';
				}
				else
					$replaces[$matches[0][$match]] = '[img' . $alt . ']' . $imgtag . '[/img]';
			}

			$data = strtr($data, $replaces);
		}

		return $data;
	}
}


text:
ALTER TABLE ${ohdsiSchema}.cohort_definition_details
  DROP CONSTRAINT FK_cdd_cd
;

ALTER TABLE cohort_definition_details
  ADD CONSTRAINT FK_cdd_cd
    FOREIGN KEY ( id)
    REFERENCES ${ohdsiSchema}.cohort_definition (id)
;


text:
@interface MTRMetronomeViewController : UIViewController

@property (nonatomic) NSUInteger minBPM;
@property (nonatomic) NSUInteger maxBPM;
@property (nonatomic) NSUInteger currentBPM;

- (instancetype)initWithMinBPM:(NSUInteger)minBPM
                        maxBPM:(NSUInteger)maxBPM
                    currentBPM:(NSUInteger)currentBPM;

@end


text:
struct resolution_t {
    int w;
    int h;
    const char *name;
} _resolutions[] = {
    {320,  200,  "320x200"  },
    {640,  400,  "640x400"  },
    {800,  480,  "800x480"  },
    {800,  600,  "800x600"  },
    {960,  600,  "960x600"  },
    {1024, 768,  "1024x768" },
    {1280, 720,  "1280x720" },
    {1280, 800,  "1280x800" },
    {1280, 960,  "1280x960" },
    {1280, 1024, "1280x1024"},
    {1366, 768,  "1366x768" },
    {1440, 900,  "1440x900" },
    {1600, 900,  "1600x900" },
    {1600, 1000, "1600x1000"},
    {1600, 1200, "1600x1200"},
    {1680, 1050, "1680x1050"},
    {1920, 1080, "1920x1080"},
    {1920, 1200, "1920x1200"},
    {1920, 1440, "1920x1440"},
    {2560, 1440, "2560x1440"},
    {2560, 1600, "2560x1600"},
    {3840, 2160, "3840x2160"},
    {4096, 2160, "4096x2160"},
    {4096, 3072, "4096x3072"},
    {7680, 4320, "7680x4320"},
    {8192, 4320, "8192x4320"},
};

typedef struct resolution_t resolution;

typedef struct {
    vec2i custom_resolution;
    int is_custom_resolution;
    settings_video old_video_settings;
    component *scaler;
    component *factor;
} video_menu_data;

resolution *find_resolution_by_settings(settings *s) {
    int w = s->video.screen_w;
    int h = s->video.screen_h;

    for(int i = 0; i < sizeof(_resolutions) / sizeof(resolution); i++) {
        if(w == _resolutions[i].w && h == _resolutions[i].h) {
            return &_resolutions[i];
        }
    }
    return NULL;
}

void resolution_toggled(component *c, void *userdata, int pos) {
    video_menu_data *local = userdata;
    settings_video *v = &settings_get()->video;
    if(local->is_custom_resolution) {
        // The first index is always the custom resolution
        if(pos == 0) {
            v->screen_w = local->custom_resolution.x;
            v->screen_h = local->custom_resolution.y;
        } else {
            v->screen_w = _resolutions[pos - 1].w;
            v->screen_h = _resolutions[pos - 1].h;
        }
    } else {
        v->screen_w = _resolutions[pos].w;
        v->screen_h = _resolutions[pos].h;
    }
}

void scaler_toggled(component *c, void *userdata, int pos) {
    video_menu_data *local = userdata;
    settings_video *v = &settings_get()->video;

    // Set scaler
    omf_free(v->scaler);
    v->scaler = strdup(textselector_get_current_text(c));

    // If scaler is NEAREST, set factor to 1 and disable
    char tmp_buf[32];
    if(textselector_get_pos(c) == 0) {
        textselector_clear_options(local->factor);
        textselector_add_option(local->factor, "1");
        component_disable(local->factor, 1);
        v->scale_factor = 1;
    } else {
        component_disable(local->factor, 0);

        int *list;
        scaler_plugin scaler;
        scaler_init(&scaler);
        plugins_get_scaler(&scaler, v->scaler);
        int len = scaler_get_factors_list(&scaler, &list);
        textselector_clear_options(local->factor);
        for(int i = 0; i < len; i++) {
            snprintf(tmp_buf, 32, "%d", list[i]);
            textselector_add_option(local->factor, tmp_buf);
        }

        // Select first scale factor from the list
        v->scale_factor = list[0];
    }

    // Always select first factor option if scaler has changed.
    textselector_set_pos(local->factor, 0);

    // If scaler is "Nearest", disable factor toggle
    component_disable(local->factor, (textselector_get_pos(c) == 0));

    // Reinig after algorithm change
    video_reinit(v->screen_w, v->screen_h, v->fullscreen, v->vsync, v->scaler, v->scale_factor);
}

void scaling_factor_toggled(component *c, void *userdata, int pos) {
    // video_menu_data *local = userdata;
    settings_video *v = &settings_get()->video;

    int *list;
    scaler_plugin scaler;
    scaler_init(&scaler);
    plugins_get_scaler(&scaler, v->scaler);
    scaler_get_factors_list(&scaler, &list);
    v->scale_factor = list[pos];

    // Reinit after factor change
    video_reinit(v->screen_w, v->screen_h, v->fullscreen, v->vsync, v->scaler, v->scale_factor);
}

void menu_video_done(component *c, void *u) {
    scene *s = u;
    video_menu_data *local = menu_get_userdata(c->parent);
    settings_video *v = &settings_get()->video;
    video_reinit(v->screen_w, v->screen_h, v->fullscreen, v->vsync, v->scaler, v->scale_factor);

    if(local->old_video_settings.screen_w != v->screen_w || local->old_video_settings.screen_h != v->screen_h ||
       local->old_video_settings.fullscreen != v->fullscreen || local->old_video_settings.vsync != v->vsync) {

        menu_set_submenu(c->parent, menu_video_confirm_create(s, &local->old_video_settings));
    } else {
        menu *m = sizer_get_obj(c->parent);
        m->finished = 1;
    }
}

void menu_video_free(component *c) {
    video_menu_data *local = menu_get_userdata(c);
    omf_free(local);
    menu_set_userdata(c, local);
}

void menu_video_submenu_done(component *c, component *submenu) {
    menu *m = sizer_get_obj(c);
    m->finished = 1;
}

component *menu_video_create(scene *s) {
    // Menu userdata
    video_menu_data *local = omf_calloc(1, sizeof(video_menu_data));
    local->old_video_settings = settings_get()->video;

    // Load settings etc.
    const char *offon_opts[] = {"OFF", "ON"};
    settings *setting = settings_get();

    // Text config
    text_settings tconf;
    text_defaults(&tconf);
    tconf.font = FONT_BIG;
    tconf.halign = TEXT_CENTER;
    tconf.cforeground = color_create(0, 121, 0, 255);

    // Create menu and its header
    component *menu = menu_create(11);
    menu_attach(menu, label_create(&tconf, "VIDEO"));
    menu_attach(menu, filler_create());

    // Resolution selector
    component *res_selector = textselector_create(&tconf, "RES:", resolution_toggled, local);
    menu_attach(menu, res_selector);

    // If custom resolution is set, add it as first selection
    resolution *res = find_resolution_by_settings(setting);
    if(!res) {
        char tmp_label[32];
        snprintf(tmp_label, 32, "%ux%u", setting->video.screen_w, setting->video.screen_h);
        textselector_add_option(res_selector, tmp_label);
        local->custom_resolution.x = setting->video.screen_w;
        local->custom_resolution.y = setting->video.screen_h;
        local->is_custom_resolution = 1;
    }

    // Add standard resolutions
    for(int i = 0; i < sizeof(_resolutions) / sizeof(resolution); i++) {
        textselector_add_option(res_selector, _resolutions[i].name);
        if(!local->is_custom_resolution && _resolutions[i].w == res->w && _resolutions[i].h == res->h) {
            textselector_set_pos(res_selector, i);
        }
    }

    // vsync and fullscreen
    menu_attach(menu, textselector_create_bind_opts(&tconf, "VSYNC", NULL, NULL, &setting->video.vsync, offon_opts, 2));
    menu_attach(menu, textselector_create_bind_opts(&tconf, "FULLSCREEN", NULL, NULL, &setting->video.fullscreen,
                                                    offon_opts, 2));

    // Scaler selection
    component *scaler = textselector_create(&tconf, "SCALER:", scaler_toggled, local);
    component *factor = textselector_create(&tconf, "SCALING FACTOR:", scaling_factor_toggled, local);
    menu_attach(menu, scaler);
    menu_attach(menu, factor);
    textselector_add_option(scaler, "NEAREST");
    textselector_add_option(factor, "1");
    local->scaler = scaler; // Save references to ease their use
    local->factor = factor;

    // Get scalers
    list mlist;
    list_create(&mlist);
    plugins_get_list_by_type(&mlist, "scaler");
    iterator it;
    list_iter_begin(&mlist, &it);
    base_plugin **plugin;
    int i = 1;
    int plugin_found = 0;
    while((plugin = iter_next(&it)) != NULL) {
        textselector_add_option(scaler, (*plugin)->get_name());
        if(strcmp((*plugin)->get_name(), setting->video.scaler) == 0) {
            textselector_set_pos(scaler, i);
            plugin_found = 1;
        }
        i++;
    }
    list_free(&mlist);
    component_disable(factor, !plugin_found);

    // Get scaling factors
    char tmp_buf[32];
    if(plugin_found) {
        // Get scaling factors
        int pindex = 0;
        int *plist;
        scaler_plugin scaler;
        scaler_init(&scaler);
        plugins_get_scaler(&scaler, setting->video.scaler);
        int plen = scaler_get_factors_list(&scaler, &plist);
        textselector_clear_options(factor);
        for(int i = 0; i < plen; i++) {
            snprintf(tmp_buf, 32, "%d", plist[i]);
            textselector_add_option(factor, tmp_buf);
            if(plist[i] == setting->video.scale_factor) {
                pindex = i;
            }
        }
        textselector_set_pos(factor, pindex);
    }

    // Done button
    menu_attach(menu, textbutton_create(&tconf, "DONE", COM_ENABLED, menu_video_done, s));

    // Userdata & free function for it
    menu_set_userdata(menu, local);
    menu_set_free_cb(menu, menu_video_free);
    menu_set_submenu_done_cb(menu, menu_video_submenu_done);
    return menu;
}


text:
/*
 * bindobject.hpp for libspeed
 * by lenormf
 */

#pragma once

#ifndef SPEED_PRIVATE_INCLUDE
#error "Do not directly include this header file"
#endif

namespace speed {
template <typename R>
class bindObject;

// Static function, no argument
template <typename R>
bindObject<R()> Bind(R (*)());

// Member function, no argument
template <typename R, typename CT>
bindObject<R(CT::*)()> Bind(R (CT::*)(), CT*);

// Static function, 1 argument
template <typename R, typename T1>
bindObject<R(T1)> Bind(R (*)(T1), T1);

// Static function, 1 placeholder
template <typename R, typename T1>
bindObject<R(T1)> Bind(R (*)(T1), PlaceHolder::_placeholder);

// Member function, 1 argument
template <typename R, typename CT, typename T1>
bindObject<R(CT::*)(T1)> Bind(R (CT::*)(T1), CT*, T1);

// Member function, 1 placeholder
template <typename R, typename CT, typename T1>
bindObject<R(CT::*)(T1)> Bind(R (CT::*)(T1), CT*, PlaceHolder::_placeholder);

// Functor: static function, no argument
template <>
template <typename R>
class bindObject<R()> {
	R (*_func)();

	bindObject(R (*func)()) :
		_func(func) {}

	public:
	R operator()() const {
		return _func();
	}

	friend bindObject<R()> Bind<>(R (*)());
};

// Functor: member function, no argument
template <>
template <typename R, typename CT>
class bindObject<R(CT::*)()> {
	R (CT::*_func)();
	CT *_inst;

	bindObject(R (CT::*func)(), CT *inst) :
		_func(func), _inst(inst) {}

	public:
	R operator()() const {
		return (_inst->*_func)();
	}

	friend bindObject<R(CT::*)()> Bind<>(R (CT::*)(), CT*);
};

// Functor: static function, 1 argument
template <>
template <typename R, typename T1>
class bindObject<R(T1)> {
	R (*_func)(T1);
	T1 _1;

	bindObject(R (*func)(T1), T1 a1) :
		_func(func), _1(a1) {}
	bindObject(R (*func)(T1), PlaceHolder::_placeholder) :
		_func(func) {}

	public:
	R operator()() const {
		return _func(_1);
	}
	R operator()(T1 __1) const {
		return _func(__1);
	}

	friend bindObject<R(T1)> Bind<>(R (*)(T1), T1);
	friend bindObject<R(T1)> Bind<>(R (*)(T1), PlaceHolder::_placeholder);
};

// Functor: member function, 1 argument
template <>
template <typename R, typename CT, typename T1>
class bindObject<R(CT::*)(T1)> {
	R (CT::*_func)(T1);
	CT *_inst;
	T1 _1;

	bindObject(R (CT::*func)(T1), CT *inst, T1 a1) :
		_func(func), _inst(inst), _1(a1) {}
	bindObject(R (CT::*func)(T1), CT *inst, PlaceHolder::_placeholder) :
		_func(func), _inst(inst) {}

	public:
	R operator()() const {
		return (_inst->*_func)(_1);
	}
	R operator()(T1 __1) const {
		return (_inst->*_func)(__1);
	}

	friend bindObject<R(CT::*)(T1)> Bind<>(R (CT::*)(T1), CT*, T1);
	friend bindObject<R(CT::*)(T1)> Bind<>(R (CT::*)(T1), CT*, PlaceHolder::_placeholder);
};
}


text:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matrizes_CompeticaoNatacao
{
    class Program
    {
        static void Main(string[] args)
        {
           //Console.WriteLine("digite o número de nadadores: ");
           //qtd_nadadores = int.Parse(Console.ReadLine());
            string[] nadadores = new string[5];
            string nome = "";

            //Console.WriteLine("Digite a quantidade de provas: ");
            //qtd_provas = int.Parse(Console.ReadLine());
            double[,] provas = new double[5, 3];
            int numero_prova = 0;
            double tempo = 0;

            double menor_tempo_total = System.Double.MaxValue;
            double menor_tempo_prova = System.Double.MaxValue;
            int indice_nadador_vencedor = 0;
            double tempo_total_nadador = 0;

            // for para captar os nomes dos nadadores
            for (int i = 0; i < nadadores.Length; i++)
            {
                Console.WriteLine("Informe o nome do nadador: ");
                nome = Console.ReadLine();
                nadadores[i] = nome;
            } // fim for nadadores

            // imput para cada prova os tempos dos nadadores
            for (int i = 0; i < 3; i++)
            {
                numero_prova = i + 1;
                Console.WriteLine("Resultados da prova: " + numero_prova);

                for (int k = 0; k < 5; k++)
                {
                    Console.WriteLine("Tempo do nadador " + nadadores[k]);
                    tempo = double.Parse(Console.ReadLine());
                    provas[k, i] = tempo;
                 }

            } // for da prova (coluna)

           //verificar o vencedor de cada prova
           for (int coluna = 0; coluna < 3; coluna++)
           {
               for (int linha = 0; linha < 5; linha++)
               {
                   if (provas[linha, coluna] < menor_tempo_prova)
                    {
                       menor_tempo_prova = provas[linha, coluna];
                       indice_nadador_vencedor = linha;
                    }
               }//for linha

               // vencedor da prova
               numero_prova = coluna + 1;
               Console.WriteLine("O vencedor da prova" + numero_prova + " foi: " + nadadores[indice_nadador_vencedor]);

               menor_tempo_prova = System.Double.MaxValue;
           }// for coluna(vencedor de cada prova)

            // verificar o nadador campeao
            // soma todas as provas que competiu -> menor tempo
            menor_tempo_total = System.Double.MaxValue;
            for (int linha = 0; linha < 5; linha++)
            {

               tempo_total_nadador = 0;

               for (int coluna = 0; coluna < 3; coluna++)
               {
                 tempo_total_nadador = tempo_total_nadador + provas[linha, coluna];
               }//fim for coluna

               if (tempo_total_nadador < menor_tempo_total)
               {
                 menor_tempo_total = tempo_total_nadador;
                 indice_nadador_vencedor = linha;
               }

            }//fim for linha

            Console.WriteLine("O nadador campeão foi: " + nadadores[indice_nadador_vencedor]);

        }
    }
}


text:
'use strict';

/*
File name:  core.client.routes.js,
Authors' Names: Liliya Artyukh, Mohammed Summon, Kristian Castaneda,
Website Name: Survey KLM,
File Description: routes for core module
*/

// Setting up route
angular.module('core').config(['$stateProvider', '$urlRouterProvider',
	function($stateProvider, $urlRouterProvider) {
		// Redirect to home view when route not found
		$urlRouterProvider.otherwise('/');

		// Home state routing
		$stateProvider.
		state('home', {
			url: '/',
			templateUrl: 'modules/core/views/home.client.view.html'
		});
	}
]);


text:
NAME=cherry_mx
include ../../common/Makefile.pcb


text:
module Sherlock
  class QueriesController < Sherlock::ApplicationController
    def show
      @query = @transaction.find_query(params[:id])
    end
  end
end


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require_self
 *= require_tree .
 */

td {
  padding-right: 8px !important;
}

.container {
  margin-right: 0 !important;
  margin-left: 0 !important;
}

.guid {
	font-family: Monaco, "Liberation Mono", Courier, monospace;
	display: inline;
}


text:
code: true
type: page
title: mexecute
---

# mexecute

Allows the execution of multiple commands or 'actions' in a single step.

It creates a redis **transaction** block and **executes** it immediately, all actions will be executed sequentially and as a single atomic and isolated operation.

[[_Redis documentation_]](https://redis.io/topics/transactions)

::: warning
Only already supported actions can be executed using **mexecute**.
:::

---

## Query Syntax

### HTTP

```http
URL: http://kuzzle:7512/ms/_mexecute
Method: POST
Body:
```

```js
{
  "actions": [
    {"action": "command", "args": {"_id": "x", "body": {"value": 1}},
    {"action": "command", "args": {"_id": "x"}},
    {"action": "...", "args": {...}}
  ]
}
```

### Other protocols

```js
{
  "controller": "ms",
  "action": "mexecute",
  "body": {
    "actions": [
        {"action": "command", "args": {"_id": "x", "body": {"value": 1}},
        {"action": "command", "args": {"_id": "x"}},
        {"action": "...", "args": {...}}
    ]
  }
}
```

---

## Body properties

- `actions`: an array of objects. Each object describes an action to be executed, using the following properties:
  - `action`: action name
  - `args`: an object containing all required arguments

---

## Response

Returns an array of error & result pairs for each executed action, in order.

```js
{
  "requestId": "<unique request identifier>",
  "status": 200,
  "error": null,
  "controller": "ms",
  "action": "mexecute",
  "collection": null,
  "index": null,
  "result": [
      ["err" | null, "result"],
      [null, "OK"],
      [null, 1],
  ]
}
```


text:
/*
  Draw a circle with three random points on the circle. Connect the points to
  form a triangle. Display the angles in the triangle. Use the mouse to drag
  a point along the perimeter of the circle. As you drag it, the triangle and
  angles are redisplayed dynamically.
*/

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseButton;

public class E15_21 extends Application {
  @Override
  public void start(Stage primaryStage) {
    final double WIDTH = 500.0;
    final double HEIGHT = 500.0;
    final double RADIUS = 200.0;

    Circle[] points = new Circle[3];
    Line[] lines = new Line[3];
    Text[] labels = new Text[3];
    Pane pane = new Pane();
    Circle circle = new Circle(WIDTH / 2, HEIGHT / 2, RADIUS);
    circle.setFill(Color.WHITE);
    circle.setStroke(Color.BLACK);
    pane.getChildren().add(circle);

    // create three points around the circle represented by Circle objects
    for (int i = 0; i < 3; i++) {
      Circle point = new Circle(RADIUS / 20);
      double randomAngle = Math.random() * 2 * Math.PI;
      double x = circle.getCenterX() + RADIUS * Math.cos(randomAngle);
      double y = circle.getCenterY() + RADIUS * Math.sin(randomAngle);
      point.setCenterX(x);
      point.setCenterY(y);
      point.setOnMouseDragged(e -> {
        if (e.getButton().equals(MouseButton.PRIMARY)) {
          double angle = Math.atan2(e.getY() - circle.getCenterY(), e.getX() - circle.getCenterX());
          Circle c = (Circle)e.getSource();
          c.setCenterX(circle.getCenterX() + RADIUS * Math.cos(angle));
          c.setCenterY(circle.getCenterY() + RADIUS * Math.sin(angle));
          angle = getAngle(lines[1], lines[2], lines[0]);
          labels[0].setText(String.format("%.5f", angle));
          angle = getAngle(lines[2], lines[1], lines[0]);
          labels[1].setText(String.format("%.5f", angle));
          angle = getAngle(lines[0], lines[2], lines[1]);
          labels[2].setText(String.format("%.5f", angle));
        }
      });
      points[i] = point;
    }

    // create three lines connecting the points
    for (int i = 0; i < 3; i++) {
      int next = i == 2 ? 0 : i + 1;
      Line line = new Line();
      line.startXProperty().bind(points[i].centerXProperty());
      line.startYProperty().bind(points[i].centerYProperty());
      line.endXProperty().bind(points[next].centerXProperty());
      line.endYProperty().bind(points[next].centerYProperty());
      lines[i] = line;
    }

    // create three Text objects to display the angles
    for (int i = 0; i < 3; i++) {
      Text text = new Text();
      text.xProperty().bind(points[i].centerXProperty());
      text.yProperty().bind(points[i].centerYProperty().subtract(RADIUS / 20));
      labels[i] = text;
    }

    pane.getChildren().addAll(points[0], points[1], points[2],
      lines[0], lines[1], lines[2], labels[0], labels[1], labels[2]);

    Scene scene = new Scene(pane, WIDTH, HEIGHT);
    primaryStage.setTitle("E15_21");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  public static double getAngle(Line x, Line y, Line z) {
    double a = distance(x);
    double b = distance(y);
    double c = distance(z);
    return Math.toDegrees(Math.acos((a * a - b * b - c * c) / (-2 * b * c)));
  }

  public static double distance(Line line) {
    double x1 = line.getStartX();
    double y1 = line.getStartY();
    double x2 = line.getEndX();
    double y2 = line.getEndY();
    return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
  }

  public static void main(String[] args) {
    launch(args);
  }
}


text:
ELECTRONVER=1.8.7
NODEJSVER=5.1.1

OS="${1}"
if [ -z "${2}" ]; then
SERVERTAG='latest'
else
SERVERTAG=tags/${2}
fi
echo "Building with openbazaar-go/$SERVERTAG"

# Get Version
PACKAGE_VERSION=$(node -p 'require("./package").version')
echo "OpenBazaar Version: $PACKAGE_VERSION"

# Create temp build dirs
mkdir dist/
rm -rf dist/*
mkdir OPENBAZAAR_TEMP/
rm -rf OPENBAZAAR_TEMP/*

echo 'Preparing to build installers...'

echo 'Installing npm packages...'
npm i -g npm@5.2
npm install electron-packager -g --silent
npm install npm-run-all -g --silent
npm install grunt-cli -g --silent
npm install grunt --save-dev --silent
npm install grunt-electron-installer --save-dev --silent
npm install --silent

rvm reinstall ruby

echo 'Building OpenBazaar app...'
npm run build

echo 'Copying transpiled files into js folder...'
cp -rf prod/* js/

echo "We are building: ${BINARY}"

case "$TRAVIS_OS_NAME" in
  "linux")

    echo 'Linux builds'
    echo 'Making dist directories'
    mkdir dist/linux64

    sudo apt-get install rpm

    echo 'Install npm packages for Linux'
    npm install -g --save-dev electron-installer-debian --silent
    npm install -g --save-dev electron-installer-redhat@2.0.0 --silent

    # Install libgconf2-4
    sudo apt-get install libgconf2-4 libgconf-2-4

    # Install rpmbuild
    sudo apt-get --only-upgrade install rpm

    # Ensure fakeroot is installed
    sudo apt-get install fakeroot

    # Retrieve Latest Server Binaries
    sudo apt-get install jq
    cd OPENBAZAAR_TEMP/
    curl -u $GITHUB_USER:$GITHUB_TOKEN -s https://api.github.com/repos/OpenBazaar/openbazaar-go/releases/$SERVERTAG > release.txt
    cat release.txt | jq -r ".assets[].browser_download_url" | xargs -n 1 curl -L -O
    cd ..

    APPNAME="openbazaar2"

    echo 'Building Linux 64-bit Installer....'

    echo "Packaging Electron application"
    electron-packager . ${APPNAME} --platform=linux --arch=x64 --electronVersion=${ELECTRONVER} --overwrite --ignore="OPENBAZAAR_TEMP" --prune --out=dist

    echo 'Move go server to electron app'
    mkdir dist/${APPNAME}-linux-x64/resources/openbazaar-go/
    cp -rf OPENBAZAAR_TEMP/openbazaar-go-linux-amd64 dist/${APPNAME}-linux-x64/resources/openbazaar-go
    rm -rf OPENBAZAAR_TEMP/*
    mv dist/${APPNAME}-linux-x64/resources/openbazaar-go/openbazaar-go-linux-amd64 dist/${APPNAME}-linux-x64/resources/openbazaar-go/openbazaard
    rm -rf dist/${APPNAME}-linux-x64/resources/app/.travis
    chmod +x dist/${APPNAME}-linux-x64/resources/openbazaar-go/openbazaard

    echo 'Create debian archive'
    electron-installer-debian --config .travis/config_amd64.json

    echo 'Create RPM archive'
    electron-installer-redhat --config .travis/config_x86_64.json

    APPNAME="openbazaar2client"

    echo 'Building Linux 64-bit Installer....'

    echo "Packaging Electron application"
    electron-packager . ${APPNAME} --platform=linux --arch=x64 --ignore="OPENBAZAAR_TEMP" --electronVersion=${ELECTRONVER} --overwrite --prune --out=dist

    echo 'Create debian archive'
    electron-installer-debian --config .travis/config_amd64.client.json

    echo 'Create RPM archive'
    electron-installer-redhat --config .travis/config_x86_64.client.json

    ;;

  "osx")

    brew update
    brew remove jq
    brew link oniguruma
    brew install jq
    brew link --overwrite fontconfig gd gnutls jasper libgphoto2 libicns libtasn1 libusb libusb-compat little-cms2 nettle openssl sane-backends webp wine git-lfs gnu-tar dpkg xz
    brew install freetype graphicsmagick
    brew link xz
    brew remove openssl
    brew install openssl
    brew link freetype graphicsmagick mono

    # Retrieve Latest Server Binaries
    cd OPENBAZAAR_TEMP/
    curl -u $GITHUB_USER:$GITHUB_TOKEN -s https://api.github.com/repos/OpenBazaar/openbazaar-go/releases/$SERVERTAG > release.txt
    cat release.txt | jq -r ".assets[].browser_download_url" | xargs -n 1 curl -L -O
    cd ..

    if [[ $BINARY == 'win' ]]; then

        brew link --overwrite fontconfig gd gnutls jasper libgphoto2 libicns libtasn1 libusb libusb-compat little-cms2 nettle openssl sane-backends webp wine git-lfs gnu-tar dpkg xz
        brew link libgsf glib pcre
        brew remove osslsigncode
        brew install mono osslsigncode
        brew reinstall openssl@1.1

        brew install homebrew/cask-versions/wine-devel

        # WINDOWS 64
        echo 'Building Windows 64-bit Installer...'
        mkdir dist/win64

        export WINEARCH=win64

        npm i electron-packager

        cd node_modules/electron-packager
        npm install rcedit
        cd ../..

        echo 'Running Electron Packager...'
        node_modules/electron-packager/bin/electron-packager.js . OpenBazaar2 --asar --out=dist --protocol-name=OpenBazaar --ignore="OPENBAZAAR_TEMP" --win32metadata.ProductName="OpenBazaar2" --win32metadata.CompanyName="OpenBazaar" --win32metadata.FileDescription='Decentralized p2p marketplace for Bitcoin' --win32metadata.OriginalFilename=OpenBazaar2.exe --protocol=ob --platform=win32 --arch=x64 --icon=imgs/openbazaar2.ico --electron-version=${ELECTRONVER} --overwrite

        echo 'Copying server binary into application folder...'
        cp -rf OPENBAZAAR_TEMP/openbazaar-go-windows-4.0-amd64.exe dist/OpenBazaar2-win32-x64/resources/
        cp -rf OPENBAZAAR_TEMP/libwinpthread-1.win64.dll dist/OpenBazaar2-win32-x64/resources/libwinpthread-1.dll
        mkdir dist/OpenBazaar2-win32-x64/resources/openbazaar-go
        mv dist/OpenBazaar2-win32-x64/resources/openbazaar-go-windows-4.0-amd64.exe dist/OpenBazaar2-win32-x64/resources/openbazaar-go/openbazaard.exe
        mv dist/OpenBazaar2-win32-x64/resources/libwinpthread-1.dll dist/OpenBazaar2-win32-x64/resources/openbazaar-go/libwinpthread-1.dll

        echo 'Building Installer...'
        grunt -v create-windows-installer --appname=OpenBazaar2 --obversion=$PACKAGE_VERSION --appdir=dist/OpenBazaar2-win32-x64 --outdir=dist/win64
        mv dist/win64/OpenBazaar2Setup.exe dist/win64/OpenBazaar2-$PACKAGE_VERSION-Setup-64.exe
        mv dist/win64/RELEASES dist/win64/RELEASES-x64

        #### CLIENT ONLY
        echo 'Running Electron Packager...'
        electron-packager . OpenBazaar2Client --asar --out=dist --protocol-name=OpenBazaar --ignore="OPENBAZAAR_TEMP" --win32metadata.ProductName="OpenBazaar2Client" --win32metadata.CompanyName="OpenBazaar" --win32metadata.FileDescription='Decentralized p2p marketplace for Bitcoin' --win32metadata.OriginalFilename=OpenBazaar2Client.exe --protocol=ob --platform=win32 --arch=x64 --icon=imgs/openbazaar2.ico --electron-version=${ELECTRONVER} --overwrite

        echo 'Building Installer...'
        grunt -v create-windows-installer --appname=OpenBazaar2Client --obversion=$PACKAGE_VERSION --appdir=dist/OpenBazaar2Client-win32-x64 --outdir=dist/win64
        mv dist/win64/OpenBazaar2ClientSetup.exe dist/win64/OpenBazaar2Client-$PACKAGE_VERSION-Setup-64.exe

        echo 'Sign the installer'
        osslsigncode sign -t http://timestamp.digicert.com -h sha1 -key .travis/ob1.pvk -pass "$OB1_SECRET" -certs .travis/ob1.spc -in dist/win64/OpenBazaar2-$PACKAGE_VERSION-Setup-64.exe -out dist/win64/OpenBazaar2-$PACKAGE_VERSION-Setup-64.exe
        osslsigncode sign -t http://timestamp.digicert.com -h sha1 -key .travis/ob1.pvk -pass "$OB1_SECRET" -certs .travis/ob1.spc -in dist/win64/OpenBazaar2Client-$PACKAGE_VERSION-Setup-64.exe -out dist/win64/OpenBazaar2Client-$PACKAGE_VERSION-Setup-64.exe

        mv dist/win64/RELEASES-x64 dist/win64/RELEASES

    else

        # OSX
        echo 'Building OSX Installer'
        mkdir dist/osx

        # Install the DMG packager
        echo 'Installing electron-installer-dmg'
        npm install -g electron-installer-dmg

        # Sign openbazaar-go binary
        echo 'Signing Go binary'
        mv OPENBAZAAR_TEMP/openbazaar-go-darwin-10.6-amd64 dist/osx/openbazaard
        rm -rf OPENBAZAAR_TEMP/*
        codesign --force --sign "$SIGNING_IDENTITY2" --timestamp --options runtime dist/osx/openbazaard

        # Notarize the zip files
        UPLOAD_INFO_PLIST="uploadinfo.plist"
        REQUEST_INFO_PLIST="request.plist"
        touch ${UPLOAD_INFO_PLIST}

        wait_for_notarization() {
          while true; do \

            echo "Checking Apple for notarization status..."; \
            /usr/bin/xcrun altool --notarization-info `/usr/libexec/PlistBuddy -c "Print :notarization-upload:RequestUUID" $UPLOAD_INFO_PLIST` -u $APPLE_ID -p $APPLE_PASS --output-format xml > "$REQUEST_INFO_PLIST" ;\

            cat $REQUEST_INFO_PLIST

            if [[ `/usr/libexec/PlistBuddy -c "Print :notarization-info:Status" ${REQUEST_INFO_PLIST}` != "in progress" ]] || [[ "$requestUUID" == "" ]] ; then \

               # check if it has been uploaded already and get the RequestUUID from the error message
               echo "Checking if binary has already been uploaded..."; \
               message=`/usr/libexec/PlistBuddy -c "Print :product-errors:0:message" $UPLOAD_INFO_PLIST`;\
               if [[ ${message} =~ ^ERROR\ ITMS-90732* ]]; then \
                   prefix="ERROR ITMS-90732: \"The software asset has already been uploaded. The upload ID is "; \
                   suffix="\" at SoftwareAssets\/EnigmaSoftwareAsset"; \
                   requestUUID=`echo "${message}" | sed -e "s/^$prefix//" -e "s/$suffix$//"`; \

                   echo "Binary has already been uploaded. Checking Apple status for request ${requestUUID}..."; \
                   /usr/bin/xcrun altool --notarization-info ${requestUUID} -u $APPLE_ID -p $APPLE_PASS --output-format xml > "$REQUEST_INFO_PLIST" ;\
               fi ;\

               if [[ `/usr/libexec/PlistBuddy -c "Print :notarization-info:Status" ${REQUEST_INFO_PLIST}` == "success" ]]; then \
                echo "Binary has been notarized"; \
                break; \
               fi; \
            fi ;\
            echo "Waiting 30 seconds to check status again..."; \
            sleep 30 ;\
          done
        }

        extract_app() {

            # use process redirection to capture the mount point and dev entry
            IFS=$'\n' read -rd '\n' mount_point dev_entry < <(
                # mount the diskimage; leave out -readonly if making changes to the filesystem
                hdiutil attach -readonly -plist "$1" | \

                # convert output plist to json
                plutil -convert json - -o - | \

                # extract mount point and dev entry
                jq -r '
                    .[] | .[] |
                    select(."volume-kind" == "hfs") |
                    ."mount-point" + "\n" + ."dev-entry"
                '
            )

            # work with the zip file
            cp -rf "${mount_point}/${2}.app" dist/osx

            # unmount the disk image
            hdiutil detach "$dev_entry"

        }

        if [[ ${BINARY} == 'osx' ]]; then

            echo 'Running Electron Packager...'
            electron-packager . OpenBazaar2 --out=dist -app-category-type=public.app-category.business --protocol-name=OpenBazaar --ignore="OPENBAZAAR_TEMP" --protocol=ob --platform=darwin --arch=x64 --icon=imgs/openbazaar2.icns --electron-version=${ELECTRONVER} --overwrite --app-version=$PACKAGE_VERSION

            echo 'Creating openbazaar-go folder in the OS X .app'
            mkdir dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Resources/openbazaar-go

            echo 'Moving binary to correct folder'
            mv dist/osx/openbazaard dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Resources/openbazaar-go/openbazaard
            chmod +x dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Resources/openbazaar-go/openbazaard

            echo 'Codesign the .app'
            codesign -s "$SIGNING_IDENTITY2" dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Frameworks/Electron\ Framework.framework/Versions/A/Libraries/libffmpeg.dylib
            codesign -s "$SIGNING_IDENTITY2" dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Frameworks/Electron\ Framework.framework/Versions/A/Libraries/libnode.dylib
            codesign --force --options runtime --deep --sign "$SIGNING_IDENTITY2" "dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/crashpad_handler"
            codesign --force --options runtime --deep --sign "$SIGNING_IDENTITY2"  "dist/OpenBazaar2-darwin-x64/OpenBazaar2.app/Contents/Frameworks/Squirrel.framework/Versions/A/Resources/ShipIt"

            codesign --force --deep --sign "$SIGNING_IDENTITY2" --timestamp --options runtime --entitlements openbazaar.entitlements dist/OpenBazaar2-darwin-x64/OpenBazaar2.app
            electron-installer-dmg dist/OpenBazaar2-darwin-x64/OpenBazaar2.app OpenBazaar2-$PACKAGE_VERSION --icon ./imgs/openbazaar2.icns --out=dist/OpenBazaar2-darwin-x64 --overwrite --background=./imgs/osx-finder_background.png --debug

            echo 'Codesign the DMG and zip'
            codesign --force --sign "$SIGNING_IDENTITY2" --timestamp --options runtime --entitlements openbazaar.entitlements dist/OpenBazaar2-darwin-x64/OpenBazaar2-$PACKAGE_VERSION.dmg
            cd dist/OpenBazaar2-darwin-x64/
            zip -q -r OpenBazaar2-mac-$PACKAGE_VERSION.zip OpenBazaar2.app
            cp -r OpenBazaar2.app ../osx/
            cp OpenBazaar2-mac-$PACKAGE_VERSION.zip ../osx/
            cp OpenBazaar2-$PACKAGE_VERSION.dmg ../osx/

            cd ../..

            zip -q -r dist/osx/OpenBazaar2.zip dist/OpenBazaar2-darwin-x64/OpenBazaar2-$PACKAGE_VERSION.dmg

            # Upload to apple and notarize
            echo "Uploading binary to Apple Notarization server for package ${PACKAGE_VERSION}..."
            xcrun altool --notarize-app --primary-bundle-id "org.openbazaar.desktop-${PACKAGE_VERSION}" --username "$APPLE_ID" --password "$APPLE_PASS" --file dist/osx/OpenBazaar2.zip --output-format xml > ${UPLOAD_INFO_PLIST}
            wait_for_notarization

            echo "Stapling ticket to the DMG..."
            xcrun stapler staple dist/osx/OpenBazaar2-$PACKAGE_VERSION.dmg

            extract_app "dist/osx/OpenBazaar2-$PACKAGE_VERSION.dmg" "OpenBazaar2"

            zip -q -r dist/osx/OpenBazaar2-mac-$PACKAGE_VERSION.zip dist/osx/OpenBazaar2.app

        else

            # Client Only
            electron-packager . OpenBazaar2Client --out=dist -app-category-type=public.app-category.business --protocol-name=OpenBazaar --ignore="OPENBAZAAR_TEMP" --protocol=ob --platform=darwin --arch=x64 --icon=imgs/openbazaar2.icns --electron-version=${ELECTRONVER} --overwrite --app-version=$PACKAGE_VERSION

            codesign -s "$SIGNING_IDENTITY2" dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app/Contents/Frameworks/Electron\ Framework.framework/Versions/A/Libraries/libffmpeg.dylib
            codesign -s "$SIGNING_IDENTITY2" dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app/Contents/Frameworks/Electron\ Framework.framework/Versions/A/Libraries/libnode.dylib
            codesign --force --options runtime --deep --sign "$SIGNING_IDENTITY2" "dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/crashpad_handler"
            codesign --force --options runtime --deep --sign "$SIGNING_IDENTITY2"  "dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app/Contents/Frameworks/Squirrel.framework/Versions/A/Resources/ShipIt"

            codesign --force --deep --sign "$SIGNING_IDENTITY2" --timestamp --options runtime --entitlements openbazaar.entitlements dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app
            electron-installer-dmg dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client.app OpenBazaar2Client-$PACKAGE_VERSION --icon ./imgs/openbazaar2.icns --out=dist/OpenBazaar2Client-darwin-x64 --overwrite --background=./imgs/osx-finder_background.png --debug

            # Client Only
            codesign --force --sign "$SIGNING_IDENTITY2" --timestamp --options runtime --entitlements openbazaar.entitlements dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client-$PACKAGE_VERSION.dmg
            cd dist/OpenBazaar2Client-darwin-x64/
            zip -q -r OpenBazaar2Client-mac-$PACKAGE_VERSION.zip OpenBazaar2Client.app
            cp -r OpenBazaar2Client.app ../osx/
            cp OpenBazaar2Client-mac-$PACKAGE_VERSION.zip ../osx/
            cp OpenBazaar2Client-$PACKAGE_VERSION.dmg ../osx/

            cd ../..

            zip -q -r dist/osx/OpenBazaar2Client.zip dist/OpenBazaar2Client-darwin-x64/OpenBazaar2Client-$PACKAGE_VERSION.dmg

            echo "Uploading client only binary to Apple Notarization server..."
            xcrun altool --notarize-app --primary-bundle-id "org.openbazaar.desktopclient-$PACKAGE_VERSION" --username "$APPLE_ID" --password "$APPLE_PASS" --file dist/osx/OpenBazaar2Client.zip --output-format xml > $UPLOAD_INFO_PLIST
            wait_for_notarization

            echo "Stapling ticket to the DMG..."
            xcrun stapler staple dist/osx/OpenBazaar2Client-$PACKAGE_VERSION.dmg

            extract_app "dist/osx/OpenBazaar2Client-$PACKAGE_VERSION.dmg" "OpenBazaar2Client"

            zip -q -r dist/osx/OpenBazaar2Client-mac-$PACKAGE_VERSION.zip dist/osx/OpenBazaar2Client.app
        fi

    fi

  ;;
esac


text:
using ::testing::InSequence;
using ::testing::Return;

namespace cobalt {
namespace bindings {
namespace testing {

namespace {
class GlobalInterfaceBindingsTest : public BindingsTestBase {
 protected:
  GlobalInterfaceBindingsTest() : BindingsTestBase(new WindowMock()) {}
  WindowMock& test_mock() {
    return *base::polymorphic_downcast<WindowMock*>(window_.get());
  }
};
}  // namespace

TEST_F(GlobalInterfaceBindingsTest, GlobalWindowIsThis) {
  std::string result;
  EXPECT_TRUE(EvaluateScript("window === this;", &result));
  EXPECT_STREQ("true", result.c_str());
}

TEST_F(GlobalInterfaceBindingsTest, GlobalOperation) {
  EXPECT_CALL(test_mock(), WindowOperation());
  EXPECT_TRUE(EvaluateScript("windowOperation();", NULL));
}

TEST_F(GlobalInterfaceBindingsTest, GlobalProperty) {
  InSequence in_sequence_dummy;

  std::string result;
  EXPECT_CALL(test_mock(), window_property()).WillOnce(Return("bar"));
  EXPECT_TRUE(EvaluateScript("windowProperty == \"bar\";", &result));
  EXPECT_STREQ("true", result.c_str());
  EXPECT_CALL(test_mock(), set_window_property("foo"));
  EXPECT_TRUE(EvaluateScript("windowProperty = \"foo\";", NULL));
}

TEST_F(GlobalInterfaceBindingsTest, GlobalPrototypeIsSet) {
  std::string result;
  EXPECT_TRUE(EvaluateScript(
      "Object.getPrototypeOf(this) === Window.prototype;", &result));
  EXPECT_STREQ("true", result.c_str());
}

TEST_F(GlobalInterfaceBindingsTest, GlobalInterfaceConstructorIsSet) {
  std::string result;
  EXPECT_TRUE(EvaluateScript("this.constructor === Window;", &result));
  EXPECT_STREQ("true", result.c_str());
}

// http://heycam.github.io/webidl/#Global
//   2. Interface members from the interface (or consequential interfaces) will
//      correspond to properties on the object itself rather than on interface
//      prototype objects.
TEST_F(GlobalInterfaceBindingsTest,
       DISABLED_PropertiesAndOperationsAreOwnProperties) {
  std::string result;
  EXPECT_TRUE(
      EvaluateScript("this.hasOwnProperty(\"windowProperty\");", &result));
  EXPECT_STREQ("true", result.c_str());
  EXPECT_TRUE(
      EvaluateScript("this.hasOwnProperty(\"windowOperation\");", &result));
  EXPECT_STREQ("true", result.c_str());
  EXPECT_TRUE(EvaluateScript(
      "Window.prototype.hasOwnProperty(\"windowProperty\");", &result));
  EXPECT_STREQ("false", result.c_str());
  EXPECT_TRUE(EvaluateScript(
      "Window.prototype.hasOwnProperty(\"windowOperation\");", &result));
  EXPECT_STREQ("false", result.c_str());
}

TEST_F(GlobalInterfaceBindingsTest, ConstructorExists) {
  std::string result;
  EXPECT_TRUE(
      EvaluateScript("this.hasOwnProperty(\"ArbitraryInterface\");", &result));
  EXPECT_STREQ("true", result.c_str());
}

TEST_F(GlobalInterfaceBindingsTest, ConstructorPrototype) {
  std::string result;
  EXPECT_TRUE(EvaluateScript("ArbitraryInterface.prototype", &result));
  EXPECT_TRUE(IsAcceptablePrototypeString("ArbitraryInterface", result))
      << result;
}

TEST_F(GlobalInterfaceBindingsTest,
       ConstructorForNoInterfaceObjectDoesNotExists) {
  std::string result;
  EXPECT_TRUE(EvaluateScript(
      "this.hasOwnProperty(\"NoInterfaceObjectInterface\");", &result));
  EXPECT_STREQ("false", result.c_str());
}

TEST_F(GlobalInterfaceBindingsTest, CallParentInterfaceOperation) {
  EXPECT_CALL(test_mock(), ParentOperation());
  EXPECT_TRUE(EvaluateScript("parentOperation();", NULL));
}

}  // namespace testing
}  // namespace bindings
}  // namespace cobalt


text:
package eu.bcvsolutions.idm.core.scheduler.exception;

import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;

/**
 * Thrown, when added scheduler cron trigger expression is wrong
 *
 * @author Radek Tomiška
 *
 */
public class InvalidCronExpressionException extends SchedulerException {

	private static final long serialVersionUID = 1L;
	private final String cron;

	public InvalidCronExpressionException(String cron, Throwable throwable) {
		super(CoreResultCode.SCHEDULER_INVALID_CRON_EXPRESSION, ImmutableMap.of("cron", cron), throwable);
		this.cron = cron;
	}

	public String getCron() {
		return cron;
	}
}


text:
<?php

namespace Rcm\Exception;

use Rcm\Exception\ExceptionInterface as RcmExceptionInterface;

class PluginInstanceNotFoundException extends \RuntimeException implements RcmExceptionInterface
{

}


text:
'use strict';

var got    = require('got');
var assert = require('assert');

var URL = 'https://maps.googleapis.com/maps/api/directions/json';

module.exports = function(options) {
  assert(options && options.origin && options.destination, 'Invalid parameters, options requires origin and destination property');
  assert(typeof(options.origin) === 'string' && typeof(options.destination) === 'string', 'Origin and destination properties only accept string');

  return got(URL, {
    query: options,
    json: true
  })
  .then(function(response) {
    var result = response.body;
    if (!result.status || result.status !== 'OK') {
      throw new Error('direction not found');
    }
    return result;
  });
};


text:
This file contains a number of front-end javascript interview questions.

## Table of Contents
1. [Questions](#questions)
 * [Question1: Consider the two functions below. Will they both return the same thing? Why or why not?](#question1)
 * [Question2: What will the code below output of adding 2 decimal numbers?](#question2)
 * [Question3: In what order will the numbers 1-4 be logged to the console when the code below is executed?](#question3)
 * [Question4: What will be the output of the seTtimeout inside a for loop?](#question4)
 * [Question5: What would the following lines of code output to the console?](#question5)
 * [Question6: How do you check if an object is an array or not?](#question6)
 * [Question7: == Vs ===](#question7)
 * [Question8: How would you compare two objects in JavaScript?](#question8)
 * [Question9: Delete can delete but](#question9)
 * [Question10: What is arrow function?](#question10)
 * [Question11: What is lambda function?](#question11)
 * [Question12: What are JavaScript types?](#question12)

2. Getting Involved
 * [Contributors](#contributors)
 * [How to Contribute](https://github.com/danlex/javascript-questions/edit/master/CONTRIBUTING.md)
 * [License](https://github.com/danlex/javascript-questions/blob/master/LICENSE)

## Questions
#### Question1.

**Consider the two functions below. Will they both return the same thing? Why or why not?**

```javascript
function foo1()
{
  return {
      bar: "hello"
  };
}

function foo2()
{
  return
  {
      bar: "hello"
  };
}

console.log("foo1 returns:");
console.log(foo1());
console.log("foo2 returns:");
console.log(foo2());
```
**Answer:**
```javascript
foo1 returns:
Object {bar: "hello"}
foo2 returns:
Undefined
```

#### Question2.
**What will the code below output of adding 2 decimal numbers? Explain your answer**

```javascript
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 == 0.3);
```
**Answer:**
```javascript
0.30000000000000004
false
```
#### Question3.
**In what order will the numbers 1-4 be logged to the console when the code below is executed? Why?**

```javascript
(function() {
   console.log(1);
   setTimeout(function(){console.log(2)}, 1000);
   setTimeout(function(){console.log(3)}, 0);
   console.log(4);
})();
```
**Answer:**
```javascript
1
4
3
2
```

#### Question4.
**What will be the output of the seTtimeout inside a for loop?**
What will be the output of the following code:
```javascript
for (var i = 0; i < 5; i++) {
  setTimeout(function() { console.log(i); }, i * 1000 );
}
Explain your answer. How could the use of closures help here?
```
**Answer:**
```javascript
The code sample shown will not display the values 0, 1, 2, 3, and 4 as might be expected;
rather, it will display 5, 5, 5, 5, and 5.

The reason for this is that each function executed within the loop will be executed after
the entire loop has completed and all will therefore reference the last value stored in i, which was 5.
```
#### Question5.
**What would the following lines of code output to the console?**
```javascript
console.log("0 || 1 = "+(0 || 1));
console.log("1 || 2 = "+(1 || 2));
console.log("0 && 1 = "+(0 && 1));
console.log("1 && 2 = "+(1 && 2));
```
**Answer:**
```javascript
0 || 1 = 1
1 || 2 = 1
0 && 1 = 0
1 && 2 = 2
```
#### Question6.
**How do you check if an object is an array or not?**
```javascript
var arrayList = [1,2,3];
```
**Answer:**

```javascript
if( Object.prototype.toString.call( arrayList ) === '[object Array]' ) {
  console.log('Array!');
}
Or
Array.isArray(arrayList);
var toString = Object.prototype.toString;

toString.call(new Date);    // [object Date]
toString.call(new String);  // [object String]
toString.call(Math);        // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined);   // [object Undefined]
toString.call(null);        // [object Null]
```
#### Question7.
**== Vs ===**

**Answer:**

The simplest way of saying that, == will not check types and === will check whether both sides are of same type.
Rule for implicit coercion: Comparison by using == does implicit type conversion under the hood. And rules for implicit coercion are as follows-

If both operands are same type use ===
undefined == null
If one operands is string another is number, convert string to number
If one is boolean and another is non-boolean, convert boolean to number and then perform comparison
While comparing a string or number to an object, try to convert the object to a primitive type and then try to compare
Be careful while comparing objects, identifiers must reference the same objects or same array.
```javascript
var a = {a: 1};
var b = {a: 1};
a == b //false
a === b //false

var c = a;
a == c//true
a === c //true
```
Special note: NaN, null and undefined will never === another type. NaN does not even === itself.
#### Question8.
**How would you compare two objects in JavaScript?**

**Answer:**

```javascript
function objectEquals(v1, v2) {
    if (typeof(v1) !== typeof(v2)) {
        return false;
    }
    if (typeof(v1) === "function") {
        return v1.toString() === v2.toString();
    }
    if (v1 instanceof Object && v2 instanceof Object) {
        if (Object.getOwnPropertyNames(v1).length !== Object.getOwnPropertyNames(v2).length) {
            return false;
        }
        var r = true;
        for (k in v1) {
            r = objectEquals(v1[k], v2[k]);
            if (!r) {
                return false;
            }
        }
        return true;
    }

    return v1 === v2;
}
```
#### Question9.
**Delete can delete but**

**Answer:**

Look at the code below, I have a property in a object and I am creating a new object where I am setting it to a new value. If I delete that property what will i get if I try to access that property?
```javascript
var myObject = {
  price: 20.99,
  get_price : function() {
    return this.price;
  }
};
var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price());
```
**Answer:**

You will see 20.99
#### Question10.
**What is arrow function?**

**Answer:**

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
```javascript
(param1, param2, …, paramN) => { statements }
```
The other benefit of using arrow functions with promises/callbacks is that it reduces the confusion surrounding the this keyword. In code with multiple nested functions, it can be difficult to keep track of and remember to bind the correct this context. In ES5, you can use workarounds like the .bind method (which is slow) or creating a closure using var self = this;.
Because arrow functions allow you to retain the scope of the caller inside the function, you don't need to create self = this closures or use bind.

As was mentioned previously, the this keyword works differently in arrow functions. The methods call(), apply(), and bind() will not change the value of this in arrow functions. (In fact, the value of this inside of a function simply can't be changed–it will be the same value as when the function was called.) If you need to bind to a different value, you'll need to use a function expression.

Arrow functions cannot be used as constructors as other functions can.

Arrow functions do not have the local variable arguments as do other functions.

Where to use arrow functions:

Use function in the global scope and for Object.prototype properties.

Use class for object constructors.

Use => everywhere else

#### Question11.
**What is lambda function?**

**Answer:**

Lambda function is a function that is passed as parameter to another function or assigned to a variable.
```javascript
test = function(){alert("Hello1");};
test2 = test;
test = function(){alert("Hello2");};

//Passing functions
var list=new Array("A","AB","ABC","ABCD");
compare = function(a,b){
 return a.length-b.length;
}
list.sort(compare);
```
#### Question12.
**What are JavaScript types?**
**Answer:**

Following are the JavaScript types:
```javascript
Number
String
Boolean
Function
Object
Null
Undefined
```

## Getting Involved

  1. [Contributors](#contributors)
  2. [How to Contribute](https://github.com/danlex/javascript-questions/edit/master/CONTRIBUTING.md)
  3. [License](https://github.com/danlex/javascript-questions/blob/master/LICENSE)

### Contributors:
This document started in 2017 as a contribution of [@danlex].