text:
from numpy import *
import Block
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from Connexion import *
import zmq
import json
from threading import Thread
import Tools
import time

class Robot(Block.Block,QWidget):
    """ this class describes a block """

    def __init__(self,members,IP = '127.0.0.1',port = '8080'):
        Block.Block.__init__(self)
        QWidget.__init__(self)
        self.IP = IP
        self.port = port
        # members is a dictionnary containing list of motors
        self.members = members
        # declaration of connexions
        # duration of the pose
        self.inputs["Duration"] = Connexion(default = "1")
        # name of the pose
        self.inputs["Name"] = Connexion(default = "toto")
        # number of the pose
        self.inputs["Number"] = Connexion(default = "0")
        # emergency stop
        self.inputs["Emergency"] = Connexion(default = "0")
        # temperature inside the robot
        self.outputs["Temperature"] = Connexion(default = "0")
        # battery voltage of the robot
        self.outputs["Voltage"] = Connexion(default = "0")
        for member in self.members:
            for art in self.members[member]:
                # which pose to present
                self.inputs[art] = Connexion(default = "M")
                # what position for each motor
                self.outputs[art] = Connexion(default = "0")

        # creation of components
        self.dict_checkbox = {}

        self.dict_checkbox["All"] = QCheckBox("Force All mou")
        self.resetButton = QPushButton("Reset Robot")
        self.abreath = QDoubleSpinBox()
        self.abreath.setPrefix("br. amp. :")
        self.abreath.setValue(3.0)
        self.abreath.setSingleStep(1)
        self.abreath.setMinimum(0.1)
        self.tbreath = QDoubleSpinBox()
        self.tbreath.setPrefix("br. per. :")
        self.tbreath.setValue(3.0)
        self.tbreath.setSingleStep(0.1)
        self.tbreath.setMinimum(0.1)

        for member in self.members:
            self.dict_checkbox[member] = QCheckBox("Force "+member+" mou")

        self.tempLabel = QLabel("Max Temp : 0deg")
        self.hottestMotor = QLabel("Hottest motor : TBD")
        self.minVoltLabel = QLabel("Min Voltage : 0V")
        self.maxVoltLabel = QLabel("Max Voltage : 0V")
        self.LoadLabel = QLabel("head : 0\nr_arm : 0,0,0,0\nl_arm : 0,0,0,0\nr_leg : 0,0,0,0,0\nl_leg : 0,0,0,0,0\ntorso : 0,0,0,0,0")

        # composition
        mainlayout = QVBoxLayout(self)
        for member in self.dict_checkbox:
            mainlayout.addWidget(self.dict_checkbox[member])
        mainlayout.addWidget(self.tempLabel)
        mainlayout.addWidget(self.hottestMotor)
        mainlayout.addWidget(self.minVoltLabel)
        mainlayout.addWidget(self.maxVoltLabel)
        mainlayout.addWidget(self.resetButton)
        mainlayout.addWidget(self.abreath)
        mainlayout.addWidget(self.tbreath)
        mainlayout.addWidget(self.LoadLabel)

        # signals
        for member in self.members:
                self.connect(self.dict_checkbox["All"],SIGNAL("toggled(bool)"),self.dict_checkbox[member],SLOT("setChecked(bool)"))

        self.show()

    def start(self):
        self.COM = clientThread(self.IP,self.port)
        self.COM.start()

    def init(self,f):
        return f

    def getInputs(self,f):
        r = {}
        r["Duration"] = self.inputs['Duration'].getValue(f)
        r["Name"] = self.inputs['Name'].getValue(f)
        r["Number"] = self.inputs['Number'].getValue(f)
        r["Abreath"] = self.abreath.value()
        r["Tbreath"] = self.tbreath.value()
        for member in self.members:
            for art in self.members[member]:
                if self.inputs["Emergency"].getValue(f) == "1":
                    a = "M"
                elif self.dict_checkbox[member].isChecked():
                    a = "M"
                else:
                    a = self.inputs[art].getValue(f)
                r[art] = a
        if self.resetButton.isDown():
            self.COM._reset = True
        else:
            self.COM._reset = False
        self.COM._robotOut = r

    def setOutputs(self,f):
        r = self.COM._robotIn
        if len(r)>0:
            self.outputs["Temperature"].setValue(float(r["Temperature"]),f)
            self.outputs["Voltage"].setValue(r["VoltageMin"],f)
            for member in self.members:
                for art in self.members[member]:
                    if r.has_key(art):
                        self.outputs[art].setValue(r[art],f)
            self.tempLabel.setText("Max Temp : "+r["Temperature"]+"deg")
            if r.has_key("Hottest"):
                self.hottestMotor.setText("Hottest motor : "+r["Hottest"])
            self.minVoltLabel.setText("Min voltage : "+r["VoltageMin"]+"V")
            self.maxVoltLabel.setText("Max voltage : "+r["VoltageMax"]+"V")
            self.LoadLabel.setText("head : "+r["v_head_y"]+","+r["v_head_z"]+"\nr_arm : "+r["v_r_shoulder_y"]+","+r["v_r_shoulder_x"]+","+r["v_r_arm_z"]+","+r["v_r_elbow_y"]+"\nl_arm : "+r["v_l_shoulder_y"]+","+r["v_l_shoulder_x"]+","+r["v_l_arm_z"]+","+r["v_l_elbow_y"]+"\nr_leg : "+r["v_r_hip_x"]+","+r["v_r_hip_z"]+","+r["v_r_hip_y"]+","+r["v_r_knee_y"]+","+r["v_r_ankle_y"]+"\nl_leg : "+r["v_l_hip_x"]+","+r["v_l_hip_z"]+","+r["v_l_hip_y"]+","+r["v_l_knee_y"]+","+r["v_l_ankle_y"]+"\ntorso : "+r["v_bust_x"]+","+r["v_bust_y"]+","+r["v_abs_z"]+","+r["v_abs_x"]+","+r["v_abs_y"])

        return f

class clientThread(Thread):

    def __init__(self,IP,port):
        # setup zmq context
        Thread.__init__(self)
        self._IP = IP
        self._port = port
        self._context = zmq.Context()
        self._socket = self._context.socket(zmq.REQ)
        self._socket.connect("tcp://"+self._IP+":"+self._port)
        self._robotIn = {}
        self._robotOut = {}
        self._reset = False
        self._active = True
        self.poll = zmq.Poller()
        self.poll.register(self._socket,zmq.POLLIN)

    def run(self):
        send = 0
        while self._active:
            t0 = Tools.getTime()
            if self._reset == False:
                if send == 0:
                    req = {"robot":{"get_pose":"1"}}
                elif send == 1:
                    req = {"robot":{"set_pose":self._robotOut}}
            else:
                req = {"robot":{"reset":"1"}}
            self._socket.send_json(req)
            expect = True
            while expect:
                socks = dict(self.poll.poll(100))
                #print socks.get(self._socket)
                if socks.get(self._socket) == zmq.POLLIN:
                    #print "t1"
                    reply = self._socket.recv_json()
                    #print reply
                    if not reply:
                        break
                    else:
                        if send == 0:
                            self._robotIn = reply
                        expect = False
                else:
                    #print "reconnect"
                    self._socket.setsockopt(zmq.LINGER, 0)
                    self._socket.close()
                    self.poll.unregister(self._socket)
                    self._socket = self._context.socket(zmq.REQ)
                    self._socket.connect("tcp://"+self._IP+":"+self._port)
                    self.poll.register(self._socket,zmq.POLLIN)
                    self._socket.send_json(req)
            if send == 0:
                send = 1
            else:
                send = 0
            while Tools.getTime()-t0<0.05:
                a=1

    def close(self):
        self._active = False
        time.sleep(0.01)
        self._socket.close()

redpajama_set_name: RedPajamaGithub


text:
sheaf::preorder_iterator::
preorder_iterator()
    : filtered_depth_first_iterator()
{

  // Preconditions:

  // Body:

  initialize_order(PREORDER);

  // Postconditions:

  ensure(invariant());
  ensure(!is_initialized());

  // Exit

  return;
}

sheaf::preorder_iterator::
preorder_iterator(const preorder_iterator& xother)
    : filtered_depth_first_iterator(xother)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit

  return;
}

sheaf::preorder_iterator::
~preorder_iterator()
{
  // Preconditions:

  // Body:

  // Postconditions:

}

bool
sheaf::preorder_iterator::
is_ancestor_of(const any*  xother) const
{
  bool result;

  // Preconditions:

  // Body:

  result = dynamic_cast<const preorder_iterator*>(xother) != 0;

  // Postconditions:

  // Exit

  return result;
}

sheaf::preorder_iterator*
sheaf::preorder_iterator::
clone() const
{
  preorder_iterator* result;

  // Preconditions:

  // Body:

  result = new preorder_iterator;

  // Postconditions:

  ensure(result != 0);
  ensure(is_same_type(result));
  ensure(!result->is_initialized());

  // Exit

  return result;
}

bool
sheaf::preorder_iterator::
invariant() const
{
  bool result = true;

  // Preconditions:

  // Body:

  invariance(filtered_depth_first_iterator::invariant());
  invariance(order()==PREORDER);

  // Postconditions:

  // Exit

  return result;
}

// OTHER CONSTRUCTORS

sheaf::preorder_iterator::
preorder_iterator(const abstract_poset_member& xanchor,
                  bool xdown,
                  bool xstrict)
    : filtered_depth_first_iterator(xanchor, xdown, xstrict, PREORDER)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}

sheaf::preorder_iterator::
preorder_iterator(const abstract_poset_member& xanchor,
                  const subposet& xfilter,
                  bool xdown,
                  bool xstrict)
    : filtered_depth_first_iterator(xanchor, xfilter, xdown, xstrict, PREORDER)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}

sheaf::preorder_iterator::
preorder_iterator(const abstract_poset_member& xanchor,
                  pod_index_type xfilter_index,
                  bool xdown,
                  bool xstrict)
    : filtered_depth_first_iterator(xanchor, xfilter_index, xdown, xstrict, PREORDER)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}

sheaf::preorder_iterator::
preorder_iterator(const abstract_poset_member& xanchor,
                  const scoped_index& xfilter_index,
                  bool xdown,
                  bool xstrict)
    : filtered_depth_first_iterator(xanchor, xfilter_index, xdown, xstrict, PREORDER)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}

sheaf::preorder_iterator::
preorder_iterator(const abstract_poset_member& xanchor,
                  const std::string& xfilter_name,
                  bool xdown,
                  bool xstrict)
    : filtered_depth_first_iterator(xanchor, xfilter_name, xdown, xstrict, PREORDER)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}


