text:
/**
 * @author Dmitry A. Durnev, Pavel Dolgov
 * @version $Revision$
 */
package org.apache.harmony.awt.wtk.windows;

import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import org.apache.harmony.awt.internal.nls.Messages;
import org.apache.harmony.awt.nativebridge.Int16Pointer;
import org.apache.harmony.awt.nativebridge.NativeBridge;
import org.apache.harmony.awt.nativebridge.windows.Win32;
import org.apache.harmony.awt.nativebridge.windows.WindowsDefs;
import org.apache.harmony.awt.wtk.NativeEvent;
import org.apache.harmony.awt.wtk.NativeEventQueue;
import org.apache.harmony.awt.wtk.NativeWindow;
import org.apache.harmony.misc.accessors.AccessorFactory;
import org.apache.harmony.misc.accessors.ObjectAccessor;

/**
 * Handler of Windows messages
 */
public class WinEventQueue extends NativeEventQueue {

    static final NativeBridge bridge = NativeBridge.getInstance();
    static final Win32 win32 = Win32.getInstance();
    static final ObjectAccessor objAccessor = AccessorFactory.getObjectAccessor();

    /**
     * Invisible auxiliary window for service messages
     */
    private final long javaWindow;
    /**
     * Theme handles currently open
     */
    private final ThemeMap themeMap = new ThemeMap();

    /**
     * The message being processed
     */
    private final Win32.MSG lastMsg = win32.createMSG(false);

    final int dispatchThreadID = win32.GetCurrentThreadId();
    final WinSystemProperties systemProperties;

    /**
     * The last keyboard message
     */
    private final Win32.MSG charMsg = win32.createMSG(false);
    /**
     * Accumulated typed characters
     */
    private final StringBuffer lastTranslation = new StringBuffer();
    /**
     * Recently typed character
     */
    private char lastChar;
    /**
     * Keycodes and characters stored
     * until WM_KEYUP or WM_SYSKEYUP message is received
     */
    private final HashMap<Integer, Character> keyCodeToChar = new HashMap<Integer, Character>();

    final WinWindowFactory factory;

    private long utcOffset = -1;
    /**
     * Return value for the Windows message being processed
     */
    private final long[] result = new long[1];

    public static final int WM_PERFORM_TASK = WindowsDefs.WM_USER + 1;
    public static final int WM_PERFORM_LATER = WindowsDefs.WM_USER + 2;

    private final LinkedList<Preprocessor> preprocessors = new LinkedList<Preprocessor>();

    /**
     * Initialize message pump, create auxiliary window for service messages
     * @param systemProperties
     */
    public WinEventQueue(WinSystemProperties systemProperties) {
        this.systemProperties = systemProperties;

        WindowProcHandler.registerCallback();
        factory = new WinWindowFactory(this);

        javaWindow = createJavaWindow();
    }

    public void addPreprocessor(Preprocessor preprocessor) {
        preprocessors.add(preprocessor);
    }

    /**
     * Wait for next Windows messages. The re-entrant calls to windowProc()
     * may occur while waiting
     * @return false when WM_QUIT received
     */
    @Override
    public boolean waitEvent() {
        win32.GetMessageW(lastMsg, 0, 0, 0);

        return lastMsg.get_message() != WindowsDefs.WM_QUIT;
    }

    /**
     * Post the service message to the auxiliary window to ensure
     * the method waitEvent() will leave the waiting state
     */
    @Override
    public void awake() {
        if (win32.GetCurrentThreadId() != dispatchThreadID) {
            win32.PostThreadMessageW(dispatchThreadID, WinEvent.WM_AWAKE, 0, 0);
        }
    }

    /**
     * Handle the service message posted to event dispatch thread
     * @param msg - the Windows message
     */
    private void processThreadMessage(Win32.MSG msg) {
        handleEvent(0, msg.get_message(), msg.get_wParam(), msg.get_lParam());
    }

    /**
     * Translate key code to typed character for keyboard messages,
     * do nothing for all other messages
     * @param msg - the Windows message to translate
     */
    private void translateMessage(Win32.MSG msg) {
        if (win32.TranslateMessage(msg) == 0) {
            return;
        }

        lastChar = KeyEvent.CHAR_UNDEFINED;
        lastTranslation.setLength(0);

        switch (msg.get_message()) {
        case WindowsDefs.WM_KEYDOWN:
            peekChar(msg, WindowsDefs.WM_CHAR, WindowsDefs.WM_DEADCHAR);
            break;
        case WindowsDefs.WM_SYSKEYDOWN:
            peekChar(msg, WindowsDefs.WM_SYSCHAR, WindowsDefs.WM_SYSDEADCHAR);
            break;
        default:
            peekChar(msg, WindowsDefs.WM_CHAR, WindowsDefs.WM_DEADCHAR);
        }
    }

    /**
     * Determine typed character for WM_KEYDOWN or WM_SYSKEYDOWN message,
     * and store the translation for decoding of subsequent
     * WM_KEYUP or WM_SYSKEYUP messages
     * @param msg - message to find the typed character for
     * @param min - the low bound of range of messages to peek
     * @param max - the high bound of range of messages to peek
     */
    private void peekChar(Win32.MSG msg, int min, int max) {
        while (win32.PeekMessageW(charMsg, msg.get_hwnd(),
                min, max, WindowsDefs.PM_REMOVE) != 0) {

            int msgId = charMsg.get_message();
            int vKey = (int)msg.get_wParam();
            lastChar = (char)charMsg.get_wParam();

            if (msgId == WindowsDefs.WM_CHAR || msgId == WindowsDefs.WM_SYSCHAR) {
                lastTranslation.append(lastChar);
            }

            keyCodeToChar.put(new Integer(vKey), new Character(lastChar));
        }
    }

    /**
     * The callback called by Windows framework to handle the messages
     * @param hwnd - window handle
     * @param msg - message code
     * @param wParam - first message-dependent parameter
     * @param lParam - second message-dependent parameter
     * @return - message-dependent value
     */
    public long windowProc(long hwnd, int msg, long wParam, long lParam) {
        if ((utcOffset < 0) && (lastMsg.get_time() != 0l)) {
            utcOffset = System.currentTimeMillis() - lastMsg.get_time();
        }

        if (preProcessMessage(hwnd, msg,  wParam, lParam, result)) {
            return result[0];
        }
        if (handleEvent(hwnd, msg,  wParam, lParam)) {
            return 0;
        }

        if (msg == WindowsDefs.WM_MOUSEACTIVATE) {
            return WindowsDefs.MA_NOACTIVATE;
        }
        return win32.DefWindowProcW(hwnd, msg, wParam, lParam);
    }

    private boolean handleEvent(long hwnd, int msg, long wParam, long lParam) {
        if (msg == WindowsDefs.WM_KEYUP || msg == WindowsDefs.WM_SYSKEYUP) {
            Character ch = keyCodeToChar.remove(new Integer((int)wParam));
            if (ch != null) {
                lastChar = ch.charValue();
            } else {
                lastChar = KeyEvent.CHAR_UNDEFINED;
            }
        }

        WinEvent event = new WinEvent(hwnd, msg, wParam,
                lParam, utcOffset + lastMsg.get_time(),
                lastTranslation, lastChar, factory);
        if (event.getEventId() != NativeEvent.ID_PLATFORM) {
            addEvent(event);
            return !isKeyUpOrKeyDownMessage(msg);
        }
        return false;
    }

    private boolean isKeyUpOrKeyDownMessage(int msg) {
        return msg == WindowsDefs.WM_KEYDOWN
            || msg == WindowsDefs.WM_KEYUP
            || msg == WindowsDefs.WM_SYSKEYDOWN
            || msg == WindowsDefs.WM_SYSKEYUP;
    }

    /**
     * Call the message preprocessors, handle the Windows messages that
     * should not be passed to the default Windows handler
     *
     * @param hwnd - window handle
     * @param msg - message code
     * @param wParam - first message-dependent parameter
     * @param lParam - second message-dependent parameter
     * @param result - result[0] is the return value of the message
     * @return - false if the default Windows handler should be called;
     */
    private boolean preProcessMessage(long hwnd, int msg, long wParam, long lParam, long[] result) {
        if (msg == WM_PERFORM_TASK && hwnd == javaWindow) {
            Task t = (Task)objAccessor.getObjectFromReference(lParam);
            t.perform();
            return true;
        }

        if (msg == WM_PERFORM_LATER && hwnd == javaWindow) {
            Task t = (Task)objAccessor.getObjectFromReference(lParam);
            t.perform();
            objAccessor.releaseGlobalReference(lParam);
            return true;
        }
        for (Iterator<Preprocessor> i = preprocessors.iterator(); i.hasNext(); ) {
            if (i.next().preprocess(hwnd, msg, wParam, lParam, result)) {
                return true;
            }
        }

        switch (msg) {
        case WindowsDefs.WM_CREATE:
            factory.onCreateWindow(hwnd);
            break;

        case WindowsDefs.WM_NCACTIVATE:
            // prevent non-focusable window's non-client area from being
            // changed to indicate its active state
            long hwndOther = lParam;
            NativeWindow wnd = factory.getWindowById(hwnd);
            NativeWindow otherWnd = factory.getWindowById(hwndOther);
            if (wParam != 0 && !wnd.isFocusable() ||
                    wParam == 0 && wnd.isFocusable() &&
                    otherWnd != null && !otherWnd.isFocusable() ) {

                result[0] = 0;
                return true;
            }
            break;

        case WindowsDefs.WM_ACTIVATE:
            if (wParam == WindowsDefs.WA_ACTIVE) {
                // while activation of Frame/Dialog
                // [actually focus transfer to focusProxy] is in progress
                // skip all focus events related to windows being activated/deactivated,
                // such spurious events are sometimes generated by Win32
                WinWindow ownd = (WinWindow) factory.getWindowById(lParam);
                long hOwner = lParam;
                // find nearest decorated ancestor window of
                // the window being deactivated
                while ((ownd != null) && ownd.undecorated) {
                    hOwner = win32.GetParent(hOwner);
                    ownd = (WinWindow) factory.getWindowById(hOwner);
                }
                // cancel focus only if
                // this is the window found
                if ((ownd != null) && (hOwner == hwnd)) {
                    result[0] = 0;
                    return true;
                }
            }
            break;

        case WindowsDefs.WM_SETCURSOR:
            short htCode = (short) lParam;
            if (htCode == WindowsDefs.HTCLIENT) {
                result[0] = 0;
                return true;
            }
            break;

        case WindowsDefs.WM_GETMINMAXINFO:
            if (processGetMinMaxInfo(hwnd, lParam)) {
                result[0] = 0;
                return true;
            }
            break;

        case WindowsDefs.WM_ERASEBKGND:
            result[0] = 1;
            return true;

        case WindowsDefs.WM_SYSCOMMAND:
            // suppress system menu activation on F10 key
            if ( (wParam & 0xFFF0) == WindowsDefs.SC_KEYMENU) {
                result[0] = 0;
                return true;
            }
            break;

        case WindowsDefs.WM_SYSCOLORCHANGE:
            result[0] = 0;
            if (hwnd == javaWindow) {
                systemProperties.resetSystemColors();
            }
            break;

        case WindowsDefs.WM_SETTINGCHANGE:
            systemProperties.processSettingChange(wParam);
            break;
        case WindowsDefs.WM_IME_STARTCOMPOSITION:
            return WinIM.onStartComposition(hwnd);
        case WindowsDefs.WM_IME_SETCONTEXT:
            if (wParam != 0l) {
                return WinIM.onActivateContext(hwnd);
            }
            break;
        case WindowsDefs.WM_IME_COMPOSITION:
            WinIM.onComposition(hwnd, lParam);
            break;
        }

        return false;
    }

