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

<rootTag>
  <Award>
    <AwardTitle>EAPSI: The Impact of Reward on Large-Scale Functional Brain Networks: An Interdisciplinary Approach to Understanding the Motivated Brain</AwardTitle>
    <AwardEffectiveDate>06/01/2010</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2011</AwardExpirationDate>
    <AwardAmount>5617</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      01090000
      <Directorate>
        <LongName>Office Of The Director</LongName>
      </Directorate>
      <Division>
        <LongName>Office Of Internatl Science &Engineering</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Anne L. Emig</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>05/28/2010</MinAmdLetterDate>
    <MaxAmdLetterDate>05/28/2010</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1015242</AwardID>
    <Investigator>
      <FirstName>Vishnu</FirstName>
      <LastName>Murty</LastName>
      <EmailAddress/>
      <StartDate>05/28/2010</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Murty Vishnu P</Name>
      <CityName>Durham</CityName>
      <ZipCode>277050000</ZipCode>
      <PhoneNumber></PhoneNumber>
      <StreetAddress></StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>North Carolina</StateName>
      <StateCode>NC</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <stdio.h>
#include <ctype.h>
#include <dirent.h>

#include <lib/mounts.h>

#include <util.h>
#include <common.h>

#define LOG_TAG "BOOT_ANDROID"
#include <lib/log.h>

typedef struct {
    list_node_t node;

    struct fstab_rec *rec;
    part_replacement_t *replacement;
} remount_entry_t;

static multiboot_data_t *multiboot_data = NULL;
static list_node_t remount_entries = LIST_INITIAL_VALUE(remount_entries);

#define MBABORT_IF_MB(fmt, ...) do { \
    if(multiboot_data->is_multiboot) \
        MBABORT(fmt, ##__VA_ARGS__); \
    else \
        LOGE(fmt, ##__VA_ARGS__); \
}while(0)

static void handle_on_early_init(void)
{
    int rc;
    char buf[PATH_MAX];
    char buf2[PATH_MAX];

    part_replacement_t *replacement;
    list_for_every_entry(&multiboot_data->replacements, replacement, part_replacement_t, node) {
        struct stat sb_orig;
        struct stat sb_loop;

        // build path to dev node
        rc = snprintf(buf, sizeof(buf), "/dev/block/%s", replacement->uevent_block->devname);
        if (SNPRINTF_ERROR(rc, sizeof(buf))) {
            MBABORT_IF_MB("Can't build path for %s\n", replacement->uevent_block->devname);
            goto finish;
        }
        char *blk_device = buf;

        // stat original device
        rc = stat(blk_device, &sb_orig);
        if (rc) {
            MBABORT_IF_MB("Can't stat device at %s\n", blk_device);
            goto finish;
        }

        const char *replacement_device;
        if (replacement->iomode==PART_REPLACEMENT_IOMODE_ALLOW) {
            continue;
        } else if (replacement->iomode==PART_REPLACEMENT_IOMODE_DENY) {
            replacement_device = "/dev/null";
        } else if (replacement->iomode==PART_REPLACEMENT_IOMODE_REDIRECT) {
            replacement_device = replacement->loopdevice;
        } else {
            MBABORT_IF_MB("invalid iomode %d\n", replacement->iomode);
            goto finish;
        }

        LOGD("replace %s with %s\n", blk_device, replacement_device);

        // stat loop device
        rc = stat(replacement_device, &sb_loop);
        if (rc) {
            MBABORT_IF_MB("Can't stat device at %s\n", replacement_device);
            goto finish;
        }

        // create path for backup node
        rc = snprintf(buf2, sizeof(buf2), "%s/replacement_backup_%s", MBPATH_DEV, replacement->uevent_block->devname);
        if (SNPRINTF_ERROR(rc, sizeof(buf2))) {
            MBABORT_IF_MB("Can't build name for backup node\n");
            goto finish;
        }

        // create backup node
        rc = mknod(buf2, S_IRUSR | S_IWUSR | S_IFBLK, makedev(major(sb_orig.st_rdev), minor(sb_orig.st_rdev)));
        if (rc) {
            MBABORT_IF_MB("Can't create backup node for device %s\n", buf2);
            goto finish;
        }

        // delete original node
        if (util_exists(blk_device, false)) {
            rc = unlink(blk_device);
            if (rc) {
                MBABORT_IF_MB("Can't delete %s\n", blk_device);
                goto finish;
            }
        }

        // create new node
        rc = mknod(blk_device, sb_orig.st_mode, makedev(major(sb_loop.st_rdev), minor(sb_loop.st_rdev)));
        if (rc) {
            MBABORT_IF_MB("Can't create replacement node at %s\n", blk_device);
            goto finish;
        }
    }

finish:
    if (multiboot_data->is_multiboot && rc)
        MBABORT("early-init failed: rc=%d errno=%d\n", rc, errno);

    return;
}

static void handle_on_post_fs_data(void)
{
    int rc;
    mounts_state_t mounts_state = LIST_INITIAL_VALUE(mounts_state);

    // scan mounted volumes
    rc = scan_mounted_volumes(&mounts_state);
    if (rc) {
        MBABORT_IF_MB("Can't scan mounted volumes: %s\n", strerror(errno));
        goto finish;
    }

    // find ESP volume
    const mounted_volume_t *volume = find_mounted_volume_by_majmin(&mounts_state, multiboot_data->espdev->major, multiboot_data->espdev->minor, 0);
    if (!volume) {
        LOGI("ESP is not mounted. do this now.\n");

        // mount ESP to our dir
        rc = util_mount_esp(multiboot_data->is_multiboot);
        if (rc) {
            MBABORT_IF_MB("Can't mount ESP: %s\n", strerror(errno));
            goto finish;
        }
    } else {
        LOGI("bind-mount ESP to %s\n", MBPATH_ESP);

        // bind-mount ESP to our dir
        rc = util_mount(volume->mount_point, MBPATH_ESP, NULL, MS_BIND, NULL);
        if (rc) {
            MBABORT_IF_MB("can't bind-mount ESP to %s: %s\n", MBPATH_ESP, strerror(errno));
            goto finish;
        }
    }

    // free mount state
    free_mounts_state(&mounts_state);

    part_replacement_t *replacement;
    list_for_every_entry(&multiboot_data->replacements, replacement, part_replacement_t, node) {
        if (!replacement->losetup_done && replacement->loopdevice) {
            if (!replacement->loopfile) {
                MBABORT_IF_MB("loopfile required for %s\n", replacement->loopdevice);
                goto finish;
            }

            // setup loop device
            LOGD("losetup %s with %s\n", replacement->loopdevice, replacement->loopfile);
            rc = util_losetup(replacement->loopdevice, replacement->loopfile, false);
            if (rc) {
                MBABORT_IF_MB("Can't setup loop device at %s for %s: %d\n", replacement->loopdevice, replacement->loopfile, rc);
                goto finish;
            }
        }
    }

finish:
    if (multiboot_data->is_multiboot && rc)
        MBABORT("post-fs-data init failed: rc=%d errno=%d\n", rc, errno);
}

static void add_remount_entry(struct fstab_rec *rec, part_replacement_t *replacement)
{
    remount_entry_t *entry = safe_malloc(sizeof(remount_entry_t));
    entry->rec = rec;
    entry->replacement = replacement;
    list_add_tail(&remount_entries, &entry->node);
}

static void handle_on_post_fstab(void)
{
    remount_entry_t *entry;
    list_for_every_entry(&remount_entries, entry, remount_entry_t, node) {
        SAFE_MOUNT(entry->replacement->bindsource, entry->rec->mount_point, entry->rec->fs_type, MS_REMOUNT|MS_BIND|entry->rec->flags, entry->rec->fs_options);
    }
}

int handle_trigger(char *cmd)
{
    multiboot_data = multiboot_get_data();

    LOGI("TRIGGER: %s\n", cmd);

    if (!strcmp(cmd, "early-init")) {
        handle_on_early_init();
    } else if (!strcmp(cmd, "post-fs-data")) {
        handle_on_post_fs_data();
    } else if (!strcmp(cmd, "post-fstab")) {
        handle_on_post_fstab();
    } else {
        LOGE("unknown trigger command: %s\n", cmd);
        return -1;
    }

    return 0;
}
#define CHECK_WRITE(fd, str) \
        len = strlen(str); \
        bytes_written = write(fd, str, len); \
        if(bytes_written!=(size_t)len) { \
            MBABORT("Can't write\n"); \
        }

static int fstab_append(int fd, const char *blk_device, const char *mount_point, const char *fs_type, const char *mnt_flags, const char *fs_mgr_flags)
{
    size_t bytes_written;
    size_t len;

    // allocate line buffer
    size_t linelen = strlen(blk_device) + strlen(mount_point) + strlen(fs_type) + strlen(mnt_flags) + strlen(fs_mgr_flags) + 6;
    char *line = safe_malloc(linelen);

    // build line
    SAFE_SNPRINTF_RET(MBABORT, -1, line, linelen, "%s %s %s %s %s\n", blk_device, mount_point, fs_type, mnt_flags, fs_mgr_flags);

    // write line
    CHECK_WRITE(fd, line);

    // free line
    free(line);

    return 0;
}

#define SKIP_WHITESPACE(x) while(isspace(*(x))) (x)++;
#define NEXT_WORD_INTERNAL(str, p) ((p)=strtok_r((str), " \t", &save_ptr))
#define FIRST_WORD(p) NEXT_WORD_INTERNAL((p), (p))
#define NEXT_WORD(p) NEXT_WORD_INTERNAL(NULL, (p))

static int process_file(FILE *fp_orig, FILE *fp_out)
{
    char line[PATH_MAX];
    char *save_ptr;
    char buf[PATH_MAX];
    const char *pcmd;

    while (fgets(line, sizeof(line), fp_orig)) {
        size_t len = strlen(line);
        pcmd = NULL;

        // skip incomplete lines
        if (len && (line[len - 1] != '\n')) {
            goto write_unmodified;
        }

        // skip over leading whitespace
        pcmd = line;
        SKIP_WHITESPACE(pcmd);

        // we want mount commands only
        if (strstr(pcmd, "mount")==pcmd && isspace(pcmd[5])) {
            /* mount <type> <device> <path> <flags ...> <options> */

            // create a copy, and keep a pointer to the start
            char *p_start = safe_strdup(pcmd);
            char *p = p_start;

            // remove newline
            p_start[strlen(p_start) - 1] = 0;

            // 'mount'
            if (!FIRST_WORD(p)) goto write_unmodified;

            // type
            if (!NEXT_WORD(p)) goto write_unmodified;
            char *type = safe_strdup(p);

            // device
            if (!NEXT_WORD(p)) goto write_unmodified;
            UNUSED char *device = safe_strdup(p);

            // path
            if (!NEXT_WORD(p)) goto write_unmodified;
            char *path = safe_strdup(p);

            // flags and options
            const char *rest = pcmd + (save_ptr-p_start);
            SKIP_WHITESPACE(rest);

            // get uevent block for this device
            uevent_block_t *uevent_block = get_blockinfo_for_path(multiboot_data->blockinfo, device);
            if (!uevent_block) goto write_unmodified;

            // get replacement for this device
            part_replacement_t *replacement = util_get_replacement(uevent_block->major, uevent_block->minor);
            if (!replacement) goto write_unmodified;

            const char *blk_device;
            const char *mnt_flags = rest;
            // determine mount args
            if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_BIND) {
                blk_device = replacement->bindsource;
                mnt_flags = "bind";
            } else if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_LOOP) {
                blk_device = replacement->loopdevice;
            } else if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_DENY) {
                // next entry
                continue;
            } else if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_ALLOW) {
                goto write_unmodified;
            } else {
                LOGE("invalid mountmode %d\n", replacement->mountmode);
                return -1;
            }

            // write modified command
            fprintf(fp_out, "    mount %s %s %s %s\n", type, blk_device, path, mnt_flags);

            // remount to apply requested mount-flags
            if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_BIND) {
                SAFE_SNPRINTF_RET(LOGE, -1, buf, sizeof(buf), "remount,bind,%s", rest);
                fprintf(fp_out, "    mount %s %s %s %s\n", type, blk_device, path, buf);
            }

            // bind mount datamedia
            if (!strcmp(path, "/data")) {
                SAFE_SNPRINTF_RET(LOGE, -1, buf, sizeof(buf), "%s%s", path, multiboot_data->datamedia_target);

                LOGI("bind-mount %s to %s\n", multiboot_data->datamedia_source, buf);
                fprintf(fp_out, "    mount %s %s %s %s\n", type, multiboot_data->datamedia_source, buf, "bind");
            }

            // next entry
            continue;
        }

        // write unmodified command