text:
import sys
import threading
import queue
import tty
import termios
import signal
import atexit

# We change the TTY settings to emit single characters (not by line) and
# ensure the settings are reversed at shutdown
old_tty_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
def reset_tty():
  print("Reset TTY settings.")
  termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty_settings)
atexit.register(reset_tty)

# Make sure we dont swallow Ctrl+C
def signal_handler(sig, frame): sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)

def monitor_stdin(char_queue):
  while True:
    ch = sys.stdin.read(1) # Blocks until next char
    if ch:
      char_queue.put(ch)
      print("Key pressed:", ch)

char_queue = queue.Queue()
input_thread = threading.Thread(target=monitor_stdin, args=(char_queue,))
input_thread.daemon = True
input_thread.start()

def has_char():
  return not char_queue.empty()

def get_char():
  return None if char_queue.empty() else char_queue.get()


text:
package io.debezium.testing.system.assertions;

import static io.debezium.testing.system.tools.WaitConditions.scaled;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.awaitility.core.ThrowingRunnable;

public interface KafkaAssertions<K, V> {

    static void awaitAssert(long timeout, TimeUnit unit, ThrowingRunnable assertion) {
        await()
                .pollDelay(2, TimeUnit.SECONDS)
                .atMost(timeout, unit)
                .untilAsserted(assertion);
    }

    static void awaitAssert(ThrowingRunnable assertion) {
        awaitAssert(scaled(1), TimeUnit.MINUTES, assertion);
    }

    default void assertTopicsExist(String... names) {
        try (Consumer<K, V> consumer = getConsumer()) {
            await().atMost(scaled(2), TimeUnit.MINUTES).untilAsserted(() -> {
                Set<String> topics = consumer.listTopics().keySet();
                assertThat(topics).contains(names);
            });
        }
    }

    default void assertRecordsCount(String topic, int count) {
        try (Consumer<K, V> consumer = getConsumer()) {
            consumer.subscribe(Collections.singleton(topic));
            ConsumerRecords<K, V> records = consumer.poll(Duration.of(10, ChronoUnit.SECONDS));
            consumer.seekToBeginning(consumer.assignment());
            assertThat(records.count()).withFailMessage("Expecting topic '%s' to have <%d> messages but it had <%d>.", topic, count, records.count()).isEqualTo(count);
        }
    }

    default void assertMinimalRecordsCount(String topic, int count) {
        try (Consumer<K, V> consumer = getConsumer()) {
            consumer.subscribe(Collections.singleton(topic));
            ConsumerRecords<K, V> records = consumer.poll(Duration.of(10, ChronoUnit.SECONDS));
            consumer.seekToBeginning(consumer.assignment());
            assertThat(
                    records.count()).withFailMessage("Expecting topic '%s' to have  at least <%d> messages but it had <%d>.", topic, count, records.count())
                            .isGreaterThanOrEqualTo(count);
        }
    }

    void assertRecordsContain(String topic, String content);

    Consumer<K, V> getConsumer();
}


text:
package com.xinyou.label.domain.viewes;

import java.math.BigDecimal;

public class STK_ITM_VIEW {
	private long stk_dt;
	private String emp_id;
	private String emp_name;
	private String ctn_baco;
	private int ctn_type;
	private String itm_id;
	private BigDecimal itm_qty;
	private BigDecimal stk_itm_qty;
	private int reason;
	private String stkloc;
	private String ctnloc;

	public String getStkloc() {
		return stkloc;
	}
	public void setStkloc(String stkloc) {
		this.stkloc = stkloc;
	}
	public String getCtnloc() {
		return ctnloc;
	}
	public void setCtnloc(String ctnloc) {
		this.ctnloc = ctnloc;
	}
	public BigDecimal getStk_itm_qty() {
		return stk_itm_qty;
	}
	public void setStk_itm_qty(BigDecimal stk_itm_qty) {
		this.stk_itm_qty = stk_itm_qty;
	}
	public int getReason() {
		return reason;
	}
	public void setReason(int reason) {
		this.reason = reason;
	}
	private String loc_baco;

	public String getLoc_baco() {
		return loc_baco;
	}
	public void setLoc_baco(String loc_baco) {
		this.loc_baco = loc_baco;
	}
	public BigDecimal getItm_qty() {
		return itm_qty;
	}
	public void setItm_qty(BigDecimal itm_qty) {
		this.itm_qty = itm_qty;
	}
	public long getStk_dt() {
		return stk_dt;
	}
	public void setStk_dt(long stk_dt) {
		this.stk_dt = stk_dt;
	}
	public String getEmp_id() {
		return emp_id;
	}
	public void setEmp_id(String emp_id) {
		this.emp_id = emp_id;
	}
	public String getEmp_name() {
		return emp_name;
	}
	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}
	public String getCtn_baco() {
		return ctn_baco;
	}
	public void setCtn_baco(String ctn_baco) {
		this.ctn_baco = ctn_baco;
	}
	public int getCtn_type() {
		return ctn_type;
	}
	public void setCtn_type(int ctn_type) {
		this.ctn_type = ctn_type;
	}
	public String getItm_id() {
		return itm_id;
	}
	public void setItm_id(String itm_id) {
		this.itm_id = itm_id;
	}
}


text:
© Bruce Wilcox, mailto:gowilcox@gmail.com www.brilligunderstanding.com
<br>Revision 2/18/2018 cs8.1

'''There's more than one way to skin a cat'''. A problem often has more than one solution. This is certainly true with ChatScript. The purpose of the Practicum series is to show you how to think about features of ChatScript and what guidelines to follow in designing and coding your bot.

#
# THEORY - philosophy and goals
#

Bots that require the user learn an English command set to function are only slightly better than a GUI.
Humans want computers to talk in human language, not visa versa.
So our job is to understand as many of the ways a user can say things as possible.
This is done using patterns.

Patterns are the lifeblood of ChatScript. The rest of ChatScript may be considered just programming,
but patterns blend into art and linguistic skillsets.  Pattern syntax is described in the beginners and advanced ChatScript
manuals and reprised in the Pattern Redux manual. This manual is not going to cover all of them.
It is here to help you make practical decisions about which pattern element to use when.

# Patterns, optimization, and the engine

Generally speaking, there is rarely any value in making a pattern
choice based on speed or memory considerations. The engine is already highly
optimzed for executing rules. My chatbot Rose has around 9,000 responders of 13,500 rules.
So she is, in a sense, largely an FAQ bot able to answer questions
like "how old is your mother", "where do you live", and "what is your favorite fruit."
She averages executing 1500-2000 rules per volley, which takes her around 13 milliseconds.
And half or more of that time is spent in the NLP pipeline preparing the input. So optimizing
patterns rarely makes sense.

## Compilation

The script compiler reads your script, confirms it is legal, and subtley adjusts it for
faster execution. Your patterns consist of elements. These include
ordinary words (`brain`), concepts (`~animals`), user variables ('$'), match variables ('_'),
factsets ('@'), comparisons (`_0>5`), and various
special characters like '{', '<<', ')', '!' and others). The engine expects each token to be uniformly spaced by a separating blank,
so however you space your code, the compiler adjusts it appropriately for execution.
Because the engine uses the lead character of an element
to branch to code handling it, it sometimes adds a prefix code to what you wrote.
If you ever look at a trace, you will see them, as well as accelerators.
```
u: MYLABEL ( $test<5) ok. ==> 00y u: 9MYLABEL ( =7$test<5 ) ok.
```

The 00y tells CS how many characters to jump ahead to reach the end of the entire rule.
The 9 in front of MYLABEL tells how many characters to skip over to reach the actual pattern.
Inside the pattern, because we did a comparison, that is prefixed with `=` and the 7 tells CS how many
characters to skip over to find the comparison operator to use.

The time it takes to execute a pattern is roughly a constant times how many
pattern elements it has to execute to succeed or fail. There is no
difference in time between matching a word (`brain`), matching a phrase of 4 words (`"life is a bowl"`),
and matching against a thousand members of a concept (`~animals`). Executing things like `!` and
`<` and `{` are only slightly faster because they don't need to do a dictionary lookup.

## Marking

The NLP pipeline takes an incoming sentence from the user and adjusts it in various ways. It will try to
fix spelling and capitalization. So if you really want to see what your patterns are trying to match, you should
use `:tokenize` to tell you what CS did to the input.

Additionally, CS will mark memberships of words in various concepts, only some of which are
shown below.

```
 My                     dog             eats            steak.
~pronoun_possessive     ~main_subject   ~main_verb      ~main_object
                        ~noun_singular  ~verb_present   ~noun_singular
                        ~pets           ~kindergarten   ~food
```

We have parts of speech, role in sentence, classifcations, age learned, etc.
You can match ANY of these in a pattern. Or use them like this:

```
u: (_~main_subject _0?~pets) Do you have a '_0?
```
which finds the main subject and determines if it is a pet animal.

Compared to patterns, marking is slow, consisting of half or more of the entire
cpu time. But it means that you can execute lots of patterns very rapidly.

## Matching algorithm

What actually happens during pattern matching is that the matcher has two things to look at.
It walks your pattern, element by element. Each element is processed in turn, without looking ahead to what
the next element is. It either succeeds or fails (or sometimes caches holding data). It also has the
sentence, which it walks, keeping track of where it is in the sentence (the position pointer).

It processes the pattern element using the current position and direction in the sentence (while normally it walks
forward it can also walk backward). So when it sees a `word`, it looks from the current position and direction to see if
it can find your word. If it can't, it fails. If it can, it sees if it meets current constraints on how far from where we are it can be.
For a simple `u: (I like worms)` when we process `I` we find it at the earliest moment in the sentence. The pattern is
as though it were `u: (< * I like worms)`. Having found `I`, it looks for `like`. If the input were
`I really like worms` then it would find `like` at word 3, which is a gap of 2 from the original `I`. The allowed gap is only 1 (words in sequence), so the match fails.
Had the pattern been `u: (I *~2 like worms)`, then the legal gap is 2 and the match would succeed.
The new position pointer in the sentence is 3 (`like`), moving forwards, and the next pattern element would hunt for `worms`.
It would find `worms` at position 4, which is a legal change, so the pattern matches.

While looking at the pattern is always moving forwards through it, the direction of movement through the sentence, which defaults
to forwards, can go backwards if `@_n-` is used. Thereafter it moves backwards until changed by `@_n+`.

 If the pattern element being processed specifies a wildcard, like `*~2`, the system stores the legal gap and moves on to the next
 token. It is not legal for that to also be a gap (else the system could not decide how to map the words to the two tokens).
 Similarly, if your pattern is `u: ( a *~2 {small} *~2 gap)` that would also not
 be legal (though not detected by the compiler at present), because if `{small}` is not matched,
 your pattern becomes `u: (a *~2 *~2 gap)`.

