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

<!DOCTYPE article PUBLIC "-//OASIS//DTD Simplified DocBook XML V1.0//EN"
"http://www.oasis-open.org/docbook/xml/simple/1.0/sdocbook.dtd">

  <title>Programming with ZooKeeper - A basic tutorial</title>

  <articleinfo>
    <legalnotice>
      <para>Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License. You may
      obtain a copy of the License at <ulink
      url="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</ulink>.</para>

      <para>Unless required by applicable law or agreed to in writing,
      software distributed under the License is distributed on an "AS IS"
      BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied. See the License for the specific language governing permissions
      and limitations under the License.</para>
    </legalnotice>

    <abstract>
      <para>This article contains sample Java code for simple implementations of barrier
      and consumers queues..</para>

    </abstract>
  </articleinfo>

    <title>Introduction</title>

    <para>In this tutorial, we show simple implementations of barriers and
    producer-consumer queues using ZooKeeper. We call the respective classes Barrier and Queue.
    These examples assume that you have at least one ZooKeeper server running.</para>

    <para>Both primitives use the following common excerpt of code:</para>

    <programlisting>
    static ZooKeeper zk = null;
    static Integer mutex;

    String root;

    SyncPrimitive(String address) {
        if(zk == null){
            try {
                System.out.println("Starting ZK:");
                zk = new ZooKeeper(address, 3000, this);
                mutex = new Integer(-1);
                System.out.println("Finished starting ZK: " + zk);
            } catch (IOException e) {
                System.out.println(e.toString());
                zk = null;
            }
        }
    }

    synchronized public void process(WatchedEvent event) {
        synchronized (mutex) {
            mutex.notify();
        }
    }
</programlisting>

<para>Both classes extend SyncPrimitive. In this way, we execute steps that are
common to all primitives in the constructor of SyncPrimitive. To keep the examples
simple, we create a ZooKeeper object the first time we instantiate either a barrier
object or a queue object, and we declare a static variable that is a reference
to this object. The subsequent instances of Barrier and Queue check whether a
ZooKeeper object exists. Alternatively, we could have the application creating a
ZooKeeper object and passing it to the constructor of Barrier and Queue.</para>
<para>
We use the process() method to process notifications triggered due to watches.
In the following discussion, we present code that sets watches. A watch is internal
structure that enables ZooKeeper to notify a client of a change to a node. For example,
if a client is waiting for other clients to leave a barrier, then it can set a watch and
wait for modifications to a particular node, which can indicate that it is the end of the wait.
This point becomes clear once we go over the examples.
</para>

<title>Barriers</title>

 <para>
 A barrier is a primitive that enables a group of processes to synchronize the
 beginning and the end of a computation. The general idea of this implementation
 is to have a barrier node that serves the purpose of being a parent for individual
 process nodes. Suppose that we call the barrier node "/b1". Each process "p" then
 creates a node "/b1/p". Once enough processes have created their corresponding
 nodes, joined processes can start the computation.
 </para>

 <para>In this example, each process instantiates a Barrier object, and its constructor takes as parameters:</para>

 <itemizedlist><listitem><para>the address of a ZooKeeper server (e.g., "zoo1.foo.com:2181")</para></listitem>
<listitem><para>the path of the barrier node on ZooKeeper (e.g., "/b1")</para></listitem>
<listitem><para>the size of the group of processes</para></listitem>
</itemizedlist>

<para>The constructor of Barrier passes the address of the Zookeeper server to the
constructor of the parent class. The parent class creates a ZooKeeper instance if
one does not exist. The constructor of Barrier then creates a
barrier node on ZooKeeper, which is the parent node of all process nodes, and
we call root (<emphasis role="bold">Note:</emphasis> This is not the ZooKeeper root "/").</para>

<programlisting>
        /**
         * Barrier constructor
         *
         * @param address
         * @param root
         * @param size
         */
        Barrier(String address, String root, int size) {
            super(address);
            this.root = root;
            this.size = size;

            // Create barrier node
            if (zk != null) {
                try {
                    Stat s = zk.exists(root, false);
                    if (s == null) {
                        zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
                                CreateMode.PERSISTENT);
                    }
                } catch (KeeperException e) {
                    System.out
                            .println("Keeper exception when instantiating queue: "
                                    + e.toString());
                } catch (InterruptedException e) {
                    System.out.println("Interrupted exception");
                }
            }

            // My node name
            try {
                name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
            } catch (UnknownHostException e) {
                System.out.println(e.toString());
            }

        }
</programlisting>
<para>
To enter the barrier, a process calls enter(). The process creates a node under
the root to represent it, using its host name to form the node name. It then wait
until enough processes have entered the barrier. A process does it by checking
the number of children the root node has with "getChildren()", and waiting for
notifications in the case it does not have enough. To receive a notification when
there is a change to the root node, a process has to set a watch, and does it
through the call to "getChildren()". In the code, we have that "getChildren()"
has two parameters. The first one states the node to read from, and the second is
a boolean flag that enables the process to set a watch. In the code the flag is true.
</para>

<programlisting>
        /**
         * Join barrier
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */

        boolean enter() throws KeeperException, InterruptedException{
            zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);

                    if (list.size() < size) {
                        mutex.wait();
                    } else {
                        return true;
                    }
                }
            }
        }
</programlisting>
<para>
Note that enter() throws both KeeperException and InterruptedException, so it is
the responsibility of the application to catch and handle such exceptions.</para>

<para>
Once the computation is finished, a process calls leave() to leave the barrier.
First it deletes its corresponding node, and then it gets the children of the root
node. If there is at least one child, then it waits for a notification (obs: note
that the second parameter of the call to getChildren() is true, meaning that
ZooKeeper has to set a watch on the the root node). Upon reception of a notification,
it checks once more whether the root node has any children.</para>

<programlisting>
        /**
         * Wait until all reach barrier
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */

        boolean leave() throws KeeperException, InterruptedException{
            zk.delete(root + "/" + name, 0);
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);
                        if (list.size() > 0) {
                            mutex.wait();
                        } else {
                            return true;
                        }
                    }
                }
        }
    }
</programlisting>

<title>Producer-Consumer Queues</title>
<para>
A producer-consumer queue is a distributed data structure that groups of processes
use to generate and consume items. Producer processes create new elements and add
them to the queue. Consumer processes remove elements from the list, and process them.
In this implementation, the elements are simple integers. The queue is represented
by a root node, and to add an element to the queue, a producer process creates a new node,
a child of the root node.
</para>

<para>
The following excerpt of code corresponds to the constructor of the object. As
with Barrier objects, it first calls the constructor of the parent class, SyncPrimitive,
that creates a ZooKeeper object if one doesn't exist. It then verifies if the root
node of the queue exists, and creates if it doesn't.
</para>
<programlisting>
        /**
         * Constructor of producer-consumer queue
         *
         * @param address
         * @param name
         */
        Queue(String address, String name) {
            super(address);
            this.root = name;
            // Create ZK node name
            if (zk != null) {
                try {
                    Stat s = zk.exists(root, false);
                    if (s == null) {
                        zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
                                CreateMode.PERSISTENT);
                    }
                } catch (KeeperException e) {
                    System.out
                            .println("Keeper exception when instantiating queue: "
                                    + e.toString());
                } catch (InterruptedException e) {
                    System.out.println("Interrupted exception");
                }
            }
        }
</programlisting>

<para>
A producer process calls "produce()" to add an element to the queue, and passes
an integer as an argument. To add an element to the queue, the method creates a
new node using "create()", and uses the SEQUENCE flag to instruct ZooKeeper to
append the value of the sequencer counter associated to the root node. In this way,
we impose a total order on the elements of the queue, thus guaranteeing that the
oldest element of the queue is the next one consumed.
</para>

<programlisting>
        /**
         * Add element to the queue.
         *
         * @param i
         * @return
         */

        boolean produce(int i) throws KeeperException, InterruptedException{
            ByteBuffer b = ByteBuffer.allocate(4);
            byte[] value;

            // Add child with value i
            b.putInt(i);
            value = b.array();
            zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT_SEQUENTIAL);

            return true;
        }
</programlisting>
<para>
To consume an element, a consumer process obtains the children of the root node,
reads the node with smallest counter value, and returns the element. Note that
if there is a conflict, then one of the two contending processes won't be able to
delete the node and the delete operation will throw an exception.</para>

<para>
A call to getChildren() returns the list of children in lexicographic order.
As lexicographic order does not necessary follow the numerical order of the counter
values, we need to decide which element is the smallest. To decide which one has
the smallest counter value, we traverse the list, and remove the prefix "element"
from each one.</para>

