text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/material_drawer_dark_background</item>
        <item name="colorPrimaryDark">@color/material_drawer_dark_selected</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="CustomTheme" parent="MaterialDrawerTheme.TranslucentStatus">
        <!-- ...and here we setting appcompat's color theme attrs -->
        <item name="colorPrimary">#96CA2D</item>
        <item name="colorPrimaryDark">#96CA2D</item>
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowFullscreen">true</item>

        <!-- MaterialDrawer specific values -->
        <item name="material_drawer_background">@color/material_drawer_dark_background</item>
        <item name="material_drawer_primary_text">@color/material_drawer_dark_primary_text</item>
        <item name="material_drawer_secondary_text">@color/material_drawer_dark_secondary_text
        </item>
        <item name="material_drawer_hint_text">@color/material_drawer_dark_hint_text</item>
        <item name="material_drawer_divider">@color/material_drawer_dark_divider</item>
        <item name="material_drawer_selected">@color/material_drawer_dark_selected</item>
        <item name="material_drawer_selected_text">#96CA2D</item>
        <item name="material_drawer_header_selection_text">
            @color/material_drawer_dark_primary_text
        </item>

        <!-- CAB :D -->
        <item name="windowActionModeOverlay">true</item>
    </style>

    <style name="MaterialSearchViewStyle">
        <!-- Background for the search bar -->
        <item name="searchBackground">@color/material_drawer_dark_background</item>

        <!-- Change voice icon -->
        <item name="searchVoiceIcon">@drawable/ic_action_voice_search_inverted</item>

        <!-- Change clear text icon -->
        <item name="searchCloseIcon">@drawable/ic_action_navigation_close_inverted</item>

        <!-- Change up icon -->
        <item name="searchBackIcon">@drawable/ic_action_navigation_arrow_back_inverted</item>

        <!-- Change icon for the suggestions -->
        <item name="searchSuggestionIcon">@drawable/ic_suggestion</item>

        <!-- Change background for the suggestions list view -->
        <item name="searchSuggestionBackground">@color/material_drawer_dark_selected</item>

        <!-- Change text color for edit text. This will also be the color of the cursor -->
        <item name="android:textColor">@color/material_drawer_dark_primary_text</item>

        <!-- Change hint text color for edit text -->
        <item name="android:textColorHint">@color/material_drawer_dark_primary_text</item>

        <!-- Hint for edit text -->
        <item name="android:hint">@string/search_hint</item>
    </style>

    <style name="TextAppearanceFinish">
        <item name="android:textColor">#fff</item>
    </style>

    <style name="ButtonBar" parent="@android:style/ButtonBar">
        <item name="android:background">@android:color/transparent</item>
        <item name="android:padding">0dp</item>
    </style>

    <style name="ButtonBarButton">
        <item name="android:minHeight">40dp</item>
    </style>

</resources>


text:
const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
const { parseYAML, guessFormat } = require('../format');

const help = ui => {
    const { bold, cyan } = ui.colors;

    ui.print(`
${bold('NAME')}
        comfy setall - Replace the configuration for a given environment

${bold('SYNOPSIS')}
        ${bold('comfy')} setall <environment> <path> [<options>]

${bold('OPTIONS')}
        <environment>     Name of the environment (must already exist in project)
        <path>            Path to a configuration file (accepts json and yml formats)
        -t, --tag=<tag>   Set a tag for this config version (default: stable)
        -h, --help        Show this very help message

${bold('EXAMPLES')}
        ${cyan('comfy setall development config/comfy.json')}
        ${cyan('comfy setall production config/api.yml -t next')}
`);
};

module.exports = (ui, modules) =>
    function* setall(rawOptions) {
        const { red, green, bold } = ui.colors;
        const options = minimist(rawOptions);
        const env = options._[0];
        const configPath = options._[1];
        const tag = options.tag || options.t || 'latest';

        if (options.help || options.h || options._.includes('help')) {
            help(ui);
            return ui.exit(0);
        }

        if (!env) {
            ui.error(red('No environment specified.'));
        }

        if (!configPath) {
            ui.error(red('No config file specified.'));
        }

        if (!env || !configPath) {
            ui.print(`${bold('SYNOPSIS')}
        ${bold('comfy')} setall <environment> <path> [<options>]

Type ${green('comfy setall --help')} for details`);
            return ui.exit(0);
        }

        const filename = configPath.startsWith(path.sep)
            ? path.normalize(configPath)
            : path.normalize(`${process.cwd()}${path.sep}${configPath}`);

        if (!fs.existsSync(filename)) {
            ui.error(`The file ${red(configPath)} doesn't exist.`);
            return ui.exit(1);
        }

        const stats = fs.statSync(filename);
        if (!stats.isFile()) {
            ui.error(`The object located at ${red(configPath)} is not a file.`);
            return ui.exit(1);
        }

        const file = fs.readFileSync(filename, 'utf-8');

        let parsedContent;

        try {
            parsedContent = parseYAML(file);
        } catch (err) {
            ui.error(red(`Failed to parse ${configPath}`));
        }

        const project = yield modules.project.retrieveFromConfig();

        yield modules.config.add(project, env, parsedContent, {
            tag,
            configName: 'default',
            format: guessFormat(path.extname(filename)),
        });

        ui.print(`${bold(green('comfy configuration successfully saved'))}`);
        return ui.exit();
    };

redpajama_set_name: RedPajamaGithub


text:
package org.apache.rya.shell;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Set;
import java.util.UUID;

import org.apache.rya.api.client.GetInstanceDetails;
import org.apache.rya.api.client.RyaClient;
import org.apache.rya.api.client.SetRyaStreamsConfiguration;
import org.apache.rya.api.client.accumulo.AccumuloConnectionDetails;
import org.apache.rya.api.instance.RyaDetails;
import org.apache.rya.api.instance.RyaDetails.RyaStreamsDetails;
import org.apache.rya.shell.util.ConsolePrinter;
import org.apache.rya.shell.util.SparqlPrompt;
import org.apache.rya.streams.api.RyaStreamsClient;
import org.apache.rya.streams.api.entity.StreamsQuery;
import org.apache.rya.streams.api.interactor.AddQuery;
import org.apache.rya.streams.api.interactor.DeleteQuery;
import org.apache.rya.streams.api.interactor.GetQuery;
import org.apache.rya.streams.api.interactor.ListQueries;
import org.apache.rya.streams.api.interactor.StartQuery;
import org.apache.rya.streams.api.interactor.StopQuery;
import org.junit.Test;

import com.google.common.base.Optional;
import com.google.common.collect.Sets;

/**
 * Unit tests the methods of {@link RyaStreamsCommands}.
 */
public class RyaStreamsCommandsTest {

    @Test
    public void configureRyaStreams() throws Exception {
        // Mock the object that performs the configure operation.
        final RyaClient mockCommands = mock(RyaClient.class);
        final SetRyaStreamsConfiguration setStreams = mock(SetRyaStreamsConfiguration.class);
        when(mockCommands.getSetRyaStreamsConfiguration()).thenReturn(setStreams);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mockCommands);
        state.connectedToInstance("unitTest");

        // Verify that no Rya Streams Client is set to the state.
        assertFalse(state.getShellState().getRyaStreamsCommands().isPresent());