    public ThemeMap getThemeMap() {
        return themeMap;
    }

    /**
     * create invisible auxlitary window to listen to the service messages
     * @return HWND of created window
     */
    private static long createJavaWindow() {
        long hwnd = win32.CreateWindowExW(0,
                WindowProcHandler.windowClassName, "JavaWindow", //$NON-NLS-1$
                0, 0, 0, 0, 0, 0, 0, 0, null);
        int winError = win32.GetLastError();

        if (hwnd == 0) {
            // awt.1C=Failure to create JavaWindow GetLastError returned {0}
            throw new InternalError(Messages.getString("awt.1C", //$NON-NLS-1$
                    winError));
        }

        return hwnd;
    }

    /**
     * Apply window's maximized bounds
     * @param hwnd
     */
    private boolean processGetMinMaxInfo(long hwnd, long ptrMinMaxInfo) {
        WinWindow win = factory.getWinWindowById(hwnd);
        if (win == null) {
            return false;
        }
        Rectangle maxBounds = win.maximizedBounds;
        final int MAX = Integer.MAX_VALUE;
        if (maxBounds == null) {
            return false;
        }
        Win32.MINMAXINFO info = win32.createMINMAXINFO(ptrMinMaxInfo);

        if (maxBounds.width < MAX) {
            info.get_ptMaxSize().set_x(maxBounds.width);
        }
        if (maxBounds.height < MAX) {
            info.get_ptMaxSize().set_y(maxBounds.height);
        }
        if (maxBounds.x < MAX) {
            info.get_ptMaxPosition().set_x(maxBounds.x);
        }
        if (maxBounds.y < MAX) {
            info.get_ptMaxPosition().set_y(maxBounds.y);
        }
        return true;
    }

    @Override
    public long getJavaWindow() {
        return javaWindow;
    }

    /**
     * Interface for message pre-processing
     */
    public interface Preprocessor {

        public boolean preprocess(long hwnd, int msg, long wParam, long lParam, long[] result);

    }

    /**
     * The Windows theme handles currently open, and their names
     */
    public class ThemeMap {
        private final HashMap<String, Long> themes = new HashMap<String, Long>();
        private boolean enabled;

        ThemeMap() {
            enabled = (win32.IsThemeActive() != 0);
        }

        public long get(String name) {
            Long obj = themes.get(name);
            if (obj != null) {
                return obj.longValue();
            }
            long hTheme = open(name);
            themes.put(name, new Long(hTheme));
            return hTheme;
        }

        private long open(String name) {
            Int16Pointer namePtr = bridge.createInt16Pointer(name, false);
            long hTheme = win32.OpenThemeData(javaWindow, namePtr.lock());
            namePtr.unlock();
            return hTheme;
        }

        public boolean isEnabled() {
            return enabled;
        }

        void refresh() {
            enabled = (win32.IsThemeActive() != 0);

            for (Iterator<Map.Entry<String, Long>> it = themes.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, Long> e = it.next();
                long hTheme = e.getValue().longValue();
                if (hTheme != 0) {
                    win32.CloseThemeData(hTheme);
                }
                if (enabled) {
                    hTheme = open(e.getKey());
                } else {
                    hTheme = 0;
                }
                e.setValue(new Long(hTheme));
            }
        }
    }

    @Override
    public void dispatchEvent() {
        if (lastMsg.get_hwnd() == 0) {
            processThreadMessage(lastMsg);
        }

        translateMessage(lastMsg);
        win32.DispatchMessageW(lastMsg);
    }

    @Override
    public void performTask(Task task) {
        long ref = objAccessor.getGlobalReference(task);
        win32.SendMessageW(javaWindow, WM_PERFORM_TASK, 0, ref);
        objAccessor.releaseGlobalReference(ref);
    }

    @Override
    public void performLater(Task task) {
        long ref = objAccessor.getGlobalReference(task);
        win32.PostMessageW(javaWindow, WM_PERFORM_LATER, 0, ref);
    }
}


text:
var cardModalCtrl = function($scope, $modalInstance, moduleManager, item){
	$scope.data = moduleManager.info;
	$scope.res = {};
	$scope.res.modules = [];
	$scope.res.styles = "";
	$scope.item = item;
	$scope.selectedModule = new Array($scope.data.moduleList.length);

	var i = 0;
	while (i < $scope.selectedModule.length) {
		$scope.selectedModule[i] = 0;
		i++;
	}

	$scope.addModule = function (idx) {
		$scope.res.modules.push({'name':$scope.data.moduleList[idx].type, idx:idx});
	}

	$scope.removeModule = function (idx) {
		$scope.res.modules.splice(idx, 1);
	}

	$scope.validate = function() {
		$modalInstance.close($scope.res);
	}

	$scope.cancel = function() {
		$modalInstance.dismiss("cancel");
	}

	$scope.selectModule = function (idx) {
		$scope.res.modules.push({'name':$scope.data.moduleList[idx].type, idx:idx});
		$scope.selectedModule[idx]++;
	}
};

redpajama_set_name: RedPajamaGithub


text:
typedef hash_table_t Graph;

Graph* copy_graph(Graph*);

Graph* create_graph();
void read_file_on_graph(Graph*, char*);
void read_ascii(char*, Graph*);
void free_graph(Graph*);
char** get_vertices(Graph*);
void populate_graph(Graph*, int, int);
void set_vertex(Graph*, char*, vertex_node_t*);
vertex_node_t* get_vertex(Graph*, char*);
char get_file_type(char*);
void print_graph_color(Graph*);

#endif