<programlisting>
        /**
         * Remove first element from the queue.
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        int consume() throws KeeperException, InterruptedException{
            int retvalue = -1;
            Stat stat = null;

            // Get the first element available
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);
                    if (list.size() == 0) {
                        System.out.println("Going to wait");
                        mutex.wait();
                    } else {
                        Integer min = new Integer(list.get(0).substring(7));
                        for(String s : list){
                            Integer tempValue = new Integer(s.substring(7));
                            //System.out.println("Temporary value: " + tempValue);
                            if(tempValue < min) min = tempValue;
                        }
                        System.out.println("Temporary value: " + root + "/element" + min);
                        byte[] b = zk.getData(root + "/element" + min,
                                    false, stat);
                        zk.delete(root + "/element" + min, 0);
                        ByteBuffer buffer = ByteBuffer.wrap(b);
                        retvalue = buffer.getInt();

                        return retvalue;
                    }
                }
            }
        }
    }
</programlisting>

<title>Complete example</title>
<para>
In the following section you can find a complete command line application to demonstrate the above mentioned
recipes. Use the following command to run it.
</para>
<programlisting>
ZOOBINDIR="[path_to_distro]/bin"
. "$ZOOBINDIR"/zkEnv.sh
java SyncPrimitive [Test Type] [ZK server] [No of elements] [Client type]
</programlisting>

<title>Queue test</title>
<para>Start a producer to create 100 elements</para>
<programlisting>
java SyncPrimitive qTest localhost 100 p
</programlisting>

<para>Start a consumer to consume 100 elements</para>
<programlisting>
java SyncPrimitive qTest localhost 100 c
</programlisting>

<title>Barrier test</title>
<para>Start a barrier with 2 participants (start as many times as many participants you'd like to enter)</para>
<programlisting>
java SyncPrimitive bTest localhost 2
</programlisting>

<title>Source Listing</title>
<example id="eg_SyncPrimitive_java">
<title>SyncPrimitive.Java</title>
<programlisting>
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Random;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;

public class SyncPrimitive implements Watcher {

    static ZooKeeper zk = null;
    static Integer mutex;

    String root;

    SyncPrimitive(String address) {
        if(zk == null){
            try {
                System.out.println("Starting ZK:");
                zk = new ZooKeeper(address, 3000, this);
                mutex = new Integer(-1);
                System.out.println("Finished starting ZK: " + zk);
            } catch (IOException e) {
                System.out.println(e.toString());
                zk = null;
            }
        }
        //else mutex = new Integer(-1);
    }

    synchronized public void process(WatchedEvent event) {
        synchronized (mutex) {
            //System.out.println("Process: " + event.getType());
            mutex.notify();
        }
    }

    /**
     * Barrier
     */
    static public class Barrier extends SyncPrimitive {
        int size;
        String name;

        /**
         * Barrier constructor
         *
         * @param address
         * @param root
         * @param size
         */
        Barrier(String address, String root, int size) {
            super(address);
            this.root = root;
            this.size = size;

            // Create barrier node
            if (zk != null) {
                try {
                    Stat s = zk.exists(root, false);
                    if (s == null) {
                        zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
                                CreateMode.PERSISTENT);
                    }
                } catch (KeeperException e) {
                    System.out
                            .println("Keeper exception when instantiating queue: "
                                    + e.toString());
                } catch (InterruptedException e) {
                    System.out.println("Interrupted exception");
                }
            }

            // My node name
            try {
                name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString());
            } catch (UnknownHostException e) {
                System.out.println(e.toString());
            }

        }

        /**
         * Join barrier
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */

        boolean enter() throws KeeperException, InterruptedException{
            zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);

                    if (list.size() < size) {
                        mutex.wait();
                    } else {
                        return true;
                    }
                }
            }
        }

        /**
         * Wait until all reach barrier
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */

        boolean leave() throws KeeperException, InterruptedException{
            zk.delete(root + "/" + name, 0);
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);
                        if (list.size() > 0) {
                            mutex.wait();
                        } else {
                            return true;
                        }
                    }
                }
        }
    }

    /**
     * Producer-Consumer queue
     */
    static public class Queue extends SyncPrimitive {

        /**
         * Constructor of producer-consumer queue
         *
         * @param address
         * @param name
         */
        Queue(String address, String name) {
            super(address);
            this.root = name;
            // Create ZK node name
            if (zk != null) {
                try {
                    Stat s = zk.exists(root, false);
                    if (s == null) {
                        zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE,
                                CreateMode.PERSISTENT);
                    }
                } catch (KeeperException e) {
                    System.out
                            .println("Keeper exception when instantiating queue: "
                                    + e.toString());
                } catch (InterruptedException e) {
                    System.out.println("Interrupted exception");
                }
            }
        }

        /**
         * Add element to the queue.
         *
         * @param i
         * @return
         */

        boolean produce(int i) throws KeeperException, InterruptedException{
            ByteBuffer b = ByteBuffer.allocate(4);
            byte[] value;

            // Add child with value i
            b.putInt(i);
            value = b.array();
            zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT_SEQUENTIAL);

            return true;
        }

        /**
         * Remove first element from the queue.
         *
         * @return
         * @throws KeeperException
         * @throws InterruptedException
         */
        int consume() throws KeeperException, InterruptedException{
            int retvalue = -1;
            Stat stat = null;

            // Get the first element available
            while (true) {
                synchronized (mutex) {
                    List<String> list = zk.getChildren(root, true);
                    if (list.size() == 0) {
                        System.out.println("Going to wait");
                        mutex.wait();
                    } else {
                        Integer min = new Integer(list.get(0).substring(7));
                        String minNode = list.get(0);
                        for(String s : list){
                            Integer tempValue = new Integer(s.substring(7));
                            //System.out.println("Temporary value: " + tempValue);
                            if(tempValue < min) {
                                min = tempValue;
                                minNode = s;
                            }
                        }
                        System.out.println("Temporary value: " + root + "/" + minNode);
                        byte[] b = zk.getData(root + "/" + minNode,
                        false, stat);
                        zk.delete(root + "/" + minNode, 0);
                        ByteBuffer buffer = ByteBuffer.wrap(b);
                        retvalue = buffer.getInt();

                        return retvalue;
                    }
                }
            }
        }
    }

    public static void main(String args[]) {
        if (args[0].equals("qTest"))
            queueTest(args);
        else
            barrierTest(args);

    }

    public static void queueTest(String args[]) {
        Queue q = new Queue(args[1], "/app1");

        System.out.println("Input: " + args[1]);
        int i;
        Integer max = new Integer(args[2]);

        if (args[3].equals("p")) {
            System.out.println("Producer");
            for (i = 0; i < max; i++)
                try{
                    q.produce(10 + i);
                } catch (KeeperException e){

                } catch (InterruptedException e){

                }
        } else {
            System.out.println("Consumer");

            for (i = 0; i < max; i++) {
                try{
                    int r = q.consume();
                    System.out.println("Item: " + r);
                } catch (KeeperException e){
                    i--;
                } catch (InterruptedException e){

                }
            }
        }
    }

    public static void barrierTest(String args[]) {
        Barrier b = new Barrier(args[1], "/b1", new Integer(args[2]));
        try{
            boolean flag = b.enter();
            System.out.println("Entered barrier: " + args[2]);
            if(!flag) System.out.println("Error when entering the barrier");
        } catch (KeeperException e){

        } catch (InterruptedException e){

        }

        // Generate random integer
        Random rand = new Random();
        int r = rand.nextInt(100);
        // Loop for rand iterations
        for (int i = 0; i < r; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {

            }
        }
        try{
            b.leave();
        } catch (KeeperException e){

        } catch (InterruptedException e){

        }
        System.out.println("Left barrier");
    }
}
</programlisting></example>


text:
date: '2011-12-14'
title: Coding For Fun - Programming the Kinect SDK
speakers:
  - Jason Awbrey
location: Spring Creek BBQ - Woodlands
---
End the year with an introduction to programming with Microsoft's Kinect SDK.

redpajama_set_name: RedPajamaGithub


text:
""" This module provides a simple task monitoring capability to track usage
    statistics for tasks.
    """

import re
import os
import datetime

try:
    import simplejson as json
except ImportError:
    import json

from focus.plugin import base
from focus import common, errors

MINS_IN_HOUR = 60
MINS_IN_DAY = MINS_IN_HOUR * 24

