text:
title: xtlang types
---

{:.note-box}

It's not really possible to explain Extempore's types without a detour into some
[memory stuff]({% link _docs/reference/memory-management.md %}),
so we'll cover some of that as well. For more info on how xtlang fits into the
big picture of Extempore, see [philosophy]({% link
_docs/overview/philosophy.md %}).

xtlang code is statically typed---the types are determined at compile time, and
the compiler checks that the types of the arguments to a function match the type
signature of that closure. If they don't match, you get a compile error, and a
(hopefully) helpful message about where things are going wrong and what needs to
be fixed.

The base types will be familiar to those who are used to working with C,
although there are a couple of slight differences. Just like C, the types are
all low level in the sense that they represent a particular bit pattern in
memory---there's no boxing and unboxing going on.

In xtlang, type annotations (a type definition following a colon in the source
code) are used to tell the compiler about the types of variables. The compiler
will infer incomplete type information (such as the size of int and float
literals), but will never silently coerce the types. If there's a problem, the
compiler will complain and you have to fix it, either with an explicit coercion
or by changing the structure of the code.

The examples here use a lot of these type annotations. This is for
clarity---some of these aren't strictly necessary (*as I'll show later*) because
the type inferencing compiler will figure out the types of variables in many
cases.

## Primitive types {#primitive-types}

### Integers {#integers}

![image](/images/int-examples.png)

Extempore supports signed integers of various different sizes:

-   `i1` (boolean)
-   `i8` (char)
-   `i32`
-   `i64` (default)

A couple of gotchas:

-   the default integer size is `i64`, so int literals in the code will be
    interpreted as `i64`, *unless* the function signature suggests otherwise
    e.g. if the signature is `[double,i32]*`, then a (single) int literal
    argument will be read as an `i32`.
-   there is no `char` type, only `i8`. In xtlang, strings are null-terminated
    char arrays/pointers with the signature `i8*`.

### Floats {#floats}

![image](/images/float-examples.png)

There are two sizes of floating point number:

-   `float` (32 bit)
-   `double` (64 bit, default)

Float literals in xtlang code (e.g. `4.2`) are interpreted as `double` unless
the type signatures suggest otherwise (as is the case with `i64` int literals).

### Pointer types {#pointer-types}

![image](/images/pointer-examples.png)

xtlang supports
[pointers](http://en.wikipedia.org/wiki/Pointer_(computer_programming)) to any
type, in fact some types (such as closures) are almost always handled by
reference (that is, through pointers). Pointers in xtlang are indicated by the
usual `*` syntax.

Examples:

-   `double*`: a pointer to a double
-   `i64**`: a pointer to a pointer to a 64-bit integer

Pointers represent *memory addresses*, and the use of pointers in xtlang is one
of the key differences between xtlang and Scheme (and indeed between xtlang and
any high-level language). C programmers will be (intimately) familiar with the
concept of pointers, and xtlang's pointers are the same (you can `printf` them
with `%p`) For others, though, a more in-depth explanation of the concept of
pointers can be found here <pointer-doc>. If
you've never encountered pointers before then I suggest you check it out before
continuing.

The way to allocate (and store a pointer to) memory is through a call to one of
xtlang's 'alloc' functions. Extempore has 3 different alloc functions: `salloc`,
`halloc` and `zalloc`. They all allocate a chunk of memory and return a pointer
type, but they differ in *where* that memory is allocated from. In order of how
'long-lived' the memory will be: `salloc` allocates memory on the stack
(shortest-lived), `zalloc` allocates memory from the current zone, and `halloc`
allocates memory from the heap (longest-lived). Finally, `alloc` is an alias for
`zalloc`.

More detail about the Extempore's memory architecture (and the difference
between `salloc`, `halloc` and `zalloc`) can be found in memory. For now, though, we'll just use `zalloc`, which
allocates memory from the current zone, which for these examples will work fine.

~~~~ xtlang
(bind-func ptr_test
  (lambda ()
    (let ((a:double* (zalloc)))
      (printf "address = %p\n" a))))

(ptr_test) ;; prints "address = 0x1163bc030"
~~~~

In this example, the function closure `ptr_test` takes no arguments, binds a
pointer to a `double` (`a`) in the `let`, and then prints the memory address
that `a` points to.

Pointers aren't very interesting, though, if you can't read and write to the
values they point to. That's where the xtlang functions `pref`, `pset!` and
`pref-ptr` come in.

Unlike in C, `*` is not a dereference *operator*, it's just the syntax for the
specifying pointer types. Instead, there's a function `pref` for *dereferencing*
a pointer (getting the value the pointer 'points' to). `pref` takes two
arguments: the pointer, and an (integer) offset. So if `a` is a pointer to a
chunk of 10 `double` in memory (such as returned by `zalloc`, for instance),
then `(pref a 2)` in xtlang is the value of the third (`pref` uses 0-based
indexing) of those `double` (equivalent to `a[2]` in C).

To *set* the value associated with a pointer, there's `pset!`. Like `pref`,
`pset!` takes a pointer as the first argument, and offset as the second
argument, but it also takes an additional third argument---the value to set into
that memory location. This must be of the appropriate type: so if the pointer is
to a double, then the value passed to `pset!` must also be a double.

~~~~ xtlang
(bind-func ptr_test2
  (lambda ()
    (let ((a:double* (zalloc))) ; allocate some memory for a double, bind
                                        ; the pointer to the symbol a
      (pset! a 0 2.4)          ; set the value at index 0 (of a) to 2.4
      (pref a 0))))            ; read the value at index 0 of a

(ptr_test2) ;; returns 2.400000
~~~~

In this example the closure `ptr_test2` takes no arguments, allocates some
memory, sets a value into that memory location, then reads it back out. Notice
that for both `pref` and `pset!` the index argument was zero---this means that
we were storing and reading the value directly into the pointer (memory
location) bound to `a`.

This is important (and useful) because the call to `zalloc` can (optionally)
take an integer argument. So, if we know we're going to store 4 doubles, we can
do this:

~~~~ xtlang
(bind-func ptr_test3
  (lambda ()
    (let ((a:double* (zalloc 4)))
      (pfill! a 1.2 3.4 4.2 1.1) ; fill the pointer a with values
      (pref a 2))))              ; read the value at index 2 of a

(ptr_test3) ;; returns 4.200000
~~~~

`(zalloc 4)` will allocate enough memory for `4` doubles (4 doubles with 64
bytes/double means 256 bytes all up).

There's one new function in this example: `pfill!`, which is helpful for filling
multiple values into a byte array. Using `pfill!` is exactly the same as calling
`pset!` 4 times with an index of 0, 1, 2, and 3, but it's a bit more concise.

Finally, one more useful way to fill values into a chunk of memory is using a
loop.

~~~~ xtlang
(bind-func ptr_test4
  (lambda ()
    (let ((a:double* (zalloc 10))
          (i:i64 0))
      (dotimes (i 10)
        (pset! a i (i64tod i)))
     (pref a 6))))

(ptr_test4) ;; returns 6.000000
~~~~

There's one more useful function for working with pointers: `pref-ptr`. Where
`(pref a 3)` returns the *value* of the 4th element of the chunk of memory
pointed to by `a`, `(pref-ptr a 3)` returns a *pointer* to that value. This also
implies that `(pref (pref-ptr a n))` is the same as `(pref (pref-ptr a 0) n)`
for any integer *n*.

One final note for C programmers: there is no `void*` in xtlang, use an `i8*`
instead.

### C Strings {#c-strings}

There's also no `char` type, just `i8`. So string literals in xtlang are
pointers to null terminated arrays (just like in C) but instead have type `i8*`.

The usual `pref` and friends for pointers (described above) are therefore your
friends if you want to slice and dice strings around. A few familiar string
functions have made their way over from the C standard library as well.

String literals in xtlang are bound globally (allocated on the heap). So you can
safely set and store pointers to them without worrying about then disappearing
on you.

~~~~ xtlang
(bind-func string_literals
  (lambda ()
    (let ((str "Vive le tour!"))
      (printf "%s\n" str))))

(string_literals) ;; prints "Vive le tour!"
~~~~

xtlang does have a nicer `String` type, defined in `libs/base/base.xtm` (TODO
more docs coming soon!).

## Aggregate types {#aggregate-types}

There are three base aggregate types in xtlang: tuples, arrays and vectors. In
each case, these names mean pretty much the same thing they do in other
languages.

Normally the best way to work with these types is by reference (that is, through
pointers). Allocating memory for a tuples, array or vector is done through a
call to one of the *alloc* functions, as in the [example above](#pointer-types)
with pointers to primitive types.

### Tuples {#tuples}

An n-tuple is a fixed-length structure with n elements. *Different* tuples can
have different lengths (different values of *n*), but a particular tuple always
has the same fixed length.

The elements of a tuple need not be of the same type, tuples are heterogeneous.
Each element can be any type that the xtlang compiler recognises, including
another tuple---turtles all the way down!

The syntax for declaring and identifying tuples in xtlang is the use of angle
brackets (`<>`). Tuples in xtlang are analogous to C structs, except without
named members. This is a bit of a pain at the moment, but named structs are high
on the Extempore to-do list at the moment and will be added in a future release.

Examples:

![image](/images/tuple-examples.png)

-   `<double,i32>*` is a pointer to a 2-tuple: the first element is a `double`
    and the second element is an `i32`
-   `<i64*,i64,float**>*` is a pointer to a 3 tuple: the first element is a
    pointer to an `i64`, the second is an `i64`, and the third is a *pointer to
    a pointer to* a `float`
-   `<double,<i64*>*>*` is a pointer to a 2-tuple, with a `double` as the first
    element and a pointer to a 1-tuple as the second

Like `pref` for pointers, getting an element from a tuple involves a function
called `tref`. So, to get element number `i` from a tuple pointer `t`, use
`(tref t i)`. If `tref` doesn't have an *i* th element, the compiler will
complain (as it should). The first argument to `tref` should be a pointer to a
tuple rather than the tuple itself, and this holds for the array and vector
equivalents as well. In fact, you'll almost never work with aggregate data types
directly, instead getting pointers to them via calls to the memory allocation
functions. The exception to this rule is if you're binding to a C library and
you need to pass structs around by value (rather than by reference).

Similarly, `tset!` is used to set a value into a tuple. Again, the compiler will
check that the value being set is of the right type, and will throw a compile
error if there's a problem.

There's `tfill!` for filling values into tuples. Again, it's up to you to make
sure that you pass values of the correct types into the different slots. But if
you don't, at least you get a compile time error rather than weird behaviour at
runtime.

And finally, if you want a *reference to* (rather than the value of) an element
in the tuple, use `tref-ptr` instead of `tref`.

All of these tuple ref/ref-ptr/set!/fill! functions have the same syntax as the
pointer (i.e. `pref`) versions. There are also equivalent functions for arrays
(with an `a` prefix) and vectors (`v` prefix). This consistency makes it easier
to remember how to work with and access the different types. And because xtlang
is strongly typed, even if you do get confused and try to `tset!` an array type
the compiler will catch the error for you.

### Vectors {#vectors}

The final aggregate data type in xtlang is the vector type. Vectors are like
arrays in that they are fixed length homogeneous type buffers, but operations
vector types will use the CPUs SIMD registers and instructions (if your hardware
has them). This can potentially give significant speedups for certain types of
processing. The downside is that there's a bit less flexibility (certain
operations can't be performed on vector elements, especially conditionals and
branching) and it does make your code a bit less portable, at least from a
performance standpoint.