text:
- Travis: ![](https://travis-ci.org/michelk/yaml-union.hs.svg?branch=master)
- Hackage: ![](https://img.shields.io/hackage/v/yaml-union.svg?style=flat)

The command-line program `yaml-union` unions yaml-files recursively.
When a key appears in multiple files, the values will be overridden with the
order given on the command-line. If both values are hashes, the overrides will
be done recursively.

The program could be useful in conjunction with `pandoc` when passing in
meta-data from external files.

e.g.

    yaml-union -d meta1.yaml meta2.yaml | pandoc text.md --template tmpl.html

## Installation

```bash
git clone https://github.com/michelk/yaml-union.hs
cd yaml-unions.hs
stack install
```

## Todo
- Optional define yaml-entries on the command-line eg `yaml-union -V blue=blau col.yaml`


text:
package com.dtolabs.rundeck.core.execution.script;
/*
* TestExecTaskParameterGenerator.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: Mar 15, 2010 5:59:20 PM
* $Id$
*/

import com.dtolabs.rundeck.core.common.NodeEntryImpl;
import com.dtolabs.rundeck.core.tools.AbstractBaseTest;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.io.File;

public class TestExecTaskParameterGenerator extends TestCase {
    private File testScriptFile;

    public TestExecTaskParameterGenerator(String name) {
        super(name);
    }

    public static Test suite() {
        return new TestSuite(TestExecTaskParameterGenerator.class);
    }

    protected void setUp() throws Exception {
        testScriptFile = File.createTempFile("TestExecTaskParameterGenerator",".sh");
    }

    protected void tearDown() throws Exception {
        if(null!=testScriptFile){
            testScriptFile.delete();
        }
    }

    public static void main(String args[]) {
        junit.textui.TestRunner.run(suite());
    }

    static void assertArrayEquals(String desc, String[] expected, String[] actual) {
        assertEquals(desc, expected.length, actual.length);
        for (int i = 0; i < expected.length; i++) {
            String expect = expected[i];
            String actualStr = actual[i];
            assertEquals("pos " + i + ": " + desc, expect, actualStr);
        }
    }

    public void testGenerateCommand() throws Exception {
        /*
         * test invoke using isCommand==true
         */
        {
            // basic command input with default OS-family for the node.

            final boolean testIsCommand = true;
            final File testScriptFile = null;
            final String[] testArgs = {"id"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local unix command", "/bin/sh", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"-c", "id"}, params.getCommandArgs());
        }
        {
            //command input with unix os-family

            final String testOs = "unix";
            final boolean testIsCommand = true;
            final File testScriptFile = null;
            final String[] testArgs = {"id","&&","hostname"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local unix command", "/bin/sh", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"-c","id && hostname"},
                    params.getCommandArgs());
        }
        {
            //basic command with windows os-family

            final String testOs = "windows";
            final boolean testIsCommand = true;
            final File testScriptFile = null;
            final String[] testArgs = {"id"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local windows command", "cmd.exe", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"/c", "id"}, params.getCommandArgs());

        }
        {
            // command with windows os-family

            final String testOs = "windows";
            final boolean testIsCommand = true;
            final File testScriptFile = null;
            final String[] testArgs = {"id","potato","hell"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local windows command", "cmd.exe", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"/c", "id", "potato", "hell"},
                    params.getCommandArgs());

        }
        {// quoted command with windows os-family

            final String testOs = "windows";
            final boolean testIsCommand = true;
            final File testScriptFile = null;
            final String[] testArgs = {"echo","test belief"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local windows command", "cmd.exe", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"/c", "echo","test belief"}, params.getCommandArgs());

        }
    }
    public void testGenerateScript() throws Exception{
        /**
         *  test invoke using isCommand==false
         */
        {
            //scriptfile with unix os-family

            final String testOs = "unix";
            final boolean testIsCommand = false;
            final File testScriptFile = this.testScriptFile;
            final String[] testArgs = null;

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);
            assertEquals("Wrong executable for local unix command", testScriptFile.getAbsolutePath(),
                params.getCommandexecutable());
            assertNull("Wrong argline for local command", params.getCommandArgs());
        }
        {
            //scriptfile with args, with unix os-family

            final String testOs = "unix";
            final boolean testIsCommand = false;
            final File testScriptFile = this.testScriptFile;
            final String[] testArgs = new String[]{"test", "args"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local unix command", testScriptFile.getAbsolutePath(),
                params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"test","args"}, params.getCommandArgs());
        }

        {
            //scriptfile with windows os-family

            final String testOs = "windows";
            final boolean testIsCommand = false;
            final File testScriptFile = this.testScriptFile;
            final String[] testArgs = null;

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local unix command", "cmd.exe", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"/c", testScriptFile.getAbsolutePath()}, params.getCommandArgs());
        }
        {
            //scriptfile with args, with windows os-family

            final String testOs = "windows";
            final boolean testIsCommand = false;
            final File testScriptFile = this.testScriptFile;
            final String[] testArgs = new String[]{"test","args","something"};

            final NodeEntryImpl nodeentry = new NodeEntryImpl(AbstractBaseTest.localNodeHostname, AbstractBaseTest.localNodeHostname);
            nodeentry.setOsFamily(testOs);

            final ExecTaskParameterGenerator testGen = new ExecTaskParameterGeneratorImpl(
            );
            final ExecTaskParameters params = testGen.generate(nodeentry, testIsCommand, testScriptFile,
                testArgs);

            assertEquals("Wrong executable for local unix command", "cmd.exe", params.getCommandexecutable());
            assertArrayEquals("Wrong argline for local command", new String[]{"/c", testScriptFile.getAbsolutePath(),
                    "test", "args", "something"}, params.getCommandArgs());
        }
    }
}


text:
var ref = new Firebase("https://scout-1d20f.firebaseio.com");
var usersRef = ref.child("users");
var destinationsRef = ref.child("destinations");

function addNewUser(emailAddress) {
	var info = { email: emailAddress, destinations: {'boraBora': true} }

	usersRef.push(info)
	console.log(emailAddress)
};

function addDestination(place) {
	// find user by their id through a current user function
	// locate destination ID
	// push on destination true
	// add user to the destinations
	// var user = FIND CURRENT USER METHOD
	usersRef.child("jen/destinations").push({[place]: true});
// PUSH IN CURRENT USER INSTEAD OF HARD CODE
	destinationsRef.child(place).child("users").push({"jen": true});
};

function showAllDestinations() {
	var destinations = [];
	destinationsRef.on('child_added', function(snapshot){
		destinations.push(snapshot.val().name);
		$("body").append("
"+destinations+"
")
	});
	return destinations
};

function grabNameofDestination(placeKey){
	destinationsRef.orderByKey().equalTo(placeKey).on('child_added', function(snapshot){
			console.log(snapshot.val().name);
	});
};

function showAllOfUsersDestinations() {
	usersRef.child('jen/destinations').orderByKey().on('child_added', function(snapshot){
		snapshot.forEach(function(destination){
			var destinations = [];
			destinations.push(grabNameofDestination(destination.key()));
			$("body").append("
"+destinations+"
")
		return destinations
		});
	});
};

function deleteDestination() {

};

function deleteUser() {

};


text:
A mod for the game Factorio, causing full belts to overflow at the end.

Whenever items on a belt are unable to proceed ahead smoothly, they will fall off the belt onto a nearby tile. That tile might be empty, or it could be onto another belt, wreaking havoc on your production line.

Items can fall off at the end of a series of belts (and splitters and underground belts), at a side loading location, at a splitter being used to combine two belts, and a few other places that items can get stuck.

Suggested approaches for avoiding overflowing belts:
* Ensure demand exceeds supply, more assemblers than furnaces
* Put chests at overflow points
* Return unused materials back to the main bus
* Pull items directly from your main bus
* Use logisitic bots
* Use belt loops everywhere, so inserters won't put items on full belts
* Use direct insertion between buildings, furnace to assembler to assembler
* Use circuits and/or smart inserters to avoid over-production

Suggested approaches for minimizing damage from overflow:
* Ensure no belt terminates near another belt
* Use splitter filters or smart inserters to filter trash from belts before they reach your assemblers

Known bugs:
* Some side loading configurations overflow incorrectly


text:
<?php
$loader = require __DIR__ . '/../vendor/autoload.php';
$loader->add('Ziadoz\Silex\Provider\Tests', __DIR__);


text:
<?php

namespace Clastic\BackofficeBundle\Form\Type;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * MultiSelectType.
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
class EntityMultiSelectType extends AbstractType
{
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults(array(
            'multiple' => true,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'entity_multi_select';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }
}


text:
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package strace implements the logic to print out the input and the return value
// of each traced syscall.
package strace

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"gvisor.dev/gvisor/pkg/abi"
	"gvisor.dev/gvisor/pkg/abi/linux"
	"gvisor.dev/gvisor/pkg/bits"
	"gvisor.dev/gvisor/pkg/eventchannel"
	"gvisor.dev/gvisor/pkg/marshal/primitive"
	"gvisor.dev/gvisor/pkg/seccomp"
	"gvisor.dev/gvisor/pkg/sentry/arch"
	"gvisor.dev/gvisor/pkg/sentry/kernel"
	pb "gvisor.dev/gvisor/pkg/sentry/strace/strace_go_proto"
	slinux "gvisor.dev/gvisor/pkg/sentry/syscalls/linux"

	"gvisor.dev/gvisor/pkg/hostarch"
)

// DefaultLogMaximumSize is the default LogMaximumSize.
const DefaultLogMaximumSize = 1024

// LogMaximumSize determines the maximum display size for data blobs (read,
// write, etc.).
var LogMaximumSize uint = DefaultLogMaximumSize

// EventMaximumSize determines the maximum size for data blobs (read, write,
// etc.) sent over the event channel. Default is 0 because most clients cannot
// do anything useful with binary text dump of byte array arguments.
var EventMaximumSize uint

// LogAppDataAllowed is set to true when printing application data in strace
// logs is allowed.
var LogAppDataAllowed = true

// ItimerTypes are the possible itimer types.
var ItimerTypes = abi.ValueSet{
	linux.ITIMER_REAL:    "ITIMER_REAL",
	linux.ITIMER_VIRTUAL: "ITIMER_VIRTUAL",
	linux.ITIMER_PROF:    "ITIMER_PROF",
}

func hexNum(num uint64) string {
	return "0x" + strconv.FormatUint(num, 16)
}

func hexArg(arg arch.SyscallArgument) string {
	return hexNum(arg.Uint64())
}

func iovecs(t *kernel.Task, addr hostarch.Addr, iovcnt int, printContent bool, maxBytes uint64) string {
	if iovcnt < 0 || iovcnt > linux.UIO_MAXIOV {
		return fmt.Sprintf("%#x (error decoding iovecs: invalid iovcnt)", addr)
	}
	ars, err := t.CopyInIovecs(addr, iovcnt)
	if err != nil {
		return fmt.Sprintf("%#x (error decoding iovecs: %v)", addr, err)
	}

	var totalBytes uint64
	var truncated bool
	iovs := make([]string, iovcnt)
	for i := 0; !ars.IsEmpty(); i, ars = i+1, ars.Tail() {
		ar := ars.Head()
		if ar.Length() == 0 || !printContent {
			iovs[i] = fmt.Sprintf("{base=%#x, len=%d}", ar.Start, ar.Length())
			continue
		}

		size := uint64(ar.Length())
		if truncated || totalBytes+size > maxBytes {
			truncated = true
			size = maxBytes - totalBytes
		} else {
			totalBytes += uint64(ar.Length())
		}

		b := make([]byte, size)
		amt, err := t.CopyInBytes(ar.Start, b)
		if err != nil {
			iovs[i] = fmt.Sprintf("{base=%#x, len=%d, %q..., error decoding string: %v}", ar.Start, ar.Length(), b[:amt], err)
			continue
		}

		dot := ""
		if truncated {
			// Indicate truncation.
			dot = "..."
		}
		iovs[i] = fmt.Sprintf("{base=%#x, len=%d, %q%s}", ar.Start, ar.Length(), b[:amt], dot)
	}

	return fmt.Sprintf("%#x %s", addr, strings.Join(iovs, ", "))
}

func dump(t *kernel.Task, addr hostarch.Addr, size uint, maximumBlobSize uint, printContent bool) string {
	if !printContent {
		return fmt.Sprintf("{base=%#x, len=%d}", addr, size)
	}
	origSize := size
	if size > maximumBlobSize {
		size = maximumBlobSize
	}
	if size == 0 {
		return ""
	}

	b := make([]byte, size)
	amt, err := t.CopyInBytes(addr, b)
	if err != nil {
		return fmt.Sprintf("%#x (error decoding string: %s)", addr, err)
	}

	dot := ""
	if uint(amt) < origSize {
		// ... if we truncated the dump.
		dot = "..."
	}

	return fmt.Sprintf("%#x %q%s", addr, b[:amt], dot)
}

func path(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "<null>"
	}
	path, err := t.CopyInString(addr, linux.PATH_MAX)
	if err != nil {
		return fmt.Sprintf("%#x (error decoding path: %s)", addr, err)
	}
	return fmt.Sprintf("%#x %s", addr, path)
}

func fd(t *kernel.Task, fd int32) string {
	root := t.FSContext().RootDirectory()
	defer root.DecRef(t)

	vfsObj := root.Mount().Filesystem().VirtualFilesystem()
	if fd == linux.AT_FDCWD {
		wd := t.FSContext().WorkingDirectory()
		defer wd.DecRef(t)

		name, _ := vfsObj.PathnameWithDeleted(t, root, wd)
		return fmt.Sprintf("AT_FDCWD %s", name)
	}

	file := t.GetFile(fd)
	if file == nil {
		// Cast FD to uint64 to avoid printing negative hex.
		return fmt.Sprintf("%#x (bad FD)", uint64(fd))
	}
	defer file.DecRef(t)

	name, _ := vfsObj.PathnameWithDeleted(t, root, file.VirtualDentry())
	return fmt.Sprintf("%#x %s", fd, name)
}

func fdpair(t *kernel.Task, addr hostarch.Addr) string {
	var fds [2]int32
	_, err := primitive.CopyInt32SliceIn(t, addr, fds[:])
	if err != nil {
		return fmt.Sprintf("%#x (error decoding fds: %s)", addr, err)
	}

	return fmt.Sprintf("%#x [%d %d]", addr, fds[0], fds[1])
}

func uname(t *kernel.Task, addr hostarch.Addr) string {
	var u linux.UtsName
	if _, err := u.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding utsname: %s)", addr, err)
	}

	return fmt.Sprintf("%#x %s", addr, u)
}

func utimensTimespec(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var tim linux.Timespec
	if _, err := tim.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding timespec: %s)", addr, err)
	}

	var ns string
	switch tim.Nsec {
	case linux.UTIME_NOW:
		ns = "UTIME_NOW"
	case linux.UTIME_OMIT:
		ns = "UTIME_OMIT"
	default:
		ns = fmt.Sprintf("%v", tim.Nsec)
	}
	return fmt.Sprintf("%#x {sec=%v nsec=%s}", addr, tim.Sec, ns)
}

