text:
package edu.pitt.apollo.runmanagerservicerestfrontend.controller;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import edu.pitt.apollo.exception.UnsupportedAuthorizationTypeException;
import edu.pitt.apollo.runmanagerservicerestfrontend.exception.UnsupportedRunActionException;
import edu.pitt.apollo.runmanagerservicerestfrontend.methods.*;
import edu.pitt.apollo.services_common.v4_0_2.MethodCallStatusEnum;
import edu.pitt.apollo.services_common.v4_0_2.RunActionEnum;
import edu.pitt.apollo.services_common.v4_0_2.SerializationFormat;
import edu.pitt.apollo.types.v4_0_2.ApolloSoftwareTypeEnum;
import edu.pitt.isg.objectserializer.exceptions.SerializationException;
import edu.pitt.isg.objectserializer.exceptions.UnsupportedSerializationFormatException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import java.math.BigInteger;

/**
 * Created by dcs27 on 5/15/15. Purpose: This class contains the RESTful interfaces associated with the runs collection.
 */
@Controller
@RequestMapping("/ws")
public class RunsController {

	@GET
	@ApiOperation(value = "Get simulation group IDs for run.", notes = "Returns the simulation group IDs for run using a comma separated input.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/rungroup", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String getRunIdsInSimulationGroup(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                                      @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new GetRunIdsInSimulationGroupForRunMethod(SerializationFormat.XML, authorization).getRunIdsInSimulationGroupForRun(runId);
	}

	@GET
	@ApiOperation(value = "Get software identification.", notes = "Returns the software identification for the given run ID.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/softwareIdentification", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String getSoftwareIdentificationForRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                                           @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new GetSoftwareIdentificationForRunMethod(SerializationFormat.XML, authorization).getSoftwareIdentificationForRun(runId);
	}

	@POST
	@ApiOperation(value = "Insert run.", notes = "Inserts a given run into the runs collection.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/runs", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String postRunToRunsCollection(@RequestHeader("Authorization") String authorization,
			@ApiParam(value = "Run message.", required = true) @RequestBody String messageBody) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {
		return new InsertRunMethod(SerializationFormat.XML, authorization).insertRun(messageBody);
	}

	@POST
	@ApiOperation(value = "Set status.", notes = "Sets the status of a given run ID using a MethodCallStatusEnum and status message.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/status", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String updateStatusOfRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
			@ApiParam(value = "Method call status enum", required = true) @RequestParam("methodCallStatusEnum") MethodCallStatusEnum statusToUpdateTo,
			@ApiParam(value = "Status message", required = true) @RequestParam("statusMessage") String statusMessage,
                             @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new SetStatusOfRunMethod(SerializationFormat.XML, authorization).setStatusOfRun(runId, statusToUpdateTo, statusMessage);
	}

	@POST
	@ApiOperation(value = "Set the last service to be called for the run.", notes = "Sets the software identification for the last service to be called for a given run ID.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/lastServiceToBeCalled", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String updateLastServiceToBeCalledForRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
			@ApiParam(value = "Software name", required = true) @RequestParam("softwareName") String softwareName,
			@ApiParam(value = "Software version", required = true) @RequestParam("softwareVersion") String softwareVersion,
			@ApiParam(value = "Software developer", required = true) @RequestParam("softwareDeveloper") String softwareDeveloper,
			@ApiParam(value = "Apollo software type enum", required = true) @RequestParam("softwareTypeEnum") ApolloSoftwareTypeEnum softwareTypeEnum,
                                             @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new SetLastServiceToBeCalledForRunMethod(SerializationFormat.XML, authorization).setLastServiceToBeCalledForRunMethod(runId, softwareName,
				softwareVersion, softwareDeveloper, softwareTypeEnum);
	}

	@GET
	@ApiOperation(value = "Get last service to be called.", notes = "Returns the software identification for the last service to be called for a given run ID.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/lastServiceToBeCalled", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String getLastServiceToBeCalledForRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                                          @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new GetLastServiceToBeCalledForRunMethod(SerializationFormat.XML, authorization).getLastServiceToBeCalledForRun(runId);
	}

	@POST
	@ApiOperation(value = "Set simulation group IDs for run.", notes = "Sets the simulation group IDs for run using a comma separated input.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/rungroup", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String addRunIdsToSimulationGroupForRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
			@ApiParam(value = "List of run IDs to associate.", required = true) @RequestParam("runIdsToAssociate") String runIdsToAssociate,
                                            @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new AddRunIdsToSimulationGroupForRun(SerializationFormat.XML, authorization).addRunIdsToSimulationGroupForRun(runId, runIdsToAssociate);

	}

	@DELETE
	@ApiOperation(value = "Delete run.", notes = "Deletes run associated with the given run ID from the system. A user will need to have proper authentication to perform this task.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}", method = RequestMethod.DELETE, headers = "Accept=application/xml")
	public @ResponseBody
	String deleteRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                     @RequestHeader("Authorization") String authorization) throws SerializationException, UnsupportedSerializationFormatException, UnsupportedAuthorizationTypeException {

		return new DeleteRunMethod(SerializationFormat.XML, authorization).deleteRun(runId);
	}

	@GET
	@ApiOperation(value = "Get status.", notes = "Returns the method call status and message for the given run ID", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}/status", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String getStatusOfRun(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                          @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedAuthorizationTypeException {

		return new GetStatusOfRunMethod(SerializationFormat.XML, authorization).getStatusForRun(runId);
	}

	@POST
	@ApiOperation(value = "Perform action on the run.", notes = "Performs an action on the run (start or terminate).", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}", method = RequestMethod.POST, headers = "Accept=application/xml")
	public @ResponseBody
	String run(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
			@ApiParam(value = "Action", required = true) @RequestParam("action") RunActionEnum action,
               @RequestHeader("Authorization") String authorization) throws UnsupportedSerializationFormatException, SerializationException, UnsupportedRunActionException, UnsupportedAuthorizationTypeException {

		switch (action) {
			case START:
				return new StartRunMethod(SerializationFormat.XML, authorization).startRun(runId);
			case TERMINATE:
				return new TerminateRunMethod(SerializationFormat.XML, authorization).terminateRun(runId);
			default:
				throw new UnsupportedRunActionException("The specified run action value \"" + action + "\" is not recognized");
		}

	}

	//We cannot create a new collection at the URL level (PUT), and we cannot DELETE the URLs collection (DELETE).

	/*--Method to get run information such as groups, types, etc--*/
	@GET
	@ApiOperation(value = "Get information for run.", notes = "Returns the service type and all simulation group IDs associated with the run.", response = String.class)
	@ApiResponses(value = {
		@ApiResponse(code = 200, message = "")
	})
	@RequestMapping(value = "/run/{runId}", method = RequestMethod.GET, headers = "Accept=application/xml")
	public @ResponseBody
	String getRunInformation(@ApiParam(value = "Run ID.", required = true) @PathVariable("runId") BigInteger runId,
                             @RequestHeader("Authorization") String authorization) throws SerializationException, UnsupportedSerializationFormatException, UnsupportedAuthorizationTypeException {

		return new GetInformationForRunMethod(SerializationFormat.XML, authorization).getInformationForRun(runId);
	}

}


text:
Role Name
=========

A role to deploy SNORT Intrusion Detection system to a target CentOS 7, Ubuntu 14.04 and Ubunti 16.04 machine

Requirements
------------

No specific requirements.

Role Variables
--------------

To set a particular configuration that fits your needs, just change the 'roles/snort/files/snort.conf' configuration file - example: <br>

Dependencies
------------

* Openstack command line clients
* Shade >=1.16.0

Example Playbook
----------------

Get teh repo
* git clone https://github.com/sonata-nfv/son-security-pilot.git
* cd son-security-pilot/install

To generate an Ubuntu 16.0 VM with Snort on an Openstack VIM:
* ansible-playbook son-cmud.yml -e "ops=create plat=snort pop='YOUR_OS_VIM' proj='YOUR_OS_TENANT' distro='YOUR_PREFERED_OPERATING_SYSTEM_DISTRO'"

To install Squid onto the local machine:
* ansible-playbook utils/deploy/snort.yml

To install Squid onto a target machine:
* ansible-playbook utils/deploy/snort.yml [-e target='IP-ADDRESS-OF-THE-GUEST-MACHINE']

License
-------

Apache 2.0

Author Information
------------------

Alberto Rocha, Altice Labs (alberto-m-rocha@alticelabs.pt)

redpajama_set_name: RedPajamaGithub