The syntax for vector types looks just like the array syntax, except the pipes
(`|`) are replaced with slashes (`/`), presumably because they're going
*faster*.

Examples:

![image](/images/vector-examples.png)

-   `/4,float/*`: a pointer to a vector of four floats
-   `/256,i32/*`: a pointer to a vector of 256 ints

In general, if you're working with vector types you'll know what you're doing,
and pick algorithms and word sizes which make good use of the vector hardware on
your computer. Unless you know that the particular code you're working on is the
performance bottleneck in your system, it's probably best to start out with
arrays, and to change to vectors later on if it becomes necessary.

### Arrays {#arrays}

An array in xtlang is a fixed length array of elements of a single type (like a
static C array). The array type signature specifies the length of the array, the
type of the array elements, and is closed off with the pipe (`|`) character.

Examples:

![image](/images/array-examples.png)

-   `|4,double|*`: a pointer to an array of 4 `double`
-   `|10000000,i32|*`: a pointer to an array of one million `i32`
-   `|3,<double,|15,float*|*>*|**`: a pointer to a pointer to an array of
    pointers to 2-tuples, the second element of which is a pointer to an array
    of 15 float pointers. Whew!

It's probably clear at this point that the combinations of types allow for heaps
of flexibility, but can get pretty confusing if you use lots of nesting of
aggregate types within one another. If you *do* need to use complex types, then
you can define your own types and the compiler can do some of the bookkeeping
for you (more on this below).

Setting and getting values from arrays is done with (you guessed it!) `aref`,
`aset!`, and `afill!`. And if you want to get a pointer into an array (that is,
not to the first element but to some element further into the array), use
`aref-ptr`.

### Closures {#closures}