        try {
            // Execute the command.
            final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
            final String message = commands.configureRyaStreams("localhost", 6);

            // Verify the request was forwarded to the mocked interactor.
            final RyaStreamsDetails expectedDetails = new RyaStreamsDetails("localhost", 6);
            verify(setStreams).setRyaStreamsConfiguration(eq("unitTest"), eq(expectedDetails));

            // Verify a RyaStreamsClient was created and added to the state.
            assertTrue(state.getShellState().getRyaStreamsCommands().isPresent());

            // Verify the correct message is reported.
            final String expected = "The Rya Instance has been updated to use the provided Rya Streams subsystem. " +
                    "Rya Streams commands are now avaiable while connected to this instance.";
            assertEquals(expected, message);
        } finally {
            state.getShellState().getRyaStreamsCommands().get().close();
        }
    }

    @Test
    public void printRyaStreamsDetails_noRyaDetails() throws Exception {
        // Mock the object that performs the configure operation.
        final RyaClient mockCommands = mock(RyaClient.class);
        final GetInstanceDetails getDetails = mock(GetInstanceDetails.class);
        when(mockCommands.getGetInstanceDetails()).thenReturn(getDetails);

        // When getting the instance details, ensure they are not found.
        when(getDetails.getDetails(eq("unitTest"))).thenReturn(Optional.absent());

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mockCommands);
        state.connectedToInstance("unitTest");

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.printRyaStreamsDetails();
        final String expected = "This instance does not have any Rya Details, so it is unable to be connected to the Rya Streams subsystem.";
        assertEquals(expected, message);
    }

    @Test
    public void printRyaStreamsDetails_notConfigured() throws Exception {
        // Mock the object that performs the configure operation.
        final RyaClient mockCommands = mock(RyaClient.class);
        final GetInstanceDetails getDetails = mock(GetInstanceDetails.class);
        when(mockCommands.getGetInstanceDetails()).thenReturn(getDetails);

        // When getting the instance details, ensure they do not have RyaStreamsDetails to print.
        final RyaDetails details = mock(RyaDetails.class);
        when(details.getRyaStreamsDetails()).thenReturn(Optional.absent());
        when(getDetails.getDetails(eq("unitTest"))).thenReturn(Optional.of(details));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mockCommands);
        state.connectedToInstance("unitTest");

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.printRyaStreamsDetails();
        final String expected = "This instance of Rya has not been configured to use a Rya Streams subsystem.";
        assertEquals(expected, message);
    }

    @Test
    public void printRyaStreamsDetails_configured() throws Exception {
        // Mock the object that performs the configure operation.
        final RyaClient mockCommands = mock(RyaClient.class);
        final GetInstanceDetails getDetails = mock(GetInstanceDetails.class);
        when(mockCommands.getGetInstanceDetails()).thenReturn(getDetails);

        // When getting the instance details, ensure they do have RyaStreamsDetails to print.
        final RyaDetails details = mock(RyaDetails.class);
        when(details.getRyaStreamsDetails()).thenReturn(Optional.of(new RyaStreamsDetails("localhost", 6)));
        when(getDetails.getDetails(eq("unitTest"))).thenReturn(Optional.of(details));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mockCommands);
        state.connectedToInstance("unitTest");

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.printRyaStreamsDetails();
        final String expected = "Kafka Hostname: localhost, Kafka Port: 6";
        assertEquals(expected, message);
    }

    @Test
    public void addQuery_userAbortsSparqlPrompt() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final AddQuery addQuery = mock(AddQuery.class);
        when(mockClient.getAddQuery()).thenReturn(addQuery);

        // Mock a SPARQL prompt that a user aborts.
        final SparqlPrompt prompt = mock(SparqlPrompt.class);
        when(prompt.getSparql()).thenReturn(Optional.absent());

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
        final String message = commands.addQuery(false, false);

        // Verify a message is printed to the user.
        assertEquals("", message);
    }

    @Test
    public void addQuery_doNotInsertQuery() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final AddQuery addQuery = mock(AddQuery.class);
        when(mockClient.getAddQuery()).thenReturn(addQuery);

        final String sparql = "SELECT * WHERE { ?a ?b ?c }";

        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, false);
        when(addQuery.addQuery(eq(sparql), eq(true), eq(false))).thenReturn(addedQuery);

        // Mock a SPARQL prompt that a user entered a query through.
        final SparqlPrompt prompt = mock(SparqlPrompt.class);
        when(prompt.getSparql()).thenReturn(Optional.of(sparql));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
        final String message = commands.addQuery(false, false);

        // Verify the interactor was invoked with the provided input.
        verify(addQuery).addQuery(sparql, true, false);

        // Verify a message is printed to the user.
        final String expected = "The added query's ID is " + addedQuery.getQueryId();
        assertEquals(expected, message);
    }

    @Test
    public void addQuery_insertConstructQuery() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final AddQuery addQuery = mock(AddQuery.class);
        when(mockClient.getAddQuery()).thenReturn(addQuery);

        final String sparql =
                "PREFIX vCard: <http://www.w3.org/2001/vcard-rdf/3.0#> " +
                "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
                "CONSTRUCT { " +
                    "?X vCard:FN ?name . " +
                    "?X vCard:URL ?url . " +
                    "?X vCard:TITLE ?title . " +
                "} " +
                "FROM <http://www.w3.org/People/Berners-Lee/card> " +
                "WHERE { " +
                    "OPTIONAL { ?X foaf:name ?name . FILTER isLiteral(?name) . } " +
                    "OPTIONAL { ?X foaf:homepage ?url . FILTER isURI(?url) . } " +
                    "OPTIONAL { ?X foaf:title ?title . FILTER isLiteral(?title) . } " +
                "}";

        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, true);
        when(addQuery.addQuery(eq(sparql), eq(false), eq(true))).thenReturn(addedQuery);

        // Mock a SPARQL prompt that a user entered a query through.
        final SparqlPrompt prompt = mock(SparqlPrompt.class);
        when(prompt.getSparql()).thenReturn(Optional.of(sparql));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
        final String message = commands.addQuery(true, true);

        // Verify the interactor was invoked with the provided input.
        verify(addQuery).addQuery(sparql, false, true);

        // Verify a message is printed to the user.
        final String expected = "The added query's ID is " + addedQuery.getQueryId();
        assertEquals(expected, message);
    }

    @Test
    public void addQuery_doNotInsertInsertUpdate() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final AddQuery addQuery = mock(AddQuery.class);
        when(mockClient.getAddQuery()).thenReturn(addQuery);

        final String sparql =
                "PREFIX Sensor: <http://example.com/Equipment.owl#> " +
                "INSERT { " +
                    "?subject Sensor:test2 ?newValue " +
                "} WHERE {" +
                    "values (?oldValue ?newValue) {" +
                        "('testValue1' 'newValue1')" +
                        "('testValue2' 'newValue2')" +
                    "}" +
                    "?subject Sensor:test1 ?oldValue" +
                "}";

        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, false);
        when(addQuery.addQuery(eq(sparql), eq(false), eq(false))).thenReturn(addedQuery);

        // Mock a SPARQL prompt that a user entered a query through.
        final SparqlPrompt prompt = mock(SparqlPrompt.class);
        when(prompt.getSparql()).thenReturn(Optional.of(sparql));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
        final String message = commands.addQuery(true, false);

        // Verify the interactor was invoked with the provided input.
        verify(addQuery).addQuery(sparql, false, false);

        // Verify a message is printed to the user.
        final String expected = "The added query's ID is " + addedQuery.getQueryId();
        assertEquals(expected, message);
    }

    @Test(expected = RuntimeException.class)
    public void addQuery_insertQueryNotCorrectType() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final AddQuery addQuery = mock(AddQuery.class);
        when(mockClient.getAddQuery()).thenReturn(addQuery);

        final String sparql = "SELECT * WHERE { ?a ?b ?c }";

        final StreamsQuery addedQuery = new StreamsQuery(UUID.randomUUID(), sparql, true, true);
        when(addQuery.addQuery(eq(sparql), eq(false), eq(true))).thenReturn(addedQuery);

        // Mock a SPARQL prompt that a user entered a query through.
        final SparqlPrompt prompt = mock(SparqlPrompt.class);
        when(prompt.getSparql()).thenReturn(Optional.of(sparql));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, prompt, mock(ConsolePrinter.class));
        commands.addQuery(true, true);
    }

    @Test
    public void deleteQuery() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final DeleteQuery deleteQuery = mock(DeleteQuery.class);
        when(mockClient.getDeleteQuery()).thenReturn(deleteQuery);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final UUID queryId = UUID.randomUUID();
        final String message = commands.deleteQuery(queryId.toString());

        // Verify the interactor was invoked with the provided parameters.
        verify(deleteQuery).delete(eq(queryId));

        // Verify a message is printed to the user.
        final String expected = "The query has been deleted.";
        assertEquals(expected, message);
    }

    @Test
    public void startQuery() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final StartQuery startQuery = mock(StartQuery.class);
        when(mockClient.getStartQuery()).thenReturn(startQuery);
        final GetQuery getQuery = mock(GetQuery.class);
        when(mockClient.getGetQuery()).thenReturn(getQuery);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Report the query as not running.
        final UUID queryId = UUID.randomUUID();
        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false, false)));

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.startQuery(queryId.toString());

        // Verify the interactor was invoked with the provided parameters.
        verify(startQuery).start(queryId);

        // Verify a message is printed to the user.
        final String expected = "The query will be processed by the Rya Streams subsystem.";
        assertEquals(expected, message);
    }

    @Test
    public void startQuery_alreadyRunning() throws Exception{
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final StartQuery startQuery = mock(StartQuery.class);
        when(mockClient.getStartQuery()).thenReturn(startQuery);
        final GetQuery getQuery = mock(GetQuery.class);
        when(mockClient.getGetQuery()).thenReturn(getQuery);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Report the query as running.
        final UUID queryId = UUID.randomUUID();
        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true, false)));

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.startQuery(queryId.toString());

        // Verify the interactor was not invoked.
        verify(startQuery, never()).start(queryId);

        // Verify a message is printed to the user.
        final String expected = "That query is already running.";
        assertEquals(expected, message);
    }

    @Test
    public void stopQuery() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final StopQuery stopQuery = mock(StopQuery.class);
        when(mockClient.getStopQuery()).thenReturn(stopQuery);
        final GetQuery getQuery = mock(GetQuery.class);
        when(mockClient.getGetQuery()).thenReturn(getQuery);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Report the query as running.
        final UUID queryId = UUID.randomUUID();
        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", true, false)));

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.stopQuery(queryId.toString());

        // Verify the interactor was invoked with the provided parameters.
        verify(stopQuery).stop(queryId);

        // Verify a message is printed to the user.
        final String expected = "The query will no longer be processed by the Rya Streams subsystem.";
        assertEquals(expected, message);
    }

    @Test
    public void stopQuery_alreadyStopped() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final StopQuery stopQuery = mock(StopQuery.class);
        when(mockClient.getStopQuery()).thenReturn(stopQuery);
        final GetQuery getQuery = mock(GetQuery.class);
        when(mockClient.getGetQuery()).thenReturn(getQuery);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Report the query as not running.
        final UUID queryId = UUID.randomUUID();
        when(getQuery.getQuery(eq(queryId))).thenReturn(java.util.Optional.of(new StreamsQuery(queryId, "sparql", false, false)));

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.stopQuery(queryId.toString());

        // Verify the interactor was not invoked with the provided parameters.
        verify(stopQuery, never()).stop(queryId);

        // Verify a message is printed to the user.
        final String expected = "That query is already stopped.";
        assertEquals(expected, message);
    }

    @Test
    public void listQueries() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final ListQueries listQueries = mock(ListQueries.class);
        when(mockClient.getListQueries()).thenReturn(listQueries);

        final Set<StreamsQuery> queries = Sets.newHashSet(
                new StreamsQuery(
                        UUID.fromString("33333333-3333-3333-3333-333333333333"),
                        "SELECT * WHERE { ?person <urn:worksAt> ?business . }",
                        true, false),
                new StreamsQuery(
                        UUID.fromString("11111111-1111-1111-1111-111111111111"),
                        "SELECT * WHERE { ?a ?b ?c . }",
                        true, false),
                new StreamsQuery(
                        UUID.fromString("22222222-2222-2222-2222-222222222222"),
                        "SELECT * WHERE { ?d ?e ?f . }",
                        false, false));
        when(listQueries.all()).thenReturn(queries);

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.listQueries();

        // Verify the correct report is returned.
        final String expected =
                "-----------------------------------------------\n" +
                " Query ID: 11111111-1111-1111-1111-111111111111\n" +
                "Is Active: true\n" +
                "Is Insert: false\n" +
                "   SPARQL: select ?a ?b ?c\n" +
                "           where {\n" +
                "             ?a ?b ?c.\n" +
                "           }\n" +
                "-----------------------------------------------\n" +
                " Query ID: 22222222-2222-2222-2222-222222222222\n" +
                "Is Active: false\n" +
                "Is Insert: false\n" +
                "   SPARQL: select ?d ?e ?f\n" +
                "           where {\n" +
                "             ?d ?e ?f.\n" +
                "           }\n" +
                "-----------------------------------------------\n" +
                " Query ID: 33333333-3333-3333-3333-333333333333\n" +
                "Is Active: true\n" +
                "Is Insert: false\n" +
                "   SPARQL: select ?person ?business\n" +
                "           where {\n" +
                "             ?person <urn:worksAt> ?business.\n" +
                "           }\n" +
                "-----------------------------------------------\n";
        assertEquals(expected, message);
    }

    @Test
    public void printQueryDetails() throws Exception {
        // Mock the object that performs the rya streams operation.
        final RyaStreamsClient mockClient = mock(RyaStreamsClient.class);
        final GetQuery getQuery = mock(GetQuery.class);
        when(mockClient.getGetQuery()).thenReturn(getQuery);

        final UUID queryId = UUID.fromString("da55cea5-c21c-46a5-ab79-5433eef4efaa");
        final StreamsQuery query = new StreamsQuery(queryId, "SELECT * WHERE { ?a ?b ?c . }", true, false);
        when(getQuery.getQuery(queryId)).thenReturn(java.util.Optional.of(query));

        // Mock a shell state and connect it to a Rya instance.
        final SharedShellState state = new SharedShellState();
        state.connectedToAccumulo(mock(AccumuloConnectionDetails.class), mock(RyaClient.class));
        state.connectedToInstance("unitTest");
        state.connectedToRyaStreams(mockClient);

        // Execute the command.
        final RyaStreamsCommands commands = new RyaStreamsCommands(state, mock(SparqlPrompt.class), mock(ConsolePrinter.class));
        final String message = commands.printQueryDetails(queryId.toString());

        // Verify the correct report is returned.
        final String expected =
                " Query ID: da55cea5-c21c-46a5-ab79-5433eef4efaa\n" +
                "Is Active: true\n" +
                "Is Insert: false\n" +
                "   SPARQL: select ?a ?b ?c\n" +
                "           where {\n" +
                "             ?a ?b ?c.\n" +
                "           }\n";
        assertEquals(expected, message);
    }
}


