text:
<?php

// Initiate the autoloader. The file should be generated by Composer.
// You will provide your own autoloader or require the files directly if you did
// not install via Composer.
require_once __DIR__ . '/../vendor/autoload.php';

// Register API keys at https://www.google.com/recaptcha/admin
$siteKey = '';
$secret = '';

// reCAPTCHA supported 40+ languages listed here: https://developers.google.com/recaptcha/docs/language
$lang = 'en';
?>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>reCAPTCHA Example</title>
        <link rel="shortcut icon" href="//www.gstatic.com/recaptcha/admin/favicon.ico" type="image/x-icon"/>

reCAPTCHA Example

        <?php if ($siteKey === '' || $secret === ''): ?>

Add your keys

If you do not have keys already then visit <tt>

                https://www.google.com/recaptcha/admin</tt> to generate them.
        Edit this file and set the respective keys in <tt>$siteKey</tt> and
        <tt>$secret</tt>. Reload the page after this.

    <?php
elseif (isset($_POST['g-recaptcha-response'])):
    // The POST data here is unfiltered because this is an example.
    // In production, *always* sanitise and validate your input'
    ?>

<tt>POST</tt> data

    <tt>
<?php var_export($_POST); ?>
</tt>
    <?php
// If the form submission includes the "g-captcha-response" field
// Create an instance of the service using your secret
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);

// If file_get_contents() is locked down on your PHP installation to disallow
// its use with URLs, then you can use the alternative request method instead.
// This makes use of fsockopen() instead.
//  $recaptcha = new \ReCaptcha\ReCaptcha($secret, new \ReCaptcha\RequestMethod\SocketPost());

// Make the call to verify the response and also pass the user's IP address
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

    if ($resp->isSuccess()):
// If the response is a success, that's it!
        ?>

Success!

That's it. Everything is working. Go integrate this into your real project.

Try again

        <?php
    else:
// If it's not successful, then one or more error codes will be returned.
        ?>

Something went wrong

The following error was returned: <?php
            foreach ($resp->getErrorCodes() as $code) {
                echo '<tt>' , $code , '</tt> ';
            }
            ?>

Check the error code reference at <tt>https://developers.google.com/recaptcha/docs/verify#error-code-reference</tt>.

Note: Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.

Try again

    <?php
    endif;
else:
// Add the g-recaptcha tag to the form you want to include the reCAPTCHA element
    ?>

Complete the reCAPTCHA then submit the form.

    <form action="/" method="post">
        <fieldset>
            <legend>An example form</legend>

Example input A: <input type="text" name="ex-a" value="foo">

Example input B: <input type="text" name="ex-b" value="bar">

            <div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>">

<input type="submit" value="Submit" />

        </fieldset>
    </form>
<?php endif; ?>


text:
using Bridge;
using Cons = System.Console;

namespace TestProject1
{
    public class AliasUsing
    {
        public AliasUsing()
        {
            Cons.WriteLine("Test");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
public class JavaClass {
    public static void main(String[] args) {
        Main.Companion.plus(42, "11");
    }
}


text:
package com.ericsson.eiffel.semantics.events;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Issuer {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("group")
    @Expose
    private String group;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ aem-sling-contrib
  ~ https://github.com/dherges/aem-sling-contrib
  ~
  ~ Copyright (c) 2016 David Herges
  ~ Licensed under the MIT license.
  -->

<node>
    <!-- @see https://sling.apache.org/documentation/bundles/content-loading-jcr-contentloader.html#xml-descriptor-files -->

    <name>devserver</name>
    <primaryNodeType>nt:unstructured</primaryNodeType>

    <property>
        <name>sling:resourceType</name>
        <value>vue/components/page/page_devserver</value>
        <type>String</type>
    </property>

</node>


text:
package org.elasticsearch.action.search.type;

import com.carrotsearch.hppc.IntArrayList;
import org.apache.lucene.search.ScoreDoc;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.NoShardAvailableActionException;
import org.elasticsearch.action.search.ReduceSearchPhaseException;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.ShardSearchFailure;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.TransportAction;
import org.elasticsearch.action.support.TransportActions;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceListener;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.fetch.ShardFetchSearchRequest;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchTransportRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.search.query.QuerySearchResultProvider;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import static org.elasticsearch.action.search.type.TransportSearchHelper.internalSearchRequest;

/**
 *
 */
public abstract class TransportSearchTypeAction extends TransportAction<SearchRequest, SearchResponse> {

    protected final ClusterService clusterService;

    protected final SearchServiceTransportAction searchService;

    protected final SearchPhaseController searchPhaseController;

    public TransportSearchTypeAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
                                     SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) {
        super(settings, SearchAction.NAME, threadPool, actionFilters);
        this.clusterService = clusterService;
        this.searchService = searchService;
        this.searchPhaseController = searchPhaseController;
    }

    protected abstract class BaseAsyncAction<FirstResult extends SearchPhaseResult> extends AbstractAsyncAction {

        protected final ActionListener<SearchResponse> listener;

        protected final GroupShardsIterator shardsIts;

        protected final SearchRequest request;

        protected final ClusterState clusterState;
        protected final DiscoveryNodes nodes;

        protected final int expectedSuccessfulOps;
        private final int expectedTotalOps;

        protected final AtomicInteger successfulOps = new AtomicInteger();
        private final AtomicInteger totalOps = new AtomicInteger();

        protected final AtomicArray<FirstResult> firstResults;
        private volatile AtomicArray<ShardSearchFailure> shardFailures;
        private final Object shardFailuresMutex = new Object();
        protected volatile ScoreDoc[] sortedShardList;

        protected BaseAsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
            this.request = request;
            this.listener = listener;

            this.clusterState = clusterService.state();
            nodes = clusterState.nodes();

            clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);

            String[] concreteIndices = clusterState.metaData().concreteIndices(request.indicesOptions(), request.indices());

            for (String index : concreteIndices) {
                clusterState.blocks().indexBlockedRaiseException(ClusterBlockLevel.READ, index);
            }

            Map<String, Set<String>> routingMap = clusterState.metaData().resolveSearchRouting(request.routing(), request.indices());

            shardsIts = clusterService.operationRouting().searchShards(clusterState, request.indices(), concreteIndices, routingMap, request.preference());
            expectedSuccessfulOps = shardsIts.size();
            // we need to add 1 for non active partition, since we count it in the total!
            expectedTotalOps = shardsIts.totalSizeWith1ForEmpty();

            firstResults = new AtomicArray<>(shardsIts.size());
        }

        public void start() {
            if (expectedSuccessfulOps == 0) {
                // no search shards to search on, bail with empty response (it happens with search across _all with no indices around and consistent with broadcast operations)
                listener.onResponse(new SearchResponse(InternalSearchResponse.empty(), null, 0, 0, buildTookInMillis(), ShardSearchFailure.EMPTY_ARRAY));
                return;
            }
            request.beforeStart();
            int shardIndex = -1;
            for (final ShardIterator shardIt : shardsIts) {
                shardIndex++;
                final ShardRouting shard = shardIt.nextOrNull();
                if (shard != null) {
                    performFirstPhase(shardIndex, shardIt, shard);
                } else {
                    // really, no shards active in this group
                    onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
                }
            }
        }

        void performFirstPhase(final int shardIndex, final ShardIterator shardIt, final ShardRouting shard) {
            if (shard == null) {
                // no more active shards... (we should not really get here, but just for safety)
                onFirstPhaseResult(shardIndex, null, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
            } else {
                final DiscoveryNode node = nodes.get(shard.currentNodeId());
                if (node == null) {
                    onFirstPhaseResult(shardIndex, shard, null, shardIt, new NoShardAvailableActionException(shardIt.shardId()));
                } else {
                    String[] filteringAliases = clusterState.metaData().filteringAliases(shard.index(), request.indices());
                    sendExecuteFirstPhase(node, internalSearchRequest(shard, shardsIts.size(), request, filteringAliases, startTime()), new SearchServiceListener<FirstResult>() {
                        @Override
                        public void onResult(FirstResult result) {
                            onFirstPhaseResult(shardIndex, shard, result, shardIt);
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            onFirstPhaseResult(shardIndex, shard, node.id(), shardIt, t);
                        }
                    });
                }
            }
        }

        void onFirstPhaseResult(int shardIndex, ShardRouting shard, FirstResult result, ShardIterator shardIt) {
            result.shardTarget(new SearchShardTarget(shard.currentNodeId(), shard.index(), shard.id()));
            processFirstPhaseResult(shardIndex, shard, result);
            // we need to increment successful ops first before we compare the exit condition otherwise if we
            // are fast we could concurrently update totalOps but then preempt one of the threads which can
            // cause the successor to read a wrong value from successfulOps if second phase is very fast ie. count etc.
            successfulOps.incrementAndGet();
            // increment all the "future" shards to update the total ops since we some may work and some may not...
            // and when that happens, we break on total ops, so we must maintain them
            final int xTotalOps = totalOps.addAndGet(shardIt.remaining() + 1);
            if (xTotalOps == expectedTotalOps) {
                try {
                    innerMoveToSecondPhase();
                } catch (Throwable e) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "] while moving to second phase", e);
                    }
                    raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
                }
            } else if (xTotalOps > expectedTotalOps) {
                raiseEarlyFailure(new ElasticsearchIllegalStateException("unexpected higher total ops [" + xTotalOps + "] compared to expected [" + expectedTotalOps + "]"));
            }
        }