write_unmodified:
        fputs(line, fp_out);

        if (pcmd && strstr(pcmd, "mount_all")==pcmd && isspace(pcmd[9])) {
            fputs("\n"
                  // start mbtrigger
                  "    write "MBPATH_TRIGGER_CMD" post-fstab\n"
                  "    start mbtrigger\n"
                  "    wait "MBPATH_TRIGGER_WAIT_FILE"\n"

                  // mbtrigger cleanup
                  "    rm "MBPATH_TRIGGER_WAIT_FILE"\n"
                  , fp_out);
        }
    }

    return 0;
}

static int patch_rc_files(void)
{
    DIR *dp;
    struct dirent *ep;
    char buf[PATH_MAX];

    dp = opendir("/");
    if (dp != NULL) {
        while ((ep=readdir (dp))) {
            if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
                continue;

            if (strcmp(util_get_file_extension(ep->d_name), "rc"))
                continue;

            // rename original file
            SAFE_SNPRINTF_RET(MBABORT, -1, buf, sizeof(buf), "%s.orig", ep->d_name);
            rename(ep->d_name, buf);

            // open original file
            FILE *fp_orig = fopen(buf, "r");
            if (!fp_orig) MBABORT("can't open %s: %s\n", buf, strerror(errno));

            // open output file
            FILE *fp_out = fopen(ep->d_name, "w");
            if (!fp_out) MBABORT("can't open %s: %s\n", ep->d_name, strerror(errno));

            // process file
            LOGV("process: %s\n", ep->d_name);
            process_file(fp_orig, fp_out);

            // close files
            fclose(fp_out);
            fclose(fp_orig);

            // set permissions for patched file
            chmod(ep->d_name, 0750);

            // delete original file
            unlink(buf);
        }
        closedir (dp);
    } else {
        MBABORT("Can't open root directory: %s\n", strerror(errno));
    }

    return 0;
}

int boot_android(void)
{
    multiboot_data = multiboot_get_data();

    int rc;
    int i;
    char buf[PATH_MAX];

    // multiboot setup
    if (multiboot_data->is_multiboot) {
        // patch all rc files
        patch_rc_files();

        // open fstab for writing
        int fd = open(multiboot_data->romfstabpath, O_WRONLY|O_TRUNC);
        if (fd<0) {
            MBABORT("Can't open init.rc for writing\n");
        }

        // write entries
        struct fstab_rec *datarec = NULL;
        for (i=0; i<multiboot_data->romfstab->num_entries; i++) {
            struct fstab_rec *rec = &multiboot_data->romfstab->recs[i];
            const char *blk_device = rec->blk_device;
            const char *mnt_flags = rec->mnt_flags_orig;

            // get uevent block for this device
            uevent_block_t *uevent_block = get_blockinfo_for_path(multiboot_data->blockinfo, rec->blk_device);
            if (!uevent_block) goto write_entry;

            // get replacement for this device
            part_replacement_t *replacement = util_get_replacement(uevent_block->major, uevent_block->minor);
            if (!replacement) goto write_entry;

            // determine mount args
            if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_BIND) {
                blk_device = replacement->bindsource;
                mnt_flags = "bind";

                add_remount_entry(rec, replacement);
            } else if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_LOOP) {
                blk_device = replacement->loopdevice;
            } else if (replacement->mountmode==PART_REPLACEMENT_MOUNTMODE_DENY) {
                continue;
            } else if (replacement->mountmode!=PART_REPLACEMENT_MOUNTMODE_ALLOW) {
                LOGE("invalid mountmode %d\n", replacement->mountmode);
            }

            // write entry
write_entry:
            fstab_append(fd, blk_device, rec->mount_point, rec->fs_type, mnt_flags, rec->fs_mgr_flags_orig);

            // save rec for /data
            if (!strcmp(rec->mount_point, "/data")) {
                datarec = rec;
            }
        }

        // bind mount datamedia
        if (datarec) {
            SAFE_SNPRINTF_RET(LOGE, -1, buf, sizeof(buf), "%s%s", datarec->mount_point, multiboot_data->datamedia_target);

            LOGI("bind-mount %s to %s\n", multiboot_data->datamedia_source, buf);
            fstab_append(fd, multiboot_data->datamedia_source, buf, datarec->fs_type, "bind", "defaults");
        }

        // close file
        close(fd);
    }

    LOGI("Booting Android\n");

    // save state
    state_save();

    // add trigger events
    rc = util_append_string_to_file("/init.rc", "\n\n"
                                    "on early-init\n"
                                    // wait for coldboot
                                    "    wait /dev/.coldboot_done\n"
                                    "\n"

                                    // start mbtrigger
                                    "    write "MBPATH_TRIGGER_CMD" early-init\n"
                                    "    start mbtrigger\n"
                                    "    wait "MBPATH_TRIGGER_WAIT_FILE"\n"

                                    // mbtrigger cleanup
                                    "    rm "MBPATH_TRIGGER_WAIT_FILE"\n"

                                    "on post-fs-data\n"
                                    // start mbtrigger
                                    "    write "MBPATH_TRIGGER_CMD" post-fs-data\n"
                                    "    start mbtrigger\n"
                                    "    wait "MBPATH_TRIGGER_WAIT_FILE"\n"

                                    // mbtrigger cleanup
                                    "    rm "MBPATH_TRIGGER_WAIT_FILE"\n"
                                    "\n"

                                    // trigger service
                                    "service mbtrigger "MBPATH_TRIGGER_BIN"\n"
                                    "    seclabel u:r:init_multiboot:s0\n"
                                    "    disabled\n"
                                    "    oneshot\n"
                                    "\n");
    if (rc) return rc;

    // run init
    return run_init(0);
}

redpajama_set_name: RedPajamaGithub


text:
versionBumpType=${1:-patch};

if [ "$versionBumpType" != "major" ] && [ "$versionBumpType" != "minor" ] && [ "$versionBumpType" != "patch" ]; then
  echo "Invalid version bump argument: ${versionBumpType}. Option must be one of the following: major, minor, patch"
  exit 1
else
  echo "Publishing and bumping with ${versionBumpType} version bump"
fi

echo "Running version bump + publish script..."
echo "."
echo "."
echo "Generating /dist and push changes + tags to Github remote 'origin'"
# Checkout master branch
git checkout master
# Version bump
grunt bump-only:"$versionBumpType"
# Generate new dist
grunt prod
# Generate new index.html page
grunt template
# Force add dist contents
git add dist/* --force
# Commit new release tag
grunt bump-commit
# Push commits/tags to master branch on remote 'origin'
git push origin master:master && git push --tags

## Update Github pages
echo "."
echo "."
echo "Updating Github pages"
echo "."
echo "."
# Generate index.html and /temp assetts for GH Pages branch
grunt build-gh-pages
# Create temporary copy of index file
cp index.html index-temp.html
# Checkout to `gh-pages` branch
git checkout -B gh-pages origin/gh-pages
git pull -r origin gh-pages
# Replace current files with temporary files
mv index-temp.html index.html
mv temp/bootstrap-slider.css css/bootstrap-slider.css
mv temp/bootstrap-slider.js js/bootstrap-slider.js
# Remove /temp directory
rm -rf temp
# Stage new files for commit
git add index.html css/bootstrap-slider.css js/bootstrap-slider.js
# Create commit with new files
git commit -m "updates"
# Push new source code to gh-pages branch
git push origin gh-pages:gh-pages -f
# Switch back to master branch
git checkout master

## Publish to NPM
echo "."
echo "."
echo "Publishing to NPM"
echo "."
echo "."
npm publish

# Notify script is complete
echo "."
echo "."
echo "Script complete"
echo ""


text:
layout: post
title: "Windows 8.1 Surface App Completed"
date:   2015-05-09 10:00:00
meta: "A Windows 8.1 project for the Store is complete."
categories: blog
tags: misc
---
We just completed a Windows 8.1 project designed for Microsoft Surface devices, which I've been working on for a while.  It will be used by a number of NFL football teams, including my home town Seattle Seahawks (go hawks!).  It was a lot of fun, and a great experience.  It will be even more exciting to watch the Seahawks play later this year :-)


text:
package org.apache.flink.table.runtime.operators.python;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.python.PythonFunctionRunner;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.python.PythonFunctionInfo;
import org.apache.flink.table.runtime.runners.python.PythonScalarFunctionRunner;
import org.apache.flink.table.runtime.types.CRow;
import org.apache.flink.table.runtime.types.CRowTypeInfo;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;

import org.apache.beam.sdk.fn.data.FnDataReceiver;

import java.util.Arrays;

/**
 * The Python {@link ScalarFunction} operator for the legacy planner.
 */