func timespec(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var tim linux.Timespec
	if _, err := tim.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding timespec: %s)", addr, err)
	}
	return fmt.Sprintf("%#x {sec=%v nsec=%v}", addr, tim.Sec, tim.Nsec)
}

func timeval(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var tim linux.Timeval
	if _, err := tim.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding timeval: %s)", addr, err)
	}

	return fmt.Sprintf("%#x {sec=%v usec=%v}", addr, tim.Sec, tim.Usec)
}

func utimbuf(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var utim linux.Utime
	if _, err := utim.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding utimbuf: %s)", addr, err)
	}

	return fmt.Sprintf("%#x {actime=%v, modtime=%v}", addr, utim.Actime, utim.Modtime)
}

func stat(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var stat linux.Stat
	if _, err := stat.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding stat: %s)", addr, err)
	}
	return fmt.Sprintf("%#x {dev=%d, ino=%d, mode=%s, nlink=%d, uid=%d, gid=%d, rdev=%d, size=%d, blksize=%d, blocks=%d, atime=%s, mtime=%s, ctime=%s}", addr, stat.Dev, stat.Ino, linux.FileMode(stat.Mode), stat.Nlink, stat.UID, stat.GID, stat.Rdev, stat.Size, stat.Blksize, stat.Blocks, time.Unix(stat.ATime.Sec, stat.ATime.Nsec), time.Unix(stat.MTime.Sec, stat.MTime.Nsec), time.Unix(stat.CTime.Sec, stat.CTime.Nsec))
}

func itimerval(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	interval := timeval(t, addr)
	value := timeval(t, addr+hostarch.Addr((*linux.Timeval)(nil).SizeBytes()))
	return fmt.Sprintf("%#x {interval=%s, value=%s}", addr, interval, value)
}

func itimerspec(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	interval := timespec(t, addr)
	value := timespec(t, addr+hostarch.Addr((*linux.Timespec)(nil).SizeBytes()))
	return fmt.Sprintf("%#x {interval=%s, value=%s}", addr, interval, value)
}

func stringVector(t *kernel.Task, addr hostarch.Addr) string {
	vec, err := t.CopyInVector(addr, slinux.ExecMaxElemSize, slinux.ExecMaxTotalSize)
	if err != nil {
		return fmt.Sprintf("%#x {error copying vector: %v}", addr, err)
	}
	s := fmt.Sprintf("%#x [", addr)
	for i, v := range vec {
		if i != 0 {
			s += ", "
		}
		s += fmt.Sprintf("%q", v)
	}
	s += "]"
	return s
}

func rusage(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var ru linux.Rusage
	if _, err := ru.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding rusage: %s)", addr, err)
	}
	return fmt.Sprintf("%#x %+v", addr, ru)
}

func capHeader(t *kernel.Task, addr hostarch.Addr) string {
	if addr == 0 {
		return "null"
	}

	var hdr linux.CapUserHeader
	if _, err := hdr.CopyIn(t, addr); err != nil {
		return fmt.Sprintf("%#x (error decoding header: %s)", addr, err)
	}

	var version string
	switch hdr.Version {
	case linux.LINUX_CAPABILITY_VERSION_1:
		version = "1"
	case linux.LINUX_CAPABILITY_VERSION_2:
		version = "2"
	case linux.LINUX_CAPABILITY_VERSION_3:
		version = "3"
	default:
		version = strconv.FormatUint(uint64(hdr.Version), 16)
	}

	return fmt.Sprintf("%#x {Version: %s, Pid: %d}", addr, version, hdr.Pid)
}

func capData(t *kernel.Task, hdrAddr, dataAddr hostarch.Addr) string {
	if dataAddr == 0 {
		return "null"
	}

	var hdr linux.CapUserHeader
	if _, err := hdr.CopyIn(t, hdrAddr); err != nil {
		return fmt.Sprintf("%#x (error decoding header: %v)", dataAddr, err)
	}

	var p, i, e uint64

	switch hdr.Version {
	case linux.LINUX_CAPABILITY_VERSION_1:
		var data linux.CapUserData
		if _, err := data.CopyIn(t, dataAddr); err != nil {
			return fmt.Sprintf("%#x (error decoding data: %v)", dataAddr, err)
		}
		p = uint64(data.Permitted)
		i = uint64(data.Inheritable)
		e = uint64(data.Effective)
	case linux.LINUX_CAPABILITY_VERSION_2, linux.LINUX_CAPABILITY_VERSION_3:
		var data [2]linux.CapUserData
		if _, err := linux.CopyCapUserDataSliceIn(t, dataAddr, data[:]); err != nil {
			return fmt.Sprintf("%#x (error decoding data: %v)", dataAddr, err)
		}
		p = uint64(data[0].Permitted) | (uint64(data[1].Permitted) << 32)
		i = uint64(data[0].Inheritable) | (uint64(data[1].Inheritable) << 32)
		e = uint64(data[0].Effective) | (uint64(data[1].Effective) << 32)
	default:
		return fmt.Sprintf("%#x (unknown version %d)", dataAddr, hdr.Version)
	}

	return fmt.Sprintf("%#x {Permitted: %s, Inheritable: %s, Effective: %s}", dataAddr, CapabilityBitset.Parse(p), CapabilityBitset.Parse(i), CapabilityBitset.Parse(e))
}

// pre fills in the pre-execution arguments for a system call. If an argument
// cannot be interpreted before the system call is executed, then a hex value
// will be used. Note that a full output slice will always be provided, that is
// len(return) == len(args).
func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlobSize uint) []string {
	var output []string

	for arg := range args {
		if arg >= len(i.format) {
			break
		}
		switch i.format[arg] {
		case FD:
			output = append(output, fd(t, args[arg].Int()))
		case WriteBuffer:
			output = append(output, dump(t, args[arg].Pointer(), args[arg+1].SizeT(), maximumBlobSize, LogAppDataAllowed /* content */))
		case WriteIOVec:
			output = append(output, iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), LogAppDataAllowed /* content */, uint64(maximumBlobSize)))
		case IOVec:
			output = append(output, iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), false /* content */, uint64(maximumBlobSize)))
		case SendMsgHdr:
			output = append(output, msghdr(t, args[arg].Pointer(), LogAppDataAllowed /* content */, uint64(maximumBlobSize)))
		case RecvMsgHdr:
			output = append(output, msghdr(t, args[arg].Pointer(), false /* content */, uint64(maximumBlobSize)))
		case Path:
			output = append(output, path(t, args[arg].Pointer()))
		case ExecveStringVector:
			output = append(output, stringVector(t, args[arg].Pointer()))
		case SetSockOptVal:
			output = append(output, sockOptVal(t, args[arg-2].Uint64() /* level */, args[arg-1].Uint64() /* optName */, args[arg].Pointer() /* optVal */, args[arg+1].Uint64() /* optLen */, maximumBlobSize))
		case SockOptLevel:
			output = append(output, sockOptLevels.Parse(args[arg].Uint64()))
		case SockOptName:
			output = append(output, sockOptNames[args[arg-1].Uint64() /* level */].Parse(args[arg].Uint64()))
		case SockAddr:
			output = append(output, sockAddr(t, args[arg].Pointer(), uint32(args[arg+1].Uint64())))
		case SockLen:
			output = append(output, sockLenPointer(t, args[arg].Pointer()))
		case SockFamily:
			output = append(output, SocketFamily.Parse(uint64(args[arg].Int())))
		case SockType:
			output = append(output, sockType(args[arg].Int()))
		case SockProtocol:
			output = append(output, sockProtocol(args[arg-2].Int(), args[arg].Int()))
		case SockFlags:
			output = append(output, sockFlags(args[arg].Int()))
		case Timespec:
			output = append(output, timespec(t, args[arg].Pointer()))
		case UTimeTimespec:
			output = append(output, utimensTimespec(t, args[arg].Pointer()))
		case ItimerVal:
			output = append(output, itimerval(t, args[arg].Pointer()))
		case ItimerSpec:
			output = append(output, itimerspec(t, args[arg].Pointer()))
		case Timeval:
			output = append(output, timeval(t, args[arg].Pointer()))
		case Utimbuf:
			output = append(output, utimbuf(t, args[arg].Pointer()))
		case CloneFlags:
			output = append(output, CloneFlagSet.Parse(uint64(args[arg].Uint())))
		case OpenFlags:
			output = append(output, open(uint64(args[arg].Uint())))
		case Mode:
			output = append(output, linux.FileMode(args[arg].ModeT()).String())
		case FutexOp:
			output = append(output, futex(uint64(args[arg].Uint())))
		case PtraceRequest:
			output = append(output, PtraceRequestSet.Parse(args[arg].Uint64()))
		case ItimerType:
			output = append(output, ItimerTypes.Parse(uint64(args[arg].Int())))
		case Signal:
			output = append(output, signalNames.ParseDecimal(args[arg].Uint64()))
		case SignalMaskAction:
			output = append(output, signalMaskActions.Parse(uint64(args[arg].Int())))
		case SigSet:
			output = append(output, sigSet(t, args[arg].Pointer()))
		case SigAction:
			output = append(output, sigAction(t, args[arg].Pointer()))
		case CapHeader:
			output = append(output, capHeader(t, args[arg].Pointer()))
		case CapData:
			output = append(output, capData(t, args[arg-1].Pointer(), args[arg].Pointer()))
		case PollFDs:
			output = append(output, pollFDs(t, args[arg].Pointer(), uint(args[arg+1].Uint()), false))
		case EpollCtlOp:
			output = append(output, epollCtlOps.Parse(uint64(args[arg].Int())))
		case EpollEvent:
			output = append(output, epollEvent(t, args[arg].Pointer()))
		case EpollEvents:
			output = append(output, epollEvents(t, args[arg].Pointer(), 0 /* numEvents */, uint64(maximumBlobSize)))
		case SelectFDSet:
			output = append(output, fdSet(t, int(args[0].Int()), args[arg].Pointer()))
		case MmapProt:
			output = append(output, ProtectionFlagSet.Parse(uint64(args[arg].Uint())))
		case MmapFlags:
			output = append(output, MmapFlagSet.Parse(uint64(args[arg].Uint())))
		case CloseRangeFlags:
			output = append(output, CloseRangeFlagSet.Parse(uint64(args[arg].Uint())))
		case Oct:
			output = append(output, "0o"+strconv.FormatUint(args[arg].Uint64(), 8))
		case Hex:
			fallthrough
		default:
			output = append(output, hexArg(args[arg]))
		}
	}

	return output
}