        void onFirstPhaseResult(final int shardIndex, @Nullable ShardRouting shard, @Nullable String nodeId, final ShardIterator shardIt, Throwable t) {
            // we always add the shard failure for a specific shard instance
            // we do make sure to clean it on a successful response from a shard
            SearchShardTarget shardTarget = new SearchShardTarget(nodeId, shardIt.shardId().getIndex(), shardIt.shardId().getId());
            addShardFailure(shardIndex, shardTarget, t);

            if (totalOps.incrementAndGet() == expectedTotalOps) {
                if (logger.isDebugEnabled()) {
                    if (t != null && !TransportActions.isShardNotAvailableException(t)) {
                        if (shard != null) {
                            logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
                        } else {
                            logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
                        }
                    } else if (logger.isTraceEnabled()) {
                        logger.trace("{}: Failed to execute [{}]", t, shard, request);
                    }
                }
                if (successfulOps.get() == 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("All shards failed for phase: [{}]", t, firstPhaseName());
                    }
                    // no successful ops, raise an exception
                    raiseEarlyFailure(new SearchPhaseExecutionException(firstPhaseName(), "all shards failed", buildShardFailures()));
                } else {
                    try {
                        innerMoveToSecondPhase();
                    } catch (Throwable e) {
                        raiseEarlyFailure(new ReduceSearchPhaseException(firstPhaseName(), "", e, buildShardFailures()));
                    }
                }
            } else {
                final ShardRouting nextShard = shardIt.nextOrNull();
                final boolean lastShard = nextShard == null;
                // trace log this exception
                if (logger.isTraceEnabled()) {
                    logger.trace(executionFailureMsg(shard, shardIt, request, lastShard), t);
                }
                if (!lastShard) {
                    try {
                        performFirstPhase(shardIndex, shardIt, nextShard);
                    } catch (Throwable t1) {
                        onFirstPhaseResult(shardIndex, shard, shard.currentNodeId(), shardIt, t1);
                    }
                } else {
                    // no more shards active, add a failure
                    if (logger.isDebugEnabled() && !logger.isTraceEnabled()) { // do not double log this exception
                        if (t != null && !TransportActions.isShardNotAvailableException(t)) {
                            logger.debug(executionFailureMsg(shard, shardIt, request, lastShard), t);
                        }
                    }
                }
            }
        }

        private String executionFailureMsg(@Nullable ShardRouting shard, final ShardIterator shardIt, SearchRequest request, boolean lastShard) {
            if (shard != null) {
                return shard.shortSummary() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
            } else {
                return shardIt.shardId() + ": Failed to execute [" + request + "] lastShard [" + lastShard + "]";
            }
        }

        protected final ShardSearchFailure[] buildShardFailures() {
            AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
            if (shardFailures == null) {
                return ShardSearchFailure.EMPTY_ARRAY;
            }
            List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList();
            ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()];
            for (int i = 0; i < failures.length; i++) {
                failures[i] = entries.get(i).value;
            }
            return failures;
        }

        protected final void addShardFailure(final int shardIndex, @Nullable SearchShardTarget shardTarget, Throwable t) {
            // we don't aggregate shard failures on non active shards (but do keep the header counts right)
            if (TransportActions.isShardNotAvailableException(t)) {
                return;
            }

            // lazily create shard failures, so we can early build the empty shard failure list in most cases (no failures)
            if (shardFailures == null) {
                synchronized (shardFailuresMutex) {
                    if (shardFailures == null) {
                        shardFailures = new AtomicArray<>(shardsIts.size());
                    }
                }
            }
            ShardSearchFailure failure = shardFailures.get(shardIndex);
            if (failure == null) {
                shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
            } else {
                // the failure is already present, try and not override it with an exception that is less meaningless
                // for example, getting illegal shard state
                if (TransportActions.isReadOverrideException(t)) {
                    shardFailures.set(shardIndex, new ShardSearchFailure(t, shardTarget));
                }
            }
        }

        private void raiseEarlyFailure(Throwable t) {
            for (AtomicArray.Entry<FirstResult> entry : firstResults.asList()) {
                try {
                    DiscoveryNode node = nodes.get(entry.value.shardTarget().nodeId());
                    if (node != null) { // should not happen (==null) but safeguard anyhow
                        searchService.sendFreeContext(node, entry.value.id(), request);
                    }
                } catch (Throwable t1) {
                    logger.trace("failed to release context", t1);
                }
            }
            listener.onFailure(t);
        }

        /**
         * Releases shard targets that are not used in the docsIdsToLoad.
         */
        protected void releaseIrrelevantSearchContexts(AtomicArray<? extends QuerySearchResultProvider> queryResults,
                                                       AtomicArray<IntArrayList> docIdsToLoad) {
            if (docIdsToLoad == null) {
                return;
            }
            // we only release search context that we did not fetch from if we are not scrolling
            if (request.scroll() == null) {
                for (AtomicArray.Entry<? extends QuerySearchResultProvider> entry : queryResults.asList()) {
                    if (docIdsToLoad.get(entry.index) == null) {
                        try {
                            DiscoveryNode node = nodes.get(entry.value.queryResult().shardTarget().nodeId());
                            if (node != null) { // should not happen (==null) but safeguard anyhow
                                searchService.sendFreeContext(node, entry.value.queryResult().id(), request);
                            }
                        } catch (Throwable t1) {
                            logger.trace("failed to release context", t1);
                        }
                    }
                }
            }
        }

        protected ShardFetchSearchRequest createFetchRequest(QuerySearchResult queryResult, AtomicArray.Entry<IntArrayList> entry, ScoreDoc[] lastEmittedDocPerShard) {
            if (lastEmittedDocPerShard != null) {
                ScoreDoc lastEmittedDoc = lastEmittedDocPerShard[entry.index];
                return new ShardFetchSearchRequest(request, queryResult.id(), entry.value, lastEmittedDoc);
            } else {
                return new ShardFetchSearchRequest(request, queryResult.id(), entry.value);
            }
        }

        protected abstract void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchTransportRequest request, SearchServiceListener<FirstResult> listener);

        protected final void processFirstPhaseResult(int shardIndex, ShardRouting shard, FirstResult result) {
            firstResults.set(shardIndex, result);

            if (logger.isTraceEnabled()) {
                logger.trace("got first-phase result from {}", result != null ? result.shardTarget() : null);
            }

            // clean a previous error on this shard group (note, this code will be serialized on the same shardIndex value level
            // so its ok concurrency wise to miss potentially the shard failures being created because of another failure
            // in the #addShardFailure, because by definition, it will happen on *another* shardIndex
            AtomicArray<ShardSearchFailure> shardFailures = this.shardFailures;
            if (shardFailures != null) {
                shardFailures.set(shardIndex, null);
            }
        }

        final void innerMoveToSecondPhase() throws Exception {
            if (logger.isTraceEnabled()) {
                StringBuilder sb = new StringBuilder();
                boolean hadOne = false;
                for (int i = 0; i < firstResults.length(); i++) {
                    FirstResult result = firstResults.get(i);
                    if (result == null) {
                        continue; // failure
                    }
                    if (hadOne) {
                        sb.append(",");
                    } else {
                        hadOne = true;
                    }
                    sb.append(result.shardTarget());
                }

                logger.trace("Moving to second phase, based on results from: {} (cluster state version: {})", sb, clusterState.version());
            }
            moveToSecondPhase();
        }

        protected abstract void moveToSecondPhase() throws Exception;

        protected abstract String firstPhaseName();
    }
}


text:
package org.geometrycommands;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.geometrycommands.LineMergeCommand.LineMergeOptions;

/**
 * The LineMergeCommand UnitTest
 * @author Jared Erickson
 */
public class LineMergeCommandTest extends BaseTest {

    @Test
    public void execute() throws Exception {

        String inputGeometry = "MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))";
        LineMergeOptions options = new LineMergeOptions();
        options.setGeometry(inputGeometry);

        Reader reader = new StringReader(inputGeometry);
        StringWriter writer = new StringWriter();

        LineMergeCommand command = new LineMergeCommand();
        command.execute(options, reader, writer);
        assertEquals("MULTILINESTRING ((-29 -27, -30 -29.7, -36 -31, -45 -33, -46 -32))",
                writer.getBuffer().toString());
    }

    @Test
    public void run() throws Exception {
        // Geometry from options
        String result = runApp(new String[]{
                "linemerge",
                "-g", "MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))"
        }, null);
        assertEquals("MULTILINESTRING ((-29 -27, -30 -29.7, -36 -31, -45 -33, -46 -32))", result);

        // Geometry from input stream
        result = runApp(new String[]{
                "linemerge",
        }, "MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45 -33,-46 -32))");
        assertEquals("MULTILINESTRING ((-29 -27, -30 -29.7, -36 -31, -45 -33, -46 -32))", result);
    }
}


text:
(function() {

    'use strict';

    var handlebars;
    var Component;
    var _Repeater;

    define(
        [
            'handlebars',
            'dessert.component'
        ],
        main
    );

    function main(
        $handlebars,
        $Component
    ) {
        handlebars = $handlebars;
        Component = $Component;

        return createRepeater();
    }

    function createRepeater() {
        if (!_Repeater) {
            class Repeater extends Component {
                constructor() {
                    super(...arguments);
                }

                static get name() {
                    return 'repeater';
                }

                render() {
                    return `<div class="repeater-container"></div>`;
                }

                api(element) {
                    super.api(element);

                    var elemCreated = this.describe('template element is created');

                    this.repeat = function repeat(template, data) {
                        var _template = handlebars.compile(template);
                        var _element;
                        data.forEach(d => {
                            _element = Component.createElement(_template(d));
                            elemCreated.fire([_element]);
                            element.append(_element);
                        });
                    };
                }

                init(element) {
                    super.init(element);
                }
            }
            _Repeater = Repeater;
        }

        return _Repeater;
    }

})();


text:
import React, { Component, PureComponent } from 'react';
import muiThemeable from 'material-ui/styles/muiThemeable';
import S from '../store/Store';
import { Add } from './Add';

const { ipcRenderer } = window.require('electron');

class Edit extends Add {
    title = 'Edit';

    constructor(props) {
        super(props);
        const entries = S.get('entries', []),
            { match } = this.props,
            { id } = match.params;
        entries.find(function(e) {
            if (e.id == id) {
                this.saved = e;
                this.orig = Object.assign({}, e);
                this.orig.tags = e.tags.slice();
                this.entry = Object.assign({}, e);
                this.entry.tags = e.tags.slice();
                const { tags } = e;
                this.state.isFavorite = tags.indexOf('favorite') !== -1;
                const { passwords } = e,
                    len = passwords.length;
                if (len > 0) {
                    const current = passwords[len - 1];
                    this.orig.password = this.entry.password = current;
                }
            }
        }, this);
        this.onPayload = this.onPayload.bind(this);
    }

    onPayload(ev, payload) {
        const { username, password } = this.refs,
            cmd = payload.cmd,
            code = payload.code;
        if (code === 0) {
            if (cmd === 'user') {
                username.input.value = payload.data;
                username.setState({ hasValue: !!payload.data });
            } else if (cmd === 'pass') {
                password.input.value = payload.data;
                password.setState({ hasValue: !!payload.data });
            } else if (cmd === 'gen') {
                this.onGen(ev, payload);
            }
        }
    }