Whenever the first real element is found, the system remembers where.
If the pattern later fails, it is allowed to unhook that match and try to rematch it later in the sentence.
This is the cheap equivalent of exploring all possible match paths, which for efficiency the system
does not do. Therefore given an input of `I want snakes and I want cookies`
and a pattern of:

```
u: ( I want ~food)
```

the system finds `I` at word 1 and sets the position pointer and the start pointer to 1.
Then hunts for `want`, finding it at word 2 legally. And hunts for a `food` concept and finds it at position 7 and
that is an illegal gap. It is allowed to restart the pattern 1 word later than the initial match.
So is "unbinds" the starting `I`, and hunts for another, finding it at word 5. Finds `want` at word 6 and a ~food at word 7 and
therefore matches.

It CANNOT match input of `I want snakes and want cookies` because it finds word 1 (`I`) and word 2 (`want`)
fails `~food` because the gap is wrong. It DOES NOT change to retrying `want` which would actually be found at
word 5 and succeed with ~food for word 6. That is a full recovery mechanism like you would find in Prolog
but is too expense here. It merely fails instead, because it only uproots the starting match.

Some initial tokens can preclude moving the start of matching for another round.  Tokens like `<` and `@_3+` if first in the pattern
will mandate the pattern starts in a specific position in the sentence.

Whenever the system sees a wildcard, it can save the gap for 1 round to see what happens. If the next token is a
start token (paren, bracket, squiggle), this can be saved across that recursive call to the pattern matcher. Otherwise
it must be resolved on the next pattern element.

# Patterns == meaning

For all bots, there are two things they have to do. They "understand meaning" and they
carry out action. The action part is usually easy. The hard part is understanding meaning.
Since bots are not truly intelligent, understanding all meaning is not possible.
Instead, bots "hunt" for specific meanings they expect. They do this with patterns.

## Overly tight vs overly general

Since bots do not "understand" meaning, it is inevitable you will either
underspecify or overspecify their patterns. If you underspecify, the bot is subject
to false positives. It thinks something means something but it doesn't.

```
u: (want ~food) I want food too.
```

The above patterns looks for a meaning about wanting food. But it will accept
`I dont want meat` as matching. It is too general.

```
u: (I want meat) I want food too.
```

Correspondingly the above pattern is too specific and missing tons of reasonable
inputs.

Machine Learning is at an advantage in that it always memorize the exact
specific training input and may generalize from that. I say may, because it may not.
ML trained on `I have a '97 Audi` may completely not recognize `I have a 1997 Audi`.

So your task in ChatScript is to strike the appropriate balance between too general and too specific.
There will always be sentences the bot screws up as a consequence.

## Account for NLP pipeline in your patterns.

Patterns should be written in the correct case. Proper names should be in uppercase,
normal words in lower case. Do not try to handle capitalization for the start of a sentence.
Likewise when you define a concept, capitalize correctly. This allows CS to echo back the
capitalization specified in the concept set when memorizing a use of it, rather than
what the user typed. The compile will warn you at times if it thinks your capitalization is wrong.

```
concept: ~carmakes (ford dodge)
#! I have a ford.
u: (_~carmakes) You have a _0. ==>  You have a ford.
```

CS will spit back the wrong casing above. But if you change the contents
of the concept set to uppercase names, then it will spit back the correct
casing regardless of what the user typed.

The other thing to avoid is writing contractions in your patterns.

```
u: (what's the weather )
```

THIS IS AWFUL! First, because CS normally takes that input and converts it into
`what is the weather`, the pattern cannot match.  Worse, it adds `what's` into the
dictionary as a legal word (foolishly it trusts you). So when the NLP pipeline
sees the word `what's`, it leaves it alone as legal, instead of fixing it to the expanded
form `what is`. Your pattern will work, but this will break a lot of patterns that were correctly written. You won't believe
how many chat sentences begin with `What is...`

# Kinds of bots

We can distinuish 3 kinds of bots: FAQ, command and control, and conversational.
The patterns needed for these bots can vary a lot.

## Command and control bot

The command and control bot maps a user's request for an action to be taken into
actually performing that action. It is similar to an FAQ bot in not initiating a
conversation, except that often it needs `entities` (critical pieces of information) to carry
out the request. E.g., `What is the weather in Seattle` is a request for weather report (intent)
with the entity of location (Seattle). If the user merely said `what is the weather`, the bot
might reply with `where?`. But that's the limit of its initiative in the conversation. Once the request is
processed, it returns to idle just like the FAQ bot.

A good starting point for building patterns for these bots is to use `Fundamental Meaning`.
This is done by taking a sample input and discarding all the words you can that will still allow
an average high schooler to understand what is being requested.
It's a form of pidgin English. E.g.

```
Please tell me what the weather will be in Seattle tomorrow.
```

You can discard a lot of words. `Please` is merely politeness.
`tell me` reduces to just `tell` because the user is talking to the
bot so directing the bots output back to the user is not necessary, it is assumed.
`tell John` would be different. And if you boil out everything else you can
you get

```
tell weather seattle tomorrow
```
If a human pretends they are a weather bot, then that pidgin
English should be sufficent to be understood.

Once you have distilled the input to its fundamental meaning, you
can then broaden it with synonyms.

```
tell + describe explain discourse speak
weather + rain snow hot cold temperature icy
seattle + (probably has no synonyms)
tomorrow + in/after 1 day, specific date, day of week
```

And other than the imperative verb, you can probably shuffle the
order of the rest of the words.

```
tell tomorrow  seattle weather
```

These steps will help you generate patterns that detect a lot of
inputs quickly.

ChatScript has an advantage over ML in that it has a dictionary and pre-existing concepts. This is analogous to having
hundreds or thousands of training sentences available which don't have to be specified.

## FAQ bot

The FAQ bot maps a user's request for information to an answer. Usually the answer is
precanned text. The bot sits idle until the request; it answers the question; and then returns to idle.

An FAQ bot needs to determine the intent and usually doesn't care
about trying to figure out any entities. With a limited repetoire
of questions it can answer, it may be enough to merely detect relevant
keywords. For example, if the FAQ has a question about `what hours are you open`,
then a pattern that just listed keywords around that might be sufficient. E.g.,

```
u: ([ hour open available close "what time" lock unlock when ])
    We're open 9-5, 7 days a week.
```
The above covers a lot of ground without being very picky. Of course it might
match inappropriately as well. `Are you open to suggestions?`. But people talking
to an FAQ bot are generally looking for information, and not as likely to wander sideways.

## Conversational bot

A conversational bot is part FAQ bot and part initiator of
conversation. If the user asks it a personal question (or any other question), the bot is expected
to have an answer (even if it is silly or a quibble) and then the bot should turn around and
ask the user something and engage in conversation. If the user is silent for a while, the bot might
initiate a gambit to get the conversation flowing again.

Patterns of a conversational bot vary from an FAQ pattern to answer `how old is your mother` to
simple keywords to initiate a conversational topic.

```
topic: ~astronomy (sun moon astronomy astronomer star galaxy)
t: We love astronomy. Do you?
```

And off we go into a conversation.

# Multiple patterns for a single intent

Since there are multiple ways for a user to express an intent, it follows that
you will have to write multiple patterns.  One way to do this is in multiple rules.

```
u: TELLNAME (what be you name) My name is Rose.
u: WHATCALL (what be you call) ^reuse(TELLNAME)
```

In this simple example, I use ^reuse in the second rule. This
insures that if I change the answer in TELLNAME, it automatically changes for
all other rules that ^reuse it. Of course, in this example one could
combine the rules into:

```
u: TELLNAME (what be you [name call]) My name is Rose.
```

but that will never hold up to all patterns. For example:

```
u: (who be you) ^reuse(TELLNAME)
```

won't instantly combine. But in fact, I recommend combining them
as follows:

```
u: TELLNAME ([
                (what be you [name call])
                (who be you)
            ])
            My name is Rose.
```

This has the advantage of faster execution, smaller code, clear immediate
visualization of the patterns and response, least wait in stepping thru code in
the debugger.  And I recommend each pattern is on a separate line as shown above.
I even prefer the response on a separate line from the pattern. It means if you use
the debugger to "step in", you see it move to a new line. Clearer.

# Clarity in pattterns

A primary rule of thumb for patterns is that they really should be easy to read. For
an experienced CS programmer, it should be obvious what you are trying to do.
Patterns with nested values of `[]` and `()` and `{}` can be very hard to read.
Rather than doing that, it is better to split them into separate patterns.
The following is NOT clear.

```
u: ( you *~2 [ ([fine hot foxy sexy] look) (look [fine hot foxy sexy]) ] )

```

and would be clearer if split into two patterns nested inside a pattern:
```
u:  ([
    ( you *~2 [fine hot foxy sexy ] look )
    ( you *~2 look [fine hot foxy sexy ] )
    ])
```

So let's assume that generally you will write your patterns as collections of
patterns, and not as ^reuse() calls.

Additionally, you should avoid wrapping pattern sections onto new lines.

```
u:  ([
    ( you *~2 [fine hot
        foxy sexy ]
        look )
    ( you *~2 look [fine hot
        foxy sexy ] )
    ])
```
The above are harder to read/understand when run onto multiple lines.

Furthermore, for every pattern line, you should supply a sample input intended
for it. This makes it clearer to a human reader what you are trying to do AND
the CS `:verify` command to test your patterns to see if they work. A form of unit test.

```
#! You have a foxy look.
#! You look sexy.
u:   ([
    ( you *~2 [fine hot foxy sexy ] look )
    ( you *~2 look [fine hot foxy sexy ] )
    ])
```

#
# PRACTICE - Specific pattern elements
#

## `*` vs `*~n`

Most patterns will work when the user provides only a small amount of input.
When they type in paragraph-long sentences, using the unrestricted
wildcard `*` has a much higher false detection rate.

```
u: ( I * ~like * you) I like you too.
```

The above rule works fine on input like `I like you`, but is silly if
the input is `I like meat but I really loathe you`.  The problem
can be alleviated by using shorter range wildcards.  My favorites
are `*~2` and `*~3`.  `*~2` is good for skipping noun descriptors. It allows
for a determiner and an adjective or an adverb and an adjective.

```
u: (I * ~like *~2 ~noun)
```

And `*~3` is good for close control of word use:

```
u: (I *~3 ~like *~3 you)
```
You don't expect many words to arise between the subject `I`
and the verb `~like`. Nor between the verb and its object.

## `<< >>`  vs  `*~nb`