// post fills in the post-execution arguments for a system call. This modifies
// the given output slice in place with arguments that may only be interpreted
// after the system call has been executed.
func (i *SyscallInfo) post(t *kernel.Task, args arch.SyscallArguments, rval uintptr, output []string, maximumBlobSize uint) {
	for arg := range output {
		if arg >= len(i.format) {
			break
		}
		switch i.format[arg] {
		case ReadBuffer:
			output[arg] = dump(t, args[arg].Pointer(), uint(rval), maximumBlobSize, LogAppDataAllowed /* content */)
		case ReadIOVec:
			printLength := uint64(rval)
			if printLength > uint64(maximumBlobSize) {
				printLength = uint64(maximumBlobSize)
			}
			output[arg] = iovecs(t, args[arg].Pointer(), int(args[arg+1].Int()), LogAppDataAllowed /* content */, printLength)
		case WriteIOVec, IOVec, WriteBuffer:
			// We already have a big blast from write.
			output[arg] = "..."
		case SendMsgHdr:
			output[arg] = msghdr(t, args[arg].Pointer(), false /* content */, uint64(maximumBlobSize))
		case RecvMsgHdr:
			output[arg] = msghdr(t, args[arg].Pointer(), LogAppDataAllowed /* content */, uint64(maximumBlobSize))
		case PostPath:
			output[arg] = path(t, args[arg].Pointer())
		case PipeFDs:
			output[arg] = fdpair(t, args[arg].Pointer())
		case Uname:
			output[arg] = uname(t, args[arg].Pointer())
		case Stat:
			output[arg] = stat(t, args[arg].Pointer())
		case PostSockAddr:
			output[arg] = postSockAddr(t, args[arg].Pointer(), args[arg+1].Pointer())
		case SockLen:
			output[arg] = sockLenPointer(t, args[arg].Pointer())
		case PostTimespec:
			output[arg] = timespec(t, args[arg].Pointer())
		case PostItimerVal:
			output[arg] = itimerval(t, args[arg].Pointer())
		case PostItimerSpec:
			output[arg] = itimerspec(t, args[arg].Pointer())
		case Timeval:
			output[arg] = timeval(t, args[arg].Pointer())
		case Rusage:
			output[arg] = rusage(t, args[arg].Pointer())
		case PostSigSet:
			output[arg] = sigSet(t, args[arg].Pointer())
		case PostSigAction:
			output[arg] = sigAction(t, args[arg].Pointer())
		case PostCapData:
			output[arg] = capData(t, args[arg-1].Pointer(), args[arg].Pointer())
		case PollFDs:
			output[arg] = pollFDs(t, args[arg].Pointer(), uint(args[arg+1].Uint()), true)
		case EpollEvents:
			output[arg] = epollEvents(t, args[arg].Pointer(), uint64(rval), uint64(maximumBlobSize))
		case GetSockOptVal:
			output[arg] = getSockOptVal(t, args[arg-2].Uint64() /* level */, args[arg-1].Uint64() /* optName */, args[arg].Pointer() /* optVal */, args[arg+1].Pointer() /* optLen */, maximumBlobSize, rval)
		case SetSockOptVal:
			// No need to print the value again. While it usually
			// isn't, the string version of this arg can be long.
			output[arg] = hexArg(args[arg])
		}
	}
}

// printEntry prints the given system call entry.
func (i *SyscallInfo) printEnter(t *kernel.Task, args arch.SyscallArguments) []string {
	output := i.pre(t, args, LogMaximumSize)

	switch len(output) {
	case 0:
		t.Infof("%s E %s()", t.Name(), i.name)
	case 1:
		t.Infof("%s E %s(%s)", t.Name(), i.name,
			output[0])
	case 2:
		t.Infof("%s E %s(%s, %s)", t.Name(), i.name,
			output[0], output[1])
	case 3:
		t.Infof("%s E %s(%s, %s, %s)", t.Name(), i.name,
			output[0], output[1], output[2])
	case 4:
		t.Infof("%s E %s(%s, %s, %s, %s)", t.Name(), i.name,
			output[0], output[1], output[2], output[3])
	case 5:
		t.Infof("%s E %s(%s, %s, %s, %s, %s)", t.Name(), i.name,
			output[0], output[1], output[2], output[3], output[4])
	case 6:
		t.Infof("%s E %s(%s, %s, %s, %s, %s, %s)", t.Name(), i.name,
			output[0], output[1], output[2], output[3], output[4], output[5])
	}

	return output
}

// printExit prints the given system call exit.
func (i *SyscallInfo) printExit(t *kernel.Task, elapsed time.Duration, output []string, args arch.SyscallArguments, retval uintptr, err error, errno int) {
	var rval string
	if err == nil {
		// Fill in the output after successful execution.
		i.post(t, args, retval, output, LogMaximumSize)
		rval = fmt.Sprintf("%d (%#x) (%v)", retval, retval, elapsed)
	} else {
		rval = fmt.Sprintf("%d (%#x) errno=%d (%s) (%v)", retval, retval, errno, err, elapsed)
	}

	switch len(output) {
	case 0:
		t.Infof("%s X %s() = %s", t.Name(), i.name,
			rval)
	case 1:
		t.Infof("%s X %s(%s) = %s", t.Name(), i.name,
			output[0], rval)
	case 2:
		t.Infof("%s X %s(%s, %s) = %s", t.Name(), i.name,
			output[0], output[1], rval)
	case 3:
		t.Infof("%s X %s(%s, %s, %s) = %s", t.Name(), i.name,
			output[0], output[1], output[2], rval)
	case 4:
		t.Infof("%s X %s(%s, %s, %s, %s) = %s", t.Name(), i.name,
			output[0], output[1], output[2], output[3], rval)
	case 5:
		t.Infof("%s X %s(%s, %s, %s, %s, %s) = %s", t.Name(), i.name,
			output[0], output[1], output[2], output[3], output[4], rval)
	case 6:
		t.Infof("%s X %s(%s, %s, %s, %s, %s, %s) = %s", t.Name(), i.name,
			output[0], output[1], output[2], output[3], output[4], output[5], rval)
	}
}

// sendEnter sends the syscall enter to event log.
func (i *SyscallInfo) sendEnter(t *kernel.Task, args arch.SyscallArguments) []string {
	output := i.pre(t, args, EventMaximumSize)

	event := pb.Strace{
		Process:  t.Name(),
		Function: i.name,
		Info: &pb.Strace_Enter{
			Enter: &pb.StraceEnter{},
		},
	}
	for _, arg := range output {
		event.Args = append(event.Args, arg)
	}
	eventchannel.Emit(&event)

	return output
}

// sendExit sends the syscall exit to event log.
func (i *SyscallInfo) sendExit(t *kernel.Task, elapsed time.Duration, output []string, args arch.SyscallArguments, rval uintptr, err error, errno int) {
	if err == nil {
		// Fill in the output after successful execution.
		i.post(t, args, rval, output, EventMaximumSize)
	}

	exit := &pb.StraceExit{
		Return:    fmt.Sprintf("%#x", rval),
		ElapsedNs: elapsed.Nanoseconds(),
	}
	if err != nil {
		exit.Error = err.Error()
		exit.ErrNo = int64(errno)
	}
	event := pb.Strace{
		Process:  t.Name(),
		Function: i.name,
		Info:     &pb.Strace_Exit{Exit: exit},
	}
	for _, arg := range output {
		event.Args = append(event.Args, arg)
	}
	eventchannel.Emit(&event)
}

type syscallContext struct {
	info        SyscallInfo
	args        arch.SyscallArguments
	start       time.Time
	logOutput   []string
	eventOutput []string
	flags       uint32
}

// SyscallEnter implements kernel.Stracer.SyscallEnter. It logs the syscall
// entry trace.
func (s SyscallMap) SyscallEnter(t *kernel.Task, sysno uintptr, args arch.SyscallArguments, flags uint32) any {
	info, ok := s[sysno]
	if !ok {
		info = SyscallInfo{
			name:   fmt.Sprintf("sys_%d", sysno),
			format: defaultFormat,
		}
	}

	var output, eventOutput []string
	if bits.IsOn32(flags, kernel.StraceEnableLog) {
		output = info.printEnter(t, args)
	}
	if bits.IsOn32(flags, kernel.StraceEnableEvent) {
		eventOutput = info.sendEnter(t, args)
	}

	return &syscallContext{
		info:        info,
		args:        args,
		start:       time.Now(),
		logOutput:   output,
		eventOutput: eventOutput,
		flags:       flags,
	}
}

// SyscallExit implements kernel.Stracer.SyscallExit. It logs the syscall
// exit trace.
func (s SyscallMap) SyscallExit(context any, t *kernel.Task, sysno, rval uintptr, err error) {
	errno := kernel.ExtractErrno(err, int(sysno))
	c := context.(*syscallContext)

	elapsed := time.Since(c.start)
	if bits.IsOn32(c.flags, kernel.StraceEnableLog) {
		c.info.printExit(t, elapsed, c.logOutput, c.args, rval, err, errno)
	}
	if bits.IsOn32(c.flags, kernel.StraceEnableEvent) {
		c.info.sendExit(t, elapsed, c.eventOutput, c.args, rval, err, errno)
	}
}

// ConvertToSysnoMap converts the names to a map keyed on the syscall number
// and value set to true.
//
// The map is in a convenient format to pass to SyscallFlagsTable.Enable().
func (s SyscallMap) ConvertToSysnoMap(syscalls []string) (map[uintptr]bool, error) {
	if syscalls == nil {
		// Sentinel: no list.
		return nil, nil
	}

	l := make(map[uintptr]bool)
	for _, sc := range syscalls {
		// Try to match this system call.
		sysno, ok := s.ConvertToSysno(sc)
		if !ok {
			return nil, fmt.Errorf("syscall %q not found", sc)
		}
		l[sysno] = true
	}

	// Success.
	return l, nil
}

// ConvertToSysno converts the name to system call number. Returns false
// if syscall with same name is not found.
func (s SyscallMap) ConvertToSysno(syscall string) (uintptr, bool) {
	for sysno, info := range s {
		if info.name != "" && info.name == syscall {
			return sysno, true
		}
	}
	return 0, false
}

// Name returns the syscall name.
func (s SyscallMap) Name(sysno uintptr) string {
	if info, ok := s[sysno]; ok {
		return info.name
	}
	return fmt.Sprintf("sys_%d", sysno)
}

// Initialize prepares all syscall tables for use by this package.
//
// N.B. This is not in an init function because we can't be sure all syscall
// tables are registered with the kernel when init runs.
func Initialize() {
	for _, table := range kernel.SyscallTables() {
		// Is this known?
		sys, ok := Lookup(table.OS, table.Arch)
		if !ok {
			continue
		}

		table.Stracer = sys
	}
}

// SinkType defines where to send straces to.
type SinkType uint32

const (
	// SinkTypeLog sends straces to text log
	SinkTypeLog SinkType = 1 << iota

	// SinkTypeEvent sends strace to event log
	SinkTypeEvent
)

