text:
"""Reload operating system on a server."""
# :license: MIT, see LICENSE for more details.

import click

import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers

@click.command(cls=SoftLayer.CLI.command.SLCommand, )
@click.argument('identifier')
@click.option('--postinstall', '-i',
              help=("Post-install script to download (Only HTTPS executes, HTTP leaves file in /root"))
@helpers.multi_option('--key', '-k', help="SSH keys to add to the root user")
@click.option('--lvm', '-l', is_flag=True, default=False, show_default=True,
              help="A flag indicating that the provision should use LVM for all logical drives.")
@environment.pass_env
def cli(env, identifier, postinstall, key, lvm):
    """Reload operating system on a server."""

    hardware = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
    key_list = []
    if key:
        for single_key in key:
            resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
            key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
            key_list.append(key_id)
    if not (env.skip_confirmations or formatting.no_going_back(hardware_id)):
        raise exceptions.CLIAbort('Aborted')

    hardware.reload(hardware_id, postinstall, key_list, lvm)


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\Throwable\Exception;

use PHPUnit\Framework\TestCase;

/**
 * @covers \Nelmio\Alice\Throwable\Exception\LogicExceptionFactory
 */
class LogicExceptionFactoryTest extends TestCase
{
    public function testCreateForUncallableMethod()
    {
        $exception = LogicExceptionFactory::createForUncallableMethod('foo');

        $this->assertEquals(
            'By its nature, "foo()" should not be called.',
            $exception->getMessage()
        );
        $this->assertEquals(0, $exception->getCode());
        $this->assertNull($exception->getPrevious());
    }

    public function testCreateForCannotDenormalizerForChainableFixtureBuilderDenormalizer()
    {
        $exception = LogicExceptionFactory::createForCannotDenormalizerForChainableFixtureBuilderDenormalizer('foo');

        $this->assertEquals(
            'As a chainable denormalizer, "foo" should be called only if "::canDenormalize() returns true. Got '
            .'false instead.',
            $exception->getMessage()
        );
        $this->assertEquals(0, $exception->getCode());
        $this->assertNull($exception->getPrevious());
    }