    componentDidMount() {
        const { title, url, email, notes } = this.refs,
            { match } = this.props,
            { id } = match.params,
            { entry } = this;
        title.input.focus();
        title.input.value = entry.title;
        title.setState({ hasValue: !!entry.title });
        url.input.value = entry.url;
        url.setState({ hasValue: !!entry.url });
        email.input.value = entry.email;
        email.setState({ hasValue: !!entry.email });
        notes.input.refs.input.value = entry.notes;
        notes.setState({ hasValue: !!entry.notes });
        ipcRenderer.on('ironclad-reply', this.onPayload);
        ipcRenderer.send('ironclad', ['user', '-p', id]);
        ipcRenderer.send('ironclad', ['pass', '-p', id]);
    }

    componentWillUnmount() {
        ipcRenderer.removeListener('ironclad-reply', this.onPayload);
    }

    getInput() {
        const { entry } = this,
            { orig } = this,
            { title, url, username, password, email, tags, notes } = entry;

        let fields = [],
            changed = false;

        if (title !== orig.title) {
            fields.push('y');
            fields.push(title);
            changed = true;
        } else {
            fields.push('n');
        }

        if (url !== orig.url) {
            fields.push('y');
            fields.push(url);
            changed = true;
        } else {
            fields.push('n');
        }

        if (username !== orig.username) {
            fields.push('y');
            fields.push(username);
            changed = true;
        } else {
            fields.push('n');
        }

        if (password !== orig.password) {
            fields.push('y');
            fields.push(password);
            changed = true;
        } else {
            fields.push('n');
        }

        if (email !== orig.email) {
            fields.push('y');
            fields.push(email);
            changed = true;
        } else {
            fields.push('n');
        }

        if (tags.join(',') !== orig.tags.join(',')) {
            fields.push('y');
            fields.push(tags.join(','));
            changed = true;
        } else {
            fields.push('n');
        }

        if (notes !== orig.notes) {
            fields.push('y');
            fields.push(notes);
            changed = true;
        } else {
            fields.push('n');
        }

        return changed ? fields : false;
    }

    mask(val) {
        return val.split('').reduce(ac => ac + '*', '');
    }

    appendNewPassword() {
        const { passwords, password } = this.entry,
            masked = this.mask(password),
            len = passwords.length;
        if (len > 0) {
            if (passwords[len - 1] !== password) {
                passwords.push(masked);
            }
        } else {
            passwords.push(masked);
        }
    }

    handleSave() {
        const { history, match } = this.props,
            { from, id } = match.params,
            next = from === 'details' ? `/details/${id}` : '/entries';
        if (this.submitOk()) {
            const input = this.getInput();
            if (input) {
                ipcRenderer.send('ironclad', ['edit', '--no-editor', id], {
                    input: input
                });
                ipcRenderer.once('ironclad-reply', (e, payload) => {
                    const cmd = payload.cmd,
                        code = payload.code;
                    if (cmd === 'edit') {
                        if (code === 0) {
                            this.appendNewPassword();
                            Object.assign(this.saved, this.entry);
                            history.push(next);
                            const { title } = this.entry,
                                msg =
                                    code === 0
                                        ? `${title} has been updated`
                                        : 'Failed to update entry';
                            S.set('snack.message', msg);
                        }
                    }
                });
            } else {
                history.push(next);
            }
        } else {
            const invalid = this.firstInvalid(),
                { input } = invalid;
            input.focus();
            window.scrollTo(0, 0);
            this.setState({
                showErrors: true
            });
        }
    }
}

export default muiThemeable()(Edit);


text:
'use strict';

var _      = require('lodash');
var render = require('../../../../system/render/common');

////////////////////////////////////////////////////////////////////////////////

module.exports = function (N) {

  // Filter middleware that renders view and required layout and sets
  //
  N.wire.after('responder:http', { priority: 10 }, function http_render(env) {

    // Don't render page on an error.
    if (env.err) {
      return;
    }

    var data = env.response.data
      , view = env.response.view || env.method;

    env.headers['Content-Type'] = 'text/html; charset=UTF-8';

    // If HEAD is requested, it's no need for real rendering.
    if ('HEAD' === env.origin.req.method) {
      env.body = null;
      return;
    }

    // Expose necessary environment/configuration values.
    data.enabled_locales = N.config.locales.enabled;

    // Start rendering.
    env.extras.puncher.start('Rendering');

    try {
      env.body = render(N, view, data, _.extend({
        runtime: env.runtime
      , apiPath: env.method
      }, env.helpers));

      if (env.response.layout) {
        env.runtime.layout = env.response.layout;
        env.body = render(N, env.response.layout, data, _.extend({
          runtime: env.runtime
        , apiPath: env.method
        , content: env.body
        }, env.helpers));
      }
    } catch (err) {
      env.err = err;
    }

    env.extras.puncher.stop();
  });
};


text:
package org.apache.jute.compiler;

/**
 * Abstract Base class for all types supported by Hadoop Record I/O.
 *
 */
abstract public class JType {

	private String mCName;
    private String mCppName;
    private String mCsharpName;
    private String mJavaName;
    protected String mMethodSuffix;
    private String mWrapper;
    private String mSharpWrapper;
    private String mUnwrapMethod;

    /**
     * Creates a new instance of JType
     */
    JType(String cname, String cppname, String csharpName, String javaname, String suffix, String wrapper, String csharpWrapper, String unwrap) {
    	mCName = cname;
        mCppName = cppname;
        mCsharpName = csharpName;
        mJavaName = javaname;
        mMethodSuffix = suffix;
        mWrapper = wrapper;
        mSharpWrapper = csharpWrapper;
        mUnwrapMethod = unwrap;
    }

    abstract String getSignature();

    String genCppDecl(String fname) {
        return "  "+mCppName+" m"+fname+";\n";
    }

	String genCDecl(String name) {
		return "    " + mCName + " "+name+";\n";
	}

    public String genCsharpDecl(String name) {
        return "  private "+mCsharpName+" " +name+";\n";
    }

    String genJavaDecl (String fname) {
        return "  private "+mJavaName+" " +fname+";\n";
    }

    String genJavaConstructorParam (String fname) {
        return "        "+mJavaName+" "+fname;
    }

    String genCppGetSet(String fname, int fIdx) {
        String getFunc = "  virtual "+mCppName+" get"+fname+"() const {\n";
        getFunc += "    return m"+fname+";\n";
        getFunc += "  }\n";
        String setFunc = "  virtual void set"+fname+"("+mCppName+" m_) {\n";
        setFunc += "    m"+fname+"=m_; bs_.set("+fIdx+");\n";
        setFunc += "  }\n";
        return getFunc+setFunc;
    }

	 String genCsharpGetSet(String fname, int fIdx) {
		 String funName=fname.equals("type")?"_Type":fname;
		 String getFunc = "  public "+getCsharpType()+" get"+capitalize(funName)+"() {";
	        getFunc += "return "+fname+";";
	        getFunc += "  }\n";
	        String setFunc = "  internal void set"+capitalize(funName)+"("+getCsharpType()+" m_) {";
	        setFunc += fname+"=m_;";
	        setFunc += "  }\n";
	        return getFunc+setFunc;
    }

    static String capitalize(String s) {
        return s.substring(0,1).toUpperCase()+s.substring(1);
    }
    String genJavaGetSet(String fname, int fIdx) {
        String getFunc = "  public "+mJavaName+" get"+capitalize(fname)+"() {\n";
        getFunc += "    return "+fname+";\n";
        getFunc += "  }\n";
        String setFunc = "  public void set"+capitalize(fname)+"("+mJavaName+" m_) {\n";
        setFunc += "    " + fname+"=m_;\n";
        setFunc += "  }\n";
        return getFunc+setFunc;
    }

    String getCType() {
    	return mCName;
    }
    String getCppType() {
        return mCppName;
    }

    String getCsharpType() {
        return mCsharpName;
    }

    String getJavaType() {
        return mJavaName;
    }

    String getJavaWrapperType() {
        return mWrapper;
    }

    String getCsharpWrapperType() {
        return mSharpWrapper;
    }

    String getMethodSuffix() {
        return mMethodSuffix;
    }

    String genJavaWriteMethod(String fname, String tag) {
        return "    a_.write"+mMethodSuffix+"("+fname+",\""+tag+"\");\n";
    }

    String genJavaReadMethod(String fname, String tag) {
        return "    "+fname+"=a_.read"+mMethodSuffix+"(\""+tag+"\");\n";
    }

    String genJavaReadWrapper(String fname, String tag, boolean decl) {
        String ret = "";
        if (decl) {
            ret = "    "+mWrapper+" "+fname+";\n";
        }
        return ret + "    "+fname+"=new "+mWrapper+"(a_.read"+mMethodSuffix+"(\""+tag+"\"));\n";
    }

    String genJavaWriteWrapper(String fname, String tag) {
        return "        a_.write"+mMethodSuffix+"("+fname+"."+mUnwrapMethod+"(),\""+tag+"\");\n";
    }

    String genJavaCompareTo(String fname) {
        return "    ret = ("+fname+" == peer."+fname+")? 0 :(("+fname+"<peer."+fname+")?-1:1);\n";
    }

    String genJavaEquals(String fname, String peer) {
        return "    ret = ("+fname+"=="+peer+");\n";
    }

    String genJavaHashCode(String fname) {
        return "    ret = (int)"+fname+";\n";
    }

    String genJavaConstructorSet(String fname, String name) {
        return "    this."+fname+"="+name+";\n";
    }

    String genCsharpWriteMethod(String fname, String tag) {
        return "    a_.write"+mMethodSuffix+"("+fname+",\""+tag+"\");\n";
    }

    String genCsharpReadMethod(String fname, String tag) {
        return "    "+fname+"=a_.read"+mMethodSuffix+"(\""+tag+"\");\n";
    }

    String genCsharpReadWrapper(String fname, String tag, boolean decl) {
        String ret = "";
        if (decl) {
            ret = "    "+mSharpWrapper+" "+fname+";\n";
        }
        return ret + "    "+fname+"=a_.read"+mMethodSuffix+"(\""+tag+"\");\n";
    }

