text:
// Copyright 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.

using Android.App;
using Android.Content;
using Android.OS;
using System;
using System.Collections.Generic;
using Sensus.Context;
using Sensus.Android.Context;
using Sensus.Android.Callbacks;
using Sensus.Android.Concurrent;
using Sensus.Encryption;
using System.Threading.Tasks;
using Sensus.Android.Notifications;
using Plugin.CurrentActivity;

// the unit test project contains the Resource class in its namespace rather than the Sensus.Android
// namespace. include that namespace below.
#if UNIT_TEST
using Sensus.Android.Tests;
#endif

namespace Sensus.Android
{
    /// <summary>
    /// Android sensus service. This is a [hybrid service](http://developer.android.com/guide/components/services.html), as it
    /// is started by the Sensus activity to run indefinitely, and the activity also binds to it. This service runs in the foreground.
    /// For now, no components other than the Sensus activity can interact with the service, as the service is not exported.
    /// </summary>
    [Service(Exported = false, Label = "Runs the SensusMobile sensing application.")]
    public class AndroidSensusService : Service
    {
        public const string KEY_STOP_SERVICE_IF_NO_PROTOCOLS_SHOULD_RUN = "STOP-SERVICE-IF-NO-PROTOCOLS-SHOULD-RUN";

        /// <summary>
        /// Gets the service intent.
        /// </summary>
        /// <returns>The service intent.</returns>
        /// <param name="stopServiceIfNoProtocolsShouldRun">If set to <c>true</c>, then add an intent extra indicating that the <see cref="AndroidSensusService"/> should stop itself immediately if no <see cref="Protocol"/> should run.</param>
        public static Intent GetServiceIntent(bool stopServiceIfNoProtocolsShouldRun)
        {
            Intent intent = new Intent(Application.Context, typeof(AndroidSensusService));
            intent.PutExtra(KEY_STOP_SERVICE_IF_NO_PROTOCOLS_SHOULD_RUN, stopServiceIfNoProtocolsShouldRun);
            return intent;
        }

        /// <summary>
        /// Starts the service.
        /// </summary>
        /// <param name="stopServiceIfNoProtocolsShouldRun">If set to <c>true</c>, then add an intent extra indicating that the <see cref="AndroidSensusService"/> should stop itself immediately if no <see cref="Protocol"/> should run.</param>
        public static void Start(bool stopServiceIfNoProtocolsShouldRun)
        {
            Intent serviceIntent = GetServiceIntent(stopServiceIfNoProtocolsShouldRun);

            // log the start of the service. the service helper might not yet exist.
            SensusServiceHelper serviceHelper = SensusServiceHelper.Get();
            string message = "About to start Android service:  ";
            if (serviceHelper == null)
            {
                Console.Error.WriteLine(message + "Service helper does not yet exist.");
            }
            else
            {
                serviceHelper.Logger.Log(message + "Service helper already exists.", LoggingLevel.Normal, typeof(AndroidSensusService));
            }

            // after android 26, starting a foreground service requires the use of StartForegroundService rather than StartService.
            // in either case, the service itself will call StartForeground after it has started. more info:
            //
            //     https://developer.android.com/reference/android/content/Context.html#startForegroundService(android.content.Intent)
            //
            // also see notes on backwards compatibility for how the compiler directives are used below:
            //
            //    see the Backwards Compatibility article for more information
#if __ANDROID_26__
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                Application.Context.StartForegroundService(serviceIntent);
            }
            else
#endif
            {
                Application.Context.StartService(serviceIntent);
            }
        }

        private readonly List<AndroidSensusServiceBinder> _bindings = new List<AndroidSensusServiceBinder>();
        private AndroidPowerConnectionChangeBroadcastReceiver _powerBroadcastReceiver;