Just as there are problems with the unrestricted wildcard `*`,
the any-order construct `<< xxx yyy zzz >>` has similar issues.
Of course it does, because it acts like this `xxx < * yyy < * zzz`.
One solution is to use the restricted range bidirectional wildcard.
This is effective when searching around a particular word, looking for
something close before or close after. It avoids having to write two
patterns to do the job.

```
u: ( bank *~3b off-shore)   # safe
u: ( << bank off-shore >>)  # unsafe
```

Both can match `I have an off-shore bank account` as well as `my bank account is off-shore`.
But the unsafe one matches `We launched our kayak from the banks of the ocean and ended up far off-shore`.

## Concepts vs `[ xxx yyy]`

A concept is a list of words or phrases. So is `[ ]` in the middle of a pattern. Does it matter which you use?
Absolutely. On a single use basis, the concept takes more memory (irrelevant) but is
faster to match. A `[ ]`  walks the list, trying to match each word in order. A concept
matches all at once as a single operation. It doesn't matter if the concept consists of thousands of members,
it matches as fast as a single word. Furthermore, the concept will match the earliest occurence
of any word. `[]` will match in the order of words found in the list.
So if an earlier word is found late in the sentence, too bad.
Given input:  `I like your soul next to my shoe`, this pattern:
```
u: (I * [ my your])
```
will match to `my`, even though your is earlier in the sentence.
This works out if the pattern is:
```
u: (I *~2 [ my your])
```

because the limitation of *~2 will cause `my` to be found too late, so it will be
rejected and the next choice `your` will work.

But it's easy to become confused about what matches when you use `[]`.
So concepts are nominally better, clearer. And when used more than once, you only
have to edit the concept, not multiple rules. Odds are when you change `[]` in a rule,
you will forget to edit other places using the same words.

The problem with using concepts is a) you move the code non-local to the rule
so it is no longer obvious what the matching criteria is and 2) you have to create
names for your concepts. So while concepts are "better", they can be more tedious to use.

This behavior of `[]` is an efficiency measure.
The engine does not do a full search of all possible paths (like Prolog would do)
because that is too expensive and rarely pays off. It at best only looks ahead to the next
token in the pattern. This allows it to suspend a wildcard for a brief moment.

There are lots of consequences of looking for words in `[ ]`  in order. One is that you
should put your rarest, most significant words first. Another is that if you really want to
find the earliest occurence of the collection, make a concept out of them and search
for the concept instead. That is guaranteed to find the earliest occurence.

## `"xxx yyy"` vs `(xxx yyy)`

Both forms mean a contiguous sequence of words must match. But there are differences.
For the quoted form, it matches all words in a single element. So it is faster than all
elements within a (). At the top level, separate words are clearer than a quoted phrase.

```
u: (I like you)     # clearer
u: ("I like you")   # slightly less clear
```
Whenever you add a nesting level, patterns are harder to understand.
So at nested levels, quoted forms are easier to read than ones in ().

```
u: ([ "I like you" testing])    # clearer
u: ([ ( I like you) testing]    # less clear
```

Things that mitigate against using quoted phrase are the following.
1) You are limited to 5 words in a quoted phrase.
2) A quoted phrase can only match the literal user input or the entirely canonical form.

If the user input is "I loved toys", you can write a quoted phrase for
"I love toy" (all canonical) or "I loved toys" (exactly given).
You cannot write a pattern like this:

```
u: ("I love toy")       # matchable
u: ("I loved toys")     # matchable
u: ("I love toys")      # unmatchable
```

because the system only detects the original user input OR the
canonical form of the input. It does NOT detect a mixture of
original and canonical.

When you use individual words, you can select for each whether to be canonical or
not because you can put `'` in front of each.

When your phrase incorporates only canonical forms of its words,
it can match any form of all of those words. When your phrase has some
non-canonical words or it is quoted with `'`, it can only match what the user
actually typed (original input).

## Using `!`

Put all ! in front of your pattern, because you avoid wasted effort on the rest

```
#! do you like Vienna
#! do you hate Earth
u: (
    ! [travel movement]
    [
        (you like [Earth Vienna])
        (you hate [Earth Vienna])
    ])
```

## Using `<< >>`

Similarly, for << >> put the rare stuff first, so if match fails it ends pattern soonest.

# `{xxx yyy}` and `[ ]` or `<< >>`

{} means optionally find one of these words. It is handy when you are
trying to align your pattern to the position pointer in a sentence.
It is, however, completely meaningless if nested inside `[ ]` or `<< >>`.

```
u: ANYORDER(  << find {testing available} green)
u: ANYONE(  [ find {testing available} green ])
```

In ANYORDER, since finding words in `{}` is optional, it matters not whether they
are found or not. So why include them?

In ANYONE, you are already trying to find one of the words in `[ ]`. So saying
that you can use the words in `{}` adds nothing over merely writing

```
u: ANYONE(  [ find testing available green ])
```

## `<< >>`  vs  `< *`

Some patterns depend on finding multiple things in any order.
The usual pattern for this is `<< xxx yyy zzz >>`. But sometimes
CS imperfectly cannot handle certain patterns this way. For example
CS 8.0 does not allow !<< xxx yyy >>, even though it should. But there is
a workaround.  You can do `( xxx < * yyy < * zzz)` to achieve the same effect.
That is, find an element anywhere, go to start, find another element anywhere, go to start,
find another element anywhere.

##  `@_n+` and `@_n-` for local context

A lot of times when I find a basic match, I want to subject it to various constraints.
It is faster and clearer to find the basic essential keyword, and then look around it for context.
Using @_n+ and @_- allows you to jump to where the primary match occured, and then check the local
context either testing forwards or testing backwards.

```
u: (_baby) ^refine()
    a: (@_0+ [carriage formula]) # not about a baby, ignore
    a: (@_0- maybe) # title of a movie, ignore
    a: () # We have detected a real baby
```

## `^setindex()` vs `_10 = _0`

When you match something and check the local context around it using ^refine(),
a problem arises when you want to match another piece of data during refinement.
Each rule starts memorizing at _0, and you risk clobbering what you have already memorized.

```
u: (_~food) ^refine()
    a: (@_0- _~number)
```

If you are looking for a count before the matched food, you destroy your food
as you memorize the number. Two solutions exist. One is to copy the original _0 to
a different variable.

```
u: (_~food) _10 = _0 ^refine()
    a: (@_0- _~number)
```

The other is to alter the starting memorization index in your pattern.

```
u: (_~food) ^refine()
    a: (^setwildcardindex(_1) @_0- _~number)
```

Of the two choices, I generally prefer the `_10 = _0` approach, because I do it at the outermost
level rule, so dont have to repeat it on multiple rejoinder rules, it takes less typing, and I consider `_0` to
be a highly volatile variable that any function I call might destroy also.

## Adding markings - `^mark()`

The normal engine preparation on your sentence is to mark all words (and their canonical forms) with
what concepts they belong in.

You can supplement these marks any time you want. For example:

```
u: (_you) if (^original(_0) == u) {^mark(u _0)} ^retry(RULE)
```

The `texting` substitutions file will change `u` in input into `you`.
But suppose you want to detect the actual `u`. The above is such a way.
It matches the changed form, checks to see if the original was actually a `u`
and marks it in that location.  Thereafter the following rule will match.

```
u: (u) Found the letter u.
```

But marking does not make the marked value appear at that position in the sentence.

```
u: (_you) if (^original(_0) == u) {^mark(beer _0)} ^retry(RULE)
```

Had we done the above, we cannot expect this to grab the word `beer`.

```
u: (_beer) I found _0.
```

The pattern will match, but the output will be `I found you`.

You can mark using any word, fake word, concept, or fake concept. There is no
restriction.

## Unmarking words - `^unmark()`

Not only can you add markings but you can also remove them.
This is handy when trying to glean data that is context sensitive.

If we want to detect blood as a body part and it is in the concept `~bodypart`
we might use a rule like this:

```
u: (_~bodypart) Found _0.
```
But maybe not all occurences of `blood` are valid.
If the following rule occurs earlier, it prevents faulty gleaning.

```
u: (_blood pressure) ^unmark(~bodypart _0) ^retry(RULE)
```

There are actually 2 ways you can unmark. You can unmark a specific
word or concept, or you can unmark the entire word. Unmarking the entire word using
`*` means CS acts as
though it is not in the sentence at all. Given input `I have low blood pressure`,
the following is what happens:

```
u: (_blood pressure) ^unmark(* _0) ^retry(RULE)
u: (_*) '_0   -- this prints out `I have low pressure.`
```

Removing the entire word is perhaps a bit drastic, and you may
want to reinstate it later. The simplest way to do that is this
sequence:

```
u: (_*) _10 = _0   -- memorize the entire sentence location

u: (_blood pressure) ^unmark(* _0) ^retry(RULE)

u: () ^mark(* _10)  -- refresh all hidden words
```
## Fixing CS substitutions

^unmark and ^mark can be used to "correct" the behavior of standard
CS substitutions that you may not want but are unwilling to remove from CS release files.
Just detect the substitution result, check the original, and mark and unmark accordingly.
For example, "have a nice day" is substituted into `~emogoodbye`. So you can't normally see it
in a pattern as `(have a nice day)`. But ... you can find it anyway.

```
u:  (_~emogoodbye)
    $_tmp = ^original(_0)
    $_tmp1 = ^"have a nice day"
    if ($_tmp == $_tmp1) {}
```

And when CS interjection splitting is on (by default), you sometimes get words
split over sentence boundaries, where pattern matching can't see them.
You can compensate by setting variables in the earlier sentence.
So `no, thanks, I hate it` which is really the same as
'thanks, no, I hate it' or 'no, i hate it, thanks'  might look like this in code:

```
u: (~no) $$no = 1
u: ([~emothanks thanks]) $$thanks = 1
u: ($$no $$thanks hate it) Hate it if you want. I don't care.
```
## Gleaning sentence chunks

^Unmark() is also useful for gleaning data from paired chunks a sentence.
In English one might say `if xxx then yyy` or `begins xxxx ends xxx`.
You can mask off sentence fragments to perform special gleaning like this:

```
u: (_* from _* to _*) _10 = _0 _11 = _1  _12 = _2
    ^unmark(* _0)  # hide prior to from
    ^unmark(* _2)  # hide after to
    ^respond(~gleantopic) # go find data in remainder
    $data1 = $$tmpdata    # save what we learned

    ^mark(* _2)           # restore to data
    ^unmark(* _1)         # hide from data
    ^respond(~gleantopic) # go find data in remainder
    $data2 = $$tmpdata    # save what we learned

    ^mark(* _0)  # restore prior to from
    ^mark(* _1)  # restore from data
```
# Patterns in IF statements