class Stats(base.Plugin):
    """ Prints usage statistics about tasks.
        """
    name = 'Stats'
    version = '0.1'
    target_version = '>=0.1'
    events = ['task_end']
    command = 'stat'

    def _sdir(self, base_dir):
        """ Return path to stats directory.

            `base_dir`
                Base directory.

            Returns string.
            """
        return os.path.join(base_dir, '.stats')

    def _setup_dir(self, base_dir):
        """ Creates stats directory for storing stat files.

            `base_dir`
                Base directory.
            """
        stats_dir = self._sdir(base_dir)

        if not os.path.isdir(stats_dir):
            try:
                os.mkdir(stats_dir)
            except OSError:
                raise errors.DirectorySetupFail()

    def _log_task(self, task):
        """ Logs task record to file.

            `task`
                ``Task`` instance.
            """
        if not task.duration:
            return

        self._setup_dir(task.base_dir)
        stats_dir = self._sdir(task.base_dir)
        duration = task.duration

        while duration > 0:
            # build filename
            date = (datetime.datetime.now() -
                    datetime.timedelta(minutes=duration))
            date_str = date.strftime('%Y%m%d')
            filename = os.path.join(stats_dir, '{0}.json'.format(date_str))

            with open(filename, 'a+') as file_:
                # fetch any existing data
                try:
                    file_.seek(0)
                    data = json.loads(file_.read())
                except (ValueError, OSError):
                    data = {}

                if not task.name in data:
                    data[task.name] = 0

                # how much total time for day
                try:
                    total_time = sum(int(x) for x in data.values())
                    if total_time > MINS_IN_DAY:
                        total_time = MINS_IN_DAY

                except ValueError:
                    total_time = 0

                # constrain to single day
                amount = duration
                if amount + total_time > MINS_IN_DAY:
                    amount = MINS_IN_DAY - total_time

                    # invalid or broken state, bail
                    if amount <= 0:
                        break

                data[task.name] += amount
                duration -= amount

                # write file
                try:
                    file_.seek(0)
                    file_.truncate(0)
                    file_.write(json.dumps(data))
                except (ValueError, OSError):
                    pass

    def _fuzzy_time_parse(self, value):
        """ Parses a fuzzy time value into a meaningful interpretation.

            `value`
                String value to parse.
            """

        value = value.lower().strip()
        today = datetime.date.today()

        if value in ('today', 't'):
            return today

        else:
            kwargs = {}

            if value in ('y', 'yesterday'):
                kwargs['days'] = -1

            elif value in ('w', 'wk', 'week', 'last week'):
                kwargs['days'] = -7

            else:
                # match days
                match = re.match(r'(\d+)\s*(d|day|days)\s*(ago)?$', value)
                if match:
                    kwargs['days'] = -int(match.groups(1)[0])

                else:
                    # match weeks
                    match = re.match(r'(\d+)\s*(w|wk|week|weeks)\s*(ago)?$',
                                     value)
                    if match:
                        kwargs['weeks'] = -int(match.groups(1)[0])

            if kwargs:
                return today + datetime.timedelta(**kwargs)

            return None

    def _get_stats(self, task, start_date):
        """ Fetches statistic information for given task and start range.
            """

        stats = []
        stats_dir = self._sdir(task.base_dir)
        date = start_date
        end_date = datetime.date.today()
        delta = datetime.timedelta(days=1)

        while date <= end_date:
            date_str = date.strftime('%Y%m%d')
            filename = os.path.join(stats_dir, '{0}.json'.format(date_str))

            if os.path.exists(filename):
                try:
                    # fetch stats content
                    with open(filename, 'r') as file_:
                        data = json.loads(file_.read())

                    # sort descending by time
                    stats.append((date, sorted(data.iteritems(),
                                               key=lambda x: x[1],
                                               reverse=True)))

                except (json.JSONDecodeError, OSError):
                    pass

            date += delta  # next day

        return stats

    def _print_stats(self, env, stats):
        """ Prints statistic information using io stream.

            `env`
                ``Environment`` object.
            `stats`
                Tuple of task stats for each date.
            """

        def _format_time(mins):
            """ Generates formatted time string.
                """
            mins = int(mins)

            if mins < MINS_IN_HOUR:
                time_str = '0:{0:02}'.format(mins)
            else:
                hours = mins // MINS_IN_HOUR
                mins %= MINS_IN_HOUR

                if mins > 0:
                    time_str = '{0}:{1:02}'.format(hours, mins)
                else:
                    time_str = '{0}'.format(hours)

            return time_str

        if not stats:
            env.io.write('No stats found.')
            return

        for date, tasks in stats:
            env.io.write('')
            total_mins = float(sum(v[1] for v in tasks))
            env.io.write('[ {0} ]'.format(date.strftime('%Y-%m-%d')))
            env.io.write('')

            for name, mins in tasks:
                # format time
                time_str = _format_time(mins)

                # generate stat line
                line = '   {0:>5}'.format(time_str)
                line += ' ({0:2.0f}%) - '.format(mins * 100.0 / total_mins)
                if len(name) > 55:
                    name = name[:55] + '...'
                line += name
                env.io.write(line)

            # generate total line
            env.io.write('_' * len(line))
            time_str = _format_time(total_mins)
            env.io.write('   {0:>5} (total)'.format(time_str))
            env.io.write('')

    def setup_parser(self, parser):
        """ Setup the argument parser.

            `parser`
                ``FocusArgParser`` object.
            """

        parser.add_argument('start', nargs='?',
                            help='starting period. defaults to today',
                            default='today')

    def execute(self, env, args):
        """ Prints task information.

            `env`
                Runtime ``Environment`` instance.
            `args`
                Arguments object from arg parser.
            """

        start = self._fuzzy_time_parse(args.start)
        if not start:
            raise errors.FocusError(u'Invalid start period provided')

        stats = self._get_stats(env.task, start)
        self._print_stats(env, stats)

    def on_taskend(self, task):
        """ Logs task usage stats when task ends.
            """
        self._log_task(task)


text:
import { npmPublish, npmLogin, execSilent, executeSilent }
  from '../../utils/process';
import { createPackageJson } from '../../utils/utils';

export default function() {
  return Promise.resolve()
    .then(() => createPackageJson('package.json', 'test-package', '0.0.1'))
    .then(() => npmLogin('admin', 'blabla', 'foo@bar.com'))
    .then(() => npmPublish())
    .then(() => executeSilent('npm logout'))
    .then(() => execSilent(
      'npm', ['-q', 'dist-tag', 'add', 'test-package@0.0.1', 'tag1', '--fetch-retries', '0']))
    .then(res => {
      if (res.code !== 0) {
        return Promise.resolve();
      }

      return Promise.reject('');
    })
    .catch(() => Promise.reject(''));
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;
using System.Collections;
using HoloToolkit.Unity;
using System.Collections.Generic;
using System;
using HoloToolkit.Unity.InputModule;

namespace HoloToolkit.Examples.GazeRuler
{
    /// <summary>
    /// manager all measure tools here
    /// </summary>
    public class MeasureManager : Singleton<MeasureManager>, IHoldHandler, IInputClickHandler
    {
        private IGeometry manager;
        public GeometryMode Mode;

        // set up prefabs
        public GameObject LinePrefab;
        public GameObject PointPrefab;
        public GameObject ModeTipObject;
        public GameObject TextPrefab;

        private void Start()
        {
            InputManager.Instance.PushFallbackInputHandler(gameObject);

            // inti measure mode
            switch (Mode)
            {
                case GeometryMode.Polygon:
                    manager = PolygonManager.Instance;
                    break;
                default:
                    manager = LineManager.Instance;
                    break;
            }
        }

        // place spatial point
        public void OnSelect()
        {
            manager.AddPoint(LinePrefab, PointPrefab, TextPrefab);
        }

        // delete latest line or geometry
        public void DeleteLine()
        {
            manager.Delete();
        }

        // delete all lines or geometry
        public void ClearAll()
        {
            manager.Clear();
        }

        // if current mode is geometry mode, try to finish geometry
        public void OnPolygonClose()
        {
            IPolygonClosable client = PolygonManager.Instance;
            client.ClosePolygon(LinePrefab, TextPrefab);
        }

        // change measure mode
        public void OnModeChange()
        {
            try
            {
                manager.Reset();
                if (Mode == GeometryMode.Line)
                {
                    Mode = GeometryMode.Polygon;
                    manager = PolygonManager.Instance;
                }
                else
                {
                    Mode = GeometryMode.Line;
                    manager = LineManager.Instance;
                }
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
            ModeTipObject.SetActive(true);
        }

        public void OnHoldStarted(HoldEventData eventData)
        {
            OnPolygonClose();
        }

        public void OnHoldCompleted(HoldEventData eventData)
        {
            // Nothing to do
        }

        public void OnHoldCanceled(HoldEventData eventData)
        {
            // Nothing to do
        }

    public void OnInputClicked(InputClickedEventData eventData)
    {
        OnSelect();
    }
}

    public class Point
    {
        public Vector3 Position { get; set; }

        public GameObject Root { get; set; }
        public bool IsStart { get; set; }
    }

    public enum GeometryMode
    {
        Line,
        Triangle,
        Rectangle,
        Cube,
        Polygon
    }
}


text:
package edu.gemini.phase2.core.model;

import edu.gemini.pot.sp.*;
import edu.gemini.spModel.data.ISPDataObject;
import edu.gemini.spModel.pio.ParamSet;
import edu.gemini.spModel.pio.PioFactory;

import java.util.ArrayList;
import java.util.List;

public final class ObsComponentShell extends ComponentShell {
    public static final String PARAM_SET_NAME = "obsComponentShell";

    public ObsComponentShell(ISPDataObject dataObject) {
        super(dataObject);
    }

    public ObsComponentShell(ParamSet pset) {
        super(pset);
    }

    public ObsComponentShell(ISPObsComponent sp)  {
        this(sp.getDataObject());
    }

    public String paramSetName() { return PARAM_SET_NAME; }

    @Override public ParamSet toParamSet(PioFactory factory) {
        return super.toParamSet(factory);
    }

    public ISPObsComponent toSp(ISPFactory factory, ISPProgram prog)  {
        try {
            ISPObsComponent sp = factory.createObsComponent(prog, dataObject.getType(), null);
            sp.setDataObject(dataObject);
            return sp;
        } catch (SPUnknownIDException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static List<ISPObsComponent> spList(ISPFactory factory, ISPProgram prog, List<ObsComponentShell> shells)  {
        List<ISPObsComponent> spList = new ArrayList<ISPObsComponent>();
        for (ObsComponentShell shell : shells) spList.add(shell.toSp(factory, prog));
        return spList;
    }

    public static List<ObsComponentShell> shellList(List<ISPObsComponent> spList)  {
        List<ObsComponentShell> shells = new ArrayList<ObsComponentShell>();
        for (ISPObsComponent sp : spList) shells.add(new ObsComponentShell(sp));
        return shells;
    }
}


text:
static char imageURLKey;

@implementation UIImageView (TFCache)

- (void)tf_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholder
                  animated:(BOOL)animated
                 faceAware:(BOOL)faceAware {
    [self tf_setImageWithURL:url
            placeholderImage:placeholder
                     options:0
                    progress:nil
                   completed:nil
                    animated:animated
                   faceAware:faceAware];
}

- (void)tf_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholder
                 completed:(SDWebImageCompletionBlock)completedBlock
                  animated:(BOOL)animated
                 faceAware:(BOOL)faceAware {
    [self tf_setImageWithURL:url
            placeholderImage:placeholder
                     options:0
                    progress:0
                   completed:completedBlock
                    animated:animated
                   faceAware:faceAware];

}

- (void)tf_setImageWithURL:(NSURL *)url
          placeholderImage:(UIImage *)placeholder
                   options:(SDWebImageOptions)options
                  progress:(SDWebImageDownloaderProgressBlock)progressBlock
                 completed:(SDWebImageCompletionBlock)completedBlock
                  animated:(BOOL)animated
                 faceAware:(BOOL)faceAware {
    [self tf_cancelCurrentImageLoad];
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    if (!(options & SDWebImageDelayPlaceholder)) {
        self.image = placeholder;
    }

    if (url) {
        __weak UIImageView *wself = self;
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (!wself) return;
            dispatch_main_sync_safe(^{
                if (!wself) return;
                if (image) {
                    __block UIImage *tempImage = nil;
                    if (faceAware) {
                        //image 人脸识别处理
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            CGRect facesRect = CGRectZero;
                            @autoreleasepool {
                                CIImage *ciImage = image.CIImage;
                                if (!ciImage) {
                                    ciImage = [CIImage imageWithCGImage:image.CGImage];
                                }
                                CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                                                          context:nil
                                                                          options:@{CIDetectorAccuracy:CIDetectorAccuracyLow}];
                                NSArray* features = [detector featuresInImage:ciImage];
                                facesRect = CGRectMake(image.size.width/2.0, image.size.height/2.0, 0, 0);
                                if (features.count > 0) {
                                    facesRect = ((CIFaceFeature*)[features objectAtIndex:0]).bounds;
                                    for (CIFaceFeature* faceFeature in features) {
                                        facesRect = CGRectUnion(facesRect, faceFeature.bounds);
                                    }
                                }
                            }
                            if (facesRect.size.width != 0 && facesRect.size.height != 0) {
                                //识别到人脸
                                tempImage = [self scaleImageFocusingOnRect:facesRect image:image];
                            }
                            dispatch_main_sync_safe(^{
                                if (animated) {
                                    CATransition *animation = [CATransition animation];
                                    animation.delegate = self;
                                    animation.duration = .35;
                                    animation.timingFunction = UIViewAnimationCurveEaseInOut;
                                    animation.type = kCATransitionFade;
                                    wself.image = tempImage?tempImage:image;
                                    [wself setNeedsLayout];
                                    [[wself layer] addAnimation:animation forKey:@"animation"];
                                }
                                else {
                                    wself.image = tempImage?tempImage:image;
                                    [wself setNeedsLayout];
                                }
                            });
                        });
                    }
                    else {
                        if (animated) {
                            CATransition *animation = [CATransition animation];
                            animation.delegate = self;
                            animation.duration = .35;
                            animation.timingFunction = UIViewAnimationCurveEaseInOut;
                            animation.type = kCATransitionFade;
                            wself.image = tempImage?tempImage:image;
                            [wself setNeedsLayout];
                            [[wself layer] addAnimation:animation forKey:@"animation"];
                        }
                        else {
                            wself.image = tempImage?tempImage:image;
                            [wself setNeedsLayout];
                        }
                    }

                } else {
                    if ((options & SDWebImageDelayPlaceholder)) {
                        wself.image = placeholder;
                        [wself setNeedsLayout];
                    }
                }
                if (completedBlock && finished) {
                    completedBlock(image, error, cacheType, url);
                }
            });
        }];
        [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
    } else {
        dispatch_main_async_safe(^{
            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
            if (completedBlock) {
                completedBlock(nil, error, SDImageCacheTypeNone, url);
            }
        });
    }
}