text:
<?php

namespace app\modules\admin\controllers;

use Yii;
use app\models\TypeTransaction;
use app\models\TypeTransactionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * TypeTransactionController implements the CRUD actions for TypeTransaction model.
 */
class TypeTransactionController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all TypeTransaction models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TypeTransactionSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new TypeTransaction model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new TypeTransaction();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    /**
     * Deletes an existing TypeTransaction model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the TypeTransaction model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return TypeTransaction the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = TypeTransaction::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<?php

add_action( 'foundation_module_init_mobile', 'foundation_base_init' );

function foundation_base_get_script_deps() {
	$settings = foundation_get_settings();
	$script_deps = array( 'jquery' );

	if ( defined( 'WPTOUCH_MODULE_SPINJS_INSTALLED' ) ) {
		$script_deps[] = 'foundation_spinjs_jquery';
	}

	if ( defined( 'WPTOUCH_MODULE_FEATURED_INSTALLED' ) && $settings->featured_enabled ) {
		$script_deps[] = 'foundation_featured';
	}

	if ( defined( 'WPTOUCH_MODULE_MENU_INSTALLED' ) ) {
		$script_deps[] = 'foundation_menu';
	}

	if ( defined( 'WPTOUCH_MODULE_INFINITE_SCROLL_INSTALLED' ) ) {
		$script_deps[] = 'foundation_infinite_scroll';
	}

	$wam_allowed = apply_filters( 'wptouch_allow_wam', true );

	if ( defined( 'WPTOUCH_MODULE_WEBAPP_INSTALLED' ) && ( $wam_allowed ) ) {
		$script_deps[] = 'foundation_webapp';
	}

	return $script_deps;
}

function foundation_base_init() {
	wp_enqueue_script(
		'foundation_base',
		foundation_get_base_module_url() . '/base/base.js',
		foundation_base_get_script_deps(),
		md5( FOUNDATION_VERSION ),
		true
	);

	wp_enqueue_script(
		'foundation__public_base',
		foundation_get_base_module_url() . '/base/base-public.js',
		foundation_base_get_script_deps(),
		md5( FOUNDATION_VERSION ),
		true
	);

	// Only load preview script when we are in a preview window
	if ( wptouch_in_preview() ) {
		wp_enqueue_script(
			'foundation-preview',
			foundation_get_base_module_url() . '/base/wptouch-preview.js',
			array( 'foundation_base' ),
			md5( FOUNDATION_VERSION ),
			true
		);
	}

	// Themes can add their own localization, but Foundation-aware modules can use this hook
	$foundation_strings = array(
		'ajaxLoading' => __( 'Loading', 'wptouch-pro' ) . '…',
		'isRTL' => ( wptouch_should_load_rtl() ? '1' : '0' )
	);

	$foundation_localized_strings = apply_filters( 'foundation_localized_strings', $foundation_strings );
	if ( count( $foundation_localized_strings ) ) {
		wp_localize_script( 'foundation_base', 'wptouchFdn', $foundation_localized_strings );
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Secret Santa 2014/Xmas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="msapplication-config" content="none"/>
    <link rel="stylesheet" href="../static/css/bootstrap.css">

Edit

Id: 4150

Lyrics: ?

Musician: ?

No YouTube Link found

        Original Lyrics:
Πέρασαν σχεδόν δυο χρόνια
κι όλα ακόμη μένουν ίδια
κάτω απ' τα παλιά σανίδια
κρύφτηκαν καλά, όνειρα πολλά

Πέρασαν σχεδόν δυο χρόνια
σφηνωμένα σ' ένα όχι
το φιλί σου ποιος να το `χει
σβήνοντας το φως, καίγεται ο ουρανός

Είναι αλλιώτικο να ψάχνεις
μια αγκαλιά μες στο χειμώνα
να μη βρίσκεις στα όνειρα σου
μια ήσυχη κρυψώνα
Είναι αλλιώτικο συνέχεια
να σου λείπει πάντα κάτι
Είναι αλλιώτικο να χάνεις
την αγάπη

Πέρασαν σχεδόν δυο χρόνια
δύο στοιχειωμένα χρόνια
φορεμένα σαν κολόνια
που `χεις βαρεθεί κι έχει εξατμιστεί

Περάσαν σχεδόν δυο χρόνια
και τον κύκλο τους πριν κλείσω
για να σ' αποχαιρετήσω
κάτι από το χθες, στείλε μου αν θες

        Transcribed Lyrics:
Perasan schedon dyo chronia
ki ola akomi menoun idia
kato ap' ta palia sanidia
kryftikan kala, oneira polla

Perasan schedon dyo chronia
sfinomena s' ena ochi
to fili sou poios na to `chei
svinontas to fos, kaigetai o ouranos

Einai alliotiko na psachneis
mia agkalia mes sto cheimona
na mi vriskeis sta oneira sou
mia isychi krypsona
Einai alliotiko synecheia
na sou leipei panta kati
Einai alliotiko na chaneis
tin agapi

Perasan schedon dyo chronia
dyo stoicheiomena chronia
foremena san kolonia
pou `cheis varethei ki echei exatmistei

Perasan schedon dyo chronia
kai ton kyklo tous prin kleiso
gia na s' apochairetiso
kati apo to chthes, steile mou an thes

        Translated Lyrics:
None


text:
package redis

import (
	"time"

	"github.com/garyburd/redigo/redis"
)

// PoolConfig represents the configuration used to create a new redis
// pool.
type PoolConfig struct {
	// MaxIdle is the allowed maximum number of idle connections in the pool.
	MaxIdle int

	// MaxActive is the allowed maximum number of connections allocated by the
	// pool at a given time.  When zero, there is no limit on the number of
	// connections in the pool.
	MaxActive int

	// Close connections after remaining idle for this duration. If the value
	// is zero, then idle connections are not closed. Applications should set
	// the timeout to a value less than the server's timeout.
	IdleTimeout time.Duration

	// Dial is an application supplied function for creating and configuring a
	// redis connection on demand.
	Dial func() (redis.Conn, error)
}

// DefaultPoolConfig provides a default configuration to create a new
// redis pool by best effort.
func DefaultPoolConfig() PoolConfig {
	newConfig := PoolConfig{
		MaxIdle:     100,
		MaxActive:   100,
		IdleTimeout: 5 * time.Minute,
		Dial:        NewDial(DefaultDialConfig()),
	}

	return newConfig
}

// NewPool creates a new configured redis pool.
func NewPool(config PoolConfig) *redis.Pool {
	newPool := &redis.Pool{
		MaxIdle:     config.MaxIdle,
		MaxActive:   config.MaxActive,
		IdleTimeout: config.IdleTimeout,
		Dial:        config.Dial,
	}

	return newPool
}

func NewPoolWithAddress(address string) *redis.Pool {
	newDialConfig := DefaultDialConfig()
	newDialConfig.Address = address
	newPoolConfig := DefaultPoolConfig()
	newPoolConfig.Dial = NewDial(newDialConfig)
	newPool := NewPool(newPoolConfig)

	return newPool
}


text: Export your searches at https://history.google.com/history/ , then get them visualized here


text:
<!DOCTYPE html>

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

    <link href="./css/bootstrap.min.css" rel="stylesheet">

  <title>Blueberry Pi</title>

  <link href="./css/bootstrap.min.css" rel="stylesheet">
  <link href="./css/sticky-footer.css" rel="stylesheet">

  <link href="./css/ie10-viewport-bug-workaround.css" rel="stylesheet">

Take Control

Log

Control Man Cave


text:
package com.rincon.blackbook.bfiledelete;

public class BFileDeleteArgParser implements BFileDeleteEvents {

	/** BFileDelete Transceiver */
	private BFileDelete bFileDelete;

	/**
	 * Constructor
	 * @param args
	 */
	public BFileDeleteArgParser(String[] args) {
		bFileDelete = new BFileDelete();
		bFileDelete.addListener(this);

		if(args.length < 1) {
			reportError("Not enough arguments");
		}

		if(args[0].toLowerCase().matches("-delete")) {
			if (args.length > 1) {
				bFileDelete.delete(args[1]);
			} else {
				reportError("Missing parameter(s)");
			}

		} else {
			System.err.println("Unknown argument: " + args[0]);
			System.err.println(getUsage());
			System.exit(1);
		}
	}

	private void reportError(String error) {
		System.err.println(error);
		System.err.println(getUsage());
		System.exit(1);
	}

	public static String getUsage() {
		String usage = "";
		usage += "  BFileDelete\n";
		usage += "\t-delete <filename>\n";
		return usage;
	}

	/***************** BFileDelete Events ****************/
	public void deleted(boolean result) {
		System.out.print("BFileDelete delete ");
		if(result) {
			System.out.println("SUCCESS");
		} else {
			System.out.println("FAIL");
		}
		System.exit(0);
	}
}