    public function testCreateForCannotHaveBothConstructorAndFactory()
    {
        $exception = LogicExceptionFactory::createForCannotHaveBothConstructorAndFactory();

        $this->assertEquals(
            'Cannot use the fixture property "__construct" and "__factory" together.',
            $exception->getMessage()
        );
        $this->assertEquals(0, $exception->getCode());
        $this->assertNull($exception->getPrevious());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.lisicnu.log4android.appender;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.github.lisicnu.log4android.Level;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

/**
 * An appender to log to a file in on the SDCard.
 *
 * @author Johan Karlsson
 * @author Dan Walkes
 */
public class FileAppender extends AbstractAppender {
    private static final String TAG = FileAppender.class.getSimpleName();

    public static final String DEFAULT_FILENAME = "autoGen";
    public static final String DEFUALT_FILE_EXT = ".log";

    /**
     * In configuration file, we have defined : start with "/" means absolute
     * path. otherwise means related to mnt/sdcard/logs/
     */
    private String fileName = DEFAULT_FILENAME + DEFUALT_FILE_EXT;

    private PrintWriter writer;

    private File mLogFile = null;

    Context mContext = null;

    /**
     * e.g. [auto]

     * %a : append file or create new file.

     * %f : use date time format. i.e. "yyyyMMddHHmmss".

     * %p : use prefix and plus index to format.

     * %s : wrap file size. unit is M. without unit.

     * usage: %p, when use this parameter, key[File] will be recognized as
     * prefix.

     * # result: prefix0.log, prefix1.log.

     * TODO
     */
    class WrapFormatter {
        final static long NO_WRAP = 0;
        /**
         * wrap file's size. in byte. default is 0, means not wrap.
         */
        long wrapSize = NO_WRAP;

        /**
         * file name formatter, only usefull when {@link #nameFormat}'s value is
         * {@link #NAME_FORMAT_DATE}
         */
        String formatter = "";

        /**
         * wrap file or not.
         *
         * @return
         */
        public boolean isWrapFile() {
            return nameFormat != NAME_FORMAT_NONE;
        }

        /**
         * append file or create new.
         */
        boolean appendFile = false;

        final static int NAME_FORMAT_NONE = 0;
        final static int NAME_FORMAT_DATE = 1;
        final static int NAME_FORMAT_PLUSINDEX = 2;
        int nameFormat = NAME_FORMAT_NONE;

        final static char PARA_CHAR = '%';
        final static String SUPPORT_PARA_FORMAT_DATE = "%f"; // date format
        final static String SUPPORT_PARA_WRAP_SIZE = "%s"; // size in M.
        final static String SUPPORT_PARA_FORMAT_PLUSINDEX = "%p"; // auto add.
        final static String SUPPORT_PARA_FILE_APPEND = "%a"; // append file.

        void wrap(String wrapStr) {
            if (wrapStr == null || wrapStr.length() == 0)
                return;

            wrapSize = NO_WRAP;
            nameFormat = NAME_FORMAT_NONE;

            int idx = wrapStr.indexOf(PARA_CHAR);
            int mLen = wrapStr.length();
            while (idx > -1 && idx < mLen) {
                int nextIdx = wrapStr.indexOf(PARA_CHAR, idx + 1);

                if (nextIdx == -1) {
                    nextIdx = mLen;
                }

                String tmp = wrapStr.substring(idx, nextIdx);
                if (tmp.startsWith(SUPPORT_PARA_FORMAT_DATE)) {
                    String tt = tmp.replace(SUPPORT_PARA_FORMAT_DATE, "").replace("-", "").trim();
                    if (tt.length() == 0) {
                        formatter = "yyyyMMdd";
                    } else {
                        formatter = tt;
                    }
                    nameFormat = NAME_FORMAT_DATE;
                } else if (tmp.startsWith(SUPPORT_PARA_WRAP_SIZE)) {
                    // size
                    String tt = tmp.replace(SUPPORT_PARA_WRAP_SIZE, "").replace("-", "").trim();
                    if (!tt.isEmpty()) {
                        try {
                            wrapSize = (long) (Float.parseFloat(tt.replace("", "")) * 1024 * 1024);
                        } catch (Exception e) {
                        }
                    }
                } else if (tmp.startsWith(SUPPORT_PARA_FORMAT_PLUSINDEX)) {
                    nameFormat = NAME_FORMAT_PLUSINDEX;
                } else if (tmp.startsWith(SUPPORT_PARA_FILE_APPEND)) {
                    appendFile = true;
                }

                idx = nextIdx;
            }
        }
    }

    final WrapFormatter wraper = new WrapFormatter();

    /**
     * when wrap file, this name will be used.
     *
     * @param wrapFormat
     */
    public void setWrapFormat(String wrapFormat) {
        wraper.wrap(wrapFormat);
//        Log.v(TAG, wrapFormat);
    }

    /**
     * Create a file appender using the specified application context. Note:
     * your application must hold android.permission.WRITE_EXTERNAL_STORAGE to
     * be able to access the SDCard.
     *
     * @param c
     */
    public FileAppender(Context c) {
        mContext = c;
    }

    /**
     * Create a file appender without application context. The logging file will
     * be placed in the root folder and will not be removed when your
     * application is removed. Use FileAppender(Context) to create a log that is
     * automatically removed when your application is removed Note: your
     * application must hold android.permission.WRITE_EXTERNAL_STORAGE to be
     * able to access the SDCard.
     */
    public FileAppender() {
    }

    /**
     * @see com.github.lisicnu.log4android.appender.AbstractAppender#open()
     */
    @Override
    public synchronized void open() throws IOException {
        File logFile = getLogFile();
        if (logFile == null) return;

        Log.i(TAG, "log file:" + logFile.getAbsolutePath());
        logOpen = false;

        if (!logFile.exists()) {
            if (!logFile.createNewFile()) {
                Log.e(TAG, "Unable to create new log file");
            }
        }

        curLogFile = logFile.getAbsolutePath();
        Log.v(TAG, curLogFile);

        FileOutputStream fileOutputStream = new FileOutputStream(logFile, wraper.appendFile);

        writer = new PrintWriter(fileOutputStream);
        writer.println("\r\n##########################################################\r\n");
        logOpen = true;
    }

    String curLogFile = "";

    public String getCurLogFile() {
        return curLogFile;
    }

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

    @Override
    public synchronized void close() throws IOException {

        Log.i(TAG, "Closing the FileAppender");

        if (writer != null) {
            writer.close();
        }
    }

    @Override
    public synchronized void doLog(String clientID, String name, long time, Level level,
                                   Object message, Throwable throwable) {
        if (logOpen && formatter != null && writer != null) {
            writer.println(formatter.format(clientID, name, time, level, message, throwable));
            writer.flush();

            if (throwable != null) {
                throwable.printStackTrace();
            }

            if (wraper != null && wraper.isWrapFile()
                    && wraper.wrapSize != WrapFormatter.NO_WRAP
                    && mLogFile.length() > wraper.wrapSize) {
                try {
                    close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    open();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else if (formatter == null) {
            Log.e(TAG, "Please set a formatter.");
        }

    }

    public long getLogSize() {
        return Appender.SIZE_UNDEFINED;
    }

    public void setContext(Context context) {
        this.mContext = context;
    }

    /**
     * Set the filename to be used
     *
     * @param fileName the filename to log to
     */
    public void setFileName(String fileName) {
        // TODO Throw IllegalArgumentException if the filename is null.
        if (fileName != null) {
            this.fileName = fileName;
        }
    }

    /**
     * Android 1.6-2.1 used {@link android.os.Environment#getExternalStorageDirectory()} to
     * return the (root) external storage directory. Folders in this subdir were
     * shared by all applications and were not removed when the application was
     * deleted. Starting with andriod 2.2, Context.getExternalFilesDir() is
     * available. This is an external directory available to the application
     * which is removed when the application is removed.
     *

     * This implementation uses Context.getExternalFilesDir() if available, if
     * not available uses {@link android.os.Environment#getExternalStorageDirectory()}.
     *
     * @return a File object representing the external storage directory used by
     * this device or null if the subdir could not be created or proven
     * to exist
     */
    protected synchronized File getExternalStorageDirectory() {

        File externalStorageDirectory;
        if (Build.VERSION.SDK_INT >= 8 && mContext != null) {
            externalStorageDirectory = mContext.getExternalCacheDir();
        } else {
            externalStorageDirectory = Environment.getExternalStorageDirectory();
        }

        if (externalStorageDirectory != null) {
            if (!externalStorageDirectory.exists()) {
                if (!externalStorageDirectory.mkdirs()) {
                    externalStorageDirectory = null;
                    Log.e(TAG, "mkdirs failed on externalStorageDirectory "
                            + externalStorageDirectory);
                }
            }
        }
        return externalStorageDirectory;
    }

    /**
     * 非wrap 的情况下, 如果不是以 /mnt/sdcard/, mnt/sdcard/ 开头的直接定位到此
     *
     * @return
     */
    private File getStorageDir() {
        String externalStorageState = Environment.getExternalStorageState();
        if (!externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }

        // 默认在外置程序包下面.logs 文件夹
        File file = getExternalStorageDirectory();

        if (fileName.startsWith("/")) {
            File tmp = new File(fileName);
            if (tmp.isDirectory())
                return tmp;

            return new File(file, getFileNameWithoutExtension(fileName));
        }

        String tmp = Environment.getExternalStorageDirectory().getPath();
        if (fileName.startsWith(tmp)) {
            file = new File(file, fileName.replace(tmp, ""));
            return file;
        }

        file = new File(file, "logs");
        file.mkdirs();
        return file;
    }

    public static String getFileNameWithoutExtension(String fileName) {

        if (fileName == null)
            return null;
        if (fileName.isEmpty())
            return "";

        String result = fileName;
        int idx = fileName.lastIndexOf(File.separator);
        if (idx != -1) {
            result = result.substring(idx + 1);
        }
        idx = result.lastIndexOf(".");
        if (idx != -1) {
            result = result.substring(0, idx);
        }
        return result;
    }

    public static String getFileName(String fileName) {

        if (fileName == null)
            return null;
        if (fileName.isEmpty())
            return "";

        String result = fileName;
        int idx = fileName.lastIndexOf(File.separator);
        if (idx != -1) {
            result = result.substring(idx + 1);
        }
        return result;
    }

    /**
     * get in parameters date formatted result without file extension.
     *
     * @return
     */
    String getTimeFileName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(wraper.formatter);
        return dateFormat.format(Calendar.getInstance().getTime());
    }

    /**
     * if the file hasn't been settled, will auto set to external storage.
     *
     * @return the log file used to log to external storage
     */
    public synchronized File getLogFile() {

        File dir = getStorageDir();
        if (dir == null) {
            Log.e(TAG, "Unable to open log file from external storage");
            return null;
        }

        switch (wraper.nameFormat) {
            case WrapFormatter.NAME_FORMAT_DATE: {
                String file = getFormattedNameWithDate(dir);
                mLogFile = new File(dir, file);
            }
            break;
            case WrapFormatter.NAME_FORMAT_PLUSINDEX: {
                String file = getFormattedNameWithPlusIndex(dir);
                mLogFile = new File(dir, file);
            }
            break;
            case WrapFormatter.NAME_FORMAT_NONE: {
                mLogFile = new File(dir, getFileName(fileName).concat(DEFUALT_FILE_EXT));
            }
            break;
            default: {
                mLogFile = new File(dir, getFileName(fileName).concat(DEFUALT_FILE_EXT));
            }
            break;
        }

        try {
            mLogFile.getParentFile().mkdirs();
            mLogFile.createNewFile();
        } catch (IOException e) {
            Log.e(TAG, "创建文件失败了..." + e.toString() + " mLogFile.getParentFile()");
        }

        return mLogFile;
    }

    public static String getRandomStr(int length) {
        String str = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        int mLen = str.length();
        StringBuffer sf = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(mLen);// 0~61
            sf.append(str.charAt(number));
        }
        return sf.toString();
    }

    private String getFormattedNameWithPlusIndex(File dir) {
        if (fileName == null || fileName.length() == 0) {
            fileName = getRandomStr(8);
        }

        String prefix = fileName;
        int start = 0;
        File[] files = dir.listFiles();
        String file = "";

        while (true) {
            file = prefix + start + DEFUALT_FILE_EXT;
            ++start;

            for (File tmp : files) {
                if (tmp.getAbsolutePath().endsWith(file)) {

                    if (!(wraper.wrapSize != WrapFormatter.NO_WRAP
                            && tmp.length() >= wraper.wrapSize)) break;
                }
            }

            break;
        }
        return file;
    }

    final static String FILE_APPEND_CHAR = "_";

    private String getFormattedNameWithDate(File dir) {

        String tmp = getTimeFileName();
        // less than zero means do not append index. otherwise plus index.
        int plusIndex = 0;

        File file;
        if (fileName == null || fileName.isEmpty()) {
            if (wraper.wrapSize <= WrapFormatter.NO_WRAP) {
                return tmp.concat(DEFUALT_FILE_EXT);
            }

            String t;
            do {
                t = tmp + FILE_APPEND_CHAR + (plusIndex++) + DEFUALT_FILE_EXT;
                file = new File(dir, t);
            } while (file.exists() && (file.length() >= wraper.wrapSize && wraper.wrapSize !=
                    WrapFormatter.NO_WRAP));

            return t;
        }

        tmp = getFileNameWithoutExtension(fileName) + tmp;
        String t;
        do {
            t = tmp + FILE_APPEND_CHAR + (plusIndex++) + DEFUALT_FILE_EXT;
            file = new File(dir, t);
        } while (file.exists() && (file.length() >= wraper.wrapSize && wraper.wrapSize !=
                WrapFormatter.NO_WRAP));

        tmp = t;

        return tmp;
    }
}


text:
DAVA_TESTCLASS (KeyedArchiveYamlTest)
{
    DAVA::RefPtr<DAVA::KeyedArchive> loadedArchive;
    DAVA::RefPtr<DAVA::KeyedArchive> testArchive;

    KeyedArchiveYamlTest()
        : loadedArchive(new DAVA::KeyedArchive())
        , testArchive(new DAVA::KeyedArchive())
    {
    }

    DAVA_TEST (TestFunction)
    {
        using namespace DAVA;

        const DAVA::String FILE_PATH("~res:/KeyedArchives/keyed_archive_original.yaml");
        const DAVA::String GENERATED_FILE_PATH("KeyedArchives/keyed_archive_created.yaml");
        //const DAVA::String GENERATED_FILE_PATH "~res:/KeyedArchives/keyed_archive_created.yaml"
        //const DAVA::String GENERATED_FILE_PATH "/Users/user/Documents/work/gitHub/dava.framework/Projects/UnitTests/Data/KeyedArchives/keyed_archive_created.yaml"

        const DAVA::String BOOLMAPID("mapNamebool");
        const DAVA::String INT32MAPID("mapNameint32");
        const DAVA::String UINT32MAPID("mapNameUInt32");
        const DAVA::String FLOATMAPID("mapNamefloat");
        const DAVA::String STRINGMAPID("mapNameString");
        const DAVA::String WSTRINGMAPID("mapNameWideString");
        const DAVA::String BYTEARRMAPID("mapNameByteArrey");
        const DAVA::String INT64MAPID("mapNameint64");
        const DAVA::String UINT64MAPID("mapNameUInt64");
        const DAVA::String VECTOR2MAPID("mapNamevector2");
        const DAVA::String VECTOR3MAPID("mapNameVector3");
        const DAVA::String VECTOR4MAPID("mapNameVector4");
        const DAVA::String MATRIX2MAPID("mapNameMatrix2");
        const DAVA::String MATRIX3MAPID("mapNameMatrix3");
        const DAVA::String MATRIX4MAPID("mapNameMatrix4");
        const DAVA::String KEYEDARCHMAPID("mapNameKArch");
        const DAVA::String INT8MAPID("mapNameInt8");
        const DAVA::String UINT8MAPID("mapNameUInt8");
        const DAVA::String INT16MAPID("mapNameInt16");
        const DAVA::String UINT16MAPID("mapNameUInt16");
        const DAVA::String FLOAT64MAPID("mapNameFloat64");
        const DAVA::String COLORMAPID("mapNameColor");
        const DAVA::String TESTKEY("testKey");

        bool loaded = false;

        loadedArchive->DeleteAllKeys();

        loaded = loadedArchive->LoadFromYamlFile(FILE_PATH);
        TEST_VERIFY(false != loaded);

        FilePath documentsPath = FileSystem::Instance()->GetCurrentDocumentsDirectory();
        FilePath generatedPath = documentsPath + GENERATED_FILE_PATH;

        FileSystem::Instance()->CreateDirectory(generatedPath.GetDirectory(), true);

        loadedArchive->SaveToYamlFile(generatedPath);

        ScopedPtr<KeyedArchive> loadedArchiveFromGeneratedFile(new KeyedArchive());
        loaded = loadedArchiveFromGeneratedFile->LoadFromYamlFile(generatedPath);

        TEST_VERIFY(false != loaded);

        TEST_VERIFY(*loadedArchive->GetVariant(BOOLMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(BOOLMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(INT32MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(INT32MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(UINT32MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(UINT32MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(FLOATMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(FLOATMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(STRINGMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(STRINGMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(WSTRINGMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(WSTRINGMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(BYTEARRMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(BYTEARRMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(INT64MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(INT64MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(UINT64MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(UINT64MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(VECTOR2MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(VECTOR2MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(VECTOR3MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(VECTOR3MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(VECTOR4MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(VECTOR4MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(MATRIX2MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(MATRIX2MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(MATRIX3MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(MATRIX3MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(MATRIX4MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(MATRIX4MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(KEYEDARCHMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(KEYEDARCHMAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(INT8MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(INT8MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(UINT8MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(UINT8MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(INT16MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(INT16MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(UINT16MAPID) == *loadedArchiveFromGeneratedFile->GetVariant(UINT16MAPID));
        TEST_VERIFY(*loadedArchive->GetVariant(COLORMAPID) == *loadedArchiveFromGeneratedFile->GetVariant(COLORMAPID));

        testArchive->SetFloat(TESTKEY, 999.0f);
        const VariantType* variantFloatPtr = testArchive->GetVariant(TESTKEY);

        testArchive->SetString(TESTKEY, "test string");
        const VariantType* variantStringPtr = testArchive->GetVariant(TESTKEY);

        VariantType variant;
        variant.SetBool(false);
        testArchive->SetVariant(TESTKEY, std::move(variant));
        const VariantType* variantPtr = testArchive->GetVariant(TESTKEY);

        TEST_VERIFY(variantFloatPtr == variantStringPtr);
        TEST_VERIFY(variantPtr == variantStringPtr);
        TEST_VERIFY(variant.GetType() == VariantType::TYPE_NONE);
    }

    DAVA_TEST (CheckCopy)
    {
        using namespace DAVA;

        KeyedArchive* arc1root = new KeyedArchive();

        const char* keySub = "sub";
        const char* keyUrl = "url";
        const char* keyInt = "i";
        const char* keyFloat = "d";

        const char* valueUrl = "https://any.com";
        const int64 valueInt = 42LL;
        const double valueFloat64 = 100.500;

        {
            KeyedArchive* arc2sub = new KeyedArchive();
            arc2sub->SetString(keyUrl, valueUrl);
            arc2sub->SetInt64(keyInt, valueInt);
            arc2sub->SetFloat64(keyFloat, valueFloat64);

            arc1root->SetArchive(keySub, arc2sub);

            SafeRelease(arc2sub);
        }

        {
            KeyedArchive* arc2sub = arc1root->GetArchive(keySub);
            TEST_VERIFY(arc2sub != nullptr);
            String cs = arc2sub->GetString(keyUrl);
            TEST_VERIFY(cs == valueUrl);
            int64 i = arc2sub->GetInt64(keyInt);
            TEST_VERIFY(i == valueInt);
            float64 f = arc2sub->GetFloat64(keyFloat);
            TEST_VERIFY(f == valueFloat64);

            // try call operator= for save keyedArchive
            arc1root->SetArchive(keySub, arc2sub);
        }
        // then check again all values
        {
            KeyedArchive* arc2sub = arc1root->GetArchive(keySub);
            TEST_VERIFY(arc2sub != nullptr);
            String cs = arc2sub->GetString(keyUrl);
            TEST_VERIFY(cs == valueUrl);
            int64 i = arc2sub->GetInt64(keyInt);
            TEST_VERIFY(i == valueInt);
            float64 f = arc2sub->GetFloat64(keyFloat);
            TEST_VERIFY(f == valueFloat64);
        }

        SafeRelease(arc1root);
    }
};


text:
package org.elasticsearch.index.query;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 */
public class IdsQueryParser implements QueryParser {

    public static final String NAME = "ids";

    @Inject
    public IdsQueryParser() {
    }

    @Override
    public String[] names() {
        return new String[]{NAME};
    }

    @Override
    public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
        XContentParser parser = parseContext.parser();

        List<BytesRef> ids = new ArrayList<>();
        Collection<String> types = null;
        String currentFieldName = null;
        float boost = 1.0f;
        String queryName = null;
        XContentParser.Token token;
        boolean idsProvided = false;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_ARRAY) {
                if ("values".equals(currentFieldName)) {
                    idsProvided = true;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        if ((token == XContentParser.Token.VALUE_STRING) ||
                                (token == XContentParser.Token.VALUE_NUMBER)) {
                            BytesRef value = parser.utf8BytesOrNull();
                            if (value == null) {
                                throw new QueryParsingException(parseContext, "No value specified for term filter");
                            }
                            ids.add(value);
                        } else {
                            throw new QueryParsingException(parseContext, "Illegal value for id, expecting a string or number, got: "
                                    + token);
                        }
                    }
                } else if ("types".equals(currentFieldName) || "type".equals(currentFieldName)) {
                    types = new ArrayList<>();
                    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                        String value = parser.textOrNull();
                        if (value == null) {
                            throw new QueryParsingException(parseContext, "No type specified for term filter");
                        }
                        types.add(value);
                    }
                } else {
                    throw new QueryParsingException(parseContext, "[ids] query does not support [" + currentFieldName + "]");
                }
            } else if (token.isValue()) {
                if ("type".equals(currentFieldName) || "_type".equals(currentFieldName)) {
                    types = ImmutableList.of(parser.text());
                } else if ("boost".equals(currentFieldName)) {
                    boost = parser.floatValue();
                } else if ("_name".equals(currentFieldName)) {
                    queryName = parser.text();
                } else {
                    throw new QueryParsingException(parseContext, "[ids] query does not support [" + currentFieldName + "]");
                }
            }
        }

        if (!idsProvided) {
            throw new QueryParsingException(parseContext, "[ids] query, no ids values provided");
        }

        if (ids.isEmpty()) {
            return Queries.newMatchNoDocsQuery();
        }

        if (types == null || types.isEmpty()) {
            types = parseContext.queryTypes();
        } else if (types.size() == 1 && Iterables.getFirst(types, null).equals("_all")) {
            types = parseContext.mapperService().types();
        }

        TermsQuery query = new TermsQuery(UidFieldMapper.NAME, Uid.createUidsForTypesAndIds(types, ids));
        query.setBoost(boost);
        if (queryName != null) {
            parseContext.addNamedQuery(queryName, query);
        }
        return query;
    }
}


text:
'use strict';

var mysql     = require( 'mysql' )
  , sqlstring = require( 'sqlstring' )
  , escapeId  = sqlstring.escapeId
  , escape    = sqlstring.escape
;

module.exports = init;

function init( rs ) {

var RS               = rs.RS
  , uuid             = RS.uuid
  , timestamp_string = RS.timestamp_string
  , Pipelet          = RS.Pipelet
  , Greedy           = RS.Greedy
  , Unique           = RS.Unique
  , Query            = RS.Query
  , extend           = RS.extend
  , class_of         = RS.class_of
  , is_array         = RS.is_array
  , clone            = extend.clone
  , object_diff      = RS.object_diff
  , RS_log           = RS.log
  , pretty           = RS_log.pretty
  , log              = RS_log.bind( null, 'mysql' )
  , de               = true
  , ug               = log
  , slice            = Array.prototype.slice
;

/* ----------------------------------------------------------------------------
    mysql_connections_set( options )

    Parameters:
    - options (optional Object): optional attributes:
      - mysql (Object): mysql npm module default connection options:
        https://www.npmjs.com/package/mysql#connection-options
*/
function MySQL_Connections_Set( options ) {
  Unique.call( this, [], options );
} // MySQL_Connections_Set()

Unique.Build( 'mysql_connections_set', MySQL_Connections_Set, function( Super ) {
  return {
    _add_value: function( t, connection ) {
      var that          = this
        , identity      = this._identity( connection )
        , mysql_options = extend( {}, this._options.mysql, connection.mysql )
      ;

      connection = extend( {}, connection );

      connection.mysql = extend( {}, mysql_options );

      // Hide paswword, preventing downstream traces from disclosing it in logs
      if( connection.mysql.password ) connection.mysql.password = '***';

      // !! Do not trace connection before hiding password to prevent having passwords in traces
      de&&ug( that._get_name( '_add_value' ) + 'adding connection:', identity );

      // Transactions are connection-based, shared by all pipelets sharing the same connection
      connection.transactions = {};

      connection.connected = false;

      // Add value immediately but don't emit anything downstream until connected to MySQL server
      that.__add_value( connection );

      t.emit_nothing();

      connect( function( error ) {
        if( ! error ) {
          de&&ug( that._get_name( '_add_value' ) + 'Connected to:', identity, connection.mysql );

          connection.connected = true;

          that.__emit_add( [ connection ] );
        }
      } );

      function connect( done ) {
        var mysql_connection = mysql.createConnection( mysql_options );

        de&&ug( that._get_name( 'connect' ) + identity, 'mysql:', connection.mysql );

        // Try to connect immediately
        mysql_connection.connect( function( error ) {
          if( error ) {
            log( that._get_name( 'connect' ) + 'Warning, while (re)connecting to mysql:', identity, ', error:', error );

            return on_error( error, done );
          }

          connection.mysql_connection = mysql_connection;

          mysql_connection.toJSON = function() { return 'mysql connection' };

          done( error );
        } );

        mysql_connection.on( 'error', function( error ) {
          log( that._get_name( 'on_error' ) + 'Warning on:', identity, ', error:', error );

          connection.connected = false;

          // Do not remove in a transaction, as we want to make sure that removal takes immediate effect downstream
          that.__emit_remove( [ connection ] );

          on_error( error, _on_error );

          function _on_error( error ) {
            if( ! error ) {
              de&&ug( that._get_name( 'on_error' ) + 'Reconnected to:', identity, connection.mysql );

              connection.connected = true;

              that.__emit_add( [ connection ] );
            }
          } // _on_error()
        } ); // on error

        function on_error( error, done ) {
          var timeout;

          switch( error.code ) {
            case 'PROTOCOL_CONNECTION_LOST':
            break;

            case 'ETIMEDOUT':
              timeout = 2000;
            break;

            case 'ECONNREFUSED':
            case 'EHOSTUNREACH':
              timeout = 10000;
            break;

            default:
              connection.mysql_connection = null;
              connection.error = error;

              log( that._get_name( 'on_error' ) + 'Fatal Error, code:', error.code, ', failed to (re)connect to:', identity, connection.mysql );

              done( error );

            return;
          }

          if( timeout ) {
            connection.set_timeout = setTimeout( try_again, 10000 );
          } else {
            try_again();
          }

          function try_again() {
            delete connection.set_timeout;

            connect( done );
          }
        } // on_error()
      } // connect()
    }, // _add_value()

    _remove_value: function( t, connection ) {
      var i = this._a_index_of( connection );

      if( i != -1 ) {
        connection = this.a[ i ];

        // ToDo: handle SQL transactions, either by terminating them now or waiting some time for them to terminate

        if( connection.mysql_connection ) {
          connection.mysql_connection.destroy();

          connection.mysql_connection = null;
        }

        de&&ug( this._get_name( '_remove_value' ), i, connection );

        if( connection.set_timeout ) {
          // We are in the process of waiting to reconnect to server on a timeout
          clearTimeout( connection.set_timeout );

          delete connection.set_timeout;
        }

        if( connection.connected ) {
          connection.connected = false;

          Super._remove_value.call( this, t, connection );
        } else {
          // We have already emitted remove downstream or never emitted add downstream
          this.__remove_value( connection );

          t.emit_nothing();
        }
      } else {
        // This should never happen because this is a unique set
        log( this._get_name( '_remove_value' ) + 'Error removing not found connection:', this._identity( connection ) );

        t.emit_nothing();
      }
    } // _remove_value()
  };
} ).singleton(); // mysql_connections_set()

rs.Singleton( 'mysql_connections', function( source, options ) {
  return source
    .optimize( { untag: 'mysql_configuration' } )
    .last()
    .mysql_connections_set( options )
  ;
} );

/* ----------------------------------------------------------------------------
    Converters
*/
var converters = ( function() {
  var converters = {};

  return {
    get: function( converter ) {
      return typeof converter == 'string' ? converters[ converter ] : converter;
    },

    set: function( name, converter ) {
      converters[ name ] = converter;
    }
  };
} )(); // converters

converters.set( 'uuid_b16', {
  // to mysql
  parse: function( id ) {
    return uuid.parse( id, new Buffer( 16 ) );
  },

  // from mysql
  serialize: function( id ) {
    return id && uuid.unparse( id );
  }
} ); // uuid_b16

converters.set( 'timestamp_t3', {
  // to mysql
  parse: function( t ) {
    return t;
  },

  // from mysql
  serialize: function( t ) {
    return timestamp_string( new Date( t ) );
  }
} ); // timestamp_t3

converters.set( 'json', {
  // to mysql
  parse: function( json ) {
    var text = JSON.stringify( json );

    //de&&ug( 'converter.json parse, JSON.stringify():', text );

    return text;
  },

  // from mysql
  serialize: function( text ) {
    try {
      var json = JSON.parse( text );

      //de&&ug( 'converter.json serialize, JSON.parse():', json );

    } catch( e ) {
      // ToDo: emit error
      log( 'JSON.parse error:', e );

      json = null;
    }

    return json;
  }
} ); // json

converters.set( 'geo_json', extend( {}, converters.get( 'json' ), {
  select: function( column, as ) {
    return "ST_AsGeoJSON( " + column + " ) AS " + ( as || column );
  },

  // sql expression to write column to mysql
  write: function( value ) {
    // srid is 4326 by default
    return "ST_GeomFromGeoJSON( " + value + " )";
  }
} ) );

converters.set( 'wkt', {
  // sql expression to read column from mysql
  select: function( column, as ) {
    return "ST_AsText( " + column + " ) AS " + ( as || column );
  },

  // sql expression to write column to mysql
  write: function( value ) {
    // force srid to 4326, because default is zero
    return "ST_GeomFromText( " + value + ", 4326 )";
  }
} );

/* ----------------------------------------------------------------------------
    @pipelet mysql_read( table, columns, connection, options )

    @parameters
    - **table** (String): mysql table name

    - **columns** (Array of Columns): see mysql() for full definition of
      Column.

    - **connection** (Pipelet): mysql_connections() output (will use the
      last added).

    - **options** (optional Object): optional attributes:
      - **key** (Array of Strings):  field names used to build *WHERE*
        clause for *DELETE*, may be aliased by *columns*.
*/
function MySQL_Read( table, columns, connection, options ) {
  var that = this
    , receivers = []
    , _name
    , parsers = {}
    , serializers = []
    , columns_aliases = []
    , processed_columns = process_columns( columns, parsers, serializers, columns_aliases )
  ;

  this._table_escaped = escapeId( table );
  this._mysql_connection = null;

  Greedy.call( this, options );

  this._add_input(
    connection,

    Greedy.Input,

    options.name + '-connection',

    {
      _add   : add_connections,
      _remove: remove_connections
    }
  );

  this._output.source = {
    _fetch: fetch,

    update_query_string: function() {}
  };

  function process_columns( columns, parsers, serializers, columns_aliases ) {
    var i = -1
      , l = columns.length
      , processed_columns = []
    ;

    // !! Do not use columns.map() because it hides user bugs, skipping undefined values
    while( ++i < l ) {
      var column    = columns[ i ]
        , a         = column
        , id
        , as        = null
        , converter = null
        , select    = null
      ;

      if ( typeof column === 'object' && column ) {
        id = column.id;
        as = column.as;
        converter = column.converter;

        column = id;
        a = as || id;

        if ( converter ) {
          converter = converters.get( converter );

          if ( converter ) {
            if ( converter.parse ) {
              parsers[ a ] = converter.parse;
            }

            if ( converter.serialize ) {
              serializers.push( { id: a, serialize: converter.serialize } );
            }

            select = converter.select;
          }
        }
      }

      if ( ! column )
        // ToDo: send error to global error dataflow
        throw new Error( 'Undefined column id'
          + ' at position ' + i
          + ' in columns: ' + JSON.stringify( columns )
          + ' of table: '   + table
        )
      ;

      columns_aliases[ a ] = column;

      // Escape column and as names
      column = escapeId( column );

      if ( as ) {
        as = escapeId( as );
      }

      if ( select ) {
        column = select( column, as );

      } else if ( as ) {
        column += ' AS ' + as;

      }

      processed_columns.push( column );
    } // while there are columns

    return processed_columns.join( '\n       , ' );
  } // process_columns()

  function name() {
    return _name || ( _name = that._get_name( 'fetch' ) );
  } // name()

  function add_connections( connections ) {
    de&&ug( that._get_name( 'add_connections' ), connections.map( connection_id ), table );

    if ( connections.length ) {
      that._mysql_connection = connections[ connections.length - 1 ].mysql_connection;
    }

    call_receivers();
  } // add_connections()

  function remove_connections( connections ) {
    de&&ug( that._get_name( 'remove_connections' ), connections.map( connection_id ), table );

    if( connections.length ) that._mysql_connection = null;
  } // remove_connections()

  function call_receivers() {
    while ( that._mysql_connection && receivers.length ) {
      fetch.apply( null, receivers.shift() );
    }
  } // call_receivers()

  function add_receiver( _arguments ) {
    de&&ug( that._get_name( 'add_receiver' ), _arguments[ 1 ] );

    receivers.push( slice.call( _arguments ) );
  } // add_receiver()

  /* --------------------------------------------------------------------------
      fetch( receiver, query )

      SELECT values from table, according to query
  */
  function fetch( receiver, query ) {
    var mysql_connection = that._mysql_connection;

    if ( ! mysql_connection ) return add_receiver( arguments );

    var table = that._table_escaped
      , _name
      , where = ''
    ;

    if ( query ) where = where_from_query( query, columns_aliases, parsers );

    var sql = '  SELECT ' + processed_columns + '\n\n  FROM ' + table + where;

    de&&ug( name() + 'sql:\n\n' + sql + '\n' );

    // ToDo: use query.on(), see https://github.com/mysqljs/mysql#streaming-query-rows
    mysql_connection.query( sql, function( error, results, fields ) {
      if ( error ) {
        log( name() + 'unable to read', table, ', error:', error );

        switch( error.code ) {
          case 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR':
          case 'ER_SERVER_SHUTDOWN':
          case 'PROTOCOL_CONNECTION_LOST':
            // We expect a new connection to execute this query later

            add_receiver( [ receiver, query ] );
          break;

          default:
            // ToDo: emit out-of-band fatal error
            log( name() + 'table:', table, ', fatal error:', error.code );

            receiver( [], true );
          break;
        }

        return;
      }

      var s = serializers.length
        , serialize
        , column
        , i
        , result
      ;

      // Loop through serializers first because the number of columns with serializers
      // is expected to be much smaller on average than the number rows returned by SELECT.
      // This allows to maximize the amount of time spent serializing columns in the inner
      // loop.
      // Also, the serializers loop has more code than the row loop which would be slower
      // if it was the inner loop.
      while ( s ) {
        serialize = serializers[ --s ];

        column    = serialize.id;
        serialize = serialize.serialize;

        // de&&ug( name() + 'serialize column:', column, 'with:', serialize );

        i = results.length;

        while ( i ) {
          result = results[ --i ];

          result[ column ] = serialize( result[ column ] );
        } // while there are results
      } // while there are serializers

      //de&&ug( name() + 'results:', results.length );

      receiver( results, true );
    } )
  } // fetch()
} // MySQL_Read()

function where_from_query( query, columns_aliases, parsers ) {
  var where = query
    .map( function( or_term ) {
      //de&&ug( 'where_from_query(), or_term:', or_term );

      or_term = Object.keys( or_term )

        .map( function( property ) {
          var value = or_term[ property ]
            , parser
          ;

          if ( property === 'flow' && value === 'error' ) {
            return false;
          }

          switch ( class_of( value ) ) {
            case 'Number':
            case 'String':
              // scalar values where strict equality is desired

              if ( parser = parsers[ property ] ) value = parser( value );

              var alias = columns_aliases[ property ];

              if ( ! alias )
                // ToDo: consider emitting an error because this fetch will effectively emit nothing after filtering
                return false;
              ;

              // ToDo: use "property" COLLATE latin1_bin = value, or utf8_bin for case-sensitive comparison
            return escapeId( alias ) + ' = ' + escape( value );

            case 'Array': // expression
            return expression_to_sql( escapeId( property ), value );

            default:
            // ToDo: emit error
            return false;
          }
        } )

        .filter( not_empty )

        .join( ' AND ' )
      ;

      return or_term || false;
    } )

    .filter( not_empty )

    .join( ' )\n     OR ( ' )
  ;

  return where ? '\n\n  WHERE ( ' + where + ' )' : '';

  function not_empty( v ) { return !!v }

  function expression_to_sql( property, expression, i ) {
    i = typeof i == 'number' ? i : 0;

    /*
      This is work in progress.

      examples:
      - expression_to_sql(
          escapeId( 'geometry' ),
          [ [ 'ST_Distance_Sphere', [ 'ST_GeomFromText', 'POINT( 2 48 )' ] ], '<=', 20000 ]
        )

        // -> ST_Distance_Sphere( ST_GeomFromText( 'POINT( 2 48 )', 4326 ), `geometry` ) <= 200000

      - expression_to_sql(
          escapeId( 'geometry' ),
          [ [ 'ST_Distance_Sphere', [ 'POINT_SRID', 2, 48 ] ], '<=', 20000 ]
        )

        // -> ST_Distance_Sphere( ST_GeomFromText( 'POINT( 2 48 )', 4326 ), `geometry` ) <= 200000

      - expression_to_sql(
          escapeId( 'geometry' ),
          [ 200000, '>=', [ 'ST_Distance_Sphere', [ 'ST_GeomFromGeoJSON', { type: "Point", coodinates: [ 2, 48 ] } ] ] ]
        )

        // -> 200000 >= ST_Distance_Sphere( ST_GeomFromGeoJSON( '{\"type\":\"Point\",\"coordinates\":[2,48]}' ), `geometry` )
    */
    var sql = '';

    while ( i < expression.length ) {
      var operator = expression[ i++ ]
        , class_of_operator = class_of( operator )
      ;

      if ( class_of_operator == "String" ) {
        switch( operator ) {
          case 'failed':
            // this is like the not operator but applying to previous result
            sql = 'NOT ( ' + ( sql || property ) + ' )';
          break;

          case '||':
            sql = '( ' + ( sql || property ) + ' ) OR ( ' + expression_to_sql( property, expression, i ) + ' )';
          break;

          case '==':
            operator = '=';
          // fall-through
          case '!=':
          case '>' :
          case '>=':
          case '<' :
          case '<=':
            sql = ( sql || property ) + ' ' + operator + ' '
          // fall-through
          case '$':
            sql += get_parameters( 1 )[ 0 ];
          break;

          case 'ST_GeomFromGeoJSON':
            sql += sql_function( operator, get_parameters( 1, [ JSON.stringify ] ) );
          break;

          case "ST_PointFromText": // WKT [, SRID = (default) 4326]
          case "ST_GeomFromText" : // WKT [, SRID = (default) 4326]
            sql += sql_function( operator, get_parameters( 2, null, [ null, 4326 ] ) );
          break;

          case 'POINT': // Longitude, Latitude
            sql += sql_function( operator, get_parameters( 2 ) );
          break;

          case 'ST_GeomFromPoint': // Longitude, Latitude [, SRID = (default) 4326]
            var parameters = get_parameters( 3 )
              , lon_lat    = parameters.slice( 0, 2 )
              , srid       = parameters[ 2 ]
            ;

            if ( typeof srid != "number" ) {
              srid = 4326;
            }

            sql += sql_function( "ST_GeomFromText",
              [ wkt_function( "POINT", lon_lat ), srid ]
            );
          break;

          // Minimum Bounding Rectangle (MBR) functions, that can use spatial indexes
          // These all take two geometry parameters. Default for the second paramenter is `property`
          case "MBRContains"       :
          case "MBRWithin"         :
          case "MBRCoveredBy"      :
          case "MBRCovers"         :
          case "MBRDisjoint"       :
          case "MBREquals"         :
          case "MBRIntersects"     :
          case "MBROverlaps"       :
          case "MBRTouches"        :
          // pass-through

          // other geometry comparison functions that do not use spatial indexes
          case "ST_Distance_Sphere": // geometry_a [, geometry_b = (default) property]
            sql += sql_function( operator, get_parameters( 2, null, [ null, property ] ) );
          break;

          default:
            // unsuported operator
            error( 'unsupported operator: ' + operator );
          return false;
        } // switch( operator )

      } else if ( class_of_operator == 'Array' ) {
        sql += expression_to_sql( property, operator );

      } else {
        error( 'operator is a ' + class_of_operator + ', expected a String' );
      }
    } // while there are operators in expression

    // In state 1, close parenthesis when number of arguments is incomplete
    // if ( expect && state == 1 ) sql += ends_with;

    return sql || property;

    function wkt_function( name, parameters ) {
      return escape( name + "( " + parameters.join( " " ) + " )" );
    } // wkt_function()

    function sql_function( name, parameters ) {
      return name + "( " + parameters.join( ", " ) + " )";
    } // sql_function()

    function get_parameters( count, converters, defaults ) {
      var parameters = []
        , j          = -1
      ;

      while ( count-- ) {
        ++j;

        if ( i < expression.length ) {
          var parameter   = expression[ i++ ]
            , sub_expression = is_array( parameter )
            , converter = converters && converters[ j ]
          ;

          if ( sub_expression ) {
            parameter = expression_to_sql( property, parameter );
          }

          if ( converter ) {
            parameter = converter( parameter );
          }

          if ( ! sub_expression ) {
            parameter = escape( parameter );
          }

        } else if ( defaults && ( parameter = defaults[ j ] ) !== undefined ) {
        } else {
          // no more parameters or default parameters
          break;
        }

        parameters.push( parameter );
      } // while ( count-- )

      return parameters;
    } // get_parameters()

    function error( message ) {
      log( 'error,', message + ', at position', i, 'in expression:', expression );
    }
  } // expression_to_sql()
} // where_from_query()

Greedy.Build( 'mysql_read', MySQL_Read );

/* ----------------------------------------------------------------------------
    @pipelet mysql_write( table, columns, connection, options )

    @parameters
    - **table** (String): mysql table name.

    - **columns** (Array of Columns): see pipelet mysql() for full
      definition of Column.

    - **connection** (Pipelet): pipelet mysql_connections() output
      (will use the last added).

    - **options** (Object): optional attributes:
      - **key** (Array of Strings): the set of fileds that uniquely define
        objects and used to build a *WHERE* clause for *DELETE* queries.
        May be aliased by columns.
*/
function MySQL_Write( table, columns, connection, options ) {
  this._table_escaped    = escapeId( table );
  this._columns          = columns;
  this._mysql_connection = null;
  this._waiters          = [];

  var column_ids          = this._column_ids          = []
    , aliases             = this._aliases             = []
    , columns_write       = this._columns_write       = []
    , properties_write    = this._properties_write    = {}
    , columns_aliases     = this._columns_aliases     = {}
    , parsers             = this._parsers             = {}
    , that = this
  ;

  columns.forEach( add_column );

  Greedy.call( this, options );

  this._add_input(
    connection,

    Greedy.Input,

    options.name + '-connection',

    {
      _add   : add_connections,
      _remove: remove_connections
    }
  );

  // return this; // if called with new
  // return undefined; // if called without new

  function add_column( column ) {
    var as        = column
      , id
      , converter
      , write
    ;

    if ( typeof column === 'object' ) {
      id = column.id;
      as = column.as || id;
      converter = column.converter;
      column = id;

      if ( converter ) {
        converter = converters.get( converter );

        if ( converter ) {
          if ( converter.parse ) {
            parsers[ as ] = converter.parse;
          }

          write = converter.write;

          if ( write ) {
            properties_write[ column ] = write;
          }
        }
      }
    }

    columns_write   .push( write    );
    column_ids      .push( column   );
    aliases         .push( as       );

    columns_aliases[ as ] = column;
  } // add_column()

  function add_connections( connections ) {
    var l = connections.length;

    de&&ug( that._get_name( 'add_connections' ), connections.map( connection_id ), table );

    if ( l ) {
      that._mysql_connection = connections[ l - 1 ].mysql_connection;

      that._call_waiters();
    }
  } // add_connections()

  function remove_connections( connections ) {
    de&&ug( that._get_name( 'remove_connections' ), connections.map( connection_id ), table );

    if( connections.length ) that._connection = null;
  } // remove_connections()
} // MySQL_Write()

function null_key_attribute_error( position, attribute, value ) {
  return {
    code: 'NULL_KEY_ATTRIBUTE',
    position: position,
    attribute: attribute,
    message: 'Key attribute "' + attribute + '" value must be defined',
    error_value: value
  };
} // null_key_attribute_error()

Greedy.Build( 'mysql_write', MySQL_Write, function( Super ) { return {
  /* --------------------------------------------------------------------------
      @method MySQL_Write.._add_waiter( method, parameters )

      @short Add a MySQL connection waiter for method with parameters

      @parameters
      - **method** (String): this instance method name e.g. ```"_add"```
        or ```"_remove"```.

      - **parameters** (Array): parameters to call method when MySQL
        connection is ready.
  */
  _add_waiter: function( method, parameters ) {
    var that = this;

    de&&ug( this._get_name( '_add_waiter' ) + 'method:' + method );

    this._waiters.push( { method: method, parameters: parameters } );
  }, // MySQL_Write.._add_waiter()

  /* --------------------------------------------------------------------------
      @method MySQL_Write.._call_waiters()

      @short Call connection waiters as long as MySQL connection is ready
  */
  _call_waiters: function() {
    var name = de && this._get_name( '_call_waiter' ) + 'calling method:'
      , waiter
    ;

    while( this._mysql_connection && ( waiter = this._waiters.shift() ) ) {
      de&&ug( name, waiter.method );

      this[ waiter.method ].apply( this, waiter.parameters );
    }
  }, // MySQL_Write.._call_waiters()

  /* --------------------------------------------------------------------------
      @method MySQL_Write.._add( values, options )

      @short Add values using SQL *INSERT*
  */
  _add: function( values, options ) {
    var that        = this
      , name        = de && this._get_name( '_add' )
      , emit_values = []
    ;

    if ( values.length == 0 ) return emit(); // nothing

    var connection = this._mysql_connection;

    if ( ! connection ) return this._add_waiter( '_add', arguments );

    var column_ids = this._column_ids;

    if ( column_ids.length === 0 ) return emit(); // nothing

    // ToDo: MySQL_Write.._add(), map Toubkal transactions to MySQL transactions

    var bulk_values = make_bulk_insert_list( values, emit_values );

    if ( typeof bulk_values !== 'string' ) { // this is an error object
      // ToDo: send error to error dataflow
      // ToDo: add tests for errors
      return emit_error( bulk_values );
    }

    var table   = this._table_escaped
      , columns = '\n\n    ( ' + column_ids.map( escape_id ).join( ', ' ) + ' )'
      , sql     = 'INSERT ' + table + columns + bulk_values
    ;

    de&&ug( name + 'sql:\n\n  ' + sql + '\n' );

    // All added values should have been removed first, the order of operations is important for MySQL
    connection.query( sql, function( error, results ) {
      if ( error ) {
        log( 'Unable to INSERT INTO', table, ', error:', error );

        /*
          ToDo: Error Handling:
          - Duplicate key: this should not happen since removes should be done first however:
            - these could be stored in an anti-state if unordered removes are desired
            - this may happen if someone added the conflicting value in the background,
              then consider updating
            - Example:
              { [Error: ER_DUP_ENTRY: Duplicate entry '100000' for key 'PRIMARY'] code: 'ER_DUP_ENTRY', errno: 1062, sqlState: '23000', index: 0 }

          - Constraints violations

            Emit errors with sender information so that added values may be removed by sender.
            Emitting to sender requires sender identification to be present either in incomming
            options or inband. Incomming options are a good candidate for sender identification
            inserted by clients' server.

            Because filter queries are used for authorizations and routing and that these do not
            interpret options, sender information must be emitted inband, allowing senders to
            query errors for updates they emitted.

            Emitted errors should be persistance-implementation-agnostic to allow senders to
            interpret errors regardless of low-level presistance implementations. This means
            that MySQL error code cannot be provided into error.

            These errors should be translatable into removes to allow the final state of senders'
            stateful pipelets to be updated.

            Finaly a mechanism must exist to stop the propagation of errors once state has been
            updated to prevent removes() to be propagated back to server, potentially alterring
            the valid state of the database.
        */
        switch( error.code ) {
          case 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR':
          case 'ER_SERVER_SHUTDOWN':
          case 'PROTOCOL_CONNECTION_LOST':
            // We expect a new connection to execute this query later
          return that._add_waiter( '_add', [ values, options ] );
        }

        emit_error( {
          // ToDo: provide toubkal error code from MySQL error

          engine: 'mysql',

          mysql: {
            table   : that._table_escaped,
            code    : error.code,
            number  : error.errno,
            sqlState: error.sqlState,
            index   : error.index,
            message : error.message,
            sql     : sql
          }
        } )

        return;
      }

      // ToDo: if results.affectedRows != values.length, we have a problem
      de&&ug( name + 'inserted rows:', results.affectedRows );

      emit(); // valid values
    } )

    /* ------------------------------------------------------------------------
        make_bulk_insert_list( values, emit_values )

        Make bulk insert list and make emit values, limited to actual columns.

        That way a read on the table should return the same values as emited
        values.

        Missing attributes will be set as null unless part of the key in
        which case an error is returned.

        There still may be some discrepencies if columns is not specified
        and some values have undefined columns.

        Returns:
          String: bulk_values
          Object: error
    */
    function make_bulk_insert_list( values, emit_values ) {
      var key              = that._options.key
        , columns          = that._aliases
        , parsers          = that._parsers
        , columns_write    = that._columns_write
        , bulk_values      = '\n\n  VALUES\n'
        , vl               = values.length
        , cl               = columns.length
        , i
        , value
        , emit_value
        , c, v, parser
        , write
        , j
      ;

      for ( i = -1; ++i < vl; ) {
        value      = values[ i ];
        emit_value = emit_values[ i ] = {};

        bulk_values += ( i ? ',\n    ' : '\n    ' );

        for ( j = -1; ++j < cl; ) {
          c = columns[ j ];
          v = value[ c ];

          emit_value[ c ] = v;

          if ( v == null ) { // null or undefined
            if ( key.indexOf( c ) !== -1 ) {
              // this attribute is part of the key, it must be provided
              return null_key_attribute_error( i, c, value );
            }

            v = null; // could have been undefined
          } else if ( parser = parsers[ c ] ) {
            v = parser( v );
          }

          v = escape( v );

          if ( write = columns_write[ j ] ) {
            v = write( v );
          }

          bulk_values += ( j ? ', ' : '( ' ) + v;
        }

        bulk_values += ' )';
      }

      return bulk_values;
    } // make_bulk_insert_list()

    function escape_id( id ) {
      return escapeId( id );
    }

    function emit() {
      return that.__emit_add( emit_values, options );
    } // emit()

    function emit_error( error ) {
      error.flow = 'error';

      // The error_flow is the flow of the first value
      // This is questionable but most likely correct
      // A sender's error handler will receive all the values
      error.error_flow = values[ 0 ].flow;

      error.operation = 'add';

      if ( options && options.sender ) {
        error.sender = options.sender; // to allow routing of error back to sender
      }

      error.values = values;

      that.__emit_add( [ error ], options );
    } // emit_error()
  }, // MySQL_Write.._add()

  /* --------------------------------------------------------------------------
      @method MySQL_Write.._remove( values, options )

      @short Removes values using SQL *DELETE*
  */
  _remove: function( values, options ) {
    var that        = this
      , emit_values = []
      , vl          = values.length
      , key         = this._key
      , kl          = key.length
      , name        = de && get_name()
      , connection  = this._mysql_connection
    ;

    // de&&ug( name + 'values:', pretty( values ), '\n  key:', key );

    if ( vl == 0 || kl == 0 ) return emit(); // propagate options

    if ( ! connection ) return this._add_waiter( '_remove', arguments );

    // ToDo: map Toubkal transactions to MySQL transactions

    // DELETE FROM table WHERE conditions

    // Build WHERE conditions based on key
    var escaped_key = this._escaped_key()
      , where       = make_where( this, escaped_key )
      , table       = this._table_escaped
      , sql         = 'DELETE FROM ' + table + where
    ;

    de&&ug( name + 'sql:\n\n  ' + sql + '\n' );

    // ToDo: in an SQL transaction implemented in a stored procedure read before delete to verify that all deleted values exist

    // All added values should have been removed first, the order of operations is important for MySQL
    connection.query( sql, function( error, results ) {
      if ( error ) {
        log( get_name() + 'unable to DELETE FROM', table, ', error:', error );

        switch( error.code ) {
          case 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR':
          case 'ER_SERVER_SHUTDOWN':
          case 'PROTOCOL_CONNECTION_LOST':
            // We expect a new connection to execute this query later
          return that._add_waiter( '_add', [ values, options ] );
        }

        emit_error( {
          // ToDo: provide toubkal error code from MySQL error

          engine: 'mysql',

          mysql: {
            table   : that._table_escaped,
            code    : error.code,
            number  : error.errno,
            sqlState: error.sqlState,
            index   : error.index,
            message : error.message,
            sql     : sql
          }
        } )

        return;
      }

      emit_values = values;

      // ToDo: if results.affectedRows != values.length, we have a problem
      de&&ug( name + 'deleted rows:', results.affectedRows );

      emit(); // valid values
    } )

    function make_where( that, escaped_key ) {
      var where = '\n\n  WHERE'
        , parsers = that._parsers
        , i, j, value, a, v, parser
      ;

      if ( kl > 1 ) {
        for ( i = -1; ++i < vl; ) {
          value = values[ i ];

          if ( i > 0 ) where += '\n     OR';

          where += ' (';

          for ( j = -1; ++j < kl; ) {
            a = key[ j ];
            v = value[ a ];

            if ( v == null ) { // null or undefined
              return emit_error( null_key_attribute_error( i, a, value ) );
            } else if ( parser = parsers[ a ] ) {
              v = parser( v );
            }

            where += ( j ? ' AND ' : ' ' )
              + escaped_key[ j ]
              + ' = ' + escape( v )
            ;
          }

          where += ' )';
        }
      } else {
        where += ' ' + escaped_key[ 0 ] + ' IN (';

        a = key[ 0 ];

        parser = parsers[ a ];

        for ( i = -1; ++i < vl; ) {
          value = values[ i ];
          v = value[ a ];

          if ( v == null ) { // null or undefined
            return emit_error( null_key_attribute_error( i, a, value ) );
          } else if ( parser ) {
            v = parser( v );
          }

          where += ( i ? ', ' : ' ' ) + escape( v );
        }

        where += ' )';
      }

      return where;
    } // make_where()

    function emit() {
      return that.__emit_remove( emit_values, options );
    } // emit()

    function emit_error( error ) {
      error.flow = 'error';

      // The error_flow is the flow of the first value
      // This is questionable but most likely correct
      // A sender's error handler will receive all the values
      error.error_flow = values[ 0 ].flow;

      error.operation = 'remove';

      if ( options && options.sender ) {
        error.sender = options.sender; // to allow routing of error back to sender
      }

      error.values = values;

      return that.__emit_add( [ error ], options );
    } // emit_error()

    function get_name() {
      return that._get_name( '_remove' )
    } // get_name()
  }, // MySQL_Write.._remove()

  /* --------------------------------------------------------------------------
      @method MySQL_Write.._update( updates, options )

      @short Update values using SQL *UPDATE*

      @description
      Where condition based on old value.

      Only updates columns specified in new values.

      Using syntax:
      ```sql
        UPDATE table
          SET col_name1=expression
          [, SET col_name2=expression]
        WHERE where_condition
      ```
  */
  _update: function( updates, options ) {
    var that         = this
      , emit_updates = []
      , ul           = updates.length
      , key          = this._key
      , kl           = key.length
      , name         = de && get_name()
      , connection   = this._mysql_connection
      , table        = this._table_escaped
      , key_escaped  = this._escaped_key()
    ;

    de&&ug( name + 'updates:', pretty( updates ), '\n  key:', key );

    if ( ul == 0 || kl == 0 ) return emit(); // propagate options

    if ( ! connection ) return this._add_waiter( '_update', arguments );

    updates.forEach( update );

    function update( update ) {
      // ToDo: MySQL_Write..update(), map Toubkal transactions to MySQL transactions

      // UPDATE table SET col=expression WHERE condition
      var set_values = make_set_values( update );

      if( set_values.length == 0 ) { // there are no values to update
        return --ul || emit(); // emit valid updates if this was the last one
      }

      // Build WHERE conditions based on key
      var sql = 'UPDATE ' + table + ' SET ' + set_values.join( ', ' ) + make_where( key_escaped, update[ 0 ] );

      de&&ug( name + 'sql:\n\n  ' + sql + '\n' );

      // All added values should have been removed first, the order of operations is important for MySQL
      connection.query( sql, function( error, results ) {
        if ( error ) {
          log( get_name() + 'unable to UPDATE', table, ', error:', error );

          switch( error.code ) {
            case 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR':
            case 'ER_SERVER_SHUTDOWN':
            case 'PROTOCOL_CONNECTION_LOST':
              // We expect a new connection to execute this query later
            return that._add_waiter( '_add', [ updates, options ] );
          }

          emit_error( {
            // ToDo: provide toubkal error code from MySQL error

            engine: 'mysql',

            mysql: {
              table   : that._table_escaped,
              code    : error.code,
              number  : error.errno,
              sqlState: error.sqlState,
              index   : error.index,
              message : error.message,
              sql     : sql
            }
          } )

          return
        } else {
          emit_updates.push( update );

          // ToDo: if results.affectedRows != values.length, we have a problem
          de&&ug( name + 'updated rows:', results.affectedRows );
        }

        --ul || emit(); // valid updates
      } )

      function make_set_values( update, i ) {
        var values              = []
          , parsers             = that._parsers
          , properties_write    = that._properties_write
        ;

        object_diff( update[ 0 ], update[ 1 ], set );

        return values;

        function set( property, added ) {
          var parser   = parsers         [ property ]
            , write    = properties_write[ property ]
            , v
          ;

          if ( parser ) added = parser( added );

          v = escape( added );

          if ( write ) {
            v = write( v );
          }

          values.push( escapeId( property ) + ' = ' + v );
        }
      } // make_set_values()
    } // update()

    function make_where( key_escaped, value ) {
      var where = '\n\n  WHERE'
        , parsers = that._parsers
        , i, a, v, parser
      ;

      if ( kl > 1 ) {
        where += ' (';

        for ( i = -1; ++i < kl; ) {
          a = key[ i ];
          v = value[ a ];

          if ( v == null ) // null or undefined
            return emit_error( null_key_attribute_error( i, a, value ) );

          if ( parser = parsers[ a ] ) v = parser( v );

          where += ( i ? ' AND ' : ' ' )
            + key_escaped[ i ]
            + ' = ' + escape( v )
          ;
        }

        where += ' )';

      } else {
        a = key[ 0 ];

        v = value[ a ];

        if ( v == null ) // null or undefined
          return emit_error( null_key_attribute_error( 0, a, value ) );

        if ( parser = parsers[ a ] ) v = parser( v );

        where += ' ' + key_escaped[ 0 ] + ' = ' + escape( v );
      }

      return where;
    } // make_where()

    function emit() {
      return that.__emit_update( emit_updates, options );
    } // emit()

    function emit_error( error ) {
      error.flow = 'error';

      // The error_flow is the flow of the first value
      // This is questionable but most likely correct
      // A sender's error handler will receive all the values
      error.error_flow = updates[ 0 ][ 0 ].flow;

      error.operation = 'update';

      if ( options && options.sender ) {
        error.sender = options.sender; // to allow routing of error back to sender
      }

      error.values = updates;

      // ToDo: emit in a transaction if there are emit_updates and options is not in an ongoing transaction
      return that.__emit_add( [ error ], options );
    } // emit_error()

    function get_name() {
      return that._get_name( '_update' )
    } // get_name()
  }, // MySQL_Write.._update()

  _escaped_key: function() {
    var that            = this
      , columns_aliases = this._columns_aliases
    ;

    return this._key.map( escape_column );

    function escape_column( a ) {
      var column = columns_aliases[ a ];

      if ( column ) return escapeId( column );

      // ToDo: MySQL_Write.._escaped_key(): emit error instead of throwing
      throw new Error(
          'key attribute "' + a + '" is not defined in columns (after optional aliasing).'
        + '\n\n  If a column has an alias (the "as" attribute) and is part of key, the alias is the name of the attribute that should be part of key.'
        + '\n\n  key: [ ' + key.join( ', ' ) + ' ]'
        + '\n\n  Columns: ' + JSON.stringify( that._columns, null, ' ' )
        + '\n\n  Aliased columns: ' + JSON.stringify( columns_aliases, null, ' ' )
        + '\n'
      );
    } // escape_column()
  } // MySQL_Write.._escaped_key()
} } ); // mysql_write()

// connection_id(): get id from connection Object
function connection_id( connection ) {
  return connection.id;
} // connection_id()

rs.Multiton( 'mysql_configuration',
  function( options ) {
    return '' + options.configuration + '#' + ( options.connection || 'root' ) + '#' + JSON.stringify( options.mysql );
  },

  function( source, options ) {
    var connection_terms = [ { id: 'toubkal_mysql#' + ( options.connection || 'root' ) } ];

    return source
      .configuration( { filepath: options.configuration } )

      /*
        Because mysql_connections() is a singleton, and this is a multiton,
        there may be multiple concurrent inputs to mysql_connections() that
        therefore need to be synchronized.
      */
      //.pass_through( { fork_tag: 'mysql_configuration'  } )

      .filter( connection_terms )

      .mysql_connections( { mysql: options.mysql } )

      .filter( connection_terms )
    ;
  }
); // mysql_configuration()

/* ----------------------------------------------------------------------------
    @pipelet mysql( table, columns, options )

    @parameters
    - **table** (String): MySQL table name. The table must exist in MySQL and
      must have a primary key that will be identical to the Pipelet's key
      unless aliased (see columns definition bellow).

    - **columns** (Array): defines all columns used for SELECT and INSERT,
      including primary key. Each column is defined as:
      - (String): column name

      - (Object): all attributes are optional except "id":
        - **id** (String): MySQL column name.

        - **as** (String): dataflow attribute name, default is the value of "id",

        - **converter**: to convert values of this column to/from mysql driver
          types. For more information on further mysql driver type convertions
          with MySQL types see
          https://www.npmjs.com/package/mysql#type-casting.

          A converter can be specified as a string for built-in converters or
          an Object:
          - (String): a built-in converter, supported converters are:
            - **"uuid_b16"**: converts a UUID to/from MySQL BINARY(16)

          - (Object): Providing the following functions:
            - **parse** (Function):
              ```parse( value ) -> value to mysql driver```

            - **serialize** (Function):
              ```serialize( <value from mysql driver> ) -> value```

    - **options** (Object): optional attributes:
      - **connection** (String): name of connection in configuration file,
        default is ```"root"```.

      - **configuration** (String): filename of configuration file, default
        is ```~/config.rs.json```.

      - **mysql** (Object): default mysql connection options, see
        @@pipelet:mysql_connections().

      - **key** (Array of Strings): defines the primary key, if key columns
        are aliased as defined above, alliased column names MUST be provided.
        default is ```[ 'id' ]```.
*/
rs.Compose( 'mysql', function( source, table, columns, options ) {
  var connection_terms = [ { id: 'toubkal_mysql#' + ( options.connection || 'root' ) } ];

  // ToDo: move connections handling outside of this pipelet, as a stateless cache
  // ToDo: handle multiple simultaneous connections for instant HA failover to another master
  // ToDo: handle reads through slave servers, different from masters used for writes
  var connections = rs
    .mysql_configuration( options )

    .pass_through()

    // mysql_configuration() is a multiton, requires explicit disconnection when source disconnects
    .remove_source_with( source )
  ;

  de&&ug( 'mysql(),', table, columns.length, options );

  var input  = source.mysql_write( table, columns, connections, { name: options.name + '_write', key: options.key } )
    , output = input .mysql_read ( table, columns, connections, { name: options.name + '_read' , key: options.key } )
  ;

  return rs.encapsulate( input, output, options );
} ); // mysql()

} // init()

// toubkal_mysql.js


text:
from gi.repository import Gio
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
from threading import Timer
import subprocess
import json
import signal
from os import listdir
import random
# import gtk.glade
import sys
import os
from xdg.DesktopEntry import DesktopEntry

bg_types = ('.png', '.jpg')

def file_filter(file_name):
    for i in bg_types:
        if file_name.lower().endswith(i):
            return True
    return False

random.seed()

class Shuffler:

    def __init__(self):

        self.indicator = Indicator(self)

        self.settings = Settings(self)

        self.bg_settings = Gio.Settings.new('org.gnome.desktop.background')

        if self.settings.background_folder is '':
            self.settings.set_background_folder(os.path.join(os.environ['HOME'], 'Pictures'))

        if self.settings.background_folder[-1] != "/" :
            self.settings.set_background_folder(self.settings.background_folder + '/')

        if self.settings.autostart:
            self.enable_autostart('activate')
        else:
            self.disable_autostart('activate')

        self.bg_timer = None
        # self.bg_list = list()

        self.update_bg_list()
        self.timer_shuffle()

    def user_call_shuffle(self, item):
        self.bg_timer.cancel()
        self.timer_shuffle()

    def shuffle(self):
        self.current_bg_index += 1
        if self.current_bg_index > len(self.bg_list):
            self.current_bg_index = 0
        self.bg_settings.set_string('picture-uri', "file://"
            + self.settings.background_folder
            + self.bg_list[self.current_bg_index])

    def timer_shuffle(self):
        # if self.bg_timer is None:
        self.bg_timer = Timer(self.settings.display_time, self.timer_shuffle)

        self.shuffle()
        self.bg_timer.start()

    def update_bg_list(self):
        self.current_bg_index = 0
        self.bg_list = []
        self.bg_list = listdir(self.settings.background_folder)
        self.bg_list = filter(file_filter, self.bg_list)
        random.shuffle(self.bg_list)
        random.shuffle(self.bg_list)
        random.shuffle(self.bg_list)

    def refresh_bg_list(self, item):
        self.update_bg_list()
        self.user_call_shuffle("activate")
        # self.timer_shuffle()

    def pause_shuffle(self, item):
        pass

    def unpause_shuffle(self, item):
        pass

    def enable_autostart(self, item):
        self.indicator.item_disable_autostart.show()
        self.indicator.item_enable_autostart.hide()
        self.create_autostarter()

    def disable_autostart(self, item):
        self.indicator.item_enable_autostart.show()
        self.indicator.item_disable_autostart.hide()
        self.delete_autostarter()

    def open_background_folder(self, item):
        try:
            subprocess.Popen(['xdg-open', self.settings.background_folder])
        except OSError:
            pass

    def open_background(self, item):
        try:
            subprocess.Popen(['xdg-open', self.settings.background_folder
                + self.bg_list[self.current_bg_index]])
        except OSError:
            pass

    def reload_settings(self, item):
        self.settings.load_settings()
        self.refresh_bg_list(item)
        if self.settings.autostart:
            self.enable_autostart(item)
        else:
            self.disable_autostart(item)

    def open_settings_file(self, item):
        try:
            subprocess.Popen(['xdg-open', self.settings.filename])
        except OSError:
            pass

    def open_preferences(self, item):
        pass

    #autostart code copied from AWN
    def get_autostart_file_path(self):
        autostart_dir = os.path.join(os.environ['HOME'], '.config',
                                     'autostart')
        return os.path.join(autostart_dir, 'background-shuffler.desktop')

    def create_autostarter(self):
        autostart_file = self.get_autostart_file_path()
        autostart_dir = os.path.dirname(autostart_file)

        if not os.path.isdir(autostart_dir):
            #create autostart dir
            try:
                os.mkdir(autostart_dir)
            except Exeption, e:
                print "creation of autostart dir failed, please make it yourself: %s" % autostart_dir
                raise e

        if not os.path.isfile(autostart_file):
            #create autostart entry
            starter_item = DesktopEntry(autostart_file)
            starter_item.set('Name', 'Background Shuffler applet')
            starter_item.set('Exec', 'background-shuffler.py')
            starter_item.set('Icon', 'background-shuffler-panel')
            starter_item.set('X-GNOME-Autostart-enabled', 'true')
            starter_item.write()
            self.settings.set_autostart(True)

    def delete_autostarter(self):
        autostart_file = self.get_autostart_file_path()
        if os.path.isfile(autostart_file):
            os.remove(autostart_file)
            self.settings.set_autostart(False)

    def quit(self, item):
        self.bg_timer.cancel()
        gtk.main_quit()
        sys.exit(0)

    def run(self):
        gtk.main()

class Indicator:

    def __init__(self, main):
        self.main = main
        self.setup_indicator()

    def setup_indicator(self):
        self.indicator = appindicator.Indicator.new(
            "background-shuffler-indicator",
            "bg-shuffler-panel",
            appindicator.IndicatorCategory.APPLICATION_STATUS)
        self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)

        # self.indicator.set_icon("pamac-tray-no-update")

        self.indicator.set_menu(self.setup_menu())

    def setup_menu(self):
        menu = gtk.Menu()

        item = gtk.MenuItem("Next Background")
        item.connect("activate", self.main.user_call_shuffle)
        item.show()
        menu.append(item)

        # self.item_pause = gtk.MenuItem("Pause Background")
        # self.item_pause.connect("activate", self.main.pause_shuffle)
        # self.item_pause.show()
        # menu.append(self.item_pause)

        # self.item_unpause = gtk.MenuItem("Unpause Background")
        # self.item_unpause.connect("activate", self.main.unpause_shuffle)
        # self.item_unpause.hide()
        # menu.append(self.item_unpause)

        item = gtk.SeparatorMenuItem()
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Refresh Background List")
        item.connect("activate", self.main.refresh_bg_list)
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Open Backgrounds Folder")
        item.connect("activate", self.main.open_background_folder)
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Open Background")
        item.connect("activate", self.main.open_background)
        item.show()
        menu.append(item)

        item = gtk.SeparatorMenuItem()
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Reload Settings")
        item.connect("activate", self.main.reload_settings)
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Open Settings File")
        item.connect("activate", self.main.open_settings_file)
        item.show()
        menu.append(item)

        # item = gtk.MenuItem("Preferences")
        # item.connect("activate", self.main.open_preferences)
        # item.show()
        # menu.append(item)

        item = gtk.SeparatorMenuItem()
        item.show()
        menu.append(item)

        self.item_enable_autostart = gtk.MenuItem("Enable Autostart")
        self.item_enable_autostart.connect("activate", self.main.enable_autostart)
        self.item_enable_autostart.show()
        menu.append(self.item_enable_autostart)

        self.item_disable_autostart = gtk.MenuItem("Disable Autostart")
        self.item_disable_autostart.connect("activate", self.main.disable_autostart)
        self.item_disable_autostart.hide()
        menu.append(self.item_disable_autostart)

        item = gtk.SeparatorMenuItem()
        item.show()
        menu.append(item)

        item = gtk.MenuItem("Quit")
        item.connect("activate", self.main.quit)
        item.show()
        menu.append(item)

        return menu

    def main(self):
        gtk.main()

# class Preferences:

#     def __init__(self, main):
#         self.main = main
#         self.gladefile = os.path.join(os.path.dirname(os.path.dirname(
#             os.path.realpath(__file__))), "background-shuffler/preferences.glade")
#         self.wTree = gtk.glade.XML(self.gladefile)

#         self.window = self.wTree.get_widget("window1")

class Settings:

    def __init__(self, main):
        self.main = main
        self.filename = os.path.join(os.environ['HOME'], '.bg-shuffler')

        self.settings_data = {
            "autostart": False,
            "background_folder": '',
            "display_time": 600,
            "reshow_time": 600}

        if not os.path.isfile(self.filename):
            self.save_settings()
        else:
            self.load_settings()

    def set_autostart(self, b):
        self.settings_data["autostart"] = b
        self.save_settings()
        self.autostart = b

    def set_background_folder(self, f):
        self.settings_data["background_folder"] = f
        self.save_settings()
        self.background_folder = f

    def set_display_time(self, t):
        self.settings_data["display_time"] = t
        self.save_settings()
        self.display_time = t

    def set_reshow_time(self, t):
        self.settings_data["reshow_time"] = t
        self.save_settings()
        self.reshow_time = t

    def load_settings(self):
        with open(self.filename) as infile:
            self.settings_data = json.load(infile)

        self.autostart = self.settings_data["autostart"]
        self.background_folder = self.settings_data["background_folder"]
        self.display_time = self.settings_data["display_time"]
        self.reshow_time = self.settings_data["reshow_time"]

    def save_settings(self):
        with open(self.filename, 'w') as outfile:
            json.dump(self.settings_data, outfile, indent = 2)

    def main(self):
        gtk.main()

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    try:
        app = Shuffler()
        app.run()
    except KeyboardInterrupt:
        app.quit("yup")
        sys.exit(0)


text:
package android.support.v4.text;

import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

class ICUCompatApi23 {
    private static final String TAG = "ICUCompatIcs";
    private static Method sAddLikelySubtagsMethod;

    ICUCompatApi23() {
    }

    static {
        try {
            sAddLikelySubtagsMethod = Class.forName("libcore.icu.ICU").getMethod("addLikelySubtags", new Class[]{Locale.class});
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public static String maximizeAndGetScript(Locale locale) {
        try {
            return ((Locale) sAddLikelySubtagsMethod.invoke(null, new Object[]{locale})).getScript();
        } catch (InvocationTargetException e) {
            Log.w(TAG, e);
            return locale.getScript();
        } catch (IllegalAccessException e2) {
            Log.w(TAG, e2);
            return locale.getScript();
        }
    }
}


text:
const pokemon = require('./pokemon');

module.exports = class Pokedex {
  pokemon(id) {
    return getPokemon(id);
  }
}

function getPokemon(id) {
  return pokemon(id);
}


text:
yum -y check-update

# Python bindings are required (because of selinux)
yum -y install libselinux-python

# Random Number Generator is required to create enough entropy to create
# new test signing keys
yum -y install rng-tools

# Install createrepo to manage rpm repository
yum -y install createrepo

# Expect is crucial during package signing,
# because 'rpm' does not give any possibility
# of performing the process in an non-interactive way
yum -y install expect

# Start rng daemon
service rngd start

# Prepare repo directory structure
if [ ! -f /var/www/repo ]
then
    echo 'Creating repo directory structure'
    mkdir -p /var/www/repo/stable/2.0/rhel/el6/i386 \
             /var/www/repo/stable/2.0/rhel/el6/x86_64 \
             /var/www/repo/stable/2.0/rhel/el7/x86_64
else
    echo 'Directory structure is already there.'
fi

# Create repositories
repo_root=/var/www/repo/stable/2.0/rhel
repo_dirs=($repo_root/el6/i386 $repo_root/el6/x86_64 \
           $repo_root/el7/x86_64)
for dir in ${repo_dirs[*]}
do
    createrepo $dir
done

# Copy gpg key config file
mkdir -p /opt/tmp/
cp /vagrant/files/key_config /opt/tmp/

# Generate Zato package test signing keys
gpg --batch --gen-key /opt/tmp/key_config

# Add private Zato package test signing key to the keyring
# Export the public key
gpg --armor --export example@example.com > /opt/tmp/zato-rpm-test.pgp.asc
# Import the public key to rpm
rpm --import /opt/tmp/zato-rpm-test.pgp.asc
echo "%_gpg_name Zato test signing key" > /etc/rpm/macros

# Copy public test Zato package signing key
if [ ! -f /var/www/repo/zato-rpm-test.pgp.asc ]
then
    sudo cp /opt/tmp/zato-rpm-test.pgp.asc /var/www/repo
else
    echo 'Zato repository test key already in place.'
fi


text:
package com.github.culmat.easyjdbc.beans.test;

import org.h2.jdbcx.JdbcDataSource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.github.culmat.easyjdbc.beans.Greeting;
import com.github.culmat.easyjdbc.beans.GreetingBean;

public class H2Test {

	private JdbcDataSource datasource;

	@Before
	public void before() throws Exception {
		 datasource = new JdbcDataSource();
		 datasource.setURL("jdbc:h2:mem:test");
	}

	@Test
	public void foo() throws Exception {
		String someone = "World";
		GreetingBean actual = new Greeting(someone).execute(datasource.getConnection());
		Assert.assertEquals("Hello World", actual.getGreeting());
	}
}