    String genCsharpWriteWrapper(String fname, String tag) {
        if (mUnwrapMethod == null) return "a_.write"+mMethodSuffix+"("+fname+","+tag+");\n";
        return "        a_.write"+mMethodSuffix+"("+fname+"."+mUnwrapMethod+"(),\""+tag+"\");\n";
    }

    String genCsharpEquals(String fname, String peer) {
    	return "    ret = ("+fname+"=="+peer+");\n";
    }

    String genCsharpHashCode(String fname) {
        return "    ret = (int)"+fname+";\n";
    }

    String genCsharpConstructorSet(String mName, String fname) {
        return "this."+fname+"="+mName+";\n";
    }

    public String genCsharpConstructorParam(String fname) {
        return "  "+mCsharpName+" " +fname;
    }
}


text:
set(CMAKE_SYSTEM_NAME Generic)

set(CMAKE_C_COMPILER xtensa-esp32-elf-gcc)
set(CMAKE_CXX_COMPILER xtensa-esp32-elf-g++)
set(CMAKE_ASM_COMPILER xtensa-esp32-elf-gcc)

set(CMAKE_C_FLAGS "-mlongcalls -Wno-frame-address" CACHE STRING "C Compiler Base Flags")
set(CMAKE_CXX_FLAGS "-mlongcalls -Wno-frame-address" CACHE STRING "C++ Compiler Base Flags")

# Can be removed after gcc 5.2.0 support is removed (ref GCC_NOT_5_2_0)
set(CMAKE_EXE_LINKER_FLAGS "-nostdlib" CACHE STRING "Linker Base Flags")


text:
<?php
namespace Hostnet\FormTwigBridge;

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * Maybe more of a functional-test, pokes around to find obvious failures in the composition
 * @covers Hostnet\FormTwigBridge\Builder
 * @author Nico Schoenmaker <nschoenmaker@hostnet.nl>
 */
class BuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testSetCsrfTokenManager()
    {
        // Test chaining
        $builder       = new Builder();
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $this->assertSame($builder, $builder->setCsrfTokenManager($token_manager->reveal()));
    }

    public function testSetTranslator()
    {
        // Test chaining
        $builder    = new Builder();
        $translator = $this->prophesize('Symfony\Component\Translation\TranslatorInterface');
        $this->assertSame(
            $builder,
            $builder->setTranslator($translator->reveal())
        );
    }

    public function testEnableAnnotationMapping()
    {
        // Test chaining
        $builder = new Builder();
        $this->assertSame($builder, $builder->enableAnnotationMapping());
    }

    public function testAddFormExtension()
    {
        // Test chaining
        $builder   = new Builder();
        $extension = $this->prophesize('Symfony\Component\Form\FormExtensionInterface');
        $this->assertSame($builder, $builder->addFormExtension($extension->reveal()));
    }

    /**
     * @expectedException DomainException
     */
    public function testCreateTwigEnvironmentBuilderWithoutCSRF()
    {
        $builder = new Builder();
        $builder->createTwigEnvironmentBuilder();
    }

    /**
     * @expectedException DomainException
     */
    public function testCreateTwigEnvironmentBuilderWithoutTranslator()
    {
        $builder       = new Builder();
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $builder->setCsrfTokenManager($token_manager->reveal())->createTwigEnvironmentBuilder();
    }

    public function testCreateTwigEnvironmentBuilder()
    {
        $builder       = new Builder();
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $builder
            ->setCsrfTokenManager($token_manager->reveal())
            ->setTranslator($this->createMock('Symfony\Component\Translation\TranslatorInterface'));
        $this->assertInstanceOf(
            '\Hostnet\FormTwigBridge\TwigEnvironmentBuilder',
            $builder->createTwigEnvironmentBuilder()
        );
    }

    /**
     * @expectedException DomainException
     */
    public function testBuildFormFactoryWithoutCSRF()
    {
        $builder = new Builder();
        $builder->buildFormFactory();
    }

    /**
     * @expectedException DomainException
     */
    public function testBuildFormFactoryWithoutTranslator()
    {
        $builder       = new Builder();
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $builder->setCsrfTokenManager($token_manager->reveal())->buildFormFactory();
    }

    public function testBuildFormFactory()
    {
        $builder       = new Builder();
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $builder
            ->setCsrfTokenManager($token_manager->reveal())
            ->setTranslator($this->createMock('Symfony\Component\Translation\TranslatorInterface'));
        $this->assertInstanceOf(
            '\Symfony\Component\Form\FormFactoryInterface',
            $builder->buildFormFactory()
        );
    }

    public function testFunctionalTest()
    {
        $builder     = new Builder();
        $environment = $builder
            ->setCsrfTokenManager($this->mockCsrf())
            ->setTranslator($this->mockTranslator())
            ->createTwigEnvironmentBuilder()
            ->prependTwigLoader($this->mockLoader())
            ->build();
        $factory     = $builder->buildFormFactory();
        $form        = $factory->createBuilder()->add('first_name')->getForm();

        $this
        ->assertEquals(
            $this->getExpectedOutput(),
            $environment->render('index.html.twig', array('form' => $form->createView()))
        );
    }

    private function getExpectedOutput()
    {
        return 'Hi.

First name' .
               '<input type="text" id="form_first_name" name="form[first_name]" required="required" />' .
               '
<input type="hidden" id="form__token" name="form[_token]" value="foo" />
';
    }

    public function testFunctionalValidationTranslationTest()
    {
        $builder     = new Builder();
        $environment = $builder
            ->setCsrfTokenManager($this->mockCsrf())
            ->setTranslator($this->mockTranslator())
            ->createTwigEnvironmentBuilder()
            ->prependTwigLoader($this->mockLoader())
            ->build();
        $factory     = $builder->buildFormFactory();
        $options     = array('constraints' => array(new NotBlank()));
        $form        = $factory->createBuilder()->add('naam', TextType::class, $options)->getForm();

        $form->submit(array('naam' => ''));
        $this
        ->assertEquals(
            $this->getExpectedTranslatedOutput(),
            $environment->render('index.html.twig', array('form' => $form->createView()))
        );
    }

    private function getExpectedTranslatedOutput()
    {
        return 'Hi.

De CSRF-token is ongeldig. Probeer het formulier opnieuw te versturen.
' .
               '

Naam

Deze waarde mag niet leeg zijn.' .
               '

<input type="text" id="form_naam" name="form[naam]" required="required" />
' .
               '<input type="hidden" id="form__token" name="form[_token]" value="foo" />
';
    }

    private function mockCsrf()
    {
        $token_manager = $this->prophesize('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $token         = new CsrfToken('form', 'foo');
        $token_manager->getToken('form')->willReturn($token);
        return $token_manager->reveal();
    }

    private function mockTranslator()
    {
        $builder = new TranslatorBuilder();
        return $builder->setLocale('nl_NL')->build();
    }

    private function mockLoader()
    {
        return new \Twig_Loader_Array(array('index.html.twig' => 'Hi.{{ form_widget(form) }}'));
    }
}


text:
The perfect starting point to integrate Algolia within your Swift project

  Documentation  •
  Community Forum  •
  Stack Overflow  •
  Report a bug  •
  FAQ  •
  Support

## ✨ Features

- Pure cross-platform Swift client
- Typed requests and responses
- Widespread use of `Result` type
- Uses the power of `Codable` protocol for easy integration of your domain models
- Thread-safe clients
- Detailed logging
- Injectable HTTP client

## Install

### Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It's integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.
Since the release of Swift 5 and Xcode 11, SPM is compatible with the iOS, macOS and tvOS build systems for creating apps.