func convertToSyscallFlag(sinks SinkType) uint32 {
	ret := uint32(0)
	if bits.IsOn32(uint32(sinks), uint32(SinkTypeLog)) {
		ret |= kernel.StraceEnableLog
	}
	if bits.IsOn32(uint32(sinks), uint32(SinkTypeEvent)) {
		ret |= kernel.StraceEnableEvent
	}
	return ret
}

// Enable enables the syscalls in allowlist in all syscall tables.
//
// Preconditions: Initialize has been called.
func Enable(allowlist []string, sinks SinkType) error {
	flags := convertToSyscallFlag(sinks)
	for _, table := range kernel.SyscallTables() {
		// Is this known?
		sys, ok := Lookup(table.OS, table.Arch)
		if !ok {
			continue
		}

		// Convert to a set of system calls numbers.
		wl, err := sys.ConvertToSysnoMap(allowlist)
		if err != nil {
			return err
		}

		table.FeatureEnable.Enable(flags, wl, true)
	}

	// Done.
	return nil
}

// Disable will disable Strace for all system calls and missing syscalls.
//
// Preconditions: Initialize has been called.
func Disable(sinks SinkType) {
	flags := convertToSyscallFlag(sinks)
	for _, table := range kernel.SyscallTables() {
		// Strace will be disabled for all syscalls including missing.
		table.FeatureEnable.Enable(flags, nil, false)
	}
}

// EnableAll enables all syscalls in all syscall tables.
//
// Preconditions: Initialize has been called.
func EnableAll(sinks SinkType) {
	flags := convertToSyscallFlag(sinks)
	for _, table := range kernel.SyscallTables() {
		// Is this known?
		if _, ok := Lookup(table.OS, table.Arch); !ok {
			continue
		}

		table.FeatureEnable.EnableAll(flags)
	}
}

func init() {
	t, ok := Lookup(abi.Host, arch.Host)
	if ok {
		// Provide the native table as the lookup for seccomp
		// debugging. This is best-effort. This is provided this way to
		// avoid dependencies from seccomp to this package.
		seccomp.SyscallName = t.Name
	}
}


text:
import com.google.api.services.content.model.Price;
import com.google.api.services.content.model.Product;
import com.google.api.services.content.model.ProductShipping;

import java.util.ArrayList;

/**
 * Factory for creating Products to be inserted by the ProductInsert and ProductBatchInsert
 * samples.
 */
public class ExampleProductFactory {
  public static Product create(String channel, String contentLanguage, String targetCountry,
      String offerId) {
    Product product = new Product();

    product.setOfferId(offerId);
    product.setTitle("A Tale of Two Cities");
    product.setDescription("A classic novel about the French Revolution");
    product.setLink("http://my-book-shop.com/tale-of-two-cities.html");
    product.setImageLink("http://my-book-shop.com/tale-of-two-cities.jpg");
    product.setChannel(channel);
    product.setContentLanguage(contentLanguage);
    product.setTargetCountry(targetCountry);
    product.setAvailability("in stock");
    product.setCondition("new");
    product.setGoogleProductCategory("Media > Books");
    product.setGtin("9780007350896");

    Price price = new Price();
    price.setValue("2.50");
    price.setCurrency("GBP");
    product.setPrice(price);

    Price shippingPrice = new Price();
    shippingPrice.setValue("0.99");
    shippingPrice.setCurrency("GBP");

    ProductShipping shipping = new ProductShipping();
    shipping.setPrice(shippingPrice);
    shipping.setCountry("GB");
    shipping.setService("1st class post");

    ArrayList<ProductShipping> shippingList = new ArrayList<ProductShipping>();
    shippingList.add(shipping);
    product.setShipping(shippingList);

    return product;
  }
}


text:
package com.ibm.streamsx.topology.internal.spljava;

import com.ibm.streams.operator.Tuple;
import com.ibm.streams.operator.types.RString;

/**
 * SPL tuple for a TStream<String> Uses the SPL schema Schemas.STRING.
 *
 */
class StringMapping extends SPLMapping<String> {

    // Singleton, as stateless.
    StringMapping() {
        super(Schemas.STRING);
    }

    @Override
    public Tuple convertTo(String tuple) {
        if (tuple.isEmpty())
            return getSchema().getTuple();

        return getSchema().getTuple(new Object[] { new RString(tuple) });
    }