text:
package cucumber.runtime.io;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipResourceIterator implements Iterator<Resource> {
    private final String path;
    private final String suffix;
    private final ZipFile jarFile;
    private final Enumeration<? extends ZipEntry> entries;
    private Resource next;

    public ZipResourceIterator(String zipPath, String path, String suffix) throws IOException {
        this.path = path;
        this.suffix = suffix;
        jarFile = new ZipFile(zipPath);
        entries = jarFile.entries();

        moveToNext();
    }

    @Override
    public boolean hasNext() {
        return next != null;
    }

    @Override
    public Resource next() {
        try {
            if (next == null) {
                throw new NoSuchElementException();
            }
            return next;
        } finally {
            moveToNext();
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    private void moveToNext() {
        next = null;
        while (entries.hasMoreElements()) {
            ZipEntry jarEntry = entries.nextElement();
            String entryName = jarEntry.getName();
            if (entryName.startsWith(path) && ClasspathIterable.hasSuffix(suffix, entryName)) {
                next = new ZipResource(jarFile, jarEntry);
                break;
            }
        }
    }
}


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Page
{
	///
	/// Starts sending each frame using the screencastFrame event.
	///
	[CommandResponse(ProtocolName.Page.StartScreencast)]
	public class StartScreencastCommandResponse
	{
	}
}


text:
                <button class="close-button" data-close aria-label="Close modal" type="button">

                </button>

{{= title }}

                <form id="form-{{=id}}" method="post" data-abide novalidate data-options="liveValidate: false;">

                            Desde
                                <input type="text" name="desde" class="datepicker-checkin" required data-max="today" />
                                La fecha inicial debe ser válida y menor que la fecha final.

                            Hasta
                                <input type="text" name="hasta" class="datepicker-checkout" required />
                                La fecha final debe ser mayor a la fecha incial.

                                <button class="md-button md-button__flat" type="submit">{{=buttonAccept}}</button>

                </form>


text:
/**
 * @author ZhangHuihua@msn.com
 */
$.setRegional("alertMsg", {
	title:{error:"Error", info:"Information", warn:"Warning", correct:"Successful", confirm:"Confirmation"},
	butMsg:{ok:"OK", yes:"Yes", no:"No", cancel:"Cancel"}
});
var alertMsg = {
	_boxId: "#alertMsgBox",
	_bgId: "#alertBackground",
	_closeTimer: null,

	_types: {error:"error", info:"info", warn:"warn", correct:"correct", confirm:"confirm"},

	_getTitle: function(key){
		return $.regional.alertMsg.title[key];
	},

	/**
	 *
	 * @param {Object} type
	 * @param {Object} msg
	 * @param {Object} buttons [button1, button2]
	 */
	_open: function(type, msg, buttons){
		$(this._boxId).remove();
		var butsHtml = "";
		if (buttons) {
			for (var i = 0; i < buttons.length; i++) {
				var sRel = buttons[i].call ? "callback" : "";
				butsHtml += DWZ.frag["alertButFrag"].replace("#butMsg#", buttons[i].name).replace("#callback#", sRel);
			}
		}
		var boxHtml = DWZ.frag["alertBoxFrag"].replace("#type#", type).replace("#title#", this._getTitle(type)).replace("#message#", msg).replace("#butFragment#", butsHtml);
		$(boxHtml).appendTo("body").css({top:-$(this._boxId).height()+"px"}).animate({top:"0px"}, 500);

		if (this._closeTimer) {
			clearTimeout(this._closeTimer);
			this._closeTimer = null;
		}
		if (this._types.info == type || this._types.correct == type){
			this._closeTimer = setTimeout(function(){alertMsg.close()}, 3500);
		} else {
			$(this._bgId).show();
		}
		var jCallButs = $(this._boxId).find("[rel=callback]");
		for (var i = 0; i < buttons.length; i++) {
			if (buttons[i].call) jCallButs.eq(i).click(buttons[i].call);
		}
	},
	close: function(){
		$(this._boxId).animate({top:-$(this._boxId).height()}, 500, function(){
			$(this).remove();
		});
		$(this._bgId).hide();
	},
	error: function(msg, options) {
		this._alert(this._types.error, msg, options);
	},
	info: function(msg, options) {
		this._alert(this._types.info, msg, options);
	},
	warn: function(msg, options) {
		this._alert(this._types.warn, msg, options);
	},
	correct: function(msg, options) {
		this._alert(this._types.correct, msg, options);
	},
	_alert: function(type, msg, options) {
		var op = {okName:$.regional.alertMsg.butMsg.ok, okCall:null};
		$.extend(op, options);
		var buttons = [
			{name:op.okName, call: op.okCall}
		];
		this._open(type, msg, buttons);
	},
	/**
	 *
	 * @param {Object} msg
	 * @param {Object} options {okName, okCal, cancelName, cancelCall}
	 */
	confirm: function(msg, options) {
		var op = {okName:$.regional.alertMsg.butMsg.ok, okCall:null, cancelName:$.regional.alertMsg.butMsg.cancel, cancelCall:null};
		$.extend(op, options);
		var buttons = [
			{name:op.okName, call: op.okCall},
			{name:op.cancelName, call: op.cancelCall}
		];
		this._open(this._types.confirm, msg, buttons);
	}
};


text:
@implementation SBSettingItemToggleSwitch

- (instancetype) initWithDictionary: (NSDictionary *) preferenceDictionary {
    self = [super init];

    if (self) {
        assert([[preferenceDictionary objectForKey:@"Type"] isEqualToString:@"PSToggleSwitchSpecifier"]);
        self.defaultValue = [preferenceDictionary objectForKey:@"DefaultValue"];
        self.key = [preferenceDictionary objectForKey:@"Key"];
        self.title = [preferenceDictionary objectForKey:@"Title"];
        self.type = @"PSToggleSwitchSpecifier";
    }

    return self;
}

-(NSString*) description {
    return [NSString stringWithFormat:@"ToggleSwitch: Title: %@; Key: %@; DefaultValue: %@;", self.title, self.key, self.defaultValue ? @"YES" : @"NO"];
}

@end


text:
package org.apache.camel.rx.support;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

import rx.Observer;
import rx.util.functions.Func1;

/**
 * A {@link Processor} which invokes an underling {@link Observer} as messages
 * arrive using the given function to convert the {@link Exchange} to the required
 * object
 */
public class ProcessorToObserver<T> implements Processor {
    private final Func1<Exchange, T> func;
    private final Observer<? super T> observer;

    public ProcessorToObserver(Func1<Exchange, T> func, Observer<? super T> observer) {
        this.func = func;
        this.observer = observer;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        Exception exception = null;
        if (exchange.isFailed()) {
            exception = exchange.getException();
        }
        if (exception != null) {
            observer.onError(exception);
        } else {
            T value = func.call(exchange);
            observer.onNext(value);
        }
    }
}


text:
> Create a package.json file

[![npm version](https://img.shields.io/npm/v/@pnpm/plugin-commands-init.svg)](https://www.npmjs.com/package/@pnpm/plugin-commands-init)

## Installation

```sh
pnpm add @pnpm/plugin-commands-init
```

## License

MIT


text:
// MESSAGE FLEXIFUNCTION_BUFFER_FUNCTION_ACK PACKING

#define MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK 153

typedef struct __mavlink_flexifunction_buffer_function_ack_t
{
 uint16_t func_index; /*< Function index*/
 uint16_t result; /*< result of acknowledge, 0=fail, 1=good*/
 uint8_t target_system; /*< System ID*/
 uint8_t target_component; /*< Component ID*/
} mavlink_flexifunction_buffer_function_ack_t;

#define MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN 6
#define MAVLINK_MSG_ID_153_LEN 6

#define MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC 109
#define MAVLINK_MSG_ID_153_CRC 109

#define MAVLINK_MESSAGE_INFO_FLEXIFUNCTION_BUFFER_FUNCTION_ACK { \
	"FLEXIFUNCTION_BUFFER_FUNCTION_ACK", \
	4, \
	{  { "func_index", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_flexifunction_buffer_function_ack_t, func_index) }, \
         { "result", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_flexifunction_buffer_function_ack_t, result) }, \
         { "target_system", NULL, MAVLINK_TYPE_UINT8_T, 0, 4, offsetof(mavlink_flexifunction_buffer_function_ack_t, target_system) }, \
         { "target_component", NULL, MAVLINK_TYPE_UINT8_T, 0, 5, offsetof(mavlink_flexifunction_buffer_function_ack_t, target_component) }, \
         } \
}

/**
 * @brief Pack a flexifunction_buffer_function_ack message
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 *
 * @param target_system System ID
 * @param target_component Component ID
 * @param func_index Function index
 * @param result result of acknowledge, 0=fail, 1=good
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
						       uint8_t target_system, uint8_t target_component, uint16_t func_index, uint16_t result)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN];
	_mav_put_uint16_t(buf, 0, func_index);
	_mav_put_uint16_t(buf, 2, result);
	_mav_put_uint8_t(buf, 4, target_system);
	_mav_put_uint8_t(buf, 5, target_component);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#else
	mavlink_flexifunction_buffer_function_ack_t packet;
	packet.func_index = func_index;
	packet.result = result;
	packet.target_system = target_system;
	packet.target_component = target_component;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK;
#if MAVLINK_CRC_EXTRA
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
}

/**
 * @brief Pack a flexifunction_buffer_function_ack message on a channel
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param target_system System ID
 * @param target_component Component ID
 * @param func_index Function index
 * @param result result of acknowledge, 0=fail, 1=good
 * @return length of the message in bytes (excluding serial stream start sign)
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
							   mavlink_message_t* msg,
						           uint8_t target_system,uint8_t target_component,uint16_t func_index,uint16_t result)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN];
	_mav_put_uint16_t(buf, 0, func_index);
	_mav_put_uint16_t(buf, 2, result);
	_mav_put_uint8_t(buf, 4, target_system);
	_mav_put_uint8_t(buf, 5, target_component);

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#else
	mavlink_flexifunction_buffer_function_ack_t packet;
	packet.func_index = func_index;
	packet.result = result;
	packet.target_system = target_system;
	packet.target_component = target_component;

        memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif

	msg->msgid = MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK;
#if MAVLINK_CRC_EXTRA
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
}

/**
 * @brief Encode a flexifunction_buffer_function_ack struct
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param msg The MAVLink message to compress the data into
 * @param flexifunction_buffer_function_ack C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_flexifunction_buffer_function_ack_t* flexifunction_buffer_function_ack)
{
	return mavlink_msg_flexifunction_buffer_function_ack_pack(system_id, component_id, msg, flexifunction_buffer_function_ack->target_system, flexifunction_buffer_function_ack->target_component, flexifunction_buffer_function_ack->func_index, flexifunction_buffer_function_ack->result);
}

/**
 * @brief Encode a flexifunction_buffer_function_ack struct on a channel
 *
 * @param system_id ID of this system
 * @param component_id ID of this component (e.g. 200 for IMU)
 * @param chan The MAVLink channel this message will be sent over
 * @param msg The MAVLink message to compress the data into
 * @param flexifunction_buffer_function_ack C-struct to read the message contents from
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_flexifunction_buffer_function_ack_t* flexifunction_buffer_function_ack)
{
	return mavlink_msg_flexifunction_buffer_function_ack_pack_chan(system_id, component_id, chan, msg, flexifunction_buffer_function_ack->target_system, flexifunction_buffer_function_ack->target_component, flexifunction_buffer_function_ack->func_index, flexifunction_buffer_function_ack->result);
}

/**
 * @brief Send a flexifunction_buffer_function_ack message
 * @param chan MAVLink channel to send the message
 *
 * @param target_system System ID
 * @param target_component Component ID
 * @param func_index Function index
 * @param result result of acknowledge, 0=fail, 1=good
 */
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS

static inline void mavlink_msg_flexifunction_buffer_function_ack_send(mavlink_channel_t chan, uint8_t target_system, uint8_t target_component, uint16_t func_index, uint16_t result)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char buf[MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN];
	_mav_put_uint16_t(buf, 0, func_index);
	_mav_put_uint16_t(buf, 2, result);
	_mav_put_uint8_t(buf, 4, target_system);
	_mav_put_uint8_t(buf, 5, target_component);

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
#else
	mavlink_flexifunction_buffer_function_ack_t packet;
	packet.func_index = func_index;
	packet.result = result;
	packet.target_system = target_system;
	packet.target_component = target_component;

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, (const char *)&packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, (const char *)&packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
#endif
}