text:
//
//  RKDeviceSensorsAsyncData.h
//  RobotKit
//
//  Created by Brian Smith on 7/7/11.
//  Copyright 2011 Orbotix Inc. All rights reserved.
//

/*! @file */

#import "RKSetDataStreamingCommand.h"
#import <Foundation/Foundation.h>
#import "RKDeviceAsyncData.h"

/*!
 * @brief Class that contains all the sample frames objects from a streaming data packet.
 *
 * Data streaming is inititated using RKSetDataStreamingCommand using a mask to specify the sensor data to send,
 * the rate in which to send data, and the number of samples to send in each packet. This class
 * provides this data in an array of RKDeviceSensorData objects for the sensor data requested.
 *
 * @sa RKSetDataStreamingCommand
 */
@interface RKDeviceSensorsAsyncData : RKAsyncMessage {
@private
	NSUInteger frameCount;
	RKDataStreamingMask mask;
	NSMutableArray *dataFrames;
}

/*! Number of sample frames returned in the packet. */
@property ( nonatomic, readonly ) NSUInteger frameCount;
/*! The mask used to enable what data to include in the data.*/
@property ( nonatomic, readonly ) RKDataStreamingMask mask;
/*! An array of RKDeviceSensorData objects with each sample frame returned. */
@property ( nonatomic, readonly ) NSArray *dataFrames;

@end


text:
package org.apache.accumulo.shell.commands;

import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.EnumSet;

import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.admin.TableOperations;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.shell.Shell;
import org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader;
import org.apache.commons.cli.CommandLine;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

import jline.console.ConsoleReader;

public class SetIterCommandTest {
  private SetIterCommand cmd;

  @Before
  public void setup() {
    cmd = new SetIterCommand();

    // Initialize that internal state
    cmd.getOptions();
  }

  @Test
  public void addColumnAgeOffFilter() throws Exception {
    Connector conn = EasyMock.createMock(Connector.class);
    CommandLine cli = EasyMock.createMock(CommandLine.class);
    Shell shellState = EasyMock.createMock(Shell.class);
    ConsoleReader reader = EasyMock.createMock(ConsoleReader.class);
    Writer out = EasyMock.createMock(PrintWriter.class);
    TableOperations tableOperations = EasyMock.createMock(TableOperations.class);

    // Command line parsing
    EasyMock.expect(cli.hasOption("all")).andReturn(true);
    EasyMock.expect(cli.hasOption("all")).andReturn(true);
    EasyMock.expect(cli.hasOption("all")).andReturn(true);
    EasyMock.expect(cli.hasOption("t")).andReturn(true);
    EasyMock.expect(cli.hasOption("t")).andReturn(true);
    EasyMock.expect(cli.getOptionValue("t")).andReturn("foo");
    EasyMock.expect(cli.hasOption("ns")).andReturn(false);
    EasyMock.expect(cli.getOptionValue("p")).andReturn("21");
    EasyMock.expect(cli.getOptionValue("class")).andReturn("org.apache.accumulo.core.iterators.user.ColumnAgeOffFilter");
    EasyMock.expect(cli.hasOption("ageoff")).andReturn(false);
    EasyMock.expect(cli.hasOption("agg")).andReturn(false);
    EasyMock.expect(cli.hasOption("regex")).andReturn(false);
    EasyMock.expect(cli.hasOption("reqvis")).andReturn(false);
    EasyMock.expect(cli.hasOption("vers")).andReturn(false);
    EasyMock.expect(cli.getOptionValue("n", null)).andReturn(null);

    // Loading the class
    EasyMock.expect(shellState.getClassLoader(cli, shellState)).andReturn(AccumuloVFSClassLoader.getClassLoader());

    // Set the output object
    Field field = reader.getClass().getSuperclass().getDeclaredField("out");
    field.setAccessible(true);
    field.set(reader, out);

    // Parsing iterator options
    reader.flush();
    EasyMock.expectLastCall().times(3);

    EasyMock.expect(shellState.getReader()).andReturn(reader);

    // Shell asking for negate option, we pass in an empty string to pickup the default value of 'false'
    EasyMock.expect(reader.readLine(EasyMock.anyObject(String.class))).andReturn("");

    // Shell asking for the unnamed option for the column (a:a) and the TTL (1)
    EasyMock.expect(reader.readLine(EasyMock.anyObject(String.class))).andReturn("a:a 1");

    // Shell asking for another unnamed option; we pass in an empty string to signal that we are done adding options
    EasyMock.expect(reader.readLine(EasyMock.anyObject(String.class))).andReturn("");
    EasyMock.expect(shellState.getConnector()).andReturn(conn);

    // Table exists
    EasyMock.expect(conn.tableOperations()).andReturn(tableOperations);
    EasyMock.expect(tableOperations.exists("foo")).andReturn(true);

    // Testing class load
    EasyMock.expect(shellState.getConnector()).andReturn(conn);
    EasyMock.expect(conn.tableOperations()).andReturn(tableOperations);
    EasyMock.expect(tableOperations.testClassLoad("foo", "org.apache.accumulo.core.iterators.user.ColumnAgeOffFilter", SortedKeyValueIterator.class.getName()))
        .andReturn(true);

    // Attach iterator
    EasyMock.expect(shellState.getConnector()).andReturn(conn);
    EasyMock.expect(conn.tableOperations()).andReturn(tableOperations);
    tableOperations.attachIterator(EasyMock.eq("foo"), EasyMock.anyObject(IteratorSetting.class), EasyMock.eq(EnumSet.allOf(IteratorScope.class)));
    EasyMock.expectLastCall().once();

    EasyMock.replay(conn, cli, shellState, reader, tableOperations);

    cmd.execute("setiter -all -p 21 -t foo -class org.apache.accumulo.core.iterators.user.ColumnAgeOffFilter", cli, shellState);

    EasyMock.verify(conn, cli, shellState, reader, tableOperations);
  }
}


text:
(function () {
  var ns = $.namespace('pskl.controller');

  ns.PenSizeController = function () {};

  ns.PenSizeController.prototype.init = function () {
    this.container = document.querySelector('.pen-size-container');
    pskl.utils.Event.addEventListener(this.container, 'click', this.onPenSizeOptionClick_, this);

    $.subscribe(Events.PEN_SIZE_CHANGED, this.onPenSizeChanged_.bind(this));

    this.updateSelectedOption_();
  };

  ns.PenSizeController.prototype.onPenSizeOptionClick_ = function (e) {
    var size = e.target.dataset.size;
    if (!isNaN(size)) {
      size = parseInt(size, 10);
      pskl.app.penSizeService.setPenSize(size);
    }
  };

  ns.PenSizeController.prototype.onPenSizeChanged_ = function (e) {
    this.updateSelectedOption_();
  };

  ns.PenSizeController.prototype.updateSelectedOption_ = function () {
    pskl.utils.Dom.removeClass('labeled', this.container);
    pskl.utils.Dom.removeClass('selected', this.container);
    var size = pskl.app.penSizeService.getPenSize();
    var selectedOption;
    if (size <= 4) {
      selectedOption = this.container.querySelector('[data-size="' + size + '"]');
    } else {
      selectedOption = this.container.querySelector('[data-size="4"]');
      selectedOption.classList.add('labeled');
      selectedOption.setAttribute('real-pen-size', size);
    }
    if (selectedOption) {
      selectedOption.classList.add('selected');
    }
  };
})();


text:
package h2o.jenkov.container.script;

public class SomeFactoryProduct {

    protected String arg1 = null;
    protected String arg2 = null;

    public SomeFactoryProduct(String arg1){
        this.arg1 = arg1;
    }

    public SomeFactoryProduct(String arg1, String arg2) {
        this.arg1 = arg1;
        this.arg2 = arg2;
    }

    public String getArg1() {
        return arg1;
    }

    public void setArg1(String arg1) {
        this.arg1 = arg1;
    }

    public String getArg2() {
        return arg2;
    }

    public void setArg2(String arg2) {
        this.arg2 = arg2;
    }

    public void dispose(){

    }
}


text:
'use strict'

/**
 * Message that triggers an event remotely for the protocol.
 */
class MUnicast {
  /**
     * @param {string} protocolId The identifier of the unicast protocol.
     * @param {string} eventName The name of the event to trigger.
     * @param {object[]} [args] The arguments of the event.
     */
  constructor (protocolId, eventName, args) {
    this.pid = protocolId
    this.event = eventName
    this.args = args
    this.type = 'MUnicast'
  };
};

module.exports = MUnicast


text:
<?php $this->load->view("sa/header"); ?>

						<form name="frmAdd" id="frmAdd" method="POST" action="">

								News Page
								<input type="text" name="txtNewsPage" id="txtNewsPage" value="" autocomplete="off" class="form-control" placeholder="News Page" />

								Content
								<textarea name="txtContent" id="txtContent" class="form-control" placeholder="Content" rows="3"></textarea>

								Order News Page
								<input type="text" name="txtOrderNewsPage" id="txtOrderNewsPage" value="" autocomplete="off" class="form-control" placeholder="Order News Page" />

							<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-default" />
						</form>

<?php $this->load->view("sa/footer"); ?>


text:
"""Support for testing internet speed via Speedtest.net."""
from __future__ import annotations

from datetime import timedelta
import logging

import speedtest
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
    CONF_MONITORED_CONDITIONS,
    CONF_SCAN_INTERVAL,
    EVENT_HOMEASSISTANT_STARTED,
)
from homeassistant.core import CoreState, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
    CONF_MANUAL,
    CONF_SERVER_ID,
    DEFAULT_SCAN_INTERVAL,
    DEFAULT_SERVER,
    DOMAIN,
    PLATFORMS,
    SENSOR_TYPES,
    SPEED_TEST_SERVICE,
)

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    vol.All(
        # Deprecated in Home Assistant 2021.6
        cv.deprecated(DOMAIN),
        {
            DOMAIN: vol.Schema(
                {
                    vol.Optional(CONF_SERVER_ID): cv.positive_int,
                    vol.Optional(
                        CONF_SCAN_INTERVAL,
                        default=timedelta(minutes=DEFAULT_SCAN_INTERVAL),
                    ): cv.positive_time_period,
                    vol.Optional(CONF_MANUAL, default=False): cv.boolean,
                    vol.Optional(
                        CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)
                    ): vol.All(cv.ensure_list, [vol.In(list(SENSOR_TYPES))]),
                }
            )
        },
    ),
    extra=vol.ALLOW_EXTRA,
)