- (NSURL *)tf_imageURL {
    return objc_getAssociatedObject(self, &imageURLKey);
}

- (void)tf_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
    [self tf_cancelCurrentAnimationImagesLoad];
    __weak UIImageView *wself = self;

    NSMutableArray *operationsArray = [[NSMutableArray alloc] init];

    for (NSURL *logoImageURL in arrayOfURLs) {
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (!wself) return;
            dispatch_main_sync_safe(^{
                __strong UIImageView *sself = wself;
                [sself stopAnimating];
                if (sself && image) {
                    NSMutableArray *currentImages = [[sself animationImages] mutableCopy];
                    if (!currentImages) {
                        currentImages = [[NSMutableArray alloc] init];
                    }
                    [currentImages addObject:image];

                    sself.animationImages = currentImages;
                    [sself setNeedsLayout];
                }
                [sself startAnimating];
            });
        }];
        [operationsArray addObject:operation];
    }

    [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"];
}

- (void)tf_cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}

- (void)tf_cancelCurrentAnimationImagesLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
}

- (UIImage *)scaleImageFocusingOnRect:(CGRect) facesRect image:(UIImage *)image {
    CGFloat multi1 = self.frame.size.width / image.size.width;
    CGFloat multi2 = self.frame.size.height / image.size.height;
    CGFloat multi = MAX(multi1, multi2);

    //We need to 'flip' the Y coordinate to make it match the iOS coordinate system one
    facesRect.origin.y = image.size.height - facesRect.origin.y - facesRect.size.height;

    facesRect = CGRectMake(facesRect.origin.x*multi, facesRect.origin.y*multi, facesRect.size.width*multi, facesRect.size.height*multi);

    CGRect imageRect = CGRectZero;
    imageRect.size.width = image.size.width * multi;
    imageRect.size.height = image.size.height * multi;
    imageRect.origin.x = MIN(0.0, MAX(-facesRect.origin.x + self.frame.size.width/2.0 - facesRect.size.width/2.0, -imageRect.size.width + self.frame.size.width));
    imageRect.origin.y = MIN(0.0, MAX(-facesRect.origin.y + self.frame.size.height/2.0 -facesRect.size.height/2.0, -imageRect.size.height + self.frame.size.height));

    imageRect = CGRectIntegral(imageRect);

    UIGraphicsBeginImageContextWithOptions(imageRect.size, YES, 2.0);
    [image drawInRect:imageRect];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

//    NSInteger theRedRectangleTag = -3312;
//    UIView* facesRectLine = [self viewWithTag:theRedRectangleTag];
//    if (!facesRectLine) {
//        facesRectLine = [[UIView alloc] initWithFrame:facesRect];
//        facesRectLine.tag = theRedRectangleTag;
//    }
//    else {
//        facesRectLine.frame = facesRect;
//    }
//
//    facesRectLine.backgroundColor = [UIColor clearColor];
//    facesRectLine.layer.borderColor = [UIColor redColor].CGColor;
//    facesRectLine.layer.borderWidth = 1;
//
//    CGRect frame = facesRectLine.frame;
//    frame.origin.x = imageRect.origin.x + frame.origin.x;
//    frame.origin.y = imageRect.origin.y + frame.origin.y;
//    facesRectLine.frame = frame;
//
//    [self addSubview:facesRectLine];

    return newImage;
}

@end


text:
class Stopwatch
  class << self
    def measure(label: nil)
      start = Time.now

      yield

      elapsed = Time.now - start
      if label
        puts "#{label} took #{"%.2f" % elapsed} seconds"
      end

      elapsed
    end
  end
end


text:
title: Heuristic Review
localeTitle: Revisión Heurística
---
## Revisión Heurística

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/user-experience-research/heuristic-review/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
function foo () {
	console.log( 'indented with tabs' );
}

export default foo;


text:
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using Microsoft.VisualStudio.PlatformUI;

namespace Microsoft.VisualStudioTools {
    /// <summary>
    /// Works around an issue w/ DialogWindow and targetting multiple versions of VS.
    ///
    /// Because the Microsoft.VisualStudio.Shell.version.0 assembly changes names
    /// we cannot refer to both v10 and v11 versions from within the same XAML file.
    /// Instead we use this subclass defined in our assembly.
    /// </summary>
    class DialogWindowVersioningWorkaround : DialogWindow {
    }
}


text:
try:
    import usocket as socket, uselect as select, uerrno as errno
except ImportError:
    try:
        import socket, select, errno
        select.poll  # Raises AttributeError for CPython implementations without poll()
    except (ImportError, AttributeError):
        print("SKIP")
        raise SystemExit

poller = select.poll()

s = socket.socket()

poller.register(s)
# https://docs.python.org/3/library/select.html#select.poll.register
# "Registering a file descriptor that's already registered is not an error,
# and has the same effect as registering the descriptor exactly once."
poller.register(s)

# 2 args are mandatory unlike register()
try:
    poller.modify(s)
except TypeError:
    print("modify:TypeError")

poller.modify(s, select.POLLIN)

poller.unregister(s)

try:
    poller.modify(s, select.POLLIN)
except OSError as e:
    assert e.args[0] == errno.ENOENT

# poll after closing the socket, should return POLLNVAL
poller.register(s)
s.close()
p = poller.poll(0)
print(len(p), p[0][-1])


text:
import createTableSection from './createTableSection';
import pagination from './pagination';
import search from './search';