While all rules can have patterns, you can even use pattern matching
inside outputmacros or rule output. You tell the `IF` statement you want
to use pattern syntax like this:

```
    if (PATTERN  $x<5 _~mainsubject)  {}
```

The reality is that outputmacros (functions) can act like rules and rules can act like
functions (but you have to pass arguments as globals).

## Placeholder rules

It is sometimes handy to have a common rule used for rejoinders from
multiple places, or to hold a common output. This can be done using a pattern
that cannot match. The most obvious is:

```
s: MYCOMMON (?) Here is common output.
    a: REJOINDER1(how) I dont know how
    a: REJOINDER2(when) I dont know when
...
u: (some pattern) ^reuse(MYCOMMON) # say what MYCOMMON says
u: (some other pattern) ^setrejoinder(OUTPUT MYCOMMON)
    I have this output, and my rejoinder will be handled by a common place.
```

#
# QUIZ - What's wrong with each of these patterns?
#

```
#! Where do i live
u: Q1( where do i live ?) On the moon?

#! I think bottle deposits are good for the earth.
u: Q2( [bottle can] (deposits are good)) I recycle.

#! Among the fruit that I like are apples.
u: Q3( << [bananas apples] are fruit  >> ) Fruit are tasty.

#! How much does the apple cost?
#! What is the price of a banana?
u: Q4([
        (how much *~5 cost)
        (what be *~5 price)
        !(price of liberty)
      ])
```

# ANSWERS
Q1 uses `I` in lower case. And the rule is overly specific.
And why use `?` in the pattern when you could change the rule to `?:`.

Q2 has useless interior `( )` so it is not the clearest.
If you thought `( deposits are good)` should have
been changed to `" deposits are good"`, you missed the
clearest answer. You don't need to use `" "` at the top level Of
a pattern.

Q3 detects `bananas are fruit` and `examples of fruit are bananas and pineapple` but not `the banana is a fruit`. To do that
you need to make banana singular in the pattern (along with `apple`) and change `are`
to the more canonical `be`. Of course limiting us to bananas and apples is ridiculous
given that CS has the in-built concept `~fruit`. You should type in your sample word like this:
`:prepare banana` and see what existing concepts cover it.

Q4 has a negative inside the `[ ]` alternatives so it will match
for almost all inputs. It should be moved first, before the `[`.
And probably you could combine the other elements into a single
pattern while generalizing further and still being clear.