#if MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
  This varient of _send() can be used to save stack space by re-using
  memory from the receive buffer.  The caller provides a
  mavlink_message_t which is the size of a full mavlink message. This
  is usually the receive buffer for the channel, and allows a reply to an
  incoming message with minimum stack space usage.
 */
static inline void mavlink_msg_flexifunction_buffer_function_ack_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan,  uint8_t target_system, uint8_t target_component, uint16_t func_index, uint16_t result)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
	char *buf = (char *)msgbuf;
	_mav_put_uint16_t(buf, 0, func_index);
	_mav_put_uint16_t(buf, 2, result);
	_mav_put_uint8_t(buf, 4, target_system);
	_mav_put_uint8_t(buf, 5, target_component);

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, buf, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
#else
	mavlink_flexifunction_buffer_function_ack_t *packet = (mavlink_flexifunction_buffer_function_ack_t *)msgbuf;
	packet->func_index = func_index;
	packet->result = result;
	packet->target_system = target_system;
	packet->target_component = target_component;

#if MAVLINK_CRC_EXTRA
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, (const char *)packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_CRC);
#else
    _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK, (const char *)packet, MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
#endif
}
#endif

#endif

// MESSAGE FLEXIFUNCTION_BUFFER_FUNCTION_ACK UNPACKING

/**
 * @brief Get field target_system from flexifunction_buffer_function_ack message
 *
 * @return System ID
 */
static inline uint8_t mavlink_msg_flexifunction_buffer_function_ack_get_target_system(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  4);
}

/**
 * @brief Get field target_component from flexifunction_buffer_function_ack message
 *
 * @return Component ID
 */
static inline uint8_t mavlink_msg_flexifunction_buffer_function_ack_get_target_component(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint8_t(msg,  5);
}

/**
 * @brief Get field func_index from flexifunction_buffer_function_ack message
 *
 * @return Function index
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_get_func_index(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  0);
}

/**
 * @brief Get field result from flexifunction_buffer_function_ack message
 *
 * @return result of acknowledge, 0=fail, 1=good
 */
static inline uint16_t mavlink_msg_flexifunction_buffer_function_ack_get_result(const mavlink_message_t* msg)
{
	return _MAV_RETURN_uint16_t(msg,  2);
}

/**
 * @brief Decode a flexifunction_buffer_function_ack message into a struct
 *
 * @param msg The message to decode
 * @param flexifunction_buffer_function_ack C-struct to decode the message contents into
 */