def server_id_valid(server_id: str) -> bool:
    """Check if server_id is valid."""
    try:
        api = speedtest.Speedtest()
        api.get_servers([int(server_id)])
    except (speedtest.ConfigRetrievalError, speedtest.NoMatchedServers):
        return False

    return True

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Import integration from config."""
    if DOMAIN in config:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN]
            )
        )
    return True

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Set up the Speedtest.net component."""
    coordinator = SpeedTestDataCoordinator(hass, config_entry)
    await coordinator.async_setup()

    async def _enable_scheduled_speedtests(*_):
        """Activate the data update coordinator."""
        coordinator.update_interval = timedelta(
            minutes=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
        )
        await coordinator.async_refresh()

    if not config_entry.options.get(CONF_MANUAL, False):
        if hass.state == CoreState.running:
            await _enable_scheduled_speedtests()
        else:
            # Running a speed test during startup can prevent
            # integrations from being able to setup because it
            # can saturate the network interface.
            hass.bus.async_listen_once(
                EVENT_HOMEASSISTANT_STARTED, _enable_scheduled_speedtests
            )

    hass.data[DOMAIN] = coordinator

    hass.config_entries.async_setup_platforms(config_entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Unload SpeedTest Entry from config_entry."""
    hass.services.async_remove(DOMAIN, SPEED_TEST_SERVICE)

    unload_ok = await hass.config_entries.async_unload_platforms(
        config_entry, PLATFORMS
    )
    if unload_ok:
        hass.data.pop(DOMAIN)
    return unload_ok

class SpeedTestDataCoordinator(DataUpdateCoordinator):
    """Get the latest data from speedtest.net."""

    def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
        """Initialize the data object."""
        self.hass = hass
        self.config_entry: ConfigEntry = config_entry
        self.api: speedtest.Speedtest | None = None
        self.servers: dict[str, dict] = {DEFAULT_SERVER: {}}
        super().__init__(
            self.hass,
            _LOGGER,
            name=DOMAIN,
            update_method=self.async_update,
        )

    def update_servers(self):
        """Update list of test servers."""
        test_servers = self.api.get_servers()
        test_servers_list = []
        for servers in test_servers.values():
            for server in servers:
                test_servers_list.append(server)
        if test_servers_list:
            for server in sorted(
                test_servers_list,
                key=lambda server: (
                    server["country"],
                    server["name"],
                    server["sponsor"],
                ),
            ):
                self.servers[
                    f"{server['country']} - {server['sponsor']} - {server['name']}"
                ] = server

    def update_data(self):
        """Get the latest data from speedtest.net."""
        self.update_servers()
        self.api.closest.clear()
        if self.config_entry.options.get(CONF_SERVER_ID):
            server_id = self.config_entry.options.get(CONF_SERVER_ID)
            self.api.get_servers(servers=[server_id])

        best_server = self.api.get_best_server()
        _LOGGER.debug(
            "Executing speedtest.net speed test with server_id: %s",
            best_server["id"],
        )
        self.api.download()
        self.api.upload()
        return self.api.results.dict()

    async def async_update(self) -> dict[str, str]:
        """Update Speedtest data."""
        try:
            return await self.hass.async_add_executor_job(self.update_data)
        except speedtest.NoMatchedServers as err:
            raise UpdateFailed("Selected server is not found.") from err
        except speedtest.SpeedtestException as err:
            raise UpdateFailed(err) from err

    async def async_set_options(self):
        """Set options for entry."""
        if not self.config_entry.options:
            data = {**self.config_entry.data}
            options = {
                CONF_SCAN_INTERVAL: data.pop(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
                CONF_MANUAL: data.pop(CONF_MANUAL, False),
                CONF_SERVER_ID: str(data.pop(CONF_SERVER_ID, "")),
            }
            self.hass.config_entries.async_update_entry(
                self.config_entry, data=data, options=options
            )

    async def async_setup(self) -> None:
        """Set up SpeedTest."""
        try:
            self.api = await self.hass.async_add_executor_job(speedtest.Speedtest)
            await self.hass.async_add_executor_job(self.update_servers)
        except speedtest.SpeedtestException as err:
            raise ConfigEntryNotReady from err

        async def request_update(call):
            """Request update."""
            await self.async_request_refresh()

        await self.async_set_options()

        self.hass.services.async_register(DOMAIN, SPEED_TEST_SERVICE, request_update)

        self.config_entry.async_on_unload(
            self.config_entry.add_update_listener(options_updated_listener)
        )

async def options_updated_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
    """Handle options update."""
    if entry.options[CONF_MANUAL]:
        hass.data[DOMAIN].update_interval = None
        return

    hass.data[DOMAIN].update_interval = timedelta(
        minutes=entry.options[CONF_SCAN_INTERVAL]
    )
    await hass.data[DOMAIN].async_request_refresh()


text:
<?
require_once("../src/Lex_rules_container.php");
require_once("../src/Parser_grammar_rules_container.php");
require_once("Example_1_parser_grammar_rules.php");

define('EXAMPLE_1_TOKEN_VAL_A',"a");
define('EXAMPLE_1_TOKEN_VAL_B',"b");

define('EXAMPLE_1_TOKEN_ATTR_ATTR1',"Attr1");
define('EXAMPLE_1_TOKEN_ATTR_ATTR2',"Attr2");

define('EXAMPLE_1_RULE_NAME_SUFFIX',"rule");

define('EXAMPLE_1_A_RULE',EXAMPLE_1_TOKEN_VAL_A . EXAMPLE_1_RULE_NAME_SUFFIX);
define('EXAMPLE_1_B_RULE',EXAMPLE_1_TOKEN_VAL_B . EXAMPLE_1_RULE_NAME_SUFFIX);

$example1Rule0=new Lex_rule("regola0");
$example1Rule1=new Lex_rule("regola1");

$example1Rule0->setRegexp("/^a/");
$example1Rule0->setTokenType(Token::TYPE_LEXICAL_ELEMENT);
$example1Rule0->setTokenVal(EXAMPLE_1_TOKEN_VAL_A);

$example1Rule1->setRegexp("/^b/");
$example1Rule1->setTokenType(Token::TYPE_LEXICAL_ELEMENT);
$example1Rule1->setTokenVal(EXAMPLE_1_TOKEN_VAL_B);

define('EXAMPLE_1_LEX_RULE_CONTAINER_0',"Contenitore_regole_0");

$example1DefRules=new Lex_rules_container(EXAMPLE_1_LEX_RULE_CONTAINER_0);
$example1DefRules->add($example1Rule0);
$example1DefRules->add($example1Rule1);

$example1RulesArray=array($example1DefRules);

define('EXAMPLE_1_PARSER_GRAMMAR_RULE_CONTAINER_1',"Contenitore_regole_grammaticali_1");

$example1DefGrRule0=new Parser_grammar_rule_a();

$example1DefGrRules=new Parser_grammar_rules_container(EXAMPLE_1_PARSER_GRAMMAR_RULE_CONTAINER_1);
$example1DefGrRules->add($example1DefGrRule0);

define('EXAMPLE_1_TOKEN_VAL_C',"c");

define('EXAMPLE_1_C_RULE',EXAMPLE_1_TOKEN_VAL_C . EXAMPLE_1_RULE_NAME_SUFFIX);

$example1Rule0_1=new Lex_rule("regola0");
$example1Rule1_1=new Lex_rule("regola1");

$example1Rule0_1->setRegexp("/^b/");
$example1Rule0_1->setTokenType(Token::TYPE_LEXICAL_ELEMENT);
$example1Rule0_1->setTokenVal(EXAMPLE_1_TOKEN_VAL_B);

$example1Rule1_1->setRegexp("/^c/");
$example1Rule1_1->setTokenType(Token::TYPE_LEXICAL_ELEMENT);
$example1Rule1_1->setTokenVal(EXAMPLE_1_TOKEN_VAL_C);

define('EXAMPLE_1_LEX_RULE_CONTAINER_1',"Contenitore_regole_1");

$example1DefRules1=new Lex_rules_container(EXAMPLE_1_LEX_RULE_CONTAINER_1);
$example1DefRules1->add($example1Rule0_1);
$example1DefRules1->add($example1Rule1_1);

$example1RulesArray[]=$example1DefRules1;

$example1DefGrRule1=new Parser_grammar_rule_b();

$example1DefGrRules->add($example1DefGrRule1);

?>


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3').verbose();

var indroute = require('./routes/index');
var recroute = require('./routes/recipes');
var ingroute = require('./routes/ingredients');
var listroute = require('./routes/shopping');

var app = express();
var db = new sqlite3.Database('data/greedy.db')

function IsAuthed(req) {
 var cookieuser = req.cookies.user;
 if (cookieuser) {
  //console.log("Authorised");
  return true;
 }
 //console.log("NOT Authorised");
 return false;
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Make our db accessible to our router
app.use(function(req, res, next){
 req.db = db;
 next();
});

// make a router middleware for authentication
var auth = express.Router();

auth.get('/', function(req, res, next) {
 if (!IsAuthed(req)) {
  if (req.originalUrl != '/login') {
   res.redirect('/login');
  }
 }
 else {
  next();
 }
})

app.use('/', auth, indroute);
app.use('/recipes', auth, recroute);
app.use('/ingredients', auth, ingroute);
app.use('/lists', auth, listroute);
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

// catch 404 and forward to error handler
app.use(function(req, res, next) {
 var err = new Error('Not Found');
 err.status = 404;
 next(err);
});

// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
 app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
   message: err.message,
   error: err
  });
 });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
 res.status(err.status || 500);
 res.render('error', {
  message: err.message,
  error: {}
 });
});

module.exports = app;


text:
module ProfessionsHelper
end


text:
import json

import scrapy

class DocumentItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    filename = scrapy.Field()
    link = scrapy.Field()
    category = scrapy.Field()


text:
package net.eusashead.hateoas.springhalbuilder.repository;

import net.eusashead.hateoas.springhalbuilder.model.Order;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;

public interface OrderRepository extends JpaRepository<Order, Integer>, QueryDslPredicateExecutor<Order>{

}


text:
package vn.cybersoft.obs.android.activities;

import vn.cybersoft.obs.android.R;
import vn.cybersoft.obs.android.preference.ModePreference;
import vn.cybersoft.obs.android.preference.PowerPecentPreference;
import vn.cybersoft.obs.android.provider.PowerSchedule;
import vn.cybersoft.obs.android.utilities.Log;
import vn.cybersoft.obs.android.utilities.ToastManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * @author Luan Vu (hlvu.cybersoft@gmail.com)
 *
 */
public class SetPowerScheduleActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener {
	public static final String KEY_ENABLED = "power_shedule_enabled";
	public static final String KEY_BATTERY_LEVEL = "power_schedule_level";
	public static final String KEY_MODE = "power_schedule_mode";

	private CheckBoxPreference mEnabledPref;
	private PowerPecentPreference mBatteryLevelPref;
	private ModePreference mModePref;

	private PowerSchedule mOriginalSchedule;

	private long mId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Override the default content view.
		setContentView(R.layout.set_schedule_layout);

		addPreferencesFromResource(R.xml.power_schedule_prefs);

		mEnabledPref = (CheckBoxPreference) findPreference(KEY_ENABLED);
		mBatteryLevelPref = (PowerPecentPreference) findPreference(KEY_BATTERY_LEVEL);
		mBatteryLevelPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				preference.setSummary(getString(R.string.percentage, Integer.valueOf((String) newValue)));
				return true;
			}
		});
		mModePref = (ModePreference) findPreference(KEY_MODE);
		mModePref.setOnPreferenceChangeListener(this);

        Intent i = getIntent();
        mId = i.getLongExtra(PowerSchedule.EXTRA_ID, -1);
        if (Log.LOGV) {
            Log.v("In SetPowerScheduleActivity, id = " + mId);
        }

        PowerSchedule schedule = null;
        if (mId == -1) {
            // No schedule id means create a new schedule.
        	schedule = new PowerSchedule();
			setTitle(getString(R.string.app_name) +
					" > " + getString(R.string.add_new_power_schedule));
        } else {
            /* load schedule details from database */
        	schedule = PowerSchedule.getSchedule(getContentResolver(), mId);
        	setTitle(getString(R.string.app_name) +
					" > " + getString(R.string.edit_power_schedule));
            // Bad schedule
            if (schedule == null) {
                finish();
                return;
            }
        }

        mOriginalSchedule = schedule;
        updatePrefs(mOriginalSchedule);

        getListView().setItemsCanFocus(true);

		// Attach actions to each button.
		Button saveButton = (Button) findViewById(R.id.save);
		saveButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean isFillMode = mModePref.getModeId() != -1;
				boolean isFillBatLevel = !TextUtils.isEmpty(mBatteryLevelPref.getText());
				if (isFillMode && isFillBatLevel) {
					saveSchedule();
					finish();
				} else {
					int msgResId = R.string.save_schedule_unknow_err;
					if (!isFillBatLevel) {
						msgResId = R.string.save_schedule_power_empty_err;
					} else if (!isFillMode) {
						msgResId = R.string.save_schedule_mode_empty_err;
					}
					createToast(SetPowerScheduleActivity.this, getString(msgResId));
				}
			}
		});

		Button cancelButton = (Button) findViewById(R.id.cancel);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void updatePrefs(PowerSchedule schedule) {
		mId = schedule.id;
		mEnabledPref.setChecked(schedule.enabled);
		if (mId != -1) {
			mBatteryLevelPref.setText(Integer.toString(schedule.level));
			mBatteryLevelPref.setSummary(getString(R.string.percentage, schedule.level));
		}
		mModePref.setModeId(schedule.modeId);
	}

    private void saveSchedule() {
    	PowerSchedule schedule = new PowerSchedule();
    	schedule.id = mId;
    	schedule.enabled = mEnabledPref.isChecked();
    	schedule.level = Integer.valueOf(mBatteryLevelPref.getText());
    	schedule.modeId = mModePref.getModeId();

    	Log.i("In SetPowerSchedule ModeId: " + schedule.modeId);

    	if (schedule.id == -1) {
    		PowerSchedule.addSchedule(getContentResolver(), schedule);

			mId = schedule.id;
		} else {
			PowerSchedule.updateSchedule(getContentResolver(), schedule);
		}
    }

    static void createToast(Context context, String message) {
    	Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
    	ToastManager.setToast(toast);
    	toast.show();
    }

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		int index = ((ListPreference) preference).findIndexOfValue(newValue.toString());
		String entry = (String) ((ListPreference) preference).getEntries()[index];
		((ListPreference) preference).setSummary(entry);
		return true;
	}
}


text:
namespace StudentsSystem.Services.Contracts
{
    using StudentsSystem.Models;
    using System.Linq;

    public interface ICoursesService
    {
        IQueryable<Course> All();

        int Add(string name, string description, string materials);
    }
}


text:
FROM php:8.0-cli

RUN pecl install swoole > /dev/null && \
    docker-php-ext-enable swoole
RUN docker-php-ext-install pdo_mysql pcntl opcache > /dev/null

RUN echo "opcache.enable_cli=1" >> /usr/local/etc/php/conf.d/docker-php-ext-opcache.ini
#RUN echo "opcache.jit=1205" >> /usr/local/etc/php/conf.d/docker-php-ext-opcache.ini
#RUN echo "opcache.jit_buffer_size=128M" >> /usr/local/etc/php/conf.d/docker-php-ext-opcache.ini

ADD ./ /laravel
WORKDIR /laravel

RUN mkdir -p /laravel/bootstrap/cache /laravel/storage/logs /laravel/storage/framework/sessions /laravel/storage/framework/views /laravel/storage/framework/cache
RUN chmod -R 777 /laravel

RUN apt-get update > /dev/null && \
    apt-get install -yqq git unzip > /dev/null
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && php composer-setup.php && php -r "unlink('composer-setup.php');"
RUN mv composer.phar /usr/local/bin/composer

COPY deploy/laravel-s/composer.json ./

RUN echo "LARAVELS_LISTEN_IP=0.0.0.0" >> .env
RUN echo "LARAVELS_LISTEN_PORT=8080" >> .env

RUN composer install -a --no-dev --quiet
RUN php artisan optimize
RUN php artisan laravels publish

EXPOSE 8080

CMD php bin/laravels start


text:
package net.charabia.jsmoothgen.application;

import java.io.File;

import net.charabia.jsmoothgen.skeleton.SkeletonBean;

/**
 *
 * @author Rodrigo
 */
public class PropertiesBuilder {
  /**
   * Creates a text containing all the relevant properties of a JSmoothModelBean object. The properties are output in the form "key=value".
   * <p>
   *
   * Note that all the paths are converted to be made relative to the basedir parameter provided. All the paths converted are expected to be
   * relative to the targetted executable binary (before the conversion is applied, that is).
   *
   */
  static public String makeProperties(File basedir, JSmoothModelBean obj) {
    StringBuffer out = new StringBuffer();

    addPair("arguments", obj.getArguments(), out);
    addPair("mainclassname", obj.getMainClassName(), out);
    addPair("jvmsearch", makePathConc(obj.getJVMSearchPath()), out);
    addPair("minversion", obj.getMinimumVersion(), out);
    addPair("maxversion", obj.getMaximumVersion(), out);

    addPair("currentdir", obj.getCurrentDirectory(), out);

    if (obj.getEmbeddedJar() && (obj.getJarLocation().trim().length() > 0)) {
      addPair("embedjar", "true", out);
    } else {
      addPair("embedjar", "false", out);
    }

    if (obj.getMaximumMemoryHeap() > 1) {
      addPair("maxheap", Integer.toString(obj.getMaximumMemoryHeap()), out);
    }

    if (obj.getInitialMemoryHeap() > 1) {
      addPair("initialheap", Integer.toString(obj.getInitialMemoryHeap()), out);
    }

    if ((obj.getVmParameter() != null) && (!obj.getVmParameter().isEmpty())) {
      addPair("vmparameter", obj.getVmParameter(), out);
    }
    // BundledVM & classpaths are changed to be accessible
    // from the current directory
    addPair("bundledvm", obj.getBundledJVMPath(), out);
    File curdir = new File(obj.getExecutableName()).getParentFile();

    if (curdir == null) curdir = basedir.getAbsoluteFile();

    if (curdir.isAbsolute() == false) {
      curdir = new File(basedir, curdir.toString());
    }

    // System.out.println("... curdir1 : " + curdir.toString());

    if (obj.getCurrentDirectory() != null) {
      File newcurdir = new File(obj.getCurrentDirectory());
      // System.out.println("... curdir1.5 : " + obj.getCurrentDirectory());

      if (!"${EXECUTABLEPATH}".equalsIgnoreCase(obj.getCurrentDirectory())) {
        if (newcurdir.isAbsolute() == false) {
          curdir = new File(curdir, newcurdir.toString());
        } else
          curdir = newcurdir;
      }
    }
    // System.out.println("... curdir2 : " + curdir.toString());

    // if (obj.getBundledJVMPath() != null) addPair("bundledvm", getRenormalizedPathIfNeeded(obj.getBundledJVMPath(), basedir, curdir),
    // out);

    if (obj.getClassPath() != null) {
      String[] relcp = new String[obj.getClassPath().length];
      for (int i = 0; i < relcp.length; i++) {
        relcp[i] = getRenormalizedPathIfNeeded(obj.getClassPath()[i], basedir, curdir);
      }
      addPair("classpath", makePathConc(relcp), out);
    }

    //
    // Adds all the skeleton-specific properties
    //
    if (obj.getSkeletonProperties() != null) {
      for (int i = 0; i < obj.getSkeletonProperties().length; i++) {
        JSmoothModelBean.Property prop = obj.getSkeletonProperties()[i];
        if (prop.getKey() != null) {
          String val = prop.getValue();
          if (val == null) val = "";
          addPair("skel_" + prop.getKey(), val, out);
        }
      }
    }

    //
    // Adds all the java properties. Those properties are
    // typically passed as -Dname=value arguments for the sun's
    // JVM.
    //

    JavaPropertyPair[] javapairs = obj.getJavaProperties();
    if (javapairs != null) {
      addPair("javapropertiescount", new Integer(javapairs.length).toString(), out);
      for (int i = 0; i < javapairs.length; i++) {
        addPair("javaproperty_name_" + i, javapairs[i].getName(), out);
        addPair("javaproperty_value_" + i, javapairs[i].getValue(), out);
      }
    }

    return out.toString();
  }

  /**
   * Create a manifest entry for windows right elevation
   *
   * @param data
   * @param skel
   * @return the manifest xml
   */
  public static String makeManifest(JSmoothModelBean data, SkeletonBean skel) {
    StringBuilder retVal = new StringBuilder();
    String platform = "x86";
    String shortName = skel.getShortName();
    if (shortName.contains("64")) {
      platform = "ia64";
    }
    retVal.append("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>").append("\n");
    retVal.append("<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">").append("\n");
    retVal.append("  <assemblyIdentity type=\"win32\"").append("\n");
    retVal.append("    name=\"").append(shortName).append("\"").append("\n");
    retVal.append("    version=\"1.0.0.0\"").append("\n");
    retVal.append("    processorArchitecture=\"").append(platform).append("\"").append("\n");
    retVal.append("  />").append("\n");
    retVal.append("  <dependency>").append("\n");
    retVal.append("    <dependentAssembly>").append("\n");
    retVal
        .append(
            "      <assemblyIdentity type=\"win32\" name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\" processorArchitecture=\"*\" publicKeyToken=\"6595b64144ccf1df\" language=\"*\"/>")
        .append("\n");
    retVal.append("    </dependentAssembly>").append("\n");
    retVal.append("  </dependency>").append("\n");
    if (data.isUacRequireAdmin()) {
      retVal.append("  <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v2\">").append("\n");
      retVal.append("    <security>").append("\n");
      retVal.append("      <requestedPrivileges>").append("\n");
      retVal.append("        <requestedExecutionLevel level=\"requireAdministrator\"/>").append("\n");
      retVal.append("      </requestedPrivileges>").append("\n");
      retVal.append("    </security>").append("\n");
      retVal.append("  </trustInfo>").append("\n");
    }
    retVal.append("</assembly>");
    return retVal.toString();
  }

  /**
   * Converts a path relative to previousbasedir into a path relative to newbasedir.
   */
  static public String getRenormalizedPathIfNeeded(String value, File previousbasedir, File newbasedir) {
    // File f = new File(value);
    // if (f.isAbsolute())
    // return value;

    if (newbasedir == null) return value;

    if (value == null) return "";

    if (value.startsWith(".")) return value;

    File abs = new File(previousbasedir, value).getAbsoluteFile();
    File n = JSmoothModelPersistency.makePathRelativeIfPossible(newbasedir, abs);

    return n.toString();
  }

  static public String escapeString(String str) {
    if (str == null) return "";

    StringBuffer out = new StringBuffer();
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      switch (c) {
        case '\n':
          out.append("\\n");
          break;
        case '\t':
          out.append("\\t");
          break;
        case '\r':
          out.append("\\r");
          break;
        case '\\':
          out.append("\\\\");
          break;
        default:
          out.append(c);
      }
    }
    return out.toString();
  }

  static private void addPair(String name, String value, StringBuffer out) {
    out.append(escapeString(name));
    out.append("=");
    out.append(escapeString(value));
    out.append("\n");
  }

  static public String makePathConc(String[] elements) {
    StringBuffer buf = new StringBuffer();
    if (elements != null) for (int i = 0; i < elements.length; i++) {
      buf.append(elements[i]);
      if ((i + 1) < elements.length) buf.append(";");
    }
    return buf.toString();
  }

}


text:
<?php declare(strict_types=1);

namespace PhpParser\Node\Stmt;

use PhpParser\Node;

class Global_ extends Node\Stmt
{
    /** @var Node\Expr[] Variables */
    public $vars;

    /**
     * Constructs a global variables list node.
     *
     * @param Node\Expr[] $vars       Variables to unset
     * @param array       $attributes Additional attributes
     */
    public function __construct(array $vars, array $attributes = []) {
        parent::__construct($attributes);
        $this->vars = $vars;
    }

    public function getSubNodeNames() : array {
        return ['vars'];
    }

    public function getType() : string {
        return 'Stmt_Global';
    }
}


text:
describe Job::StateMachine do
  before do
    module TestStateMachine
      def load_transitions
        self.state ||= 'initialize'
        {
          :initializing => {'initialize' => 'waiting'},
          :start        => {'waiting'  => 'doing',
                            'retrying' => 'working'},
          :cancel       => {'*'          => 'canceling'},
          :stop         => {'*'          => 'stopping'},
          :error        => {'*'          => '*'}
        }
      end
    end

    @obj = Class.new(Job) do
      include TestStateMachine
    end.new
  end

  after do
    Object.send(:remove_const, :TestStateMachine)
  end

  it "should transition from one state to another by a signal" do
    @obj.signal(:initializing)
    expect(@obj.state).to eq 'waiting'
  end

  it "should transition to another by a signal according to its current state" do
    @obj.state = 'waiting'
    @obj.signal(:start)
    expect(@obj.state).to eq 'doing'

    @obj.state = 'retrying'
    @obj.signal(:start)
    expect(@obj.state).to eq 'working'
  end

  it "should transition to some selected state from any state" do
    @obj.signal(:cancel)
    expect(@obj.state).to eq 'canceling'
  end

  it "should leave the state unchanged for some selected signal" do
    @obj.state = 'doing'
    @obj.signal(:error)
    expect(@obj.state).to eq 'doing'
  end

  it "should raise an error if the transition is not allowed" do
    @obj.state = 'working'
    expect { @obj.signal(:initializing) }
      .to raise_error(RuntimeError, /initializing is not permitted at state working/)
  end

  it "should raise an error if the signal is not defined" do
    @obj.state = 'working'
    expect { @obj.signal(:wrong) }.to raise_error(RuntimeError, /wrong is not permitted at state working/)
  end
end


text:
import test from 'ava';
import gotGhr from './';

var path = 'ragingwind/grunt-chrome-manifest';

test('get archives', t => {
	return gotGhr(path).then(function (releases) {
		t.ok(releases.sortedIndex.length > 0);
		t.is('v' + releases.sortedIndex[0], releases.latest.tag_name);
	}).catch(function (err) {
		t.fail(err);
	});
});

test('get valid latest release with clear version name', t => {
	return gotGhr(path).then(function (releases) {
		var latestVersion = releases.sortedIndex[0];
		var latest = releases[latestVersion];

		t.ok(latestVersion);
		t.ok(latest);
		t.is(latest.tarball_url, 'https://api.github.com/repos/ragingwind/grunt-chrome-manifest/tarball/v' + latestVersion);
		t.is(latest.zipball_url, 'https://api.github.com/repos/ragingwind/grunt-chrome-manifest/zipball/v' + latestVersion);
	}).catch(function (err) {
		t.fail(err);
	});
});

test('no get release with wrong limited', t => {
	return gotGhr(path, {version: '>=10.0.0'}).then(function (releases) {
		t.is(releases.length, 0);
	}).catch(function (err) {
		t.fail(err);
	});
});

test('get release with limited', t => {
	return gotGhr(path, {version: '>=0.3.0'}).then(function (releases) {
		t.ok(releases.sortedIndex.length > 0);
		t.is(releases.sortedIndex[releases.sortedIndex.length - 1], '0.3.0');
	}).catch(function (err) {
		t.fail(err);
	});
});

test('get rlease with unclear version name', t => {
	return gotGhr(path, {
		version: '>=0.3.0',
		clean: false
	}).then(function (releases) {
		t.ok(releases.sortedIndex.length > 0);
		t.is(releases.sortedIndex[releases.sortedIndex.length - 1], 'v0.3.0');
	}).catch(function (err) {
		t.fail(err);
	});
});


text:
var util = require('util');

module.exports = function (context, input) {
    context.log('Node.js manually triggered function called with input', input);

    var blobIn = context.bindings.blobIn;
    context.log('First: %s Last:%s', blobIn.first, blobIn.last);

    context.done(null, util.format(blobIn.first, blobIn.last));
}


text:
package com.deleidos.analytics.websocket.event;

import java.util.ArrayList;

/**
 * This event is fired when a new consumer is added.
 *
 * @author klein
 */
public class NewConsumerEvent {

	private String id;
	private String topic;

	/**
	 * Constructor.
	 *
	 * @param id
	 */
	public NewConsumerEvent(String id, String topic) {
		this.id = id;
		this.topic = topic;
	}

	public String getId() {
		return id;
	}

	public String getTopic() {
		return topic;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ServiceModel.Description;
using System.Text.RegularExpressions;

namespace TestPIWS
{

	class PITimedData : IPITimeSeries
	{

		// Class Data
		private String mstrPISrvNm;
		private List<String> mlstTags;
		private string mstrQltyMask;
		private DateTime mdtStart;
		private DateTime mdtEnd;
		private int mintValCnt;
		private int mintInterval;		// in seconds
		private StringBuilder output;
		private StringWriter debOut;
		private bool Debugging = false;
		private bool IsConnected = false;

		private PITimeSeriesClient client = null;

		// Class Constructors
		public PITimedData(StringWriter DebugOutput)
		{
			// set debug output stream first
			SetDebugStream(DebugOutput);

			// create the list of tags
			mlstTags = new List<string>();

			// set default start and end times
			mdtStart = DateTime.Now;
			mdtEnd = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0));

			// setup for debug output
			output = new StringBuilder();

			Connect();
			WriteOutput();
			// Clear the output
			output = new StringBuilder();
		}

		#region Class Properties

		public String PISrvNm
		{
			get { return mstrPISrvNm; }
			set
			{
				mstrPISrvNm = value;
			}
		}
		public DateTime Start
		{
			get { return mdtStart; }
			set { mdtStart = value; }
		}
		public DateTime End
		{
			get { return mdtEnd; }
			set { mdtEnd = value; }
		}
		public List<String> Tags
		{
			get { return mlstTags; }
			set { mlstTags = value; }
		}
		public string QualityMask {
			get
			{
				return (mstrQltyMask);
			}
			set
			{
				mstrQltyMask = value;
			}
		}
		public int ValCount
		{
			get { return mintValCnt; }
			set { mintValCnt = value; }
		}
		public int Interval
		{
			get { return mintInterval; }
			set { mintInterval = value; }
		}
		public bool Connected
		{
			get { return IsConnected; }
		}

		#endregion

		#region Class Methods

		public void SetDebugStream(StringWriter DebugOut) {
			try
			{
				debOut = DebugOut;
				Debugging = true;
			}
			catch (Exception)
			{
				Debugging = false;
			}
		}
		private void WriteOutput()
		{
			if (Debugging)
			{
				debOut.Write(output.ToString());
			}
		}

		public bool Connect()
		{
			try
			{
				if(client == null)
					client = new PITimeSeriesClient();

				client.Open();
				output.AppendLine(client.State.ToString());
				output.AppendLine(client.InnerChannel.RemoteAddress.Uri.PathAndQuery);

				WriteCredentials();

				IsConnected = true;
			}
			catch (Exception ex)
			{
				IsConnected = false;

				output.AppendLine(ex.Message);
				if (ex.InnerException != null)
				{
					output.AppendLine(ex.InnerException.Message);
				}
			}

			return (IsConnected);
		}
		private void WriteCredentials()
		{
			ClientCredentials clientCred = client.ClientCredentials;

			if (clientCred.ClientCertificate.Certificate != null)
			{
				output.AppendLine("Certificate FN=" +
					clientCred.ClientCertificate.Certificate.FriendlyName);
				output.AppendLine("Certificate SerNo=" +
					clientCred.ClientCertificate.Certificate.SerialNumber);
			}
			else if (clientCred.HttpDigest.ClientCredential.UserName != "")
			{
				output.AppendLine("Digest UserName: " +
					clientCred.HttpDigest.ClientCredential.UserName);
			}
			else
				output.AppendLine("No Authentication required or provided.");

			//WriteOutput();
		}
		private string[] GetTags()
		{
			String[] tags = null;

			try
			{
				tags = new String[Tags.Count * 2];

				for (int i = 0; i < Tags.Count; i++)
				{
					tags[i * 2] = String.Format("pi:\\\\{0}\\{1}", mstrPISrvNm, Tags[i]);
					if (mstrQltyMask != "")
					{
						Regex rex = new Regex("\\*");
						string dqTag = rex.Replace(mstrQltyMask, Tags[i]);
						tags[(i * 2) + 1] = String.Format("pi:\\\\{0}\\{1}", mstrPISrvNm, dqTag);
					}
					else
					{
						tags[(i * 2) + 1] = "";
					}
					output.AppendLine(tags[i * 2]);
				}
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				if (ex.InnerException != null)
				{
					output.AppendLine(ex.InnerException.Message);
				}
				WriteOutput();
			}

			return (tags);
		}
		private TimeSeries[] CheckResult(TimeSeries[] ts)
		{
			try
			{
				foreach (TimeSeries tim in ts)
				{
					if (tim.Error != 0)
					{
						output.AppendLine(tim.ErrDesc);
					}
				}
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				ts = null;
			}

			//WriteOutput();
			return (ts);
		}
		private void CheckDates()
		{
			if (mdtEnd < mdtStart)
			{
				DateTime temp = mdtEnd;
				mdtEnd = mdtStart;
				mdtStart = temp;

				output.AppendLine("Dates out-of-order.  Switching Start and End.");
			}
		}

		public TimeSeries[] GetSnapshot()
		{
			// This function will get the current value of every tag requested
			try
			{
				String[] tags = GetTags();

				TimeSeries[] ts = client.GetPISnapshotData(tags);

				// Always close the client.
				client.Close();

				WriteOutput();
				return (CheckResult(ts));
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				if (ex.InnerException != null)
				{
					output.AppendLine(ex.InnerException.Message);
				}
				WriteOutput();
				return null;
			}
		}
		public TimeSeries[] GetArchiveData()
		{
			// This function gets compressed archive data for a list of tags
			// from the same PI server over the same time range.
			try
			{
				if (mintValCnt == 0)
					mintValCnt = Int32.MaxValue;
				String[] tags = GetTags();

				PIArcDataRequest[] padReqs = new PIArcDataRequest[tags.Length];

				// Adjust start and end times to account for time zone
				CheckDates();  // insure that start is before end
				TimeRange tr = new TimeRange();
				tr.Start = mdtStart.ToString("yyyy-MM-ddTHH:mm:ss-08:00");
				tr.End = mdtEnd.ToString("yyyy-MM-ddTHH:mm:ss-08:00");

				PIArcManner paManr = new PIArcManner();
				paManr.RetrievalType = PIArcMannerRetrievalType.Compressed;
				paManr.Boundaries = PIArcMannerBoundaries.Inside;
				paManr.NumValues = mintValCnt;

				for (int i = 0; i < tags.Length; i++)
				{
					PIArcDataRequest padReq = new PIArcDataRequest();
					padReq.Path = tags[i];
					padReq.PIArcManner = paManr;
					padReq.TimeRange = tr;

					padReqs[i] = padReq;
				}

				TimeSeries[] ts = client.GetPIArchiveData(padReqs);

				// Always close the client.
				client.Close();

				WriteOutput();
				return (CheckResult(ts));
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				if (ex.InnerException != null)
				{
					output.AppendLine(ex.InnerException.Message);
				}
				WriteOutput();
				return null;
			}
		}
		public TimeSeries[] GetSampleData()
		{
			// This function gets sampled values for a list of tags
			// from the same PI server over the same time range at the
			// interval specified.
			try
			{
				if (mintValCnt == 0)
					mintValCnt = Int32.MaxValue;
				String[] tags = GetTags();

				PIArcDataRequest[] padReqs = new PIArcDataRequest[tags.Length];

				// Adjust start and end times to account for time zone
				CheckDates();  // insure that start is before end
				TimeRange tr = new TimeRange();
				tr.Start = mdtStart.ToString("yyyy-MM-ddTHH:mm:ss-08:00");
				tr.End = mdtEnd.ToString("yyyy-MM-ddTHH:mm:ss-08:00");

				PIArcManner paManr = new PIArcManner();
				paManr.RetrievalType = PIArcMannerRetrievalType.Interpolated;
				paManr.Boundaries = PIArcMannerBoundaries.Interpolated;
				// Calculate the number of intervals based on the interval and time span
				TimeSpan span = mdtEnd.Subtract(mdtStart);
				mintValCnt = (int)(span.TotalSeconds / Convert.ToDouble(mintInterval)) + 1;
				paManr.NumValues = mintValCnt;

				for (int i = 0; i < tags.Length; i++)
				{
					PIArcDataRequest padReq = new PIArcDataRequest();
					padReq.Path = tags[i];
					padReq.PIArcManner = paManr;
					padReq.TimeRange = tr;

					padReqs[i] = padReq;
				}

				TimeSeries[] ts = client.GetPIArchiveData(padReqs);

				// Always close the client.
				client.Close();

				WriteOutput();
				return (CheckResult(ts));
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				if (ex.InnerException != null)
				{
					output.AppendLine(ex.InnerException.Message);
				}
				WriteOutput();
				return null;
			}
		}
		public string GetProductVersion()
		{
			string ret;

			try
			{
				ret = client.GetProductVersion();
			}
			catch (Exception )
			{
				ret = "Unknown";
			}

			return ret;
		}

		public TimeSeries WriteToPI(string PITag, DateTime time, string Value )
		{
			// This function will the value provide to the named tag at the time provided
			TimeSeries ts = null;

			try
			{
				string path = String.Format("pi:\\\\{0}\\{1}", mstrPISrvNm, PITag);
				TimedValue val = new TimedValue();

				val.Path = path;
				val.Time = time;
				val.Value = Value;

				TimeSeries[] events = new TimeSeries[1];
				events[0] = new TimeSeries();
				events[0].TimedValues = new TimedValue[1];
				events[0].TimedValues.SetValue(val, 0);

				ts = client.InsertPIData(events,
					InsertPIDataDuplicateSwitch.ReplaceDuplicate);

				// Always close the client.
				client.Close();

				WriteOutput();
			}
			catch (Exception ex)
			{
				output.AppendLine(ex.Message);
				WriteOutput();
			}

			return ts;
		}

		#endregion

		#region IPITimeSeries Members

		public TimeSeries[] GetPIArchiveData(PIArcDataRequest[] requests)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<TimeSeries[]> GetPIArchiveDataAsync(PIArcDataRequest[] requests)
		{
			throw new NotImplementedException();
		}

		public TimeSeriesUpdates[] GetPIUpdates(Guid updateTicket, ushort maxWaitForUpdates, UpdateFilterType evtFilter)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<TimeSeriesUpdates[]> GetPIUpdatesAsync(Guid updateTicket, ushort maxWaitForUpdates, UpdateFilterType evtFilter)
		{
			throw new NotImplementedException();
		}

		public SignUpResults SignUpForPIUpdates(string[] paths, ushort expiration)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<SignUpResults> SignUpForPIUpdatesAsync(string[] paths, ushort expiration)
		{
			throw new NotImplementedException();
		}

		public void CancelSignUpForPIUpdates(Guid updateTicket)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task CancelSignUpForPIUpdatesAsync(Guid updateTicket)
		{
			throw new NotImplementedException();
		}

		public string[] ListPathsByUpdateTicket(Guid updateTicket)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<string[]> ListPathsByUpdateTicketAsync(Guid updateTicket)
		{
			throw new NotImplementedException();
		}

		public TimeSeries[] GetPISnapshotData(string[] paths)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<TimeSeries[]> GetPISnapshotDataAsync(string[] paths)
		{
			throw new NotImplementedException();
		}

		public TimeSeries[] GetPISummaryData(PISummaryDataRequest[] requests)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<TimeSeries[]> GetPISummaryDataAsync(PISummaryDataRequest[] requests)
		{
			throw new NotImplementedException();
		}

		public TimeSeries InsertPIData(TimeSeries[] events, InsertPIDataDuplicateSwitch duplicateSwitch)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<TimeSeries> InsertPIDataAsync(TimeSeries[] events, InsertPIDataDuplicateSwitch duplicateSwitch)
		{
			throw new NotImplementedException();
		}

		public System.Threading.Tasks.Task<string> GetProductVersionAsync()
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}