const lookupModal = {
    selector: '#form-modal',
    elements: {
        close: 'i[class="fa fa-times-circle"]',
        title: 'div[class^="Form-title"]',
        select: 'button[class*="save"]',
        cancel: 'button[class*="cancel"]',
        save: 'button[class*="save"]'
    },
    sections: {
        search,
        pagination,
        table: createTableSection({
            elements: {
                name: 'td[class~="name-column"]',
                selected: 'input[type="radio", value="1"]',
            }

        })
    }
};

module.exports = lookupModal;


text:
class TForm1 : public TForm
{
__published:	// IDE-managed Components
        TAbZipView *AbZipView1;
        TMemo *Memo1;
        TMainMenu *MainMenu1;
        TMenuItem *File1;
        TMenuItem *Open1;
        TMenuItem *Close1;
        TMenuItem *N1;
        TMenuItem *Exit1;
        TMenuItem *Action1;
        TMenuItem *Extract1;
        TMenuItem *Add1;
        TMenuItem *Clearmemo1;
        TOpenDialog *OpenDialog1;
        TAbZipKit *AbZipKit1;
        void __fastcall Open1Click(TObject *Sender);
        void __fastcall Extract1Click(TObject *Sender);
        void __fastcall Close1Click(TObject *Sender);
        void __fastcall Exit1Click(TObject *Sender);
        void __fastcall AbZipView1DblClick(TObject *Sender);
        void __fastcall Clearmemo1Click(TObject *Sender);
        void __fastcall Add1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
        __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif


text:
<?php

/** Rend_Factory_AuthAdapter_Digest */
require_once "Rend/Factory/AuthAdapter/Digest.php";

/**
 * @category Rend
 * @subpackage UnitTest
 */
class Rend_Factory_AuthAdapter_DigestTest extends PHPUnit_Framework_TestCase
{

    /**
     * @var Rend_Factory_Log
     */
    private $_factory;

    /**
     *
     */
    public function setUp()
    {
        $this->_factory = new Rend_Factory_AuthAdapter_Digest();
    }

    /**
     *
     */
    public function testFilenameIsConfigurable()
    {
        $adapter = $this->_factory
                        ->setFilename("filename")
                        ->create();

        $this->assertEquals(
            "filename",
            $adapter->getFilename()
        );
    }

    /**
     *
     */
    public function testPasswordIsConfigurable()
    {
        $adapter = $this->_factory
                        ->setPassword("password")
                        ->create();

        $this->assertEquals(
            "password",
            $adapter->getPassword()
        );
    }

    /**
     *
     */
    public function testRealmIsConfigurable()
    {
        $adapter = $this->_factory
                        ->setRealm("realm")
                        ->create();

        $this->assertEquals(
            "realm",
            $adapter->getRealm()
        );
    }

    /**
     *
     */
    public function testUsernameIsConfigurable()
    {
        $adapter = $this->_factory
                        ->setUsername("username")
                        ->create();

        $this->assertEquals(
            "username",
            $adapter->getUsername()
        );
    }

}


text:
#include "flutter/sky/engine/core/rendering/style/StyleFilterData.h"

namespace blink {

StyleFilterData::StyleFilterData()
{
}

StyleFilterData::StyleFilterData(const StyleFilterData& o)
{
}

bool StyleFilterData::operator==(const StyleFilterData& o) const
{
    return true;
}

} // namespace blink


text:
#include <string.h>
#include <stdint.h>

/* macros to override the function names for efficient linking and multiple instantiations */
#ifndef HEAPMGR_INIT
#define HEAPMGR_INIT   heapmgrInit
#endif

#ifndef HEAPMGR_MALLOC
#define HEAPMGR_MALLOC heapmgrMalloc
#endif

#ifndef HEAPMGR_FREE
#define HEAPMGR_FREE heapmgrFree
#endif

#ifndef HEAPMGR_GETMETRICS
#define HEAPMGR_GETMETRICS heapmgrGetMetrics
#endif

#ifndef HEAPMGR_SANITY_CHECK
#define HEAPMGR_SANITY_CHECK heapmgrSanityCheck
#endif

#ifndef HEAPMGR_PREFIXED
#define HEAPMGR_PREFIXED(_name) heapmgr ## _name
#endif

/* macros to lock and unlock a mutex to synchronize tasks using this heap */
#ifndef HEAPMGR_LOCK
#define HEAPMGR_LOCK()
#endif

#ifndef HEAPMGR_UNLOCK
#define HEAPMGR_UNLOCK()
#endif

/* macro for implementation specific initialization routine */
#ifndef HEAPMGR_IMPL_INIT
#define HEAPMGR_IMPL_INIT()
#endif

/* macros for string operation */
#ifndef HEAPMGR_MEMSET
#define HEAPMGR_MEMSET(_d,_v,_c) memset(_d,_v,_c)
#endif

/* macro for debug assert */
#ifndef HEAPMGR_ASSERT
#define HEAPMGR_ASSERT(_exp)
#endif

/* constant value for heap size */
#undef AUTOHEAPSIZE
#ifndef HEAPMGR_SIZE
  #define HEAPMGR_SIZE 1024
#elif defined(HEAPMGR_SIZE) && (HEAPMGR_SIZE == 0)
  #undef HEAPMGR_SIZE
  #define AUTOHEAPSIZE
#endif

/* Minimum wasted bytes to justify splitting a block before allocation */
#ifndef HEAPMGR_MIN_BLKSZ
#define HEAPMGR_MIN_BLKSZ    4
#endif

/* Profiling memory allocations showed that a significant % of very high
 * frequency allocations/frees are for block sizes less than or equal to 16.
 */
#ifndef HEAPMGR_SMALL_BLKSZ
#define HEAPMGR_SMALL_BLKSZ  16
#endif

#ifdef HEAPMGR_PROFILER
#ifndef osal_memset
#define osal_memset memset
#endif
#define HEAPMGR_INIT_X       'X'
#define HEAPMGR_ALOC         'A'
#define HEAPMGR_REIN         'F'
#endif

/* Namespace */
#define HEAPMGR_FF1 HEAPMGR_PREFIXED(Ff1)
#define HEAPMGR_FF2 HEAPMGR_PREFIXED(Ff2)
#define HEAPMGR_HEAPSTORE HEAPMGR_PREFIXED(HeapStore)
#define HEAPMGR_HEAP HEAPMGR_PREFIXED(Heap)
#ifdef HEAPMGR_METRICS
#define HEAPMGR_BLKMAX HEAPMGR_PREFIXED(BlkMax)
#define HEAPMGR_BLKCNT HEAPMGR_PREFIXED(BlkCnt)
#define HEAPMGR_BLKFREE HEAPMGR_PREFIXED(BlkFree)
#define HEAPMGR_MEMALO HEAPMGR_PREFIXED(MemAlo)
#define HEAPMGR_MEMMAX HEAPMGR_PREFIXED(MemMax)
#define HEAPMGR_MEMUB  HEAPMGR_PREFIXED(MemUB)
#define HEAPMGR_MEMFAIL HEAPMGR_PREFIXED(MemFail)
#endif

typedef uint8_t  hmU8_t;
typedef uint16_t hmU16_t;
typedef uint32_t hmU32_t;

/** @internal memory block header */
#ifdef AUTOHEAPSIZE
  #ifdef CC26X2
    typedef hmU32_t  heapmgrHdr_t;
  #else // !CC26X2
    typedef hmU16_t  heapmgrHdr_t;
  #endif // CC26X2
#else // !AUTOHEAPSIZE
  #if HEAPMGR_SIZE < 32770
    typedef hmU16_t  heapmgrHdr_t;
  #else /* HEAPMGR_SIZE < 32770 */
    typedef hmU32_t  heapmgrHdr_t;
  #endif /* HEAPMGR_SIZE < 32770 */
#endif // AUTOHEAPSIZE

/** @internal flag bit in memory block header to indicate that the block is allocated */
#ifdef AUTOHEAPSIZE
  #ifdef CC26X2
    #define HEAPMGR_IN_USE   0x80000000u
  #else // !CC26X2
    #define HEAPMGR_IN_USE   0x8000u
  #endif // CC26X2
#else // !AUTOHEAPSIZE
  #if HEAPMGR_SIZE < 32770
    #define HEAPMGR_IN_USE   0x8000u
  #else /* HEAPMGR_SIZE < 32770 */
    #define HEAPMGR_IN_USE   0x80000000u
  #endif /* HEAPMGR_SIZE < 32770 */
#endif // AUTOHEAPSIZE

/* This number sets the size of the small-block bucket. Although profiling
 * shows max simultaneous alloc of 16x18, timing without profiling overhead
 * shows that the best worst case is achieved with the following.
 */
#define SMALLBLKHEAP        232

/* To maintain data alignment of the pointer returned, reserve the greater
 * space for the memory block header. */
#if defined _M_IX86 || defined _M_IA64
#define HEAPMGR_ALIGN_SIZE 1
#elif defined __ICC430__
#define HEAPMGR_ALIGN_SIZE 2
#elif defined __ICCARM__
#define HEAPMGR_ALIGN_SIZE 4
#elif defined __GNUC__ && defined i386
#define HEAPMGR_ALIGN_SIZE 4
#elif defined __GNUC__ && defined __arm__
#define HEAPMGR_ALIGN_SIZE 4
#elif defined (ccs)  || (rvmdk)
#define HEAPMGR_ALIGN_SIZE 4
#elif defined __TI_COMPILER_VERSION__ && defined __TI_ARM__
#define HEAPMGR_ALIGN_SIZE 4
#else
#error "Unsupported platform or compiler"
#endif

#ifdef AUTOHEAPSIZE
  #define HDRSZ 4
  typedef hmU32_t heapmgrAlign_t;
#else // !AUTOHEAPSIZE
  #if HEAPMGR_ALIGN_SIZE == 1 && HEAPMGR_SIZE < 32770
  #define HDRSZ 2
  typedef hmU16_t heapmgrAlign_t;
  #elif HEAPMGR_ALIGN_SIZE == 2 && HEAPMGR_SIZE < 32770
  #define HDRSZ 2
  typedef hmU16_t heapmgrAlign_t;
  #else
  #define HDRSZ 4
  typedef hmU32_t heapmgrAlign_t;
  #endif
#endif // AUTOHEAPSIZE

/*********************************************************************
 * GLOBAL VARIABLES
 */

/*********************************************************************
 * EXTERNAL VARIABLES
 */

/*********************************************************************
 * EXTERNAL FUNCTIONS
 */

/*********************************************************************
 * LOCAL VARIABLES
 */

static heapmgrHdr_t *HEAPMGR_FF1;  // First free block in the small-block bucket.
static heapmgrHdr_t *HEAPMGR_FF2;  // First free block after the small-block bucket.

#ifdef HEAPMGR_METRICS
hmU16_t HEAPMGR_BLKMAX  = 0; // Max cnt of all blocks ever seen at once.
hmU16_t HEAPMGR_BLKCNT  = 0; // Current cnt of all blocks.
hmU16_t HEAPMGR_BLKFREE = 0; // Current cnt of free blocks.
hmU16_t HEAPMGR_MEMALO  = 0; // Current total memory allocated.
hmU16_t HEAPMGR_MEMMAX  = 0; // Max total memory ever allocated at once.
hmU16_t HEAPMGR_MEMUB   = 0; // Upper-bound of memory usage
hmU16_t HEAPMGR_MEMFAIL = 0; // Memory allocation failure count
#endif

#ifdef HEAPMGR_PROFILER
#define HEAPMGR_PROMAX  8
/* The profiling buckets must differ by at least HEAPMGR_MIN_BLKSZ; the
 * last bucket must equal the max alloc size. Set the bucket sizes to
 * whatever sizes necessary to show how your application is using memory.
 */
static hmU16_t proCnt[HEAPMGR_PROMAX] =
{
  HEAPMGR_SMALL_BLKSZ, 48, 112, 176, 192, 224, 256, 65535
};
static hmU16_t proCur[HEAPMGR_PROMAX] = { 0 };
static hmU16_t proMax[HEAPMGR_PROMAX] = { 0 };
static hmU16_t proTot[HEAPMGR_PROMAX] = { 0 };
static hmU16_t proSmallBlkMiss;
#endif

/** @intenral Memory Allocation Heap. */
#ifdef AUTOHEAPSIZE
  static heapmgrAlign_t *HEAPMGR_HEAPSTORE;
  static hmU8_t         *HEAPMGR_HEAP;

