text:
# ORACS

## Data structure

Depot-vehicle combination:

- Route
- Deliver quantities
- Total deliver quantity
- Route cost
- Travel time

Customer:

- Total deliver quantity
- List of routes with:
  - Depot
  - Vehicle type
  - Route index
  - Deliver quantity

## Classes

### Depot

Data members:

- List of vehicles
- Leftover inventory

Functions:

### Vehicle

Data members:

- Type
- Route
- Leftover capacity
- Leftover travel time

Functions:

- Route cost

### Route

Data members:

- Ordered list of customers (index)
- Delivery quantity
- Total delivery quantity
- Service time
- Travel distance

Functions:

### Customer (TODO)

Data members:

- Demand
- Total delivery quantity
- Depot

## Initialisation

### Load data

Load `m`, the number of depots. Load `K`, the number of vehicles types. Load `n`, the number of customers.

Load distance matrix `distanceMatrix` into Matrix datatype with dimensions (n + m) x (n + m).
Create depot matrix `depotMatrix` with dimensions m x (K + 1).
Load customer matrix `customerMatrix` with dimension n x 2.
Load vehicle matrix `vehicleMatrix` with dimension K x 4

### Create empty solution

For each depot (m depots):

- Select row from `depotMatrix`
- Set inventory by calling `Solution::addDepot(I_j)`
- For each vehicle type:
  - Add `n_jk` vehicles by calling `Depot::addVehicle(k)` function

For each customer in `customerMatrix`:

- Create customer by calling `Solution::addCustomer(demand, servicetime)`

### Construct initial solution

1. Sort `customerMatrix` on ascending demand.
2. Create `depotCustomerAllocation` (is a `vector<vector<int>>`). Create `depotCustomerDemand`.
3. Loop over `customerMatrix`:
    - Create `leftoverDemand = customer.getDemand()`.
    - While `leftoverDemand > 0`
        - Find smallest distance to depots, say `smallDepot`.
        - Add customer.
    - end

4. Loop over depot (m depots):
    - Sort vehicles based on costs.
    - Create `customerList` and `customerDropOff`.
    - Loop over sorted vehicle list:
        - Create `leftoverCapacity = vehicle.getCapacity()`
        - while (`leftoverCapacity > 0`) do
            - Take new customer from `depotCustomerAllocation` (first time random).
            - Add customer to `customerList` and `customerDropOff`.
            - Update `leftoverCapacity`.
            - if (`leftoverCapacity >= demand`) then
                - Delete from `depotCustomerAllocation`.
            - else update `depotCustomerDemand`.
        - end
        - `route = cheapestInsertion(customerList)`
        - `vehicle.setRoute(route, deliverQuantities)`
        - `Customers.addRoute(route, deliverQuantities)`

#### cheapestInsertion(customerList)

1. Create `route = {0, 0};`
2. While customerList is not empty
    - For each customer in customerList
        - For each insertion option (N - 1):
            - Check if minimum
    - Update route by inserting cheapest.
    - Remove customer from customerList.
3. Ready to rambo.

 Select seed customer from customer list. Store in toBeRemoved.
2. Find q-1 nearest customers. Store in toBeRemoved.
3. removeCustomers(solution, toBeRemoved) (see below)

### removeCustomers(solution, toBeRemoved)

1. For each customer in toBeRemoved:
    - For each vehicle of customer:
        - Find place customer in route
        - Remove customer from route (and dropoff)
        - Update load, length, serviceTime, route cost
        - Remove depot+vehicle_id from customer
2. toBeReinserted = toBeRemoved (for later use)
3. Return destroyed solution and toBeReinserted

### costRemoval(solution)

1. For customers 1,...,n:
   - computeRemovalGain(solution, customer) (see below)
   - store result in vector gains, along with customer_id (gains = [[1,gain_1],...,[n,gain_n]])
2. Find q largest gains, store corresponding customer_ids in toBeRemoved
3. removeCustomers(solution, toBeRemoved)

### computeRemovalGain(solution, customer)

1. For each vehicle of customer, compute vehicleRemovalGain:
    - Find place in route
    - Distance gain: Use distanceMatrix (multiply by alpha)
    - Feasibility gain (only if route is infeasible in the first place):
        - Find old and new travel duration (travel time + service time)
        - Use arithmetic.
    - vehicleRemovalGain = distance gain + feasibility gain
    - totalRemovalGain = sum(vehicleRemovalGain)
    - totalRemovalGain = totalRemovalGain * uniform(a, b) (a = 0.8, b = 1.2)(RNG).
2. return totalRemovalGain

### routeRemoval(solution)

1. Pick random non-empty vehicle.
2. Find corresponding route
3. Store at random min(q, route.length()) customers in toBeRemoved
4. removeCustomers(solution, toBeRemoved)

### reinsert(solution, toBeReinserted)

1. demand = demand(toBeReinserted)
2. While toBeReinserted is not empty
    - Select random customer from toBeReinserted.
    - minInsertion = Infinity
    - depot = -1, vehicle = -1, idx = -1 (initilize insertion location)
    - For each vehicle
        - For each insertion option
            - Find insertionCost:
                - Additional travel costs
                - Infeasibility penalties
            - If (insertion costs < minInsertion)
                - minInsertion = insertionCost
                - update: depot, vehicle, and idx
    - Insert customer at depot, vehicle, idx:
    - If (insufficient inventory/capacity)
        - Allocate as much as possible and split demand
        - Update demand
    - If (sufficient inventory and capacity)
        - Allocate all demand
        - remove customer from toBeReinserted
3. Return solution
Note: we can alternatively check in advance for sufficient inventory/capacity, and discard the insertion option
if insufficient. One problem is that all insertion options may be discarded (a simple workaround is to repeat the
search, now allowing for splits).
I suggest moving this to the tuning phase (if it turns out that too many splits are generated,
this is one place where we can look.)

## Algorithm Structure

### Solutions

solutions: `best_feasible`, `best_solution`, `s`, `s_prime`
f(solution) = cost(solution) + penalty(solution)

cost(solution) = sum(travelCosts)
penalty(solution) = penalty * travelTimeViolation(solution)
penalty is a parameter between `iota_min` and `iota_max = iota_min*delta^100` (or delta^10, whatever) multiplied by
factor delta if solution is infeasible

### Initialise

`penalty = iota_min (global)`
`s = initialSolution()`
`best_solution = s`

if `s` is feasible:

- `best_feasible = s`

else:

- `best_feasible` = empty (objective value: inf)

`T = r*f(s) (0 < r < 1)` (Temperature for simulated annealing)

`iter == 1`
repeat:

- `s_prime` = DestroyAndRepair(s)
    if f(`s_prime`) < (1 + theta)*f(`best_solution`):
    - for (routine in routineList):
         - `s_prime` = routine(`s_prime`)
         if (improvement):
            - return to first routine (that is, reenter for-loop) #this is rather extensive,
            (an alternative is to move to the next routine if the current routine does not yield further improvements)

    `best_solution` =  min(`s_prime`, `best_solution`) #compare objectives, use same global penalty parameter

    if `s_prime` is feasible
    -    `best_feasible` = min(`s_prime`, `best_feasible`) #compare objectives

    simulatedAnnealing(`s_prime, s`) (simulatedAnnealing: see below)
    updatePenalty(`s`)
    `iter++`

until `iter == max_iter` or comp_time > max_comp_time

### updatePenalty(solution)

if(solution is not feasible)

- penalty = min(iota_max, iota * delta)

else

- penalty = max(iota_min, iota / delta)

### simulatedAnnealing(s1, s2)

if f(s1) <= f(s2):

-  T = r*f(s1) (0<r<1)
    return s1

else
-   diff = f(s1) - f(s)
    generate random variate u~U(0,1)
    if (u < exp(-diff/T))
    -   return s1 with probability exp(-diff/T)
        T = max(r*T, T_min) (0 < r <1, T_min is minimum temperature)

### 1-insertion intra route ###
minInsertion = 0
For each depot
-    For each vehicle
        - For each dummy customer in route
            - For each insertion option in route
                - Compute insertionCosts (distance + feasibility)
                if (insertionCosts < minInsertion)
                    - minInsertion = insertionCosts
                    store depot + vehicle + customer + insertion option

Execute best option: (change route + deliveries for (depot,vehicle))
### end ###

### 2-opt intra route ###
bestOption = 0
For each depot
-    For each vehicle
     -   For i = 1 to route.size()
            - c1 = route[i - 1]
            c2 = route[i]
            For j = i + 1 to route.size()
                - c3 = route[j]
                c4 = route[j + 1]
                saving = distance - distance[c1,c2] - distance[c3,c4] + distance[c1,c3] + distance[c2,c4]
                if saving < bestOption
                    - bestOption = saving
                    store i, j

Execute best option: newRoute = oldRoute[0,i - 1] + revert(oldRoute[i,j]) + oldRoute[j+1, route.size()], change deliveries analagously


text:
# Nand2Tetris Assembler PHP Implementation

PHP implementation of the nand2tetris assembler project:
https://www.nand2tetris.org/project06

## Getting Started

### Prerequisites

You will need to have PHP installed before getting started:
https://www.php.net/manual/en/install.php

You'll also need to have a few Hack `asm` files ready to assemble

### Installing

Clone the repository anywhere in your system

```
cd [location]
git clone https://github.com/chickenn00dle/hack_assembler.git [new_name]
cd [new_name]
```

## Running the tests

If you don't have any `asm` files to test, grab some from the official nand2Tetris website:
https://www.nand2tetris.org/project06

Using `Max.asm` provided by the nand2Tetris, make sure you are in the assembler directory and you have added `Add.asm` to this directory.

```
php assembler.php Max.asm
```

This will scan Max.asm and generate a new file called Max.hack

Verify this matches the provided compare file provided in project 6 here:
https://www.nand2tetris.org/software

## Authors