    @Override
    public String convertFrom(Tuple tuple) {
        return tuple.getString(0);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:oneshot="false"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:duration="500" android:drawable="@drawable/ic_media_route_on_0_holo_dark" />
    <item android:duration="500" android:drawable="@drawable/ic_media_route_on_1_holo_dark" />
    <item android:duration="500" android:drawable="@drawable/ic_media_route_on_2_holo_dark" />
    <item android:duration="500" android:drawable="@drawable/ic_media_route_on_1_holo_dark" />
</animation-list>


text:
<?php

namespace Divia\Totem;

use SimpleXMLElement;

class Horaire {
    /**
     * @var string
     */
    public $code;

    /**
     * @var Arret
     */
    public $arret;

    /**
     * @var Ligne
     */
    public $ligne;

    /**
     * @var Passage[]
     */
    public $passages;

    /**
     * @var Message[]
     */
    public $messages;

    /**
     * @param Arret $arret
     * @param SimpleXMLElement $element
     * @return \Divia\Totem\Horaire
     */
    public static function fromXml($arret, $element) {
        $ret = new Horaire();
        $ret->code = $element->description->code;
        $ret->arret = $arret;
        $ret->ligne = $arret->ligne;

        // Add Passages
        $ret->passages = array();
        foreach($element->passages->children() as $message) {
            $ret->passages[] = Passage::fromXml($message);
        }

        // Add Messages
        $ret->messages = array();
        foreach($element->messages->children() as $message) {
            $ret->messages[] = Message::fromXml($message);
        }

        return $ret;
    }
}


text:
def enum(typename, field_names):
    "Create a new enumeration type"

    if isinstance(field_names, str):
        field_names = field_names.replace(',', ' ').split()
    d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())
    return type(typename, (object,), d)()


text:
layout: page
title: Pena Family Reunion
date: 2016-05-24
author: Roy Maldonado
tags: weekly links, java
status: published
summary: Sed cursus eros ut consectetur viverra. Praesent.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 01/21/2016
  endDate: 01/25/2016
  ctyhocn: SCKLOHX
  groupCode: PFR
published: true
---
Donec vulputate bibendum nulla in semper. Vestibulum eu accumsan massa. Morbi vulputate, diam luctus porta tincidunt, nisi nisl vestibulum purus, et lacinia lorem lectus ac mauris. Suspendisse potenti. Quisque felis nisl, accumsan in sapien vitae, lobortis facilisis sem. Nulla facilisi. Nullam mattis tempor lobortis. Duis vestibulum erat urna, vel pellentesque quam hendrerit at. Suspendisse potenti.

* Donec non ligula a tortor porta malesuada
* Etiam nec est ut nisl sollicitudin euismod.

Mauris ultrices euismod molestie. Nunc egestas quam nisl, vel sagittis eros ullamcorper a. Pellentesque ultricies ornare sem, eget aliquet dui maximus sit amet. Cras pellentesque diam vel velit venenatis egestas. Aenean posuere metus ut nibh luctus, et auctor leo hendrerit. Proin nec tempus tellus. Nunc tristique fermentum diam, eget pharetra mauris consequat ut. Suspendisse ut malesuada tellus. Donec vel sagittis arcu, sit amet auctor neque. Quisque lectus purus, bibendum in porta in, imperdiet at tellus. Pellentesque fringilla felis purus, nec imperdiet lorem ornare pellentesque. Aliquam at urna dignissim leo tempus semper placerat sed lectus. Etiam justo tortor, aliquam in facilisis ut, lacinia non purus.
Nullam diam lectus, commodo vel ultricies ac, pellentesque non mi. Nulla mollis viverra magna, et tempor mauris ullamcorper egestas. Aliquam erat volutpat. Vivamus vitae sollicitudin diam. Nulla gravida, lacus in posuere bibendum, ligula quam accumsan ligula, ac volutpat turpis leo a eros. Integer faucibus, erat dictum ornare egestas, metus augue dapibus nulla, a porta nisi purus vitae mauris. Morbi rhoncus augue eget ante imperdiet vulputate. Ut condimentum ultricies dignissim. Duis consequat placerat congue.


text:
module Propellor.Property.User where

import System.Posix

import Propellor

data Eep = YesReallyDeleteHome

accountFor :: UserName -> Property
accountFor user = check (isNothing <$> catchMaybeIO (homedir user)) $ cmdProperty "adduser"
	[ "--disabled-password"
	, "--gecos", ""
	, user
	]
	`describe` ("account for " ++ user)

-- | Removes user home directory!! Use with caution.
nuked :: UserName -> Eep -> Property
nuked user _ = check (isJust <$> catchMaybeIO (homedir user)) $ cmdProperty "userdel"
	[ "-r"
	, user
	]
	`describe` ("nuked user " ++ user)

-- | Only ensures that the user has some password set. It may or may
-- not be the password from the PrivData.
hasSomePassword :: UserName -> Context -> Property
hasSomePassword user context = check ((/= HasPassword) <$> getPasswordStatus user) $
	hasPassword user context

hasPassword :: UserName -> Context -> Property
hasPassword user context = withPrivData (Password user) context $ \getpassword ->
	property (user ++ " has password") $
		getpassword $ \password -> makeChange $
			withHandle StdinHandle createProcessSuccess
				(proc "chpasswd" []) $ \h -> do
					hPutStrLn h $ user ++ ":" ++ password
					hClose h

lockedPassword :: UserName -> Property
lockedPassword user = check (not <$> isLockedPassword user) $ cmdProperty "passwd"
	[ "--lock"
	, user
	]
	`describe` ("locked " ++ user ++ " password")

data PasswordStatus = NoPassword | LockedPassword | HasPassword
	deriving (Eq)

getPasswordStatus :: UserName -> IO PasswordStatus
getPasswordStatus user = parse . words <$> readProcess "passwd" ["-S", user]
  where
	parse (_:"L":_) = LockedPassword
	parse (_:"NP":_) = NoPassword
	parse (_:"P":_) = HasPassword
	parse _ = NoPassword

isLockedPassword :: UserName -> IO Bool
isLockedPassword user = (== LockedPassword) <$> getPasswordStatus user

homedir :: UserName -> IO FilePath
homedir user = homeDirectory <$> getUserEntryForName user


text:
import {expect} from '@playwright/test';
import {ConstantHelper, test} from '@umbraco/playwright-testhelpers';
import {TemplateBuilder} from "@umbraco/json-models-builders";

test.describe('Templates', () => {
  test.beforeEach(async ({page, umbracoApi}) => {
    // TODO: REMOVE THIS WHEN SQLITE IS FIXED
    // Wait so we don't bombard the API
    await page.waitForTimeout(1000);
    await umbracoApi.login();
  });

  async function navigateToSettings(page, umbracoUi) {
    await umbracoUi.goToSection(ConstantHelper.sections.settings);
    await umbracoUi.waitForTreeLoad(ConstantHelper.sections.settings);
  }

  async function createTemplate(page, umbracoUi) {
    await navigateToSettings(page, umbracoUi);
    await umbracoUi.clickElement(umbracoUi.getTreeItem("settings", ["Templates"]), {button: "right"});
    await umbracoUi.clickElement(umbracoUi.getContextMenuAction(ConstantHelper.actions.create));
  }

  test('Create template', async ({page, umbracoApi, umbracoUi}) => {
    const name = "Create template test";
    await umbracoApi.templates.ensureNameNotExists(name);

    await createTemplate(page, umbracoUi);
    // We have to wait for the ace editor to load, because when the editor is loading it will "steal" the focus briefly,
    // which causes the save event to fire if we've added something to the header field, causing errors.
    await page.waitForTimeout(500);

    // Type name
    await umbracoUi.getEditorHeaderName(name)
    // Save
    // We must drop focus for the auto save event to occur.
    await page.focus('.btn-success');
    // And then wait for the auto save event to finish by finding the page in the tree view.
    // This is a bit of a roundabout way to find items in a tree view since we dont use umbracoTreeItem
    // but we must be able to wait for the save event to finish, and we can't do that with umbracoTreeItem
    const label = await page.locator("a:has-text('Create template test')");
    await expect(label).toBeVisible({timeout: 10000});
    // Now that the auto save event has finished we can save
    // and there wont be any duplicates or file in use errors.
    await umbracoUi.clickElement(umbracoUi.getButtonByLabelKey(ConstantHelper.buttons.save));
    //Assert
    await umbracoUi.isSuccessNotificationVisible();
    // For some reason cy.umbracoErrorNotification tries to click the element which is not possible
    // if it doesn't actually exist, making should('not.be.visible') impossible.
    await expect(await page.locator('.umb-notifications__notifications > .alert-error')).not.toBeVisible();

    // Clean up
    await umbracoApi.templates.ensureNameNotExists(name);
  });

  test('Unsaved changes stay', async ({page, umbracoApi, umbracoUi}) => {
    const name = "Templates Unsaved Changes Stay test";
    const edit = "var num = 5;";
    await umbracoApi.templates.ensureNameNotExists(name);

    const template = new TemplateBuilder()
      .withName(name)
      .withContent('@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage\n')
      .build();

    await umbracoApi.templates.saveTemplate(template);

    await navigateToSettings(page, umbracoUi);

    // Open partial view
    await umbracoUi.clickElement(umbracoUi.getTreeItem("settings", ["Templates", name]));
    // Edit
    await page.locator('.ace_content').type(edit);
    await expect(await page.locator('.ace_content')).toBeVisible();
    await expect(await page.locator('.btn-success')).toBeVisible();

    // Navigate away
    await umbracoUi.goToSection(ConstantHelper.sections.content);
    await umbracoUi.waitForTreeLoad(ConstantHelper.sections.content);

    // Click stay button
    await page.locator('umb-button[label="Stay"] button:enabled').click();

    // Assert
    // That the same document is open
    await expect(await page.locator('#headerName')).toHaveValue(name);
    await expect(await page.locator('.ace_content')).toContainText(edit);

    // Clean up
    await umbracoApi.templates.ensureNameNotExists(name);
  });

  test('Discard unsaved changes', async ({page, umbracoApi, umbracoUi}) => {
    const name = "Discard changes test";
    const edit = "var num = 5;";

    await umbracoApi.templates.ensureNameNotExists(name);

    const template = new TemplateBuilder()
      .withName(name)
      .withContent('@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage\n')
      .build();

    await umbracoApi.templates.saveTemplate(template);

    await navigateToSettings(page, umbracoUi);

    // Open partial view
    await umbracoUi.clickElement(umbracoUi.getTreeItem("settings", ["Templates", name]));
    // Edit
    await page.locator('.ace_content').type(edit);
    await expect(await page.locator('.ace_content')).toBeVisible();
    await expect(await page.locator('.btn-success')).toBeVisible();

    // Navigate away
    await umbracoUi.goToSection(ConstantHelper.sections.content);
    await umbracoUi.waitForTreeLoad(ConstantHelper.sections.content);
    // Click discard
    await page.locator('umb-button[label="Discard changes"] button:enabled').click();
    // Navigate back
    await navigateToSettings(page, umbracoUi);

    // Asserts
    await expect(await page.locator('.ace_content')).not.toContainText(edit);
    // cy.umbracoPartialViewExists(fileName).then(exists => { expect(exists).to.be.false; }); TODO: Switch to template
    await umbracoApi.templates.ensureNameNotExists(name);
  });

  test('Insert macro', async ({page, umbracoApi, umbracoUi}) => {
    const name = 'InsertMacroTest';

    await umbracoApi.templates.ensureNameNotExists(name);
    await umbracoApi.macros.ensureNameNotExists(name);

    const template = new TemplateBuilder()
      .withName(name)
      .withContent('')
      .build();

    await umbracoApi.templates.saveTemplate(template);

    await umbracoApi.macros.save(name);

    await navigateToSettings(page, umbracoUi);
    await umbracoUi.clickElement(umbracoUi.getTreeItem("settings", ["Templates", name]));
    // Insert macro
    await umbracoUi.clickElement(umbracoUi.getButtonByLabelKey(ConstantHelper.buttons.insert));

    await page.locator('.umb-insert-code-box__title >> text=Macro').click();
    await page.locator(`.umb-card-grid-item[title='${name}']`).click();

    // Assert
    await expect(await page.locator('.ace_content')).toContainText('@await Umbraco.RenderMacroAsync("' + name + '")');

    // Clean
    await umbracoApi.templates.ensureNameNotExists(name);
    await umbracoApi.macros.ensureNameNotExists(name);
  });

  test('Insert value', async ({page, umbracoApi, umbracoUi}) => {
    const name = 'Insert Value Test';

    await umbracoApi.templates.ensureNameNotExists(name);

    const partialView = new TemplateBuilder()
      .withName(name)
      .withContent('')
      .build();

    await umbracoApi.templates.saveTemplate(partialView);

    await navigateToSettings(page, umbracoUi);
    await umbracoUi.clickElement(umbracoUi.getTreeItem("settings", ["Templates", name]));

    // Insert value
    await umbracoUi.clickElement(umbracoUi.getButtonByLabelKey(ConstantHelper.buttons.insert));
    await page.locator('.umb-insert-code-box__title >> text=Value').click();

    await page.selectOption('select', 'umbracoBytes');
    await umbracoUi.clickElement(umbracoUi.getButtonByLabelKey(ConstantHelper.buttons.submit));

    // assert
    await expect(await page.locator('.ace_content')).toContainText('@Model.Value("umbracoBytes")');

    // Clean
    await umbracoApi.templates.ensureNameNotExists(name);
  });
});


text:
package org.sakaiproject.evaluation.logic.externals;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.sakaiproject.evaluation.logic.model.EvalHierarchyNode;
import org.sakaiproject.evaluation.providers.EvalHierarchyProvider;

/**
 * This brings in the hierarchy information and gives us the ability to control the
 * hierarchy
 *
 * @author Aaron Zeckoski (aaron@caret.cam.ac.uk)
 */
public interface ExternalHierarchyLogic extends EvalHierarchyProvider, ExternalHierarchyPermissions {

   /**
    * Add a new node to a hierarchy
    *
    * @param parentNodeId the unique id for the parent of this node, can be null if this is the root or a top level node
    * @return the object representing the newly added node
    */
   public EvalHierarchyNode addNode(String parentNodeId);

   /**
    * Remove a node from the hierarchy if it is possible,
    * nodes can only be removed if they have no children associations,
    * root nodes can never be removed,
    * nodes which have evalgroups assigned to them cannot be removed,
    * exception occurs if these rules are violated
    * <br/>NOTE: this will remove associated template items from their association
    * with the node and place them back in the default level
    *
    * @param nodeId a unique id for a hierarchy node
    * @return the object representing the parent of the removed node
    */
   public EvalHierarchyNode removeNode(String nodeId);

   /**
    * Save meta data on a node, this has to be done separately from creating a node
    *
    * @param nodeId a unique id for a hierarchy node
    * @param title the title of the node
    * @param description a description for this node
    * @return the object representing the updated node
    */
   public EvalHierarchyNode updateNodeData(String nodeId, String title, String description);

   /**
    * Set this set to be the set of eval group ids associated with this node,
    * can also be used to clear the associated ids
    *
    * @param nodeId a unique id for a hierarchy node
    * @param evalGroupIds the unique IDs of eval groups to associate, if this is an
    * empty set then this will clear the associations so there are no groups associated
    */
   public void setEvalGroupsForNode(String nodeId, Set<String> evalGroupIds);

   /**
    * Get all the children node ids which exist under the set of supplied nodes
    * @param nodes a set of eval hierarchy nodes
    * @param includeSuppliedNodeIds include the nodes ids of the supplied collection of nodes
    * @return a set of all unique child nodes
    */
   public Set<String> getAllChildrenNodes(Collection<EvalHierarchyNode> nodes, boolean includeSuppliedNodeIds);

   /**
    * Create a sorted list of nodes based on a set of input nodes,
    * list goes from root (or highest parent) down to the bottom most node
    *
    * @param nodes a collection of nodes
    * @return a list of {@link EvalHierarchyNode}
    */
   public List<EvalHierarchyNode> getSortedNodes(Collection<EvalHierarchyNode> nodes);

}


text:
<?php

namespace Artesaos\Zenvia\Http;

use Artesaos\Zenvia\Contracts\RequestManagerInterface;
use Artesaos\Zenvia\Exceptions\ZenviaRequestException;
use Carbon\Carbon;
use Http\Client\Exception\TransferException;
use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;

class RequestManager implements RequestManagerInterface
{
    /**
     * @var \Http\Client\HttpClient
     */
    private $httpClient;

    private $url;

    public function __construct()
    {
        $this->setUrl('https://private-anon-4abaa2a33-zenviasms.apiary-mock.com/');
    }