  uint32 HEAPMGR_SIZE;

#ifdef __IAR_SYSTEMS_ICC__
  #pragma section = "RWDATA"
  #pragma section = "CSTACK"
#elif defined (__TI_COMPILER_VERSION__)
  extern char heapStart;
  extern char heapEnd;
#endif //__IAR_SYSTEMS_ICC__
#else // !AUTOHEAPSIZE
  static heapmgrAlign_t  HEAPMGR_HEAPSTORE[ HEAPMGR_SIZE/sizeof(heapmgrAlign_t) ];
  static hmU8_t         *HEAPMGR_HEAP = (hmU8_t *)&HEAPMGR_HEAPSTORE;
#endif // AUTOHEAPSIZE

/**
 * @brief   Initialize the heap memory management system.
 */
void HEAPMGR_INIT( void )
{
  heapmgrHdr_t *tmp;
#ifdef AUTOHEAPSIZE
#ifdef __IAR_SYSTEMS_ICC__
  uint32 endOfRwData  = ((uint32)__section_end("RWDATA") + 4) & ~3;
  uint32 startOfStack =  (uint32)__section_begin("CSTACK");
#elif defined(__TI_COMPILER_VERSION__)
  uint32 endOfRwData  = (((uint32)&heapStart) + 4) & ~3;
  uint32 startOfStack =  (uint32)&heapEnd;
#endif //__IAR_SYSTEMS_ICC__

  HEAPMGR_SIZE      = (startOfStack - endOfRwData); // both values are word aligned
  HEAPMGR_HEAPSTORE = (heapmgrAlign_t *)endOfRwData;
  HEAPMGR_HEAP      = (hmU8_t *)HEAPMGR_HEAPSTORE;

  // clear heap (optional)
  // Note: When AUTOHEAPSIZE isn't defined, heap is cleared by C runtime.
  for (tmp = (heapmgrHdr_t *)HEAPMGR_HEAPSTORE;
       tmp < (heapmgrHdr_t *)((uint32)HEAPMGR_HEAPSTORE+HEAPMGR_SIZE);
       tmp++)
  {
    *tmp = 0;
  }
#endif // AUTOHEAPSIZE

  /* Implementation specific initialization */
  HEAPMGR_IMPL_INIT();

#ifdef HEAPMGR_PROFILER
  (void)HEAPMGR_MEMSET( HEAPMGR_HEAP, HEAPMGR_INIT_X, (HEAPMGR_SIZE/HDRSZ)*HDRSZ );
#endif

  // Setup a NULL block at the end of the heap for fast comparisons with zero.
  tmp = (heapmgrHdr_t *)(HEAPMGR_HEAP + (HEAPMGR_SIZE / HDRSZ)*HDRSZ - HDRSZ);
  *tmp = 0;

  // Setup a small-block bucket.
  tmp = (heapmgrHdr_t *)HEAPMGR_HEAP;
  *tmp = (SMALLBLKHEAP / HDRSZ) * HDRSZ;

  // Setup the wilderness.
  tmp = (heapmgrHdr_t *)(HEAPMGR_HEAP + (SMALLBLKHEAP / HDRSZ)*HDRSZ);
  *tmp = ((HEAPMGR_SIZE/HDRSZ) * HDRSZ) - (SMALLBLKHEAP/HDRSZ)*HDRSZ - HDRSZ;

  // Setup a NULL block that is never freed so that the small-block bucket
  // is never coalesced with the wilderness.
  HEAPMGR_FF1 = tmp;
  HEAPMGR_FF2 = HEAPMGR_MALLOC( 0 );
  HEAPMGR_FF1 = (heapmgrHdr_t *)HEAPMGR_HEAP;

#ifdef HEAPMGR_METRICS
  /* Start with the small-block bucket and the wilderness - don't count the
   * end-of-heap NULL block nor the end-of-small-block NULL block.
   */
  HEAPMGR_BLKCNT = HEAPMGR_BLKFREE = 2;
  HEAPMGR_MEMFAIL = 0;
#endif
}

/**
 * @brief   Implementation of the allocator functionality.
 * @param   size - number of bytes to allocate from the heap.
 * @return  void * - pointer to the heap allocation; NULL if error or failure.
 */
void *HEAPMGR_MALLOC( hmU16_t size )
{
  heapmgrHdr_t *prev = NULL;
  heapmgrHdr_t *hdr;
  heapmgrHdr_t tmp;
  hmU8_t coal = 0;

  HEAPMGR_ASSERT( size );

  size += HDRSZ;

  // Calculate required bytes to add to 'size' to align to heapmgrAlign_t.
  if ( sizeof( heapmgrAlign_t ) == 2 )
  {
    size += (size & 0x01);
  }
  else if ( sizeof( heapmgrAlign_t ) != 1 )
  {
    const hmU8_t mod = size % sizeof( heapmgrAlign_t );

    if ( mod != 0 )
    {
      size += (sizeof( heapmgrAlign_t ) - mod);
    }
  }

  HEAPMGR_LOCK();  /* Lock the mutex */

  // Smaller allocations are first attempted in the small-block bucket.
  if ( size <= HEAPMGR_SMALL_BLKSZ )
  {
    hdr = HEAPMGR_FF1;
  }
  else
  {
    hdr = HEAPMGR_FF2;
  }
  tmp = *hdr;

  do
  {
    if ( tmp & HEAPMGR_IN_USE )
    {
      tmp ^= HEAPMGR_IN_USE;
      coal = 0;
    }
    else
    {
      if ( coal != 0 )
      {
#ifdef HEAPMGR_METRICS
        HEAPMGR_BLKCNT--;
        HEAPMGR_BLKFREE--;
#endif

        *prev += *hdr;

        if ( *prev >= size )
        {
          hdr = prev;
          tmp = *hdr;
          break;
        }
      }
      else
      {
        if ( tmp >= size )
        {
          break;
        }

        coal = 1;
        prev = hdr;
      }
    }

    hdr = (heapmgrHdr_t *)((hmU8_t *)hdr + tmp);

    tmp = *hdr;
    if ( tmp == 0 )
    {
      hdr = NULL;
      break;
    }

  }
  while ( 1 );

  if ( hdr == NULL )
  {
#ifdef HEAPMGR_METRICS
    HEAPMGR_MEMFAIL++;
#endif
  }
  else
  {
    tmp -= size;

    // Determine whether the threshold for splitting is met.
    if ( tmp >= HEAPMGR_MIN_BLKSZ )
    {
      // Split the block before allocating it.
      heapmgrHdr_t *next = (heapmgrHdr_t *)((hmU8_t *)hdr + size);
      *next = tmp;
      *hdr = (size | HEAPMGR_IN_USE);

#ifdef HEAPMGR_METRICS
      HEAPMGR_BLKCNT++;
      if ( HEAPMGR_BLKMAX < HEAPMGR_BLKCNT )
      {
        HEAPMGR_BLKMAX = HEAPMGR_BLKCNT;
      }
      HEAPMGR_MEMALO += size;
      {
        hmU16_t ub = (hmU16_t)(unsigned)(((hmU8_t *)hdr + size) - HEAPMGR_HEAP);
        if (HEAPMGR_MEMUB < ub)
        {
          HEAPMGR_MEMUB = ub;
        }
      }
#endif
    }
    else
    {
#ifdef HEAPMGR_METRICS
      HEAPMGR_MEMALO += (hmU16_t) *hdr;
      HEAPMGR_BLKFREE--;
      {
        hmU16_t ub = (hmU16_t)(unsigned)(((hmU8_t *)hdr + *hdr) - HEAPMGR_HEAP);
        if (HEAPMGR_MEMUB < ub)
        {
          HEAPMGR_MEMUB = ub;
        }
      }
#endif

      *hdr |= HEAPMGR_IN_USE;
    }

#ifdef HEAPMGR_METRICS
    if ( HEAPMGR_MEMMAX < HEAPMGR_MEMALO )
    {
      HEAPMGR_MEMMAX = HEAPMGR_MEMALO;
    }
#endif

#ifdef HEAPMGR_PROFILER
    {
      hmU8_t idx;
      size = *hdr ^ HEAPMGR_IN_USE;

      for ( idx = 0; idx < HEAPMGR_PROMAX; idx++ )
      {
        if ( size <= proCnt[idx] )
        {
          break;
        }
      }
      proCur[idx]++;
      if ( proMax[idx] < proCur[idx] )
      {
        proMax[idx] = proCur[idx];
      }
      proTot[idx]++;
    }
#endif

    hdr = (heapmgrHdr_t *) ((hmU8_t *) hdr + HDRSZ);

#ifdef HEAPMGR_PROFILER
    (void)osal_memset( (hmU8_t *)hdr, HEAPMGR_ALOC, (size - HDRSZ) );

    /* A small-block could not be allocated in the small-block bucket.
     * When this occurs significantly frequently, increase the size of the
     * bucket in order to restore better worst case run times. Set the first
     * profiling bucket size in proCnt[] to the small-block bucket size and
     * divide proSmallBlkMiss by the corresponding proTot[] size to get % miss.
     * Best worst case time on TrasmitApp was achieved at a 0-15% miss rate
     * during steady state Tx load, 0% during idle and steady state Rx load.
     */
    if ( (size <= HEAPMGR_SMALL_BLKSZ) && (hdr > HEAPMGR_FF2) )
    {
      proSmallBlkMiss++;
    }
#endif
  }

  HEAPMGR_UNLOCK();  /* unlock the mutex */

  return (void *)hdr;
}

/**
 * @brief         Re-allocates a memory block of the requested
 *                size.
 *                Note that this function always re-allocates
 *                even if the requested size is lower than the
 *                original.
 * @param ptr     pointer to the existing memory block.
 * @param size    size in bytes of the memory block to
 *                re-allocate
 *
 * @return void*  pointer to the memory block of newly
 *                re-allocation or if reallocation fails
 *                returns the pointer to the original memory
 *                block.
 */
void *HEAPMGR_REALLOC( void* ptr, hmU16_t size )
{
  void *newPtr;
  heapmgrHdr_t *currHdr;
  hmU16_t origSize;

  HEAPMGR_ASSERT( size );

  currHdr = (heapmgrHdr_t *)((hmU8_t *)ptr - HDRSZ);

  origSize = (hmU16_t)((*currHdr) & (~HEAPMGR_IN_USE));

  if ( origSize == size )
  {
    return ptr;
  }

  newPtr = HEAPMGR_MALLOC( size );

  if ( newPtr )
  {
    hmU16_t n = origSize < size ? origSize : size;
    memcpy( newPtr, ptr, n );
    HEAPMGR_FREE( ptr );
    return newPtr;
  }

  return NULL;
}

/**
 * @brief   Implementation of the de-allocator functionality.
 * @param   ptr - pointer to the memory to free.
 */
void HEAPMGR_FREE( void *ptr )
{
  heapmgrHdr_t *currHdr;

  HEAPMGR_LOCK();

  HEAPMGR_ASSERT(((hmU8_t *)ptr >= (hmU8_t *)HEAPMGR_HEAPSTORE) &&
                 ((hmU8_t *)ptr < (hmU8_t *)HEAPMGR_HEAPSTORE+(HEAPMGR_SIZE/HDRSZ)*HDRSZ));

  currHdr = (heapmgrHdr_t *)((hmU8_t *)ptr - HDRSZ);

  HEAPMGR_ASSERT(*currHdr & HEAPMGR_IN_USE);

  *currHdr &= ~HEAPMGR_IN_USE;

#ifdef HEAPMGR_PROFILER
  {
    hmU16_t size = *currHdr;
    hmU8_t idx;

    for ( idx = 0; idx < HEAPMGR_PROMAX; idx++ )
    {
      if ( size <= proCnt[idx] )
      {
        break;
      }
    }

    proCur[idx]--;
  }
#endif

#ifdef HEAPMGR_METRICS
  HEAPMGR_MEMALO -= (hmU16_t) *currHdr;
  HEAPMGR_BLKFREE++;
#endif

  if ( HEAPMGR_FF1 > currHdr )
  {
    HEAPMGR_FF1 = currHdr;
  }

#ifdef HEAPMGR_PROFILER
  (void)HEAPMGR_MEMSET( (hmU8_t *)currHdr+HDRSZ, HEAPMGR_REIN, (*currHdr - HDRSZ) );
#endif

  HEAPMGR_UNLOCK();
}

#ifdef HEAPMGR_METRICS
/**
 * @brief   obtain heap usage metrics
 * @param   pBlkMax   pointer to a variable to store max cnt of all blocks ever seen at once
 * @param   pBlkCnt   pointer to a variable to store current cnt of all blocks
 * @param   pBlkFree  pointer to a variable to store current cnt of free blocks
 * @param   pMemAlo   pointer to a variable to store current total memory allocated
 * @param   pMemMax   pointer to a variable to store max total memory ever allocated at once
 * @param   pMemUB    pointer to a variable to store the upper bound of memory usage
 */
void HEAPMGR_GETMETRICS(hmU16_t *pBlkMax,
                        hmU16_t *pBlkCnt,
                        hmU16_t *pBlkFree,
                        hmU16_t *pMemAlo,
                        hmU16_t *pMemMax,
                        hmU16_t *pMemUB)
{
  HEAPMGR_LOCK();
  *pBlkMax = HEAPMGR_BLKMAX;
  *pBlkCnt = HEAPMGR_BLKCNT;
  *pBlkFree = HEAPMGR_BLKFREE;
  *pMemAlo = HEAPMGR_MEMALO;
  *pMemMax = HEAPMGR_MEMMAX;
  *pMemUB = HEAPMGR_MEMUB;
  HEAPMGR_UNLOCK();
}

/**
 * @brief   Sanity checks heap
 * @return  0 when heap is OK. Non-zero, otherwise.
 */
int HEAPMGR_SANITY_CHECK(void)
{
  heapmgrHdr_t *hdr;
  heapmgrHdr_t tmp;
  int result = 0;

  HEAPMGR_LOCK();

  hdr = HEAPMGR_FF1;
  for (;;)
  {
    tmp = *hdr;
    tmp &= ~HEAPMGR_IN_USE;
    if (tmp == 0)
    {
      if ((hmU8_t *) hdr != (HEAPMGR_HEAP + (HEAPMGR_SIZE / HDRSZ)*HDRSZ - HDRSZ))
      {
        result = 1;
      }
      break;
    }
    hdr = (heapmgrHdr_t *)((hmU8_t *)hdr + tmp);
    if ((hmU8_t *) hdr >= (HEAPMGR_HEAP + (HEAPMGR_SIZE / HDRSZ) *HDRSZ))
    {
      result = 2;
      break;
    }
  }

  HEAPMGR_UNLOCK();
  return result;
}

#endif /* HEAPMGR_METRICS */

/*********************************************************************
*********************************************************************/


text:
<?php

namespace Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;

use function is_resource;
use function stream_get_contents;

/**
 * Type that maps an SQL CLOB to a PHP string.
 */
class TextType extends Type
{
    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $column, AbstractPlatform $platform)
    {
        return $platform->getClobTypeDeclarationSQL($column);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return is_resource($value) ? stream_get_contents($value) : $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return Types::TEXT;
    }
}


