text:
001    package org.apache.commons.ssl.asn1;
002
003    import org.apache.commons.ssl.util.Hex;
004
005    import java.io.ByteArrayInputStream;
006    import java.io.ByteArrayOutputStream;
007    import java.io.IOException;
008    import java.io.InputStream;
009    import java.util.Enumeration;
010    import java.util.Vector;
011
012    public abstract class ASN1OctetString
013        extends ASN1Object
014        implements ASN1OctetStringParser {
015        byte[] string;
016
017        /**
018         * return an Octet String from a tagged object.
019         *
020         * @param obj      the tagged object holding the object we want.
021         * @param explicit true if the object is meant to be explicitly
022         *                 tagged false otherwise.
023         * @throws IllegalArgumentException if the tagged object cannot
024         *                                  be converted.
025         */
026        public static ASN1OctetString getInstance(
027            ASN1TaggedObject obj,
028            boolean explicit) {
029            return getInstance(obj.getObject());
030        }
031
032        /**
033         * return an Octet String from the given object.
034         *
035         * @param obj the object we want converted.
036         * @throws IllegalArgumentException if the object cannot be converted.
037         */
038        public static ASN1OctetString getInstance(
039            Object obj) {
040            if (obj == null || obj instanceof ASN1OctetString) {
041                return (ASN1OctetString) obj;
042            }
043
044            if (obj instanceof ASN1TaggedObject) {
045                return getInstance(((ASN1TaggedObject) obj).getObject());
046            }
047
048            if (obj instanceof ASN1Sequence) {
049                Vector v = new Vector();
050                Enumeration e = ((ASN1Sequence) obj).getObjects();
051
052                while (e.hasMoreElements()) {
053                    v.addElement(e.nextElement());
054                }
055
056                return new BERConstructedOctetString(v);
057            }
058
059            throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
060        }
061
062        /** @param string the octets making up the octet string. */
063        public ASN1OctetString(
064            byte[] string) {
065            this.string = string;
066        }
067
068        public ASN1OctetString(
069            DEREncodable obj) {
070            try {
071                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
072                DEROutputStream dOut = new DEROutputStream(bOut);
073
074                dOut.writeObject(obj);
075                dOut.close();
076
077                this.string = bOut.toByteArray();
078            }
079            catch (IOException e) {
080                throw new IllegalArgumentException("Error processing object : " + e.toString());
081            }
082        }
083
084        public InputStream getOctetStream() {
085            return new ByteArrayInputStream(string);
086        }
087
088        public ASN1OctetStringParser parser() {
089            return this;
090        }
091
092        public byte[] getOctets() {
093            return string;
094        }
095
096        public int hashCode() {
097            byte[] b = this.getOctets();
098            int value = 0;
099
100            for (int i = 0; i != b.length; i++) {
101                value ^= (b[i] & 0xff) << (i % 4);
102            }
103
104            return value;
105        }
106
107        boolean asn1Equals(
108            DERObject o) {
109            if (!(o instanceof ASN1OctetString)) {
110                return false;
111            }
112
113            ASN1OctetString other = (ASN1OctetString) o;
114
115            byte[] b1 = other.string;
116            byte[] b2 = this.string;
117
118            if (b1.length != b2.length) {
119                return false;
120            }
121
122            for (int i = 0; i != b1.length; i++) {
123                if (b1[i] != b2[i]) {
124                    return false;
125                }
126            }
127
128            return true;
129        }
130
131        abstract void encode(DEROutputStream out)
132            throws IOException;
133
134        public String toString() {
135            return "#" + Hex.encode(string);
136        }
137    }


text:
const express = require('express');
const cookieParser = require("cookie-parser");
const sessions = require('express-session');
const morgan = require('morgan');
const axios = require('axios');

const app = express();
const port = 3000;
app.use(express.json());

const oneDay = 1000 * 60 * 60 * 24;

app.use(sessions({
  secret: "this_is_my_secret_key",
  saveUninitialized: true,
  cookie: { maxAge: oneDay },
  resave: false
}));
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(express.static('static'));
app.use(morgan('dev'));

app.post('/centrifugo/connect', (req, res) => {
  console.log(req.body);
  console.log(req.cookies);

  if (req.session.userid) {
    res.json({
      "result": {
        "user": req.session.userid
      }
    });
  } else
    res.json({
      "disconnect": {
        "code": 1000,
        "reason": "unauthorized",
        "reconnect": false
      }
    });
});

app.post('/centrifugo/rpc1', (req, res) => {
  console.log(req.body);
  res.json({ result: { data: { "user": req.body.user, "service": "rpc1" } } });
});

app.post('/centrifugo/rpc2', (req, res) => {
  console.log(req.body);
  res.json({ result: { data: { "user": req.body.user, "service": "rpc2" } } });
});

const myusername = 'demo-user'
const mypassword = 'demo-pass'

app.post('/login', (req, res) => {
  if (req.body.username == myusername && req.body.password == mypassword) {
    req.session.userid = req.body.username;
    res.redirect('/');
  } else {
    res.send('Invalid username or password');
  }
});

app.get('/logout', (req, res) => {
  req.session.destroy();
  res.redirect('/');
});

app.get('/', (req, res) => {
  if (req.session.userid) {
    res.sendFile('views/app.html', { root: __dirname });
  } else
    res.sendFile('views/login.html', { root: __dirname })
});

const centrifugoApiClient = axios.create({
  baseURL: `http://centrifugo:8000/api`,
  headers: {
    Authorization: `apikey my_api_key`,
    'Content-Type': 'application/json',
  },
});

setInterval(async () => {
  try {
    await centrifugoApiClient.post('', {
      method: 'publish',
      params: {
        channel: '#' + myusername, // construct personal channel name.
        data: {
          time: Math.floor(new Date().getTime() / 1000),
        },
      },
    });
  } catch (e) {
    console.error(e.message);
  }
}, 5000);

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

redpajama_set_name: RedPajamaGithub


text:
package org.vthai.game.ancientbattleship.battlefield.objects;

import org.vthai.game.ancientbattleship.battlefield.event.Event;

public class Voidness implements Occupiable {

   @Override
   public void absorbEvent(Event event) {
      // TODO Auto-generated method stub

   }

}


text:
package com.structurizr.annotation;

import java.lang.annotation.*;

/**
 * A type-level annotation that can be used to signify that the component
 * on which this annotation is placed has a relationship to the named software system,
 * creating a relationship from the component to the software system.
 */
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(UsesSoftwareSystems.class)
public @interface UsesSoftwareSystem {

    String name();
    String description() default "";
    String technology() default "";

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <?php

    global $path, $embed;

    ?>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<?php if (!$embed) { ?>

kWh/d Zoomer

<?php } ?>

: Hover on bar for info, press to zoom in

Date / Time

        <input id="return" type="button" value="Back" style="font-size:18px; height:40px;"/>

