text:
---
layout: post
title: Week Seven
---

### Past Week
This past week I worked on the project with my group. I was in charge of getting the data and setting up aws. All things considered, it went very smooth and we managed to finish the project on time. I was using some of these tools for the first time so it took me a while to know how they worked but it went smoothly otherwise. In class we have started learning about xlm.

### What is in my way
I only have one test on Tuesday. Besides that, I think we can start working on the next project to get an early start.

### Next Week
The week is looking pretty relaxed, so our group could begin to know the requirements and who is going to be doing what. I will continue to do the readings. Other than that is just the regular assignments in my other classes, and another ongoing project for database management.

### Tip of the Week
If you are working on an android app or are interested in keeping up with android news, [Android Weekly](http://androidweekly.net/) has really good resources that they compile in an email and update you on weekly. The news are very varied so I can usually find something interesting.


text:
# Onyx
A simple, yet flexible 2D game engine.

Current features include:
- Fast 2D sprite batching, with OpenGL 4.6 backend
- Audio - playing and loading MP3s, WAVs and FLACs
- Scene/Game Object/Component design

# Building
```bash
vendor/premake/premake5 gmake
make config=release
```
This will generate a static library in bin/release/onyx/, copy this to your project and link it.

repository: thebigcx/Onyx

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: thebigcx/Onyx


text:
# Million-text-analysis
 Million text analysis，from get million text data，Pretreatment text data to text data classification
 my data from China News Network https://www.chinanews.com/
## This project contains three parts：
1. get data
2. Pretreatment data
3. classify data
## environment
1. python 3.5
2. xgboost
3. sklearn
4. numpy
5. Scipy
6. selenium
7. Scrapy
8.mysql
9. ......
## first: get news data
Get the url information of the crawl news
```
 cd geturllist
 python geturllist.py
```

the news urllist url Have a certain law：

http://www.chinanews.com/scroll-news/+type+/+year+/+month+day+/+news.shtml<\br>

example:http://www.chinanews.com/scroll-news/it/2012/1201/news.shtml<\br>

then use these url to get news content

use Scrapy to get news and mysql to store data

Mysql configuration is in \getnewsdata\nengyuan\chezhiwang\pipelines

there is a spider zhongche.py

I get about 1.9 millon news
## Second：Pretreatment data
Read mysql data and Participle

```
python getword.py
```
I use jieba to Participle
there is a train_text.txt example in mynews
```
python chuli3.py
```
to remove some words
## classify data
first
```
cd Classifier
python news_Bayes.py
```
to get tfidf feature and bayes classification
your should read code to build folder
```
python news_XGBoost.py
```
to use XGBoost classification
## the acc about my get news data is 94%

license: MIT


text:
# Forge-Game-Data-Language [![Build Status](https://travis-ci.org/Crowbar-Sledgehammer/forge-game-data-language.svg)](https://travis-ci.org/Crowbar-Sledgehammer/forge-game-data-language)
Syntax highlighting rules for Forge Game Data (.fdg) files.

Language keywords were taken from the source sdk [wiki/FGD](https://developer.valvesoftware.com/wiki/FGD).

# Installation (Manual)
Check the [Releases](https://github.com/Crowbar-Sledgehammer/forge-game-data-language/releases) page for compiled .tmLanguage files.
Download and extract the newest release into your sublime packages folder <kbd>File > Preferences > Browse Packages</kbd>.


text:
The examples are designed to work on Mac and Linux. If you're using Windows,
feel free to reach out to me to request updates for examples that don't work
correctly.

## Calls from Go to C (`go_to_c` folder)

These examples use [cgo](https://golang.org/cmd/cgo/) to enable calls to C.

- Calling a C snippet in the cgo comment: [c_in_comment](https://github.com/draffensperger/go-interlang/tree/master/go_to_c/c_in_comment/main.go)
- Calling a C statically-linked library (`.a` file): [static_c_lib](https://github.com/draffensperger/go-interlang/tree/master/go_to_c/static_c_lib)
- Calling a C dynamically-linked library (`.so` or `.dylib`): [dynamic_c_lib](https://github.com/draffensperger/go-interlang/tree/master/go_to_c/dynamic_c_lib)

## Calls from Go to C++ (`go_to_cxx` folder)

C++ has more complex calling conventions (e.g. function overloading, inheritance, templates) and so it uses [name mangling](https://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B) which adds a step when calling it from Go. Below are ways to do it.

 That allows any language that can call C dynamic libraries to call Go.

- Call from Python via [ctypes](https://docs.python.org/2/library/ctypes.html):
  [python_to_go.py](https://github.com/draffensperger/go-interlang/blob/master/dyn_langs_to_go/python_to_go.py)
- Call from Node.js via [ffi](https://github.com/node-ffi/node-ffi) npm module:
  [nodejs_to_go.js](https://github.com/draffensperger/go-interlang/blob/master/dyn_langs_to_go/nodejs_to_go.js)
- Call from Ruby via [ffi](https://github.com/ffi/ffi) gem: [ruby_to_go.rb](https://github.com/draffensperger/go-interlang/blob/master/dyn_langs_to_go/ruby_to_go.rb)
- Call from Java via [JNA](https://github.com/java-native-access/jna): [JavaToGo.java](https://github.com/draffensperger/go-interlang/blob/master/dyn_langs_to_go/java_to_go/src/main/java/javatogo/JavaToGo.java)

# Cross-language call benchmarks

There is a cost to calling between languages a Go to C call is about 50x slower
than a pure Go call and a Ruby FFI call is about 30x slower than a pure Ruby
call. For more details, see the [benchmarks](https://github.com/draffensperger/go-interlang/tree/master/benchmarks) section.

# Helpful Links

Cgo documentation: [golang.og/cmd/cgo/](https://golang.org/cmd/cgo/)

Documentation for `go` command (see especially `go build` section and "Calling between Go and C"):
[golang.org/cmd/go/](https://golang.org/cmd/go/)

SWIG Documentation: [swig.org](http://swig.org/)

SWIG Go examples: [github.com/swig/swig/tree/master/Examples/go](https://github.com/swig/swig/tree/master/Examples/go)

Gccgo documentation: [golang.org/doc/install/gccgo](https://golang.org/doc/install/gccgo)

# License

The code in this repo is [MIT Licensed](http://opensource.org/licenses/MIT).

repository: dexterchan/go-interlang

repo_name: dexterchan/go-interlang


text:
# DragonBorn

Dungeons & Dragons 5th edition character creation and tracker App designed especially with tablet and mobile devices in mind.

## Create

Making a new character is simple and easy with a step-by-step walkthrough to help you build a fun, memorable hero!

## Track

Keep a tab on all your character's stats, gear, spells and more as you play!

## Guide

Track the progress of your campaign and keep all your players synced!

### Current Release Plan

Phase I: Assisted hero creation and more interactive gear/weapon/spell section in character sheet

Phase II: Tracking character play during a campaign

Phase III: DM edition with guide section to manage a campaign

### Interested in Contributing?

Dragonborn is a React/Redux, Typescript application using Firebase as a backend. If you have experience working with these and want to help, feel free to reach out!

repository: ckoukoutchos/dragonborn

gha_language: TypeScript

gha_license_id: MIT

repo_name: ckoukoutchos/dragonborn


text:
---
layout: work
title: Conversation seat II
tags:
  - work
type:
  - speculative
retailer:
  - VSOP
exhibitions: First shown at 'Collect' at the Saatchi Gallery, London, 2010.
collections:
order: 200
stock:
menus:
  - work
  - toCommission
date: 2011-01-01
social: Conversation seat II
awards:
thumbnail: //images.quru.com/image?src=/kwf/KWFConversationSeatII.jpg&width=175&height=175&fill=auto&top=0.075&bottom=0.95938
headimage: //images.quru.com/image?src=kwf/KWFConversationSeatII/Conversation%20seat%20II%20d.jpg&icc=srgb&strip=0
otherimages:
  - //images.quru.com/image?src=kwf/KWFConversationSeatII/Conversation%20seat%20II%20c.jpg&icc=srgb&strip=0
  - //images.quru.com/image?src=/kwf/KWFConversationSeatIISat.jpg
  - //images.quru.com/image?src=/kwf/KWFConversationSeatII.jpg
  - //images.quru.com/image?src=/kwf/Conversation+seat.jpg
summary: A one-off, rippled ash seat for two people in ‘conversation’.
houzzcategory: Indoor Benches

---
_1350mm wide/long x 430mm deep x 1350mm high, (53” x 17” x 53”)_

A one-off in rippled ash with a white wax oil finish.

A seat designed for two people in ‘conversation’. It is a play on the dialogue between two separate chairs when bought together - symbolised by the two high-backed ends set at opposing angles, both looking out and in, that are linked by one continuous seating plane.

This piece is the evolution of a design resulting from a ‘Creative award’ given by South East Arts. It is now currently on show with and available from [VSOP](https://www.vsopprojects.com/ "VSOP, New York") in Greenport, New York.


text:
Workstation End-to-End Tests
============================

This folder houses all end-to-end tests for the Workstation product configuration.

# Build

```
fx set workstation_eng.chromebook-x64 --release --args=flutter_driver_enabled=true

fx build
```

# Run
## Emulator

```
fx test --e2e -o ermine_session_shell_e2e_test
```

## Atlas

### Prerequisite
- A paved Atlas - follow [this guide](https://fuchsia.dev/fuchsia-src/development/hardware/chromebook) if needed

```
fx serve-remote --tunnel-ports=9095,9096,9097,9098,9099

env FUCHSIA_PROXY_PORTS=9095,9096,9097,9098,9099 fx test -f -o --e2e experiences_ermine_smoke_e2e_test
```

repository: gnoliyil/fuchsia

branch_name: refs/heads/main

repo_name: gnoliyil/fuchsia


text:
# internet-check
Bash script to check internet connection
Uses zenity for alert messages
Uses ping to check internet connection

# Usage
```
$ chmod +x internet-check.sh
$ ./internet-check.sh [-d] [-c] [-i] [-p PING_ADDRESS]
```
  -d  Alert if internet *disconnects* and **exit**

  -c  Alert if internet *connects* and **exit**

  -i  **Do not exit** after connect/disconnect. If connected, continue check for disconnect and vise versa. To be used for continuous background operation

# Usage as a startup application

- Open your startup appliction editor and select add command
- Browse to internet-check.sh
- Add argumets -d -i
- Redirect all output to /dev/null

As shown below :
>  /[path to internet-check.sh]/**internet-check.sh -d -i &>/dev/null**

repository: renjithis/internet-check

repo_name: renjithis/internet-check


text:
# Nand2Tetris Assembler
Assembler for Hack Computer's Machine Language written in C++

## Features
1. Convert the Assembly code for Software Simulated computer (Hack) into its Binary equivalent.
2. Supports Variables and Labels in the Language
3. Support Removal of Comments.

## Checklist
- [x] Instructions Commands (A_Command, C_Command, L_Command)
- [x] SymbolTable (Variables)
- [x] SymbolTable (Labels)
- [x] Comments (Single Line)
- [ ] Comments (Multi Line)

## Usage
1. Clone the master git repository:
`git clone --recursive https://github.com/iamarshsingh/nand2tetris`

2. Navigate to `./Assembler/src` directory and execute the makefile:
`./make`

3. Produce the binary executables,
`./make assembler`

4. Now you can convert the Asm files into binaries,
`./assembler fileName.asm`

Sample Assembly files along with correct outputs are provides in `./Assembler/tests`


text:
# Pizza Time!

#### Written by Maxwell Meyer

## Applied Technologies

This project was built using:

- HTML
- CSS
- Bootstrap
- Javascript
- jQuery
- GIT/Terminal
- Github

## Description/Goals

The user will be able to build their own pizza using any unique combination of the available toppings, and see how much the pizza will cost based on their chosen combination and size.

## Setup

1. Follow link to my Github repo
2. Alternatively, clone the repository from GH via [this link]()
3. Navigate to the root directory of the newly cloned project
4. Open the index.html file in the browser via live server

## Specifications:

```
Describe: Pizza object constructor (Pizza());

Test: "Should correctly initialize a new pizza object"

Code: let testPizza = new Pizza();

Expect: testPizza.toEqual({price: undefined, toppings: undefined, size: undefined})

```

```

 Describe: calcSize() method for Pizza objects (Pizza.prototype.calcSize());

 Test: "Should determine size cost of a pizza based on pizza size input"

 Code: let testPizza1 = new Pizza([], "medium");
       testPizza1.calcSize();

 Expect: testPizza1.toEqual({price: 2500, toppings: Array(0), size: "medium"})

```

```

 Describe: calcSize() method for Pizza objects (Pizza.prototype.calcSize());

 Test: "Should determine size cost of a pizza based on pizza size input"

 Code: let testPizza2 = new Pizza([], "large");
       testPizza2.calcSize();

 Expect: testPizza2.toEqual({price: 2750, toppings: Array(0), size: "large"})

```

```

 Describe: calcSize() method for Pizza objects (Pizza.prototype.calcSize());

 Test: "Should determine size cost of a pizza based on pizza size input"

 Code: let testPizza3 = new Pizza([], "family");
       testPizza3.calcSize();

 Expect: testPizza3.toEqual({price: 21000, toppings: Array(0), size: "family"})

```

```
 Describe: calcToppings() method for Pizza objects (Pizza.prototype.calcToppings())

 Test: "Should update the cost of the pizza object according to the quantity of selected toppings based on user input"

 Code: let testPizza4 = new Pizza([1], "undefined");
       testPizza4.calcToppings();

 Expect: testPizza4.toEqual({price: 100, toppings: Array(1), size: "undefined"})

```

```
 Describe: calcToppings() method for Pizza objects (Pizza.prototype.calcToppings())

 Test: "Should update the cost of the pizza object according to the quantity of selected toppings based on user input"

 Code: let testPizza5 = new Pizza([6], "undefined");
       testPizza5.calcToppings();

 Expect: testPizza5.toEqual({price: 600, toppings: Array(6), size: "undefined"})

```

```
 Describe: use calcSize() and calcToppings() methods in conjunction to determine the total cost for Pizza objects (Pizza.prototype.calcSize(), Pizza.prototype.calcToppings())

 Test: "Should determine the total cost of a pizza object based on both input size, and input toppings"

 Code: let testPizza6 = new Pizza([5], "family");
       testPizza6.calcSize();
       testPizza6.calcToppings();

 Expect: testPizza6.toEqual({price: 21500, toppings: Array(5), size: "family"})

```

## Known Bugs

Some customers have complained about the price of the pizzas.

## License Information

You can find all applicable licensing information [here](https://opensource.org/licenses/MIT).

## Contact me!

Maxwell Meyer

<EMAIL_ADDRESS>

repository: MaxwellMeyer/pizza-proj

repo_name: MaxwellMeyer/pizza-proj


text:
# Immutable State

Using immutable objects whenever possible results in robust implementations. Function calls and state changes become predictable.
Using value objects instead of raw data structures like arrays or plain strings adds type safety, acts as documentation and makes code much more
readable. All very important properties for long-lived applications that are constantly reshaped.

The [EventEngine\Data](https://github.com/event-engine/php-data) package provides useful helpers to speed up development of immutable objects.
In fact, when using the Prototyping or Functional Flavour **all application state should be immutable**.

{.alert .alert-warning}
For the OOP Flavour the only exception are Aggregate Roots. But even then it's recommended
to use a single internal state property within the AR that references immutable state and is the only mutable part of the object.

## PHPStorm Templates

Writing immutable value objects in PHP is painful because you need a lot of boilerplate code and always have the risk to
introduce bugs due to typos.

Libraries like [FPP](https://github.com/prolic/fpp) aim to simplify the task of writing immutable objects and combine them to complex structures.

{.alert .alert-dark}
FPP works quite well and you can use it together with Event Engine.

However, if you don't want to learn another meta language but still want to avoid writing all the boilerplate that comes along with immutable objects,
`EventEngine\Data` combined with PHPStorm Live Templates might be for you.

{.alert .alert-info}
Keep in mind that both FPP and EventEngine\Data are only suggestions. You don't have to use them. It's also fine if you prefer working with a serializer library.

The `EventEngine\Data` package contains a set of live templates specifically designed to work together with the `EventEngine\Data\ImmutableRecord`.

You can import the templates by following official [PHPStorm instructions](https://www.jetbrains.com/help/phpstorm/sharing-live-templates.html).
Please find the `settings.zip` [here](https://github.com/event-engine/php-data/blob/master/.env/PHPStorm/settings.zip).

## Scalar Value Objects

Each scalar PHP type (string, int, float, bool) has a corresponding template that you can access by typing `vo_<scalar type>` in a PHP file.

1. Create an empty value object class.
2. Invoke the template in the class body.
3. Define the name of the inner property.

See examples:

vo_string

vo_int

vo_float

vo_bool

## Specialized Scalar Types

### vo_uuid

A UUID value object template is included, too. It works with the well known [ramsey/uuid](https://github.com/ramsey/uuid) library.
Along with the `vo_uuid` template you also get a `use_uuid` template. Use them in combination like shown in the example:

![Value Object Template vo_uuid](img/VO/vo_uuid.gif)

### vo_datetime

The `vo_datetime` is another specialized scalar value object template. It uses PHP's built-in `\DateTimeImmutable`, ensures
`UTC` is used as well as a standard format for from/to string conversion.

The `FORMAT` constant can be used to change the format. By default it is `'Y-m-d\TH:i:s.u`, which is the same format as of the `Message::createdAt` property.

![Value Object Template vo_datetime](img/VO/vo_datetime.gif)

## List / Collection

If you need a list or collection with all items being of the same type you can use the `vo_collection` template. It generates quite a lot of code so that you can work with the list
out-of-box. Feel free to add more methods, either to the template or after code generation if it is specific to the concrete class.

The template needs two information:

1. The item class. The item class should at least have a `public static from<RawType>($rawType)` method, a `public to<RawType>()` method and a `public equals(ItemClass $other): bool` method.
    Of course all immutable objects generated with our VO templates can be used as item class.
2. The raw type of the items, one of: `string, int, float, bool, array`

![Value Object Template vo_collection](img/VO/vo_collection.gif)

{.alert .alert-warning}
If you use the `push()` and `pop()` methods, keep in mind that the list is immutable. That said, only the returned list contains the change (item appended, last item removed).
This also means, that you have to use `last()` before `pop()` to get the last item of the list.

## Complex Types

Immutable objects can have arbitrary complexity. So far we only learned about single value objects and lists. What's missing is the ability to combine them to complex objects/types.
A simple PHPStorm Live Template is not suitable for the job. Hence, `EventEngine\Data` provides the interface `ImmutableRecord` and the trait `ImmutableRecordLogic` to help you out.

{.alert .alert-info}
When you use PHPStorm and import the **settings.zip** linked above, you have a new file template **ImmutableRecord** that you can choose when adding a new class to the project.
The template for **getter** methods is also aligned. **ImmutableRecord** requires getter methods that exactly match with the properties they provide read access to. Hence, the **get** prefix
is removed in the file template. The example shows both in action.

These are the steps required to get a working `ImmutableRecord`:

1. Create a class that implements `ImmutableRecord` and uses the `ImmutableRecordLogic` trait (either use the file template or create the class by hand).
2. Add properties and their types. You can use the live template `record_field`, which also adds a constant for each property to avoid typos.
3. Generate getter methods for the properties with appropriate return types. The getter methods should be named like the properties.

{.alert .alert-info}
**ImmutableRecordLogic** relies on the return types of getter methods to know which property type class should be used when creating a record instance from raw data.

![Immutable Record](img/VO/immutable_record.gif)

### fromArray vs. fromRecordData

By default `ImmutableRecordLogic` provides two ways to instantiate an object:
- `fromArray()`: create the record from an array containing raw data, especially useful when mapping user input or database results.
- `fromRecordData()`: create the record from value objects.

```php
<?php
declare(strict_types=1);

namespace ProophExample;

use ProophExample\ValueObject\GivenName;
use ProophExample\ValueObject\Person;
use ProophExample\ValueObject\UserId;
use Ramsey\Uuid\Uuid;

$john = Person::fromArray([
    Person::USER_ID => Uuid::uuid4()->toString(),
    Person::NAME => 'John',
    Person::AGE =>  42
]);

$jane = Person::fromRecordData([
    Person::USER_ID => UserId::generate(),
    Person::NAME => GivenName::fromString('Jane')
]);

```

{.alert .alert-info}
It is recommended to add named constructors to a record class
using the [Ubiquitous Language](https://martinfowler.com/bliki/UbiquitousLanguage.html){: class="alert-link"} of the domain.
Those methods can use `fromRecordData()` internally.

For example we could add a `register()` method to our `Person` class. The `UserId` is generated internally and `Age` is nullable and is not required by default.

```php
<?php
declare(strict_types=1);

namespace ProophExample\ValueObject;

use EventEngine\Data\ImmutableRecord;
use EventEngine\Data\ImmutableRecordLogic;

final class Person implements ImmutableRecord
{
    use ImmutableRecordLogic;

    public const USER_ID = 'userId';
    public const NAME = 'name';
    public const AGE = 'age';

    /**
     * @var Age|null
     */
    private $age;

    /**
     * @var GivenName
     */
    private $name;

    /**
     * @var UserId
     */
    private $userId;

    public static function register(GivenName $givenName): self
    {
        return self::fromRecordData([
            self::USER_ID => UserId::generate(),
            self::NAME => $givenName
        ]);
    }

    /* ... getter methods */
}

```

### Nullable Properties

{.alert .alert-warning}
**ImmutableRecordLogic** validates the given data. If a property (or to be more precise the return type of the corresponding getter method) is not marked as nullable, then it throws an exception.
Property data validation is delegated to the property type classes. You don't have to replicate it.

### Array Properties

It's recommended to use the `vo_collection` live template (see above) to generate lists/collections as immutable types. Such a type class can then be used for a record property.
However, in some cases you might want to use a plain php array instead of an extra class to keep a list of items in a record property. In that case you have to add a `private static arrayPropItemTypeMap(): array` method,
that returns a mapping of **property name to type class**. PHP does not provide a way to specify array item types in return types (yet). Hence, `ImmutableRecordLogic` needs a hint.

Let's look at an example. We a add a `friends` property to our `Person` record, define array as property/return type and provide a mapping that friends are also of type `Person`.

![Immutable Record with array prop](img/VO/immutable_record_array_prop.gif)

### Initialize Properties

If we replace the plain array type of the previous example with the `FriendsList` generated earlier, our `Person` class would look like this:

```php
<?php
declare(strict_types=1);

namespace ProophExample\ValueObject;

use EventEngine\Data\ImmutableRecord;
use EventEngine\Data\ImmutableRecordLogic;

final class Person implements ImmutableRecord
{
    use ImmutableRecordLogic;

    public const USER_ID = 'userId';
    public const NAME = 'name';
    public const AGE = 'age';
    public const FRIENDS = 'friends';

    /**
     * @var FriendsList
     */
    private $friends;

    /**
     * @var Age|null
     */
    private $age;

    /**
     * @var GivenName
     */
    private $name;

    /**
     * @var UserId
     */
    private $userId;

    public static function register(GivenName $givenName): self
    {
        return self::fromRecordData([
            self::USER_ID => UserId::generate(),
            self::NAME => $givenName
        ]);
    }

    /**
     * @return FriendsList
     */
    public function friends(): FriendsList
    {
        return $this->friends;
    }

    /* ... other getter methods */
}

```

{.alert .alert-light}
Again: no extra mapping required! Try to favor collection classes over plain arrays!

When a new person registers for our service their friends list would be empty. Hence, we don't want to require that property in the `register()` named constructor.
On the other hand we also don't want to make the `friendsList` property nullable. Iterating over an empty list results in no iteration at all. No need to check against null first.
To solve the conflict we can override the empty `init()` method of `ImmutableRecordLogic`. The method is called after all properties have been set, but before the null check is performed
(which would result in an exception for the current `Person::register()` implementation).

```php
<?php
declare(strict_types=1);

namespace ProophExample\ValueObject;

use EventEngine\Data\ImmutableRecord;
use EventEngine\Data\ImmutableRecordLogic;

final class Person implements ImmutableRecord
{
    use ImmutableRecordLogic;

    public const USER_ID = 'userId';
    public const NAME = 'name';
    public const AGE = 'age';
    public const FRIENDS = 'friends';

    /**
     * @var FriendsList
     */
    private $friends;

    /**
     * @var Age|null
     */
    private $age;

    /**
     * @var GivenName
     */
    private $name;

    /**
     * @var UserId
     */
    private $userId;

    public static function register(GivenName $givenName): self
    {
        return self::fromRecordData([
            self::USER_ID => UserId::generate(),
            self::NAME => $givenName
        ]);
    }

    private function init(): void
    {
        if(null === $this->friends) {
            $this->friends = FriendsList::emptyList();
        }
    }

    /* ... getter methods */
}

```

{.alert .alert-danger}
Never override `__construct()` of **ImmutableRecodLogic**!
Always use the `init()` hook for setting default values.

repository: event-engine/docs

gha_language: PHP

repo_name: event-engine/docs


text:
Serenity is an embedded ruby for OpenOffice documents (.odt files). You provide an .odt template with ruby code inside a special markup and the data and Serenity generates the document. If you know erb all of this should sound familiar.

Pure Images Support
===================
You must put a mock image in your odt template and give it a name. That name will be used to replace the mock image for the actual image. You can also assign any properties you want to the mock image and they will be kept once the image is replaced. Your Serenity Class then need to have @images instance variable, which need to look like this:

@images = {"image_name_1" => '/path/to/the/real/image'}

Important Changes
=================

As of version 0.2.0 serenity is using instance variables in the templates. In previous versions, your instance variables would be converted to local before passing to the template, so while in the code you had `@title = 'Serenity'`, you had to put `{%= title }` in the template to get serenity to work. This has now changed and you need to use instance variables in the templates: `{%= @title }`. Honestly, I don't know why I did it this way in the first place, considering that people are used to instance variables in templates from rails.

Usage
======

Serenity is best demonstrated with an example. The first picture shows the template with the ruby code, next image shows the generated document. The template, output and the sample script can be found in the showcase directory.

![Serenity template](http://github.com/kremso/serenity/blob/master/showcase/imgs/serenity_template.png?raw=true)

The image above is a screenshot of showcase.odt from the [showcase](http://github.com/kremso/serenity/blob/master/showcase) directory. It's a regular OpenOffice document with ruby code embedded inside a special markup. That ruby code drives the document creation. You can use conditionals, loops, blocks — in fact, the whole ruby language and you can apply any OpenOffice formatting to the outputted variables or static text.

The second line in the template is `{%= @title%}` what means: output the value of variable title. It's bold and big, in fact, it's has the 'Heading 1' style applied. That variable will be replaced in the generated document, but it will still be a 'Heading 1'.

You can now take that template, provide the data and generate the final document:

    require 'rubygems'
    require 'serenity'

    class Showcase
      include Serenity::Generator

      Person = Struct.new(:name, :items)
      Item = Struct.new(:name, :usage)

      def generate_showcase
        @title = 'Serenity inventory'

        mals_items = [Item.new('Moses Brothers Self-Defense Engine Frontier Model B', 'Lock and load')]
        mal = Person.new('Malcolm Reynolds', mals_items)

        jaynes_items = [Item.new('Vera', 'Callahan full-bore auto-lock with a customized trigger, double cartridge and thorough gauge'),
                        Item.new('Lux', 'Ratatata'),
                        Item.new('Knife', 'Cut-throat')]
        jayne = Person.new('Jayne Cobb', jaynes_items)

        @crew = [mal, jayne]

        render_odt 'showcase.odt'
      end
    end

The key parts are `include Serenity::Generator` and `render_odt`. The data for the template must be provided as instance variables.

Following picture shows the generated document. It's a screenshot of the showcase_output.odt document from the [showcase](http://github.com/kremso/serenity/blob/master/showcase) directory.

![Generated document](http://github.com/kremso/serenity/blob/master/showcase/imgs/serenity_output.png?raw=true)

Installation
============

    gem install serenity-odt

Yeah, serenity is already taken on gemcutter.

Creating templates
===================

Templates are created directly in OpenOffice. Ruby code is enclosed in special markup:

+ `{%= %}` is for ruby code which should be output to the final document. `to_s` is applied to anything found inside this markup
+ `{% %}` is for everything else — loops, ifs, ends and any other non-outputting code

Any special formatting should by applied directly on the markup. E.g. if you need to ouput the value of variable title in bold font, write `{%= title %}`, select in in OpenOffice and make it bold. See the showcase.odt for more examples.

Contact
=======

kramar[dot]tomas[at]gmail.com

repository: theoo/serenity

gha_language: Ruby

repo_name: theoo/serenity


text:
# Parallel Point Cloud Processing and Segmentation
## Ardra Singh (ardras), Rohan Varma (rohanv)

Proposal

Checkpoint Report

## Introduction and Brief Overview:

In our project, we study spatially local computation on 3-d pointclouds of sizes in the millions and present two main ways with which we can increase speed/throughput on a GPU while preserving the performance accuracy of the end result. By spatially-local, we mean that each pixel independently, performs a computation based on the points in its local neighborhood.
There are two main contributions we want to highlight here. First, we show a mapping of approximate local neighborhoods to CUDA thread blocks to accelerate GPU throughput while preserving accuracy.
Secondly, we implement a fast parallel version of the contour-preserving resampler presented in this paper to subsample the pointcloud (preserving just 5% of the points does well!) while preserving important features. This helps to alleviate the cost of the high redundancy, while still preserving output accuracy.

Specifically we chose to study the critical problem of segmentation which is an important step in many computer vision application pipelines. That is,  “clustering” point clouds into multiple homogeneous regions, the points in the same region will have the same properties. This problem has many applications in robotics such as intelligent vehicles, autonomous mapping, navigation, household tasks and so on. Point clouds are a particular challenge because they often have uneven point density, high redundancy, and are noisy with many outliers.

Since it not clear what is the best “metric” for evaluating segmentation, we build a simple object detector (by computing features and finding the nearest neighbor in a pre-computed object feature database). On a high level, we say a segmentation of good quality, if it’s able to reliably detect objects which we have trained upon. We would like to emphasize here, that the object detection is not the main focus of our project. Instead, we show how we can perform fast processing of point-cloud data on a GPU.

We primarily use the RGB-D Object Database which has point clouds of scenes with objects like below as well as models of the objects themselves which we use to train features (using the point cloud library).

## Design 1:

The block diagram of the initial design is as above. We use the quick shift algorithm to perform the image segmentation. It is amenable to parallelism because of it’s computational characteristics and memory access patterns as described below.

### Quick Shift Segmentation:

The quick shift segmentation occurs in 2 steps, it first computes a local density estimate before assigning a parent to every node. Both steps are spatially local since each point performs a computation by iterating over its local neighborhoods. We choose the neighborhood sizes to not only ensure accuracy but also to control the granularity of the segmentation.

```
function compute_density() {
  for each point p in pointcloud:
    for each neighbor x in neighborhood(p):
      density[p] += dist_estimate(p,x);
    end
  end
}
```

```
function construct_tree(){
  for each point p in pointcloud:
    for each neighbor x in neighborhood(p):
      if(density[x] > density[p] && dist(x,p) < min_dist)
        parents[p] = x;
        min_dist = dist(x,p)
    end
  end
}

```
### Implementation Details:
The first contribution is to leverage the spatial local characteristics of the computation to voxelize the pointcloud and map each voxel to a CUDA thread block. This way every point in a voxel performs the same computation over its neighborhood and possesses the same memory access patterns. This change to the original framework makes it well suited for a fast CUDA implementation. We voxelize by cubing the minimum bounding box of the point cloud. The neighborhood of a voxel is its neighboring voxels.
We note that to compare to the sequential version fairly, we use a k-d tree (efficient for spatially local data access) to store the point cloud.

## Design 2:

After our first design, we wanted to accelerate the segmentation by taking advantage of the redundancy in the point cloud. i.e We ask, are we processing more points than we need to?

Here we introduce our second main contribution, a resampling block into our design. The sampling step occurs in two stages, we first need to assign an importance weight to each point (effectively a local high pass filter, again a spatially local computation), before performing a weighted sampling of the points. The latter can be implemented quickly with the help of CUDA  thrust libraries. It turns out we can subsample by preserving up to 5% of the total number of points and preserve detection performance.

### Importance Weight Sampling Algorithm:
We show very basic pseudocode below to show the structure of the weight assignment algorithm. As can be seen below, the weight computation is again a spatially local computation since each point iterates over its local neighborhood to compute its importance weight.

```
function compute_weight() {
  for each point p in pointcloud:
    weighted_sum =0;
    for each neighbor x in neighborhood(p):
      weighted_sum += weighted_neighbor(p,x);
    end
    weight[p] = dist(x, weighted_sum)
  end
}
```
We then sample points according to these weights. We mention a caveat here; that is, our weighted CPU-based sequential sampler, performs the sampling naively with O(KN) (K is the number of samples). (The sampler pre-computes a rolling sum of the normalized weights and then samples a uniform random number and see in which bin it falls (binary search)). While we implement this same algorithm on CUDA to perform the sampling, this is not the fastest way to perform weighted sampling on a CPU. A faster CPU-based implementation would be based on the Alias-Walker method which samples in O(K+N).
Another interesting point is that the sampler helps to smoothen the uneven density of points across the space.

## Results:
Below is an image of the result of the segmentation on the kitchen scene. The original point cloud has around 3 million points and we preserve only 80000 samples. We also show the output of the object detection phase for a cereal box using the segments generated by our point cloud segmentation framework. The reported results correspond to running our implementations on the GHC cluster which has 8 2-way hyperthreaded cores for the multithreaded implementation, and the NVidia GeForce GTX1080 GPU with CUDA capability 6.0.

### GPU vs. CPU:
Our main focus was to maximize segmentation throughput on a GPU, and so, although we optimized the CPU implentation with openMP pragmas to run on 16 threads, it is still not the best possible CPU implementation.

The graph shown below compares the runtime for various computation steps of the segmentation process for our openMP and CUDA implementations. The overall speedup of the CUDA implementation over the openMP implementation increases from 8X for 100k points to ~20X for 2 million points. This non-linear increase in speedup is in sync with what we expect since increasing the number of points increases the point density which in turn increases per voxel computation at a cubic order. Also, the speedup of the sampling step is more than 1000X because we use highly optimized thrust library functions for the parallel scan and gather operations.

### Time with Sampling vs. Without Sampling:
This graph compares speedup of CUDA with and without sampling over the multithreaded openMP implementation. Without sampling the CUDA implementation is only 2X faster, however incorporating the sampling step in CUDA boosts the speedup up to ~20X.
We note that the overhead of sampling is largely negligible compared to the drastic speedup of the segmentation block. We note that we sample a range of points from 10k to 100k points which preserves detection performance. In addition, sampling is especially useful when doing coarse segmentations (since we need to search over larger neighborhoods, higher density would imply extremely expensive computations).

### Comparison with Segmentation of an Image:

Images are highly regular as opposed to point clouds which exhibit high irregularity. Here, we intend to analyze how much the uneven density of points in the space affects our performance. This unevenness affects the number of points each block/voxel processes which in turn leads to extremely skewed workload imbalance patterns. We equalize the number of pixels in the image and the number of points in the point cloud for fair comparison.

Example of image segmentation, original image and segmented image:

## Conclusion

In conclusion, we studied the problem of fast parallel segmentation for point clouds and implemented frameworks with which we were able to segment point clouds consisting of millions of points in a few seconds. Specifically, we design both a multi-threaded CPU and an optimized GPU implementation which gives us speedup on the order of 20x. A key contribution is the incorporation of a subsampling stage preceding the actual segmentation which helps to further accelerate the segmentation stage without compromising segmentation quality.

## References

1. Fast Resampling of 3D Point Clouds via Graphs: https://arxiv.org/abs/1702.06397
2. Really quick shift: Image segmentation on a GPU http://www.vision.cs.ucla.edu/papers/fulkersonS10really.pdf
3. Min-Cut Based Segmentation of Point Clouds http://www.cs.princeton.edu/~funk/s3dv09.pdf
4. 3D Point Cloud Segmentation: A survey http://ieeexplore.ieee.org/document/6758588/

repository: dkoguciuk/pcseg

repo_name: dkoguciuk/pcseg


text:
# pokeapi-type-generator

Generate Typescript types for each resource in [PokeAPI](https://pokeapi.co/docs/v2.html/). It downloads the relevant JSON docs from the [docs site](https://github.com/PokeAPI/pokeapi.co/tree/master/src/docs), parses each file, and builds a module `pokeapi-js-wrapper` with exported interfaces for each resource. Feel free to open an issue if anything needs to be improved! If this gets used enough, it might be useful to contribute to [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped).

## Usage

### Option 1: Running it yourself

- Clone the repository
- Run `yarn` (or `npm install`) to install necessary packages
- Use `yarn start` to output the `index.d.ts` file to the `generated-types/` top-level directory
- Fix up some missing styles related to [known issues](#knownissues)

### Option 2: Copy the `index.d.ts` file from `generated-types` directory

- Copy/paste the generated output. NOTE: it could be out of date, so it's probably better to just run it yourself

## Known Issues

- There is at least one instance of incorrectly typed properties that I attempt to fix in code
  - `Ability` resource, property `effect_entries` improperly uses `names` instead of `VerboseEffect`
- Resources `MoveDamageClass` and `MoveMetaData` appear as property types, but are not listed in the docs
  - You will need to define `MoveDamageClass` as `NamedAPIResource`
  - You will need to define `MoveMetaData` according to the `meta` property in the `Moves` [resource](https://pokeapi.co/docs/v2.html#moves)
- Null/optional types
  - Unfortunately the docs do not provide any reliable information about when a field could be null or not. Without some enhancements to the docs, I'm not sure how much can be done to add nullability.

repository: ccabrales/pokeapi-type-generator

repo_name: ccabrales/pokeapi-type-generator


text:
First player to reach 100 wins.

## Technologies Used

* HTML
* CSS
* jQuery

## Specs

| Behavior |  Input   |  Output  |
|----------|:--------:|:--------:|
|Users begin with a Total Score of 0 and the score is displayed on the screen. | n/a | score of 0. |
|User will push roll die button and a random number between 1-6 will be displayed in output section | click roll button | either 1-6 |
|RESULTING ROLL IS A ONE|||
|Program will evaluate if the result is 1 or not a 1. If the result is a 1 the program will clear the player's tempScore| 1 | score of 0 |
|RESULTING ROLL IS NOT A ONE|||
|Program will evaluate if the result is not a 1. The program stores this value in a variable called tempScore.| 3 | N/A |
|Step A) Continuation of if the result is not a 1, the player can choose to hold by clicking a hold button.  If the user clicks hold, the program will add tempScore to the user's total score and display the new total score | Score is 0 and roll is 3 | Score = 3 |
|Step B) Continuation of if the result is not a 1, if the player does not "hold" they will click the roll die button. | click roll button | either 1-6 |
|The program will add the roll value to the tempScore variable| Total Score = 0, tempScore = 3, roll value = 5 | tempScore = 8 |
|Repeat steps A and B until player clicks hold button |||
|GAME END|||
|The first player's to have a total score of >= 100 will end the game!| Player 2 Total score = 100 | You Win! |

## Installation

* `$ git clone https://github.com/nrsantamaria/pig-dice-game`
* `$ cd pig-dice-game`
* `$ open index.html`

## Known Bugs
* n/a

## Support and contact details

_Please contact Nicole Santamaria at<EMAIL_ADDRESS>if you have any questions._

## License

*This software is licensed under MIT license.*

```
Copyright (c) 2017 Nicole Santamaria
```

repository: nrsantamaria/pig-dice-game

repo_name: nrsantamaria/pig-dice-game


text:
# dotfiles
Public configuration files used by ruby apps

# ⚠ This is now a private repo ⚠
Due to the Github IP Allow-Listing project, Trailhead had to:
* Remove all public repositories from `devforce`
* Move away from CodeClimate, due to SFCI migration

If you relied on any files in this repository to be public, please copy it into your own project.

### Rubocop configuration:
We're using rubocop as linter to keep our ruby code with the same format.

### Usage:
##### In your repo's Gemfile add this to the development section:
```
  gem 'rubocop-rails_config', '~> 0.2'
  gem 'rubocop-rspec'
```

##### In your repo's .gitignore add:
```
# Rubocop temporary files
.rubocop-https---*
```

##### In your repo's .codeclimate.yml add:
```
prepare:
  fetch:
    - url: 'https://raw.githubusercontent.com/airbnb/ruby/master/rubocop-airbnb/config/rubocop-style.yml'
      path: '.rubocop_airbnb.yml'
    - url: 'https://raw.githubusercontent.com/devforce/dotfiles/master/rubocop/rubocop_trailhead.yml'
      path: '.rubocop_trailhead.yml'
```
Code Climate configuration looks like this because rubocop is not allowed to follow links, so we download the file beforehand using the above.

##### In your repo's `.rubocop.yml` add:
```
inherit_from:
  - .rubocop_airbnb.yml
  - .rubocop_trailhead.yml
```
We inherit from a local file instead of directly from the remote so Codeclimate can read the file.

##### Add any Cop overides into your `.rubocop.yml`.
    Metrics/LineLength:
      Max: 42

##### In your repo add `.rubocop_airbnb.yml` with this content:
```
inherit_from:
  - https://raw.githubusercontent.com/airbnb/ruby/master/rubocop-airbnb/config/rubocop-style.yml
```

##### In your repo add `.rubocop_trailhead.yml` with this content:
```
inherit_from:
  - https://raw.githubusercontent.com/devforce/dotfiles/master/rubocop/rubocop_trailhead.yml
```
##### In your repo you can run rubocop on just your changed files:
```bash
git status --porcelain | grep M | xargs bundle exec rubocop
```
Or for just rb files:
```bash
git status --porcelain | grep M | grep '\.rb' | xargs bundle exec rubocop
```

repository: devforce/dotfiles

repo_name: devforce/dotfiles


text:
#  Creating an example AWS photo analyzer application using the AWS SDK for JavaScript (v3)

## Purpose
The cross-service example demonstrates how to build an app that analyzes nature images located in an Amazon Simple Storage Service (Amazon S3) bucket
by using the AWS Rekognition service. For example, the following image shows a lake.

![AWS Photo Analyzer](images/Lake1.png)

After the application analyzes this image, it creates this data:
*	Panoramic - 99.99971
*	Outdoors - 99.99971
*	Nature - 99.99971
*	Landscape - 99.99971
*	Scenery	 - 99.99971
*	Wilderness - 96.90007
*	Water - 93.501465
*	Lake - 87.28128

The application can analyze many images and generate reports for each image in a
separate Amazon S3 bucket, breaking the image down into a series of labels. In addition, this application uses Amazon Simple Email Service (Amazon SES)
to send emails with a link to each reports to the recipient. The app uses the following AWS services:

- [AWS Rekognition](https://aws.amazon.com/rekognition/)
- [Amazon Simple Storage Services (S3)](https://aws.amazon.com/s3/)
- [Amazon Simple Email Services (SES)](https://aws.amazon.com/ses/)

## Prerequisites

To build this cross-service example, you need the following:

* An AWS account. For more information see [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/overview.html).
* A project environment to run this Node JavaScript example, and install the required AWS SDK for JavaScript and third-party modules.  For instructions, see [Create a Node.js project environment](#create-a-nodejs-project-environment) on this page.
* At least one email address verified on Amazon SES. For instructions, see [Verifying an email address on Amazon SES](#verifying-an-email-address-on-amazon-ses).
* The following AWS resources:
    - An unauthenticated AWS Identity and Access Management (IAM) user role with the following permissions:
        - sns:*

**Note**: An unauthenticated role enables you to provide permissions to unauthenticated users to use the AWS Services. To create an authenticated role, see [Amazon Cognito Identity Pools (Federated Identities)](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html).

 For instructions on creating the minimum resources required for this tutorial, see [Create the resources](#create-the-resources) on this page.

## ⚠ Important
* We recommend that you grant this code least privilege, or at most the minimum permissions required to perform the task. For more information, see [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege) in the *AWS Identity and Access Management User Guide*.
* This code has not been tested in all AWS Regions. Some AWS services are available only in specific [Regions](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
* Running this code might result in charges to your AWS account. We recommend you destroy the resources when you are finished. For instructions, see [Destroying the resources](#destroying-the-resources).
* Running the unit tests might result in charges to your AWS account.
* This tutorial is written to work with the specific versions defined in the *package.json*. If you change these versions, the tutorial may not work correctly.

## Create the resources
You can create the AWS resources required for this cross-service example using either of the following:
- [The Amazon CloudFormation](#create-the-resources-using-amazon-cloudformation)
- [The AWS Management Console](#create-the-resources-using-the-aws-management-console)

### Create the resources using Amazon CloudFormation
To run the stack using the AWS CLI:

1. Install and configure the AWS CLI following the instructions in the AWS CLI User Guide.

2. Open the AWS Command Console from the *./photo-analyzer* folder.

3. Run the following command, replacing *STACK_NAME* with a unique name for the stack.
```
aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
```
**Important**: The stack name must be unique within an AWS Region and AWS account. You can specify up to 128 characters, and numbers and hyphens are allowed.

4. Open [AWS CloudFormation in the AWS Management Console](https://aws.amazon.com/cloudformation/), and open the **Stacks** page.

![ ](images/cloud_formation_stacks.png)

5. Choose the **Resources** tab. The **Physical ID** of the **IDENTITY_POOL_ID** you require for this cross-service example is displayed.

![ ](images/cloud_formation_resources_tab.png)

For more information on the create-stack command parameters, see the [AWS CLI Command Reference guide](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html), and the [AWS CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html).

### Create the resources using the AWS Management Console
#### Create an unauthenticated user role
1. Open [AWS Cognito in the AWS Management Console](https://aws.amazon.com/cloudformation/), and open the *Stacks* page.
2. Choose **Manage Identity Pools**.
3. Choose **Create new identity pool**.
4. In the **Identity pool name** field, give your identity pool a name.
5. Select the **Enable access to unauthenticated identities** checkbox.
6. Choose **Create Pool**.
7. Choose **Allow**.
8. Take note of the **Identity pool ID**, which is highlighted in red in the **Get AWS Credentials** section.

![ ](images/identity_pool_ids.png)

9. Choose **Edit identity pool**.
10. Take note of the name of the role in the **Unauthenticated role** field.

#### Adding permissions to an unauthenticated user role
11. Open [IAM in the AWS Management Console](https://aws.amazon.com/iam/), and open the *Roles* page.
12. Search for the unauthenticated role you just created.
13. Open the role.
14. Click the down arrow beside the policy name.
15. Choose **Edit Policy**.
16. Choose the **JSON** tab.
17. Delete the existing content, and paste the code below into it.
```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": "rekognition:DetectLabels",
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject",
                "s3:DeleteObject",
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": "ses:SendEmail",
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}
```
18. Choose **Review Policy**.
19. Choose **Save Changes**.

### Verifying an email address on Amazon SES
1. Open [AWS SES in the AWS Management Console](https://aws.amazon.com/SES/), and open the **Email Addresses** page.
2. Choose **Verify a New Email Address**.
3. Enter a working email address, and choose **Verify This Email Address**.
4. Open the email in your email application, and verify it.

## Create a Node.js project environment

1. Clone the [AWS Code Samples repo](https://github.com/awsdocs/aws-doc-sdk-examples) to your local environment.
See [the Github documentation](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository) for
instructions.

2. Run the following commands in sequence in the AWS CLI command line to install the AWS service client modules and third-party modules listed in the *package.json*:

```
npm install node -g
cd javascriptv3/example_code/cross-services/photo-analyzer
npm install
```
## Building the code
This app runs from the browser, so we create the interface using HTML and CSS.
The app uses JavaScript to provide basic interactive features, and Node.js to invoke the AWS Services.

### Creating the HTML and CSS
In **index.html**, the **head** section loads [JQuery](https://jquery.com/), [DataTables CDN](https://cdn.datatables.net/), and [BootStrap](https://getbootstrap.com/) libraries.
It also loads **stlyes.css**, which applies styles to the HTML,
and the **main.js**, which contains the following JavaScript and Node.js functions used in the app.

**Note**: **main.js** is a bundled file containing all the required JavaScript. You'll create this later in the tutorial.

The remaining code defines the interface features, including a table and buttons.

```html
<!DOCTYPE html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
    <script src="https://cdn.datatables.net/v/dt/dt-1.10.20/datatables.min.js"></script>
    <script src="./js/main.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.20/datatables.min.css"/>
    <link rel="stylesheet" href="./css/styles.css"/>

    <title>AWS Photo Analyzer</title>

    <script>
        function myFunction() {
            alert("The form was submitted");
        }
    </script>

</head>

<body>
<div class="container">

<h2>AWS Photo Analyzer Application</h2>
<p>Upload images to an S3 Bucket. Each image will be analysed!</p>

    <input id="imageupload" type="file" name="file" /><br/><br/>
    <button id="addimage" onclick="addToBucket()">Add image</button>
</div>
</div>
<div class ="container" >
    <br>

    <p>Select the following button to determine the number of images in the bucket.</p>

    <button onclick="getImages()">Get Images</button>
    <table id="myTable" class="display" style="width:100%">
        <thead>
        <tr>
            <th>Name</th>
            <th>Owner</th>
            <th>Date</th>
            <th>Size</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
        <tr>
            <th>Name</th>
            <th>Owner</th>
            <th>Date</th>
            <th>Size</th>
        </tr>
        </tfoot>
        <div id="success3"></div>
    </table>

</div>
<div class="container">
<p>You can generate a report that analyzes the images in the S3 bucket. You can send the report to the following email address. </p>
<label for="email">Email address:</label><br>
<input type="text" id="email" name="email" value=""><br>

<div>
    <br>

    <p>Click the followi ng button to obtain a report</p>
    <button onclick="ProcessImages()">Analyze Photos</button>
</div>
</div>
</body>
</html>
```
### Creating the JavaScript and Node.js
The **./js/libs/** folders contains a file for each of the AWS Service clients required. You must
replace "REGION" with your AWS Region, and replace "IDENTITY_POOL_ID" with the Amazon Cognito identity pool id
you created in [Create the resources](#create-the-resources) on this page. Here's an example of one of these client configuration files:

```javascript
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { RekognitionClient } from "@aws-sdk/client-rekognition";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an AWS Rekognition service client object.
const rekognitionClient = new RekognitionClient({
    region: REGION,
    credentials: fromCognitoIdentityPool({
        client: new CognitoIdentityClient({ region: REGION }),
        identityPoolId: IDENTITY_POOL_ID,
    }),
});

export { rekognitionClient };
```
In **./js/index.js**, you first import all the required AWS Service and third party modules, and set global parameters.
```javascript
import { DetectLabelsCommand } from "@aws-sdk/client-rekognition";
import { rekognitionClient } from "../libs/rekognitionClient.js";
import { ListObjectsCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { REGION, s3Client } from "../libs/s3Client.js";
import { sesClient } from "../libs/sesClient.js";
import { SendEmailCommand } from "@aws-sdk/client-ses";

// Set global parameters.
const BUCKET_IMAGES = "BUCKET_IMAGES";
const BUCKET_REPORTS ="BUCKET_REPORTS";
const EMAIL_SENDER_ADDRESS = "EMAIL_SENDER_ADDRESS"; // A verified Amazon SES email.
```

Next, you define functions for working with the table.
```javascript
// Load table parameters.
$(function() {
  $('#myTable').DataTable( {
    scrollY:        "500px",
    scrollX:        true,
    scrollCollapse: true,
    paging:         true,
    columnDefs: [
      { width: 200, targets: 0 }
    ],
    fixedColumns: true
  } );
} );

// Load images from Amazon S3 bucket to the table.
const loadTable = async () => {
  window.alert = function() {};
  try {
    const listVideoParams = {
      Bucket: BUCKET_IMAGES
    };
    const data = await s3Client.send(new ListObjectsCommand(listVideoParams));
    console.log("Success", data);
    for (let i = 0; i < data.Contents.length; i++) {
      console.log('checking')
      var t = $('#myTable').DataTable();
      t.row.add([
        data.Contents[i].Key,
        data.Contents[i].Owner,
        data.Contents[i].LastModified,
        data.Contents[i].Size
      ]).draw(false);
    };
  } catch (err) {
    console.log("Error", err);
  }
};
loadTable();

// Refresh page to populate table with latest images.
const getImages = async () => {
  window.location.reload();
};
window.getImages = getImages;
```
Next you define the functions for adding an image to the Amazon S3 bucket (*addToBucket*), analyzing the image (*ProcessImages*), creating the CSV report (*create_csv_file*),
uploading the report to the Amazon S3 bucket (*uploadFile*), and sending the specified recepient email notification about each image (*sendEmail*).
```javascript
const addToBucket = async () => {
  try{
    // Create the parameters for uploading the video.
    const files = document.getElementById("imageupload").files;
    const file = files[0];
    const key = document.getElementById("imageupload").files[0].name
    const uploadParams = {
      Bucket: BUCKET_IMAGES,
      Body: file,
      Key: key
    };

    const data = await s3Client.send(new PutObjectCommand(uploadParams));
    console.log("Success - image uploaded");
  } catch (err) {
    console.log("Error", err);
  }
};
// Expose function to browser.
window.addToBucket = addToBucket;

const ProcessImages = async () => {
  try {
    const listPhotosParams = {
      Bucket: BUCKET_IMAGES,
    };
    // Retrieve list of objects in the Amazon S3 bucket.
    const data = await s3Client.send(new ListObjectsCommand(listPhotosParams));
    console.log("Success, list of objects in bucket retrieved.", data);

    // Loop through images. For each image, retreive the image name,
    // then analyze image by detecting it's labels, then parse results
    // into CSV format.
    for (let i = 0; i < data.Contents.length; i++) {
      const key = data.Contents[i].Key;
      const imageParams = {
        Image: {
          S3Object: {
            Bucket: BUCKET_IMAGES,
            Name: key,
          },
        },
      };

      const lastdata = await rekognitionClient.send(
        new DetectLabelsCommand(imageParams)
      );
      console.log("Success, labels detected.", lastdata);
      var objectsArray = [];
      // Parse results into CVS format.
      const noOfLabels = lastdata.Labels.length;
      var j;
      for (j = 0; j < data.Contents.length; j++) {
        var name = JSON.stringify(lastdata.Labels[j].Name);
        var confidence = JSON.stringify(lastdata.Labels[j].Confidence);
        var arrayfirst = [];
        var arraysecond = [];
        arrayfirst.push(name);
        arraysecond.push(confidence);
        arrayfirst.push(arraysecond);
        objectsArray.push(arrayfirst);
      }
      // Create a CSV file report for each images.
      create_csv_file(objectsArray, key);
    }
  } catch (err) {
    console.log("Error", err);
  }
};
// Expose function to browser.
window.ProcessImages = ProcessImages;

// Helper function to create the CSV report.
function create_csv_file(objectsArray, key) {
  // Define the heading for each row of the data.
  var csv = "Object, Confidance \n";

  // Merge the data with CSV.
  objectsArray.forEach(function (row) {
    csv += row.join(",");
    csv += "\n";
  });
  // Upload the CSV file to Amazon S3 bucket for reports.
  uploadFile(csv, key);
}

// Helper function to upload reports to Amazon S3 bucket for reports.
const uploadFile = async (csv, key) => {
  const uploadParams = {
    Bucket: BUCKET_REPORTS,
    Body: csv,
    Key: key + ".csv",
  };
  try {
    const data = await s3Client.send(new PutObjectCommand(uploadParams));
    const linkToCSV =
      "https://s3.console.aws.amazon.com/s3/object/" +
      uploadParams.Bucket +
      "?region=" +
      REGION +
      "&prefix=" +
      uploadParams.Key;
    console.log("Success. Report uploaded to " + linkToCSV + ".");

    // Send an email to notify user when report is available.
    sendEmail(uploadParams.Bucket, uploadParams.Key, linkToCSV);
  } catch (err) {
    console.log("Error", err);
  }
};
// Helper function to send an email to user.
const sendEmail = async (bucket, key, linkToCSV) => {
  const toEmail = document.getElementById("email").value;
  const fromEmail = EMAIL_SENDER_ADDRESS; //
  try {
    // Set the parameters
    const params = {
      Destination: {
        /* required */
        CcAddresses: [
          /* more items */
        ],
        ToAddresses: [
          toEmail, //RECEIVER_ADDRESS
          /* more To-email addresses */
        ],
      },
      Message: {
        /* required */
        Body: {
          /* required */
          Html: {
            Charset: "UTF-8",
            Data:
              "<h1>Hello!</h1><p>Please see the the analyzed video report for " +
              key +
              " <a href=" +
              linkToCSV +
              "> here</a></p>",
          },
          Text: {
            Charset: "UTF-8",
            Data:
              "Hello,\\r\\n" +
              "Please see the attached file for the analyzed video report at" +
              linkToCSV +
              "\n\n",
          },
        },
        Subject: {
          Charset: "UTF-8",
          Data: key + " analyzed video report ready",
        },
      },
      Source: fromEmail, // SENDER_ADDRESS
      ReplyToAddresses: [
        /* more items */
      ],
    };
    const data = await sesClient.send(new SendEmailCommand(params));
    console.log("Success. Email sent.", data);
  } catch (err) {
    console.log("Error", err);
  }
};
```
**Important**: You must bundle all the JavaScript and Node.js code required for the app into a single
 file (**main.js**) to run the app. For instructions, see [Bundling the scripts](#bundling-the-scripts).

### Bundling the scripts
This is a static site consisting only of HTML, CSS, and client-side JavaScript.
However, a build step is required to enable the modules to work natively in the browser.

To bundle the JavaScript and Node.js for this example in a single file named main.js,
enter the following commands in sequence in the AWS CLI command line:

```
cd javascriptv3/example_code/cross-services/photo-analyzer/src
webpack index.js --mode development --target web --devtool false -o main.js
```
## Run the app
Open the index.html in your favorite browser, and follow the onscreen instructions.

## Destroying the resources
4. Open [AWS CloudFormation in the AWS Management Console](https://aws.amazon.com/cloudformation/), and open the *Stacks* page.

![ ](images/cloud_formation_stacks.png)

5. Select the stack you created in [Create the resources](#create-the-resources) on this page.

6. Choose **Delete**.

### Next steps
Congratulations! You have created and deployed the AWS Photo Analyzer application.
For more AWS multiservice examples, see
[usecases](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/usecases).

repository: awsdocs/aws-doc-sdk-examples

gha_language: Java

repo_name: awsdocs/aws-doc-sdk-examples


text:
# Nootraf's Pizza Palace
#### A local website for pizza ordering, {Feb 29,2020}
#### By **Fartoon Abdi**
## Description
This website allows the local Kenyan people to easily order affordable pizza and have it delivered at their doorsteps.
## Setup/Installation Requirements
* Install Linux, Ubuntu
* Install Visual Studio Code
* Creation of a repository in Github
## Known Bugs
There are no known bugs in this application/website.
## Technologies Used
HTML,CSS,JavaScript(JQuery).
## Support and contact details
If you run into any issues while using this website,feel free to reach me via my e-mail<EMAIL_ADDRESS>### License
MIT License

Copyright (c) [2020] [Massachusetes Institute of Technology]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Copyright (c) {2020} **{Fartoon Abdi,Nootraf's Pizza Palace}**

repository: Nootraf/Nootraf-s-Pizza-Palace

repo_name: Nootraf/Nootraf-s-Pizza-Palace


text:
Rate My Drink is an application that allows users to rate a drink (or honestly anything) on a scale of 1-5 and submit any other relevant information (comments, pictures, etc)

Rate My Drink is written in TypeScript and can be run by simply opening the HTML file ```index.html```

Development plan is as follows:

1. Create individual entries (with name, rating, and comment).
2. Create UI such that entries can be considered a CRUD application

3. Enable average ratings that aggregate individual ratings (e.g. rated 4.5/5 overall)

Stretch goals:
1. require users to be authenticated?
    -maybe add some social network capability
2. deploy to some external server


text:
---
title: Join data
seotitle: Join data with Flux
description: >
  Flux supports inner, full outer, left outer, and right outer joins.
  Learn how to use the `join` package to join two data sets with common values.
menu:
  flux_0_x:
    name: Join data
weight: 8
related:
  - /flux/v0.x/stdlib/join/
  - /flux/v0.x/stdlib/join/inner/
  - /flux/v0.x/stdlib/join/left/
  - /flux/v0.x/stdlib/join/right/
  - /flux/v0.x/stdlib/join/full/
  - /flux/v0.x/stdlib/join/time/
---

Use the Flux [`join` package](/flux/v0.x/stdlib/join/) to join two data sets based on common values.
Learn how join two data sets using the following join methods:

{{< flex >}}
{{< flex-content "quarter" >}}

Inner join

  {{< svg svg="static/svgs/join-diagram.svg" class="inner small center" >}}

{{< /flex-content >}}
{{< flex-content "quarter" >}}

Left outer join

  {{< svg svg="static/svgs/join-diagram.svg" class="left small center" >}}

{{< /flex-content >}}
{{< flex-content "quarter" >}}

Right outer join

  {{< svg svg="static/svgs/join-diagram.svg" class="right small center" >}}

{{< /flex-content >}}
{{< flex-content "quarter" >}}

Full outer join

  {{< svg svg="static/svgs/join-diagram.svg" class="full small center" >}}

{{< /flex-content >}}
{{< /flex >}}

{{% note %}}
#### When to use the join package

We recommend using the `join` package to join streams that have mostly different
schemas or that come from two separate data sources.
If you're joining data from the same data source with the same schema, using
[`union()`](/flux/v0.x/stdlib/universe/union/) and [`pivot()`](/flux/v0.x/stdlib/universe/pivot/)
to combine the data will likely be more performant.

For more information, see
[When to use union and pivot instead of join functions](/{{< latest "influxdb" >}}/query-data/flux/join/#when-to-use-union-and-pivot-instead-of-join-functions).
{{% /note %}}

- [How join functions work](#how-join-functions-work)
  - [Input streams](#input-streams)
  - [Join predicate function (on)](#join-predicate-function-on)
  - [Join output function (as)](#join-output-function-as)
- [Perform join operations](#perform-join-operations)
  {{< children type="anchored-list" filterOut="Troubleshoot join operations" >}}
- [Troubleshoot join operations](#troubleshoot-join-operations)

## How join functions work

`join` functions join _two_ streams of tables together based
on common values in each input stream.

- [Input streams](#input-streams)
- [Join predicate function (on)](#join-predicate-function-on)
- [Join output function (as)](#join-output-function-as)

### Input streams

Each input stream is assigned to the `left` or `right` parameter.
Input streams can be defined from any valid data source.
For more information, see:

- [Query data sources](/flux/v0.x/query-data/)
- Define ad hoc tables with [`array.from()`](/flux/v0.x/stdlib/array/from/)

#### Data requirements

To join data, each input stream must have the following:

- **One or more columns with common values to join on**.
  Columns do not need identical labels, but they do need to have comparable values.
- **Identical [group keys](/flux/v0.x/get-started/data-model/#group-key)**.
  Functions in the `join` package use group keys to quickly determine what tables
  from each input stream should be paired and evaluated for the join operation.
  _Both input streams should have the same group key._
  If they don't, your join operation may not find any matching tables and will
  return unexpected output.
  If the group keys of your input streams are not identical, use
  [`group()`](/flux/v0.x/stdlib/universe/group/) to regroup each input
  stream before joining them together.

  {{% note %}}
Only tables with the same [group key instance](/flux/v0.x/get-started/data-model/#example-group-key-instances)
are joined.
  {{% /note %}}

### Join predicate function (on)

`join` package functions require the `on` parameter to compare values from each input stream (represented by `l` (left) and `r` (right))
and returns `true` or `false`.
Rows that return `true` are joined.
This parameter is a [predicate function](/flux/v0.x/get-started/syntax-basics/#predicate-functions).

```js
(l, r) => l.column == r.column
```

### Join output function (as)

`join` package functions _(except [`join.time()`](/flux/v0.x/stdlib/join/time/))_
require the `as` parameter to define the output schema of the join.
The `as` parameter returns a new record using values from
joined rows–left (`l`) and right (`r`).

```js
(l, r) => ({l with name: r.name, location: r.location})
```

{{% note %}}
#### Do not modify group key columns

Do not modify group key columns. The `as` function must return the same group key as both input streams to successfully perform a join.
{{% /note %}}

## Perform join operations

The `join` package supports the following join types and special use cases:

{{< children type="anchored-list" filterOut="Troubleshoot join operations" >}}

{{< children readmore=true filterOut="Troubleshoot join operations" >}}

## Troubleshoot join operations

For information about unexpected behaviors and errors when using the `join` package,
see [Troubleshoot join operations](/flux/v0.x/join-data/troubleshoot-joins/).


text:
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. Argo Workflows is implemented as a Kubernetes CRD.

* Define workflows where each step in the workflow is a container.
* Model multi-step workflows as a sequence of tasks or capture the dependencies between tasks using a graph \(DAG\).
* Easily run compute intensive jobs for machine learning or data processing in a fraction of the time using Argo Workflows on Kubernetes.
* Run CI/CD pipelines natively on Kubernetes without configuring complex software development products.

Learn more on the Kubeflow website: [**https://argoproj.github.io/projects/argo**](https://argoproj.github.io/projects/argo)\*\*\*\*


text:
\mainpage Main Page

---
# UNI HALL click

UNI HALL click is a simple solution for adding an unipolar Hall switch to your design. It carries the Melexis US5881 unipolar Hall-effect switch and a 74LVC1T45 single bit, dual supply translating transceiver.

[click Product page](https://www.mikroe.com/uni-hall-click)

---

#### Click library

- **Author**        : Mikroe Team
- **Date**          : Dec 2019.
- **Type**          : GPIO type

# Software Support

We provide a library for the UniHall Click
as well as a demo application (example), developed using MikroElektronika
[compilers](https://shop.mikroe.com/compilers).
The demo can run on all the main MikroElektronika [development boards](https://shop.mikroe.com/development-boards).

Package can be downloaded/installed directly form compilers IDE(recommended way), or downloaded from our LibStock, or found on mikroE github account.

## Library Description

> This library contains API for UniHall Click driver.

#### Standard key functions :

- Config Object Initialization function.
> void unihall_cfg_setup ( unihall_cfg_t *cfg );

- Initialization function.
> UNIHALL_RETVAL unihall_init ( unihall_t *ctx, unihall_cfg_t *cfg );

- Click Default Configuration function.
> void unihall_default_cfg ( unihall_t *ctx );

#### Example key functions :

- Detecting north pole magnetic fields status function.
> uint8_t unihall_detecting_magnetic_fields ( unihall_t *ctx );

## Examples Description

>
> This is a example which demonstrates the use of UNI HALL Click board.
>

**The demo application is composed of two sections :**

### Application Init

>
> Initialization driver enable's - GPIO and start write log.
>

```c

void application_init ( void )
{
    log_cfg_t log_cfg;
    unihall_cfg_t cfg;

    /**
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX
     * are defined as HAL_PIN_NC, you will
     * need to define them manually for log to work.
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_printf(&logger, " --- Application Init ---\r\n");

    //  Click initialization.

    unihall_cfg_setup( &cfg );
    UNIHALL_MAP_MIKROBUS( cfg, MIKROBUS_1 );
    unihall_init( &unihall, &cfg );

    unihall_state = UNIHALL_NORTH_POLE_DETECTED;
    unihall_state_old = UNIHALL_NORTH_POLE_DETECTED;

    log_printf(&logger, "---------------------------\r\n");
    log_printf(&logger, "        Initialization     \r\n");
    log_printf(&logger, "---------------------------\r\n");
    log_printf(&logger, " Detecting magnetic fields \r\n");
    log_printf(&logger, "---------------------------\r\n");

    Delay_ms( 100 );
}

```

### Application Task

>
> Detect the north pole magnetic fields near the UNI HALL Click.
> Results are being sent to the Usart Terminal where you can track their changes.
> All data logs on usb uart when magnetic field is detected.
>

```c

void application_task ( void )
{
    unihall_state = unihall_detecting_magnetic_fields( &unihall );

    if ( ( unihall_state == UNIHALL_NORTH_POLE_NOT_DETECTED ) && ( unihall_state_old == UNIHALL_NORTH_POLE_DETECTED ) )
    {
        unihall_state_old = UNIHALL_NORTH_POLE_NOT_DETECTED;
        log_printf(&logger, "      ~ NOT DETECTED ~\r\n");
    }

    if ( ( unihall_state == UNIHALL_NORTH_POLE_DETECTED ) && ( unihall_state_old == UNIHALL_NORTH_POLE_NOT_DETECTED ) )
    {

        log_printf(&logger, "        ~ DETECTED ~\r\n");
        unihall_state_old = UNIHALL_NORTH_POLE_DETECTED;
    }
}

```

The full application code, and ready to use projects can be  installed directly form compilers IDE(recommneded) or found on LibStock page or mikroE GitHub accaunt.

**Other mikroE Libraries used in the example:**

- MikroSDK.Board
- MikroSDK.Log
- Click.UniHall

**Additional notes and informations**

Depending on the development board you are using, you may need
[USB UART click](https://shop.mikroe.com/usb-uart-click),
[USB UART 2 Click](https://shop.mikroe.com/usb-uart-2-click) or
[RS232 Click](https://shop.mikroe.com/rs232-click) to connect to your PC, for
development systems with no UART to USB interface available on the board. The
terminal available in all Mikroelektronika
[compilers](https://shop.mikroe.com/compilers), or any other terminal application
of your choice, can be used to read the message.

---

gha_language: C

gha_license_id: NOASSERTION


text:
# SilverStripe Asset Proxy

## Description

Attempts to fetch missing asset files from a remote host, by intercepting 404 errors.  The idea is to pull down missing asset files from staging/production sites as needed, without needing to do full syncs of the assets folder.

Unfortunately, this will NOT WORK with SilverStripe's normal image handling stuff (like eg `$Image.SetWidth`) because these don't generate image tags / URLs (needed to trigger 404s) if the images don't exist locally.

However, this can be solved by using this module in conjunction with [Image Profiles](https://github.com/bcairns/silverstripe-imageprofiles).

## Usage

After installing the module, define an `ASSETPROXY_HOST` constant in either _config.php or _ss_environment.php:

```
define('ASSETPROXY_HOST','http://my-source-server.com');
```

## Known Issues

* If the source image is changed (while retaining an identical filename) the new version will not replace the old one.  Suggested workaround is to just delete your local version of the file and let the latest be re-fetched.

## Acknowledgements

* This module is inspired by Drupal's [Stage File Proxy](https://www.drupal.org/project/stage_file_proxy) module.


text:
###Before Running

Go to https://myaccount.google.com/lesssecureapps
and turn the toggle ON

After that

### To Run

```
python sendMail.py "gmail username" "gmail password" "file name"
```

repository: ajwahir/cookie

repo_name: ajwahir/cookie


text:
---
title: Design emails in Journey Optimizer
description: Learn how to design your emails content
feature: Overview
topic: Content Management
role: User
level: Intermediate
---
# Design your email content in the user interface {#create-email-content}

Once you have [created your message](create-message.md), you can start creating your email content.

1. From your newly created message, select **[!UICONTROL Email designer]** in the **[!UICONTROL Body]** section.

    ![](assets/import-html_1.png)

1. In the Email Designer home page, choose how you want to design your email from the following options:

    * Select **[!UICONTROL Design from scratch]** to use the email designer capabilities to create your email content. [Learn more](#design-scratch)

    * Select **[!UICONTROL Start from template]** to create your email from a built-in list of templates. Note that you cannot create other templates.

    * Select **[!UICONTROL Code your own]** to enter or paste HTML raw code. [Learn more](existing-content.md#import-raw-html-code).

    * Select **[!UICONTROL Import HTML]** to import an HTML file or .zip folder. [Learn more](existing-content.md#import-html-content-from-file).

    ![](assets/email_designer_25.png)

## Design from scratch {#design-scratch}

>[!CONTEXTUALHELP]
>id="ac_structure_components"
>title="About Structure components"
>abstract="Structure components define the layout of the email."

>[!CONTEXTUALHELP]
>id="ac_edition_columns"
>title="Defining email columns"
>abstract="The Email Designer allows you to easily define the layout of your email by defining column structure."

The Email Designer allows you to easily define the structure of your email. By adding and moving structural elements with simple drag-and-drop actions, you can design the shape of your email within seconds.

To start building your email content with the email designer, follow the steps below:

1. After selecting the **[!UICONTROL Design from scratch]** option, start designing your email content by drag and dropping **[!UICONTROL Structure components]** to define the layout of your email.

   >[!NOTE]
   >
   >Note that stack of columns are not compatible with all email programs. When not supported, columns will not be stacked.
   >
   >Once placed in the email, you cannot move nor remove your components unless there is already a content component or a fragment placed inside.

    ![](assets/email_designer_2.png)

1. Add as many **[!UICONTROL Structure components]** as needed.

   Select the **[!UICONTROL n:n column]** component to define the number of columns of your choice (between 3 and 10). You can also define the width of each column by moving the arrows at the bottom of each column.

   >[!NOTE]
   >
   >Each column size cannot be under 10% of the total width of the structure component. You cannot remove a column that is not empty.

1. From the **[!UICONTROL Content components]** drop-down, you can add as many **[!UICONTROL Content components]** as you need in your structure component. [Learn more about Content components](content-components.md).

    ![](assets/email_designer_3.png)

1. Each component can be further customized with the **[!UICONTROL Component settings]** section. For example, you can change your text style, the padding or margin of your component. [Learn more about styles in the Email Editor](https://experienceleague.adobe.com/docs/campaign-standard/using/designing-content/styles.html).

    ![](assets/email_designer_4.png)

1. From the **[!UICONTROL Assets picker]**, you can directly add assets stored in the **[!UICONTROL Assets library]** to your email. [Learn more about asset management](assets-essentials.md).

    Double-click the folder which contained your assets and drag and drop the asset you want to add to your email.

    ![](assets/email_designer_5.png)

1. Add personalization fields to customize the content from your profiles data. [Learn more about content personalization](personalization/personalize.md).

    ![](assets/email_designer_6.png)

1. In the **[!UICONTROL Links]** tab in the left pane, check the list of all the URLs of your content that will be tracked. You can modify their **[!UICONTROL Tracking Type]**, **[!UICONTROL Label]** and **[!UICONTROL Tags]** if needed.

    ![](assets/email_designer_7.png)

    >[!NOTE]
    >
    >Learn more about links and message tracking in [this page](message-tracking.md).

1. If needed, you can switch to code editor to further personalize your email by clicking **[!UICONTROL Switch to code editor]** from the advanced menu. For more information on the code editor, refer to this [page](existing-content.md#import-raw-html-code).

    >[!NOTE]
    >
    >You will not be able to use the visual designer for this email after switching to the code editor.

    ![](assets/email_designer_26.png)

1. Click **[!UICONTROL Show preview]** to check your email rendering. You can choose the desktop or mobile view.

    For more information on how preview your email, refer to [Preview and test your messages](preview.md).

    ![](assets/email_designer_8.png)

1. When your email is ready, click **[!UICONTROL Save & Close]**.

Your email content can now be used in a message. [Learn how to send a message](publish-manage-message.md).

## Create the text version of an email {#generate-text-version}

It is recommended to create a text version of your email body, which is used when HTML content cannot be displayed.

By default, the Email Designer creates a **[!UICONTROL Plain text]** version of your email, including personalization fields. This  version is automatically generated and synchronized with the HTML version of your content.

If you prefer using a different content for the plain text version, follow the steps below:

1. From your email, select the **[!UICONTROL Plain text]** tab.

    ![](assets/text_version_3.png)

1. Use the **[!UICONTROL Sync with HTML]** toggle to disable synchronization.

    ![](assets/text_version_1.png)

1. Click the check mark to confirm your choice.

    ![](assets/text_version_2.png)

1. You can then edit the plain text version as desired.

>[!CAUTION]
>
>* Changes made in **[!UICONTROL Plain text]** view are not reflected in HTML view.
>
>*  If you re-enable the **[!UICONTROL Sync with HTML]** option  after updating your plain text content, your changes will be lost, and replaced with text content generated from the HTML version.

## Use a preheader {#preheader}

>[!CONTEXTUALHELP]
>id="ac_edition_preheader"
>title="Using a preheader"
>abstract="The preheader lets you configure a short summary text that can help you better track and customize your emails."

>[!NOTE]
>
>Note that preheaders are not compatible with all email clients. When not supported, the preheader does not display.

A preheader is a short summary text that follows the subject line when viewing an email from your email client. The preheader can help you better track and customize your emails.

1. From the Email designer, add a **[!UICONTROL Structure components]** to start designing your email.

    ![](assets/preheader_1.png)

1. From the **[!UICONTROL Body settings]** right pane, click **Edit** next to the **[!UICONTROL Preheader]** field to add content.

    ![](assets/preheader_2.png)

1. Add your preheader. You can further personalize it by clicking the **[!UICONTROL Add personalization]** icon.

    ![](assets/preheader_3.png)

1. From the **[!UICONTROL Edit Personalization]** window, you can add **[!UICONTROL Content block]**, **[!UICONTROL Dynamic content]** or **[!UICONTROL Personalization fields]**.

1. Click **[!UICONTROL Validate]** to check your personalization syntax.

    ![](assets/preheader_4.png)

1. Click **[!UICONTROL Save]**.

Your preheader is now configured for your email.

## Background settings {#about-backgrounds}

>[!CONTEXTUALHELP]
>id="ac_edition_backgroundimage"
>title="Background settings"
>abstract="The Email designer lets you personnalize background color or background image for your content.Note that background image is not supported by all email clients."
>additional-url="https://docs.google.com/spreadsheets/d/1TLo62YKm3tThUWDOIliCQFWs3dpNjpDfw6DdTr1oGOw/edit#gid=0" text="Additional info"

When it comes to setting backgrounds with the Email Designer, Adobe recommends the following:

1. Apply a background color to the body of your email if required by your design.
1. In most cases, set background colors at the column level.
1. Try not to use background colors on image or text components as they are difficult to manage.

Below are the available background settings that you can use.

* Set a **[!UICONTROL Background color]** for the whole email. Make sure you select the body settings in the navigation tree accessible from the left Palette.

* Set the same background color for all structure components by selecting **[!UICONTROL Viewport background color]**. This option enables you to select a different setting from the background color.

* Set a different background color for each structure component. Select a structure in the navigation tree accessible from the left Palette to apply a specific background color only to that structure.

  Make sure you do not set a viewport background color as it may hide the structure background colors.

* Set a **[!UICONTROL Background image]** for the content of a structure component.

  >[!NOTE]
  >
  >Some email programs do not support background images. When not supported, the row background color will be used instead. Make sure you select an appropriate fallback background color in case the image cannot be displayed.

* Set a background color at the column level.

  >[!NOTE]
  >
  >This is the most common use case. Adobe recommends setting background colors at the column level as this allows for more flexibility when editing the whole email content.

  You can also set a background image at the column level, but this is rarely used.

## Adjust vertical alignment and padding {#adjusting-vertical-alignment-and-padding}

You want to adjust padding and vertical alignment inside a structure component composed of three columns. To do this, follow the steps below:

1. Select the structure component directly in the email or using the structure tree available from the left **Palette**.
1. From the **contextual toolbar**, click **[!UICONTROL Select a column]** and choose the one that you want to edit. You can also select it from the structure tree.

   The editable parameters for that column are displayed in the **[!UICONTROL Settings]** pane on the right.

1. Under **[!UICONTROL Vertical alignment]**, select **[!UICONTROL Up]**.

   The content component displays on top of the column.

1. Under **[!UICONTROL Padding]**, define the top padding inside the column. Click the lock icon to break synchronization with the bottom padding.

   Define the left and right padding for that column.

1. Proceed similarly to adjust the other columns' alignment and padding.

1. Save your changes.

## Define a style for links {#about-styling-links}

You can underline a link and select its color and target in the Email Designer.

1. In a component where a link is inserted, select the label text of your link.

1. In the component settings, check **[!UICONTROL Underline link]** to underline the label text of your link.

1. To select in which browsing context your link will be opened select a **[!UICONTROL Target]**.

1. To change the color of your link, click on **[!UICONTROL Link color]**.

1. Pick the color you need.

1. Save your changes.

## Add inline styling attributes {#adding-inline-styling-attributes}

In the Email Designer interface, when you select an element and display its settings on the side panel, you can customize the inline attributes and their value for that specific element.

1. Select an element in your content.
1. On the side panel, look for the **[!UICONTROL Styles Inline]** settings.

1. Modify the values of the existing attributes, or add new ones using the **+** button. You can add any attribute and value that is CSS-compliant.

The styling is then applied to the selected element. If the child elements do not have specific styling attributes defined, the styling of the parent element is inherited.