* **Rasmy Nguyen** - *Initial work* - [Chickenn00dle](https://github.com/chickenn00dle)

## License

This project is licensed under the MIT License

## Acknowledgments

The folks over at [nand2Tetris](www.nand2tetris.org) did an amazing job of putting together an approachable course that taught me a ton about how computers work under the hood. Thank you!

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# inversify-restify-utils

[![Join the chat at https://gitter.im/inversify/InversifyJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/inversify/InversifyJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://secure.travis-ci.org/inversify/inversify-restify-utils.svg?branch=master)](https://travis-ci.org/inversify/inversify-restify-utils)
[![Test Coverage](https://codeclimate.com/github/inversify/inversify-restify-utils/badges/coverage.svg)](https://codeclimate.com/github/inversify/inversify-restify-utils/coverage)
[![npm version](https://badge.fury.io/js/inversify-restify-utils.svg)](http://badge.fury.io/js/inversify-restify-utils)
[![Dependencies](https://david-dm.org/inversify/inversify-restify-utils.svg)](https://david-dm.org/inversify/inversify-restify-utils#info=dependencies)
[![img](https://david-dm.org/inversify/inversify-restify-utils/dev-status.svg)](https://david-dm.org/inversify/inversify-restify-utils/#info=devDependencies)
[![img](https://david-dm.org/inversify/inversify-restify-utils/peer-status.svg)](https://david-dm.org/inversify/inversify-restify-utils/#info=peerDependenciess)
[![Known Vulnerabilities](https://snyk.io/test/github/inversify/inversify-restify-utils/badge.svg)](https://snyk.io/test/github/inversify/inversify-restify-utils)

[![NPM](https://nodei.co/npm/inversify-restify-utils.png?downloads=true&downloadRank=true)](https://nodei.co/npm/inversify-restify-utils/)
[![NPM](https://nodei.co/npm-dl/inversify-restify-utils.png?months=9&height=3)](https://nodei.co/npm/inversify-restify-utils/)

Some utilities for the development of restify application with Inversify.

## Installation
You can install `inversify-restify-utils` using npm:

```
$ npm install inversify inversify-restify-utils reflect-metadata restify --save
```

The `inversify-restify-utils` type definitions are included in the npm module and require TypeScript 2.0.
Please refer to the [InversifyJS documentation](https://github.com/inversify/InversifyJS#installation) to learn more about the installation process.

## The Basics

### Step 1: Decorate your controllers
To use a class as a "controller" for your restify app, simply add the `@Controller` decorator to the class. Similarly, decorate methods of the class to serve as request handlers.
The following example will declare a controller that responds to `GET /foo'.

```ts
import { Request } from 'restify';
import { Controller, Get, interfaces } from 'inversify-restify-utils';
import { injectable, inject } from 'inversify';

@Controller('/foo')
@injectable()
export class FooController implements interfaces.Controller {

    constructor( @inject('FooService') private fooService: FooService ) {}

    @Get('/')
    private index(req: Request): string {
        return this.fooService.get(req.query.id);
    }
}
```

### Step 2: Configure container and server
Configure the inversify container in your composition root as usual.

Then, pass the container to the InversifyRestifyServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the restify app.
Then just call server.build() to prepare your app.

In order for the InversifyRestifyServer to find your controllers, you must bind them to the `TYPE.Controller` service identifier and tag the binding with the controller's name.
The `Controller` interface exported by inversify-restify-utils is empty and solely for convenience, so feel free to implement your own if you want.

```ts
import { Container } from 'inversify';
import { interfaces, InversifyRestifyServer, TYPE } from 'inversify-restify-utils';

// set up container
let container = new Container();

// note that you *must* bind your controllers to Controller
container.bind<interfaces.Controller>(TYPE.Controller).to(FooController).whenTargetNamed('FooController');
container.bind<FooService>('FooService').to(FooService);

// create server
let server = new InversifyRestifyServer(container);

let app = server.build();
app.listen(3000);
```

Restify ServerOptions can be provided as a second parameter to the InversifyRestifyServer constructor:

```let server = new InversifyRestifyServer(container, { name: "my-server" });```

Restify ServerOptions can be extended with `defaultRoot` where one can define a default path that will be prepended to all your controllers:

```let server = new InversifyRestifyServer(container, { name: "my-server", defaultRoot: "/v1" });```

## InversifyRestifyServer
A wrapper for a restify Application.

### `.setConfig(configFn)`
Optional - exposes the restify application object for convenient loading of server-level middleware.

```ts
import * as morgan from 'morgan';
// ...
let server = new InversifyRestifyServer(container);
server.setConfig((app) => {
    const logger = morgan('combined')
    app.use(logger);
});
```

### `.build()`
Attaches all registered controllers and middleware to the restify application. Returns the application instance.

```ts
// ...
let server = new InversifyRestifyServer(container);
server
    .setConfig(configFn)
    .build()
    .listen(3000, 'localhost', callback);
```

## Decorators

### `@Controller(path, [middleware, ...])`

Registers the decorated class as a controller with a root path, and optionally registers any global middleware for this controller.

### `@Method(method, path, [middleware, ...])`

Registers the decorated controller method as a request handler for a particular path and method, where the method name is a valid restify routing method.

### `@SHORTCUT(path, [middleware, ...])`

Shortcut decorators which are simply wrappers for `@Method`. Right now these include `@Get`, `@Post`, `@Put`, `@Patch`, `@Head`, `@Delete`, and `@Options`. For anything more obscure, use `@Method` (Or make a PR :smile:).

## Middleware
Middleware can be either an instance of `restify.RequestHandler` or an InversifyJS service idenifier.

The simplest way to use middleware is to define a `restify.RequestHandler` instance and pass that handler as decorator parameter.

```ts
// ...
const loggingHandler = (req: restify.Request, res: restify.Response, next: restify.Next) => {
  console.log(req);
  next();
};

@Controller('/foo', loggingHandler)
@injectable()
export class FooController implements interfaces.Controller {

    constructor( @inject('FooService') private fooService: FooService ) {}

    @Get('/', loggingHandler)
    private index(req: restify.Request): string {
        return this.fooService.get(req.query.id);
    }
}
```

But if you wish to take full advantage of InversifyJS you can bind the same handler to your IOC container and pass the handler's service identifier to decorators.

```ts
// ...
import { TYPES } from 'types';
// ...
const loggingHandler = (req: restify.Request, res: restify.Response, next: restify.Next) => {
  console.log(req);
  next();
};
container.bind<restify.RequestHandler>(TYPES.LoggingMiddleware).toConstantValue(loggingHandler);
// ...
@Controller('/foo', TYPES.LoggingMiddleware)
@injectable()
export class FooController implements interfaces.Controller {

    constructor( @inject('FooService') private fooService: FooService ) {}

    @Get('/', TYPES.LoggingMiddleware)
    private index(req: restify.Request): string {
        return this.fooService.get(req.query.id);
    }
}
```

repository: inversify/inversify-restify-utils

gha_language: TypeScript

gha_license_id: MIT

repo_name: inversify/inversify-restify-utils


text:
# Array Methods

Array methods are javaScript built-in functions that are inherited from the object prototype

## Object prototypes

Each array object comes (inherits) with it a second object that is the prototype, the prototype object are built in properties and functions known as methods because they are stored in an object

When you create an array literal the array immediately inherits the object prototype

This will be shown in the code below

```js
// Array.prototype contains all the array methods and properties
const ArrayPrototype = Array.prototype;
// Try it in the console
console.log(ArrayPrototype);

// declare an empty array inherits the prototype object
const newArray = [];

// Logging the output the new array in the console you will be able to see hte inherited second object "the prototype object"
console.log(newArray);

// Expanding the array The output shown should be like this
[]
length: 0
__proto__: Array(0)  // expanding it, you will see all the built-in methods and properties thar can be used in the array

```

In this section are going to be shown how the most important methods are under the hood, in [functional array methods](array-methods/03-functional-array-methods) we will see them in action.

There are a lot methods and you don't need to master all of them in this chapter but is good to know where they are and during your journey in code you will master all of them

Almost every object have their own prototype and this topic will be touched deeply in future modules `Object prototype and inheritance`, in mean time lets keep it only with Array-prototype

---

## Links

- [CODEPROJECT Reference](https://reference.codeproject.com/book/javascript/Reference/Global_Objects/Array/prototype)
- [Array Prototype](https://www.youtube.com/watch?v=Qx70BuDB8tk&t=3s)
- [doesitmutate.xyz](https://doesitmutate.xyz/)
- [Higher-Order Functions](https://medium.com/humans-create-software/a-dirt-simple-introduction-to-higher-order-functions-in-javascript-b33bf9e19056)
- [Map](https://www.youtube.com/watch?v=bCqtb-Z5YGQ&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&index=2)
- [Reduce Basics](https://www.youtube.com/watch?v=Wl98eZpkp-c&list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84&index=3)


text:
---
layout: default
---

# 1997-06-05 - Re: Webpage picketing (fwd)

## Header Data

From: Jim Choate<EMAIL_ADDRESS>To<EMAIL_ADDRESS>(Cypherpunks Distributed Remailer)

Message Hash: 010a86512cb0d5b2b614a18c1320ea4f8fd54869cc0167da546d6325f4f55bc8

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1997-06-05 02:23:53 UTC

Raw Date: Thu, 5 Jun 1997 10:23:53 +0800

## Raw message

```
{% raw  %}From: Jim Choate<EMAIL_ADDRESS>Date: Thu, 5 Jun 1997 10:23:53 +0800
To<EMAIL_ADDRESS>(Cypherpunks Distributed Remailer)
Subject: Re: Webpage picketing (fwd)
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text

Hi,

Forwarded message:

> From: "William H. Geiger III"<EMAIL_ADDRESS>> Date: Wed, 04 Jun 97 10:00:46 -0500
> Subject: Re: Webpage picketing (fwd)

> I think that your analogy is slightly flawed.
>
> While the farmers have a right to protest on the side of the road they do
> not have a right to interfere with the travelers on the road.

Correct and using my model would in no way interfere with a users use of the
network. It would not add excessive delay or other impedemants. It would be
a one time event that occured when the site was initialy accessed. Much like
having to go past the picketers on the side of the road at least once.

> There is no real way you could picket on the "Info highway" as you have no
> right to interfere with the packets traveling on the highway. You can
> stand of to the side if you want but somehow I don't think that the
> packets will be watching. :)

If it is a fully privately funded highway, I agree. If it accepts public
money I obviously disagree with you. As to the packets watching, no more so
than the cars being used are watching the picketers. This is a straw man
argument. The issue here is not the packets but the paticipants.

   _______________________________________________________________________
  |                                                                       |
  |            Speak the truth, but leave immediately after.              |
  |                                                                       |
  |                                     Slovenian Proverb                 |
  |                                                                       |
  |     Jim Choate<EMAIL_ADDRESS>       |
  |     The Armadillo Group                        www.ssz.com            |
  |     Austin, Texas, USA<PHONE_NUMBER>           |
  |_______________________________________________________________________|

{% endraw %}
```

## Thread

+ Return to [June 1997](/archive/1997/06)

+ Return to "[Declan McCullagh <declan@pathfinder.com>](/authors/declan_mccullagh_declan_at_pathfinder_com_)"
+ Return to "[Jim Choate <ravage@EINSTEIN.ssz.com>](/authors/jim_choate_ravage_at_einstein_ssz_com_)"
+ Return to "["William H. Geiger III" <whgiii@amaranth.com>](/authors/william_h_geiger_iii_whgiii_at_amaranth_com_)"

+ 1997-06-05 (Thu, 5 Jun 1997 10:23:53 +0800) - Re: Webpage picketing (fwd) - _Jim Choate<EMAIL_ADDRESS>  + 1997-06-05 (Thu, 5 Jun 1997 10:44:29 +0800) - [Re: Webpage picketing (fwd)](/archive/1997/06/a63948b39076cfc96d0502bd9290dd3a0e65dc0328d1ed1c5632b3e5445c46ec) - _"William H. Geiger III"<EMAIL_ADDRESS>  + 1997-06-05 (Thu, 5 Jun 1997 12:40:24 +0800) - [Government money, Net picketing, and public fora](/archive/1997/06/3237d18894f77e1454ad3ac351d2ed10f5c0613342f70553533a8c098ad1b6de) - _Declan McCullagh<EMAIL_ADDRESS>


text:
#   PyColloid
##  A simple colloid simulation

A simple simulation of a group of particles in a box, with electromagnetic interactions. As an output you will get two files, a *png* with the first and last state, and a *gif* with the temporal evolution.

![](output/output.gif)

## Prerequisites

*   **[Python3](https://www.python.org/)**
*   **[Gnuplot](http://gnuplot.sourceforge.net/)**

You will need a *bash* or other UNIX-based terminal for running the following commands. However, you can run the simulation by hand by running [``main.py``](src/main.py), and then, by running [``PlotCopy.gp``](src/PlotCopy.gp).

##  Usage

Download the latest release from [releases](https://github.com/JARA99/PyColloid/releases).

<!-- Then go to the project folder and follow the execution instructions.

```
cd PyColloid
``` -->

Then extract the source code. Open a terminal on the PyColloid folder and then just execute the shell script [``RUN.sh``](RUN.sh) by typing:

```
./RUN.sh
```

<!-- Optionally you can use the virtualenv provided by doing ``source venv-simulation/bin/activate`` and then executing the shell script. -->

Ideally you will get a terminal output like this:

```
Case: [Low/High]APF
[n] frames in animation sequence
```

But most likely you will have some: ``Collision loop exceeded for this particle``. Which means that you will have overlaps between particles in the animation. You can try minimizing this by putting a higher value on *CollisionLoops* (see the next list), but you will increase the computation time. Other method is to play with the *DeltaTime*, *MaxVo* and *ForceConstant* parameters, this will not add computation time, but change the whole simulation environment.

You can change the parameters of the simulation by changing the [Parameters.txt](Parameters.txt) file. This file its by itself very self-explanatory but here is a bit of documentation:

*   **Case:** Select the method of sorting the initial state by choosing the scenario *HighAPF* (high atomic packing factor), or *LowAPF* (low atomic packing factor).
*   **APF:** Set a fixed APF, this will rewrite the number of particles, you can turn it off by tying -1.
*   **Particles:** Number of particles on the simulation.
*   **Mass:** Mass of each particle.
*   **MaxCharge:** Maximum charge of each particle.
*   **MinCharge:** Minimum charge of each particle.
*   **MaxRadius:** Maximum radius of each particle.
*   **MinRadius:** Minimum radius of each particle.
*   **MaxX:** *x* length of the box.
*   **MinY:** *y* length of the box.
*   **MaxVo:** Maximum initial velocity in any direction for the particles.
*   **ForceConstant:** Parameter k used on Coulumb's law.
*   **DeltaTime:** Time of each evolving interval.
*   **Iterations:** Total of DeltaTime iterated.
*   **CollisionLoops:** Maximum iterations for calculating a collision.
*   **Palette:** Palette used for coloring the charge, you can use any of the ones listed [here](src/gnuplot-palettes/Palettes.png).
*   **Invert:** Invert the palette on plot.

Finally, you can change some parameters and re-plot without having to re-simulate by simply typing:

```
./RePlot.sh
```

---

##  Palettes

Remember you can choose the palette of your choice from this list:

![](src/gnuplot-palettes/Palettes.png)

<!-- Maintain the dimensions of the box in a way that the atomic packing factor doesn't go over *0.7*.[^1]

[^1]: Consult [this article](https://en.wikipedia.org/wiki/Atomic_packing_factor) for more information on *APF*. -->

---

##  To Do

- [ ] Improve collision dynamics.
- [x] Program [InitialValues.py](src/InitialValues.py)
- [x] Program [TemporalEvolution.py](src/TemporalEvolution.py)
- [x] Program [CollisionDetector.py](src/CollisionDetector.py)
- [x] Program [CollisionDynamics.py](src/CollisionDynamics.py)
- [x] Program [main.py](src/main.py)
- [x] Program the plotter base
- [x] Finish the plotter

<!-- Fork the repository for collaboration, then send your pull requests. -->

gha_language: Python


text:
# homebridge-open-smart-led-strip-driver

Supports the Open Smart LED Strip Driver module controled through GPIO pins.
This plugin requires/uses third-party NodeJS libraries to send the crontrols to the driver module using the GPIO pins (probably in your Raspberry PI).

# Installation

1. Follow the instruction in [homebridge](https://www.npmjs.com/package/homebridge) for the homebridge server installation.

2. The plugin is published through [NPM](https://www.npmjs.com/package/homebridge-open-smart-led-strip-driver) and should be installed "globally" by typing: `npm install -g homebridge-open-smart-led-strip-driver`

3. Update your configuration file. See [config-sample.json](https://github.com/metbosch/homebridge-open-smart-led-strip-driver/blob/master/config-sample.json) in this repository for a sample.

# Configuration

Example:

```bash
{
  "accessory": "OpenSmartLedStrip",
  "name": "RGB Led Strip",
  "pin_clk": "GPIO17",
  "pin_dat": "GPIO18"
}
```

The mandatory options are:
 * ```name``` Accessory name.
 * ```pin_clk``` Pin identifier for the clock port (See [raspi-pi wiki](https://github.com/nebrius/raspi-io/wiki/Pin-Information) for more information about pin naming).
 * ```pin_dat``` Pin identifier for the data port (See [raspi-pi wiki](https://github.com/nebrius/raspi-io/wiki/Pin-Information) for more information about pin naming).

The other available options are:
 * ```manufacter``` Manufacter name to be displayed.
 * ```model``` Model name to be displayed.
 * ```serial``` Serial number to be displayed.
 * ```delay``` Delay in miliseconds between writes in the clock/data pins.


text:
---
layout: post
title: Bash Scripting
subtitle: Links to help you get started scripting in Bash
tags: [bash, automation]
---

## A collection of really useful links for bash scripting

#### For loops:

##### Here are some links to tutorials I've compiled so you can get some extra practice using/crafting for loops. All of these will contain information we haven't covered yet in addition to the basic for loop.

[https://jvns.ca/blog/2017/03/26/bash-quirks/](https://jvns.ca/blog/2017/03/26/bash-quirks/) [https://astrobiomike.github.io/bash/for_loops](https://astrobiomike.github.io/bash/for_loops) [https://ryanstutorials.net/bash-scripting-tutorial/bash-loops.php](https://ryanstutorials.net/bash-scripting-tutorial/bash-loops.php) [http://tldp.org/LDP/abs/html/loops1.html#EX22](http://tldp.org/LDP/abs/html/loops1.html#EX22)

##### Warning about using the output of 'ls' as a set for a for loop:

[http://mywiki.wooledge.org/ParsingLs](http://mywiki.wooledge.org/ParsingLs)

#### More bash goodies:

[http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/](http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) [https://google.github.io/styleguide/shell.xml](https://google.github.io/styleguide/shell.xml) Test your skills!! [https://cmdchallenge.com/](https://cmdchallenge.com/) Environment to test out code if you think something weird might be going on with your setup (warning - there might also be something weird with this setup, I haven't played with it a whole lot). [https://repl.it/languages](https://repl.it/languages)

#### Regex Practice

![](https://imgs.xkcd.com/comics/regular_expressions.png) (Comic: www.xkcd.com/208)

##### Lots of options for practice - choose your favorite!

[https://regexr.com/](https://regexr.com/) [https://regexone.com/](https://regexone.com/) [http://rubular.com/](http://rubular.com/) Regex combined with sed and awk: [https://likegeeks.com/regex-tutorial-linux/?epik=0wDgLEvIWHzZ9](https://likegeeks.com/regex-tutorial-linux/?epik=0wDgLEvIWHzZ9)

##### Regex golf - match a string with the shortest possible expression:

[https://alf.nu/RegexGolf](https://alf.nu/RegexGolf)

##### Bash scripting cheatsheet: [https://devhints.io/bash](https://devhints.io/bash)

##### Common/userful bash one-liners: [http://www.bashoneliners.com/](http://www.bashoneliners.com/)

##### Friend's github page with too much awesome information to put it into any other category - spend some time digging around: [https://github.com/crazyhottommy/getting-started-with-genomics-tools-and-resources](https://github.com/crazyhottommy/getting-started-with-genomics-tools-and-resources)


text:
---
layout: post
title:  "Webpack HMR and Production"
date:   2017-07-06 14:18:00 -0400
categories:
label: ep-040
number: 40
tiny_description: Use Webpack Hot Module Reload and compile for production.
---

Hot module reloading (HMR) allows Webpack to update the code of your Elm application without losing the state. If you have a complex model and have to walk through several steps to get the state exactly as you want it, HMR will save you a significant amount of development time. Use [elm-hot-loader](https://github.com/fluxxu/elm-hot-loader) to enable it in your Webpack and Elm application.

Once you're ready to deploy your Elm application to production, Webpack can help you compile the app without the debugger, and minify the final file.

### Examples

**webpack.config.js**

```js
const path = require('path')

module.exports = function(env) {
  return {
    entry: './js/app.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js'
    },
    module: {
      loaders: [{
        test: /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        use: [{
          loader: 'elm-hot-loader'
        },{
          loader: 'elm-webpack-loader',
          options: (env && env.production) ? {} : {debug: true, warn: true}
        }]
      }]
    }
  }
}

```

#### Links

* [elm-hot-loader](https://github.com/fluxxu/elm-hot-loader)

repository: thaterikperson/elmseeds

extension: markdown

repo_name: thaterikperson/elmseeds


text:
# altitude-azimuth-calculator
Find out what coordinates you need to point your telescope at to find a specific point in the sky.

This calculation is implemented using the process at http://www.stargazing.net/kepler/altaz.html

To use the calculator one needs to first know:
1. **Latitude** of observing location
2. **Longitude** of observing location
3. **Right Ascension** of location in the sky
4. **Declination** of location in the sky

**ALL ABOVE VALUES MUST BE IN DECIMAL FORMAT**

Happy Stargazing


text:
# READ ME
This repo serves as a place to store summaries and notes about papers I read.

### 2018-12

* Automatic Paper Summary Generation from Visual and Textual Information [[paper](https://arxiv.org/abs/1811.06943v1)][[repo](https://cvpaperchallenge.github.io/AutoPaperSummaryGen/)]


text:
# Getting Started

Let's get started using F2!

First, we need to have a canvas in our page.

```html
<canvas id="myChart"></canvas>
```

Now that we have a canvas we can use, we need to include F2 in our page.

```html
<!-- online -->
<script src="https://gw.alipayobjects.com/os/antv/assets/f2/3.1.0/f2.js"></script>
```

Now, we can create a chart. We add a script to our page:

```javascript
const data = [
  { genre: 'Sports', sold: 275 },
  { genre: 'Strategy', sold: 115 },
  { genre: 'Action', sold: 120 },
  { genre: 'Shooter', sold: 350 },
  { genre: 'Other', sold: 150 },
];

const chart = new F2.Chart({
  id: 'myChart', // the canvas dom's id
  width: 500,
  height: 300
});
// load the data
chart.source(data);
// draw a column chart
chart.interval().position('genre*sold').color('genre');
chart.render();
```

<img src="https://gw.alipayobjects.com/zos/rmsportal/DilorPgmSmZjWNkEqIdp.png" width="256">

It's that easy to get started using F2! From here you can explore the many options that can help you customize your charts with scales, tooltip, axis, geoms, legends and much more.

There are many examples of F2 that are available in the `/demos` folder of `f2.zip` that is attached to every [release](https://github.com/antvis/f2/releases).


text:
# Polly CircuitBreaker extensions for Microsoft.Extensions.DependencyInjection

[![NuGet](https://img.shields.io/nuget/v/Jyb.Polly.CircuitBreaker.DependencyInjection.svg)](https://www.nuget.org/packages/Jyb.Polly.CircuitBreaker.DependencyInjection/)
![Build And Deploy](https://github.com/jybbang/Polly.CircuitBreaker.DependencyInjection/workflows/Build%20And%20Deploy/badge.svg)
[![License: MIT](https://img.shields.io/badge/License-BSD3-yellow.svg)](https://github.com/jybbang/Polly.CircuitBreaker.DependencyInjection/blob/master/LICENSE)

**Polly.CircuitBreaker.DependencyInjection
 is a Polly CircuitBreaker extensions for Microsoft.Extensions.DependencyInjection.**

You can install [Polly.CircuitBreaker.DependencyInjection with NuGet](https://www.nuget.org/packages/Jyb.Polly.CircuitBreaker.DependencyInjection/):

```
Install-Package Jyb.Polly.CircuitBreaker.DependencyInjection
```

To use, with an `IServiceCollection` instance :

```c#
services.AddCircuitBreaker(Configuration);
```
Or, you don't use `IConfiguration`

```c#
services.AddCircuitBreaker();
```

CircuitBreaker Factory is registered as scope. You can configure this with the `serviceLifetime` parameter.

### ICircuitBreaker usage

To use sustainable CircuitBreaker, add a dependency on `ICircuitBreaker` (similar ILogger):

```c#
public class CircuitBreakerBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
{
    private readonly ILogger<TRequest> _logger;
    private readonly ICircuitBreaker<TRequest> _cb;

    public CircuitBreakerBehaviour(ILogger<TRequest> logger, ICircuitBreaker<TRequest> cb)
    {
        _logger = logger;
        _cb = cb;
    }

    public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var policy = _cb.GetPolicy<FallbackHandledException>((ex, t) => _logger.LogWarning("Circuit broken."), () => _logger.LogInformation("Circuit reset."));
        return policy.ExecuteAsync(() => next());
    }
}
```

`ICircuitBreaker<CategoryName>` always return same object when CategoryName is same. (like a ILogger).

That means you can not change configuration after circuit breaker initialized. (for the first time calling the GetPolicy function with parameters.)

### Configuration usage

Starting config with your `appsettings.json` :

```json
"CircuitBreakerOptions" : {
  "CircuitBreakers" : {
    "category1" : { "ExceptionsAllowedBeforeBreaking" : 1, "DurationOfBreak" : "00:01:00" },
    "category2" : { "ExceptionsAllowedBeforeBreaking" : 2, "DurationOfBreak" : "00:02:00" },
    "category3" : { "ExceptionsAllowedBeforeBreaking" : 3, "DurationOfBreak" : "00:03:00" }
  }
}
```

## Copyright

Copyright (c) Jungyoung bang.

### POLLY

[Polly](https://github.com/App-vNext/Polly)


text:
merlinbitte
===========

merlinbitte is a roguelike.

It is based on [libtcod] and written in C++11.

Building
--------

To clone libtcod, you need [mercurial]. Clone libtcod into a directory that is parallel to the
merlinbitte directory:

    hg clone https://bitbucket.org/jice/libtcod
    git clone git://github.com/mntmn/merlinbitte.git

OSX
---

For OSX 10.9, I included a custom makefile for libtcod 1.5.2: libtcod_makefile_osx.

    brew install sdl

    cp ./merlinbitte/libtcod_makefile_osx ./libtcod/
    cd libtcod

Now, comment out line 652 in src/sys_sdl_c.c, the one saying

        CustomSDLMain();

So it says

        //CustomSDLMain();

Then, compile libtcod:

    make -f libtcod_makefile_osx

    cd ../merlinbitte
    make -f Makefile_osx

Linux
-----

On Linux, you need at least GCC 4.7. This was tested with Debian 7.0 testing and on Arch Linux.

    sudo apt-get install libsdl-dev  # (debian linux)
    sudo pacman install sdl          # (arch linux)

    cd libtcod
    make -f makefiles/makefile-linux

    cd ../merlinbitte
    make -f Makefile_linux all

Playing
-------

- cursor keys to move
- t key to take items
- u key to use items from inventory (also use for eating)
- m key to manipulate (close doors)
- s key to smash (windows)
- S key to sleep
- w key to wield/wear

Hint to survive:
Find your way out of the apartment and go north in the staircase. Then immediately go left. Don't waste time, find food quickly and eat it. Find clothes and weapons. Find more food. Don't starve!

License
-------

MIT

  [libtcod]: http://doryen.eptalys.net/libtcod/
  [mercurial]: http://mercurial.selenic.com/

repository: mntmn/merlinbitte

repo_name: mntmn/merlinbitte


text:
# Minecraft Tile Compiler
Create TMS tiles compatible with leaflet using [BlockMap](https://github.com/Minecraft-Technik-Wiki/BlockMap)

## Usage
```
  npm install --global
  tile-compiler --help
```

Or with docker:

```
  docker built -t blocktiles .
  docker run -it -v <mc world folder>:/world -v `pwd`/tiles:/tiles -it blocktiles -m overworld,the_nether,the_end -c PNGQUANT /world
```

Rename `tileConfig.json5.example` to `tileConfig.json5` and edit it to your liking

repository: LambdaCraft/tile-compiler

gha_language: JavaScript

repo_name: LambdaCraft/tile-compiler


text:
---
layout: post
date:	2010-07-02 07:06:00
title:  More signs of the times....
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I was intrigued by this "head meat"

until I realized that it is probably "bheja" or brain....and that "kalu soup" is made from trotters....so you can truly eat, head to foot!

<lj-cut text="a few more">

If, after eating all that, you develop a rash and can't drive...

you have to go for some tharphy....

but then, of course, you will get a headache trying to put your kid in this school:

How rare to find honesty in this world...this auto describes itself as "dangerous".....

And, living in an apartment building where milk sachets are delivered every morning and are often stolen (sometimes by monkeys)...I loved the idea of a Milk Box that I saw on a gate as we walked:

</lj-cut>

In all the rush of traffic, this one intrigued me a lot....

WHOM does s/he call dad? The policeman? God? The fellow-passenger?

It's definitely worth having MLC around all the time!


text:
# UE4 component-based interaction system with built-in replication
by doomtrinity

In this UE4 sample project you'll find a stripped-down version of the interaction system that we're using in the game Retchid.

It's a rather simple system, based on a custom interaction component with built-in replication, that can be used to handle the interaction with objects like buttons, levers, doors, etc.

You can dissect the project, you'll find the documentation in the source files.

Tested on UE 4.22.3 and 4.26.1 (make sure to checkout the matching branch)

![interaction_system_door](https://user-images.githubusercontent.com/16953856/123490853-77f2f300-d615-11eb-9173-a8c493093dcf.PNG)

## Links
- [UE4 Forums](https://forums.unrealengine.com/t/component-based-interaction-system-with-built-in-replication/232091)
- [YouTube](https://www.youtube.com/watch?v=Dd5ZCetPw3w)

repository: muhammadmoizulhaq/InteractionSystem

repo_name: muhammadmoizulhaq/InteractionSystem


text:
# graphql-code-directive

Use a GraphQL Schema Directive to define Javascript logic, have that logic executed as a resolver.

## Links

1. [NPM](https://www.npmjs.com/package/graphql-code-directive)
2. [Examples](https://github.com/danstarns/graphql-code-directive/blob/main/examples/fetch.js)
3. [Blog Post](https://medium.com/@danstarns/writing-javascript-directly-in-your-graphql-schema-285ae7906d94)

## What

Its a directive you can use on Fields:

```graphql
directive @code(source: String!) on FIELD_DEFINITION
```

You define Javascript logic in the `source` argument. The source is wrapped in an IFFE & passed into a [https://nodejs.org/api/vm.html](https://nodejs.org/api/vm.html). Supports Promises & you can use dependency injection via the context.

## Installing

```bash
$ npm install graphql-code-directive
```

## Usage

```js
const { ApolloServer } = require("apollo-server");
const codeDirective = require("graphql-code-directive");
const fetch = require("node-fetch");

const typeDefs = `
    type Todo {
        id: ID!
        userId: ID!
        title: String!
        completed: Boolean
    }

    type Query {
        todos: [Todo]
            @code(
                source: """
                const response = await context.fetch('https://jsonplaceholder.typicode.com/todos');
                return response.json()
                """
            )
    }
`;

const server = new ApolloServer({
  typeDefs: [codeDirective.typeDefs, typeDefs],
  schemaDirectives: {
    code: codeDirective.CodeDirective,
  },
  context: () => {
    return {
      fetch,
    };
  },
});

server.listen(4000).then(() => console.log("http://localhost:4000"));
```

## FAQ

### How to dependency inject ?

Inside the code source you have access to the four global variables:

1. `rootValue`
2. `args`
3. `context`
4. `resolveInfo`

So for example if you were to write a 'Normal' Javascript resolver the variables would map to each argument:

```javascript
function myResolver(rootValue, args, context, resolveInfo) {}
```

### Is this safe ?

Make sure you disable introspection & yes it is safe. You are in control of what the VM has access to, via `context`, and the Node.js team has done a good job at isolating the VM.

### Is it testable ?

Unit testing could become cumbersome, this is because you would have to parse the definitions into an AST in order to access the `source`. You can however write solid integration tests, why not checkout [https://www.apollographql.com/docs/apollo-server/testing/testing/](https://www.apollographql.com/docs/apollo-server/testing/testing/) ?

### Can I use the new Schema Directives ?

Yes! There are 3 exports:

1. `typeDefs` - A string of the directives type definitions
2. `CodeDirective` - A legacy `SchemaDirectiveVisitor` that you are most likely to be familiar with
3. `codeDirective` - A functional approach to Schema Directives that returns a transformer

#### Using with new Schema Directives

```js
const { codeDirective } = require("graphql-code-directive");
const { makeExecutableSchema } = require("@graphql-tools/schema");

const { codeDirectiveTypeDefs, codeDirectiveTransformer } = codeDirective();

let schema = makeExecutableSchema({
  typeDefs: [codeDirectiveTypeDefs, typeDefs],
  resolvers: {},
});

schema = codeDirectiveTransformer(schema);
```

## Licence

MIT licence.

repository: danstarns/graphql-code-directive

branch_name: refs/heads/main

repo_name: danstarns/graphql-code-directive


text:
@title How to export feeds to another reader

If you want to try out another reader, you can copy your feeds from NetNewsWire to that other reader.

Most (maybe all?) readers support a format called OPML. (For the curious: you can find out more about OPML at opml.org.)

To make a copy of your feeds that another reader can import, do this:

1. Choose File > Export Feeds….

2. In the save sheet that appears, choose a location for the file, then click Save.

Now you have a file — probably called MySubscriptions.opml, though you might have changed the name — that you can import into another reader. (Consult the documentation of that other reader for how to import an OPML file.)

gha_language: Objective-C


text:
## CustomNavBar
#### [Download as zip](https://grapecity.github.io/DownGit/#/home?url=https://github.com/GrapeCity/ComponentOne-WinForms-Samples/tree/master/NetFramework\Reports\C1WebReport\CS\CustomNavBar)
____
#### Create a custom navigation bar to page through the report.
____
The sample disables the C1WebReport built-in navigation bar and uses the control's properties and events to build a custom replacement.


text:
# Tea.lock
### _A tea-themed cryptography machine built in spreadsheets_

* Symmetrical key encryption

* Uses standard spreadsheet functions. No hidden tricks, no backdoors, just data being converted into unreadable strings.

* Questions should be directed to<EMAIL_ADDRESS>


text:
# Consumer Driven Contract Tests with Pact & TypeScript

This is a sample project to demonstrate consumer driven contract testing using the PACT framework and TypeScript.

This repo consists of a `provider service` and a `consumer service`. The interactions between these 2 services will be tested used PACT.

The `provider` service which is responsible for CRUD-ing & maintaining a movie database and the `consumer` service makes use of the APIs exposed by the `provider` to do further operations.

## Project Structure

```
├── README.md
├── consumer                                    # consumer service
│   ├── jest.config.js                          # Jest test configurations
│   ├── logs                                    # Logs generated by pact for debugging issues
│   │   └── pact.log
│   ├── package.json
│   ├── src
│   │   ├── actions.ts                          # Contains application business logic
│   └── └── pacts
            └── movies.contract.test.ts         # Contains the consumer contract tests
├── contracts
│   └── movie_consumer-movie_producer.json      # Generated PACT contract
└── provider                                    # provider service
    ├── jest.config.js                          # Jest test configurations
    ├── package.json
    ├── pacts
    │   └── movies.contract.test.ts             # Contains the provider contract tests
    ├── src
    │   ├── actions.ts                          # Contains application business logic
    │   ├── app.ts                              # Contains the API endpoints
    │   ├── data                                # Sqlite Datastore of the service
    │   ├── entity                              # TypeORM entities
    └── └── server.ts                           # Server initializer
```

## Installation

`This project is written with Node version v12.18.4`

Install node

```
https://nodejs.org/en/
```

Install yarn

```
https://classic.yarnpkg.com/en/docs/install#mac-stable
```

## Provider SetUp

Go to the provider directory

```
cd provider/
```

Run yarn to get all the required libraries

```
yarn
```

To run the provider server run

```
yarn start
```

This brings up the application at `http://localhost:3001` You can hit `http://localhost:3001/movies` to return a list of movies in the system

## Consumer SetUp

Go to the consumer directory

```
cd consumer/
```

Run yarn to get all the required libraries

```
yarn
```

## PACT Broker Setup

The tests require a PACT broker to be running. To start the broker run the below command from the root project directory

```
docker-compose up
```

This brings up the broker application as well a PostgreSQL database to store the contracts and verification results.

The broker app can be accessed at `http://localhost:9292/`

## Running Consumer Contract Tests

Go to the consumer directory

```
cd consumer/
```

Run

```
yarn test
```

The above command runs the contract tests and generates the PACT contract file under the `contracts` directory

## Running Provider Contract Tests

Go to the provider directory

```
cd provider/
```

Before running the provider test, you need to bring up the provider server. You can do that by running

```
yarn start
```

Once the application is up run the tests using

```
yarn test
```

The above command picks up the PACT contract file from the `contracts` directory which was generated by the consumer contract tests and run the tests against the provider.

## pact-cli

The docker pact-cli can be used to perform multiple functions like running the verifications, accessing the broker and also to verify whether the application can be deployed safely.

A sample command to run `can-i-deploy`

```
docker run --rm pactfoundation/pact-cli broker can-i-deploy --pacticipant "Movie Consumer" --latest --broker-base-url http://host.docker.internal:9292
```

## References

https://hub.docker.com/r/pactfoundation/pact-cli https://hub.docker.com/r/pactfoundation/pact-broker https://github.com/pact-foundation/pact-js


text:
![Version](https://img.shields.io/badge/version-0.5.1-orange.svg)
![Maintained YES](https://img.shields.io/badge/Maintained%3F-yes-green.svg)
![Ask Me Anything !](https://img.shields.io/badge/Ask%20me-anything-1abc9c.svg)

# ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/ct/ct64r.png?raw=true) **ONLINE TOOLS ([codetabs.com](https://codetabs.com))**

version 0.5.1

1. [Count LOC (lines of code) online from github repos or zipped uploaded folder](#count-loc-online)
2. [Video2Gif](#video2gif)
3. [CORS proxy](#cors-proxy)
4. [Github Stars graphical history](#github-stars-graphical-history)
5. [Alexa Ranking](#alexa)
6. [HTTP Headers](#headers)
7. [API weather temp](#weather)

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/loc48.png?raw=true)
# **COUNT LOC ONLINE**

### **[DEMO and DOCS online](https://codetabs.com/count-loc/count-loc-online.html)**

- Enter user/repo , then click add or select a zipped folder and upload it
- File max size 200mb;
- Petitions are limited to 1 every 5 secs. You will get a 429 error if you exceed

![Example](https://github.com/jolav/codetabs/blob/master/www/_public/images/locExample.png?raw=true)

**API LOC**

*  Make a GET HTTP Request
`https://api.codetabs.com/v1/loc?github=USERNAME/REPONAME`

Example :
https://api.codetabs.com/v1/loc?github=jolav/codetabs

Response (JSON) :

```json
[
 {
  "language": "JavaScript",
  "files": 1,
  "lines": 176,
  "blanks": 14,
  "comments": 6,
  "linesOfCode": 156
 },
 ... more languages
 {
  "language": "Total",
  "files": 8,
  "lines": 921,
  "blanks": 132,
  "comments": 46,
  "linesOfCode": 743
 }
]
```

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/gif48.png?raw=true)
# **VIDEO2GIF**

### **[Read DOCS online](https://codetabs.com/video2gif/video-to-gif.html)**

- Tool for converting videos to animated gifs
- File max size 100mb
- Limit : 1 request every 30 seconds. Once reached subsequent requests will result in error 429 (too many requests) until your quota is cleared.

**Parameters**

Frames : Set frame rate (frames per second). Max value 10, default 5.

Start : Seek to given time position in seconds. "hh:mm:ss" syntax is also supported. Default is from start
> - 100 - begin from second 100
> - 01:40 - begin from minute 1 and second 40

Duration : Restrict the captured video sequence to the duration specified in seconds. "hh:mm:ss" syntax is also supported. Default is all duration
> - 200 - take 200 seconds from start
> - 03:20 - take 3 minutes and 20 seconds from start

Scale : Set width:height , if one parameter is -1 it will automatically determine the other while preserving the aspect ratio. Default is 320:160. Max 480.
> - 480:480 set width = 480 and height = 480
> - 380:-1 set width = 380 and height automatically preserving the aspect ratio
> - -1:320 set height = 320 and width automatically preserving the aspect ratio

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/proxy48.png?raw=true)
# **CORS-PROXY**

### **[Read DOCS online](https://codetabs.com/cors-proxy/cors-proxy.html)**

- Free CORS proxy server to bypass same-origin policy related to performing standard AJAX requests to 3rd party services.
You can use to prevent mixed content of images and JSON data proxying the resources to serve them under https.
- API URL => append the url with the resource you want to "https://api.codetabs.com/v1/proxy/"
- Each request is limited to 5mb (2mb for old endpoint) size download to avoid abuse.
- Only suppports GET request.
- Limit : 5 request per second. Once reached subsequent requests will result in error 429 (too many requests) until your quota is cleared.

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/stars48.png?raw=true)
# **GITHUB STARS GRAPHICAL HISTORY**

### **[DEMO online](https://codetabs.com/github-stars/github-star-history.html)**

- Enter user/repo , then click add.
- Petitions are limited to 1 every 5 secs. You will get a 429 error if you exceed

![Example](https://github.com/jolav/codetabs/blob/master/www/_public/images/starExample.png?raw=true)

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/alexa48.png?raw=true)
# **ALEXA**

Tool for know Alexa Ranking Top 1 million about a website.

### **[Get Alexa Ranking Online](https://codetabs.com/alexa/alexa-ranking.html)**

- Petitions are limited to 5 per second. You will get a 429 error if you exceed

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/headers48.png?raw=true)
# **HEADERS**

Tool to get list of response headers including redirect chain of a HTTP connection

### **[DEMO and DOCS online](https://codetabs.com/http-headers/headers.html)**

- Petitions are limited to 5 per second. You will get a 429 error if you exceed

## ![logo](https://github.com/jolav/codetabs/blob/master/www/_public/icons/weather48.png?raw=true)
# **WEATHER**

### **[Read DOCS online](https://codetabs.com/weather/weather.html)**

- Petitions are limited to 5 per sec. You will get a 429 error if you exceed
- CORS is enabled allowing Javascript make requests across domain boundaries
- Supported formats, json and xml

## **Acknowledgment**

* This site includes Curtis Gagliardi cgag/loc for counting lines of code.

repository: aspiringdevslog/codetabs

repo_name: aspiringdevslog/codetabs


text:
# Authentications

## API key in HTTP header

``X-Api-Key: XXXXXXXXXXXXXXXXXXXX``

## User auth  & cookie

TODO

# Resources

## Photo

### POST /api/v1/photo

Request:
body: multipart
    - properties: entities.Photo
    - file: photo
Response:
response.Data = entities.Photo

### PUT /api/v1/photo

body: model.Photo (JSON)

response code: 200

response body: Json {"code": int, "photo": models.Photo }

code:
- 0: ok
- 1: Name is too long (max length: 255)
- 2: Camera is too long (max length: 255)
- 3: Lens is too long (max length: 255)
- 4: ShutterSpeed is too long (max length: 255)
- 5: Location is too long (max length: 255)
- 6: Latitude is out of range ( -90.00 < latitude < +90.00
- 7: Longitude is out of range (-180 < longitude < +180.00
- 8: Hey Marty "TakenAt" is in the future !

### GET /api/v1/photo/:id

response: -> JSON model.Photo

### DELETE /api/v1/photo/:id

response: 204 (if success)

### GET /api/v1/photo/search

for now return all photos

response: []model.Photo (JSON)

repository: peerpx/peerpx

repo_name: peerpx/peerpx


text:
# Saturate Nodes Load Balancer Plugin

A Jenkins plugin which allows to saturate nodes as much as possible.

Table of contents
---

1. [Overview](#overview)
1. [Building](#building)
1. [Basic Usage](#basic-usage)
1. [Authors](#authors)
1. [License](#license)

Overview
---

By default Jenkins uses a consistent hashing algorithm for load balancing: It always tries to execute a job on the same node where it was executed before.
This approach has one big disadvantage in case of cloud based CI - it keeps a lot of nodes up and running.

The Saturate Nodes Load Balancer plugin addresses this issue using a pretty simple algorithm:
- Select nodes of the specified label.
- Order node based on the time it was connected to the Jenkins master.
- Pick-up the available executor.

As a result it should minimize the number of used nodes.

Let's take a look at an example. Suppose there is only one node:
- nodeA with 4 executors (e1, e2, e3, e4)

Now you need to run 10 builds from 10 different jobs. To avoid a queue you use some cloud plugin (let's say [EC2 Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Amazon+EC2+Plugin)), which will dynamically spawn more nodes:
- nodeB with 4 executors (e5, e6, e7, e8)
- nodeC with 4 executors (e9, e10, e11, e12)

According to Jenkins history this would result in something like:
- nodeA => j1#1
- nodeA => j2#1
- nodeA => j3#1
- nodeA => j4#1
- nodeB => j5#1
- nodeB => j6#1
- nodeB => j7#1
- nodeB => j8#1
- nodeC => j9#1
- nodeC => j10#1

When new builds from some of these jobs will be started, they will get executed on same nodes:
- nodeA => j1#2
- nodeB => j5#2
- nodeB => j8#2
- nodeC => j9#2

As a result, the cloud plugin will not be able to shutdown any node, because it none is idle.

With the Saturate Nodes Load Balancer Plugin this would simply look like:
- nodeA => j1#2
- nodeA => j5#2
- nodeA => j8#2
- nodeA => j9#2

And nodeB and nodeC are not needed anymore - the cloud plugin can shut them down.

Of course, such a simple implementation has some disadvantages as well:
- It always tries to use all executors of each node.
- It does not take into account any kind of history to balance the jobs.
- Old nodes will have no chance to get replaced.

Building
---

Prerequisites:

- JDK 7 (or above)
- Apache Maven

Build process is straight forward:

```Shell
mvn install
```

Basic Usage
---

To get started:

1. Install the plugin.
1. Go to the Jenkins Configuration.
1. Find "Saturate Nodes Load Balancer".
1. Enable "Override default load balancer".

The plugin allows you to enable/disable the Load Balancer on-the-fly.

If you want to monitor its logs, you can add `org.jenkinsci.plugins.saturatenodes.SaturateNodesLoadBalancer` to the [loggers](https://wiki.jenkins-ci.org/display/JENKINS/Logging) of your Jenkins master.

Also, you can configure the [system Groovy script](https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin) and execute it during the night (to minimize number of used nodes in nightly builds):
```groovy
import org.jenkinsci.plugins.saturatenodes.SaturateNodesLoadBalancer

Jenkins.getInstance().getQueue().setLoadBalancer(new SaturateNodesLoadBalancer())
```
And to restore default one:
```groovy
import hudson.model.LoadBalancer

Jenkins.getInstance().getQueue().setLoadBalancer(LoadBalancer.CONSISTENT_HASH)
```

Authors
---

Alexander Akbashev -<EMAIL_ADDRESS>
License
---

Licensed under the [MIT License (MIT)](LICENSE).


text:
---
layout: page
category: Documentation
title: Diff Examples
submenu: diff-examples
sidebar-url: docs-sidebar.html
---

All examples are runnable.
Checkout our github repository:

```text
git clone https://github.com/javers/javers.git
cd javers
```

Run examples as unit tests:

```text
./gradlew javers-core:test --tests BasicEntityDiffExample
```

Compare two Entity objects

Let’s start with something simple. This example shows how to find a diff between two objects of
the `Employee` class. Every employee has his own identity, so the `Employee` class is mapped as Entity.
Our employee has some basic properties, collections, and references.
Just the usual stuff.

**The case**

We have two objects, `frodoOld` and `frodoNew`.
These objects represent two versions of the same being (a person called Frodo).
To find out what’s changed, just call:

```java
    javers.compare(frodoOld, frodoNew)
```

**Configuration**

JaVers needs to know that the `Employee` class is an
[Entity](/documentation/domain-configuration/#entity)
and the `Address` class is a
[Value Object](/documentation/domain-configuration/#value-object).
It’s enough to annotate the `name` field with the `@Id` annotation to map `Employee` as Entity.
`Address` is mapped as Value Object by default.
See [domain-model-mapping](/documentation/domain-configuration/#domain-model-mapping) for
more details about JaVers’ type system.

**What’s important**

Notice that both objects have the same Id value — `'Frodo'`.
That’s why they are matched and compared.
JaVers matches only objects with the same
[`GlobalId`]({{ site.github_core_main_url }}org/javers/core/metamodel/object/GlobalId.java).
In this case, the GlobalId value is: `'Employee/Frodo'`.
Without the `@TypeName` annotation, it would be `'org.javers.core.examples.model.Employee/frodo'`.

[`Employee.java`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/model/Employee.java):

```java
@TypeName("Employee")
public class Employee {

    @Id
    private String name;

    private Position position;

    private int salary;

    private int age;

    private Employee boss;

    private List<Employee> subordinates = new ArrayList<>();

    private Address primaryAddress;

    private Set<String> skills;

    ... // omitted
}
```

[`Address.java`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/model/Address.java):

```java
public class Address {
    private String city;

    private String street;

    ... // omitted
}
```

[`BasicEntityDiffExample.java`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/BasicEntityDiffExample.java):

```java
@Test
public void shouldCompareTwoEntities() {
  //given
  Javers javers = JaversBuilder.javers()
          .withListCompareAlgorithm(LEVENSHTEIN_DISTANCE)
          .build();

  Employee frodoOld = EmployeeBuilder.Employee("Frodo")
          .withAge(40)
          .withPosition("Townsman")
          .withSalary(10_000)
          .withPrimaryAddress(new Address("Shire"))
          .withSkills("management")
          .withSubordinates(new Employee("Sam"))
          .build();

  Employee frodoNew = EmployeeBuilder.Employee("Frodo")
          .withAge(41)
          .withPosition("Hero")
          .withBoss(new Employee("Gandalf"))
          .withPrimaryAddress(new Address("Mordor"))
          .withSalary(12_000)
          .withSkills("management", "agile coaching")
          .withSubordinates(new Employee("Sméagol"), new Employee("Sam"))
          .build();

  //when
  Diff diff = javers.compare(frodoOld, frodoNew);

  //then
  assertThat(diff.getChanges()).hasSize(14);
}
```

The resulting [`Diff`]({{ site.github_core_main_url }}org/javers/core/diff/Diff.java)
is a container for the list of [`Changes`]({{ site.github_core_main_url }}org/javers/core/diff/Change.java).

There are three main types of Changes:

* [NewObject]({{ site.github_core_main_url }}org/javers/core/diff/changetype/NewObject.java) —
  when an object is present only in the right graph,
* [ObjectRemoved]({{ site.github_core_main_url }}org/javers/core/diff/changetype/ObjectRemoved.java) —
  when an object is present only in the left graph,
* [PropertyChange]({{ site.github_core_main_url }}org/javers/core/diff/changetype/PropertyChange.java) —
  most common — a changed property (field or getter).

PropertyChange has the following subtypes:

* [ContainerChange]({{ site.github_core_main_url }}org/javers/core/diff/changetype/container/ContainerChange.java)
  — list of changed items in Set, List or Array,
* [MapChange]({{ site.github_core_main_url }}org/javers/core/diff/changetype/map/MapChange.java)
  — list of changed Map entries,
* [ReferenceChange]({{ site.github_core_main_url }}org/javers/core/diff/changetype/ReferenceChange.java)
  — changed Entity reference,
* [ValueChange]({{ site.github_core_main_url }}org/javers/core/diff/changetype/ValueChange.java)
  — changed Primitive or Value.

**You can print** the list of Changes using `prettyPrint()`:

```java
System.out.println("diff pretty print:");
System.out.println(diff.prettyPrint());
```

output:

```text
diff pretty print:
Diff:
* new object: Employee/Sméagol
  - 'boss' = 'Employee/Frodo'
  - 'name' = 'Sméagol'
  - 'salary' = '10000'
* new object: Employee/Gandalf
  - 'name' = 'Gandalf'
  - 'salary' = '10000'
* changes on Employee/Frodo :
  - 'age' changed: '40' -> '41'
  - 'boss' = 'Employee/Gandalf'
  - 'position' changed: 'Townsman' -> 'Hero'
  - 'primaryAddress.city' changed: 'Shire' -> 'Mordor'
  - 'salary' changed: '10000' -> '12000'
  - 'skills' collection changes :
     · 'agile coaching' added
  - 'subordinates' collection changes :
     0. 'Employee/Sméagol' added
```

**Iterating** over the list of Changes:

```java
System.out.println("iterating over changes:");
diff.getChanges().forEach(change -> System.out.println("- " + change));
```

output:

```
iterating over changes:
- NewObject{ new object: Employee/Gandalf }
- NewObject{ new object: Employee/Sméagol }
- InitialValueChange{ property: 'name', left:'',  right:'Sméagol' }
- InitialValueChange{ property: 'salary', left:'',  right:'10000' }
- ReferenceChange{ property: 'boss', left:'',  right:'Employee/Frodo' }
- InitialValueChange{ property: 'name', left:'',  right:'Gandalf' }
- InitialValueChange{ property: 'salary', left:'',  right:'10000' }
- ValueChange{ property: 'position', left:'Townsman',  right:'Hero' }
- ValueChange{ property: 'salary', left:'10000',  right:'12000' }
- ValueChange{ property: 'age', left:'40',  right:'41' }
- ReferenceChange{ property: 'boss', left:'',  right:'Employee/Gandalf' }
- ListChange{ property: 'subordinates', elementChanges:1, left.size: 1, right.size: 2}
- SetChange{ property: 'skills', elementChanges:1, left.size: 1, right.size: 2}
- ValueChange{ property: 'city', left:'Shire',  right:'Mordor' }
```

Iterating over the list of Changes **grouped by objects**:

```java
System.out.println("iterating over changes grouped by objects");
diff.groupByObject().forEach(byObject -> {
    System.out.println("* changes on " +byObject.getGlobalId().value() + " : ");
    byObject.get().forEach(change -> System.out.println("  - " + change));
});
```

output:

```
iterating over changes grouped by objects
* changes on Employee/Sméagol :
  - NewObject{ new object: Employee/Sméagol }
  - InitialValueChange{ property: 'name', left:'',  right:'Sméagol' }
  - InitialValueChange{ property: 'salary', left:'',  right:'10000' }
  - ReferenceChange{ property: 'boss', left:'',  right:'Employee/Frodo' }
* changes on Employee/Gandalf :
  - NewObject{ new object: Employee/Gandalf }
  - InitialValueChange{ property: 'name', left:'',  right:'Gandalf' }
  - InitialValueChange{ property: 'salary', left:'',  right:'10000' }
* changes on Employee/Frodo :
  - ValueChange{ property: 'position', left:'Townsman',  right:'Hero' }
  - ValueChange{ property: 'salary', left:'10000',  right:'12000' }
  - ValueChange{ property: 'age', left:'40',  right:'41' }
  - ReferenceChange{ property: 'boss', left:'',  right:'Employee/Gandalf' }
  - ListChange{ property: 'subordinates', elementChanges:1, left.size: 1, right.size: 2}
  - SetChange{ property: 'skills', elementChanges:1, left.size: 1, right.size: 2}
  - ValueChange{ property: 'city', left:'Shire',  right:'Mordor' }
```

Diff can be easily **serialized to JSON**:

```java
System.out.println(javers.getJsonConverter().toJson(diff));
```

```json
{
  "changes": [
    {
      "changeType": "NewObject",
      "globalId": {
        "entity": "Employee",
        "cdoId": "Gandalf"
      }
    },
    {
      "changeType": "NewObject",
      "globalId": {
        "entity": "Employee",
        "cdoId": "Sméagol"
      }
    },
    {
      "changeType": "InitialValueChange",
      "globalId": {
        "entity": "Employee",
        "cdoId": "Gandalf"
      },
      "property": "name",
      "propertyChangeType": "PROPERTY_VALUE_CHANGED"
    }
...
```

Compare graphs

JaVers can compare arbitrary complex structures of objects.
In this example, we show how you can deeply compare employee hierarchies to detect specific types of changes.

For simplicity of this example, the data model is reduced to the one class —
[Employee](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/model/Employee.java)
 (the same as in the previous example).

Conceptually, an employee hierarchy is a tree.
Technically, we have a graph with cycles here (since the relationship between boss and employees is bidirectional).

**The case**

We are comparing two versions (historical states) of the employee hierarchy in order
to detect the four types of changes:

- employee hired — `NewObject`,
- employee fired — `ObjectRemoved`,
- salary change — `ValueChange`,
- boss change — `ReferenceChange`.

**Configuration**

JaVers needs to know that `Employee` class is an [Entity](/documentation/domain-configuration/#entity).
It’s enough to annotate the `name` field with the `@Id` annotation.

**What’s important**

JaVers makes no assumptions about your data structures
and treats them just like graphs with cycles (the same as JVM does).
There are no limitations on the number of nodes in the graph.

[`shouldDetectHired()`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java#L14):

```java
/** NewObject example */
@Test
public void shouldDetectHired() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss").addSubordinates(
          new Employee("Great Developer"));

  Employee newBoss = new Employee("Big Boss").addSubordinates(
          new Employee("Great Developer"),
          new Employee("Hired One"),
          new Employee("Hired Second"));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  assertThat(diff.getObjectsByChangeType(NewObject.class))
      .hasSize(2)
      .containsOnly(new Employee("Hired One"),
                    new Employee("Hired Second"));

  System.out.println(diff);
}
```

output:

```text
Diff:
* new object: Employee/Hired One
  - 'boss' = 'Employee/Big Boss'
  - 'name' = 'Hired One'
  - 'salary' = '10000'
* new object: Employee/Hired Second
  - 'boss' = 'Employee/Big Boss'
  - 'name' = 'Hired Second'
  - 'salary' = '10000'
* changes on Employee/Big Boss :
  - 'subordinates' collection changes :
     1. 'Employee/Hired One' added
     2. 'Employee/Hired Second' added
```

[`shouldDetectFired()`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java):

```java
/** ObjectRemoved example */
@Test
public void shouldDetectFired() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Great Developer"),
      new Employee("Team Lead").addSubordinates(
              new Employee("Another Dev"),
              new Employee("To Be Fired")
      ));

  Employee newBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Great Developer"),
      new Employee("Team Lead").addSubordinates(
              new Employee("Another Dev")
      ));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  assertThat(diff.getChangesByType(ObjectRemoved.class)).hasSize(1);

  System.out.println(diff);
}
```

output:

```text
Diff:
* object removed: Employee/To Be Fired
  - 'boss' reference 'Employee/Team Lead' unset
  - 'name' value 'To Be Fired' unset
  - 'salary' value '10000' unset
* changes on Employee/Team Lead :
  - 'subordinates' collection changes :
     1. 'Employee/To Be Fired' removed
```

[`shouldDetectSalaryChange()`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java):

```java
  /** ValueChange example */
  @Test
  public void shouldDetectSalaryChange(){
    //given
    Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Noisy Manager"),
      new Employee("Great Developer", 10000));

  Employee newBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Noisy Manager"),
      new Employee("Great Developer", 20000));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  ValueChange change =  diff.getChangesByType(ValueChange.class).get(0);

  assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
  assertThat(change.getPropertyName()).isEqualTo("salary");
  assertThat(change.getLeft()).isEqualTo(10000);
  assertThat(change.getRight()).isEqualTo(20000);

  System.out.println(diff);
}
```

output:

```text
Diff:
* changes on Employee/Great Developer :
  - 'salary' changed: '10000' -> '20000'
```

[`shouldDetectBossChange()`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/EmployeeHierarchiesDiffExample.java#L102):

```java
/** ReferenceChange example */
@Test
public void shouldDetectBossChange() {
  //given
  Javers javers = JaversBuilder.javers().build();

  Employee oldBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Manager One")
         .addSubordinate(new Employee("Great Developer")),
      new Employee("Manager Second"));

  Employee newBoss = new Employee("Big Boss").addSubordinates(
      new Employee("Manager One"),
      new Employee("Manager Second")
         .addSubordinate(new Employee("Great Developer")));

  //when
  Diff diff = javers.compare(oldBoss, newBoss);

  //then
  ReferenceChange change = diff.getChangesByType(ReferenceChange.class).get(0);

  assertThat(change.getAffectedLocalId()).isEqualTo("Great Developer");
  assertThat(change.getLeft().value()).endsWith("Manager One");
  assertThat(change.getRight().value()).endsWith("Manager Second");

  System.out.println(diff);
}
```

output:

```text
Diff:
* changes on Employee/Manager One :
  - 'subordinates' collection changes :
     0. 'Employee/Great Developer' removed
* changes on Employee/Great Developer :
  - 'boss' reference changed: 'Employee/Manager One' -> 'Employee/Manager Second'
* changes on Employee/Manager Second :
  - 'subordinates' collection changes :
     0. 'Employee/Great Developer' added
```

Compare top-level Value Objects

This example shows how to find a diff between two objects of the `Address` class.
Address is a typical [Value Object](/documentation/domain-configuration/#value-object), it doesn’t have its own identity.
It’s just a complex value holder.

**The case**

We have two objects, `address1` and `address2`. These objects represent two different addresses.
To find out what the difference is, just call:

```java
javers.compare(address1, address2)
```

**What’s important**

When JaVers knows nothing about a class, it treats it as Value Object.
As we said in the previous example, JaVers compares only objects with the same GlobalId.

What’s the Address Id? It’s based on the path in the object graph.
In this case, both objects are roots, so the path is simply `'/'`
and the GlobalId is `'org.javers.core.examples.model.Address/'`.

[`Address.java`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/model/Address.java):

```java
public class Address {
    private String city;

    private String street;

    ... // omitted
}
```

[`BasicValueObjectDiffExample.java`](https://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/BasicValueObjectDiffExample.java):

```java
@Test
public void shouldCompareTwoObjects() {

  //given
  Javers javers = JaversBuilder.javers().build();

  Address address1 = new Address("New York","5th Avenue");
  Address address2 = new Address("New York","6th Avenue");

  //when
  Diff diff = javers.compare(address1, address2);

  //then
  //there should be one change of type {@link ValueChange}
  ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

  assertThat(diff.getChanges()).hasSize(1);
  assertThat(change.getAffectedGlobalId().value())
            .isEqualTo("org.javers.core.examples.model.Address/");
  assertThat(change.getPropertyName()).isEqualTo("street");
  assertThat(change.getLeft()).isEqualTo("5th Avenue");
  assertThat(change.getRight()).isEqualTo("6th Avenue");

  System.out.println(diff);
}
```

The output of running this program is:

```
Diff:
* changes on org.javers.core.examples.model.Address/ :
  - 'street' changed: '5th Avenue' -> '6th Avenue'
```

Compare top-level collections

JaVers can compare arbitrary complex structures of objects,
including collections passed as top-level handles.

If you want to compare top-level collections with Primitives or
[Values](/documentation/domain-configuration/#ValueType)
(see [domain-model-mapping](/documentation/domain-configuration/#domain-model-mapping)),
you can use the standard `javers.compare(Object, Object)` method.
Collection items will be compared using `equals()`, resulting in a flat list of Changes.

But when you need to compare top-level collections with complex items,
like Entities or Value Objects, use `javers.compareCollections(Collection, Collection, Class)`.
This method builds object graphs and compares them deeply,
using `itemClass` as a hint about the item’s type.

**The case**

When collections are properties of a domain object, for example:

```java
public class Boss {
    @Id private String name;

    private final List<Person> subordinates = new ArrayList<>();
}
```

JaVers uses Reflection and captures `Person` as the item type in the `subordinates` collection.

But when collections are passed as top-level references, for example:

```java
Diff diff = javers.compare(oldList, newList);
```

due to type erasure, there is no way to statically determine the type of items stored in collections.

Luckily, `compareCollections()` comes to the rescue
and gives you exactly the same diff result for top-level collections as if they were object properties.

[`ComparingTopLevelCollectionExample`<wbr/>`.java`](http://github.com/javers/javers/blob/master/javers-core/src/test/java/org/javers/core/examples/ComparingTopLevelCollectionExample.java):

```java
  @Test
  public void shouldDeeplyCompareTwoTopLevelCollections() {
    //given
    Javers javers = JaversBuilder.javers().build();

    List<Person> oldList = Lists.asList( new Person("tommy", "Tommy Smart") );
    List<Person> newList = Lists.asList( new Person("tommy", "Tommy C. Smart") );

    //when
    Diff diff = javers.compareCollections(oldList, newList, Person.class);

    //then
    //there should be one change of type {@link ValueChange}
    ValueChange change = diff.getChangesByType(ValueChange.class).get(0);

    assertThat(diff.getChanges()).hasSize(1);
    assertThat(change.getPropertyName()).isEqualTo("name");
    assertThat(change.getLeft()).isEqualTo("Tommy Smart");
    assertThat(change.getRight()).isEqualTo("Tommy C. Smart");

    System.out.println(diff);
  }
```

The output:

```text
Diff:
* changes on org.javers.core.examples.model.Person/tommy :
  - 'name' changed: 'Tommy Smart' -> 'Tommy C. Smart'
```

Groovy diff example

In JaVers we love the [Groovy](http://www.groovy-lang.org/) language.
From the very beginning of the JaVers project, we used the [Spock framework](http://docs.spockframework.org)
for writing tests.
One of Groovy’s killer features is excellent interoperability with Java.
Looking from the other side, modern Java frameworks should be Groovy friendly.

As you know, all Java classes extend the `Object` class.
All Groovy classes extend `GroovyObject`,
that’s how Groovy implements its metaprogramming features.

Good news, JaVers is fully compatible with Groovy!
You can compare and commit Groovy objects in the same way as plain Java objects.
Let’s see how it works:

[`GroovyDiffExample.groovy`](http://github.com/javers/javers/blob/master/javers-core/src/test/groovy/org/javers/core/examples/GroovyDiffExample.groovy):

```groovy
class GroovyDiffExample extends Specification {

    @TupleConstructor
    class Person {
        @Id login
        String lastName
    }

    def "should calculate diff for GroovyObjects"(){
      given:
      def javers = JaversBuilder.javers().build()

      when:
      def diff = javers.compare(
          new Person('bob','Uncle'),
          new Person('bob','Martin')
      )

      then:
      diff.changes.size() == 1
      diff.changes[0].left == 'Uncle'
      diff.changes[0].right == 'Martin'
    }
}
```

No special JaVers configuration is required for Groovy.
In the example, we use the `FIELD` (default) mapping style.
Since Groovy generates getters and setters on the fly, you
can also use the `BEAN` mapping style without adding boilerplate code to domain classes.

## Custom Value comparator example

In this example, we show how to use
[Custom Value comparators](/documentation/diff-configuration/#custom-value-comparators)
to play with `BigDecimals` equality.

Javers comes with two Custom comparators for `BigDecimals`,
they are ready to use in your project:

* [`CustomBigDecimalComparator`](https://github.com/javers/javers/blob/master/javers-core/src/main/java/org/javers/core/diff/custom/CustomBigDecimalComparator.java)
  compares BigDecimals after rounding to the required scale,
* [`BigDecimalComparatorWithFixedEquals`](https://github.com/javers/javers/blob/master/javers-core/src/main/java/org/javers/core/diff/custom/BigDecimalComparatorWithFixedEquals.java)
  compares BigDecimals in the correct (arithmetical) way — ignoring trailing zeros.

[`CustomBigDecimalComparator.java`](https://github.com/javers/javers/blob/master/javers-core/src/main/java/org/javers/core/diff/custom/CustomBigDecimalComparator.java):

```java
public class CustomBigDecimalComparator implements CustomValueComparator<BigDecimal>{
    private int significantDecimalPlaces;

    public CustomBigDecimalComparator(int significantDecimalPlaces) {
        this.significantDecimalPlaces = significantDecimalPlaces;
    }

    @Override
    public boolean equals(BigDecimal a, BigDecimal b) {
        return round(a).equals(round(b));
    }

    @Override
    public String toString(BigDecimal value) {
        return round(value).toString();
    }

    private BigDecimal round(BigDecimal val) {
        return val.setScale(significantDecimalPlaces, ROUND_HALF_UP);
    }
}
```

Comparing `BigDecimals` rounded to two decimal digits (Groovy):

```groovy
class ValueObject {
    BigDecimal value
    List<BigDecimal> values
}

def "should compare BigDecimal properties with desired precision"(){
  given:
  def javers = JaversBuilder.javers()
         .registerValue(BigDecimal, new CustomBigDecimalComparator(2)).build()

  expect:
  javers.compare(new ValueObject(value: 1.123), new ValueObject(value: 1.124)).changes.size() == 0
  javers.compare(new ValueObject(value: 1.12),  new ValueObject(value: 1.13)).changes.size()  == 1
}
```

[`BigDecimalComparatorWithFixedEquals.java`](https://github.com/javers/javers/blob/master/javers-core/src/main/java/org/javers/core/diff/custom/BigDecimalComparatorWithFixedEquals.java):
```java
public class BigDecimalComparatorWithFixedEquals implements CustomValueComparator<BigDecimal> {
    @Override
    public boolean equals(BigDecimal a, BigDecimal b) {
        return a.compareTo(b) == 0;
    }

    @Override
    public String toString(BigDecimal value) {
        return value.stripTrailingZeros().toString();
    }
}
```

Comparing `BigDecimals` in the correct, arithmetical way (Groovy):

```groovy
def "should compare BigDecimal with fixed equals"() {
    when: "comparing using BigDecimal.equals()"
    def javers = JaversBuilder.javers().build()

    then:
    javers.compare(new ValueObject(value: 1.000), new ValueObject(value: 1.00)).changes.size() == 1

    when: "comparing using arithmetical equals()"
    javers = JaversBuilder.javers()
            .registerValue(BigDecimal, new BigDecimalComparatorWithFixedEquals())
            .build()

    then:
    javers.compare(new ValueObject(value: 1.000), new ValueObject(value: 1.00)).changes.size() == 0
    javers.compare(new ValueObject(value: 1.100), new ValueObject(value: 1.20)).changes.size() == 1
}
```

## Custom Property comparator example

In this example, we show how to use a
[Custom Property comparator](/documentation/diff-configuration/#custom-property-comparators)
to calculate `SetChange`.
Our comparator is called `FunnyStringComparator` and it compares Strings as character Sets.
The logic is simple. When two Strings are built from the same set of characters —
we don’t see a difference. Otherwise, we log each added or removed character.

Check the full example implemented in
[CustomPropertyComparatorExample.groovy](https://github.com/javers/javers/blob/master/javers-core/src/test/groovy/org/javers/core/examples/CustomPropertyComparatorExample.groovy)
as a Spock test.
Here we show the most essential part.

First, the comparator implementation:

```groovy
/**
 * Compares Strings as character sets
 */
class FunnyStringComparator implements CustomPropertyComparator<String, SetChange> {
    @Override
    Optional<SetChange> compare(String left, String right, PropertyChangeMetadata metadata, Property property) {
        if (equals(left, right)) {
            return Optional.empty()
        }

        Set leftSet = left.toCharArray().toSet()
        Set rightSet = right.toCharArray().toSet()

        List<ContainerElementChange> changes = []
        Sets.difference(leftSet, rightSet).forEach{c -> changes.add(new ValueRemoved(c))}
        Sets.difference(rightSet, leftSet).forEach{c -> changes.add(new ValueAdded(c))}

        return Optional.of(new SetChange(metadata, changes))
    }

    @Override
    boolean equals(String a, String b) {
        a.toCharArray().toSet() == b.toCharArray().toSet()
    }

    @Override
    String toString(String value) {
        return value;
    }
}
```

In the test, we compare two Value Objects with a `String` property:

```groovy
class ValueObject {
    String value
}
```

Let’s see how `FunnyStringComparator` compares String properties:

```groovy
def "should use FunnyStringComparator to compare String properties"(){
    given:
    def javers = JaversBuilder.javers()
            .registerCustomType(String, new FunnyStringComparator()).build()

    when:
    def diff = javers.compare(new ValueObject(value: "aaa"), new ValueObject(value: "a"))
    println "first diff: "+ diff

    then:
    diff.changes.size() == 0

    when:
    diff = javers.compare(new ValueObject(value: "aaa"), new ValueObject(value: "b"))
    println "second diff: "+ diff

    then:
    diff.changes.size() == 1
    diff.changes[0] instanceof SetChange
    diff.changes[0].changes.size() == 2 // two item changes in this SetChange
}
```

output:

```text
first diff: Diff:

second diff: Diff:
* changes on org.javers.core.examples.CustomPropertyComparatorExample$Entity/ :
  - 'value' collection changes :
    . 'a' removed
    . 'b' added
```


text:
# `bililiteRange` data

Often, we want to keep data that is specific to a given element, and shared by all ranges on that element.
Simply setting `element.foo = bar` works, but in the olden days (Internet Explorer 6) that
caused [memory leaks](http://crockford.com/javascript/memory/leak.html). That is no longer a problem, but
putting so many new fields on the element lacks a certain elegance. So we create a single field, `element.bililiteRangeData`,
and store all our fields in that, with `element.bililiteRangeData.foo = bar`.

To avoid any possibility of a name conflict, we use a private variable `const dataKey = Symbol()` and actually do
`element[dataKey].foo`. To expose that (since `dataKey` is not exposed)
we define for each range `range.data = range.element[dataKey]`.

So, for example,

````js
let range = bililiteRange( document.querySelector('div.editor') );
range.data.hilighter = 'Prism';

// elsewhere in the code
let range2 = bililiteRange( document.querySelector('div.editor') );
console.log(range2.data.hilighter); // 'Prism'
````

## Options

That works well, but I created `bililiteRange` in part to implement the [ex line editor](ex.md), and I want some data to have default
values that can be changed for each element. So `data` is actually an object with a prototype.
`bililiteRange.createOption(prop, descriptor)` does `Object.defineProperty(data.prototype, prop, descriptor)`. Now every range has a
property `prop` with an
[object descriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).

So to set `autoindent`, do `bililiteRange.createOption('autoindent', {value: false})`.

The difference with `Object.defineProperty` is that the defaults are `{
		enumerable: true,
		writable: true,
		configurable: true
	}` rather than `false`.

## Monitored options

There is one more option that can be added to the property descriptor: `monitored`. `bililiteRange.createOption(prop, {monitored: true})`
adds a `set` handler for `prop` that, whenever `prop` is set (as in `range.data[prop] = newValue`), that change is signaled in two ways:

1. ``range.dispatch(CustomEvent(`data-${prop}`, {detail: newValue}))`` for use with EventListeners.

2. ``range.element.setAttribute(`data-${prop}`, newValue)`` for use with MutationObservers. Note that attributes have very limited legal
characters, so this will silently fail if `data-${prop}` is not a legal attribute name.

### `data.trigger`

The function `range.data.trigger()` will trigger the `CustomEvent` and `setAttribute` for all monitored options. This is useful for initializing
things after defining the data, without setting options to differ from their defaults. Call this after all your `bililiteRange.createOption`s
(the program can't call this automatically since there's no way to know when the user is done).

## JSON

`bililiteRange.prototype.ex` uses
[`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) to display
options. The data object, therefore has a
[`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior) method
that only returns `data` fields that were defined with `bililiteRange.createOption` *and* are defined on this particular element.

Thus,

```js
bililiteRange.createOption('foo', {value: 1}); // data created for all bililiteRange's
bililiteRange.createOption('bar', {value: 2});

const range = bililiteRange(element);
range.data.baz = 3; // data created for this bililiteRange's element only
range.data.foo = 7; // modify an option created above.

console.log( JSON.stringify(range.data) ); // {"foo":7}
console.log( JSON.stringify(range.data.all) ); // {"foo":7,"bar":2}
```

If you really want to stringify *all* of `range.data`, use `JSON.stringify( Object.assign({}, range.data))` to copy it.

## "Reserved" fields

The following are `data` fields used by this package:

`bililiteRange.js`: `mousetime`, `liveRanges`, `oldText`, `selection`, `sendkeysBounds`, `sendkeysOriginalText`

`bililiteRange.undo.js`: `undos`

`bililiteRange.lines.js`: `autoindent`, `tabsize`

`bililiteRange.find.js`: `bigwords`, `dotall`, `global`, `ignorecase`, `magic`, `multiline`, `sections`,
`sentences`, `unicode`, `words`, `wrapscan`

`bililiteRange.ex.js`: `directory`, `file`, `reader`, `stderr`, `stderr`, `savestatus`, `writer`

repository: productinfo/bililiteRange

repo_name: productinfo/bililiteRange


text:
# Self-Ensembling Semi-Supervised 3D Object Detection with Graph-Level Consistency
Created by Yifan Liu from
National University of Singapore

This work is an extension based on SESS. The instructions of running the code is the same as SESS's.

The architecture of the new model is as follows:
![structure](https://user-images.githubusercontent.com/48831875/115020625-6f7f8d00-9eed-11eb-8a1d-059b3e81de47.png)

The Readme.md of original SESS is shown below.
# SESS: Self-Ensembling Semi-Supervised 3D Object Detection
Created by Na Zhao from
National University of Singapore

![teaser](https://github.com/Na-Z/sess/blob/master/teaser.jpg)

## Introduction
This repository contains the PyTorch implementation for our CVPR 2020 Paper
"SESS: Self-Ensembling Semi-Supervised 3D Object Detection" by Na Zhao, Tat Seng Chua, Gim Hee Lee
[[paper](https://arxiv.org/pdf/1912.11803.pdf)]

The performance of existing point cloud-based 3D object detection methods heavily relies on large-scale high-quality 3D
annotations. However, such annotations are often tedious and expensive to collect. Semi-supervised learning is a good
alternative to mitigate the data annotation issue, but has remained largely unexplored in 3D object detection. Inspired
by the recent success of self-ensembling technique in semi-supervised image classification task, we propose SESS, a
self-ensembling semi-supervised 3D object detection framework. Specifically, we design a thorough perturbation scheme
to enhance generalization of the network on unlabeled and new unseen data. Furthermore, we propose three consistency
losses to enforce the consistency between two sets of predicted 3D object proposals, to facilitate the learning of
structure and semantic invariances of objects. Extensive experiments conducted on SUN RGB-D and ScanNet datasets
demonstrate the effectiveness of SESS in both inductive and transductive semi-supervised 3D object detection. Our SESS
achieves competitive performance compared to the state-of-the-art fully-supervised method by using only 50% labeled data.

## Setup
- Install `python` --This repo is tested with `python 3.6.8`.
- Install `pytorch` with CUDA -- This repo is tested with `torch 1.1`, `CUDA 9.0`.
It may wrk with newer versions, but that is not gauranteed.
- Install `tensorflow` (for Tensorboard) -- This repo is tested with `tensorflow 1.14`.
- Compile the CUDA layers for PointNet++, which is used in the backbone network:
    ```
    cd pointnet2
    python setup.py install
    ```
- Install dependencies
    ```
    pip install -r requirements.txt
    ```

## Usage
### Data preparation
For SUNRGB-D, follow the [README](https://github.com/Na-Z/sess/blob/master/sunrgbd/README.md) under `sunrgbd` folder.

For ScanNet, follow the [README](https://github.com/Na-Z/sess/blob/master/scannet/README.md) under `scannet` folder.

### Running experiments
For SUNRGB-D, using the following command to train and evaluate:

    python scripts/run_sess_sunrgbd.py

For ScanNet, using the following command to train and evaluate:

    python scripts/run_sess_scannet.py

Note that we have included the pretaining phase, training phase, and two evaluation phases
 (inductive and transductive semi-supervised learning) as four functions in each script.
You are free to uncomment any function execution line to skip the corresponding phase.

## Citation
Please cite our paper if it is helpful to your research:

    @inproceedings{zhao2020sess,
      title={SESS: Self-Ensembling Semi-Supervised 3D Object Detection},
      author={Zhao, Na and Chua, Tat-Seng and Lee, Gim Hee},
      booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
      pages={11079--11087},
      year={2020}
    }

## Acknowledgement
Our implementation leverages on the source code from the following repositories:
- [Deep Hough Voting for 3D Object Detection in Point Clouds](https://github.com/facebookresearch/votenet)
- [Mean teachers are better role models](https://github.com/CuriousAI/mean-teacher)
- [Pointnet2/Pointnet++ PyTorch](https://github.com/erikwijmans/Pointnet2_PyTorch)

repository: Richard-LYF/sess

repo_name: Richard-LYF/sess


text:
---
title: Get the Client-side Object of the Embedded RadCalendar
page_title: Get the Client-side Object of the Embedded RadCalendar - RadScheduler
description: Check our Web Forms article about Get the Client-side Object of the Embedded RadCalendar.
slug: scheduler/how-to/get-the-client-side-object-of-the-embedded-radcalendar
tags: get,the,client-side,object,of,the,embedded,radcalendar
published: True
position: 4
---

# Get the Client-side Object of the Embedded RadCalendar

##

Since the popup calendar in RadScheduler is RadCalendar, its client-side object is registered on the page and can be obtained as usual by using:

````JavaScript

<script type="text/javascript">
function pageLoad()
{
   var schedulerPopupCalendar = $find('<%= RadScheduler1.ClientID + "_SelectedDateCalendar" %>');
   alert(schedulerPopupCalendar.get_id());
}
</script>

````

The RadCalendar client object can be further operated with by using its [client-side API]({%slug calendar/client-side-programming/radcalendar-object%}).

repository: telerik/ajax-docs

gha_language: C#

repo_name: telerik/ajax-docs