@Internal
public class PythonScalarFunctionOperator extends AbstractPythonScalarFunctionOperator<CRow, CRow, Row, Row> {

	private static final long serialVersionUID = 1L;

	/**
	 * The collector used to collect records.
	 */
	private transient StreamRecordCRowWrappingCollector cRowWrapper;

	/**
	 * The type serializer for the forwarded fields.
	 */
	private transient TypeSerializer<CRow> forwardedInputSerializer;

	public PythonScalarFunctionOperator(
		PythonFunctionInfo[] scalarFunctions,
		RowType inputType,
		RowType outputType,
		int[] udfInputOffsets,
		int[] forwardedFields) {
		super(scalarFunctions, inputType, outputType, udfInputOffsets, forwardedFields);
	}

	@Override
	public void open() throws Exception {
		super.open();
		this.cRowWrapper = new StreamRecordCRowWrappingCollector(output);

		CRowTypeInfo forwardedInputTypeInfo = new CRowTypeInfo(new RowTypeInfo(
			Arrays.stream(forwardedFields)
				.mapToObj(i -> inputType.getFields().get(i))
				.map(RowType.RowField::getType)
				.map(TypeConversions::fromLogicalToDataType)
				.map(TypeConversions::fromDataTypeToLegacyInfo)
				.toArray(TypeInformation[]::new)));
		forwardedInputSerializer = forwardedInputTypeInfo.createSerializer(getExecutionConfig());
	}

	@Override
	public void bufferInput(CRow input) {
		CRow forwardedFieldsRow = new CRow(Row.project(input.row(), forwardedFields), input.change());
		if (getExecutionConfig().isObjectReuseEnabled()) {
			forwardedFieldsRow = forwardedInputSerializer.copy(forwardedFieldsRow);
		}
		forwardedInputQueue.add(forwardedFieldsRow);
	}

	@Override
	public Row getUdfInput(CRow element) {
		return Row.project(element.row(), udfInputOffsets);
	}

	@Override
	@SuppressWarnings("ConstantConditions")
	public void emitResults() {
		Row udfResult;
		while ((udfResult = udfResultQueue.poll()) != null) {
			CRow input = forwardedInputQueue.poll();
			cRowWrapper.setChange(input.change());
			cRowWrapper.collect(Row.join(input.row(), udfResult));
		}
	}

	@Override
	public PythonFunctionRunner<Row> createPythonFunctionRunner(FnDataReceiver<Row> resultReceiver) {
		return new PythonScalarFunctionRunner(
			getRuntimeContext().getTaskName(),
			resultReceiver,
			scalarFunctions,
			scalarFunctions[0].getPythonFunction().getPythonEnv(),
			udfInputType,
			udfOutputType,
			getContainingTask().getEnvironment().getTaskManagerInfo().getTmpDirectories());
	}

	/**
	 * The collector is used to convert a {@link Row} to a {@link CRow}.
	 */
	private static class StreamRecordCRowWrappingCollector implements Collector<Row> {

		private final Collector<StreamRecord<CRow>> out;
		private final CRow reuseCRow = new CRow();

		/**
		 * For Table API & SQL jobs, the timestamp field is not used.
		 */
		private final StreamRecord<CRow> reuseStreamRecord = new StreamRecord<>(reuseCRow);

		StreamRecordCRowWrappingCollector(Collector<StreamRecord<CRow>> out) {
			this.out = out;
		}

		public void setChange(boolean change) {
			this.reuseCRow.change_$eq(change);
		}

		@Override
		public void collect(Row record) {
			reuseCRow.row_$eq(record);
			out.collect(reuseStreamRecord);
		}

		@Override
		public void close() {
			out.close();
		}
	}
}


text:
description(
"This tests that bytecode code generation doesn't crash when it encounters odd cases of an ignored result."
);

function emptyStatementDoWhileTest()
{
    do
        ;
    while (false) { }
    return true;
}

shouldBeTrue("emptyStatementDoWhileTest()");

function debuggerDoWhileTest()
{
    do
        debugger;
    while (false) { }
    return true;
}

shouldBeTrue("debuggerDoWhileTest()");

function continueDoWhileTest()
{
    var i = 0;
    do
        i++;
    while (i < 10) {
        do
            continue;
        while (false) { }
    }
    return true;
}

shouldBeTrue("continueDoWhileTest()");

function breakDoWhileTest()
{
    var i = 0;
    do
        i++;
    while (i < 10) {
        do
            continue;
        while (false) { }
    }
    return true;
}

shouldBeTrue("breakDoWhileTest()");

function tryDoWhileTest()
{
    do
        try { } catch (o) { }
    while (false) { }
    return true;
}

shouldBeTrue("tryDoWhileTest()");


text:
/*
** Author: Eric Veach, July 1994.
// C# Port port by: Lars Brubaker
//                  larsbrubaker@gmail.com
// Copyright (C) 2007
**
*/

using System;
namespace Tesselate
{
    public class ContourVertex : IComparable<ContourVertex>
    {
        internal ContourVertex _nextVertex;		/* next vertex (never null) */
        internal ContourVertex _prevVertex;		/* previous vertex (never null) */
        internal HalfEdge _edgeThisIsOriginOf;	/* a half-edge with this origin */
        internal int _clientIndex;		/* client's data */
        /* Internal data (keep hidden) */
        /* vertex location in 3D */

        internal double _C_0;
        internal double _C_1;
        internal double _C_2;
        internal double x, y;		/* projection onto the sweep plane */
        internal RefItem<ContourVertex> _priorityQueueHandle;	/* to allow deletion from priority queue */

        public int CompareTo(ContourVertex otherVertex)
        {
            if (VertEq(otherVertex))
            {
                return 0;
            }
            if (this.VertLeq(otherVertex))
            {
                return -1;
            }
            return 1;
        }

        public bool Equal2D(ContourVertex OtherVertex) => (x == OtherVertex.x && y == OtherVertex.y);

        public static double EdgeEval(ContourVertex u, ContourVertex v, ContourVertex w)
        {
            /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w),
             * evaluates the t-coord of the edge uw at the s-coord of the vertex v.
             * Returns v.t - (uw)(v.s), ie. the signed distance from uw to v.
             * If uw is vertical (and thus passes thru v), the result is zero.
             *
             * The calculation is extremely accurate and stable, even when v
             * is very close to u or w.  In particular if we set v.t = 0 and
             * let r be the negated result (this evaluates (uw)(v.s)), then
             * r is guaranteed to satisfy MIN(u.t,w.t) <= r <= MAX(u.t,w.t).
             */
            double gapL, gapR;
            if (!((u.VertLeq(u) && v.VertLeq(v))))
            {
                throw new Exception();
            }

            gapL = v.x - u.x;
            gapR = w.x - v.x;
            if (gapL + gapR > 0)
            {
                if (gapL < gapR)
                {
                    return (v.y - u.y) + (u.y - w.y) * (gapL / (gapL + gapR));
                }
                else
                {
                    return (v.y - w.y) + (w.y - u.y) * (gapR / (gapL + gapR));
                }
            }

            // vertical line
            return 0;
        }

        static public double EdgeSign(ContourVertex u, ContourVertex v, ContourVertex w)
        {
            /* Returns a number whose sign matches EdgeEval(u,w) but which
             * is cheaper to evaluate.  Returns > 0, == 0 , or < 0
             * as v is above, on, or below the edge uw.
             */
            double gapL, gapR;
            if (!u.VertLeq(v) || !v.VertLeq(w))
            {
                throw new System.Exception();
            }

            gapL = v.x - u.x;
            gapR = w.x - v.x;
            if (gapL + gapR > 0)
            {
                return (v.y - w.y) * gapL + (v.y - u.y) * gapR;
            }
            /* vertical line */
            return 0;
        }

        public bool VertEq(ContourVertex v) => ((x == v.x) && y == v.y);

        public bool VertLeq(ContourVertex v) => ((x < v.x) || (x == v.x && y <= v.y));

        public bool TransLeq(ContourVertex v) => ((y < v.y) || (y == v.y && x <= v.x));

        public static bool VertCCW(ContourVertex u, ContourVertex v, ContourVertex w)
        {
            /* For almost-degenerate situations, the results are not reliable.
             * Unless the floating-point arithmetic can be performed without
             * rounding errors, *any* implementation will give incorrect results
             * on some degenerate inputs, so the client must have some way to
             * handle this situation.
             */
            return (u.x * (v.y - w.y) + v.x * (w.y - u.y) + w.x * (u.y - v.y)) >= 0;
        }

#if DEBUG
        public override string ToString()
        {
            return _C_0 + "," + _C_1 + "," + _C_2;
        }
#endif
    }
}


text:
GoldStandards
=============

Each GS file is serialized in a TSV (tab separated value file) format.

The GS lists the cross language relations held by the surface forms
(generally variables or literals shared between couple of files).

The GS is structured as follows:
- src file name
- row number in which the surface form is spotted in the original project
- column number in which the surface form is spotted in the original project.
  '\t' is considered as 4 white spaces
- destination file name
- row number in which the surface form is spotted in the original project
- column number in which the surface form is spotted in the original project.
  '\t' is considered as 4 white spaces

# Authors
//

# Licence
Apache v2


text:
const { symbols } = require("@realm/common");

const dictionaryHandler = {
  get(target, key) {
    // Allows us to detect if this is a proxied Dictionary on JSC pre-v11. See realm-common/symbols.ts for details.
    if (key === symbols.IS_PROXIED_DICTIONARY) {
      return true;
    }

    if (typeof target[key] === "function") {
      return function () {
        return target[key].apply(target, arguments);
      };
    }

    if (typeof key === "symbol") {
      key = Symbol.keyFor(key);
    }

    return target.getter(key);
  },

  set(target, key, value, receiver) {
    target.setter(key, value);
    return receiver;
  },

  has(target, key) {
    return target._has(key);
  },

  deleteProperty(target, key) {
    // this array must be kept in sync with methods implemented by js_dictonary.hpp
    const methodNames = ["set", "remove", "addListener", "removeListener", "removeAllListeners"];
    if (!methodNames.includes(key)) {
      target.remove(key);
    }
    return true;
  },

  ownKeys(target) {
    return target._keys();
  },

  getOwnPropertyDescriptor() {
    return {
      enumerable: true,
      configurable: true,
      writeable: true,
    };
  },
};

function DictionaryProxy(dictionary) {
  return new Proxy(dictionary, dictionaryHandler);
}

module.exports = {
  DictionaryProxy,
};


text:
The OpenROAD unit testing framework is a OpenROAD language version of JUnit, by smart cookies Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent's Smalltalk testing framework. Each is the de facto standard unit testing framework for its respective language.