```
u: Q4 (!(price of liberty)
       ["how much" "what be"] *~5 [cost price fee]
      )

# Summary

Fluency in pattern construction requires a limber mind,
able to imagine how to broaden a match while not accepting
wrong inputs. But it will enable your bots to
seem amazingly human!


text:
package com.val.ebtm.dto;

import android.accounts.Account;
import android.accounts.AccountManager;

import com.val.ebtm.InfoUsuario;

/**
 * Created by V on 19/03/16.
 *
 * Clase que crea objetos con al información de un usuario, al modo de factoría.
 * Muy necesaria esta clase para no arrastrar las dependecias necesarias con las clases
 * que gestionan la información del usuario y aislarla de la propia información del usuario
 * neta; para no arrastrar esas dependecias a la parte servidora en el proceso de serialización
 * deserialización
 *
 * @see InfoUsuario
 *
 * @author  Val
 * @version 1.1.3
 */
public class FactoryUsuario
{

    private static String[] componListaCorreos  (String lexpr)
    {
        String[] lista_correos = null;

        lista_correos = lexpr.split(",");

        return lista_correos;
    }

    private static String[] getCuentasMail (AccountManager accountManager)
    {
        String[] cuentas_mail = null;
        String str_aux = null;

        Account[] list = accountManager.getAccounts();

        str_aux = new String();
        for (Account cuenta : list)
        {

            if (cuenta.type.equals(InfoUsuario.ID_CUENTA_GOOGLE))
            {
                str_aux = str_aux + cuenta.name+",";
            }

        }

        cuentas_mail = componListaCorreos(str_aux.substring(0, str_aux.length() - 1));

        return cuentas_mail;
    }

    public static InfoUsuario crearInfoUsuario (AccountManager accountManager)
    {
        InfoUsuario infoUsuario = null;

            infoUsuario = new InfoUsuario();

            infoUsuario.setLista_emails(getCuentasMail (accountManager));

        return infoUsuario;

    }
}


text: <!DOCTYPE html>


text:
<?php

// Import the base ManagementHandler.
import('pages.management.ManagementHandler');

class SettingsHandler extends ManagementHandler {
	/**
	 * Constructor.
	 */
	function SettingsHandler() {
		parent::Handler();
		$this->addRoleAssignment(
			ROLE_ID_MANAGER,
			array(
				'index',
				'settings',
				'publication',
				'distribution',
			)
		);
	}

	//
	// Public handler methods
	//
	/**
	 * Display settings index page.
	 * @param $request PKPRequest
	 * @param $args array
	 */
	function index($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$templateMgr->display('management/settings/index.tpl');
	}

	/**
	 * Route to other settings operations.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function settings($args, $request) {
		$path = array_shift($args);
		switch($path) {
			case 'index':
				$this->index($args, $request);
				break;
			case 'journal':
				$this->journal($args, $request);
				break;
			case 'website':
				$this->website($args, $request);
				break;
			case 'publication':
				$this->publication($args, $request);
				break;
			case 'distribution':
				$this->distribution($args, $request);
				break;
			case 'access':
				$this->access($args, $request);
				break;
			default:
				assert(false);
		}
	}

	/**
	 * Display The Journal page.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function journal($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$templateMgr->display('management/settings/journal.tpl');
	}

	/**
	 * Display website page.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function website($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$journal = $request->getJournal();
		$templateMgr->assign('enableAnnouncements', $journal->getSetting('enableAnnouncements'));
		$templateMgr->display('management/settings/website.tpl');
	}

	/**
	 * Display publication process page.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function publication($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$templateMgr->display('management/settings/workflow.tpl');
	}

	/**
	 * Display distribution process page.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function distribution($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$templateMgr->display('management/settings/distribution.tpl');
	}

	/**
	 * Display Access and Security page.
	 * @param $args array
	 * @param $request PKPRequest
	 */
	function access($args, $request) {
		$templateMgr = TemplateManager::getManager($request);
		$this->setupTemplate($request);
		$templateMgr->display('management/settings/access.tpl');
	}
}

?>


text:
package com.splunk;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.Callable;

/**
 * Takes an InputStream containing a UTF-8 encoded XML document containing one or more
 * root 'results' elements, and wraps a 'doc' element around
 * all of them so normal XML parsers can handle the stream. Multiple root 'results'
 * elements occur when getting results from an export search.
 *
 * It works by finding the first instance of '<results' and inserting
 * the string '<doc>' before it, and then returning '</doc>' after the end of the stream
 * it is filtering.
 */
class InsertRootElementFilterInputStream extends FilterInputStream {
    private final ByteArrayInputStream suffix = new ByteArrayInputStream("</doc>".getBytes("UTF-8"));
    private boolean wrotePrefix;

    private byte[] oneByte = new byte[1];

    InsertRootElementFilterInputStream(InputStream in) throws IOException {
        // Wrap in with a pushback stream so we can write our modified version back
        // onto the beginning of it.
        super(new PushbackInputStream(in, 512));
        PushbackInputStream pin = (PushbackInputStream)this.in;

        // Read bytes until we reach '>', then push everything we read, followed by "<doc>",
        // back onto the stream. If we run out of input before we reach '>', then don't
        // modify the stream.
        ByteArrayOutputStream beforeResultsChars = new ByteArrayOutputStream();
        ByteArrayOutputStream atResultsChars = new ByteArrayOutputStream();

        int ch;
        while (true) {
            ch = this.in.read();
            if (ch == -1) {
                // Never found a results element to write after, don't touch the stream.
                wrotePrefix = false;
                pin.unread(beforeResultsChars.toByteArray());
                return;
            } else if (ch == (int)'<') {
                // Try extending
                atResultsChars.reset();
                int ech;
                boolean matched = true;
                for (byte b : "results".getBytes("UTF-8")) {
                    ech = this.in.read();
                    atResultsChars.write(ech);
                    if (ech != b) {
                        // Extension failed. Put the bytes back on and search again.
                        pin.unread(atResultsChars.toByteArray());
                        matched = false;
                        break;
                    }
                }

                if (matched) {
                    // If we reach here, the extension succeeded, so we insert <doc>, unread everything,
                    // and return.

                    // Unread the match.
                    pin.unread(atResultsChars.toByteArray());
                    // Unread the opening '<' that led to our extension
                    pin.unread(ch);
                    // Add a '<doc>' element to our read charactes and unread them.
                    beforeResultsChars.write("<doc>".getBytes("UTF-8"));
                    pin.unread(beforeResultsChars.toByteArray());
                    wrotePrefix = true;
                    return;
                } else {
                    // Extension didn't find a match. Put the byte on and continue.
                    beforeResultsChars.write(ch);
                }
            } else {
                // Not a character of interest. Put it on the buffer and continue.
                beforeResultsChars.write(ch);
            }
        }
    }

    @Override
    public int read(byte[] buffer, int offset, int length) throws IOException {
        int result = in.read(buffer, offset, length);
        if (result == -1 && wrotePrefix) {
            // No more bytes to read from in, and we have written '<doc>' earlier in the stream
            return suffix.read(buffer, offset, length);
        } else {
            // in still has data to return, so we return it.
            return result;
        }
    }

    @Override
    public int read() throws IOException {
        // Override to dispatch to the other read method. The third overload of read in FilterInputStream
        // already dispatches to read(byte[], int, int).
        if (read(oneByte, 0, 1) == -1) {
            return -1;
        } else {
            return oneByte[0];
        }
    }
}


text:
namespace Xyun.Xylona.Common.Extensions
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics.Contracts;
    using System.Runtime.CompilerServices;

    /// <summary>
    ///     Extensions to System.Type.
    /// </summary>
    public static class TypeExtensions
    {
        #region Public Methods and Operators

        /// <summary>
        /// Gets the assembly qualified name of a type with only the full name and assembly name.
        ///     No version or public key token is included.
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <returns>
        /// The short assembly qualified name.
        /// </returns>
        public static string GetShortAssemblyQualifiedName(this Type type)
        {
            Contract.Requires(type != null);

            return string.Format("{0}, {1}", type.FullName, type.Assembly.GetName().Name);
        }

        /// <summary>
        /// Gets the type without nullability.
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <returns>
        /// If nullable, the underlying type; otherwise the type itself.
        /// </returns>
        public static Type GetTypeWithoutNullability(this Type type)
        {
            Contract.Requires(type != null);

            return type.IsNullableType()
                       ? new NullableConverter(type).UnderlyingType
                       : type;
        }

        /// <summary>
        /// Determines whether the specified type is an anonymous type.
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified type is an anonymous type; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsAnonymousType(this Type type)
        {
            Contract.Requires(type != null);

            return type.IsDefined(typeof(CompilerGeneratedAttribute), false) && type.FullName.Contains("AnonymousType");
        }

        /// <summary>
        /// Determines whether the specified type is null-able.
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <returns>
        /// <c>true</c> if the specified type is null-able; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsNullableType(this Type type)
        {
            Contract.Requires(type != null);

            return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
        }

        /// <summary>
        /// Determines whether the type to check is a subclass of the specified raw generic type.
        ///     From: http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-generic-class
        /// </summary>
        /// <param name="toCheck">
        /// The type to check.
        /// </param>
        /// <param name="generic">
        /// The generic type.
        /// </param>
        /// <returns>
        /// <c>true</c> if the type is a subclass; otherwise, <c>flase</c>.
        /// </returns>
        public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
        {
            while (toCheck != null && toCheck != typeof(object))
            {
                Type cur = toCheck.IsGenericType
                               ? toCheck.GetGenericTypeDefinition()
                               : toCheck;
                if (generic == cur)
                {
                    return true;
                }

                toCheck = toCheck.BaseType;
            }

            return false;
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.facebook.scrumptious"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>
    <application android:label="@string/app_name"
                 android:icon="@drawable/icon"
                 android:name=".ScrumptiousApplication">
        <activity android:name="MainActivity"
                  android:label="@string/app_name"
                  android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name="PickerActivity"
                  android:label="@string/app_name" />
        <activity android:name="com.facebook.LoginActivity"
                  android:theme="@android:style/Theme.Translucent.NoTitleBar"
                  android:label="@string/app_name" />
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
    </application>
</manifest>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using static CodeJam.DebugCode;

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;

using JetBrains.Annotations;

using static CodeJam.PlatformDependent;

namespace CodeJam.IO
{
	/// IO assertions class.
	[PublicAPI]
	public static class DebugIoCode
	{
		/// Asserts that specified path is either absolute or relative not rooted path.
		/// <param name="path">The path.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void IsWellFormedPath(
			[NotNull] string path,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNullNorEmpty(path, argName);
			if (!PathHelpers.IsWellFormedPath(path))
				throw IoCodeExceptions.ArgumentNotWellFormedPath(argName, path);
		}

		/// Asserts that specified path is well-formed full path.
		/// <param name="path">The path.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void IsWellFormedAbsolutePath(
			[NotNull] string path,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNullNorEmpty(path, argName);
			if (!PathHelpers.IsWellFormedAbsolutePath(path))
				throw IoCodeExceptions.ArgumentNotWellFormedAbsolutePath(argName, path);
		}

		/// Asserts that specified path is well-formed full path.
		/// <param name="path">The path.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void IsWellFormedRelativePath(
			[NotNull] string path,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNullNorEmpty(path, argName);
			if (!PathHelpers.IsWellFormedRelativePath(path))
				throw IoCodeExceptions.ArgumentRootedOrNotRelativePath(argName, path);
		}

		/// Asserts that specified path is well formed and ends with directory or volume separator chars.
		/// <param name="path">The path.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void IsWellFormedContainerPath(
			[NotNull] string path,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNullNorEmpty(path, argName);
			if (!PathHelpers.IsWellFormedContainerPath(path))
				throw IoCodeExceptions.ArgumentNotVolumeOrDirectoryPath(argName, path);
		}

		/// Asserts that specified path is well-formed simple name.
		/// <param name="path">The path.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void IsWellFormedSimpleName(
			[NotNull] string path,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNullNorEmpty(path, argName);
			if (!PathHelpers.IsWellFormedSimpleName(path))
				throw IoCodeExceptions.ArgumentNotSimpleName(argName, path);
		}

		#region IO path
		/// Asserts that specified file does exist.
		/// <param name="filePath">Path to the file.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void FileExists(
			[NotNull] string filePath,
			[NotNull, InvokerParameterName] string argName)
		{
			Code.NotNull(filePath, argName);
			if (!File.Exists(filePath))
				throw Directory.Exists(filePath)
					? IoCodeExceptions.ArgumentDirectoryExistsFileExpected(argName, filePath)
					: IoCodeExceptions.ArgumentFileNotFound(argName, filePath);
		}

		/// Asserts that specified directory does exist.
		/// <param name="directoryPath">Path to the directory.</param>
		/// <param name="argName">Name of the argument.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void DirectoryExists(
			[NotNull] string directoryPath,
			[NotNull, InvokerParameterName] string argName)
		{
			if (!Directory.Exists(directoryPath))
				throw File.Exists(directoryPath)
					? IoCodeExceptions.ArgumentFileExistsDirectoryExpected(argName, directoryPath)
					: IoCodeExceptions.ArgumentDirectoryNotFound(argName, directoryPath);
		}

		/// Asserts that specified path is not a path to existent file or a directory.
		/// <param name="path">The path.</param>
		[Conditional(DebugCondition), DebuggerHidden, MethodImpl(AggressiveInlining)]
		[AssertionMethod]
		public static void PathIsFree([NotNull] string path)
		{
			if (Directory.Exists(path))
				throw IoCodeExceptions.DirectoryExists(path);
			if (File.Exists(path))
				throw IoCodeExceptions.FileExists(path);
		}
		#endregion
	}
}


text:
from ecsminion import ECSMinion
import os

def get_client(token):
    """ Returns a configured ECS client using current session information. """
    client = ECSMinion(
        token=token,
        token_endpoint=get_token_endpoint(),
        ecs_endpoint=get_ecs_endpoint())
    return client

def authenticate(username, password):
    client = ECSMinion(
        username=username,
        password=password,
        token_endpoint=get_token_endpoint(),
        ecs_endpoint=get_ecs_endpoint(),
        cache_token=False)
    return client.get_token()

def get_token_endpoint():
    return os.getenv("ECS_BASE_URL", "").rstrip("/")+"/login"

def get_ecs_endpoint():
    return os.getenv("ECS_BASE_URL", "")


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="question_1">*Challenge Question 1:</string>
    <string name="answer_1">*Challenge Answer 1:</string>
    <string name="question_2">*Challenge Question 2:</string>
    <string name="answer_2">*Challenge Answer 2:</string>
    <string name="select_one">Select one</string>
    <string name="note">Note:</string>
    <string name="note_text">To reset a forgotten password, your answer must match exactly what you input into the text box above. The answer will be case and punctuation sensitive. Both the question and the answer will be accessible to your Security Administrator</string>
</resources>


text:
//===- SwapByteOrder.h - Generic and optimized byte swaps -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file declares generic and optimized functions to swap the byte order of
// an integral type.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_SUPPORT_SWAPBYTEORDER_H
#define LLVM_SUPPORT_SWAPBYTEORDER_H

#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
#include <cstddef>
#include <type_traits>
#if defined(_MSC_VER) && !defined(_DEBUG)
#include <stdlib.h>
#endif

#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__)
#include <endian.h>
#elif defined(_AIX)
#include <sys/machine.h>
#elif defined(__sun)
/* Solaris provides _BIG_ENDIAN/_LITTLE_ENDIAN selector in sys/types.h */
#include <sys/types.h>
#define BIG_ENDIAN 4321
#define LITTLE_ENDIAN 1234
#if defined(_BIG_ENDIAN)
#define BYTE_ORDER BIG_ENDIAN
#else
#define BYTE_ORDER LITTLE_ENDIAN
#endif
#else
#if !defined(BYTE_ORDER) && !defined(_WIN32)
#include <machine/endian.h>
#endif
#endif

namespace llvm {
namespace sys {

#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
constexpr bool IsBigEndianHost = true;
#else
constexpr bool IsBigEndianHost = false;
#endif

static const bool IsLittleEndianHost = !IsBigEndianHost;

/// SwapByteOrder_16 - This function returns a byte-swapped representation of
/// the 16-bit argument.
inline uint16_t SwapByteOrder_16(uint16_t value) {
#if defined(_MSC_VER) && !defined(_DEBUG)
  // The DLL version of the runtime lacks these functions (bug!?), but in a
  // release build they're replaced with BSWAP instructions anyway.
  return _byteswap_ushort(value);
#else
  uint16_t Hi = value << 8;
  uint16_t Lo = value >> 8;
  return Hi | Lo;
#endif
}

/// This function returns a byte-swapped representation of the 32-bit argument.
inline uint32_t SwapByteOrder_32(uint32_t value) {
#if defined(__llvm__) || (defined(__GNUC__) && !defined(__ICC))
  return __builtin_bswap32(value);
#elif defined(_MSC_VER) && !defined(_DEBUG)
  return _byteswap_ulong(value);
#else
  uint32_t Byte0 = value & 0x000000FF;
  uint32_t Byte1 = value & 0x0000FF00;
  uint32_t Byte2 = value & 0x00FF0000;
  uint32_t Byte3 = value & 0xFF000000;
  return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
#endif
}

/// This function returns a byte-swapped representation of the 64-bit argument.
inline uint64_t SwapByteOrder_64(uint64_t value) {
#if defined(__llvm__) || (defined(__GNUC__) && !defined(__ICC))
  return __builtin_bswap64(value);
#elif defined(_MSC_VER) && !defined(_DEBUG)
  return _byteswap_uint64(value);
#else
  uint64_t Hi = SwapByteOrder_32(uint32_t(value));
  uint32_t Lo = SwapByteOrder_32(uint32_t(value >> 32));
  return (Hi << 32) | Lo;
#endif
}

inline unsigned char  getSwappedBytes(unsigned char C) { return C; }
inline   signed char  getSwappedBytes(signed char C) { return C; }
inline          char  getSwappedBytes(char C) { return C; }

inline unsigned short getSwappedBytes(unsigned short C) { return SwapByteOrder_16(C); }
inline   signed short getSwappedBytes(  signed short C) { return SwapByteOrder_16(C); }

inline unsigned int   getSwappedBytes(unsigned int   C) { return SwapByteOrder_32(C); }
inline   signed int   getSwappedBytes(  signed int   C) { return SwapByteOrder_32(C); }

#if __LONG_MAX__ == __INT_MAX__
inline unsigned long  getSwappedBytes(unsigned long  C) { return SwapByteOrder_32(C); }
inline   signed long  getSwappedBytes(  signed long  C) { return SwapByteOrder_32(C); }
#elif __LONG_MAX__ == __LONG_LONG_MAX__
inline unsigned long  getSwappedBytes(unsigned long  C) { return SwapByteOrder_64(C); }
inline   signed long  getSwappedBytes(  signed long  C) { return SwapByteOrder_64(C); }
#else
#error "Unknown long size!"
#endif

inline unsigned long long getSwappedBytes(unsigned long long C) {
  return SwapByteOrder_64(C);
}
inline signed long long getSwappedBytes(signed long long C) {
  return SwapByteOrder_64(C);
}

inline float getSwappedBytes(float C) {
  union {
    uint32_t i;
    float f;
  } in, out;
  in.f = C;
  out.i = SwapByteOrder_32(in.i);
  return out.f;
}

inline double getSwappedBytes(double C) {
  union {
    uint64_t i;
    double d;
  } in, out;
  in.d = C;
  out.i = SwapByteOrder_64(in.i);
  return out.d;
}

template <typename T>
inline typename std::enable_if<std::is_enum<T>::value, T>::type
getSwappedBytes(T C) {
  return static_cast<T>(
      getSwappedBytes(static_cast<typename std::underlying_type<T>::type>(C)));
}

template<typename T>
inline void swapByteOrder(T &Value) {
  Value = getSwappedBytes(Value);
}

} // end namespace sys
} // end namespace llvm

#endif


text:
@interface NoticeViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIButton *button;

@end

@implementation NoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self setupMessage:_message btnMsg:_btnMsg btnColor:_btnColor icon:_iconImage];
}

- (void)setupMessage:(NSString *)message btnMsg:(NSString *)btnMsg btnColor:(UIColor *)btnColor icon:(UIImage *)iconImg
{
    self.messageLabel.text = message;
    [self.button setTitle:btnMsg forState:UIControlStateNormal];
    self.button.backgroundColor = btnColor;
    self.iconImageView.image = iconImg;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)cancelPress:(id)sender
{
    [[NoticeModal sharedInstance] hide];
}

- (IBAction)buttonPress:(id)sender
{
    [[NoticeModal sharedInstance] hide];
    [_delegate noticeViewControllerButtonPressWithTag:_tag];
}

@end


text:
<title>OGRE: Ogre::BspNode::Brush Struct Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre::BspNode::Brush

Ogre::BspNode::Brush Struct Reference

#include <OgreBspNode.h>

List of all members.

Public Attributes

list< Plane >::type 	planes

SceneQuery::WorldFragment 	fragment

Detailed Description

Definition at line 147 of file OgreBspNode.h.

Member Data Documentation

          SceneQuery::WorldFragment Ogre::BspNode::Brush::fragment

Definition at line 150 of file OgreBspNode.h.

          list<Plane>::type Ogre::BspNode::Brush::planes

Definition at line 149 of file OgreBspNode.h.

The documentation for this struct was generated from the following file:

OgreBspNode.h

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 08:22:36 2012


text:
/* eslint-disable no-param-reassign */

import {
  SerializedError,
  createAsyncThunk,
  createSlice,
} from '@reduxjs/toolkit';

import * as api from '../constants/api';
import AdjustedTrace from '../models/AdjustedTrace';
import Span from '../models/Span';
import TraceSummary from '../models/TraceSummary';
import { ensureV2TraceData } from '../util/trace';

const {
  treeCorrectedForClockSkew,
  traceSummary: buildTraceSummary,
  traceSummaries: buildTraceSummaries,
  detailedTraceSummary: buildDetailedTraceSummary,
} = require('../zipkin');

export const searchTraces = createAsyncThunk(
  'traces/search',
  async (params: { [key: string]: string }, thunkApi) => {
    const ps = new URLSearchParams(params);

    // We need to import RootState in order to give the type to getState.
    // Importing RootState will result in a cyclic import.
    // So use any type to avoid this.
    const { search, traces }: TracesState = (thunkApi.getState() as any).traces;
    // If the query is the same as the previous query, it will not fetch again.
    if (search.prevQuery === ps.toString()) {
      return {
        traces,
        traceSummaries: search.traceSummaries,
        query: ps.toString(),
      };
    }

    const resp = await fetch(`${api.TRACES}?${ps.toString()}`);
    if (!resp.ok) {
      throw Error(resp.statusText);
    }
    const rawTraces: Span[][] = await resp.json();

    const newTraces = rawTraces.reduce(
      (acc, rawTrace) => {
        const [{ traceId }] = rawTrace;
        const skewCorrectedTrace = treeCorrectedForClockSkew(rawTrace);
        acc[traceId] = {
          rawTrace,
          skewCorrectedTrace,
        };
        return acc;
      },
      {} as {
        [key: string]: {
          rawTrace: Span[];
          skewCorrectedTrace: any;
        };
      },
    );

    const traceSummaries: TraceSummary[] = buildTraceSummaries(
      ps.get('serviceName'),
      Object.keys(newTraces).map((traceId) =>
        buildTraceSummary(newTraces[traceId].skewCorrectedTrace),
      ),
    );

    return {
      traces: newTraces,
      traceSummaries,
      query: ps.toString(),
    };
  },
);

export const loadTrace = createAsyncThunk(
  'traces/load',
  async (traceId: string, thunkApi) => {
    // We need to import RootState in order to give the type to getState.
    // Importing RootState will result in a cyclic import.
    // So use any type to avoid this.
    const { traces }: TracesState = (thunkApi.getState() as any).traces;

    if (traces[traceId]) {
      const { rawTrace, skewCorrectedTrace } = traces[traceId];
      let { adjustedTrace } = traces[traceId];
      if (adjustedTrace) {
        // this trace has already been calculated by buildDetailedTraceSummary
        return traces[traceId];
      }
      if (skewCorrectedTrace) {
        adjustedTrace = buildDetailedTraceSummary(skewCorrectedTrace);
        return {
          rawTrace,
          skewCorrectedTrace,
          adjustedTrace,
        };
      }
    }

    const resp = await fetch(`${api.TRACE}/${traceId}`);
    if (!resp.ok) {
      throw Error(resp.statusText);
    }
    const rawTrace: Span[] = await resp.json();
    const skewCorrectedTrace = treeCorrectedForClockSkew(rawTrace);
    const adjustedTrace: AdjustedTrace = buildDetailedTraceSummary(
      skewCorrectedTrace,
    );
    return {
      rawTrace,
      skewCorrectedTrace,
      adjustedTrace,
    };
  },
);

const readFileAsync = (blob: Blob) => {
  return new Promise<any>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.onerror = () => {
      reject(reader.error);
    };
    reader.readAsText(blob);
  });
};

export const loadJsonTrace = createAsyncThunk(
  'traces/loadJson',
  async (blob: Blob) => {
    const rawTraceStr = await readFileAsync(blob);
    const rawTrace: Span[] = JSON.parse(rawTraceStr);
    ensureV2TraceData(rawTrace);
    const [{ traceId }] = rawTrace;
    const skewCorrectedTrace = treeCorrectedForClockSkew(rawTrace);
    const adjustedTrace: AdjustedTrace = buildDetailedTraceSummary(
      skewCorrectedTrace,
    );
    return {
      traceId,
      trace: {
        rawTrace,
        skewCorrectedTrace,
        adjustedTrace,
      },
    };
  },
);

export interface TracesState {
  traces: {
    [traceId: string]: {
      // When fetching a specific trace, these isLoading and error states are used.
      // They are not used in the search.
      isLoading?: boolean;
      error?: SerializedError;

      rawTrace?: Span[];
      adjustedTrace?: AdjustedTrace;
      // This is a trace data with only the clock-skew modified.
      // It is the intermediate data used to optimize the conversion process of the trace.
      skewCorrectedTrace?: any;
    };
  };
  search: {
    // When searching, isLoading and error states are used.
    // They are not used when fetching a specific trace.
    isLoading: boolean;
    error?: SerializedError;
    // Save the previous query to avoid doing the same query unnecessarily.
    prevQuery?: string;
    traceSummaries: TraceSummary[];
  };
}

const initialState: TracesState = {
  traces: {},
  search: {
    isLoading: false,
    error: undefined,
    prevQuery: undefined,
    traceSummaries: [],
  },
};

const tracesSlice = createSlice({
  name: 'traces',
  initialState,
  reducers: {
    clearSearch: (state) => {
      state.search.isLoading = false;
      state.search.error = undefined;
      state.search.prevQuery = undefined;
      state.search.traceSummaries = [];
    },
  },
  extraReducers: (builder) => {
    builder.addCase(searchTraces.pending, (state) => {
      const newSearchState = {
        ...state.search,
        isLoading: true,
        error: undefined,
      };
      state.search = newSearchState;
    });

    builder.addCase(searchTraces.fulfilled, (state, action) => {
      const { traces } = action.payload;
      const newTraces = { ...state.traces };
      Object.keys(traces).forEach((traceId) => {
        newTraces[traceId] = traces[traceId];
      });
      const newSearchState = {
        isLoading: false,
        error: undefined,
        prevQuery: action.payload.query,
        traceSummaries: action.payload.traceSummaries,
      };
      state.search = newSearchState;
      state.traces = newTraces;
    });

    builder.addCase(searchTraces.rejected, (state, action) => {
      const newSearchState = {
        ...state.search,
        isLoading: false,
        error: action.error,
      };
      state.search = newSearchState;
    });

    builder.addCase(loadTrace.pending, (state, action) => {
      const traceId = action.meta.arg;
      const newTraces = { ...state.traces };
      if (!newTraces[traceId]) {
        newTraces[traceId] = {};
      }
      newTraces[traceId].isLoading = true;
      newTraces[traceId].error = undefined;
      state.traces = newTraces;
    });

    builder.addCase(loadTrace.fulfilled, (state, action) => {
      const traceId = action.meta.arg;
      const newTraces = { ...state.traces };
      newTraces[traceId] = { ...action.payload };
      newTraces[traceId].isLoading = false;
      newTraces[traceId].error = undefined;
      state.traces = newTraces;
    });

    builder.addCase(loadTrace.rejected, (state, action) => {
      const traceId = action.meta.arg;
      const newTraces = { ...state.traces };
      newTraces[traceId].isLoading = false;
      newTraces[traceId].error = action.error;
      state.traces = newTraces;
    });

    // It's easier to handle isLoading and error statuses on the component side,
    // so don't change them here.
    builder.addCase(loadJsonTrace.fulfilled, (state, action) => {
      const { traceId, trace } = action.payload;
      const newTraces = { ...state.traces };
      newTraces[traceId] = trace;
      state.traces = newTraces;
    });
  },
});

export default tracesSlice;

export const { clearSearch } = tracesSlice.actions;


text:
"""
FILE: sample_copy_model_to_async.py

DESCRIPTION:
    This sample demonstrates how to copy a custom model from a source Form Recognizer resource
    to a target Form Recognizer resource.

    The model used in this sample can be created in the sample_build_model_async.py using the
    training files in https://aka.ms/azsdk/formrecognizer/sampletrainingfiles

USAGE:
    python sample_copy_model_to_async.py

    Set the environment variables with your own values before running the sample:
    1) AZURE_FORM_RECOGNIZER_SOURCE_ENDPOINT - the endpoint to your source Form Recognizer resource.
    2) AZURE_FORM_RECOGNIZER_SOURCE_KEY - your source Form Recognizer API key
    3) AZURE_FORM_RECOGNIZER_TARGET_ENDPOINT - the endpoint to your target Form Recognizer resource.
    4) AZURE_FORM_RECOGNIZER_TARGET_KEY - your target Form Recognizer API key
    5) AZURE_SOURCE_MODEL_ID - the model ID from the source resource to be copied over to the target resource.
        - OR -
       CONTAINER_SAS_URL - The shared access signature (SAS) Url of your Azure Blob Storage container with your training files.
       A model will be built and used to run the sample.
"""

import os
import asyncio

async def sample_copy_model_to_async(custom_model_id):
    # [START begin_copy_document_model_to_async]
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient

    source_endpoint = os.environ["AZURE_FORM_RECOGNIZER_SOURCE_ENDPOINT"]
    source_key = os.environ["AZURE_FORM_RECOGNIZER_SOURCE_KEY"]
    target_endpoint = os.environ["AZURE_FORM_RECOGNIZER_TARGET_ENDPOINT"]
    target_key = os.environ["AZURE_FORM_RECOGNIZER_TARGET_KEY"]
    source_model_id = os.getenv("AZURE_SOURCE_MODEL_ID", custom_model_id)

    target_client = DocumentModelAdministrationClient(endpoint=target_endpoint, credential=AzureKeyCredential(target_key))
    async with target_client:
        target = await target_client.get_copy_authorization(
            description="model copied from other resource"
        )

    source_client = DocumentModelAdministrationClient(endpoint=source_endpoint, credential=AzureKeyCredential(source_key))
    async with source_client:
        poller = await source_client.begin_copy_document_model_to(
            model_id=source_model_id,
            target=target  # output from target client's call to get_copy_authorization()
        )
        copied_over_model = await poller.result()

    print("Model ID: {}".format(copied_over_model.model_id))
    print("Description: {}".format(copied_over_model.description))
    print("Model created on: {}\n".format(copied_over_model.created_on))
    print("Doc types the model can recognize:")
    for name, doc_type in copied_over_model.doc_types.items():
        print("\nDoc Type: '{}' which has the following fields:".format(name))
        for field_name, field in doc_type.field_schema.items():
            print("Field: '{}' has type '{}' and confidence score {}".format(
                field_name, field["type"], doc_type.field_confidence[field_name]
            ))
    # [END begin_copy_document_model_to_async]

async def main():
    model_id = None
    if os.getenv("CONTAINER_SAS_URL"):

        from azure.core.credentials import AzureKeyCredential
        from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient
        from azure.ai.formrecognizer import ModelBuildMode

        endpoint = os.getenv("AZURE_FORM_RECOGNIZER_SOURCE_ENDPOINT")
        key = os.getenv("AZURE_FORM_RECOGNIZER_SOURCE_KEY")

        if not endpoint or not key:
            raise ValueError("Please provide endpoint and API key to run the samples.")

        document_model_admin_client = DocumentModelAdministrationClient(
            endpoint=endpoint, credential=AzureKeyCredential(key)
        )
        async with document_model_admin_client:
            model = await (await document_model_admin_client.begin_build_document_model(ModelBuildMode.TEMPLATE, blob_container_url=os.getenv("CONTAINER_SAS_URL"))).result()
            model_id = model.model_id

    await sample_copy_model_to_async(model_id)

if __name__ == '__main__':
    asyncio.run(main())


text:
ToDo for Espérance
=========================

- More assertion methods
- More tests
- Spec for expansion


text:
using System.Reflection;

[assembly: AssemblyTitle("CslaContrib.MEF in .NET 4")]
[assembly: AssemblyDescription("Extends CSLA .NET framework with MEF support for Repository and ObjectFactory data access.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("CslaContrib.MEF.NET4")]
[assembly: AssemblyCulture("")]


text:
LightGBM FAQ
=======================

### Catalog

- [Critical](FAQ.md#Critical)
- [LightGBM](FAQ.md#LightGBM)
- [R-package](FAQ.md#R-package)
- [Python-package](FAQ.md#python-package)

---

### Critical

You encountered a critical issue when using LightGBM (crash, prediction error, non sense outputs...). Who should you contact?

If your issue is not critical, just post an issue [Microsoft/LightGBM repository](https://github.com/Microsoft/LightGBM/issues).

If it is a critical issue, identify first what error you have:

* Do you think it is reproducible on CLI (command line interface), R, and/or Python?
* Is it specific to a wrapper? (R or Python?)
* Is it specific to the compiler? (gcc versions? MinGW versions?)
* Is it specific to your Operating System? (Windows? Linux?)
* Are you able to reproduce this issue with a simple case?
* Are you able to (not) reproduce this issue after removing all optimization flags and compiling LightGBM in debug mode?

Depending on the answers, while opening your issue, feel free to ping (just mention them with the arobase (@) symbol) appropriately so we can attempt to solve your problem faster:

* [@guolinke](https://github.com/guolinke) (C++ code / R package / Python package)
* [@Laurae2](https://github.com/Laurae2) (R package)
* [@wxchan](https://github.com/wxchan) (Python package)
* [@huanzhang12](https://github.com/huanzhang12) (GPU support)

Remember this is a free/open community support. We may not be available 24/7 to provide support.

---

### LightGBM

- **Question 1**: Where do I find more details about LightGBM parameters?

- **Solution 1**: Look at [Parameters.md](Parameters.md) and [Laurae++/Parameters](https://sites.google.com/view/lauraepp/parameters) website

---

- **Question 2**: On datasets with million of features, training do not start (or starts after a very long time).

- **Solution 2**: Use a smaller value for `bin_construct_sample_cnt` and a larger value for `min_data`.

---

- **Question 3**: When running LightGBM on a large dataset, my computer runs out of RAM.

- **Solution 3**: Multiple solutions: set `histogram_pool_size` parameter to the MB you want to use for LightGBM (histogram_pool_size + dataset size = approximately RAM used), lower `num_leaves` or lower `max_bin` (see [issue #562](https://github.com/Microsoft/LightGBM/issues/562)).

---

- **Question 4**: I am using Windows. Should I use Visual Studio or MinGW for compiling LightGBM?

- **Solution 4**: It is recommended to [use Visual Studio](https://github.com/Microsoft/LightGBM/issues/542) as its performance is higher for LightGBM.

---

- **Question 5**: When using LightGBM GPU, I cannot reproduce results over several runs.

- **Solution 5**: It is a normal issue, there is nothing we/you can do about, you may try to use `gpu_use_dp = true` for reproducibility (see [issue #560](https://github.com/Microsoft/LightGBM/pull/560#issuecomment-304561654)). You may also use CPU version.

---

- **Question 6**: Bagging is not reproducible when changing the number of threads.

- **Solution 6**: As LightGBM bagging is running multithreaded, its output is dependent on the number of threads used. There is [no workaround currently](https://github.com/Microsoft/LightGBM/issues/632).

---

- **Question 7**: I tried to use Random Forest mode, and LightGBM crashes!

- **Solution 7**: It is by design. You must use `bagging_fraction` and `feature_fraction` different from 1, along with a `bagging_freq`. See [this thread](https://github.com/Microsoft/LightGBM/issues/691) as an example.

---

- **Question 8**: CPU are not kept busy (like 10% CPU usage only) in Windows when using LightGBM on very large datasets with many core systems.

- **Solution 8**: Please use [use Visual Studio](https://github.com/Microsoft/LightGBM/issues/740) as it may be 10x faster than MinGW especially for very large trees.

---

### R-package

- **Question 1**: Any training command using LightGBM does not work after an error occurred during the training of a previous LightGBM model.

- **Solution 1**: Run `lgb.unloader(wipe = TRUE)` in the R console, and recreate the LightGBM datasets (this will wipe all LightGBM-related variables). Due to the pointers, choosing to not wipe variables will not fix the error. This is a known issue: [Microsoft/LightGBM#698](https://github.com/Microsoft/LightGBM/issues/698).

- **Question 2**: I used `setinfo`, tried to print my `lgb.Dataset`, and now the R console froze!

- **Solution 2**: Avoid printing the `lgb.Dataset` after using `setinfo`. This is a known bug: [Microsoft/LightGBM#539](https://github.com/Microsoft/LightGBM/issues/539).

---

### Python-package

- **Question 1**: I see error messages like this when install from github using `python setup.py install`.

    ```
    error: Error: setup script specifies an absolute path:

    /Users/Microsoft/LightGBM/python-package/lightgbm/../../lib_lightgbm.so

    setup() arguments must *always* be /-separated paths relative to the
    setup.py directory, *never* absolute paths.
    ```

- **Solution 1**: this error should be solved in latest version. If you still meet this error, try to remove lightgbm.egg-info folder in your python-package and reinstall, or check [this thread on stackoverflow](http://stackoverflow.com/questions/18085571/pip-install-error-setup-script-specifies-an-absolute-path).

---

- **Question 2**: I see error messages like `Cannot get/set label/weight/init_score/group/num_data/num_feature before construct dataset`, but I already construct dataset by some code like `train = lightgbm.Dataset(X_train, y_train)`, or error messages like `Cannot set predictor/reference/categorical feature after freed raw data, set free_raw_data=False when construct Dataset to avoid this.`.

- **Solution 2**: Because LightGBM constructs bin mappers to build trees, and train and valid Datasets within one Booster share the same bin mappers, categorical features and feature names etc., the Dataset objects are constructed when construct a Booster. And if you set free_raw_data=True (default), the raw data (with python data struct) will be freed. So, if you want to:

  + get label(or weight/init_score/group) before construct dataset, it's same as get `self.label`
  + set label(or weight/init_score/group) before construct dataset, it's same as `self.label=some_label_array`
  + get num_data(or num_feature) before construct dataset, you can get data with `self.data`, then if your data is `numpy.ndarray`, use some code like `self.data.shape`
  + set predictor(or reference/categorical feature) after construct dataset, you should set free_raw_data=False or init a Dataset object with the same raw data