The final important type in xtlang is the
[closure](http://en.wikipedia.org/wiki/Closure_(computer_science)) type, and
understanding closures is crucial to understanding how xtlang works as a whole.

xtlang's closures are lexical closures (like in Scheme), which means that they
are the combination of a function and its referencing environment. This
basically means that any variables referred to in the scope of the function
(even if they weren't passed in as arguments) is captured along with the
function, and the whole 'world' (as far as each little function is concerned)
can be passed around in a nice little package.

In xtlang, closure types are indicated by square brackets (`[]`), with the first
element inside the brackets being the return type, and any other elements
representing the type signature of the function.

Examples:

![image](/images/closure-examples.png)

-   `[i64]*`: a pointer to a closure which takes no arguments and returns a
    single `i64`
-   `[i64,double,double]*`: a pointer to a closure which takes two `double`
    arguments and returns a single `i64`
-   `[<i64,i32>*,|8,double|*]*`: a pointer to a closure which takes as a n
    argument a pointer to an 8-element `double` array and returns a pointer to a
    2-tuple
-   `[[i64,i32]*,[double]*]*`: a pointer to a closure which takes a pointer to a
    closure (which returns a `double`) as an argument and returns a pointer to
    another closure

The last example in particular is interesting: closures can take closures as
arguments, and closures can return other closures. This comes in handy in lots
of situations, as lots of the files in Extempore's `examples` directory show.

The way to make closures in xtlang is with a [lambda
form](http://en.wikipedia.org/wiki/Lambda_(programming)), just like in Scheme. A
`lambda` returns an *anonymous* function closure---that's what it means for
xtlang to have 'first class' functions/closures. Closures don't have to have
names, they can be elements of lists and arrays, they can be passed to and
returned from other closures, they can do anything any other type can do.

Sometimes, though, we want to give a closure a name, and that's where
`bind-func` comes in. `bind-func` is the (only) way in xtlang to assign a global
name to a closure. Here's an example of creating a simple (named) xtlang closure
using `bind-func`

~~~~ xtlang
(bind-func xt_add
  (lambda (a:i64 b:i64)
    (+ a b)))

(xt_add 3 6) ;; returns 9
~~~~

`xt_add` takes two int arguments (see how the `i64` type annotations are
provided in the initial argument list) and returns their sum. It's also worth
noting that when we compile `xt_add` the log view prints the closure's type
signature:

~~~~ sourceCode
Compiled xt_add >>> [i64,i64,i64]*
~~~~

`bind-func` is xtlang's equivalent to Scheme's `define`, although with the
limitation that `define` in Scheme can bind any scheme object (not just a
closure) to a symbol, while in xtlang `bind-func` has to return a closure (via a
`lambda` form). Although if you need to compile & bind an xtlang entity of some
other type, there are other functions like `bind-val` and `bind-type` which will
do the necessary for you.

As another example, if you want to return a closure from the function it's
exactly like you would do it in Scheme:

~~~~ xtlang
(bind-func make_xt_adder
  (lambda (a:i64)
    (lambda (b:i64)
      (+ a b))))

;; type of make_xt_adder is [[i64,i64]*,i64]*

(bind-func test_xt_adder
  (lambda (c:i64)
    ((make_xt_adder 3) c)))

;; type of test_xt_adder is [i64,i64]*

(test_xt_adder 5) ;; returns 8
~~~~

This example is a bit more complicated: the first closure (`make_xt_adder`)
takes one argument `a` and returns a closure (notice the *second* `lambda` form
inside the toplevel one) which takes one argument `b` and adds it to `a`. Note
that `a` is 'baked in' to this closure---it's not passed in directly, but it's
referenced from the outside scope. We say that this closure (which has no
name---it's anonymous) 'closes over' `a`.

Then, in the second function (`test_xt_adder`) we call `make_xt_adder` with an
argument of 3, so this will return a function closure with one argument which
adds 3 to that argument. This (returned) function then gets passed the argument
`c` (in this example, it's called with an argument of 5), so the end result is
3 + 5 = 8. Whew! That's confusing to read in words, but if you stare at the code
long enough you'll reach enlightenment. Or something.

## Named types {#named-types}

To round it off, you can also define your own types. This is convenient: it's
easier to type `my_type` than `[double*,<i64,i32>,float,float]`, especially if
it's a type that you'll be using a lot in your code.

There are two ways to define a custom type: `bind-type` and `bind-alias`.

Examples:

~~~~ xtlang
(bind-alias my_type_1 <i64,double>)
(bind-type my_type_2 <float,[i64,i32]*,|3,double|*>)
~~~~

`bind-type` tells the xtlang compiler about your new type, which provides some
safety benefits: the more the compiler knows about the types in your code, the
more errors it can throw at compile time and save messy runtime errors and
tricky debugging.

As an example, let's make a 2D 'point' type, and a function for calculating the
euclidean distance between two points.

~~~~ xtlang
(bind-type point <double,double>)

(bind-func euclid_distance
  (lambda (a:point* b:point*)
    (sqrt (+ (pow (- (tref a 0)
                     (tref b 0))
                  2.0)
             (pow (- (tref a 1)
                     (tref b 1))
                  2.0)))))
~~~~

To test this out, we can check the diagonal length of the unit square, which
should be `sqrt(2) = 1.41`

~~~~ xtlang
(bind-func test_unit_square_diagonal
  (lambda ()
    (let ((bot_left:point* (alloc))
          (top_right:point* (alloc)))
      (tfill! bot_left 0.0 0.0)
      (tfill! top_right 1.0 1.0)
      (printf "The length of the unit square's diagonal is %f\n"
              (euclid_distance bot_left
                               top_right)))))

(test_unit_square_diagonal)

;; prints "The length of the unit square's diagonal is 1.414214"
~~~~

Now, what happens if we change this testing example to make `top_right` and
`bot_left` just plain tuples of type `<double,double>` instead of being our new
`point` type.

~~~~ xtlang
(bind-func test_unit_square_diagonal_2
  (lambda ()
    (let ((bot_left:<double,double>* (alloc))
          (top_right:<double,double>* (alloc)))
      (tfill! bot_left 0.0 0.0)
      (tfill! top_right 1.0 1.0)
      (printf "The length of the unit square's diagonal is %f\n"
              (euclid_distance bot_left
                               top_right)))))
~~~~

Now, instead of compiling nicely, we get the compiler error:

~~~~ sourceCode
Compiler Error: Type Error: (euclid_distance bot_left top_right)
 function argument does not match. Expected "%point*" but got "{double,double}*"
~~~~

Even though `point` *is* just a `<double,double>` (check the `bind-type`
definition above), the compiler won't let us compile the function. This is a
good thing most of the time, because it makes us be more explicit about what we
actually mean in our code, and saves us from the silly mistakes that can happen
when we're not clear about what we want.

There are lots of possibilities for the use of custom types, and there's no
problem with binding as many as you need to make your code and intention
clearer. Binding custom types could, for instance, allow for the construction of
a 'data structures' library like the C++ STL containers library or the Java
collections framework.

`bind-alias`, in contrast to `bind-type`, is just a simple alias for the given
type. The xtlang compiler, when it sees `my_alias` in the code, will simply
substitute in the appropriate type (in this case `<i64,|3,double|*>*`) before it
generates the LLVM IR to send to the compiler. `bind-alias` doesn't tell the
compiler as much about the code as `bind-type` does, which can lead to
execution-time problems which would otherwise have been caught by the compiler.
So you should almost always use `bind-type` over `bind-alias`.

## Generics {#generics}

With [generics](https://en.wikipedia.org/wiki/Generic_programming), xtlang
provides a way to specify types and closures without concrete types. This allows
you to write re-usable code and algorithms for various different types and
functions, and allows the compiler to figure out the specific "concrete" types
later. This is all still compiled code, and it's all still very efficient (no
boxing/unboxing going on). It's just nice to not have to write a separate `sort`
function for lists of `i32` and `i64` for example.

{:.note-box}

This section is under construction, but for now have a look in
`libs/core/adt.xtm` for Extempore's [abstract data
type](https://en.wikipedia.org/wiki/Abstract_data_type) (ADT) functionality.


text:
using System.Xml.Serialization;

namespace Digiseller.Client.Core.Models.Response.CategoryGoods
{
    [XmlRoot(ElementName = "pages")]
    public class Pages
    {
        [XmlElement(ElementName = "num")]
        public int PageNumber { get; set; }
        [XmlElement(ElementName = "rows")]
        public int RowsCount { get; set; }
        [XmlAttribute(AttributeName = "cnt")]
        public int PagesCount { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.dataformat.protobuf;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.dataformat.protobuf.generated.AddressBookProtos;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class ProtobufConverterTest {

    @Test
    public void testIfCorrectlyParseMap() {
        final Map<String, Object> phoneNumber = new HashMap<>();
        phoneNumber.put("number", "011122233");
        phoneNumber.put("type", "MOBILE");

        final Map<String, Object> phoneNumber2 = new HashMap<>();
        phoneNumber2.put("number", "5542454");
        phoneNumber2.put("type", 2);

        final Map<String, Object> address = new HashMap<>();
        address.put("street", "awesome street");
        address.put("street_number", 12);
        address.put("is_valid", false);

        final Map<String, Object> input = new HashMap<>();

        input.put("name", "Martin");
        input.put("id", 1234);
        input.put("phone", Arrays.asList(phoneNumber, phoneNumber2));
        input.put("email", "some@some.com");
        input.put("nicknames", Arrays.asList("awesome1", "awesome2"));
        input.put("address", address);

        final AddressBookProtos.Person message
                = (AddressBookProtos.Person) ProtobufConverter.toProto(input, AddressBookProtos.Person.getDefaultInstance());

        // assert primitives types and strings
        assertEquals("Martin", message.getName());
        assertEquals(1234, message.getId());
        assertEquals("some@some.com", message.getEmail());

        // assert nested message
        assertEquals("awesome street", message.getAddress().getStreet());
        assertEquals(12, message.getAddress().getStreetNumber());
        assertFalse(message.getAddress().getIsValid());

        // assert repeated messages
        assertEquals("011122233", message.getPhone(0).getNumber());
        assertEquals("MOBILE", message.getPhone(0).getType().name());
        assertEquals("5542454", message.getPhone(1).getNumber());
        assertEquals("WORK", message.getPhone(1).getType().name());

        assertEquals("awesome1", message.getNicknames(0));
        assertEquals("awesome2", message.getNicknames(1));
    }

    @Test
    public void testIfThrowsErrorInCaseNestedMessageNotMap() {
        final Map<String, Object> input = new HashMap<>();

        input.put("name", "Martin");
        input.put("id", 1234);
        input.put("address", "wrong address");

        assertThrows(IllegalArgumentException.class,
                () -> ProtobufConverter.toProto(input, AddressBookProtos.Person.getDefaultInstance()));
    }

    @Test
    public void testIfThrowsErrorInCaseRepeatedFieldIsNotList() {
        final Map<String, Object> input = new HashMap<>();

        input.put("name", "Martin");
        input.put("id", 1234);
        input.put("nicknames", "wrong nickname");

        assertThrows(IllegalArgumentException.class,
                () -> ProtobufConverter.toProto(input, AddressBookProtos.Person.getDefaultInstance()));
    }

    @Test
    public void testIfItCorrectlyConvertMessageToMap() {
        final Map<String, Object> phoneNumber = new HashMap<>();
        phoneNumber.put("number", "011122233");
        phoneNumber.put("type", "MOBILE");

        final Map<String, Object> phoneNumber2 = new HashMap<>();
        phoneNumber2.put("number", "5542454");
        phoneNumber2.put("type", "WORK");

        final Map<String, Object> address = new HashMap<>();
        address.put("street", "awesome street");
        address.put("street_number", 12);
        address.put("is_valid", false);

        final Map<String, Object> input = new HashMap<>();

        input.put("name", "Martin");
        input.put("id", 1234);
        input.put("phone", Arrays.asList(phoneNumber, phoneNumber2));
        input.put("email", "some@some.com");
        input.put("nicknames", Arrays.asList("awesome1", "awesome2"));
        input.put("address", address);

        final AddressBookProtos.Person message
                = (AddressBookProtos.Person) ProtobufConverter.toProto(input, AddressBookProtos.Person.getDefaultInstance());

        final Map<String, Object> resultedMessageMap = ProtobufConverter.toMap(message);

        assertEquals(input, resultedMessageMap);

    }

}


text:
<!-- estilo base das paginas -->
<link rel="stylesheet" href="../css/estilo.css">
<link rel="stylesheet" href="../css/editarPerfil.css">
<link rel="stylesheet" href="../css/cadastro.css">
<link rel="stylesheet" href="../css/estudio.css">
<link rel="stylesheet" href="../css/perfil.css">
<!-- estilo responsivo das paginas -->
<link rel="stylesheet" href="../estatico/css/responsivo/estilo.css">
<link rel="stylesheet" href="../estatico/css/responsivo/editarPerfil.css">
<link rel="stylesheet" href="../estatico/css/responsivo/cadastro.css">
<link rel="stylesheet" href="../estatico/css/responsivo/estudio.css">
<link rel="stylesheet" href="../estatico/css/responsivo/perfil.css">
<!-- javascript -->
<script src="../estatico/js/jquery.js"></script>
<script src="../estatico/js/valida.js"></script>


text:
import $ from 'jquery';

function createTaskChooser(id) {
  const chooserElement = $('#' + id + '-chooser');
  const taskName = chooserElement.find('[data-chooser-title]');
  const input = $('#' + id);
  const editAction = chooserElement.find('.edit-link');

  $('.action-choose', chooserElement).on('click', () => {
    // eslint-disable-next-line no-undef
    ModalWorkflow({
      url: chooserElement.data('chooserUrl'),
      // eslint-disable-next-line no-undef
      onload: TASK_CHOOSER_MODAL_ONLOAD_HANDLERS,
      responses: {
        taskChosen(data) {
          input.val(data.id);
          taskName.text(data.name);
          chooserElement.removeClass('blank');
          editAction.attr('href', data.edit_url);
        },
      },
    });
  });
}
window.createTaskChooser = createTaskChooser;


text:
. "$ZPLUG_HOME/init.zsh"

zplug "themes/robbyrussell", from:oh-my-zsh, as:theme
zplug "zsh-users/zsh-syntax-highlighting", defer:3
zplug "zsh-users/zsh-autosuggestions"
zplug "zsh-users/zsh-completions"

if ! zplug check --verbose; then
  printf "Install? [y/N]: "
  if read -q; then
    echo
    zplug install
  fi
fi

zplug load


text:
using BYUtv.CalendarWidget.Models;
using BYUtv.CalendarWidget.Services;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;

namespace BYUtv.CalendarWidget.Drivers
{
    /*
     * Driver
     * Drivers are similar to MVC controllers, but they act at the level of a content part instead of at the level of the full request.
     * They typically prepare shapes for rendering and handle post-backs from admin editors.
     */
    public class CalendarWidgetDriver : ContentPartDriver<CalendarWidgetPart>
    {
        private readonly IOrchardServices _orchardServices;
        private readonly ICalendarService _calendarService; // a custom service that we use to retrieve data and create objects

        public Localizer T { get; set; } // handles string localization

        /*
         * IDependency
         * Services should implement IDependency, if they do:
         * the application framework will discover all dependencies and will take care of instantiating and injecting instances as needed.
         */
        public CalendarWidgetDriver(IOrchardServices orchardServices, ICalendarService calendarService)
        {
            _orchardServices = orchardServices;
            _calendarService = calendarService;

            T = NullLocalizer.Instance;
        }

        // GET - Render Shape
        protected override DriverResult Display(CalendarWidgetPart part, string displayType, dynamic shapeHelper)
        {
            /*
             * Shape
             * A very malleable object (dynamic data model) that contains all the information required in order to dispaly its data.
             * All data needs to be transformed into a shape (a blob of data) before it can be rendered in a template.
             * The template is aware of all the shapes (tree of shapes) that it needs to render.
             * Modules can create or modify (new or existing) shapes.
             * http://docs.orchardproject.net/Documentation/Accessing-and-rendering-shapes
             */
            return ContentShape("Parts_CalendarWidget", // Shape type names the shape and binds it to a template, by convention, all part shapes begin with Parts_ followed by the name of the part.  Orchard uses this convention to lookup the view to use (Views/Parts/CalendarWidget.cshtml).  Do not forget to add a node in Placement.info for this shape.
                () => shapeHelper.Parts_CalendarWidget( // function expression, the Dispaly method uses a pattern of shapeHelper.Parts_Name
                    CalendarEvents: _calendarService.GetCalendarEvents(part) // objects that will be available in the view as part of the dynamic model (in CalendarWidget.cshtml @Model.CalendarItems)
                )
            );
        }

        // GET - Render Shape
        protected override DriverResult Editor(CalendarWidgetPart part, dynamic shapeHelper)
        {
            // Creating a model, or view-model, in this way will allow us to pass additional data to the view that is not contained in CalendarWidgetPart.
            var model = new CalendarWidgetPartQueries
            {
                Queries = _calendarService.GetCalendarQueries(),
                QueryId = part.QueryId
            };

            return ContentShape("Parts_CalendarWidget_Edit",
                () => shapeHelper.EditorTemplate( // shapeHelper.EditorTemplate is a special shape that has a TemplateName and Model property, use this shape when creating admin editor views.
                    TemplateName: "Parts/CalendarWidget", // searches within Views/EditorTemplates for the template named CalendarWidget.cshtml (Views/EditorTemplates/Parts/CalendarWidget.cshtml).
                    Model: model, // type CalendarWidgetPartQueries
                    Prefix: Prefix
                )
            );
        }

        // POST - Post-back from admin editor
        protected override DriverResult Editor(CalendarWidgetPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, new string[] { "Queries" }); // populates part with the data returned by the view.  The view recieved Queries via the view-model CalendarWidgetPartQueries but we are only concerned with those attributes that are in CalendarWidgetPart

            // logic to test if we have the correct values to store in the database
            if (part.QueryId <= 0)
            {
                updater.AddModelError("QueryId", T("You must select a query.")); // model error with localization
            }

            return Editor(part, shapeHelper);
        }
    }
}


text:
package org.wso2.carbon.event.output.adaptor.manager.admin.internal.ds;

import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.event.output.adaptor.core.OutputEventAdaptorService;
import org.wso2.carbon.event.output.adaptor.manager.admin.internal.util.OutputEventAdaptorHolder;
import org.wso2.carbon.event.output.adaptor.manager.admin.internal.util.OutputEventAdaptorManagerHolder;
import org.wso2.carbon.event.output.adaptor.manager.core.OutputEventAdaptorManagerService;

/**
 * this class is used to get the EventAdaptorManager service.
 *
 * @scr.component name="output.event.adaptor.manager.admin.component" immediate="true"
 * @scr.reference name="output.event.adaptor.manager.service"
 * interface="org.wso2.carbon.event.output.adaptor.manager.core.OutputEventAdaptorManagerService" cardinality="1..1"
 * policy="dynamic" bind="setEventAdaptorManagerService" unbind="unSetEventAdaptorManagerService"
 * @scr.reference name="output.event.adaptor.service"
 * interface="org.wso2.carbon.event.output.adaptor.core.OutputEventAdaptorService" cardinality="1..1"
 * policy="dynamic" bind="setEventAdaptorService" unbind="unSetEventAdaptorService"
 */
public class OutputEventAdaptorManagerAdminServiceDS {
    protected void activate(ComponentContext context) {

    }

    protected void setEventAdaptorManagerService(
            OutputEventAdaptorManagerService outputEventAdaptorManagerService) {
        OutputEventAdaptorManagerHolder.getInstance().registerEventAdaptorManagerService(outputEventAdaptorManagerService);
    }

    protected void unSetEventAdaptorManagerService(
            OutputEventAdaptorManagerService outputEventAdaptorManagerService) {
        OutputEventAdaptorManagerHolder.getInstance().unRegisterEventAdaptorManagerService(outputEventAdaptorManagerService);
    }

    protected void setEventAdaptorService(
            OutputEventAdaptorService outputEventAdaptorService) {
        OutputEventAdaptorHolder.getInstance().registerEventService(outputEventAdaptorService);
    }

    protected void unSetEventAdaptorService(OutputEventAdaptorService eventAdaptorService) {
        OutputEventAdaptorHolder.getInstance().unRegisterEventService(eventAdaptorService);
    }
}


text:
<?php

echo '
';
// Surpressing last updated date. Planned to be implimented in ~2019
// the_modified_date('F j, Y', '
Last updated ', '
');
if (get_field('reviewed_on')) {
	echo '
Last reviewed ' . date_format(date_create(get_field('reviewed_on')), 'F j, Y') . '
';
}
the_tags('
Tags: ','','
');
echo '
See a problem on this page? Let us know.
';
//echo do_shortcode('[contact-form-7 id="42260" title="Report a problem"]');
echo '

';
echo '
';

get_template_part( 'content', 'pagecss' );
get_template_part( 'content', 'pagejs' );

?>


text:
test.assert_approx_equals(sakura_fall(5), 80)
test.assert_approx_equals(sakura_fall(10), 40)
test.assert_approx_equals(sakura_fall(-1), 0)


text:
using System.Collections.Generic;
using System.Linq;
using SuggestionBox.Data.Entities;
using ToolKit.Data;
using ToolKit.Data.NHibernate;

namespace SuggestionBox.Data.Repositories
{
    /// <summary>
    /// Implementation of the Question Repository
    /// </summary>
    public class QuestionRepository : Repository<Question, int>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="QuestionRepository"/> class.
        /// </summary>
        public QuestionRepository()
        {
            if (!SessionPool.Contains("feedback"))
            {
                SessionPool.Add("feedback", Database.Feedback);
            }

            Context = new NHibernateUnitOfWork(SessionPool.Session("feedback"));
        }

        /// <summary>
        /// Gets the active questions.
        /// </summary>
        /// <returns>
        /// The active questions.
        /// </returns>
        public List<Question> GetActiveQuestions()
        {
            return Context.Get<Question>().Where(q => q.Active).ToList();
        }

        /// <summary>
        /// Gets all questions.
        /// </summary>
        /// <returns>
        /// All questions.
        /// </returns>
        public List<Question> GetAllQuestions()
        {
            return FindAll().ToList();
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FS_StartRain : FiniteState {

	public ParticleSystem rainParticles;
	public float startRainDuration = 5;
	public AnimationCurve bringRainCurve;
	public MicLoudness audienceLoudness;
	[Range(0,1)]
	public float minLoudness = 0.4f;

	private float baseRate;
	private float rainAcceleration;
	private float rainAmount;
	private ParticleSystem.EmissionModule rainEmitter;

	protected override void OnInitialize()
	{
		rainEmitter = rainParticles.emission;
		baseRate = rainEmitter.rateOverTimeMultiplier;
		rainAcceleration = baseRate / startRainDuration;
		rainEmitter.rateOverTimeMultiplier = 0;
		rainEmitter.enabled = false;
	}

	protected override void OnEnter ()
	{
		rainEmitter.enabled = true;
		audienceLoudness.SetActive(true);
	}

	protected override void OnProcess ()
	{
		// if the audience mic loudness is over a certain level
		bool isAudienceLoud = audienceLoudness.GetLoudness() >= minLoudness;

		// Emergency override
		if (isAudienceLoud == false) isAudienceLoud = Input.GetKey(KeyCode.Space);

		string debugText = audienceLoudness.GetLoudness().ToString("0.00") + " / " + minLoudness.ToString("0.00");
		DebugText.instance.SetText(debugText);

		if (isAudienceLoud)
		{
			rainAmount += rainAcceleration * Time.deltaTime;
		}
		else
		{
			rainAmount -= rainAcceleration * Time.deltaTime;
		}

		rainAmount = Mathf.Clamp(rainAmount, 0, baseRate);

		float t = bringRainCurve.Evaluate(rainAmount / baseRate);

		RainAudio.instance.SetHighRainVolume(t);
		rainEmitter.rateOverTimeMultiplier = t * baseRate;

		if (rainAmount >= baseRate)
		{
			finiteStateController.GoToNextState();
		}
	}

	protected override void OnExit ()
	{
		DebugText.instance.SetText("");
		audienceLoudness.SetActive(false);
	}
}


text:
define("dijit/form/_RadioButtonMixin", [
	"dojo/_base/array", // array.forEach
	"dojo/_base/declare", // declare
	"dojo/dom-attr", // domAttr.set
	"dojo/_base/lang", // lang.hitch
	"dojo/query!css2", // query
	"../registry"    // registry.getEnclosingWidget
], function(array, declare, domAttr, lang, query, registry){

	// module:
	//		dijit/form/_RadioButtonMixin

	return declare("dijit.form._RadioButtonMixin", null, {
		// summary:
		//		Mixin to provide widget functionality for an HTML radio button

		// type: [private] String
		//		type attribute on `<input>` node.
		//		Users should not change this value.
		type: "radio",

		_getRelatedWidgets: function(){
			// Private function needed to help iterate over all radio buttons in a group.
			var ary = [];
			query("input[type=radio]", this.focusNode.form || this.ownerDocument).forEach(// can't use name= since query doesn't support [] in the name
				lang.hitch(this, function(inputNode){
					if(inputNode.name == this.name && inputNode.form == this.focusNode.form){
						var widget = registry.getEnclosingWidget(inputNode);
						if(widget){
							ary.push(widget);
						}
					}
				})
			);
			return ary;
		},

		_setCheckedAttr: function(/*Boolean*/ value){
			// If I am being checked then have to deselect currently checked radio button
			this.inherited(arguments);
			if(!this._created){
				return;
			}
			if(value){
				array.forEach(this._getRelatedWidgets(), lang.hitch(this, function(widget){
					if(widget != this && widget.checked){
						widget.set('checked', false);
					}
				}));
			}
		},

		_getSubmitValue: function(/*String*/ value){
			return value == null ? "on" : value;
		},

		_onClick: function(/*Event*/ e){
			if(this.checked || this.disabled){ // nothing to do
				e.stopPropagation();
				e.preventDefault();
				return false;
			}
			if(this.readOnly){ // ignored by some browsers so we have to resync the DOM elements with widget values
				e.stopPropagation();
				e.preventDefault();
				array.forEach(this._getRelatedWidgets(), lang.hitch(this, function(widget){
					domAttr.set(this.focusNode || this.domNode, 'checked', widget.checked);
				}));
				return false;
			}
			return this.inherited(arguments);
		}
	});
});


text:
class PhysXWorldManager {

private:
	physx::PxScene *world;
	physx::PxDefaultAllocator gAllocator;
	physx::PxDefaultErrorCallback gErrorCallback;
//physx::PxVisualDebuggerConnection* gConnection = NULL;
	physx::PxCooking* mCooking;
	float timeStep;

	PhysXRigidManager * rigidManager;
	PhysXSoftManager * softManager;
	PhysXParticleManager * particleManager;
	PhysXCharacterManager * characterManager;

public:
	PhysXWorldManager();
	~PhysXWorldManager();

	void update();
	void setGravity(float x, float y, float z);
	physx::PxMaterial * createMaterial(float dynamicFrction, float staticFriction, float restitution);

	void addRigid(const std::string & scene, int nbVertices, float * vertices, int nbIndices, unsigned int * indices, float * transform, physx::PxMaterial * material, nau::physics::IPhysics::BoundingVolume shape, bool isStatic = false);
	void setRigidProperty(std::string scene, std::string propName, float value);
	void setRigidProperty(std::string scene, std::string propName, float * value);
	void moveRigid(std::string scene, float * transform);

	void addCloth(const std::string & scene, int nbVertices, float * vertices, int nbIndices, unsigned int * indices, float * transform, nau::physics::IPhysics::SceneCondition condition, float * conditionValue);
	void setSoftProperty(std::string scene, std::string propName, float value);
	void setSoftProperty(std::string scene, std::string propName, float * value);
	void moveSoft(std::string scene, float * transform);

	void addParticles(const std::string &scene, const std::string &material, float maxParticles, float * positions, float *transform);
	std::map<std::string, int> * getMaterialParticleNb();

	void addCharacter(const std::string &scene, int nbVertices, float *vertices, int nbIndices, unsigned int *indices, float *transform, physx::PxMaterial * material, float * up);
	void setCharacterProperty(std::string scene, std::string propName, float * value);
	void moveCharacter(std::string scene, float * transform);

	void addCamera(const std::string & scene, float * position, float * up, float pace, float minPace, float hitMagnitude, float timeStep, float stepOffset, float mass, float radius, float height, physx::PxMaterial * material);
	bool hasCamera(std::string cameraName) { return characterManager->hasCamera(cameraName); };
	std::map<std::string, float *> * getCameraPositions();

	void setTimeStep(float tStep) { timeStep = tStep; };

};

#endif


text:
class WebDriver::Remote::Bridge
  command :addCookie,                       :post,    "session/:session_id/:context/cookie"
  command :goBack,                          :post,    "session/:session_id/:context/back"
  command :clearElement,                    :post,    "session/:session_id/:context/element/:id/clear"
  command :clickElement,                    :post,    "session/:session_id/:context/element/:id/click"
  command :close,                           :delete,  "session/:session_id/:context/window"
  command :getCurrentUrl,                   :get,     "session/:session_id/:context/url"
  command :deleteAllCookies,                :delete,  "session/:session_id/:context/cookie"
  command :deleteCookie,                    :delete,  "session/:session_id/:context/cookie/:name"
  command :dragElement,                     :post,    "session/:session_id/:context/element/:id/drag"
  command :elementEquals,                   :get,     "session/:session_id/:context/element/:id/equals/:other"
  command :executeScript,                   :post,    "session/:session_id/:context/execute"
  command :findElement,                     :post,    "session/:session_id/:context/element"
  command :findElements,                    :post,    "session/:session_id/:context/elements"
  command :findChildElement,                :post,    "session/:session_id/:context/element/:id/element/:using"
  command :findChildElements,               :post,    "session/:session_id/:context/element/:id/elements/:using"
  command :goForward,                       :post,    "session/:session_id/:context/forward"
  command :get,                             :post,    "session/:session_id/:context/url"
  command :getActiveElement,                :post,    "session/:session_id/:context/element/active"
  command :getAllCookies,                   :get,     "session/:session_id/:context/cookie"
  # command :getCookie # TODO: getCookie
  command :getCurrentWindowHandle,          :get,     "session/:session_id/:context/window_handle"
  command :getElementAttribute,             :get,     "session/:session_id/:context/element/:id/attribute/:name"
  command :getElementLocation,              :get,     "session/:session_id/:context/element/:id/location"
  command :getElementSize,                  :get,     "session/:session_id/:context/element/:id/size"
  command :getElementText,                  :get,     "session/:session_id/:context/element/:id/text"
  command :getElementValue,                 :get,     "session/:session_id/:context/element/:id/value"
  command :getSpeed,                        :get,     "session/:session_id/:context/speed"
  command :getElementTagName,               :get,     "session/:session_id/:context/element/:id/name"
  command :getTitle,                        :get,     "session/:session_id/:context/title"
  command :getElementValueOfCssProperty,    :get,     "session/:session_id/:context/element/:id/css/:property_name"
  command :getVisible,                      :get,     "session/:session_id/:context/visible"
  command :getWindowHandles,                :get,     "session/:session_id/:context/window_handles"
  command :hoverOverElement,                :post,    "session/:session_id/:context/element/:id/hover"
  command :isElementDisplayed,              :get,     "session/:session_id/:context/element/:id/displayed"
  command :isElementEnabled,                :get,     "session/:session_id/:context/element/:id/enabled"
  command :isElementSelected,               :get,     "session/:session_id/:context/element/:id/selected"
  command :newSession,                      :post,    "session"
  command :getPageSource,                   :get,     "session/:session_id/:context/source"
  command :quit,                            :delete,  "session/:session_id"
  command :refresh,                         :post,    "session/:session_id/:context/refresh"
  command :screenshot,                      :get,     "session/:session_id/:context/screenshot"
  command :sendKeysToElement,               :post,    "session/:session_id/:context/element/:id/value"
  command :setElementSelected,              :post,    "session/:session_id/:context/element/:id/selected"
  command :setSpeed,                        :post,    "session/:session_id/:context/speed"
  command :setVisible,                      :post,    "session/:session_id/:context/visible"
  command :submitElement,                   :post,    "session/:session_id/:context/element/:id/submit"
  command :switchToFrame,                   :post,    "session/:session_id/:context/frame/:id"
  # command :switchToFrameByIndex # TODO: switchToFrameByIndex
  # command :switchToDefaultContent # TODO: switchToDefaultContent
  command :switchToWindow,                  :post,    "session/:session_id/:context/window/:name"
  command :toggleElement,                   :post,    "session/:session_id/:context/element/:id/toggle"
end


text: cp -R  ../prototype0/Assets/prototype0_assets/* ./


text:
version: 1.2.1
title: Coleções
---

Listas, tuplas, listas de palavras-chave e mapas.

{% include toc.html %}

## Listas

As listas são simples coleções de valores que podem incluir múltiplos tipos; listas também podem incluir valores não-exclusivos:

```elixir
iex> [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
```

Elixir implementa listas como listas encadeadas. Isso significa que acessar a profundidade da lista é uma operação `O(n)`. Por essa razão, é normalmente mais rápido inserir um elemento no início do que no final.

```elixir
iex> list = [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
iex> ["π"] ++ list
["π", 3.14, :pie, "Apple"]
iex> list ++ ["Cherry"]
[3.14, :pie, "Apple", "Cherry"]
```

### Concatenação de listas

A concatenação de listas usa o operador `++/2`.

```elixir
iex> [1, 2] ++ [3, 4, 1]
[1, 2, 3, 4, 1]
```

Uma pequena nota sobre o formato de nome (`++/2`) usado acima. Em Elixir (e Erlang, sobre o qual Elixir é construído), o nome de uma função ou operador tem dois componentes: o nome em si (neste caso `++`) e sua _aridade_. Aridade é uma parte central quando se fala sobre código Elixir (e Erlang). Indica o número de argumentos que uma dada função aceita (dois, nesse nosso exemplo). Aridade e o nome são combinados com uma barra. Iremos falar mais sobre isto mais tarde; este conhecimento irá ajudá-lo a entender a notação por enquanto.

### Subtração de listas

O suporte para subtração é provido pelo operador `--/2`; é seguro subtrair um valor que não existe:

```elixir
iex> ["foo", :bar, 42] -- [42, "bar"]
["foo", :bar]
```

Esteja atento para valores duplicados. Para cada elemento na direita, a primeira ocorrência deste é removida da esquerda:

```elixir
iex> [1,2,2,3,2,3] -- [1,2,3,2]
[2, 3]
```

**Nota:** subtração de listas usa [comparação estrita](../basics/#comparação) para match de valores.

### Topo / Cauda

Quando usamos listas é comum trabalhar com o topo e o fim da lista. O topo é o primeiro elemento da lista e a cauda são os elementos restantes. Elixir provê funções úteis, `hd` e `tl`, para trabalhar com essas partes:

```elixir
iex> hd [3.14, :pie, "Apple"]
3.14
iex> tl [3.14, :pie, "Apple"]
[:pie, "Apple"]
```

Além das funções citadas, pode-se usar [pattern matching](../pattern-matching) e o operador cons `|` para dividir a lista em topo e cauda; veremos este padrão em futuras lições:

```elixir
iex> [head | tail] = [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
iex> head
3.14
iex> tail
[:pie, "Apple"]
```

## Tuplas

As tuplas são similares às listas porém são armazenadas de maneira contígua em memória. Isto permite acessar a sua profundidade de forma rápida porém sua modificação é custosa; a nova tupla deve ser armazenada inteira na memória. As tuplas são definidas com chaves.

```elixir
iex> {3.14, :pie, "Apple"}
{3.14, :pie, "Apple"}
```

É comum usar tuplas como um mecanismo que retorna informação adicional de funções; a utilidade disso ficará mais aparente quando vermos [pattern matching](../pattern-matching/):

```elixir
iex> File.read("path/to/existing/file")
{:ok, "... contents ..."}
iex> File.read("path/to/unknown/file")
{:error, :enoent}
```

## Listas de palavras-chave

As listas de palavras-chave e os mapas são coleções associativas no Elixir; ambas implementam o módulo `Dict`. No Elixir, uma lista de palavras-chave é uma lista especial de tuplas de dois elementos cujo o primeiro elemento é um átomo; eles compartilham o desempenho das listas:

```elixir
iex> [foo: "bar", hello: "world"]
[foo: "bar", hello: "world"]
iex> [{:foo, "bar"}, {:hello, "world"}]
[foo: "bar", hello: "world"]
```

As três características relevantes das listas de palavras-chave são:

+ As chaves são átomos.
+ As chaves estão ordenadas.
+ As chaves não são únicas.

Por essas razões as listas de palavras-chave são frequentemente usadas para passar opções a funções.

## Mapas

Em Elixir, mapas normalmente são a escolha para armazenamento chave-valor. A diferença entre os mapas e as listas de palavras-chave está no fato de que os mapas permitem chaves de qualquer tipo e não seguem uma ordem. Você pode definir um mapa com a sintaxe `%{}`:

```elixir
iex> map = %{:foo => "bar", "hello" => :world}
%{:foo => "bar", "hello" => :world}
iex> map[:foo]
"bar"
iex> map["hello"]
:world
```

A partir do Elixir 1.2, variáveis são permitidas como chaves do mapa:

```elixir
iex> key = "hello"
"hello"
iex> %{key => "world"}
%{"hello" => "world"}
```

Se um elemento duplicado é inserido no mapa, este sobrescreverá o valor anterior;

```elixir
iex> %{:foo => "bar", :foo => "hello world"}
%{foo: "hello world"}
```

Como podemos ver na saída anterior, há uma sintaxe especial para os mapas que contém apenas átomos como chaves:

```elixir
iex> %{foo: "bar", hello: "world"}
%{foo: "bar", hello: "world"}
iex> %{foo: "bar", hello: "world"} == %{:foo => "bar", :hello => "world"}
true
```

Além disso, existe uma sintaxe especial para acessar átomos como chaves:

```elixir
iex> map = %{foo: "bar", hello: "world"}
%{foo: "bar", hello: "world"}
iex> map.hello
"world"
```

Outra propriedade interessante de mapas é que eles têm sua própria sintaxe para atualizar e acessar átomos como chaves:

```elixir
iex> map = %{foo: "bar", hello: "world"}
%{foo: "bar", hello: "world"}
iex> %{map | foo: "baz"}
%{foo: "baz", hello: "world"}
```


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Algorithms</title>
  <meta property="og:title" content="Algorithms" />
  <meta name="twitter:title" content="Algorithms" />
  <meta name="author" content="Isaac Zhou"/>
  <link href='http://www.primerpy.com/img/py.png' rel='icon' type='image/x-icon'/>
  <meta property="og:image" content="http://www.primerpy.com/img/py.png" />
  <meta name="twitter:image" content="http://www.primerpy.com/img/py.png" />
  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@username" />
  <meta name="twitter:creator" content="@username" />
  <meta property="og:url" content="http://www.primerpy.com/tags/algorithms/" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="PrimerPy" />

  <meta name="generator" content="Hugo 0.30.2" />
  <link rel="canonical" href="http://www.primerpy.com/tags/algorithms/" />
  <link rel="alternate" href="http://www.primerpy.com/tags/algorithms/index.xml" type="application/rss+xml" title="PrimerPy">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="http://www.primerpy.com/css/main.css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />
  <link rel="stylesheet" href="http://www.primerpy.com/css/highlighting.css" />
  <link rel="stylesheet" href="http://www.primerpy.com/css/pygment_highlights.css" />
  <link rel="stylesheet" href="http://www.primerpy.com/css/highlight.min.css" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css" integrity="sha256-sCl5PUOGMLfFYctzDW3MtRib0ctyUvI9Qsmq2wXOeBY=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css" integrity="sha256-BFeI1V+Vh1Rk37wswuOYn5lsTcaU96hGaI7OUVCLjPc=" crossorigin="anonymous" />

      <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
      <button class="pswp__button pswp__button--share" title="Share"></button>
      <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
      <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

    <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    </button>
    <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    </button>

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        Toggle navigation

      </button>
      PrimerPy

              Focus

                  Data Analysis

                  Visualization

              Flow

                  Emacs

                  Python

              About

              Tags

#Algorithms

Binary Addition

                Posted on November 11, 2017

                  We can add binary numbers together, just like we can with base 10 numbers
In the example below:
 a is in base 10 – because we have 10 possible digits, the highest value we can represent with one digit is 9 When we want to represent a value one higher, we need to add another digit. a now has two digits – we incremented the invisible leading digit, which was 0 and is now 1, and set the last digit back to zero.
                  [Read More]

                    #python

                    #algorithms

              Isaac Zhou

           •
          2017

             •
            PrimerPy

          Hugo v0.30.2 powered  •  Theme by Beautiful Jekyll adapted to Beautiful Hugo


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mystack;

/**
 *
 * @author Felipe Pontes <felipemfpontes@gmail.com>
 */
public class MyStack {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        // TODO code application logic here
        Stack s = new Stack();

        for (int i = 0; i < 55; i++) {
            s.push(i);
        }

        System.out.println("My stack: " + s.size());

        while (!s.isEmpty()) {
            int r = (int) s.pop();
            System.out.println("Returns from stack: " + r);
        }

        System.out.println("My stack: " + s.size());
    }

}


text:
_[www.codever.land/bookmarks/t/margin](https://www.codever.land/bookmarks/t/margin)_
---
#### [Create boxes in the terminal](https://github.com/sindresorhus/boxen#readme)
_https://github.com/sindresorhus/boxen#readme_

Create boxes in the terminal. Contribute to sindresorhus/boxen development by creating an account on GitHub.
* **tags**: [node.js](../tagged/node.js.md), [terminal](../tagged/terminal.md), [cli](../tagged/cli.md), [box](../tagged/box.md), [margin](../tagged/margin.md), [border](../tagged/border.md)
---


text:
cs601-webmail-skeleton
======================

Some goodies to help start the CS601 webmail project


text:
module Remarkable # :nodoc:
  module ActiveRecord # :nodoc:
    module Matchers # :nodoc:
      class ProtectAttributes < Remarkable::Matcher::Base
        def initialize(*attributes)
          attributes.extract_options!
          @attributes = attributes
        end

        def matches?(subject)
          @subject = subject

          assert_matcher_for(@attributes) do |attribute|
            @attribute = attribute
            protect_from_mass_updates?
          end
        end

        def description
          "protect #{@attributes.to_sentence} from mass updates"
        end

        private

        def protect_from_mass_updates?
          attribute  = @attribute.to_sym
          protected  = subject_class.protected_attributes || []
          accessible = subject_class.accessible_attributes || []

          return true if !protected.empty?  && protected.include?(attribute.to_s)
          return true if !accessible.empty? && !accessible.include?(attribute.to_s)

          @missing = accessible.empty? ? "#{subject_class} is protecting #{protected.to_a.to_sentence}, but not #{attribute}." :
                                         "#{subject_class} has made #{attribute} accessible"
          return false
        end

        def expectation
          "that #{@attribute} cannot be set on mass update"
        end
      end

      # TODO Deprecate this method and the matcher.
      def protect_attributes(*attributes) #:nodoc:
        warn "[DEPRECATION] should_protect_attributes is deprecated. " <<
             "Use should_not_allow_mass_assignment_of instead."
        ProtectAttributes.new(*attributes)
      end
    end
  end
end


text: require 'digest/sha2'


text:
package org.apache.druid.server.coordination;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.utils.ZKPaths;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.segment.loading.SegmentLoaderConfig;
import org.apache.druid.server.initialization.ZkPathsConfig;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.concurrent.ExecutorService;

/**
 * Use {@link org.apache.druid.server.coordinator.HttpLoadQueuePeon} for segment load/drops.
 */
@Deprecated
public class ZkCoordinator
{
  private static final EmittingLogger log = new EmittingLogger(ZkCoordinator.class);

  private final Object lock = new Object();

  private final DataSegmentChangeHandler dataSegmentChangeHandler;
  private final ObjectMapper jsonMapper;
  private final ZkPathsConfig zkPaths;
  private final DruidServerMetadata me;
  private final CuratorFramework curator;

  @Nullable
  private volatile PathChildrenCache loadQueueCache;
  private volatile boolean started = false;
  private final ExecutorService segmentLoadUnloadService;

  @Inject
  public ZkCoordinator(
      SegmentLoadDropHandler loadDropHandler,
      ObjectMapper jsonMapper,
      ZkPathsConfig zkPaths,
      DruidServerMetadata me,
      CuratorFramework curator,
      SegmentLoaderConfig config
  )
  {
    this.dataSegmentChangeHandler = loadDropHandler;
    this.jsonMapper = jsonMapper;
    this.zkPaths = zkPaths;
    this.me = me;
    this.curator = curator;
    this.segmentLoadUnloadService = Execs.multiThreaded(
        config.getNumLoadingThreads(),
        "ZKCoordinator--%d"
    );
  }

  @LifecycleStart
  public void start() throws IOException
  {
    synchronized (lock) {
      if (started) {
        return;
      }

      log.info("Starting zkCoordinator for server[%s]", me.getName());

      final String loadQueueLocation = ZKPaths.makePath(zkPaths.getLoadQueuePath(), me.getName());
      final String servedSegmentsLocation = ZKPaths.makePath(zkPaths.getServedSegmentsPath(), me.getName());
      final String liveSegmentsLocation = ZKPaths.makePath(zkPaths.getLiveSegmentsPath(), me.getName());

      loadQueueCache = new PathChildrenCache(
          curator,
          loadQueueLocation,
          true,
          true,
          Execs.singleThreaded("ZkCoordinator")
      );

      try {
        curator.newNamespaceAwareEnsurePath(loadQueueLocation).ensure(curator.getZookeeperClient());
        curator.newNamespaceAwareEnsurePath(servedSegmentsLocation).ensure(curator.getZookeeperClient());
        curator.newNamespaceAwareEnsurePath(liveSegmentsLocation).ensure(curator.getZookeeperClient());

        loadQueueCache.getListenable().addListener(
            (client, event) -> {
              final ChildData child = event.getData();
              switch (event.getType()) {
                case CHILD_ADDED:
                  childAdded(child);
                  break;
                case CHILD_REMOVED:
                  log.info("zNode[%s] was removed", event.getData().getPath());
                  break;
                default:
                  log.info("Ignoring event[%s]", event);
              }
            }

        );
        loadQueueCache.start();
      }
      catch (Exception e) {
        Throwables.propagateIfPossible(e, IOException.class);
        throw new RuntimeException(e);
      }

      started = true;
    }
  }

  private void childAdded(ChildData child)
  {
    segmentLoadUnloadService.submit(() -> {
      final String path = child.getPath();
      DataSegmentChangeRequest request = new SegmentChangeRequestNoop();
      try {
        final DataSegmentChangeRequest finalRequest = jsonMapper.readValue(
            child.getData(),
            DataSegmentChangeRequest.class
        );

        finalRequest.go(
            dataSegmentChangeHandler,
            () -> {
              try {
                curator.delete().guaranteed().forPath(path);
                log.info("Completed request [%s]", finalRequest.asString());
              }
              catch (Exception e) {
                try {
                  curator.delete().guaranteed().forPath(path);
                }
                catch (Exception e1) {
                  log.error(e1, "Failed to delete zNode[%s], but ignoring exception.", path);
                }
                log.error(e, "Exception while removing zNode[%s]", path);
                throw new RuntimeException(e);
              }
            }
        );
      }
      catch (Exception e) {
        // Something went wrong in either deserializing the request using jsonMapper or when invoking it
        try {
          curator.delete().guaranteed().forPath(path);
        }
        catch (Exception e1) {
          log.error(e1, "Failed to delete zNode[%s], but ignoring exception.", path);
        }

        log.makeAlert(e, "Segment load/unload: uncaught exception.")
           .addData("node", path)
           .addData("nodeProperties", request)
           .emit();
      }
    });
  }

  @LifecycleStop
  public void stop()
  {
    log.info("Stopping ZkCoordinator for [%s]", me);
    synchronized (lock) {
      if (!started) {
        return;
      }

      try {
        loadQueueCache.close();
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }
      finally {
        loadQueueCache = null;
        started = false;
      }
    }
  }

  public boolean isStarted()
  {
    return started;
  }
}


text:
from yapsy.IPlugin import IPlugin
import validictory

class ValidateJson(IPlugin):

    @staticmethod
    def run(req):
        try:
            response_json = req.req.json()
            validictory.validate(response_json, req.test['outcomes']['validate_json']['schema'])
            return req.pass_test("Json response matches the schema provided")
        except ValueError as error:
            return req.fail_test("Json response fails to match the schema provided {0}".format(error))


text:
import {
	verify,
} from '../src/dancer';
import testData from './single_data';

describe('verifying abstracted single blocks', () => {
	testData.forEach((test, i) => {
		it('should work correctly for message #' + i, () => {
			verify(test.key, test.nonce, test.tag, test.cipher).then(() => {}).catch((error) => {
				expect(error).toBe(undefined);
			});
		});
	});
});


text:
import random
import gzip
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
from .structures import SearchResults, SearchItem
import os

REQUEST_URL = "https://{}/{}"
BASE_URL = "www.google.co.uk"
GOOGLE_SEARCH = "search?hl=en&q={}"
SEARCH_NEWS = "&tbm=nws"
CUSTOMIZED_DATE = "&tbs=cdr:1,cd_min:{},cd_max:{}"
HTML_PARSER = 'html.parser'

def fetch_page(query):
    url = REQUEST_URL.format(BASE_URL, query)
    request = urllib.request.Request(url)
    request.add_header('User-agent', _random_user_agent())
    request.add_header('connection', 'keep-alive')
    request.add_header('Accept-Encoding', 'gzip, deflate, sdch, br')
    request.add_header('referer', REQUEST_URL.format(BASE_URL, ""))
    print(url)
    response = urllib.request.urlopen(request)

    data = response.read()
    print(type(data))
    return gzip.decompress(data)

def search_news(query, date_start=None, date_end=None):
    url = GOOGLE_SEARCH + SEARCH_NEWS
    url = url.format(_url_encode(query))

    if date_start is not None and date_end is not None:
        url += CUSTOMIZED_DATE.format(_url_encode_date(date_start), _url_encode_date(date_end))

    content = fetch_page(url)
    dom = BeautifulSoup(content, HTML_PARSER)
    search_result = SearchResults(query)
    links = dom.find_all('a', {'class': 'l _HId'})
    for link in links:
        search_result.append(SearchItem(link.text, link.get('href')))

    return search_result

def search_web(query, date_start=None, date_end=None):
    url = GOOGLE_SEARCH.format(_url_encode(query))

    if date_start is not None and date_end is not None:
        url += CUSTOMIZED_DATE.format(_url_encode_date(date_start), _url_encode_date(date_end))

    content = fetch_page(url)
    dom = BeautifulSoup(content, HTML_PARSER)
    print(dom.prettify())
    search_result = SearchResults(query)
    links = dom.find_all('h3', {'class':'r'})
    for link in links:
        search_result.append(SearchItem(link.a.text, link.a.get('href')))

    return search_result

def _url_encode(data):
    return urllib.parse.quote_plus(data)

def _url_encode_date(date):
    return _url_encode("{}/{}/{}".format(date.day, date.month, date.year))

def _random_user_agent():
    file_path = '{}/useragents'.format(os.path.dirname(__file__))
    with open(file_path, 'r') as file:
        user_agents = file.read().splitlines()
        line_num = len(user_agents)
        return user_agents[random.randrange(line_num)]

def write_to_local(content):
    with open("sample.html", "w") as text_file:
        text_file.write(content.decode())

def write_bytes(content):
    with open("sample.bytes", "wb") as text_file:
        text_file.write(content)


text:
const wchar *St(MSGID StringId)
{
  return StringId;
}
#endif


text:
#ifndef INCLUDED_cpp_Lib
#define INCLUDED_cpp_Lib

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

HX_DECLARE_CLASS1(cpp,Lib)
namespace cpp{

class HXCPP_CLASS_ATTRIBUTES  Lib_obj : public hx::Object{
	public:
		typedef hx::Object super;
		typedef Lib_obj OBJ_;
		Lib_obj();
		Void __construct();

	public:
		inline void *operator new( size_t inSize, bool inContainer=false)
			{ return hx::Object::operator new(inSize,inContainer); }
		static hx::ObjectPtr< Lib_obj > __new();
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		//~Lib_obj();

		HX_DO_RTTI;
		static void __boot();
		static void __register();
		::String __ToString() const { return HX_CSTRING("Lib"); }

		static Dynamic load( ::String lib,::String prim,int nargs);
		static Dynamic load_dyn();

		static Dynamic loadLazy( ::String lib,::String prim,int nargs);
		static Dynamic loadLazy_dyn();

};

} // end namespace cpp

#endif /* INCLUDED_cpp_Lib */


text:
title: The Ooda Loops
localeTitle: Los bucles de ooda
---
El OODA Loop es acerca de qué tan rápido puede iterar. A menudo se hace referencia en los círculos de Lean Startup.

![OODA](https://upload.wikimedia.org/wikipedia/commons/3/3a/OODA.Boyd.svg)

## ver también

[OODA Loop](https://en.wikipedia.org/wiki/OODA_loop)


text:
package edu.ncrn.cornell.xml

import edu.ncrn.cornell.Util._

//import cats._
//import cats.instances.all._
//import cats.syntax.eq._

import scala.xml.Node
import XpathEnumerator._

/**
  * @author Brandon Barker
  *         9/14/2016
  */
trait XpathEnumerator {

  /**
    * The list of root nodes to start from, typically from an XML document
    */
  protected val nodesIn: List[Node]

  protected val boundaries: BoundarySchemas = BoundarySchemas(Nil)

  var nonEmpty: Boolean = true

  //TODO: need a way to establish boundary conditions on recursion; for instance,
  //TODO leaf nodes (simpleTypes) in XSD, or elements with text data in XML, are
  //TODO leaf nodes and thus natural boundaries. However, we may only want to traverse
  //TODO up to something in the current namespace, or e disregard traversal beyond
  //TODO specified nodes, etc.

  //var XmlFile = ???

  //TODO: add public interface for enumerate that only takes List[Node] as input, along with any optional args

  /**
    *
    * @param nonEmpty If true, return only XPaths with nonEmpty values.
    * @return A list of tuples of (XPath, value at XPath)
    */
  def enumerate(
    nonEmpty: Boolean, newNodeFilters: NodeFilters
  ): List[(String, String)]

  /**
    * Typical use case that can be overridden if necessary.
    * @return A list of unfiltered tuples of XPaths and value at
    *         XPath, with the exception that empty values are filtered.
    */
  def enumSimple = enumerate(nonEmpty = true, NodeFilters(List(
    NodeFilterGeneric((_, _) => true))
  ))

}

object XpathEnumerator{

  sealed abstract class NodeFilter(fun: (String, Node) => Boolean)
  extends Function2[String, Node, Boolean] {
    override def apply(ident: String, node: Node): Boolean = fun(ident, node)
  }

  final case class NodeFilters(filters: List[NodeFilter])
  extends Function2[String, Node, Boolean] {
    override def apply(ident: String, node: Node): Boolean = {

      val x = 2+2 // DEBUG

      filters.forall(nf => nf(ident, node))
    }
  }

  val noFilter = NodeFilters(List(
    NodeFilterGeneric((x1: String, x2: Node) => true)
  ))

  final case class NodeFilterGeneric(fun: (String, Node) => Boolean)
    extends NodeFilter(fun)

  //TODO: make arguments of returned function HList? Ideal not to have HList in public API, though.
//  implicit def NodeFilterToFunction2(nodeFilter: NodeFilter)
//  : (String, Node) => Boolean =
//    (cPath: String, node: Node) => nodeFilter match {
//      case nf: NodeFilterPath => nf.fun(cPath, node)
//    }

  def cleanXpath(xpath: String) = xpath.replaceFirst("/#PCDATA", "")
  /**
    * Helper function to add XPaths to a node sequence; assume a default of root nodes.
    */
  def pathifyNodes(
    nodes: List[Node], parPath: String, nonEmpty: Boolean
  ): List[(Node, String)] = {
    def nodeNotEmpty(node: Node) =
      if (nonEmpty) node.text =!= "" else true
    nodes.filter(nodeNotEmpty).groupBy(nn => parPath + nn.label).toList.flatMap{
      case(xpath, labNodes) =>
        def xindex(index: Int) = if (labNodes.size > 1) s"[${index + 1}]" else ""
        labNodes.zipWithIndex.map{case (nn, ii) => (nn, xpath + xindex(ii))}
    }
  }

}


text:
class Meetup < ActiveRecord::Base
  acts_as_taggable_on :tags

	scope :enabled, -> { where(:disabled => false) }
end


text:
package me.snowdrop.data.hibernatesearch.config.infinispan.remote.crud;

import me.snowdrop.data.hibernatesearch.config.infinispan.remote.InfinispanRemoteTestUtils;
import me.snowdrop.data.hibernatesearch.crud.CEntity;
import me.snowdrop.data.hibernatesearch.crud.CrudTestBase;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author Ales Justin
 */
@SpringBootTest(classes = InfinispanRemoteCrudConfiguration.class)
@RunWith(SpringRunner.class)
public class InfinispanRemoteCrudTest extends CrudTestBase {

    @Autowired
    private RemoteCacheManager remoteCacheManager;

    @Before
    public void checkForServer() {
        InfinispanRemoteTestUtils.checkForServer(remoteCacheManager);
    }

    @Override
    protected CEntity create() {
        return new CEntity(1, "foobar");
    }
}


text: angular.module('selectPuzzleStats', []);


text:
namespace Orleans.ShoppingCart.Silo.Extensions;

internal static class ProductDetailsExtensions
{
    internal static Faker<ProductDetails> GetBogusFaker(this ProductDetails productDetails) =>
        new Faker<ProductDetails>()
            .StrictMode(true)
            .RuleFor(p => p.Id, (f, p) => f.Random.Number(1, 100_000).ToString())
            .RuleFor(p => p.Name, (f, p) => f.Commerce.ProductName())
            .RuleFor(p => p.Description, (f, p) => f.Lorem.Sentence())
            .RuleFor(p => p.UnitPrice, (f, p) => decimal.Parse(f.Commerce.Price(max: 170)))
            .RuleFor(p => p.Quantity, (f, p) => f.Random.Number(0, 1_200))
            .RuleFor(p => p.ImageUrl, (f, p) => f.Image.PicsumUrl())
            .RuleFor(p => p.Category, (f, p) => f.PickRandom<ProductCategory>())
            .RuleFor(p => p.DetailsUrl, (f, p) => f.Internet.Url());

    internal static bool MatchesFilter(this ProductDetails product, string? filter)
    {
        if (filter is null or { Length: 0 })
        {
            return true;
        }

        if (product is not null)
        {
            return product.Name.Contains(filter, StringComparison.OrdinalIgnoreCase)
                || product.Description.Contains(filter, StringComparison.OrdinalIgnoreCase);
        }

        return false;
    }
}


text:
@implementation UIImage (Extend)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (UIImage *)screenshot
{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;

    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            CGContextConcatCTM(context, [window transform]);
            CGContextTranslateCTM(context,
                                  -[window bounds].size.width * [[window layer] anchorPoint].x,
                                  -[window bounds].size.height * [[window layer] anchorPoint].y);
            [[window layer] renderInContext:context];
            CGContextRestoreGState(context);
        }
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)rotateImage
{
    CGImageRef imgRef           = self.CGImage;
    CGFloat width               = CGImageGetWidth(imgRef);
    CGFloat height              = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds               = CGRectMake(0, 0, width, height);

    CGFloat scaleRatio          = 1;

    CGFloat boundHeight;
    UIImageOrientation orient = self.imageOrientation;
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(width, height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight        = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width  = boundHeight;
            transform          = CGAffineTransformMakeTranslation(height, width);
            transform          = CGAffineTransformScale(transform, -1.0, 1.0);
            transform          = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight        = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width  = boundHeight;
            transform          = CGAffineTransformMakeTranslation(0.0, width);
            transform          = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight        = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width  = boundHeight;
            transform          = CGAffineTransformMakeScale(-1.0, 1.0);
            transform          = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight        = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width  = boundHeight;
            transform          = CGAffineTransformMakeTranslation(height, 0.0);
            transform          = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    }

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

- (UIImage *)imageCompressForTargetWidth:(CGFloat)defineWidth
{
    UIImage *newImage      = nil;
    CGSize imageSize       = self.size;
    CGFloat width          = imageSize.width;
    CGFloat height         = imageSize.height;
    CGFloat targetWidth    = defineWidth;
    CGFloat targetHeight   = height / (width / targetWidth);
    CGSize size            = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor    = 0.0;
    CGFloat scaledWidth    = targetWidth;
    CGFloat scaledHeight   = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor  = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect      = CGRectZero;
    thumbnailRect.origin      = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [self drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }

    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage *)compressImageWith:(UIImage *)image
{
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = ([UIScreen mainScreen].bounds.size.width) * ([UIScreen mainScreen].scale);
    float height = image.size.height/(image.size.width/width);

    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;

    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));

    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }

    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();

    return newImage;
}

@end

#pragma mark - MARK:

@implementation UIImage (ImageEffects)

- (UIImage *)applySubtleEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
    return [self applyBlurWithRadius:3 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
    return [self applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyExtraLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyDarkEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
{
    const CGFloat EffectColorAlpha = 0.6;
    UIColor *effectColor = tintColor;
    int componentCount = (int)CGColorGetNumberOfComponents(tintColor.CGColor);
    if (componentCount == 2) {
        CGFloat b;
        if ([tintColor getWhite:&b alpha:NULL]) {
            effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
        }
    }
    else {
        CGFloat r, g, b;
        if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
            effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
        }
    }
    return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
}

- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius
                       tintColor:(UIColor *)tintColor
           saturationDeltaFactor:(CGFloat)saturationDeltaFactor
                       maskImage:(UIImage *)maskImage
{
    // Check pre-conditions.
    if (self.size.width < 1 || self.size.height < 1) {
        NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
        return nil;
    }
    if (!self.CGImage) {
        NSLog (@"*** error: image must be backed by a CGImage: %@", self);
        return nil;
    }
    if (maskImage && !maskImage.CGImage) {
        NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
        return nil;
    }

    CGRect imageRect = { CGPointZero, self.size };
    UIImage *effectImage = self;

    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
    BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
    if (hasBlur || hasSaturationChange) {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectInContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(effectInContext, 1.0, -1.0);
        CGContextTranslateCTM(effectInContext, 0, -self.size.height);
        CGContextDrawImage(effectInContext, imageRect, self.CGImage);

        vImage_Buffer effectInBuffer;
        effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
        effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
        effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
        effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
        vImage_Buffer effectOutBuffer;
        effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
        effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
        effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
        effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

        if (hasBlur) {
            // A description of how to compute the box kernel width from the Gaussian
            // radius (aka standard deviation) appears in the SVG spec:
            // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
            //
            // For larger values of 's' (s >= 2.0), an approximation can be used: Three
            // successive box-blurs build a piece-wise quadratic convolution kernel, which
            // approximates the Gaussian kernel to within roughly 3%.
            //
            // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
            //
            // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
            //
            CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
            uint32_t radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
            if (radius % 2 != 1) {
                radius += 1; // force radius to be odd so that the three box-blur methodology works.
            }
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
        }
        BOOL effectImageBuffersAreSwapped = NO;
        if (hasSaturationChange) {
            CGFloat s = saturationDeltaFactor;
            CGFloat floatingPointSaturationMatrix[] = {
                0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                0,                    0,                    0,  1,
            };
            const int32_t divisor = 256;
            NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
            int16_t saturationMatrix[matrixSize];
            for (NSUInteger i = 0; i < matrixSize; ++i) {
                saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
            }
            if (hasBlur) {
                vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                effectImageBuffersAreSwapped = YES;
            }
            else {
                vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
            }
        }
        if (!effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if (effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Set up output context.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef outputContext = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -self.size.height);

    // Draw base image.
    CGContextDrawImage(outputContext, imageRect, self.CGImage);

    // Draw effect image.
    if (hasBlur) {
        CGContextSaveGState(outputContext);
        if (maskImage) {
            CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
        }
        CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
        CGContextRestoreGState(outputContext);
    }

    // Add in color tint.
    if (tintColor) {
        CGContextSaveGState(outputContext);
        CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
        CGContextFillRect(outputContext, imageRect);
        CGContextRestoreGState(outputContext);
    }

    // Output image is ready.
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outputImage;
}

@end


text:
<?php
namespace fay\models\tables;

use fay\core\db\Table;

class Likes extends Table{
	protected $_name = 'likes';
	protected $_primary = array('post_id', 'user_id');

	/**
	 * @return Likes
	 */
	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public function rules(){
		return array(
			array(array('post_id', 'user_id', 'create_time'), 'int', array('min'=>0, 'max'=>4294967295)),
		);
	}

	public function labels(){
		return array(
			'post_id'=>'Post Id',
			'user_id'=>'User Id',
			'create_time'=>'Create Time',
		);
	}

	public function filters(){
		return array(
			'post_id'=>'intval',
			'user_id'=>'intval',
			'create_time'=>'',
		);
	}
}


text:
#ifndef MONGOC_HOST_LIST_PRIVATE_H
#define MONGOC_HOST_LIST_PRIVATE_H

#include "mongoc-host-list.h"

BSON_BEGIN_DECLS

bool _mongoc_host_list_from_string (mongoc_host_list_t *host_list,
                                    const char         *host_and_port);

BSON_END_DECLS

#endif /* MONGOC_HOST_LIST_PRIVATE_H */


text:
module.exports = (function () {
  'use strict';
  // Dependencies
  var conf = require('../configuration.js');

  /**
  * ## Main function
  *
  * Used to give the MyPads URL
  */
  return function (gid, pid) {
    var l      = window.location;
    var url    = l.protocol + '//' + l.host + l.pathname + '?/mypads/group/' + gid;
    var suffix = (pid ? '/pad/view/' + pid : '/view');
    window.prompt(conf.LANG.GROUP.SHARE_LINK, url + suffix);
  };
}).call(this);