This document explains the OpenROAD-specific aspects of the design and usage of the OpenROAD UnitTest Framework.
For background information on the basic design of the framework the reader is referred to Kent's original paper, "Simple Smalltalk Testing: With Patterns".

The following information assumes knowledge of OpenROAD.

## System requirements

  * OpenROAD 6.2 (due to renameapp requirement)
       * Ingres (for example Ingres 10.2 + latest patch) for test database
  * Cygwin (from https://www.cygwin.com/)
      * bash (some bash extensions have been used)
      * diffutils (diff)

## Using the OpenROAD UnitTest Framework to write tests

### Installation

The components needed to write and run tests can be found in the 'UnitTestFramework' application.

To be able to use it from your own code, import the `UnitTestFramework` application from the `UnitTestFramework.xml` file into your repository database. Then you can use this application as an included application in your own application.

Note that you will have to do this before you can run the examples that are provided with the OpenROAD UnitTest Framework unless you run one of the command line scripts (or_tests.bash or or_tests.bat), which will import the 'UnitTestFramework.xml' file before importing and executing other test applications.

### The Framework

The framework is very simple, it consists of:

  * A set of user classes similar to JUnit (Test, TestCase, Assert, Error, etc.)
  * A set of global variables (G_Error to reference the error of the last "Exception", G_Assert to reference the Assert object providing assertion methods, G_Helper to provide Helper functionally)
  * The TestRunnerGhost frame, that invokes the "run" method on the test suite referenced in an attribute of the Helper object (G_Helper global variable), and writes out test results and statistics/timings.
  * The 4GL procedure "executeTests" that adds a test to the test suite in the Helper object, which will start the TestRunnerGhost frame (as independent thread).
  * The 3GL Procedure GetTickCount() - used for timing calculation

### Environment variables used by the OpenROAD UnitTest Framework

The following environment variables are used when running tests using the framework:

  * `OR_UNITTEST_TESTDIR` Specifies a directory used for testing input/output. If not set it defaults to the current working directory. This directory must be writeable by the user.
  * `OR_UNITTEST_GEN_XML_STATS` Specifies if test statistics should be written in JUnit XML format. Valid values TRUE and FALSE (default).
  * `OR_UNITTEST_STATSFILE` Specifies the file (including path) the test statistics will be written to. If not set it defaults to `orunitteststats.log` in the directory specified by the `OR_UNITTEST_TESTDIR` environment variable.
  * `OR_UNITTEST_STATSFILE_XML` Specifies the file (including path) the XML test statistics will be written to. If not set it defaults to `orunitteststats.xml` in the directory specified by the `OR_UNITTEST_TESTDIR` environment variable. It is only used if `OR_UNITTEST_GEN_XML_STATS=TRUE`.
  * `OR_UNITTEST_TMPDIR` Specifies a directory used for temporary files used by the test cases. If not set it defaults to to a directory named `temp` in the directory specified by the `OR_UNITTEST_TESTDIR` environment variable.
  If this does not exist, a `testtemp` directory in the current working directory will be used.
  If this doesn't exist either, the following envronment variables will be checked (in this order): `II_TEMPORARY`, `TMPDIR`, `TEMP`, `TMP`.
  If they are not set the following directories are checked (in this order):
  On Unix: `/tmp`, `/var/tmp`, `/usr/tmp`
  On Windows: `C:\TEMP`, `C:\TMP`, the `TEMP` and `TMP` directories under the current working directory
  If none of the above exists, then the current working directory will be used.
  * `OR_UNITTEST_RESOURCEDIR` Specifies a directory containing additional resources (files) used for the tests. If not set it defaults to to a directory named `resources` in the directory specified by the `OR_UNITTEST_TESTDIR` environment variable.
  If this does not exist, a `resources` directory in the current working directory will be used.
  If this doesn't exist either, the temporary directory (see `OR_UNITTEST_TMPDIR` above) will be used.

### Test Cases

The basic building blocks of unit testing are "test cases", which represent scenarios that must be set up and checked for correctness. In the OpenROAD UnitTest Framework, test cases are represented by the TestCase class in the UnitTestFramework application. To make your own test cases you must create subclasses of TestCase.

An instance of a TestCase class is an object that can run test methods, together with optional set-up and tidy-up code.

The testing code of a TestCase instance should be entirely self contained and [idempotent](https://en.wikipedia.org/wiki/Idempotence), such that it can be run either in isolation or in arbitrary combination with any number of other test cases.

### Creating a simple test case

  1. Create a new application:
       1. Include application `UnitTestFramework` in the new application.
  2. Within the application create a new User Class:
       1. Make sure the superclass is `testcase` (from the `UnitTestFramework` application).
       2. Create a new test method in the Userclass editor, make sure the method's name starts with `test`.
       3. Create the code for the test method in the Script of the class.

         Within the test\* methods you execute the methods/procedures to be tested (add other components needed within the test methods to the application).
         In order to test something, use one of the 'assert\*' methods of the Assert class (using G_Assert global variable). If the assertion fails when the test case runs, an AssertionError will be raised, and the testing framework will identify the test case as a 'failure'. Other exceptions that do not arise from explicit 'assert' checks are identified by the testing framework as 'errors'.

         Example script:

```
         METHOD test1()=
         {
             G_Assert.assertEquals(expectedVarchar='ingres', actualVarchar=CurSession.UserName, errortext = 'This test has to be run by user "ingres"!');
         }
```
  3. Create 4gl procedure named `runtests`

      1. Ensure `runtests` calls the 4GL procedure `executeTests`with parameter `test` set to an object of the TestCase userclass above

         Example script:

```
         PROCEDURE runtests()=
         {
             CALLPROC executeTests(test = MyTest.Create());
         }
```

      2. Ensure `runtests` is the starting component for the application
  4. Run your test application - results will be written to the log file (and Trace Window if it exists)

### Re-using set-up and tear-down code

Now, such test cases can be numerous, and their set-up can be repetitive.

In order to prevent duplication such set-up code can be factored out by overriding a method called `setUp()`, which the testing framework will automatically invoke before the test method(s) run.
Similarly, tear-down code can be factored out by overriding a method called `tearDown()`, which the testing framework will automatically invoke after all test method(s) ran in order to tidy-up.

Example script:
```
    INITIALIZE=
    DECLARE
        table_names = ARRAY OF StringObject;
        i = INTEGER NOT NULL;
    ENDDDECLARE

    METHOD setUp()=
    {
        i=1;
        // Populate the table_name array once - it will be used in several test methods
        SELECT table_name as table_names[i].Value FROM iitables WHERE owner = _dba()
        BEGIN
            i=i+1;
        END;
        COMMIT;
    }
```

### TestCase classes with several test methods

A TestCase subclass can have several test methods, all of them having a name starting with `test`.
All these methods will be executed when running the test.
The methods are invoked in alphabetical order (case-insensitive).

### Applications with several test classes

When having multiple test classes in a test application,
they can all be executed by adding a call to `executeTests()` for each of them within the in the `runtests()` procedure.

### Skipping tests

A test can be skipped by invoking the `skipTest()` method (using the G_Assert global variable).
This can be done in either the `setUp()` method (which will skip all tests in the class) or in each test method.

Example script:

```
    METHOD Setup()=
    BEGIN
        IF CurSession.OperatingSystem = SY_UNIX THEN
            G_Assert.SkipTest(errortext = 'The features to be tested are not supported on Unix.');
        ENDIF;
    END
```

### Where to place testing code

You can place the definitions of test cases and test suites in the same application as the code they are to test,
but there are several advantages to placing the test code in a separate application:

* The shipped code does not need to include the UnitTestFramework application
* The test application can be run standalone from the command line
* The test code can more easily be separated from shipped code
* There is less temptation to change test code to fit the code it tests without a good reason
* Test code should be modified much less frequently than the code it tests
* Tested code can be refactored more easily
* If the testing strategy changes, there is no need to change the source code

### Test Results

Test results (status, timings, etc.) are logged in the log file (and trace window).
You can also run the application from command line and test the return status of the application.
The exit codes have the following meaning:

Code | Explanation
---- | -----------
0 | Success (OK)
1 | Error/failure
2 | Skipped tests (but otherwise ok)

### Running tests interactively

A test application can be run interactively from the OpenROAD Workbench using a "Run" menu item or toolbar button.

### Running tests from the command line

In order to run tests from the command line you can use the following command:

w4gldev rundbapp _database testapplication_ -Llogfile -Tyes

There is also a script file `or_tests.bash` (and wrapper batch script `or_tests.bat` for Windows calling `or_tests.bash`),
which will execute all test case applications which have been placed as XML export files in the `unittests` subdirectory.
This script will import the UnitTestFramework application from the 'UnitTestFramework.xml' file before importing and executing other test applications in the `unittests` subdirectory.

Usage:    bash or_tests.bash _testdatabase_

The script will also print out the test results to the console.

### Configuring tests run by or_tests.bash

There are configuration options for tests that are run automated by using or_tests.bash script described above.

#### Ignoring tests

If there is a file called `ignore_apps.lst` in the `unittests` subdirectory, then the applications listed in this file will be ignored.
That is, the _application_ will not be executed.
These tests will be indicated with an `IGNORED` status in the output of or_tests.bash.

#### Configuring tests

Tests for an application can be configured using an optional _application_.cfg file in the `unittests` subdirectory.
The file can contain lines in the format

OPTION=value

with the following meaning:

OPTION | Explanation
------ | -----------
RUNNER | Specifies the command used to execute the test application after importing. This could also be a (batch) script. Default: `w4gldev rundbapp ...`; If set to `runimage` the application will be imaged using makeimage before running using "w4gldev rundbapp"
RUNTIMEOUT | Specifies the timeout period in secs when running the test application - default value: 300. After the timeout period the process running the test will be aborted.
RUNFLAGS | Specifies additional command line flags passed to the RUNNER.
MAKEIMAGEFLAGS | Specifies additional flags used by the makeimage command, if RUNNER is set to `runimage`.

### The GUI test runner

There is a graphical front end that you can use in order to run your tests.
To use the GUI test runner, simply run the `UnitTestRunner` application (can be imported from `UnitTestRunner.xml`)
either from the Workbench or from command line.

### Asertion methods

There are several methods of the Assert class (available via the G_Assert global variable), which can be used to test different conditions,
usually to compare an actual value with an expected value:
* assertEquals()
* assertGreaterEquals()
* assertGreaterThan()
* assertLessEquals()
* assertLessThan()
* assertNotEquals()
* assertNotNull()
* assertNotSame()
* assertNull()
* assertSame()

### Helper attributes and methods

The Helper class (available via the G_Helper global variable) provides useful attributes and methods that can be used within the test methods:

Attribute | Explanation
--------- | -----------
DirectorySeparator | The OS specific directory separator
ResourceDir | The directory containing resource files - see description of the `OR_UNITTEST_RESOURCEDIR` environment variable
TempDir | The directory containing temporary files - see description of the `OR_UNITTEST_TMPDIR` environment variable
TestDir | The directory containing test files - see description of the `OR_UNITTEST_TESTDIR` environment variable
TestStatsFile | The file test statistics will be written to - see description of the `OR_UNITTEST_STATSFILE` environment variable
TestStatsFileXml | The XML file test statistics will be written to - see description of the `OR_UNITTEST_STATSFILE_XML` environment variable

Method              | Explanation
------------------- | -----------
GetResourceFilePath | Returns a file path in the ResourceDir created from a `filename` in portable format (using "!" directory separator)
GetTempFilePath     | Returns a file path in the TempDir created from a `filename` in portable format (using "!" directory separator); optional `register_name` parameter specifies if the filename should be registered for deletion using RemoveRegisteredTempFile() or RemoveRegisteredTempFiles()
LocalFilename       | Returns a file name in local (OS specific) format created from a `filename` in portable format (using "!" directory separator)
RemoveFile          | Removes file with the given `filename` in local (OS specific) format
RemoveRegisteredTempFile | Removes registered file with `filename` in portable format
RemoveRegisteredTempFiles | Removes all registered files

## Terms of use

See the LICENSE file.


text:
import threading
import time

# Worker thread
def worker(n, sema):
    # Wait to be signalled
    sema.acquire()
    # Do some work
    print("Working", n)

# Create some threads
sema = threading.Semaphore(0)
nworkers = 10
for n in range(nworkers):
    t = threading.Thread(target=worker, args=(n, sema,))
    t.daemon=True
    t.start()

print('About to release first worker')
time.sleep(5)
sema.release()
time.sleep(1)
print('About to release second worker')
time.sleep(5)
sema.release()
time.sleep(1)
print('Goodbye')


text:
package org.elasticsearch.search.aggregations.bucket.histogram;

import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.CardinalityUpperBound;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.bucket.BucketsAggregator;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalHistogram.EmptyBucketInfo;
import org.elasticsearch.search.aggregations.bucket.terms.LongKeyedBucketOrds;
import org.elasticsearch.search.aggregations.support.AggregationContext;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiConsumer;

import static org.elasticsearch.search.aggregations.bucket.histogram.DoubleBounds.getEffectiveMax;
import static org.elasticsearch.search.aggregations.bucket.histogram.DoubleBounds.getEffectiveMin;

/**
 * Base class for functionality shared between aggregators for this
 * {@code histogram} aggregation.
 */
public abstract class AbstractHistogramAggregator extends BucketsAggregator {
    protected final DocValueFormat formatter;
    protected final double interval;
    protected final double offset;
    protected final BucketOrder order;
    protected final boolean keyed;
    protected final long minDocCount;
    protected final DoubleBounds extendedBounds;
    protected final DoubleBounds hardBounds;
    protected final LongKeyedBucketOrds bucketOrds;

    public AbstractHistogramAggregator(
        String name,
        AggregatorFactories factories,
        double interval,
        double offset,
        BucketOrder order,
        boolean keyed,
        long minDocCount,
        DoubleBounds extendedBounds,
        DoubleBounds hardBounds,
        DocValueFormat formatter,
        AggregationContext context,
        Aggregator parent,
        CardinalityUpperBound cardinalityUpperBound,
        Map<String, Object> metadata
    ) throws IOException {
        super(name, factories, context, parent, CardinalityUpperBound.MANY, metadata);
        if (interval <= 0) {
            throw new IllegalArgumentException("interval must be positive, got: " + interval);
        }
        this.interval = interval;
        this.offset = offset;
        this.order = order;
        order.validate(this);
        this.keyed = keyed;
        this.minDocCount = minDocCount;
        this.extendedBounds = extendedBounds;
        this.hardBounds = hardBounds;
        this.formatter = formatter;
        bucketOrds = LongKeyedBucketOrds.build(bigArrays(), cardinalityUpperBound);
    }

    @Override
    public InternalAggregation[] buildAggregations(long[] owningBucketOrds) throws IOException {
        return buildAggregationsForVariableBuckets(owningBucketOrds, bucketOrds, (bucketValue, docCount, subAggregationResults) -> {
            double roundKey = Double.longBitsToDouble(bucketValue);
            double key = roundKey * interval + offset;
            return new InternalHistogram.Bucket(key, docCount, keyed, formatter, subAggregationResults);
        }, (owningBucketOrd, buckets) -> {
            // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order
            CollectionUtil.introSort(buckets, BucketOrder.key(true).comparator());

            EmptyBucketInfo emptyBucketInfo = null;
            if (minDocCount == 0) {
                emptyBucketInfo = new EmptyBucketInfo(
                    interval,
                    offset,
                    getEffectiveMin(extendedBounds),
                    getEffectiveMax(extendedBounds),
                    buildEmptySubAggregations()
                );
            }
            return new InternalHistogram(name, buckets, order, minDocCount, emptyBucketInfo, formatter, keyed, metadata());
        });
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        InternalHistogram.EmptyBucketInfo emptyBucketInfo = null;
        if (minDocCount == 0) {
            emptyBucketInfo = new InternalHistogram.EmptyBucketInfo(
                interval,
                offset,
                getEffectiveMin(extendedBounds),
                getEffectiveMax(extendedBounds),
                buildEmptySubAggregations()
            );
        }
        return new InternalHistogram(name, Collections.emptyList(), order, minDocCount, emptyBucketInfo, formatter, keyed, metadata());
    }

    @Override
    public void doClose() {
        Releasables.close(bucketOrds);
    }

    @Override
    public void collectDebugInfo(BiConsumer<String, Object> add) {
        add.accept("total_buckets", bucketOrds.size());
        super.collectDebugInfo(add);
    }
}


text:
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
module Refined.LessThanEq where

import Refined (Predicate(..))
import Data.Monoid ((<>))

import GHC.TypeLits (Nat, KnownNat, natVal)

data LessThanEq (n :: Nat)

instance (Ord x, Num x, KnownNat n) => Predicate (LessThanEq n) x where
  validate p x =
    if x <= fromIntegral x'
      then Nothing
      else Just ("Value is not less than or eq " <> show x')
    where
      x' = natVal p


text:
<?php

namespace Cekurte\Resource\Query\Language\Expr;

use Cekurte\Resource\Query\Language\Contract\ExprInterface;
use Cekurte\Resource\Query\Language\Expr\GteExpr;

/**
 * LteExpr
 *
 * @author João Paulo Cercal <jpcercal@gmail.com>
 */
class LteExpr extends GteExpr implements ExprInterface
{
    /**
     * @inheritdoc
     */
    public function __construct($field, $value)
    {
        parent::__construct($field, $value);

        $this->expression = 'lte';
        $this->operator   = '<=';
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'Less than or equal';
    }
}


text:
**Sand** is a fun physics based drawing game that you can play on your browser, you can use different colors to draw as well as change the nature of your drawn pixels to simulate the behavior of gravity on water, rock and air.

As with writing any type of game, you always need to have the following features:

- User interface
- Data structures.
- Game engine which handles: graphics and user input
- The main game loop
- Physics effects

## **Project Structure**

Our project is quite simple, so we'll go ahead and create 3 new files:

 ![files](files.png)

- **logic.js** : This file will contain all of our JavaScript logic and game implementation
- **main.html** : We will put our game UI here, for now all we need is a "screen" and instructions, so this should be simple to setup.
- **style.css** : Some styling for our UI.

You can initialize a **git** repository if you want to keep track of your changes, but since this is a one day project, we'll go ahead without it.

## User Interface

Any game needs a proper User Interface, otherwise it would be unplayable, in our cases we don't need to create something fancy, so let's get started.

We'll go ahead and create our **main.html** file:

```html
<!DOCTYPE html>

<html>
<head>
    <title>Sand Game</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
    <canvas id="screen" width="960" height="640"></canvas>

    <section id="guide"></section>

    <script type="text/javascript" src="logic.js"></script>
</body>
</html>

```

As you can see, it's quite straight forward, we have our **canvas** element where the game will be rendered (We'll talk about more this later in this tutorial), a **guide** section to explain how the game can be played and finally we include our logic JavaScript.

We'll go ahead and set the guide code block as follows:

```html
    <section id="guide">
        <p>Use your mouse to draw.</p>

        <p>To change drawing color/type, you can press:</p>

        <p>To clear the screen press <b>Escape</b></p>

        <br/>

        <ul class="keyboard">
            <li><span>A</span> Air</li>
            <li><span>W</span> Water</li>
            <li><span>S</span> Static</li>
            <li><span>L</span> Land</li>
        </ul>

        <ul class="keyboard">
            <li><span>1</span> Orange</li>
            <li><span>2</span> Light blue</li>
            <li><span>3</span> Yellow</li>
            <li><span>4</span> Light Green</li>
        </ul>

        <ul class="keyboard">
            <li><span>5</span> Pink</li>
            <li><span>6</span> Gray</li>
            <li><span>7</span> Purple</li>
            <li><span>8</span> Blue</li>
        </ul>

        <ul class="keyboard">
            <li><span>9</span> Magenta</li>
            <li><span>0</span> Black</li>
            <li><span>-</span> Brown</li>
            <li><span>=</span> Red</li>
        </ul>

        <br class="clear" />
    </section>

```

This will display a list of keyboard keys that the player can use to change the type of pixels he's drawing. The player can also press **Escape** to clear the entire screen.

We can now style our UI to make nice and clean, you can go ahead and add the following code to the **style.css** file:

```css
* {
    margin: 0px;
}

html {
    font-family: Tahoma;
}

p {
    text-align: center;
    margin-bottom: 10px;
}

.clear {
    clear: both;
}

#screen {
    margin: 20px auto 0px auto;
    display: block;
    border: 4px solid #898989;
}

#screen:hover {
    cursor: crosshair;
}

#guide {
    width: 960px;
    padding-top: 30px;
    margin: 0px auto;
}

.keyboard {
    float: left;
    width: 25%;
    margin: 0px;
    box-sizing: border-box;
    list-style: none;
    padding-bottom: 20px;
}

.keyboard li {
    margin-bottom: 10px;
}

.keyboard li span {
    display: inline-block;
    padding: 6px 0px;
    width: 36px;
    text-align: center;
    border-radius: 4px;
    background-color: #e5e5e5;
    font-weight: bold;
    margin-right: 10px;
}
```

You can now open the main.html file in your browser, and if you did everything correctly, you should see the following result:

![ui-1](ui-1.png)

 We have a UI now! all we have to do now is bring to it life.

## Data structures.

Since this is a drawing game, our only game object is the screen itself. So to keep things simple we'll be modeling our screen in the form of a 2 dimensional array, in the spirit of keeping things simple.

## Game Engine

Since we're building a web game, we will be using **JavaScript** to write our game logic, I chose to encapsulate the entire engine into one big class called **Sand**, let's go ahead and add it to our **logic.js** file:

```javascript
/**
 * Implements a physics based drawing game.
 * @class
 * @namespace
 * @this {Sand}
 */
function Sand() {
    /* Class initialization code goes here. */
}
```

Don't be alarmed, that is indeed a function and not a class, but in JavaScript there is a nifty feature callled **Prototypal Inheritance**, which allows you to implement **class** models similar to how you would do it in **Object Oriented Programming**, but it is not quite the same thing, you can learn more about this here: http://javascript.crockford.com/prototypal.html

### **Graphics**

One of the best ways to program games on the web is by using the HTML5 **Canvas API**, which is basically a drawing board with a great set of tools that we can use to paint anything we like, from rectangles and circles to paths and images. You can learn more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API

Using **Canvas** will greatly simplify our task, as we can rely on ready to use functions and methods to draw stuff.

We'll go ahead and add some **Canvas** related properties to our class:

```javascript
/**
 * Implements a physics based drawing game.
 * @class
 * @namespace
 * @this {Sand}
 */
function Sand() {
    /**
     * The first property is screenCanvas which is just a reference to the DOM canvas element we
     * added to our html document earlier, we'll be using this to get our 2d drawing context as
     * well as some attributes such as the width and height which will be used later.
     */
    this.screenCanvas = document.getElementById( "screen" );

    /**
     * The second property, canvasContext, is the  canvas context object, which contains all of
     * the powerful canvas APIs that you can use to interact with it. We'll use this mainly to
     * draw our pixels in our screen.
     */
    this.canvasContext = this.screenCanvas.getContext( "2d" );

    /**
     * The third property, tileSize, is the size of each "pixel" in our game screen, it's
     * basically the number of actual pixels our rectangular tile will occupy in the canvas box.
     * Starting from now we'll refer to the drawn pixels as tiles, so that we can differentiate
     * between the big game pixels and the actual browser/display pixels. This argument will be
     * used to do some calculations as well as draw our tiles.
     */
    this.tileSize = 10;

    /**
     * The following 2 properties are the number of tiles in each direction of our screen, we
     * divide the actual dimensions of our canvas - that we set as element attributes in our
     * html file - by the tile size, which gives us how many tiles we will be able to fit in our
     * screen.
     */
    this.horizontalTileCount = this.screenCanvas.width / this.tileSize;
    this.verticalTileCount = this.screenCanvas.height / this.tileSize;

  	/* This is our screen, as explained earlier, this will be a 2 dimensional array. */
    this.tiles = [];
}

/* We instantiate our class with thew new keyword. See just like OO programming! */
var game = new Sand();
```

You can go ahead and refresh your page now, if you did everything correctly, then you should see no difference compared to the previous phase, however keep an eye on your browser developer console, in case there are some errors.

Next we'll add some constants that we will be using in our physics and graphics logic, you can go ahead and add the following code to the top of your **logic.js** file, right before the **Sand** class:

```javascript
/* Tile types and colors. */
var TILE_AIR = "a",
    TILE_LAND  = "l",
    TILE_WATER  = "w",
    TILE_STATIC = "s",
    /* This array will be used in screen intialization */
    TILE_TYPES = [ TILE_AIR, TILE_LAND, TILE_WATER, TILE_STATIC ],
    /* This object will be used to decide which color to use when we're drawing each tile. */
    TILE_COLORS = {
        "a": "#ffffff",
        "l": "#2affa2",
        "w": "#add8e6",
        "s": "#000000",
        "0": "#000000",
        "1": "#f7941d",
        "2": "#00ffff",
        "3": "#fff200",
        "4": "#00ff00",
        "5": "#ec008c",
        "6": "#959595",
        "7": "#92278f",
        "8": "#0000ff",
        "9": "#ff00ff",
        "-": "#754c24",
        "=": "#ed1c24"
    };
```

As you can see, we have 4 tile natures: air, land, water, and static tiles which can have multiple colors.

Static tiles can either have the value **s** or the other color values. All of them are considered static tiles, they are basically tiles that don't move when drawn and they don't have any kind of physics effect.

### **Initialization**

We'll go ahead and add a new method to our **Sand** class, called **initialize**, this method will initialize our screen data structure to randomized values, just for the fun of it. You can add this code right after your **Sand** class:

```javascript
/**
 * Initializes the screen with randomized tiles.
 * @name initialize
 * @function
 * @memberof Sand
 * @returns {void}
 */
Sand.prototype.initialize = function() {
    var i = 0, L = this.horizontalTileCount,
        j = 0, M = this.verticalTileCount,
        column = [];
    for( ; i < L; ++i ) {
        for( j = 0; j < M; ++j )
            /* As you can see here, we used TILE_TYPES to get random tile natures. */
            column.push( TILE_TYPES[ Math.floor( Math.random() * 4 ) ] );

        this.tiles.push( column );

        column = [];
    }
};
```

We'll go ahead and call this method in our main class constructor:

```javascript
function Sand() {
    this.screenCanvas = document.getElementById( "screen" );
    this.canvasContext = this.screenCanvas.getContext( "2d" );

    this.tileSize = 10;

    this.horizontalTileCount = this.screenCanvas.width / this.tileSize;
    this.verticalTileCount = this.screenCanvas.height / this.tileSize;

    this.tiles = [];

+   this.initialize(); /* New code! */
}

```

**Note:** If you're copy pasting the code, make sure to remove the **+** in front of each line, I am including those so that you can tell which new lines of code have been added. I highly advise you to type the code yourself, so that you can get used to it.

Now that we have our screen, we can go ahead and write some code to render it to our **Canvas**! To do that, we'll add a new method:

```javascript
/**
 * Redraws the a set of tiles
 * This is an optimization to avoid redrawing the entire screen
 * Instead we only draw the tile that have changes.
 * @name drawScreen
 * @function
 * @memberof Sand
 * @param {Array} tilesToRedraw A list of tiles (x, y and new value ) to redraw.
 * @returns {void}
 */
Sand.prototype.drawScreen = function( tilesToRedraw ) {
    var i = 0, L = tilesToRedraw.length,
        tiles = this.tiles;

    for( ; i < L; ++i ) {
        var tile = tilesToRedraw[ i ];

        tiles[ tile.x ][ tile.y ] = tile.value;

      	/* These are the only Canvas APIs we'll be using this game */
        /* This one changes the filling color that canvas will be using to draw. */
        this.canvasContext.fillStyle = TILE_COLORS[ tile.value ];

      	/**
      	 * This one tells canvas to draw a rectangle at the specified coordinates and with the
      	 * specified dimensions: x, y, width and height.
      	 */
        this.canvasContext.fillRect( tile.x * this.tileSize, tile.y * this.tileSize, this.tileSize, this.tileSize );
    }
};
```

As you've probably noticed, we've applied a nifty little optimization to our rendering code. Since the drawing is happening each time the game loop runs, it will significantly affect performance the larger our drawing screen gets. So to minimize this, we'll only give our drawing method a specific list of tiles to re-draw, these tiles are the ones that have changed since the last time the game loop has ran, this way we avoid redrawing everything every single time, which saves us resources and makes the game run much faster.

You can go ahead and add this code right after your **initialize** method.

### **First frame**

Since we initialized our screen with random tiles, and since we have an optimized rendering algorithm, we need to render the entire screen the first time the game runs, because everything everything is new in this case. so we'll go ahead and add the following code to our **Sand** class constructor:

```javascript
/**
 * Implements a physics based drawing game.
 * @class
 * @namespace
 * @this {Sand}
 */
function Sand() {
    this.screenCanvas = document.getElementById( "screen" );
    this.canvasContext = this.screenCanvas.getContext( "2d" );

    this.tileSize = 10;

    this.horizontalTileCount = this.screenCanvas.width / this.tileSize;
    this.verticalTileCount = this.screenCanvas.height / this.tileSize;

    this.tiles = [];

+   this.isDrawing = false; /* Flag: To check if we're currently drawing with the mouse. */

+   this.currentTileType = "s"; /* Current drawing tile type. Black static tile by default. */

    this.initialize();

+   var x = 0, L = this.horizontalTileCount,
+       y = 0, M = this.verticalTileCount,
+       tiles = this.tiles,
+       tilesToRedraw = [];

+   for( ; x < L; x++ ) {
+       for( y = 0; y < M; y++ ) {
+           tilesToRedraw.push(
+               { x: x, y: y, value: tiles[ x ][ y ] }
+           );
+       }
+   }

+   this.drawScreen( tilesToRedraw );
}

```

Go ahead and refresh your game page now, you should now see some results at last!

 ![ui-2](ui-2.png)

As you can see, the **initialize** method did its job!

### **Main Game Loop**

Let's go ahead and write our main game loop, which will be in the form of a method named **render**. This method will run continuously and will execute all the logic and drawing code.

Instead of using a traditional loop, and to maximize frame rate performance we will be using the HTML5 **requestAnimationFrame** API, this method allows our logic and rendering to run before the browser paints the next frame, which will make our animations run much smoother, and save resources when we're not focused on the game browser tab, since it gets paused in that case. You can learn more about this feature here: https://css-tricks.com/using-requestanimationframe/

Go ahead and this code right after your **drawScreen** method

```javascript
/**
 * Start the rendering game loop.
 * This handles all the game physics
 * @name render
 * @function
 * @memberof Sand
 * @returns {void}
 */
Sand.prototype.render = function() {
    var tilesToRedraw = [];

    /* Redraw the changed tiles. */
    this.drawScreen( tilesToRedraw );

    /* Execute the render function at next browser frame redraw. */
    requestAnimationFrame( this.render.bind( this ) );
};
```

And then call it after you instantiate your class, so that the game loop can start to run.

```javascript
    var  game = new Sand();
+   game.render(); /* Start the game! */
```

### **Physics Effects**

As explained in the beginning, our tiles will simulate gravity behavior that depends on their specific nature, whether it is water, air or land/stone.

We'll create a new method called **applyPhysics** which will loop through all tiles in our screen and apply a specific gravity behavior when it finds the required conditions for it to behave in such way. for instance if a land/stone tile is above a water tile, then the land/stone tile should switch places with as if it was faling through it, hence simulating gravity, we can apply the same logic for water/air and land/water situations.

We will also add one last behaviour specific to the water tiles. Since water is not solid, it moves if doesn't find a stable container where it can reach equilibrium. So to simulate this, we'll look for water tiles that have air tile neihbours and simply switch places with them. We'll also flip a coin to decide the direction our water tile will go.

This little trick will allows us to achieve a "liquid" effect, though not a 100% simulation, but it is close enough to pass.

Once this method finishes running, it will return the list of tiles that were affected, so that we can re-draw them as explained earlier.

You can go ahead and add the following code right below your **drawScreen** method:

```javascript
/**
 * Applie gravity effect on each type of tile.
 * This affects tiles of nature: water, air and land.
 * @name applyPhysics
 * @function
 * @memberof Sand
 * @returns {void}
 */
Sand.prototype.applyPhysics = function() {
    var x = 0, L = this.horizontalTileCount,
        y = 0, M = this.verticalTileCount,
        tiles = this.tiles,
        tile, tileBelow, tileBefore, tileBelowBefore,
        tilesToRedraw = [],
        changeOccurred = false;

    for( ; x < L; x++ ) {
        for( y = 0; y < M; y++ ) {
            tile = tiles[ x ][ y ];
            tileBelow = tiles[ x ][ y + 1 ];
            changeOccurred = false;

            if( y < M - 1 ) {
                /* Land tiles go down if there is water or air below them */
                if( tile === TILE_LAND && ( tileBelow === TILE_AIR || tileBelow === TILE_WATER ) ) {
                    changeOccurred = true;
                } else if( tile === TILE_WATER && tileBelow === TILE_AIR ) { /* Water tiles go down if there is air below them. */
                    changeOccurred = true;
                }

                /* Mark these tiles as changed, to avoid checking them again in the loop. */
                if( changeOccurred ) {
                    tilesToRedraw.push(
                        { x: x, y: y, value: tileBelow },
                        { x: x, y: y + 1, value: tile }
                    );

                    tiles[ x ][ y ] = -1;
                    tiles[ x ][ y + 1 ] = -1;

                    changeOccurred = false;
                }

                /* Do a coin flip and decide which direction to move water tiles, to simulate water behaviour. */
                if( x > 0 ) {
                    tileBefore = tiles[ x - 1 ][ y ];
                    tileBelowBefore = tiles[ x - 1 ][ y + 1 ];

                    var cointFlip = Math.floor( Math.random() * 2 );

                    if( cointFlip && tile === TILE_WATER && tileBefore == TILE_AIR && tileBelow !== TILE_AIR ) {
                        changeOccurred = true;
                    } else if( !cointFlip && tile === TILE_AIR && tileBefore === TILE_WATER && tileBelowBefore !== TILE_AIR ) {
                        changeOccurred = true;
                    }

                    /* Mark these tiles as changed, to avoid checking them again in the loop. */
                    if( changeOccurred ) {
                        tilesToRedraw.push(
                            { x: x, y: y, value: tileBefore },
                            { x: x - 1, y: y, value: tile }
                        );

                        tiles[ x ][ y ] = -1;
                        tiles[ x - 1 ][ y ] = -1;
                    }
                }
            }
        }
    }

    return tilesToRedraw;
};
```

And then call it in your **render** method:

```javascript
Sand.prototype.render = function() {
+   var tilesToRedraw = this.applyPhysics(); /* We replaced the previous line with a call to the physics method. */

+   /* Redraw the changed tiles. */
+   this.drawScreen( tilesToRedraw );

    /* Execute the render function at next browser frame redraw. */
    requestAnimationFrame( this.render.bind( this ) );
};
```

Refresh your page and check the results, you've got animation now! As you can see blue tiles behave like water, green tiles behave like land/stone, pretty cool!

### **User Input**

We're almost done with our game, all that is left now is to add our user input handling logic, since our game runs on the web, we can simple use the good old event listeners and set up callbacks to apply the changes.

**Mouse events:**

- **Mouse Down:** The user left clicked the mouse and hasn't released it yet,  we can tell the game engine that the user is attempting to draw.
- **Mouse Up:** The user has released the left click of the mouse, we can tell the game engine that the user stopped drawing.
- **Mouse Move:** So that we can tell where to draw our tiles within our canvas.

**Keyboard events:**

- **Alphanumeric**: Using the **TILE_COLORS** variable that we defined earlier, we can decide what type of tile to draw.
- **Escape Key:** Which will make the game engine clear the drawing screen entirely.

We'll go ahead and create a new method called **setupEvents**

You can add this code right below your **initialize** method:

```javascript
/**
 * Setup keyboard and mouse events*
 * - Keyboard: To change tile type and to reset the screen
 * - Mouse: To draw tiles.
 * @name setupEvents
 * @function
 * @memberof Sand
 * @returns {void}
 */
Sand.prototype.setupEvents = function() {
    var screenCanvas = this.screenCanvas;

    screenCanvas.addEventListener( "mousedown", this.startDrawing.bind( this ) );  //The state of clicking mouse.

    document.addEventListener( "mouseup", this.stopDrawing.bind( this ) );  //The state of mousebutton1 is up.
    document.addEventListener( "mousemove", this.processDrawing.bind( this ) );
    document.addEventListener( "keypress", this.updateCurrentTileType.bind( this ) );
    document.addEventListener( "keyup", this.clearScreen.bind( this ) );
};

```

All we've done is ask the browser to execute those callbacks every time an event is detected.

**Note:** We use the bind method to tell the browser to execute the callbacks with the right **this** context, you can learn more about this here: https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/

Let's add our input handling methods now, you can add this right below your **setupEvents** method:

```javascript
/**
 * Enables drawing when the mouse moves
 * This gets executed when we hold the left mouse button down.
 * @name startDrawing
 * @function
 * @memberof Sand
 * @param {Object} event DOM event object.
 * @returns {void}
 */
Sand.prototype.startDrawing = function( event ) {
    this.isDrawing = true;

    this.processDrawing( event );
};

/**
 * Disable drawing when the mouse moves
 * This gets executed when we release the left mouse button.
 * @name stopDrawing
 * @function
 * @memberof Sand
 * @param {Object} event DOM event object.
 * @returns {void}
 */
Sand.prototype.stopDrawing = function( event ) {
    this.isDrawing = false;
};

/**
 * Changes the tile type that we're currently drawing
 * This gets executed when we press the relevant keyboard keys.
 * @name updateCurrentTileType
 * @function
 * @memberof Sand
 * @param {Object} event DOM event object.
 * @returns {void}
 */
Sand.prototype.updateCurrentTileType = function( event ) {
    if( !TILE_COLORS[ event.key ] )
        return;

    this.currentTileType = event.key;
};

/**
 * Draws the tile at the current mouse position
 * This gets executed when we move the mouse and when drawing mode is on.
 * @name processDrawing
 * @function
 * @memberof Sand
 * @param {Object} event DOM event object.
 * @returns {void}
 */
Sand.prototype.processDrawing = function( event ) {
    if( !this.isDrawing )
        return;

    var targetTile = {
            x: Math.floor( ( event.pageX - this.screenCanvas.offsetLeft ) / this.tileSize ),
            y: Math.floor( ( event.pageY - this.screenCanvas.offsetTop ) / this.tileSize )
        };

    /**
     * If we're currently drawing and the mouse is on top of a tile, we redraw it.
     * We basically check if the mouse is inside the screen boundaries.
     */
    if( targetTile.x >= 0 && targetTile.x < this.horizontalTileCount && targetTile.y >= 0 && targetTile.y < this.verticalTileCount ) {
        this.drawScreen( [{
            x: targetTile.x,
            y: targetTile.y,
            value: this.currentTileType
        }]);
    }
};

/**
 * Replaces all tiles with air tiles.
 * This gets executed when we press the Escape keY>
 * @name clearScreen
 * @function
 * @memberof Sand
 * @param {Object} event DOM event object.
 * @returns {void}
 */
Sand.prototype.clearScreen = function( event ) {
    if( event.keyCode !== 27 )
        return;

    var x = 0, L = this.horizontalTileCount,
        y = 0, M = this.verticalTileCount,
        tiles = this.tiles,
        tilesToRedraw = [];

    for( ; x < L; x++ ) {
        for( y = 0; y < M; y++ ) {
            this.tiles[ x ][ y ] = TILE_AIR;

            tilesToRedraw.push(
                { x: x, y: y, value: TILE_AIR }
            );
        }
    }

    this.drawScreen( tilesToRedraw );
};
```

The code is quite simple and straight forward, just read the accompanying comments and it should be easy to understand.

The moment of truth, all we have to do now, is call our **setupEvents** method within our **Sand** class constructor:

```javascript
function Sand() {
    this.screenCanvas = document.getElementById( "screen" );
    this.canvasContext = this.screenCanvas.getContext( "2d" );

    this.tileSize = 10;

    this.horizontalTileCount = this.screenCanvas.width / this.tileSize;
    this.verticalTileCount = this.screenCanvas.height / this.tileSize;

    this.tiles = [];

    this.isDrawing = false; /* Flag: To check if we're currently drawing with the mouse. */

    this.currentTileType = "s"; /* Current drawing tile type. Black static tile by default. */

    this.initialize();

+   this.setupEvents();

    var x = 0, L = this.horizontalTileCount,
        y = 0, M = this.verticalTileCount,
        tiles = this.tiles,
        tilesToRedraw = [];

    for( ; x < L; x++ ) {
        for( y = 0; y < M; y++ ) {
            tilesToRedraw.push(
                { x: x, y: y, value: tiles[ x ][ y ] }
            );
        }
    }

    this.drawScreen( tilesToRedraw );
}
```

Go ahead and refresh your game now, you will be able to change the drawing type of your tile just by pressing the associated keys and draw whatever you like, just make sure to press **Escape** to get a clean drawing screen.


text:
<?php
require( 'config.php' );

include( template( '../template/index.html' ) );


text:
module ActiveRecord
  module Associations
    class DisableJoinsAssociationScope < AssociationScope # :nodoc:
      def scope(association)
        source_reflection = association.reflection
        owner = association.owner
        unscoped = association.klass.unscoped
        reverse_chain = get_chain(source_reflection, association, unscoped.alias_tracker).reverse

        last_reflection, last_ordered, last_join_ids = last_scope_chain(reverse_chain, owner)

        add_constraints(last_reflection, last_reflection.join_primary_key, last_join_ids, owner, last_ordered)
      end

      private
        def last_scope_chain(reverse_chain, owner)
          first_item = reverse_chain.shift
          first_scope = [first_item, false, [owner._read_attribute(first_item.join_foreign_key)]]

          reverse_chain.inject(first_scope) do |(reflection, ordered, join_ids), next_reflection|
            key = reflection.join_primary_key
            records = add_constraints(reflection, key, join_ids, owner, ordered)
            foreign_key = next_reflection.join_foreign_key
            record_ids = records.pluck(foreign_key)
            records_ordered = records && records.order_values.any?

            [next_reflection, records_ordered, record_ids]
          end
        end

        def add_constraints(reflection, key, join_ids, owner, ordered)
          scope = reflection.build_scope(reflection.aliased_table).where(key => join_ids)
          scope = reflection.constraints.inject(scope) do |memo, scope_chain_item|
            item = eval_scope(reflection, scope_chain_item, owner)
            scope.unscope!(*item.unscope_values)
            scope.where_clause += item.where_clause
            scope.order_values = item.order_values | scope.order_values
            scope
          end

          if scope.order_values.empty? && ordered
            split_scope = DisableJoinsAssociationRelation.create(scope.klass, key, join_ids)
            split_scope.where_clause += scope.where_clause
            split_scope
          else
            scope
          end
        end
    end
  end
end


text:
/*
 * Derived from com.android.mms.ui.ConversationListItem
 * (tag android-4.4.4_r2.0.1)
 */

package ca.bmaupin.merge.sms.ui;

import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.QuickContactBadge;
import android.widget.RelativeLayout;
import android.widget.TextView;

import ca.bmaupin.merge.sms.R;
import ca.bmaupin.merge.sms.data.Contact;
import ca.bmaupin.merge.sms.data.Conversation;

/**
 * This class manages the view for given conversation.
 */
public class ConversationListItem extends RelativeLayout {
    private Context mContext;
    private TextView mSubjectView;
    private TextView mFromView;
    private TextView mDateView;
    private View mAttachmentView;
    private QuickContactBadge mAvatarView;

    static private Drawable sDefaultContactImage;

    private Conversation mConversation;

    public static final StyleSpan STYLE_BOLD = new StyleSpan(Typeface.BOLD);

    public ConversationListItem(Context context) {
        super(context);
        mContext = context;
    }

    public ConversationListItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;

        if (sDefaultContactImage == null) {
            sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mFromView = (TextView) findViewById(R.id.from);
        mSubjectView = (TextView) findViewById(R.id.subject);

        mDateView = (TextView) findViewById(R.id.date);
        mAttachmentView = findViewById(R.id.attachment);
        mAvatarView = (QuickContactBadge) findViewById(R.id.avatar);
    }

    public Conversation getConversation() {
        return mConversation;
    }

    /**
     * Only used for header binding.
     */
    public void bind(String title, String explain) {
        mFromView.setText(title);
        mSubjectView.setText(explain);
    }

    private CharSequence formatMessage() {
        String from = mConversation.getRecipients().formatNames(", ");

        SpannableStringBuilder buf = new SpannableStringBuilder(from);

        if (mConversation.getMessageCount() > 1) {
            int before = buf.length();
            buf.append(mContext.getResources().getString(R.string.message_count_format,
                    mConversation.getMessageCount()));
            buf.setSpan(new ForegroundColorSpan(
                    mContext.getResources().getColor(R.color.message_count_color)),
                    before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }

        return buf;
    }

    private void updateAvatarView() {
        Drawable avatarDrawable;
        if (mConversation.getRecipients().size() == 1) {
            Contact contact = mConversation.getRecipients().get(0);
            avatarDrawable = contact.getAvatar(mContext, sDefaultContactImage);

            if (contact.existsInDatabase()) {
                mAvatarView.assignContactUri(contact.getUri());
            } else {
                mAvatarView.assignContactFromPhone(contact.getNumber(), true);
            }
        } else {
            // TODO get a multiple recipients asset (or do something else)
            avatarDrawable = sDefaultContactImage;
            mAvatarView.assignContactUri(null);
        }
        mAvatarView.setImageDrawable(avatarDrawable);
        mAvatarView.setVisibility(View.VISIBLE);
    }

    public final void bind(Context context, final Conversation conversation) {
        //if (DEBUG) Log.v(TAG, "bind()");

        mConversation = conversation;

        boolean hasAttachment = conversation.hasAttachment();
        mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);

        // Date
        mDateView.setText(MessageUtils.formatTimeStampString(context, conversation.getDate()));

        // From.
        mFromView.setText(formatMessage());

        // Subject
        mSubjectView.setText(conversation.getSnippet());
        LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
        // We have to make the subject left of whatever optional items are shown on the right.
        subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
            (R.id.date));

        updateAvatarView();
    }

    public final void unbind() {
    }
}


text:
layout: post
title: Guérison et pleine santé avec Irène Grosjean
date: 2017-08-27 11:43:00 +02:00
categories:
- nutrition
tags: []
status: publish
type: post
published: true
author:
  first_name: Nico
excerpt:
---

<iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2F819834784836219%2Fvideos%2F865674126918951%2F&show_text=0&width=560" width="560" height="315" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true"></iframe>

<https://www.facebook.com/819834784836219/videos/865674126918951/>

## À voir aussi

<https://hypnodingues.org/nutrition/le-temoignage-de-mon-parcours-et-de-mon-retour-a-la-sante-segolene-quenin/>


text:
package mods.alice.cheatstar.utility;

public class TypeTransformer
{
	public static byte truncateIntToUnsignedByte(int value)
	{
		return (byte)value;
	}

	public static int expandUnsignedByteToInt(byte value)
	{
		int t;

		if(value < 0)
		{
			t = 256 + (int)value;
		}
		else
		{
			t = value;
		}

		return t;
	}
}


text:
require 'spec_helper'
require 'puppet/forge/errors'

describe Puppet::Forge::Errors do
  describe 'SSLVerifyError' do
    subject { Puppet::Forge::Errors::SSLVerifyError }
    let(:exception) { subject.new(:uri => 'https://fake.com:1111') }

    it 'should return a valid single line error' do
      exception.message.should == 'Unable to verify the SSL certificate at https://fake.com:1111'
    end

    it 'should return a valid multiline error' do
      exception.multiline.should == <<-EOS.chomp
Could not connect via HTTPS to https://fake.com:1111
  Unable to verify the SSL certificate
    The certificate may not be signed by a valid CA
    The CA bundle included with OpenSSL may not be valid or up to date
      EOS
    end
  end

  describe 'CommunicationError' do
    subject { Puppet::Forge::Errors::CommunicationError }
    let(:socket_exception) { SocketError.new('There was a problem') }
    let(:exception) { subject.new(:uri => 'http://fake.com:1111', :original => socket_exception) }

    it 'should return a valid single line error' do
      exception.message.should == 'Unable to connect to the server at http://fake.com:1111. Detail: There was a problem.'
    end

    it 'should return a valid multiline error' do
      exception.multiline.should == <<-EOS.chomp
Could not connect to http://fake.com:1111
  There was a network communications problem
    The error we caught said 'There was a problem'
    Check your network connection and try again
      EOS
    end
  end

end


text:
import angular from 'angular';

import userNotifications from './service';

import './style.scss';

export default angular
    .module('ignite-console.user-notifications', [])
    .service('UserNotifications', userNotifications);


text:
package edu.uci.ics.asterix.metadata.feeds;

import org.json.JSONException;
import org.json.JSONObject;

import edu.uci.ics.asterix.common.feeds.FeedConnectionId;
import edu.uci.ics.asterix.common.feeds.FeedConstants;
import edu.uci.ics.asterix.common.feeds.message.FeedMessage;

/**
 * A feed control message indicating the need to execute a give AQL.
 */
public class XAQLFeedMessage extends FeedMessage {

    private static final long serialVersionUID = 1L;

    private final String aql;
    private final FeedConnectionId connectionId;

    public XAQLFeedMessage(FeedConnectionId connectionId, String aql) {
        super(MessageType.XAQL);
        this.connectionId = connectionId;
        this.aql = aql;
    }

    @Override
    public String toString() {
        return messageType.name() + " " + connectionId + " [" + aql + "] ";
    }

    public FeedConnectionId getConnectionId() {
        return connectionId;
    }

    public String getAql() {
        return aql;
    }

    @Override
    public JSONObject toJSON() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put(FeedConstants.MessageConstants.MESSAGE_TYPE, messageType.name());
        obj.put(FeedConstants.MessageConstants.DATAVERSE, connectionId.getFeedId().getDataverse());
        obj.put(FeedConstants.MessageConstants.FEED, connectionId.getFeedId().getFeedName());
        obj.put(FeedConstants.MessageConstants.DATASET, connectionId.getDatasetName());
        obj.put(FeedConstants.MessageConstants.AQL, aql);
        return obj;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Michelia 2(no. 6): 92 (1880)

#### Original name
Phoma tamaricella Sacc.

### Remarks
null


text:
package org.apache.activemq.transport.failover;

import org.apache.activemq.command.BrokerInfo;
import org.apache.activemq.transport.DefaultTransportListener;
import org.apache.activemq.transport.Transport;

import java.io.IOException;
import java.net.URI;

class BackupTransport extends DefaultTransportListener{
	private final FailoverTransport failoverTransport;
	private Transport transport;
	private URI uri;
	private boolean disposed;
	private BrokerInfo brokerInfo;

	BackupTransport(FailoverTransport ft){
		this.failoverTransport=ft;
	}

	@Override
    public void onException(IOException error) {
		this.disposed=true;
		if (failoverTransport!=null) {
			this.failoverTransport.reconnect(false);
		}
	}

	@Override
	public void onCommand(Object command) {
		if (command instanceof BrokerInfo) {
			brokerInfo = (BrokerInfo) command;
		}
	}

	public BrokerInfo getBrokerInfo() {
		return brokerInfo;
	}

	public Transport getTransport() {
		return transport;
	}
	public void setTransport(Transport transport) {
		this.transport = transport;
		this.transport.setTransportListener(this);
	}
	public URI getUri() {
		return uri;
	}
	public void setUri(URI uri) {
		this.uri = uri;
	}

	public boolean isDisposed() {
		return disposed || transport != null && transport.isDisposed();
	}

	public void setDisposed(boolean disposed) {
		this.disposed = disposed;
	}

	@Override
    public int hashCode() {
		return uri != null ? uri.hashCode():-1;
	}

	@Override
    public boolean equals(Object obj) {
		if (obj instanceof BackupTransport) {
			BackupTransport other = (BackupTransport) obj;
			return uri== null && other.uri==null ||
				(uri != null && other.uri != null && uri.equals(other.uri));
		}
		return false;
	}

    @Override
    public String toString() {
        return "Backup transport: " + uri;
    }
}