To use SwiftPM, you should use Xcode 11 to open your project. Click `File` -> `Swift Packages` -> `Add Package Dependency`, enter [InstantSearch repo's URL](https://github.com/algolia/algoliasearch-client-swift).

If you're a framework author and use Swift API Client as a dependency, update your `Package.swift` file:

```swift
let package = Package(
    // 8.16.0 ..< 9.0.0
    dependencies: [
        .package(url: "https://github.com/algolia/algoliasearch-client-swift", from: "8.16.0")
    ],
    // ...
)
```

Add `import AlgoliaSearchClient` to your source files.

### Cocoapods

[CocoaPods](https://cocoapods.org/) is a dependency manager for Cocoa projects.

To install Algolia Swift Client, simply add the following line to your Podfile:

```ruby
pod 'AlgoliaSearchClient', '~> 8.16'
# pod 'InstantSearchClient', '~> 6.0' // Swift 4.2
# pod 'InstantSearchClient', '~> 5.0' // Swift 4.1
```

Then, run the following command:

```bash
$ pod update
```

### Carthage

[Carthage](https://github.com/Carthage/Carthage) is a simple, decentralized dependency manager for Cocoa.

- To install InstantSearch, simply add the following line to your Cartfile:
```ruby
github "algolia/algoliasearch-client-swift" ~> 8.16
# github "algolia/algoliasearch-client-swift" ~> 6.0.0 // Swift 4.2
# github "algolia/algoliasearch-client-swift" ~> 5.0.0 // Swift 4.1
```

- Launch the following commands from the project directory (for v.8.0+)
 ```shell
 carthage update
 ./Carthage/Checkouts/algoliasearch-client-swift/carthage-prebuild
 carthage build
 ```

If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained [over at Carthage](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application).

## 💡 Getting Started

### Initialize the client

To start, you need to initialize the client. To do this, you need your **Application ID** and **API Key**.
You can find both on [your Algolia account](https://www.algolia.com/api-keys).

```swift
let client = Client(appID: "YourApplicationID", apiKey: "YourAdminAPIKey")
let index = client.index(withName: "your_index_name")
```

### Push data

Without any prior configuration, you can start indexing contacts in the `contacts` index using the following code:

```swift
struct Contact: Encodable {
  let firstname: String
  let lastname: String
  let followers: Int
  let company: String
}

let contacts: [Contact] = [
  .init(firstname: "Jimmie", lastname: "Barninger", followers: 93, company: "California Paint"),
  .init(firstname: "Warren", lastname: "Speach", followers: 42, company: "Norwalk Crmc")
]

let index = client.index(withName: "contacts")
index.saveObjects(contacts, autoGeneratingObjectID: true) { result in
  if case .success(let response) = result {
    print("Response: \(response)")
  }
}
```

### Search

You can now search for contacts by `firstname`, `lastname`, `company`, etc. (even with typos):

```swift
index.search(query: "jimmie") { result in
  switch result {
  case .failure(let error):
    print("Error: \(error)")
  case .success(let response):
    print("Response: \(response)")
    do {
      let foundContacts: [Contact] = try response.extractsHits()
      print("Found contacts: \(foundContacts)")
    } catch let error {
      print("Contact parsing error: \(error)")
    }
  }
}
```

### Configure

Settings can be customized to tune the search behavior. For example, you can add a custom sort by number of followers to the already great built-in relevance:

```swift
let settings = Settings()
  .set(\.customRanking, to: [.desc("followers")])
index.setSettings(settings) { result in
  if case .failure(let error) = result {
    print("Error when applying settings: \(error)")
  }
}
```

You can also configure the list of attributes you want to index by order of importance (first = most important):

**Note:** Since the engine is designed to suggest results as you type, you'll generally search by prefix.
In this case the order of attributes is very important to decide which hit is the best:

```swift
let settings = Settings()
  .set(\.searchableAttributes, to: ["lastname", "firstname", "company"])
index.setSettings(settings) { result in
  if case .failure(let error) = result {
    print("Error when applying settings: \(error)")
  }
}
```

For full documentation, visit the [Algolia Swift API Client's documentation](https://www.algolia.com/doc/api-client/getting-started/install/swift/).

## 📝 Examples

You can find code samples in the [Algolia's API Clients playground](https://github.com/algolia/api-clients-playground/tree/master/swift).

## Use the Dockerfile

If you want to contribute to this project without installing all its dependencies, you can use our Docker image. Please check our [dedicated guide](DOCKER_README.MD) to learn more.

## 📄 License

Algolia Swift API Client is an open-sourced software licensed under the [MIT license](LICENSE).

## Notes

### Objective-C support

The Swift API client is compatible with Objective-C up to version 7.0.5. Please use this version of the client if you're working with an Objective-C project.

### Swift 3

You can use this library with Swift by one of the following ways:

- `pod 'AlgoliaSearch-Client-Swift', '~> 4.8.1'`
- `pod 'AlgoliaSearch-Client-Swift', :git => 'https://github.com/algolia/algoliasearch-client-swift.git', :branch => 'swift-3'`

## Getting Help

- **Need help**? Ask a question to the [Algolia Community](https://discourse.algolia.com/) or on [Stack Overflow](http://stackoverflow.com/questions/tagged/algolia).
- **Encountering an issue?** Before reaching out to support, we recommend heading to our [FAQ](https://www.algolia.com/doc/api-client/troubleshooting/faq/swift/) where you will find answers for the most common issues and gotchas with the client.
- **Found a bug?** You can open a [GitHub issue](https://github.com/algolia/algoliasearch-client-swift/issues).


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

namespace PTL.ATT.GUI
{
    partial class ModelDetailsForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.modelDetails = new System.Windows.Forms.TextBox();
            this.close = new System.Windows.Forms.Button();
            this.save = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // modelDetails
            //
            this.modelDetails.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.modelDetails.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.modelDetails.Location = new System.Drawing.Point(12, 12);
            this.modelDetails.Multiline = true;
            this.modelDetails.Name = "modelDetails";
            this.modelDetails.ReadOnly = true;
            this.modelDetails.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.modelDetails.Size = new System.Drawing.Size(753, 462);
            this.modelDetails.TabIndex = 0;
            this.modelDetails.WordWrap = false;
            //
            // close
            //
            this.close.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.close.Location = new System.Drawing.Point(690, 480);
            this.close.Name = "close";
            this.close.Size = new System.Drawing.Size(75, 23);
            this.close.TabIndex = 1;
            this.close.Text = "Close";
            this.close.UseVisualStyleBackColor = true;
            this.close.Click += new System.EventHandler(this.close_Click);
            //
            // save
            //
            this.save.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.save.Location = new System.Drawing.Point(609, 480);
            this.save.Name = "save";
            this.save.Size = new System.Drawing.Size(75, 23);
            this.save.TabIndex = 2;
            this.save.Text = "Save";
            this.save.UseVisualStyleBackColor = true;
            this.save.Click += new System.EventHandler(this.save_Click);
            //
            // ModelDetailsForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(777, 511);
            this.Controls.Add(this.save);
            this.Controls.Add(this.close);
            this.Controls.Add(this.modelDetails);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
            this.Name = "ModelDetailsForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Model details";
            this.Load += new System.EventHandler(this.ModelDetailsForm_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox modelDetails;
        private System.Windows.Forms.Button close;
        private System.Windows.Forms.Button save;
    }
}


text:
#ifndef MICROPY_INCLUDED__STAGE_H
#define MICROPY_INCLUDED__STAGE_H

#include "shared-module/_stage/__init__.h"

#endif  // MICROPY_INCLUDED__STAGE


text:
package br.com.bomrastreio.api.digest;

import br.com.bomrastreio.api.notification.RetryableMailSender;
import br.com.bomrastreio.api.tenant.TenantHolder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DigestDeliverer {

  private static final Logger LOGGER = LoggerFactory.getLogger(DigestDeliverer.class);

  private final Environment environment;
  private final Configuration configuration;
  private final DigestService digestService;
  private final RetryableMailSender retryableMailSender;

  @Autowired
  public DigestDeliverer(
    Environment environment, Configuration configuration, DigestService digestService, RetryableMailSender retryableMailSender
  ) {
    this.environment = environment;
    this.configuration = configuration;
    this.digestService = digestService;
    this.retryableMailSender = retryableMailSender;
  }

  /**
   * Find all tenants and start deliver.
   */
  public void deliver() {
    digestService.findDeliverableTenants()
      .forEach(this::deliverBy);
  }

  /**
   * Define the current tenant and deliver the mail per
   * digest type. Each type has a directory where there is a
   * default template. Into this template, all the information
   * from digest will be filled.
   *
   * @param tenantId Current tenant id
   */
  private void deliverBy(String tenantId) {
    try {
      TenantHolder.set(tenantId);
      Map<DigestType, List<Digest>> group = digestService.findDeliverables()
        .stream().collect(Collectors.groupingBy(Digest::getType));

      group.forEach((type, digests) -> {
        List<?> references = digestService.findReferences(type, digests);
        retryableMailSender.send(createPreparator(tenantId, type, references));
      });

    } finally {
      TenantHolder.remove();
    }
  }

  /**
   * Create a preparator to prepare message for delivery.
   *
   * @param type       The digests type
   * @param references Digests to be delivered
   * @param tenant     Current tenant id
   * @return A mime message preparator for digest
   */
  private MimeMessagePreparator createPreparator(String tenant, DigestType type, List<?> references) {
    return mimeMessage -> {
      MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
      messageHelper.setSubject("Eventos diário");
      messageHelper.setTo(tenant);
      messageHelper.setFrom(
        environment.getRequiredProperty("app.mail.default-sender"),
        environment.getRequiredProperty("app.mail.default-personal")
      );

      Map<String, Object> model = new HashMap<String, Object>() {{
        put("references", references);
        put("referencesCount", references.size());
      }};

      messageHelper.setText(createContent(type, model), true);
    };
  }

  /**
   * Apply the values to the template.
   *
   * @param type  Type of the digests
   * @param model Model with the data to be processed
   * @return The filled template string
   */
  private String createContent(DigestType type, Map<String, Object> model) {
    try {
      String typeName = StringUtils.lowerCase(type.name());
      Template template = configuration.getTemplate("/" + typeName + "/digest/default.ftl");
      return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (Exception ex) {
      LOGGER.error("Exception while processing template", ex);
      throw new IllegalStateException("Exception while processing template");
    }
  }

}


text:
#include "pch.hpp"

#include <core/IndexerTrack.h>

#include <core/Common.h>
#include <core/db/Connection.h>
#include <core/db/Statement.h>
#include <core/Library/Base.h>
#include <core/filestreams/Factory.h>

#include <boost/lexical_cast.hpp>

//////////////////////////////////////////////////////////////////////////////

using namespace musik::core;

//////////////////////////////////////////////////////////////////////////////

IndexerTrack::IndexerTrack(DBINT id)
 :meta(NULL)
 ,id(id)
 ,tempSortOrder(0)
{
}

IndexerTrack::~IndexerTrack(void){
    if(this->meta){
        delete this->meta;
        this->meta  = NULL;
    }
}

const utfchar* IndexerTrack::GetValue(const char* metakey){
    if(metakey && this->meta){
        MetadataMap::iterator metavalue = this->meta->metadata.find(metakey);
        if(metavalue!=this->meta->metadata.end()){
            return metavalue->second.c_str();
        }
    }
    return NULL;
}

void IndexerTrack::SetValue(const char* metakey,const utfchar* value){
    this->InitMeta();
    if(metakey && value){
        this->meta->metadata.insert(std::pair<std::string,utfstring>(metakey,value));
    }
}

void IndexerTrack::ClearValue(const char* metakey){
    if(this->meta){
        this->meta->metadata.erase(metakey);
    }
}

void IndexerTrack::SetThumbnail(const char *data,long size){
    this->InitMeta();

    if(this->meta->thumbnailData)
        delete this->meta->thumbnailData;

    this->meta->thumbnailData        = new char[size];
    this->meta->thumbnailSize        = size;

    memcpy(this->meta->thumbnailData,data,size);
}

const utfchar* IndexerTrack::URI(){
    return NULL;
}

const utfchar* IndexerTrack::URL(){
    return this->GetValue("path");
}

Track::MetadataIteratorRange IndexerTrack::GetValues(const char* metakey){
    if(this->meta){
        return this->meta->metadata.equal_range(metakey);
    }
    return Track::MetadataIteratorRange();
}

Track::MetadataIteratorRange IndexerTrack::GetAllValues(){
    if(this->meta){
        return Track::MetadataIteratorRange(this->meta->metadata.begin(),this->meta->metadata.end());
    }
    return Track::MetadataIteratorRange();
}

DBINT IndexerTrack::Id(){
    return this->id;
}

void IndexerTrack::InitMeta(){
    if(!this->meta){
        // Create the metadata
        this->meta  = new MetaData();
    }
}

bool IndexerTrack::CompareDBAndFileInfo(const boost::filesystem::utfpath &file,db::Connection &dbConnection,DBINT currentFolderId){

    try{
        this->SetValue("path",file.string().c_str());
        this->SetValue("filename",file.leaf().c_str());

        utfstring::size_type lastDot = file.leaf().find_last_of(UTF("."));
        if(lastDot!=utfstring::npos){
            this->SetValue("extension",file.leaf().substr(lastDot+1).c_str());
        }

        DBINT fileSize  = (DBINT)boost::filesystem::file_size(file);
        DBTIME fileTime = (DBTIME)boost::filesystem::last_write_time(file);

        this->SetValue("filesize",boost::lexical_cast<utfstring>(fileSize).c_str());
        this->SetValue("filetime",boost::lexical_cast<utfstring>(fileTime).c_str());

        db::CachedStatement stmt("SELECT id,filename,filesize,filetime FROM tracks t WHERE folder_id=? AND filename=?",dbConnection);
        stmt.BindInt(0,currentFolderId);
        stmt.BindTextUTF(1,this->GetValue("filename"));

        bool fileDifferent(true);

        if(stmt.Step()==db::Row){
            // File found in database.
            this->id    = stmt.ColumnInt(0);
            fileDifferent    = false;

            // Check if the track needs to be reread.
            if(fileSize!=stmt.ColumnInt(2) || fileTime!=stmt.ColumnInt(3)){
                fileDifferent    = true;
            }
        }
        return fileDifferent;
    }catch(...){
    }
    return false;
}

bool IndexerTrack::Save(db::Connection &dbConnection,utfstring libraryDirectory,DBINT folderId){

    MetadataMap metadataCopy(this->meta->metadata);

    unsigned int count;

    db::ScopedTransaction transaction(dbConnection);

    //////////////////////////////////////////////////////////////////////////////
    // Start by removing existing relations
    if(this->id!=0){
        db::CachedStatement deleteGenre("DELETE FROM track_genres WHERE track_id=?",dbConnection);
        deleteGenre.BindInt(0,this->id);
        deleteGenre.Step();

        db::CachedStatement deleteArtist("DELETE FROM track_artists WHERE track_id=?",dbConnection);
        deleteArtist.BindInt(0,this->id);
        deleteArtist.Step();

        db::CachedStatement deleteMeta("DELETE FROM track_meta WHERE track_id=?",dbConnection);
        deleteMeta.BindInt(0,this->id);
        deleteMeta.Step();
    }

    //////////////////////////////////////////////////////////////////////////////
    // 1. Start by inserting as many tags as possible into the tracks-table
    {
        db::CachedStatement stmt("INSERT OR REPLACE INTO tracks (id,track,bpm,duration,filesize,year,folder_id,title,filename,filetime,sort_order1) VALUES (?,?,?,?,?,?,?,?,?,?,?)",dbConnection);

        // Bind all "static" tags (the once that are in the tracks tables)
        stmt.BindTextUTF(1,this->GetValue("track"));
        stmt.BindTextUTF(2,this->GetValue("bpm"));
        stmt.BindTextUTF(3,this->GetValue("duration"));
        stmt.BindTextUTF(4,this->GetValue("filesize"));
        stmt.BindTextUTF(5,this->GetValue("year"));
        stmt.BindInt(6,folderId);
        stmt.BindTextUTF(7,this->GetValue("title"));
        stmt.BindTextUTF(8,this->GetValue("filename"));
        stmt.BindTextUTF(9,this->GetValue("filetime"));
        stmt.BindInt(10,this->tempSortOrder);

        if(this->id!=0){
            stmt.BindInt(0,this->id);
        }

        if(stmt.Step()==db::Done){
            if(this->id==0){
                this->id    = dbConnection.LastInsertedId();
            }
        }
    }

    //////////////////////////////////////////////////////////////////////////////
    // 2. Remove tags that has been used.
    metadataCopy.erase("track");
    metadataCopy.erase("bpm");
    metadataCopy.erase("duration");
    metadataCopy.erase("year");
    metadataCopy.erase("title");
    metadataCopy.erase("filename");
    metadataCopy.erase("filetime");
    metadataCopy.erase("filesize");
    metadataCopy.erase("title");
    metadataCopy.erase("path");
    metadataCopy.erase("extension");

    //////////////////////////////////////////////////////////////////////////////
    // 3. Read genres
    utfstring    visualGenres;
    DBINT            genreId(0);
    count            = 0;
    std::set<utfstring> alreadySetGenres;        // Cache for not saving duplicates

    MetadataIteratorRange genres    = this->GetValues("genre");
    while(genres.first!=genres.second){

        if(alreadySetGenres.find(genres.first->second)==alreadySetGenres.end()){
            alreadySetGenres.insert(genres.first->second);

            // First save the genre
            genreId        = this->_GetGenre(dbConnection,genres.first->second,true);

            // Second, add to the visual genre
            if(count!=0){
                visualGenres    += UTF(", ");
            }
            visualGenres    += genres.first->second;

            ++count;
        }
        ++genres.first;
    }
    if(count>1 || genreId==0){
        // Check for new genre, but do not insert the relation, this is the visual_genre_id field in the database
        genreId        = this->_GetGenre(dbConnection,visualGenres,false,true);
    }
    metadataCopy.erase("genre");

    //////////////////////////////////////////////////////////////////////////////
    // 4. Read artists
    utfstring    visualArtists;
    DBINT            artistId(0);
    count            = 0;
    std::set<utfstring> alreadySetArtists;        // Cache for not saving duplicates

    MetadataIteratorRange artists = this->GetValues("artist");
    while(artists.first!=artists.second){

        if(alreadySetArtists.find(artists.first->second)==alreadySetArtists.end()){
            alreadySetArtists.insert(artists.first->second);

            // First save the artist
            artistId        = this->_GetArtist(dbConnection,artists.first->second,true);

            // Second, add to the visual artist
            if(count!=0){
                visualArtists    += UTF(", ");
            }
            visualArtists    += artists.first->second;

            ++count;
        }

        ++artists.first;
    }
    if(count>1 || artistId==0){
        // Check for new artist, but do not insert the relation, this is the visual_artist_id field in the database
        artistId        = this->_GetArtist(dbConnection,visualArtists,false,true);
    }
    metadataCopy.erase("artist");

    //////////////////////////////////////////////////////////////////////////////
    // 5. Read album
    DBINT albumId(0);
    {
        db::CachedStatement stmt("SELECT id FROM albums WHERE name=?",dbConnection);
        const utfchar *album=this->GetValue("album");
        if(album==NULL){
            album=UTF("");
        }

        stmt.BindTextUTF(0,album);

        if(stmt.Step()==db::Row){
            albumId    = stmt.ColumnInt(0);
        }else{
            // INSERT a new album
            db::Statement insertAlbum("INSERT INTO albums (name) VALUES (?)",dbConnection);
            insertAlbum.BindTextUTF(0,album);

            if(insertAlbum.Step()==db::Done){
                albumId    = dbConnection.LastInsertedId();
            }
        }
    }

    metadataCopy.erase("album");

    //////////////////////////////////////////////////////////////////////////////
    // 6. Thumbnail
    DBINT thumbnailId(0);

    if(this->meta->thumbnailData){
        UINT64 sum    = Checksum(this->meta->thumbnailData,this->meta->thumbnailSize);

        db::CachedStatement thumbs("SELECT id FROM thumbnails WHERE filesize=? AND checksum=?",dbConnection);
        thumbs.BindInt(0,this->meta->thumbnailSize);
        thumbs.BindInt64(1,sum);

        if(thumbs.Step()==db::Row){
            thumbnailId    = thumbs.ColumnInt(0);
        }

        if(thumbnailId==0){
            // INSERT thumbnail
            db::Statement insertThumb("INSERT INTO thumbnails (filesize,checksum) VALUES (?,?)",dbConnection);
            insertThumb.BindInt(0,this->meta->thumbnailSize);
            insertThumb.BindInt64(1,sum);

            if(insertThumb.Step()==db::Done){
                thumbnailId    = dbConnection.LastInsertedId();
            }

            // Save the file
            utfstring filename    = libraryDirectory+UTF("thumbs/")+boost::lexical_cast<utfstring>(thumbnailId)+UTF(".jpg");

            // TODO, fix for UTF wide of not
#ifdef UTF_WIDECHAR
            FILE *thumbFile        = _wfopen(filename.c_str(),UTF("wb"));
#else
            FILE *thumbFile        = fopen(filename.c_str(),UTF("wb"));
#endif
            fwrite(this->meta->thumbnailData,sizeof(char),this->meta->thumbnailSize,thumbFile);
            fclose(thumbFile);

        }

    }

    //////////////////////////////////////////////////////////////////////////////
    // 5. Update tracks table with relations
    {
        db::CachedStatement stmt("UPDATE tracks SET album_id=?,visual_genre_id=?,visual_artist_id=?,thumbnail_id=? WHERE id=?",dbConnection);
        stmt.BindInt(0,albumId);
        stmt.BindInt(1,genreId);
        stmt.BindInt(2,artistId);
        stmt.BindInt(3,thumbnailId);
        stmt.BindInt(4,this->id);
        stmt.Step();
    }

    //////////////////////////////////////////////////////////////////////////////
    // 6. Fields that are left in tagsCopy should be meta-data (extra tags)

    {
        db::CachedStatement selectMetaKey("SELECT id FROM meta_keys WHERE name=?",dbConnection);

        db::CachedStatement selectMetaValue("SELECT id FROM meta_values WHERE meta_key_id=? AND content=?",dbConnection);
        db::CachedStatement insertMetaValue("INSERT INTO meta_values (meta_key_id,content) VALUES (?,?)",dbConnection);

        db::CachedStatement insertTrackMeta("INSERT INTO track_meta (track_id,meta_value_id) VALUES (?,?)",dbConnection);

        // Loop through the tags
        for(MetadataMap::const_iterator metaData=metadataCopy.begin();metaData!=metadataCopy.end();++metaData){

            // 1. Find the meta_key
            DBINT metaKeyId(0);
            std::string key;

            selectMetaKey.BindText(0,metaData->first);

            if(selectMetaKey.Step()==db::Row){
                // key found
                metaKeyId    = selectMetaKey.ColumnInt(0);
            }else{
                // key not found, INSERT
                db::CachedStatement insertMetaKey("INSERT INTO meta_keys (name) VALUES (?)",dbConnection);
                insertMetaKey.BindText(0,metaData->first);
                if(insertMetaKey.Step()==db::Done){
                    metaKeyId    = dbConnection.LastInsertedId();
                }
            }
            selectMetaKey.Reset();

            // 2. Find meta value
            if(metaKeyId!=0){
                DBINT metaValueId(0);
                // 2.1 Find meta_value
                selectMetaValue.BindInt(0,metaKeyId);
                selectMetaValue.BindTextUTF(1,metaData->second);

                if(selectMetaValue.Step()==db::Row){
                    // Value found
                    metaValueId    = selectMetaValue.ColumnInt(0);
                }else{
                    // Value not found, INSERT
                    insertMetaValue.BindInt(0,metaKeyId);
                    insertMetaValue.BindTextUTF(1,metaData->second);
                    if(insertMetaValue.Step()==db::Done){
                        metaValueId    = dbConnection.LastInsertedId();
                    }
                    insertMetaValue.Reset();
                }
                selectMetaValue.Reset();

                // 3. INSERT into the track_meta table
                if(metaValueId!=0){
                    insertTrackMeta.BindInt(0,this->id);
                    insertTrackMeta.BindInt(1,metaValueId);
                    insertTrackMeta.Step();
                    insertTrackMeta.Reset();
                }
            }

        }

    }

    return true;
}

DBINT IndexerTrack::_GetGenre(db::Connection &dbConnection,utfstring genre,bool addRelation,bool aggregated){
    DBINT genreId(0);
    {
        db::CachedStatement stmt("SELECT id FROM genres WHERE name=?",dbConnection);
        stmt.BindTextUTF(0,genre);
        if(stmt.Step()==db::Row){
            genreId    = stmt.ColumnInt(0);
        }
    }

    if(genreId==0){
        // Insert the genre
        DBINT aggregatedInt    = (aggregated?1:0);

        db::CachedStatement stmt("INSERT INTO genres (name,aggregated) VALUES (?,?)",dbConnection);
        stmt.BindTextUTF(0,genre);
        stmt.BindInt(1,aggregatedInt);

        if(stmt.Step()==db::Done){
            genreId        = dbConnection.LastInsertedId();
        }
    }

    if(addRelation){
        // Insert into track_genres
        db::Statement stmt("INSERT INTO track_genres (track_id,genre_id) VALUES (?,?)",dbConnection);
        stmt.BindInt(0,this->id);
        stmt.BindInt(1,genreId);
        stmt.Step();
    }

    return genreId;
}

DBINT IndexerTrack::_GetArtist(db::Connection &dbConnection,utfstring artist,bool addRelation,bool aggregated){
    DBINT artistId(0);

    db::CachedStatement stmt("SELECT id FROM artists WHERE name=?",dbConnection);
    stmt.BindTextUTF(0,artist);

    if(stmt.Step()==db::Row){
        artistId    = stmt.ColumnInt(0);
    }

    if(artistId==0){
        // Insert the genre
        DBINT aggregatedInt    = (aggregated?1:0);
        db::Statement insertArtist("INSERT INTO artists (name,aggregated) VALUES (?,?)",dbConnection);
        insertArtist.BindTextUTF(0,artist);
        insertArtist.BindInt(1,aggregatedInt);

        if(insertArtist.Step()==db::Done){
            artistId        = dbConnection.LastInsertedId();
        }
    }

    if(addRelation){
        // Insert into track_genres
        db::CachedStatement insertRel("INSERT INTO track_artists (track_id,artist_id) VALUES (?,?)",dbConnection);
        insertRel.BindInt(0,this->id);
        insertRel.BindInt(1,artistId);
        insertRel.Step();
    }

    return artistId;
}

TrackPtr IndexerTrack::Copy(){
    return TrackPtr(new IndexerTrack(this->id));
}

IndexerTrack::MetaData::MetaData()
 :thumbnailData(NULL)
 ,thumbnailSize(0)
{
}

IndexerTrack::MetaData::~MetaData(){
    if(this->thumbnailData)
        delete this->thumbnailData;
}

bool IndexerTrack::GetTrackMetadata(db::Connection &db){
    db::Statement genres("SELECT g.name FROM genres g,track_genres tg WHERE tg.genre_id=g.id AND tg.track_id=? ORDER BY tg.id",db);
    db::Statement artists("SELECT ar.name FROM artists ar,track_artists ta WHERE ta.artist_id=ar.id AND ta.track_id=? ORDER BY ta.id",db);
    db::Statement allMetadata("SELECT mv.content,mk.name FROM meta_values mv,meta_keys mk,track_meta tm WHERE tm.track_id=? AND tm.meta_value_id=mv.id AND mv.meta_key_id=mk.id ORDER BY tm.id",db);
    db::Statement track("SELECT t.track,t.bpm,t.duration,t.filesize,t.year,t.title,t.filename,t.thumbnail_id,p.path||f.relative_path||'/'||t.filename,al.name,t.filetime,t.sort_order1 FROM tracks t,folders f,paths p,albums al WHERE t.id=? AND t.folder_id=f.id AND f.path_id=p.id AND t.album_id=al.id",db);

    track.BindInt(0,this->id);
    if(track.Step()==db::Row){
        this->SetValue("track",track.ColumnTextUTF(0));
        this->SetValue("bpm",track.ColumnTextUTF(1));
        this->SetValue("duration",track.ColumnTextUTF(2));
        this->SetValue("filesize",track.ColumnTextUTF(3));
        this->SetValue("year",track.ColumnTextUTF(4));
        this->SetValue("title",track.ColumnTextUTF(5));
        this->SetValue("filename",track.ColumnTextUTF(6));
        this->SetValue("thumbnail_id",track.ColumnTextUTF(7));
        this->SetValue("path",track.ColumnTextUTF(8));
        this->SetValue("album",track.ColumnTextUTF(9));
        this->SetValue("filetime",track.ColumnTextUTF(10));
        this->tempSortOrder = track.ColumnInt(11);

        // genres
        genres.BindInt(0,this->id);
        while(genres.Step()==db::Row){
            this->SetValue("genre",genres.ColumnTextUTF(0));
        }
        // artists
        artists.BindInt(0,this->id);
        while(artists.Step()==db::Row){
            this->SetValue("artist",artists.ColumnTextUTF(0));
        }
        // other metadata
        allMetadata.BindInt(0,this->id);
        while(allMetadata.Step()==db::Row){
            this->SetValue(allMetadata.ColumnText(1),allMetadata.ColumnTextUTF(0));
        }

        return true;
    }
    return false;
}


text:
import { IMethod } from './IMethod';
import { IStackFrame } from './IStackFrame';

export interface IInnerError {
  message?:string;
  type?:string;
  code?:string;
  data?:any;
  inner?:IInnerError
  stack_trace?:IStackFrame[];
  target_method?:IMethod;
}


text:
const { execSync } = require('child_process');
const semver = require('semver');
const chalk = require('chalk');
const path = require('path');
const docker = require('../docker');

const REPO_URL = 'https://github.com/linagora/openpaas-esn.git';
const REQUIRED_NODE_VERSION = '>=6';
const ERROR_CODE = {
  REQUIRED_NODE_VERSION: 1,
  DOCKER: 2
};

module.exports = {
  command: 'init',
  desc: 'init OpenPaaS',
  builder: {
    dir: {
      alias: 'd',
      describe: 'destination directory',
      type: 'string',
      default: 'openpaas'
    },
    'with-npm': {
      describe: 'force to use NPM instead of Yarn to install dependencies',
      type: 'boolean'
    }
  },
  handler(argv) {
    const projectDir = argv.dir;
    const withNpm = argv.withNpm;

    checkNodeVersion();
    checkDocker();

    cloneRepo(projectDir);

    installDependencies(path.join(process.cwd(), projectDir), withNpm);
    initServices();
    initOpenPaaS(projectDir);
  },
};

function checkNodeVersion() {
  if (!semver.satisfies(process.version, REQUIRED_NODE_VERSION)) {
    console.error(chalk.red(
        'You are currently running Node %s but OpenPaaS requires %s. ' +
        'Please use a supported version of Node.\n'
      ),
      process.version,
      REQUIRED_NODE_VERSION);
    exit(ERROR_CODE.REQUIRED_NODE_VERSION);
  }
}

function checkDocker() {
  try {
    execSync('docker ps');
  } catch (error) {
    exit(ERROR_CODE.DOCKER);
  }
}

function getYarnVersionIfAvailable() {
  try {
    return (execSync('yarn --version 2> /dev/null').toString() || '').trim();
  } catch (error) {
    return null;
  }
}

function cloneRepo(outDir = 'openpaas') {
  return execSync(`git clone --depth=1 ${REPO_URL} ${outDir}`, { stdio: 'inherit' });
}

function installDependencies(projectDir, withNpm) {
  let command;

  if (!withNpm && getYarnVersionIfAvailable()) {
    command = 'yarn global add grunt-cli bower && yarn';
  } else {
    command = 'npm i -g grunt-cli bower && npm i';
  }

  return execSync(command, { stdio: 'inherit', cwd: projectDir });
}

function initServices() {
  docker.start();
}

function initOpenPaaS(projectDir) {
  const execOptions = { stdio: 'inherit', cwd: projectDir };
  execSync('node ./bin/cli db --host localhost --port 27017 --database esn', execOptions);
  execSync('node ./bin/cli elasticsearch --host localhost --port 9200', execOptions);
  execSync('node ./bin/cli populate', execOptions);
  execSync('node ./bin/cli platformadmin init --email admin@open-paas.org', execOptions);
}

function exit(code = 0) {
  if (code) {
    console.error(chalk.red(`exit with error code ${code}`));
  }

  process.exit(code);
}


text:
<title>CopyTexture</title>

CopyTexture()

Syntax

Result = CopyTexture(#Texture, #NewTexture)

Description

Creates a new texture which is the exact copy of the specified texture.

Parameters

#Texture

The texture to copy.

#NewTexture

A number to identify the new texture.
#PB_Any can be used to auto-generate this number.

Return value

Nonzero if the texture was successfully duplicated, zero otherwise. If #PB_Any was used
for the #NewTexture parameter then the generated number is returned on success.

Supported OS
All

Texture Index - CreateCubeMapTexture() ->


text:
namespace Framework.Domain.Mapping
{
    using System.Security;

    ///-------------------------------------------------------------------------------------------------
    /// <summary>
    ///     System log mapping.
    /// </summary>
    ///-------------------------------------------------------------------------------------------------

    public class SystemLogMapping : EntityMapping<SystemLog>
    {
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Initializes a new instance of the SystemLogMapping class.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------
        public SystemLogMapping()
        {
            this.Property(x => x.Timestamp).IsRequired();
            this.Property(x => x.MachineName).HasMaxLength(250).IsOptional();
            this.Property(x => x.Message).HasMaxLength(4000).IsRequired();
            this.Property(x => x.User).HasMaxLength(250).IsOptional();
            this.Property(x => x.Type).IsRequired();
            this.Property(x => x.ExceptionType).HasMaxLength(250).IsOptional();
            this.Property(x => x.ApplicationName).HasMaxLength(250).IsOptional();
            this.Property(x => x.SourceFile).HasMaxLength(250).IsOptional();
            this.Property(x => x.MethodName).HasMaxLength(250).IsOptional();
            this.Property(x => x.Component).HasMaxLength(250).IsOptional();
            this.Property(x => x.LineNumber).IsOptional();
        }
    }
}


text:
package com.github.donmahallem.cs.kvf.gson;

import java.util.HashMap;

public class DataObject {

    HashMap<String,Object> mData=new HashMap<>();

    @Override
    public String toString() {
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("DataObject{");
        boolean first=true;
        for(String key:this.mData.keySet()){
            if(!first){
                stringBuilder.append(',');
            }else
                first=false;
            stringBuilder.append(key);
        }
        stringBuilder.append('}');
        return stringBuilder.toString();
    }

    public void put(String name, Object value){
        if(name==null)
            throw new NullPointerException("name must not be null");
        if(value==null)
            this.mData.remove(name);
        this.mData.put(name,value);
    }

    public Object get(String name){
        if(name==null)
            throw new NullPointerException("name must not be null");
        return this.mData.get(name);
    }

    public float getAsFloat(String name){
        final Object obj=this.get(name);
        if(obj instanceof Float)
            return (float)obj;
        else if(obj instanceof String) {
            final float val = Float.parseFloat((String) obj);
            this.mData.put(name,val);
            return val;
        }else
            throw new ClassCastException(name+" is of type: "+obj.getClass().getName());
    }

    public String getAsString(String name){
        return (String)this.get(name);
    }
}


text:
package br.uff.dam.model;

import java.nio.ByteBuffer;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;

public class BaseRawDataModel {

    private static final long serialVersionUID = 3L;

    @PrimaryKey(value="id")
    private long id;

    @Column(value="rawdata_timestamp")
    private long rawDataTimestamp;

    @Column(value = "src_addr")
    private String sourceIPAddress;

    @Column(value = "dest_addr")
    private String DestinationIPAddress;

    @Column(value = "tcp_seq_number")
    private long tcpSequenceNumber;

    @Column(value = "tcp_ack_number")
    private long tcpAckNumber;

    @Column(value = "raw_data")
    private ByteBuffer rawData;

    private byte[] rawDataInBytes;

    public BaseRawDataModel(){

    }

    /**
     * @return the rawDataTimestamp
     */
    public long getRawDataTimestamp() {
        return rawDataTimestamp;
    }

    /**
     * @param rawDataTimestamp the rawDataTimestamp to set
     */
    public void setRawDataTimestamp(long rawDataTimestamp) {
        this.rawDataTimestamp = rawDataTimestamp;
    }

//    /**
//     * @return the rawData
//     */
//    public ByteBuffer getRawData() {
//        return rawData;
//    }

    /**
     * @param rawData the rawData to set
     */
    public void setRawData(ByteBuffer rawData) {
        this.rawData = rawData;
    }

    /**
     * @return the tcpAckNumber
     */
    public long getTcpAckNumber() {
        return tcpAckNumber;
    }

    public void setTcpAckNumber(long tcpAckNumber) {
        this.tcpAckNumber = tcpAckNumber;
    }

    /**
     * @return the sourceIPAddress
     */
    public String getSourceIPAddress() {
        return sourceIPAddress;
    }

    /**
     * @param sourceIPAddress the sourceIPAddress to set
     */
    public void setSourceIPAddress(String sourceIPAddress) {
        this.sourceIPAddress = sourceIPAddress;
    }

    /**
     * @return the DestinationIPAddress
     */
    public String getDestinationIPAddress() {
        return DestinationIPAddress;
    }

    /**
     * @param DestinationIPAddress the DestinationIPAddress to set
     */
    public void setDestinationIPAddress(String DestinationIPAddress) {
        this.DestinationIPAddress = DestinationIPAddress;
    }

    /**
     * @return the tcpSequenceNumber
     */
    public long getTcpSequenceNumber() {
        return tcpSequenceNumber;
    }

    /**
     * @param tcpSequenceNumber the tcpSequenceNumber to set
     */
    public void setTcpSequenceNumber(long tcpSequenceNumber) {
        this.tcpSequenceNumber = tcpSequenceNumber;
    }

    public byte[] getRawDataInBytes(){
        ByteBuffer buffer = rawData.duplicate();

        // Retrieve bytes between the position and limit
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes, 0, bytes.length);
        rawDataInBytes = bytes;
        return rawDataInBytes;
    }

    /**
     * @return the id
     */
    public long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(long id) {
        this.id = id;
    }

}


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.DeviceConfiguration;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Ios Custom Configuration.
 */
public class IosCustomConfiguration extends DeviceConfiguration implements IJsonBackedObject {

    /**
     * The Payload.
     * Payload. (UTF8 encoded byte array)
     */
    @SerializedName(value = "payload", alternate = {"Payload"})
    @Expose
	@Nullable
    public byte[] payload;

    /**
     * The Payload File Name.
     * Payload file name (.mobileconfig
     */
    @SerializedName(value = "payloadFileName", alternate = {"PayloadFileName"})
    @Expose
	@Nullable
    public String payloadFileName;

    /**
     * The Payload Name.
     * Name that is displayed to the user.
     */
    @SerializedName(value = "payloadName", alternate = {"PayloadName"})
    @Expose
	@Nullable
    public String payloadName;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.contextualsearch;

import org.chromium.chrome.browser.contextualsearch.ContextualSearchSelectionController.SelectionType;

/**
 * Defines the interface between a {@link ContextualSearchSelectionController} and the code that
 * handles callbacks.
 */
interface ContextualSearchSelectionHandler {
    /**
     * Handle a scroll event on the base page.
     */
    public void handleScroll();

    /**
     * Handle the selection being cleared on the base page.
     */
    public void handleSelectionCleared();

    /**
     * Handle a valid tap gesture on the base page.
     */
    public void handleValidTap();

    /**
     * Handle an invalid tap gesture on the base page.
     */
    public void handleInvalidTap();

    /**
     * Handle a new selection of the given type, created at the given x,y position.
     */
    public void handleSelection(String selection, boolean selectionValid, SelectionType type,
            float x, float y);

    /**
     * Handle a modification to the selection, done at the given x,y position.
     * @param selection The new selection.
     * @param selectionValid Whether the new selection is valid.
     * @param x The x position of the adjustment.
     * @param y The y position of the adjustment.
     */
    public void handleSelectionModification(
            String selection, boolean selectionValid, float x, float y);

    /**
     * Handle a dismissal of the selection on the base page.
     */
    public void handleSelectionDismissal();

    /**
     * Handle suppression of a Tap gesture.
     */
    public void handleSuppressedTap();

    /**
     * Handle a Tap gesture that has not been suppressed by showing the Tap Search UI.
     */
    public void handleNonSuppressedTap();

    /**
     * Handle updating metrics to reflect that a Tap gesture <i>would</i> be suppressed
     * for the given heuristics.
     * @param tapHeuristics The set of heuristics that would suppress the Tap.
     */
    public void handleMetricsForWouldSuppressTap(ContextualSearchHeuristics tapHeuristics);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6a6a6a</color>
    <color name="colorPrimaryDark">#76a285</color>
    <color name="colorAccent">#011632</color>
    <color name="actionbar_opacity">#33e6881c</color>
    <color name="primary">#A8D8B9</color>
    <color name="primary_dark">#A8D8B9</color>
    <color name="primary_light">#586ce8</color>
    <color name="accent">#e133bfff</color>
    <color name="primary_text">#212121</color>
    <color name="secondary_text">#727272</color>
    <color name="icons">#FFFFFF</color>
    <color name="divider">#B6B6B6</color>
</resources>


text:
namespace DirectX
{
    class SpriteBatch;
    class CommonStates;
    class Texture2D;
}

namespace ThunderRumble
{
    enum class TexturePosition
    {
        None,
        Centered
    };

    struct TextureHandle
    {
        TextureHandle() = default;
        TextureHandle(std::shared_ptr<DX::Texture> texture) : Texture(texture) {}

        std::shared_ptr<DX::Texture> Texture;
        DirectX::XMUINT2 GetTextureSize() const { return DirectX::XMUINT2{ static_cast<uint32_t>(Texture->Width()), static_cast<uint32_t>(Texture->Height()) }; }
    };

    class RenderContext
    {
    public:
        void Begin(DirectX::FXMMATRIX transformMatrix = MatrixIdentity, DirectX::SpriteSortMode sortMode = DirectX::SpriteSortMode::SpriteSortMode_Deferred);
        void End();

        void Draw(const TextureHandle &texture, const DirectX::XMFLOAT2 &position, float rotation = 0.0f, float scale = 1.0f, DirectX::FXMVECTOR color = DirectX::Colors::White, TexturePosition texturePosition = TexturePosition::Centered);
        void Draw(const TextureHandle &texture, const RECT &destinationRect, DirectX::FXMVECTOR color = DirectX::Colors::White);

        void DrawString(std::shared_ptr<DirectX::SpriteFont> font, const std::wstring &message, const DirectX::XMFLOAT2 &position, DirectX::FXMVECTOR color = DirectX::Colors::White, float rotation = 0, const DirectX::XMFLOAT2 &origin = Float2Zero, float scale = 1);
    private:
        RenderContext(std::shared_ptr<DirectX::SpriteBatch> spriteBatch, ID3D11BlendState *blendstate);

        ID3D11BlendState*                     m_blendState;
        std::shared_ptr<DirectX::SpriteBatch> m_spriteBatch;

        static const DirectX::XMMATRIX MatrixIdentity;
        static const DirectX::XMFLOAT2 Float2Zero;

        friend class RenderManager;
    };
}