        public override void OnCreate()
        {
            base.OnCreate();

            // initialize the current activity plugin here as well as in the main activity
            // since this service may be created by iteself without a main activity (e.g.,
            // on boot or on OS restart of the service). we want the plugin to have be
            // initialized regardless of how the app comes to be created.
            CrossCurrentActivity.Current.Init(Application);

            SensusContext.Current = new AndroidSensusContext
            {
                Platform = Platform.Android,
                MainThreadSynchronizer = new MainConcurrent(),
                SymmetricEncryption = new SymmetricEncryption(SensusServiceHelper.ENCRYPTION_KEY),
                CallbackScheduler = new AndroidCallbackScheduler(this),
                Notifier = new AndroidNotifier(),
                PowerConnectionChangeListener = new AndroidPowerConnectionChangeListener()
            };

            // promote this service to a foreground service as soon as possible. we use a foreground service for several
            // reasons. it's honest and transparent. it lets us work effectively with the android 8.0 restrictions on
            // background services. we can run forever without being killed. we receive background location updates, etc.
            (SensusContext.Current.Notifier as AndroidNotifier).UpdateForegroundServiceNotificationBuilder();
            StartForeground(AndroidNotifier.FOREGROUND_SERVICE_NOTIFICATION_ID, (SensusContext.Current.Notifier as AndroidNotifier).BuildForegroundServiceNotification());

            // https://developer.android.com/reference/android/content/Intent#ACTION_POWER_CONNECTED
            // This is intended for applications that wish to register specifically to this notification. Unlike ACTION_BATTERY_CHANGED,
            // applications will be woken for this and so do not have to stay active to receive this notification. This action can be
            // used to implement actions that wait until power is available to trigger.
            //
            // We use the same receiver for both the connected and disconnected intents.
            _powerBroadcastReceiver = new AndroidPowerConnectionChangeBroadcastReceiver();
            IntentFilter powerConnectFilter = new IntentFilter();
            powerConnectFilter.AddAction(Intent.ActionPowerConnected);
            powerConnectFilter.AddAction(Intent.ActionPowerDisconnected);
            powerConnectFilter.AddCategory(Intent.CategoryDefault);
            RegisterReceiver(_powerBroadcastReceiver, powerConnectFilter);

            // must come after context initialization. also, it is here -- below StartForeground -- because it can
            // take a while to complete and we don't want to run afoul of the short timing requirements on calling
            // StartForeground.
            SensusServiceHelper.Initialize(() => new AndroidSensusServiceHelper());

            AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper;

            // we might have failed to create the service helper. it's also happened that the service is created
            // after the service helper is disposed.
            if (serviceHelper == null)
            {
                Stop();
            }
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper;

            // there might be a race condition between the calling of this method and the stopping/disposal of the service helper.
            // if the service helper is stopped/disposed before the service is stopped but after this method is called (e.g., by
            // an alarm callback), the service helper will be null.
            if (serviceHelper != null)
            {
                serviceHelper.Logger.Log("Sensus service received start command (startId=" + startId + ", flags=" + flags + ").", LoggingLevel.Normal, GetType());

                // update the foreground service notification with information about loaded/running studies.
                (SensusContext.Current.Notifier as AndroidNotifier).ReissueForegroundServiceNotification();

                // if the service started but there are no protocols that should be running, then stop the app now. there is no
                // reason for the app to be running in this situation, and the user will likely be annoyed at the presence of the
                // foreground service notification.
                if (intent != null && intent.GetBooleanExtra(KEY_STOP_SERVICE_IF_NO_PROTOCOLS_SHOULD_RUN, false) && serviceHelper.RunningProtocolIds.Count == 0)
                {
                    serviceHelper.Logger.Log("Started service without running protocols. Stopping service now.", LoggingLevel.Normal, GetType());
                    Stop();
                    return StartCommandResult.NotSticky;
                }

                // acquire wake lock before this method returns to ensure that the device does not sleep prematurely, interrupting the execution of a callback.
                serviceHelper.KeepDeviceAwakeAsync().Wait();

                Task.Run(async () =>
                {
                    try
                    {
                        // the service can be stopped without destroying the service object. in such cases,
                        // subsequent calls to start the service will not call OnCreate. therefore, it's
                        // important that any code called here is okay to call multiple times, even if the
                        // service is running. calling this when the service is running can happen because
                        // sensus receives a signal on device boot and for any callback alarms that are
                        // requested. furthermore, all calls here should be nonblocking / async so we don't
                        // tie up the UI thread.
                        await serviceHelper.StartAsync();

                        if (intent != null)
                        {
                            AndroidCallbackScheduler callbackScheduler = SensusContext.Current.CallbackScheduler as AndroidCallbackScheduler;

                            if (callbackScheduler.IsCallback(intent))
                            {
                                await callbackScheduler.RaiseCallbackAsync(intent);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        serviceHelper.Logger.Log("Exception while responding to on-start command:  " + ex.Message, LoggingLevel.Normal, GetType());
                    }
                    finally
                    {
                        serviceHelper.LetDeviceSleepAsync().Wait();
                    }
                });
            }

            // if the service is killed by the system (e.g., due to resource constraints), ask the system to restart
            // the service when possible.
            return StartCommandResult.Sticky;
        }

        public override IBinder OnBind(Intent intent)
        {
            AndroidSensusServiceBinder binder = new AndroidSensusServiceBinder();

            lock (_bindings)
            {
                _bindings.Add(binder);
            }

            return binder;
        }

        public void Stop()
        {
            NotifyBindingsOfStop();
            StopSelf();
        }

        private void NotifyBindingsOfStop()
        {
            // let everyone who is bound to the service know that we're going to stop.
            lock (_bindings)
            {
                foreach (AndroidSensusServiceBinder binding in _bindings)
                {
                    try
                    {
                        binding.OnServiceStop?.Invoke();
                    }
                    catch (Exception ex)
                    {
                        SensusServiceHelper.Get()?.Logger.Log("Exception while notifying binding of service stop:  " + ex.Message, LoggingLevel.Normal, GetType());
                    }
                }

                _bindings.Clear();
            }
        }

        public override void OnDestroy()
        {
            Console.Error.WriteLine("--------------------------- Destroying Service ---------------------------");

            // we used to stop all protocols when destroying the service, but this is not appropriate. if we're
            // destroying the service because the user has stopped the app, then we'll already have stopped the
            // protocols as requested by the user. if the os is destroying the service to reclaim resources, then
            // the protocol should be left running. if the os subsequently kills the app's process, the protocols
            // will restart when the os resumes the process and service. so, don't stop the protocols.

            SensusServiceHelper.Get()?.Logger.Log("Destroying service.", LoggingLevel.Normal, GetType());  // the service helper will be null if we failed to create it within OnCreate

            NotifyBindingsOfStop();

            // we've seen cases where the receiver doesn't get registered before the service is
            // destroyed. catch exception raised from attempting to unregister a receiver that
            // hasn't been registered.
            try
            {
                UnregisterReceiver(_powerBroadcastReceiver);
            }
            catch (Exception)
            { }

            try
            {
                (SensusContext.Current.Notifier as AndroidNotifier).OnDestroy();
            }
            catch (Exception)
            { }

            // do this last so that we don't dispose the service and its system services too early.
            base.OnDestroy();
        }
    }
}


text:
"""
Copyright (c) 2012 - 2015, Marian Steinbach, Ernesto Ruge
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import locale

LOCALE = 'de_DE.UTF8'

BOOTSTRAP_SERVE_LOCAL = True

MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_USERNAME = ''
MONGO_PASSWORD = ''
MONGO_DBNAME = 'ris'

ES_HOST = 'localhost'
ES_PORT = 9200

BASIC_AUTH_USERNAME = 'YOUR-USERNAME'
BASIC_AUTH_PASSWORD = 'YOUR-PASSWORD'
SECRET_KEY = 'RANDOM-STRING'
BOOTSTRAP_SERVE_LOCAL = True

BASE_DIR = '/srv/www/ris-web'

stopwords_path = "/srv/www/ris-web/config/synonyms_global.txt"
synonyms_path =  "/srv/www/ris-web/config/stopwords_de_global.txt"
thumbs_path = "/srv/www/ris-web/webapp/static/thumbs/"

redpajama_set_name: RedPajamaGithub


text:
package testmd.storage;

import org.slf4j.LoggerFactory;
import testmd.PermutationResult;
import testmd.PreviousResults;
import testmd.util.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;

/**
 * Writes results to stored markdown-based file.
 */
public class ResultsWriter {

    public static final String SEPARATOR = "---------------------------------------";
    boolean wroteWarning = false;

    public void write(File file, String testHash, Collection<PreviousResults> results) {

        SortedSet<PreviousResults> sortedResults = new TreeSet<>(new Comparator<PreviousResults>() {
            @Override
            public int compare(PreviousResults o1, PreviousResults o2) {
                return o1.getTestName().compareTo(o2.getTestName());
            }
        });
        sortedResults.addAll(results);

        try {
            file.getParentFile().mkdirs();

            LoggerFactory.getLogger(getClass()).debug("Writing results to " + file.getAbsolutePath());
            ResultsWriter resultsWriter = new ResultsWriter();

            try (FileWriter fileWriter = new FileWriter(file)) {
                for (PreviousResults result : results) {
                    resultsWriter.write(result.getTestClass(), result.getTestName(), result.getResults(), fileWriter);
                }

                fileWriter.write("\n");
                fileWriter.write("# Test Version: \""+testHash+"\" #");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    protected void write(String testClass, String testName, Collection<PermutationResult> results, Writer out) throws IOException {
        if (!wroteWarning) {
            out.append("**NOTE: This output is generated and parsed by TestMD. Please read it, but DO NOT EDIT MANUALLY**\n");
            wroteWarning = true;
        }

        out.append("\n# Test: \"").append(testName).append("\" #\n\n");

        if (results.size() == 0) {
            out.append("**NO PERMUTATIONS**\n");
        } else if (shouldPrintTables(results)) {
            printWithTables(results, out);
        } else {
            printWithoutTables(results, out);
        }

        out.flush();
    }

    protected boolean shouldPrintTables(Collection<PermutationResult> results) {
        if (results == null || results.size() == 0) {
            return false;
        }

        PermutationResult result = results.iterator().next();
        return result.getTableParameters() != null && result.getTableParameters().size() > 0;

    }

    protected void printWithoutTables(Collection<PermutationResult> passedResults, Writer out) throws IOException {
        List<PermutationResult> results = new ArrayList(passedResults);
        Collections.sort(results);

        int i = 0;
        for (PermutationResult result : results) {
            i++;
            if (!result.isValid()) {
                continue;
            }

            out.append("## Permutation ").append(result.getKey());
            if (result.isVerified()) {
                out.append(" (verified)");
            } else {
                out.append(" _NOT VERIFIED");
                if (result.getNotVerifiedMessage() != null) {
                    out.append(": ").append(result.getNotVerifiedMessage());
                }
                out.append("_");
            }
            out.append(" ##\n\n");

            for (Map.Entry<String, String> entry : result.getParameters().entrySet()) {
                appendMapEntry(entry, out);
            }

            if (result.getNotes().size() > 0) {
                out.append("\n");
                out.append("#### Notes ####\n");
                out.append("\n");

                for (Map.Entry<String, String> entry : result.getNotes().entrySet()) {
                    appendMapEntry(entry, out);
                }
            }

            if (result.getResults().entrySet().size() > 0) {
                out.append("\n");
                out.append("#### Results ####\n");
                out.append("\n");

                for (Map.Entry<String, String> entry : result.getResults().entrySet()) {
                    appendMapEntry(entry, out);
                }
            }

            if (i < results.size()) {
                out.append("\n"+SEPARATOR+"\n\n");
            }
        }
    }

    protected void printWithTables(Collection<PermutationResult> passedResults, Writer out) throws IOException {
        List<PermutationResult> results = new ArrayList(passedResults);
        Collections.sort(results);

        SortedMap<String, List<PermutationResult>> resultsByTable = new TreeMap<String, List<PermutationResult>>();
        for (PermutationResult result : passedResults) {
            String tableKey = result.getTableKey();
            if (!resultsByTable.containsKey(tableKey)) {
                resultsByTable.put(tableKey, new ArrayList<PermutationResult>());
            }
            resultsByTable.get(tableKey).add(result);
        }

        if (resultsByTable.isEmpty()) {
            return;
        }

        int testCount = 0;
        int resultIndex = 0;
        for (Map.Entry<String, List<PermutationResult>> entry : resultsByTable.entrySet()) {
            resultIndex++;
            List<PermutationResult> tableResults = new ArrayList<PermutationResult>();
            for (PermutationResult result : entry.getValue()) {
                if (result.isValid()) {
                    tableResults.add(result);
                }
            }

            if (tableResults.size() == 0) {
                continue;
            }

            if (testCount++ > 0) {
                out.append(SEPARATOR + "\n\n");
            }

            boolean hasParams = false;
            for (Map.Entry<String, String> descriptionEntry : tableResults.get(0).getParameters().entrySet()) {
                if (!tableResults.get(0).getTableParameters().contains(descriptionEntry.getKey())) {
                    appendMapEntry(descriptionEntry, out);
                    hasParams = true;
                }
            }

            SortedMap<String, Integer> maxColumnLengths = new TreeMap<String, Integer>();
            int permutationNameColLength = "Permutation".length();
            int verifiedColLength = "Verified".length();

            Map<String, String> verifiedMessages = new HashMap<String, String>();
            for (PermutationResult result : tableResults) {
                if (result.getKey().length() > permutationNameColLength) {
                    permutationNameColLength = result.getKey().length();
                }

                String verifiedMessage = StringUtils.trimToNull(result.getNotVerifiedMessage());
                if (verifiedMessage == null) {
                    verifiedMessage = String.valueOf(result.isVerified());
                }
                verifiedMessages.put(result.getKey(), verifiedMessage);

                if (verifiedMessage.length() > verifiedColLength) {
                    verifiedColLength = verifiedMessage.length();
                }
                for (String columnName : result.getTableParameters()) {
                    Integer oldMax = maxColumnLengths.get(columnName);
                    if (oldMax == null) {
                        oldMax = columnName.length();
                        maxColumnLengths.put(columnName, oldMax);
                    }
                    String storedValue = result.getParameters().get(columnName);
                    if (storedValue != null) {
                        if (oldMax < storedValue.length()) {
                            maxColumnLengths.put(columnName, storedValue.length());
                        }
                    }
                }
            }

            if (hasParams) {
                out.append("\n");
            }

            String headerRow = "| "+StringUtils.pad("Permutation", permutationNameColLength)+" | "+StringUtils.pad("Verified", verifiedColLength)+" |";
            for (Map.Entry<String, Integer> columnEntry : maxColumnLengths.entrySet()) {
                headerRow += " "+StringUtils.pad(columnEntry.getKey(), columnEntry.getValue())+" |";
            }
            headerRow += " OPERATIONS\n";

            String headerSeparator = "| :"+StringUtils.repeat("-", permutationNameColLength - 1)+" | :"+StringUtils.repeat("-", verifiedColLength - 1)+" |";
            for (Map.Entry<String, Integer> columnEntry : maxColumnLengths.entrySet()) {
                headerSeparator += " :"+StringUtils.repeat("-", columnEntry.getValue() - 1)+" |";
            }
            headerSeparator += " :------\n";

            out.append(headerRow);
            out.append(headerSeparator);

            SortedMap<String, String> permutationRows = new TreeMap<String, String>();
            for (PermutationResult result : tableResults) {
                StringBuilder row = new StringBuilder();
                row.append("| ").append(StringUtils.pad(result.getKey(), permutationNameColLength))
                        .append(" | ")
                        .append(StringUtils.pad(verifiedMessages.get(result.getKey()), verifiedColLength))
                        .append(" |");

                String rowKey = "";
                for (Map.Entry<String, Integer> columnAndLength : maxColumnLengths.entrySet()) {
                    String cellValue = result.getParameters().get(columnAndLength.getKey());
                    String cellString;
                    if (cellValue == null) {
                        cellString = "";
                    } else {
                        cellString = clean(cellValue);
                    }

                    rowKey += " "+StringUtils.pad(cellString, columnAndLength.getValue())+ " |";
                }
                row.append(rowKey);

                List<String> details = new ArrayList<String>();
                for (Map.Entry<String, String> notesEntry : result.getNotes().entrySet()) {
                    details.add(" __"+notesEntry.getKey()+"__: "+clean(notesEntry.getValue()));
                }
                for (Map.Entry<String, String> dataEntry : result.getResults().entrySet()) {
                    details.add(" **" + dataEntry.getKey() + "**: " + clean(dataEntry.getValue()));
                }

                for (int i=0; i<details.size(); i++) {
                    if (i > 0) {
                        row.append("| ").append(StringUtils.pad("", permutationNameColLength)).append(" | ")
                                .append(StringUtils.pad("", verifiedColLength)).append(" |");
                        for (Map.Entry<String, Integer> nameAndLength : maxColumnLengths.entrySet()) {
                            row.append(" ").append(StringUtils.pad("", nameAndLength.getValue())).append(" |");
                        }

                    }
                    row.append(details.get(i)).append("\n");
                }

                permutationRows.put(rowKey, row.toString());
            }
            out.append(StringUtils.join(permutationRows.values(), "", StringUtils.STANDARD_STRING_FORMAT, false));
            if (resultIndex < resultsByTable.size()) {
                out.append("\n");
            }
        }
    }

    private String clean(String string) {
        return string.replace("\r\n", "\n").replace("\n", "<br>").replace("|", "|");
    }

    private void appendMapEntry(Map.Entry<String, String> entry, Writer out) throws IOException {
        String value = entry.getValue();
        value  = value.replace("\r\n", "\n");

        boolean multiLine = value.contains("\n");

        out.append("- **").append(entry.getKey());

        if (multiLine) {
            out.append(" =>**\n");
        } else {
            out.append(":** ");
        }
        if (multiLine) {
            out.append(StringUtils.indent(value, 4));
        } else {
            out.append(value);
        }

        out.append("\n");
    }

}


text:
Low-level SQLite3 bindings for Haskell
======================================

[![Build Status](https://travis-ci.org/IreneKnapp/direct-sqlite.png?branch=master)](https://travis-ci.org/IreneKnapp/direct-sqlite) ![Hackage](https://img.shields.io/hackage/v/direct-sqlite.svg?style=flat-square)

This package is not very different from the other SQLite3 bindings out there, but it fixes a few deficiencies I was finding. As compared to bindings-sqlite3, it is slightly higher-level, in that it supports marshalling of data values to and from the database. In particular, it supports strings encoded as UTF8, and BLOBs represented as ByteStrings.

For contribtions, please read [contributing guide](CONTRIBUTING.md) before sending PRs.

# Contributors

- [Irene Knapp](https://github.com/nurpax) author
- [Janne Hellsten](https://github.com/nurpax) long-term maintainer
- [Sergey Bushnyak](https://github.com/sigrlami) long-term maintainer
- [Joshua Chia](https://github.com/jchia) current maintainer


text:
package com.palantir.docker.compose.configuration;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class AdditionalEnvironmentValidatorShould {

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void throw_exception_when_additional_environment_variables_contain_docker_variables() {
        Map<String, String> variables = ImmutableMap.<String, String>builder()
                .put("DOCKER_HOST", "tcp://some-host:2376")
                .put("SOME_VARIABLE", "Some Value")
                .build();
        exception.expect(IllegalStateException.class);
        exception.expectMessage("The following variables");
        exception.expectMessage("DOCKER_HOST");
        exception.expectMessage("cannot exist in your additional environment");
        AdditionalEnvironmentValidator.validate(variables);
    }

    @Test
    public void validate_arbitrary_environment_variables() {
        Map<String, String> variables = ImmutableMap.<String, String>builder()
                .put("SOME_VARIABLE", "Some Value")
                .build();

        assertThat(AdditionalEnvironmentValidator.validate(variables), is(variables));
    }
}


text:
require 'spec_helper'

RSpec.describe Formstack::Model do
  let(:client) { spy("Test Client instance") }
  subject(:subclass) {
    Class.new do
      include Formstack::Model
      def self.client_method
        :test
      end
    end
  }

  before :each do
    allow(Formstack).to receive(:client).and_return(client)
  end

  describe "::all" do
    it "calls plural client_method passing args to client and initializes list of objects" do
      allow(client).to receive(:tests).with(arg: :val).and_return([{ "id" => 1 }])
      objects = subclass.all(arg: :val)
      expect(objects.size).to eq(1)
      expect(objects.first["id"]).to eq(1)
    end

    it "initializes with list in {response_nesting} if method defined" do
      subclass.class_eval do
        def self.response_nesting
          "nesting"
        end
      end

      allow(client).to receive(:tests).and_return("nesting" => [{ "id" => 1 }])
      objects = subclass.all
      expect(objects.size).to eq(1)
      expect(objects.first["id"]).to eq(1)
    end

    it "allows calling create on returned array" do
      allow(client).to receive(:tests).and_return([{}])
      allow(client).to receive(:create_test).with(123, :attributes).and_return({ "id" => "123" })
      allow(client).to receive(:test).with("123").and_return({ "id" => "123" })
      collection = subclass.all(123)
      created = collection.create(:attributes)
      expect(created[:id]).to eq("123")
    end
  end

  describe "::find" do
    it "calls client_method passing args to client and initializes an object" do
      allow(client).to receive(:test).with(1).and_return({ "id" => 1, "name" => "Foo" })
      object = subclass.find(1)
      expect(object["id"]).to eq(1)
      expect(object["name"]).to eq("Foo")
    end
  end

  describe "::create" do
    it "calls create_{client_method} passing args to client and initializes and loads object" do
      allow(client).to receive(:create_test).with(name: "val").and_return({ "id" => 123 })
      object = subclass.create(name: "val")
      expect(client).to have_received(:test).with(123)
      expect(object).to be_a(subclass)
    end

    it "does not load object on error" do
      allow(client).to receive(:create_test).and_return({ "status" => "error" })
      object = subclass.create
      expect(object["status"]).to eq("error")
    end
  end

  describe "#initialize" do
    it "sets passed args to @attributes" do
      object = subclass.new("name" => "value")
      expect(object.attributes).to eq("name" => "value")
    end
  end

  describe "#[]" do
    it "delegates to @attributes" do
      object = subclass.new("name" => "value")
      expect(object["name"]).to eq("value")
    end

    it "stringifies any symbol passed" do
      object = subclass.new("name" => "value")
      expect(object[:name]).to eq("value")
    end
  end

  describe "#load" do
    it "resets @attributes from a call to client_method with id attr" do
      object = subclass.new("id" => "123")
      expect(client).to receive(:test).with("123").and_return("id" => "123", "name" => "Foo")
      object.load
      expect(object[:name]).to eq("Foo")
    end
  end

  describe "#update" do
    it "updates @attributes with passed hash stringifying keys and calls update_{client_method}" do
      object = subclass.new("id" => "123", "name" => "Bar")
      expect(client).to receive(:update_test).with("123", "id" => "123", "name" => "Foo").and_return("success" => "1")
      object.update(name: "Foo")
      expect(object[:name]).to eq("Foo")
    end
  end

  describe "#delete" do
    it "calls delete_{client_method} on client" do
      object = subclass.new("id" => "123")
      expect(client).to receive(:delete_test).with("123").and_return("success" => "1")
      object.delete
    end
  end
end


text:
{% extends "base.html" %}

{% block content %}

                        Calendar
                        Control panel

 Home

Calendar

Draggable Events

Lunch

Go home

Do homework

Work on UI design

Sleep tight

                                            <input type='checkbox' id='drop-remove' /> remove after drop

Create Event

                                        <button type="button" id="color-chooser-btn" class="btn btn-danger btn-block btn-sm dropdown-toggle" data-toggle="dropdown">Color </button>

 Green

 Blue

 Navy

 Yellow

 Orange

 Aqua

 Red

 Fuchsia

 Purple

                                        <input id="new-event" type="text" class="form-control" placeholder="Event Title">

                                            <button id="add-new-event" type="button" class="btn btn-default btn-flat">Add</button>

{% endblock content %}


text:
#include <windows.h>
#include <stdio.h>
#include <conio.h>

#include "../../api/inc/fmod.h"
#include "../../api/inc/fmod_errors.h"

void ERRCHECK(FMOD_RESULT result)
{
    if (result != FMOD_OK)
    {
        printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
        exit(-1);
    }
}

int main(int argc, char *argv[])
{
    FMOD_SYSTEM      *system;
    FMOD_SOUND       *sound1, *sound2, *sound3;
    FMOD_CHANNEL     *channel = 0;
    FMOD_RESULT       result;
    int               key;
    unsigned int      version;

    /*
        Create a System object and initialize.
    */
    result = FMOD_System_Create(&system);
    ERRCHECK(result);

    result = FMOD_System_GetVersion(system, &version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }

    result = FMOD_System_Init(system, 32, FMOD_INIT_NORMAL, NULL);
    ERRCHECK(result);

    result = FMOD_System_CreateSound(system, "../media/drumloop.wav", FMOD_HARDWARE, 0, &sound1);
    ERRCHECK(result);

    result = FMOD_Sound_SetMode(sound1, FMOD_LOOP_OFF); /* drumloop.wav has embedded loop points which automatically makes looping turn on, */
    ERRCHECK(result);                                   /* so turn it off here.  We could have also just put FMOD_LOOP_OFF in the above CreateSound call. */

    result = FMOD_System_CreateSound(system, "../media/jaguar.wav", FMOD_SOFTWARE, 0, &sound2);
    ERRCHECK(result);

    result = FMOD_System_CreateSound(system, "../media/swish.wav", FMOD_HARDWARE, 0, &sound3);
    ERRCHECK(result);

    printf("===================================================================\n");
    printf("PlaySound Example.  Copyright (c) Firelight Technologies 2004-2011.\n");
    printf("===================================================================\n");
    printf("\n");
    printf("Press '1' to play a mono sound using hardware mixing\n");
    printf("Press '2' to play a mono sound using software mixing\n");
    printf("Press '3' to play a stereo sound using hardware mixing\n");
    printf("Press 'Esc' to quit\n");
    printf("\n");

    /*
        Main loop.
    */
    do
    {
        if (_kbhit())
        {
            key = _getch();

            switch (key)
            {
                case '1' :
                {
                    result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound1, 0, &channel);
                    ERRCHECK(result);
                    break;
                }
                case '2' :
                {
                    result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound2, 0, &channel);
                    ERRCHECK(result);
                    break;
                }
                case '3' :
                {
                    result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound3, 0, &channel);
                    ERRCHECK(result);
                    break;
                }
            }
        }

        FMOD_System_Update(system);

        {
            unsigned int ms = 0;
            unsigned int lenms = 0;
            int          playing = 0;
            int          paused = 0;
            int          channelsplaying = 0;

            if (channel)
            {
                FMOD_SOUND *currentsound = 0;

                result = FMOD_Channel_IsPlaying(channel, &playing);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
                {
                    ERRCHECK(result);
                }

                result = FMOD_Channel_GetPaused(channel, &paused);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
                {
                    ERRCHECK(result);
                }

                result = FMOD_Channel_GetPosition(channel, &ms, FMOD_TIMEUNIT_MS);
                if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
                {
                    ERRCHECK(result);
                }

                FMOD_Channel_GetCurrentSound(channel, &currentsound);
                if (currentsound)
                {
                    result = FMOD_Sound_GetLength(currentsound, &lenms, FMOD_TIMEUNIT_MS);
                    if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
                    {
                        ERRCHECK(result);
                    }
                }
            }

            result = FMOD_Sound_GetLength(sound1, &lenms, FMOD_TIMEUNIT_MS);
            if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
            {
                ERRCHECK(result);
            }

            FMOD_System_GetChannelsPlaying(system, &channelsplaying);

            printf("Time %02d:%02d:%02d/%02d:%02d:%02d : %s : Channels Playing %2d\r", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : playing ? "Playing" : "Stopped", channelsplaying);
        }

        Sleep(10);

    } while (key != 27);

    printf("\n");

    /*
        Shut down
    */
    result = FMOD_Sound_Release(sound1);
    ERRCHECK(result);
    result = FMOD_Sound_Release(sound2);
    ERRCHECK(result);
    result = FMOD_Sound_Release(sound3);
    ERRCHECK(result);
    result = FMOD_System_Close(system);
    ERRCHECK(result);
    result = FMOD_System_Release(system);
    ERRCHECK(result);

    return 0;
}


text:
'use strict';
// controller for actions for a specific note

// note model
const Note = require("../models/Note");

// Category model
const Category = require("../models/category");

// method for showing a list of notes
module.exports.index = (req, res) =>
{
	Note.find({}, (err, notes) =>
	{
		if (err) throw err;
			console.log(notes);
		res.render("notes-index", { "notes": notes });

	});
};

// method for new note form
module.exports.newNote = (req, res) =>
{
	Category.find({}, (err, categories) =>
	{
		console.log(categories);
		if(err) throw err;
		res.render("new-note", {"categories" : categories});
	});
};

// method for viewing individual note
module.exports.show = (req, res) =>
{
	Note.findById(req.params.id, (err, note) =>
	{
		if (err) throw err;
		res.render("show-note", {note: note});
	});
};

// method for for making new notes
module.exports.create = (req, res) =>
{
	Note.create(req.body, (err, note) =>
	{
		if (err) throw err;
		console.log(note);
		res.redirect(`/notes/${note._id}`);
	});
};

// method for deleting notes
module.exports.destroy = (req, res) =>
{
	Note.findByIdAndRemove(req.params.id, (err) =>
	{
		if (err) throw err;
		res.redirect("/notes");
	});

};

// method for deleting notes
module.exports.edit = (req, res) =>
{
	Note.findById(req.params.id, (err, note) =>
	{
		if (err) throw err;
			console.log(note);
		res.render("edit-note", {"note":note});

	});
};

// method for updating notes
module.exports.update = (req, res) =>
{
	Note.findByIdAndUpdate(req.params.id, {title: req.body.title, text :req.body.text}, () =>
	{
		res.redirect(`/notes/${req.params.id}`);

	});
};


text:
import sys
import csv
from optparse import make_option

from django.core.management.base import BaseCommand

from modoboa.core import load_core_settings
from modoboa.core.extensions import exts_pool
from modoboa.core.management.commands import CloseConnectionMixin
from ...models import Domain

class Command(BaseCommand, CloseConnectionMixin):
    help = 'Export domains and domain aliases to a csv'

    option_list = BaseCommand.option_list + (
        make_option(
            '--sepchar', action='store_true', dest='sepchar', default=';'
        ),
    )

    def handle(self, *args, **kwargs):
        exts_pool.load_all()
        load_core_settings()

        csvwriter = csv.writer(sys.stdout, delimiter=kwargs['sepchar'])
        for dom in Domain.objects.all():
            dom.to_csv(csvwriter)


text:
@implementation RDYSettingFontSize

+ (NSArray *)fontSizeType {
    return @[@"大", @"中", @"小"];
}

@end


text:
package org.junit;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * If you allocate external resources in a {@link org.junit.Before} method you need to release them
 * after the test runs. Annotating a public void method
 * with @After causes that method to be run after the {@link org.junit.Test} method. All @After
 * methods are guaranteed to run even if a {@link org.junit.Before} or {@link org.junit.Test} method throws an
 * exception. The @After methods declared in superclasses will be run after those of the current
 * class, unless they are overridden in the current class.
 *

 * Here is a simple example:
 *

 * public class Example {
 *    File output;
 *    @Before public void createOutputFile() {
 *          output= new File(...);
 *    }
 *    @Test public void something() {
 *          ...
 *    }
 *    @After public void deleteOutputFile() {
 *          output.delete();
 *    }
 * }
 *

 *
 * @see org.junit.Before
 * @see org.junit.Test
 * @since 4.0
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {
}


text:
source $(dirname $0)/scripts/env_conf.sh
root=$(dirname $(${abspath} $0)) 2>/dev/null
root=${root:-.}
cd ${root}

# dev
export PY_BIN_DIR=${root}/venv/bin
source ${PY_BIN_DIR}/activate
export SYSTEM_CONFIG=development

# prod
# export PY_BIN_DIR=/usr/local/venvs/$(PROJECT_NAME)s/bin
# source ${PY_BIN_DIR}/activate
# export SYSTEM_CONFIG=production


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 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.
//
//*********************************************************//

using System;
using System.Collections.Generic;

namespace Microsoft.NodejsTools.Debugger {
    sealed class NodeEventEventArgs : EventArgs {
        private readonly Dictionary<string, object> _data;

        public NodeEventEventArgs(Dictionary<string, object> data) {
            _data = data;
        }

        public Dictionary<string, object> Data {
            get { return _data; }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
            android:text="加载页面"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/textView"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text=""
            android:ems="10"
            android:id="@+id/views"/>
    <TextView
            android:text="弹窗数据"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/textView2"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:text=""
            android:ems="10"
            android:id="@+id/editText2"/>
    <Button
            android:text="获取当前xml配置"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/button"/>
    <Button
            android:text="修改当前XML配置"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/button2"/>
    <Button
            android:text="跳转界面"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/button3"/>
</LinearLayout>


text:
#include "PreCompiled.h"
#include "OfficeUtils.h"

#include "Sdk/Quqi/UploadInfo.h"
#include "Sdk/Quqi/DocumentStorageBase.h"
#include "Sdk/Quqi/DocumentStorageManager.h"

USING_NS_QUQI_SDK;

bool OfficeUtils::saveContent( QuqiSDK::OfficeUploadInfo &info, int_32 storage_id, const String& content, uint_8 key[16], bool is_encrypt )
{
	info.content_md5 = CodecUtil::md5(content);
	info.content_size = content.size();
	info.storage_path = formatTimeForPath();
	info.storage_name = StringUtil::toString(info.quqi_id) +"_"+ StringUtil::toString(info.tree_id) +"_"+
		StringUtil::toString(info.node_id) +"_"+ StringUtil::toString(info.version) + "_" +
		StringUtil::toString(info.type) + "_" + info.content_md5;

	DocumentStorageInfo dsi;
	dsi.path = info.storage_path;
	dsi.name = info.storage_name;

	DocumentStorageBase *storage = DocumentStorageManager::getInstance().getStorage(storage_id);
	if (storage == NULL)
	{
		return false;
	}
	if (is_encrypt)
	{
		storage->saveContent(dsi, content, key);
	}
	else
	{
		storage->saveRawContent(dsi, content);
	}
	return true;
}

String OfficeUtils::formatTimeForPath()
{
	std::time_t t= std::time(NULL);
	char mbstr[100];
	if(std::strftime(mbstr,sizeof(mbstr),"%y/%m/%d",std::localtime(&t))){
		return StringUtil::toString(mbstr);
	}
	return "";
}


text:
<form method='post' id="searchToken" target="_self">
  Search:

  <input type="text" name="searchValue">

  <input type='submit' name='submit' value='Search'>

</form>


text:
<?php
namespace Hyperframework\Db;

use PDO;
use Exception;
use Hyperframework\Db\Test\DbCustomConnection;
use Hyperframework\Common\Config;
use Hyperframework\Db\Test\TestCase as Base;

class DbClientEngineTest extends Base {
    private $engine;

    protected function setUp() {
        parent::setUp();
        DbImportCommand::execute(
            'Document',
            [[1, 'doc 1', 12.34], [2, 'doc 2', null]],
            ['column_names' => ['id', 'name', 'decimal']]
        );
        $this->engine = new DbClientEngine;
    }

    protected function tearDown() {
        DbClient::delete('Document', null);
        parent::tearDown();
    }

    public function testFindColumnByColumns() {
        $this->assertSame(1, $this->engine->findColumnByColumns(
            'Document', 'id', ['name' => 'doc 1']
        ));
    }

    public function testFindColumnById() {
        $this->assertSame(
            'doc 1',
            $this->engine->findColumnById('Document', 'name', 1)
        );
    }

    public function testFindRow() {
        $this->assertSame(
            ['name' => 'doc 1'],
            $this->engine->findRow("SELECT name FROM Document WHERE id = 1")
        );
    }

    public function testFindRowByColumns() {
        $this->assertSame(
            ['id' => 1],
            $this->engine->findRowByColumns(
                'Document', ['name' => 'doc 1'], ['id']
            )
        );
    }

    public function testFindRowById() {
        $this->assertSame(
            ['id' => 1, 'name' => 'doc 1', 'decimal' => '12.34'],
            $this->engine->findRowById('Document', '1')
        );
    }

    public function testFindAll() {
        $this->assertEquals(
            [['name' => 'doc 1']],
            $this->engine->findAll("SELECT name FROM Document WHERE id = 1")
        );
    }

    public function testFindAllByColumns() {
        $this->assertSame(
            [['id' => 1]],
            $this->engine->findAllByColumns(
                'Document', ['name' => 'doc 1'], ['id']
            )
        );
    }

    public function testFind() {
        $statement = $this->engine->find("SELECT * FROM Document");
        $this->assertTrue($statement instanceof DbStatement);
    }

    public function testFindByColumns() {
        $statement = $this->engine->findByColumns(
            'Document', ['name' => 'doc 1']
        );
        $this->assertSame(1, $statement->rowCount());
        $this->assertSame(3, count($statement->fetch(PDO::FETCH_ASSOC)));
        $this->assertSame(
            2, $this->engine->findByColumns('Document', [])->rowCount()
        );
        $this->assertSame(1, count($this->engine->findByColumns(
            'Document', [], ['name']
        )->fetch(PDO::FETCH_ASSOC)));
        $this->assertSame(2, count($this->engine->findByColumns(
            'Document', [], ['id', 'name']
        )->fetch(PDO::FETCH_ASSOC)));
        $this->assertSame(3, count($this->engine->findByColumns(
            'Document', [], []
        )->fetch(PDO::FETCH_ASSOC)));
    }

    public function testCount() {
        $this->assertSame(1, $this->engine->count('Document', 'id > ?', [1]));
        $this->assertSame(1, $this->engine->count(
            'Document', ['name' => 'doc 1'])
        );
    }

    public function testMin() {
        $this->assertSame(
            1, $this->engine->min('Document', 'id', 'id > ?', [0])
        );
        $this->assertSame(
            1, $this->engine->min('Document', 'id', ['name' => 'doc 1'])
        );
    }

    public function testMax() {
        $this->assertSame(
            2, $this->engine->max('Document', 'id', 'id > ?', [1])
        );
        $this->assertSame(
            1, $this->engine->min('Document', 'id', ['name' => 'doc 1'])
        );
    }

    public function testAverage() {
        $this->assertEquals(
            1.5, $this->engine->average('Document', 'id', 'id > ?', [0])
        );
        $this->assertEquals(
            1, $this->engine->average('Document', 'id', ['name' => 'doc 1'])
        );
    }

    public function testInsert() {
        $this->engine->insert('Document', ['id' => 3]);
        $this->assertSame(3, $this->engine->count('Document'));
    }

    public function testUpdate() {
        $this->engine->update(
            'Document', ['name' => 'updated 1'], 'id = ?', [1]
        );
        $row = $this->engine->findRowById('Document', 1);
        $this->assertSame('updated 1', $row['name']);
        $this->engine->update('Document', ['name' => 'updated 2'], ['id' => 1]);
        $row = $this->engine->findRowById('Document', 1);
        $this->assertSame('updated 2', $row['name']);
        $this->engine->update('Document', ['name' => 'updated 3'], null);
        $row = $this->engine->findRowById('Document', 1);
        $this->assertSame('updated 3', $row['name']);
        $row = $this->engine->findRowById('Document', 2);
        $this->assertSame('updated 3', $row['name']);
    }

    public function testDelete() {
        $this->engine->delete('Document', 'id = ?', [1]);
        $this->assertFalse($this->engine->findRowById('Document', 1));
        $this->engine->delete('Document', ['id' => 2]);
        $this->assertFalse($this->engine->findRowById('Document', 2));
    }

    public function testDeleteAll() {
        $this->engine->delete('Document', null);
        $this->assertTrue(0 === $this->engine->count('Document'));
    }

    public function testDeleteById() {
        $this->engine->delete('Document', 1);
        $this->assertFalse($this->engine->findRowById('Document', 1));
    }

    public function testUpdateById() {
        $row = ['name' => 'updated'];
        $this->assertTrue($this->engine->updateById('Document', $row, 1));
        $this->assertSame(
            'updated', $this->engine->findColumnById('Document', 'name', 1)
        );
    }

    public function testExecute() {
        $this->assertSame(
            1, $this->engine->execute('DELETE FROM Document WHERE id = ?', [1])
        );
        $this->assertFalse($this->engine->findRowById('Document', 1));
    }

    public function testGetLastInsertId() {
        $row = [];
        $this->engine->insert('Document', $row);
        $this->assertNotNull($this->engine->getLastInsertId());
    }

    public function testTransaction() {
        $this->engine->beginTransaction();
        $this->assertTrue($this->engine->inTransaction());
        $this->engine->delete('Document', 1);
        $this->engine->commit();
        $this->assertFalse($this->engine->inTransaction());
        $this->assertFalse($this->engine->findRowById('Document', 1));
    }

    public function testRollback() {
        $this->engine->beginTransaction();
        $this->engine->delete('Document', 1);
        $this->engine->rollback();
        $this->assertTrue(is_array($this->engine->findRowById('Document', 1)));
    }

    public function testQuoteIdentifier() {
       $this->assertSame(
           1, strpos($this->engine->quoteIdentifier('id'), 'id')
       );
    }

    public function testPrepare() {
        $this->assertTrue($this->engine->prepare('SELECT * FROM Document', [])
            instanceof DbStatement);
    }

    public function testSetConnectionWhenConnectionPoolIsEnabled() {
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->assertTrue($connection === $this->engine->getConnection());
        $this->engine->connect('custom');
        $this->assertTrue($connection === $this->engine->getConnection());
    }

    public function testSetConnectionWhenConnectionPoolIsDisabled() {
        Config::set('hyperframework.db.enable_connection_pool', false);
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->assertTrue($connection === $this->engine->getConnection());
        $this->engine->setConnection($connection);
        $this->engine->connect('custom');
        $this->assertNotSame($connection, $this->engine->getConnection());
    }

    public function testCloseConnectionWhenConnectionPoolIsEnabled() {
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection();
        $this->assertNull($this->engine->getConnection(false));
        $this->engine->connect('custom');
        $this->assertNotSame($connection, $this->engine->getConnection());
    }

    public function testCloseConnectionWhenConnectionPoolIsDisabled() {
        Config::set('hyperframework.db.enable_connection_pool', false);
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection();
        $this->assertNull($this->engine->getConnection(false));
    }

    public function testCloseConnectionByNameWhenConnectionPoolIsEnabled() {
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection('custom');
        $this->assertNull($this->engine->getConnection(false));
        $this->engine->connect('custom');
        $this->assertNotSame($connection, $this->engine->getConnection());
    }

    public function testCloseConnectionByNameWhenConnectionPoolIsDisabled() {
        Config::set('hyperframework.db.enable_connection_pool', false);
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection('custom');
        $this->assertNotSame($connection, $this->engine->getConnection());
    }

    public function
        testCloseNonExistentConnectionByNameWhenConnectionPoolIsEnabled()
    {
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection('unknown');
        $this->assertSame($connection, $this->engine->getConnection());
    }

    public function
        testCloseNonExistentConnectionByNameWhenConnectionPoolIsDisabled()
    {
        Config::set('hyperframework.db.enable_connection_pool', false);
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->closeConnection('unknown');
        $this->assertSame($connection, $this->engine->getConnection());
    }

    public function testClosePooledConnection() {
        $connection = new DbCustomConnection;
        $this->engine->setConnection($connection);
        $this->engine->connect('default');
        $this->engine->closeConnection('custom');
        $this->assertNotNull($this->engine->getConnection(false));
        $this->engine->connect('custom');
        $this->assertNotSame($connection, $this->engine->getConnection());
    }

    public function testCloseNullConnection() {
        $this->engine->closeConnection();
        $this->assertNull($this->engine->getConnection(false));
    }

    public function testGetNullConnection() {
        $this->assertNull($this->engine->getConnection(false));
    }

    public function testConnectWhenConnectionPoolIsEnabled() {
        $this->engine->connect('backup');
        $connection = $this->engine->getConnection();
        $this->engine->connect('backup');
        $this->assertSame('backup', $connection->getName());
        $this->assertSame($this->engine->getConnection(), $connection);
    }

    public function testConnectWhenConnectionPoolIsDisabled() {
        Config::set('hyperframework.db.enable_connection_pool', false);
        $this->engine->connect('backup');
        $connectionA = $this->engine->getConnection();
        $this->engine->connect('backup');
        $connectionB = $this->engine->getConnection();
        $this->assertSame('backup', $connectionA->getName());
        $this->assertSame('backup', $connectionB->getName());
        $this->assertNotSame($connectionA, $connectionB);
    }
}


text:
#ifndef __BASE__LIFETIME_H__
#define __BASE__LIFETIME_H__

#include <tbb/atomic.h>
#include <tbb/mutex.h>

#include "base/dependency.h"
#include "base/queue_task.h"
#include "base/util.h"

class LifetimeActor;
class LifetimeManager;

//
// The Lifetime management framework enables a structured approach to the
// problem of tracking inter-dependencies between objects for the purpose
// of orderly deletion and cleanup.  The dependencies are represented as
// an acyclic graph with LifetimeActors being the nodes and LifetimeRefs
// being the links.  The dependency tracker lets us implement "on delete
// cascade" behavior wherein the deletion of an object triggers deletion
// of all it's dependents, the dependents' dependents and so on.
//
// Each object that requires lifetime management contains an instance of
// a derived class of LifetimeActor embedded in it. The derived class is
// specific to the object type and typically contains a back pointer to
// the object. The convention is to name the derived class as DeleteActor
// and the instance of it as deleter_.
//
// Each managed object (other than the root object) contains one or more
// LifetimeRef instances.  A LifetimeRef instance corresponds to a parent
// object on which the object is dependent. The LifetimeRef instances are
// normally created and linked to the parent objects' LifetimeActor when
// the managed object is constructed.  Each LifetimeRef contains a back
// pointer to the managed object.  The convention is to name the members
// as xxx_delete_ref_, where xxx corresponds to the parent object class.
//
// The deletion of a managed object can be triggered by calling Delete on
// it's actor from any thread. This in turn results in cascaded calls to
// Delete as described above. Further, the LifetimeActor also enqueues a
// a delete event to the LifetimeManager for deferred processing.  This
// event is processed by the LifetimeManager in the desired Task context.
//
// When a managed object is destroyed, all the LifetimeRefs to it's parent
// objects are also destroyed.  This automatically causes the LifetimeRefs
// to get removed from the list of dependents in the parents' DeleteActor.
// This in turn also enqueues a delete event to the parent DeleteActor's
// LifetimeManager if appropriate i.e. if the parent DeleteActor's list of
// dependents has become empty.
//
// The LifetimeManager DeleteExecutor processes delete events for Actors
// in the context of the desired Task.  It makes sure that there are no
// dependents and that all relevant state in the DeleteActor's object has
// been cleaned up i.e. the object may be deleted, before destroying the
// object.
//
// Note that object deletes are triggered from top to bottom while object
// destruction happens in the reverse order.
//
// In addition to having other managed objects as dependents it's common
// to also have other lightweight objects as dependents. These lightweight
// dependents should not be tracked using LifetimeRefs, but can instead be
// tracked using simple reference counts. When the reference count becomes
// 0, a delete event for the actor should be posted to the LifetimeManager.
//

//
// Base class for a reference to a managed lifetime object.
//
class LifetimeRefBase {
public:
    LifetimeRefBase(LifetimeActor *actor);
    virtual ~LifetimeRefBase();

    // called when the lifetime actor delete is called.
    // implements "ON DELETE CASCADE" semantics.
    virtual void Delete() = 0;

    void Reset(LifetimeActor *actor) {
        ref_.reset(actor);
    }

    bool IsSet() const { return ref_.get() != NULL; }

private:
    DependencyRef<LifetimeRefBase, LifetimeActor> ref_;
    DISALLOW_COPY_AND_ASSIGN(LifetimeRefBase);
};

//
// Class template to create LifetimeRefs for specific object types.
//
// Ref is the type of the dependent object.
// The LifetimeActor parameter is the actor for the parent object.
//
template <class Ref>
class LifetimeRef : public LifetimeRefBase {
public:
    LifetimeRef(Ref *ptr, LifetimeActor *actor)
            : LifetimeRefBase(actor), ptr_(ptr) {
    }

    virtual void Delete() {
        ptr_->ManagedDelete();
    }

private:
    Ref *ptr_;
    DISALLOW_COPY_AND_ASSIGN(LifetimeRef);
};

// Member of an object that has managed lifetime.
class LifetimeActor {
public:
    LifetimeActor(LifetimeManager *manager);
    virtual ~LifetimeActor();

    // Trigger the deletion of an object.
    // May be called from any thread.
    virtual void Delete();

    void RetryDelete();

    // Prevent/Resume deletion of object - for testing only.
    void PauseDelete();
    void ResumeDelete();

    bool IsDeleted() const { return deleted_; }
    bool HasDependents() const { return !dependents_.empty(); }

    const uint64_t create_time_stamp_usecs() const {
        return create_time_stamp_usecs_;
    }
    const uint64_t delete_time_stamp_usecs() const {
        return delete_time_stamp_usecs_;
    }

private:
    typedef DependencyList<LifetimeRefBase, LifetimeActor> Dependents;
    friend class DependencyRef<LifetimeRefBase, LifetimeActor>;
    friend class LifetimeManager;

    // Called to check dependencies.
    virtual bool MayDelete() const = 0;

    // Called under the manager thread in order to remove the object state.
    virtual void Shutdown();

    // Called immediately before the object is destroyed.
    virtual void DeleteComplete();

    // Must be called under a specific Task.
    virtual void Destroy() = 0;

    void PropagateDelete();
    void DependencyAdd(DependencyRef<LifetimeRefBase, LifetimeActor> *node);
    void DependencyRemove(DependencyRef<LifetimeRefBase, LifetimeActor> *node);

    void ReferenceIncrement();
    bool ReferenceDecrementAndTest();

    bool shutdown_invoked() { return shutdown_invoked_; }
    void set_shutdown_invoked() { shutdown_invoked_ = true; }

    tbb::mutex mutex_;
    LifetimeManager *manager_;
    tbb::atomic<bool> deleted_;
    int refcount_;
    bool shutdown_invoked_;
    bool delete_paused_;
    uint64_t create_time_stamp_usecs_;
    uint64_t delete_time_stamp_usecs_;
    Dependents dependents_;

    DISALLOW_COPY_AND_ASSIGN(LifetimeActor);
};

//
// Handles deletion in the correct task context.
//
// The pointer to the actor is wrapped inside a LifetimeActorRef to prevent
// the WorkQueue from deleting the actor.
//
class LifetimeManager {
public:
    LifetimeManager(int task_id);
    virtual ~LifetimeManager();

    // Return the number of times work queue task executions were deferred.
    size_t GetQueueDeferCount() { return defer_count_; }

protected:
    virtual void SetQueueDisable(bool disabled);

private:
    friend class LifetimeActor;

    struct LifetimeActorRef {
        LifetimeActor *actor;
    };

    // Enqueue Delete event.
    void Enqueue(LifetimeActor *actor);

    // Enqueue Delete event. Used by the actor code which has already
    // incremented the reference count.
    void EnqueueNoIncrement(LifetimeActor *actor);

    // Check if global (not per-actor) conditions for destruction are
    // satisfied.  Should be over-ridden by derived class if required.
    virtual bool MayDestroy() { return true; }

    bool DeleteExecutor(LifetimeActorRef actor_ref);

    int defer_count_;
    WorkQueue<LifetimeActorRef> queue_;

    DISALLOW_COPY_AND_ASSIGN(LifetimeManager);
};

#endif


text:
{-# LANGUAGE ScopedTypeVariables #-}
module Main where

import Control.Concurrent (threadDelay)
import Control.Exception (catch)
import System.Exit (ExitCode)
import Test.Tasty (defaultMain, testGroup, TestTree)
import Test.Tasty.HUnit
import System.Process
import System.FilePath (replaceExtension)

import TestFW.TestGCMCheck (tests)

main :: IO ()
main = do
    -- Setup
    server <- spawnProcess "stack" ["exec", "--", "GRACeServer", "-l", "libraries"]
    threadDelay 10000000  -- wait a second for the server to get started

    -- Test
    defaultMain (testGroup "Test all"
      [ TestFW.TestGCMCheck.tests
      , serviceTests
      ]) `catch` \(e :: ExitCode) -> return ()

    -- Teardown
    terminateProcess server

serviceTests = testGroup "Unit tests"
  [ testService "libraries" [] "test/libraries.exp"
  , testService "library/cld"  [] "test/library_cld.exp"
  , testService "library/crud" [] "test/library_crud.exp"
  , testSubmit "crud" "test/submit_crud.json"
  , testSubmit "cld" "test/submit_newcld.json"
  , testSubmit "cld" "test/submit_xcld.json"
  , testSubmit "cld" "test/submit_xcld2.json"
  , testSubmit "cld" "test/submit_shcld.json"
  , testSubmit "fullgcm" "test/submit_d3_2.json"
  ]

testSubmit :: String -> FilePath -> TestTree
testSubmit lib input = testService ("submit/" ++ lib) flags exp
 where
  flags = [ "-H", "Content-Type: application/json"
          ,  "--data", '@' : input ]
  exp   = replaceExtension input "exp"

testService :: String -> [String] -> FilePath -> TestTree
testService endpoint options file = testCase ("Testing: " ++ file) $ do
    out <- readProcess "curl" (options ++ ["-s", url]) ""
    exp <- readFile file
    out @?= exp
  where
    url = "http://localhost:8081/" ++ endpoint


text:
package jasenmoloy.wirelesscontrol.presentation.ui;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

import junit.framework.Assert;

import jasenmoloy.wirelesscontrol.R;
import jasenmoloy.wirelesscontrol.application.data.GeofenceData;
import jasenmoloy.wirelesscontrol.application.debug.Debug;
import jasenmoloy.wirelesscontrol.adapters.AddGeofencePresenter;
import jasenmoloy.wirelesscontrol.adapters.AddGeofencePresenterImpl;
import jasenmoloy.wirelesscontrol.adapters.AddGeofenceView;

/**
 * Created by jasenmoloy on 2/17/16.
 */
public class AddGeofenceActivity extends AppCompatActivity implements AddGeofenceView, GoogleMap.SnapshotReadyCallback {
    /// ----------------------
    /// Class Fields
    /// ----------------------

    private static final String TAG = AddGeofenceActivity.class.getSimpleName();
    private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 1;

    private class GeofenceNameTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //Stubbed
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //Stubbed
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(validateUserNameInput(s.toString()))
                UIHelper.enableButton(mSaveButton);
            else
                UIHelper.disableButton(mSaveButton);
        }
    }

    /// ----------------------
    /// Object Fields
    /// ----------------------

    private GoogleMap mMap;
    private LocationManager mLocationManager;
    private Location mLocation;

    private GeofenceMarker mGeofence;
    private EditText mGeofenceName;
    private Button mSaveButton;

    private AddGeofencePresenter mPresenter;

    private GeofenceData mGeofenceSaveData;

    private int mStandardGeofenceRadius; //JAM TODO: Should be moved to a global resources location

    /// ----------------------
    /// Public Methods
    /// ----------------------

    @Override
    public void onCameraChange(CameraPosition cameraPos) {
        UpdateGeofenceMarker(cameraPos.target);
    }

    public void onSaveButtonClick(View view) {
        String displayName = mGeofenceName.getText().toString().trim(); //Trim any trailing whitespace.

        //JAM Convert user's input into something better for IDs and filenames
        String formattedName = createFormattedName(displayName);

        mGeofenceSaveData = new GeofenceData(
                displayName,
                formattedName,
                mGeofence.getPosition(),
                mGeofence.getRadius()
        );

        //JAM Clean and format the map before taking a snapshot
        try {
            mMap.setMyLocationEnabled(false);
            mMap.moveCamera(CameraUpdateFactory.zoomTo(mMap.getMaxZoomLevel() * 0.8f));

            //JAM wait a moment until the location marker disappears from the map before taking a snapshot
            Thread.sleep(200L); //JAM TODO Resources file?
        }
        catch(SecurityException secEx) {
            Debug.logError(TAG, secEx.getMessage());
        }
        catch(InterruptedException ex) {
            Debug.logWarn(TAG, ex.getMessage());
        }

        //JAM Grab screenshot of the map
        mMap.snapshot(this);
    }

    @Override
    public void onGeofenceSaveSuccess() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); //Prevents reinstantiation if the activity already exists
        startActivity(intent);

        //We no longer have use for this activity to lets destroy it
        finish();

        //Display a toast to the user to inform them the save was successful!
        UIHelper.displayToast(this, Toast.LENGTH_SHORT, getString(R.string.addgeofence_toast_successful));
    }

    @Override
    public void onGeofenceSaveError() {
        //Notify the user that an error has occurred
        UIHelper.displayOkDialog(this,
                R.string.addgeofence_error_dialog_title,
                R.string.addgeofence_error_dialog_body,
                R.string.general_button_text_error,
                true,
                null);

        //JAM TODO: Depending on the error, stay on the current screen and attempt to have the user save again (if possible).
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        //Initialize map to begin in Los Angeles to start.
        mMap.moveCamera(
                CameraUpdateFactory.newLatLngZoom(
                        new LatLng(34.0500, -118.2500), mMap.getMaxZoomLevel() * 0.8f)
        );

        //Initialize new geofence marker that will be placed
        initGeofenceMarker(mMap.getCameraPosition().target);

        //Check and/or request permission if the app can use the user's location.
        if ( ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSION_ACCESS_FINE_LOCATION);
        }
        else {
            mPresenter.initializeMapPosition();
        }
    }

    @Override
    public void onSnapshotReady(Bitmap map) {
        if(map == null) {
            //JAM Enable your location again
            try {
                mMap.setMyLocationEnabled(true);
            }
            catch(SecurityException secEx) {
                Debug.logError(TAG, secEx.getMessage());
            }

            onGeofenceSaveError();
            return;
        }

        //Add bitmap to geofence save data
        mGeofenceSaveData.addBitmap(map);

        //Let presenter know we're ready to save the data
        mPresenter.saveGeofence(mGeofenceSaveData);
        mGeofenceSaveData = null;
    }

    public void initializeMyLocationOnMap(Location lastKnownLocation)
    {
        try {
            mMap.setMyLocationEnabled(true);

            if( mLocationManager == null ) {
                mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                mLocation = lastKnownLocation;
            }

            //Get the user's current position
            LatLng currentPos = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentPos, mMap.getMaxZoomLevel() * 0.8f);

            //Update the marker to that position before the users see the map animation
            UpdateGeofenceMarker(currentPos);

            //Update the camera to point to where the user is located and zoom in a bit.
            mMap.animateCamera(cameraUpdate);
        }
        catch(SecurityException secEx) {
            //TODO Request permissions to access the user's location.
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    public void displayLocationNotFoundToast() {
        UIHelper.displayToast(this, Toast.LENGTH_SHORT, getString(R.string.addgeofence_toast_location_not_found));
    }

    /// ----------------------
    /// Protected Methods
    /// ----------------------

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

        mStandardGeofenceRadius = getResources().getInteger(R.integer.standard_geofence_radius);

        //Set up the activity's view
        setContentView(R.layout.activity_addgeofence);

        //Initialize any viewGroup related fields
        mGeofenceName = (EditText) findViewById(R.id.addgeofence_name);
        mGeofenceName.addTextChangedListener(new GeofenceNameTextWatcher());

        //Grab the "Save" button
        mSaveButton = (Button) findViewById(R.id.addgeofence_savebutton);

        //Start the button as not clickable we don't have a name to save just yet
        UIHelper.disableButton(mSaveButton);

        //Set the toolbar according to the activity layout
        Toolbar myChildToolbar =
                (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(myChildToolbar);

        //Enable the "Up" button to go back to the parent activity
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.addgeofence_geofencemap);
        mapFragment.getMapAsync(this);

        mPresenter = new AddGeofencePresenterImpl(this, this);
        mPresenter.onCreate();
        mPresenter.registerReceiver(LocalBroadcastManager.getInstance(this));
    }

    @Override
    protected void onStart() {
        //Stubbed
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Stubbed
    }

    @Override
    protected void onPause() {
        //Stubbed
        super.onPause();
    }

    @Override
    protected void onStop() {
        //Stubbed
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mPresenter.onDestroy();
        super.onDestroy();
    }

    /// ----------------------
    /// Private Methods
    /// ----------------------

    private void initGeofenceMarker(LatLng position) {
        //Set the listener for our map.
        mMap.setOnCameraChangeListener(this);

        mGeofence = new GeofenceMarker(position, mStandardGeofenceRadius);
        mGeofence.addToMap(mMap);
    }

    private void UpdateGeofenceMarker(LatLng position) {
        Assert.assertNotNull(position);

        mGeofence.updateMarker(position, mStandardGeofenceRadius);
    }

    private boolean validateUserNameInput(String userInput) {
        if(userInput.length() == 0 || userInput.length() > 100)
            return false;

        return true;
    }

    private String createFormattedName(String str) {
        return str.trim().replaceAll("[^a-zA-Z0-9-]", "_");
    }
}


text:
using namespace concurrency;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Devices::AllJoyn;
using namespace digital::pervasive::sample::relaynode;

std::map<alljoyn_interfacedescription, WeakReference*> relaynodeConsumer::SourceInterfaces;

relaynodeConsumer::relaynodeConsumer(AllJoynBusAttachment^ busAttachment)
    : m_busAttachment(busAttachment),
    m_proxyBusObject(nullptr),
    m_busObject(nullptr),
    m_sessionListener(nullptr),
    m_sessionId(0)
{
    m_weak = new WeakReference(this);
    m_signals = ref new relaynodeSignals();
    m_nativeBusAttachment = AllJoynHelpers::GetInternalBusAttachment(m_busAttachment);
}

relaynodeConsumer::~relaynodeConsumer()
{
    AllJoynBusObjectManager::ReleaseBusObject(m_nativeBusAttachment, AllJoynHelpers::PlatformToMultibyteString(ServiceObjectPath).data());
    if (SessionListener != nullptr)
    {
        alljoyn_busattachment_setsessionlistener(m_nativeBusAttachment, m_sessionId, nullptr);
        alljoyn_sessionlistener_destroy(SessionListener);
    }
    if (nullptr != ProxyBusObject)
    {
        alljoyn_proxybusobject_destroy(ProxyBusObject);
    }
    delete m_weak;
}

void relaynodeConsumer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
{
    if (sessionId == m_sessionId)
    {
        AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason));
        SessionLost(this, args);
    }
}

void relaynodeConsumer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
    if (sessionId == m_sessionId)
    {
        auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
        SessionMemberAdded(this, args);
    }
}

void relaynodeConsumer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
    if (sessionId == m_sessionId)
    {
        auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
        SessionMemberRemoved(this, args);
    }
}

QStatus relaynodeConsumer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler)
{
    alljoyn_interfacedescription_member member;
    if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
    {
        return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
    }

    return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL);
}

IAsyncOperation<relaynodeJoinSessionResult^>^ relaynodeConsumer::JoinSessionAsync(
    _In_ AllJoynServiceInfo^ serviceInfo, _Inout_ relaynodeWatcher^ watcher)
{
    return create_async([serviceInfo, watcher]() -> relaynodeJoinSessionResult^
    {
        auto result = ref new relaynodeJoinSessionResult();
        result->Status = AllJoynStatus::Ok;
        result->Consumer = nullptr;

        result->Consumer = ref new relaynodeConsumer(watcher->BusAttachment);
        result->Status = result->Consumer->JoinSession(serviceInfo);

        return result;
    });
}

IAsyncOperation<relaynodeSetStateResult^>^ relaynodeConsumer::SetStateAsync(_In_ int32 interfaceMemberRelayId, _In_ byte interfaceMemberState)
{
    return create_async([this, interfaceMemberRelayId, interfaceMemberState]() -> relaynodeSetStateResult^
    {
        auto result = ref new relaynodeSetStateResult();

        alljoyn_message message = alljoyn_message_create(m_nativeBusAttachment);
        size_t argCount = 2;
        alljoyn_msgarg inputs = alljoyn_msgarg_array_create(argCount);

        TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(inputs, 0), "i", interfaceMemberRelayId);
        TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(inputs, 1), "y", interfaceMemberState);

        QStatus status = alljoyn_proxybusobject_methodcall(
            ProxyBusObject,
            "digital.pervasive.sample.relaynode",
            "SetState",
            inputs,
            argCount,
            message,
            c_MessageTimeoutInMilliseconds,
            0);
        result->Status = static_cast<int>(status);

        alljoyn_message_destroy(message);
        alljoyn_msgarg_destroy(inputs);

        return result;
    });
}
IAsyncOperation<relaynodeGetStateResult^>^ relaynodeConsumer::GetStateAsync(_In_ int32 interfaceMemberRelayId)
{
    return create_async([this, interfaceMemberRelayId]() -> relaynodeGetStateResult^
    {
        auto result = ref new relaynodeGetStateResult();

        alljoyn_message message = alljoyn_message_create(m_nativeBusAttachment);
        size_t argCount = 1;
        alljoyn_msgarg inputs = alljoyn_msgarg_array_create(argCount);

        TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(inputs, 0), "i", interfaceMemberRelayId);

        QStatus status = alljoyn_proxybusobject_methodcall(
            ProxyBusObject,
            "digital.pervasive.sample.relaynode",
            "GetState",
            inputs,
            argCount,
            message,
            c_MessageTimeoutInMilliseconds,
            0);
        result->Status = static_cast<int>(status);
        if (ER_OK == status)
        {
            result->Status = AllJoynStatus::Ok;
            byte argument0;
            status = static_cast<QStatus>(TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "y", &argument0));
            result->State = argument0;

            if (status != ER_OK)
            {
                result->Status = static_cast<int>(status);
            }
        }
        else if (ER_BUS_REPLY_IS_ERROR_MESSAGE == status)
        {
            alljoyn_msgarg errorArg = alljoyn_message_getarg(message, 1);
            if (nullptr != errorArg)
            {
                uint16 errorStatus;
                status = alljoyn_msgarg_get_uint16(errorArg, &errorStatus);
                if (ER_OK == status)
                {
                    status = static_cast<QStatus>(errorStatus);
                }
            }
            result->Status = static_cast<int>(status);
        }

        alljoyn_message_destroy(message);
        alljoyn_msgarg_destroy(inputs);

        return result;
    });
}

void relaynodeConsumer::OnPropertyChanged(_In_ alljoyn_proxybusobject obj, _In_ PCSTR interfaceName, _In_ const alljoyn_msgarg changed, _In_ const alljoyn_msgarg invalidated)
{
    UNREFERENCED_PARAMETER(obj);
    UNREFERENCED_PARAMETER(interfaceName);
    UNREFERENCED_PARAMETER(changed);
    UNREFERENCED_PARAMETER(invalidated);
}

void relaynodeConsumer::CallButtonPressedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
    auto source = SourceInterfaces.find(member->iface);
    if (source == SourceInterfaces.end())
    {
        return;
    }

    auto consumer = source->second->Resolve<relaynodeConsumer>();
    if (consumer->Signals != nullptr)
    {
        auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
        auto eventArgs = ref new relaynodeButtonPressedReceivedEventArgs();
        eventArgs->MessageInfo = callInfo;

        consumer->Signals->CallButtonPressedReceived(consumer->Signals, eventArgs);
    }
}

void relaynodeConsumer::CallRelayStateChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
    auto source = SourceInterfaces.find(member->iface);
    if (source == SourceInterfaces.end())
    {
        return;
    }

    auto consumer = source->second->Resolve<relaynodeConsumer>();
    if (consumer->Signals != nullptr)
    {
        auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
        auto eventArgs = ref new relaynodeRelayStateChangedReceivedEventArgs();
        eventArgs->MessageInfo = callInfo;

        int32 argument0;
        TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "i", &argument0);

        eventArgs->RelayId = argument0;
        byte argument1;
        TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 1), "y", &argument1);

        eventArgs->State = argument1;

        consumer->Signals->CallRelayStateChangedReceived(consumer->Signals, eventArgs);
    }
}

int32 relaynodeConsumer::JoinSession(_In_ AllJoynServiceInfo^ serviceInfo)
{
    alljoyn_sessionlistener_callbacks callbacks =
    {
        AllJoynHelpers::SessionLostHandler<relaynodeConsumer>,
        AllJoynHelpers::SessionMemberAddedHandler<relaynodeConsumer>,
        AllJoynHelpers::SessionMemberRemovedHandler<relaynodeConsumer>
    };

    alljoyn_busattachment_enableconcurrentcallbacks(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment));

    SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak);
    alljoyn_sessionopts sessionOpts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, true, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);

    std::vector<char> sessionNameUtf8 = AllJoynHelpers::PlatformToMultibyteString(serviceInfo->UniqueName);
    RETURN_IF_QSTATUS_ERROR(alljoyn_busattachment_joinsession(
        m_nativeBusAttachment,
        &sessionNameUtf8[0],
        serviceInfo->SessionPort,
        SessionListener,
        &m_sessionId,
        sessionOpts));
    alljoyn_sessionopts_destroy(sessionOpts);

    ServiceObjectPath = serviceInfo->ObjectPath;
    std::vector<char> objectPath = AllJoynHelpers::PlatformToMultibyteString(ServiceObjectPath);

    if (objectPath.empty())
    {
        return AllJoynStatus::Fail;
    }

    ProxyBusObject = alljoyn_proxybusobject_create(m_nativeBusAttachment, &sessionNameUtf8[0], &objectPath[0], m_sessionId);
    if (nullptr == ProxyBusObject)
    {
        return AllJoynStatus::Fail;
    }

    alljoyn_interfacedescription description = alljoyn_busattachment_getinterface(m_nativeBusAttachment, "digital.pervasive.sample.relaynode");
    if (nullptr == description)
    {
        return AllJoynStatus::Fail;
    }

    unsigned int noneMechanismIndex = 0;
    bool authenticationMechanismsContainsNone = m_busAttachment->AuthenticationMechanisms->IndexOf(AllJoynAuthenticationMechanism::None, &noneMechanismIndex);
    QCC_BOOL interfaceIsSecure = alljoyn_interfacedescription_issecure(description);

    // If the current set of AuthenticationMechanisms supports authentication,
    // determine whether to secure the connection.
    if (AllJoynHelpers::CanSecure(m_busAttachment->AuthenticationMechanisms))
    {
        // Secure the connection if the org.alljoyn.Bus.Secure XML annotation
        // is specified, or if None is not present in AuthenticationMechanisms.
        if (!authenticationMechanismsContainsNone || interfaceIsSecure)
        {
            alljoyn_proxybusobject_secureconnection(ProxyBusObject, QCC_FALSE);
        }
    }
    else
    {
        // If the current set of AuthenticationMechanisms does not support authentication
        // but the interface requires security, report an error.
        if (interfaceIsSecure)
        {
            return static_cast<int32>(ER_BUS_NO_AUTHENTICATION_MECHANISM);
        }
    }

    RETURN_IF_QSTATUS_ERROR(AllJoynBusObjectManager::GetBusObject(m_nativeBusAttachment, AllJoynHelpers::PlatformToMultibyteString(ServiceObjectPath).data(), &m_busObject));
    RETURN_IF_QSTATUS_ERROR(alljoyn_proxybusobject_addinterface(ProxyBusObject, description));

    if (!AllJoynBusObjectManager::BusObjectIsRegistered(m_nativeBusAttachment, m_busObject))
    {
        RETURN_IF_QSTATUS_ERROR(alljoyn_busobject_addinterface(BusObject, description));
    }

    QStatus result = AddSignalHandler(
        m_nativeBusAttachment,
        description,
        "ButtonPressed",
        [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallButtonPressedSignalHandler(member, message); });
    if (result != ER_OK)
    {
        return static_cast<int32>(result);
    }
    result = AddSignalHandler(
        m_nativeBusAttachment,
        description,
        "RelayStateChanged",
        [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallRelayStateChangedSignalHandler(member, message); });
    if (result != ER_OK)
    {
        return static_cast<int32>(result);
    }

    SourceInterfaces[description] = m_weak;
    RETURN_IF_QSTATUS_ERROR(AllJoynBusObjectManager::TryRegisterBusObject(m_nativeBusAttachment, BusObject, true));
    m_signals->Initialize(BusObject, m_sessionId);

    return AllJoynStatus::Ok;
}


text:
package org.zstack.sdk.iam2.api;

public class RemoveIAM2ProjectLoginExpiredResult {

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="Hello">Hello World, Click Me!</string>
    <string name="ApplicationName">TwitterSpalsh</string>
</resources>


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using System.Net;
using System.Threading;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.RecoveryServices.Backup.Properties;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;

namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.ServiceClientAdapterNS
{
    /// <summary>
    /// Basic utilities and initializations for client proxy
    /// </summary>
    public class ClientProxyBase
    {
        protected IAzureContext Context;

        /// <summary>
        /// Client request id.
        /// </summary>
        protected string ClientRequestId;

        /// <summary>
        /// Cancellation Token Source
        /// </summary>
        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        public CancellationToken CmdletCancellationToken;

        /// <summary>
        /// AzureContext based ctor
        /// </summary>
        /// <param name="context">Azure Context</param>
        public ClientProxyBase(IAzureContext context)
        {
            Context = context;

            RefreshClientRequestId();

            // Temp code to be able to test internal env.
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        }

        /// <summary>
        /// Assigns a new client request ID to be used in each service client call - for logging purposes
        /// </summary>
        public void RefreshClientRequestId()
        {
            ClientRequestId = Guid.NewGuid().ToString() + "-" + DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ssZ") + "-PS";
        }

        /// <summary>
        /// Gets the client request ID set by the context
        /// </summary>
        /// <returns>Client request ID</returns>
        public string GetClientRequestId()
        {
            return ClientRequestId;
        }

        /// <summary>
        /// Gets Recovery Services vault name from the vault context
        /// </summary>
        /// <returns></returns>
        public string GetResourceName()
        {
            if (string.IsNullOrEmpty(PSRecoveryServicesClient.arsVault.Name))
            {
                throw new ArgumentException(Resources.SetVaultContextFirst);
            }
            return PSRecoveryServicesClient.arsVault.Name;
        }

        /// <summary>
        /// Gets Recovery Services Vault's resource group name from the vault context
        /// </summary>
        /// <returns></returns>
        public string GetResourceGroupName()
        {
            if (string.IsNullOrEmpty(PSRecoveryServicesClient.arsVault.ResourceGroupName))
            {
                throw new ArgumentException(Resources.SetVaultContextFirst);
            }
            return PSRecoveryServicesClient.arsVault.ResourceGroupName;
        }

        /// <summary>
        /// Gets Recovery Services Vault's location from the vault context
        /// </summary>
        /// <returns></returns>
        public string GetResourceLocation()
        {
            if (string.IsNullOrEmpty(PSRecoveryServicesClient.arsVault.Location))
            {
                throw new ArgumentException(Resources.SetVaultContextFirst);
            }
            return PSRecoveryServicesClient.arsVault.Location;
        }
    }
}


text:
Stacey is a simple flat-file cms that takes content from `.txt` files, image files and implied directory structure and generates a website.

If you look in the `/content` and `/templates` folders, you should get the general idea of how it all works.

## Installation

Copy to server, `chmod 777 app/_cache`.

If you want clean urls, `mv htaccess .htaccess`

## Documentation

Stacey app's original documentation and more will be available on our wiki, right now it's in the content.