static inline void mavlink_msg_flexifunction_buffer_function_ack_decode(const mavlink_message_t* msg, mavlink_flexifunction_buffer_function_ack_t* flexifunction_buffer_function_ack)
{
#if MAVLINK_NEED_BYTE_SWAP
	flexifunction_buffer_function_ack->func_index = mavlink_msg_flexifunction_buffer_function_ack_get_func_index(msg);
	flexifunction_buffer_function_ack->result = mavlink_msg_flexifunction_buffer_function_ack_get_result(msg);
	flexifunction_buffer_function_ack->target_system = mavlink_msg_flexifunction_buffer_function_ack_get_target_system(msg);
	flexifunction_buffer_function_ack->target_component = mavlink_msg_flexifunction_buffer_function_ack_get_target_component(msg);
#else
	memcpy(flexifunction_buffer_function_ack, _MAV_PAYLOAD(msg), MAVLINK_MSG_ID_FLEXIFUNCTION_BUFFER_FUNCTION_ACK_LEN);
#endif
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
StringUtils.TraditionalBinaryPrefix (Facebook's realtime distributed database, powered by Apache Hadoop based on 0.20-append branch 0.20.1-dev API)
</TITLE>

<META NAME="date" CONTENT="2011-03-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

org.apache.hadoop.util

Enum StringUtils.TraditionalBinaryPrefix

java.lang.Object
  java.lang.Enum<StringUtils.TraditionalBinaryPrefix>
      org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<StringUtils.TraditionalBinaryPrefix>

Enclosing class:
StringUtils

public static enum StringUtils.TraditionalBinaryPrefix
extends java.lang.Enum<StringUtils.TraditionalBinaryPrefix>

The traditional binary prefixes, kilo, mega, ..., exa,
 which can be represented by a 64-bit integer.
 TraditionalBinaryPrefix symbol are case insensitive.

Enum Constant Summary

EXA

GIGA

KILO

MEGA

PETA

TERA

Field Summary

 char
symbol

 long
value

Method Summary

static long
string2long(java.lang.String s)

          Convert a string to long.

static StringUtils.TraditionalBinaryPrefix
valueOf(char symbol)

static StringUtils.TraditionalBinaryPrefix
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static StringUtils.TraditionalBinaryPrefix[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

KILO

public static final StringUtils.TraditionalBinaryPrefix KILO

MEGA

public static final StringUtils.TraditionalBinaryPrefix MEGA

GIGA

public static final StringUtils.TraditionalBinaryPrefix GIGA

TERA

public static final StringUtils.TraditionalBinaryPrefix TERA

PETA

public static final StringUtils.TraditionalBinaryPrefix PETA

EXA

public static final StringUtils.TraditionalBinaryPrefix EXA

Field Detail

value

public final long value

symbol

public final char symbol

Method Detail

values

public static StringUtils.TraditionalBinaryPrefix[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (StringUtils.TraditionalBinaryPrefix c : StringUtils.TraditionalBinaryPrefix.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static StringUtils.TraditionalBinaryPrefix valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

valueOf

public static StringUtils.TraditionalBinaryPrefix valueOf(char symbol)

Returns:
The TraditionalBinaryPrefix object corresponding to the symbol.

string2long

public static long string2long(java.lang.String s)

Convert a string to long.
 The input string is first be trimmed
 and then it is parsed with traditional binary prefix.

 For example,
 "-1230k" will be converted to -1230 * 1024 = -1259520;
 "891g" will be converted to 891 * 1024^3 = 956703965184;

Parameters:
s - input string

Returns:
a long value represented by the input string.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

This release is based on the Facebook's version of Hadoop.
Copyright © 2009 The Apache Software Foundation.


text:
package com.aston.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class ReflectionHelper {

	public static Class<?> genericOneType(Type returnType) {
		if (returnType instanceof ParameterizedType) {
			ParameterizedType ptype = (ParameterizedType) returnType;
			Type[] typeArguments = ptype.getActualTypeArguments();
			if (typeArguments != null && typeArguments.length == 1)
				return (Class<?>) typeArguments[0];
		}
		return null;
	}

	public static boolean isList(Class<?> type) {
		return List.class.isAssignableFrom(type);
	}
}


text:
package konstructs.api

import scala.collection.JavaConverters._

import org.scalatest.{ Matchers, WordSpec }

class ApiSpec extends WordSpec with Matchers {

  val SomeType = new BlockType(Array(0,0,0,0,0,0), BlockShape.BLOCK, false, false, BlockState.SOLID, BlockType.NO_CLASSES)

  "A BlockFilter" should {

    "Match a namespace" in {
      val filter = BlockFilterFactory
        .withNamespace("org/test")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual true
    }

    "Match a name" in {
      val filter = BlockFilterFactory
        .withName("test")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual true
    }

    "Match a name and namespace" in {
      val filter = BlockFilterFactory
        .withNamespace("org/test")
        .withName("test")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual true
    }

    "Not match an invalid namespace" in {
      val filter = BlockFilterFactory
        .withNamespace("invalid")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual false
    }

    "Not match an invalid name" in {
      val filter = BlockFilterFactory
        .withName("invalid")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual false
    }

    "Not match an invalid name even though namespace is correct" in {
      val filter = BlockFilterFactory
        .withNamespace("org/test")
        .withName("invalid")
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual false
    }

    "Match one name or another" in {
      val filter = BlockFilterFactory
        .withName("test")
        .or(BlockFilterFactory
          .withName("invalid"))
      filter.matches(new BlockTypeId("org/test", "test"), SomeType) shouldEqual true
    }

    "Match a complex filter" in {
      val filter = BlockFilterFactory
        .withNamespace("org/konstructs/forest")
        .or(BlockFilterFactory.VACUUM)
        .or(BlockFilterFactory
            .withNamespace("org/konstructs")
            .withName("wood"))
        .or(BlockFilterFactory
            .withNamespace("org/konstructs")
            .withName("leaves"));
      filter.matches(new BlockTypeId("org/konstructs", "vacuum"), SomeType) shouldEqual true
      filter.matches(new BlockTypeId("org/konstructs", "leaves"), SomeType) shouldEqual true
      filter.matches(new BlockTypeId("org/konstructs", "wood"), SomeType) shouldEqual true
      filter.matches(new BlockTypeId("org/konstructs/forest", "sapling"), SomeType) shouldEqual true
    }

  }

}


text:
package silhouette.password

/**
 * Defines the password hashers used by the application.
 *
 * Sometimes it's needed to change the password hashing algorithm, because of a better algorithm or some
 * similar case. But the passwords stored in the backing store cannot easily be converted with another
 * algorithm because they're hashed and cannot be decrypted back to plain text. For such case Silhouette
 * supports the change of hashing algorithms on the fly. So if a user successfully authenticates after
 * the application has changed the hashing algorithm, the provider hashes the entered plain-text password
 * again with the new algorithm and overrides the auth info in the backing store with the new hash.
 *
 * The password hasher registry defines the current password hasher which is able to hash all new passwords
 * and also match the passwords stored in the backing store for this algorithm. And also a list of deprecated
 * hashers, which should match passwords that are stored in the baking store but which are different to the
 * current hasher.
 *
 * @param current    The current password hasher used by the application.
 * @param deprecated The deprecated list of password hashers.
 */
final case class PasswordHasherRegistry(current: PasswordHasher, deprecated: List[PasswordHasher] = List()) {

  /**
   * Returns the complete list of supported password hashers.
   *
   * @return The complete list of supported password hashers.
   */
  def all: List[PasswordHasher] = current +: deprecated

  /**
   * Finds the password hasher suitable for the given password info.
   *
   * First it checks if the current hasher is suitable for the given password hasher. As next it checks
   * if a deprecated password hasher is suitable for the given password info. If non of the registered
   * password hasher is suitable for the given password info, this method returns `None`.
   *
   * @param passwordInfo The password info to return a suitable password hasher for.
   * @return Maybe a suitable password hasher, otherwise None.
   */
  def find(passwordInfo: PasswordInfo): Option[PasswordHasher] = all.find(_.isSuitable(passwordInfo))

  /**
   * Indicates if a hasher is in the list of deprecated hashers.
   *
   * @param hasher The hasher to check the deprecation status for.
   * @return True if the given hasher is deprecated, false otherwise.
   */
  def isDeprecated(hasher: PasswordHasher): Boolean = deprecated.contains(hasher)
}


text:
package de.adito.propertly.core.common;

import de.adito.propertly.core.spi.IPropertyDescription;
import de.adito.propertly.core.spi.IPropertyPit;
import de.adito.propertly.core.spi.IPropertyPitProvider;

/**
 * A helper class to quickly supply getters and setters.
 *
 * @author PaL
 *         Date: 12.10.12
 *         Time: 23:10
 */
public class GetterSetterGen
{

  private GetterSetterGen()
  {
  }

  public static void run(IPropertyPit<?, ?, ?> pPit)
  {
    run(pPit, null);
  }

  public static void run(IPropertyPitProvider<?, ?, ?> pPitProvider, String pPitName)
  {
    String pit = pPitName == null || pPitName.isEmpty() ? "" : pPitName + ".";
    for (IPropertyDescription<?, ?> prop : pPitProvider.getPit().getPropertyDescriptions())
    {
      System.out.println("public IProperty<" + prop.getSourceType().getSimpleName() + ", " +
          prop.getType().getSimpleName() + "> getProperty" + capitalize(prop.getName()) +
          "(){return " + pit + "getProperty(" + prop.getName().toUpperCase() + ");}");

      System.out.println("public " + prop.getType().getSimpleName() + " get" + capitalize(prop.getName()) +
          "(){return " + pit + "getValue(" + prop.getName().toUpperCase() + ");}");

      System.out.println("public void set" + capitalize(prop.getName()) + "(" + prop.getType().getSimpleName() +
          " p" + capitalize(prop.getName()) + "){" + pit + "setValue(" + prop.getName().toUpperCase() + ", p" +
          capitalize(prop.getName()) + ");}");
    }
  }

  static String capitalize(String pStr)
  {
    if (pStr == null || pStr.isEmpty())
      return pStr;
    return pStr.substring(0, 1).toUpperCase() + pStr.substring(1, pStr.length());
  }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cephalocereus zehntneri Britton & Rose

### Remarks
null


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/io.h>

#ifndef _WIN32

#include "io.h"

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>

#include <winpr/crt.h>
#include <winpr/path.h>
#include <winpr/file.h>

/**
 * I/O Manager Routines
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff551797/
 *
 * These routines are only accessible to kernel drivers, but we need
 * similar functionality in WinPR in user space.
 *
 * This is a best effort non-conflicting port of this API meant for
 * non-Windows, WinPR usage only.
 *
 * References:
 *
 * Device Objects and Device Stacks:
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff543153/
 *
 * Driver Development Part 1: Introduction to Drivers:
 * http://www.codeproject.com/Articles/9504/Driver-Development-Part-1-Introduction-to-Drivers/
 */

#define DEVICE_FILE_PREFIX_PATH "\\Device\\"

static char* GetDeviceFileNameWithoutPrefixA(LPCSTR lpName)
{
	char* lpFileName;

	if (!lpName)
		return NULL;

	if (strncmp(lpName, DEVICE_FILE_PREFIX_PATH, sizeof(DEVICE_FILE_PREFIX_PATH) - 1) != 0)
		return NULL;

	lpFileName =
	    _strdup(&lpName[strnlen(DEVICE_FILE_PREFIX_PATH, sizeof(DEVICE_FILE_PREFIX_PATH))]);
	return lpFileName;
}

static char* GetDeviceFileUnixDomainSocketBaseFilePathA(void)
{
	char* lpTempPath;
	char* lpPipePath;
	lpTempPath = GetKnownPath(KNOWN_PATH_TEMP);

	if (!lpTempPath)
		return NULL;

	lpPipePath = GetCombinedPath(lpTempPath, ".device");
	free(lpTempPath);
	return lpPipePath;
}

static char* GetDeviceFileUnixDomainSocketFilePathA(LPCSTR lpName)
{
	char* lpPipePath = NULL;
	char* lpFileName = NULL;
	char* lpFilePath = NULL;
	lpPipePath = GetDeviceFileUnixDomainSocketBaseFilePathA();

	if (!lpPipePath)
		return NULL;

	lpFileName = GetDeviceFileNameWithoutPrefixA(lpName);

	if (!lpFileName)
	{
		free(lpPipePath);
		return NULL;
	}

	lpFilePath = GetCombinedPath(lpPipePath, (char*)lpFileName);
	free(lpPipePath);
	free(lpFileName);
	return lpFilePath;
}

/**
 * IoCreateDevice:
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff548397/
 */

NTSTATUS _IoCreateDeviceEx(PDRIVER_OBJECT_EX DriverObject, ULONG DeviceExtensionSize,
                           PUNICODE_STRING DeviceName, DEVICE_TYPE DeviceType,
                           ULONG DeviceCharacteristics, BOOLEAN Exclusive,
                           PDEVICE_OBJECT_EX* DeviceObject)
{
	int status;
	char* DeviceBasePath;
	DEVICE_OBJECT_EX* pDeviceObjectEx;
	DeviceBasePath = GetDeviceFileUnixDomainSocketBaseFilePathA();

	if (!DeviceBasePath)
		return STATUS_NO_MEMORY;

	if (!PathFileExistsA(DeviceBasePath))
	{
		if (mkdir(DeviceBasePath, S_IRUSR | S_IWUSR | S_IXUSR) != 0)
		{
			free(DeviceBasePath);
			return STATUS_ACCESS_DENIED;
		}
	}

	free(DeviceBasePath);
	pDeviceObjectEx = (DEVICE_OBJECT_EX*)calloc(1, sizeof(DEVICE_OBJECT_EX));

	if (!pDeviceObjectEx)
		return STATUS_NO_MEMORY;

	ConvertFromUnicode(CP_UTF8, 0, DeviceName->Buffer, DeviceName->Length / 2,
	                   &(pDeviceObjectEx->DeviceName), 0, NULL, NULL);

	if (!pDeviceObjectEx->DeviceName)
	{
		free(pDeviceObjectEx);
		return STATUS_NO_MEMORY;
	}

	pDeviceObjectEx->DeviceFileName =
	    GetDeviceFileUnixDomainSocketFilePathA(pDeviceObjectEx->DeviceName);

	if (!pDeviceObjectEx->DeviceFileName)
	{
		free(pDeviceObjectEx->DeviceName);
		free(pDeviceObjectEx);
		return STATUS_NO_MEMORY;
	}

	if (PathFileExistsA(pDeviceObjectEx->DeviceFileName))
	{
		if (unlink(pDeviceObjectEx->DeviceFileName) == -1)
		{
			free(pDeviceObjectEx->DeviceName);
			free(pDeviceObjectEx->DeviceFileName);
			free(pDeviceObjectEx);
			return STATUS_ACCESS_DENIED;
		}
	}

	status = mkfifo(pDeviceObjectEx->DeviceFileName, 0666);

	if (status != 0)
	{
		free(pDeviceObjectEx->DeviceName);
		free(pDeviceObjectEx->DeviceFileName);
		free(pDeviceObjectEx);

		switch (errno)
		{
			case EACCES:
				return STATUS_ACCESS_DENIED;

			case EEXIST:
				return STATUS_OBJECT_NAME_EXISTS;

			case ENAMETOOLONG:
				return STATUS_NAME_TOO_LONG;

			case ENOENT:
			case ENOTDIR:
				return STATUS_NOT_A_DIRECTORY;

			case ENOSPC:
				return STATUS_DISK_FULL;

			default:
				return STATUS_INTERNAL_ERROR;
		}
	}

	*((ULONG_PTR*)(DeviceObject)) = (ULONG_PTR)pDeviceObjectEx;
	return STATUS_SUCCESS;
}

/**
 * IoDeleteDevice:
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff549083/
 */

VOID _IoDeleteDeviceEx(PDEVICE_OBJECT_EX DeviceObject)
{
	DEVICE_OBJECT_EX* pDeviceObjectEx;
	pDeviceObjectEx = (DEVICE_OBJECT_EX*)DeviceObject;

	if (!pDeviceObjectEx)
		return;

	unlink(pDeviceObjectEx->DeviceFileName);
	free(pDeviceObjectEx->DeviceName);
	free(pDeviceObjectEx->DeviceFileName);
	free(pDeviceObjectEx);
}

/**
 * IoCreateSymbolicLink:
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff549043/
 */

static NTSTATUS _IoCreateSymbolicLinkEx(PUNICODE_STRING SymbolicLinkName,
                                        PUNICODE_STRING DeviceName)
{
	return STATUS_SUCCESS;
}

/**
 * IoDeleteSymbolicLink:
 * http://msdn.microsoft.com/en-us/library/windows/hardware/ff549085/
 */

static NTSTATUS _IoDeleteSymbolicLinkEx(PUNICODE_STRING SymbolicLinkName)
{
	return STATUS_SUCCESS;
}

#endif


text:
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Tools.WindowsInstallerXml;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Management;  // Reference C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Management.dll
using System.Security.AccessControl;
using System.Security.Principal;
using System.ServiceProcess;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace MinionConfigurationExtension {
    public class MinionConfiguration : WixExtension {

        [CustomAction]
        public static ActionResult ReadConfig_IMCAC(Session session) {
            /*
            When the installation begins, there may be a previous installation with existing config.
            If existing config is found, we need to verify that it is in a secure state. If it is
            secure then it will be used as is, unchanged.

            We will read the values from existing config to possibly display in the GUI, but it will
            be for informational purposes only. The only CONFIG_TYPES that will be edited are
            DEFAULT and CUSTOM.

            The two config options and their defaults are:
              - master: salt
              - id: hostname

            If the CONFIG_TYPE is not "Existing", and the master and minion id are not the defaults,
            then those values will be used to update either the Default config or a Custom config.

            This function writes msi properties:
              - MASTER
              - MINION_ID
              - CONFIG_TYPE

            A GUI installation can show these msi properties because this function is called before the GUI.
            */
            session.Log("...BEGIN ReadConfig_IMCAC");
            string ProgramData    = System.Environment.GetEnvironmentVariable("ProgramData");

            string oldRootDir = @"C:\salt";
            string newRootDir =  Path.Combine(ProgramData, @"Salt Project\Salt");

            // Create msi proporties
            session["ROOTDIR_old"] = oldRootDir;
            session["ROOTDIR_new"] = newRootDir;

            string abortReason = "";
            // Insert the first abort reason here
            if (abortReason.Length > 0) {
                session["AbortReason"] = abortReason;
            }

            session.Log("...Looking for existing config");
            string REGISTRY_ROOTDIR = session["EXISTING_ROOTDIR"];          // From registry
            string reg_config = "";
            if (REGISTRY_ROOTDIR.Length > 0){
                reg_config = REGISTRY_ROOTDIR + @"\conf\minion";
            }
            // Search for configuration in this order: registry, new layout, old layout
            string minion_config_file = cutil.get_file_that_exist(session, new string[] {
                reg_config,
                newRootDir + @"\conf\minion",
                oldRootDir + @"\conf\minion"});
            string minion_config_dir = "";

            // Check for a minion.d directory
            if (File.Exists(minion_config_file)) {
                string minion_dot_d_dir = minion_config_file + ".d";
                session.Log("...minion_dot_d_dir = " + minion_dot_d_dir);
                if (Directory.Exists(minion_dot_d_dir)) {
                    session.Log("... folder exists minion_dot_d_dir = " + minion_dot_d_dir);
                    DirectorySecurity dirSecurity = Directory.GetAccessControl(minion_dot_d_dir);
                    IdentityReference sid = dirSecurity.GetOwner(typeof(SecurityIdentifier));
                    session.Log("...owner of the minion config dir " + sid.Value);
                } else {
                    session.Log("... folder does not exist: " + minion_dot_d_dir);
                }
            }

            // Check for existing config
            if (File.Exists(minion_config_file)) {
                // We found an existing config
                session["CONFIG_TYPE"] = "Existing";

                // Make sure the directory where the config was found is secure
                minion_config_dir = Path.GetDirectoryName(minion_config_file);
                // Owner must be one of "Local System" or "Administrators"
                // It looks like the NullSoft installer sets the owner to
                // Administrators while the MSI installer sets the owner to
                // Local System. Salt only sets the owner of the `C:\salt`
                // directory when it starts and doesn't concern itself with the
                // conf directory. So we have to check for both.
                List<string> valid_sids = new List<string>();
                valid_sids.Add("S-1-5-18");      //Local System
                valid_sids.Add("S-1-5-32-544");  //Administrators

                // Get the SID for the owner of the conf directory
                FileSecurity fileSecurity = File.GetAccessControl(minion_config_dir);
                IdentityReference sid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
                session.Log("...owner of the minion config file " + sid.Value);

                // Check to see if it's in the list of valid SIDs
                if (!valid_sids.Contains(sid.Value)) {
                    // If it's not in the list we don't want to use it. Do the following:
                    // - set INSECURE_CONFIG_FOUND to the insecure config dir
                    // - set CONFIG_TYPE to Default
                    session.Log("...Insecure config found, using default config");
                    session["INSECURE_CONFIG_FOUND"] = minion_config_dir;
                    session["CONFIG_TYPE"] = "Default";
                    session["GET_CONFIG_TEMPLATE_FROM_MSI_STORE"] = "True";    // Use template instead
                }
            } else {
                session["GET_CONFIG_TEMPLATE_FROM_MSI_STORE"] = "True";    // Use template
            }

            // Set the default values for master and id
            String master_from_previous_installation = "";
            String id_from_previous_installation = "";
            // Read master and id from main config file (if such a file exists)
            if (minion_config_file.Length > 0) {
                read_master_and_id_from_file_IMCAC(session, minion_config_file, ref master_from_previous_installation, ref id_from_previous_installation);
            }
            // Read master and id from minion.d/*.conf (if they exist)
            if (Directory.Exists(minion_config_dir)) {
                var conf_files = System.IO.Directory.GetFiles(minion_config_dir, "*.conf");
                foreach (var conf_file in conf_files) {
                    if (conf_file.Equals("_schedule.conf")) { continue; }            // skip _schedule.conf
                    read_master_and_id_from_file_IMCAC(session, conf_file, ref master_from_previous_installation, ref id_from_previous_installation);
                }
            }

            if (session["MASTER"] == "") {
                session["MASTER"] = "salt";
            }
            if (session["MINION_ID"] == "") {
                session["MINION_ID"] = "hostname";
            }

            session.Log("...CONFIG_TYPE msi property  = " + session["CONFIG_TYPE"]);
            session.Log("...MASTER      msi property  = " + session["MASTER"]);
            session.Log("...MINION_ID   msi property  = " + session["MINION_ID"]);

            // A list of config types that will be edited. Existing config will NOT be edited
            List<string> editable_types = new List<string>();
            editable_types.Add("Default");
            editable_types.Add("Custom");
            if (editable_types.Contains(session["CONFIG_TYPE"])) {
                // master
                if (master_from_previous_installation != "") {
                    session.Log("...MASTER      kept config   =" + master_from_previous_installation);
                    session["MASTER"] = master_from_previous_installation;
                    session["CONFIG_FOUND"] = "True";
                    session.Log("...MASTER set to kept config");
                }

                // minion id
                if (id_from_previous_installation != "") {
                    session.Log("...MINION_ID   kept config   =" + id_from_previous_installation);
                    session.Log("...MINION_ID set to kept config ");
                    session["MINION_ID"] = id_from_previous_installation;
                }
            }

            // Save the salt-master public key
            // This assumes the install is silent.
            // Saving should only occur in WriteConfig_DECAC,
            // IMCAC is easier and no harm because there is no public master key in the installer.
            string MASTER_KEY = cutil.get_property_IMCAC(session, "MASTER_KEY");
            string ROOTDIR    = cutil.get_property_IMCAC(session, "ROOTDIR");
            string pki_minion_dir = Path.Combine(ROOTDIR, @"conf\minion.d\pki\minion");
            var master_key_file = Path.Combine(pki_minion_dir, "minion_master.pub");
            session.Log("...master_key_file           = " + master_key_file);
            bool MASTER_KEY_set = MASTER_KEY != "";
            session.Log("...master key earlier config file exists = " + File.Exists(master_key_file));
            session.Log("...master key msi property given         = " + MASTER_KEY_set);
            if (MASTER_KEY_set) {
                String master_key_lines = "";   // Newline after 64 characters
                int count_characters = 0;
                foreach (char character in MASTER_KEY) {
                    master_key_lines += character;
                    count_characters += 1;
                    if (count_characters % 64 == 0) {
                        master_key_lines += Environment.NewLine;
                    }
                }
                string new_master_pub_key =
                  "-----BEGIN PUBLIC KEY-----" + Environment.NewLine +
                  master_key_lines + Environment.NewLine +
                  "-----END PUBLIC KEY-----";
                if (!Directory.Exists(pki_minion_dir)) {
                    // The <Directory> declaration in Product.wxs does not create the folders
                    Directory.CreateDirectory(pki_minion_dir);
                }
                File.WriteAllText(master_key_file, new_master_pub_key);
            }
            session.Log("...END ReadConfig_IMCAC");
            return ActionResult.Success;
        }

        private static void write_master_and_id_to_file_DECAC(Session session, String config_file, string csv_multimasters, String id) {
            /* How to
             * read line
             * if line master, read multimaster, replace
             * if line id, replace
             * copy through line
            */

            session.Log("...BEGIN write_master_and_id_to_file_DECAC");
            session.Log("...want to write master and id to " + config_file);
            session.Log("......master: " + csv_multimasters);
            session.Log("......id: " + id);

            if (File.Exists(config_file)) {
                session.Log("...config_file exists: " + config_file);
            } else {
                session.Log("......ERROR: no config file found: {0}", config_file);
                return;
            }

            // Load current config
            string config_content = File.ReadAllText(config_file);

            // Only attempt to replace master if master value is passed
            // If master value is not passed, the default is "salt"
            if (csv_multimasters != "salt") {
                // Let's see if we have multiple masters
                char[] separators = new char[] { ',', ' ' };
                string[] multimasters = csv_multimasters.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                string masters = string.Join(Environment.NewLine, multimasters);
                string master_value = "";
                if (multimasters.Length > 1) {
                    // Multimaster
                    master_value = "master:";
                    foreach (string master in multimasters) {
                        master_value += Environment.NewLine + "- " + master;
                    }
                    master_value = master_value.Trim() + Environment.NewLine;
                } else {
                    // Single Master
                    master_value = "master: " + masters.Trim() + Environment.NewLine;
                }
                session.Log("...New Master Value: {0}", master_value);

                bool master_emitted = false;

                // Single master entry
                Regex regx_single_master = new Regex(@"(^master:[ \t]+\S+\r?\n?)", RegexOptions.Multiline);
                // Search config using single master matcher
                session.Log("...Searching for single_master");
                session.Log(config_content);
                MatchCollection master_matches = regx_single_master.Matches(config_content);
                // If one is found, replace with the new master value and done
                if (master_matches.Count == 1) {
                    session.Log("......Found single master, setting new master value");
                    config_content = regx_single_master.Replace(config_content, master_value);
                    master_emitted = true;
                } else if (master_matches.Count > 1) {
                    session.Log("......ERROR Found multiple matches for single master");
                }

                if (!master_emitted) {
                    // Multimaster entry
                    Regex regx_multi_master = new Regex(@"(^master: *(?:\r?\n?- +.*\r?\n?)+\r?\n?)", RegexOptions.Multiline);
                    // Search config using multi master matcher
                    session.Log("...Searching for multi master");
                    master_matches = regx_multi_master.Matches(config_content);
                    // If one is found, replace with the new master value and done
                    if (master_matches.Count == 1) {
                        session.Log("......Found multi master, setting new master value");
                        config_content = regx_multi_master.Replace(config_content, master_value);
                        master_emitted = true;
                    } else if (master_matches.Count > 1) {
                        session.Log("......ERROR Found multiple matches for multi master");
                    }
                }

                if (!master_emitted) {
                    // Commented master entry
                    Regex regx_commented_master = new Regex(@"(^# *master: *\S+\r?\n?)", RegexOptions.Multiline);
                    // Search config using commented master matcher
                    session.Log("...Searching for commented master");
                    master_matches = regx_commented_master.Matches(config_content);
                    // If one is found, replace with the new master value and done
                    if (master_matches.Count == 1) {
                        session.Log("......Found commented master, setting new master value");
                        // This one's a little different, we want to keep the comment
                        // and add the new master on the next line
                        config_content = regx_commented_master.Replace(config_content, "$1" + master_value);
                        master_emitted = true;
                    } else if (master_matches.Count > 1) {
                        session.Log("......ERROR Found multiple matches for single master");
                    }
                }

                if (!master_emitted) {
                    // Commented multi master entry
                    Regex regx_commented_multi_master = new Regex(@"(^# *master: *(?:\r?\n?# *- +.+\r?\n?)+)", RegexOptions.Multiline);
                    // Search config using commented multi master matcher
                    session.Log("...Searching for commented multi master");
                    master_matches = regx_commented_multi_master.Matches(config_content);
                    // If one is found, replace with the new master value and done
                    if (master_matches.Count == 1) {
                        session.Log("......Found commented multi master, setting new master value");
                        // This one's a little different, we want to keep the comment
                        // and add the new master on the next line
                        config_content = regx_commented_multi_master.Replace(config_content, "$1" + master_value);
                        master_emitted = true;
                    } else if (master_matches.Count > 1) {
                        session.Log("......ERROR Found multiple matches for single master");
                    }
                }
                if (!master_emitted) {
                    session.Log("......No master found in config, appending master");
                    config_content = config_content + master_value;
                    master_emitted = true;
                }
            }

            // Only attempt to replace the minion id if a minion id is passed
            // If the minion id is not passed, the default is "hostname"
            if (id != "hostname") {

                string id_value = "id: " + id + Environment.NewLine;
                bool id_emitted = false;

                // id entry
                Regex regx_id = new Regex(@"(^id:[ \t]+\S+\r?\n?)", RegexOptions.Multiline);
                // Search config using id matcher
                session.Log("...Searching for id");
                MatchCollection id_matches = regx_id.Matches(config_content);
                // If one is found, replace with the new id value and done
                if (id_matches.Count == 1) {
                    session.Log("......Found id, setting new id value");
                    config_content = regx_id.Replace(config_content, id_value);
                    id_emitted = true;
                } else if (id_matches.Count > 1) {
                    session.Log("......ERROR Found multiple matches for id");
                }

                if (!id_emitted) {
                    // commented id entry
                    Regex regx_commented_id = new Regex(@"(^# *id: *\S+\r?\n?)", RegexOptions.Multiline);
                    // Search config using commented id matcher
                    session.Log("...Searching for commented id");
                    id_matches = regx_commented_id.Matches(config_content);
                    // If one is found, replace with the new id value and done
                    if (id_matches.Count == 1) {
                        session.Log("......Found commented id, setting new id value");
                        config_content = regx_commented_id.Replace(config_content, "$1" + id_value);
                        id_emitted = true;
                    } else if (id_matches.Count > 1) {
                        session.Log("......ERROR Found multiple matches for commented id");
                    }
                }

                if (!id_emitted) {
                    // commented id entry
                    Regex regx_commented_id_empty = new Regex(@"(^# *id: *\r?\n?)", RegexOptions.Multiline);
                    // Search config using commented id matcher
                    session.Log("...Searching for commented id");
                    id_matches = regx_commented_id_empty.Matches(config_content);
                    // If one is found, replace with the new id value and done
                    if (id_matches.Count == 1) {
                        session.Log("......Found commented id, setting new id value");
                        config_content = regx_commented_id_empty.Replace(config_content, "$1" + id_value);
                        id_emitted = true;
                    } else if (id_matches.Count > 1) {
                        session.Log("......ERROR Found multiple matches for commented id");
                    }
                }
                if (!id_emitted) {
                    session.Log("......No minion ID found in config, appending minion ID");
                    config_content = config_content + id_value;
                    id_emitted = true;
                }
            }
            session.Log("...Writing config content to: {0}", config_file);
            File.WriteAllText(config_file, config_content);

            session.Log("...END write_master_and_id_to_file_DECAC");
        }

        private static void read_master_and_id_from_file_IMCAC(Session session, String configfile, ref String ref_master, ref String ref_id) {
            /* How to match multimasters *
                match `master: `MASTER*:
                if MASTER:
                  master = MASTER
                else, a list of masters may follow:
                  while match `- ` MASTER:
                    master += MASTER
            */
            if (configfile.Length == 0) {
                session.Log("...configfile not passed");
                return;
            }
            if (!File.Exists(configfile)) {
                session.Log("...configfile does not exist: " + configfile);
                return;
            }
            session.Log("...searching master and id in " + configfile);
            bool configExists = File.Exists(configfile);
            session.Log("......file exists " + configExists);
            if (!configExists) { return; }
            string[] configLines = File.ReadAllLines(configfile);
            Regex line_key_maybe_value = new Regex(@"^([a-zA-Z_]+):\s*([0-9a-zA-Z_.-]*)\s*$");
            Regex line_listvalue = new Regex(@"^\s*-\s*(.*)$");
            bool look_for_keys_otherwise_look_for_multimasters = true;
            List<string> multimasters = new List<string>();
            foreach (string line in configLines) {
                if (look_for_keys_otherwise_look_for_multimasters && line_key_maybe_value.IsMatch(line)) {
                    Match m = line_key_maybe_value.Match(line);
                    string key = m.Groups[1].ToString();
                    string maybe_value = m.Groups[2].ToString();
                    //session.Log("...ANY KEY " + key + " " + maybe_value);
                    if (key == "master") {
                        if (maybe_value.Length > 0) {
                            ref_master = maybe_value;
                            session.Log("......master " + ref_master);
                        } else {
                            session.Log("...... now searching multimasters");
                            look_for_keys_otherwise_look_for_multimasters = false;
                        }
                    }
                    if (key == "id" && maybe_value.Length > 0) {
                        ref_id = maybe_value;
                        session.Log("......id " + ref_id);
                    }
                } else if (line_listvalue.IsMatch(line)) {
                    Match m = line_listvalue.Match(line);
                    multimasters.Add(m.Groups[1].ToString());
                } else {
                    look_for_keys_otherwise_look_for_multimasters = true;
                }
            }
            if (multimasters.Count > 0) {
                ref_master = string.Join(",", multimasters.ToArray());
                session.Log("......master " + ref_master);
            }
        }

       [CustomAction]
        public static void stop_service(Session session, string a_service) {
            // the installer cannot assess the log file unless it is released.
            session.Log("...stop_service " + a_service);
            ServiceController service = new ServiceController(a_service);
            service.Stop();
            var timeout = new TimeSpan(0, 0, 1); // seconds
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        }

       [CustomAction]
        public static ActionResult kill_python_exe(Session session) {
            // because a running process can prevent removal of files
            // Get full path and command line from running process
            // see https://github.com/saltstack/salt/issues/42862
            session.Log("...BEGIN kill_python_exe");
            using (var wmi_searcher = new ManagementObjectSearcher
                ("SELECT ProcessID, ExecutablePath, CommandLine FROM Win32_Process WHERE Name = 'python.exe'")) {
                foreach (ManagementObject wmi_obj in wmi_searcher.Get()) {
                    try {
                        String ProcessID = wmi_obj["ProcessID"].ToString();
                        Int32 pid = Int32.Parse(ProcessID);
                        String ExecutablePath = wmi_obj["ExecutablePath"].ToString();
                        String CommandLine = wmi_obj["CommandLine"].ToString();
                        if (CommandLine.ToLower().Contains("salt") || ExecutablePath.ToLower().Contains("salt")) {
                            session.Log("...kill_python_exe " + ExecutablePath + " " + CommandLine);
                            Process proc11 = Process.GetProcessById(pid);
                            proc11.Kill();
                        }
                    } catch (Exception) {
                        // ignore wmiresults without these properties
                    }
                }
            }
            session.Log("...END kill_python_exe");
            return ActionResult.Success;
        }

        [CustomAction]
        public static ActionResult del_NSIS_DECAC(Session session) {
            // Leaves the Config
            /*
             * If NSIS is installed:
             *   remove salt-minion service,
             *   remove registry
             *   remove files, except /salt/conf and /salt/var
             *
             *   The msi cannot use uninst.exe because the service would no longer start.
            */
            session.Log("...BEGIN del_NSIS_DECAC");
            RegistryKey HKLM = Registry.LocalMachine;

            string ARPstring = @"Microsoft\Windows\CurrentVersion\Uninstall\Salt Minion";
            RegistryKey ARPreg = cutil.get_registry_SOFTWARE_key(session, ARPstring);
            string uninstexe = "";
            if (ARPreg != null) uninstexe = ARPreg.GetValue("UninstallString").ToString();
            session.Log("from REGISTRY uninstexe = " + uninstexe);

            string SOFTWAREstring = @"Salt Project\Salt";
            RegistryKey SOFTWAREreg = cutil.get_registry_SOFTWARE_key(session, SOFTWAREstring);
            var bin_dir = "";
            if (SOFTWAREreg != null) bin_dir = SOFTWAREreg.GetValue("bin_dir").ToString();
            session.Log("from REGISTRY bin_dir = " + bin_dir);
            if (bin_dir == "") bin_dir = @"C:\salt\bin";
            session.Log("bin_dir = " + bin_dir);

            session.Log("Going to stop service salt-minion ...");
            cutil.shellout(session, "sc stop salt-minion");

            session.Log("Going to delete service salt-minion ...");
            cutil.shellout(session, "sc delete salt-minion");

            session.Log("Going to kill ...");
            kill_python_exe(session);

            session.Log("Going to delete ARP registry entry ...");
            cutil.del_registry_SOFTWARE_key(session, ARPstring);

            session.Log("Going to delete SOFTWARE registry entry ...");
            cutil.del_registry_SOFTWARE_key(session, SOFTWAREstring);

            session.Log("Going to delete uninst.exe ...");
            cutil.del_file(session, uninstexe);

            // This deletes any file that starts with "salt" from the install_dir
            var bindirparent = Path.GetDirectoryName(bin_dir);
            session.Log(@"Going to delete bindir\..\salt\*.*    ...   " + bindirparent);
            if (Directory.Exists(bindirparent)){
                try { foreach (FileInfo fi in new DirectoryInfo(bindirparent).GetFiles("salt*.*")) { fi.Delete(); } } catch (Exception) {; }
            }

            // This deletes the bin directory
            session.Log("Going to delete bindir ... " + bin_dir);
            cutil.del_dir(session, bin_dir);

            session.Log("...END del_NSIS_DECAC");
            return ActionResult.Success;
        }

        [CustomAction]
        public static ActionResult WriteConfig_DECAC(Session session) {
            /*
             * This function must leave the config files according to the CONFIG_TYPE's 1-3
             * This function is deferred (_DECAC)
             * This function runs after the msi has created the c:\salt\conf\minion file, which is a comment-only text.
             * If there was a previous install, there could be many config files.
             * The previous install c:\salt\conf\minion file could contain non-comments.
             * One of the non-comments could be master.
             * It could be that this installer has a different master.
             *
             */
            // Must have this signature or cannot uninstall not even write to the log
            session.Log("...BEGIN WriteConfig_DECAC");
            // Get msi properties
            string master = cutil.get_property_DECAC(session, "master");;
            string id = cutil.get_property_DECAC(session, "id");;
            string config_type = cutil.get_property_DECAC(session, "config_type");
            string MINION_CONFIG = cutil.get_property_DECAC(session, "MINION_CONFIG");
            string CONFDIR = cutil.get_property_DECAC(session, "CONFDIR");
            string MINION_CONFIGFILE = Path.Combine(CONFDIR, "minion");
            session.Log("...MINION_CONFIGFILE {0}", MINION_CONFIGFILE);
            bool file_exists = File.Exists(MINION_CONFIGFILE);
            session.Log("...file exists {0}", file_exists);

            // Get environment variables
            string ProgramData = System.Environment.GetEnvironmentVariable("ProgramData");

            if (MINION_CONFIG.Length > 0) {
                session.Log("...Found MINION_CONFIG: {0}", MINION_CONFIG);
                apply_minion_config_DECAC(session, MINION_CONFIG);  // A single msi property is written to file
                session.Log("...END WriteConfig_DECAC");
                return ActionResult.Success;
            }
            switch (config_type) {
                case "Existing":
                    session.Log("...CONFIG_TYPE: Existing, no changes will be made");
                    return ActionResult.Success;
                case "Custom":
                    // copy custom file before updating master and minion id
                    session.Log("...CONFIG_TYPE: Custom, copying custom config");
                    save_custom_config_file_DECAC(session);
                    break;
                case "Default":
                    // This is just a placeholder for CONFIG_TYPE=Default
                    session.Log("...CONFIG_TYPE: Default, using default config");
                    break;
                default:
                    session.Log("...UNKNOWN CONFIG_TYPE: " + config_type);
                    // Not sure if this is a valid ActionResult, but we need to die here
                    return ActionResult.Failure;
            }

            write_master_and_id_to_file_DECAC(session, MINION_CONFIGFILE, master, id); // Two msi properties are replaced inside files
            session.Log("...END WriteConfig_DECAC");
            return ActionResult.Success;
        }

        [CustomAction]
        public static ActionResult MoveInsecureConfig_DECAC(Session session) {
            // This appends .insecure-yyyy-MM-ddTHH-mm-ss to an insecure config directory
            // C:\salt\conf.insecure-2021-10-01T12-23-32
            // Only called when INSECURE_CONFIG_FOUND is set to an insecure minion config dir
            session.Log("...BEGIN MoveInsecureConf_DECAC");

            string minion_config_dir = cutil.get_property_DECAC(session, "INSECURE_CONFIG_FOUND");
            string timestamp_bak = ".insecure-" + DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss");
            cutil.Move_dir(session, minion_config_dir, timestamp_bak);

            session.Log("...END MoveInsecureConf_DECAC");

            return ActionResult.Success;
        }

        private static void save_custom_config_file_DECAC(Session session) {
            session.Log("...BEGIN save_custom_config_file_DECAC");
            string custom_config = cutil.get_property_DECAC(session, "custom_config");
            string CONFDIR       = cutil.get_property_DECAC(session, "CONFDIR");

            // Make sure a CUSTOM_CONFIG file has been passed
            if (!(custom_config.Length > 0 )) {
                session.Log("...CUSTOM_CONFIG not passed");
                return;
            }

            // Make sure the CUSTOM_CONFIG file exists
            // Try as passed
            if (File.Exists(custom_config)) {
                session.Log("...found full path to CUSTOM_CONFIG: " + custom_config);
            } else {
                // try relative path
                session.Log("...no CUSTOM_CONFIG: " + custom_config);
                session.Log("...Try relative path");
                string directory_of_the_msi = cutil.get_property_DECAC(session, "sourcedir");
                custom_config = Path.Combine(directory_of_the_msi, custom_config);
                if (File.Exists(custom_config)) {
                    session.Log("...found relative path to CUSTOM_CONFIG: " + custom_config);
                } else {
                    // CUSTOM_CONFIG not found
                    session.Log("...CUSTOM_CONFIG not found: " + custom_config);
                    return;
                }
            }
            // Copy the custom config (passed via the CLI, for now)
            if (!File.Exists(CONFDIR)) {
                session.Log("...Creating CONFDIR: " + CONFDIR);
                Directory.CreateDirectory(CONFDIR);
            }
            File.Copy(custom_config, Path.Combine(CONFDIR, "minion"), true);
            session.Log("...END save_custom_config_file_DECAC");
        }

       [CustomAction]
        public static ActionResult DeleteConfig_DECAC(Session session) {
            // This removes not only config, but ROOTDIR or subfolders of ROOTDIR, depending on properties CLEAN_INSTALL and REMOVE_CONFIG
            // Called on install, upgrade and uninstall
            session.Log("...BEGIN DeleteConfig_DECAC");

            // Determine wether to delete everything and DIRS
            string CLEAN_INSTALL = cutil.get_property_DECAC(session, "CLEAN_INSTALL");
            string REMOVE_CONFIG = cutil.get_property_DECAC(session, "REMOVE_CONFIG");
            string INSTALLDIR    = cutil.get_property_DECAC(session, "INSTALLDIR");
            string bindir        = Path.Combine(INSTALLDIR, "bin");
            string ROOTDIR       = cutil.get_property_DECAC(session, "ROOTDIR");
            string ProgramData   = System.Environment.GetEnvironmentVariable("ProgramData");
            string ROOTDIR_old   = @"C:\salt";
            string ROOTDIR_new   =  Path.Combine(ProgramData, @"Salt Project\Salt");
            // The registry subkey deletes itself

            if (CLEAN_INSTALL.Length > 0) {
                session.Log("...CLEAN_INSTALL -- remove both old and new root_dirs");
                cutil.del_dir(session, ROOTDIR_old);
                cutil.del_dir(session, ROOTDIR_new);
            }

            session.Log("...deleting bindir (msi only deletes what it installed, not *.pyc)  = " + bindir);
            cutil.del_dir(session, bindir);

            if (REMOVE_CONFIG.Length > 0) {
                session.Log("...REMOVE_CONFIG -- remove the current root_dir");
                cutil.del_dir(session, ROOTDIR);
            } else {
                session.Log("...Not REMOVE_CONFIG -- remove var and srv from the current root_dir");
                cutil.del_dir(session, ROOTDIR, "var");
                cutil.del_dir(session, ROOTDIR, "srv");
            }

            session.Log("...END DeleteConfig_DECAC");
            return ActionResult.Success;
        }

       [CustomAction]
        public static ActionResult MoveConfig_DECAC(Session session) {
            // This moves the root_dir from the old location (C:\salt) to the
            // new location (%ProgramData%\Salt Project\Salt)
            session.Log("...BEGIN MoveConfig_DECAC");

            // Get %ProgramData%
            string ProgramData   = System.Environment.GetEnvironmentVariable("ProgramData");

            string RootDirOld = @"C:\salt";
            string RootDirNew = Path.Combine(ProgramData, @"Salt Project\Salt");
            string RootDirNewParent = Path.Combine(ProgramData, @"Salt Project");

            session.Log("...RootDirOld       " + RootDirOld + " exists: " + Directory.Exists(RootDirOld));
            session.Log("...RootDirNew       " + RootDirNew + " exists: " + Directory.Exists(RootDirNew));
            session.Log("...RootDirNewParent " + RootDirNewParent + " exists: " + Directory.Exists(RootDirNewParent));

            // Create parent dir if it doesn't exist
            if (! Directory.Exists(RootDirNewParent)) {
                Directory.CreateDirectory(RootDirNewParent);
            }

            // Requires that the parent directory exists
            // Requires that the NewDir does NOT exist
            Directory.Move(RootDirOld, RootDirNew);

            session.Log("...END MoveConfig_DECAC");
            return ActionResult.Success;
        }

        private static void apply_minion_config_DECAC(Session session, string MINION_CONFIG) {
            // Precondition: parameter MINION_CONFIG contains the content of the MINION_CONFIG property and is not empty
            // Remove all other config
            session.Log("...apply_minion_config_DECAC BEGIN");
            string CONFDIR      = cutil.get_property_DECAC(session, "CONFDIR");
            string MINION_D_DIR = Path.Combine(CONFDIR, "minion.d");
            // Write conf/minion
            string lines = MINION_CONFIG.Replace("^", Environment.NewLine);
            cutil.Writeln_file(session, CONFDIR, "minion", lines);
            // Remove conf/minion_id
            string minion_id = Path.Combine(CONFDIR, "minion_id");
            session.Log("...searching " + minion_id);
            if (File.Exists(minion_id)) {
                File.Delete(minion_id);
                session.Log("...deleted   " + minion_id);
            }
            // Remove conf/minion.d/*.conf
            session.Log("...searching *.conf in " + MINION_D_DIR);
            if (Directory.Exists(MINION_D_DIR)) {
                var conf_files = System.IO.Directory.GetFiles(MINION_D_DIR, "*.conf");
                foreach (var conf_file in conf_files) {
                    File.Delete(conf_file);
                    session.Log("...deleted   " + conf_file);
                }
            }
            session.Log(@"...apply_minion_config_DECAC END");
        }

        [CustomAction]
        public static ActionResult  BackupConfig_DECAC(Session session) {
            session.Log("...BackupConfig_DECAC BEGIN");
            string timestamp_bak = "-" + DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss") + ".bak";
            session.Log("...timestamp_bak = " + timestamp_bak);
            cutil.Move_file(session, @"C:\salt\conf\minion", timestamp_bak);
            cutil.Move_file(session, @"C:\salt\conf\minion_id", timestamp_bak);
            cutil.Move_dir(session, @"C:\salt\conf\minion.d", timestamp_bak);
            session.Log("...BackupConfig_DECAC END");

            return ActionResult.Success;
        }
    }
}


text:
// Copyright 2003
// Association for Universities for Research in Astronomy, Inc.,
// Observatory Control System, Gemini Telescopes Project.
//
// $Id: ValueSearchCondition.java 35363 2011-06-05 09:22:23Z abrighton $

package jsky.catalog;

import jsky.util.StringUtil;

/**
 * Represents a search condition for values in a given table column,
 * or parameters to a query or request.
 */
public class ValueSearchCondition extends AbstractSearchCondition {

    /** The minimum value */
    private Comparable _val;

    /**
     * Create a new ValueSearchCondition for the given column or parameter description.
     */
    public ValueSearchCondition(FieldDesc fieldDesc, Comparable<?> val) {
        super(fieldDesc);
        _val = val;
    }

    /**
     * Create a new numerical ValueSearchCondition for the given column or parameter description.
     */
    public ValueSearchCondition(FieldDesc fieldDesc, double val) {
        this(fieldDesc, new Double(val));
    }

    /**
     * Create a new String ValueSearchCondition for the given column or parameter description.
     */
    public ValueSearchCondition(FieldDesc fieldDesc, String val) {
        this(fieldDesc, (Comparable) val.trim());
    }

    /** Return the value (actually a Double or String) */
    public Comparable<?> getVal() {
        return _val;
    }

    /**
     * Return true if the condition is true for the given value.
     *
     * @param val The value to be checked against the condition.
     * @return true if the value satisfies the condition.
     */
    public boolean isTrueFor(Comparable val) {
        if (_val instanceof String && val instanceof String) {
            return StringUtil.match((String) _val, (String) val);
        }
        return (_val.compareTo(val) == 0);
    }

    /**
     * Return true if the condition is true for the given numeric value.
     * If the condition was specified as a String, the return value is false.
     *
     * @param val The value to be checked against the condition.
     * @return true if the value satisfies the condition.
     */
    public boolean isTrueFor(double val) {
        return isTrueFor(new Double(val));
    }

    /** Return the value as a String. */
    public String getValueAsString(String sep) {
        return _val.toString();
    }

    /**
     * Test cases
     */
    public static void main(String[] args) {
        ValueSearchCondition s = new ValueSearchCondition(new FieldDescAdapter("X"), 22);

        if (!s.isTrueFor(22.))
            throw new RuntimeException("test failed for 22.: " + s);
        if (s.isTrueFor(23.))
            throw new RuntimeException("test failed for 23.: " + s);

        s = new ValueSearchCondition(new FieldDescAdapter("S"), "aaa");
        if (!s.isTrueFor("aaa"))
            throw new RuntimeException("test failed for \"aaa\": " + s);
        if (s.isTrueFor("mmm"))
            throw new RuntimeException("test failed for \"mmm\": " + s);

        System.out.println("All tests passed");
    }
}


text:
function out = M_motion( param, img , img_prev, prev_img_shift , ti )

if ( nargin == 1 )
    out.weight = param.motionWeight;
    out.numtypes = length( param.motionAngles );
    for i = 1 : length( param.motionAngles ),
        out.descriptions{i} = sprintf('Motion Direction %g',param.motionAngles(i));
    end
else
    out.imgShift = shiftImage( img , param.motionAngles(ti) );
    out.map = abs( img .* prev_img_shift - img_prev .* out.imgShift );

    % this rule comes from:
    % http://ilab.usc.edu/publications/doc/Itti_etal03spienn.pdf
    % "Values smaller than 3.0 are set to zero"
    % note: this doens't seem to work ? (9/4/09)
    % out.map( out.map < 3/255 ) = 0;
end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('contact_manager', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='event',
            name='name',
            field=models.CharField(max_length=200, unique=True),
        ),
    ]


text:
using Storm.Mvvm;
using TodoListFull.Models;
using TodoListFull.Services;
using TodoListFull.ViewModels;
using Xamarin.Forms;

namespace TodoListFull.Views
{
	public partial class DetailsPage : ContentPage
	{
		public DetailsPage()
		{
			InitializeComponent();
		}
	}
}


text:
package com.smockin.admin.persistence.dao;

import com.smockin.admin.persistence.entity.AppConfig;
import com.smockin.admin.persistence.entity.ServerConfig;
import com.smockin.admin.persistence.enums.ServerTypeEnum;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by mgallina.
 */
public interface AppConfigDAO extends JpaRepository<AppConfig, Long> {

}


text:
package com.oath.cyclops.internal.react.async.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

import cyclops.function.Cacheable;
import cyclops.function.Memoize;

import lombok.AllArgsConstructor;
import lombok.experimental.Wither;

@AllArgsConstructor
@Wither
public class PipelineBuilder {

    private final ExecutionPipeline builder;
    private final boolean autoOptimise; //fan out then syncrhonous there after
    private final Executor optimisingExec;
    private final boolean autoMemoize;
    private final Cacheable memoizeFactory;

    public PipelineBuilder() {
        builder = new ExecutionPipeline();
        autoOptimise = false;
        optimisingExec = null;
        autoMemoize = false;
        memoizeFactory = null;
    }

    private <T, R> Function<T, R> memoize(final Function<T, R> fn) {

        if (!autoMemoize)
            return fn;
        if (memoizeFactory == null)
            return Memoize.memoizeFunction(fn);
        return Memoize.memoizeFunction(fn, memoizeFactory);
    }

    public PipelineBuilder(final boolean autoOptimise, final Executor optimisingExec, final boolean autoMemoize, final Cacheable memoizeFactory) {
        builder = new ExecutionPipeline();
        this.autoOptimise = autoOptimise;
        this.optimisingExec = optimisingExec;
        this.autoMemoize = autoMemoize;
        this.memoizeFactory = memoizeFactory;
    }

    public <T, R> PipelineBuilder thenCompose(final Function<? super T, CompletableFuture<? extends R>> fn) {
        if (autoOptimise && builder.functionListSize() == 0)
            return thenComposeAsync(fn, optimisingExec);
        return withBuilder(builder.thenCompose((Function) memoize(fn)));
    }

    public <T, R> PipelineBuilder thenComposeAsync(final Function<? super T, CompletableFuture<? extends R>> fn, final Executor exec) {
        if (autoOptimise) {//if we already have a function present, compose with that
            if (builder.functionListSize() > 0)
                return thenCompose(fn);
        }

        return withBuilder(builder.thenComposeAsync((Function) memoize(fn), exec));

    }

    public <T, R> PipelineBuilder thenApplyAsync(final Function<T, R> fn, final Executor exec) {
        if (autoOptimise) {//if we already have a function present, compose with that
            if (builder.functionListSize() > 0)
                return thenApply(fn);
        }
        return withBuilder(builder.thenApplyAsync(memoize(fn), exec));

    }

    public <T> PipelineBuilder peek(final Consumer<? super T> c) {

        return withBuilder(builder.peek(c));

    }

    public <T, R> PipelineBuilder thenApply(final Function<? super T, ? extends R> fn) {
        if (autoOptimise && builder.functionListSize() == 0)
            return withBuilder(builder.thenApplyAsync(memoize(fn), optimisingExec));
        return withBuilder(builder.thenApply(memoize(fn)));

    }

    public <X extends Throwable, T> PipelineBuilder exceptionally(final Function<? super X, ? extends T> fn) {

        return withBuilder(builder.exceptionally(fn));
    }

    public <T, X extends Throwable> PipelineBuilder whenComplete(final BiConsumer<? super T, ? super X> fn) {
        return withBuilder(builder.whenComplete(fn));
    }

    public <T> FastFuture<T> build() {

        return new FastFuture<T>(
                                 builder.toFinalPipeline(), 0);
    }

    public PipelineBuilder onFail(final Consumer<Throwable> onFail) {
        return withBuilder(builder.onFail(onFail));
    }

    public boolean isSequential() {
        return builder.isSequential();
    }
}


text:
{% extends "nsa/layout.html" %}

{% block title %}Warrant required{% endblock %}

{% block header %}

{% endblock %}

{% block content %}

Have you received the appropriate warrant for this access?

        I have received a FISA warrant

        I have not received a FISA warrant

{% endblock %}