text:
@interface PodsDummy_Pods_RYImagePicker : NSObject
@end
@implementation PodsDummy_Pods_RYImagePicker
@end


text:
Imagine a bot with hundreds of different responses, where each response is localized in different languages. Each response with multiple different possible answers (actions)...

Because of the number of dialogs and prompts this generates, hard-coding this isn't a viable option. Also, maintaining something like this would be difficult and time-consuming.

With that in mind, the best decision is to make the bot completely data driven. Store the responses and actions in a data storage, while allowing any editing to potentially be done through a management interface.

This sample covers building a dynamic bot, completely dependant on a seperate data storage.

> This project demonstrates the ability to provide a solution to customers, wherever they are. Not only does it have a great reach with Bot Framework, but it's also developed in a maintainable fashion with a common code base. It leverages technologies and development stacks which the customer can take care of - ensuring the future of the project.

## Project ###
Project | Author(s)
---------|----------
DynamicDialogApi, DynamicDialogBot | [Anders Thun](https://twitter.com/AndersThun), [Dag König](https://twitter.com/buzzfrog), [Peter Bryntesson](https://twitter.com/petbry57), [Simon Jäger](https://twitter.com/simonjaegr), [Tess Ferrandez](https://twitter.com/TessFerrandez)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0  | March 22, 2017 | Initial release

### Disclaimer ###
**THIS CODE IN THIS REPOSITORY IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

---

## Prerequisites ##

This sample requires the following:

  * [Visual Studio 2017](https://www.visualstudio.com/downloads)
  * [Bot Framework SDK](https://docs.botframework.com/en-us/downloads/)
  * [ASP.NET Core](https://www.asp.net/core)
  * [Azure Subscription](https://azure.microsoft.com/en-us/free/)

## Getting started ##

To get started, clone this repository (```git clone https://github.com/simonjaeger/dynamic-dialog-bot-sample```) and follow the steps.

### Create the Azure SQL Database ###

1. Go to the [Azure Portal](http://portal.azure.com/) and sign into your subscription.

1. Click on **New** to create a new resource.

    ![Create a new resource in Azure Portal](/Images/newresource.png)

1. Search for "SQL Database" and pick **SQL Database** by Microsoft.

    ![Search for SQL Database](/Images/newazuresqldb.png)

1. Click **Create**.

1. Finalize the configuration for the Azure SQL Database.
    1. Enter a database name.
    1. Pick the subscription.
    1. Select a blank database.
    1. Configure the server settings, remember the user name and password.
    1. Pick a pricing tier.

1. Click **Create**.

    ![Create a new Azure SQL Database](/Images/createazuresqldb.png)

### Configure the Web API ###

1. Launch the Web API project, **\DynamicDialogApi\DynamicDialogApi.sln** Visual Studio 2017.

1. Click on **View** in the top menu.

1. Click on **SQL Server Object Explorer**.

    ![Open the SQL Server Object Explorer](/Images/sqlserverexplorer.png)

1. Click on **Add SQL Server**.

1. Expand **Azure**.

1. Select the same account and subscription you signed into the Azure Portal with.

1. Select the Azure SQL Database that you created.

1. Enter the user name and password that you configured earlier.

1. Click on **Connect**.

    ![Connect to the the Azure SQL Server](/Images/connecttodb.png)

1. Add your client IP to the firewall if needed. Click on **OK**.

    ![Connect to the the Azure SQL Server](/Images/addipfirewall.png)

1. Right click on the Azure SQL Database in the SQL Server Object Explorer.

1. Click on **Properties**.

1. Copy the **Connection string**.

    ![Copy the connection string](/Images/connectionstring.png)

1. Open **appsettings.json** in the DynamicDialogApi project.

1. Replace "YOUR CONNECTION STRING" with your connection string.

1. Locate the **Password=\*\*\*\*\*\*\*\*** part of the connection string. Replace the asterisks with the password that you configured earlier for your Azure SQL Database.

    ![Edit the connection string](/Images/connectionstringpassword.png)

1. Click on **Tools** in the top menu.
1. Expand **NuGet Package Manager** and click on **Package Manager Console**.

    ![Edit the connection string](/Images/packagemanagerconsole.png)

1. Run the following commands. This will prepare the Azure SQL Database with required schemas.
    1. Add-Migration "Initial"
    1. Update-Database

1. Right click on the Azure SQL Database in the SQL Server Object Explorer.

1. Click on **New Query...**

1. Select your Azure SQL Database in the query window.

1. Copy the contents of the script file, **\Scripts\db-script.sql** and paste it in the query window.

1. Click on **Execute**.

    ![Edit the connection string](/Images/sqlquery.png)

1. Right click on the Web API project, **DynamicDialogApi** in the Solution Explorer.

1. Click on **Properties**.

    ![Edit the connection string](/Images/projectproperties.png)

1. Click on **Debug**.

1. Copy the **App URL** (default http://localhost:8087/). This is the URL which the Web API will run at.

1. Click on the **Start Debugging** button to start the Web API.

    ![Edit the connection string](/Images/startdebuggingapi.png)

### Configure the Bot ###

1. Launch the bot project, **\DynamicDialogBot\DynamicDialogBot.sln** Visual Studio 2017.

1. Expand the **Services** folder.

1. Open the **ResponseService.cs** file.

1. Replace "<YOUR API ENDPOINT>" with the **App URL** of your Web API.

1. Open **Web.config**.

1. Replace "YOUR APP ID" and "YOUR APP PASSWORD" with your own configuration (see (https://docs.botframework.com/en-us/bot-framework-guide-id/)[https://docs.botframework.com/en-us/bot-framework-guide-id/]) or empty. Leaving the properties blank works for debugging and testing the sample.

    ```xml
    <appSettings>
        <!-- update these with your BotId, Microsoft App Id and your Microsoft App Password-->
        <add key="BotId" value="YourBotId" />
        <add key="MicrosoftAppId" value="" />
        <add key="MicrosoftAppPassword" value="" />
    </appSettings>
    ```

1. Right click on the bot project, **DynamicDialogBot** in the Solution Explorer.

1. Click on **Properties**.

    ![Edit the connection string](/Images/projectpropertiesbot.png)

1. Click on **Web**.

1. Copy the **Project Url** (default http://localhost:3978/). This is the URL which the bot will run at.

1. Click on the **Start Debugging** button to start the bot.

    ![Edit the connection string](/Images/startdebuggingbot.png)

### Run the Bot Emulator ###

1. Launch the Bot Framework Channel Emulator.

1. Enter the **Project Url** and "/api/messages in the "Enter your endpoint URL" section. In example: http://localhost:3978/api/messages

1. Click on **Connect**.

    ![Edit the connection string](/Images/emulatorconnect.png)

1. You can now try out the bot!

    ![Edit the connection string](/Images/emulatorconnected.png)

## Contributing ##

If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md).

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

## Additional resources ##

- [Bot Framework](https://dev.botframework.com/)

- [AlarmBot Sample](https://github.com/Microsoft/BotBuilder/tree/master/CSharp/Samples/AlarmBot)

- [Azure SQL Database](https://azure.microsoft.com/en-us/services/sql-database/?b=16.50)

## Copyright
Copyright (c) 2017 Microsoft. All rights reserved.


text:
use error::GitError;

pub type EmptyResult = Result<(), GitError>;


text:
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/init_task.h>
#include <linux/fs.h>
#include <linux/mqueue.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>

static struct signal_struct init_signals = INIT_SIGNALS(init_signals);
static struct sighand_struct init_sighand = INIT_SIGHAND(init_sighand);
/*
 * Initial thread structure.
 *
 * We need to make sure that this is THREAD_SIZE aligned due to the
 * way process stacks are handled. This is done by having a special
 * "init_task" linker map entry..
 */
union thread_union init_thread_union __init_task_data =
	{ INIT_THREAD_INFO(init_task) };

/*
 * Initial task structure.
 *
 * All other task structs will be allocated on slabs in fork.c
 */
struct task_struct init_task = INIT_TASK(init_task);
EXPORT_SYMBOL(init_task);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.udacity.gradle.builditbigger.joker"
    >

    <application
        android:label="@string/app_name"
        android:supportsRtl="true"
        >
        <activity
            android:name=".JokeActivity"
            >
        </activity>
    </application>

</manifest>


text:
require "hotel_beds/action/operation"
require_relative "envelope"
require_relative "request"
require_relative "response"

module HotelBeds
  module TicketSearch
    class Operation < HotelBeds::Action::Operation
      remote_method :getTicketAvail
      remote_namespace :TicketAvailRQ
      envelope_class Envelope
      request_class Request
      response_class Response
    end
  end
end


text:
<?php namespace Neonbug\Common\Traits;

use App;
use Event;
use Hash;

trait PasswordTrait {

	protected static $booted_password_trait = false;

	public static function bootPasswordTrait()
	{
		if (self::$booted_password_trait === true) return;
		self::$booted_password_trait = true;

		//TODO remove this file for 1.0 release, since it's here just for backwards compatiblity
	}

}


text:
class FormProtectController < ApplicationController

  def protect
       session[:noisy_image] = NoisyImage.new(5)
       session[:code] = session[:noisy_image].code
       session[:image_blog] = session[:noisy_image].code_image
       render :nothing=>true
  end

  def show_image
     send_data session[:image_blog], :type => 'image/jpeg', :disposition => 'inline'
     k = Kirby.new
     k.update_code(session[:code])
  end

  def show_code
     @c = session[:code]
  end

  def show_code_kirby
     @c = session[:code]
  end

 def check
   k = Kirby.new
   @t = k.show_code_from_base
   @letter = params[:id]
   @l_ln = @letter.length
   @real = @t.str.to_s[0,@l_ln]

   right = @real.split('')
   entered = @letter.split('')
   tm = entered.length

   i=0
   @err=0
   @colored=''
   tm.times do
     if right[i]==entered[i]
      @colored+=""+entered[i].to_s+""
     else
      @colored+=""+entered[i].to_s+""
      @err=@err.succ()
     end
     i=i.succ()
   end

 end

end