    /**
     * {@inheritdoc}
     */
    public function sendRequest($method, $uri, array $body = [], $access_code, $protocolVersion = '1.1')
    {
        $request = MessageFactoryDiscovery::find()->createRequest($method, $this->getUrl().$uri, ['authorization'=>"Basic $access_code",'content-type'=>'application/json','accept'=>'application/json'], json_encode($body), $protocolVersion);
        try {
            $response = ResponseHandler::convert($this->getHttpClient()->sendRequest($request),'psr7');

            ResponseHandler::handleWithErrors($response);
            return $response;
        } catch (TransferException $e) {
            throw new ZenviaRequestException('Error while requesting data from Zenvia API: '.$e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function convertDateFormatFromArrayField(array $data, $field, $format)
    {
        if(isset($data['sendSmsRequest'][$field])){
            $data['sendSmsRequest'][$field] = (new Carbon($data['sendSmsRequest'][$field]))->format($format);
        }elseif(isset($data['sendSmsMultiRequest']['sendSmsRequestList'])){
            foreach($data['sendSmsMultiRequest']['sendSmsRequestList'] as &$value){
                if($value[$field]){
                    $value[$field] = (new Carbon($value[$field]))->format($format);
                }
            }
            $data = array_intersect_key($data, array_flip(array_filter(array_keys($data), 'is_string')));
        }
        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function setHttpClient(HttpClient $httpClient)
    {
        $this->httpClient = $httpClient;
        return $this;
    }

    /**
     * @return HttpClient
     * @throws ZenviaRequestException
     */
    public function getHttpClient()
    {
        if ($this->httpClient === null) {
            $this->httpClient = HttpClientDiscovery::find();
            if ($this->httpClient === null){
                throw new ZenviaRequestException('The RequestManager expects a valid Http Client or Adapter, none given. Please install a valid Http Client or Adapter');
            }
        }
        return $this->httpClient;
    }

    /**
     * @return mixed
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @param $url
     * @return mixed
     */
    public function setUrl($url)
    {
        $this->url = $url;
    }
}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>Creating virtual machines in libvirt with virt-install · Leif Madsen</title>

  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/poole-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-overrides.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/hyde-x.css">
  <link rel="stylesheet" href="http://blog.leifmadsen.com/css/highlight/monokai.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://blog.leifmadsen.com/touch-icon-144-precomposed.png">
  <link href="http://blog.leifmadsen.com/favicon.png" rel="icon">

  <meta name="description" content="Leif Madsen's Blog">
  <meta name="keywords" content="blog,leif,madsen,canada,containers,asterisk,development,devops,infrastructure,implementation engineer">

Leif Madsen

I’m not clever enough for a tagline.

Blog

Posts

Copyright © 2016 License

       Powered by Hugo and Hyde-X

Creating virtual machines in libvirt with virt-install

    Dec 16, 2016 · 4 minute read · Comments

    libvirtlinuxvirtualizationconsole

I’ve been wanting to automate my virtual machine instantiation for a while now,
but I’ve always hated the idea of having to spin up multiple bits of
infrastruction to deal with PXE booting, web server to host a kickstart file,
etc. Luckily, I ran into some stuff today, and figured out how to automate
virtual machine instantitation without having to resort to anything outside of
localhost.

Preface

I have an LVM logical volume that hosts my virtual machines my M.2 disk drive,
and everything else on the host running from the SSD. This means that I have
/var/lib/libvirt/images/ mounted to my M.2 drive, and everything else on the
SSD (except for swap as well).

Originally I was trying to get all this working with the user session, but the
user doesn’t have permission to make networking changes and to attach to the
bridged network. A few things on the internet seemed to indicate running as a
user wasn’t possible because of this. I suspect there are some permissions
things and SElinux tweaks I could do to make it work, but path of least
resistence for now is how it’ll be.

That just means the following commands are going to be run with sudo. Of
course if you are just going to use the default network then you might be
able to get away with doing some of this in a user session.

Using virt-install

Using the virt-install application we can instantitate a virtual machine from
the console. I got this all working by running the following command:

sudo virt-install --name testing --memory 1024 \
    --disk /var/lib/libvirt/images/testing.qcow2,size=20,bus=virtio \
    --cdrom /var/lib/libvirt/isos/centos7.iso \
    --boot cdrom \
    --network bridge=br0 \
    --noautoconsole --vnc

If we look at this command, it defines the following things:

virtual machine is named testing

we define 1024 MB of memory (RAM) to this VM

the VM will use a qcow2 backing disk with a size of 20GB, over the virtio bus

we’ll mount the centos7.iso into the CDROM (boot media)

tell the system to boot from the CDROM

assign the network to bridge to interface br0

don’t start a console, and enable VNC

I originally did this so that 1) I could validate that everything was going to
work :) and 2) so that I could perform a minimal install to generate my initial
anaconda-ks.cfg file (kickstart file).

After installation, I scp’d the file down to my host and moved onto the next
step. Automation ftw!

Automating our virtual machine instantiation

Next up we just need to make a couple changes to our virt-install command so
that we use the new kickstart file for our deployment. First though, we need to
add a reboot value to the default anaconda-ks.cfg file.

Kickstart file

The following is the default generated kickstart file from a CentOS 7 minimal
install.

You’ll see that I’ve added reboot right after the clearpart command, and
just before the %packages command.

#version=DEVEL
# System authorization information
auth --enableshadow --passalgo=sha512
# Use CDROM installation media
cdrom
# Use graphical install
graphical
# Run the Setup Agent on first boot
firstboot --enable
ignoredisk --only-use=vda
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
# System language
lang en_US.UTF-8

# Network information
network  --bootproto=dhcp --device=eth0 --ipv6=auto --activate
network  --hostname=localhost.localdomain

# Root password
rootpw --iscrypted <ENCRYPTED_PASSWORD>
# System services
services --enabled="chronyd"
# System timezone
timezone America/New_York --isUtc
user --groups=wheel --name=stack --password=<ENCRYPTED_PASSWORD> --iscrypted --gecos="stack"
# System bootloader configuration
bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=vda
autopart --type=lvm
# Partition clearing information
clearpart --none --initlabel

reboot

%packages
@^minimal
@core
chrony
kexec-tools

%end

%addon com_redhat_kdump --enable --reserve-mb='auto'

%end

%anaconda
pwpolicy root --minlen=6 --minquality=50 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=50 --notstrict --nochanges --notempty
pwpolicy luks --minlen=6 --minquality=50 --notstrict --nochanges --notempty
%end

Kickstart-based virtual machine instantiation

And here is our modified virt-install line which will get you a CentOS 7
virtual machine created. Once the installation completes, the VM will shut
down, and you can start it back up with sudo virsh start <machine_name>.

Here is the command that will install your VM for you using the local kickstart
file.

sudo virt-install --name testing --memory 1024 \
    --disk /var/lib/libvirt/images/testing.qcow2,size=20,bus=virtio \
    --location /var/lib/libvirt/isos/centos7.iso \
    --boot cdrom \
    --network bridge=br0 \
    --noautoconsole --vnc \
    --initrd-inject anaconda-ks.cfg \
    --extra-args "inst.ks=file:/anaconda-ks.cfg"

Please enable JavaScript to view the comments powered by Disqus.


text:
package middleware

import (
	"context"
	"fmt"
	"time"

	"github.com/influxdata/influxdb/v2/kit/platform"
	"github.com/influxdata/kapacitor/task/taskmodel"
)

// Coordinator is a type which is used to react to
// task related actions
type Coordinator interface {
	TaskCreated(context.Context, *taskmodel.Task) error
	TaskUpdated(ctx context.Context, from, to *taskmodel.Task) error
	TaskDeleted(context.Context, platform.ID) error
	RunCancelled(ctx context.Context, runID platform.ID) error
	RunRetried(ctx context.Context, task *taskmodel.Task, run *taskmodel.Run) error
	RunForced(ctx context.Context, task *taskmodel.Task, run *taskmodel.Run) error
}

// CoordinatingTaskService acts as a TaskService decorator that handles coordinating the api request
// with the required task control actions asynchronously via a message dispatcher
type CoordinatingTaskService struct {
	taskmodel.TaskService
	coordinator Coordinator

	now func() time.Time
}

// New constructs a new coordinating task service
func New(service taskmodel.TaskService, coordinator Coordinator) *CoordinatingTaskService {
	c := &CoordinatingTaskService{
		TaskService: service,
		coordinator: coordinator,
		now: func() time.Time {
			return time.Now().UTC()
		},
	}

	return c
}

// CreateTask Creates a task in the existing task service and Publishes the change so any TaskD service can lease it.
func (s *CoordinatingTaskService) CreateTask(ctx context.Context, tc taskmodel.TaskCreate) (*taskmodel.Task, error) {
	t, err := s.TaskService.CreateTask(ctx, tc)
	if err != nil {
		return t, err
	}

	if err := s.coordinator.TaskCreated(ctx, t); err != nil {
		if derr := s.TaskService.DeleteTask(ctx, t.ID); derr != nil {
			return t, fmt.Errorf("schedule task failed: %s\n\tcleanup also failed: %s", err, derr)
		}

		return t, err
	}

	return t, nil
}

// UpdateTask Updates a task and publishes the change so the task owner can act on the update
func (s *CoordinatingTaskService) UpdateTask(ctx context.Context, id platform.ID, upd taskmodel.TaskUpdate) (*taskmodel.Task, error) {
	from, err := s.TaskService.FindTaskByID(ctx, id)
	if err != nil {
		return nil, err
	}

	to, err := s.TaskService.UpdateTask(ctx, id, upd)
	if err != nil {
		return to, err
	}

	return to, s.coordinator.TaskUpdated(ctx, from, to)
}

// DeleteTask delete the task and publishes the change, to allow the task owner to find out about this change faster.
func (s *CoordinatingTaskService) DeleteTask(ctx context.Context, id platform.ID) error {
	if err := s.coordinator.TaskDeleted(ctx, id); err != nil {
		return err
	}

	return s.TaskService.DeleteTask(ctx, id)
}

// CancelRun Cancel the run and publish the cancellation.
func (s *CoordinatingTaskService) CancelRun(ctx context.Context, taskID, runID platform.ID) error {
	if err := s.TaskService.CancelRun(ctx, taskID, runID); err != nil {
		return err
	}

	return s.coordinator.RunCancelled(ctx, runID)
}

// RetryRun calls retry on the task service and publishes the retry.
func (s *CoordinatingTaskService) RetryRun(ctx context.Context, taskID, runID platform.ID) (*taskmodel.Run, error) {
	t, err := s.TaskService.FindTaskByID(ctx, taskID)
	if err != nil {
		return nil, err
	}

	r, err := s.TaskService.RetryRun(ctx, taskID, runID)
	if err != nil {
		return r, err
	}

	return r, s.coordinator.RunRetried(ctx, t, r)
}

// ForceRun create the forced run in the task system and publish to the pubSub.
func (s *CoordinatingTaskService) ForceRun(ctx context.Context, taskID platform.ID, scheduledFor int64) (*taskmodel.Run, error) {
	t, err := s.TaskService.FindTaskByID(ctx, taskID)
	if err != nil {
		return nil, err
	}

	r, err := s.TaskService.ForceRun(ctx, taskID, scheduledFor)
	if err != nil {
		return r, err
	}

	return r, s.coordinator.RunForced(ctx, t, r)
}