        <input class="time" type="button" value="D" time="1"/>
        <input class="time" type="button" value="W" time="7"/>
        <input class="time" type="button" value="M" time="30"/>
        <input class="time" type="button" value="Y" time="365"/> |
        <input id="zoomin" type="button" value="+"/>
        <input id="zoomout" type="button" value="-"/>
        <input id="left" type="button" value="<"/>
        <input id="right" type="button" value=">"/>


text:
enum
{
    CAT_MISC = 0,
    CAT_CLOSE = 2,
    CAT_LOW = 4,
    CAT_MEDIUM = 5,
    CAT_HIGH,
    CAT_JUMPING,
    CAT_PROJECTILE,
    CAT_BASIC,
    CAT_VICTORY, // or defeat
    CAT_THROW,
    CAT_SCRAP,
    CAT_DESTRUCTION
};

enum
{
    STATE_STANDING = 1,
    STATE_WALKTO,
    STATE_WALKFROM,
    STATE_CROUCHING,
    STATE_CROUCHBLOCK,
    STATE_JUMPING,
    STATE_RECOIL,
    STATE_FALLEN,
    STATE_STANDING_UP,
    STATE_STUNNED,
    STATE_VICTORY,
    STATE_DEFEAT,
    STATE_SCRAP,
    STATE_DESTRUCTION,
    STATE_WALLDAMAGE, // Took damage from wall (electrocution)
    STATE_DONE        // destruction or scrap has completed
};

enum
{
    HAR_EVENT_JUMP,
    HAR_EVENT_AIR_TURN,
    HAR_EVENT_WALK,
    HAR_EVENT_AIR_ATTACK_DONE,        // Touched the floor after executing a move in the air
    HAR_EVENT_ATTACK,                 // Executed a move, may not hit
    HAR_EVENT_ENEMY_BLOCK,            // Opponent blocked your move
    HAR_EVENT_ENEMY_BLOCK_PROJECTILE, // Opponent blocked your projectile
    HAR_EVENT_BLOCK,                  // You blocked your opponents move
    HAR_EVENT_BLOCK_PROJECTILE,       // You blocked your opponents projectile
    HAR_EVENT_LAND_HIT,               // Landed a hit on the opponent
    HAR_EVENT_LAND_HIT_PROJECTILE,    // Landed a projectile hit on the opponent
    HAR_EVENT_TAKE_HIT,               // Hit by HAR
    HAR_EVENT_TAKE_HIT_PROJECTILE,    // Hit by projectile
    HAR_EVENT_HAZARD_HIT,             // Hit by hazard
    HAR_EVENT_ENEMY_HAZARD_HIT,
    HAR_EVENT_STUN,
    HAR_EVENT_ENEMY_STUN,
    HAR_EVENT_RECOVER,  // regained control after recoil/stun
    HAR_EVENT_HIT_WALL, // Touched a wall
    HAR_EVENT_LAND,     // Touched the floor
    HAR_EVENT_DEFEAT,
    HAR_EVENT_SCRAP,
    HAR_EVENT_DESTRUCTION,
    HAR_EVENT_DONE // match done, no more scrap/destruction
};

typedef struct har_event_t {
    uint8_t type;
    uint8_t player_id;
    union {
        af_move *move; // for attack/hit
        bk_info *info; // for hazard hit
        int wall;      // for hit wall
        int direction; // jump direction
    };
} har_event;

enum
{
    DAMAGETYPE_LOW, // Damage to low area of har
    DAMAGETYPE_HIGH // Damage to high area of har
};

typedef void (*har_action_hook_cb)(int action, void *data);
typedef void (*har_hook_cb)(har_event event, void *data);

typedef struct har_hook_t {
    har_hook_cb cb;
    void *data;
} har_hook;

typedef struct action_buffer_t {
    char actions[10];
    uint8_t count;
    uint32_t age;
} action_buffer;

typedef struct game_player_t game_player;

typedef struct har_t {
    game_player *gp;
    uint8_t id;        // Har ID
    uint8_t player_id; // Player number, 0 or 1
    uint8_t pilot_id;  // Pilot ID
    uint8_t state;
    uint8_t executing_move;
    uint8_t flinching;
    uint8_t close;
    uint8_t enqueued;
    af *af_data;
    uint8_t damage_done;     // Damage was done this animation
    uint8_t damage_received; // Damage was received this animation
    uint8_t air_attacked;
    uint8_t is_wallhugging;  // HAR is standing right next to a wall
    uint8_t is_grabbed;      // Is being moved by another object. Set by ex, ey tags
    float last_damage_value; // Last damage value taken

    float jump_boost; // Agility generated speed modifier for jumping
    float fall_boost; // Agility generated speed modifier for falling

    int in_stasis_ticks; // Handle stasis activator

    int16_t health_max, health;
    float endurance_max, endurance;
    char inputs[11];
    uint8_t hard_close;

    uint8_t stun_timer;
    uint8_t delay; // used for 'stretching' frames in netplay

    // ptr, pe, etc. stuff
    uint8_t p_pal_ref;
    uint8_t p_har_switch;
    uint8_t p_color_ref;
    int p_ticks_left;
    unsigned int p_ticks_length;
    uint8_t p_color_fn;

    list har_hooks;

    har_action_hook_cb action_hook_cb;
    void *action_hook_cb_data;

    action_buffer act_buf[OBJECT_EVENT_BUFFER_SIZE];

#ifdef DEBUGMODE
    surface cd_debug;
#endif
} har;

void har_install_action_hook(har *h, har_action_hook_cb hook, void *data);
void har_install_hook(har *h, har_hook_cb hook, void *data);
void har_bootstrap(object *obj);
int har_create(object *obj, af *af_data, int dir, int har_id, int pilot_id, int player_id);
void har_set_ani(object *obj, int animation_id, int repeat);
int har_is_active(object *obj);
int har_is_crouching(har *h);
int har_is_walking(har *h);
int har_is_blocking(har *h, af_move *move);
void har_copy_actions(object *new, object *old);

#endif // HAR_H


text:
- Back up
- Version control
- Collaborate with other people
- **Evidence of your work/contribution**

# Online document and training
- Pro Git <https://git-scm.com/book/en/v2>
- Learning Git Branching <http://learngitbranching.js.org/>
- Try Git <https://try.github.io>

# Help
`git help command-name` will show the usage of the commannd-name.

# Simple operation flow (single person, no branch)
## Create new project and local repository
1. Create github account
1. Create new project with README.md and LICENCE
1. at the local computer, move to proper directory then issue "git clone" command. git supports ssh git and http protocols, Using http(https) is easy for small update.

```
    git clone https://github.com/UseName/ProjectName.git
```

## add/commit/push/fetch+merge
1. Create or Modify file
1. Issue `git add` command, this command tells to git that the change of the file will be commited (STAGE)
1. If related modification is made, issue `git commit` command to confirm the change. Local commit can be easily restored, so it's not necessary to be so nervous.
1. Test the code.
1. issue `git push` command to synchronize the local and remote (github) repository.
1. If file is updated on github, issue `git fetch` command to retrieve, and `git merge origin/master` to synchronize the local and remote (github) repository.
    + master  (local master repository)
    + origin/master (copy of remote(github) master repository)
1. Issue `git status` command to check update/STAGE, `git log`/`git reflog` command to check commit history.

# (Optional) Operation flow to initialize repository in local instead of clone
Repository can be made using `git init` command instead of `git clone` command.

1. Create working directory and edit files
1. Issue `git init` command
1. Issue `git add` and `git commit` commmand
1. Issue `git status` command to check if git operation was properly done
1. Repeat edit - `git add` - `git commit`, if necessary
1. Create empty project in Github
1. Issue `git remote add` command to register the Github project as a remote repsitory
1. Issue `git push` command to synchronize

# Branch Operation flow
Assumes that bugfix0123 and feature0031 are to be implemented, but master branchis to be untouched until merge.

1. Create bugfix0123 branch. `git branch bugfix0123`
1. Create feature0031 branch. `git branch feature0031`
1. Switch to bugfix0123 branch. `git checkout bugfix0123`
1. Edit necessary files, `git add`, `git commit` and test in bugfix0123 branch. At this point the modification is not affected to master or feature0031
1. Switch to feature0031 branch. `git checkout feature0031`
1. Edit necessary files, `git add`, `git commit` and test in feature0031 branch. At this point the modification is not affected to master or bugfix0031
1. Merge bugfix0123 branch
    1. Return to master branch: `git branch master`
    1. Merge branch: `git merge --no-ff bugfix0123`
1. Merge feature0031 branch
    1. Return to master branch: `git branch master`
    1. Merge branch: `git merge --no-ff feature0031`
    1. If conflict occur, edit conflicted file, `git add`, `git commit`
1. Delete bugfix0123 branch. `git branch -d bugfix0123`

## Restore to previous commit

```
    kato@katoB502E:~/sandbox$ mkdir gittest
    kato@katoB502E:~/sandbox$ cd gittest
    kato@katoB502E:~/sandbox/gittest$ git init
    Initialized empty Git repository in /home/kato/sandbox/gittest/.git/
    kato@katoB502E:~/sandbox/gittest$ vim testfile
    kato@katoB502E:~/sandbox/gittest$ cat testfile
    v0: Initial test file
    kato@katoB502E:~/sandbox/gittest$ git status
    On branch master

    Untracked files:
      (use "git add <file>..." to include in what will be committed)

    	testfile

    nothing added to commit but untracked files present (use "git add" to track)
    kato@katoB502E:~/sandbox/gittest$ git add testfile
    kato@katoB502E:~/sandbox/gittest$ git commit testfile -m "v0"
    [master (root-commit) a19d4a7] v0
     1 file changed, 1 insertion(+)
     create mode 100644 testfile
    kato@katoB502E:~/sandbox/gittest$ git status
    On branch master
    nothing to commit, working directory clean
    kato@katoB502E:~/sandbox/gittest$ git branch
    * master
    kato@katoB502E:~/sandbox/gittest$ echo v1 new file >>testfile
    kato@katoB502E:~/sandbox/gittest$ cat testfile
    v0: Initial test file
    v1 new file
    kato@katoB502E:~/sandbox/gittest$ git commit -a -m "v1"
    [master 837d789] v1
     1 file changed, 1 insertion(+)
    kato@katoB502E:~/sandbox/gittest$ git log
    commit 837d789a719133a98cf4327ba4addf7de0178e03
    Author: Shinji Kato <hole.in1.kato@gmail.com>
    Date:   Thu Aug 3 10:05:42 2017 +0630

        v1

    commit a19d4a776b3ad52166a9a3bba23809e8a5fd9e9e
    Author: Shinji Kato <hole.in1.kato@gmail.com>
    Date:   Thu Aug 3 10:03:48 2017 +0630

        v0
    kato@katoB502E:~/sandbox/gittest$ cat testfile
    v0: Initial test file
    v1 new file
    kato@katoB502E:~/sandbox/gittest$ git checkout a19d
    Note: checking out 'a19d'.

    You are in 'detached HEAD' state. You can look around, make experimental
    changes and commit them, and you can discard any commits you make in this
    state without impacting any branches by performing another checkout.

    If you want to create a new branch to retain commits you create, you may
    do so (now or later) by using -b with the checkout command again. Example:

      git checkout -b <new-branch-name>

    HEAD is now at a19d4a7... v0
    kato@katoB502E:~/sandbox/gittest$ git branch
    * (HEAD detached at a19d4a7)
      master
    kato@katoB502E:~/sandbox/gittest$ cat testfile
    v0: Initial test file
    kato@katoB502E:~/sandbox/gittest$ git checkout master
    Previous HEAD position was a19d4a7... v0
    Switched to branch 'master'
    kato@katoB502E:~/sandbox/gittest$ cat testfile
    v0: Initial test file
    v1 new file
    kato@katoB502E:~/sandbox/gittest$ git branch
    * master
```

# Pull request Operation flow (good for large community)
This method is considered to be standard, but requires more effort than next one. This kind of overhead needs to be accepted when many people collaborate togather.

1. Login Github site, open the project you want to contribute.
1. Press **Fork** button. It will copy the project in your account.
1. *Clone* the project which you made in your account.
1. In the local repository, make a *Branch* and perform necessary *commit* and test.
1. After confirmeing the change, *Push* to your forked repository.
1. Verify the change at Forked repository
1. Press **Pull Request** button at Github site (your Forked repository)


text:
+++
Talk_date = ""
Talk_start_time = ""
Talk_end_time = ""
Title = "PedidosYa Hearts DevOps"
Type = "talk"
Speakers = ["gonzalo-lopez-grassi"]
+++

PedidosYa es un emprendimiento surgido en Uruguay que se transformó en líder del mercado de compra de comida online en varios países de Latinoamérica. En los últimos años muchas decisiones, tales como incorporar delivery de supermercados o farmacias, han hecho crecer de forma exponencial el flujo de usuarios y solicitudes de la plataforma.

Partiendo hace 6 años desde una aplicación monolítica y llegando a hoy, con una plataforma distribuida en más de 30 micro-servicios, los roles de Cloud Computing y la cultura DevOps jugaron un papel determinante en el proceso.

Esta charla expone varios de los problemas presentados en el camino, las soluciones aplicadas y las lecciones aprendidas.


text:
[![Build Status](https://travis-ci.org/go-jira/jira.svg?branch=master)](https://travis-ci.org/go-jira/jira)
[![GoDoc](https://godoc.org/github.com/go-jira/jira?status.svg)](https://godoc.org/github.com/go-jira/jira)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

# go-jira

Simple command line client for Atlassian's Jira service written in Go.

## GDPR USERNAME DISCLAIMER

When this tool was initial written the "username" parameter was widely used in the Atlassian API.
Due to GDPR restrictions this parameter was been almost completely phased out other then V1 login.
The "--user" field is still provided as a default global, however moving forward any usage of this field should be phased out in favor of the "--login" option.

Commands which previously took a username will now expect an email address such as watch, create, assign, etc...

## Install

### Download

You can download one of the pre-built binaries for **go-jira** [here](https://github.com/go-jira/jira/releases).

### Build

You can build and install the official repository with [Go](https://golang.org/dl/) (before running the below command, ensure you have `GO111MODULE=on` set in your environment):

	go get github.com/go-jira/jira/cmd/jira

This will checkout this repository into `$GOPATH/src/github.com/go-jira/jira/`, build, and install it.

It should then be available in $GOPATH/bin/jira.

## Usage

#### Setting up TAB completion

Since go-jira is built with the "kingpin" golang command line library we support bash/zsh shell completion automatically:

 * <https://github.com/alecthomas/kingpin/tree/v2.2.5#bashzsh-shell-completion>

For example, in bash, adding something along the lines of:

  `eval "$(jira --completion-script-bash)"`

to your bashrc, or .profile (assuming go-jira binary is already in your path) will cause jira to offer tab completion behavior.

## Configuration

**go-jira** uses a configuration hierarchy.  When loading the configuration from disk it will recursively look through all parent directories in your current path looking for a **.jira.d** directory.  If your current directory is not a child directory of your homedir, then your homedir will also be inspected for a **.jira.d** directory.  From all of **.jira.d** directories discovered **go-jira** will load a **<command>.yml** file (ie for `jira list` it will load `.jira.d/list.yml`) then it will merge in any properties from the **config.yml** if found.  The configuration properties found in a file closest to your current working directory will have precedence.  Properties overridden with command line options will have final precedence.

The complicated configuration hierarchy is used because **go-jira** attempts to be context aware.  For example, if you are working on a "foo" project and you `cd` into your project workspace, wouldn't it be nice if `jira ls` automatically knew to list only issues related to the "foo" project?  Likewise when you `cd` to the "bar" project then `jira ls` should only list issues related to "bar" project.  You can do this with by creating a configuration under your project workspace at **./.jira.d/config.yml** that looks like:

```yaml
project: foo
```

You will need to specify your local jira endpoint first, typically in your homedir like:

```bash
mkdir ~/.jira.d

cat <<EOM >~/.jira.d/config.yml
endpoint: https://jira.mycompany.com
EOM
```

Then use `jira login` to authenticate yourself as $USER. To change your username, use the `-u` CLI flag or set `user:` in your config.yml

### Dynamic Configuration

If the **.jira.d/config.yml** file is executable, then **go-jira** will attempt to execute the file and use the stdout for configuration.  You can use this to customize templates or other overrides depending on what type of operation you are running.  For example if you would like to use the "table" template when ever you run `jira ls`, then you can create a template like this:

```sh
#!/bin/sh

echo "endpoint: https://jira.mycompany.com"
echo "editor: emacs -nw"

case $JIRA_OPERATION in
    list)
      echo "template: table";;
esac
```

Or if you always set the same overrides when you create an issue for your project you can do something like this:

```sh
#!/bin/sh
echo "project: GOJIRA"

case $JIRA_OPERATION in
    create)
        echo "assignee: $USER"
        echo "watchers: mothra"
        ;;
esac
```

### Custom Commands
You can now create custom commands for `jira` just by editing your `.jira.d/config.yml` config file.  These commands are effectively shell-scripts that can have documented options and arguments. The basic format is like:
```yaml
custom-commands:
  - command1
  - command2
```
##### Commands
Where the individual commands are maps with these keys:
* `name: string` [**required**] This is the command name, so for `jira foobar` you would have `name: foobar`
* `help: string` This is help message displayed in the usage for the command
* `hidden: bool` This command will be hidden from users, but still executable.  Sometimes useful for constructing complex commands where one custom command might call another.
* `default: bool` Use this for compound command groups.  If you wanted to have `jira foo bar` and `jira foo baz` you would have two commands with `name: foo bar` and `name: foo baz`.  Then if you wanted `jira foo baz` to be called by default when you type `jira foo` you would set `default: true` for that custom command.
* `options: list`  This is the list of possible option flags that the command will accept
* `args: list` This is the list of command arguments (like the ISSUE) that the command will accept.
* `aliases: string list`: This is a list of alternate names that the user can provide on the command line to run the same command.  Typically used to shorten the command name or provide alternatives that users might expect.
* `script: string` [**required**] This is the script that will be executed as the action for this command. The value will be treated as a template and substitutions for options and arguments will be made before executing.

##### Options
These are possible keys under the command `options` property:
* `name: string` [**required**] Name of the option, so `name: foobar` will result in `--foobar` option.
* `help: string` The help message displayed in usage for the option.
* `type: string`:  The type of the option, can be one of these values: `BOOL`, `COUNTER`, `ENUM`, `FLOAT32`, `FLOAT64`, `INT8`, `INT16`, `INT32`, `INT64`, `INT`, `STRING`, `STRINGMAP`, `UINT8`, `UINT16`, `UINT32`,  `UINT64` and `UINT`.  Most of these are primitive data types an should be self-explanatory.  The default type is `STRING`. There are some special types:
  * `COUNTER` will be an integer type that increments each time the option is used.  So something like `--count --count` will results in `{{options.count}}` of `2`.
  * `ENUM` type is used with the `enum` property.  The raw type is a string and **must** be one of the values listed in the `enum` property.
  * `STRINGMAP` is a `string => string` map with the format of `KEY=VALUE`.  So `--override foo=bar --override bin=baz` will allow for `{{options.override.foo}}` to be `bar` and `{{options.override.bin}}` to be `baz`.
* `short: char` The single character option to be used so `short: c` will allow for `-c`.
* `required: bool` Indicate that this option must be provided on the command line.  Conflicts with the `default` property.
* `default: any` Specify the default value for the option.  Conflicts with the `required` property.
* `hidden: bool` Hide the option from the usage help message, but otherwise works fine.  Sometimes useful for developer options that user should not play with.
* `repeat: bool` Indicate that this option can be repeated.  Not applicable for `COUNTER` and `STRINGMAP` types.  This will turn the option value into an array that you can iterate over.  So `--day Monday --day Thursday` can be used like `{{range options.day}}Day: {{.}}{{end}}`
* `enum: string list` Used with the `type: ENUM` property, it is a list of strings values that represent the set of possible values the option accepts.

##### Arguments
These are possible keys under the command `args` property:
* `name: string` [**required**] Name of the option, so `name: ISSUE` will show in the usage as `jira <command> ISSUE`.  This also represents the name of the argument to be used in the script template, so `{{args.ISSUE}}`.
* `help: string` The help message displayed in usage for the argument.
* `type: string`:  The type of the argument, can be one of these values: `BOOL`, `COUNTER`, `ENUM`, `FLOAT32`, `FLOAT64`, `INT8`, `INT16`, `INT32`, `INT64`, `INT`, `STRING`, `STRINGMAP`, `UINT8`, `UINT16`, `UINT32`,  `UINT64` and `UINT`.  Most of these are primitive data types an should be self-explanatory.  The default type is `STRING`.  There are some special types:
  * `COUNTER` will be an integer type that increments each the argument is provided  So something like `jira <command> ISSUE-12 ISSUE-23` will results in `{{args.ISSUE}}` of `2`.
  * `ENUM` type is used with the `enum` property.  The raw type is a string and **must** be one of the values listed in the `enum` property.
  * `STRINGMAP` is a `string => string` map with the format of `KEY=VALUE`.  So `jira <command> foo=bar bin=baz` along with a `name: OVERRIDE` property will allow for `{{args.OVERRIDE.foo}}` to be `bar` and `{{args.OVERRIDE.bin}}` to be `baz`.
* `required: bool` Indicate that this argument must be provided on the command line.  Conflicts with the `default` property.
* `default: any` Specify the default value for the argument.  Conflicts with the `required` property.
* `repeat: bool` Indicate that this argument can be repeated.  Not applicable for `COUNTER` and `STRINGMAP` types.  This will turn the template value into an array that you can iterate over.  So `jira <command> ISSUE-12 ISSUE-23` can be used like `{{range args.ISSUE}}Issue: {{.}}{{end}}`
* `enum: string list` Used with the `type: ENUM` property, it is a list of strings values that represent the set of possible values for the argument.

##### Script Template
The `script` property is a template that would produce `/bin/sh` compatible syntax after the template has been processed.  There are 2 key template functions `{{args}}` and `{{options}}` that return the parsed arguments and option flags as a map.

To demonstrate how you might use args and options here is a `custom-test` command:
```yaml
custom-commands:
  - name: custom-test
    help: Testing the custom commands
    options:
      - name: abc
        short: a
        default: default
      - name: day
        type: ENUM
        enum:
          - Monday
          - Tuesday
          - Wednesday
          - Thursday
          - Friday
        required: true
    args:
      - name: ARG
        required: true
      - name: MORE
        repeat: true
    script: |
      echo COMMAND {{args.ARG}} --abc {{options.abc}} --day {{options.day}} {{range $more := args.MORE}}{{$more}} {{end}}
```

Then to run it:
```
$ jira custom-test
ERROR Invalid Usage: required flag --day not provided

$ jira custom-test --day Sunday
ERROR Invalid Usage: enum value must be one of Monday,Tuesday,Wednesday,Thursday,Friday, got 'Sunday'

$ jira custom-test --day Tuesday
ERROR Invalid Usage: required argument 'ARG' not provided

$ jira custom-test --day Tuesday arg1
COMMAND arg1 --abc default --day Tuesday

$ jira custom-test --day Tuesday arg1 more1 more2 more3
COMMAND arg1 --abc default --day Tuesday more1 more2 more3

$ jira custom-test --day Tuesday arg1 more1 more2 more3 --abc non-default
COMMAND arg1 --abc non-default --day Tuesday more1 more2 more3

$ jira custom-test --day Tuesday arg1 more1 more2 more3 -a short-non-default
COMMAND arg1 --abc short-non-default --day Tuesday more1 more2 more3
```

The script has access to all the environment variables that are in your current environment plus those that `jira` will set.  `jira` sets environment variables for each config property it has parsed from `.jira.d/config.yml` or the command configs at `.jira.d/<command>.yml`.  It might be useful to see all environment variables that `jira` is producing, so here is a simple custom command to list them:
```yaml
custom-commands:
  - name: env
    help: print the JIRA environment variables available to custom commands
    script: |
      env | grep JIRA
 ```

You could use the environment variables automatically, so if your `.jira.d/config.yml` looks something like this:
```yaml
project: PROJECT
custom-commands:
  - name: print-project
    help: print the name of the configured project
    script: "echo $JIRA_PROJECT"
```

##### Examples

* `jira mine` for listing issues assigned to you
```yaml
custom-commands:
  - name: mine
    help: display issues assigned to me
    script: |-
      if [ -n "$JIRA_PROJECT" ]; then
          # if `project: ...` configured just list the issues for current project
          {{jira}} list --template table --query "resolution = unresolved and assignee=currentuser() and project = $JIRA_PROJECT ORDER BY priority asc, created"
      else
          # otherwise list issues for all project
          {{jira}} list --template table --query "resolution = unresolved and assignee=currentuser() ORDER BY priority asc, created"
      fi
```
* `jira sprint` for listing issues in your current sprint
```yaml
custom-commands:
  - name: sprint
    help: display issues for active sprint
    script: |-
      if [ -n "$JIRA_PROJECT" ]; then
          # if `project: ...` configured just list the issues for current project
          {{jira}} list --template table --query "sprint in openSprints() and type != epic and resolution = unresolved and project=$JIRA_PROJECT ORDER BY rank asc, created"
      else
          # otherwise list issues for all project
          {{jira}} list --template table --query "sprint in openSprints() and type != epic and resolution = unresolved ORDER BY rank asc, created"
      fi
```

### Editing

When you run command like `jira edit` it will open up your favorite editor with the templatized output so you can quickly edit.  When the editor
closes **go-jira** will submit the completed form.  The order which **go-jira** attempts to determine your preferred editor is:

* **editor** property in any config.yml file
* **JIRA_EDITOR** environment variable
* **EDITOR** environment variable
* vim

### Templates

**go-jira** has the ability to customize most output (and editor input) via templates.  There are default templates available for all operations,
which may or may not work for your actual jira implementation.  Jira is endlessly customizable, so it is hard to provide default templates
that will work for all issue types.

When running a command like `jira edit` it will look through the current directory hierarchy trying to find a file that matches **.jira.d/templates/edit**,
if found it will use that file as the template, otherwise it will use the default **edit** template hard-coded into **go-jira**.  You can export the default
hard-coded templates with `jira export-templates` which will write them to **~/.jira.d/templates/**.

#### Writing/Editing Templates

First the basic templating functionality is defined by the Go language 'text/template' library.  The library reference documentation can be found [here](https://golang.org/pkg/text/template/), and there is a good primer document [here](https://gohugo.io/templates/go-templates/).  `go-jira` also provides a few extra helper functions to make it a bit easier to format the data, those functions are defined [here](https://github.com/go-jira/jira/blob/master/jiracli/templates.go#L64).

Knowing what data and fields are available to any given template is not obvious. The easiest approach to determine what is available is to use the `debug` template on any given operation.  For example to find out what is available to the "view" templates, you can use:
```
jira view GOJIRA-321 -t debug
```

This will print out the data in JSON format that is available to the template.  You can do this for any other operation, like "list":
```
jira list -t debug
```

### Authentication

#### Atlassian Cloud

For Atlassian Cloud hosted Jira [API Tokens are now required](https://developer.atlassian.com/cloud/jira/platform/deprecation-notice-basic-auth-and-cookie-based-auth/).  You will automatically be prompted for an API Token if your jira endpoint ends in `.atlassian.net`.

##### Quickstart API Token and Keychain

1. Edit your config or execute the snippit (make sure to replace `<SUBDOMAIN>` and `<EMAIL>`)
```
export SUBDOMAIN="https://<SUBDOMAIN>.atlassian.net"
export EMAIL="<EMAIL>"
mkdir -p ~/.jira.d
printf "endpoint: $SUBDOMAIN\nuser: $EMAIL\npassword-source: keyring" > ~/.jira.d/config.yml
```
2. Create a new API Token at [id.atlassian.com](https://id.atlassian.com/manage-profile/security)
3. Execute `jira session` and enter your API Token. `jira` will add your session to the keyring.

#### Private Jira Service
If you are using a private Jira service, you can force `jira` to use an api-token by setting the `authentication-method: api-token` property in your `$HOME/.jira.d/config.yml` file.  The API Token needs to be presented to the Jira service on every request, so it is recommended to store this API Token security within your OS's keyring, or using the `pass`/`gopass` service as documented below so that it can be programmatically accessed via `jira` and not prompt you every time.  For a less-secure option you can also provide the API token via a `JIRA_API_TOKEN` environment variable.  If you are unable to use an api-token for an Atlassian Cloud hosted Jira then you can still force `jira` to use the old session based authentication (until it the hosted system stops accepting it) by setting `authentication-method: session`.

The API Token authentication requires both the token and the email of the user. The email mut be set in the  `user:` in your config.yml. Failure to provide the `user` will result in a 401 error.

If your Jira service still allows you to use the Session based authentication method then `jira` will prompt for a password automatically when get a response header from the Jira service that indicates you do not have an active session (ie the `X-Ausername` header is set to `anonymous`).  Then after authentication we cache the `cloud.session.token` cookie returned by the service [session login api](https://docs.atlassian.com/jira/REST/cloud/#auth/1/session-login) and reuse that on subsequent requests.  Typically this cookie will be valid for several hours (depending on the service configuration).  To automatically securely store your password for easy reuse by jira You can enable a `password-source` via `.jira.d/config.yml` with possible values of `keyring`, `pass` or `gopass`.

#### User vs Login
The Jira service has sometimes differing opinions about how a user is identified.  In other words the ID you login with might not be ID that the jira system recognized you as.  This matters when trying to identify a user via various Jira REST APIs (like issue assignment).  This is especially relevant when trying to authenticate with an API Token where the authentication user is usually an email address, but within the Jira system the user is identified by a user name.  To accommodate this `jira` now supports two different properties in the config file.  So when authentication using the API Tokens you will likely want something like this in your `$HOME/.jira.d/config.yml` file:
```yaml
user: person
login: person@example.com
```

You can also override these values on the command line with `jira --user person --login person@example.com`.  The `login` value will be used only for authentication purposes, the `user` value will be used when a user name is required for any Jira service API calls.

#### `keyring` password source
On OSX and Linux there are a few keyring providers that `go-jira` can use (via this [golang module](https://github.com/tmc/keyring)).  To integrate `go-jira` with a supported keyring just add this configuration to `$HOME/.jira.d/config.yml`:
```yaml
password-source: keyring
```
After setting this and issuing a `jira login`, your credentials will be stored in your platform's backend (e.g. Keychain for Mac OS X) automatically. Subsequent operations, like a `jira ls`, should automatically login.

#### `pass` password source
An alternative to the keyring password source is the `pass` tool (documentation [here](https://www.passwordstore.org/)).  This uses gpg to encrypt/decrypt passwords on demand and by using `gpg-agent` you can cache the gpg credentials for a period of time so you will not be prompted repeatedly for decrypting the passwords.  The advantage over the keyring integration is that `pass` can be used on more platforms than OSX and Linux, although it does require more setup.  To use `pass` for password storage and retrieval via `go-jira` just add this configuration to `$HOME/.jira.d/config.yml`:
```yaml
password-source: pass
password-name: jira.example.com/myuser
```

This assumes you have already setup `pass` correctly on your system.  Specifically you will need to have created a gpg key like this:

```
$ gpg --gen-key
```

Then you will need the GPG Key ID you want associated with `pass`.  First list the available keys:
```
$ gpg --list-keys
/home/gojira/.gnupg/pubring.gpg
-------------------------------------------------
pub   2048R/A307D709 2016-12-18
uid                  Go Jira <gojira@example.com>
sub   2048R/F9A047B8 2016-12-18
```

Then initialize the `pass` tool to use the correct key:
```
$ pass init "Go Jira <gojira@example.com>"
```

Now insert your password with the name you configured.

```
$ pass insert jira.example.com/myuser
```

You probably want to setup gpg-agent so that you don't have to type in your gpg passphrase all the time.  You can get `gpg-agent` to automatically start by adding something like this to your `$HOME/.bashrc`
```bash
if [ -f $HOME/.gpg-agent-info ]; then
    . $HOME/.gpg-agent-info
    export GPG_AGENT_INFO
fi

if [ ! -f $HOME/.gpg-agent.conf ]; then
  cat <<EOM >$HOME/.gpg-agent.conf
default-cache-ttl 604800
max-cache-ttl 604800
default-cache-ttl-ssh 604800
max-cache-ttl-ssh 604800
EOM
fi

if [ -n "${GPG_AGENT_INFO}" ]; then
    nc  -U "${GPG_AGENT_INFO%%:*}" >/dev/null </dev/null
    if [ ! -S "${GPG_AGENT_INFO%%:*}" -o $? != 0 ]; then
        # set passphrase cache so I only have to type my passphrase once a day
        eval $(gpg-agent --options $HOME/.gpg-agent.conf --daemon --write-env-file $HOME/.gpg-agent-info --use-standard-socket --log-file $HOME/tmp/gpg-agent.log --verbose)
    fi
fi
export GPG_TTY=$(tty)
```

#### `gopass` password source
There is also the possibility to use [gopass](https://www.gopass.pw/) as a password source. `gopass` (like `pass`) uses gpg to encrypt/decrypt passwords. To use `gopass` for password storagte and retrieval via `go-jira` just add this configuration to `$HOME/.jira.d/config.yml`:
```yaml
password-source: gopass
password-name: jira.example.com/myuser
```

For this to work, you need a working `gopass` installation.

To configure your `gpg-agent` to cache your gpg passphrase take a look at the `pass` section of the readme.

#### `stdin` password source

When `password-source` is set to `stdin`, the `jira login` command will read from stdin until EOF, and the bytes read will be the used as the password. This is useful if you have some other programmatic method for fetching passwords. For example, if `password-generator` creates a one-time password and prints it to stdout, you could use it like this.

```bash
$ ./password-generator | jira login --endpoint=https://my.jira.endpoint.com --user=USERNAME
```

#### Switch path  used for password source
For `gopass` and `pass` it is possible to specify the full path for the `password-source` tool  used for retrieval of the password. This can be accomplised
by setting the `password-source-path` option in the configuration file.

E.g.
```yaml
password-source: gopass
password-name: jira.example.com/myuser
password-source-path: /path/to/my-special-gopass
```

This will cause go-jira to use the `gopass` style cli interaction with the `my-special-gopass` binary.

If you ommit the `password-source-path` option, either `gopass` (for `gopass`) or `pass` (for `pass`)
will be used.


text:
import unittest

from ZSI import schema, ParsedSoap, TC

"""Bug [ 1520092 ] URI Bug: urllib.quote escaping reserved chars
   Bug [ 2748314 ] Malformed type attribute (bad NS) with 2.1a1 but not with 2.
"""

class MyInt_Def(TC.Integer, schema.TypeDefinition):
        # ComplexType/SimpleContent derivation of built-in type
        schema = "urn:vim25"
        type = (schema, "myInt")
        def __init__(self, pname, **kw):
            self.attribute_typecode_dict = {}
            TC.Integer.__init__(self, pname, **kw)
            #class Holder(int):
            #    __metaclass__ = pyclass_type
            #    typecode = self
            #self.pyclass = Holder
            self.pyclass = int

class TestCase(unittest.TestCase):

    def check_type_attribute_qname_in_default_ns(self):
        msg = """
<ns1:test xsi:type="ns1:myInt" xmlns:ns1="urn:vim25" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://www.w3.org/2001/XMLSchema">
100
</ns1:test>"""
        ps = ParsedSoap(msg, envelope=False)
        pyobj = ps.Parse(TC.AnyType(pname=("urn:vim25","test")))
        self.failUnless(pyobj == 100, 'failed to parse type in default ns')

    def check_element_in_default_ns(self):
        msg = """
<test xsi:type="myInt" xmlns="urn:vim25" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
100
</test>"""
        ps = ParsedSoap(msg, envelope=False)
        pyobj = ps.Parse(TC.AnyType(pname=("urn:vim25","test")))
        self.failUnless(pyobj == 100, 'failed to parse element in default ns')

#
# Creates permutation of test options: "check", "check_any", etc
#
_SEP = '_'
for t in [i[0].split(_SEP) for i in filter(lambda i: callable(i[1]), TestCase.__dict__.items())]:
    test = ''
    for f in t:
        test += f
        if globals().has_key(test): test += _SEP; continue
        def _closure():
            name = test
            def _makeTestSuite():
                suite = unittest.TestSuite()
                suite.addTest(unittest.makeSuite(TestCase, name))
                return suite
            return _makeTestSuite

        globals()[test] = _closure()
        test += _SEP

makeTestSuite = check
def main():
    unittest.main(defaultTest="makeTestSuite")
if __name__ == "__main__" : main()


text:
A simple bower package providing the [Roboto](http://www.google.com/fonts/specimen/Roboto) fontface. The font was created by [Christian Robertson](https://plus.google.com/110879635926653430880/about).

## Installing

Assuming you have [NodeJS](http://nodejs.org/) and [Bower](http://bower.io/) installed globally just open up a terminal, navigate to your projects root directory and then execute

```
$ bower install roboto-fontface --save
```


text:
title: Discordian date
id: 59f4eafba0343628bb682785
challengeType: 5
videoUrl: ''
localeTitle: Discordian日期
---

## Description

任务:
将给定日期从公历转换为Discordian日历 。

## Instructions

## Tests

```yml
tests:
  - text: <code>discordianDate</code>是一个函数。
    testString: 'assert(typeof discordianDate === "function", "<code>discordianDate</code> is a function.");'
  - text: '<code>discordianDate(new Date(2010, 6, 22))</code> <code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code> <code>discordianDate(new Date(2010, 6, 22))</code>应该返回<code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code> 。'
    testString: 'assert(discordianDate(new Date(2010, 6, 22)) === "Pungenday, the 57th day of Confusion in the YOLD 3176", "<code>discordianDate(new Date(2010, 6, 22))</code> should return <code>"Pungenday, the 57th day of Confusion in the YOLD 3176"</code>.");'
  - text: '<code>discordianDate(new Date(2012, 1, 28))</code>应该返回<code>"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"</code> 。'
    testString: 'assert(discordianDate(new Date(2012, 1, 28)) === "Prickle-Prickle, the 59th day of Chaos in the YOLD 3178", "<code>discordianDate(new Date(2012, 1, 28))</code> should return <code>"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"</code>.");'
  - text: '<code>discordianDate(new Date(2012, 1, 29))</code> <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!"</code> <code>discordianDate(new Date(2012, 1, 29))</code>应该返回<code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!"</code> 。'
    testString: 'assert(discordianDate(new Date(2012, 1, 29)) === "Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!", "<code>discordianDate(new Date(2012, 1, 29))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\"s Day!"</code>.");'
  - text: '<code>discordianDate(new Date(2012, 2, 1))</code>应该返回<code>"Setting Orange, the 60th day of Chaos in the YOLD 3178"</code> 。'
    testString: 'assert(discordianDate(new Date(2012, 2, 1)) === "Setting Orange, the 60th day of Chaos in the YOLD 3178", "<code>discordianDate(new Date(2012, 2, 1))</code> should return <code>"Setting Orange, the 60th day of Chaos in the YOLD 3178"</code>.");'
  - text: '<code>discordianDate(new Date(2010, 0, 5))</code> <code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code> <code>discordianDate(new Date(2010, 0, 5))</code>应该返回<code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code> 。'
    testString: 'assert(discordianDate(new Date(2010, 0, 5)) === "Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!", "<code>discordianDate(new Date(2010, 0, 5))</code> should return <code>"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"</code>.");'
  - text: '<code>discordianDate(new Date(2011, 4, 3))</code>应该返回<code>"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"</code> 。'
    testString: 'assert(discordianDate(new Date(2011, 4, 3)) === "Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!", "<code>discordianDate(new Date(2011, 4, 3))</code> should return <code>"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"</code>.");'
  - text: '<code>discordianDate(new Date(2015, 9, 19))</code> <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code> <code>discordianDate(new Date(2015, 9, 19))</code>应该返回<code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code> 。'
    testString: 'assert(discordianDate(new Date(2015, 9, 19)) === "Boomtime, the 73rd day of Bureaucracy in the YOLD 3181", "<code>discordianDate(new Date(2015, 9, 19))</code> should return <code>"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"</code>.");'

```

## Challenge Seed

```js
function discordianDate (date) {
  // Good luck!
  return true;
}

```

## Solution

```js
// solution required
```


text:
import debug from 'debug';

import React, { PureComponent } from 'react';

import NewVersionInfoView from './NewVersionInfoView';

import UpdateChecksAPI from './UpdateChecksAPI';

import Flags, { DISABLE_REMOTE_INTERACTION, FORCE_UPDATE_CHECKS, UPDATE_SERVER_URL } from '../../util/Flags';

import Metadata from '../../util/Metadata';

const log = debug('UpdateChecks');

class NoopComponent extends PureComponent {
  render() {
    return null;
  }
}

const DEFAULT_UPDATE_SERVER_URL = process.env.NODE_ENV === 'production'
  ? 'https://camunda-modeler-updates.camunda.com/'
  : 'https://camunda-modeler-update-server-staging.camunda.com';

const PRIVACY_PREFERENCES_CONFIG_KEY = 'editor.privacyPreferences';
const UPDATE_CHECKS_CONFIG_KEY = 'editor.updateChecks';

const FIVE_MINUTES_MS = 1000 * 60 * 5;
const TWENTY_FOUR_HOURS_MS = 1000 * 60 * 60 * 24;

export default class UpdateChecks extends PureComponent {

  constructor(props) {
    super(props);

    if (Flags.get(DISABLE_REMOTE_INTERACTION)) {
      return new NoopComponent();
    }

    const updateServerUrl = Flags.get(UPDATE_SERVER_URL, DEFAULT_UPDATE_SERVER_URL);

    this.updateChecksAPI = new UpdateChecksAPI(updateServerUrl);

    this.state = {
      showModal: false
    };
  }

  componentDidMount() {
    this.scheduleCheck();
  }

  componentWillUnmount() {
    this.unscheduleChecks();
  }

  rescheduleCheck() {
    if (process.env.NODE_ENV !== 'test') {
      this._checkTimeout = setTimeout(() => {
        this.scheduleCheck();
      }, FIVE_MINUTES_MS);
    }
  }

  unscheduleChecks() {
    clearTimeout(this._checkTimeout);
  }

  scheduleCheck() {

    this.unscheduleChecks();

    this.rescheduleCheck();

    return this.performCheck().catch(error => {
      this.checkFailed(error);
    });
  }

  checkPerformed(result) {
    if (typeof this.props.onCheckPerformed === 'function') {
      this.props.onCheckPerformed(result);
    }
  }

  checkFailed(error) {
    log('failed', error);

    this.checkPerformed({
      resolution: 'failed',
      error
    });
  }

  checkSkipped(reason) {
    log('skipped', reason);

    this.checkPerformed({
      resolution: 'skipped',
      reason
    });
  }

  checkCompleted(update) {
    this.checkPerformed({
      resolution: 'completed',
      update
    });
  }

  async performCheck() {
    const {
      config
    } = this.props;

    const privacyPreferences = await config.get(PRIVACY_PREFERENCES_CONFIG_KEY);
    if (!privacyPreferences || !privacyPreferences.ENABLE_UPDATE_CHECKS) {
      return this.checkSkipped('privacy-settings');
    }

    const updateCheckInfo = await config.get(UPDATE_CHECKS_CONFIG_KEY);

    if (!Flags.get(FORCE_UPDATE_CHECKS) && !this.isTimeExceeded(updateCheckInfo && updateCheckInfo.lastChecked || 0)) {
      return this.checkSkipped('not-due');
    }

    return this.checkLatestVersion(updateCheckInfo);
  }

  async checkLatestVersion(updateCheckInfo) {

    log('Checking for update');

    const {
      config,
      _getGlobal
    } = this.props;

    const responseJSON = await this.updateChecksAPI.checkLatestVersion(
      config, _getGlobal, updateCheckInfo && updateCheckInfo.latestVersion
    );

    if (!responseJSON.isSuccessful) {
      const {
        error
      } = responseJSON;

      return this.checkFailed(error);
    }

    const responseBody = responseJSON.response;
    const update = responseBody.update;

    let newUpdateCheckInfo = updateCheckInfo || {};

    if (update) {
      log('Found update', update.latestVersion);

      const currentVersion = 'v' + Metadata.data.version;
      const latestVersion = update.latestVersion;
      const downloadURL = update.downloadURL;
      const releases = update.releases;

      this.setState({
        currentVersion,
        latestVersionInfo: {
          latestVersion,
          downloadURL,
          releases
        },
        showModal: true
      });

      newUpdateCheckInfo.latestVersion = latestVersion;
    } else {
      log('No update');
    }

    newUpdateCheckInfo.lastChecked = Date.now();

    await config.set(UPDATE_CHECKS_CONFIG_KEY, newUpdateCheckInfo);

    return this.checkCompleted(update);
  }

  isTimeExceeded(previousTime) {
    return Math.abs(Date.now() - previousTime) >= TWENTY_FOUR_HOURS_MS;
  }

  onClose = () => {
    this.setState({
      showModal: false
    });
  }

  onGoToDownloadPage = () => {
    const {
      latestVersionInfo
    } = this.state;

    const {
      _getGlobal
    } = this.props;

    _getGlobal('backend').send('external:open-url', { url: latestVersionInfo.downloadURL });
    this.onClose();
  }

  render() {
    const {
      showModal,
      latestVersionInfo,
      currentVersion
    } = this.state;

    return <React.Fragment>
      { showModal && <NewVersionInfoView
        onClose={ this.onClose }
        onGoToDownloadPage={ this.onGoToDownloadPage }
        latestVersionInfo={ latestVersionInfo }
        currentVersion={ currentVersion } /> }
    </React.Fragment>;
  }
}


text:
/**
 * Theme Name: Umbra
 * Theme URI: http://time.ly/
 * Author: Timely Network Inc
 * Author URI: http://time.ly/
 * Description: A dark calendar theme, well suited for websites with a dark background.
 * Version: 2.0.0-core
 * Tags: dark, black, gray, inverse
 */


text:
package com.intellij.openapi.wm.impl.status;

import com.intellij.ui.Gray;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.ComponentUI;
import java.awt.*;

/**
 * User: spLeaner
 */
public class StatusBarUI extends ComponentUI {
  private static final Dimension MAX_SIZE = new Dimension(Integer.MAX_VALUE, 23);
  private static final Dimension MIN_SIZE = new Dimension(100, 23);

  private static final Border BACKGROUND_PAINTER = new BackgroundPainter();

  @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass"})
  public static ComponentUI createUI(JComponent x) {
      return new StatusBarUI();
  }

  @Override
  public void paint(final Graphics g, final JComponent c) {
    final Rectangle bounds = c.getBounds();
    BACKGROUND_PAINTER.paintBorder(c, g, 0, 0, bounds.width, bounds.height);
  }

  @Override
  public Dimension getMinimumSize(JComponent c) {
    return MIN_SIZE; // TODO
  }

  @Override
  public Dimension getMaximumSize(JComponent c) {
    return MAX_SIZE;
  }

  private static final class BackgroundPainter implements Border {
    private static final Color BORDER_TOP_COLOR = Gray._145;
    private static final Color BORDER2_TOP_COLOR = Gray._255;
    private static final Color BORDER_BOTTOM_COLOR = Gray._255;

    private static final Color BG_COLOR = Gray._238;

    private static final Insets INSETS = new Insets(0, 0, 0, 0);

    public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
      final Graphics2D g2d = (Graphics2D) g.create();

      final Color background = UIUtil.getPanelBackground();

      g2d.setColor(background);
      g2d.fillRect(0, 0, width, height);

      g2d.setColor(UIUtil.isUnderDarcula() ? BORDER_TOP_COLOR.darker().darker() : BORDER_TOP_COLOR);
      g2d.drawLine(0, 0, width, 0);

      if (!UIUtil.isUnderDarcula()) {
        g2d.setColor(BORDER2_TOP_COLOR);
        g2d.drawLine(0, 1, width, 1);
      }

      g2d.setColor(UIUtil.isUnderDarcula() ? BORDER_BOTTOM_COLOR.darker().darker() : BORDER_BOTTOM_COLOR);
      g2d.drawLine(0, height, width, height);

      g2d.dispose();
    }

    public Insets getBorderInsets(Component c) {
      return INSETS;
    }

    public boolean isBorderOpaque() {
      return true;
    }
  }
}


text:
import UpdateNotifier = require("update-notifier");

let notifier = UpdateNotifier();

if (notifier.update) {
	notifier.notify();
}

console.log(notifier.update);

// Also exposed as a class
notifier = new UpdateNotifier.UpdateNotifier({
	updateCheckInterval: 1000 * 60 * 60 * 24 * 7 // 1 week
});

if (notifier.update) {
    notifier.notify(); // test no options
    notifier.notify({}); // test empty object

    // test all options
    notifier.notify({
        message: 'Update available: ' + notifier.update.latest,
        defer: false,
        boxenOpts: {
            padding: 1,
            margin: 1,
            align: 'center',
            borderColor: 'yellow',
            borderStyle: 'round',
        },
    });
}


text:
define(function()
{
	var sysConfigFile = function()
	{
		var node,
			data,

		init = function(_node, _data)
		{
			this.node = _node;
			this.data = _data;

			var i = parseInt((this.data.fileRepairPeriod/1000/60).toString().split(".")[0]),
				s = parseInt((this.data.fileRepairPeriod-i*60*1000)/1000);

			$("input[name=fileRepairI]",that.node).val(i);
			$("input[name=fileRepairS]",that.node).val(s);
			$("input[name=fileReplication]",that.node).val(this.data.fileStrategy.replication);

			return this;
		},

		destroy = function()
		{

		},

		that =
		{
			init: init,
			destroy: destroy
		};

		return that;
	}

	return sysConfigFile;
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.mysema.home</groupId>
    <artifactId>mysema-source</artifactId>
    <version>0.3.0</version>
  </parent>

  <groupId>com.mysema.scalagen</groupId>
  <artifactId>scalagen-maven-plugin_${scala.version}</artifactId>
  <version>0.3.0</version>
  <name>Scalagen - Maven plugin</name>
  <description>Scalagen Maven plugin</description>
  <packaging>maven-plugin</packaging>

  <properties>
    <mvn.version>2.2.1</mvn.version>
  </properties>

  <profiles>
    <profile>
      <id>scala-2.9.x</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <scala.version>2.9.3</scala.version>
      </properties>
    </profile>

    <profile>
      <id>scala-2.10.x</id>
      <properties>
        <scala.version>2.10.1</scala.version>
      </properties>
    </profile>
  </profiles>

  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <dependencies>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-plugin-api</artifactId>
      <version>${mvn.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-model</artifactId>
      <version>${mvn.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-project</artifactId>
      <version>${mvn.version}</version>
    </dependency>

    <dependency>
      <groupId>com.mysema.scalagen</groupId>
      <artifactId>scalagen_${scala.version}</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>

  </dependencies>

</project>


text:
'use strict';
var app = angular.module('angularApp')
  .controller('ManageProtocolCtrl', function (protocolService,navigationService,groupService,$scope,$rootScope,$filter,ngTableParams,$http,$location,$modal) {
    $rootScope.tabs = navigationService.get();
    $rootScope.groups = groupService.getGroups.data.get();
    $scope.protocolData = protocolService.protocolData;
  });


text:
<?php
/**
 * Show error page.
 *
 * @version 1.1
 * @author MPI
 * */
header('Content-Type: text/html; charset=utf-8');
error_reporting(0);

$codes = array(
		400 => array('400 Bad Request', 'Špatná syntaxe požadavku.'),
		401 => array('401 Unauthorized', 'Požadavek vyžaduje ověření.'),
		403 => array('403 Forbidden', 'Požadavek byl zamítnut.'),
		404 => array('404 Not Found', 'Požadovaná stránka nebyla nalezena.'),
		405 => array('405 Method Not Allowed', 'Metoda specifikovaná v požadavku není povolená.'),
		408 => array('408 Request Timeout', 'Při čekání na požadavek vypršel časový limit serveru.'),
		500 => array('500 Internal Server Error', 'Na serveru došlo k chybě, a proto nelze požadavek splnit.'),
		501 => array('501 Not Implemented', 'Server není schopen požadavek zpracovat.'),
		502 => array('502 Bad Gateway', 'Nesprávná odpověď vzdáleného serveru.'),
		503 => array('503 Service Unavailable', 'Server je momentálně nedostupný.'),
		504 => array('504 Gateway Timeout', 'Nesprávná odpověď vzdáleného serveru.'),
		505 => array('505 HTTP Version Not Supported', 'Server nepodporuje verzi protokolu HTTP použitou v požadavku.')
);
$i = 404; // default error id
if(isset($_GET["code"]) && is_numeric($_GET["code"]) && array_key_exists($_GET["code"], $codes)) {
	$i = $_GET["code"];
}
?>
<!DOCTYPE html>

<meta charset="UTF-8">
<base href="/~martin/asterisk_admin/">
<title><?php echo htmlspecialchars("Error ".$i);?></title>
<link href="error/error.css" rel="stylesheet" type="text/css" />

<?php echo htmlspecialchars("Chyba ".$i);?>

<?php echo htmlspecialchars($codes[$i][1]);?>

Try it again later.


text:
"""Nonlinear transform coding."""

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_compression as tfc
import tensorflow_probability as tfp
from toy_sources import compression_model

tfpd = tfp.distributions

class NTCModel(compression_model.CompressionModel):
  """Nonlinear transform coding model."""

  def __init__(self, analysis, synthesis, prior_type="deep",
               dither=(1, 1, 0, 0), soft_round=(1, 0), guess_offset=False,
               **kwargs):
    """Initializer.

    Args:
      analysis: A `Layer` object implementing the analysis transform.
      synthesis: A `Layer` object implementing the synthesis transform.
      prior_type: String. Either 'deep' for `DeepFactorized` prior, or
        'gsm/gmm/lsm/lmm-X' for Gaussian/Logistic Scale Mixture/Mixture Model
        with X components.
      dither: Sequence of 4 Booleans. Whether to use dither for: rate term
        during training, distortion term during training, rate term during
        testing, distortion term during testing, respectively.
      soft_round: Sequence of 2 Booleans. Whether to use soft rounding during
        training or testing, respectively.
      guess_offset: Boolean. When not using soft rounding, whether to use the
        mode centering heuristic to determine the quantization offset during
        testing.
      **kwargs: Other arguments passed through to `CompressionModel` class.
    """
    super().__init__(**kwargs)
    self._analysis = analysis
    self._synthesis = synthesis
    self.prior_type = str(prior_type)
    self.dither = tuple(bool(i) for i in dither)
    self.soft_round = tuple(bool(i) for i in soft_round)
    self.guess_offset = bool(guess_offset)

    if self.prior_type == "deep":
      self._prior = tfc.DeepFactorized(
          batch_shape=[self.ndim_latent], dtype=self.dtype)
    elif self.prior_type[:4] in ("gsm-", "gmm-", "lsm-", "lmm-"):
      components = int(self.prior_type[4:])
      shape = (self.ndim_latent, components)
      self.logits = tf.Variable(tf.random.normal(shape, dtype=self.dtype))
      self.log_scale = tf.Variable(
          tf.random.normal(shape, mean=2., dtype=self.dtype))
      if "s" in self.prior_type:
        self.loc = 0.
      else:
        self.loc = tf.Variable(tf.random.normal(shape, dtype=self.dtype))
    else:
      raise ValueError(f"Unknown prior_type: '{prior_type}'.")

    self._logit_alpha = tf.Variable(-3, dtype=self.dtype, name="logit_alpha")
    self._force_alpha = tf.Variable(
        -1, trainable=False, dtype=self.dtype, name="force_alpha")

  def prior(self, soft_round, scale=None, alpha=None, skip_noise=False):
    if self.prior_type == "deep":
      prior = self._prior
    elif self.prior_type[:4] in ("gsm-", "gmm-", "lsm-", "lmm-"):
      cls = tfpd.Normal if self.prior_type.startswith("g") else tfpd.Logistic
      prior = tfpd.MixtureSameFamily(
          mixture_distribution=tfpd.Categorical(logits=self.logits),
          components_distribution=cls(
              loc=self.loc, scale=tf.math.exp(self.log_scale)),
      )
    if soft_round:
      if alpha is None:
        alpha = self.alpha
      prior = tfc.SoftRoundAdapter(prior, alpha)
    if skip_noise:
      return prior
    return tfc.UniformNoiseAdapter(prior)

  @property
  def ndim_latent(self):
    return self._analysis.output_shape[-1]

  def analysis(self, x):
    y = tf.cast(x, self.dtype)
    if y.shape[-1] != self.ndim_source:
      raise ValueError(
          f"Expected {self.ndim_source} trailing dimensions, "
          f"received {y.shape[-1]}.")
    batch_shape = tf.shape(y)[:-1]
    y = tf.reshape(y, (-1, self.ndim_source))
    y = self._analysis(y)
    assert y.shape[-1] == self.ndim_latent
    return tf.reshape(y, tf.concat([batch_shape, [self.ndim_latent]], 0))

  def synthesis(self, y):
    x = tf.cast(y, self.dtype)
    if x.shape[-1] != self.ndim_latent:
      raise ValueError(
          f"Expected {self.ndim_latent} trailing dimensions, "
          f"received {x.shape[-1]}.")
    batch_shape = tf.shape(x)[:-1]
    x = tf.reshape(x, (-1, self.ndim_latent))
    x = self._synthesis(x)
    assert x.shape[-1] == self.ndim_source
    return tf.reshape(x, tf.concat([batch_shape, [self.ndim_source]], 0))

  @property
  def force_alpha(self):
    return tf.convert_to_tensor(self._force_alpha)

  @force_alpha.setter
  def force_alpha(self, value):
    if value is None:
      value = -1.
    self._force_alpha.assign(value)

  @property
  def alpha(self):
    return tf.math.sigmoid(self._logit_alpha) * 4.

  @alpha.setter
  def alpha(self, value):
    value = tf.convert_to_tensor(value, self.dtype)

    def get_logit_alpha():
      a = tf.clip_by_value(value / 4., 0., 1.)
      logit_alpha = tf.math.log(a / (1. - a))
      return logit_alpha

    self._logit_alpha.assign(
        tf.cond(value < 0, lambda: self._logit_alpha, get_logit_alpha))

  def encode_decode(self, x, dither_rate, dither_dist, soft_round,
                    guess_offset=None, offset=0., seed=None):
    if guess_offset is None:
      guess_offset = self.guess_offset
    # It doesn't make sense to use both guess_offset and soft_round.
    assert not (guess_offset and soft_round)

    def perturb(inputs, dither, prior, offset):
      if dither:
        if soft_round:
          inputs = tfc.soft_round(inputs, alpha=self.alpha)
        inputs += tf.random.uniform(
            tf.shape(inputs), -.5, .5, dtype=self.dtype, seed=seed)
        if soft_round:
          inputs = tfc.soft_round_conditional_mean(inputs, alpha=self.alpha)
        return inputs
      else:
        if guess_offset:
          offset += tfc.quantization_offset(prior)
        return tfc.round_st(inputs, offset)

    assert x.shape[-1] == self.ndim_source
    y = self.analysis(x)

    rates = 0.
    prior = self.prior(soft_round=soft_round)

    y_dist = perturb(y, dither_dist, prior, offset)
    if dither_rate == dither_dist:
      y_rate = y_dist
    else:
      y_rate = perturb(y, dither_rate, prior, offset)

    x_hat = self.synthesis(y_dist)
    log_probs = prior.log_prob(y_rate)
    rates += tf.reduce_sum(log_probs, axis=-1) / tf.cast(
        -tf.math.log(2.), self.dtype)

    return y_dist, x_hat, rates

  def quantize(self, x, **kwargs):
    y_hat, x_hat, rates = self.encode_decode(x, False, False, False, **kwargs)
    # Find the unique set of latents for these inputs. Converts integer indexes
    # on the infinite lattice to scalar indexes into a codebook (which is only
    # valid for this set of inputs).
    _, i, indexes = np.unique(
        tf.reshape(y_hat, [-1, self.ndim_latent]),
        return_index=True, return_inverse=True, axis=0)
    codebook = tf.gather(tf.reshape(x_hat, [-1, self.ndim_source]), i, axis=0)
    rates = tf.gather(tf.reshape(rates, [-1]), i)
    indexes = tf.reshape(tf.cast(indexes, tf.int32), tf.shape(x)[:-1])
    return codebook, rates, indexes

  def train_losses(self, x):
    _, x_hat, rates = self.encode_decode(
        x, self.dither[0], self.dither[1], self.soft_round[0])
    distortions = self.distortion_fn(x, x_hat)
    return rates, distortions

  def test_losses(self, x):
    _, x_hat, rates = self.encode_decode(
        x, self.dither[2], self.dither[3], self.soft_round[1])
    distortions = self.distortion_fn(x, x_hat)
    return rates, distortions

  def plot_transfer(self, intervals, figsize=None, soft_round=None, **kwargs):
    if not len(intervals) == self.ndim_source == self.ndim_latent == 1:
      raise ValueError("This method is only defined for 1D models.")
    if soft_round is None:
      soft_round = self.soft_round[1]

    x = [tf.linspace(float(i[0]), float(i[1]), int(i[2])) for i in intervals]
    x = tf.meshgrid(*x, indexing="ij")
    x = tf.stack(x, axis=-1)

    y_hat, _, _ = self.encode_decode(x, False, False, soft_round, **kwargs)

    y = self.analysis(x)
    # We feed y here so we can visualize the full behavior of the synthesis
    # transform (not just at the quantized latent values).
    x_hat = self.synthesis(y)

    x = np.squeeze(x.numpy(), -1)
    y = np.squeeze(y.numpy(), -1)
    x_hat = np.squeeze(x_hat.numpy(), -1)
    y_hat = np.squeeze(y_hat.numpy(), -1)

    ylim = np.min(y), np.max(y)

    boundaries = np.nonzero(y_hat[1:] != y_hat[:-1])[0]
    lboundaries = (y_hat[boundaries] + y_hat[boundaries + 1]) / 2
    dboundaries = (x[boundaries] + x[boundaries + 1]) / 2

    lcodebook = np.unique(y_hat)
    dcodebook = self.synthesis(lcodebook[:, None]).numpy()
    dcodebook = np.squeeze(dcodebook, -1)
    mask = np.logical_and(ylim[0] < lcodebook, lcodebook < ylim[1])
    lcodebook = lcodebook[mask]
    dcodebook = dcodebook[mask]

    plt.figure(figsize=figsize or (16, 14))
    plt.plot(x, y, label="analysis transform")
    plt.plot(x_hat, y, label="synthesis transform")

    plt.gca().set_aspect("equal", "box")
    # Flip y axis if latent space is reversed.
    if y[0] > y[-1]:
      plt.gca().invert_yaxis()
    plt.xticks(dcodebook)
    plt.yticks(lcodebook)
    plt.grid(False)
    plt.xlabel("source space")
    plt.ylabel("latent space")

    xmin = plt.axis()[0]
    ymin = plt.axis()[2]
    for x, y in zip(dcodebook, lcodebook):
      plt.plot([xmin, x, x], [y, y, ymin], "black", lw=1)
      plt.plot(
          [x], [y], "black", marker="o", ms=5, lw=1,
          label="codebook" if x == dcodebook[0] else None)
    for x, y in zip(dboundaries, lboundaries):
      plt.plot([xmin, x, x], [y, y, ymin], "black", lw=1, ls=":")
      plt.plot(
          [x], [y], "black", marker="o", ms=3, lw=1, ls=":",
          label="boundaries" if x == dboundaries[0] else None)

    plt.legend(loc="upper left")

  def plot_jacobians(self, which, intervals, arrow_intervals, scale=2,
                     figsize=None):
    if not (len(intervals) == len(arrow_intervals) ==
            self.ndim_source == self.ndim_latent == 2):
      raise ValueError("This method is only defined for 2D models.")
    if which not in ("analysis", "synthesis"):
      raise ValueError("`which` must be 'analysis' or 'synthesis'.")

    data = [tf.linspace(float(i[0]), float(i[1]), int(i[2])) for i in intervals]
    data = tf.meshgrid(*data, indexing="ij")
    data = tf.stack(data, axis=-1)
    data_dist = self.source.prob(data).numpy()

    if which == "analysis":
      arrow_data = [
          tf.linspace(float(i[0]), float(i[1]), int(i[2]))
          for i in arrow_intervals
      ]
      arrow_data = tf.meshgrid(*arrow_data, indexing="ij")
      arrow_data = tf.stack(arrow_data, axis=-1)
      arrow_data = tf.reshape(arrow_data, (-1, arrow_data.shape[-1]))
      with tf.GradientTape(watch_accessed_variables=False) as tape:
        tape.watch(arrow_data)
        arrow_latents = self.analysis(arrow_data)
      # First dimension is batch, second is latent dim, third is source dim.
      jacobian = tape.batch_jacobian(arrow_latents, arrow_data)
      jacobian = tf.linalg.inv(jacobian)
      jacobian = tf.transpose(jacobian, (0, 2, 1))
    else:
      arrow_latents = [
          tf.linspace(float(i[0]), float(i[1]), int(i[2]))
          for i in arrow_intervals
      ]
      arrow_latents = tf.meshgrid(*arrow_latents, indexing="ij")
      arrow_latents = tf.stack(arrow_latents, axis=-1)
      arrow_latents = tf.reshape(arrow_latents, (-1, arrow_latents.shape[-1]))
      with tf.GradientTape(watch_accessed_variables=False) as tape:
        tape.watch(arrow_latents)
        arrow_data = self.synthesis(arrow_latents)
      jacobian = tape.batch_jacobian(arrow_data, arrow_latents)
      jacobian = tf.transpose(jacobian, (0, 2, 1))

    google_pink = (0xf4/255, 0x39/255, 0xa0/255)
    google_purple = (0xa1/255, 0x42/255, 0xf4/255)

    plt.figure(figsize=figsize or (16, 14))
    plt.imshow(
        data_dist, vmin=0, vmax=data_dist.max(), origin="lower",
        extent=(data[0, 0, 1], data[0, -1, 1], data[0, 0, 0], data[-1, 0, 0]))
    plt.quiver(
        arrow_data[:, 1], arrow_data[:, 0],
        jacobian[:, 0, 1], jacobian[:, 0, 0],
        pivot="tail", angles="xy", headlength=4, headaxislength=4, units="dots",
        color=google_pink, scale_units="xy", scale=scale,
    )
    plt.quiver(
        arrow_data[:, 1], arrow_data[:, 0],
        jacobian[:, 1, 1], jacobian[:, 1, 0],
        pivot="tail", angles="xy", headlength=4, headaxislength=4, units="dots",
        color=google_purple, scale_units="xy", scale=scale,
    )
    plt.axis("image")
    plt.grid(False)
    plt.xlim(data[0, 0, 1], data[0, -1, 1])
    plt.ylim(data[0, 0, 0], data[-1, 0, 0])
    plt.xlabel("source dimension 1")
    plt.ylabel("source dimension 2")

  def plot_prior_latent(self, intervals, figsize=None, **kwargs):
    if len(intervals) != self.ndim_latent or self.ndim_latent not in (1, 2):
      raise ValueError("This method is only defined for 1D or 2D models.")

    y = [tf.linspace(float(i[0]), float(i[1]), int(i[2])) for i in intervals]
    y = tf.meshgrid(*y, indexing="ij")
    y = tf.stack(y, axis=-1)
    prob = tfpd.Independent(self.prior(**kwargs), 1).prob(y)

    if self.ndim_latent == 1:
      plt.figure(figsize=figsize or (16, 6))
      plt.plot(y, prob)
      plt.xlabel("latent space")
      plt.ylabel("prior")
      plt.grid(True)
      plt.xticks(np.arange(*np.ceil(intervals[0][:2])))
    else:
      plt.figure(figsize=figsize or (16, 14))
      plt.imshow(
          prob, vmin=0, vmax=np.max(prob), origin="lower",
          extent=(y[0, 0, 1], y[0, -1, 1], y[0, 0, 0], y[-1, 0, 0]))
      plt.axis("image")
      plt.grid(False)
      plt.xlim(y[0, 0, 1], y[0, -1, 1])
      plt.ylim(y[0, 0, 0], y[-1, 0, 0])
      plt.xlabel("latent dimension 1")
      plt.ylabel("latent dimension 2")

  def plot_prior(self, figsize=None, xlim=None, **kwargs):
    prior = self.prior(**kwargs)
    assert not tuple(prior.event_shape)
    if not xlim:
      xlim = (tf.reduce_min(tfc.lower_tail(prior, 1e-5)),
              tf.reduce_max(tfc.upper_tail(prior, 1e-5)))
    y = tf.linspace(xlim[0], xlim[1], 1000)[:, None]
    prob = prior.prob(y)
    plt.figure(figsize=figsize or (16, 8))
    plt.plot(y, prob)
    plt.grid()
    plt.xlabel("latent space")
    plt.ylabel("$p$")
    plt.figure(figsize=figsize or (16, 8))
    plt.imshow(
        tf.transpose(prob), aspect="auto",
        extent=(xlim[0], xlim[1], -.5, self.ndim_latent - .5))
    plt.xlabel("latent space")
    plt.ylabel("latent dimension")


text: Loopback Tri API


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="@dimen/smart_watch_2_control_width"
    android:layout_height="@dimen/smart_watch_2_control_height"
    android:background="@android:color/background_dark"
    android:orientation="vertical"
    android:weightSum="2"
    android:gravity="center"
    tools:ignore="ContentDescription,PxUsage" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:text="@string/app_name"
        android:textSize="8dp" />

</LinearLayout>


text:
package iso20022

// Set of elements used to provide reference and status information on the original transactions, included in the original instruction, to which the cancellation request message applies.
type PaymentTransaction58 struct {

	// Unique identification, as assigned by the assigner, to unambiguously identify a cancellation request.
	//
	// Usage: The cancellation request identification can be used for reconciliation or to link tasks relating to the cancellation request.
	CancellationIdentification *Max35Text `xml:"CxlId,omitempty"`

	// Set of elements to uniquely and unambiguously identify an exception or an investigation workflow.
	Case *Case3 `xml:"Case,omitempty"`

	// Unique identification, as assigned by the original instructing party for the original instructed party, to unambiguously identify the original instruction.
	OriginalInstructionIdentification *Max35Text `xml:"OrgnlInstrId,omitempty"`

	// Unique identification, as assigned by the original initiating party, to unambiguously identify the original transaction.
	OriginalEndToEndIdentification *Max35Text `xml:"OrgnlEndToEndId,omitempty"`

	// Amount of money, as provided in the original transaction, to be moved between the debtor and the creditor, before deduction of charges, expressed in the currency, as ordered by the original initiating party.
	//
	// Usage: This amount has to be transported unchanged through the transaction chain.
	OriginalInstructedAmount *ActiveOrHistoricCurrencyAndAmount `xml:"OrgnlInstdAmt,omitempty"`

	// Date at which the initiating party originally requested the clearing agent to process the payment.
	OriginalRequestedExecutionDate *ISODate `xml:"OrgnlReqdExctnDt,omitempty"`

	// Date at which the creditor originally requested the collection of the amount of money from the debtor.
	OriginalRequestedCollectionDate *ISODate `xml:"OrgnlReqdColltnDt,omitempty"`

	// Provides detailed information on the cancellation reason.
	CancellationReasonInformation []*PaymentCancellationReason2 `xml:"CxlRsnInf,omitempty"`

	// Key elements used to identify the original transaction that is being referred to.
	OriginalTransactionReference *OriginalTransactionReference20 `xml:"OrgnlTxRef,omitempty"`

	// Additional information that cannot be captured in the structured elements and/or any other specific block.
	SupplementaryData []*SupplementaryData1 `xml:"SplmtryData,omitempty"`
}

func (p *PaymentTransaction58) SetCancellationIdentification(value string) {
	p.CancellationIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction58) AddCase() *Case3 {
	p.Case = new(Case3)
	return p.Case
}

func (p *PaymentTransaction58) SetOriginalInstructionIdentification(value string) {
	p.OriginalInstructionIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction58) SetOriginalEndToEndIdentification(value string) {
	p.OriginalEndToEndIdentification = (*Max35Text)(&value)
}

func (p *PaymentTransaction58) SetOriginalInstructedAmount(value, currency string) {
	p.OriginalInstructedAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (p *PaymentTransaction58) SetOriginalRequestedExecutionDate(value string) {
	p.OriginalRequestedExecutionDate = (*ISODate)(&value)
}

func (p *PaymentTransaction58) SetOriginalRequestedCollectionDate(value string) {
	p.OriginalRequestedCollectionDate = (*ISODate)(&value)
}

func (p *PaymentTransaction58) AddCancellationReasonInformation() *PaymentCancellationReason2 {
	newValue := new(PaymentCancellationReason2)
	p.CancellationReasonInformation = append(p.CancellationReasonInformation, newValue)
	return newValue
}

func (p *PaymentTransaction58) AddOriginalTransactionReference() *OriginalTransactionReference20 {
	p.OriginalTransactionReference = new(OriginalTransactionReference20)
	return p.OriginalTransactionReference
}

func (p *PaymentTransaction58) AddSupplementaryData() *SupplementaryData1 {
	newValue := new(SupplementaryData1)
	p.SupplementaryData = append(p.SupplementaryData, newValue)
	return newValue
}


text:
A wrapping queue of integer.
Please check the unit test to see how it works.


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

namespace HiPMobile.iOS
{
    public static class HipConstants
    {
        public static string[] menuItems = new string[] { "Übersicht", "Lizenzen" };
        public static string[] viewControllers = new string[] { "MainScreenViewController", "LicenseScreenViewController" };
    }
}